diff --git a/bin/knowledge-mcp.js b/bin/knowledge-mcp.js index fbf1004..f77db8a 100755 --- a/bin/knowledge-mcp.js +++ b/bin/knowledge-mcp.js @@ -34543,6 +34543,68 @@ VALUES (9, datetime('now')); COMMIT; `; +var MIGRATION_10_PROMOTION_INBOX = ` +CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + source_kind TEXT NOT NULL, + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'pending', + requires_approval INTEGER NOT NULL DEFAULT 0, + checks_json TEXT NOT NULL DEFAULT '{}', + idempotency_key TEXT NOT NULL UNIQUE, + duplicate_of TEXT, + approved_by TEXT, + promoted_record_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + reviewed_at TEXT, + promoted_at TEXT +); + +CREATE TABLE IF NOT EXISTS durable_knowledge_records ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + confidence REAL, + valid_from TEXT NOT NULL, + valid_to TEXT, + promoted_from_candidate_id TEXT NOT NULL UNIQUE + REFERENCES knowledge_promotion_candidates(id) ON DELETE RESTRICT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_status + ON knowledge_promotion_candidates(status, updated_at); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_kind_key + ON knowledge_promotion_candidates(record_kind, canonical_key); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_hash + ON knowledge_promotion_candidates(record_kind, content_hash); +CREATE INDEX IF NOT EXISTS idx_durable_records_kind_key + ON durable_knowledge_records(record_kind, canonical_key, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_hash + ON durable_knowledge_records(record_kind, content_hash, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_validity + ON durable_knowledge_records(status, valid_to); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (10, datetime('now')); +`; function openKnowledgeDb(path) { assertLocalCatalogMode("opening the local knowledge.db catalog"); ensureParentDir(path); @@ -34575,6 +34637,8 @@ function migrateKnowledgeDb(path) { applyMigration8(db); if (needsMigration9(db)) applyMigration9(db); + if (needsMigration10(db)) + applyMigration10(db); return { path, schema_version: getSchemaVersion(db) }; } finally { db.close(); @@ -34655,6 +34719,12 @@ function applyMigration9(db) { } db.exec(MIGRATION_9_REBUILD_FTS); } +function needsMigration10(db) { + return getSchemaVersion(db) < 10 || !tableExists(db, "knowledge_promotion_candidates") || !tableExists(db, "durable_knowledge_records"); +} +function applyMigration10(db) { + db.exec(MIGRATION_10_PROMOTION_INBOX); +} function getKnowledgeDbStats(path) { const db = openKnowledgeDb(path); try { @@ -34680,7 +34750,9 @@ function getKnowledgeDbStats(path) { sync_changes: count(db, "knowledge_sync_changes"), sync_conflicts: count(db, "knowledge_sync_conflicts"), sync_table_clocks: count(db, "knowledge_sync_table_clocks"), - sync_imports: count(db, "knowledge_sync_imports") + sync_imports: count(db, "knowledge_sync_imports"), + promotion_candidates: count(db, "knowledge_promotion_candidates"), + durable_records: count(db, "durable_knowledge_records") }; } finally { db.close(); @@ -35448,7 +35520,7 @@ function createArtifactStore(config2, workspace) { } // src/service.ts -import { createHash as createHash18 } from "crypto"; +import { createHash as createHash19 } from "crypto"; import { spawnSync as spawnSync2 } from "child_process"; import { existsSync as existsSync14, readFileSync as readFileSync12 } from "fs"; import { hostname as hostname5 } from "os"; @@ -36046,6 +36118,23 @@ function recordRedactionFindings(db, input) { } return input.findings.length; } +function createApprovalGate(db, input) { + const now = input.created_at ?? new Date().toISOString(); + const id = `approval_${randomUUID3()}`; + db.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + id, + input.action, + input.target_uri ?? null, + "approved", + input.reason ?? null, + input.approved_by ?? "local-cli", + JSON.stringify(input.metadata ?? {}), + now, + now + ]); + return { id, status: "approved" }; +} var COMMON_BARE_TOKEN_PATTERNS = [ { type: "github_token", severity: "high", regex: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_token]" }, { type: "github_pat_token", severity: "high", regex: /\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_pat_token]" }, @@ -43592,10 +43681,503 @@ async function preflightKnowledgeMachine(options = {}) { } } +// src/promotion-inbox.ts +import { createHash as createHash12 } from "crypto"; +function stableId7(prefix, value, length = 24) { + return `${prefix}_${createHash12("sha256").update(value).digest("hex").slice(0, length)}`; +} +function normalizedText(value) { + return value.normalize("NFKC").trim().replace(/\s+/g, " "); +} +function normalizedKey(value) { + return normalizedText(value).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, ""); +} +function parseJson3(value, fallback) { + try { + return JSON.parse(value); + } catch { + return fallback; + } +} +function asCandidate(row) { + return { + ...row, + record_kind: row.record_kind, + source_kind: row.source_kind, + status: row.status, + source_refs: parseJson3(row.source_refs_json, []), + evidence_refs: parseJson3(row.evidence_refs_json, []), + requires_approval: row.requires_approval === 1, + checks: parseJson3(row.checks_json, emptyChecks()), + metadata: parseJson3(row.metadata_json, {}) + }; +} +function asDurableRecord(row) { + return { + ...row, + record_kind: row.record_kind, + source_refs: parseJson3(row.source_refs_json, []), + evidence_refs: parseJson3(row.evidence_refs_json, []), + metadata: parseJson3(row.metadata_json, {}) + }; +} +function emptyChecks() { + return { + citations: { provided: 0, valid: 0, invalid: 0, entries: [] }, + invalid_source_refs: [], + stale_refs: [], + duplicate_record_ids: [], + duplicate_candidate_ids: [], + conflicting_record_ids: [], + conflicting_candidate_ids: [], + approval_reasons: [] + }; +} +function normalizeEvidenceRef(input) { + const value = typeof input === "string" ? { ref: input } : input; + return { + ref: normalizedText(value.ref), + citation_id: value.citation_id ?? null, + chunk_id: value.chunk_id ?? null, + revision: value.revision ?? null, + hash: value.hash ?? null, + observed_at: value.observed_at ?? null, + expires_at: value.expires_at ?? null, + status: value.status ?? null + }; +} +function validReference(ref) { + try { + const parsed = new URL(ref); + return parsed.protocol.length > 1 && (parsed.hostname.length > 0 || parsed.pathname.length > 0); + } catch { + return /^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(ref); + } +} +function staleStatus(status) { + return ["deleted", "stale", "invalidated", "reindex_required", "expired", "superseded"].includes((status ?? "").toLowerCase()); +} +function metadataStatus(value) { + if (!value) + return null; + const metadata = parseJson3(value, {}); + if (metadata.stale === true) + return "stale"; + return typeof metadata.status === "string" ? metadata.status : null; +} +function citationIdentifier(evidence) { + if (evidence.citation_id) + return evidence.citation_id; + const match = evidence.ref.match(/^(?:cite|citation):(.+)$/); + return match?.[1] ?? null; +} +function chunkIdentifier(evidence) { + if (evidence.chunk_id) + return evidence.chunk_id; + const match = evidence.ref.match(/^chunk:(.+)$/); + return match?.[1] ?? null; +} +function inspectCitation(db, evidence, now) { + const explicitStale = staleStatus(evidence.status) || Boolean(evidence.expires_at && evidence.expires_at <= now); + if (!evidence.ref || !validReference(evidence.ref)) { + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "invalid_reference" }; + } + const citationId = citationIdentifier(evidence); + const citation = db.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, + sr.source_id, sr.created_at AS revision_created_at, + (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at + FROM citations c + LEFT JOIN chunks ch ON ch.id = c.chunk_id + LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE c.id = ? OR c.source_uri = ? + ORDER BY c.created_at DESC + LIMIT 1`).get(citationId, evidence.ref); + if (citation) { + const hashMismatch = Boolean(evidence.hash && citation.revision_hash && evidence.hash !== citation.revision_hash); + const revisionMismatch = Boolean(evidence.revision && citation.revision && evidence.revision !== citation.revision); + const oldRevision = Boolean(citation.revision_created_at && citation.latest_revision_at && citation.revision_created_at < citation.latest_revision_at); + const stale = explicitStale || staleStatus(metadataStatus(citation.chunk_metadata_json)) || hashMismatch || revisionMismatch || oldRevision; + return { + ref: evidence.ref, + valid: true, + resolved_by: "citation", + stale, + reason: hashMismatch ? "hash_mismatch" : revisionMismatch ? "revision_mismatch" : oldRevision ? "newer_source_revision" : stale ? "stale_citation" : null + }; + } + const chunkId = chunkIdentifier(evidence); + if (chunkId) { + const chunk = db.query(`SELECT ch.metadata_json, sr.hash, sr.revision + FROM chunks ch LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE ch.id = ?`).get(chunkId); + if (!chunk) + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "chunk_not_found" }; + const mismatch = Boolean(evidence.hash && chunk.hash && evidence.hash !== chunk.hash || evidence.revision && chunk.revision && evidence.revision !== chunk.revision); + const stale = explicitStale || staleStatus(metadataStatus(chunk.metadata_json)) || mismatch; + return { ref: evidence.ref, valid: true, resolved_by: "chunk", stale, reason: mismatch ? "source_version_mismatch" : stale ? "stale_chunk" : null }; + } + const source = db.query("SELECT metadata_json FROM sources WHERE uri = ? LIMIT 1").get(evidence.ref); + if (source) { + const stale = explicitStale || staleStatus(metadataStatus(source.metadata_json)); + return { ref: evidence.ref, valid: true, resolved_by: "source", stale, reason: stale ? "stale_source" : null }; + } + const runMatch = evidence.ref.match(/^knowledge:\/\/project\/runs\/([^/?#]+)/); + if (runMatch) { + const run = db.query("SELECT id FROM runs WHERE id = ?").get(decodeURIComponent(runMatch[1])); + if (!run) + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "run_not_found" }; + return { ref: evidence.ref, valid: true, resolved_by: "run", stale: explicitStale, reason: explicitStale ? "expired_evidence" : null }; + } + return { + ref: evidence.ref, + valid: true, + resolved_by: "external_uri", + stale: explicitStale, + reason: explicitStale ? "expired_evidence" : null + }; +} +function candidateById(db, id) { + return db.query("SELECT * FROM knowledge_promotion_candidates WHERE id = ?").get(id) ?? null; +} +function assessCandidate(db, row, now) { + const evidence = parseJson3(row.evidence_refs_json, []); + const sourceRefs = parseJson3(row.source_refs_json, []); + const metadata = parseJson3(row.metadata_json, {}); + const checks3 = emptyChecks(); + checks3.invalid_source_refs = sourceRefs.filter((ref) => !validReference(ref)); + checks3.citations.entries = evidence.map((entry) => inspectCitation(db, entry, now)); + checks3.citations.provided = evidence.length; + checks3.citations.valid = checks3.citations.entries.filter((entry) => entry.valid).length; + checks3.citations.invalid = checks3.citations.entries.length - checks3.citations.valid; + checks3.stale_refs = checks3.citations.entries.filter((entry) => entry.stale).map((entry) => entry.ref); + checks3.duplicate_record_ids = db.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND content_hash = ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(row.record_kind, row.content_hash).map((entry) => entry.id); + checks3.duplicate_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND content_hash = ? AND status NOT IN ('rejected') + ORDER BY created_at`).all(row.id, row.record_kind, row.content_hash).map((entry) => entry.id); + checks3.conflicting_record_ids = db.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + checks3.conflicting_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND canonical_key = ? AND content_hash <> ? + AND status IN ('ready', 'needs_approval', 'promoted') + ORDER BY created_at`).all(row.id, row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + const duplicateOf = checks3.duplicate_record_ids[0] ?? checks3.duplicate_candidate_ids[0] ?? null; + const blocked = sourceRefs.length === 0 || evidence.length === 0 || checks3.invalid_source_refs.length > 0 || checks3.citations.invalid > 0; + if (row.record_kind === "decision" || row.record_kind === "claim") + checks3.approval_reasons.push(`${row.record_kind}_requires_review`); + if (metadata.requested_approval === true) + checks3.approval_reasons.push("explicit_approval_request"); + if (checks3.stale_refs.length > 0) + checks3.approval_reasons.push("stale_evidence"); + if (checks3.conflicting_record_ids.length > 0 || checks3.conflicting_candidate_ids.length > 0) { + checks3.approval_reasons.push("conflicting_knowledge"); + } + const requiresApproval = checks3.approval_reasons.length > 0; + const status = duplicateOf ? "duplicate" : blocked ? "blocked" : requiresApproval ? "needs_approval" : "ready"; + db.run(`UPDATE knowledge_promotion_candidates + SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, [status, requiresApproval ? 1 : 0, JSON.stringify(checks3), duplicateOf, now, now, row.id]); + return asCandidate(candidateById(db, row.id)); +} +function enqueueKnowledgePromotion(dbPath, input) { + const kinds = ["lesson", "decision", "claim"]; + const sourceKinds = ["memento", "session", "report"]; + if (!kinds.includes(input.kind)) + throw new Error("Promotion kind must be lesson, decision, or claim."); + if (!sourceKinds.includes(input.sourceKind)) + throw new Error("Promotion source kind must be memento, session, or report."); + const titleResult = redactSecrets(normalizedText(input.title)); + const contentResult = redactSecrets(normalizedText(input.content)); + if (!titleResult.text) + throw new Error("Promotion title is required."); + if (!contentResult.text) + throw new Error("Promotion content is required."); + const sourceRefs = Array.from(new Set(input.sourceRefs.map(normalizedText).filter(Boolean))).sort(); + const evidenceRefs = input.evidenceRefs.map(normalizeEvidenceRef).filter((entry) => entry.ref.length > 0).sort((a, b) => a.ref.localeCompare(b.ref)); + const canonicalKey = normalizedKey(input.canonicalKey ?? titleResult.text); + if (!canonicalKey) + throw new Error("Promotion canonical key is empty after normalization."); + const contentHash = `sha256:${createHash12("sha256").update(`${input.kind}\x00${normalizedText(contentResult.text).toLowerCase()}`).digest("hex")}`; + const idempotencyKey = stableId7("promote", [ + input.sourceKind, + input.kind, + canonicalKey, + contentHash, + ...sourceRefs + ].join("\x00")); + const id = stableId7("promotion", idempotencyKey); + const now = (input.now ?? new Date).toISOString(); + const metadata = { + ...input.metadata ?? {}, + requested_approval: input.requiresApproval === true, + confidence: input.confidence ?? null, + valid_from: input.validFrom ?? now, + valid_to: input.validTo ?? null, + redactions: titleResult.findings.length + contentResult.findings.length + }; + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const existing = db.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(idempotencyKey); + if (existing) + return { created: false, candidate: asCandidate(existing) }; + db.run(`INSERT INTO knowledge_promotion_candidates ( + id, record_kind, title, content, canonical_key, content_hash, source_kind, + source_refs_json, evidence_refs_json, status, requires_approval, checks_json, + idempotency_key, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`, [ + id, + input.kind, + titleResult.text, + contentResult.text, + canonicalKey, + contentHash, + input.sourceKind, + JSON.stringify(sourceRefs), + JSON.stringify(evidenceRefs), + idempotencyKey, + JSON.stringify(metadata), + now, + now + ]); + const findings = [...titleResult.findings, ...contentResult.findings]; + if (findings.length > 0) { + recordRedactionFindings(db, { + source_uri: sourceRefs[0] ?? `knowledge://promotion/${id}`, + findings, + metadata: { promotion_candidate_id: id }, + created_at: now + }); + } + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "enqueue_promotion", + target_uri: `knowledge://promotion/${id}`, + decision: "info", + metadata: { record_kind: input.kind, source_kind: input.sourceKind, source_refs: sourceRefs }, + created_at: now + }); + return { created: true, candidate: assessCandidate(db, candidateById(db, id), now) }; + } finally { + db.close(); + } +} +function getKnowledgePromotion(dbPath, id) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const row = candidateById(db, id); + return row ? asCandidate(row) : null; + } finally { + db.close(); + } +} +function listKnowledgePromotions(dbPath, options = {}) { + migrateKnowledgeDb(dbPath); + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const conditions = []; + const params = []; + if (options.status === "inbox" || !options.status) { + conditions.push("status IN ('ready', 'needs_approval', 'blocked')"); + } else { + conditions.push("status = ?"); + params.push(options.status); + } + if (options.kind) { + conditions.push("record_kind = ?"); + params.push(options.kind); + } + const db = openKnowledgeDb(dbPath); + try { + return db.query(`SELECT * FROM knowledge_promotion_candidates + WHERE ${conditions.join(" AND ")} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...params, limit).map(asCandidate); + } finally { + db.close(); + } +} +function reviewKnowledgePromotion(dbPath, id, now = new Date) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted" || row.status === "rejected") + return asCandidate(row); + return assessCandidate(db, row, now.toISOString()); + } finally { + db.close(); + } +} +function promoteKnowledgeCandidate(dbPath, id, options = {}) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = (options.now ?? new Date).toISOString(); + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted" && row.promoted_record_id) { + const existingRecord = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(row.promoted_record_id); + return { + ok: true, + promoted: false, + requires_approval: row.requires_approval === 1, + candidate: asCandidate(row), + record: existingRecord ? asDurableRecord(existingRecord) : null, + approval_id: null, + reason: "already_promoted" + }; + } + if (row.status === "rejected") + throw new Error(`Promotion candidate ${id} was rejected.`); + const candidate = assessCandidate(db, row, now); + if (candidate.status === "duplicate") { + return { ok: true, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "duplicate" }; + } + if (candidate.status === "blocked") { + return { ok: false, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "citation_check_failed" }; + } + if (candidate.requires_approval && !options.approveWrite) { + return { ok: false, promoted: false, requires_approval: true, candidate, record: null, approval_id: null, reason: "approval_required" }; + } + if (candidate.requires_approval && !options.approvedBy?.trim()) { + throw new Error("Promotion approval requires --approved-by ."); + } + const approvedBy = candidate.requires_approval ? options.approvedBy.trim() : null; + let approvalId = null; + if (candidate.requires_approval) { + approvalId = createApprovalGate(db, { + action: "promote_durable_knowledge", + target_uri: `knowledge://promotion/${candidate.id}`, + reason: candidate.checks.approval_reasons.join(", "), + approved_by: approvedBy, + metadata: { promotion_candidate_id: candidate.id, checks: candidate.checks }, + created_at: now + }).id; + } + const recordId = stableId7("durable", candidate.id); + const metadata = { + ...candidate.metadata, + promotion_candidate_id: candidate.id, + source_kind: candidate.source_kind, + checks: candidate.checks, + approval_id: approvalId, + provenance: generatedArtifactProvenance({ + generated_from: `knowledge://promotion/${candidate.id}`, + artifact_key: `durable/${candidate.record_kind}/${candidate.canonical_key}`, + source_refs: candidate.source_refs, + citation_required: true + }) + }; + db.run(`INSERT INTO durable_knowledge_records ( + id, record_kind, title, content, canonical_key, content_hash, status, + source_refs_json, evidence_refs_json, confidence, valid_from, valid_to, + promoted_from_candidate_id, approved_by, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + recordId, + candidate.record_kind, + candidate.title, + candidate.content, + candidate.canonical_key, + candidate.content_hash, + candidate.checks.conflicting_record_ids.length > 0 ? "conflicted" : "active", + JSON.stringify(candidate.source_refs), + JSON.stringify(candidate.evidence_refs), + typeof candidate.metadata.confidence === "number" ? candidate.metadata.confidence : null, + typeof candidate.metadata.valid_from === "string" ? candidate.metadata.valid_from : now, + typeof candidate.metadata.valid_to === "string" ? candidate.metadata.valid_to : null, + candidate.id, + approvedBy, + JSON.stringify(metadata), + now, + now + ]); + db.run(`UPDATE knowledge_promotion_candidates + SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? + WHERE id = ?`, [approvedBy, recordId, now, now, candidate.id]); + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "promote_durable_knowledge", + target_uri: `knowledge://durable/${recordId}`, + decision: "allow", + metadata: { promotion_candidate_id: candidate.id, approval_id: approvalId, source_refs: candidate.source_refs }, + created_at: now + }); + const promotedCandidate = asCandidate(candidateById(db, candidate.id)); + const record2 = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(recordId); + return { + ok: true, + promoted: true, + requires_approval: candidate.requires_approval, + candidate: promotedCandidate, + record: asDurableRecord(record2), + approval_id: approvalId, + reason: null + }; + } finally { + db.close(); + } +} +function rejectKnowledgePromotion(dbPath, id, options = {}) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = (options.now ?? new Date).toISOString(); + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted") + throw new Error(`Promotion candidate ${id} is already promoted.`); + db.run(`UPDATE knowledge_promotion_candidates + SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, [options.rejectedBy?.trim() || null, now, now, id]); + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "reject_promotion", + target_uri: `knowledge://promotion/${id}`, + decision: "deny", + metadata: { rejected_by: options.rejectedBy ?? null }, + created_at: now + }); + return asCandidate(candidateById(db, id)); + } finally { + db.close(); + } +} +function listDurableKnowledgeRecords(dbPath, options = {}) { + migrateKnowledgeDb(dbPath); + const conditions = []; + const params = []; + if (options.kind) { + conditions.push("record_kind = ?"); + params.push(options.kind); + } + if (options.status) { + conditions.push("status = ?"); + params.push(options.status); + } + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const db = openKnowledgeDb(dbPath); + try { + return db.query(`SELECT * FROM durable_knowledge_records + ${conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...params, limit).map(asDurableRecord); + } finally { + db.close(); + } +} + // src/reindex.ts -import { createHash as createHash12, randomUUID as randomUUID10 } from "crypto"; -function stableId7(prefix, value) { - return `${prefix}_${createHash12("sha256").update(value).digest("hex").slice(0, 20)}`; +import { createHash as createHash13, randomUUID as randomUUID10 } from "crypto"; +function stableId8(prefix, value) { + return `${prefix}_${createHash13("sha256").update(value).digest("hex").slice(0, 20)}`; } function queueCounts(dbPath) { const db = openKnowledgeDb(dbPath); @@ -43655,7 +44237,7 @@ function enqueueMissingEmbeddings(options) { try { const write = db.transaction(() => { for (const row of rows) { - const id = stableId7("rq", `embedding\x00${row.chunk_id}\x00${reason}`); + const id = stableId8("rq", `embedding\x00${row.chunk_id}\x00${reason}`); const before = db.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding", row.chunk_id, reason); if (before) { alreadyQueued += 1; @@ -43780,7 +44362,7 @@ async function refreshEmbeddingIndex(options) { } // src/rules-provenance.ts -import { createHash as createHash13 } from "crypto"; +import { createHash as createHash14 } from "crypto"; import { existsSync as existsSync12, lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync10, statSync as statSync2 } from "fs"; import { basename as basename5, extname as extname2, join as join6, relative as relative4, resolve as resolve4, sep as sep4 } from "path"; import { pathToFileURL as pathToFileURL3 } from "url"; @@ -43812,10 +44394,10 @@ var SKIP_DIRECTORIES = new Set([ var SENSITIVE_PATH_RE = /(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i; var SELECTED_PROMPT_OR_PLAN_RE = /(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i; function sha256Text2(text) { - return `sha256:${createHash13("sha256").update(text).digest("hex")}`; + return `sha256:${createHash14("sha256").update(text).digest("hex")}`; } function sha256Bytes(bytes) { - return `sha256:${createHash13("sha256").update(bytes).digest("hex")}`; + return `sha256:${createHash14("sha256").update(bytes).digest("hex")}`; } function normalizePath(value) { return value.split(sep4).join("/"); @@ -44332,9 +44914,9 @@ async function importRulesProvenance(options = {}) { } // src/web-search.ts -import { createHash as createHash14, randomUUID as randomUUID11 } from "crypto"; +import { createHash as createHash15, randomUUID as randomUUID11 } from "crypto"; function stableHash(value) { - return `sha256:${createHash14("sha256").update(value).digest("hex")}`; + return `sha256:${createHash15("sha256").update(value).digest("hex")}`; } function estimateTokens3(text) { const words = text.trim().split(/\s+/).filter(Boolean).length; @@ -44583,9 +45165,9 @@ async function runProviderWebSearch(options) { } // src/wiki-compiler.ts -import { createHash as createHash15, randomUUID as randomUUID12 } from "crypto"; -function stableId8(prefix, value) { - return `${prefix}_${createHash15("sha256").update(value).digest("hex").slice(0, 20)}`; +import { createHash as createHash16, randomUUID as randomUUID12 } from "crypto"; +function stableId9(prefix, value) { + return `${prefix}_${createHash16("sha256").update(value).digest("hex").slice(0, 20)}`; } function slugify3(value) { const slug = value.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80); @@ -44758,7 +45340,7 @@ function upsertWikiPage(db, input) { for (const row of existing) db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [input.pageId]); - const chunkId = stableId8("chk", `${input.pageId}\x00${input.contentHash}`); + const chunkId = stableId9("chk", `${input.pageId}\x00${input.contentHash}`); db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ chunkId, @@ -44789,7 +45371,7 @@ function replacePageCitations(db, pageId, citations, now) { for (const citation of citations) { db.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - stableId8("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID12()}`), + stableId9("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID12()}`), pageId, citation.chunk_id, citation.source_uri, @@ -44809,7 +45391,7 @@ function upsertIndex(db, input) { artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`, [ - stableId8("idx", `wiki-topic\x00${input.path}`), + stableId9("idx", `wiki-topic\x00${input.path}`), "wiki_topic", input.title, input.artifactUri, @@ -44858,7 +45440,7 @@ async function compileWikiPage(options) { content_type: "text/markdown", metadata: { generated_from: "wiki_compile" } }); - const pageId = stableId8("wiki", path); + const pageId = stableId9("wiki", path); const citations = rows.map((row) => ({ chunk_id: row.chunk_id, source_uri: row.source_uri ?? "unknown", @@ -44887,7 +45469,7 @@ async function compileWikiPage(options) { content_type: "text/markdown", metadata: { generated_from: "wiki_compile_concept" } }); - const conceptPageId = stableId8("wiki", conceptPath); + const conceptPageId = stableId9("wiki", conceptPath); const log = await appendLog2(options.store, { ts: now, event: "wiki_compile_completed", @@ -44993,7 +45575,7 @@ async function fileAnswerToWiki(options) { prompt: options.prompt, citations: citations.length }, nowDate); - const pageId = stableId8("wiki", path); + const pageId = stableId9("wiki", path); const db = openKnowledgeDb(options.dbPath); try { recordStorageObjects(db, [artifact, log], nowDate); @@ -45129,15 +45711,15 @@ function lintWiki(options) { } // src/wiki-layout.ts -import { createHash as createHash16 } from "crypto"; +import { createHash as createHash17 } from "crypto"; function todayParts2(now) { const year = String(now.getUTCFullYear()); const month = String(now.getUTCMonth() + 1).padStart(2, "0"); const day = String(now.getUTCDate()).padStart(2, "0"); return { year, month, day }; } -function stableId9(prefix, value) { - return `${prefix}_${createHash16("sha256").update(value).digest("hex").slice(0, 20)}`; +function stableId10(prefix, value) { + return `${prefix}_${createHash17("sha256").update(value).digest("hex").slice(0, 20)}`; } function estimateTokenCount4(text) { const words = text.trim().split(/\s+/).filter(Boolean).length; @@ -45256,7 +45838,7 @@ function provenanceFor(artifact) { } function recordWikiChunk(db, pageId, title, artifact, body, now) { const provenance = provenanceFor(artifact); - const chunkId = stableId9("chk", `${pageId}\x00${artifact.hash ?? artifact.uri}`); + const chunkId = stableId10("chk", `${pageId}\x00${artifact.hash ?? artifact.uri}`); const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(pageId); for (const row of existing) db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); @@ -45292,7 +45874,7 @@ function recordWikiLayoutCatalog(db, artifacts, now = new Date) { artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`, [ - stableId9("idx", "root:indexes/root.md"), + stableId10("idx", "root:indexes/root.md"), "root", "root", rootIndex.uri, @@ -45307,7 +45889,7 @@ function recordWikiLayoutCatalog(db, artifacts, now = new Date) { ]); } if (wikiReadme) { - const wikiPageId = stableId9("wiki", "wiki/README.md"); + const wikiPageId = stableId10("wiki", "wiki/README.md"); db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET @@ -45335,7 +45917,7 @@ function recordWikiLayoutCatalog(db, artifacts, now = new Date) { } // src/workspace-migration.ts -import { createHash as createHash17 } from "crypto"; +import { createHash as createHash18 } from "crypto"; import { cpSync, chmodSync as chmodSync4, @@ -45362,12 +45944,12 @@ function walkFiles(root, base = root) { function hashFiles(root, files) { if (files.length === 0) return { sha256: null, bytes: 0 }; - const tree = createHash17("sha256"); + const tree = createHash18("sha256"); let bytes = 0; for (const file2 of files) { const path = join7(root, file2); const body = readFileSync11(path); - const fileHash = createHash17("sha256").update(body).digest("hex"); + const fileHash = createHash18("sha256").update(body).digest("hex"); bytes += body.byteLength; tree.update(file2); tree.update("\x00"); @@ -45982,7 +46564,7 @@ function resolvePeerWorkspace(input) { return ensureKnowledgeWorkspace(workspaceForHome(projectKnowledgeHome(target)).home); } function workspaceMachineId(workspace) { - return `${hostname5()}:${createHash18("sha256").update(workspace.home).digest("hex").slice(0, 12)}`; + return `${hostname5()}:${createHash19("sha256").update(workspace.home).digest("hex").slice(0, 12)}`; } function shellQuote2(value) { return `'${value.replace(/'/g, "'\\''")}'`; @@ -46272,6 +46854,44 @@ function rowsWithJsonFields(rows, fields = ["metadata_json"]) { return next; }); } +function parseInventoryJsonArray(value) { + if (typeof value !== "string") + return []; + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } +} +function parseInventoryJsonObject(value) { + if (typeof value !== "string") + return {}; + return parseMetadataJson(value); +} +function promotionCandidateInventoryRow(row) { + const next = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.requires_approval = next.requires_approval === 1 || next.requires_approval === true; + next.checks = parseInventoryJsonObject(next.checks_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.checks_json; + delete next.metadata_json; + return next; +} +function durableRecordInventoryRow(row) { + const next = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.metadata_json; + return next; +} function selectInventoryRows(db, sql, params = []) { return db.query(sql).all(...params); } @@ -46329,7 +46949,9 @@ function emptyKnowledgeDbStats() { sync_changes: 0, sync_conflicts: 0, sync_table_clocks: 0, - sync_imports: 0 + sync_imports: 0, + promotion_candidates: 0, + durable_records: 0 }; } function emptySearchResult(query2, limit, semantic = false) { @@ -46418,7 +47040,7 @@ function legacyAgentContextPack(options, context, policy) { redactions += quote.redactions; const ref = citation.source_ref ?? citation.source_uri ?? citation.artifact_path ?? citation.artifact_uri ?? citation.id; return { - id: `cite_${createHash18("sha256").update(`${citation.id}\x00${ref}`).digest("hex").slice(0, 12)}`, + id: `cite_${createHash19("sha256").update(`${citation.id}\x00${ref}`).digest("hex").slice(0, 12)}`, kind: citation.artifact_uri || citation.artifact_path ? "artifact" : "source", ref, source_ref: citation.source_ref, @@ -46444,7 +47066,7 @@ function legacyAgentContextPack(options, context, policy) { const preview2 = redactPreviewForPack(excerpt2.text, policy, 520); redactions += preview2.redactions; return { - id: `ev_${createHash18("sha256").update(`${excerpt2.kind}\x00${excerpt2.result_id}\x00${excerpt2.citation_id ?? ""}`).digest("hex").slice(0, 14)}`, + id: `ev_${createHash19("sha256").update(`${excerpt2.kind}\x00${excerpt2.result_id}\x00${excerpt2.citation_id ?? ""}`).digest("hex").slice(0, 14)}`, kind: excerpt2.kind, title: compactText(result?.title ?? citation?.ref ?? excerpt2.kind, 100), text_preview: preview2.text, @@ -46462,7 +47084,7 @@ function legacyAgentContextPack(options, context, policy) { const usedCitationIds = new Set(evidence.flatMap((entry) => entry.citation_ids)); const usedCitations = citations.filter((citation) => usedCitationIds.has(citation.id)); const warnings = Array.from(new Set(context.warnings)); - const idempotencyKey = `ctx_${createHash18("sha256").update([source, purpose, query2, warnings.join(","), evidence.map((entry) => entry.id).join(",")].join("\x00")).digest("hex").slice(0, 20)}`; + const idempotencyKey = `ctx_${createHash19("sha256").update([source, purpose, query2, warnings.join(","), evidence.map((entry) => entry.id).join(",")].join("\x00")).digest("hex").slice(0, 20)}`; const pack = { ok: true, format: "knowledge-agent-context-pack", @@ -46575,7 +47197,7 @@ function emptyAgentContextPack(options) { const query2 = (options.query ?? options.topic ?? "").normalize("NFKC").trim().replace(/\s+/g, " "); const maxItems = Math.max(1, Math.min(options.maxItems ?? options.limit ?? 8, 50)); const maxTokens = Math.max(500, Math.min(options.maxTokens ?? 6000, 1e5)); - const idempotencyKey = `ctx_${createHash18("sha256").update(["empty", source, purpose, query2, options.topic ?? "", options.since ?? ""].join("\x00")).digest("hex").slice(0, 20)}`; + const idempotencyKey = `ctx_${createHash19("sha256").update(["empty", source, purpose, query2, options.topic ?? "", options.since ?? ""].join("\x00")).digest("hex").slice(0, 20)}`; return { ok: true, format: "knowledge-agent-context-pack", @@ -47118,6 +47740,27 @@ class KnowledgeService { return emptyKnowledgeDbStats(); return getKnowledgeDbStats(workspace.knowledgeDbPath); } + enqueuePromotion(input) { + return enqueueKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, input); + } + promotionInbox(options = {}) { + return listKnowledgePromotions(this.ensureWorkspace().knowledgeDbPath, options); + } + getPromotion(id) { + return getKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id); + } + reviewPromotion(id, now) { + return reviewKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, now); + } + promoteCandidate(id, options = {}) { + return promoteKnowledgeCandidate(this.ensureWorkspace().knowledgeDbPath, id, options); + } + rejectPromotion(id, options = {}) { + return rejectKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, options); + } + durableRecords(options = {}) { + return listDurableKnowledgeRecords(this.ensureWorkspace().knowledgeDbPath, options); + } itemOnlyInventory(params) { const workspace = this.workspace; const { items, limit, includeArchived, storePath, storeExists, storeReadError } = params; @@ -47149,7 +47792,9 @@ class KnowledgeService { sync_changes: stats.sync_changes, sync_conflicts: stats.sync_conflicts, sync_table_clocks: stats.sync_table_clocks, - sync_imports: stats.sync_imports + sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records }; return { ok: true, @@ -47190,6 +47835,8 @@ class KnowledgeService { sync_conflicts: [], approval_gates: [], audit_events: [], + promotion_candidates: [], + durable_records: [], message: `${items.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)` }; } @@ -47380,6 +48027,55 @@ class KnowledgeService { ORDER BY created_at DESC LIMIT ? `, [limit])); + const promotionCandidates = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + source_kind, + source_refs_json, + evidence_refs_json, + status, + requires_approval, + checks_json, + duplicate_of, + approved_by, + promoted_record_id, + metadata_json, + created_at, + updated_at, + reviewed_at, + promoted_at + FROM knowledge_promotion_candidates + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(promotionCandidateInventoryRow); + const durableRecords = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + status, + source_refs_json, + evidence_refs_json, + confidence, + valid_from, + valid_to, + promoted_from_candidate_id, + approved_by, + metadata_json, + created_at, + updated_at + FROM durable_knowledge_records + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(durableRecordInventoryRow); const summary = { legacy_items: legacyStore.items.length, active_items: activeItems.length, @@ -47405,7 +48101,9 @@ class KnowledgeService { sync_changes: stats.sync_changes, sync_conflicts: stats.sync_conflicts, sync_table_clocks: stats.sync_table_clocks, - sync_imports: stats.sync_imports + sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records }; return { ok: true, @@ -47446,6 +48144,8 @@ class KnowledgeService { sync_conflicts: syncConflicts, approval_gates: approvalGates, audit_events: auditEvents, + promotion_candidates: promotionCandidates, + durable_records: durableRecords, message: `${legacyStore.items.length} item(s), ${stats.sources} source(s), ${stats.chunks} chunk(s), ${stats.wiki_pages} wiki page(s), ${stats.storage_objects} artifact(s)` }; } finally { diff --git a/bin/knowledge.js b/bin/knowledge.js index 15a2ca3..47f4092 100755 --- a/bin/knowledge.js +++ b/bin/knowledge.js @@ -1,104 +1,104 @@ #!/usr/bin/env bun // @bun -var Wb=Object.create;var{getPrototypeOf:Ub,defineProperty:YQ,getOwnPropertyNames:Xb}=Object;var Gb=Object.prototype.hasOwnProperty;function Qb($){return this[$]}var Yb,qb,zb=($,_,J)=>{var U=$!=null&&typeof $==="object";if(U){var W=_?Yb??=new WeakMap:qb??=new WeakMap,X=W.get($);if(X)return X}J=$!=null?Wb(Ub($)):{};let G=_||!$||!$.__esModule?YQ(J,"default",{value:$,enumerable:!0}):J;for(let Q of Xb($))if(!Gb.call(G,Q))YQ(G,Q,{get:Qb.bind($,Q),enumerable:!0});if(U)W.set($,G);return G};var i1=($,_)=>()=>(_||$((_={exports:{}}).exports,_),_.exports);var jb=($)=>$;function Ob($,_){this[$]=jb.bind(null,_)}var s4=($,_)=>{for(var J in _)YQ($,J,{get:_[J],enumerable:!0,configurable:!0,set:Ob.bind(_,J)})};var m=($,_)=>()=>($&&(_=$($=0)),_);var n$=import.meta.require;function A($,_,J){function U(Q,Y){if(!Q._zod)Object.defineProperty(Q,"_zod",{value:{def:Y,constr:G,traits:new Set},enumerable:!1});if(Q._zod.traits.has($))return;Q._zod.traits.add($),_(Q,Y);let q=G.prototype,L=Object.keys(q);for(let N=0;N{if(J?.Parent&&Q instanceof J.Parent)return!0;return Q?._zod?.traits?.has($)}}),Object.defineProperty(G,"name",{value:$}),G}function N6($){if($)Object.assign(f2,$);return f2}var aV,Y8,q8,O0,C2,f2;var P2=m(()=>{Y8=Object.freeze({status:"aborted"});q8=Symbol("zod_brand");O0=class O0 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};C2=class C2 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(aV=globalThis).__zod_globalConfig??(aV.__zod_globalConfig={});f2=globalThis.__zod_globalConfig});var C={};s4(C,{unwrapMessage:()=>IU,uint8ArrayToHex:()=>sh,uint8ArrayToBase64url:()=>th,uint8ArrayToBase64:()=>$F,stringifyPrimitive:()=>k,slugify:()=>_7,shallowClone:()=>W7,safeExtend:()=>lh,required:()=>rh,randomString:()=>yh,propertyKeyTypes:()=>fU,promiseAllObject:()=>vh,primitiveTypes:()=>U7,prefixIssues:()=>r6,pick:()=>uh,partial:()=>ih,parsedType:()=>f,optionalKeys:()=>X7,omit:()=>dh,objectClone:()=>Th,numKeys:()=>hh,nullish:()=>w1,normalizeParams:()=>y,mergeDefs:()=>c0,merge:()=>nh,jsonStringifyReplacer:()=>hJ,joinValues:()=>E,issue:()=>xJ,isPlainObject:()=>g1,isObject:()=>T2,hexToUint8Array:()=>ah,getSizableOrigin:()=>CU,getParsedType:()=>mh,getLengthableOrigin:()=>PU,getEnumValues:()=>gU,getElementAtPath:()=>Zh,floatSafeRemainder:()=>$7,finalizeIssue:()=>d6,extend:()=>ch,explicitlyAborted:()=>Y7,escapeRegex:()=>N4,esc:()=>z8,defineLazy:()=>Z$,createTransparentProxy:()=>xh,cloneDef:()=>Sh,clone:()=>P6,cleanRegex:()=>kU,cleanEnum:()=>ph,captureStackTrace:()=>j8,cached:()=>mJ,base64urlToUint8Array:()=>oh,base64ToUint8Array:()=>eV,assignProp:()=>I1,assertNotEqual:()=>kh,assertNever:()=>Ch,assertIs:()=>fh,assertEqual:()=>gh,assert:()=>Ph,allowsEval:()=>J7,aborted:()=>k1,NUMBER_FORMAT_RANGES:()=>G7,Class:()=>_F,BIGINT_FORMAT_RANGES:()=>Q7});function gh($){return $}function kh($){return $}function fh($){}function Ch($){throw Error("Unexpected value in exhaustive check")}function Ph($){}function gU($){let _=Object.values($).filter((U)=>typeof U==="number");return Object.entries($).filter(([U,W])=>_.indexOf(+U)===-1).map(([U,W])=>W)}function E($,_="|"){return $.map((J)=>k(J)).join(_)}function hJ($,_){if(typeof _==="bigint")return _.toString();return _}function mJ($){return{get value(){{let J=$();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function w1($){return $===null||$===void 0}function kU($){let _=$.startsWith("^")?1:0,J=$.endsWith("$")?$.length-1:$.length;return $.slice(_,J)}function $7($,_){let J=$/_,U=Math.round(J),W=Number.EPSILON*Math.max(Math.abs(J),1);if(Math.abs(J-U)J?.[U],$)}function vh($){let _=Object.keys($),J=_.map((U)=>$[U]);return Promise.all(J).then((U)=>{let W={};for(let X=0;X<_.length;X++)W[_[X]]=U[X];return W})}function yh($=10){let J="";for(let U=0;U<$;U++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function z8($){return JSON.stringify($)}function _7($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function T2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function g1($){if(T2($)===!1)return!1;let _=$.constructor;if(_===void 0)return!0;if(typeof _!=="function")return!0;let J=_.prototype;if(T2(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function W7($){if(g1($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function hh($){let _=0;for(let J in $)if(Object.prototype.hasOwnProperty.call($,J))_++;return _}function N4($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function P6($,_,J){let U=new $._zod.constr(_??$._zod.def);if(!_||J?.parent)U._zod.parent=$;return U}function y($){let _=$;if(!_)return{};if(typeof _==="string")return{error:()=>_};if(_?.message!==void 0){if(_?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");_.error=_.message}if(delete _.message,typeof _.error==="string")return{..._,error:()=>_.error};return _}function xh($){let _;return new Proxy({},{get(J,U,W){return _??(_=$()),Reflect.get(_,U,W)},set(J,U,W,X){return _??(_=$()),Reflect.set(_,U,W,X)},has(J,U){return _??(_=$()),Reflect.has(_,U)},deleteProperty(J,U){return _??(_=$()),Reflect.deleteProperty(_,U)},ownKeys(J){return _??(_=$()),Reflect.ownKeys(_)},getOwnPropertyDescriptor(J,U){return _??(_=$()),Reflect.getOwnPropertyDescriptor(_,U)},defineProperty(J,U,W){return _??(_=$()),Reflect.defineProperty(_,U,W)}})}function k($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function X7($){return Object.keys($).filter((_)=>{return $[_]._zod.optin==="optional"&&$[_]._zod.optout==="optional"})}function uh($,_){let J=$._zod.def,U=J.checks;if(U&&U.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let X=c0($._zod.def,{get shape(){let G={};for(let Q in _){if(!(Q in J.shape))throw Error(`Unrecognized key: "${Q}"`);if(!_[Q])continue;G[Q]=J.shape[Q]}return I1(this,"shape",G),G},checks:[]});return P6($,X)}function dh($,_){let J=$._zod.def,U=J.checks;if(U&&U.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let X=c0($._zod.def,{get shape(){let G={...$._zod.def.shape};for(let Q in _){if(!(Q in J.shape))throw Error(`Unrecognized key: "${Q}"`);if(!_[Q])continue;delete G[Q]}return I1(this,"shape",G),G},checks:[]});return P6($,X)}function ch($,_){if(!g1(_))throw Error("Invalid input to extend: expected a plain object");let J=$._zod.def.checks;if(J&&J.length>0){let X=$._zod.def.shape;for(let G in _)if(Object.getOwnPropertyDescriptor(X,G)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let W=c0($._zod.def,{get shape(){let X={...$._zod.def.shape,..._};return I1(this,"shape",X),X}});return P6($,W)}function lh($,_){if(!g1(_))throw Error("Invalid input to safeExtend: expected a plain object");let J=c0($._zod.def,{get shape(){let U={...$._zod.def.shape,..._};return I1(this,"shape",U),U}});return P6($,J)}function nh($,_){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let J=c0($._zod.def,{get shape(){let U={...$._zod.def.shape,..._._zod.def.shape};return I1(this,"shape",U),U},get catchall(){return _._zod.def.catchall},checks:_._zod.def.checks??[]});return P6($,J)}function ih($,_,J){let W=_._zod.def.checks;if(W&&W.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let G=c0(_._zod.def,{get shape(){let Q=_._zod.def.shape,Y={...Q};if(J)for(let q in J){if(!(q in Q))throw Error(`Unrecognized key: "${q}"`);if(!J[q])continue;Y[q]=$?new $({type:"optional",innerType:Q[q]}):Q[q]}else for(let q in Q)Y[q]=$?new $({type:"optional",innerType:Q[q]}):Q[q];return I1(this,"shape",Y),Y},checks:[]});return P6(_,G)}function rh($,_,J){let U=c0(_._zod.def,{get shape(){let W=_._zod.def.shape,X={...W};if(J)for(let G in J){if(!(G in X))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;X[G]=new $({type:"nonoptional",innerType:W[G]})}else for(let G in W)X[G]=new $({type:"nonoptional",innerType:W[G]});return I1(this,"shape",X),X}});return P6(_,U)}function k1($,_=0){if($.aborted===!0)return!0;for(let J=_;J<$.issues.length;J++)if($.issues[J]?.continue!==!0)return!0;return!1}function Y7($,_=0){if($.aborted===!0)return!0;for(let J=_;J<$.issues.length;J++)if($.issues[J]?.continue===!1)return!0;return!1}function r6($,_){return _.map((J)=>{var U;return(U=J).path??(U.path=[]),J.path.unshift($),J})}function IU($){return typeof $==="string"?$:$?.message}function d6($,_,J){let U=$.message?$.message:IU($.inst?._zod.def?.error?.($))??IU(_?.error?.($))??IU(J.customError?.($))??IU(J.localeError?.($))??"Invalid input",{inst:W,continue:X,input:G,...Q}=$;if(Q.path??(Q.path=[]),Q.message=U,_?.reportInput)Q.input=G;return Q}function CU($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function PU($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function f($){let _=typeof $;switch(_){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let J=$;if(J&&Object.getPrototypeOf(J)!==Object.prototype&&"constructor"in J&&J.constructor)return J.constructor.name}}return _}function xJ(...$){let[_,J,U]=$;if(typeof _==="string")return{message:_,code:"custom",input:J,inst:U};return{..._}}function ph($){return Object.entries($).filter(([_,J])=>{return Number.isNaN(Number.parseInt(_,10))}).map((_)=>_[1])}function eV($){let _=atob($),J=new Uint8Array(_.length);for(let U=0;U<_.length;U++)J[U]=_.charCodeAt(U);return J}function $F($){let _="";for(let J=0;J<$.length;J++)_+=String.fromCharCode($[J]);return btoa(_)}function oh($){let _=$.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-_.length%4)%4);return eV(_+J)}function th($){return $F($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ah($){let _=$.replace(/^0x/,"");if(_.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(_.length/2);for(let U=0;U<_.length;U+=2)J[U/2]=Number.parseInt(_.slice(U,U+2),16);return J}function sh($){return Array.from($).map((_)=>_.toString(16).padStart(2,"0")).join("")}class _F{constructor(...$){}}var sV,j8,J7,mh=($)=>{let _=typeof $;switch(_){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${_}`)}},fU,U7,G7,Q7;var s=m(()=>{P2();sV=Symbol("evaluating");j8="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};J7=mJ(()=>{if(f2.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});fU=new Set(["string","number","symbol"]),U7=new Set(["string","number","bigint","boolean","symbol","undefined"]);G7={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Q7={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function uJ($,_=(J)=>J.message){let J={},U=[];for(let W of $.issues)if(W.path.length>0)J[W.path[0]]=J[W.path[0]]||[],J[W.path[0]].push(_(W));else U.push(_(W));return{formErrors:U,fieldErrors:J}}function dJ($,_=(J)=>J.message){let J={_errors:[]},U=(W,X=[])=>{for(let G of W.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((Q)=>U({issues:Q},[...X,...G.path]));else if(G.code==="invalid_key")U({issues:G.issues},[...X,...G.path]);else if(G.code==="invalid_element")U({issues:G.issues},[...X,...G.path]);else{let Q=[...X,...G.path];if(Q.length===0)J._errors.push(_(G));else{let Y=J,q=0;while(qJ.message){let J={errors:[]},U=(W,X=[])=>{var G,Q;for(let Y of W.issues)if(Y.code==="invalid_union"&&Y.errors.length)Y.errors.map((q)=>U({issues:q},[...X,...Y.path]));else if(Y.code==="invalid_key")U({issues:Y.issues},[...X,...Y.path]);else if(Y.code==="invalid_element")U({issues:Y.issues},[...X,...Y.path]);else{let q=[...X,...Y.path];if(q.length===0){J.errors.push(_(Y));continue}let L=J,N=0;while(Ntypeof U==="object"?U.key:U);for(let U of J)if(typeof U==="number")_.push(`[${U}]`);else if(typeof U==="symbol")_.push(`[${JSON.stringify(String(U))}]`);else if(/[^\w$]/.test(U))_.push(`[${JSON.stringify(U)}]`);else{if(_.length)_.push(".");_.push(U)}return _.join("")}function D8($){let _=[],J=[...$.issues].sort((U,W)=>(U.path??[]).length-(W.path??[]).length);for(let U of J)if(_.push(`\u2716 ${U.message}`),U.path?.length)_.push(` \u2192 at ${WF(U.path)}`);return _.join(` -`)}var JF=($,_)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:_,enumerable:!1}),$.message=JSON.stringify(_,hJ,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},TU,p6;var q7=m(()=>{P2();s();TU=A("$ZodError",JF),p6=A("$ZodError",JF,{Parent:Error})});var cJ=($)=>(_,J,U,W)=>{let X=U?{...U,async:!1}:{async:!1},G=_._zod.run({value:J,issues:[]},X);if(G instanceof Promise)throw new O0;if(G.issues.length){let Q=new(W?.Err??$)(G.issues.map((Y)=>d6(Y,X,N6())));throw j8(Q,W?.callee),Q}return G.value},L8,lJ=($)=>async(_,J,U,W)=>{let X=U?{...U,async:!0}:{async:!0},G=_._zod.run({value:J,issues:[]},X);if(G instanceof Promise)G=await G;if(G.issues.length){let Q=new(W?.Err??$)(G.issues.map((Y)=>d6(Y,X,N6())));throw j8(Q,W?.callee),Q}return G.value},B8,nJ=($)=>(_,J,U)=>{let W=U?{...U,async:!1}:{async:!1},X=_._zod.run({value:J,issues:[]},W);if(X instanceof Promise)throw new O0;return X.issues.length?{success:!1,error:new($??TU)(X.issues.map((G)=>d6(G,W,N6())))}:{success:!0,data:X.value}},z7,iJ=($)=>async(_,J,U)=>{let W=U?{...U,async:!0}:{async:!0},X=_._zod.run({value:J,issues:[]},W);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new $(X.issues.map((G)=>d6(G,W,N6())))}:{success:!0,data:X.value}},j7,H8=($)=>(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return cJ($)(_,J,W)},$m,N8=($)=>(_,J,U)=>{return cJ($)(_,J,U)},_m,V8=($)=>async(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return lJ($)(_,J,W)},Jm,F8=($)=>async(_,J,U)=>{return lJ($)(_,J,U)},Wm,R8=($)=>(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return nJ($)(_,J,W)},Um,K8=($)=>(_,J,U)=>{return nJ($)(_,J,U)},Xm,M8=($)=>async(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return iJ($)(_,J,W)},Gm,A8=($)=>async(_,J,U)=>{return iJ($)(_,J,U)},Qm;var O7=m(()=>{P2();q7();s();L8=cJ(p6),B8=lJ(p6),z7=nJ(p6),j7=iJ(p6),$m=H8(p6),_m=N8(p6),Jm=V8(p6),Wm=F8(p6),Um=R8(p6),Xm=K8(p6),Gm=M8(p6),Qm=A8(p6)});var o6={};s4(o6,{xid:()=>H7,uuid7:()=>jm,uuid6:()=>zm,uuid4:()=>qm,uuid:()=>S2,uppercase:()=>u7,unicodeEmail:()=>UF,undefined:()=>m7,ulid:()=>B7,time:()=>P7,string:()=>S7,sha512_hex:()=>Pm,sha512_base64url:()=>Sm,sha512_base64:()=>Tm,sha384_hex:()=>km,sha384_base64url:()=>Cm,sha384_base64:()=>fm,sha256_hex:()=>wm,sha256_base64url:()=>gm,sha256_base64:()=>Im,sha1_hex:()=>Am,sha1_base64url:()=>Em,sha1_base64:()=>bm,rfc5322Email:()=>Dm,number:()=>SU,null:()=>h7,nanoid:()=>V7,md5_hex:()=>Rm,md5_base64url:()=>Mm,md5_base64:()=>Km,mac:()=>E7,lowercase:()=>x7,ksuid:()=>N7,ipv6:()=>b7,ipv4:()=>A7,integer:()=>v7,idnEmail:()=>Lm,httpProtocol:()=>k7,html5Email:()=>Om,hostname:()=>Nm,hex:()=>Fm,guid:()=>R7,extendedDuration:()=>Ym,emoji:()=>M7,email:()=>K7,e164:()=>f7,duration:()=>F7,domain:()=>Vm,datetime:()=>T7,date:()=>C7,cuid2:()=>L7,cuid:()=>D7,cidrv6:()=>I7,cidrv4:()=>w7,browserEmail:()=>Bm,boolean:()=>y7,bigint:()=>Z7,base64url:()=>b8,base64:()=>g7});function M7(){return new RegExp(Hm,"u")}function GF($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function P7($){return new RegExp(`^${GF($)}$`)}function T7($){let _=GF({precision:$.precision}),J=["Z"];if($.local)J.push("");if($.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${_}(?:${J.join("|")})`;return new RegExp(`^${XF}T(?:${U})$`)}function ZU($,_){return new RegExp(`^[A-Za-z0-9+/]{${$}}${_}$`)}function vU($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var D7,L7,B7,H7,N7,V7,F7,Ym,R7,S2=($)=>{if(!$)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}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},qm,zm,jm,K7,Om,Dm,UF,Lm,Bm,Hm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",A7,b7,E7=($)=>{let _=N4($??":");return new RegExp(`^(?:[0-9A-F]{2}${_}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${_}){5}[0-9a-f]{2}$`)},w7,I7,g7,b8,Nm,Vm,k7,f7,XF="(?:(?:\\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])))",C7,S7=($)=>{let _=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${_}$`)},Z7,v7,SU,y7,h7,m7,x7,u7,Fm,Rm,Km,Mm,Am,bm,Em,wm,Im,gm,km,fm,Cm,Pm,Tm,Sm;var E8=m(()=>{s();D7=/^[cC][0-9a-z]{6,}$/,L7=/^[0-9a-z]+$/,B7=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,H7=/^[0-9a-vA-V]{20}$/,N7=/^[A-Za-z0-9]{27}$/,V7=/^[a-zA-Z0-9_-]{21}$/,F7=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ym=/^[-+]?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)?)??$/,R7=/^([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})$/,qm=S2(4),zm=S2(6),jm=S2(7),K7=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Om=/^[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])?)*$/,Dm=/^(([^<>()\[\]\\.,;:\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,}))$/,UF=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Lm=UF,Bm=/^[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])?)*$/;A7=/^(?:(?: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])$/,b7=/^(([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}|:))$/,w7=/^((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])$/,I7=/^(([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])$/,g7=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,b8=/^[A-Za-z0-9_-]*$/,Nm=/^(?=.{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])?)*\.?$/,Vm=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,k7=/^https?$/,f7=/^\+[1-9]\d{6,14}$/,C7=new RegExp(`^${XF}$`);Z7=/^-?\d+n?$/,v7=/^-?\d+$/,SU=/^-?\d+(?:\.\d+)?$/,y7=/^(?:true|false)$/i,h7=/^null$/i,m7=/^undefined$/i,x7=/^[^A-Z]*$/,u7=/^[^a-z]*$/,Fm=/^[0-9a-fA-F]*$/;Rm=/^[0-9a-fA-F]{32}$/,Km=ZU(22,"=="),Mm=vU(22),Am=/^[0-9a-fA-F]{40}$/,bm=ZU(27,"="),Em=vU(27),wm=/^[0-9a-fA-F]{64}$/,Im=ZU(43,"="),gm=vU(43),km=/^[0-9a-fA-F]{96}$/,fm=ZU(64,""),Cm=vU(64),Pm=/^[0-9a-fA-F]{128}$/,Tm=ZU(86,"=="),Sm=vU(86)});function QF($,_,J){if($.issues.length)_.issues.push(...r6(J,$.issues))}var W6,YF,w8,I8,d7,c7,l7,n7,i7,r7,p7,o7,t7,rJ,a7,s7,e7,$q,_q,Jq,Wq,Uq,Xq;var g8=m(()=>{P2();E8();s();W6=A("$ZodCheck",($,_)=>{var J;$._zod??($._zod={}),$._zod.def=_,(J=$._zod).onattach??(J.onattach=[])}),YF={number:"number",bigint:"bigint",object:"date"},w8=A("$ZodCheckLessThan",($,_)=>{W6.init($,_);let J=YF[typeof _.value];$._zod.onattach.push((U)=>{let W=U._zod.bag,X=(_.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(_.value{if(_.inclusive?U.value<=_.value:U.value<_.value)return;U.issues.push({origin:J,code:"too_big",maximum:typeof _.value==="object"?_.value.getTime():_.value,input:U.value,inclusive:_.inclusive,inst:$,continue:!_.abort})}}),I8=A("$ZodCheckGreaterThan",($,_)=>{W6.init($,_);let J=YF[typeof _.value];$._zod.onattach.push((U)=>{let W=U._zod.bag,X=(_.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(_.value>X)if(_.inclusive)W.minimum=_.value;else W.exclusiveMinimum=_.value}),$._zod.check=(U)=>{if(_.inclusive?U.value>=_.value:U.value>_.value)return;U.issues.push({origin:J,code:"too_small",minimum:typeof _.value==="object"?_.value.getTime():_.value,input:U.value,inclusive:_.inclusive,inst:$,continue:!_.abort})}}),d7=A("$ZodCheckMultipleOf",($,_)=>{W6.init($,_),$._zod.onattach.push((J)=>{var U;(U=J._zod.bag).multipleOf??(U.multipleOf=_.value)}),$._zod.check=(J)=>{if(typeof J.value!==typeof _.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%_.value===BigInt(0):$7(J.value,_.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:_.value,input:J.value,inst:$,continue:!_.abort})}}),c7=A("$ZodCheckNumberFormat",($,_)=>{W6.init($,_),_.format=_.format||"float64";let J=_.format?.includes("int"),U=J?"int":"number",[W,X]=G7[_.format];$._zod.onattach.push((G)=>{let Q=G._zod.bag;if(Q.format=_.format,Q.minimum=W,Q.maximum=X,J)Q.pattern=v7}),$._zod.check=(G)=>{let Q=G.value;if(J){if(!Number.isInteger(Q)){G.issues.push({expected:U,format:_.format,code:"invalid_type",continue:!1,input:Q,inst:$});return}if(!Number.isSafeInteger(Q)){if(Q>0)G.issues.push({input:Q,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:U,inclusive:!0,continue:!_.abort});else G.issues.push({input:Q,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:U,inclusive:!0,continue:!_.abort});return}}if(QX)G.issues.push({origin:"number",input:Q,code:"too_big",maximum:X,inclusive:!0,inst:$,continue:!_.abort})}}),l7=A("$ZodCheckBigIntFormat",($,_)=>{W6.init($,_);let[J,U]=Q7[_.format];$._zod.onattach.push((W)=>{let X=W._zod.bag;X.format=_.format,X.minimum=J,X.maximum=U}),$._zod.check=(W)=>{let X=W.value;if(XU)W.issues.push({origin:"bigint",input:X,code:"too_big",maximum:U,inclusive:!0,inst:$,continue:!_.abort})}}),n7=A("$ZodCheckMaxSize",($,_)=>{var J;W6.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!w1(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if(_.maximum{let W=U.value;if(W.size<=_.maximum)return;U.issues.push({origin:CU(W),code:"too_big",maximum:_.maximum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),i7=A("$ZodCheckMinSize",($,_)=>{var J;W6.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!w1(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(_.minimum>W)U._zod.bag.minimum=_.minimum}),$._zod.check=(U)=>{let W=U.value;if(W.size>=_.minimum)return;U.issues.push({origin:CU(W),code:"too_small",minimum:_.minimum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),r7=A("$ZodCheckSizeEquals",($,_)=>{var J;W6.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!w1(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.minimum=_.size,W.maximum=_.size,W.size=_.size}),$._zod.check=(U)=>{let W=U.value,X=W.size;if(X===_.size)return;let G=X>_.size;U.issues.push({origin:CU(W),...G?{code:"too_big",maximum:_.size}:{code:"too_small",minimum:_.size},inclusive:!0,exact:!0,input:U.value,inst:$,continue:!_.abort})}}),p7=A("$ZodCheckMaxLength",($,_)=>{var J;W6.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!w1(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if(_.maximum{let W=U.value;if(W.length<=_.maximum)return;let G=PU(W);U.issues.push({origin:G,code:"too_big",maximum:_.maximum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),o7=A("$ZodCheckMinLength",($,_)=>{var J;W6.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!w1(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(_.minimum>W)U._zod.bag.minimum=_.minimum}),$._zod.check=(U)=>{let W=U.value;if(W.length>=_.minimum)return;let G=PU(W);U.issues.push({origin:G,code:"too_small",minimum:_.minimum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),t7=A("$ZodCheckLengthEquals",($,_)=>{var J;W6.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!w1(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.minimum=_.length,W.maximum=_.length,W.length=_.length}),$._zod.check=(U)=>{let W=U.value,X=W.length;if(X===_.length)return;let G=PU(W),Q=X>_.length;U.issues.push({origin:G,...Q?{code:"too_big",maximum:_.length}:{code:"too_small",minimum:_.length},inclusive:!0,exact:!0,input:U.value,inst:$,continue:!_.abort})}}),rJ=A("$ZodCheckStringFormat",($,_)=>{var J,U;if(W6.init($,_),$._zod.onattach.push((W)=>{let X=W._zod.bag;if(X.format=_.format,_.pattern)X.patterns??(X.patterns=new Set),X.patterns.add(_.pattern)}),_.pattern)(J=$._zod).check??(J.check=(W)=>{if(_.pattern.lastIndex=0,_.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:_.format,input:W.value,..._.pattern?{pattern:_.pattern.toString()}:{},inst:$,continue:!_.abort})});else(U=$._zod).check??(U.check=()=>{})}),a7=A("$ZodCheckRegex",($,_)=>{rJ.init($,_),$._zod.check=(J)=>{if(_.pattern.lastIndex=0,_.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:_.pattern.toString(),inst:$,continue:!_.abort})}}),s7=A("$ZodCheckLowerCase",($,_)=>{_.pattern??(_.pattern=x7),rJ.init($,_)}),e7=A("$ZodCheckUpperCase",($,_)=>{_.pattern??(_.pattern=u7),rJ.init($,_)}),$q=A("$ZodCheckIncludes",($,_)=>{W6.init($,_);let J=N4(_.includes),U=new RegExp(typeof _.position==="number"?`^.{${_.position}}${J}`:J);_.pattern=U,$._zod.onattach.push((W)=>{let X=W._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(U)}),$._zod.check=(W)=>{if(W.value.includes(_.includes,_.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:_.includes,input:W.value,inst:$,continue:!_.abort})}}),_q=A("$ZodCheckStartsWith",($,_)=>{W6.init($,_);let J=new RegExp(`^${N4(_.prefix)}.*`);_.pattern??(_.pattern=J),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(U)=>{if(U.value.startsWith(_.prefix))return;U.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:_.prefix,input:U.value,inst:$,continue:!_.abort})}}),Jq=A("$ZodCheckEndsWith",($,_)=>{W6.init($,_);let J=new RegExp(`.*${N4(_.suffix)}$`);_.pattern??(_.pattern=J),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(U)=>{if(U.value.endsWith(_.suffix))return;U.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:_.suffix,input:U.value,inst:$,continue:!_.abort})}});Wq=A("$ZodCheckProperty",($,_)=>{W6.init($,_),$._zod.check=(J)=>{let U=_.schema._zod.run({value:J.value[_.property],issues:[]},{});if(U instanceof Promise)return U.then((W)=>QF(W,J,_.property));QF(U,J,_.property);return}}),Uq=A("$ZodCheckMimeType",($,_)=>{W6.init($,_);let J=new Set(_.mime);$._zod.onattach.push((U)=>{U._zod.bag.mime=_.mime}),$._zod.check=(U)=>{if(J.has(U.value.type))return;U.issues.push({code:"invalid_value",values:_.mime,input:U.value.type,inst:$,continue:!_.abort})}}),Xq=A("$ZodCheckOverwrite",($,_)=>{W6.init($,_),$._zod.check=(J)=>{J.value=_.tx(J.value)}})});class k8{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let J=$.split(` +var AA=Object.create;var{getPrototypeOf:bA,defineProperty:BY,getOwnPropertyNames:wA}=Object;var gA=Object.prototype.hasOwnProperty;function kA($){return this[$]}var IA,fA,CA=($,_,J)=>{var U=$!=null&&typeof $==="object";if(U){var W=_?IA??=new WeakMap:fA??=new WeakMap,X=W.get($);if(X)return X}J=$!=null?AA(bA($)):{};let G=_||!$||!$.__esModule?BY(J,"default",{value:$,enumerable:!0}):J;for(let Y of wA($))if(!gA.call(G,Y))BY(G,Y,{get:kA.bind($,Y),enumerable:!0});if(U)W.set($,G);return G};var t0=($,_)=>()=>(_||$((_={exports:{}}).exports,_),_.exports);var PA=($)=>$;function TA($,_){this[$]=PA.bind(null,_)}var e6=($,_)=>{for(var J in _)BY($,J,{get:_[J],enumerable:!0,configurable:!0,set:TA.bind(_,J)})};var x=($,_)=>()=>($&&(_=$($=0)),_);var i$=import.meta.require;function M($,_,J){function U(Y,Q){if(!Y._zod)Object.defineProperty(Y,"_zod",{value:{def:Q,constr:G,traits:new Set},enumerable:!1});if(Y._zod.traits.has($))return;Y._zod.traits.add($),_(Y,Q);let q=G.prototype,L=Object.keys(q);for(let N=0;N{if(J?.Parent&&Y instanceof J.Parent)return!0;return Y?._zod?.traits?.has($)}}),Object.defineProperty(G,"name",{value:$}),G}function V_($){if($)Object.assign(T1,$);return T1}var QR,O8,L8,O4,S1,T1;var Z1=x(()=>{O8=Object.freeze({status:"aborted"});L8=Symbol("zod_brand");O4=class O4 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};S1=class S1 extends Error{constructor($){super(`Encountered unidirectional transform during encode: ${$}`);this.name="ZodEncodeError"}};(QR=globalThis).__zod_globalConfig??(QR.__zod_globalConfig={});T1=globalThis.__zod_globalConfig});var C={};e6(C,{unwrapMessage:()=>PU,uint8ArrayToHex:()=>Em,uint8ArrayToBase64url:()=>Km,uint8ArrayToBase64:()=>jR,stringifyPrimitive:()=>I,slugify:()=>Qq,shallowClone:()=>zq,safeExtend:()=>Lm,required:()=>Nm,randomString:()=>Ym,propertyKeyTypes:()=>ZU,promiseAllObject:()=>Gm,primitiveTypes:()=>jq,prefixIssues:()=>p_,pick:()=>jm,partial:()=>Hm,parsedType:()=>f,optionalKeys:()=>Dq,omit:()=>Dm,objectClone:()=>Wm,numKeys:()=>Qm,nullish:()=>k0,normalizeParams:()=>y,mergeDefs:()=>i4,merge:()=>Bm,jsonStringifyReplacer:()=>nJ,joinValues:()=>b,issue:()=>iJ,isPlainObject:()=>f0,isObject:()=>v1,hexToUint8Array:()=>Fm,getSizableOrigin:()=>vU,getParsedType:()=>qm,getLengthableOrigin:()=>yU,getEnumValues:()=>TU,getElementAtPath:()=>Xm,floatSafeRemainder:()=>Yq,finalizeIssue:()=>n_,extend:()=>Om,explicitlyAborted:()=>Bq,escapeRegex:()=>V6,esc:()=>B8,defineLazy:()=>Z$,createTransparentProxy:()=>zm,cloneDef:()=>Um,clone:()=>T_,cleanRegex:()=>SU,cleanEnum:()=>Vm,captureStackTrace:()=>H8,cached:()=>cJ,base64urlToUint8Array:()=>Rm,base64ToUint8Array:()=>zR,assignProp:()=>I0,assertNotEqual:()=>eh,assertNever:()=>_m,assertIs:()=>$m,assertEqual:()=>sh,assert:()=>Jm,allowsEval:()=>qq,aborted:()=>C0,NUMBER_FORMAT_RANGES:()=>Oq,Class:()=>DR,BIGINT_FORMAT_RANGES:()=>Lq});function sh($){return $}function eh($){return $}function $m($){}function _m($){throw Error("Unexpected value in exhaustive check")}function Jm($){}function TU($){let _=Object.values($).filter((U)=>typeof U==="number");return Object.entries($).filter(([U,W])=>_.indexOf(+U)===-1).map(([U,W])=>W)}function b($,_="|"){return $.map((J)=>I(J)).join(_)}function nJ($,_){if(typeof _==="bigint")return _.toString();return _}function cJ($){return{get value(){{let J=$();return Object.defineProperty(this,"value",{value:J}),J}throw Error("cached value already set")}}}function k0($){return $===null||$===void 0}function SU($){let _=$.startsWith("^")?1:0,J=$.endsWith("$")?$.length-1:$.length;return $.slice(_,J)}function Yq($,_){let J=$/_,U=Math.round(J),W=Number.EPSILON*Math.max(Math.abs(J),1);if(Math.abs(J-U)J?.[U],$)}function Gm($){let _=Object.keys($),J=_.map((U)=>$[U]);return Promise.all(J).then((U)=>{let W={};for(let X=0;X<_.length;X++)W[_[X]]=U[X];return W})}function Ym($=10){let J="";for(let U=0;U<$;U++)J+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return J}function B8($){return JSON.stringify($)}function Qq($){return $.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function v1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function f0($){if(v1($)===!1)return!1;let _=$.constructor;if(_===void 0)return!0;if(typeof _!=="function")return!0;let J=_.prototype;if(v1(J)===!1)return!1;if(Object.prototype.hasOwnProperty.call(J,"isPrototypeOf")===!1)return!1;return!0}function zq($){if(f0($))return{...$};if(Array.isArray($))return[...$];if($ instanceof Map)return new Map($);if($ instanceof Set)return new Set($);return $}function Qm($){let _=0;for(let J in $)if(Object.prototype.hasOwnProperty.call($,J))_++;return _}function V6($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function T_($,_,J){let U=new $._zod.constr(_??$._zod.def);if(!_||J?.parent)U._zod.parent=$;return U}function y($){let _=$;if(!_)return{};if(typeof _==="string")return{error:()=>_};if(_?.message!==void 0){if(_?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");_.error=_.message}if(delete _.message,typeof _.error==="string")return{..._,error:()=>_.error};return _}function zm($){let _;return new Proxy({},{get(J,U,W){return _??(_=$()),Reflect.get(_,U,W)},set(J,U,W,X){return _??(_=$()),Reflect.set(_,U,W,X)},has(J,U){return _??(_=$()),Reflect.has(_,U)},deleteProperty(J,U){return _??(_=$()),Reflect.deleteProperty(_,U)},ownKeys(J){return _??(_=$()),Reflect.ownKeys(_)},getOwnPropertyDescriptor(J,U){return _??(_=$()),Reflect.getOwnPropertyDescriptor(_,U)},defineProperty(J,U,W){return _??(_=$()),Reflect.defineProperty(_,U,W)}})}function I($){if(typeof $==="bigint")return $.toString()+"n";if(typeof $==="string")return`"${$}"`;return`${$}`}function Dq($){return Object.keys($).filter((_)=>{return $[_]._zod.optin==="optional"&&$[_]._zod.optout==="optional"})}function jm($,_){let J=$._zod.def,U=J.checks;if(U&&U.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let X=i4($._zod.def,{get shape(){let G={};for(let Y in _){if(!(Y in J.shape))throw Error(`Unrecognized key: "${Y}"`);if(!_[Y])continue;G[Y]=J.shape[Y]}return I0(this,"shape",G),G},checks:[]});return T_($,X)}function Dm($,_){let J=$._zod.def,U=J.checks;if(U&&U.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let X=i4($._zod.def,{get shape(){let G={...$._zod.def.shape};for(let Y in _){if(!(Y in J.shape))throw Error(`Unrecognized key: "${Y}"`);if(!_[Y])continue;delete G[Y]}return I0(this,"shape",G),G},checks:[]});return T_($,X)}function Om($,_){if(!f0(_))throw Error("Invalid input to extend: expected a plain object");let J=$._zod.def.checks;if(J&&J.length>0){let X=$._zod.def.shape;for(let G in _)if(Object.getOwnPropertyDescriptor(X,G)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let W=i4($._zod.def,{get shape(){let X={...$._zod.def.shape,..._};return I0(this,"shape",X),X}});return T_($,W)}function Lm($,_){if(!f0(_))throw Error("Invalid input to safeExtend: expected a plain object");let J=i4($._zod.def,{get shape(){let U={...$._zod.def.shape,..._};return I0(this,"shape",U),U}});return T_($,J)}function Bm($,_){if($._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let J=i4($._zod.def,{get shape(){let U={...$._zod.def.shape,..._._zod.def.shape};return I0(this,"shape",U),U},get catchall(){return _._zod.def.catchall},checks:_._zod.def.checks??[]});return T_($,J)}function Hm($,_,J){let W=_._zod.def.checks;if(W&&W.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let G=i4(_._zod.def,{get shape(){let Y=_._zod.def.shape,Q={...Y};if(J)for(let q in J){if(!(q in Y))throw Error(`Unrecognized key: "${q}"`);if(!J[q])continue;Q[q]=$?new $({type:"optional",innerType:Y[q]}):Y[q]}else for(let q in Y)Q[q]=$?new $({type:"optional",innerType:Y[q]}):Y[q];return I0(this,"shape",Q),Q},checks:[]});return T_(_,G)}function Nm($,_,J){let U=i4(_._zod.def,{get shape(){let W=_._zod.def.shape,X={...W};if(J)for(let G in J){if(!(G in X))throw Error(`Unrecognized key: "${G}"`);if(!J[G])continue;X[G]=new $({type:"nonoptional",innerType:W[G]})}else for(let G in W)X[G]=new $({type:"nonoptional",innerType:W[G]});return I0(this,"shape",X),X}});return T_(_,U)}function C0($,_=0){if($.aborted===!0)return!0;for(let J=_;J<$.issues.length;J++)if($.issues[J]?.continue!==!0)return!0;return!1}function Bq($,_=0){if($.aborted===!0)return!0;for(let J=_;J<$.issues.length;J++)if($.issues[J]?.continue===!1)return!0;return!1}function p_($,_){return _.map((J)=>{var U;return(U=J).path??(U.path=[]),J.path.unshift($),J})}function PU($){return typeof $==="string"?$:$?.message}function n_($,_,J){let U=$.message?$.message:PU($.inst?._zod.def?.error?.($))??PU(_?.error?.($))??PU(J.customError?.($))??PU(J.localeError?.($))??"Invalid input",{inst:W,continue:X,input:G,...Y}=$;if(Y.path??(Y.path=[]),Y.message=U,_?.reportInput)Y.input=G;return Y}function vU($){if($ instanceof Set)return"set";if($ instanceof Map)return"map";if($ instanceof File)return"file";return"unknown"}function yU($){if(Array.isArray($))return"array";if(typeof $==="string")return"string";return"unknown"}function f($){let _=typeof $;switch(_){case"number":return Number.isNaN($)?"nan":"number";case"object":{if($===null)return"null";if(Array.isArray($))return"array";let J=$;if(J&&Object.getPrototypeOf(J)!==Object.prototype&&"constructor"in J&&J.constructor)return J.constructor.name}}return _}function iJ(...$){let[_,J,U]=$;if(typeof _==="string")return{message:_,code:"custom",input:J,inst:U};return{..._}}function Vm($){return Object.entries($).filter(([_,J])=>{return Number.isNaN(Number.parseInt(_,10))}).map((_)=>_[1])}function zR($){let _=atob($),J=new Uint8Array(_.length);for(let U=0;U<_.length;U++)J[U]=_.charCodeAt(U);return J}function jR($){let _="";for(let J=0;J<$.length;J++)_+=String.fromCharCode($[J]);return btoa(_)}function Rm($){let _=$.replace(/-/g,"+").replace(/_/g,"/"),J="=".repeat((4-_.length%4)%4);return zR(_+J)}function Km($){return jR($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Fm($){let _=$.replace(/^0x/,"");if(_.length%2!==0)throw Error("Invalid hex string length");let J=new Uint8Array(_.length/2);for(let U=0;U<_.length;U+=2)J[U/2]=Number.parseInt(_.slice(U,U+2),16);return J}function Em($){return Array.from($).map((_)=>_.toString(16).padStart(2,"0")).join("")}class DR{constructor(...$){}}var qR,H8,qq,qm=($)=>{let _=typeof $;switch(_){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN($)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray($))return"array";if($===null)return"null";if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return"promise";if(typeof Map<"u"&&$ instanceof Map)return"map";if(typeof Set<"u"&&$ instanceof Set)return"set";if(typeof Date<"u"&&$ instanceof Date)return"date";if(typeof File<"u"&&$ instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${_}`)}},ZU,jq,Oq,Lq;var e=x(()=>{Z1();qR=Symbol("evaluating");H8="captureStackTrace"in Error?Error.captureStackTrace:(...$)=>{};qq=cJ(()=>{if(T1.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch($){return!1}});ZU=new Set(["string","number","symbol"]),jq=new Set(["string","number","bigint","boolean","symbol","undefined"]);Oq={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Lq={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function lJ($,_=(J)=>J.message){let J={},U=[];for(let W of $.issues)if(W.path.length>0)J[W.path[0]]=J[W.path[0]]||[],J[W.path[0]].push(_(W));else U.push(_(W));return{formErrors:U,fieldErrors:J}}function rJ($,_=(J)=>J.message){let J={_errors:[]},U=(W,X=[])=>{for(let G of W.issues)if(G.code==="invalid_union"&&G.errors.length)G.errors.map((Y)=>U({issues:Y},[...X,...G.path]));else if(G.code==="invalid_key")U({issues:G.issues},[...X,...G.path]);else if(G.code==="invalid_element")U({issues:G.issues},[...X,...G.path]);else{let Y=[...X,...G.path];if(Y.length===0)J._errors.push(_(G));else{let Q=J,q=0;while(qJ.message){let J={errors:[]},U=(W,X=[])=>{var G,Y;for(let Q of W.issues)if(Q.code==="invalid_union"&&Q.errors.length)Q.errors.map((q)=>U({issues:q},[...X,...Q.path]));else if(Q.code==="invalid_key")U({issues:Q.issues},[...X,...Q.path]);else if(Q.code==="invalid_element")U({issues:Q.issues},[...X,...Q.path]);else{let q=[...X,...Q.path];if(q.length===0){J.errors.push(_(Q));continue}let L=J,N=0;while(Ntypeof U==="object"?U.key:U);for(let U of J)if(typeof U==="number")_.push(`[${U}]`);else if(typeof U==="symbol")_.push(`[${JSON.stringify(String(U))}]`);else if(/[^\w$]/.test(U))_.push(`[${JSON.stringify(U)}]`);else{if(_.length)_.push(".");_.push(U)}return _.join("")}function V8($){let _=[],J=[...$.issues].sort((U,W)=>(U.path??[]).length-(W.path??[]).length);for(let U of J)if(_.push(`\u2716 ${U.message}`),U.path?.length)_.push(` \u2192 at ${LR(U.path)}`);return _.join(` +`)}var OR=($,_)=>{$.name="$ZodError",Object.defineProperty($,"_zod",{value:$._zod,enumerable:!1}),Object.defineProperty($,"issues",{value:_,enumerable:!1}),$.message=JSON.stringify(_,nJ,2),Object.defineProperty($,"toString",{value:()=>$.message,enumerable:!1})},hU,o_;var Hq=x(()=>{Z1();e();hU=M("$ZodError",OR),o_=M("$ZodError",OR,{Parent:Error})});var pJ=($)=>(_,J,U,W)=>{let X=U?{...U,async:!1}:{async:!1},G=_._zod.run({value:J,issues:[]},X);if(G instanceof Promise)throw new O4;if(G.issues.length){let Y=new(W?.Err??$)(G.issues.map((Q)=>n_(Q,X,V_())));throw H8(Y,W?.callee),Y}return G.value},R8,oJ=($)=>async(_,J,U,W)=>{let X=U?{...U,async:!0}:{async:!0},G=_._zod.run({value:J,issues:[]},X);if(G instanceof Promise)G=await G;if(G.issues.length){let Y=new(W?.Err??$)(G.issues.map((Q)=>n_(Q,X,V_())));throw H8(Y,W?.callee),Y}return G.value},K8,tJ=($)=>(_,J,U)=>{let W=U?{...U,async:!1}:{async:!1},X=_._zod.run({value:J,issues:[]},W);if(X instanceof Promise)throw new O4;return X.issues.length?{success:!1,error:new($??hU)(X.issues.map((G)=>n_(G,W,V_())))}:{success:!0,data:X.value}},Nq,aJ=($)=>async(_,J,U)=>{let W=U?{...U,async:!0}:{async:!0},X=_._zod.run({value:J,issues:[]},W);if(X instanceof Promise)X=await X;return X.issues.length?{success:!1,error:new $(X.issues.map((G)=>n_(G,W,V_())))}:{success:!0,data:X.value}},Vq,F8=($)=>(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return pJ($)(_,J,W)},Am,E8=($)=>(_,J,U)=>{return pJ($)(_,J,U)},bm,M8=($)=>async(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return oJ($)(_,J,W)},wm,A8=($)=>async(_,J,U)=>{return oJ($)(_,J,U)},gm,b8=($)=>(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return tJ($)(_,J,W)},km,w8=($)=>(_,J,U)=>{return tJ($)(_,J,U)},Im,g8=($)=>async(_,J,U)=>{let W=U?{...U,direction:"backward"}:{direction:"backward"};return aJ($)(_,J,W)},fm,k8=($)=>async(_,J,U)=>{return aJ($)(_,J,U)},Cm;var Rq=x(()=>{Z1();Hq();e();R8=pJ(o_),K8=oJ(o_),Nq=tJ(o_),Vq=aJ(o_),Am=F8(o_),bm=E8(o_),wm=M8(o_),gm=A8(o_),km=b8(o_),Im=w8(o_),fm=g8(o_),Cm=k8(o_)});var t_={};e6(t_,{xid:()=>Mq,uuid7:()=>Zm,uuid6:()=>Sm,uuid4:()=>Tm,uuid:()=>y1,uppercase:()=>pq,unicodeEmail:()=>BR,undefined:()=>lq,ulid:()=>Eq,time:()=>mq,string:()=>uq,sha512_hex:()=>Jx,sha512_base64url:()=>Ux,sha512_base64:()=>Wx,sha384_hex:()=>em,sha384_base64url:()=>_x,sha384_base64:()=>$x,sha256_hex:()=>tm,sha256_base64url:()=>sm,sha256_base64:()=>am,sha1_hex:()=>rm,sha1_base64url:()=>om,sha1_base64:()=>pm,rfc5322Email:()=>ym,number:()=>mU,null:()=>iq,nanoid:()=>bq,md5_hex:()=>cm,md5_base64url:()=>lm,md5_base64:()=>im,mac:()=>Pq,lowercase:()=>rq,ksuid:()=>Aq,ipv6:()=>Cq,ipv4:()=>fq,integer:()=>nq,idnEmail:()=>hm,httpProtocol:()=>vq,html5Email:()=>vm,hostname:()=>um,hex:()=>nm,guid:()=>gq,extendedDuration:()=>Pm,emoji:()=>Iq,email:()=>kq,e164:()=>yq,duration:()=>wq,domain:()=>dm,datetime:()=>xq,date:()=>hq,cuid2:()=>Fq,cuid:()=>Kq,cidrv6:()=>Sq,cidrv4:()=>Tq,browserEmail:()=>mm,boolean:()=>cq,bigint:()=>dq,base64url:()=>I8,base64:()=>Zq});function Iq(){return new RegExp(xm,"u")}function NR($){return typeof $.precision==="number"?$.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":$.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function mq($){return new RegExp(`^${NR($)}$`)}function xq($){let _=NR({precision:$.precision}),J=["Z"];if($.local)J.push("");if($.offset)J.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let U=`${_}(?:${J.join("|")})`;return new RegExp(`^${HR}T(?:${U})$`)}function xU($,_){return new RegExp(`^[A-Za-z0-9+/]{${$}}${_}$`)}function uU($){return new RegExp(`^[A-Za-z0-9_-]{${$}}$`)}var Kq,Fq,Eq,Mq,Aq,bq,wq,Pm,gq,y1=($)=>{if(!$)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}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},Tm,Sm,Zm,kq,vm,ym,BR,hm,mm,xm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",fq,Cq,Pq=($)=>{let _=V6($??":");return new RegExp(`^(?:[0-9A-F]{2}${_}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${_}){5}[0-9a-f]{2}$`)},Tq,Sq,Zq,I8,um,dm,vq,yq,HR="(?:(?:\\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])))",hq,uq=($)=>{let _=$?`[\\s\\S]{${$?.minimum??0},${$?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${_}$`)},dq,nq,mU,cq,iq,lq,rq,pq,nm,cm,im,lm,rm,pm,om,tm,am,sm,em,$x,_x,Jx,Wx,Ux;var f8=x(()=>{e();Kq=/^[cC][0-9a-z]{6,}$/,Fq=/^[0-9a-z]+$/,Eq=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Mq=/^[0-9a-vA-V]{20}$/,Aq=/^[A-Za-z0-9]{27}$/,bq=/^[a-zA-Z0-9_-]{21}$/,wq=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Pm=/^[-+]?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)?)??$/,gq=/^([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})$/,Tm=y1(4),Sm=y1(6),Zm=y1(7),kq=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,vm=/^[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])?)*$/,ym=/^(([^<>()\[\]\\.,;:\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,}))$/,BR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,hm=BR,mm=/^[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])?)*$/;fq=/^(?:(?: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])$/,Cq=/^(([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}|:))$/,Tq=/^((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])$/,Sq=/^(([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])$/,Zq=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,I8=/^[A-Za-z0-9_-]*$/,um=/^(?=.{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])?)*\.?$/,dm=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,vq=/^https?$/,yq=/^\+[1-9]\d{6,14}$/,hq=new RegExp(`^${HR}$`);dq=/^-?\d+n?$/,nq=/^-?\d+$/,mU=/^-?\d+(?:\.\d+)?$/,cq=/^(?:true|false)$/i,iq=/^null$/i,lq=/^undefined$/i,rq=/^[^A-Z]*$/,pq=/^[^a-z]*$/,nm=/^[0-9a-fA-F]*$/;cm=/^[0-9a-fA-F]{32}$/,im=xU(22,"=="),lm=uU(22),rm=/^[0-9a-fA-F]{40}$/,pm=xU(27,"="),om=uU(27),tm=/^[0-9a-fA-F]{64}$/,am=xU(43,"="),sm=uU(43),em=/^[0-9a-fA-F]{96}$/,$x=xU(64,""),_x=uU(64),Jx=/^[0-9a-fA-F]{128}$/,Wx=xU(86,"=="),Ux=uU(86)});function VR($,_,J){if($.issues.length)_.issues.push(...p_(J,$.issues))}var X_,RR,C8,P8,oq,tq,aq,sq,eq,$7,_7,J7,W7,sJ,U7,X7,G7,Y7,Q7,q7,z7,j7,D7;var T8=x(()=>{Z1();f8();e();X_=M("$ZodCheck",($,_)=>{var J;$._zod??($._zod={}),$._zod.def=_,(J=$._zod).onattach??(J.onattach=[])}),RR={number:"number",bigint:"bigint",object:"date"},C8=M("$ZodCheckLessThan",($,_)=>{X_.init($,_);let J=RR[typeof _.value];$._zod.onattach.push((U)=>{let W=U._zod.bag,X=(_.inclusive?W.maximum:W.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(_.value{if(_.inclusive?U.value<=_.value:U.value<_.value)return;U.issues.push({origin:J,code:"too_big",maximum:typeof _.value==="object"?_.value.getTime():_.value,input:U.value,inclusive:_.inclusive,inst:$,continue:!_.abort})}}),P8=M("$ZodCheckGreaterThan",($,_)=>{X_.init($,_);let J=RR[typeof _.value];$._zod.onattach.push((U)=>{let W=U._zod.bag,X=(_.inclusive?W.minimum:W.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(_.value>X)if(_.inclusive)W.minimum=_.value;else W.exclusiveMinimum=_.value}),$._zod.check=(U)=>{if(_.inclusive?U.value>=_.value:U.value>_.value)return;U.issues.push({origin:J,code:"too_small",minimum:typeof _.value==="object"?_.value.getTime():_.value,input:U.value,inclusive:_.inclusive,inst:$,continue:!_.abort})}}),oq=M("$ZodCheckMultipleOf",($,_)=>{X_.init($,_),$._zod.onattach.push((J)=>{var U;(U=J._zod.bag).multipleOf??(U.multipleOf=_.value)}),$._zod.check=(J)=>{if(typeof J.value!==typeof _.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof J.value==="bigint"?J.value%_.value===BigInt(0):Yq(J.value,_.value)===0)return;J.issues.push({origin:typeof J.value,code:"not_multiple_of",divisor:_.value,input:J.value,inst:$,continue:!_.abort})}}),tq=M("$ZodCheckNumberFormat",($,_)=>{X_.init($,_),_.format=_.format||"float64";let J=_.format?.includes("int"),U=J?"int":"number",[W,X]=Oq[_.format];$._zod.onattach.push((G)=>{let Y=G._zod.bag;if(Y.format=_.format,Y.minimum=W,Y.maximum=X,J)Y.pattern=nq}),$._zod.check=(G)=>{let Y=G.value;if(J){if(!Number.isInteger(Y)){G.issues.push({expected:U,format:_.format,code:"invalid_type",continue:!1,input:Y,inst:$});return}if(!Number.isSafeInteger(Y)){if(Y>0)G.issues.push({input:Y,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:U,inclusive:!0,continue:!_.abort});else G.issues.push({input:Y,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:$,origin:U,inclusive:!0,continue:!_.abort});return}}if(YX)G.issues.push({origin:"number",input:Y,code:"too_big",maximum:X,inclusive:!0,inst:$,continue:!_.abort})}}),aq=M("$ZodCheckBigIntFormat",($,_)=>{X_.init($,_);let[J,U]=Lq[_.format];$._zod.onattach.push((W)=>{let X=W._zod.bag;X.format=_.format,X.minimum=J,X.maximum=U}),$._zod.check=(W)=>{let X=W.value;if(XU)W.issues.push({origin:"bigint",input:X,code:"too_big",maximum:U,inclusive:!0,inst:$,continue:!_.abort})}}),sq=M("$ZodCheckMaxSize",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if(_.maximum{let W=U.value;if(W.size<=_.maximum)return;U.issues.push({origin:vU(W),code:"too_big",maximum:_.maximum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),eq=M("$ZodCheckMinSize",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(_.minimum>W)U._zod.bag.minimum=_.minimum}),$._zod.check=(U)=>{let W=U.value;if(W.size>=_.minimum)return;U.issues.push({origin:vU(W),code:"too_small",minimum:_.minimum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),$7=M("$ZodCheckSizeEquals",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.size!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.minimum=_.size,W.maximum=_.size,W.size=_.size}),$._zod.check=(U)=>{let W=U.value,X=W.size;if(X===_.size)return;let G=X>_.size;U.issues.push({origin:vU(W),...G?{code:"too_big",maximum:_.size}:{code:"too_small",minimum:_.size},inclusive:!0,exact:!0,input:U.value,inst:$,continue:!_.abort})}}),_7=M("$ZodCheckMaxLength",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.maximum??Number.POSITIVE_INFINITY;if(_.maximum{let W=U.value;if(W.length<=_.maximum)return;let G=yU(W);U.issues.push({origin:G,code:"too_big",maximum:_.maximum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),J7=M("$ZodCheckMinLength",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(_.minimum>W)U._zod.bag.minimum=_.minimum}),$._zod.check=(U)=>{let W=U.value;if(W.length>=_.minimum)return;let G=yU(W);U.issues.push({origin:G,code:"too_small",minimum:_.minimum,inclusive:!0,input:W,inst:$,continue:!_.abort})}}),W7=M("$ZodCheckLengthEquals",($,_)=>{var J;X_.init($,_),(J=$._zod.def).when??(J.when=(U)=>{let W=U.value;return!k0(W)&&W.length!==void 0}),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.minimum=_.length,W.maximum=_.length,W.length=_.length}),$._zod.check=(U)=>{let W=U.value,X=W.length;if(X===_.length)return;let G=yU(W),Y=X>_.length;U.issues.push({origin:G,...Y?{code:"too_big",maximum:_.length}:{code:"too_small",minimum:_.length},inclusive:!0,exact:!0,input:U.value,inst:$,continue:!_.abort})}}),sJ=M("$ZodCheckStringFormat",($,_)=>{var J,U;if(X_.init($,_),$._zod.onattach.push((W)=>{let X=W._zod.bag;if(X.format=_.format,_.pattern)X.patterns??(X.patterns=new Set),X.patterns.add(_.pattern)}),_.pattern)(J=$._zod).check??(J.check=(W)=>{if(_.pattern.lastIndex=0,_.pattern.test(W.value))return;W.issues.push({origin:"string",code:"invalid_format",format:_.format,input:W.value,..._.pattern?{pattern:_.pattern.toString()}:{},inst:$,continue:!_.abort})});else(U=$._zod).check??(U.check=()=>{})}),U7=M("$ZodCheckRegex",($,_)=>{sJ.init($,_),$._zod.check=(J)=>{if(_.pattern.lastIndex=0,_.pattern.test(J.value))return;J.issues.push({origin:"string",code:"invalid_format",format:"regex",input:J.value,pattern:_.pattern.toString(),inst:$,continue:!_.abort})}}),X7=M("$ZodCheckLowerCase",($,_)=>{_.pattern??(_.pattern=rq),sJ.init($,_)}),G7=M("$ZodCheckUpperCase",($,_)=>{_.pattern??(_.pattern=pq),sJ.init($,_)}),Y7=M("$ZodCheckIncludes",($,_)=>{X_.init($,_);let J=V6(_.includes),U=new RegExp(typeof _.position==="number"?`^.{${_.position}}${J}`:J);_.pattern=U,$._zod.onattach.push((W)=>{let X=W._zod.bag;X.patterns??(X.patterns=new Set),X.patterns.add(U)}),$._zod.check=(W)=>{if(W.value.includes(_.includes,_.position))return;W.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:_.includes,input:W.value,inst:$,continue:!_.abort})}}),Q7=M("$ZodCheckStartsWith",($,_)=>{X_.init($,_);let J=new RegExp(`^${V6(_.prefix)}.*`);_.pattern??(_.pattern=J),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(U)=>{if(U.value.startsWith(_.prefix))return;U.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:_.prefix,input:U.value,inst:$,continue:!_.abort})}}),q7=M("$ZodCheckEndsWith",($,_)=>{X_.init($,_);let J=new RegExp(`.*${V6(_.suffix)}$`);_.pattern??(_.pattern=J),$._zod.onattach.push((U)=>{let W=U._zod.bag;W.patterns??(W.patterns=new Set),W.patterns.add(J)}),$._zod.check=(U)=>{if(U.value.endsWith(_.suffix))return;U.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:_.suffix,input:U.value,inst:$,continue:!_.abort})}});z7=M("$ZodCheckProperty",($,_)=>{X_.init($,_),$._zod.check=(J)=>{let U=_.schema._zod.run({value:J.value[_.property],issues:[]},{});if(U instanceof Promise)return U.then((W)=>VR(W,J,_.property));VR(U,J,_.property);return}}),j7=M("$ZodCheckMimeType",($,_)=>{X_.init($,_);let J=new Set(_.mime);$._zod.onattach.push((U)=>{U._zod.bag.mime=_.mime}),$._zod.check=(U)=>{if(J.has(U.value.type))return;U.issues.push({code:"invalid_value",values:_.mime,input:U.value.type,inst:$,continue:!_.abort})}}),D7=M("$ZodCheckOverwrite",($,_)=>{X_.init($,_),$._zod.check=(J)=>{J.value=_.tx(J.value)}})});class S8{constructor($=[]){if(this.content=[],this.indent=0,this)this.args=$}indented($){this.indent+=1,$(this),this.indent-=1}write($){if(typeof $==="function"){$(this,{execution:"sync"}),$(this,{execution:"async"});return}let J=$.split(` `).filter((X)=>X),U=Math.min(...J.map((X)=>X.length-X.trimStart().length)),W=J.map((X)=>X.slice(U)).map((X)=>" ".repeat(this.indent*2)+X);for(let X of W)this.content.push(X)}compile(){let $=Function,_=this?.args,U=[...(this?.content??[""]).map((W)=>` ${W}`)];return new $(..._,U.join(` -`))}}var Gq;var Qq=m(()=>{Gq={major:4,minor:4,patch:3}});function kq($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function bF($){if(!b8.test($))return!1;let _=$.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),J=_.padEnd(Math.ceil(_.length/4)*4,"=");return kq(J)}function EF($,_=null){try{let J=$.split(".");if(J.length!==3)return!1;let[U]=J;if(!U)return!1;let W=JSON.parse(atob(U));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&(!("alg"in W)||W.alg!==_))return!1;return!0}catch{return!1}}function zF($,_,J){if($.issues.length)_.issues.push(...r6(J,$.issues));_.value[J]=$.value}function T8($,_,J,U,W,X){let G=J in U;if($.issues.length){if(W&&X&&!G)return;_.issues.push(...r6(J,$.issues))}if(!G&&!W){if(!$.issues.length)_.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[J]});return}if($.value===void 0){if(G)_.value[J]=void 0}else _.value[J]=$.value}function wF($){let _=Object.keys($.shape);for(let U of _)if(!$.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${U}": expected a Zod schema`);let J=X7($.shape);return{...$,keys:_,keySet:new Set(_),numKeys:_.length,optionalKeys:new Set(J)}}function IF($,_,J,U,W,X){let G=[],Q=W.keySet,Y=W.catchall._zod,q=Y.def.type,L=Y.optin==="optional",N=Y.optout==="optional";for(let F in _){if(F==="__proto__")continue;if(Q.has(F))continue;if(q==="never"){G.push(F);continue}let B=Y.run({value:_[F],issues:[]},U);if(B instanceof Promise)$.push(B.then((H)=>T8(H,J,F,_,L,N)));else T8(B,J,F,_,L,N)}if(G.length)J.issues.push({code:"unrecognized_keys",keys:G,input:_,inst:X});if(!$.length)return J;return Promise.all($).then(()=>{return J})}function jF($,_,J,U){for(let X of $)if(X.issues.length===0)return _.value=X.value,_;let W=$.filter((X)=>!k1(X));if(W.length===1)return _.value=W[0].value,W[0];return _.issues.push({code:"invalid_union",input:_.value,inst:J,errors:$.map((X)=>X.issues.map((G)=>d6(G,U,N6())))}),_}function OF($,_,J,U){let W=$.filter((X)=>X.issues.length===0);if(W.length===1)return _.value=W[0].value,_;if(W.length===0)_.issues.push({code:"invalid_union",input:_.value,inst:J,errors:$.map((X)=>X.issues.map((G)=>d6(G,U,N6())))});else _.issues.push({code:"invalid_union",input:_.value,inst:J,errors:[],inclusive:!1});return _}function Yq($,_){if($===_)return{valid:!0,data:$};if($ instanceof Date&&_ instanceof Date&&+$===+_)return{valid:!0,data:$};if(g1($)&&g1(_)){let J=Object.keys(_),U=Object.keys($).filter((X)=>J.indexOf(X)!==-1),W={...$,..._};for(let X of U){let G=Yq($[X],_[X]);if(!G.valid)return{valid:!1,mergeErrorPath:[X,...G.mergeErrorPath]};W[X]=G.data}return{valid:!0,data:W}}if(Array.isArray($)&&Array.isArray(_)){if($.length!==_.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let U=0;U<$.length;U++){let W=$[U],X=_[U],G=Yq(W,X);if(!G.valid)return{valid:!1,mergeErrorPath:[U,...G.mergeErrorPath]};J.push(G.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function DF($,_,J){let U=new Map,W;for(let Q of _.issues)if(Q.code==="unrecognized_keys"){W??(W=Q);for(let Y of Q.keys){if(!U.has(Y))U.set(Y,{});U.get(Y).l=!0}}else $.issues.push(Q);for(let Q of J.issues)if(Q.code==="unrecognized_keys")for(let Y of Q.keys){if(!U.has(Y))U.set(Y,{});U.get(Y).r=!0}else $.issues.push(Q);let X=[...U].filter(([,Q])=>Q.l&&Q.r).map(([Q])=>Q);if(X.length&&W)$.issues.push({...W,keys:X});if(k1($))return $;let G=Yq(_.value,J.value);if(!G.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(G.mergeErrorPath)}`);return $.value=G.data,$}function LF($,_){for(let J=$.length-1;J>=0;J--)if($[J]._zod[_]!=="optional")return J+1;return 0}function BF($,_,J){if($.issues.length)_.issues.push(...r6(J,$.issues));_.value[J]=$.value}function HF($,_,J,U,W){for(let X=0;X=W){_.value.length=X;break}_.issues.push(...r6(X,G.issues))}_.value[X]=G.value}for(let X=_.value.length-1;X>=U.length;X--)if(J[X]._zod.optout==="optional"&&_.value[X]===void 0)_.value.length=X;else break;return _}function NF($,_,J,U,W,X,G){if($.issues.length)if(fU.has(typeof U))J.issues.push(...r6(U,$.issues));else J.issues.push({code:"invalid_key",origin:"map",input:W,inst:X,issues:$.issues.map((Q)=>d6(Q,G,N6()))});if(_.issues.length)if(fU.has(typeof U))J.issues.push(...r6(U,_.issues));else J.issues.push({origin:"map",code:"invalid_element",input:W,inst:X,key:U,issues:_.issues.map((Q)=>d6(Q,G,N6()))});J.value.set($.value,_.value)}function VF($,_){if($.issues.length)_.issues.push(...$.issues);_.value.add($.value)}function FF($,_){if(_===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function RF($,_){if($.value===void 0)$.value=_.defaultValue;return $}function KF($,_){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:_});return $}function f8($,_,J){if($.issues.length)return $.aborted=!0,$;return _._zod.run({value:$.value,issues:$.issues,fallback:$.fallback},J)}function C8($,_,J){if($.issues.length)return $.aborted=!0,$;if((J.direction||"forward")==="forward"){let W=_.transform($.value,$);if(W instanceof Promise)return W.then((X)=>P8($,X,_.out,J));return P8($,W,_.out,J)}else{let W=_.reverseTransform($.value,$);if(W instanceof Promise)return W.then((X)=>P8($,X,_.in,J));return P8($,W,_.in,J)}}function P8($,_,J,U){if($.issues.length)return $.aborted=!0,$;return J._zod.run({value:_,issues:$.issues},U)}function MF($){return $.value=Object.freeze($.value),$}function AF($,_,J,U){if(!$){let W={code:"custom",input:J,inst:U,path:[...U._zod.def.path??[]],continue:!U._zod.def.abort};if(U._zod.def.params)W.params=U._zod.def.params;_.issues.push(xJ(W))}}var F$,Z2,_6,qq,zq,jq,Oq,Dq,Lq,Bq,Hq,Nq,Vq,Fq,Rq,Kq,Mq,Aq,bq,Eq,wq,Iq,gq,fq,Cq,Pq,Tq,Sq,S8,Zq,yU,Z8,vq,yq,hq,mq,xq,uq,dq,cq,lq,nq,gF,iq,hU,rq,pq,oq,v8,tq,aq,sq,eq,$z,_z,Jz,y8,Wz,Uz,Xz,Gz,Qz,Yz,qz,zz,h8,mU,jz,Oz,Dz,Lz,Bz,Hz,Nz;var Vz=m(()=>{g8();P2();O7();E8();s();Qq();s();F$=A("$ZodType",($,_)=>{var J;$??($={}),$._zod.def=_,$._zod.bag=$._zod.bag||{},$._zod.version=Gq;let U=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))U.unshift($);for(let W of U)for(let X of W._zod.onattach)X($);if(U.length===0)(J=$._zod).deferred??(J.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let W=(G,Q,Y)=>{let q=k1(G),L;for(let N of Q){if(N._zod.def.when){if(Y7(G))continue;if(!N._zod.def.when(G))continue}else if(q)continue;let F=G.issues.length,B=N._zod.check(G);if(B instanceof Promise&&Y?.async===!1)throw new O0;if(L||B instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await B,G.issues.length===F)return;if(!q)q=k1(G,F)});else{if(G.issues.length===F)continue;if(!q)q=k1(G,F)}}if(L)return L.then(()=>{return G});return G},X=(G,Q,Y)=>{if(k1(G))return G.aborted=!0,G;let q=W(Q,U,Y);if(q instanceof Promise){if(Y.async===!1)throw new O0;return q.then((L)=>$._zod.parse(L,Y))}return $._zod.parse(q,Y)};$._zod.run=(G,Q)=>{if(Q.skipChecks)return $._zod.parse(G,Q);if(Q.direction==="backward"){let q=$._zod.parse({value:G.value,issues:[]},{...Q,skipChecks:!0});if(q instanceof Promise)return q.then((L)=>{return X(L,G,Q)});return X(q,G,Q)}let Y=$._zod.parse(G,Q);if(Y instanceof Promise){if(Q.async===!1)throw new O0;return Y.then((q)=>W(q,U,Q))}return W(Y,U,Q)}}Z$($,"~standard",()=>({validate:(W)=>{try{let X=z7($,W);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return j7($,W).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}))}),Z2=A("$ZodString",($,_)=>{F$.init($,_),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??S7($._zod.bag),$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=String(J.value)}catch(W){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:$}),J}}),_6=A("$ZodStringFormat",($,_)=>{rJ.init($,_),Z2.init($,_)}),qq=A("$ZodGUID",($,_)=>{_.pattern??(_.pattern=R7),_6.init($,_)}),zq=A("$ZodUUID",($,_)=>{if(_.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[_.version];if(U===void 0)throw Error(`Invalid UUID version: "${_.version}"`);_.pattern??(_.pattern=S2(U))}else _.pattern??(_.pattern=S2());_6.init($,_)}),jq=A("$ZodEmail",($,_)=>{_.pattern??(_.pattern=K7),_6.init($,_)}),Oq=A("$ZodURL",($,_)=>{_6.init($,_),$._zod.check=(J)=>{try{let U=J.value.trim();if(!_.normalize&&_.protocol?.source===k7.source){if(!/^https?:\/\//i.test(U)){J.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:J.value,inst:$,continue:!_.abort});return}}let W=new URL(U);if(_.hostname){if(_.hostname.lastIndex=0,!_.hostname.test(W.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_.hostname.source,input:J.value,inst:$,continue:!_.abort})}if(_.protocol){if(_.protocol.lastIndex=0,!_.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:_.protocol.source,input:J.value,inst:$,continue:!_.abort})}if(_.normalize)J.value=W.href;else J.value=U;return}catch(U){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:$,continue:!_.abort})}}}),Dq=A("$ZodEmoji",($,_)=>{_.pattern??(_.pattern=M7()),_6.init($,_)}),Lq=A("$ZodNanoID",($,_)=>{_.pattern??(_.pattern=V7),_6.init($,_)}),Bq=A("$ZodCUID",($,_)=>{_.pattern??(_.pattern=D7),_6.init($,_)}),Hq=A("$ZodCUID2",($,_)=>{_.pattern??(_.pattern=L7),_6.init($,_)}),Nq=A("$ZodULID",($,_)=>{_.pattern??(_.pattern=B7),_6.init($,_)}),Vq=A("$ZodXID",($,_)=>{_.pattern??(_.pattern=H7),_6.init($,_)}),Fq=A("$ZodKSUID",($,_)=>{_.pattern??(_.pattern=N7),_6.init($,_)}),Rq=A("$ZodISODateTime",($,_)=>{_.pattern??(_.pattern=T7(_)),_6.init($,_)}),Kq=A("$ZodISODate",($,_)=>{_.pattern??(_.pattern=C7),_6.init($,_)}),Mq=A("$ZodISOTime",($,_)=>{_.pattern??(_.pattern=P7(_)),_6.init($,_)}),Aq=A("$ZodISODuration",($,_)=>{_.pattern??(_.pattern=F7),_6.init($,_)}),bq=A("$ZodIPv4",($,_)=>{_.pattern??(_.pattern=A7),_6.init($,_),$._zod.bag.format="ipv4"}),Eq=A("$ZodIPv6",($,_)=>{_.pattern??(_.pattern=b7),_6.init($,_),$._zod.bag.format="ipv6",$._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:$,continue:!_.abort})}}}),wq=A("$ZodMAC",($,_)=>{_.pattern??(_.pattern=E7(_.delimiter)),_6.init($,_),$._zod.bag.format="mac"}),Iq=A("$ZodCIDRv4",($,_)=>{_.pattern??(_.pattern=w7),_6.init($,_)}),gq=A("$ZodCIDRv6",($,_)=>{_.pattern??(_.pattern=I7),_6.init($,_),$._zod.check=(J)=>{let U=J.value.split("/");try{if(U.length!==2)throw Error();let[W,X]=U;if(!X)throw Error();let G=Number(X);if(`${G}`!==X)throw Error();if(G<0||G>128)throw Error();new URL(`http://[${W}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:$,continue:!_.abort})}}});fq=A("$ZodBase64",($,_)=>{_.pattern??(_.pattern=g7),_6.init($,_),$._zod.bag.contentEncoding="base64",$._zod.check=(J)=>{if(kq(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:$,continue:!_.abort})}});Cq=A("$ZodBase64URL",($,_)=>{_.pattern??(_.pattern=b8),_6.init($,_),$._zod.bag.contentEncoding="base64url",$._zod.check=(J)=>{if(bF(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:$,continue:!_.abort})}}),Pq=A("$ZodE164",($,_)=>{_.pattern??(_.pattern=f7),_6.init($,_)});Tq=A("$ZodJWT",($,_)=>{_6.init($,_),$._zod.check=(J)=>{if(EF(J.value,_.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:$,continue:!_.abort})}}),Sq=A("$ZodCustomStringFormat",($,_)=>{_6.init($,_),$._zod.check=(J)=>{if(_.fn(J.value))return;J.issues.push({code:"invalid_format",format:_.format,input:J.value,inst:$,continue:!_.abort})}}),S8=A("$ZodNumber",($,_)=>{F$.init($,_),$._zod.pattern=$._zod.bag.pattern??SU,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=Number(J.value)}catch(G){}let W=J.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return J;let X=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:W,inst:$,...X?{received:X}:{}}),J}}),Zq=A("$ZodNumberFormat",($,_)=>{c7.init($,_),S8.init($,_)}),yU=A("$ZodBoolean",($,_)=>{F$.init($,_),$._zod.pattern=y7,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=Boolean(J.value)}catch(X){}let W=J.value;if(typeof W==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:$}),J}}),Z8=A("$ZodBigInt",($,_)=>{F$.init($,_),$._zod.pattern=Z7,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=BigInt(J.value)}catch(W){}if(typeof J.value==="bigint")return J;return J.issues.push({expected:"bigint",code:"invalid_type",input:J.value,inst:$}),J}}),vq=A("$ZodBigIntFormat",($,_)=>{l7.init($,_),Z8.init($,_)}),yq=A("$ZodSymbol",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W==="symbol")return J;return J.issues.push({expected:"symbol",code:"invalid_type",input:W,inst:$}),J}}),hq=A("$ZodUndefined",($,_)=>{F$.init($,_),$._zod.pattern=m7,$._zod.values=new Set([void 0]),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"undefined",code:"invalid_type",input:W,inst:$}),J}}),mq=A("$ZodNull",($,_)=>{F$.init($,_),$._zod.pattern=h7,$._zod.values=new Set([null]),$._zod.parse=(J,U)=>{let W=J.value;if(W===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:W,inst:$}),J}}),xq=A("$ZodAny",($,_)=>{F$.init($,_),$._zod.parse=(J)=>J}),uq=A("$ZodUnknown",($,_)=>{F$.init($,_),$._zod.parse=(J)=>J}),dq=A("$ZodNever",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:$}),J}}),cq=A("$ZodVoid",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"void",code:"invalid_type",input:W,inst:$}),J}}),lq=A("$ZodDate",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=new Date(J.value)}catch(Q){}let W=J.value,X=W instanceof Date;if(X&&!Number.isNaN(W.getTime()))return J;return J.issues.push({expected:"date",code:"invalid_type",input:W,...X?{received:"Invalid Date"}:{},inst:$}),J}});nq=A("$ZodArray",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!Array.isArray(W))return J.issues.push({expected:"array",code:"invalid_type",input:W,inst:$}),J;J.value=Array(W.length);let X=[];for(let G=0;GzF(q,J,G)));else zF(Y,J,G)}if(X.length)return Promise.all(X).then(()=>J);return J}});gF=A("$ZodObject",($,_)=>{if(F$.init($,_),!Object.getOwnPropertyDescriptor(_,"shape")?.get){let Q=_.shape;Object.defineProperty(_,"shape",{get:()=>{let Y={...Q};return Object.defineProperty(_,"shape",{value:Y}),Y}})}let U=mJ(()=>wF(_));Z$($._zod,"propValues",()=>{let Q=_.shape,Y={};for(let q in Q){let L=Q[q]._zod;if(L.values){Y[q]??(Y[q]=new Set);for(let N of L.values)Y[q].add(N)}}return Y});let W=T2,X=_.catchall,G;$._zod.parse=(Q,Y)=>{G??(G=U.value);let q=Q.value;if(!W(q))return Q.issues.push({expected:"object",code:"invalid_type",input:q,inst:$}),Q;Q.value={};let L=[],N=G.shape;for(let F of G.keys){let B=N[F],H=B._zod.optin==="optional",V=B._zod.optout==="optional",R=B._zod.run({value:q[F],issues:[]},Y);if(R instanceof Promise)L.push(R.then((M)=>T8(M,Q,F,q,H,V)));else T8(R,Q,F,q,H,V)}if(!X)return L.length?Promise.all(L).then(()=>Q):Q;return IF(L,q,Q,Y,U.value,$)}}),iq=A("$ZodObjectJIT",($,_)=>{gF.init($,_);let J=$._zod.parse,U=mJ(()=>wF(_)),W=(F)=>{let B=new k8(["shape","payload","ctx"]),H=U.value,V=(w)=>{let b=z8(w);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};B.write("const input = payload.value;");let R=Object.create(null),M=0;for(let w of H.keys)R[w]=`key_${M++}`;B.write("const newResult = {};");for(let w of H.keys){let b=R[w],I=z8(w),v=F[w],g=v?._zod?.optin==="optional",x=v?._zod?.optout==="optional";if(B.write(`const ${b} = ${V(w)};`),g&&x)B.write(` - if (${b}.issues.length) { - if (${I} in input) { - payload.issues = payload.issues.concat(${b}.issues.map(iss => ({ +`))}}var O7;var L7=x(()=>{O7={major:4,minor:4,patch:3}});function v7($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}}function ZR($){if(!I8.test($))return!1;let _=$.replace(/[-_]/g,(U)=>U==="-"?"+":"/"),J=_.padEnd(Math.ceil(_.length/4)*4,"=");return v7(J)}function vR($,_=null){try{let J=$.split(".");if(J.length!==3)return!1;let[U]=J;if(!U)return!1;let W=JSON.parse(atob(U));if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&(!("alg"in W)||W.alg!==_))return!1;return!0}catch{return!1}}function FR($,_,J){if($.issues.length)_.issues.push(...p_(J,$.issues));_.value[J]=$.value}function h8($,_,J,U,W,X){let G=J in U;if($.issues.length){if(W&&X&&!G)return;_.issues.push(...p_(J,$.issues))}if(!G&&!W){if(!$.issues.length)_.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[J]});return}if($.value===void 0){if(G)_.value[J]=void 0}else _.value[J]=$.value}function yR($){let _=Object.keys($.shape);for(let U of _)if(!$.shape?.[U]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${U}": expected a Zod schema`);let J=Dq($.shape);return{...$,keys:_,keySet:new Set(_),numKeys:_.length,optionalKeys:new Set(J)}}function hR($,_,J,U,W,X){let G=[],Y=W.keySet,Q=W.catchall._zod,q=Q.def.type,L=Q.optin==="optional",N=Q.optout==="optional";for(let R in _){if(R==="__proto__")continue;if(Y.has(R))continue;if(q==="never"){G.push(R);continue}let B=Q.run({value:_[R],issues:[]},U);if(B instanceof Promise)$.push(B.then((H)=>h8(H,J,R,_,L,N)));else h8(B,J,R,_,L,N)}if(G.length)J.issues.push({code:"unrecognized_keys",keys:G,input:_,inst:X});if(!$.length)return J;return Promise.all($).then(()=>{return J})}function ER($,_,J,U){for(let X of $)if(X.issues.length===0)return _.value=X.value,_;let W=$.filter((X)=>!C0(X));if(W.length===1)return _.value=W[0].value,W[0];return _.issues.push({code:"invalid_union",input:_.value,inst:J,errors:$.map((X)=>X.issues.map((G)=>n_(G,U,V_())))}),_}function MR($,_,J,U){let W=$.filter((X)=>X.issues.length===0);if(W.length===1)return _.value=W[0].value,_;if(W.length===0)_.issues.push({code:"invalid_union",input:_.value,inst:J,errors:$.map((X)=>X.issues.map((G)=>n_(G,U,V_())))});else _.issues.push({code:"invalid_union",input:_.value,inst:J,errors:[],inclusive:!1});return _}function B7($,_){if($===_)return{valid:!0,data:$};if($ instanceof Date&&_ instanceof Date&&+$===+_)return{valid:!0,data:$};if(f0($)&&f0(_)){let J=Object.keys(_),U=Object.keys($).filter((X)=>J.indexOf(X)!==-1),W={...$,..._};for(let X of U){let G=B7($[X],_[X]);if(!G.valid)return{valid:!1,mergeErrorPath:[X,...G.mergeErrorPath]};W[X]=G.data}return{valid:!0,data:W}}if(Array.isArray($)&&Array.isArray(_)){if($.length!==_.length)return{valid:!1,mergeErrorPath:[]};let J=[];for(let U=0;U<$.length;U++){let W=$[U],X=_[U],G=B7(W,X);if(!G.valid)return{valid:!1,mergeErrorPath:[U,...G.mergeErrorPath]};J.push(G.data)}return{valid:!0,data:J}}return{valid:!1,mergeErrorPath:[]}}function AR($,_,J){let U=new Map,W;for(let Y of _.issues)if(Y.code==="unrecognized_keys"){W??(W=Y);for(let Q of Y.keys){if(!U.has(Q))U.set(Q,{});U.get(Q).l=!0}}else $.issues.push(Y);for(let Y of J.issues)if(Y.code==="unrecognized_keys")for(let Q of Y.keys){if(!U.has(Q))U.set(Q,{});U.get(Q).r=!0}else $.issues.push(Y);let X=[...U].filter(([,Y])=>Y.l&&Y.r).map(([Y])=>Y);if(X.length&&W)$.issues.push({...W,keys:X});if(C0($))return $;let G=B7(_.value,J.value);if(!G.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(G.mergeErrorPath)}`);return $.value=G.data,$}function bR($,_){for(let J=$.length-1;J>=0;J--)if($[J]._zod[_]!=="optional")return J+1;return 0}function wR($,_,J){if($.issues.length)_.issues.push(...p_(J,$.issues));_.value[J]=$.value}function gR($,_,J,U,W){for(let X=0;X=W){_.value.length=X;break}_.issues.push(...p_(X,G.issues))}_.value[X]=G.value}for(let X=_.value.length-1;X>=U.length;X--)if(J[X]._zod.optout==="optional"&&_.value[X]===void 0)_.value.length=X;else break;return _}function kR($,_,J,U,W,X,G){if($.issues.length)if(ZU.has(typeof U))J.issues.push(...p_(U,$.issues));else J.issues.push({code:"invalid_key",origin:"map",input:W,inst:X,issues:$.issues.map((Y)=>n_(Y,G,V_()))});if(_.issues.length)if(ZU.has(typeof U))J.issues.push(...p_(U,_.issues));else J.issues.push({origin:"map",code:"invalid_element",input:W,inst:X,key:U,issues:_.issues.map((Y)=>n_(Y,G,V_()))});J.value.set($.value,_.value)}function IR($,_){if($.issues.length)_.issues.push(...$.issues);_.value.add($.value)}function fR($,_){if(_===void 0&&($.issues.length||$.fallback))return{issues:[],value:void 0};return $}function CR($,_){if($.value===void 0)$.value=_.defaultValue;return $}function PR($,_){if(!$.issues.length&&$.value===void 0)$.issues.push({code:"invalid_type",expected:"nonoptional",input:$.value,inst:_});return $}function Z8($,_,J){if($.issues.length)return $.aborted=!0,$;return _._zod.run({value:$.value,issues:$.issues,fallback:$.fallback},J)}function v8($,_,J){if($.issues.length)return $.aborted=!0,$;if((J.direction||"forward")==="forward"){let W=_.transform($.value,$);if(W instanceof Promise)return W.then((X)=>y8($,X,_.out,J));return y8($,W,_.out,J)}else{let W=_.reverseTransform($.value,$);if(W instanceof Promise)return W.then((X)=>y8($,X,_.in,J));return y8($,W,_.in,J)}}function y8($,_,J,U){if($.issues.length)return $.aborted=!0,$;return J._zod.run({value:_,issues:$.issues},U)}function TR($){return $.value=Object.freeze($.value),$}function SR($,_,J,U){if(!$){let W={code:"custom",input:J,inst:U,path:[...U._zod.def.path??[]],continue:!U._zod.def.abort};if(U._zod.def.params)W.params=U._zod.def.params;_.issues.push(iJ(W))}}var R$,h1,J_,H7,N7,V7,R7,K7,F7,E7,M7,A7,b7,w7,g7,k7,I7,f7,C7,P7,T7,S7,Z7,y7,h7,m7,x7,u7,m8,d7,dU,x8,n7,c7,i7,l7,r7,p7,o7,t7,a7,s7,mR,e7,nU,$z,_z,Jz,u8,Wz,Uz,Xz,Gz,Yz,Qz,qz,d8,zz,jz,Dz,Oz,Lz,Bz,Hz,Nz,n8,cU,Vz,Rz,Kz,Fz,Ez,Mz,Az;var bz=x(()=>{T8();Z1();Rq();f8();e();L7();e();R$=M("$ZodType",($,_)=>{var J;$??($={}),$._zod.def=_,$._zod.bag=$._zod.bag||{},$._zod.version=O7;let U=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))U.unshift($);for(let W of U)for(let X of W._zod.onattach)X($);if(U.length===0)(J=$._zod).deferred??(J.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let W=(G,Y,Q)=>{let q=C0(G),L;for(let N of Y){if(N._zod.def.when){if(Bq(G))continue;if(!N._zod.def.when(G))continue}else if(q)continue;let R=G.issues.length,B=N._zod.check(G);if(B instanceof Promise&&Q?.async===!1)throw new O4;if(L||B instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await B,G.issues.length===R)return;if(!q)q=C0(G,R)});else{if(G.issues.length===R)continue;if(!q)q=C0(G,R)}}if(L)return L.then(()=>{return G});return G},X=(G,Y,Q)=>{if(C0(G))return G.aborted=!0,G;let q=W(Y,U,Q);if(q instanceof Promise){if(Q.async===!1)throw new O4;return q.then((L)=>$._zod.parse(L,Q))}return $._zod.parse(q,Q)};$._zod.run=(G,Y)=>{if(Y.skipChecks)return $._zod.parse(G,Y);if(Y.direction==="backward"){let q=$._zod.parse({value:G.value,issues:[]},{...Y,skipChecks:!0});if(q instanceof Promise)return q.then((L)=>{return X(L,G,Y)});return X(q,G,Y)}let Q=$._zod.parse(G,Y);if(Q instanceof Promise){if(Y.async===!1)throw new O4;return Q.then((q)=>W(q,U,Y))}return W(Q,U,Y)}}Z$($,"~standard",()=>({validate:(W)=>{try{let X=Nq($,W);return X.success?{value:X.data}:{issues:X.error?.issues}}catch(X){return Vq($,W).then((G)=>G.success?{value:G.data}:{issues:G.error?.issues})}},vendor:"zod",version:1}))}),h1=M("$ZodString",($,_)=>{R$.init($,_),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??uq($._zod.bag),$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=String(J.value)}catch(W){}if(typeof J.value==="string")return J;return J.issues.push({expected:"string",code:"invalid_type",input:J.value,inst:$}),J}}),J_=M("$ZodStringFormat",($,_)=>{sJ.init($,_),h1.init($,_)}),H7=M("$ZodGUID",($,_)=>{_.pattern??(_.pattern=gq),J_.init($,_)}),N7=M("$ZodUUID",($,_)=>{if(_.version){let U={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[_.version];if(U===void 0)throw Error(`Invalid UUID version: "${_.version}"`);_.pattern??(_.pattern=y1(U))}else _.pattern??(_.pattern=y1());J_.init($,_)}),V7=M("$ZodEmail",($,_)=>{_.pattern??(_.pattern=kq),J_.init($,_)}),R7=M("$ZodURL",($,_)=>{J_.init($,_),$._zod.check=(J)=>{try{let U=J.value.trim();if(!_.normalize&&_.protocol?.source===vq.source){if(!/^https?:\/\//i.test(U)){J.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:J.value,inst:$,continue:!_.abort});return}}let W=new URL(U);if(_.hostname){if(_.hostname.lastIndex=0,!_.hostname.test(W.hostname))J.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:_.hostname.source,input:J.value,inst:$,continue:!_.abort})}if(_.protocol){if(_.protocol.lastIndex=0,!_.protocol.test(W.protocol.endsWith(":")?W.protocol.slice(0,-1):W.protocol))J.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:_.protocol.source,input:J.value,inst:$,continue:!_.abort})}if(_.normalize)J.value=W.href;else J.value=U;return}catch(U){J.issues.push({code:"invalid_format",format:"url",input:J.value,inst:$,continue:!_.abort})}}}),K7=M("$ZodEmoji",($,_)=>{_.pattern??(_.pattern=Iq()),J_.init($,_)}),F7=M("$ZodNanoID",($,_)=>{_.pattern??(_.pattern=bq),J_.init($,_)}),E7=M("$ZodCUID",($,_)=>{_.pattern??(_.pattern=Kq),J_.init($,_)}),M7=M("$ZodCUID2",($,_)=>{_.pattern??(_.pattern=Fq),J_.init($,_)}),A7=M("$ZodULID",($,_)=>{_.pattern??(_.pattern=Eq),J_.init($,_)}),b7=M("$ZodXID",($,_)=>{_.pattern??(_.pattern=Mq),J_.init($,_)}),w7=M("$ZodKSUID",($,_)=>{_.pattern??(_.pattern=Aq),J_.init($,_)}),g7=M("$ZodISODateTime",($,_)=>{_.pattern??(_.pattern=xq(_)),J_.init($,_)}),k7=M("$ZodISODate",($,_)=>{_.pattern??(_.pattern=hq),J_.init($,_)}),I7=M("$ZodISOTime",($,_)=>{_.pattern??(_.pattern=mq(_)),J_.init($,_)}),f7=M("$ZodISODuration",($,_)=>{_.pattern??(_.pattern=wq),J_.init($,_)}),C7=M("$ZodIPv4",($,_)=>{_.pattern??(_.pattern=fq),J_.init($,_),$._zod.bag.format="ipv4"}),P7=M("$ZodIPv6",($,_)=>{_.pattern??(_.pattern=Cq),J_.init($,_),$._zod.bag.format="ipv6",$._zod.check=(J)=>{try{new URL(`http://[${J.value}]`)}catch{J.issues.push({code:"invalid_format",format:"ipv6",input:J.value,inst:$,continue:!_.abort})}}}),T7=M("$ZodMAC",($,_)=>{_.pattern??(_.pattern=Pq(_.delimiter)),J_.init($,_),$._zod.bag.format="mac"}),S7=M("$ZodCIDRv4",($,_)=>{_.pattern??(_.pattern=Tq),J_.init($,_)}),Z7=M("$ZodCIDRv6",($,_)=>{_.pattern??(_.pattern=Sq),J_.init($,_),$._zod.check=(J)=>{let U=J.value.split("/");try{if(U.length!==2)throw Error();let[W,X]=U;if(!X)throw Error();let G=Number(X);if(`${G}`!==X)throw Error();if(G<0||G>128)throw Error();new URL(`http://[${W}]`)}catch{J.issues.push({code:"invalid_format",format:"cidrv6",input:J.value,inst:$,continue:!_.abort})}}});y7=M("$ZodBase64",($,_)=>{_.pattern??(_.pattern=Zq),J_.init($,_),$._zod.bag.contentEncoding="base64",$._zod.check=(J)=>{if(v7(J.value))return;J.issues.push({code:"invalid_format",format:"base64",input:J.value,inst:$,continue:!_.abort})}});h7=M("$ZodBase64URL",($,_)=>{_.pattern??(_.pattern=I8),J_.init($,_),$._zod.bag.contentEncoding="base64url",$._zod.check=(J)=>{if(ZR(J.value))return;J.issues.push({code:"invalid_format",format:"base64url",input:J.value,inst:$,continue:!_.abort})}}),m7=M("$ZodE164",($,_)=>{_.pattern??(_.pattern=yq),J_.init($,_)});x7=M("$ZodJWT",($,_)=>{J_.init($,_),$._zod.check=(J)=>{if(vR(J.value,_.alg))return;J.issues.push({code:"invalid_format",format:"jwt",input:J.value,inst:$,continue:!_.abort})}}),u7=M("$ZodCustomStringFormat",($,_)=>{J_.init($,_),$._zod.check=(J)=>{if(_.fn(J.value))return;J.issues.push({code:"invalid_format",format:_.format,input:J.value,inst:$,continue:!_.abort})}}),m8=M("$ZodNumber",($,_)=>{R$.init($,_),$._zod.pattern=$._zod.bag.pattern??mU,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=Number(J.value)}catch(G){}let W=J.value;if(typeof W==="number"&&!Number.isNaN(W)&&Number.isFinite(W))return J;let X=typeof W==="number"?Number.isNaN(W)?"NaN":!Number.isFinite(W)?"Infinity":void 0:void 0;return J.issues.push({expected:"number",code:"invalid_type",input:W,inst:$,...X?{received:X}:{}}),J}}),d7=M("$ZodNumberFormat",($,_)=>{tq.init($,_),m8.init($,_)}),dU=M("$ZodBoolean",($,_)=>{R$.init($,_),$._zod.pattern=cq,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=Boolean(J.value)}catch(X){}let W=J.value;if(typeof W==="boolean")return J;return J.issues.push({expected:"boolean",code:"invalid_type",input:W,inst:$}),J}}),x8=M("$ZodBigInt",($,_)=>{R$.init($,_),$._zod.pattern=dq,$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=BigInt(J.value)}catch(W){}if(typeof J.value==="bigint")return J;return J.issues.push({expected:"bigint",code:"invalid_type",input:J.value,inst:$}),J}}),n7=M("$ZodBigIntFormat",($,_)=>{aq.init($,_),x8.init($,_)}),c7=M("$ZodSymbol",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W==="symbol")return J;return J.issues.push({expected:"symbol",code:"invalid_type",input:W,inst:$}),J}}),i7=M("$ZodUndefined",($,_)=>{R$.init($,_),$._zod.pattern=lq,$._zod.values=new Set([void 0]),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"undefined",code:"invalid_type",input:W,inst:$}),J}}),l7=M("$ZodNull",($,_)=>{R$.init($,_),$._zod.pattern=iq,$._zod.values=new Set([null]),$._zod.parse=(J,U)=>{let W=J.value;if(W===null)return J;return J.issues.push({expected:"null",code:"invalid_type",input:W,inst:$}),J}}),r7=M("$ZodAny",($,_)=>{R$.init($,_),$._zod.parse=(J)=>J}),p7=M("$ZodUnknown",($,_)=>{R$.init($,_),$._zod.parse=(J)=>J}),o7=M("$ZodNever",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{return J.issues.push({expected:"never",code:"invalid_type",input:J.value,inst:$}),J}}),t7=M("$ZodVoid",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(typeof W>"u")return J;return J.issues.push({expected:"void",code:"invalid_type",input:W,inst:$}),J}}),a7=M("$ZodDate",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{if(_.coerce)try{J.value=new Date(J.value)}catch(Y){}let W=J.value,X=W instanceof Date;if(X&&!Number.isNaN(W.getTime()))return J;return J.issues.push({expected:"date",code:"invalid_type",input:W,...X?{received:"Invalid Date"}:{},inst:$}),J}});s7=M("$ZodArray",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!Array.isArray(W))return J.issues.push({expected:"array",code:"invalid_type",input:W,inst:$}),J;J.value=Array(W.length);let X=[];for(let G=0;GFR(q,J,G)));else FR(Q,J,G)}if(X.length)return Promise.all(X).then(()=>J);return J}});mR=M("$ZodObject",($,_)=>{if(R$.init($,_),!Object.getOwnPropertyDescriptor(_,"shape")?.get){let Y=_.shape;Object.defineProperty(_,"shape",{get:()=>{let Q={...Y};return Object.defineProperty(_,"shape",{value:Q}),Q}})}let U=cJ(()=>yR(_));Z$($._zod,"propValues",()=>{let Y=_.shape,Q={};for(let q in Y){let L=Y[q]._zod;if(L.values){Q[q]??(Q[q]=new Set);for(let N of L.values)Q[q].add(N)}}return Q});let W=v1,X=_.catchall,G;$._zod.parse=(Y,Q)=>{G??(G=U.value);let q=Y.value;if(!W(q))return Y.issues.push({expected:"object",code:"invalid_type",input:q,inst:$}),Y;Y.value={};let L=[],N=G.shape;for(let R of G.keys){let B=N[R],H=B._zod.optin==="optional",V=B._zod.optout==="optional",K=B._zod.run({value:q[R],issues:[]},Q);if(K instanceof Promise)L.push(K.then((E)=>h8(E,Y,R,q,H,V)));else h8(K,Y,R,q,H,V)}if(!X)return L.length?Promise.all(L).then(()=>Y):Y;return hR(L,q,Y,Q,U.value,$)}}),e7=M("$ZodObjectJIT",($,_)=>{mR.init($,_);let J=$._zod.parse,U=cJ(()=>yR(_)),W=(R)=>{let B=new S8(["shape","payload","ctx"]),H=U.value,V=(w)=>{let A=B8(w);return`shape[${A}]._zod.run({ value: input[${A}], issues: [] }, ctx)`};B.write("const input = payload.value;");let K=Object.create(null),E=0;for(let w of H.keys)K[w]=`key_${E++}`;B.write("const newResult = {};");for(let w of H.keys){let A=K[w],g=B8(w),v=R[w],k=v?._zod?.optin==="optional",u=v?._zod?.optout==="optional";if(B.write(`const ${A} = ${V(w)};`),k&&u)B.write(` + if (${A}.issues.length) { + if (${g} in input) { + payload.issues = payload.issues.concat(${A}.issues.map(iss => ({ ...iss, - path: iss.path ? [${I}, ...iss.path] : [${I}] + path: iss.path ? [${g}, ...iss.path] : [${g}] }))); } } - if (${b}.value === undefined) { - if (${I} in input) { - newResult[${I}] = undefined; + if (${A}.value === undefined) { + if (${g} in input) { + newResult[${g}] = undefined; } } else { - newResult[${I}] = ${b}.value; + newResult[${g}] = ${A}.value; } - `);else if(!g)B.write(` - const ${b}_present = ${I} in input; - if (${b}.issues.length) { - payload.issues = payload.issues.concat(${b}.issues.map(iss => ({ + `);else if(!k)B.write(` + const ${A}_present = ${g} in input; + if (${A}.issues.length) { + payload.issues = payload.issues.concat(${A}.issues.map(iss => ({ ...iss, - path: iss.path ? [${I}, ...iss.path] : [${I}] + path: iss.path ? [${g}, ...iss.path] : [${g}] }))); } - if (!${b}_present && !${b}.issues.length) { + if (!${A}_present && !${A}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, - path: [${I}] + path: [${g}] }); } - if (${b}_present) { - if (${b}.value === undefined) { - newResult[${I}] = undefined; + if (${A}_present) { + if (${A}.value === undefined) { + newResult[${g}] = undefined; } else { - newResult[${I}] = ${b}.value; + newResult[${g}] = ${A}.value; } } `);else B.write(` - if (${b}.issues.length) { - payload.issues = payload.issues.concat(${b}.issues.map(iss => ({ + if (${A}.issues.length) { + payload.issues = payload.issues.concat(${A}.issues.map(iss => ({ ...iss, - path: iss.path ? [${I}, ...iss.path] : [${I}] + path: iss.path ? [${g}, ...iss.path] : [${g}] }))); } - if (${b}.value === undefined) { - if (${I} in input) { - newResult[${I}] = undefined; + if (${A}.value === undefined) { + if (${g} in input) { + newResult[${g}] = undefined; } } else { - newResult[${I}] = ${b}.value; + newResult[${g}] = ${A}.value; } - `)}B.write("payload.value = newResult;"),B.write("return payload;");let K=B.compile();return(w,b)=>K(F,w,b)},X,G=T2,Q=!f2.jitless,q=Q&&J7.value,L=_.catchall,N;$._zod.parse=(F,B)=>{N??(N=U.value);let H=F.value;if(!G(H))return F.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),F;if(Q&&q&&B?.async===!1&&B.jitless!==!0){if(!X)X=W(_.shape);if(F=X(F,B),!L)return F;return IF([],H,F,B,N,$)}return J(F,B)}});hU=A("$ZodUnion",($,_)=>{F$.init($,_),Z$($._zod,"optin",()=>_.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),Z$($._zod,"optout",()=>_.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),Z$($._zod,"values",()=>{if(_.options.every((U)=>U._zod.values))return new Set(_.options.flatMap((U)=>Array.from(U._zod.values)));return}),Z$($._zod,"pattern",()=>{if(_.options.every((U)=>U._zod.pattern)){let U=_.options.map((W)=>W._zod.pattern);return new RegExp(`^(${U.map((W)=>kU(W.source)).join("|")})$`)}return});let J=_.options.length===1?_.options[0]._zod.run:null;$._zod.parse=(U,W)=>{if(J)return J(U,W);let X=!1,G=[];for(let Q of _.options){let Y=Q._zod.run({value:U.value,issues:[]},W);if(Y instanceof Promise)G.push(Y),X=!0;else{if(Y.issues.length===0)return Y;G.push(Y)}}if(!X)return jF(G,U,$,W);return Promise.all(G).then((Q)=>{return jF(Q,U,$,W)})}});rq=A("$ZodXor",($,_)=>{hU.init($,_),_.inclusive=!1;let J=_.options.length===1?_.options[0]._zod.run:null;$._zod.parse=(U,W)=>{if(J)return J(U,W);let X=!1,G=[];for(let Q of _.options){let Y=Q._zod.run({value:U.value,issues:[]},W);if(Y instanceof Promise)G.push(Y),X=!0;else G.push(Y)}if(!X)return OF(G,U,$,W);return Promise.all(G).then((Q)=>{return OF(Q,U,$,W)})}}),pq=A("$ZodDiscriminatedUnion",($,_)=>{_.inclusive=!1,hU.init($,_);let J=$._zod.parse;Z$($._zod,"propValues",()=>{let W={};for(let X of _.options){let G=X._zod.propValues;if(!G||Object.keys(G).length===0)throw Error(`Invalid discriminated union option at index "${_.options.indexOf(X)}"`);for(let[Q,Y]of Object.entries(G)){if(!W[Q])W[Q]=new Set;for(let q of Y)W[Q].add(q)}}return W});let U=mJ(()=>{let W=_.options,X=new Map;for(let G of W){let Q=G._zod.propValues?.[_.discriminator];if(!Q||Q.size===0)throw Error(`Invalid discriminated union option at index "${_.options.indexOf(G)}"`);for(let Y of Q){if(X.has(Y))throw Error(`Duplicate discriminator value "${String(Y)}"`);X.set(Y,G)}}return X});$._zod.parse=(W,X)=>{let G=W.value;if(!T2(G))return W.issues.push({code:"invalid_type",expected:"object",input:G,inst:$}),W;let Q=U.value.get(G?.[_.discriminator]);if(Q)return Q._zod.run(W,X);if(_.unionFallback||X.direction==="backward")return J(W,X);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:_.discriminator,options:Array.from(U.value.keys()),input:G,path:[_.discriminator],inst:$}),W}}),oq=A("$ZodIntersection",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value,X=_.left._zod.run({value:W,issues:[]},U),G=_.right._zod.run({value:W,issues:[]},U);if(X instanceof Promise||G instanceof Promise)return Promise.all([X,G]).then(([Y,q])=>{return DF(J,Y,q)});return DF(J,X,G)}});v8=A("$ZodTuple",($,_)=>{F$.init($,_);let J=_.items;$._zod.parse=(U,W)=>{let X=U.value;if(!Array.isArray(X))return U.issues.push({input:X,inst:$,expected:"tuple",code:"invalid_type"}),U;U.value=[];let G=[],Q=LF(J,"optin"),Y=LF(J,"optout");if(!_.rest){if(X.lengthJ.length)U.issues.push({code:"too_big",maximum:J.length,inclusive:!0,input:X,inst:$,origin:"array"})}let q=Array(J.length);for(let L=0;L{q[L]=F}));else q[L]=N}if(_.rest){let L=J.length-1,N=X.slice(J.length);for(let F of N){L++;let B=_.rest._zod.run({value:F,issues:[]},W);if(B instanceof Promise)G.push(B.then((H)=>BF(H,U,L)));else BF(B,U,L)}}if(G.length)return Promise.all(G).then(()=>HF(q,U,J,X,Y));return HF(q,U,J,X,Y)}});tq=A("$ZodRecord",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!g1(W))return J.issues.push({expected:"record",code:"invalid_type",input:W,inst:$}),J;let X=[],G=_.keyType._zod.values;if(G){J.value={};let Q=new Set;for(let q of G)if(typeof q==="string"||typeof q==="number"||typeof q==="symbol"){Q.add(typeof q==="number"?q.toString():q);let L=_.keyType._zod.run({value:q,issues:[]},U);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:L.issues.map((B)=>d6(B,U,N6())),input:q,path:[q],inst:$});continue}let N=L.value,F=_.valueType._zod.run({value:W[q],issues:[]},U);if(F instanceof Promise)X.push(F.then((B)=>{if(B.issues.length)J.issues.push(...r6(q,B.issues));J.value[N]=B.value}));else{if(F.issues.length)J.issues.push(...r6(q,F.issues));J.value[N]=F.value}}let Y;for(let q in W)if(!Q.has(q))Y=Y??[],Y.push(q);if(Y&&Y.length>0)J.issues.push({code:"unrecognized_keys",input:W,inst:$,keys:Y})}else{J.value={};for(let Q of Reflect.ownKeys(W)){if(Q==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(W,Q))continue;let Y=_.keyType._zod.run({value:Q,issues:[]},U);if(Y instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof Q==="string"&&SU.test(Q)&&Y.issues.length){let N=_.keyType._zod.run({value:Number(Q),issues:[]},U);if(N instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(N.issues.length===0)Y=N}if(Y.issues.length){if(_.mode==="loose")J.value[Q]=W[Q];else J.issues.push({code:"invalid_key",origin:"record",issues:Y.issues.map((N)=>d6(N,U,N6())),input:Q,path:[Q],inst:$});continue}let L=_.valueType._zod.run({value:W[Q],issues:[]},U);if(L instanceof Promise)X.push(L.then((N)=>{if(N.issues.length)J.issues.push(...r6(Q,N.issues));J.value[Y.value]=N.value}));else{if(L.issues.length)J.issues.push(...r6(Q,L.issues));J.value[Y.value]=L.value}}}if(X.length)return Promise.all(X).then(()=>J);return J}}),aq=A("$ZodMap",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!(W instanceof Map))return J.issues.push({expected:"map",code:"invalid_type",input:W,inst:$}),J;let X=[];J.value=new Map;for(let[G,Q]of W){let Y=_.keyType._zod.run({value:G,issues:[]},U),q=_.valueType._zod.run({value:Q,issues:[]},U);if(Y instanceof Promise||q instanceof Promise)X.push(Promise.all([Y,q]).then(([L,N])=>{NF(L,N,J,G,W,$,U)}));else NF(Y,q,J,G,W,$,U)}if(X.length)return Promise.all(X).then(()=>J);return J}});sq=A("$ZodSet",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!(W instanceof Set))return J.issues.push({input:W,inst:$,expected:"set",code:"invalid_type"}),J;let X=[];J.value=new Set;for(let G of W){let Q=_.valueType._zod.run({value:G,issues:[]},U);if(Q instanceof Promise)X.push(Q.then((Y)=>VF(Y,J)));else VF(Q,J)}if(X.length)return Promise.all(X).then(()=>J);return J}});eq=A("$ZodEnum",($,_)=>{F$.init($,_);let J=gU(_.entries),U=new Set(J);$._zod.values=U,$._zod.pattern=new RegExp(`^(${J.filter((W)=>fU.has(typeof W)).map((W)=>typeof W==="string"?N4(W):W.toString()).join("|")})$`),$._zod.parse=(W,X)=>{let G=W.value;if(U.has(G))return W;return W.issues.push({code:"invalid_value",values:J,input:G,inst:$}),W}}),$z=A("$ZodLiteral",($,_)=>{if(F$.init($,_),_.values.length===0)throw Error("Cannot create literal schema with no valid values");let J=new Set(_.values);$._zod.values=J,$._zod.pattern=new RegExp(`^(${_.values.map((U)=>typeof U==="string"?N4(U):U?N4(U.toString()):String(U)).join("|")})$`),$._zod.parse=(U,W)=>{let X=U.value;if(J.has(X))return U;return U.issues.push({code:"invalid_value",values:_.values,input:X,inst:$}),U}}),_z=A("$ZodFile",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(W instanceof File)return J;return J.issues.push({expected:"file",code:"invalid_type",input:W,inst:$}),J}}),Jz=A("$ZodTransform",($,_)=>{F$.init($,_),$._zod.optin="optional",$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new C2($.constructor.name);let W=_.transform(J.value,J);if(U.async)return(W instanceof Promise?W:Promise.resolve(W)).then((G)=>{return J.value=G,J.fallback=!0,J});if(W instanceof Promise)throw new O0;return J.value=W,J.fallback=!0,J}});y8=A("$ZodOptional",($,_)=>{F$.init($,_),$._zod.optin="optional",$._zod.optout="optional",Z$($._zod,"values",()=>{return _.innerType._zod.values?new Set([..._.innerType._zod.values,void 0]):void 0}),Z$($._zod,"pattern",()=>{let J=_.innerType._zod.pattern;return J?new RegExp(`^(${kU(J.source)})?$`):void 0}),$._zod.parse=(J,U)=>{if(_.innerType._zod.optin==="optional"){let W=J.value,X=_.innerType._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>FF(G,W));return FF(X,W)}if(J.value===void 0)return J;return _.innerType._zod.run(J,U)}}),Wz=A("$ZodExactOptional",($,_)=>{y8.init($,_),Z$($._zod,"values",()=>_.innerType._zod.values),Z$($._zod,"pattern",()=>_.innerType._zod.pattern),$._zod.parse=(J,U)=>{return _.innerType._zod.run(J,U)}}),Uz=A("$ZodNullable",($,_)=>{F$.init($,_),Z$($._zod,"optin",()=>_.innerType._zod.optin),Z$($._zod,"optout",()=>_.innerType._zod.optout),Z$($._zod,"pattern",()=>{let J=_.innerType._zod.pattern;return J?new RegExp(`^(${kU(J.source)}|null)$`):void 0}),Z$($._zod,"values",()=>{return _.innerType._zod.values?new Set([..._.innerType._zod.values,null]):void 0}),$._zod.parse=(J,U)=>{if(J.value===null)return J;return _.innerType._zod.run(J,U)}}),Xz=A("$ZodDefault",($,_)=>{F$.init($,_),$._zod.optin="optional",Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);if(J.value===void 0)return J.value=_.defaultValue,J;let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>RF(X,_));return RF(W,_)}});Gz=A("$ZodPrefault",($,_)=>{F$.init($,_),$._zod.optin="optional",Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);if(J.value===void 0)J.value=_.defaultValue;return _.innerType._zod.run(J,U)}}),Qz=A("$ZodNonOptional",($,_)=>{F$.init($,_),Z$($._zod,"values",()=>{let J=_.innerType._zod.values;return J?new Set([...J].filter((U)=>U!==void 0)):void 0}),$._zod.parse=(J,U)=>{let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>KF(X,$));return KF(W,$)}});Yz=A("$ZodSuccess",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new C2("ZodSuccess");let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>{return J.value=X.issues.length===0,J});return J.value=W.issues.length===0,J}}),qz=A("$ZodCatch",($,_)=>{F$.init($,_),$._zod.optin="optional",Z$($._zod,"optout",()=>_.innerType._zod.optout),Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>{if(J.value=X.value,X.issues.length)J.value=_.catchValue({...J,error:{issues:X.issues.map((G)=>d6(G,U,N6()))},input:J.value}),J.issues=[],J.fallback=!0;return J});if(J.value=W.value,W.issues.length)J.value=_.catchValue({...J,error:{issues:W.issues.map((X)=>d6(X,U,N6()))},input:J.value}),J.issues=[],J.fallback=!0;return J}}),zz=A("$ZodNaN",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{if(typeof J.value!=="number"||!Number.isNaN(J.value))return J.issues.push({input:J.value,inst:$,expected:"nan",code:"invalid_type"}),J;return J}}),h8=A("$ZodPipe",($,_)=>{F$.init($,_),Z$($._zod,"values",()=>_.in._zod.values),Z$($._zod,"optin",()=>_.in._zod.optin),Z$($._zod,"optout",()=>_.out._zod.optout),Z$($._zod,"propValues",()=>_.in._zod.propValues),$._zod.parse=(J,U)=>{if(U.direction==="backward"){let X=_.out._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>f8(G,_.in,U));return f8(X,_.in,U)}let W=_.in._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>f8(X,_.out,U));return f8(W,_.out,U)}});mU=A("$ZodCodec",($,_)=>{F$.init($,_),Z$($._zod,"values",()=>_.in._zod.values),Z$($._zod,"optin",()=>_.in._zod.optin),Z$($._zod,"optout",()=>_.out._zod.optout),Z$($._zod,"propValues",()=>_.in._zod.propValues),$._zod.parse=(J,U)=>{if((U.direction||"forward")==="forward"){let X=_.in._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>C8(G,_,U));return C8(X,_,U)}else{let X=_.out._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>C8(G,_,U));return C8(X,_,U)}}});jz=A("$ZodPreprocess",($,_)=>{h8.init($,_)}),Oz=A("$ZodReadonly",($,_)=>{F$.init($,_),Z$($._zod,"propValues",()=>_.innerType._zod.propValues),Z$($._zod,"values",()=>_.innerType._zod.values),Z$($._zod,"optin",()=>_.innerType?._zod?.optin),Z$($._zod,"optout",()=>_.innerType?._zod?.optout),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then(MF);return MF(W)}});Dz=A("$ZodTemplateLiteral",($,_)=>{F$.init($,_);let J=[];for(let U of _.parts)if(typeof U==="object"&&U!==null){if(!U._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...U._zod.traits].shift()}`);let W=U._zod.pattern instanceof RegExp?U._zod.pattern.source:U._zod.pattern;if(!W)throw Error(`Invalid template literal part: ${U._zod.traits}`);let X=W.startsWith("^")?1:0,G=W.endsWith("$")?W.length-1:W.length;J.push(W.slice(X,G))}else if(U===null||U7.has(typeof U))J.push(N4(`${U}`));else throw Error(`Invalid template literal part: ${U}`);$._zod.pattern=new RegExp(`^${J.join("")}$`),$._zod.parse=(U,W)=>{if(typeof U.value!=="string")return U.issues.push({input:U.value,inst:$,expected:"string",code:"invalid_type"}),U;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(U.value))return U.issues.push({input:U.value,inst:$,code:"invalid_format",format:_.format??"template_literal",pattern:$._zod.pattern.source}),U;return U}}),Lz=A("$ZodFunction",($,_)=>{return F$.init($,_),$._def=_,$._zod.def=_,$.implement=(J)=>{if(typeof J!=="function")throw Error("implement() must be called with a function");return function(...U){let W=$._def.input?L8($._def.input,U):U,X=Reflect.apply(J,this,W);if($._def.output)return L8($._def.output,X);return X}},$.implementAsync=(J)=>{if(typeof J!=="function")throw Error("implementAsync() must be called with a function");return async function(...U){let W=$._def.input?await B8($._def.input,U):U,X=await Reflect.apply(J,this,W);if($._def.output)return await B8($._def.output,X);return X}},$._zod.parse=(J,U)=>{if(typeof J.value!=="function")return J.issues.push({code:"invalid_type",expected:"function",input:J.value,inst:$}),J;if($._def.output&&$._def.output._zod.def.type==="promise")J.value=$.implementAsync(J.value);else J.value=$.implement(J.value);return J},$.input=(...J)=>{let U=$.constructor;if(Array.isArray(J[0]))return new U({type:"function",input:new v8({type:"tuple",items:J[0],rest:J[1]}),output:$._def.output});return new U({type:"function",input:J[0],output:$._def.output})},$.output=(J)=>{return new $.constructor({type:"function",input:$._def.input,output:J})},$}),Bz=A("$ZodPromise",($,_)=>{F$.init($,_),$._zod.parse=(J,U)=>{return Promise.resolve(J.value).then((W)=>_.innerType._zod.run({value:W,issues:[]},U))}}),Hz=A("$ZodLazy",($,_)=>{F$.init($,_),Z$($._zod,"innerType",()=>{let J=_;if(!J._cachedInner)J._cachedInner=_.getter();return J._cachedInner}),Z$($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),Z$($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),Z$($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),Z$($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(J,U)=>{return $._zod.innerType._zod.run(J,U)}}),Nz=A("$ZodCustom",($,_)=>{W6.init($,_),F$.init($,_),$._zod.parse=(J,U)=>{return J},$._zod.check=(J)=>{let U=J.value,W=_.fn(U);if(W instanceof Promise)return W.then((X)=>AF(X,J,U,$));AF(W,J,U,$);return}})});function Fz(){return{localeError:ym()}}var ym=()=>{let $={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function _(W){return $[W]??null}let J={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${W.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${Q}`;return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${X}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${k(W.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${W.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${X} ${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${W.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${W.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${X} ${W.minimum.toString()} ${G.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${W.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${W.prefix}"`;if(X.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${X.suffix}"`;if(X.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${X.includes}"`;if(X.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${X.pattern}`;return`${J[X.format]??W.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${W.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${W.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${W.keys.length>1?"\u0629":""}: ${E(W.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${W.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${W.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var kF=m(()=>{s()});function Rz(){return{localeError:hm()}}var hm=()=>{let $={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${W.expected}, daxil olan ${Q}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${X}, daxil olan ${Q}`}case"invalid_value":if(W.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${k(W.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${W.origin??"d\u0259y\u0259r"} ${X}${W.maximum.toString()} ${G.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${W.origin??"d\u0259y\u0259r"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${X.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(X.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${X.suffix}" il\u0259 bitm\u0259lidir`;if(X.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${X.includes}" daxil olmal\u0131d\u0131r`;if(X.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${X.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${J[X.format]??W.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${W.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${W.keys.length>1?"lar":""}: ${E(W.keys,", ")}`;case"invalid_key":return`${W.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${W.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var fF=m(()=>{s()});function CF($,_,J,U){let W=Math.abs($),X=W%10,G=W%100;if(G>=11&&G<=19)return U;if(X===1)return _;if(X>=2&&X<=4)return J;return U}function Kz(){return{localeError:mm()}}var mm=()=>{let $={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function _(W){return $[W]??null}let J={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},U={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${W.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${Q}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${X}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${k(W.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Q=Number(W.maximum),Y=CF(Q,G.unit.one,G.unit.few,G.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${G.verb} ${X}${W.maximum.toString()} ${Y}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Q=Number(W.minimum),Y=CF(Q,G.unit.one,G.unit.few,G.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${G.verb} ${X}${W.minimum.toString()} ${Y}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${X.includes}"`;if(X.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${W.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${E(W.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${W.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${W.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var PF=m(()=>{s()});function Mz(){return{localeError:xm()}}var xm=()=>{let $={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${W.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${Q}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${X}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${Q}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${k(W.values[0])}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${X}${W.minimum.toString()} ${G.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${X.pattern}`;let G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(X.format==="emoji")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="datetime")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="date")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(X.format==="time")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="duration")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${G} ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${W.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${W.keys.length>1?"\u043E\u0432\u0435":""}: ${E(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${W.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var TF=m(()=>{s()});function Az(){return{localeError:um()}}var um=()=>{let $={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function _(W){return $[W]??null}let J={regex:"entrada",email:"adre\xE7a electr\xF2nica",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\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${W.expected}, s'ha rebut ${Q}`;return`Tipus inv\xE0lid: s'esperava ${X}, s'ha rebut ${Q}`}case"invalid_value":if(W.values.length===1)return`Valor inv\xE0lid: s'esperava ${k(W.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${E(W.values," o ")}`;case"too_big":{let X=W.inclusive?"com a m\xE0xim":"menys de",G=_(W.origin);if(G)return`Massa gran: s'esperava que ${W.origin??"el valor"} contingu\xE9s ${X} ${W.maximum.toString()} ${G.unit??"elements"}`;return`Massa gran: s'esperava que ${W.origin??"el valor"} fos ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"com a m\xEDnim":"m\xE9s de",G=_(W.origin);if(G)return`Massa petit: s'esperava que ${W.origin} contingu\xE9s ${X} ${W.minimum.toString()} ${G.unit}`;return`Massa petit: s'esperava que ${W.origin} fos ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${X.prefix}"`;if(X.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${X.suffix}"`;if(X.format==="includes")return`Format inv\xE0lid: ha d'incloure "${X.includes}"`;if(X.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${X.pattern}`;return`Format inv\xE0lid per a ${J[X.format]??W.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${W.divisor}`;case"unrecognized_keys":return`Clau${W.keys.length>1?"s":""} no reconeguda${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${W.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${W.origin}`;default:return"Entrada inv\xE0lida"}}};var SF=m(()=>{s()});function bz(){return{localeError:dm()}}var dm=()=>{let $={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function _(W){return $[W]??null}let J={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 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 \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},U={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${W.expected}, obdr\u017Eeno ${Q}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${X}, obdr\u017Eeno ${Q}`}case"invalid_value":if(W.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${k(W.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${W.origin??"hodnota"} mus\xED m\xEDt ${X}${W.maximum.toString()} ${G.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${W.origin??"hodnota"} mus\xED b\xFDt ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${W.origin??"hodnota"} mus\xED m\xEDt ${X}${W.minimum.toString()} ${G.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${W.origin??"hodnota"} mus\xED b\xFDt ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${X.prefix}"`;if(X.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${X.suffix}"`;if(X.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${X.includes}"`;if(X.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${X.pattern}`;return`Neplatn\xFD form\xE1t ${J[X.format]??W.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${W.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${E(W.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${W.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${W.origin}`;default:return"Neplatn\xFD vstup"}}};var ZF=m(()=>{s()});function Ez(){return{localeError:cm()}}var cm=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function _(W){return $[W]??null}let J={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\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",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"},U={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ugyldigt input: forventede instanceof ${W.expected}, fik ${Q}`;return`Ugyldigt input: forventede ${X}, fik ${Q}`}case"invalid_value":if(W.values.length===1)return`Ugyldig v\xE6rdi: forventede ${k(W.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Q=U[W.origin]??W.origin;if(G)return`For stor: forventede ${Q??"value"} ${G.verb} ${X} ${W.maximum.toString()} ${G.unit??"elementer"}`;return`For stor: forventede ${Q??"value"} havde ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Q=U[W.origin]??W.origin;if(G)return`For lille: forventede ${Q} ${G.verb} ${X} ${W.minimum.toString()} ${G.unit}`;return`For lille: forventede ${Q} havde ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ugyldig streng: skal starte med "${X.prefix}"`;if(X.format==="ends_with")return`Ugyldig streng: skal ende med "${X.suffix}"`;if(X.format==="includes")return`Ugyldig streng: skal indeholde "${X.includes}"`;if(X.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${X.pattern}`;return`Ugyldig ${J[X.format]??W.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${E(W.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${W.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${W.origin}`;default:return"Ugyldigt input"}}};var vF=m(()=>{s()});function wz(){return{localeError:lm()}}var lm=()=>{let $={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 _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"Zahl",array:"Array"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${W.expected}, erhalten ${Q}`;return`Ung\xFCltige Eingabe: erwartet ${X}, erhalten ${Q}`}case"invalid_value":if(W.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${k(W.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Zu gro\xDF: erwartet, dass ${W.origin??"Wert"} ${X}${W.maximum.toString()} ${G.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${W.origin??"Wert"} ${X}${W.maximum.toString()} ist`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Zu klein: erwartet, dass ${W.origin} ${X}${W.minimum.toString()} ${G.unit} hat`;return`Zu klein: erwartet, dass ${W.origin} ${X}${W.minimum.toString()} ist`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ung\xFCltiger String: muss mit "${X.prefix}" beginnen`;if(X.format==="ends_with")return`Ung\xFCltiger String: muss mit "${X.suffix}" enden`;if(X.format==="includes")return`Ung\xFCltiger String: muss "${X.includes}" enthalten`;if(X.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${X.pattern} entsprechen`;return`Ung\xFCltig: ${J[X.format]??W.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${W.divisor} sein`;case"unrecognized_keys":return`${W.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${E(W.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${W.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${W.origin}`;default:return"Ung\xFCltige Eingabe"}}};var yF=m(()=>{s()});function Iz(){return{localeError:nm()}}var nm=()=>{let $={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function _(W){return $[W]??null}let J={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 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 \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(typeof W.expected==="string"&&/^[A-Z]/.test(W.expected))return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${W.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${Q}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${X}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${k(W.values[0])}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${X}${W.maximum.toString()} ${G.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${X}${W.minimum.toString()} ${G.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${X.prefix}"`;if(X.format==="ends_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${X.suffix}"`;if(X.format==="includes")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${X.includes}"`;if(X.format==="regex")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${X.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${J[X.format]??W.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${W.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${W.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${W.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${E(W.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${W.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${W.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var hF=m(()=>{s()});function xU(){return{localeError:im()}}var im=()=>{let $={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 _(W){return $[W]??null}let J={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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;return`Invalid input: expected ${X}, received ${Q}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${k(W.values[0])}`;return`Invalid option: expected one of ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${X}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Too small: expected ${W.origin} to have ${X}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Invalid string: must start with "${X.prefix}"`;if(X.format==="ends_with")return`Invalid string: must end with "${X.suffix}"`;if(X.format==="includes")return`Invalid string: must include "${X.includes}"`;if(X.format==="regex")return`Invalid string: must match pattern ${X.pattern}`;return`Invalid ${J[X.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":if(W.options&&Array.isArray(W.options)&&W.options.length>0)return`Invalid discriminator value. Expected ${W.options.map((G)=>`'${G}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};var gz=m(()=>{s()});function kz(){return{localeError:rm()}}var rm=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function _(W){return $[W]??null}let J={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",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\u016Dro",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"},U={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${W.expected}, ricevi\u011Dis ${Q}`;return`Nevalida enigo: atendi\u011Dis ${X}, ricevi\u011Dis ${Q}`}case"invalid_value":if(W.values.length===1)return`Nevalida enigo: atendi\u011Dis ${k(W.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Tro granda: atendi\u011Dis ke ${W.origin??"valoro"} havu ${X}${W.maximum.toString()} ${G.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${W.origin??"valoro"} havu ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Tro malgranda: atendi\u011Dis ke ${W.origin} havu ${X}${W.minimum.toString()} ${G.unit}`;return`Tro malgranda: atendi\u011Dis ke ${W.origin} estu ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${X.prefix}"`;if(X.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${X.suffix}"`;if(X.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${X.includes}"`;if(X.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${X.pattern}`;return`Nevalida ${J[X.format]??W.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${W.divisor}`;case"unrecognized_keys":return`Nekonata${W.keys.length>1?"j":""} \u015Dlosilo${W.keys.length>1?"j":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${W.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${W.origin}`;default:return"Nevalida enigo"}}};var mF=m(()=>{s()});function fz(){return{localeError:pm()}}var pm=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function _(W){return $[W]??null}let J={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",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\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${W.expected}, recibido ${Q}`;return`Entrada inv\xE1lida: se esperaba ${X}, recibido ${Q}`}case"invalid_value":if(W.values.length===1)return`Entrada inv\xE1lida: se esperaba ${k(W.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Q=U[W.origin]??W.origin;if(G)return`Demasiado grande: se esperaba que ${Q??"valor"} tuviera ${X}${W.maximum.toString()} ${G.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${Q??"valor"} fuera ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Q=U[W.origin]??W.origin;if(G)return`Demasiado peque\xF1o: se esperaba que ${Q} tuviera ${X}${W.minimum.toString()} ${G.unit}`;return`Demasiado peque\xF1o: se esperaba que ${Q} fuera ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${X.prefix}"`;if(X.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${X.suffix}"`;if(X.format==="includes")return`Cadena inv\xE1lida: debe incluir "${X.includes}"`;if(X.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${X.pattern}`;return`Inv\xE1lido ${J[X.format]??W.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${W.divisor}`;case"unrecognized_keys":return`Llave${W.keys.length>1?"s":""} desconocida${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${U[W.origin]??W.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${U[W.origin]??W.origin}`;default:return"Entrada inv\xE1lida"}}};var xF=m(()=>{s()});function Cz(){return{localeError:om()}}var om=()=>{let $={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function _(W){return $[W]??null}let J={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${W.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${Q} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${X} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${Q} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(W.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${k(W.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${E(W.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${W.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${W.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} ${G.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${X.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(X.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${X.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(X.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${X.includes}" \u0628\u0627\u0634\u062F`;if(X.format==="regex")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${X.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${J[X.format]??W.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${W.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${W.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${E(W.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${W.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${W.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var uF=m(()=>{s()});function Pz(){return{localeError:tm()}}var tm=()=>{let $={string:{unit:"merkki\xE4",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\xE4iv\xE4m\xE4\xE4r\xE4n"}};function _(W){return $[W]??null}let J={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",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\xE4iv\xE4m\xE4\xE4r\xE4",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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Virheellinen tyyppi: odotettiin instanceof ${W.expected}, oli ${Q}`;return`Virheellinen tyyppi: odotettiin ${X}, oli ${Q}`}case"invalid_value":if(W.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${k(W.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Liian suuri: ${G.subject} t\xE4ytyy olla ${X}${W.maximum.toString()} ${G.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Liian pieni: ${G.subject} t\xE4ytyy olla ${X}${W.minimum.toString()} ${G.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${X.prefix}"`;if(X.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${X.suffix}"`;if(X.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${X.includes}"`;if(X.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${X.pattern}`;return`Virheellinen ${J[X.format]??W.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${W.divisor} monikerta`;case"unrecognized_keys":return`${W.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${E(W.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\xF6te"}}};var dF=m(()=>{s()});function Tz(){return{localeError:am()}}var am=()=>{let $={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function _(W){return $[W]??null}let J={regex:"entr\xE9e",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\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entr\xE9e invalide : instanceof ${W.expected} attendu, ${Q} re\xE7u`;return`Entr\xE9e invalide : ${X} attendu, ${Q} re\xE7u`}case"invalid_value":if(W.values.length===1)return`Entr\xE9e invalide : ${k(W.values[0])} attendu`;return`Option invalide : une valeur parmi ${E(W.values,"|")} attendue`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Trop grand : ${U[W.origin]??"valeur"} doit ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${U[W.origin]??"valeur"} doit \xEAtre ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Trop petit : ${U[W.origin]??"valeur"} doit ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Trop petit : ${U[W.origin]??"valeur"} doit \xEAtre ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${X.prefix}"`;if(X.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${X.suffix}"`;if(X.format==="includes")return`Cha\xEEne invalide : doit inclure "${X.includes}"`;if(X.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${X.pattern}`;return`${J[X.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${W.divisor}`;case"unrecognized_keys":return`Cl\xE9${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${E(W.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${W.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entr\xE9e invalide"}}};var cF=m(()=>{s()});function Sz(){return{localeError:sm()}}var sm=()=>{let $={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function _(W){return $[W]??null}let J={regex:"entr\xE9e",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\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entr\xE9e invalide : attendu instanceof ${W.expected}, re\xE7u ${Q}`;return`Entr\xE9e invalide : attendu ${X}, re\xE7u ${Q}`}case"invalid_value":if(W.values.length===1)return`Entr\xE9e invalide : attendu ${k(W.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"\u2264":"<",G=_(W.origin);if(G)return`Trop grand : attendu que ${W.origin??"la valeur"} ait ${X}${W.maximum.toString()} ${G.unit}`;return`Trop grand : attendu que ${W.origin??"la valeur"} soit ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"\u2265":">",G=_(W.origin);if(G)return`Trop petit : attendu que ${W.origin} ait ${X}${W.minimum.toString()} ${G.unit}`;return`Trop petit : attendu que ${W.origin} soit ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${X.prefix}"`;if(X.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${X.suffix}"`;if(X.format==="includes")return`Cha\xEEne invalide : doit inclure "${X.includes}"`;if(X.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${X.pattern}`;return`${J[X.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${W.divisor}`;case"unrecognized_keys":return`Cl\xE9${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${E(W.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${W.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entr\xE9e invalide"}}};var lF=m(()=>{s()});function Zz(){return{localeError:em()}}var em=()=>{let $={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},_={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},J=(q)=>q?$[q]:void 0,U=(q)=>{let L=J(q);if(L)return L.label;return q??$.unknown.label},W=(q)=>`\u05D4${U(q)}`,X=(q)=>{return(J(q)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},G=(q)=>{if(!q)return null;return _[q]??null},Q={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",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:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},Y={nan:"NaN"};return(q)=>{switch(q.code){case"invalid_type":{let L=q.expected,N=Y[L??""]??U(L),F=f(q.input),B=Y[F]??$[F]?.label??F;if(/^[A-Z]/.test(q.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${q.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${B}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${N}, \u05D4\u05EA\u05E7\u05D1\u05DC ${B}`}case"invalid_value":{if(q.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${k(q.values[0])}`;let L=q.values.map((B)=>k(B));if(q.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L[0]} \u05D0\u05D5 ${L[1]}`;let N=L[L.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L.slice(0,-1).join(", ")} \u05D0\u05D5 ${N}`}case"too_big":{let L=G(q.origin),N=W(q.origin??"value");if(q.origin==="string")return`${L?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${q.maximum.toString()} ${L?.unit??""} ${q.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(q.origin==="number"){let H=q.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${q.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${q.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${H}`}if(q.origin==="array"||q.origin==="set"){let H=q.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",V=q.inclusive?`${q.maximum} ${L?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${q.maximum} ${L?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${V}`.trim()}let F=q.inclusive?"<=":"<",B=X(q.origin??"value");if(L?.unit)return`${L.longLabel} \u05DE\u05D3\u05D9: ${N} ${B} ${F}${q.maximum.toString()} ${L.unit}`;return`${L?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${N} ${B} ${F}${q.maximum.toString()}`}case"too_small":{let L=G(q.origin),N=W(q.origin??"value");if(q.origin==="string")return`${L?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${q.minimum.toString()} ${L?.unit??""} ${q.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(q.origin==="number"){let H=q.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${q.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${q.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${H}`}if(q.origin==="array"||q.origin==="set"){let H=q.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(q.minimum===1&&q.inclusive){let R=q.origin==="set"?"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3":"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${R}`}let V=q.inclusive?`${q.minimum} ${L?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${q.minimum} ${L?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${V}`.trim()}let F=q.inclusive?">=":">",B=X(q.origin??"value");if(L?.unit)return`${L.shortLabel} \u05DE\u05D3\u05D9: ${N} ${B} ${F}${q.minimum.toString()} ${L.unit}`;return`${L?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${N} ${B} ${F}${q.minimum.toString()}`}case"invalid_format":{let L=q;if(L.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${L.prefix}"`;if(L.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${L.suffix}"`;if(L.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${L.includes}"`;if(L.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${L.pattern}`;let N=Q[L.format],F=N?.label??L.format,H=(N?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${F} \u05DC\u05D0 ${H}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${q.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${q.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${q.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${E(q.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${W(q.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var nF=m(()=>{s()});function vz(){return{localeError:$x()}}var $x=()=>{let $={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function _(W){return $[W]??null}let J={regex:"unos",email:"email 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:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},U={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${W.expected}, a primljeno je ${Q}`;return`Neispravan unos: o\u010Dekuje se ${X}, a primljeno je ${Q}`}case"invalid_value":if(W.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${k(W.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Q=U[W.origin]??W.origin;if(G)return`Preveliko: o\u010Dekivano da ${Q??"vrijednost"} ima ${X}${W.maximum.toString()} ${G.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${Q??"vrijednost"} bude ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Q=U[W.origin]??W.origin;if(G)return`Premalo: o\u010Dekivano da ${Q} ima ${X}${W.minimum.toString()} ${G.unit}`;return`Premalo: o\u010Dekivano da ${Q} bude ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${X.prefix}"`;if(X.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${X.suffix}"`;if(X.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${X.includes}"`;if(X.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${X.pattern}`;return`Neispravna ${J[X.format]??W.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${W.divisor}`;case"unrecognized_keys":return`Neprepoznat${W.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${E(W.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${U[W.origin]??W.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${U[W.origin]??W.origin}`;default:return"Neispravan unos"}}};var iF=m(()=>{s()});function yz(){return{localeError:_x()}}var _x=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function _(W){return $[W]??null}let J={regex:"bemenet",email:"email c\xEDm",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\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},U={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${W.expected}, a kapott \xE9rt\xE9k ${Q}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${X}, a kapott \xE9rt\xE9k ${Q}`}case"invalid_value":if(W.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${k(W.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`T\xFAl nagy: ${W.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${X}${W.maximum.toString()} ${G.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${W.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${W.origin} m\xE9rete t\xFAl kicsi ${X}${W.minimum.toString()} ${G.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${W.origin} t\xFAl kicsi ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\xC9rv\xE9nytelen string: "${X.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(X.format==="ends_with")return`\xC9rv\xE9nytelen string: "${X.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(X.format==="includes")return`\xC9rv\xE9nytelen string: "${X.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(X.format==="regex")return`\xC9rv\xE9nytelen string: ${X.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${J[X.format]??W.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${W.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${W.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${W.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var rF=m(()=>{s()});function pF($,_,J){return Math.abs($)===1?_:J}function pJ($){if(!$)return"";let _=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],J=$[$.length-1];return $+(_.includes(J)?"\u0576":"\u0568")}function hz(){return{localeError:Jx()}}var Jx=()=>{let $={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function _(W){return $[W]??null}let J={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},U={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${W.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${Q}`;return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${X}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${k(W.values[1])}`;return`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Q=Number(W.maximum),Y=pF(Q,G.unit.one,G.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pJ(W.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${X}${W.maximum.toString()} ${Y}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pJ(W.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Q=Number(W.minimum),Y=pF(Q,G.unit.one,G.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pJ(W.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${X}${W.minimum.toString()} ${Y}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pJ(W.origin)} \u056C\u056B\u0576\u056B ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${X.prefix}"-\u0578\u057E`;if(X.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${X.suffix}"-\u0578\u057E`;if(X.format==="includes")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${X.includes}"`;if(X.format==="regex")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${X.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${J[X.format]??W.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${W.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${W.keys.length>1?"\u0576\u0565\u0580":""}. ${E(W.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${pJ(W.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${pJ(W.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var oF=m(()=>{s()});function mz(){return{localeError:Wx()}}var Wx=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input tidak valid: diharapkan instanceof ${W.expected}, diterima ${Q}`;return`Input tidak valid: diharapkan ${X}, diterima ${Q}`}case"invalid_value":if(W.values.length===1)return`Input tidak valid: diharapkan ${k(W.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Terlalu besar: diharapkan ${W.origin??"value"} memiliki ${X}${W.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: diharapkan ${W.origin??"value"} menjadi ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Terlalu kecil: diharapkan ${W.origin} memiliki ${X}${W.minimum.toString()} ${G.unit}`;return`Terlalu kecil: diharapkan ${W.origin} menjadi ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`String tidak valid: harus dimulai dengan "${X.prefix}"`;if(X.format==="ends_with")return`String tidak valid: harus berakhir dengan "${X.suffix}"`;if(X.format==="includes")return`String tidak valid: harus menyertakan "${X.includes}"`;if(X.format==="regex")return`String tidak valid: harus sesuai pola ${X.pattern}`;return`${J[X.format]??W.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${W.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${W.origin}`;default:return"Input tidak valid"}}};var tF=m(()=>{s()});function xz(){return{localeError:Ux()}}var Ux=()=>{let $={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function _(W){return $[W]??null}let J={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",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\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",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\xF6lugildi",jwt:"JWT",template_literal:"gildi"},U={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${Q} \xFEar sem \xE1 a\xF0 vera instanceof ${W.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${Q} \xFEar sem \xE1 a\xF0 vera ${X}`}case"invalid_value":if(W.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${k(W.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin??"gildi"} hafi ${X}${W.maximum.toString()} ${G.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin??"gildi"} s\xE9 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin} hafi ${X}${W.minimum.toString()} ${G.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin} s\xE9 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${X.prefix}"`;if(X.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${X.suffix}"`;if(X.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${X.includes}"`;if(X.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${X.pattern}`;return`Rangt ${J[X.format]??W.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${W.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${W.keys.length>1?"ir lyklar":"ur lykill"}: ${E(W.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${W.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${W.origin}`;default:return"Rangt gildi"}}};var aF=m(()=>{s()});function uz(){return{localeError:Xx()}}var Xx=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"numero",array:"vettore"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input non valido: atteso instanceof ${W.expected}, ricevuto ${Q}`;return`Input non valido: atteso ${X}, ricevuto ${Q}`}case"invalid_value":if(W.values.length===1)return`Input non valido: atteso ${k(W.values[0])}`;return`Opzione non valida: atteso uno tra ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Troppo grande: ${W.origin??"valore"} deve avere ${X}${W.maximum.toString()} ${G.unit??"elementi"}`;return`Troppo grande: ${W.origin??"valore"} deve essere ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Troppo piccolo: ${W.origin} deve avere ${X}${W.minimum.toString()} ${G.unit}`;return`Troppo piccolo: ${W.origin} deve essere ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Stringa non valida: deve iniziare con "${X.prefix}"`;if(X.format==="ends_with")return`Stringa non valida: deve terminare con "${X.suffix}"`;if(X.format==="includes")return`Stringa non valida: deve includere "${X.includes}"`;if(X.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${X.pattern}`;return`Input non valido: ${J[X.format]??W.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${W.divisor}`;case"unrecognized_keys":return`Chiav${W.keys.length>1?"i":"e"} non riconosciut${W.keys.length>1?"e":"a"}: ${E(W.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${W.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${W.origin}`;default:return"Input non valido"}}};var sF=m(()=>{s()});function dz(){return{localeError:Gx()}}var Gx=()=>{let $={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function _(W){return $[W]??null}let J={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},U={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${W.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${Q}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${X}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${Q}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(W.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${k(W.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${E(W.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let X=W.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",G=_(W.origin);if(G)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${W.origin??"\u5024"}\u306F${W.maximum.toString()}${G.unit??"\u8981\u7D20"}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${W.origin??"\u5024"}\u306F${W.maximum.toString()}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let X=W.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",G=_(W.origin);if(G)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${W.origin}\u306F${W.minimum.toString()}${G.unit}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${W.origin}\u306F${W.minimum.toString()}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${X.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${J[X.format]??W.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${W.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${W.keys.length>1?"\u7FA4":""}: ${E(W.keys,"\u3001")}`;case"invalid_key":return`${W.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${W.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var eF=m(()=>{s()});function cz(){return{localeError:Qx()}}var Qx=()=>{let $={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function _(W){return $[W]??null}let J={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},U={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${W.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${Q}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${X}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${k(W.values[0])}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${E(W.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin} \u10D8\u10E7\u10DD\u10E1 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${X.prefix}"-\u10D8\u10D7`;if(X.format==="ends_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${X.suffix}"-\u10D8\u10D7`;if(X.format==="includes")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${X.includes}"-\u10E1`;if(X.format==="regex")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${X.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${W.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${W.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${E(W.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${W.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${W.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var $R=m(()=>{s()});function uU(){return{localeError:Yx()}}var Yx=()=>{let $={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function _(W){return $[W]??null}let J={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},U={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${W.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${Q}`;return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${X} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${k(W.values[0])}`;return`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${X} ${W.maximum.toString()} ${G.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin} ${X} ${W.minimum.toString()} ${G.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin} ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${X.prefix}"`;if(X.format==="ends_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${X.suffix}"`;if(X.format==="includes")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${X.includes}"`;if(X.format==="regex")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${X.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${W.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${E(W.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${W.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${W.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};var lz=m(()=>{s()});function nz(){return uU()}var _R=m(()=>{lz()});function iz(){return{localeError:qx()}}var qx=()=>{let $={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function _(W){return $[W]??null}let J={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${W.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${Q}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${X}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${Q}\uC785\uB2C8\uB2E4`}case"invalid_value":if(W.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${k(W.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${E(W.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let X=W.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",G=X==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",Q=_(W.origin),Y=Q?.unit??"\uC694\uC18C";if(Q)return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${W.maximum.toString()}${Y} ${X}${G}`;return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${W.maximum.toString()} ${X}${G}`}case"too_small":{let X=W.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",G=X==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",Q=_(W.origin),Y=Q?.unit??"\uC694\uC18C";if(Q)return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${W.minimum.toString()}${Y} ${X}${G}`;return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${W.minimum.toString()} ${X}${G}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${X.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${J[X.format]??W.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${W.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${E(W.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${W.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${W.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var JR=m(()=>{s()});function WR($){let _=Math.abs($),J=_%10,U=_%100;if(U>=11&&U<=19||J===0)return"many";if(J===1)return"one";return"few"}function rz(){return{localeError:zx()}}var dU=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)},zx=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function _(W,X,G,Q){let Y=$[W]??null;if(Y===null)return Y;return{unit:Y.unit[X],verb:Y.verb[Q][G?"inclusive":"notInclusive"]}}let J={regex:"\u012Fvestis",email:"el. pa\u0161to 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\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},U={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Gautas tipas ${Q}, o tik\u0117tasi - instanceof ${W.expected}`;return`Gautas tipas ${Q}, o tik\u0117tasi - ${X}`}case"invalid_value":if(W.values.length===1)return`Privalo b\u016Bti ${k(W.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${E(W.values,"|")} pasirinkim\u0173`;case"too_big":{let X=U[W.origin]??W.origin,G=_(W.origin,WR(Number(W.maximum)),W.inclusive??!1,"smaller");if(G?.verb)return`${dU(X??W.origin??"reik\u0161m\u0117")} ${G.verb} ${W.maximum.toString()} ${G.unit??"element\u0173"}`;let Q=W.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${dU(X??W.origin??"reik\u0161m\u0117")} turi b\u016Bti ${Q} ${W.maximum.toString()} ${G?.unit}`}case"too_small":{let X=U[W.origin]??W.origin,G=_(W.origin,WR(Number(W.minimum)),W.inclusive??!1,"bigger");if(G?.verb)return`${dU(X??W.origin??"reik\u0161m\u0117")} ${G.verb} ${W.minimum.toString()} ${G.unit??"element\u0173"}`;let Q=W.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${dU(X??W.origin??"reik\u0161m\u0117")} turi b\u016Bti ${Q} ${W.minimum.toString()} ${G?.unit}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${X.prefix}"`;if(X.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${X.suffix}"`;if(X.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${X.includes}"`;if(X.format==="regex")return`Eilut\u0117 privalo atitikti ${X.pattern}`;return`Neteisingas ${J[X.format]??W.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${W.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${W.keys.length>1?"i":"as"} rakt${W.keys.length>1?"ai":"as"}: ${E(W.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let X=U[W.origin]??W.origin;return`${dU(X??W.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var UR=m(()=>{s()});function pz(){return{localeError:jx()}}var jx=()=>{let $={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function _(W){return $[W]??null}let J={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},U={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${W.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${Q}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${X}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${Q}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${k(W.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin} \u0434\u0430 \u0438\u043C\u0430 ${X}${W.minimum.toString()} ${G.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${X.pattern}`;return`Invalid ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${E(W.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${W.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${W.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var XR=m(()=>{s()});function oz(){return{localeError:Ox()}}var Ox=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"nombor"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input tidak sah: dijangka instanceof ${W.expected}, diterima ${Q}`;return`Input tidak sah: dijangka ${X}, diterima ${Q}`}case"invalid_value":if(W.values.length===1)return`Input tidak sah: dijangka ${k(W.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Terlalu besar: dijangka ${W.origin??"nilai"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: dijangka ${W.origin??"nilai"} adalah ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Terlalu kecil: dijangka ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Terlalu kecil: dijangka ${W.origin} adalah ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`String tidak sah: mesti bermula dengan "${X.prefix}"`;if(X.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${X.suffix}"`;if(X.format==="includes")return`String tidak sah: mesti mengandungi "${X.includes}"`;if(X.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${X.pattern}`;return`${J[X.format]??W.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${E(W.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${W.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${W.origin}`;default:return"Input tidak sah"}}};var GR=m(()=>{s()});function tz(){return{localeError:Dx()}}var Dx=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"getal"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ongeldige invoer: verwacht instanceof ${W.expected}, ontving ${Q}`;return`Ongeldige invoer: verwacht ${X}, ontving ${Q}`}case"invalid_value":if(W.values.length===1)return`Ongeldige invoer: verwacht ${k(W.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Q=W.origin==="date"?"laat":W.origin==="string"?"lang":"groot";if(G)return`Te ${Q}: verwacht dat ${W.origin??"waarde"} ${X}${W.maximum.toString()} ${G.unit??"elementen"} ${G.verb}`;return`Te ${Q}: verwacht dat ${W.origin??"waarde"} ${X}${W.maximum.toString()} is`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Q=W.origin==="date"?"vroeg":W.origin==="string"?"kort":"klein";if(G)return`Te ${Q}: verwacht dat ${W.origin} ${X}${W.minimum.toString()} ${G.unit} ${G.verb}`;return`Te ${Q}: verwacht dat ${W.origin} ${X}${W.minimum.toString()} is`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ongeldige tekst: moet met "${X.prefix}" beginnen`;if(X.format==="ends_with")return`Ongeldige tekst: moet op "${X.suffix}" eindigen`;if(X.format==="includes")return`Ongeldige tekst: moet "${X.includes}" bevatten`;if(X.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${X.pattern}`;return`Ongeldig: ${J[X.format]??W.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${W.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${W.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${W.origin}`;default:return"Ongeldige invoer"}}};var QR=m(()=>{s()});function az(){return{localeError:Lx()}}var Lx=()=>{let $={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function _(W){return $[W]??null}let J={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\xE5de",ipv6:"IPv6-omr\xE5de",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"},U={nan:"NaN",number:"tall",array:"liste"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ugyldig input: forventet instanceof ${W.expected}, fikk ${Q}`;return`Ugyldig input: forventet ${X}, fikk ${Q}`}case"invalid_value":if(W.values.length===1)return`Ugyldig verdi: forventet ${k(W.values[0])}`;return`Ugyldig valg: forventet en av ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`For stor(t): forventet ${W.origin??"value"} til \xE5 ha ${X}${W.maximum.toString()} ${G.unit??"elementer"}`;return`For stor(t): forventet ${W.origin??"value"} til \xE5 ha ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`For lite(n): forventet ${W.origin} til \xE5 ha ${X}${W.minimum.toString()} ${G.unit}`;return`For lite(n): forventet ${W.origin} til \xE5 ha ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${X.prefix}"`;if(X.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${X.suffix}"`;if(X.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${X.includes}"`;if(X.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${X.pattern}`;return`Ugyldig ${J[X.format]??W.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${E(W.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${W.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${W.origin}`;default:return"Ugyldig input"}}};var YR=m(()=>{s()});function sz(){return{localeError:Bx()}}var Bx=()=>{let $={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function _(W){return $[W]??null}let J={regex:"giren",email:"epostag\xE2h",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\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},U={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`F\xE2sit giren: umulan instanceof ${W.expected}, al\u0131nan ${Q}`;return`F\xE2sit giren: umulan ${X}, al\u0131nan ${Q}`}case"invalid_value":if(W.values.length===1)return`F\xE2sit giren: umulan ${k(W.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Fazla b\xFCy\xFCk: ${W.origin??"value"}, ${X}${W.maximum.toString()} ${G.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${W.origin??"value"}, ${X}${W.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Fazla k\xFC\xE7\xFCk: ${W.origin}, ${X}${W.minimum.toString()} ${G.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${W.origin}, ${X}${W.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`F\xE2sit metin: "${X.prefix}" ile ba\u015Flamal\u0131.`;if(X.format==="ends_with")return`F\xE2sit metin: "${X.suffix}" ile bitmeli.`;if(X.format==="includes")return`F\xE2sit metin: "${X.includes}" ihtiv\xE2 etmeli.`;if(X.format==="regex")return`F\xE2sit metin: ${X.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${J[X.format]??W.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${W.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`${W.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${W.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var qR=m(()=>{s()});function ez(){return{localeError:Hx()}}var Hx=()=>{let $={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function _(W){return $[W]??null}let J={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${W.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${Q} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${X} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${Q} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(W.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${k(W.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${E(W.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${W.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${W.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} \u0648\u064A`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} ${G.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} \u0648\u064A`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${X.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(X.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${X.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(X.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${X.includes}" \u0648\u0644\u0631\u064A`;if(X.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${X.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${J[X.format]??W.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${W.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${W.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${E(W.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${W.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${W.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var zR=m(()=>{s()});function $j(){return{localeError:Nx()}}var Nx=()=>{let $={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function _(W){return $[W]??null}let J={regex:"wyra\u017Cenie",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\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},U={nan:"NaN",number:"liczba",array:"tablica"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${W.expected}, otrzymano ${Q}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${X}, otrzymano ${Q}`}case"invalid_value":if(W.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${k(W.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${X}${W.maximum.toString()} ${G.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${X}${W.minimum.toString()} ${G.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${X.prefix}"`;if(X.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${X.suffix}"`;if(X.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${X.includes}"`;if(X.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${X.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${J[X.format]??W.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${W.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${W.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${W.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var jR=m(()=>{s()});function _j(){return{localeError:Vx()}}var Vx=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function _(W){return $[W]??null}let J={regex:"padr\xE3o",email:"endere\xE7o 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\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o 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\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Tipo inv\xE1lido: esperado instanceof ${W.expected}, recebido ${Q}`;return`Tipo inv\xE1lido: esperado ${X}, recebido ${Q}`}case"invalid_value":if(W.values.length===1)return`Entrada inv\xE1lida: esperado ${k(W.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Muito grande: esperado que ${W.origin??"valor"} tivesse ${X}${W.maximum.toString()} ${G.unit??"elementos"}`;return`Muito grande: esperado que ${W.origin??"valor"} fosse ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Muito pequeno: esperado que ${W.origin} tivesse ${X}${W.minimum.toString()} ${G.unit}`;return`Muito pequeno: esperado que ${W.origin} fosse ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${X.prefix}"`;if(X.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${X.suffix}"`;if(X.format==="includes")return`Texto inv\xE1lido: deve incluir "${X.includes}"`;if(X.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${X.pattern}`;return`${J[X.format]??W.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${W.divisor}`;case"unrecognized_keys":return`Chave${W.keys.length>1?"s":""} desconhecida${W.keys.length>1?"s":""}: ${E(W.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${W.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${W.origin}`;default:return"Campo inv\xE1lido"}}};var OR=m(()=>{s()});function Jj(){return{localeError:Fx()}}var Fx=()=>{let $={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function _(W){return $[W]??null}let J={regex:"intrare",email:"adres\u0103 de 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:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},U={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;return`Intrare invalid\u0103: a\u0219teptat ${X}, primit ${Q}`}case"invalid_value":if(W.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${k(W.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Prea mare: a\u0219teptat ca ${W.origin??"valoarea"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${W.origin??"valoarea"} s\u0103 fie ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Prea mic: a\u0219teptat ca ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Prea mic: a\u0219teptat ca ${W.origin} s\u0103 fie ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${X.prefix}"`;if(X.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${X.suffix}"`;if(X.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${X.includes}"`;if(X.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${X.pattern}`;return`Format invalid: ${J[X.format]??W.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${W.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${E(W.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${W.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${W.origin}`;default:return"Intrare invalid\u0103"}}};var DR=m(()=>{s()});function LR($,_,J,U){let W=Math.abs($),X=W%10,G=W%100;if(G>=11&&G<=19)return U;if(X===1)return _;if(X>=2&&X<=4)return J;return U}function Wj(){return{localeError:Rx()}}var Rx=()=>{let $={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${W.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${Q}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${X}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${Q}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${k(W.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Q=Number(W.maximum),Y=LR(Q,G.unit.one,G.unit.few,G.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${X}${W.maximum.toString()} ${Y}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Q=Number(W.minimum),Y=LR(Q,G.unit.one,G.unit.few,G.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${X}${W.minimum.toString()} ${Y}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin} \u0431\u0443\u0434\u0435\u0442 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${W.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${W.keys.length>1?"\u0438":""}: ${E(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${W.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};var BR=m(()=>{s()});function Uj(){return{localeError:Kx()}}var Kx=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function _(W){return $[W]??null}let J={regex:"vnos",email:"e-po\u0161tni 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 \u010Das",date:"ISO datum",time:"ISO \u010Das",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 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},U={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${W.expected}, prejeto ${Q}`;return`Neveljaven vnos: pri\u010Dakovano ${X}, prejeto ${Q}`}case"invalid_value":if(W.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${k(W.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Preveliko: pri\u010Dakovano, da bo ${W.origin??"vrednost"} imelo ${X}${W.maximum.toString()} ${G.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${W.origin??"vrednost"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Premajhno: pri\u010Dakovano, da bo ${W.origin} imelo ${X}${W.minimum.toString()} ${G.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${X.prefix}"`;if(X.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${X.suffix}"`;if(X.format==="includes")return`Neveljaven niz: mora vsebovati "${X.includes}"`;if(X.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${X.pattern}`;return`Neveljaven ${J[X.format]??W.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${W.divisor}`;case"unrecognized_keys":return`Neprepoznan${W.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${E(W.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${W.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${W.origin}`;default:return"Neveljaven vnos"}}};var HR=m(()=>{s()});function Xj(){return{localeError:Mx()}}var Mx=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function _(W){return $[W]??null}let J={regex:"regulj\xE4rt 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\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},U={nan:"NaN",number:"antal",array:"lista"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${W.expected}, fick ${Q}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${X}, fick ${Q}`}case"invalid_value":if(W.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${k(W.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.maximum.toString()} ${G.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${W.origin??"v\xE4rdet"} att ha ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.minimum.toString()} ${G.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${X.prefix}"`;if(X.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${X.suffix}"`;if(X.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${X.includes}"`;if(X.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${X.pattern}"`;return`Ogiltig(t) ${J[X.format]??W.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${E(W.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${W.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${W.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var NR=m(()=>{s()});function Gj(){return{localeError:Ax()}}var Ax=()=>{let $={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function _(W){return $[W]??null}let J={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${W.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Q}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${X}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${k(W.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${E(W.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${X}${W.maximum.toString()} ${G.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${X}${W.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin} ${X}${W.minimum.toString()} ${G.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin} ${X}${W.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${X.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${W.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${W.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${E(W.keys,", ")}`;case"invalid_key":return`${W.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${W.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};var VR=m(()=>{s()});function Qj(){return{localeError:bx()}}var bx=()=>{let $={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function _(W){return $[W]??null}let J={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},U={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${W.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${Q}`;return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${X} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${Q}`}case"invalid_value":if(W.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${k(W.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",G=_(W.origin);if(G)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.maximum.toString()} ${G.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",G=_(W.origin);if(G)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.minimum.toString()} ${G.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${X.prefix}"`;if(X.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${X.suffix}"`;if(X.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${X.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(X.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${X.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${W.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${E(W.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${W.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${W.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var FR=m(()=>{s()});function Yj(){return{localeError:Ex()}}var Ex=()=>{let $={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function _(W){return $[W]??null}let J={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\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${W.expected}, al\u0131nan ${Q}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${X}, al\u0131nan ${Q}`}case"invalid_value":if(W.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${k(W.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\xC7ok b\xFCy\xFCk: beklenen ${W.origin??"de\u011Fer"} ${X}${W.maximum.toString()} ${G.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${W.origin??"de\u011Fer"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ge\xE7ersiz metin: "${X.prefix}" ile ba\u015Flamal\u0131`;if(X.format==="ends_with")return`Ge\xE7ersiz metin: "${X.suffix}" ile bitmeli`;if(X.format==="includes")return`Ge\xE7ersiz metin: "${X.includes}" i\xE7ermeli`;if(X.format==="regex")return`Ge\xE7ersiz metin: ${X.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${J[X.format]??W.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${W.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${W.keys.length>1?"lar":""}: ${E(W.keys,", ")}`;case"invalid_key":return`${W.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${W.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var RR=m(()=>{s()});function cU(){return{localeError:wx()}}var wx=()=>{let $={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${W.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${Q}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${X}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${Q}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${k(W.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin} \u0431\u0443\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${W.keys.length>1?"\u0456":""}: ${E(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${W.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};var qj=m(()=>{s()});function zj(){return cU()}var KR=m(()=>{qj()});function jj(){return{localeError:Ix()}}var Ix=()=>{let $={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function _(W){return $[W]??null}let J={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},U={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${W.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${Q} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${X} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${Q} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(W.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${k(W.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${E(W.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${W.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${W.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${X}${W.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${W.origin} \u06A9\u06D2 ${X}${W.minimum.toString()} ${G.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${W.origin} \u06A9\u0627 ${X}${W.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${X.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${W.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${W.keys.length>1?"\u0632":""}: ${E(W.keys,"\u060C ")}`;case"invalid_key":return`${W.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${W.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var MR=m(()=>{s()});function Oj(){return{localeError:gx()}}var gx=()=>{let $={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"raqam",array:"massiv"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${W.expected}, qabul qilingan ${Q}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${X}, qabul qilingan ${Q}`}case"invalid_value":if(W.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${k(W.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Juda katta: kutilgan ${W.origin??"qiymat"} ${X}${W.maximum.toString()} ${G.unit} ${G.verb}`;return`Juda katta: kutilgan ${W.origin??"qiymat"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Juda kichik: kutilgan ${W.origin} ${X}${W.minimum.toString()} ${G.unit} ${G.verb}`;return`Juda kichik: kutilgan ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${X.prefix}" bilan boshlanishi kerak`;if(X.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${X.suffix}" bilan tugashi kerak`;if(X.format==="includes")return`Noto\u2018g\u2018ri satr: "${X.includes}" ni o\u2018z ichiga olishi kerak`;if(X.format==="regex")return`Noto\u2018g\u2018ri satr: ${X.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${J[X.format]??W.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${W.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${W.keys.length>1?"lar":""}: ${E(W.keys,", ")}`;case"invalid_key":return`${W.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${W.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var AR=m(()=>{s()});function Dj(){return{localeError:kx()}}var kx=()=>{let $={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function _(W){return $[W]??null}let J={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 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\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},U={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${W.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${Q}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${X}, nh\u1EADn \u0111\u01B0\u1EE3c ${Q}`}case"invalid_value":if(W.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${k(W.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${W.origin??"gi\xE1 tr\u1ECB"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${W.origin??"gi\xE1 tr\u1ECB"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${X.prefix}"`;if(X.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${X.suffix}"`;if(X.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${X.includes}"`;if(X.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${X.pattern}`;return`${J[X.format]??W.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${W.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${E(W.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${W.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${W.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var bR=m(()=>{s()});function Lj(){return{localeError:fx()}}var fx=()=>{let $={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function _(W){return $[W]??null}let J={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},U={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${W.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${Q}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${X}\uFF0C\u5B9E\u9645\u63A5\u6536 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${k(W.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${W.origin??"\u503C"} ${X}${W.maximum.toString()} ${G.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${W.origin??"\u503C"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${X.prefix}" \u5F00\u5934`;if(X.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${X.suffix}" \u7ED3\u5C3E`;if(X.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${X.includes}"`;if(X.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${X.pattern}`;return`\u65E0\u6548${J[X.format]??W.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${W.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${E(W.keys,", ")}`;case"invalid_key":return`${W.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${W.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var ER=m(()=>{s()});function Bj(){return{localeError:Cx()}}var Cx=()=>{let $={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function _(W){return $[W]??null}let J={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",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 \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${W.expected}\uFF0C\u4F46\u6536\u5230 ${Q}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${X}\uFF0C\u4F46\u6536\u5230 ${Q}`}case"invalid_value":if(W.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${k(W.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${W.origin??"\u503C"} \u61C9\u70BA ${X}${W.maximum.toString()} ${G.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${W.origin??"\u503C"} \u61C9\u70BA ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${W.origin} \u61C9\u70BA ${X}${W.minimum.toString()} ${G.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${W.origin} \u61C9\u70BA ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${X.prefix}" \u958B\u982D`;if(X.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${X.suffix}" \u7D50\u5C3E`;if(X.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${X.includes}"`;if(X.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${X.pattern}`;return`\u7121\u6548\u7684 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${W.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${W.keys.length>1?"\u5011":""}\uFF1A${E(W.keys,"\u3001")}`;case"invalid_key":return`${W.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${W.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var wR=m(()=>{s()});function Hj(){return{localeError:Px()}}var Px=()=>{let $={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function _(W){return $[W]??null}let J={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",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:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},U={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Q=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${W.expected}, \xE0m\u1ECD\u0300 a r\xED ${Q}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${X}, \xE0m\u1ECD\u0300 a r\xED ${Q}`}case"invalid_value":if(W.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${k(W.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${E(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${W.origin??"iye"} ${G.verb} ${X}${W.maximum} ${G.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${X}${W.maximum}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${W.origin} ${G.verb} ${X}${W.minimum} ${G.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${X}${W.minimum}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${X.prefix}"`;if(X.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${X.suffix}"`;if(X.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${X.includes}"`;if(X.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${X.pattern}`;return`A\u1E63\xEC\u1E63e: ${J[X.format]??W.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${W.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${E(W.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${W.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${W.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var IR=m(()=>{s()});var oJ={};s4(oJ,{zhTW:()=>Bj,zhCN:()=>Lj,yo:()=>Hj,vi:()=>Dj,uz:()=>Oj,ur:()=>jj,uk:()=>cU,ua:()=>zj,tr:()=>Yj,th:()=>Qj,ta:()=>Gj,sv:()=>Xj,sl:()=>Uj,ru:()=>Wj,ro:()=>Jj,pt:()=>_j,ps:()=>ez,pl:()=>$j,ota:()=>sz,no:()=>az,nl:()=>tz,ms:()=>oz,mk:()=>pz,lt:()=>rz,ko:()=>iz,km:()=>uU,kh:()=>nz,ka:()=>cz,ja:()=>dz,it:()=>uz,is:()=>xz,id:()=>mz,hy:()=>hz,hu:()=>yz,hr:()=>vz,he:()=>Zz,frCA:()=>Sz,fr:()=>Tz,fi:()=>Pz,fa:()=>Cz,es:()=>fz,eo:()=>kz,en:()=>xU,el:()=>Iz,de:()=>wz,da:()=>Ez,cs:()=>bz,ca:()=>Az,bg:()=>Mz,be:()=>Kz,az:()=>Rz,ar:()=>Fz});var Nj=m(()=>{kF();fF();PF();TF();SF();ZF();vF();yF();hF();gz();mF();xF();uF();dF();cF();lF();nF();iF();rF();oF();tF();aF();sF();eF();$R();_R();lz();JR();UR();XR();GR();QR();YR();qR();zR();jR();OR();DR();BR();HR();NR();VR();FR();RR();KR();qj();MR();AR();bR();ER();wR();IR()});class Vj{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,..._){let J=_[0];if(this._map.set($,J),J&&typeof J==="object"&&"id"in J)this._idmap.set(J.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let _=this._map.get($);if(_&&typeof _==="object"&&"id"in _)this._idmap.delete(_.id);return this._map.delete($),this}get($){let _=$._zod.parent;if(_){let J={...this.get(_)??{}};delete J.id;let U={...J,...this._map.get($)};return Object.keys(U).length?U:void 0}return this._map.get($)}has($){return this._map.has($)}}function lU(){return new Vj}var gR,m8,x8,w6;var nU=m(()=>{m8=Symbol("ZodOutput"),x8=Symbol("ZodInput");(gR=globalThis).__zod_globalRegistry??(gR.__zod_globalRegistry=lU());w6=globalThis.__zod_globalRegistry});function Fj($,_){return new $({type:"string",...y(_)})}function Rj($,_){return new $({type:"string",coerce:!0,...y(_)})}function u8($,_){return new $({type:"string",format:"email",check:"string_format",abort:!1,...y(_)})}function iU($,_){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...y(_)})}function d8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...y(_)})}function c8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...y(_)})}function l8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...y(_)})}function n8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...y(_)})}function rU($,_){return new $({type:"string",format:"url",check:"string_format",abort:!1,...y(_)})}function i8($,_){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...y(_)})}function r8($,_){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...y(_)})}function p8($,_){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...y(_)})}function o8($,_){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...y(_)})}function t8($,_){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...y(_)})}function a8($,_){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...y(_)})}function s8($,_){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...y(_)})}function e8($,_){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...y(_)})}function $G($,_){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...y(_)})}function Kj($,_){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...y(_)})}function _G($,_){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...y(_)})}function JG($,_){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...y(_)})}function WG($,_){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...y(_)})}function UG($,_){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...y(_)})}function XG($,_){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...y(_)})}function GG($,_){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...y(_)})}function Mj($,_){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...y(_)})}function Aj($,_){return new $({type:"string",format:"date",check:"string_format",...y(_)})}function bj($,_){return new $({type:"string",format:"time",check:"string_format",precision:null,...y(_)})}function Ej($,_){return new $({type:"string",format:"duration",check:"string_format",...y(_)})}function wj($,_){return new $({type:"number",checks:[],...y(_)})}function Ij($,_){return new $({type:"number",coerce:!0,checks:[],...y(_)})}function gj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...y(_)})}function kj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...y(_)})}function fj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...y(_)})}function Cj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...y(_)})}function Pj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...y(_)})}function Tj($,_){return new $({type:"boolean",...y(_)})}function Sj($,_){return new $({type:"boolean",coerce:!0,...y(_)})}function Zj($,_){return new $({type:"bigint",...y(_)})}function vj($,_){return new $({type:"bigint",coerce:!0,...y(_)})}function yj($,_){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...y(_)})}function hj($,_){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...y(_)})}function mj($,_){return new $({type:"symbol",...y(_)})}function xj($,_){return new $({type:"undefined",...y(_)})}function uj($,_){return new $({type:"null",...y(_)})}function dj($){return new $({type:"any"})}function cj($){return new $({type:"unknown"})}function lj($,_){return new $({type:"never",...y(_)})}function nj($,_){return new $({type:"void",...y(_)})}function ij($,_){return new $({type:"date",...y(_)})}function rj($,_){return new $({type:"date",coerce:!0,...y(_)})}function pj($,_){return new $({type:"nan",...y(_)})}function m4($,_){return new w8({check:"less_than",...y(_),value:$,inclusive:!1})}function t6($,_){return new w8({check:"less_than",...y(_),value:$,inclusive:!0})}function x4($,_){return new I8({check:"greater_than",...y(_),value:$,inclusive:!1})}function T6($,_){return new I8({check:"greater_than",...y(_),value:$,inclusive:!0})}function pU($){return x4(0,$)}function oU($){return m4(0,$)}function tU($){return t6(0,$)}function aU($){return T6(0,$)}function l0($,_){return new d7({check:"multiple_of",...y(_),value:$})}function n0($,_){return new n7({check:"max_size",...y(_),maximum:$})}function u4($,_){return new i7({check:"min_size",...y(_),minimum:$})}function f1($,_){return new r7({check:"size_equals",...y(_),size:$})}function C1($,_){return new p7({check:"max_length",...y(_),maximum:$})}function D0($,_){return new o7({check:"min_length",...y(_),minimum:$})}function P1($,_){return new t7({check:"length_equals",...y(_),length:$})}function v2($,_){return new a7({check:"string_format",format:"regex",...y(_),pattern:$})}function y2($){return new s7({check:"string_format",format:"lowercase",...y($)})}function h2($){return new e7({check:"string_format",format:"uppercase",...y($)})}function m2($,_){return new $q({check:"string_format",format:"includes",...y(_),includes:$})}function x2($,_){return new _q({check:"string_format",format:"starts_with",...y(_),prefix:$})}function u2($,_){return new Jq({check:"string_format",format:"ends_with",...y(_),suffix:$})}function sU($,_,J){return new Wq({check:"property",property:$,schema:_,...y(J)})}function d2($,_){return new Uq({check:"mime_type",mime:$,...y(_)})}function V4($){return new Xq({check:"overwrite",tx:$})}function c2($){return V4((_)=>_.normalize($))}function l2(){return V4(($)=>$.trim())}function n2(){return V4(($)=>$.toLowerCase())}function i2(){return V4(($)=>$.toUpperCase())}function r2(){return V4(($)=>_7($))}function oj($,_,J){return new $({type:"array",element:_,...y(J)})}function Sx($,_,J){return new $({type:"union",options:_,...y(J)})}function Zx($,_,J){return new $({type:"union",options:_,inclusive:!1,...y(J)})}function vx($,_,J,U){return new $({type:"union",options:J,discriminator:_,...y(U)})}function yx($,_,J){return new $({type:"intersection",left:_,right:J})}function hx($,_,J,U){let W=J instanceof F$;return new $({type:"tuple",items:_,rest:W?J:null,...y(W?U:J)})}function mx($,_,J,U){return new $({type:"record",keyType:_,valueType:J,...y(U)})}function xx($,_,J,U){return new $({type:"map",keyType:_,valueType:J,...y(U)})}function ux($,_,J){return new $({type:"set",valueType:_,...y(J)})}function dx($,_,J){let U=Array.isArray(_)?Object.fromEntries(_.map((W)=>[W,W])):_;return new $({type:"enum",entries:U,...y(J)})}function cx($,_,J){return new $({type:"enum",entries:_,...y(J)})}function lx($,_,J){return new $({type:"literal",values:Array.isArray(_)?_:[_],...y(J)})}function tj($,_){return new $({type:"file",...y(_)})}function nx($,_){return new $({type:"transform",transform:_})}function ix($,_){return new $({type:"optional",innerType:_})}function rx($,_){return new $({type:"nullable",innerType:_})}function px($,_,J){return new $({type:"default",innerType:_,get defaultValue(){return typeof J==="function"?J():W7(J)}})}function ox($,_,J){return new $({type:"nonoptional",innerType:_,...y(J)})}function tx($,_){return new $({type:"success",innerType:_})}function ax($,_,J){return new $({type:"catch",innerType:_,catchValue:typeof J==="function"?J:()=>J})}function sx($,_,J){return new $({type:"pipe",in:_,out:J})}function ex($,_){return new $({type:"readonly",innerType:_})}function $u($,_,J){return new $({type:"template_literal",parts:_,...y(J)})}function _u($,_){return new $({type:"lazy",getter:_})}function Ju($,_){return new $({type:"promise",innerType:_})}function aj($,_,J){let U=y(J);return U.abort??(U.abort=!0),new $({type:"custom",check:"custom",fn:_,...U})}function sj($,_,J){return new $({type:"custom",check:"custom",fn:_,...y(J)})}function ej($,_){let J=kR((U)=>{return U.addIssue=(W)=>{if(typeof W==="string")U.issues.push(xJ(W,U.value,J._zod.def));else{let X=W;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=U.value),X.inst??(X.inst=J),X.continue??(X.continue=!J._zod.def.abort),U.issues.push(xJ(X))}},$(U.value,U)},_);return J}function kR($,_){let J=new W6({check:"custom",...y(_)});return J._zod.check=$,J}function $O($){let _=new W6({check:"describe"});return _._zod.onattach=[(J)=>{let U=w6.get(J)??{};w6.add(J,{...U,description:$})}],_._zod.check=()=>{},_}function _O($){let _=new W6({check:"meta"});return _._zod.onattach=[(J)=>{let U=w6.get(J)??{};w6.add(J,{...U,...$})}],_._zod.check=()=>{},_}function JO($,_){let J=y(_),U=J.truthy??["true","1","yes","on","y","enabled"],W=J.falsy??["false","0","no","off","n","disabled"];if(J.case!=="sensitive")U=U.map((B)=>typeof B==="string"?B.toLowerCase():B),W=W.map((B)=>typeof B==="string"?B.toLowerCase():B);let X=new Set(U),G=new Set(W),Q=$.Codec??mU,Y=$.Boolean??yU,L=new($.String??Z2)({type:"string",error:J.error}),N=new Y({type:"boolean",error:J.error}),F=new Q({type:"pipe",in:L,out:N,transform:(B,H)=>{let V=B;if(J.case!=="sensitive")V=V.toLowerCase();if(X.has(V))return!0;else if(G.has(V))return!1;else return H.issues.push({code:"invalid_value",expected:"stringbool",values:[...X,...G],input:H.value,inst:F,continue:!1}),{}},reverseTransform:(B,H)=>{if(B===!0)return U[0]||"true";else return W[0]||"false"},error:J.error});return F}function tJ($,_,J,U={}){let W=y(U),X={...y(U),check:"string_format",type:"string",format:_,fn:typeof J==="function"?J:(Q)=>J.test(Q),...W};if(J instanceof RegExp)X.pattern=J;return new $(X)}var QG;var fR=m(()=>{g8();nU();Vz();s();QG={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function T1($){let _=$?.target??"draft-2020-12";if(_==="draft-4")_="draft-04";if(_==="draft-7")_="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??w6,target:_,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function i$($,_,J={path:[],schemaPath:[]}){var U;let W=$._zod.def,X=_.seen.get($);if(X){if(X.count++,J.schemaPath.includes($))X.cycle=J.path;return X.schema}let G={schema:{},count:1,cycle:void 0,path:J.path};_.seen.set($,G);let Q=$._zod.toJSONSchema?.();if(Q)G.schema=Q;else{let L={...J,schemaPath:[...J.schemaPath,$],path:J.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(_,G.schema,L);else{let F=G.schema,B=_.processors[W.type];if(!B)throw Error(`[toJSONSchema]: Non-representable type encountered: ${W.type}`);B($,_,F,L)}let N=$._zod.parent;if(N){if(!G.ref)G.ref=N;i$(N,_,L),_.seen.get(N).isParent=!0}}let Y=_.metadataRegistry.get($);if(Y)Object.assign(G.schema,Y);if(_.io==="input"&&c6($))delete G.schema.examples,delete G.schema.default;if(_.io==="input"&&"_prefault"in G.schema)(U=G.schema).default??(U.default=G.schema._prefault);return delete G.schema._prefault,_.seen.get($).schema}function S1($,_){let J=$.seen.get(_);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let U=new Map;for(let G of $.seen.entries()){let Q=$.metadataRegistry.get(G[0])?.id;if(Q){let Y=U.get(Q);if(Y&&Y!==G[0])throw Error(`Duplicate schema id "${Q}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);U.set(Q,G[0])}}let W=(G)=>{let Q=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let N=$.external.registry.get(G[0])?.id,F=$.external.uri??((H)=>H);if(N)return{ref:F(N)};let B=G[1].defId??G[1].schema.id??`schema${$.counter++}`;return G[1].defId=B,{defId:B,ref:`${F("__shared")}#/${Q}/${B}`}}if(G[1]===J)return{ref:"#"};let q=`${"#"}/${Q}/`,L=G[1].schema.id??`__schema${$.counter++}`;return{defId:L,ref:q+L}},X=(G)=>{if(G[1].schema.$ref)return;let Q=G[1],{ref:Y,defId:q}=W(G);if(Q.def={...Q.schema},q)Q.defId=q;let L=Q.schema;for(let N in L)delete L[N];L.$ref=Y};if($.cycles==="throw")for(let G of $.seen.entries()){let Q=G[1];if(Q.cycle)throw Error(`Cycle detected: #/${Q.cycle?.join("/")}/ + `)}B.write("payload.value = newResult;"),B.write("return payload;");let F=B.compile();return(w,A)=>F(R,w,A)},X,G=v1,Y=!T1.jitless,q=Y&&qq.value,L=_.catchall,N;$._zod.parse=(R,B)=>{N??(N=U.value);let H=R.value;if(!G(H))return R.issues.push({expected:"object",code:"invalid_type",input:H,inst:$}),R;if(Y&&q&&B?.async===!1&&B.jitless!==!0){if(!X)X=W(_.shape);if(R=X(R,B),!L)return R;return hR([],H,R,B,N,$)}return J(R,B)}});nU=M("$ZodUnion",($,_)=>{R$.init($,_),Z$($._zod,"optin",()=>_.options.some((U)=>U._zod.optin==="optional")?"optional":void 0),Z$($._zod,"optout",()=>_.options.some((U)=>U._zod.optout==="optional")?"optional":void 0),Z$($._zod,"values",()=>{if(_.options.every((U)=>U._zod.values))return new Set(_.options.flatMap((U)=>Array.from(U._zod.values)));return}),Z$($._zod,"pattern",()=>{if(_.options.every((U)=>U._zod.pattern)){let U=_.options.map((W)=>W._zod.pattern);return new RegExp(`^(${U.map((W)=>SU(W.source)).join("|")})$`)}return});let J=_.options.length===1?_.options[0]._zod.run:null;$._zod.parse=(U,W)=>{if(J)return J(U,W);let X=!1,G=[];for(let Y of _.options){let Q=Y._zod.run({value:U.value,issues:[]},W);if(Q instanceof Promise)G.push(Q),X=!0;else{if(Q.issues.length===0)return Q;G.push(Q)}}if(!X)return ER(G,U,$,W);return Promise.all(G).then((Y)=>{return ER(Y,U,$,W)})}});$z=M("$ZodXor",($,_)=>{nU.init($,_),_.inclusive=!1;let J=_.options.length===1?_.options[0]._zod.run:null;$._zod.parse=(U,W)=>{if(J)return J(U,W);let X=!1,G=[];for(let Y of _.options){let Q=Y._zod.run({value:U.value,issues:[]},W);if(Q instanceof Promise)G.push(Q),X=!0;else G.push(Q)}if(!X)return MR(G,U,$,W);return Promise.all(G).then((Y)=>{return MR(Y,U,$,W)})}}),_z=M("$ZodDiscriminatedUnion",($,_)=>{_.inclusive=!1,nU.init($,_);let J=$._zod.parse;Z$($._zod,"propValues",()=>{let W={};for(let X of _.options){let G=X._zod.propValues;if(!G||Object.keys(G).length===0)throw Error(`Invalid discriminated union option at index "${_.options.indexOf(X)}"`);for(let[Y,Q]of Object.entries(G)){if(!W[Y])W[Y]=new Set;for(let q of Q)W[Y].add(q)}}return W});let U=cJ(()=>{let W=_.options,X=new Map;for(let G of W){let Y=G._zod.propValues?.[_.discriminator];if(!Y||Y.size===0)throw Error(`Invalid discriminated union option at index "${_.options.indexOf(G)}"`);for(let Q of Y){if(X.has(Q))throw Error(`Duplicate discriminator value "${String(Q)}"`);X.set(Q,G)}}return X});$._zod.parse=(W,X)=>{let G=W.value;if(!v1(G))return W.issues.push({code:"invalid_type",expected:"object",input:G,inst:$}),W;let Y=U.value.get(G?.[_.discriminator]);if(Y)return Y._zod.run(W,X);if(_.unionFallback||X.direction==="backward")return J(W,X);return W.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:_.discriminator,options:Array.from(U.value.keys()),input:G,path:[_.discriminator],inst:$}),W}}),Jz=M("$ZodIntersection",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value,X=_.left._zod.run({value:W,issues:[]},U),G=_.right._zod.run({value:W,issues:[]},U);if(X instanceof Promise||G instanceof Promise)return Promise.all([X,G]).then(([Q,q])=>{return AR(J,Q,q)});return AR(J,X,G)}});u8=M("$ZodTuple",($,_)=>{R$.init($,_);let J=_.items;$._zod.parse=(U,W)=>{let X=U.value;if(!Array.isArray(X))return U.issues.push({input:X,inst:$,expected:"tuple",code:"invalid_type"}),U;U.value=[];let G=[],Y=bR(J,"optin"),Q=bR(J,"optout");if(!_.rest){if(X.lengthJ.length)U.issues.push({code:"too_big",maximum:J.length,inclusive:!0,input:X,inst:$,origin:"array"})}let q=Array(J.length);for(let L=0;L{q[L]=R}));else q[L]=N}if(_.rest){let L=J.length-1,N=X.slice(J.length);for(let R of N){L++;let B=_.rest._zod.run({value:R,issues:[]},W);if(B instanceof Promise)G.push(B.then((H)=>wR(H,U,L)));else wR(B,U,L)}}if(G.length)return Promise.all(G).then(()=>gR(q,U,J,X,Q));return gR(q,U,J,X,Q)}});Wz=M("$ZodRecord",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!f0(W))return J.issues.push({expected:"record",code:"invalid_type",input:W,inst:$}),J;let X=[],G=_.keyType._zod.values;if(G){J.value={};let Y=new Set;for(let q of G)if(typeof q==="string"||typeof q==="number"||typeof q==="symbol"){Y.add(typeof q==="number"?q.toString():q);let L=_.keyType._zod.run({value:q,issues:[]},U);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length){J.issues.push({code:"invalid_key",origin:"record",issues:L.issues.map((B)=>n_(B,U,V_())),input:q,path:[q],inst:$});continue}let N=L.value,R=_.valueType._zod.run({value:W[q],issues:[]},U);if(R instanceof Promise)X.push(R.then((B)=>{if(B.issues.length)J.issues.push(...p_(q,B.issues));J.value[N]=B.value}));else{if(R.issues.length)J.issues.push(...p_(q,R.issues));J.value[N]=R.value}}let Q;for(let q in W)if(!Y.has(q))Q=Q??[],Q.push(q);if(Q&&Q.length>0)J.issues.push({code:"unrecognized_keys",input:W,inst:$,keys:Q})}else{J.value={};for(let Y of Reflect.ownKeys(W)){if(Y==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(W,Y))continue;let Q=_.keyType._zod.run({value:Y,issues:[]},U);if(Q instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof Y==="string"&&mU.test(Y)&&Q.issues.length){let N=_.keyType._zod.run({value:Number(Y),issues:[]},U);if(N instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(N.issues.length===0)Q=N}if(Q.issues.length){if(_.mode==="loose")J.value[Y]=W[Y];else J.issues.push({code:"invalid_key",origin:"record",issues:Q.issues.map((N)=>n_(N,U,V_())),input:Y,path:[Y],inst:$});continue}let L=_.valueType._zod.run({value:W[Y],issues:[]},U);if(L instanceof Promise)X.push(L.then((N)=>{if(N.issues.length)J.issues.push(...p_(Y,N.issues));J.value[Q.value]=N.value}));else{if(L.issues.length)J.issues.push(...p_(Y,L.issues));J.value[Q.value]=L.value}}}if(X.length)return Promise.all(X).then(()=>J);return J}}),Uz=M("$ZodMap",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!(W instanceof Map))return J.issues.push({expected:"map",code:"invalid_type",input:W,inst:$}),J;let X=[];J.value=new Map;for(let[G,Y]of W){let Q=_.keyType._zod.run({value:G,issues:[]},U),q=_.valueType._zod.run({value:Y,issues:[]},U);if(Q instanceof Promise||q instanceof Promise)X.push(Promise.all([Q,q]).then(([L,N])=>{kR(L,N,J,G,W,$,U)}));else kR(Q,q,J,G,W,$,U)}if(X.length)return Promise.all(X).then(()=>J);return J}});Xz=M("$ZodSet",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(!(W instanceof Set))return J.issues.push({input:W,inst:$,expected:"set",code:"invalid_type"}),J;let X=[];J.value=new Set;for(let G of W){let Y=_.valueType._zod.run({value:G,issues:[]},U);if(Y instanceof Promise)X.push(Y.then((Q)=>IR(Q,J)));else IR(Y,J)}if(X.length)return Promise.all(X).then(()=>J);return J}});Gz=M("$ZodEnum",($,_)=>{R$.init($,_);let J=TU(_.entries),U=new Set(J);$._zod.values=U,$._zod.pattern=new RegExp(`^(${J.filter((W)=>ZU.has(typeof W)).map((W)=>typeof W==="string"?V6(W):W.toString()).join("|")})$`),$._zod.parse=(W,X)=>{let G=W.value;if(U.has(G))return W;return W.issues.push({code:"invalid_value",values:J,input:G,inst:$}),W}}),Yz=M("$ZodLiteral",($,_)=>{if(R$.init($,_),_.values.length===0)throw Error("Cannot create literal schema with no valid values");let J=new Set(_.values);$._zod.values=J,$._zod.pattern=new RegExp(`^(${_.values.map((U)=>typeof U==="string"?V6(U):U?V6(U.toString()):String(U)).join("|")})$`),$._zod.parse=(U,W)=>{let X=U.value;if(J.has(X))return U;return U.issues.push({code:"invalid_value",values:_.values,input:X,inst:$}),U}}),Qz=M("$ZodFile",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{let W=J.value;if(W instanceof File)return J;return J.issues.push({expected:"file",code:"invalid_type",input:W,inst:$}),J}}),qz=M("$ZodTransform",($,_)=>{R$.init($,_),$._zod.optin="optional",$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new S1($.constructor.name);let W=_.transform(J.value,J);if(U.async)return(W instanceof Promise?W:Promise.resolve(W)).then((G)=>{return J.value=G,J.fallback=!0,J});if(W instanceof Promise)throw new O4;return J.value=W,J.fallback=!0,J}});d8=M("$ZodOptional",($,_)=>{R$.init($,_),$._zod.optin="optional",$._zod.optout="optional",Z$($._zod,"values",()=>{return _.innerType._zod.values?new Set([..._.innerType._zod.values,void 0]):void 0}),Z$($._zod,"pattern",()=>{let J=_.innerType._zod.pattern;return J?new RegExp(`^(${SU(J.source)})?$`):void 0}),$._zod.parse=(J,U)=>{if(_.innerType._zod.optin==="optional"){let W=J.value,X=_.innerType._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>fR(G,W));return fR(X,W)}if(J.value===void 0)return J;return _.innerType._zod.run(J,U)}}),zz=M("$ZodExactOptional",($,_)=>{d8.init($,_),Z$($._zod,"values",()=>_.innerType._zod.values),Z$($._zod,"pattern",()=>_.innerType._zod.pattern),$._zod.parse=(J,U)=>{return _.innerType._zod.run(J,U)}}),jz=M("$ZodNullable",($,_)=>{R$.init($,_),Z$($._zod,"optin",()=>_.innerType._zod.optin),Z$($._zod,"optout",()=>_.innerType._zod.optout),Z$($._zod,"pattern",()=>{let J=_.innerType._zod.pattern;return J?new RegExp(`^(${SU(J.source)}|null)$`):void 0}),Z$($._zod,"values",()=>{return _.innerType._zod.values?new Set([..._.innerType._zod.values,null]):void 0}),$._zod.parse=(J,U)=>{if(J.value===null)return J;return _.innerType._zod.run(J,U)}}),Dz=M("$ZodDefault",($,_)=>{R$.init($,_),$._zod.optin="optional",Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);if(J.value===void 0)return J.value=_.defaultValue,J;let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>CR(X,_));return CR(W,_)}});Oz=M("$ZodPrefault",($,_)=>{R$.init($,_),$._zod.optin="optional",Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);if(J.value===void 0)J.value=_.defaultValue;return _.innerType._zod.run(J,U)}}),Lz=M("$ZodNonOptional",($,_)=>{R$.init($,_),Z$($._zod,"values",()=>{let J=_.innerType._zod.values;return J?new Set([...J].filter((U)=>U!==void 0)):void 0}),$._zod.parse=(J,U)=>{let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>PR(X,$));return PR(W,$)}});Bz=M("$ZodSuccess",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new S1("ZodSuccess");let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>{return J.value=X.issues.length===0,J});return J.value=W.issues.length===0,J}}),Hz=M("$ZodCatch",($,_)=>{R$.init($,_),$._zod.optin="optional",Z$($._zod,"optout",()=>_.innerType._zod.optout),Z$($._zod,"values",()=>_.innerType._zod.values),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>{if(J.value=X.value,X.issues.length)J.value=_.catchValue({...J,error:{issues:X.issues.map((G)=>n_(G,U,V_()))},input:J.value}),J.issues=[],J.fallback=!0;return J});if(J.value=W.value,W.issues.length)J.value=_.catchValue({...J,error:{issues:W.issues.map((X)=>n_(X,U,V_()))},input:J.value}),J.issues=[],J.fallback=!0;return J}}),Nz=M("$ZodNaN",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{if(typeof J.value!=="number"||!Number.isNaN(J.value))return J.issues.push({input:J.value,inst:$,expected:"nan",code:"invalid_type"}),J;return J}}),n8=M("$ZodPipe",($,_)=>{R$.init($,_),Z$($._zod,"values",()=>_.in._zod.values),Z$($._zod,"optin",()=>_.in._zod.optin),Z$($._zod,"optout",()=>_.out._zod.optout),Z$($._zod,"propValues",()=>_.in._zod.propValues),$._zod.parse=(J,U)=>{if(U.direction==="backward"){let X=_.out._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>Z8(G,_.in,U));return Z8(X,_.in,U)}let W=_.in._zod.run(J,U);if(W instanceof Promise)return W.then((X)=>Z8(X,_.out,U));return Z8(W,_.out,U)}});cU=M("$ZodCodec",($,_)=>{R$.init($,_),Z$($._zod,"values",()=>_.in._zod.values),Z$($._zod,"optin",()=>_.in._zod.optin),Z$($._zod,"optout",()=>_.out._zod.optout),Z$($._zod,"propValues",()=>_.in._zod.propValues),$._zod.parse=(J,U)=>{if((U.direction||"forward")==="forward"){let X=_.in._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>v8(G,_,U));return v8(X,_,U)}else{let X=_.out._zod.run(J,U);if(X instanceof Promise)return X.then((G)=>v8(G,_,U));return v8(X,_,U)}}});Vz=M("$ZodPreprocess",($,_)=>{n8.init($,_)}),Rz=M("$ZodReadonly",($,_)=>{R$.init($,_),Z$($._zod,"propValues",()=>_.innerType._zod.propValues),Z$($._zod,"values",()=>_.innerType._zod.values),Z$($._zod,"optin",()=>_.innerType?._zod?.optin),Z$($._zod,"optout",()=>_.innerType?._zod?.optout),$._zod.parse=(J,U)=>{if(U.direction==="backward")return _.innerType._zod.run(J,U);let W=_.innerType._zod.run(J,U);if(W instanceof Promise)return W.then(TR);return TR(W)}});Kz=M("$ZodTemplateLiteral",($,_)=>{R$.init($,_);let J=[];for(let U of _.parts)if(typeof U==="object"&&U!==null){if(!U._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...U._zod.traits].shift()}`);let W=U._zod.pattern instanceof RegExp?U._zod.pattern.source:U._zod.pattern;if(!W)throw Error(`Invalid template literal part: ${U._zod.traits}`);let X=W.startsWith("^")?1:0,G=W.endsWith("$")?W.length-1:W.length;J.push(W.slice(X,G))}else if(U===null||jq.has(typeof U))J.push(V6(`${U}`));else throw Error(`Invalid template literal part: ${U}`);$._zod.pattern=new RegExp(`^${J.join("")}$`),$._zod.parse=(U,W)=>{if(typeof U.value!=="string")return U.issues.push({input:U.value,inst:$,expected:"string",code:"invalid_type"}),U;if($._zod.pattern.lastIndex=0,!$._zod.pattern.test(U.value))return U.issues.push({input:U.value,inst:$,code:"invalid_format",format:_.format??"template_literal",pattern:$._zod.pattern.source}),U;return U}}),Fz=M("$ZodFunction",($,_)=>{return R$.init($,_),$._def=_,$._zod.def=_,$.implement=(J)=>{if(typeof J!=="function")throw Error("implement() must be called with a function");return function(...U){let W=$._def.input?R8($._def.input,U):U,X=Reflect.apply(J,this,W);if($._def.output)return R8($._def.output,X);return X}},$.implementAsync=(J)=>{if(typeof J!=="function")throw Error("implementAsync() must be called with a function");return async function(...U){let W=$._def.input?await K8($._def.input,U):U,X=await Reflect.apply(J,this,W);if($._def.output)return await K8($._def.output,X);return X}},$._zod.parse=(J,U)=>{if(typeof J.value!=="function")return J.issues.push({code:"invalid_type",expected:"function",input:J.value,inst:$}),J;if($._def.output&&$._def.output._zod.def.type==="promise")J.value=$.implementAsync(J.value);else J.value=$.implement(J.value);return J},$.input=(...J)=>{let U=$.constructor;if(Array.isArray(J[0]))return new U({type:"function",input:new u8({type:"tuple",items:J[0],rest:J[1]}),output:$._def.output});return new U({type:"function",input:J[0],output:$._def.output})},$.output=(J)=>{return new $.constructor({type:"function",input:$._def.input,output:J})},$}),Ez=M("$ZodPromise",($,_)=>{R$.init($,_),$._zod.parse=(J,U)=>{return Promise.resolve(J.value).then((W)=>_.innerType._zod.run({value:W,issues:[]},U))}}),Mz=M("$ZodLazy",($,_)=>{R$.init($,_),Z$($._zod,"innerType",()=>{let J=_;if(!J._cachedInner)J._cachedInner=_.getter();return J._cachedInner}),Z$($._zod,"pattern",()=>$._zod.innerType?._zod?.pattern),Z$($._zod,"propValues",()=>$._zod.innerType?._zod?.propValues),Z$($._zod,"optin",()=>$._zod.innerType?._zod?.optin??void 0),Z$($._zod,"optout",()=>$._zod.innerType?._zod?.optout??void 0),$._zod.parse=(J,U)=>{return $._zod.innerType._zod.run(J,U)}}),Az=M("$ZodCustom",($,_)=>{X_.init($,_),R$.init($,_),$._zod.parse=(J,U)=>{return J},$._zod.check=(J)=>{let U=J.value,W=_.fn(U);if(W instanceof Promise)return W.then((X)=>SR(X,J,U,$));SR(W,J,U,$);return}})});function wz(){return{localeError:Yx()}}var Yx=()=>{let $={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function _(W){return $[W]??null}let J={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${W.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${Y}`;return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${X}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${I(W.values[0])}`;return`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${W.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${X} ${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631"}`;return`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${W.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${W.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${X} ${W.minimum.toString()} ${G.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${W.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${W.prefix}"`;if(X.format==="ends_with")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${X.suffix}"`;if(X.format==="includes")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${X.includes}"`;if(X.format==="regex")return`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${X.pattern}`;return`${J[X.format]??W.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${W.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${W.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${W.keys.length>1?"\u0629":""}: ${b(W.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${W.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${W.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var xR=x(()=>{e()});function gz(){return{localeError:Qx()}}var Qx=()=>{let $={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${W.expected}, daxil olan ${Y}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${X}, daxil olan ${Y}`}case"invalid_value":if(W.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${I(W.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${W.origin??"d\u0259y\u0259r"} ${X}${W.maximum.toString()} ${G.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${W.origin??"d\u0259y\u0259r"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${X.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(X.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${X.suffix}" il\u0259 bitm\u0259lidir`;if(X.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${X.includes}" daxil olmal\u0131d\u0131r`;if(X.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${X.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${J[X.format]??W.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${W.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${W.keys.length>1?"lar":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${W.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var uR=x(()=>{e()});function dR($,_,J,U){let W=Math.abs($),X=W%10,G=W%100;if(G>=11&&G<=19)return U;if(X===1)return _;if(X>=2&&X<=4)return J;return U}function kz(){return{localeError:qx()}}var qx=()=>{let $={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function _(W){return $[W]??null}let J={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},U={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${W.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${Y}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${X}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${I(W.values[0])}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Y=Number(W.maximum),Q=dR(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${G.verb} ${X}${W.maximum.toString()} ${Q}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Y=Number(W.minimum),Q=dR(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${G.verb} ${X}${W.minimum.toString()} ${Q}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${W.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${X.includes}"`;if(X.format==="regex")return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${W.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${W.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${W.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var nR=x(()=>{e()});function Iz(){return{localeError:zx()}}var zx=()=>{let $={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${W.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${Y}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${X}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${I(W.values[0])}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${X}${W.minimum.toString()} ${G.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${W.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${X.pattern}`;let G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(X.format==="emoji")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="datetime")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="date")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(X.format==="time")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(X.format==="duration")G="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${G} ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${W.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${W.keys.length>1?"\u043E\u0432\u0435":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${W.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var cR=x(()=>{e()});function fz(){return{localeError:jx()}}var jx=()=>{let $={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function _(W){return $[W]??null}let J={regex:"entrada",email:"adre\xE7a electr\xF2nica",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\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${W.expected}, s'ha rebut ${Y}`;return`Tipus inv\xE0lid: s'esperava ${X}, s'ha rebut ${Y}`}case"invalid_value":if(W.values.length===1)return`Valor inv\xE0lid: s'esperava ${I(W.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${b(W.values," o ")}`;case"too_big":{let X=W.inclusive?"com a m\xE0xim":"menys de",G=_(W.origin);if(G)return`Massa gran: s'esperava que ${W.origin??"el valor"} contingu\xE9s ${X} ${W.maximum.toString()} ${G.unit??"elements"}`;return`Massa gran: s'esperava que ${W.origin??"el valor"} fos ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"com a m\xEDnim":"m\xE9s de",G=_(W.origin);if(G)return`Massa petit: s'esperava que ${W.origin} contingu\xE9s ${X} ${W.minimum.toString()} ${G.unit}`;return`Massa petit: s'esperava que ${W.origin} fos ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${X.prefix}"`;if(X.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${X.suffix}"`;if(X.format==="includes")return`Format inv\xE0lid: ha d'incloure "${X.includes}"`;if(X.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${X.pattern}`;return`Format inv\xE0lid per a ${J[X.format]??W.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${W.divisor}`;case"unrecognized_keys":return`Clau${W.keys.length>1?"s":""} no reconeguda${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${W.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${W.origin}`;default:return"Entrada inv\xE0lida"}}};var iR=x(()=>{e()});function Cz(){return{localeError:Dx()}}var Dx=()=>{let $={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function _(W){return $[W]??null}let J={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 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 \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},U={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${W.expected}, obdr\u017Eeno ${Y}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${X}, obdr\u017Eeno ${Y}`}case"invalid_value":if(W.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${I(W.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${W.origin??"hodnota"} mus\xED m\xEDt ${X}${W.maximum.toString()} ${G.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${W.origin??"hodnota"} mus\xED b\xFDt ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${W.origin??"hodnota"} mus\xED m\xEDt ${X}${W.minimum.toString()} ${G.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${W.origin??"hodnota"} mus\xED b\xFDt ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${X.prefix}"`;if(X.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${X.suffix}"`;if(X.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${X.includes}"`;if(X.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${X.pattern}`;return`Neplatn\xFD form\xE1t ${J[X.format]??W.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${W.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${b(W.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${W.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${W.origin}`;default:return"Neplatn\xFD vstup"}}};var lR=x(()=>{e()});function Pz(){return{localeError:Ox()}}var Ox=()=>{let $={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function _(W){return $[W]??null}let J={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\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",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"},U={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ugyldigt input: forventede instanceof ${W.expected}, fik ${Y}`;return`Ugyldigt input: forventede ${X}, fik ${Y}`}case"invalid_value":if(W.values.length===1)return`Ugyldig v\xE6rdi: forventede ${I(W.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`For stor: forventede ${Y??"value"} ${G.verb} ${X} ${W.maximum.toString()} ${G.unit??"elementer"}`;return`For stor: forventede ${Y??"value"} havde ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`For lille: forventede ${Y} ${G.verb} ${X} ${W.minimum.toString()} ${G.unit}`;return`For lille: forventede ${Y} havde ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ugyldig streng: skal starte med "${X.prefix}"`;if(X.format==="ends_with")return`Ugyldig streng: skal ende med "${X.suffix}"`;if(X.format==="includes")return`Ugyldig streng: skal indeholde "${X.includes}"`;if(X.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${X.pattern}`;return`Ugyldig ${J[X.format]??W.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${W.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${W.origin}`;default:return"Ugyldigt input"}}};var rR=x(()=>{e()});function Tz(){return{localeError:Lx()}}var Lx=()=>{let $={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 _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"Zahl",array:"Array"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${W.expected}, erhalten ${Y}`;return`Ung\xFCltige Eingabe: erwartet ${X}, erhalten ${Y}`}case"invalid_value":if(W.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${I(W.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Zu gro\xDF: erwartet, dass ${W.origin??"Wert"} ${X}${W.maximum.toString()} ${G.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${W.origin??"Wert"} ${X}${W.maximum.toString()} ist`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Zu klein: erwartet, dass ${W.origin} ${X}${W.minimum.toString()} ${G.unit} hat`;return`Zu klein: erwartet, dass ${W.origin} ${X}${W.minimum.toString()} ist`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ung\xFCltiger String: muss mit "${X.prefix}" beginnen`;if(X.format==="ends_with")return`Ung\xFCltiger String: muss mit "${X.suffix}" enden`;if(X.format==="includes")return`Ung\xFCltiger String: muss "${X.includes}" enthalten`;if(X.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${X.pattern} entsprechen`;return`Ung\xFCltig: ${J[X.format]??W.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${W.divisor} sein`;case"unrecognized_keys":return`${W.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${W.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${W.origin}`;default:return"Ung\xFCltige Eingabe"}}};var pR=x(()=>{e()});function Sz(){return{localeError:Bx()}}var Bx=()=>{let $={string:{unit:"\u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03AE\u03C1\u03B5\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},file:{unit:"bytes",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},array:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},set:{unit:"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"},map:{unit:"\u03BA\u03B1\u03C4\u03B1\u03C7\u03C9\u03C1\u03AE\u03C3\u03B5\u03B9\u03C2",verb:"\u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9"}};function _(W){return $[W]??null}let J={regex:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2",email:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 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 \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1 \u03BA\u03B1\u03B9 \u03CE\u03C1\u03B1",date:"ISO \u03B7\u03BC\u03B5\u03C1\u03BF\u03BC\u03B7\u03BD\u03AF\u03B1",time:"ISO \u03CE\u03C1\u03B1",duration:"ISO \u03B4\u03B9\u03AC\u03C1\u03BA\u03B5\u03B9\u03B1",ipv4:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv4",ipv6:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 IPv6",mac:"\u03B4\u03B9\u03B5\u03CD\u03B8\u03C5\u03BD\u03C3\u03B7 MAC",cidrv4:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv4",cidrv6:"\u03B5\u03CD\u03C1\u03BF\u03C2 IPv6",base64:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64",base64url:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC \u03BA\u03C9\u03B4\u03B9\u03BA\u03BF\u03C0\u03BF\u03B9\u03B7\u03BC\u03AD\u03BD\u03B7 \u03C3\u03B5 base64url",json_string:"\u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC JSON",e164:"\u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2 E.164",jwt:"JWT",template_literal:"\u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(typeof W.expected==="string"&&/^[A-Z]/.test(W.expected))return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD instanceof ${W.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${Y}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${X}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${I(W.values[0])}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD \u03AD\u03BD\u03B1 \u03B1\u03C0\u03CC ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${X}${W.maximum.toString()} ${G.unit??"\u03C3\u03C4\u03BF\u03B9\u03C7\u03B5\u03AF\u03B1"}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${X}${W.minimum.toString()} ${G.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${W.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03BE\u03B5\u03BA\u03B9\u03BD\u03AC \u03BC\u03B5 "${X.prefix}"`;if(X.format==="ends_with")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B5\u03BB\u03B5\u03B9\u03CE\u03BD\u03B5\u03B9 \u03BC\u03B5 "${X.suffix}"`;if(X.format==="includes")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C0\u03B5\u03C1\u03B9\u03AD\u03C7\u03B5\u03B9 "${X.includes}"`;if(X.format==="regex")return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C3\u03C5\u03BC\u03B2\u03BF\u03BB\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03C4\u03B1\u03B9\u03C1\u03B9\u03AC\u03B6\u03B5\u03B9 \u03BC\u03B5 \u03C4\u03BF \u03BC\u03BF\u03C4\u03AF\u03B2\u03BF ${X.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${J[X.format]??W.format}`}case"not_multiple_of":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF\u03C2 \u03B1\u03C1\u03B9\u03B8\u03BC\u03CC\u03C2: \u03C0\u03C1\u03AD\u03C0\u03B5\u03B9 \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 \u03C0\u03BF\u03BB\u03BB\u03B1\u03C0\u03BB\u03AC\u03C3\u03B9\u03BF \u03C4\u03BF\u03C5 ${W.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${W.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${W.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${W.origin}`;case"invalid_union":return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2";case"invalid_element":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03C4\u03B9\u03BC\u03AE \u03C3\u03C4\u03BF ${W.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var oR=x(()=>{e()});function iU(){return{localeError:Hx()}}var Hx=()=>{let $={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 _(W){return $[W]??null}let J={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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;return`Invalid input: expected ${X}, received ${Y}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${I(W.values[0])}`;return`Invalid option: expected one of ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Too big: expected ${W.origin??"value"} to have ${X}${W.maximum.toString()} ${G.unit??"elements"}`;return`Too big: expected ${W.origin??"value"} to be ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Too small: expected ${W.origin} to have ${X}${W.minimum.toString()} ${G.unit}`;return`Too small: expected ${W.origin} to be ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Invalid string: must start with "${X.prefix}"`;if(X.format==="ends_with")return`Invalid string: must end with "${X.suffix}"`;if(X.format==="includes")return`Invalid string: must include "${X.includes}"`;if(X.format==="regex")return`Invalid string: must match pattern ${X.pattern}`;return`Invalid ${J[X.format]??W.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${W.divisor}`;case"unrecognized_keys":return`Unrecognized key${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Invalid key in ${W.origin}`;case"invalid_union":if(W.options&&Array.isArray(W.options)&&W.options.length>0)return`Invalid discriminator value. Expected ${W.options.map((G)=>`'${G}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${W.origin}`;default:return"Invalid input"}}};var Zz=x(()=>{e()});function vz(){return{localeError:Nx()}}var Nx=()=>{let $={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function _(W){return $[W]??null}let J={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",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\u016Dro",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"},U={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${W.expected}, ricevi\u011Dis ${Y}`;return`Nevalida enigo: atendi\u011Dis ${X}, ricevi\u011Dis ${Y}`}case"invalid_value":if(W.values.length===1)return`Nevalida enigo: atendi\u011Dis ${I(W.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Tro granda: atendi\u011Dis ke ${W.origin??"valoro"} havu ${X}${W.maximum.toString()} ${G.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${W.origin??"valoro"} havu ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Tro malgranda: atendi\u011Dis ke ${W.origin} havu ${X}${W.minimum.toString()} ${G.unit}`;return`Tro malgranda: atendi\u011Dis ke ${W.origin} estu ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${X.prefix}"`;if(X.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${X.suffix}"`;if(X.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${X.includes}"`;if(X.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${X.pattern}`;return`Nevalida ${J[X.format]??W.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${W.divisor}`;case"unrecognized_keys":return`Nekonata${W.keys.length>1?"j":""} \u015Dlosilo${W.keys.length>1?"j":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${W.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${W.origin}`;default:return"Nevalida enigo"}}};var tR=x(()=>{e()});function yz(){return{localeError:Vx()}}var Vx=()=>{let $={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function _(W){return $[W]??null}let J={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",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\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${W.expected}, recibido ${Y}`;return`Entrada inv\xE1lida: se esperaba ${X}, recibido ${Y}`}case"invalid_value":if(W.values.length===1)return`Entrada inv\xE1lida: se esperaba ${I(W.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Demasiado grande: se esperaba que ${Y??"valor"} tuviera ${X}${W.maximum.toString()} ${G.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${Y??"valor"} fuera ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Demasiado peque\xF1o: se esperaba que ${Y} tuviera ${X}${W.minimum.toString()} ${G.unit}`;return`Demasiado peque\xF1o: se esperaba que ${Y} fuera ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${X.prefix}"`;if(X.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${X.suffix}"`;if(X.format==="includes")return`Cadena inv\xE1lida: debe incluir "${X.includes}"`;if(X.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${X.pattern}`;return`Inv\xE1lido ${J[X.format]??W.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${W.divisor}`;case"unrecognized_keys":return`Llave${W.keys.length>1?"s":""} desconocida${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${U[W.origin]??W.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${U[W.origin]??W.origin}`;default:return"Entrada inv\xE1lida"}}};var aR=x(()=>{e()});function hz(){return{localeError:Rx()}}var Rx=()=>{let $={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function _(W){return $[W]??null}let J={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${W.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${Y} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${X} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${Y} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(W.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${I(W.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;return`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${b(W.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${W.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${W.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} ${G.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${X.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(X.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${X.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(X.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${X.includes}" \u0628\u0627\u0634\u062F`;if(X.format==="regex")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${X.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${J[X.format]??W.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${W.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${W.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${b(W.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${W.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${W.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var sR=x(()=>{e()});function mz(){return{localeError:Kx()}}var Kx=()=>{let $={string:{unit:"merkki\xE4",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\xE4iv\xE4m\xE4\xE4r\xE4n"}};function _(W){return $[W]??null}let J={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",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\xE4iv\xE4m\xE4\xE4r\xE4",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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Virheellinen tyyppi: odotettiin instanceof ${W.expected}, oli ${Y}`;return`Virheellinen tyyppi: odotettiin ${X}, oli ${Y}`}case"invalid_value":if(W.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${I(W.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Liian suuri: ${G.subject} t\xE4ytyy olla ${X}${W.maximum.toString()} ${G.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Liian pieni: ${G.subject} t\xE4ytyy olla ${X}${W.minimum.toString()} ${G.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${X.prefix}"`;if(X.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${X.suffix}"`;if(X.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${X.includes}"`;if(X.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${X.pattern}`;return`Virheellinen ${J[X.format]??W.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${W.divisor} monikerta`;case"unrecognized_keys":return`${W.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${b(W.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\xF6te"}}};var eR=x(()=>{e()});function xz(){return{localeError:Fx()}}var Fx=()=>{let $={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function _(W){return $[W]??null}let J={regex:"entr\xE9e",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\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={string:"cha\xEEne",number:"nombre",int:"entier",boolean:"bool\xE9en",bigint:"grand entier",symbol:"symbole",undefined:"ind\xE9fini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entr\xE9e invalide : instanceof ${W.expected} attendu, ${Y} re\xE7u`;return`Entr\xE9e invalide : ${X} attendu, ${Y} re\xE7u`}case"invalid_value":if(W.values.length===1)return`Entr\xE9e invalide : ${I(W.values[0])} attendu`;return`Option invalide : une valeur parmi ${b(W.values,"|")} attendue`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Trop grand : ${U[W.origin]??"valeur"} doit ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${U[W.origin]??"valeur"} doit \xEAtre ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Trop petit : ${U[W.origin]??"valeur"} doit ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Trop petit : ${U[W.origin]??"valeur"} doit \xEAtre ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${X.prefix}"`;if(X.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${X.suffix}"`;if(X.format==="includes")return`Cha\xEEne invalide : doit inclure "${X.includes}"`;if(X.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${X.pattern}`;return`${J[X.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${W.divisor}`;case"unrecognized_keys":return`Cl\xE9${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${b(W.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${W.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entr\xE9e invalide"}}};var $K=x(()=>{e()});function uz(){return{localeError:Ex()}}var Ex=()=>{let $={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function _(W){return $[W]??null}let J={regex:"entr\xE9e",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\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Entr\xE9e invalide : attendu instanceof ${W.expected}, re\xE7u ${Y}`;return`Entr\xE9e invalide : attendu ${X}, re\xE7u ${Y}`}case"invalid_value":if(W.values.length===1)return`Entr\xE9e invalide : attendu ${I(W.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"\u2264":"<",G=_(W.origin);if(G)return`Trop grand : attendu que ${W.origin??"la valeur"} ait ${X}${W.maximum.toString()} ${G.unit}`;return`Trop grand : attendu que ${W.origin??"la valeur"} soit ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"\u2265":">",G=_(W.origin);if(G)return`Trop petit : attendu que ${W.origin} ait ${X}${W.minimum.toString()} ${G.unit}`;return`Trop petit : attendu que ${W.origin} soit ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${X.prefix}"`;if(X.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${X.suffix}"`;if(X.format==="includes")return`Cha\xEEne invalide : doit inclure "${X.includes}"`;if(X.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${X.pattern}`;return`${J[X.format]??W.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${W.divisor}`;case"unrecognized_keys":return`Cl\xE9${W.keys.length>1?"s":""} non reconnue${W.keys.length>1?"s":""} : ${b(W.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${W.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${W.origin}`;default:return"Entr\xE9e invalide"}}};var _K=x(()=>{e()});function dz(){return{localeError:Mx()}}var Mx=()=>{let $={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},_={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},J=(q)=>q?$[q]:void 0,U=(q)=>{let L=J(q);if(L)return L.label;return q??$.unknown.label},W=(q)=>`\u05D4${U(q)}`,X=(q)=>{return(J(q)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},G=(q)=>{if(!q)return null;return _[q]??null},Y={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",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:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},Q={nan:"NaN"};return(q)=>{switch(q.code){case"invalid_type":{let L=q.expected,N=Q[L??""]??U(L),R=f(q.input),B=Q[R]??$[R]?.label??R;if(/^[A-Z]/.test(q.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${q.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${B}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${N}, \u05D4\u05EA\u05E7\u05D1\u05DC ${B}`}case"invalid_value":{if(q.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${I(q.values[0])}`;let L=q.values.map((B)=>I(B));if(q.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L[0]} \u05D0\u05D5 ${L[1]}`;let N=L[L.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${L.slice(0,-1).join(", ")} \u05D0\u05D5 ${N}`}case"too_big":{let L=G(q.origin),N=W(q.origin??"value");if(q.origin==="string")return`${L?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${q.maximum.toString()} ${L?.unit??""} ${q.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(q.origin==="number"){let H=q.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${q.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${q.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${H}`}if(q.origin==="array"||q.origin==="set"){let H=q.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",V=q.inclusive?`${q.maximum} ${L?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${q.maximum} ${L?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${V}`.trim()}let R=q.inclusive?"<=":"<",B=X(q.origin??"value");if(L?.unit)return`${L.longLabel} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.maximum.toString()} ${L.unit}`;return`${L?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.maximum.toString()}`}case"too_small":{let L=G(q.origin),N=W(q.origin??"value");if(q.origin==="string")return`${L?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${q.minimum.toString()} ${L?.unit??""} ${q.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(q.origin==="number"){let H=q.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${q.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${q.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${H}`}if(q.origin==="array"||q.origin==="set"){let H=q.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(q.minimum===1&&q.inclusive){let K=q.origin==="set"?"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3":"\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${K}`}let V=q.inclusive?`${q.minimum} ${L?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${q.minimum} ${L?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${N} ${H} \u05DC\u05D4\u05DB\u05D9\u05DC ${V}`.trim()}let R=q.inclusive?">=":">",B=X(q.origin??"value");if(L?.unit)return`${L.shortLabel} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.minimum.toString()} ${L.unit}`;return`${L?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${N} ${B} ${R}${q.minimum.toString()}`}case"invalid_format":{let L=q;if(L.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${L.prefix}"`;if(L.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${L.suffix}"`;if(L.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${L.includes}"`;if(L.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${L.pattern}`;let N=Y[L.format],R=N?.label??L.format,H=(N?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${R} \u05DC\u05D0 ${H}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${q.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${q.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${q.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${b(q.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${W(q.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var JK=x(()=>{e()});function nz(){return{localeError:Ax()}}var Ax=()=>{let $={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function _(W){return $[W]??null}let J={regex:"unos",email:"email 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:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},U={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${W.expected}, a primljeno je ${Y}`;return`Neispravan unos: o\u010Dekuje se ${X}, a primljeno je ${Y}`}case"invalid_value":if(W.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${I(W.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Preveliko: o\u010Dekivano da ${Y??"vrijednost"} ima ${X}${W.maximum.toString()} ${G.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${Y??"vrijednost"} bude ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=U[W.origin]??W.origin;if(G)return`Premalo: o\u010Dekivano da ${Y} ima ${X}${W.minimum.toString()} ${G.unit}`;return`Premalo: o\u010Dekivano da ${Y} bude ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${X.prefix}"`;if(X.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${X.suffix}"`;if(X.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${X.includes}"`;if(X.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${X.pattern}`;return`Neispravna ${J[X.format]??W.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${W.divisor}`;case"unrecognized_keys":return`Neprepoznat${W.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${b(W.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${U[W.origin]??W.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${U[W.origin]??W.origin}`;default:return"Neispravan unos"}}};var WK=x(()=>{e()});function cz(){return{localeError:bx()}}var bx=()=>{let $={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function _(W){return $[W]??null}let J={regex:"bemenet",email:"email c\xEDm",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\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},U={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${W.expected}, a kapott \xE9rt\xE9k ${Y}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${X}, a kapott \xE9rt\xE9k ${Y}`}case"invalid_value":if(W.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${I(W.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`T\xFAl nagy: ${W.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${X}${W.maximum.toString()} ${G.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${W.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${W.origin} m\xE9rete t\xFAl kicsi ${X}${W.minimum.toString()} ${G.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${W.origin} t\xFAl kicsi ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\xC9rv\xE9nytelen string: "${X.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(X.format==="ends_with")return`\xC9rv\xE9nytelen string: "${X.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(X.format==="includes")return`\xC9rv\xE9nytelen string: "${X.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(X.format==="regex")return`\xC9rv\xE9nytelen string: ${X.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${J[X.format]??W.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${W.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${W.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${W.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var UK=x(()=>{e()});function XK($,_,J){return Math.abs($)===1?_:J}function eJ($){if(!$)return"";let _=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],J=$[$.length-1];return $+(_.includes(J)?"\u0576":"\u0568")}function iz(){return{localeError:wx()}}var wx=()=>{let $={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function _(W){return $[W]??null}let J={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},U={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${W.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${Y}`;return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${X}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${I(W.values[1])}`;return`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Y=Number(W.maximum),Q=XK(Y,G.unit.one,G.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${X}${W.maximum.toString()} ${Q}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Y=Number(W.minimum),Q=XK(Y,G.unit.one,G.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${X}${W.minimum.toString()} ${Q}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${eJ(W.origin)} \u056C\u056B\u0576\u056B ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${X.prefix}"-\u0578\u057E`;if(X.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${X.suffix}"-\u0578\u057E`;if(X.format==="includes")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${X.includes}"`;if(X.format==="regex")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${X.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${J[X.format]??W.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${W.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${W.keys.length>1?"\u0576\u0565\u0580":""}. ${b(W.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${eJ(W.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${eJ(W.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var GK=x(()=>{e()});function lz(){return{localeError:gx()}}var gx=()=>{let $={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input tidak valid: diharapkan instanceof ${W.expected}, diterima ${Y}`;return`Input tidak valid: diharapkan ${X}, diterima ${Y}`}case"invalid_value":if(W.values.length===1)return`Input tidak valid: diharapkan ${I(W.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Terlalu besar: diharapkan ${W.origin??"value"} memiliki ${X}${W.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: diharapkan ${W.origin??"value"} menjadi ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Terlalu kecil: diharapkan ${W.origin} memiliki ${X}${W.minimum.toString()} ${G.unit}`;return`Terlalu kecil: diharapkan ${W.origin} menjadi ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`String tidak valid: harus dimulai dengan "${X.prefix}"`;if(X.format==="ends_with")return`String tidak valid: harus berakhir dengan "${X.suffix}"`;if(X.format==="includes")return`String tidak valid: harus menyertakan "${X.includes}"`;if(X.format==="regex")return`String tidak valid: harus sesuai pola ${X.pattern}`;return`${J[X.format]??W.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${W.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${W.origin}`;default:return"Input tidak valid"}}};var YK=x(()=>{e()});function rz(){return{localeError:kx()}}var kx=()=>{let $={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function _(W){return $[W]??null}let J={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",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\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",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\xF6lugildi",jwt:"JWT",template_literal:"gildi"},U={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${Y} \xFEar sem \xE1 a\xF0 vera instanceof ${W.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${Y} \xFEar sem \xE1 a\xF0 vera ${X}`}case"invalid_value":if(W.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${I(W.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin??"gildi"} hafi ${X}${W.maximum.toString()} ${G.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin??"gildi"} s\xE9 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin} hafi ${X}${W.minimum.toString()} ${G.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${W.origin} s\xE9 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${X.prefix}"`;if(X.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${X.suffix}"`;if(X.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${X.includes}"`;if(X.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${X.pattern}`;return`Rangt ${J[X.format]??W.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${W.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${W.keys.length>1?"ir lyklar":"ur lykill"}: ${b(W.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${W.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${W.origin}`;default:return"Rangt gildi"}}};var QK=x(()=>{e()});function pz(){return{localeError:Ix()}}var Ix=()=>{let $={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"numero",array:"vettore"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input non valido: atteso instanceof ${W.expected}, ricevuto ${Y}`;return`Input non valido: atteso ${X}, ricevuto ${Y}`}case"invalid_value":if(W.values.length===1)return`Input non valido: atteso ${I(W.values[0])}`;return`Opzione non valida: atteso uno tra ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Troppo grande: ${W.origin??"valore"} deve avere ${X}${W.maximum.toString()} ${G.unit??"elementi"}`;return`Troppo grande: ${W.origin??"valore"} deve essere ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Troppo piccolo: ${W.origin} deve avere ${X}${W.minimum.toString()} ${G.unit}`;return`Troppo piccolo: ${W.origin} deve essere ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Stringa non valida: deve iniziare con "${X.prefix}"`;if(X.format==="ends_with")return`Stringa non valida: deve terminare con "${X.suffix}"`;if(X.format==="includes")return`Stringa non valida: deve includere "${X.includes}"`;if(X.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${X.pattern}`;return`Input non valido: ${J[X.format]??W.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${W.divisor}`;case"unrecognized_keys":return`Chiav${W.keys.length>1?"i":"e"} non riconosciut${W.keys.length>1?"e":"a"}: ${b(W.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${W.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${W.origin}`;default:return"Input non valido"}}};var qK=x(()=>{e()});function oz(){return{localeError:fx()}}var fx=()=>{let $={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function _(W){return $[W]??null}let J={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},U={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${W.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${Y}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${X}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${Y}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(W.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${I(W.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${b(W.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let X=W.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",G=_(W.origin);if(G)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${W.origin??"\u5024"}\u306F${W.maximum.toString()}${G.unit??"\u8981\u7D20"}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${W.origin??"\u5024"}\u306F${W.maximum.toString()}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let X=W.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",G=_(W.origin);if(G)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${W.origin}\u306F${W.minimum.toString()}${G.unit}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${W.origin}\u306F${W.minimum.toString()}${X}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${X.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(X.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${X.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${J[X.format]??W.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${W.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${W.keys.length>1?"\u7FA4":""}: ${b(W.keys,"\u3001")}`;case"invalid_key":return`${W.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${W.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var zK=x(()=>{e()});function tz(){return{localeError:Cx()}}var Cx=()=>{let $={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function _(W){return $[W]??null}let J={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10D5\u10D4\u10DA\u10D8",json_string:"JSON \u10D5\u10D4\u10DA\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},U={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10D5\u10D4\u10DA\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${W.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${Y}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${X}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${I(W.values[0])}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${b(W.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${W.origin} \u10D8\u10E7\u10DD\u10E1 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${X.prefix}"-\u10D8\u10D7`;if(X.format==="ends_with")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${X.suffix}"-\u10D8\u10D7`;if(X.format==="includes")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${X.includes}"-\u10E1`;if(X.format==="regex")return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D4\u10DA\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${X.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${W.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${W.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${W.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${W.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var jK=x(()=>{e()});function lU(){return{localeError:Px()}}var Px=()=>{let $={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function _(W){return $[W]??null}let J={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},U={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${W.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${Y}`;return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${X} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${I(W.values[0])}`;return`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${X} ${W.maximum.toString()} ${G.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin} ${X} ${W.minimum.toString()} ${G.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${W.origin} ${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${X.prefix}"`;if(X.format==="ends_with")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${X.suffix}"`;if(X.format==="includes")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${X.includes}"`;if(X.format==="regex")return`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${X.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${W.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${b(W.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${W.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${W.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}};var az=x(()=>{e()});function sz(){return lU()}var DK=x(()=>{az()});function ez(){return{localeError:Tx()}}var Tx=()=>{let $={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function _(W){return $[W]??null}let J={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${W.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${Y}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${X}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${Y}\uC785\uB2C8\uB2E4`}case"invalid_value":if(W.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${I(W.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${b(W.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let X=W.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",G=X==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",Y=_(W.origin),Q=Y?.unit??"\uC694\uC18C";if(Y)return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${W.maximum.toString()}${Q} ${X}${G}`;return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${W.maximum.toString()} ${X}${G}`}case"too_small":{let X=W.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",G=X==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",Y=_(W.origin),Q=Y?.unit??"\uC694\uC18C";if(Y)return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${W.minimum.toString()}${Q} ${X}${G}`;return`${W.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${W.minimum.toString()} ${X}${G}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${X.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(X.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${X.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${J[X.format]??W.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${W.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${b(W.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${W.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${W.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var OK=x(()=>{e()});function LK($){let _=Math.abs($),J=_%10,U=_%100;if(U>=11&&U<=19||J===0)return"many";if(J===1)return"one";return"few"}function $j(){return{localeError:Sx()}}var rU=($)=>{return $.charAt(0).toUpperCase()+$.slice(1)},Sx=()=>{let $={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function _(W,X,G,Y){let Q=$[W]??null;if(Q===null)return Q;return{unit:Q.unit[X],verb:Q.verb[Y][G?"inclusive":"notInclusive"]}}let J={regex:"\u012Fvestis",email:"el. pa\u0161to 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\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},U={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Gautas tipas ${Y}, o tik\u0117tasi - instanceof ${W.expected}`;return`Gautas tipas ${Y}, o tik\u0117tasi - ${X}`}case"invalid_value":if(W.values.length===1)return`Privalo b\u016Bti ${I(W.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${b(W.values,"|")} pasirinkim\u0173`;case"too_big":{let X=U[W.origin]??W.origin,G=_(W.origin,LK(Number(W.maximum)),W.inclusive??!1,"smaller");if(G?.verb)return`${rU(X??W.origin??"reik\u0161m\u0117")} ${G.verb} ${W.maximum.toString()} ${G.unit??"element\u0173"}`;let Y=W.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${rU(X??W.origin??"reik\u0161m\u0117")} turi b\u016Bti ${Y} ${W.maximum.toString()} ${G?.unit}`}case"too_small":{let X=U[W.origin]??W.origin,G=_(W.origin,LK(Number(W.minimum)),W.inclusive??!1,"bigger");if(G?.verb)return`${rU(X??W.origin??"reik\u0161m\u0117")} ${G.verb} ${W.minimum.toString()} ${G.unit??"element\u0173"}`;let Y=W.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${rU(X??W.origin??"reik\u0161m\u0117")} turi b\u016Bti ${Y} ${W.minimum.toString()} ${G?.unit}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${X.prefix}"`;if(X.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${X.suffix}"`;if(X.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${X.includes}"`;if(X.format==="regex")return`Eilut\u0117 privalo atitikti ${X.pattern}`;return`Neteisingas ${J[X.format]??W.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${W.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${W.keys.length>1?"i":"as"} rakt${W.keys.length>1?"ai":"as"}: ${b(W.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let X=U[W.origin]??W.origin;return`${rU(X??W.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var BK=x(()=>{e()});function _j(){return{localeError:Zx()}}var Zx=()=>{let $={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function _(W){return $[W]??null}let J={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},U={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${W.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${Y}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${X}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${Y}`}case"invalid_value":if(W.values.length===1)return`Invalid input: expected ${I(W.values[0])}`;return`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin} \u0434\u0430 \u0438\u043C\u0430 ${X}${W.minimum.toString()} ${G.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${W.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${X.pattern}`;return`Invalid ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${W.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${W.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var HK=x(()=>{e()});function Jj(){return{localeError:vx()}}var vx=()=>{let $={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"nombor"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Input tidak sah: dijangka instanceof ${W.expected}, diterima ${Y}`;return`Input tidak sah: dijangka ${X}, diterima ${Y}`}case"invalid_value":if(W.values.length===1)return`Input tidak sah: dijangka ${I(W.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Terlalu besar: dijangka ${W.origin??"nilai"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"elemen"}`;return`Terlalu besar: dijangka ${W.origin??"nilai"} adalah ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Terlalu kecil: dijangka ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Terlalu kecil: dijangka ${W.origin} adalah ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`String tidak sah: mesti bermula dengan "${X.prefix}"`;if(X.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${X.suffix}"`;if(X.format==="includes")return`String tidak sah: mesti mengandungi "${X.includes}"`;if(X.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${X.pattern}`;return`${J[X.format]??W.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${W.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${b(W.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${W.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${W.origin}`;default:return"Input tidak sah"}}};var NK=x(()=>{e()});function Wj(){return{localeError:yx()}}var yx=()=>{let $={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"getal"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ongeldige invoer: verwacht instanceof ${W.expected}, ontving ${Y}`;return`Ongeldige invoer: verwacht ${X}, ontving ${Y}`}case"invalid_value":if(W.values.length===1)return`Ongeldige invoer: verwacht ${I(W.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin),Y=W.origin==="date"?"laat":W.origin==="string"?"lang":"groot";if(G)return`Te ${Y}: verwacht dat ${W.origin??"waarde"} ${X}${W.maximum.toString()} ${G.unit??"elementen"} ${G.verb}`;return`Te ${Y}: verwacht dat ${W.origin??"waarde"} ${X}${W.maximum.toString()} is`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin),Y=W.origin==="date"?"vroeg":W.origin==="string"?"kort":"klein";if(G)return`Te ${Y}: verwacht dat ${W.origin} ${X}${W.minimum.toString()} ${G.unit} ${G.verb}`;return`Te ${Y}: verwacht dat ${W.origin} ${X}${W.minimum.toString()} is`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ongeldige tekst: moet met "${X.prefix}" beginnen`;if(X.format==="ends_with")return`Ongeldige tekst: moet op "${X.suffix}" eindigen`;if(X.format==="includes")return`Ongeldige tekst: moet "${X.includes}" bevatten`;if(X.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${X.pattern}`;return`Ongeldig: ${J[X.format]??W.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${W.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${W.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${W.origin}`;default:return"Ongeldige invoer"}}};var VK=x(()=>{e()});function Uj(){return{localeError:hx()}}var hx=()=>{let $={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function _(W){return $[W]??null}let J={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\xE5de",ipv6:"IPv6-omr\xE5de",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"},U={nan:"NaN",number:"tall",array:"liste"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ugyldig input: forventet instanceof ${W.expected}, fikk ${Y}`;return`Ugyldig input: forventet ${X}, fikk ${Y}`}case"invalid_value":if(W.values.length===1)return`Ugyldig verdi: forventet ${I(W.values[0])}`;return`Ugyldig valg: forventet en av ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`For stor(t): forventet ${W.origin??"value"} til \xE5 ha ${X}${W.maximum.toString()} ${G.unit??"elementer"}`;return`For stor(t): forventet ${W.origin??"value"} til \xE5 ha ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`For lite(n): forventet ${W.origin} til \xE5 ha ${X}${W.minimum.toString()} ${G.unit}`;return`For lite(n): forventet ${W.origin} til \xE5 ha ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${X.prefix}"`;if(X.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${X.suffix}"`;if(X.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${X.includes}"`;if(X.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${X.pattern}`;return`Ugyldig ${J[X.format]??W.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${W.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${W.origin}`;default:return"Ugyldig input"}}};var RK=x(()=>{e()});function Xj(){return{localeError:mx()}}var mx=()=>{let $={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function _(W){return $[W]??null}let J={regex:"giren",email:"epostag\xE2h",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\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},U={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`F\xE2sit giren: umulan instanceof ${W.expected}, al\u0131nan ${Y}`;return`F\xE2sit giren: umulan ${X}, al\u0131nan ${Y}`}case"invalid_value":if(W.values.length===1)return`F\xE2sit giren: umulan ${I(W.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Fazla b\xFCy\xFCk: ${W.origin??"value"}, ${X}${W.maximum.toString()} ${G.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${W.origin??"value"}, ${X}${W.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Fazla k\xFC\xE7\xFCk: ${W.origin}, ${X}${W.minimum.toString()} ${G.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${W.origin}, ${X}${W.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`F\xE2sit metin: "${X.prefix}" ile ba\u015Flamal\u0131.`;if(X.format==="ends_with")return`F\xE2sit metin: "${X.suffix}" ile bitmeli.`;if(X.format==="includes")return`F\xE2sit metin: "${X.includes}" ihtiv\xE2 etmeli.`;if(X.format==="regex")return`F\xE2sit metin: ${X.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${J[X.format]??W.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${W.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${W.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var KK=x(()=>{e()});function Gj(){return{localeError:xx()}}var xx=()=>{let $={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function _(W){return $[W]??null}let J={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},U={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${W.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${Y} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${X} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${Y} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(W.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${I(W.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${b(W.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${W.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${W.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${X}${W.maximum.toString()} \u0648\u064A`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} ${G.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${W.origin} \u0628\u0627\u06CC\u062F ${X}${W.minimum.toString()} \u0648\u064A`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${X.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(X.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${X.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(X.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${X.includes}" \u0648\u0644\u0631\u064A`;if(X.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${X.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${J[X.format]??W.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${W.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${W.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${b(W.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${W.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${W.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var FK=x(()=>{e()});function Yj(){return{localeError:ux()}}var ux=()=>{let $={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function _(W){return $[W]??null}let J={regex:"wyra\u017Cenie",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\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},U={nan:"NaN",number:"liczba",array:"tablica"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${W.expected}, otrzymano ${Y}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${X}, otrzymano ${Y}`}case"invalid_value":if(W.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${I(W.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${X}${W.maximum.toString()} ${G.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${X}${W.minimum.toString()} ${G.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${W.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${X.prefix}"`;if(X.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${X.suffix}"`;if(X.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${X.includes}"`;if(X.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${X.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${J[X.format]??W.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${W.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${W.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${W.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var EK=x(()=>{e()});function Qj(){return{localeError:dx()}}var dx=()=>{let $={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function _(W){return $[W]??null}let J={regex:"padr\xE3o",email:"endere\xE7o 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\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o 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\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},U={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Tipo inv\xE1lido: esperado instanceof ${W.expected}, recebido ${Y}`;return`Tipo inv\xE1lido: esperado ${X}, recebido ${Y}`}case"invalid_value":if(W.values.length===1)return`Entrada inv\xE1lida: esperado ${I(W.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Muito grande: esperado que ${W.origin??"valor"} tivesse ${X}${W.maximum.toString()} ${G.unit??"elementos"}`;return`Muito grande: esperado que ${W.origin??"valor"} fosse ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Muito pequeno: esperado que ${W.origin} tivesse ${X}${W.minimum.toString()} ${G.unit}`;return`Muito pequeno: esperado que ${W.origin} fosse ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${X.prefix}"`;if(X.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${X.suffix}"`;if(X.format==="includes")return`Texto inv\xE1lido: deve incluir "${X.includes}"`;if(X.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${X.pattern}`;return`${J[X.format]??W.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${W.divisor}`;case"unrecognized_keys":return`Chave${W.keys.length>1?"s":""} desconhecida${W.keys.length>1?"s":""}: ${b(W.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${W.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${W.origin}`;default:return"Campo inv\xE1lido"}}};var MK=x(()=>{e()});function qj(){return{localeError:nx()}}var nx=()=>{let $={string:{unit:"caractere",verb:"s\u0103 aib\u0103"},file:{unit:"octe\u021Bi",verb:"s\u0103 aib\u0103"},array:{unit:"elemente",verb:"s\u0103 aib\u0103"},set:{unit:"elemente",verb:"s\u0103 aib\u0103"},map:{unit:"intr\u0103ri",verb:"s\u0103 aib\u0103"}};function _(W){return $[W]??null}let J={regex:"intrare",email:"adres\u0103 de 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:"dat\u0103 \u0219i or\u0103 ISO",date:"dat\u0103 ISO",time:"or\u0103 ISO",duration:"durat\u0103 ISO",ipv4:"adres\u0103 IPv4",ipv6:"adres\u0103 IPv6",mac:"adres\u0103 MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"\u0219ir codat base64",base64url:"\u0219ir codat base64url",json_string:"\u0219ir JSON",e164:"num\u0103r E.164",jwt:"JWT",template_literal:"intrare"},U={nan:"NaN",string:"\u0219ir",number:"num\u0103r",boolean:"boolean",function:"func\u021Bie",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"num\u0103r mare",void:"void",never:"never",map:"hart\u0103",set:"set"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;return`Intrare invalid\u0103: a\u0219teptat ${X}, primit ${Y}`}case"invalid_value":if(W.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${I(W.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Prea mare: a\u0219teptat ca ${W.origin??"valoarea"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${W.origin??"valoarea"} s\u0103 fie ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Prea mic: a\u0219teptat ca ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Prea mic: a\u0219teptat ca ${W.origin} s\u0103 fie ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${X.prefix}"`;if(X.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${X.suffix}"`;if(X.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${X.includes}"`;if(X.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${X.pattern}`;return`Format invalid: ${J[X.format]??W.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${W.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${b(W.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${W.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${W.origin}`;default:return"Intrare invalid\u0103"}}};var AK=x(()=>{e()});function bK($,_,J,U){let W=Math.abs($),X=W%10,G=W%100;if(G>=11&&G<=19)return U;if(X===1)return _;if(X>=2&&X<=4)return J;return U}function zj(){return{localeError:cx()}}var cx=()=>{let $={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${W.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${Y}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${X}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${I(W.values[0])}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G){let Y=Number(W.maximum),Q=bK(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${X}${W.maximum.toString()} ${Q}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G){let Y=Number(W.minimum),Q=bK(Y,G.unit.one,G.unit.few,G.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${X}${W.minimum.toString()} ${Q}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${W.origin} \u0431\u0443\u0434\u0435\u0442 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${W.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${W.keys.length>1?"\u0438":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${W.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}};var wK=x(()=>{e()});function jj(){return{localeError:ix()}}var ix=()=>{let $={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function _(W){return $[W]??null}let J={regex:"vnos",email:"e-po\u0161tni 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 \u010Das",date:"ISO datum",time:"ISO \u010Das",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 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},U={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${W.expected}, prejeto ${Y}`;return`Neveljaven vnos: pri\u010Dakovano ${X}, prejeto ${Y}`}case"invalid_value":if(W.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${I(W.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Preveliko: pri\u010Dakovano, da bo ${W.origin??"vrednost"} imelo ${X}${W.maximum.toString()} ${G.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${W.origin??"vrednost"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Premajhno: pri\u010Dakovano, da bo ${W.origin} imelo ${X}${W.minimum.toString()} ${G.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${X.prefix}"`;if(X.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${X.suffix}"`;if(X.format==="includes")return`Neveljaven niz: mora vsebovati "${X.includes}"`;if(X.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${X.pattern}`;return`Neveljaven ${J[X.format]??W.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${W.divisor}`;case"unrecognized_keys":return`Neprepoznan${W.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${b(W.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${W.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${W.origin}`;default:return"Neveljaven vnos"}}};var gK=x(()=>{e()});function Dj(){return{localeError:lx()}}var lx=()=>{let $={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function _(W){return $[W]??null}let J={regex:"regulj\xE4rt 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\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},U={nan:"NaN",number:"antal",array:"lista"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${W.expected}, fick ${Y}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${X}, fick ${Y}`}case"invalid_value":if(W.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${I(W.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.maximum.toString()} ${G.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${W.origin??"v\xE4rdet"} att ha ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.minimum.toString()} ${G.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${W.origin??"v\xE4rdet"} att ha ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${X.prefix}"`;if(X.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${X.suffix}"`;if(X.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${X.includes}"`;if(X.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${X.pattern}"`;return`Ogiltig(t) ${J[X.format]??W.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${W.divisor}`;case"unrecognized_keys":return`${W.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${b(W.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${W.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${W.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var kK=x(()=>{e()});function Oj(){return{localeError:rx()}}var rx=()=>{let $={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function _(W){return $[W]??null}let J={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},U={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${W.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Y}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${X}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${I(W.values[0])}`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${b(W.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${X}${W.maximum.toString()} ${G.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${X}${W.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin} ${X}${W.minimum.toString()} ${G.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${W.origin} ${X}${W.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${X.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(X.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${X.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${W.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${W.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${W.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}};var IK=x(()=>{e()});function Lj(){return{localeError:px()}}var px=()=>{let $={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function _(W){return $[W]??null}let J={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},U={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${W.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${Y}`;return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${X} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${I(W.values[0])}`;return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",G=_(W.origin);if(G)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.maximum.toString()} ${G.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",G=_(W.origin);if(G)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.minimum.toString()} ${G.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${W.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${X} ${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${X.prefix}"`;if(X.format==="ends_with")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${X.suffix}"`;if(X.format==="includes")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${X.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(X.format==="regex")return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${X.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${J[X.format]??W.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${W.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${b(W.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${W.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${W.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var fK=x(()=>{e()});function Bj(){return{localeError:ox()}}var ox=()=>{let $={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function _(W){return $[W]??null}let J={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\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${W.expected}, al\u0131nan ${Y}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${X}, al\u0131nan ${Y}`}case"invalid_value":if(W.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${I(W.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\xC7ok b\xFCy\xFCk: beklenen ${W.origin??"de\u011Fer"} ${X}${W.maximum.toString()} ${G.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${W.origin??"de\u011Fer"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Ge\xE7ersiz metin: "${X.prefix}" ile ba\u015Flamal\u0131`;if(X.format==="ends_with")return`Ge\xE7ersiz metin: "${X.suffix}" ile bitmeli`;if(X.format==="includes")return`Ge\xE7ersiz metin: "${X.includes}" i\xE7ermeli`;if(X.format==="regex")return`Ge\xE7ersiz metin: ${X.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${J[X.format]??W.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${W.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${W.keys.length>1?"lar":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${W.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var CK=x(()=>{e()});function pU(){return{localeError:tx()}}var tx=()=>{let $={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function _(W){return $[W]??null}let J={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},U={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${W.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${Y}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${X}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${Y}`}case"invalid_value":if(W.values.length===1)return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${I(W.values[0])}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${W.origin} \u0431\u0443\u0434\u0435 ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${X.prefix}"`;if(X.format==="ends_with")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${X.suffix}"`;if(X.format==="includes")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${X.includes}"`;if(X.format==="regex")return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${X.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${W.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${W.keys.length>1?"\u0456":""}: ${b(W.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${W.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${W.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}};var Hj=x(()=>{e()});function Nj(){return pU()}var PK=x(()=>{Hj()});function Vj(){return{localeError:ax()}}var ax=()=>{let $={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function _(W){return $[W]??null}let J={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},U={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${W.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${Y} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${X} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${Y} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(W.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${I(W.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${b(W.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${W.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${X}${W.maximum.toString()} ${G.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${W.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${X}${W.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${W.origin} \u06A9\u06D2 ${X}${W.minimum.toString()} ${G.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${W.origin} \u06A9\u0627 ${X}${W.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${X.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(X.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${X.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${W.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${W.keys.length>1?"\u0632":""}: ${b(W.keys,"\u060C ")}`;case"invalid_key":return`${W.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${W.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var TK=x(()=>{e()});function Rj(){return{localeError:sx()}}var sx=()=>{let $={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"},map:{unit:"yozuv",verb:"bo\u2018lishi kerak"}};function _(W){return $[W]??null}let J={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"},U={nan:"NaN",number:"raqam",array:"massiv"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${W.expected}, qabul qilingan ${Y}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${X}, qabul qilingan ${Y}`}case"invalid_value":if(W.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${I(W.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Juda katta: kutilgan ${W.origin??"qiymat"} ${X}${W.maximum.toString()} ${G.unit} ${G.verb}`;return`Juda katta: kutilgan ${W.origin??"qiymat"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Juda kichik: kutilgan ${W.origin} ${X}${W.minimum.toString()} ${G.unit} ${G.verb}`;return`Juda kichik: kutilgan ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${X.prefix}" bilan boshlanishi kerak`;if(X.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${X.suffix}" bilan tugashi kerak`;if(X.format==="includes")return`Noto\u2018g\u2018ri satr: "${X.includes}" ni o\u2018z ichiga olishi kerak`;if(X.format==="regex")return`Noto\u2018g\u2018ri satr: ${X.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${J[X.format]??W.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${W.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${W.keys.length>1?"lar":""}: ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${W.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var SK=x(()=>{e()});function Kj(){return{localeError:ex()}}var ex=()=>{let $={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function _(W){return $[W]??null}let J={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 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\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},U={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${W.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${Y}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${X}, nh\u1EADn \u0111\u01B0\u1EE3c ${Y}`}case"invalid_value":if(W.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${I(W.values[0])}`;return`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${W.origin??"gi\xE1 tr\u1ECB"} ${G.verb} ${X}${W.maximum.toString()} ${G.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${W.origin??"gi\xE1 tr\u1ECB"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${W.origin} ${G.verb} ${X}${W.minimum.toString()} ${G.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${X.prefix}"`;if(X.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${X.suffix}"`;if(X.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${X.includes}"`;if(X.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${X.pattern}`;return`${J[X.format]??W.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${W.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${b(W.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${W.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${W.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var ZK=x(()=>{e()});function Fj(){return{localeError:$u()}}var $u=()=>{let $={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function _(W){return $[W]??null}let J={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},U={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${W.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${Y}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${X}\uFF0C\u5B9E\u9645\u63A5\u6536 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${I(W.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${W.origin??"\u503C"} ${X}${W.maximum.toString()} ${G.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${W.origin??"\u503C"} ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${W.origin} ${X}${W.minimum.toString()} ${G.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${W.origin} ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${X.prefix}" \u5F00\u5934`;if(X.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${X.suffix}" \u7ED3\u5C3E`;if(X.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${X.includes}"`;if(X.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${X.pattern}`;return`\u65E0\u6548${J[X.format]??W.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${W.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${b(W.keys,", ")}`;case"invalid_key":return`${W.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${W.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var vK=x(()=>{e()});function Ej(){return{localeError:_u()}}var _u=()=>{let $={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function _(W){return $[W]??null}let J={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",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 \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},U={nan:"NaN"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${W.expected}\uFF0C\u4F46\u6536\u5230 ${Y}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${X}\uFF0C\u4F46\u6536\u5230 ${Y}`}case"invalid_value":if(W.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${I(W.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${W.origin??"\u503C"} \u61C9\u70BA ${X}${W.maximum.toString()} ${G.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${W.origin??"\u503C"} \u61C9\u70BA ${X}${W.maximum.toString()}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${W.origin} \u61C9\u70BA ${X}${W.minimum.toString()} ${G.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${W.origin} \u61C9\u70BA ${X}${W.minimum.toString()}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${X.prefix}" \u958B\u982D`;if(X.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${X.suffix}" \u7D50\u5C3E`;if(X.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${X.includes}"`;if(X.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${X.pattern}`;return`\u7121\u6548\u7684 ${J[X.format]??W.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${W.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${W.keys.length>1?"\u5011":""}\uFF1A${b(W.keys,"\u3001")}`;case"invalid_key":return`${W.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${W.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var yK=x(()=>{e()});function Mj(){return{localeError:Ju()}}var Ju=()=>{let $={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function _(W){return $[W]??null}let J={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",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:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},U={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(W)=>{switch(W.code){case"invalid_type":{let X=U[W.expected]??W.expected,G=f(W.input),Y=U[G]??G;if(/^[A-Z]/.test(W.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${W.expected}, \xE0m\u1ECD\u0300 a r\xED ${Y}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${X}, \xE0m\u1ECD\u0300 a r\xED ${Y}`}case"invalid_value":if(W.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${I(W.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${b(W.values,"|")}`;case"too_big":{let X=W.inclusive?"<=":"<",G=_(W.origin);if(G)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${W.origin??"iye"} ${G.verb} ${X}${W.maximum} ${G.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${X}${W.maximum}`}case"too_small":{let X=W.inclusive?">=":">",G=_(W.origin);if(G)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${W.origin} ${G.verb} ${X}${W.minimum} ${G.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${X}${W.minimum}`}case"invalid_format":{let X=W;if(X.format==="starts_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${X.prefix}"`;if(X.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${X.suffix}"`;if(X.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${X.includes}"`;if(X.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${X.pattern}`;return`A\u1E63\xEC\u1E63e: ${J[X.format]??W.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${W.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${b(W.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${W.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${W.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var hK=x(()=>{e()});var $W={};e6($W,{zhTW:()=>Ej,zhCN:()=>Fj,yo:()=>Mj,vi:()=>Kj,uz:()=>Rj,ur:()=>Vj,uk:()=>pU,ua:()=>Nj,tr:()=>Bj,th:()=>Lj,ta:()=>Oj,sv:()=>Dj,sl:()=>jj,ru:()=>zj,ro:()=>qj,pt:()=>Qj,ps:()=>Gj,pl:()=>Yj,ota:()=>Xj,no:()=>Uj,nl:()=>Wj,ms:()=>Jj,mk:()=>_j,lt:()=>$j,ko:()=>ez,km:()=>lU,kh:()=>sz,ka:()=>tz,ja:()=>oz,it:()=>pz,is:()=>rz,id:()=>lz,hy:()=>iz,hu:()=>cz,hr:()=>nz,he:()=>dz,frCA:()=>uz,fr:()=>xz,fi:()=>mz,fa:()=>hz,es:()=>yz,eo:()=>vz,en:()=>iU,el:()=>Sz,de:()=>Tz,da:()=>Pz,cs:()=>Cz,ca:()=>fz,bg:()=>Iz,be:()=>kz,az:()=>gz,ar:()=>wz});var Aj=x(()=>{xR();uR();nR();cR();iR();lR();rR();pR();oR();Zz();tR();aR();sR();eR();$K();_K();JK();WK();UK();GK();YK();QK();qK();zK();jK();DK();az();OK();BK();HK();NK();VK();RK();KK();FK();EK();MK();AK();wK();gK();kK();IK();fK();CK();PK();Hj();TK();SK();ZK();vK();yK();hK()});class bj{constructor(){this._map=new WeakMap,this._idmap=new Map}add($,..._){let J=_[0];if(this._map.set($,J),J&&typeof J==="object"&&"id"in J)this._idmap.set(J.id,$);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove($){let _=this._map.get($);if(_&&typeof _==="object"&&"id"in _)this._idmap.delete(_.id);return this._map.delete($),this}get($){let _=$._zod.parent;if(_){let J={...this.get(_)??{}};delete J.id;let U={...J,...this._map.get($)};return Object.keys(U).length?U:void 0}return this._map.get($)}has($){return this._map.has($)}}function oU(){return new bj}var mK,c8,i8,g_;var tU=x(()=>{c8=Symbol("ZodOutput"),i8=Symbol("ZodInput");(mK=globalThis).__zod_globalRegistry??(mK.__zod_globalRegistry=oU());g_=globalThis.__zod_globalRegistry});function wj($,_){return new $({type:"string",...y(_)})}function gj($,_){return new $({type:"string",coerce:!0,...y(_)})}function l8($,_){return new $({type:"string",format:"email",check:"string_format",abort:!1,...y(_)})}function aU($,_){return new $({type:"string",format:"guid",check:"string_format",abort:!1,...y(_)})}function r8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,...y(_)})}function p8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...y(_)})}function o8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...y(_)})}function t8($,_){return new $({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...y(_)})}function sU($,_){return new $({type:"string",format:"url",check:"string_format",abort:!1,...y(_)})}function a8($,_){return new $({type:"string",format:"emoji",check:"string_format",abort:!1,...y(_)})}function s8($,_){return new $({type:"string",format:"nanoid",check:"string_format",abort:!1,...y(_)})}function e8($,_){return new $({type:"string",format:"cuid",check:"string_format",abort:!1,...y(_)})}function $5($,_){return new $({type:"string",format:"cuid2",check:"string_format",abort:!1,...y(_)})}function _5($,_){return new $({type:"string",format:"ulid",check:"string_format",abort:!1,...y(_)})}function J5($,_){return new $({type:"string",format:"xid",check:"string_format",abort:!1,...y(_)})}function W5($,_){return new $({type:"string",format:"ksuid",check:"string_format",abort:!1,...y(_)})}function U5($,_){return new $({type:"string",format:"ipv4",check:"string_format",abort:!1,...y(_)})}function X5($,_){return new $({type:"string",format:"ipv6",check:"string_format",abort:!1,...y(_)})}function kj($,_){return new $({type:"string",format:"mac",check:"string_format",abort:!1,...y(_)})}function G5($,_){return new $({type:"string",format:"cidrv4",check:"string_format",abort:!1,...y(_)})}function Y5($,_){return new $({type:"string",format:"cidrv6",check:"string_format",abort:!1,...y(_)})}function Q5($,_){return new $({type:"string",format:"base64",check:"string_format",abort:!1,...y(_)})}function q5($,_){return new $({type:"string",format:"base64url",check:"string_format",abort:!1,...y(_)})}function z5($,_){return new $({type:"string",format:"e164",check:"string_format",abort:!1,...y(_)})}function j5($,_){return new $({type:"string",format:"jwt",check:"string_format",abort:!1,...y(_)})}function Ij($,_){return new $({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...y(_)})}function fj($,_){return new $({type:"string",format:"date",check:"string_format",...y(_)})}function Cj($,_){return new $({type:"string",format:"time",check:"string_format",precision:null,...y(_)})}function Pj($,_){return new $({type:"string",format:"duration",check:"string_format",...y(_)})}function Tj($,_){return new $({type:"number",checks:[],...y(_)})}function Sj($,_){return new $({type:"number",coerce:!0,checks:[],...y(_)})}function Zj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"safeint",...y(_)})}function vj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"float32",...y(_)})}function yj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"float64",...y(_)})}function hj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"int32",...y(_)})}function mj($,_){return new $({type:"number",check:"number_format",abort:!1,format:"uint32",...y(_)})}function xj($,_){return new $({type:"boolean",...y(_)})}function uj($,_){return new $({type:"boolean",coerce:!0,...y(_)})}function dj($,_){return new $({type:"bigint",...y(_)})}function nj($,_){return new $({type:"bigint",coerce:!0,...y(_)})}function cj($,_){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...y(_)})}function ij($,_){return new $({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...y(_)})}function lj($,_){return new $({type:"symbol",...y(_)})}function rj($,_){return new $({type:"undefined",...y(_)})}function pj($,_){return new $({type:"null",...y(_)})}function oj($){return new $({type:"any"})}function tj($){return new $({type:"unknown"})}function aj($,_){return new $({type:"never",...y(_)})}function sj($,_){return new $({type:"void",...y(_)})}function ej($,_){return new $({type:"date",...y(_)})}function $D($,_){return new $({type:"date",coerce:!0,...y(_)})}function _D($,_){return new $({type:"nan",...y(_)})}function m6($,_){return new C8({check:"less_than",...y(_),value:$,inclusive:!1})}function a_($,_){return new C8({check:"less_than",...y(_),value:$,inclusive:!0})}function x6($,_){return new P8({check:"greater_than",...y(_),value:$,inclusive:!1})}function S_($,_){return new P8({check:"greater_than",...y(_),value:$,inclusive:!0})}function eU($){return x6(0,$)}function $X($){return m6(0,$)}function _X($){return a_(0,$)}function JX($){return S_(0,$)}function l4($,_){return new oq({check:"multiple_of",...y(_),value:$})}function r4($,_){return new sq({check:"max_size",...y(_),maximum:$})}function u6($,_){return new eq({check:"min_size",...y(_),minimum:$})}function P0($,_){return new $7({check:"size_equals",...y(_),size:$})}function T0($,_){return new _7({check:"max_length",...y(_),maximum:$})}function L4($,_){return new J7({check:"min_length",...y(_),minimum:$})}function S0($,_){return new W7({check:"length_equals",...y(_),length:$})}function m1($,_){return new U7({check:"string_format",format:"regex",...y(_),pattern:$})}function x1($){return new X7({check:"string_format",format:"lowercase",...y($)})}function u1($){return new G7({check:"string_format",format:"uppercase",...y($)})}function d1($,_){return new Y7({check:"string_format",format:"includes",...y(_),includes:$})}function n1($,_){return new Q7({check:"string_format",format:"starts_with",...y(_),prefix:$})}function c1($,_){return new q7({check:"string_format",format:"ends_with",...y(_),suffix:$})}function WX($,_,J){return new z7({check:"property",property:$,schema:_,...y(J)})}function i1($,_){return new j7({check:"mime_type",mime:$,...y(_)})}function R6($){return new D7({check:"overwrite",tx:$})}function l1($){return R6((_)=>_.normalize($))}function r1(){return R6(($)=>$.trim())}function p1(){return R6(($)=>$.toLowerCase())}function o1(){return R6(($)=>$.toUpperCase())}function t1(){return R6(($)=>Qq($))}function JD($,_,J){return new $({type:"array",element:_,...y(J)})}function Uu($,_,J){return new $({type:"union",options:_,...y(J)})}function Xu($,_,J){return new $({type:"union",options:_,inclusive:!1,...y(J)})}function Gu($,_,J,U){return new $({type:"union",options:J,discriminator:_,...y(U)})}function Yu($,_,J){return new $({type:"intersection",left:_,right:J})}function Qu($,_,J,U){let W=J instanceof R$;return new $({type:"tuple",items:_,rest:W?J:null,...y(W?U:J)})}function qu($,_,J,U){return new $({type:"record",keyType:_,valueType:J,...y(U)})}function zu($,_,J,U){return new $({type:"map",keyType:_,valueType:J,...y(U)})}function ju($,_,J){return new $({type:"set",valueType:_,...y(J)})}function Du($,_,J){let U=Array.isArray(_)?Object.fromEntries(_.map((W)=>[W,W])):_;return new $({type:"enum",entries:U,...y(J)})}function Ou($,_,J){return new $({type:"enum",entries:_,...y(J)})}function Lu($,_,J){return new $({type:"literal",values:Array.isArray(_)?_:[_],...y(J)})}function WD($,_){return new $({type:"file",...y(_)})}function Bu($,_){return new $({type:"transform",transform:_})}function Hu($,_){return new $({type:"optional",innerType:_})}function Nu($,_){return new $({type:"nullable",innerType:_})}function Vu($,_,J){return new $({type:"default",innerType:_,get defaultValue(){return typeof J==="function"?J():zq(J)}})}function Ru($,_,J){return new $({type:"nonoptional",innerType:_,...y(J)})}function Ku($,_){return new $({type:"success",innerType:_})}function Fu($,_,J){return new $({type:"catch",innerType:_,catchValue:typeof J==="function"?J:()=>J})}function Eu($,_,J){return new $({type:"pipe",in:_,out:J})}function Mu($,_){return new $({type:"readonly",innerType:_})}function Au($,_,J){return new $({type:"template_literal",parts:_,...y(J)})}function bu($,_){return new $({type:"lazy",getter:_})}function wu($,_){return new $({type:"promise",innerType:_})}function UD($,_,J){let U=y(J);return U.abort??(U.abort=!0),new $({type:"custom",check:"custom",fn:_,...U})}function XD($,_,J){return new $({type:"custom",check:"custom",fn:_,...y(J)})}function GD($,_){let J=xK((U)=>{return U.addIssue=(W)=>{if(typeof W==="string")U.issues.push(iJ(W,U.value,J._zod.def));else{let X=W;if(X.fatal)X.continue=!1;X.code??(X.code="custom"),X.input??(X.input=U.value),X.inst??(X.inst=J),X.continue??(X.continue=!J._zod.def.abort),U.issues.push(iJ(X))}},$(U.value,U)},_);return J}function xK($,_){let J=new X_({check:"custom",...y(_)});return J._zod.check=$,J}function YD($){let _=new X_({check:"describe"});return _._zod.onattach=[(J)=>{let U=g_.get(J)??{};g_.add(J,{...U,description:$})}],_._zod.check=()=>{},_}function QD($){let _=new X_({check:"meta"});return _._zod.onattach=[(J)=>{let U=g_.get(J)??{};g_.add(J,{...U,...$})}],_._zod.check=()=>{},_}function qD($,_){let J=y(_),U=J.truthy??["true","1","yes","on","y","enabled"],W=J.falsy??["false","0","no","off","n","disabled"];if(J.case!=="sensitive")U=U.map((B)=>typeof B==="string"?B.toLowerCase():B),W=W.map((B)=>typeof B==="string"?B.toLowerCase():B);let X=new Set(U),G=new Set(W),Y=$.Codec??cU,Q=$.Boolean??dU,L=new($.String??h1)({type:"string",error:J.error}),N=new Q({type:"boolean",error:J.error}),R=new Y({type:"pipe",in:L,out:N,transform:(B,H)=>{let V=B;if(J.case!=="sensitive")V=V.toLowerCase();if(X.has(V))return!0;else if(G.has(V))return!1;else return H.issues.push({code:"invalid_value",expected:"stringbool",values:[...X,...G],input:H.value,inst:R,continue:!1}),{}},reverseTransform:(B,H)=>{if(B===!0)return U[0]||"true";else return W[0]||"false"},error:J.error});return R}function _W($,_,J,U={}){let W=y(U),X={...y(U),check:"string_format",type:"string",format:_,fn:typeof J==="function"?J:(Y)=>J.test(Y),...W};if(J instanceof RegExp)X.pattern=J;return new $(X)}var D5;var uK=x(()=>{T8();tU();bz();e();D5={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function Z0($){let _=$?.target??"draft-2020-12";if(_==="draft-4")_="draft-04";if(_==="draft-7")_="draft-07";return{processors:$.processors??{},metadataRegistry:$?.metadata??g_,target:_,unrepresentable:$?.unrepresentable??"throw",override:$?.override??(()=>{}),io:$?.io??"output",counter:0,seen:new Map,cycles:$?.cycles??"ref",reused:$?.reused??"inline",external:$?.external??void 0}}function l$($,_,J={path:[],schemaPath:[]}){var U;let W=$._zod.def,X=_.seen.get($);if(X){if(X.count++,J.schemaPath.includes($))X.cycle=J.path;return X.schema}let G={schema:{},count:1,cycle:void 0,path:J.path};_.seen.set($,G);let Y=$._zod.toJSONSchema?.();if(Y)G.schema=Y;else{let L={...J,schemaPath:[...J.schemaPath,$],path:J.path};if($._zod.processJSONSchema)$._zod.processJSONSchema(_,G.schema,L);else{let R=G.schema,B=_.processors[W.type];if(!B)throw Error(`[toJSONSchema]: Non-representable type encountered: ${W.type}`);B($,_,R,L)}let N=$._zod.parent;if(N){if(!G.ref)G.ref=N;l$(N,_,L),_.seen.get(N).isParent=!0}}let Q=_.metadataRegistry.get($);if(Q)Object.assign(G.schema,Q);if(_.io==="input"&&c_($))delete G.schema.examples,delete G.schema.default;if(_.io==="input"&&"_prefault"in G.schema)(U=G.schema).default??(U.default=G.schema._prefault);return delete G.schema._prefault,_.seen.get($).schema}function v0($,_){let J=$.seen.get(_);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let U=new Map;for(let G of $.seen.entries()){let Y=$.metadataRegistry.get(G[0])?.id;if(Y){let Q=U.get(Y);if(Q&&Q!==G[0])throw Error(`Duplicate schema id "${Y}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);U.set(Y,G[0])}}let W=(G)=>{let Y=$.target==="draft-2020-12"?"$defs":"definitions";if($.external){let N=$.external.registry.get(G[0])?.id,R=$.external.uri??((H)=>H);if(N)return{ref:R(N)};let B=G[1].defId??G[1].schema.id??`schema${$.counter++}`;return G[1].defId=B,{defId:B,ref:`${R("__shared")}#/${Y}/${B}`}}if(G[1]===J)return{ref:"#"};let q=`${"#"}/${Y}/`,L=G[1].schema.id??`__schema${$.counter++}`;return{defId:L,ref:q+L}},X=(G)=>{if(G[1].schema.$ref)return;let Y=G[1],{ref:Q,defId:q}=W(G);if(Y.def={...Y.schema},q)Y.defId=q;let L=Y.schema;for(let N in L)delete L[N];L.$ref=Q};if($.cycles==="throw")for(let G of $.seen.entries()){let Y=G[1];if(Y.cycle)throw Error(`Cycle detected: #/${Y.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let G of $.seen.entries()){let Q=G[1];if(_===G[0]){X(G);continue}if($.external){let q=$.external.registry.get(G[0])?.id;if(_!==G[0]&&q){X(G);continue}}if($.metadataRegistry.get(G[0])?.id){X(G);continue}if(Q.cycle){X(G);continue}if(Q.count>1){if($.reused==="ref"){X(G);continue}}}}function Z1($,_){let J=$.seen.get(_);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(Q)=>{let Y=$.seen.get(Q);if(Y.ref===null)return;let q=Y.def??Y.schema,L={...q},N=Y.ref;if(Y.ref=null,N){U(N);let B=$.seen.get(N),H=B.schema;if(H.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))q.allOf=q.allOf??[],q.allOf.push(H);else Object.assign(q,H);if(Object.assign(q,L),Q._zod.parent===N)for(let R in q){if(R==="$ref"||R==="allOf")continue;if(!(R in L))delete q[R]}if(H.$ref&&B.def)for(let R in q){if(R==="$ref"||R==="allOf")continue;if(R in B.def&&JSON.stringify(q[R])===JSON.stringify(B.def[R]))delete q[R]}}let F=Q._zod.parent;if(F&&F!==N){U(F);let B=$.seen.get(F);if(B?.schema.$ref){if(q.$ref=B.schema.$ref,B.def)for(let H in q){if(H==="$ref"||H==="allOf")continue;if(H in B.def&&JSON.stringify(q[H])===JSON.stringify(B.def[H]))delete q[H]}}}$.override({zodSchema:Q,jsonSchema:q,path:Y.path??[]})};for(let Q of[...$.seen.entries()].reverse())U(Q[0]);let W={};if($.target==="draft-2020-12")W.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")W.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let Q=$.external.registry.get(_)?.id;if(!Q)throw Error("Schema is missing an `id` property");W.$id=$.external.uri(Q)}Object.assign(W,J.def??J.schema);let X=$.metadataRegistry.get(_)?.id;if(X!==void 0&&W.id===X)delete W.id;let G=$.external?.defs??{};for(let Q of $.seen.entries()){let Y=Q[1];if(Y.def&&Y.defId){if(Y.def.id===Y.defId)delete Y.def.id;G[Y.defId]=Y.def}}if($.external);else if(Object.keys(G).length>0)if($.target==="draft-2020-12")W.$defs=G;else W.definitions=G;try{let Q=JSON.parse(JSON.stringify(W));return Object.defineProperty(Q,"~standard",{value:{..._["~standard"],jsonSchema:{input:aJ(_,"input",$.processors),output:aJ(_,"output",$.processors)}},enumerable:!1,writable:!1}),Q}catch(Q){throw Error("Error converting schema to JSON.")}}function c6($,_){let J=_??{seen:new Set};if(J.seen.has($))return!1;J.seen.add($);let U=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return c6(U.element,J);if(U.type==="set")return c6(U.valueType,J);if(U.type==="lazy")return c6(U.getter(),J);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return c6(U.innerType,J);if(U.type==="intersection")return c6(U.left,J)||c6(U.right,J);if(U.type==="record"||U.type==="map")return c6(U.keyType,J)||c6(U.valueType,J);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return c6(U.in,J)||c6(U.out,J)}if(U.type==="object"){for(let W in U.shape)if(c6(U.shape[W],J))return!0;return!1}if(U.type==="union"){for(let W of U.options)if(c6(W,J))return!0;return!1}if(U.type==="tuple"){for(let W of U.items)if(c6(W,J))return!0;if(U.rest&&c6(U.rest,J))return!0;return!1}return!1}var WO=($,_={})=>(J)=>{let U=T1({...J,processors:_});return i$($,U),S1(U,$),Z1(U,$)},aJ=($,_,J={})=>(U)=>{let{libraryOptions:W,target:X}=U??{},G=T1({...W??{},target:X,io:_,processors:J});return i$($,G),S1(G,$),Z1(G,$)};var eU=m(()=>{nU()});function $X($,_){if("_idmap"in $){let U=$,W=T1({..._,processors:YG}),X={};for(let Y of U._idmap.entries()){let[q,L]=Y;i$(L,W)}let G={},Q={registry:U,uri:_?.uri,defs:X};W.external=Q;for(let Y of U._idmap.entries()){let[q,L]=Y;S1(W,L),G[q]=Z1(W,L)}if(Object.keys(X).length>0){let Y=W.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[Y]:X}}return{schemas:G}}let J=T1({..._,processors:YG});return i$($,J),S1(J,$),Z1(J,$)}var Wu,UO=($,_,J,U)=>{let W=J;W.type="string";let{minimum:X,maximum:G,format:Q,patterns:Y,contentEncoding:q}=$._zod.bag;if(typeof X==="number")W.minLength=X;if(typeof G==="number")W.maxLength=G;if(Q){if(W.format=Wu[Q]??Q,W.format==="")delete W.format;if(Q==="time")delete W.format}if(q)W.contentEncoding=q;if(Y&&Y.size>0){let L=[...Y];if(L.length===1)W.pattern=L[0].source;else if(L.length>1)W.allOf=[...L.map((N)=>({..._.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"?{type:"string"}:{},pattern:N.source}))]}},XO=($,_,J,U)=>{let W=J,{minimum:X,maximum:G,format:Q,multipleOf:Y,exclusiveMaximum:q,exclusiveMinimum:L}=$._zod.bag;if(typeof Q==="string"&&Q.includes("int"))W.type="integer";else W.type="number";let N=typeof L==="number"&&L>=(X??Number.NEGATIVE_INFINITY),F=typeof q==="number"&&q<=(G??Number.POSITIVE_INFINITY),B=_.target==="draft-04"||_.target==="openapi-3.0";if(N)if(B)W.minimum=L,W.exclusiveMinimum=!0;else W.exclusiveMinimum=L;else if(typeof X==="number")W.minimum=X;if(F)if(B)W.maximum=q,W.exclusiveMaximum=!0;else W.exclusiveMaximum=q;else if(typeof G==="number")W.maximum=G;if(typeof Y==="number")W.multipleOf=Y},GO=($,_,J,U)=>{J.type="boolean"},QO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},YO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},qO=($,_,J,U)=>{if(_.target==="openapi-3.0")J.type="string",J.nullable=!0,J.enum=[null];else J.type="null"},zO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},jO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},OO=($,_,J,U)=>{J.not={}},DO=($,_,J,U)=>{},LO=($,_,J,U)=>{},BO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},HO=($,_,J,U)=>{let W=$._zod.def,X=gU(W.entries);if(X.every((G)=>typeof G==="number"))J.type="number";if(X.every((G)=>typeof G==="string"))J.type="string";J.enum=X},NO=($,_,J,U)=>{let W=$._zod.def,X=[];for(let G of W.values)if(G===void 0){if(_.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof G==="bigint")if(_.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else X.push(Number(G));else X.push(G);if(X.length===0);else if(X.length===1){let G=X[0];if(J.type=G===null?"null":typeof G,_.target==="draft-04"||_.target==="openapi-3.0")J.enum=[G];else J.const=G}else{if(X.every((G)=>typeof G==="number"))J.type="number";if(X.every((G)=>typeof G==="string"))J.type="string";if(X.every((G)=>typeof G==="boolean"))J.type="boolean";if(X.every((G)=>G===null))J.type="null";J.enum=X}},VO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},FO=($,_,J,U)=>{let W=J,X=$._zod.pattern;if(!X)throw Error("Pattern not found in template literal");W.type="string",W.pattern=X.source},RO=($,_,J,U)=>{let W=J,X={type:"string",format:"binary",contentEncoding:"binary"},{minimum:G,maximum:Q,mime:Y}=$._zod.bag;if(G!==void 0)X.minLength=G;if(Q!==void 0)X.maxLength=Q;if(Y)if(Y.length===1)X.contentMediaType=Y[0],Object.assign(W,X);else Object.assign(W,X),W.anyOf=Y.map((q)=>({contentMediaType:q}));else Object.assign(W,X)},KO=($,_,J,U)=>{J.type="boolean"},MO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},AO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},bO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},EO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},wO=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},IO=($,_,J,U)=>{let W=J,X=$._zod.def,{minimum:G,maximum:Q}=$._zod.bag;if(typeof G==="number")W.minItems=G;if(typeof Q==="number")W.maxItems=Q;W.type="array",W.items=i$(X.element,_,{...U,path:[...U.path,"items"]})},gO=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="object",W.properties={};let G=X.shape;for(let q in G)W.properties[q]=i$(G[q],_,{...U,path:[...U.path,"properties",q]});let Q=new Set(Object.keys(G)),Y=new Set([...Q].filter((q)=>{let L=X.shape[q]._zod;if(_.io==="input")return L.optin===void 0;else return L.optout===void 0}));if(Y.size>0)W.required=Array.from(Y);if(X.catchall?._zod.def.type==="never")W.additionalProperties=!1;else if(!X.catchall){if(_.io==="output")W.additionalProperties=!1}else if(X.catchall)W.additionalProperties=i$(X.catchall,_,{...U,path:[...U.path,"additionalProperties"]})},qG=($,_,J,U)=>{let W=$._zod.def,X=W.inclusive===!1,G=W.options.map((Q,Y)=>i$(Q,_,{...U,path:[...U.path,X?"oneOf":"anyOf",Y]}));if(X)J.oneOf=G;else J.anyOf=G},kO=($,_,J,U)=>{let W=$._zod.def,X=i$(W.left,_,{...U,path:[...U.path,"allOf",0]}),G=i$(W.right,_,{...U,path:[...U.path,"allOf",1]}),Q=(q)=>("allOf"in q)&&Object.keys(q).length===1,Y=[...Q(X)?X.allOf:[X],...Q(G)?G.allOf:[G]];J.allOf=Y},fO=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="array";let G=_.target==="draft-2020-12"?"prefixItems":"items",Q=_.target==="draft-2020-12"?"items":_.target==="openapi-3.0"?"items":"additionalItems",Y=X.items.map((F,B)=>i$(F,_,{...U,path:[...U.path,G,B]})),q=X.rest?i$(X.rest,_,{...U,path:[...U.path,Q,..._.target==="openapi-3.0"?[X.items.length]:[]]}):null;if(_.target==="draft-2020-12"){if(W.prefixItems=Y,q)W.items=q}else if(_.target==="openapi-3.0"){if(W.items={anyOf:Y},q)W.items.anyOf.push(q);if(W.minItems=Y.length,!q)W.maxItems=Y.length}else if(W.items=Y,q)W.additionalItems=q;let{minimum:L,maximum:N}=$._zod.bag;if(typeof L==="number")W.minItems=L;if(typeof N==="number")W.maxItems=N},CO=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="object";let G=X.keyType,Y=G._zod.bag?.patterns;if(X.mode==="loose"&&Y&&Y.size>0){let L=i$(X.valueType,_,{...U,path:[...U.path,"patternProperties","*"]});W.patternProperties={};for(let N of Y)W.patternProperties[N.source]=L}else{if(_.target==="draft-07"||_.target==="draft-2020-12")W.propertyNames=i$(X.keyType,_,{...U,path:[...U.path,"propertyNames"]});W.additionalProperties=i$(X.valueType,_,{...U,path:[...U.path,"additionalProperties"]})}let q=G._zod.values;if(q){let L=[...q].filter((N)=>typeof N==="string"||typeof N==="number");if(L.length>0)W.required=L}},PO=($,_,J,U)=>{let W=$._zod.def,X=i$(W.innerType,_,U),G=_.seen.get($);if(_.target==="openapi-3.0")G.ref=W.innerType,J.nullable=!0;else J.anyOf=[X,{type:"null"}]},TO=($,_,J,U)=>{let W=$._zod.def;i$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},SO=($,_,J,U)=>{let W=$._zod.def;i$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType,J.default=JSON.parse(JSON.stringify(W.defaultValue))},ZO=($,_,J,U)=>{let W=$._zod.def;i$(W.innerType,_,U);let X=_.seen.get($);if(X.ref=W.innerType,_.io==="input")J._prefault=JSON.parse(JSON.stringify(W.defaultValue))},vO=($,_,J,U)=>{let W=$._zod.def;i$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType;let G;try{G=W.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}J.default=G},yO=($,_,J,U)=>{let W=$._zod.def,X=W.in._zod.traits.has("$ZodTransform"),G=_.io==="input"?X?W.out:W.in:W.out;i$(G,_,U);let Q=_.seen.get($);Q.ref=G},hO=($,_,J,U)=>{let W=$._zod.def;i$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType,J.readOnly=!0},mO=($,_,J,U)=>{let W=$._zod.def;i$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},zG=($,_,J,U)=>{let W=$._zod.def;i$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},xO=($,_,J,U)=>{let W=$._zod.innerType;i$(W,_,U);let X=_.seen.get($);X.ref=W},YG;var _X=m(()=>{eU();s();Wu={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},YG={string:UO,number:XO,boolean:GO,bigint:QO,symbol:YO,null:qO,undefined:zO,void:jO,never:OO,any:DO,unknown:LO,date:BO,enum:HO,literal:NO,nan:VO,template_literal:FO,file:RO,success:KO,custom:MO,function:AO,transform:bO,map:EO,set:wO,array:IO,object:gO,union:qG,intersection:kO,tuple:fO,record:CO,nullable:PO,nonoptional:TO,default:SO,prefault:ZO,catch:vO,pipe:yO,readonly:hO,promise:mO,optional:zG,lazy:xO}});class uO{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($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let _=$?.target??"draft-2020-12";if(_==="draft-4")_="draft-04";if(_==="draft-7")_="draft-07";this.ctx=T1({processors:YG,target:_,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,_={path:[],schemaPath:[]}){return i$($,this.ctx,_)}emit($,_){if(_){if(_.cycles)this.ctx.cycles=_.cycles;if(_.reused)this.ctx.reused=_.reused;if(_.external)this.ctx.external=_.external}S1(this.ctx,$);let J=Z1(this.ctx,$),{"~standard":U,...W}=J;return W}}var CR=m(()=>{_X();eU()});var PR={};var TR=()=>{};var L0={};s4(L0,{version:()=>Gq,util:()=>C,treeifyError:()=>O8,toJSONSchema:()=>$X,toDotPath:()=>WF,safeParseAsync:()=>j7,safeParse:()=>z7,safeEncodeAsync:()=>Gm,safeEncode:()=>Um,safeDecodeAsync:()=>Qm,safeDecode:()=>Xm,registry:()=>lU,regexes:()=>o6,process:()=>i$,prettifyError:()=>D8,parseAsync:()=>B8,parse:()=>L8,meta:()=>_O,locales:()=>oJ,isValidJWT:()=>EF,isValidBase64URL:()=>bF,isValidBase64:()=>kq,initializeContext:()=>T1,globalRegistry:()=>w6,globalConfig:()=>f2,formatError:()=>dJ,flattenError:()=>uJ,finalize:()=>Z1,extractDefs:()=>S1,encodeAsync:()=>Jm,encode:()=>$m,describe:()=>$O,decodeAsync:()=>Wm,decode:()=>_m,createToJSONSchemaMethod:()=>WO,createStandardJSONSchemaMethod:()=>aJ,config:()=>N6,clone:()=>P6,_xor:()=>Zx,_xid:()=>a8,_void:()=>nj,_uuidv7:()=>n8,_uuidv6:()=>l8,_uuidv4:()=>c8,_uuid:()=>d8,_url:()=>rU,_uppercase:()=>h2,_unknown:()=>cj,_union:()=>Sx,_undefined:()=>xj,_ulid:()=>t8,_uint64:()=>hj,_uint32:()=>Pj,_tuple:()=>hx,_trim:()=>l2,_transform:()=>nx,_toUpperCase:()=>i2,_toLowerCase:()=>n2,_templateLiteral:()=>$u,_symbol:()=>mj,_superRefine:()=>ej,_success:()=>tx,_stringbool:()=>JO,_stringFormat:()=>tJ,_string:()=>Fj,_startsWith:()=>x2,_slugify:()=>r2,_size:()=>f1,_set:()=>ux,_safeParseAsync:()=>iJ,_safeParse:()=>nJ,_safeEncodeAsync:()=>M8,_safeEncode:()=>R8,_safeDecodeAsync:()=>A8,_safeDecode:()=>K8,_regex:()=>v2,_refine:()=>sj,_record:()=>mx,_readonly:()=>ex,_property:()=>sU,_promise:()=>Ju,_positive:()=>pU,_pipe:()=>sx,_parseAsync:()=>lJ,_parse:()=>cJ,_overwrite:()=>V4,_optional:()=>ix,_number:()=>wj,_nullable:()=>rx,_null:()=>uj,_normalize:()=>c2,_nonpositive:()=>tU,_nonoptional:()=>ox,_nonnegative:()=>aU,_never:()=>lj,_negative:()=>oU,_nativeEnum:()=>cx,_nanoid:()=>r8,_nan:()=>pj,_multipleOf:()=>l0,_minSize:()=>u4,_minLength:()=>D0,_min:()=>T6,_mime:()=>d2,_maxSize:()=>n0,_maxLength:()=>C1,_max:()=>t6,_map:()=>xx,_mac:()=>Kj,_lte:()=>t6,_lt:()=>m4,_lowercase:()=>y2,_literal:()=>lx,_length:()=>P1,_lazy:()=>_u,_ksuid:()=>s8,_jwt:()=>GG,_isoTime:()=>bj,_isoDuration:()=>Ej,_isoDateTime:()=>Mj,_isoDate:()=>Aj,_ipv6:()=>$G,_ipv4:()=>e8,_intersection:()=>yx,_int64:()=>yj,_int32:()=>Cj,_int:()=>gj,_includes:()=>m2,_guid:()=>iU,_gte:()=>T6,_gt:()=>x4,_float64:()=>fj,_float32:()=>kj,_file:()=>tj,_enum:()=>dx,_endsWith:()=>u2,_encodeAsync:()=>V8,_encode:()=>H8,_emoji:()=>i8,_email:()=>u8,_e164:()=>XG,_discriminatedUnion:()=>vx,_default:()=>px,_decodeAsync:()=>F8,_decode:()=>N8,_date:()=>ij,_custom:()=>aj,_cuid2:()=>o8,_cuid:()=>p8,_coercedString:()=>Rj,_coercedNumber:()=>Ij,_coercedDate:()=>rj,_coercedBoolean:()=>Sj,_coercedBigint:()=>vj,_cidrv6:()=>JG,_cidrv4:()=>_G,_check:()=>kR,_catch:()=>ax,_boolean:()=>Tj,_bigint:()=>Zj,_base64url:()=>UG,_base64:()=>WG,_array:()=>oj,_any:()=>dj,TimePrecision:()=>QG,NEVER:()=>Y8,JSONSchemaGenerator:()=>uO,JSONSchema:()=>PR,Doc:()=>k8,$output:()=>m8,$input:()=>x8,$constructor:()=>A,$brand:()=>q8,$ZodXor:()=>rq,$ZodXID:()=>Vq,$ZodVoid:()=>cq,$ZodUnknown:()=>uq,$ZodUnion:()=>hU,$ZodUndefined:()=>hq,$ZodUUID:()=>zq,$ZodURL:()=>Oq,$ZodULID:()=>Nq,$ZodType:()=>F$,$ZodTuple:()=>v8,$ZodTransform:()=>Jz,$ZodTemplateLiteral:()=>Dz,$ZodSymbol:()=>yq,$ZodSuccess:()=>Yz,$ZodStringFormat:()=>_6,$ZodString:()=>Z2,$ZodSet:()=>sq,$ZodRegistry:()=>Vj,$ZodRecord:()=>tq,$ZodRealError:()=>p6,$ZodReadonly:()=>Oz,$ZodPromise:()=>Bz,$ZodPreprocess:()=>jz,$ZodPrefault:()=>Gz,$ZodPipe:()=>h8,$ZodOptional:()=>y8,$ZodObjectJIT:()=>iq,$ZodObject:()=>gF,$ZodNumberFormat:()=>Zq,$ZodNumber:()=>S8,$ZodNullable:()=>Uz,$ZodNull:()=>mq,$ZodNonOptional:()=>Qz,$ZodNever:()=>dq,$ZodNanoID:()=>Lq,$ZodNaN:()=>zz,$ZodMap:()=>aq,$ZodMAC:()=>wq,$ZodLiteral:()=>$z,$ZodLazy:()=>Hz,$ZodKSUID:()=>Fq,$ZodJWT:()=>Tq,$ZodIntersection:()=>oq,$ZodISOTime:()=>Mq,$ZodISODuration:()=>Aq,$ZodISODateTime:()=>Rq,$ZodISODate:()=>Kq,$ZodIPv6:()=>Eq,$ZodIPv4:()=>bq,$ZodGUID:()=>qq,$ZodFunction:()=>Lz,$ZodFile:()=>_z,$ZodExactOptional:()=>Wz,$ZodError:()=>TU,$ZodEnum:()=>eq,$ZodEncodeError:()=>C2,$ZodEmoji:()=>Dq,$ZodEmail:()=>jq,$ZodE164:()=>Pq,$ZodDiscriminatedUnion:()=>pq,$ZodDefault:()=>Xz,$ZodDate:()=>lq,$ZodCustomStringFormat:()=>Sq,$ZodCustom:()=>Nz,$ZodCodec:()=>mU,$ZodCheckUpperCase:()=>e7,$ZodCheckStringFormat:()=>rJ,$ZodCheckStartsWith:()=>_q,$ZodCheckSizeEquals:()=>r7,$ZodCheckRegex:()=>a7,$ZodCheckProperty:()=>Wq,$ZodCheckOverwrite:()=>Xq,$ZodCheckNumberFormat:()=>c7,$ZodCheckMultipleOf:()=>d7,$ZodCheckMinSize:()=>i7,$ZodCheckMinLength:()=>o7,$ZodCheckMimeType:()=>Uq,$ZodCheckMaxSize:()=>n7,$ZodCheckMaxLength:()=>p7,$ZodCheckLowerCase:()=>s7,$ZodCheckLessThan:()=>w8,$ZodCheckLengthEquals:()=>t7,$ZodCheckIncludes:()=>$q,$ZodCheckGreaterThan:()=>I8,$ZodCheckEndsWith:()=>Jq,$ZodCheckBigIntFormat:()=>l7,$ZodCheck:()=>W6,$ZodCatch:()=>qz,$ZodCUID2:()=>Hq,$ZodCUID:()=>Bq,$ZodCIDRv6:()=>gq,$ZodCIDRv4:()=>Iq,$ZodBoolean:()=>yU,$ZodBigIntFormat:()=>vq,$ZodBigInt:()=>Z8,$ZodBase64URL:()=>Cq,$ZodBase64:()=>fq,$ZodAsyncError:()=>O0,$ZodArray:()=>nq,$ZodAny:()=>xq});var G4=m(()=>{s();E8();Nj();_X();CR();TR();P2();O7();q7();Vz();g8();Qq();nU();fR();eU()});var jG={};s4(jG,{uppercase:()=>h2,trim:()=>l2,toUpperCase:()=>i2,toLowerCase:()=>n2,startsWith:()=>x2,slugify:()=>r2,size:()=>f1,regex:()=>v2,property:()=>sU,positive:()=>pU,overwrite:()=>V4,normalize:()=>c2,nonpositive:()=>tU,nonnegative:()=>aU,negative:()=>oU,multipleOf:()=>l0,minSize:()=>u4,minLength:()=>D0,mime:()=>d2,maxSize:()=>n0,maxLength:()=>C1,lte:()=>t6,lt:()=>m4,lowercase:()=>y2,length:()=>P1,includes:()=>m2,gte:()=>T6,gt:()=>x4,endsWith:()=>u2});var OG=m(()=>{G4()});var p2={};s4(p2,{time:()=>lO,duration:()=>nO,datetime:()=>dO,date:()=>cO,ZodISOTime:()=>UX,ZodISODuration:()=>XX,ZodISODateTime:()=>JX,ZodISODate:()=>WX});function dO($){return Mj(JX,$)}function cO($){return Aj(WX,$)}function lO($){return bj(UX,$)}function nO($){return Ej(XX,$)}var JX,WX,UX,XX;var GX=m(()=>{G4();YX();JX=A("ZodISODateTime",($,_)=>{Rq.init($,_),a$.init($,_)});WX=A("ZodISODate",($,_)=>{Kq.init($,_),a$.init($,_)});UX=A("ZodISOTime",($,_)=>{Mq.init($,_),a$.init($,_)});XX=A("ZodISODuration",($,_)=>{Aq.init($,_),a$.init($,_)})});var SR=($,_)=>{TU.init($,_),$.name="ZodError",Object.defineProperties($,{format:{value:(J)=>dJ($,J)},flatten:{value:(J)=>uJ($,J)},addIssue:{value:(J)=>{$.issues.push(J),$.message=JSON.stringify($.issues,hJ,2)}},addIssues:{value:(J)=>{$.issues.push(...J),$.message=JSON.stringify($.issues,hJ,2)}},isEmpty:{get(){return $.issues.length===0}}})},ZR,l6;var iO=m(()=>{G4();G4();s();ZR=A("ZodError",SR),l6=A("ZodError",SR,{Parent:Error})});var DG,LG,BG,HG,NG,VG,FG,RG,KG,MG,AG,bG;var rO=m(()=>{G4();iO();DG=cJ(l6),LG=lJ(l6),BG=nJ(l6),HG=iJ(l6),NG=H8(l6),VG=N8(l6),FG=V8(l6),RG=F8(l6),KG=R8(l6),MG=K8(l6),AG=M8(l6),bG=A8(l6)});var QX={};s4(QX,{xor:()=>hD,xid:()=>QD,void:()=>PD,uuidv7:()=>eO,uuidv6:()=>sO,uuidv4:()=>aO,uuid:()=>tO,url:()=>$D,unknown:()=>v1,union:()=>CX,undefined:()=>fD,ulid:()=>GD,uint64:()=>gD,uint32:()=>ED,tuple:()=>dG,transform:()=>TX,templateLiteral:()=>sD,symbol:()=>kD,superRefine:()=>H5,success:()=>pD,stringbool:()=>GL,stringFormat:()=>VD,string:()=>sJ,strictObject:()=>vD,set:()=>cD,refine:()=>B5,record:()=>cG,readonly:()=>q5,promise:()=>eD,preprocess:()=>YL,prefault:()=>_5,pipe:()=>zX,partialRecord:()=>xD,optional:()=>$W,object:()=>ZD,number:()=>wG,nullish:()=>rD,nullable:()=>_W,null:()=>CG,nonoptional:()=>J5,never:()=>fX,nativeEnum:()=>lD,nanoid:()=>WD,nan:()=>oD,meta:()=>UL,map:()=>dD,mac:()=>zD,looseRecord:()=>uD,looseObject:()=>yD,literal:()=>nD,lazy:()=>O5,ksuid:()=>YD,keyof:()=>SD,jwt:()=>ND,json:()=>QL,ipv6:()=>jD,ipv4:()=>qD,invertCodec:()=>aD,intersection:()=>xG,int64:()=>ID,int32:()=>bD,int:()=>qX,instanceof:()=>XL,httpUrl:()=>_D,hostname:()=>FD,hex:()=>RD,hash:()=>KD,guid:()=>oO,function:()=>$L,float64:()=>AD,float32:()=>MD,file:()=>iD,exactOptional:()=>tG,enum:()=>PX,emoji:()=>JD,email:()=>pO,e164:()=>HD,discriminatedUnion:()=>mD,describe:()=>WL,date:()=>TD,custom:()=>JL,cuid2:()=>XD,cuid:()=>UD,codec:()=>tD,cidrv6:()=>DD,cidrv4:()=>OD,check:()=>_L,catch:()=>X5,boolean:()=>IG,bigint:()=>wD,base64url:()=>BD,base64:()=>LD,array:()=>UW,any:()=>CD,_function:()=>$L,_default:()=>eG,_ZodString:()=>OX,ZodXor:()=>yG,ZodXID:()=>FX,ZodVoid:()=>ZG,ZodUnknown:()=>TG,ZodUnion:()=>GW,ZodUndefined:()=>kG,ZodUUID:()=>d4,ZodURL:()=>JW,ZodULID:()=>VX,ZodType:()=>K$,ZodTuple:()=>uG,ZodTransform:()=>pG,ZodTemplateLiteral:()=>z5,ZodSymbol:()=>gG,ZodSuccess:()=>W5,ZodStringFormat:()=>a$,ZodString:()=>a2,ZodSet:()=>nG,ZodRecord:()=>o2,ZodReadonly:()=>Y5,ZodPromise:()=>D5,ZodPreprocess:()=>Q5,ZodPrefault:()=>$5,ZodPipe:()=>QW,ZodOptional:()=>SX,ZodObject:()=>XW,ZodNumberFormat:()=>y1,ZodNumber:()=>e2,ZodNullable:()=>aG,ZodNull:()=>fG,ZodNonOptional:()=>ZX,ZodNever:()=>SG,ZodNanoID:()=>BX,ZodNaN:()=>G5,ZodMap:()=>lG,ZodMAC:()=>EG,ZodLiteral:()=>iG,ZodLazy:()=>j5,ZodKSUID:()=>RX,ZodJWT:()=>gX,ZodIntersection:()=>mG,ZodIPv6:()=>MX,ZodIPv4:()=>KX,ZodGUID:()=>eJ,ZodFunction:()=>L5,ZodFile:()=>rG,ZodExactOptional:()=>oG,ZodEnum:()=>t2,ZodEmoji:()=>LX,ZodEmail:()=>DX,ZodE164:()=>IX,ZodDiscriminatedUnion:()=>hG,ZodDefault:()=>sG,ZodDate:()=>WW,ZodCustomStringFormat:()=>s2,ZodCustom:()=>qW,ZodCodec:()=>YW,ZodCatch:()=>U5,ZodCUID2:()=>NX,ZodCUID:()=>HX,ZodCIDRv6:()=>bX,ZodCIDRv4:()=>AX,ZodBoolean:()=>$_,ZodBigIntFormat:()=>kX,ZodBigInt:()=>__,ZodBase64URL:()=>wX,ZodBase64:()=>EX,ZodArray:()=>vG,ZodAny:()=>PG});function jX($,_,J){let U=Object.getPrototypeOf($),W=vR.get(U);if(!W)W=new Set,vR.set(U,W);if(W.has(_))return;W.add(_);for(let X in J){let G=J[X];Object.defineProperty(U,X,{configurable:!0,enumerable:!1,get(){let Q=G.bind(this);return Object.defineProperty(this,X,{configurable:!0,writable:!0,enumerable:!0,value:Q}),Q},set(Q){Object.defineProperty(this,X,{configurable:!0,writable:!0,enumerable:!0,value:Q})}})}}function sJ($){return Fj(a2,$)}function pO($){return u8(DX,$)}function oO($){return iU(eJ,$)}function tO($){return d8(d4,$)}function aO($){return c8(d4,$)}function sO($){return l8(d4,$)}function eO($){return n8(d4,$)}function $D($){return rU(JW,$)}function _D($){return rU(JW,{protocol:o6.httpProtocol,hostname:o6.domain,...C.normalizeParams($)})}function JD($){return i8(LX,$)}function WD($){return r8(BX,$)}function UD($){return p8(HX,$)}function XD($){return o8(NX,$)}function GD($){return t8(VX,$)}function QD($){return a8(FX,$)}function YD($){return s8(RX,$)}function qD($){return e8(KX,$)}function zD($){return Kj(EG,$)}function jD($){return $G(MX,$)}function OD($){return _G(AX,$)}function DD($){return JG(bX,$)}function LD($){return WG(EX,$)}function BD($){return UG(wX,$)}function HD($){return XG(IX,$)}function ND($){return GG(gX,$)}function VD($,_,J={}){return tJ(s2,$,_,J)}function FD($){return tJ(s2,"hostname",o6.hostname,$)}function RD($){return tJ(s2,"hex",o6.hex,$)}function KD($,_){let J=_?.enc??"hex",U=`${$}_${J}`,W=o6[U];if(!W)throw Error(`Unrecognized hash format: ${U}`);return tJ(s2,U,W,_)}function wG($){return wj(e2,$)}function qX($){return gj(y1,$)}function MD($){return kj(y1,$)}function AD($){return fj(y1,$)}function bD($){return Cj(y1,$)}function ED($){return Pj(y1,$)}function IG($){return Tj($_,$)}function wD($){return Zj(__,$)}function ID($){return yj(kX,$)}function gD($){return hj(kX,$)}function kD($){return mj(gG,$)}function fD($){return xj(kG,$)}function CG($){return uj(fG,$)}function CD(){return dj(PG)}function v1(){return cj(TG)}function fX($){return lj(SG,$)}function PD($){return nj(ZG,$)}function TD($){return ij(WW,$)}function UW($,_){return oj(vG,$,_)}function SD($){let _=$._zod.def.shape;return PX(Object.keys(_))}function ZD($,_){let J={type:"object",shape:$??{},...C.normalizeParams(_)};return new XW(J)}function vD($,_){return new XW({type:"object",shape:$,catchall:fX(),...C.normalizeParams(_)})}function yD($,_){return new XW({type:"object",shape:$,catchall:v1(),...C.normalizeParams(_)})}function CX($,_){return new GW({type:"union",options:$,...C.normalizeParams(_)})}function hD($,_){return new yG({type:"union",options:$,inclusive:!1,...C.normalizeParams(_)})}function mD($,_,J){return new hG({type:"union",options:_,discriminator:$,...C.normalizeParams(J)})}function xG($,_){return new mG({type:"intersection",left:$,right:_})}function dG($,_,J){let U=_ instanceof F$,W=U?J:_;return new uG({type:"tuple",items:$,rest:U?_:null,...C.normalizeParams(W)})}function cG($,_,J){if(!_||!_._zod)return new o2({type:"record",keyType:sJ(),valueType:$,...C.normalizeParams(_)});return new o2({type:"record",keyType:$,valueType:_,...C.normalizeParams(J)})}function xD($,_,J){let U=P6($);return U._zod.values=void 0,new o2({type:"record",keyType:U,valueType:_,...C.normalizeParams(J)})}function uD($,_,J){return new o2({type:"record",keyType:$,valueType:_,mode:"loose",...C.normalizeParams(J)})}function dD($,_,J){return new lG({type:"map",keyType:$,valueType:_,...C.normalizeParams(J)})}function cD($,_){return new nG({type:"set",valueType:$,...C.normalizeParams(_)})}function PX($,_){let J=Array.isArray($)?Object.fromEntries($.map((U)=>[U,U])):$;return new t2({type:"enum",entries:J,...C.normalizeParams(_)})}function lD($,_){return new t2({type:"enum",entries:$,...C.normalizeParams(_)})}function nD($,_){return new iG({type:"literal",values:Array.isArray($)?$:[$],...C.normalizeParams(_)})}function iD($){return tj(rG,$)}function TX($){return new pG({type:"transform",transform:$})}function $W($){return new SX({type:"optional",innerType:$})}function tG($){return new oG({type:"optional",innerType:$})}function _W($){return new aG({type:"nullable",innerType:$})}function rD($){return $W(_W($))}function eG($,_){return new sG({type:"default",innerType:$,get defaultValue(){return typeof _==="function"?_():C.shallowClone(_)}})}function _5($,_){return new $5({type:"prefault",innerType:$,get defaultValue(){return typeof _==="function"?_():C.shallowClone(_)}})}function J5($,_){return new ZX({type:"nonoptional",innerType:$,...C.normalizeParams(_)})}function pD($){return new W5({type:"success",innerType:$})}function X5($,_){return new U5({type:"catch",innerType:$,catchValue:typeof _==="function"?_:()=>_})}function oD($){return pj(G5,$)}function zX($,_){return new QW({type:"pipe",in:$,out:_})}function tD($,_,J){return new YW({type:"pipe",in:$,out:_,transform:J.decode,reverseTransform:J.encode})}function aD($){let _=$._zod.def;return new YW({type:"pipe",in:_.out,out:_.in,transform:_.reverseTransform,reverseTransform:_.transform})}function q5($){return new Y5({type:"readonly",innerType:$})}function sD($,_){return new z5({type:"template_literal",parts:$,...C.normalizeParams(_)})}function O5($){return new j5({type:"lazy",getter:$})}function eD($){return new D5({type:"promise",innerType:$})}function $L($){return new L5({type:"function",input:Array.isArray($?.input)?dG($?.input):$?.input??UW(v1()),output:$?.output??v1()})}function _L($){let _=new W6({check:"custom"});return _._zod.check=$,_}function JL($,_){return aj(qW,$??(()=>!0),_)}function B5($,_={}){return sj(qW,$,_)}function H5($,_){return ej($,_)}function XL($,_={}){let J=new qW({type:"custom",check:"custom",fn:(U)=>U instanceof $,abort:!0,...C.normalizeParams(_)});return J._zod.bag.Class=$,J._zod.check=(U)=>{if(!(U.value instanceof $))U.issues.push({code:"invalid_type",expected:$.name,input:U.value,inst:J,path:[...J._zod.def.path??[]]})},J}function QL($){let _=O5(()=>{return CX([sJ($),wG(),IG(),CG(),UW(_),cG(sJ(),_)])});return _}function YL($,_){return new Q5({type:"pipe",in:TX($),out:_})}var vR,K$,OX,a2,a$,DX,eJ,d4,JW,LX,BX,HX,NX,VX,FX,RX,KX,EG,MX,AX,bX,EX,wX,IX,gX,s2,e2,y1,$_,__,kX,gG,kG,fG,PG,TG,SG,ZG,WW,vG,XW,GW,yG,hG,mG,uG,o2,lG,nG,t2,iG,rG,pG,SX,oG,aG,sG,$5,ZX,W5,U5,G5,QW,YW,Q5,Y5,z5,j5,D5,L5,qW,WL,UL,GL=(...$)=>JO({Codec:YW,Boolean:$_,String:a2},...$);var YX=m(()=>{G4();G4();_X();eU();OG();GX();rO();vR=new WeakMap;K$=A("ZodType",($,_)=>{return F$.init($,_),Object.assign($["~standard"],{jsonSchema:{input:aJ($,"input"),output:aJ($,"output")}}),$.toJSONSchema=WO($,{}),$.def=_,$.type=_.type,Object.defineProperty($,"_def",{value:_}),$.parse=(J,U)=>DG($,J,U,{callee:$.parse}),$.safeParse=(J,U)=>BG($,J,U),$.parseAsync=async(J,U)=>LG($,J,U,{callee:$.parseAsync}),$.safeParseAsync=async(J,U)=>HG($,J,U),$.spa=$.safeParseAsync,$.encode=(J,U)=>NG($,J,U),$.decode=(J,U)=>VG($,J,U),$.encodeAsync=async(J,U)=>FG($,J,U),$.decodeAsync=async(J,U)=>RG($,J,U),$.safeEncode=(J,U)=>KG($,J,U),$.safeDecode=(J,U)=>MG($,J,U),$.safeEncodeAsync=async(J,U)=>AG($,J,U),$.safeDecodeAsync=async(J,U)=>bG($,J,U),jX($,"ZodType",{check(...J){let U=this.def;return this.clone(C.mergeDefs(U,{checks:[...U.checks??[],...J.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}),{parent:!0})},with(...J){return this.check(...J)},clone(J,U){return P6(this,J,U)},brand(){return this},register(J,U){return J.add(this,U),this},refine(J,U){return this.check(B5(J,U))},superRefine(J,U){return this.check(H5(J,U))},overwrite(J){return this.check(V4(J))},optional(){return $W(this)},exactOptional(){return tG(this)},nullable(){return _W(this)},nullish(){return $W(_W(this))},nonoptional(J){return J5(this,J)},array(){return UW(this)},or(J){return CX([this,J])},and(J){return xG(this,J)},transform(J){return zX(this,TX(J))},default(J){return eG(this,J)},prefault(J){return _5(this,J)},catch(J){return X5(this,J)},pipe(J){return zX(this,J)},readonly(){return q5(this)},describe(J){let U=this.clone();return w6.add(U,{description:J}),U},meta(...J){if(J.length===0)return w6.get(this);let U=this.clone();return w6.add(U,J[0]),U},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(J){return J(this)}}),Object.defineProperty($,"description",{get(){return w6.get($)?.description},configurable:!0}),$}),OX=A("_ZodString",($,_)=>{Z2.init($,_),K$.init($,_),$._zod.processJSONSchema=(U,W,X)=>UO($,U,W,X);let J=$._zod.bag;$.format=J.format??null,$.minLength=J.minimum??null,$.maxLength=J.maximum??null,jX($,"_ZodString",{regex(...U){return this.check(v2(...U))},includes(...U){return this.check(m2(...U))},startsWith(...U){return this.check(x2(...U))},endsWith(...U){return this.check(u2(...U))},min(...U){return this.check(D0(...U))},max(...U){return this.check(C1(...U))},length(...U){return this.check(P1(...U))},nonempty(...U){return this.check(D0(1,...U))},lowercase(U){return this.check(y2(U))},uppercase(U){return this.check(h2(U))},trim(){return this.check(l2())},normalize(...U){return this.check(c2(...U))},toLowerCase(){return this.check(n2())},toUpperCase(){return this.check(i2())},slugify(){return this.check(r2())}})}),a2=A("ZodString",($,_)=>{Z2.init($,_),OX.init($,_),$.email=(J)=>$.check(u8(DX,J)),$.url=(J)=>$.check(rU(JW,J)),$.jwt=(J)=>$.check(GG(gX,J)),$.emoji=(J)=>$.check(i8(LX,J)),$.guid=(J)=>$.check(iU(eJ,J)),$.uuid=(J)=>$.check(d8(d4,J)),$.uuidv4=(J)=>$.check(c8(d4,J)),$.uuidv6=(J)=>$.check(l8(d4,J)),$.uuidv7=(J)=>$.check(n8(d4,J)),$.nanoid=(J)=>$.check(r8(BX,J)),$.guid=(J)=>$.check(iU(eJ,J)),$.cuid=(J)=>$.check(p8(HX,J)),$.cuid2=(J)=>$.check(o8(NX,J)),$.ulid=(J)=>$.check(t8(VX,J)),$.base64=(J)=>$.check(WG(EX,J)),$.base64url=(J)=>$.check(UG(wX,J)),$.xid=(J)=>$.check(a8(FX,J)),$.ksuid=(J)=>$.check(s8(RX,J)),$.ipv4=(J)=>$.check(e8(KX,J)),$.ipv6=(J)=>$.check($G(MX,J)),$.cidrv4=(J)=>$.check(_G(AX,J)),$.cidrv6=(J)=>$.check(JG(bX,J)),$.e164=(J)=>$.check(XG(IX,J)),$.datetime=(J)=>$.check(dO(J)),$.date=(J)=>$.check(cO(J)),$.time=(J)=>$.check(lO(J)),$.duration=(J)=>$.check(nO(J))});a$=A("ZodStringFormat",($,_)=>{_6.init($,_),OX.init($,_)}),DX=A("ZodEmail",($,_)=>{jq.init($,_),a$.init($,_)});eJ=A("ZodGUID",($,_)=>{qq.init($,_),a$.init($,_)});d4=A("ZodUUID",($,_)=>{zq.init($,_),a$.init($,_)});JW=A("ZodURL",($,_)=>{Oq.init($,_),a$.init($,_)});LX=A("ZodEmoji",($,_)=>{Dq.init($,_),a$.init($,_)});BX=A("ZodNanoID",($,_)=>{Lq.init($,_),a$.init($,_)});HX=A("ZodCUID",($,_)=>{Bq.init($,_),a$.init($,_)});NX=A("ZodCUID2",($,_)=>{Hq.init($,_),a$.init($,_)});VX=A("ZodULID",($,_)=>{Nq.init($,_),a$.init($,_)});FX=A("ZodXID",($,_)=>{Vq.init($,_),a$.init($,_)});RX=A("ZodKSUID",($,_)=>{Fq.init($,_),a$.init($,_)});KX=A("ZodIPv4",($,_)=>{bq.init($,_),a$.init($,_)});EG=A("ZodMAC",($,_)=>{wq.init($,_),a$.init($,_)});MX=A("ZodIPv6",($,_)=>{Eq.init($,_),a$.init($,_)});AX=A("ZodCIDRv4",($,_)=>{Iq.init($,_),a$.init($,_)});bX=A("ZodCIDRv6",($,_)=>{gq.init($,_),a$.init($,_)});EX=A("ZodBase64",($,_)=>{fq.init($,_),a$.init($,_)});wX=A("ZodBase64URL",($,_)=>{Cq.init($,_),a$.init($,_)});IX=A("ZodE164",($,_)=>{Pq.init($,_),a$.init($,_)});gX=A("ZodJWT",($,_)=>{Tq.init($,_),a$.init($,_)});s2=A("ZodCustomStringFormat",($,_)=>{Sq.init($,_),a$.init($,_)});e2=A("ZodNumber",($,_)=>{S8.init($,_),K$.init($,_),$._zod.processJSONSchema=(U,W,X)=>XO($,U,W,X),jX($,"ZodNumber",{gt(U,W){return this.check(x4(U,W))},gte(U,W){return this.check(T6(U,W))},min(U,W){return this.check(T6(U,W))},lt(U,W){return this.check(m4(U,W))},lte(U,W){return this.check(t6(U,W))},max(U,W){return this.check(t6(U,W))},int(U){return this.check(qX(U))},safe(U){return this.check(qX(U))},positive(U){return this.check(x4(0,U))},nonnegative(U){return this.check(T6(0,U))},negative(U){return this.check(m4(0,U))},nonpositive(U){return this.check(t6(0,U))},multipleOf(U,W){return this.check(l0(U,W))},step(U,W){return this.check(l0(U,W))},finite(){return this}});let J=$._zod.bag;$.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),$.isFinite=!0,$.format=J.format??null});y1=A("ZodNumberFormat",($,_)=>{Zq.init($,_),e2.init($,_)});$_=A("ZodBoolean",($,_)=>{yU.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>GO($,J,U,W)});__=A("ZodBigInt",($,_)=>{Z8.init($,_),K$.init($,_),$._zod.processJSONSchema=(U,W,X)=>QO($,U,W,X),$.gte=(U,W)=>$.check(T6(U,W)),$.min=(U,W)=>$.check(T6(U,W)),$.gt=(U,W)=>$.check(x4(U,W)),$.gte=(U,W)=>$.check(T6(U,W)),$.min=(U,W)=>$.check(T6(U,W)),$.lt=(U,W)=>$.check(m4(U,W)),$.lte=(U,W)=>$.check(t6(U,W)),$.max=(U,W)=>$.check(t6(U,W)),$.positive=(U)=>$.check(x4(BigInt(0),U)),$.negative=(U)=>$.check(m4(BigInt(0),U)),$.nonpositive=(U)=>$.check(t6(BigInt(0),U)),$.nonnegative=(U)=>$.check(T6(BigInt(0),U)),$.multipleOf=(U,W)=>$.check(l0(U,W));let J=$._zod.bag;$.minValue=J.minimum??null,$.maxValue=J.maximum??null,$.format=J.format??null});kX=A("ZodBigIntFormat",($,_)=>{vq.init($,_),__.init($,_)});gG=A("ZodSymbol",($,_)=>{yq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>YO($,J,U,W)});kG=A("ZodUndefined",($,_)=>{hq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>zO($,J,U,W)});fG=A("ZodNull",($,_)=>{mq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>qO($,J,U,W)});PG=A("ZodAny",($,_)=>{xq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>DO($,J,U,W)});TG=A("ZodUnknown",($,_)=>{uq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>LO($,J,U,W)});SG=A("ZodNever",($,_)=>{dq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>OO($,J,U,W)});ZG=A("ZodVoid",($,_)=>{cq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>jO($,J,U,W)});WW=A("ZodDate",($,_)=>{lq.init($,_),K$.init($,_),$._zod.processJSONSchema=(U,W,X)=>BO($,U,W,X),$.min=(U,W)=>$.check(T6(U,W)),$.max=(U,W)=>$.check(t6(U,W));let J=$._zod.bag;$.minDate=J.minimum?new Date(J.minimum):null,$.maxDate=J.maximum?new Date(J.maximum):null});vG=A("ZodArray",($,_)=>{nq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>IO($,J,U,W),$.element=_.element,jX($,"ZodArray",{min(J,U){return this.check(D0(J,U))},nonempty(J){return this.check(D0(1,J))},max(J,U){return this.check(C1(J,U))},length(J,U){return this.check(P1(J,U))},unwrap(){return this.element}})});XW=A("ZodObject",($,_)=>{iq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>gO($,J,U,W),C.defineLazy($,"shape",()=>{return _.shape}),jX($,"ZodObject",{keyof(){return PX(Object.keys(this._zod.def.shape))},catchall(J){return this.clone({...this._zod.def,catchall:J})},passthrough(){return this.clone({...this._zod.def,catchall:v1()})},loose(){return this.clone({...this._zod.def,catchall:v1()})},strict(){return this.clone({...this._zod.def,catchall:fX()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(J){return C.extend(this,J)},safeExtend(J){return C.safeExtend(this,J)},merge(J){return C.merge(this,J)},pick(J){return C.pick(this,J)},omit(J){return C.omit(this,J)},partial(...J){return C.partial(SX,this,J[0])},required(...J){return C.required(ZX,this,J[0])}})});GW=A("ZodUnion",($,_)=>{hU.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>qG($,J,U,W),$.options=_.options});yG=A("ZodXor",($,_)=>{GW.init($,_),rq.init($,_),$._zod.processJSONSchema=(J,U,W)=>qG($,J,U,W),$.options=_.options});hG=A("ZodDiscriminatedUnion",($,_)=>{GW.init($,_),pq.init($,_)});mG=A("ZodIntersection",($,_)=>{oq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>kO($,J,U,W)});uG=A("ZodTuple",($,_)=>{v8.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>fO($,J,U,W),$.rest=(J)=>$.clone({...$._zod.def,rest:J})});o2=A("ZodRecord",($,_)=>{tq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>CO($,J,U,W),$.keyType=_.keyType,$.valueType=_.valueType});lG=A("ZodMap",($,_)=>{aq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>EO($,J,U,W),$.keyType=_.keyType,$.valueType=_.valueType,$.min=(...J)=>$.check(u4(...J)),$.nonempty=(J)=>$.check(u4(1,J)),$.max=(...J)=>$.check(n0(...J)),$.size=(...J)=>$.check(f1(...J))});nG=A("ZodSet",($,_)=>{sq.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>wO($,J,U,W),$.min=(...J)=>$.check(u4(...J)),$.nonempty=(J)=>$.check(u4(1,J)),$.max=(...J)=>$.check(n0(...J)),$.size=(...J)=>$.check(f1(...J))});t2=A("ZodEnum",($,_)=>{eq.init($,_),K$.init($,_),$._zod.processJSONSchema=(U,W,X)=>HO($,U,W,X),$.enum=_.entries,$.options=Object.values(_.entries);let J=new Set(Object.keys(_.entries));$.extract=(U,W)=>{let X={};for(let G of U)if(J.has(G))X[G]=_.entries[G];else throw Error(`Key ${G} not found in enum`);return new t2({..._,checks:[],...C.normalizeParams(W),entries:X})},$.exclude=(U,W)=>{let X={..._.entries};for(let G of U)if(J.has(G))delete X[G];else throw Error(`Key ${G} not found in enum`);return new t2({..._,checks:[],...C.normalizeParams(W),entries:X})}});iG=A("ZodLiteral",($,_)=>{$z.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>NO($,J,U,W),$.values=new Set(_.values),Object.defineProperty($,"value",{get(){if(_.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return _.values[0]}})});rG=A("ZodFile",($,_)=>{_z.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>RO($,J,U,W),$.min=(J,U)=>$.check(u4(J,U)),$.max=(J,U)=>$.check(n0(J,U)),$.mime=(J,U)=>$.check(d2(Array.isArray(J)?J:[J],U))});pG=A("ZodTransform",($,_)=>{Jz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>bO($,J,U,W),$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new C2($.constructor.name);J.addIssue=(X)=>{if(typeof X==="string")J.issues.push(C.issue(X,J.value,_));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=J.value),G.inst??(G.inst=$),J.issues.push(C.issue(G))}};let W=_.transform(J.value,J);if(W instanceof Promise)return W.then((X)=>{return J.value=X,J.fallback=!0,J});return J.value=W,J.fallback=!0,J}});SX=A("ZodOptional",($,_)=>{y8.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>zG($,J,U,W),$.unwrap=()=>$._zod.def.innerType});oG=A("ZodExactOptional",($,_)=>{Wz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>zG($,J,U,W),$.unwrap=()=>$._zod.def.innerType});aG=A("ZodNullable",($,_)=>{Uz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>PO($,J,U,W),$.unwrap=()=>$._zod.def.innerType});sG=A("ZodDefault",($,_)=>{Xz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>SO($,J,U,W),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});$5=A("ZodPrefault",($,_)=>{Gz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>ZO($,J,U,W),$.unwrap=()=>$._zod.def.innerType});ZX=A("ZodNonOptional",($,_)=>{Qz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>TO($,J,U,W),$.unwrap=()=>$._zod.def.innerType});W5=A("ZodSuccess",($,_)=>{Yz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>KO($,J,U,W),$.unwrap=()=>$._zod.def.innerType});U5=A("ZodCatch",($,_)=>{qz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>vO($,J,U,W),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});G5=A("ZodNaN",($,_)=>{zz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>VO($,J,U,W)});QW=A("ZodPipe",($,_)=>{h8.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>yO($,J,U,W),$.in=_.in,$.out=_.out});YW=A("ZodCodec",($,_)=>{QW.init($,_),mU.init($,_)});Q5=A("ZodPreprocess",($,_)=>{QW.init($,_),jz.init($,_)}),Y5=A("ZodReadonly",($,_)=>{Oz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>hO($,J,U,W),$.unwrap=()=>$._zod.def.innerType});z5=A("ZodTemplateLiteral",($,_)=>{Dz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>FO($,J,U,W)});j5=A("ZodLazy",($,_)=>{Hz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>xO($,J,U,W),$.unwrap=()=>$._zod.def.getter()});D5=A("ZodPromise",($,_)=>{Bz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>mO($,J,U,W),$.unwrap=()=>$._zod.def.innerType});L5=A("ZodFunction",($,_)=>{Lz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>AO($,J,U,W)});qW=A("ZodCustom",($,_)=>{Nz.init($,_),K$.init($,_),$._zod.processJSONSchema=(J,U,W)=>MO($,J,U,W)});WL=$O,UL=_O});function hR($){N6({customError:$})}function mR(){return N6().customError}var yR,N5;var xR=m(()=>{G4();yR={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($){})(N5||(N5={}))});function Qu($,_){let J=$.$schema;if(J==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(J==="http://json-schema.org/draft-07/schema#")return"draft-7";if(J==="http://json-schema.org/draft-04/schema#")return"draft-4";return _??"draft-2020-12"}function Yu($,_){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let J=$.slice(1).split("/").filter(Boolean);if(J.length===0)return _.rootSchema;let U=_.version==="draft-2020-12"?"$defs":"definitions";if(J[0]===U){let W=J[1];if(!W||!_.defs[W])throw Error(`Reference not found: ${$}`);return _.defs[W]}throw Error(`Reference not found: ${$}`)}function uR($,_){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return l.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let W=$.$ref;if(_.refs.has(W))return _.refs.get(W);if(_.processing.has(W))return l.lazy(()=>{if(!_.refs.has(W))throw Error(`Circular reference not resolved: ${W}`);return _.refs.get(W)});_.processing.add(W);let X=Yu(W,_),G=S6(X,_);return _.refs.set(W,G),_.processing.delete(W),G}if($.enum!==void 0){let W=$.enum;if(_.version==="openapi-3.0"&&$.nullable===!0&&W.length===1&&W[0]===null)return l.null();if(W.length===0)return l.never();if(W.length===1)return l.literal(W[0]);if(W.every((G)=>typeof G==="string"))return l.enum(W);let X=W.map((G)=>l.literal(G));if(X.length<2)return X[0];return l.union([X[0],X[1],...X.slice(2)])}if($.const!==void 0)return l.literal($.const);let J=$.type;if(Array.isArray(J)){let W=J.map((X)=>{let G={...$,type:X};return uR(G,_)});if(W.length===0)return l.never();if(W.length===1)return W[0];return l.union(W)}if(!J)return l.any();let U;switch(J){case"string":{let W=l.string();if($.format){let X=$.format;if(X==="email")W=W.check(l.email());else if(X==="uri"||X==="uri-reference")W=W.check(l.url());else if(X==="uuid"||X==="guid")W=W.check(l.uuid());else if(X==="date-time")W=W.check(l.iso.datetime());else if(X==="date")W=W.check(l.iso.date());else if(X==="time")W=W.check(l.iso.time());else if(X==="duration")W=W.check(l.iso.duration());else if(X==="ipv4")W=W.check(l.ipv4());else if(X==="ipv6")W=W.check(l.ipv6());else if(X==="mac")W=W.check(l.mac());else if(X==="cidr")W=W.check(l.cidrv4());else if(X==="cidr-v6")W=W.check(l.cidrv6());else if(X==="base64")W=W.check(l.base64());else if(X==="base64url")W=W.check(l.base64url());else if(X==="e164")W=W.check(l.e164());else if(X==="jwt")W=W.check(l.jwt());else if(X==="emoji")W=W.check(l.emoji());else if(X==="nanoid")W=W.check(l.nanoid());else if(X==="cuid")W=W.check(l.cuid());else if(X==="cuid2")W=W.check(l.cuid2());else if(X==="ulid")W=W.check(l.ulid());else if(X==="xid")W=W.check(l.xid());else if(X==="ksuid")W=W.check(l.ksuid())}if(typeof $.minLength==="number")W=W.min($.minLength);if(typeof $.maxLength==="number")W=W.max($.maxLength);if($.pattern)W=W.regex(new RegExp($.pattern));U=W;break}case"number":case"integer":{let W=J==="integer"?l.number().int():l.number();if(typeof $.minimum==="number")W=W.min($.minimum);if(typeof $.maximum==="number")W=W.max($.maximum);if(typeof $.exclusiveMinimum==="number")W=W.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")W=W.gt($.minimum);if(typeof $.exclusiveMaximum==="number")W=W.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")W=W.lt($.maximum);if(typeof $.multipleOf==="number")W=W.multipleOf($.multipleOf);U=W;break}case"boolean":{U=l.boolean();break}case"null":{U=l.null();break}case"object":{let W={},X=$.properties||{},G=new Set($.required||[]);for(let[Y,q]of Object.entries(X)){let L=S6(q,_);W[Y]=G.has(Y)?L:L.optional()}if($.propertyNames){let Y=S6($.propertyNames,_),q=$.additionalProperties&&typeof $.additionalProperties==="object"?S6($.additionalProperties,_):l.any();if(Object.keys(W).length===0){U=l.record(Y,q);break}let L=l.object(W).passthrough(),N=l.looseRecord(Y,q);U=l.intersection(L,N);break}if($.patternProperties){let Y=$.patternProperties,q=Object.keys(Y),L=[];for(let F of q){let B=S6(Y[F],_),H=l.string().regex(new RegExp(F));L.push(l.looseRecord(H,B))}let N=[];if(Object.keys(W).length>0)N.push(l.object(W).passthrough());if(N.push(...L),N.length===0)U=l.object({}).passthrough();else if(N.length===1)U=N[0];else{let F=l.intersection(N[0],N[1]);for(let B=2;BS6(Y,_)),Q=X&&typeof X==="object"&&!Array.isArray(X)?S6(X,_):void 0;if(Q)U=l.tuple(G).rest(Q);else U=l.tuple(G);if(typeof $.minItems==="number")U=U.check(l.minLength($.minItems));if(typeof $.maxItems==="number")U=U.check(l.maxLength($.maxItems))}else if(Array.isArray(X)){let G=X.map((Y)=>S6(Y,_)),Q=$.additionalItems&&typeof $.additionalItems==="object"?S6($.additionalItems,_):void 0;if(Q)U=l.tuple(G).rest(Q);else U=l.tuple(G);if(typeof $.minItems==="number")U=U.check(l.minLength($.minItems));if(typeof $.maxItems==="number")U=U.check(l.maxLength($.maxItems))}else if(X!==void 0){let G=S6(X,_),Q=l.array(G);if(typeof $.minItems==="number")Q=Q.min($.minItems);if(typeof $.maxItems==="number")Q=Q.max($.maxItems);U=Q}else U=l.array(l.any());break}default:throw Error(`Unsupported type: ${J}`)}return U}function S6($,_){if(typeof $==="boolean")return $?l.any():l.never();let J=uR($,_),U=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let Q=$.anyOf.map((q)=>S6(q,_)),Y=l.union(Q);J=U?l.intersection(J,Y):Y}if($.oneOf&&Array.isArray($.oneOf)){let Q=$.oneOf.map((q)=>S6(q,_)),Y=l.xor(Q);J=U?l.intersection(J,Y):Y}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)J=U?J:l.any();else{let Q=U?J:S6($.allOf[0],_),Y=U?0:1;for(let q=Y;q<$.allOf.length;q++)Q=l.intersection(Q,S6($.allOf[q],_));J=Q}if($.nullable===!0&&_.version==="openapi-3.0")J=l.nullable(J);if($.readOnly===!0)J=l.readonly(J);if($.default!==void 0)J=J.default($.default);let W={},X=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let Q of X)if(Q in $)W[Q]=$[Q];let G=["contentEncoding","contentMediaType","contentSchema"];for(let Q of G)if(Q in $)W[Q]=$[Q];for(let Q of Object.keys($))if(!Gu.has(Q))W[Q]=$[Q];if(Object.keys(W).length>0)_.registry.add(J,W);if($.description)J=J.describe($.description);return J}function qL($,_){if(typeof $==="boolean")return $?l.any():l.never();let J;try{J=JSON.parse(JSON.stringify($))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let U=Qu(J,_?.defaultTarget),W=J.$defs||J.definitions||{},X={version:U,defs:W,refs:new Map,processing:new Set,rootSchema:J,registry:_?.registry??w6};return S6(J,X)}var l,Gu;var dR=m(()=>{nU();OG();GX();YX();l={...QX,...jG,iso:p2},Gu=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"])});var V5={};s4(V5,{string:()=>qu,number:()=>zu,date:()=>Du,boolean:()=>ju,bigint:()=>Ou});function qu($){return Rj(a2,$)}function zu($){return Ij(e2,$)}function ju($){return Sj($_,$)}function Ou($){return vj(__,$)}function Du($){return rj(WW,$)}var cR=m(()=>{G4();YX()});var F5={};s4(F5,{xor:()=>hD,xid:()=>QD,void:()=>PD,uuidv7:()=>eO,uuidv6:()=>sO,uuidv4:()=>aO,uuid:()=>tO,util:()=>C,url:()=>$D,uppercase:()=>h2,unknown:()=>v1,union:()=>CX,undefined:()=>fD,ulid:()=>GD,uint64:()=>gD,uint32:()=>ED,tuple:()=>dG,trim:()=>l2,treeifyError:()=>O8,transform:()=>TX,toUpperCase:()=>i2,toLowerCase:()=>n2,toJSONSchema:()=>$X,templateLiteral:()=>sD,symbol:()=>kD,superRefine:()=>H5,success:()=>pD,stringbool:()=>GL,stringFormat:()=>VD,string:()=>sJ,strictObject:()=>vD,startsWith:()=>x2,slugify:()=>r2,size:()=>f1,setErrorMap:()=>hR,set:()=>cD,safeParseAsync:()=>HG,safeParse:()=>BG,safeEncodeAsync:()=>AG,safeEncode:()=>KG,safeDecodeAsync:()=>bG,safeDecode:()=>MG,registry:()=>lU,regexes:()=>o6,regex:()=>v2,refine:()=>B5,record:()=>cG,readonly:()=>q5,property:()=>sU,promise:()=>eD,prettifyError:()=>D8,preprocess:()=>YL,prefault:()=>_5,positive:()=>pU,pipe:()=>zX,partialRecord:()=>xD,parseAsync:()=>LG,parse:()=>DG,overwrite:()=>V4,optional:()=>$W,object:()=>ZD,number:()=>wG,nullish:()=>rD,nullable:()=>_W,null:()=>CG,normalize:()=>c2,nonpositive:()=>tU,nonoptional:()=>J5,nonnegative:()=>aU,never:()=>fX,negative:()=>oU,nativeEnum:()=>lD,nanoid:()=>WD,nan:()=>oD,multipleOf:()=>l0,minSize:()=>u4,minLength:()=>D0,mime:()=>d2,meta:()=>UL,maxSize:()=>n0,maxLength:()=>C1,map:()=>dD,mac:()=>zD,lte:()=>t6,lt:()=>m4,lowercase:()=>y2,looseRecord:()=>uD,looseObject:()=>yD,locales:()=>oJ,literal:()=>nD,length:()=>P1,lazy:()=>O5,ksuid:()=>YD,keyof:()=>SD,jwt:()=>ND,json:()=>QL,iso:()=>p2,ipv6:()=>jD,ipv4:()=>qD,invertCodec:()=>aD,intersection:()=>xG,int64:()=>ID,int32:()=>bD,int:()=>qX,instanceof:()=>XL,includes:()=>m2,httpUrl:()=>_D,hostname:()=>FD,hex:()=>RD,hash:()=>KD,guid:()=>oO,gte:()=>T6,gt:()=>x4,globalRegistry:()=>w6,getErrorMap:()=>mR,function:()=>$L,fromJSONSchema:()=>qL,formatError:()=>dJ,float64:()=>AD,float32:()=>MD,flattenError:()=>uJ,file:()=>iD,exactOptional:()=>tG,enum:()=>PX,endsWith:()=>u2,encodeAsync:()=>FG,encode:()=>NG,emoji:()=>JD,email:()=>pO,e164:()=>HD,discriminatedUnion:()=>mD,describe:()=>WL,decodeAsync:()=>RG,decode:()=>VG,date:()=>TD,custom:()=>JL,cuid2:()=>XD,cuid:()=>UD,core:()=>L0,config:()=>N6,coerce:()=>V5,codec:()=>tD,clone:()=>P6,cidrv6:()=>DD,cidrv4:()=>OD,check:()=>_L,catch:()=>X5,boolean:()=>IG,bigint:()=>wD,base64url:()=>BD,base64:()=>LD,array:()=>UW,any:()=>CD,_function:()=>$L,_default:()=>eG,_ZodString:()=>OX,ZodXor:()=>yG,ZodXID:()=>FX,ZodVoid:()=>ZG,ZodUnknown:()=>TG,ZodUnion:()=>GW,ZodUndefined:()=>kG,ZodUUID:()=>d4,ZodURL:()=>JW,ZodULID:()=>VX,ZodType:()=>K$,ZodTuple:()=>uG,ZodTransform:()=>pG,ZodTemplateLiteral:()=>z5,ZodSymbol:()=>gG,ZodSuccess:()=>W5,ZodStringFormat:()=>a$,ZodString:()=>a2,ZodSet:()=>nG,ZodRecord:()=>o2,ZodRealError:()=>l6,ZodReadonly:()=>Y5,ZodPromise:()=>D5,ZodPreprocess:()=>Q5,ZodPrefault:()=>$5,ZodPipe:()=>QW,ZodOptional:()=>SX,ZodObject:()=>XW,ZodNumberFormat:()=>y1,ZodNumber:()=>e2,ZodNullable:()=>aG,ZodNull:()=>fG,ZodNonOptional:()=>ZX,ZodNever:()=>SG,ZodNanoID:()=>BX,ZodNaN:()=>G5,ZodMap:()=>lG,ZodMAC:()=>EG,ZodLiteral:()=>iG,ZodLazy:()=>j5,ZodKSUID:()=>RX,ZodJWT:()=>gX,ZodIssueCode:()=>yR,ZodIntersection:()=>mG,ZodISOTime:()=>UX,ZodISODuration:()=>XX,ZodISODateTime:()=>JX,ZodISODate:()=>WX,ZodIPv6:()=>MX,ZodIPv4:()=>KX,ZodGUID:()=>eJ,ZodFunction:()=>L5,ZodFirstPartyTypeKind:()=>N5,ZodFile:()=>rG,ZodExactOptional:()=>oG,ZodError:()=>ZR,ZodEnum:()=>t2,ZodEmoji:()=>LX,ZodEmail:()=>DX,ZodE164:()=>IX,ZodDiscriminatedUnion:()=>hG,ZodDefault:()=>sG,ZodDate:()=>WW,ZodCustomStringFormat:()=>s2,ZodCustom:()=>qW,ZodCodec:()=>YW,ZodCatch:()=>U5,ZodCUID2:()=>NX,ZodCUID:()=>HX,ZodCIDRv6:()=>bX,ZodCIDRv4:()=>AX,ZodBoolean:()=>$_,ZodBigIntFormat:()=>kX,ZodBigInt:()=>__,ZodBase64URL:()=>wX,ZodBase64:()=>EX,ZodArray:()=>vG,ZodAny:()=>PG,TimePrecision:()=>QG,NEVER:()=>Y8,$output:()=>m8,$input:()=>x8,$brand:()=>q8});var zL=m(()=>{G4();G4();gz();G4();_X();dR();Nj();GX();GX();cR();YX();OG();iO();rO();xR();N6(xU())});var lR={};s4(lR,{z:()=>F5,xor:()=>hD,xid:()=>QD,void:()=>PD,uuidv7:()=>eO,uuidv6:()=>sO,uuidv4:()=>aO,uuid:()=>tO,util:()=>C,url:()=>$D,uppercase:()=>h2,unknown:()=>v1,union:()=>CX,undefined:()=>fD,ulid:()=>GD,uint64:()=>gD,uint32:()=>ED,tuple:()=>dG,trim:()=>l2,treeifyError:()=>O8,transform:()=>TX,toUpperCase:()=>i2,toLowerCase:()=>n2,toJSONSchema:()=>$X,templateLiteral:()=>sD,symbol:()=>kD,superRefine:()=>H5,success:()=>pD,stringbool:()=>GL,stringFormat:()=>VD,string:()=>sJ,strictObject:()=>vD,startsWith:()=>x2,slugify:()=>r2,size:()=>f1,setErrorMap:()=>hR,set:()=>cD,safeParseAsync:()=>HG,safeParse:()=>BG,safeEncodeAsync:()=>AG,safeEncode:()=>KG,safeDecodeAsync:()=>bG,safeDecode:()=>MG,registry:()=>lU,regexes:()=>o6,regex:()=>v2,refine:()=>B5,record:()=>cG,readonly:()=>q5,property:()=>sU,promise:()=>eD,prettifyError:()=>D8,preprocess:()=>YL,prefault:()=>_5,positive:()=>pU,pipe:()=>zX,partialRecord:()=>xD,parseAsync:()=>LG,parse:()=>DG,overwrite:()=>V4,optional:()=>$W,object:()=>ZD,number:()=>wG,nullish:()=>rD,nullable:()=>_W,null:()=>CG,normalize:()=>c2,nonpositive:()=>tU,nonoptional:()=>J5,nonnegative:()=>aU,never:()=>fX,negative:()=>oU,nativeEnum:()=>lD,nanoid:()=>WD,nan:()=>oD,multipleOf:()=>l0,minSize:()=>u4,minLength:()=>D0,mime:()=>d2,meta:()=>UL,maxSize:()=>n0,maxLength:()=>C1,map:()=>dD,mac:()=>zD,lte:()=>t6,lt:()=>m4,lowercase:()=>y2,looseRecord:()=>uD,looseObject:()=>yD,locales:()=>oJ,literal:()=>nD,length:()=>P1,lazy:()=>O5,ksuid:()=>YD,keyof:()=>SD,jwt:()=>ND,json:()=>QL,iso:()=>p2,ipv6:()=>jD,ipv4:()=>qD,invertCodec:()=>aD,intersection:()=>xG,int64:()=>ID,int32:()=>bD,int:()=>qX,instanceof:()=>XL,includes:()=>m2,httpUrl:()=>_D,hostname:()=>FD,hex:()=>RD,hash:()=>KD,guid:()=>oO,gte:()=>T6,gt:()=>x4,globalRegistry:()=>w6,getErrorMap:()=>mR,function:()=>$L,fromJSONSchema:()=>qL,formatError:()=>dJ,float64:()=>AD,float32:()=>MD,flattenError:()=>uJ,file:()=>iD,exactOptional:()=>tG,enum:()=>PX,endsWith:()=>u2,encodeAsync:()=>FG,encode:()=>NG,emoji:()=>JD,email:()=>pO,e164:()=>HD,discriminatedUnion:()=>mD,describe:()=>WL,default:()=>Lu,decodeAsync:()=>RG,decode:()=>VG,date:()=>TD,custom:()=>JL,cuid2:()=>XD,cuid:()=>UD,core:()=>L0,config:()=>N6,coerce:()=>V5,codec:()=>tD,clone:()=>P6,cidrv6:()=>DD,cidrv4:()=>OD,check:()=>_L,catch:()=>X5,boolean:()=>IG,bigint:()=>wD,base64url:()=>BD,base64:()=>LD,array:()=>UW,any:()=>CD,_function:()=>$L,_default:()=>eG,_ZodString:()=>OX,ZodXor:()=>yG,ZodXID:()=>FX,ZodVoid:()=>ZG,ZodUnknown:()=>TG,ZodUnion:()=>GW,ZodUndefined:()=>kG,ZodUUID:()=>d4,ZodURL:()=>JW,ZodULID:()=>VX,ZodType:()=>K$,ZodTuple:()=>uG,ZodTransform:()=>pG,ZodTemplateLiteral:()=>z5,ZodSymbol:()=>gG,ZodSuccess:()=>W5,ZodStringFormat:()=>a$,ZodString:()=>a2,ZodSet:()=>nG,ZodRecord:()=>o2,ZodRealError:()=>l6,ZodReadonly:()=>Y5,ZodPromise:()=>D5,ZodPreprocess:()=>Q5,ZodPrefault:()=>$5,ZodPipe:()=>QW,ZodOptional:()=>SX,ZodObject:()=>XW,ZodNumberFormat:()=>y1,ZodNumber:()=>e2,ZodNullable:()=>aG,ZodNull:()=>fG,ZodNonOptional:()=>ZX,ZodNever:()=>SG,ZodNanoID:()=>BX,ZodNaN:()=>G5,ZodMap:()=>lG,ZodMAC:()=>EG,ZodLiteral:()=>iG,ZodLazy:()=>j5,ZodKSUID:()=>RX,ZodJWT:()=>gX,ZodIssueCode:()=>yR,ZodIntersection:()=>mG,ZodISOTime:()=>UX,ZodISODuration:()=>XX,ZodISODateTime:()=>JX,ZodISODate:()=>WX,ZodIPv6:()=>MX,ZodIPv4:()=>KX,ZodGUID:()=>eJ,ZodFunction:()=>L5,ZodFirstPartyTypeKind:()=>N5,ZodFile:()=>rG,ZodExactOptional:()=>oG,ZodError:()=>ZR,ZodEnum:()=>t2,ZodEmoji:()=>LX,ZodEmail:()=>DX,ZodE164:()=>IX,ZodDiscriminatedUnion:()=>hG,ZodDefault:()=>sG,ZodDate:()=>WW,ZodCustomStringFormat:()=>s2,ZodCustom:()=>qW,ZodCodec:()=>YW,ZodCatch:()=>U5,ZodCUID2:()=>NX,ZodCUID:()=>HX,ZodCIDRv6:()=>bX,ZodCIDRv4:()=>AX,ZodBoolean:()=>$_,ZodBigIntFormat:()=>kX,ZodBigInt:()=>__,ZodBase64URL:()=>wX,ZodBase64:()=>EX,ZodArray:()=>vG,ZodAny:()=>PG,TimePrecision:()=>QG,NEVER:()=>Y8,$output:()=>m8,$input:()=>x8,$brand:()=>q8});var Lu;var nR=m(()=>{zL();zL();Lu=F5});var J9=i1((Qr)=>{class sL extends Error{constructor($,_,J){super(J);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=_,this.exitCode=$,this.nestedError=void 0}}class zA extends sL{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Qr.CommanderError=sL;Qr.InvalidArgumentError=zA});var e5=i1((Or)=>{var{InvalidArgumentError:zr}=J9();class jA{constructor($,_){switch(this.description=_||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,_){if(_===this.defaultValue||!Array.isArray(_))return[$];return _.concat($)}default($,_){return this.defaultValue=$,this.defaultValueDescription=_,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(_,J)=>{if(!this.argChoices.includes(_))throw new zr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(_,J);return _},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function jr($){let _=$.name()+($.variadic===!0?"...":"");return $.required?"<"+_+">":"["+_+"]"}Or.Argument=jA;Or.humanReadableArgName=jr});var eL=i1((Hr)=>{var{humanReadableArgName:Br}=e5();class OA{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let _=$.commands.filter((U)=>!U._hidden),J=$._getHelpCommand();if(J&&!J._hidden)_.push(J);if(this.sortSubcommands)_.sort((U,W)=>{return U.name().localeCompare(W.name())});return _}compareOptions($,_){let J=(U)=>{return U.short?U.short.replace(/^-/,""):U.long.replace(/^--/,"")};return J($).localeCompare(J(_))}visibleOptions($){let _=$.options.filter((U)=>!U.hidden),J=$._getHelpOption();if(J&&!J.hidden){let U=J.short&&$._findOption(J.short),W=J.long&&$._findOption(J.long);if(!U&&!W)_.push(J);else if(J.long&&!W)_.push($.createOption(J.long,J.description));else if(J.short&&!U)_.push($.createOption(J.short,J.description))}if(this.sortOptions)_.sort(this.compareOptions);return _}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let _=[];for(let J=$.parent;J;J=J.parent){let U=J.options.filter((W)=>!W.hidden);_.push(...U)}if(this.sortOptions)_.sort(this.compareOptions);return _}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((_)=>{_.description=_.description||$._argsDescription[_.name()]||""});if($.registeredArguments.find((_)=>_.description))return $.registeredArguments;return[]}subcommandTerm($){let _=$.registeredArguments.map((J)=>Br(J)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(_?" "+_:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,_){return _.visibleCommands($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleSubcommandTerm(_.subcommandTerm(U))))},0)}longestOptionTermLength($,_){return _.visibleOptions($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleOptionTerm(_.optionTerm(U))))},0)}longestGlobalOptionTermLength($,_){return _.visibleGlobalOptions($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleOptionTerm(_.optionTerm(U))))},0)}longestArgumentTermLength($,_){return _.visibleArguments($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleArgumentTerm(_.argumentTerm(U))))},0)}commandUsage($){let _=$._name;if($._aliases[0])_=_+"|"+$._aliases[0];let J="";for(let U=$.parent;U;U=U.parent)J=U.name()+" "+J;return J+_+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let _=[];if($.argChoices)_.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")_.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)_.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)_.push(`env: ${$.envVar}`);if(_.length>0)return`${$.description} (${_.join(", ")})`;return $.description}argumentDescription($){let _=[];if($.argChoices)_.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0)_.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(_.length>0){let J=`(${_.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}formatHelp($,_){let J=_.padWidth($,_),U=_.helpWidth??80;function W(L,N){return _.formatItem(L,J,N,_)}let X=[`${_.styleTitle("Usage:")} ${_.styleUsage(_.commandUsage($))}`,""],G=_.commandDescription($);if(G.length>0)X=X.concat([_.boxWrap(_.styleCommandDescription(G),U),""]);let Q=_.visibleArguments($).map((L)=>{return W(_.styleArgumentTerm(_.argumentTerm(L)),_.styleArgumentDescription(_.argumentDescription(L)))});if(Q.length>0)X=X.concat([_.styleTitle("Arguments:"),...Q,""]);let Y=_.visibleOptions($).map((L)=>{return W(_.styleOptionTerm(_.optionTerm(L)),_.styleOptionDescription(_.optionDescription(L)))});if(Y.length>0)X=X.concat([_.styleTitle("Options:"),...Y,""]);if(_.showGlobalOptions){let L=_.visibleGlobalOptions($).map((N)=>{return W(_.styleOptionTerm(_.optionTerm(N)),_.styleOptionDescription(_.optionDescription(N)))});if(L.length>0)X=X.concat([_.styleTitle("Global Options:"),...L,""])}let q=_.visibleCommands($).map((L)=>{return W(_.styleSubcommandTerm(_.subcommandTerm(L)),_.styleSubcommandDescription(_.subcommandDescription(L)))});if(q.length>0)X=X.concat([_.styleTitle("Commands:"),...q,""]);return X.join(` -`)}displayWidth($){return DA($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((_)=>{if(_==="[options]")return this.styleOptionText(_);if(_==="[command]")return this.styleSubcommandText(_);if(_[0]==="["||_[0]==="<")return this.styleArgumentText(_);return this.styleCommandText(_)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((_)=>{if(_==="[options]")return this.styleOptionText(_);if(_[0]==="["||_[0]==="<")return this.styleArgumentText(_);return this.styleSubcommandText(_)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,_){return Math.max(_.longestOptionTermLength($,_),_.longestGlobalOptionTermLength($,_),_.longestSubcommandTermLength($,_),_.longestArgumentTermLength($,_))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,_,J,U){let X=" ".repeat(2);if(!J)return X+$;let G=$.padEnd(_+$.length-U.displayWidth($)),Q=2,q=(this.helpWidth??80)-_-Q-2,L;if(q{let G=X.match(U);if(G===null){W.push("");return}let Q=[G.shift()],Y=this.displayWidth(Q[0]);G.forEach((q)=>{let L=this.displayWidth(q);if(Y+L<=_){Q.push(q),Y+=L;return}W.push(Q.join(""));let N=q.trimStart();Q=[N],Y=this.displayWidth(N)}),W.push(Q.join(""))}),W.join(` -`)}}function DA($){let _=/\x1b\[\d*(;\d*)*m/g;return $.replace(_,"")}Hr.Help=OA;Hr.stripColor=DA});var $B=i1((Kr)=>{var{InvalidArgumentError:Fr}=J9();class BA{constructor($,_){this.flags=$,this.description=_||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let J=Rr($);if(this.short=J.shortFlag,this.long=J.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,_){return this.defaultValue=$,this.defaultValueDescription=_,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let _=$;if(typeof $==="string")_={[$]:!0};return this.implied=Object.assign(this.implied||{},_),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,_){if(_===this.defaultValue||!Array.isArray(_))return[$];return _.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(_,J)=>{if(!this.argChoices.includes(_))throw new Fr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(_,J);return _},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return LA(this.name().replace(/^no-/,""));return LA(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class HA{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((_)=>{if(_.negate)this.negativeOptions.set(_.attributeName(),_);else this.positiveOptions.set(_.attributeName(),_)}),this.negativeOptions.forEach((_,J)=>{if(this.positiveOptions.has(J))this.dualOptions.add(J)})}valueFromOption($,_){let J=_.attributeName();if(!this.dualOptions.has(J))return!0;let U=this.negativeOptions.get(J).presetArg,W=U!==void 0?U:!1;return _.negate===(W===$)}}function LA($){return $.split("-").reduce((_,J)=>{return _+J[0].toUpperCase()+J.slice(1)})}function Rr($){let _,J,U=/^-[^-]$/,W=/^--[^-]/,X=$.split(/[ |,]+/).concat("guard");if(U.test(X[0]))_=X.shift();if(W.test(X[0]))J=X.shift();if(!_&&U.test(X[0]))_=X.shift();if(!_&&W.test(X[0]))_=J,J=X.shift();if(X[0].startsWith("-")){let G=X[0],Q=`option creation failed due to '${G}' in option flags '${$}'`;if(/^-[^-][^-]/.test(G))throw Error(`${Q} +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let G of $.seen.entries()){let Y=G[1];if(_===G[0]){X(G);continue}if($.external){let q=$.external.registry.get(G[0])?.id;if(_!==G[0]&&q){X(G);continue}}if($.metadataRegistry.get(G[0])?.id){X(G);continue}if(Y.cycle){X(G);continue}if(Y.count>1){if($.reused==="ref"){X(G);continue}}}}function y0($,_){let J=$.seen.get(_);if(!J)throw Error("Unprocessed schema. This is a bug in Zod.");let U=(Y)=>{let Q=$.seen.get(Y);if(Q.ref===null)return;let q=Q.def??Q.schema,L={...q},N=Q.ref;if(Q.ref=null,N){U(N);let B=$.seen.get(N),H=B.schema;if(H.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))q.allOf=q.allOf??[],q.allOf.push(H);else Object.assign(q,H);if(Object.assign(q,L),Y._zod.parent===N)for(let K in q){if(K==="$ref"||K==="allOf")continue;if(!(K in L))delete q[K]}if(H.$ref&&B.def)for(let K in q){if(K==="$ref"||K==="allOf")continue;if(K in B.def&&JSON.stringify(q[K])===JSON.stringify(B.def[K]))delete q[K]}}let R=Y._zod.parent;if(R&&R!==N){U(R);let B=$.seen.get(R);if(B?.schema.$ref){if(q.$ref=B.schema.$ref,B.def)for(let H in q){if(H==="$ref"||H==="allOf")continue;if(H in B.def&&JSON.stringify(q[H])===JSON.stringify(B.def[H]))delete q[H]}}}$.override({zodSchema:Y,jsonSchema:q,path:Q.path??[]})};for(let Y of[...$.seen.entries()].reverse())U(Y[0]);let W={};if($.target==="draft-2020-12")W.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")W.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let Y=$.external.registry.get(_)?.id;if(!Y)throw Error("Schema is missing an `id` property");W.$id=$.external.uri(Y)}Object.assign(W,J.def??J.schema);let X=$.metadataRegistry.get(_)?.id;if(X!==void 0&&W.id===X)delete W.id;let G=$.external?.defs??{};for(let Y of $.seen.entries()){let Q=Y[1];if(Q.def&&Q.defId){if(Q.def.id===Q.defId)delete Q.def.id;G[Q.defId]=Q.def}}if($.external);else if(Object.keys(G).length>0)if($.target==="draft-2020-12")W.$defs=G;else W.definitions=G;try{let Y=JSON.parse(JSON.stringify(W));return Object.defineProperty(Y,"~standard",{value:{..._["~standard"],jsonSchema:{input:JW(_,"input",$.processors),output:JW(_,"output",$.processors)}},enumerable:!1,writable:!1}),Y}catch(Y){throw Error("Error converting schema to JSON.")}}function c_($,_){let J=_??{seen:new Set};if(J.seen.has($))return!1;J.seen.add($);let U=$._zod.def;if(U.type==="transform")return!0;if(U.type==="array")return c_(U.element,J);if(U.type==="set")return c_(U.valueType,J);if(U.type==="lazy")return c_(U.getter(),J);if(U.type==="promise"||U.type==="optional"||U.type==="nonoptional"||U.type==="nullable"||U.type==="readonly"||U.type==="default"||U.type==="prefault")return c_(U.innerType,J);if(U.type==="intersection")return c_(U.left,J)||c_(U.right,J);if(U.type==="record"||U.type==="map")return c_(U.keyType,J)||c_(U.valueType,J);if(U.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return c_(U.in,J)||c_(U.out,J)}if(U.type==="object"){for(let W in U.shape)if(c_(U.shape[W],J))return!0;return!1}if(U.type==="union"){for(let W of U.options)if(c_(W,J))return!0;return!1}if(U.type==="tuple"){for(let W of U.items)if(c_(W,J))return!0;if(U.rest&&c_(U.rest,J))return!0;return!1}return!1}var zD=($,_={})=>(J)=>{let U=Z0({...J,processors:_});return l$($,U),v0(U,$),y0(U,$)},JW=($,_,J={})=>(U)=>{let{libraryOptions:W,target:X}=U??{},G=Z0({...W??{},target:X,io:_,processors:J});return l$($,G),v0(G,$),y0(G,$)};var UX=x(()=>{tU()});function XX($,_){if("_idmap"in $){let U=$,W=Z0({..._,processors:O5}),X={};for(let Q of U._idmap.entries()){let[q,L]=Q;l$(L,W)}let G={},Y={registry:U,uri:_?.uri,defs:X};W.external=Y;for(let Q of U._idmap.entries()){let[q,L]=Q;v0(W,L),G[q]=y0(W,L)}if(Object.keys(X).length>0){let Q=W.target==="draft-2020-12"?"$defs":"definitions";G.__shared={[Q]:X}}return{schemas:G}}let J=Z0({..._,processors:O5});return l$($,J),v0(J,$),y0(J,$)}var gu,jD=($,_,J,U)=>{let W=J;W.type="string";let{minimum:X,maximum:G,format:Y,patterns:Q,contentEncoding:q}=$._zod.bag;if(typeof X==="number")W.minLength=X;if(typeof G==="number")W.maxLength=G;if(Y){if(W.format=gu[Y]??Y,W.format==="")delete W.format;if(Y==="time")delete W.format}if(q)W.contentEncoding=q;if(Q&&Q.size>0){let L=[...Q];if(L.length===1)W.pattern=L[0].source;else if(L.length>1)W.allOf=[...L.map((N)=>({..._.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"?{type:"string"}:{},pattern:N.source}))]}},DD=($,_,J,U)=>{let W=J,{minimum:X,maximum:G,format:Y,multipleOf:Q,exclusiveMaximum:q,exclusiveMinimum:L}=$._zod.bag;if(typeof Y==="string"&&Y.includes("int"))W.type="integer";else W.type="number";let N=typeof L==="number"&&L>=(X??Number.NEGATIVE_INFINITY),R=typeof q==="number"&&q<=(G??Number.POSITIVE_INFINITY),B=_.target==="draft-04"||_.target==="openapi-3.0";if(N)if(B)W.minimum=L,W.exclusiveMinimum=!0;else W.exclusiveMinimum=L;else if(typeof X==="number")W.minimum=X;if(R)if(B)W.maximum=q,W.exclusiveMaximum=!0;else W.exclusiveMaximum=q;else if(typeof G==="number")W.maximum=G;if(typeof Q==="number")W.multipleOf=Q},OD=($,_,J,U)=>{J.type="boolean"},LD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},BD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},HD=($,_,J,U)=>{if(_.target==="openapi-3.0")J.type="string",J.nullable=!0,J.enum=[null];else J.type="null"},ND=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},VD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},RD=($,_,J,U)=>{J.not={}},KD=($,_,J,U)=>{},FD=($,_,J,U)=>{},ED=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},MD=($,_,J,U)=>{let W=$._zod.def,X=TU(W.entries);if(X.every((G)=>typeof G==="number"))J.type="number";if(X.every((G)=>typeof G==="string"))J.type="string";J.enum=X},AD=($,_,J,U)=>{let W=$._zod.def,X=[];for(let G of W.values)if(G===void 0){if(_.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof G==="bigint")if(_.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else X.push(Number(G));else X.push(G);if(X.length===0);else if(X.length===1){let G=X[0];if(J.type=G===null?"null":typeof G,_.target==="draft-04"||_.target==="openapi-3.0")J.enum=[G];else J.const=G}else{if(X.every((G)=>typeof G==="number"))J.type="number";if(X.every((G)=>typeof G==="string"))J.type="string";if(X.every((G)=>typeof G==="boolean"))J.type="boolean";if(X.every((G)=>G===null))J.type="null";J.enum=X}},bD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},wD=($,_,J,U)=>{let W=J,X=$._zod.pattern;if(!X)throw Error("Pattern not found in template literal");W.type="string",W.pattern=X.source},gD=($,_,J,U)=>{let W=J,X={type:"string",format:"binary",contentEncoding:"binary"},{minimum:G,maximum:Y,mime:Q}=$._zod.bag;if(G!==void 0)X.minLength=G;if(Y!==void 0)X.maxLength=Y;if(Q)if(Q.length===1)X.contentMediaType=Q[0],Object.assign(W,X);else Object.assign(W,X),W.anyOf=Q.map((q)=>({contentMediaType:q}));else Object.assign(W,X)},kD=($,_,J,U)=>{J.type="boolean"},ID=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},fD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},CD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},PD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},TD=($,_,J,U)=>{if(_.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},SD=($,_,J,U)=>{let W=J,X=$._zod.def,{minimum:G,maximum:Y}=$._zod.bag;if(typeof G==="number")W.minItems=G;if(typeof Y==="number")W.maxItems=Y;W.type="array",W.items=l$(X.element,_,{...U,path:[...U.path,"items"]})},ZD=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="object",W.properties={};let G=X.shape;for(let q in G)W.properties[q]=l$(G[q],_,{...U,path:[...U.path,"properties",q]});let Y=new Set(Object.keys(G)),Q=new Set([...Y].filter((q)=>{let L=X.shape[q]._zod;if(_.io==="input")return L.optin===void 0;else return L.optout===void 0}));if(Q.size>0)W.required=Array.from(Q);if(X.catchall?._zod.def.type==="never")W.additionalProperties=!1;else if(!X.catchall){if(_.io==="output")W.additionalProperties=!1}else if(X.catchall)W.additionalProperties=l$(X.catchall,_,{...U,path:[...U.path,"additionalProperties"]})},L5=($,_,J,U)=>{let W=$._zod.def,X=W.inclusive===!1,G=W.options.map((Y,Q)=>l$(Y,_,{...U,path:[...U.path,X?"oneOf":"anyOf",Q]}));if(X)J.oneOf=G;else J.anyOf=G},vD=($,_,J,U)=>{let W=$._zod.def,X=l$(W.left,_,{...U,path:[...U.path,"allOf",0]}),G=l$(W.right,_,{...U,path:[...U.path,"allOf",1]}),Y=(q)=>("allOf"in q)&&Object.keys(q).length===1,Q=[...Y(X)?X.allOf:[X],...Y(G)?G.allOf:[G]];J.allOf=Q},yD=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="array";let G=_.target==="draft-2020-12"?"prefixItems":"items",Y=_.target==="draft-2020-12"?"items":_.target==="openapi-3.0"?"items":"additionalItems",Q=X.items.map((R,B)=>l$(R,_,{...U,path:[...U.path,G,B]})),q=X.rest?l$(X.rest,_,{...U,path:[...U.path,Y,..._.target==="openapi-3.0"?[X.items.length]:[]]}):null;if(_.target==="draft-2020-12"){if(W.prefixItems=Q,q)W.items=q}else if(_.target==="openapi-3.0"){if(W.items={anyOf:Q},q)W.items.anyOf.push(q);if(W.minItems=Q.length,!q)W.maxItems=Q.length}else if(W.items=Q,q)W.additionalItems=q;let{minimum:L,maximum:N}=$._zod.bag;if(typeof L==="number")W.minItems=L;if(typeof N==="number")W.maxItems=N},hD=($,_,J,U)=>{let W=J,X=$._zod.def;W.type="object";let G=X.keyType,Q=G._zod.bag?.patterns;if(X.mode==="loose"&&Q&&Q.size>0){let L=l$(X.valueType,_,{...U,path:[...U.path,"patternProperties","*"]});W.patternProperties={};for(let N of Q)W.patternProperties[N.source]=L}else{if(_.target==="draft-07"||_.target==="draft-2020-12")W.propertyNames=l$(X.keyType,_,{...U,path:[...U.path,"propertyNames"]});W.additionalProperties=l$(X.valueType,_,{...U,path:[...U.path,"additionalProperties"]})}let q=G._zod.values;if(q){let L=[...q].filter((N)=>typeof N==="string"||typeof N==="number");if(L.length>0)W.required=L}},mD=($,_,J,U)=>{let W=$._zod.def,X=l$(W.innerType,_,U),G=_.seen.get($);if(_.target==="openapi-3.0")G.ref=W.innerType,J.nullable=!0;else J.anyOf=[X,{type:"null"}]},xD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},uD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType,J.default=JSON.parse(JSON.stringify(W.defaultValue))},dD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);if(X.ref=W.innerType,_.io==="input")J._prefault=JSON.parse(JSON.stringify(W.defaultValue))},nD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType;let G;try{G=W.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}J.default=G},cD=($,_,J,U)=>{let W=$._zod.def,X=W.in._zod.traits.has("$ZodTransform"),G=_.io==="input"?X?W.out:W.in:W.out;l$(G,_,U);let Y=_.seen.get($);Y.ref=G},iD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType,J.readOnly=!0},lD=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},B5=($,_,J,U)=>{let W=$._zod.def;l$(W.innerType,_,U);let X=_.seen.get($);X.ref=W.innerType},rD=($,_,J,U)=>{let W=$._zod.innerType;l$(W,_,U);let X=_.seen.get($);X.ref=W},O5;var GX=x(()=>{UX();e();gu={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},O5={string:jD,number:DD,boolean:OD,bigint:LD,symbol:BD,null:HD,undefined:ND,void:VD,never:RD,any:KD,unknown:FD,date:ED,enum:MD,literal:AD,nan:bD,template_literal:wD,file:gD,success:kD,custom:ID,function:fD,transform:CD,map:PD,set:TD,array:SD,object:ZD,union:L5,intersection:vD,tuple:yD,record:hD,nullable:mD,nonoptional:xD,default:uD,prefault:dD,catch:nD,pipe:cD,readonly:iD,promise:lD,optional:B5,lazy:rD}});class pD{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($){this.ctx.counter=$}get seen(){return this.ctx.seen}constructor($){let _=$?.target??"draft-2020-12";if(_==="draft-4")_="draft-04";if(_==="draft-7")_="draft-07";this.ctx=Z0({processors:O5,target:_,...$?.metadata&&{metadata:$.metadata},...$?.unrepresentable&&{unrepresentable:$.unrepresentable},...$?.override&&{override:$.override},...$?.io&&{io:$.io}})}process($,_={path:[],schemaPath:[]}){return l$($,this.ctx,_)}emit($,_){if(_){if(_.cycles)this.ctx.cycles=_.cycles;if(_.reused)this.ctx.reused=_.reused;if(_.external)this.ctx.external=_.external}v0(this.ctx,$);let J=y0(this.ctx,$),{"~standard":U,...W}=J;return W}}var dK=x(()=>{GX();UX()});var nK={};var cK=()=>{};var B4={};e6(B4,{version:()=>O7,util:()=>C,treeifyError:()=>N8,toJSONSchema:()=>XX,toDotPath:()=>LR,safeParseAsync:()=>Vq,safeParse:()=>Nq,safeEncodeAsync:()=>fm,safeEncode:()=>km,safeDecodeAsync:()=>Cm,safeDecode:()=>Im,registry:()=>oU,regexes:()=>t_,process:()=>l$,prettifyError:()=>V8,parseAsync:()=>K8,parse:()=>R8,meta:()=>QD,locales:()=>$W,isValidJWT:()=>vR,isValidBase64URL:()=>ZR,isValidBase64:()=>v7,initializeContext:()=>Z0,globalRegistry:()=>g_,globalConfig:()=>T1,formatError:()=>rJ,flattenError:()=>lJ,finalize:()=>y0,extractDefs:()=>v0,encodeAsync:()=>wm,encode:()=>Am,describe:()=>YD,decodeAsync:()=>gm,decode:()=>bm,createToJSONSchemaMethod:()=>zD,createStandardJSONSchemaMethod:()=>JW,config:()=>V_,clone:()=>T_,_xor:()=>Xu,_xid:()=>J5,_void:()=>sj,_uuidv7:()=>t8,_uuidv6:()=>o8,_uuidv4:()=>p8,_uuid:()=>r8,_url:()=>sU,_uppercase:()=>u1,_unknown:()=>tj,_union:()=>Uu,_undefined:()=>rj,_ulid:()=>_5,_uint64:()=>ij,_uint32:()=>mj,_tuple:()=>Qu,_trim:()=>r1,_transform:()=>Bu,_toUpperCase:()=>o1,_toLowerCase:()=>p1,_templateLiteral:()=>Au,_symbol:()=>lj,_superRefine:()=>GD,_success:()=>Ku,_stringbool:()=>qD,_stringFormat:()=>_W,_string:()=>wj,_startsWith:()=>n1,_slugify:()=>t1,_size:()=>P0,_set:()=>ju,_safeParseAsync:()=>aJ,_safeParse:()=>tJ,_safeEncodeAsync:()=>g8,_safeEncode:()=>b8,_safeDecodeAsync:()=>k8,_safeDecode:()=>w8,_regex:()=>m1,_refine:()=>XD,_record:()=>qu,_readonly:()=>Mu,_property:()=>WX,_promise:()=>wu,_positive:()=>eU,_pipe:()=>Eu,_parseAsync:()=>oJ,_parse:()=>pJ,_overwrite:()=>R6,_optional:()=>Hu,_number:()=>Tj,_nullable:()=>Nu,_null:()=>pj,_normalize:()=>l1,_nonpositive:()=>_X,_nonoptional:()=>Ru,_nonnegative:()=>JX,_never:()=>aj,_negative:()=>$X,_nativeEnum:()=>Ou,_nanoid:()=>s8,_nan:()=>_D,_multipleOf:()=>l4,_minSize:()=>u6,_minLength:()=>L4,_min:()=>S_,_mime:()=>i1,_maxSize:()=>r4,_maxLength:()=>T0,_max:()=>a_,_map:()=>zu,_mac:()=>kj,_lte:()=>a_,_lt:()=>m6,_lowercase:()=>x1,_literal:()=>Lu,_length:()=>S0,_lazy:()=>bu,_ksuid:()=>W5,_jwt:()=>j5,_isoTime:()=>Cj,_isoDuration:()=>Pj,_isoDateTime:()=>Ij,_isoDate:()=>fj,_ipv6:()=>X5,_ipv4:()=>U5,_intersection:()=>Yu,_int64:()=>cj,_int32:()=>hj,_int:()=>Zj,_includes:()=>d1,_guid:()=>aU,_gte:()=>S_,_gt:()=>x6,_float64:()=>yj,_float32:()=>vj,_file:()=>WD,_enum:()=>Du,_endsWith:()=>c1,_encodeAsync:()=>M8,_encode:()=>F8,_emoji:()=>a8,_email:()=>l8,_e164:()=>z5,_discriminatedUnion:()=>Gu,_default:()=>Vu,_decodeAsync:()=>A8,_decode:()=>E8,_date:()=>ej,_custom:()=>UD,_cuid2:()=>$5,_cuid:()=>e8,_coercedString:()=>gj,_coercedNumber:()=>Sj,_coercedDate:()=>$D,_coercedBoolean:()=>uj,_coercedBigint:()=>nj,_cidrv6:()=>Y5,_cidrv4:()=>G5,_check:()=>xK,_catch:()=>Fu,_boolean:()=>xj,_bigint:()=>dj,_base64url:()=>q5,_base64:()=>Q5,_array:()=>JD,_any:()=>oj,TimePrecision:()=>D5,NEVER:()=>O8,JSONSchemaGenerator:()=>pD,JSONSchema:()=>nK,Doc:()=>S8,$output:()=>c8,$input:()=>i8,$constructor:()=>M,$brand:()=>L8,$ZodXor:()=>$z,$ZodXID:()=>b7,$ZodVoid:()=>t7,$ZodUnknown:()=>p7,$ZodUnion:()=>nU,$ZodUndefined:()=>i7,$ZodUUID:()=>N7,$ZodURL:()=>R7,$ZodULID:()=>A7,$ZodType:()=>R$,$ZodTuple:()=>u8,$ZodTransform:()=>qz,$ZodTemplateLiteral:()=>Kz,$ZodSymbol:()=>c7,$ZodSuccess:()=>Bz,$ZodStringFormat:()=>J_,$ZodString:()=>h1,$ZodSet:()=>Xz,$ZodRegistry:()=>bj,$ZodRecord:()=>Wz,$ZodRealError:()=>o_,$ZodReadonly:()=>Rz,$ZodPromise:()=>Ez,$ZodPreprocess:()=>Vz,$ZodPrefault:()=>Oz,$ZodPipe:()=>n8,$ZodOptional:()=>d8,$ZodObjectJIT:()=>e7,$ZodObject:()=>mR,$ZodNumberFormat:()=>d7,$ZodNumber:()=>m8,$ZodNullable:()=>jz,$ZodNull:()=>l7,$ZodNonOptional:()=>Lz,$ZodNever:()=>o7,$ZodNanoID:()=>F7,$ZodNaN:()=>Nz,$ZodMap:()=>Uz,$ZodMAC:()=>T7,$ZodLiteral:()=>Yz,$ZodLazy:()=>Mz,$ZodKSUID:()=>w7,$ZodJWT:()=>x7,$ZodIntersection:()=>Jz,$ZodISOTime:()=>I7,$ZodISODuration:()=>f7,$ZodISODateTime:()=>g7,$ZodISODate:()=>k7,$ZodIPv6:()=>P7,$ZodIPv4:()=>C7,$ZodGUID:()=>H7,$ZodFunction:()=>Fz,$ZodFile:()=>Qz,$ZodExactOptional:()=>zz,$ZodError:()=>hU,$ZodEnum:()=>Gz,$ZodEncodeError:()=>S1,$ZodEmoji:()=>K7,$ZodEmail:()=>V7,$ZodE164:()=>m7,$ZodDiscriminatedUnion:()=>_z,$ZodDefault:()=>Dz,$ZodDate:()=>a7,$ZodCustomStringFormat:()=>u7,$ZodCustom:()=>Az,$ZodCodec:()=>cU,$ZodCheckUpperCase:()=>G7,$ZodCheckStringFormat:()=>sJ,$ZodCheckStartsWith:()=>Q7,$ZodCheckSizeEquals:()=>$7,$ZodCheckRegex:()=>U7,$ZodCheckProperty:()=>z7,$ZodCheckOverwrite:()=>D7,$ZodCheckNumberFormat:()=>tq,$ZodCheckMultipleOf:()=>oq,$ZodCheckMinSize:()=>eq,$ZodCheckMinLength:()=>J7,$ZodCheckMimeType:()=>j7,$ZodCheckMaxSize:()=>sq,$ZodCheckMaxLength:()=>_7,$ZodCheckLowerCase:()=>X7,$ZodCheckLessThan:()=>C8,$ZodCheckLengthEquals:()=>W7,$ZodCheckIncludes:()=>Y7,$ZodCheckGreaterThan:()=>P8,$ZodCheckEndsWith:()=>q7,$ZodCheckBigIntFormat:()=>aq,$ZodCheck:()=>X_,$ZodCatch:()=>Hz,$ZodCUID2:()=>M7,$ZodCUID:()=>E7,$ZodCIDRv6:()=>Z7,$ZodCIDRv4:()=>S7,$ZodBoolean:()=>dU,$ZodBigIntFormat:()=>n7,$ZodBigInt:()=>x8,$ZodBase64URL:()=>h7,$ZodBase64:()=>y7,$ZodAsyncError:()=>O4,$ZodArray:()=>s7,$ZodAny:()=>r7});var Q6=x(()=>{e();f8();Aj();GX();dK();cK();Z1();Rq();Hq();bz();T8();L7();tU();uK();UX()});var H5={};e6(H5,{uppercase:()=>u1,trim:()=>r1,toUpperCase:()=>o1,toLowerCase:()=>p1,startsWith:()=>n1,slugify:()=>t1,size:()=>P0,regex:()=>m1,property:()=>WX,positive:()=>eU,overwrite:()=>R6,normalize:()=>l1,nonpositive:()=>_X,nonnegative:()=>JX,negative:()=>$X,multipleOf:()=>l4,minSize:()=>u6,minLength:()=>L4,mime:()=>i1,maxSize:()=>r4,maxLength:()=>T0,lte:()=>a_,lt:()=>m6,lowercase:()=>x1,length:()=>S0,includes:()=>d1,gte:()=>S_,gt:()=>x6,endsWith:()=>c1});var N5=x(()=>{Q6()});var a1={};e6(a1,{time:()=>aD,duration:()=>sD,datetime:()=>oD,date:()=>tD,ZodISOTime:()=>qX,ZodISODuration:()=>zX,ZodISODateTime:()=>YX,ZodISODate:()=>QX});function oD($){return Ij(YX,$)}function tD($){return fj(QX,$)}function aD($){return Cj(qX,$)}function sD($){return Pj(zX,$)}var YX,QX,qX,zX;var jX=x(()=>{Q6();OX();YX=M("ZodISODateTime",($,_)=>{g7.init($,_),a$.init($,_)});QX=M("ZodISODate",($,_)=>{k7.init($,_),a$.init($,_)});qX=M("ZodISOTime",($,_)=>{I7.init($,_),a$.init($,_)});zX=M("ZodISODuration",($,_)=>{f7.init($,_),a$.init($,_)})});var iK=($,_)=>{hU.init($,_),$.name="ZodError",Object.defineProperties($,{format:{value:(J)=>rJ($,J)},flatten:{value:(J)=>lJ($,J)},addIssue:{value:(J)=>{$.issues.push(J),$.message=JSON.stringify($.issues,nJ,2)}},addIssues:{value:(J)=>{$.issues.push(...J),$.message=JSON.stringify($.issues,nJ,2)}},isEmpty:{get(){return $.issues.length===0}}})},lK,i_;var eD=x(()=>{Q6();Q6();e();lK=M("ZodError",iK),i_=M("ZodError",iK,{Parent:Error})});var V5,R5,K5,F5,E5,M5,A5,b5,w5,g5,k5,I5;var $O=x(()=>{Q6();eD();V5=pJ(i_),R5=oJ(i_),K5=tJ(i_),F5=aJ(i_),E5=F8(i_),M5=E8(i_),A5=M8(i_),b5=A8(i_),w5=b8(i_),g5=w8(i_),k5=g8(i_),I5=k8(i_)});var DX={};e6(DX,{xor:()=>iO,xid:()=>LO,void:()=>mO,uuidv7:()=>GO,uuidv6:()=>XO,uuidv4:()=>UO,uuid:()=>WO,url:()=>YO,unknown:()=>h0,union:()=>vX,undefined:()=>yO,ulid:()=>OO,uint64:()=>ZO,uint32:()=>PO,tuple:()=>r5,transform:()=>hX,templateLiteral:()=>XL,symbol:()=>vO,superRefine:()=>FG,success:()=>_L,stringbool:()=>OL,stringFormat:()=>bO,string:()=>WW,strictObject:()=>nO,set:()=>tO,refine:()=>KG,record:()=>p5,readonly:()=>LG,promise:()=>GL,preprocess:()=>BL,prefault:()=>GG,pipe:()=>BX,partialRecord:()=>rO,optional:()=>XW,object:()=>dO,number:()=>C5,nullish:()=>$L,nullable:()=>GW,null:()=>v5,nonoptional:()=>YG,never:()=>ZX,nativeEnum:()=>aO,nanoid:()=>zO,nan:()=>JL,meta:()=>jL,map:()=>oO,mac:()=>NO,looseRecord:()=>pO,looseObject:()=>cO,literal:()=>sO,lazy:()=>NG,ksuid:()=>BO,keyof:()=>uO,jwt:()=>AO,json:()=>LL,ipv6:()=>VO,ipv4:()=>HO,invertCodec:()=>UL,intersection:()=>i5,int64:()=>SO,int32:()=>CO,int:()=>LX,instanceof:()=>DL,httpUrl:()=>QO,hostname:()=>wO,hex:()=>gO,hash:()=>kO,guid:()=>JO,function:()=>YL,float64:()=>fO,float32:()=>IO,file:()=>eO,exactOptional:()=>_G,enum:()=>yX,emoji:()=>qO,email:()=>_O,e164:()=>MO,discriminatedUnion:()=>lO,describe:()=>zL,date:()=>xO,custom:()=>qL,cuid2:()=>DO,cuid:()=>jO,codec:()=>WL,cidrv6:()=>KO,cidrv4:()=>RO,check:()=>QL,catch:()=>zG,boolean:()=>P5,bigint:()=>TO,base64url:()=>EO,base64:()=>FO,array:()=>qW,any:()=>hO,_function:()=>YL,_default:()=>UG,_ZodString:()=>NX,ZodXor:()=>d5,ZodXID:()=>AX,ZodVoid:()=>x5,ZodUnknown:()=>h5,ZodUnion:()=>jW,ZodUndefined:()=>S5,ZodUUID:()=>d6,ZodURL:()=>YW,ZodULID:()=>MX,ZodType:()=>F$,ZodTuple:()=>l5,ZodTransform:()=>e5,ZodTemplateLiteral:()=>BG,ZodSymbol:()=>T5,ZodSuccess:()=>QG,ZodStringFormat:()=>a$,ZodString:()=>$2,ZodSet:()=>t5,ZodRecord:()=>s1,ZodReadonly:()=>OG,ZodPromise:()=>VG,ZodPreprocess:()=>DG,ZodPrefault:()=>XG,ZodPipe:()=>DW,ZodOptional:()=>mX,ZodObject:()=>zW,ZodNumberFormat:()=>m0,ZodNumber:()=>J2,ZodNullable:()=>JG,ZodNull:()=>Z5,ZodNonOptional:()=>xX,ZodNever:()=>m5,ZodNanoID:()=>KX,ZodNaN:()=>jG,ZodMap:()=>o5,ZodMAC:()=>f5,ZodLiteral:()=>a5,ZodLazy:()=>HG,ZodKSUID:()=>bX,ZodJWT:()=>TX,ZodIntersection:()=>c5,ZodIPv6:()=>gX,ZodIPv4:()=>wX,ZodGUID:()=>UW,ZodFunction:()=>RG,ZodFile:()=>s5,ZodExactOptional:()=>$G,ZodEnum:()=>e1,ZodEmoji:()=>RX,ZodEmail:()=>VX,ZodE164:()=>PX,ZodDiscriminatedUnion:()=>n5,ZodDefault:()=>WG,ZodDate:()=>QW,ZodCustomStringFormat:()=>_2,ZodCustom:()=>LW,ZodCodec:()=>OW,ZodCatch:()=>qG,ZodCUID2:()=>EX,ZodCUID:()=>FX,ZodCIDRv6:()=>IX,ZodCIDRv4:()=>kX,ZodBoolean:()=>W2,ZodBigIntFormat:()=>SX,ZodBigInt:()=>U2,ZodBase64URL:()=>CX,ZodBase64:()=>fX,ZodArray:()=>u5,ZodAny:()=>y5});function HX($,_,J){let U=Object.getPrototypeOf($),W=rK.get(U);if(!W)W=new Set,rK.set(U,W);if(W.has(_))return;W.add(_);for(let X in J){let G=J[X];Object.defineProperty(U,X,{configurable:!0,enumerable:!1,get(){let Y=G.bind(this);return Object.defineProperty(this,X,{configurable:!0,writable:!0,enumerable:!0,value:Y}),Y},set(Y){Object.defineProperty(this,X,{configurable:!0,writable:!0,enumerable:!0,value:Y})}})}}function WW($){return wj($2,$)}function _O($){return l8(VX,$)}function JO($){return aU(UW,$)}function WO($){return r8(d6,$)}function UO($){return p8(d6,$)}function XO($){return o8(d6,$)}function GO($){return t8(d6,$)}function YO($){return sU(YW,$)}function QO($){return sU(YW,{protocol:t_.httpProtocol,hostname:t_.domain,...C.normalizeParams($)})}function qO($){return a8(RX,$)}function zO($){return s8(KX,$)}function jO($){return e8(FX,$)}function DO($){return $5(EX,$)}function OO($){return _5(MX,$)}function LO($){return J5(AX,$)}function BO($){return W5(bX,$)}function HO($){return U5(wX,$)}function NO($){return kj(f5,$)}function VO($){return X5(gX,$)}function RO($){return G5(kX,$)}function KO($){return Y5(IX,$)}function FO($){return Q5(fX,$)}function EO($){return q5(CX,$)}function MO($){return z5(PX,$)}function AO($){return j5(TX,$)}function bO($,_,J={}){return _W(_2,$,_,J)}function wO($){return _W(_2,"hostname",t_.hostname,$)}function gO($){return _W(_2,"hex",t_.hex,$)}function kO($,_){let J=_?.enc??"hex",U=`${$}_${J}`,W=t_[U];if(!W)throw Error(`Unrecognized hash format: ${U}`);return _W(_2,U,W,_)}function C5($){return Tj(J2,$)}function LX($){return Zj(m0,$)}function IO($){return vj(m0,$)}function fO($){return yj(m0,$)}function CO($){return hj(m0,$)}function PO($){return mj(m0,$)}function P5($){return xj(W2,$)}function TO($){return dj(U2,$)}function SO($){return cj(SX,$)}function ZO($){return ij(SX,$)}function vO($){return lj(T5,$)}function yO($){return rj(S5,$)}function v5($){return pj(Z5,$)}function hO(){return oj(y5)}function h0(){return tj(h5)}function ZX($){return aj(m5,$)}function mO($){return sj(x5,$)}function xO($){return ej(QW,$)}function qW($,_){return JD(u5,$,_)}function uO($){let _=$._zod.def.shape;return yX(Object.keys(_))}function dO($,_){let J={type:"object",shape:$??{},...C.normalizeParams(_)};return new zW(J)}function nO($,_){return new zW({type:"object",shape:$,catchall:ZX(),...C.normalizeParams(_)})}function cO($,_){return new zW({type:"object",shape:$,catchall:h0(),...C.normalizeParams(_)})}function vX($,_){return new jW({type:"union",options:$,...C.normalizeParams(_)})}function iO($,_){return new d5({type:"union",options:$,inclusive:!1,...C.normalizeParams(_)})}function lO($,_,J){return new n5({type:"union",options:_,discriminator:$,...C.normalizeParams(J)})}function i5($,_){return new c5({type:"intersection",left:$,right:_})}function r5($,_,J){let U=_ instanceof R$,W=U?J:_;return new l5({type:"tuple",items:$,rest:U?_:null,...C.normalizeParams(W)})}function p5($,_,J){if(!_||!_._zod)return new s1({type:"record",keyType:WW(),valueType:$,...C.normalizeParams(_)});return new s1({type:"record",keyType:$,valueType:_,...C.normalizeParams(J)})}function rO($,_,J){let U=T_($);return U._zod.values=void 0,new s1({type:"record",keyType:U,valueType:_,...C.normalizeParams(J)})}function pO($,_,J){return new s1({type:"record",keyType:$,valueType:_,mode:"loose",...C.normalizeParams(J)})}function oO($,_,J){return new o5({type:"map",keyType:$,valueType:_,...C.normalizeParams(J)})}function tO($,_){return new t5({type:"set",valueType:$,...C.normalizeParams(_)})}function yX($,_){let J=Array.isArray($)?Object.fromEntries($.map((U)=>[U,U])):$;return new e1({type:"enum",entries:J,...C.normalizeParams(_)})}function aO($,_){return new e1({type:"enum",entries:$,...C.normalizeParams(_)})}function sO($,_){return new a5({type:"literal",values:Array.isArray($)?$:[$],...C.normalizeParams(_)})}function eO($){return WD(s5,$)}function hX($){return new e5({type:"transform",transform:$})}function XW($){return new mX({type:"optional",innerType:$})}function _G($){return new $G({type:"optional",innerType:$})}function GW($){return new JG({type:"nullable",innerType:$})}function $L($){return XW(GW($))}function UG($,_){return new WG({type:"default",innerType:$,get defaultValue(){return typeof _==="function"?_():C.shallowClone(_)}})}function GG($,_){return new XG({type:"prefault",innerType:$,get defaultValue(){return typeof _==="function"?_():C.shallowClone(_)}})}function YG($,_){return new xX({type:"nonoptional",innerType:$,...C.normalizeParams(_)})}function _L($){return new QG({type:"success",innerType:$})}function zG($,_){return new qG({type:"catch",innerType:$,catchValue:typeof _==="function"?_:()=>_})}function JL($){return _D(jG,$)}function BX($,_){return new DW({type:"pipe",in:$,out:_})}function WL($,_,J){return new OW({type:"pipe",in:$,out:_,transform:J.decode,reverseTransform:J.encode})}function UL($){let _=$._zod.def;return new OW({type:"pipe",in:_.out,out:_.in,transform:_.reverseTransform,reverseTransform:_.transform})}function LG($){return new OG({type:"readonly",innerType:$})}function XL($,_){return new BG({type:"template_literal",parts:$,...C.normalizeParams(_)})}function NG($){return new HG({type:"lazy",getter:$})}function GL($){return new VG({type:"promise",innerType:$})}function YL($){return new RG({type:"function",input:Array.isArray($?.input)?r5($?.input):$?.input??qW(h0()),output:$?.output??h0()})}function QL($){let _=new X_({check:"custom"});return _._zod.check=$,_}function qL($,_){return UD(LW,$??(()=>!0),_)}function KG($,_={}){return XD(LW,$,_)}function FG($,_){return GD($,_)}function DL($,_={}){let J=new LW({type:"custom",check:"custom",fn:(U)=>U instanceof $,abort:!0,...C.normalizeParams(_)});return J._zod.bag.Class=$,J._zod.check=(U)=>{if(!(U.value instanceof $))U.issues.push({code:"invalid_type",expected:$.name,input:U.value,inst:J,path:[...J._zod.def.path??[]]})},J}function LL($){let _=NG(()=>{return vX([WW($),C5(),P5(),v5(),qW(_),p5(WW(),_)])});return _}function BL($,_){return new DG({type:"pipe",in:hX($),out:_})}var rK,F$,NX,$2,a$,VX,UW,d6,YW,RX,KX,FX,EX,MX,AX,bX,wX,f5,gX,kX,IX,fX,CX,PX,TX,_2,J2,m0,W2,U2,SX,T5,S5,Z5,y5,h5,m5,x5,QW,u5,zW,jW,d5,n5,c5,l5,s1,o5,t5,e1,a5,s5,e5,mX,$G,JG,WG,XG,xX,QG,qG,jG,DW,OW,DG,OG,BG,HG,VG,RG,LW,zL,jL,OL=(...$)=>qD({Codec:OW,Boolean:W2,String:$2},...$);var OX=x(()=>{Q6();Q6();GX();UX();N5();jX();$O();rK=new WeakMap;F$=M("ZodType",($,_)=>{return R$.init($,_),Object.assign($["~standard"],{jsonSchema:{input:JW($,"input"),output:JW($,"output")}}),$.toJSONSchema=zD($,{}),$.def=_,$.type=_.type,Object.defineProperty($,"_def",{value:_}),$.parse=(J,U)=>V5($,J,U,{callee:$.parse}),$.safeParse=(J,U)=>K5($,J,U),$.parseAsync=async(J,U)=>R5($,J,U,{callee:$.parseAsync}),$.safeParseAsync=async(J,U)=>F5($,J,U),$.spa=$.safeParseAsync,$.encode=(J,U)=>E5($,J,U),$.decode=(J,U)=>M5($,J,U),$.encodeAsync=async(J,U)=>A5($,J,U),$.decodeAsync=async(J,U)=>b5($,J,U),$.safeEncode=(J,U)=>w5($,J,U),$.safeDecode=(J,U)=>g5($,J,U),$.safeEncodeAsync=async(J,U)=>k5($,J,U),$.safeDecodeAsync=async(J,U)=>I5($,J,U),HX($,"ZodType",{check(...J){let U=this.def;return this.clone(C.mergeDefs(U,{checks:[...U.checks??[],...J.map((W)=>typeof W==="function"?{_zod:{check:W,def:{check:"custom"},onattach:[]}}:W)]}),{parent:!0})},with(...J){return this.check(...J)},clone(J,U){return T_(this,J,U)},brand(){return this},register(J,U){return J.add(this,U),this},refine(J,U){return this.check(KG(J,U))},superRefine(J,U){return this.check(FG(J,U))},overwrite(J){return this.check(R6(J))},optional(){return XW(this)},exactOptional(){return _G(this)},nullable(){return GW(this)},nullish(){return XW(GW(this))},nonoptional(J){return YG(this,J)},array(){return qW(this)},or(J){return vX([this,J])},and(J){return i5(this,J)},transform(J){return BX(this,hX(J))},default(J){return UG(this,J)},prefault(J){return GG(this,J)},catch(J){return zG(this,J)},pipe(J){return BX(this,J)},readonly(){return LG(this)},describe(J){let U=this.clone();return g_.add(U,{description:J}),U},meta(...J){if(J.length===0)return g_.get(this);let U=this.clone();return g_.add(U,J[0]),U},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(J){return J(this)}}),Object.defineProperty($,"description",{get(){return g_.get($)?.description},configurable:!0}),$}),NX=M("_ZodString",($,_)=>{h1.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>jD($,U,W,X);let J=$._zod.bag;$.format=J.format??null,$.minLength=J.minimum??null,$.maxLength=J.maximum??null,HX($,"_ZodString",{regex(...U){return this.check(m1(...U))},includes(...U){return this.check(d1(...U))},startsWith(...U){return this.check(n1(...U))},endsWith(...U){return this.check(c1(...U))},min(...U){return this.check(L4(...U))},max(...U){return this.check(T0(...U))},length(...U){return this.check(S0(...U))},nonempty(...U){return this.check(L4(1,...U))},lowercase(U){return this.check(x1(U))},uppercase(U){return this.check(u1(U))},trim(){return this.check(r1())},normalize(...U){return this.check(l1(...U))},toLowerCase(){return this.check(p1())},toUpperCase(){return this.check(o1())},slugify(){return this.check(t1())}})}),$2=M("ZodString",($,_)=>{h1.init($,_),NX.init($,_),$.email=(J)=>$.check(l8(VX,J)),$.url=(J)=>$.check(sU(YW,J)),$.jwt=(J)=>$.check(j5(TX,J)),$.emoji=(J)=>$.check(a8(RX,J)),$.guid=(J)=>$.check(aU(UW,J)),$.uuid=(J)=>$.check(r8(d6,J)),$.uuidv4=(J)=>$.check(p8(d6,J)),$.uuidv6=(J)=>$.check(o8(d6,J)),$.uuidv7=(J)=>$.check(t8(d6,J)),$.nanoid=(J)=>$.check(s8(KX,J)),$.guid=(J)=>$.check(aU(UW,J)),$.cuid=(J)=>$.check(e8(FX,J)),$.cuid2=(J)=>$.check($5(EX,J)),$.ulid=(J)=>$.check(_5(MX,J)),$.base64=(J)=>$.check(Q5(fX,J)),$.base64url=(J)=>$.check(q5(CX,J)),$.xid=(J)=>$.check(J5(AX,J)),$.ksuid=(J)=>$.check(W5(bX,J)),$.ipv4=(J)=>$.check(U5(wX,J)),$.ipv6=(J)=>$.check(X5(gX,J)),$.cidrv4=(J)=>$.check(G5(kX,J)),$.cidrv6=(J)=>$.check(Y5(IX,J)),$.e164=(J)=>$.check(z5(PX,J)),$.datetime=(J)=>$.check(oD(J)),$.date=(J)=>$.check(tD(J)),$.time=(J)=>$.check(aD(J)),$.duration=(J)=>$.check(sD(J))});a$=M("ZodStringFormat",($,_)=>{J_.init($,_),NX.init($,_)}),VX=M("ZodEmail",($,_)=>{V7.init($,_),a$.init($,_)});UW=M("ZodGUID",($,_)=>{H7.init($,_),a$.init($,_)});d6=M("ZodUUID",($,_)=>{N7.init($,_),a$.init($,_)});YW=M("ZodURL",($,_)=>{R7.init($,_),a$.init($,_)});RX=M("ZodEmoji",($,_)=>{K7.init($,_),a$.init($,_)});KX=M("ZodNanoID",($,_)=>{F7.init($,_),a$.init($,_)});FX=M("ZodCUID",($,_)=>{E7.init($,_),a$.init($,_)});EX=M("ZodCUID2",($,_)=>{M7.init($,_),a$.init($,_)});MX=M("ZodULID",($,_)=>{A7.init($,_),a$.init($,_)});AX=M("ZodXID",($,_)=>{b7.init($,_),a$.init($,_)});bX=M("ZodKSUID",($,_)=>{w7.init($,_),a$.init($,_)});wX=M("ZodIPv4",($,_)=>{C7.init($,_),a$.init($,_)});f5=M("ZodMAC",($,_)=>{T7.init($,_),a$.init($,_)});gX=M("ZodIPv6",($,_)=>{P7.init($,_),a$.init($,_)});kX=M("ZodCIDRv4",($,_)=>{S7.init($,_),a$.init($,_)});IX=M("ZodCIDRv6",($,_)=>{Z7.init($,_),a$.init($,_)});fX=M("ZodBase64",($,_)=>{y7.init($,_),a$.init($,_)});CX=M("ZodBase64URL",($,_)=>{h7.init($,_),a$.init($,_)});PX=M("ZodE164",($,_)=>{m7.init($,_),a$.init($,_)});TX=M("ZodJWT",($,_)=>{x7.init($,_),a$.init($,_)});_2=M("ZodCustomStringFormat",($,_)=>{u7.init($,_),a$.init($,_)});J2=M("ZodNumber",($,_)=>{m8.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>DD($,U,W,X),HX($,"ZodNumber",{gt(U,W){return this.check(x6(U,W))},gte(U,W){return this.check(S_(U,W))},min(U,W){return this.check(S_(U,W))},lt(U,W){return this.check(m6(U,W))},lte(U,W){return this.check(a_(U,W))},max(U,W){return this.check(a_(U,W))},int(U){return this.check(LX(U))},safe(U){return this.check(LX(U))},positive(U){return this.check(x6(0,U))},nonnegative(U){return this.check(S_(0,U))},negative(U){return this.check(m6(0,U))},nonpositive(U){return this.check(a_(0,U))},multipleOf(U,W){return this.check(l4(U,W))},step(U,W){return this.check(l4(U,W))},finite(){return this}});let J=$._zod.bag;$.minValue=Math.max(J.minimum??Number.NEGATIVE_INFINITY,J.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,$.maxValue=Math.min(J.maximum??Number.POSITIVE_INFINITY,J.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,$.isInt=(J.format??"").includes("int")||Number.isSafeInteger(J.multipleOf??0.5),$.isFinite=!0,$.format=J.format??null});m0=M("ZodNumberFormat",($,_)=>{d7.init($,_),J2.init($,_)});W2=M("ZodBoolean",($,_)=>{dU.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>OD($,J,U,W)});U2=M("ZodBigInt",($,_)=>{x8.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>LD($,U,W,X),$.gte=(U,W)=>$.check(S_(U,W)),$.min=(U,W)=>$.check(S_(U,W)),$.gt=(U,W)=>$.check(x6(U,W)),$.gte=(U,W)=>$.check(S_(U,W)),$.min=(U,W)=>$.check(S_(U,W)),$.lt=(U,W)=>$.check(m6(U,W)),$.lte=(U,W)=>$.check(a_(U,W)),$.max=(U,W)=>$.check(a_(U,W)),$.positive=(U)=>$.check(x6(BigInt(0),U)),$.negative=(U)=>$.check(m6(BigInt(0),U)),$.nonpositive=(U)=>$.check(a_(BigInt(0),U)),$.nonnegative=(U)=>$.check(S_(BigInt(0),U)),$.multipleOf=(U,W)=>$.check(l4(U,W));let J=$._zod.bag;$.minValue=J.minimum??null,$.maxValue=J.maximum??null,$.format=J.format??null});SX=M("ZodBigIntFormat",($,_)=>{n7.init($,_),U2.init($,_)});T5=M("ZodSymbol",($,_)=>{c7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>BD($,J,U,W)});S5=M("ZodUndefined",($,_)=>{i7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>ND($,J,U,W)});Z5=M("ZodNull",($,_)=>{l7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>HD($,J,U,W)});y5=M("ZodAny",($,_)=>{r7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>KD($,J,U,W)});h5=M("ZodUnknown",($,_)=>{p7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>FD($,J,U,W)});m5=M("ZodNever",($,_)=>{o7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>RD($,J,U,W)});x5=M("ZodVoid",($,_)=>{t7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>VD($,J,U,W)});QW=M("ZodDate",($,_)=>{a7.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>ED($,U,W,X),$.min=(U,W)=>$.check(S_(U,W)),$.max=(U,W)=>$.check(a_(U,W));let J=$._zod.bag;$.minDate=J.minimum?new Date(J.minimum):null,$.maxDate=J.maximum?new Date(J.maximum):null});u5=M("ZodArray",($,_)=>{s7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>SD($,J,U,W),$.element=_.element,HX($,"ZodArray",{min(J,U){return this.check(L4(J,U))},nonempty(J){return this.check(L4(1,J))},max(J,U){return this.check(T0(J,U))},length(J,U){return this.check(S0(J,U))},unwrap(){return this.element}})});zW=M("ZodObject",($,_)=>{e7.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>ZD($,J,U,W),C.defineLazy($,"shape",()=>{return _.shape}),HX($,"ZodObject",{keyof(){return yX(Object.keys(this._zod.def.shape))},catchall(J){return this.clone({...this._zod.def,catchall:J})},passthrough(){return this.clone({...this._zod.def,catchall:h0()})},loose(){return this.clone({...this._zod.def,catchall:h0()})},strict(){return this.clone({...this._zod.def,catchall:ZX()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(J){return C.extend(this,J)},safeExtend(J){return C.safeExtend(this,J)},merge(J){return C.merge(this,J)},pick(J){return C.pick(this,J)},omit(J){return C.omit(this,J)},partial(...J){return C.partial(mX,this,J[0])},required(...J){return C.required(xX,this,J[0])}})});jW=M("ZodUnion",($,_)=>{nU.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>L5($,J,U,W),$.options=_.options});d5=M("ZodXor",($,_)=>{jW.init($,_),$z.init($,_),$._zod.processJSONSchema=(J,U,W)=>L5($,J,U,W),$.options=_.options});n5=M("ZodDiscriminatedUnion",($,_)=>{jW.init($,_),_z.init($,_)});c5=M("ZodIntersection",($,_)=>{Jz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>vD($,J,U,W)});l5=M("ZodTuple",($,_)=>{u8.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>yD($,J,U,W),$.rest=(J)=>$.clone({...$._zod.def,rest:J})});s1=M("ZodRecord",($,_)=>{Wz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>hD($,J,U,W),$.keyType=_.keyType,$.valueType=_.valueType});o5=M("ZodMap",($,_)=>{Uz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>PD($,J,U,W),$.keyType=_.keyType,$.valueType=_.valueType,$.min=(...J)=>$.check(u6(...J)),$.nonempty=(J)=>$.check(u6(1,J)),$.max=(...J)=>$.check(r4(...J)),$.size=(...J)=>$.check(P0(...J))});t5=M("ZodSet",($,_)=>{Xz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>TD($,J,U,W),$.min=(...J)=>$.check(u6(...J)),$.nonempty=(J)=>$.check(u6(1,J)),$.max=(...J)=>$.check(r4(...J)),$.size=(...J)=>$.check(P0(...J))});e1=M("ZodEnum",($,_)=>{Gz.init($,_),F$.init($,_),$._zod.processJSONSchema=(U,W,X)=>MD($,U,W,X),$.enum=_.entries,$.options=Object.values(_.entries);let J=new Set(Object.keys(_.entries));$.extract=(U,W)=>{let X={};for(let G of U)if(J.has(G))X[G]=_.entries[G];else throw Error(`Key ${G} not found in enum`);return new e1({..._,checks:[],...C.normalizeParams(W),entries:X})},$.exclude=(U,W)=>{let X={..._.entries};for(let G of U)if(J.has(G))delete X[G];else throw Error(`Key ${G} not found in enum`);return new e1({..._,checks:[],...C.normalizeParams(W),entries:X})}});a5=M("ZodLiteral",($,_)=>{Yz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>AD($,J,U,W),$.values=new Set(_.values),Object.defineProperty($,"value",{get(){if(_.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return _.values[0]}})});s5=M("ZodFile",($,_)=>{Qz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>gD($,J,U,W),$.min=(J,U)=>$.check(u6(J,U)),$.max=(J,U)=>$.check(r4(J,U)),$.mime=(J,U)=>$.check(i1(Array.isArray(J)?J:[J],U))});e5=M("ZodTransform",($,_)=>{qz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>CD($,J,U,W),$._zod.parse=(J,U)=>{if(U.direction==="backward")throw new S1($.constructor.name);J.addIssue=(X)=>{if(typeof X==="string")J.issues.push(C.issue(X,J.value,_));else{let G=X;if(G.fatal)G.continue=!1;G.code??(G.code="custom"),G.input??(G.input=J.value),G.inst??(G.inst=$),J.issues.push(C.issue(G))}};let W=_.transform(J.value,J);if(W instanceof Promise)return W.then((X)=>{return J.value=X,J.fallback=!0,J});return J.value=W,J.fallback=!0,J}});mX=M("ZodOptional",($,_)=>{d8.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>B5($,J,U,W),$.unwrap=()=>$._zod.def.innerType});$G=M("ZodExactOptional",($,_)=>{zz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>B5($,J,U,W),$.unwrap=()=>$._zod.def.innerType});JG=M("ZodNullable",($,_)=>{jz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>mD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});WG=M("ZodDefault",($,_)=>{Dz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>uD($,J,U,W),$.unwrap=()=>$._zod.def.innerType,$.removeDefault=$.unwrap});XG=M("ZodPrefault",($,_)=>{Oz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>dD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});xX=M("ZodNonOptional",($,_)=>{Lz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>xD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});QG=M("ZodSuccess",($,_)=>{Bz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>kD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});qG=M("ZodCatch",($,_)=>{Hz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>nD($,J,U,W),$.unwrap=()=>$._zod.def.innerType,$.removeCatch=$.unwrap});jG=M("ZodNaN",($,_)=>{Nz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>bD($,J,U,W)});DW=M("ZodPipe",($,_)=>{n8.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>cD($,J,U,W),$.in=_.in,$.out=_.out});OW=M("ZodCodec",($,_)=>{DW.init($,_),cU.init($,_)});DG=M("ZodPreprocess",($,_)=>{DW.init($,_),Vz.init($,_)}),OG=M("ZodReadonly",($,_)=>{Rz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>iD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});BG=M("ZodTemplateLiteral",($,_)=>{Kz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>wD($,J,U,W)});HG=M("ZodLazy",($,_)=>{Mz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>rD($,J,U,W),$.unwrap=()=>$._zod.def.getter()});VG=M("ZodPromise",($,_)=>{Ez.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>lD($,J,U,W),$.unwrap=()=>$._zod.def.innerType});RG=M("ZodFunction",($,_)=>{Fz.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>fD($,J,U,W)});LW=M("ZodCustom",($,_)=>{Az.init($,_),F$.init($,_),$._zod.processJSONSchema=(J,U,W)=>ID($,J,U,W)});zL=YD,jL=QD});function oK($){V_({customError:$})}function tK(){return V_().customError}var pK,EG;var aK=x(()=>{Q6();pK={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($){})(EG||(EG={}))});function Cu($,_){let J=$.$schema;if(J==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(J==="http://json-schema.org/draft-07/schema#")return"draft-7";if(J==="http://json-schema.org/draft-04/schema#")return"draft-4";return _??"draft-2020-12"}function Pu($,_){if(!$.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let J=$.slice(1).split("/").filter(Boolean);if(J.length===0)return _.rootSchema;let U=_.version==="draft-2020-12"?"$defs":"definitions";if(J[0]===U){let W=J[1];if(!W||!_.defs[W])throw Error(`Reference not found: ${$}`);return _.defs[W]}throw Error(`Reference not found: ${$}`)}function sK($,_){if($.not!==void 0){if(typeof $.not==="object"&&Object.keys($.not).length===0)return i.never();throw Error("not is not supported in Zod (except { not: {} } for never)")}if($.unevaluatedItems!==void 0)throw Error("unevaluatedItems is not supported");if($.unevaluatedProperties!==void 0)throw Error("unevaluatedProperties is not supported");if($.if!==void 0||$.then!==void 0||$.else!==void 0)throw Error("Conditional schemas (if/then/else) are not supported");if($.dependentSchemas!==void 0||$.dependentRequired!==void 0)throw Error("dependentSchemas and dependentRequired are not supported");if($.$ref){let W=$.$ref;if(_.refs.has(W))return _.refs.get(W);if(_.processing.has(W))return i.lazy(()=>{if(!_.refs.has(W))throw Error(`Circular reference not resolved: ${W}`);return _.refs.get(W)});_.processing.add(W);let X=Pu(W,_),G=Z_(X,_);return _.refs.set(W,G),_.processing.delete(W),G}if($.enum!==void 0){let W=$.enum;if(_.version==="openapi-3.0"&&$.nullable===!0&&W.length===1&&W[0]===null)return i.null();if(W.length===0)return i.never();if(W.length===1)return i.literal(W[0]);if(W.every((G)=>typeof G==="string"))return i.enum(W);let X=W.map((G)=>i.literal(G));if(X.length<2)return X[0];return i.union([X[0],X[1],...X.slice(2)])}if($.const!==void 0)return i.literal($.const);let J=$.type;if(Array.isArray(J)){let W=J.map((X)=>{let G={...$,type:X};return sK(G,_)});if(W.length===0)return i.never();if(W.length===1)return W[0];return i.union(W)}if(!J)return i.any();let U;switch(J){case"string":{let W=i.string();if($.format){let X=$.format;if(X==="email")W=W.check(i.email());else if(X==="uri"||X==="uri-reference")W=W.check(i.url());else if(X==="uuid"||X==="guid")W=W.check(i.uuid());else if(X==="date-time")W=W.check(i.iso.datetime());else if(X==="date")W=W.check(i.iso.date());else if(X==="time")W=W.check(i.iso.time());else if(X==="duration")W=W.check(i.iso.duration());else if(X==="ipv4")W=W.check(i.ipv4());else if(X==="ipv6")W=W.check(i.ipv6());else if(X==="mac")W=W.check(i.mac());else if(X==="cidr")W=W.check(i.cidrv4());else if(X==="cidr-v6")W=W.check(i.cidrv6());else if(X==="base64")W=W.check(i.base64());else if(X==="base64url")W=W.check(i.base64url());else if(X==="e164")W=W.check(i.e164());else if(X==="jwt")W=W.check(i.jwt());else if(X==="emoji")W=W.check(i.emoji());else if(X==="nanoid")W=W.check(i.nanoid());else if(X==="cuid")W=W.check(i.cuid());else if(X==="cuid2")W=W.check(i.cuid2());else if(X==="ulid")W=W.check(i.ulid());else if(X==="xid")W=W.check(i.xid());else if(X==="ksuid")W=W.check(i.ksuid())}if(typeof $.minLength==="number")W=W.min($.minLength);if(typeof $.maxLength==="number")W=W.max($.maxLength);if($.pattern)W=W.regex(new RegExp($.pattern));U=W;break}case"number":case"integer":{let W=J==="integer"?i.number().int():i.number();if(typeof $.minimum==="number")W=W.min($.minimum);if(typeof $.maximum==="number")W=W.max($.maximum);if(typeof $.exclusiveMinimum==="number")W=W.gt($.exclusiveMinimum);else if($.exclusiveMinimum===!0&&typeof $.minimum==="number")W=W.gt($.minimum);if(typeof $.exclusiveMaximum==="number")W=W.lt($.exclusiveMaximum);else if($.exclusiveMaximum===!0&&typeof $.maximum==="number")W=W.lt($.maximum);if(typeof $.multipleOf==="number")W=W.multipleOf($.multipleOf);U=W;break}case"boolean":{U=i.boolean();break}case"null":{U=i.null();break}case"object":{let W={},X=$.properties||{},G=new Set($.required||[]);for(let[Q,q]of Object.entries(X)){let L=Z_(q,_);W[Q]=G.has(Q)?L:L.optional()}if($.propertyNames){let Q=Z_($.propertyNames,_),q=$.additionalProperties&&typeof $.additionalProperties==="object"?Z_($.additionalProperties,_):i.any();if(Object.keys(W).length===0){U=i.record(Q,q);break}let L=i.object(W).passthrough(),N=i.looseRecord(Q,q);U=i.intersection(L,N);break}if($.patternProperties){let Q=$.patternProperties,q=Object.keys(Q),L=[];for(let R of q){let B=Z_(Q[R],_),H=i.string().regex(new RegExp(R));L.push(i.looseRecord(H,B))}let N=[];if(Object.keys(W).length>0)N.push(i.object(W).passthrough());if(N.push(...L),N.length===0)U=i.object({}).passthrough();else if(N.length===1)U=N[0];else{let R=i.intersection(N[0],N[1]);for(let B=2;BZ_(Q,_)),Y=X&&typeof X==="object"&&!Array.isArray(X)?Z_(X,_):void 0;if(Y)U=i.tuple(G).rest(Y);else U=i.tuple(G);if(typeof $.minItems==="number")U=U.check(i.minLength($.minItems));if(typeof $.maxItems==="number")U=U.check(i.maxLength($.maxItems))}else if(Array.isArray(X)){let G=X.map((Q)=>Z_(Q,_)),Y=$.additionalItems&&typeof $.additionalItems==="object"?Z_($.additionalItems,_):void 0;if(Y)U=i.tuple(G).rest(Y);else U=i.tuple(G);if(typeof $.minItems==="number")U=U.check(i.minLength($.minItems));if(typeof $.maxItems==="number")U=U.check(i.maxLength($.maxItems))}else if(X!==void 0){let G=Z_(X,_),Y=i.array(G);if(typeof $.minItems==="number")Y=Y.min($.minItems);if(typeof $.maxItems==="number")Y=Y.max($.maxItems);U=Y}else U=i.array(i.any());break}default:throw Error(`Unsupported type: ${J}`)}return U}function Z_($,_){if(typeof $==="boolean")return $?i.any():i.never();let J=sK($,_),U=$.type||$.enum!==void 0||$.const!==void 0;if($.anyOf&&Array.isArray($.anyOf)){let Y=$.anyOf.map((q)=>Z_(q,_)),Q=i.union(Y);J=U?i.intersection(J,Q):Q}if($.oneOf&&Array.isArray($.oneOf)){let Y=$.oneOf.map((q)=>Z_(q,_)),Q=i.xor(Y);J=U?i.intersection(J,Q):Q}if($.allOf&&Array.isArray($.allOf))if($.allOf.length===0)J=U?J:i.any();else{let Y=U?J:Z_($.allOf[0],_),Q=U?0:1;for(let q=Q;q<$.allOf.length;q++)Y=i.intersection(Y,Z_($.allOf[q],_));J=Y}if($.nullable===!0&&_.version==="openapi-3.0")J=i.nullable(J);if($.readOnly===!0)J=i.readonly(J);if($.default!==void 0)J=J.default($.default);let W={},X=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let Y of X)if(Y in $)W[Y]=$[Y];let G=["contentEncoding","contentMediaType","contentSchema"];for(let Y of G)if(Y in $)W[Y]=$[Y];for(let Y of Object.keys($))if(!fu.has(Y))W[Y]=$[Y];if(Object.keys(W).length>0)_.registry.add(J,W);if($.description)J=J.describe($.description);return J}function HL($,_){if(typeof $==="boolean")return $?i.any():i.never();let J;try{J=JSON.parse(JSON.stringify($))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let U=Cu(J,_?.defaultTarget),W=J.$defs||J.definitions||{},X={version:U,defs:W,refs:new Map,processing:new Set,rootSchema:J,registry:_?.registry??g_};return Z_(J,X)}var i,fu;var eK=x(()=>{tU();N5();jX();OX();i={...DX,...H5,iso:a1},fu=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"])});var MG={};e6(MG,{string:()=>Tu,number:()=>Su,date:()=>yu,boolean:()=>Zu,bigint:()=>vu});function Tu($){return gj($2,$)}function Su($){return Sj(J2,$)}function Zu($){return uj(W2,$)}function vu($){return nj(U2,$)}function yu($){return $D(QW,$)}var $F=x(()=>{Q6();OX()});var AG={};e6(AG,{xor:()=>iO,xid:()=>LO,void:()=>mO,uuidv7:()=>GO,uuidv6:()=>XO,uuidv4:()=>UO,uuid:()=>WO,util:()=>C,url:()=>YO,uppercase:()=>u1,unknown:()=>h0,union:()=>vX,undefined:()=>yO,ulid:()=>OO,uint64:()=>ZO,uint32:()=>PO,tuple:()=>r5,trim:()=>r1,treeifyError:()=>N8,transform:()=>hX,toUpperCase:()=>o1,toLowerCase:()=>p1,toJSONSchema:()=>XX,templateLiteral:()=>XL,symbol:()=>vO,superRefine:()=>FG,success:()=>_L,stringbool:()=>OL,stringFormat:()=>bO,string:()=>WW,strictObject:()=>nO,startsWith:()=>n1,slugify:()=>t1,size:()=>P0,setErrorMap:()=>oK,set:()=>tO,safeParseAsync:()=>F5,safeParse:()=>K5,safeEncodeAsync:()=>k5,safeEncode:()=>w5,safeDecodeAsync:()=>I5,safeDecode:()=>g5,registry:()=>oU,regexes:()=>t_,regex:()=>m1,refine:()=>KG,record:()=>p5,readonly:()=>LG,property:()=>WX,promise:()=>GL,prettifyError:()=>V8,preprocess:()=>BL,prefault:()=>GG,positive:()=>eU,pipe:()=>BX,partialRecord:()=>rO,parseAsync:()=>R5,parse:()=>V5,overwrite:()=>R6,optional:()=>XW,object:()=>dO,number:()=>C5,nullish:()=>$L,nullable:()=>GW,null:()=>v5,normalize:()=>l1,nonpositive:()=>_X,nonoptional:()=>YG,nonnegative:()=>JX,never:()=>ZX,negative:()=>$X,nativeEnum:()=>aO,nanoid:()=>zO,nan:()=>JL,multipleOf:()=>l4,minSize:()=>u6,minLength:()=>L4,mime:()=>i1,meta:()=>jL,maxSize:()=>r4,maxLength:()=>T0,map:()=>oO,mac:()=>NO,lte:()=>a_,lt:()=>m6,lowercase:()=>x1,looseRecord:()=>pO,looseObject:()=>cO,locales:()=>$W,literal:()=>sO,length:()=>S0,lazy:()=>NG,ksuid:()=>BO,keyof:()=>uO,jwt:()=>AO,json:()=>LL,iso:()=>a1,ipv6:()=>VO,ipv4:()=>HO,invertCodec:()=>UL,intersection:()=>i5,int64:()=>SO,int32:()=>CO,int:()=>LX,instanceof:()=>DL,includes:()=>d1,httpUrl:()=>QO,hostname:()=>wO,hex:()=>gO,hash:()=>kO,guid:()=>JO,gte:()=>S_,gt:()=>x6,globalRegistry:()=>g_,getErrorMap:()=>tK,function:()=>YL,fromJSONSchema:()=>HL,formatError:()=>rJ,float64:()=>fO,float32:()=>IO,flattenError:()=>lJ,file:()=>eO,exactOptional:()=>_G,enum:()=>yX,endsWith:()=>c1,encodeAsync:()=>A5,encode:()=>E5,emoji:()=>qO,email:()=>_O,e164:()=>MO,discriminatedUnion:()=>lO,describe:()=>zL,decodeAsync:()=>b5,decode:()=>M5,date:()=>xO,custom:()=>qL,cuid2:()=>DO,cuid:()=>jO,core:()=>B4,config:()=>V_,coerce:()=>MG,codec:()=>WL,clone:()=>T_,cidrv6:()=>KO,cidrv4:()=>RO,check:()=>QL,catch:()=>zG,boolean:()=>P5,bigint:()=>TO,base64url:()=>EO,base64:()=>FO,array:()=>qW,any:()=>hO,_function:()=>YL,_default:()=>UG,_ZodString:()=>NX,ZodXor:()=>d5,ZodXID:()=>AX,ZodVoid:()=>x5,ZodUnknown:()=>h5,ZodUnion:()=>jW,ZodUndefined:()=>S5,ZodUUID:()=>d6,ZodURL:()=>YW,ZodULID:()=>MX,ZodType:()=>F$,ZodTuple:()=>l5,ZodTransform:()=>e5,ZodTemplateLiteral:()=>BG,ZodSymbol:()=>T5,ZodSuccess:()=>QG,ZodStringFormat:()=>a$,ZodString:()=>$2,ZodSet:()=>t5,ZodRecord:()=>s1,ZodRealError:()=>i_,ZodReadonly:()=>OG,ZodPromise:()=>VG,ZodPreprocess:()=>DG,ZodPrefault:()=>XG,ZodPipe:()=>DW,ZodOptional:()=>mX,ZodObject:()=>zW,ZodNumberFormat:()=>m0,ZodNumber:()=>J2,ZodNullable:()=>JG,ZodNull:()=>Z5,ZodNonOptional:()=>xX,ZodNever:()=>m5,ZodNanoID:()=>KX,ZodNaN:()=>jG,ZodMap:()=>o5,ZodMAC:()=>f5,ZodLiteral:()=>a5,ZodLazy:()=>HG,ZodKSUID:()=>bX,ZodJWT:()=>TX,ZodIssueCode:()=>pK,ZodIntersection:()=>c5,ZodISOTime:()=>qX,ZodISODuration:()=>zX,ZodISODateTime:()=>YX,ZodISODate:()=>QX,ZodIPv6:()=>gX,ZodIPv4:()=>wX,ZodGUID:()=>UW,ZodFunction:()=>RG,ZodFirstPartyTypeKind:()=>EG,ZodFile:()=>s5,ZodExactOptional:()=>$G,ZodError:()=>lK,ZodEnum:()=>e1,ZodEmoji:()=>RX,ZodEmail:()=>VX,ZodE164:()=>PX,ZodDiscriminatedUnion:()=>n5,ZodDefault:()=>WG,ZodDate:()=>QW,ZodCustomStringFormat:()=>_2,ZodCustom:()=>LW,ZodCodec:()=>OW,ZodCatch:()=>qG,ZodCUID2:()=>EX,ZodCUID:()=>FX,ZodCIDRv6:()=>IX,ZodCIDRv4:()=>kX,ZodBoolean:()=>W2,ZodBigIntFormat:()=>SX,ZodBigInt:()=>U2,ZodBase64URL:()=>CX,ZodBase64:()=>fX,ZodArray:()=>u5,ZodAny:()=>y5,TimePrecision:()=>D5,NEVER:()=>O8,$output:()=>c8,$input:()=>i8,$brand:()=>L8});var NL=x(()=>{Q6();Q6();Zz();Q6();GX();eK();Aj();jX();jX();$F();OX();N5();eD();$O();aK();V_(iU())});var _F={};e6(_F,{z:()=>AG,xor:()=>iO,xid:()=>LO,void:()=>mO,uuidv7:()=>GO,uuidv6:()=>XO,uuidv4:()=>UO,uuid:()=>WO,util:()=>C,url:()=>YO,uppercase:()=>u1,unknown:()=>h0,union:()=>vX,undefined:()=>yO,ulid:()=>OO,uint64:()=>ZO,uint32:()=>PO,tuple:()=>r5,trim:()=>r1,treeifyError:()=>N8,transform:()=>hX,toUpperCase:()=>o1,toLowerCase:()=>p1,toJSONSchema:()=>XX,templateLiteral:()=>XL,symbol:()=>vO,superRefine:()=>FG,success:()=>_L,stringbool:()=>OL,stringFormat:()=>bO,string:()=>WW,strictObject:()=>nO,startsWith:()=>n1,slugify:()=>t1,size:()=>P0,setErrorMap:()=>oK,set:()=>tO,safeParseAsync:()=>F5,safeParse:()=>K5,safeEncodeAsync:()=>k5,safeEncode:()=>w5,safeDecodeAsync:()=>I5,safeDecode:()=>g5,registry:()=>oU,regexes:()=>t_,regex:()=>m1,refine:()=>KG,record:()=>p5,readonly:()=>LG,property:()=>WX,promise:()=>GL,prettifyError:()=>V8,preprocess:()=>BL,prefault:()=>GG,positive:()=>eU,pipe:()=>BX,partialRecord:()=>rO,parseAsync:()=>R5,parse:()=>V5,overwrite:()=>R6,optional:()=>XW,object:()=>dO,number:()=>C5,nullish:()=>$L,nullable:()=>GW,null:()=>v5,normalize:()=>l1,nonpositive:()=>_X,nonoptional:()=>YG,nonnegative:()=>JX,never:()=>ZX,negative:()=>$X,nativeEnum:()=>aO,nanoid:()=>zO,nan:()=>JL,multipleOf:()=>l4,minSize:()=>u6,minLength:()=>L4,mime:()=>i1,meta:()=>jL,maxSize:()=>r4,maxLength:()=>T0,map:()=>oO,mac:()=>NO,lte:()=>a_,lt:()=>m6,lowercase:()=>x1,looseRecord:()=>pO,looseObject:()=>cO,locales:()=>$W,literal:()=>sO,length:()=>S0,lazy:()=>NG,ksuid:()=>BO,keyof:()=>uO,jwt:()=>AO,json:()=>LL,iso:()=>a1,ipv6:()=>VO,ipv4:()=>HO,invertCodec:()=>UL,intersection:()=>i5,int64:()=>SO,int32:()=>CO,int:()=>LX,instanceof:()=>DL,includes:()=>d1,httpUrl:()=>QO,hostname:()=>wO,hex:()=>gO,hash:()=>kO,guid:()=>JO,gte:()=>S_,gt:()=>x6,globalRegistry:()=>g_,getErrorMap:()=>tK,function:()=>YL,fromJSONSchema:()=>HL,formatError:()=>rJ,float64:()=>fO,float32:()=>IO,flattenError:()=>lJ,file:()=>eO,exactOptional:()=>_G,enum:()=>yX,endsWith:()=>c1,encodeAsync:()=>A5,encode:()=>E5,emoji:()=>qO,email:()=>_O,e164:()=>MO,discriminatedUnion:()=>lO,describe:()=>zL,default:()=>hu,decodeAsync:()=>b5,decode:()=>M5,date:()=>xO,custom:()=>qL,cuid2:()=>DO,cuid:()=>jO,core:()=>B4,config:()=>V_,coerce:()=>MG,codec:()=>WL,clone:()=>T_,cidrv6:()=>KO,cidrv4:()=>RO,check:()=>QL,catch:()=>zG,boolean:()=>P5,bigint:()=>TO,base64url:()=>EO,base64:()=>FO,array:()=>qW,any:()=>hO,_function:()=>YL,_default:()=>UG,_ZodString:()=>NX,ZodXor:()=>d5,ZodXID:()=>AX,ZodVoid:()=>x5,ZodUnknown:()=>h5,ZodUnion:()=>jW,ZodUndefined:()=>S5,ZodUUID:()=>d6,ZodURL:()=>YW,ZodULID:()=>MX,ZodType:()=>F$,ZodTuple:()=>l5,ZodTransform:()=>e5,ZodTemplateLiteral:()=>BG,ZodSymbol:()=>T5,ZodSuccess:()=>QG,ZodStringFormat:()=>a$,ZodString:()=>$2,ZodSet:()=>t5,ZodRecord:()=>s1,ZodRealError:()=>i_,ZodReadonly:()=>OG,ZodPromise:()=>VG,ZodPreprocess:()=>DG,ZodPrefault:()=>XG,ZodPipe:()=>DW,ZodOptional:()=>mX,ZodObject:()=>zW,ZodNumberFormat:()=>m0,ZodNumber:()=>J2,ZodNullable:()=>JG,ZodNull:()=>Z5,ZodNonOptional:()=>xX,ZodNever:()=>m5,ZodNanoID:()=>KX,ZodNaN:()=>jG,ZodMap:()=>o5,ZodMAC:()=>f5,ZodLiteral:()=>a5,ZodLazy:()=>HG,ZodKSUID:()=>bX,ZodJWT:()=>TX,ZodIssueCode:()=>pK,ZodIntersection:()=>c5,ZodISOTime:()=>qX,ZodISODuration:()=>zX,ZodISODateTime:()=>YX,ZodISODate:()=>QX,ZodIPv6:()=>gX,ZodIPv4:()=>wX,ZodGUID:()=>UW,ZodFunction:()=>RG,ZodFirstPartyTypeKind:()=>EG,ZodFile:()=>s5,ZodExactOptional:()=>$G,ZodError:()=>lK,ZodEnum:()=>e1,ZodEmoji:()=>RX,ZodEmail:()=>VX,ZodE164:()=>PX,ZodDiscriminatedUnion:()=>n5,ZodDefault:()=>WG,ZodDate:()=>QW,ZodCustomStringFormat:()=>_2,ZodCustom:()=>LW,ZodCodec:()=>OW,ZodCatch:()=>qG,ZodCUID2:()=>EX,ZodCUID:()=>FX,ZodCIDRv6:()=>IX,ZodCIDRv4:()=>kX,ZodBoolean:()=>W2,ZodBigIntFormat:()=>SX,ZodBigInt:()=>U2,ZodBase64URL:()=>CX,ZodBase64:()=>fX,ZodArray:()=>u5,ZodAny:()=>y5,TimePrecision:()=>D5,NEVER:()=>O8,$output:()=>c8,$input:()=>i8,$brand:()=>L8});var hu;var JF=x(()=>{NL();NL();hu=AG});var Y9=t0((hr)=>{class zB extends Error{constructor($,_,J){super(J);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=_,this.exitCode=$,this.nestedError=void 0}}class CM extends zB{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}hr.CommanderError=zB;hr.InvalidArgumentError=CM});var GY=t0((nr)=>{var{InvalidArgumentError:ur}=Y9();class PM{constructor($,_){switch(this.description=_||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue($,_){if(_===this.defaultValue||!Array.isArray(_))return[$];return _.concat($)}default($,_){return this.defaultValue=$,this.defaultValueDescription=_,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(_,J)=>{if(!this.argChoices.includes(_))throw new ur(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(_,J);return _},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function dr($){let _=$.name()+($.variadic===!0?"...":"");return $.required?"<"+_+">":"["+_+"]"}nr.Argument=PM;nr.humanReadableArgName=dr});var jB=t0((rr)=>{var{humanReadableArgName:lr}=GY();class TM{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let _=$.commands.filter((U)=>!U._hidden),J=$._getHelpCommand();if(J&&!J._hidden)_.push(J);if(this.sortSubcommands)_.sort((U,W)=>{return U.name().localeCompare(W.name())});return _}compareOptions($,_){let J=(U)=>{return U.short?U.short.replace(/^-/,""):U.long.replace(/^--/,"")};return J($).localeCompare(J(_))}visibleOptions($){let _=$.options.filter((U)=>!U.hidden),J=$._getHelpOption();if(J&&!J.hidden){let U=J.short&&$._findOption(J.short),W=J.long&&$._findOption(J.long);if(!U&&!W)_.push(J);else if(J.long&&!W)_.push($.createOption(J.long,J.description));else if(J.short&&!U)_.push($.createOption(J.short,J.description))}if(this.sortOptions)_.sort(this.compareOptions);return _}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let _=[];for(let J=$.parent;J;J=J.parent){let U=J.options.filter((W)=>!W.hidden);_.push(...U)}if(this.sortOptions)_.sort(this.compareOptions);return _}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((_)=>{_.description=_.description||$._argsDescription[_.name()]||""});if($.registeredArguments.find((_)=>_.description))return $.registeredArguments;return[]}subcommandTerm($){let _=$.registeredArguments.map((J)=>lr(J)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(_?" "+_:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,_){return _.visibleCommands($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleSubcommandTerm(_.subcommandTerm(U))))},0)}longestOptionTermLength($,_){return _.visibleOptions($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleOptionTerm(_.optionTerm(U))))},0)}longestGlobalOptionTermLength($,_){return _.visibleGlobalOptions($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleOptionTerm(_.optionTerm(U))))},0)}longestArgumentTermLength($,_){return _.visibleArguments($).reduce((J,U)=>{return Math.max(J,this.displayWidth(_.styleArgumentTerm(_.argumentTerm(U))))},0)}commandUsage($){let _=$._name;if($._aliases[0])_=_+"|"+$._aliases[0];let J="";for(let U=$.parent;U;U=U.parent)J=U.name()+" "+J;return J+_+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let _=[];if($.argChoices)_.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")_.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)_.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)_.push(`env: ${$.envVar}`);if(_.length>0)return`${$.description} (${_.join(", ")})`;return $.description}argumentDescription($){let _=[];if($.argChoices)_.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0)_.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(_.length>0){let J=`(${_.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}formatHelp($,_){let J=_.padWidth($,_),U=_.helpWidth??80;function W(L,N){return _.formatItem(L,J,N,_)}let X=[`${_.styleTitle("Usage:")} ${_.styleUsage(_.commandUsage($))}`,""],G=_.commandDescription($);if(G.length>0)X=X.concat([_.boxWrap(_.styleCommandDescription(G),U),""]);let Y=_.visibleArguments($).map((L)=>{return W(_.styleArgumentTerm(_.argumentTerm(L)),_.styleArgumentDescription(_.argumentDescription(L)))});if(Y.length>0)X=X.concat([_.styleTitle("Arguments:"),...Y,""]);let Q=_.visibleOptions($).map((L)=>{return W(_.styleOptionTerm(_.optionTerm(L)),_.styleOptionDescription(_.optionDescription(L)))});if(Q.length>0)X=X.concat([_.styleTitle("Options:"),...Q,""]);if(_.showGlobalOptions){let L=_.visibleGlobalOptions($).map((N)=>{return W(_.styleOptionTerm(_.optionTerm(N)),_.styleOptionDescription(_.optionDescription(N)))});if(L.length>0)X=X.concat([_.styleTitle("Global Options:"),...L,""])}let q=_.visibleCommands($).map((L)=>{return W(_.styleSubcommandTerm(_.subcommandTerm(L)),_.styleSubcommandDescription(_.subcommandDescription(L)))});if(q.length>0)X=X.concat([_.styleTitle("Commands:"),...q,""]);return X.join(` +`)}displayWidth($){return SM($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((_)=>{if(_==="[options]")return this.styleOptionText(_);if(_==="[command]")return this.styleSubcommandText(_);if(_[0]==="["||_[0]==="<")return this.styleArgumentText(_);return this.styleCommandText(_)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((_)=>{if(_==="[options]")return this.styleOptionText(_);if(_[0]==="["||_[0]==="<")return this.styleArgumentText(_);return this.styleSubcommandText(_)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,_){return Math.max(_.longestOptionTermLength($,_),_.longestGlobalOptionTermLength($,_),_.longestSubcommandTermLength($,_),_.longestArgumentTermLength($,_))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,_,J,U){let X=" ".repeat(2);if(!J)return X+$;let G=$.padEnd(_+$.length-U.displayWidth($)),Y=2,q=(this.helpWidth??80)-_-Y-2,L;if(q{let G=X.match(U);if(G===null){W.push("");return}let Y=[G.shift()],Q=this.displayWidth(Y[0]);G.forEach((q)=>{let L=this.displayWidth(q);if(Q+L<=_){Y.push(q),Q+=L;return}W.push(Y.join(""));let N=q.trimStart();Y=[N],Q=this.displayWidth(N)}),W.push(Y.join(""))}),W.join(` +`)}}function SM($){let _=/\x1b\[\d*(;\d*)*m/g;return $.replace(_,"")}rr.Help=TM;rr.stripColor=SM});var DB=t0((sr)=>{var{InvalidArgumentError:tr}=Y9();class vM{constructor($,_){this.flags=$,this.description=_||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let J=ar($);if(this.short=J.shortFlag,this.long=J.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default($,_){return this.defaultValue=$,this.defaultValueDescription=_,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let _=$;if(typeof $==="string")_={[$]:!0};return this.implied=Object.assign(this.implied||{},_),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_concatValue($,_){if(_===this.defaultValue||!Array.isArray(_))return[$];return _.concat($)}choices($){return this.argChoices=$.slice(),this.parseArg=(_,J)=>{if(!this.argChoices.includes(_))throw new tr(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(_,J);return _},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return ZM(this.name().replace(/^no-/,""));return ZM(this.name())}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class yM{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((_)=>{if(_.negate)this.negativeOptions.set(_.attributeName(),_);else this.positiveOptions.set(_.attributeName(),_)}),this.negativeOptions.forEach((_,J)=>{if(this.positiveOptions.has(J))this.dualOptions.add(J)})}valueFromOption($,_){let J=_.attributeName();if(!this.dualOptions.has(J))return!0;let U=this.negativeOptions.get(J).presetArg,W=U!==void 0?U:!1;return _.negate===(W===$)}}function ZM($){return $.split("-").reduce((_,J)=>{return _+J[0].toUpperCase()+J.slice(1)})}function ar($){let _,J,U=/^-[^-]$/,W=/^--[^-]/,X=$.split(/[ |,]+/).concat("guard");if(U.test(X[0]))_=X.shift();if(W.test(X[0]))J=X.shift();if(!_&&U.test(X[0]))_=X.shift();if(!_&&W.test(X[0]))_=J,J=X.shift();if(X[0].startsWith("-")){let G=X[0],Y=`option creation failed due to '${G}' in option flags '${$}'`;if(/^-[^-][^-]/.test(G))throw Error(`${Y} - a short flag is a single dash and a single character - either use a single dash and a single character (for a short flag) - - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(U.test(G))throw Error(`${Q} -- too many short flags`);if(W.test(G))throw Error(`${Q} -- too many long flags`);throw Error(`${Q} -- unrecognised flag format`)}if(_===void 0&&J===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:_,longFlag:J}}Kr.Option=BA;Kr.DualOptions=HA});var NA=i1((wr)=>{function br($,_){if(Math.abs($.length-_.length)>3)return Math.max($.length,_.length);let J=[];for(let U=0;U<=$.length;U++)J[U]=[U];for(let U=0;U<=_.length;U++)J[0][U]=U;for(let U=1;U<=_.length;U++)for(let W=1;W<=$.length;W++){let X=1;if($[W-1]===_[U-1])X=0;else X=1;if(J[W][U]=Math.min(J[W-1][U]+1,J[W][U-1]+1,J[W-1][U-1]+X),W>1&&U>1&&$[W-1]===_[U-2]&&$[W-2]===_[U-1])J[W][U]=Math.min(J[W][U],J[W-2][U-2]+1)}return J[$.length][_.length]}function Er($,_){if(!_||_.length===0)return"";_=Array.from(new Set(_));let J=$.startsWith("--");if(J)$=$.slice(2),_=_.map((G)=>G.slice(2));let U=[],W=3,X=0.4;if(_.forEach((G)=>{if(G.length<=1)return;let Q=br($,G),Y=Math.max($.length,G.length);if((Y-Q)/Y>X){if(QG.localeCompare(Q)),J)U=U.map((G)=>`--${G}`);if(U.length>1)return` + - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(U.test(G))throw Error(`${Y} +- too many short flags`);if(W.test(G))throw Error(`${Y} +- too many long flags`);throw Error(`${Y} +- unrecognised flag format`)}if(_===void 0&&J===void 0)throw Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:_,longFlag:J}}sr.Option=vM;sr.DualOptions=yM});var hM=t0((Wp)=>{function _p($,_){if(Math.abs($.length-_.length)>3)return Math.max($.length,_.length);let J=[];for(let U=0;U<=$.length;U++)J[U]=[U];for(let U=0;U<=_.length;U++)J[0][U]=U;for(let U=1;U<=_.length;U++)for(let W=1;W<=$.length;W++){let X=1;if($[W-1]===_[U-1])X=0;else X=1;if(J[W][U]=Math.min(J[W-1][U]+1,J[W][U-1]+1,J[W-1][U-1]+X),W>1&&U>1&&$[W-1]===_[U-2]&&$[W-2]===_[U-1])J[W][U]=Math.min(J[W][U],J[W-2][U-2]+1)}return J[$.length][_.length]}function Jp($,_){if(!_||_.length===0)return"";_=Array.from(new Set(_));let J=$.startsWith("--");if(J)$=$.slice(2),_=_.map((G)=>G.slice(2));let U=[],W=3,X=0.4;if(_.forEach((G)=>{if(G.length<=1)return;let Y=_p($,G),Q=Math.max($.length,G.length);if((Q-Y)/Q>X){if(YG.localeCompare(Y)),J)U=U.map((G)=>`--${G}`);if(U.length>1)return` (Did you mean one of ${U.join(", ")}?)`;if(U.length===1)return` -(Did you mean ${U[0]}?)`;return""}wr.suggestSimilar=Er});var KA=i1((Sr)=>{var gr=n$("events").EventEmitter,_B=n$("child_process"),J1=n$("path"),$Q=n$("fs"),c$=n$("process"),{Argument:kr,humanReadableArgName:fr}=e5(),{CommanderError:JB}=J9(),{Help:Cr,stripColor:Pr}=eL(),{Option:VA,DualOptions:Tr}=$B(),{suggestSimilar:FA}=NA();class UB extends gr{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(_)=>c$.stdout.write(_),writeErr:(_)=>c$.stderr.write(_),outputError:(_,J)=>J(_),getOutHelpWidth:()=>c$.stdout.isTTY?c$.stdout.columns:void 0,getErrHelpWidth:()=>c$.stderr.isTTY?c$.stderr.columns:void 0,getOutHasColors:()=>WB()??(c$.stdout.isTTY&&c$.stdout.hasColors?.()),getErrHasColors:()=>WB()??(c$.stderr.isTTY&&c$.stderr.hasColors?.()),stripColor:(_)=>Pr(_)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let _=this;_;_=_.parent)$.push(_);return $}command($,_,J){let U=_,W=J;if(typeof U==="object"&&U!==null)W=U,U=null;W=W||{};let[,X,G]=$.match(/([^ ]+) *(.*)/),Q=this.createCommand(X);if(U)Q.description(U),Q._executableHandler=!0;if(W.isDefault)this._defaultCommandName=Q._name;if(Q._hidden=!!(W.noHelp||W.hidden),Q._executableFile=W.executableFile||null,G)Q.arguments(G);if(this._registerCommand(Q),Q.parent=this,Q.copyInheritedSettings(this),U)return this;return Q}createCommand($){return new UB($)}createHelp(){return Object.assign(new Cr,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,_){if(!$._name)throw Error(`Command passed to .addCommand() must have a name -- specify the name in Command constructor or using .name()`);if(_=_||{},_.isDefault)this._defaultCommandName=$._name;if(_.noHelp||_.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,_){return new kr($,_)}argument($,_,J,U){let W=this.createArgument($,_);if(typeof J==="function")W.default(U).argParser(J);else W.default(J);return this.addArgument(W),this}arguments($){return $.trim().split(/ +/).forEach((_)=>{this.argument(_)}),this}addArgument($){let _=this.registeredArguments.slice(-1)[0];if(_&&_.variadic)throw Error(`only the last argument can be variadic '${_.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,_){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,J,U]=$.match(/([^ ]+) *(.*)/),W=_??"display help for command",X=this.createCommand(J);if(X.helpOption(!1),U)X.arguments(U);if(W)X.description(W);return this._addImplicitHelpCommand=!0,this._helpCommand=X,this}addHelpCommand($,_){if(typeof $!=="object")return this.helpCommand($,_),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,_){let J=["preSubcommand","preAction","postAction"];if(!J.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'. -Expecting one of '${J.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(_);else this._lifeCycleHooks[$]=[_];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(_)=>{if(_.code!=="commander.executeSubCommandAsync")throw _};return this}_exit($,_,J){if(this._exitCallback)this._exitCallback(new JB($,_,J));c$.exit($)}action($){let _=(J)=>{let U=this.registeredArguments.length,W=J.slice(0,U);if(this._storeOptionsAsProperties)W[U]=this;else W[U]=this.opts();return W.push(this),$.apply(this,W)};return this._actionHandler=_,this}createOption($,_){return new VA($,_)}_callParseArg($,_,J,U){try{return $.parseArg(_,J)}catch(W){if(W.code==="commander.invalidArgument"){let X=`${U} ${W.message}`;this.error(X,{exitCode:W.exitCode,code:W.code})}throw W}}_registerOption($){let _=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(_){let J=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${J}' -- already used by option '${_.flags}'`)}this.options.push($)}_registerCommand($){let _=(U)=>{return[U.name()].concat(U.aliases())},J=_($).find((U)=>this._findCommand(U));if(J){let U=_(this._findCommand(J)).join("|"),W=_($).join("|");throw Error(`cannot add command '${W}' as already have command '${U}'`)}this.commands.push($)}addOption($){this._registerOption($);let _=$.name(),J=$.attributeName();if($.negate){let W=$.long.replace(/^--no-/,"--");if(!this._findOption(W))this.setOptionValueWithSource(J,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(J,$.defaultValue,"default");let U=(W,X,G)=>{if(W==null&&$.presetArg!==void 0)W=$.presetArg;let Q=this.getOptionValue(J);if(W!==null&&$.parseArg)W=this._callParseArg($,W,Q,X);else if(W!==null&&$.variadic)W=$._concatValue(W,Q);if(W==null)if($.negate)W=!1;else if($.isBoolean()||$.optional)W=!0;else W="";this.setOptionValueWithSource(J,W,G)};if(this.on("option:"+_,(W)=>{let X=`error: option '${$.flags}' argument '${W}' is invalid.`;U(W,X,"cli")}),$.envVar)this.on("optionEnv:"+_,(W)=>{let X=`error: option '${$.flags}' value '${W}' from env '${$.envVar}' is invalid.`;U(W,X,"env")});return this}_optionEx($,_,J,U,W){if(typeof _==="object"&&_ instanceof VA)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let X=this.createOption(_,J);if(X.makeOptionMandatory(!!$.mandatory),typeof U==="function")X.default(W).argParser(U);else if(U instanceof RegExp){let G=U;U=(Q,Y)=>{let q=G.exec(Q);return q?q[0]:Y},X.default(W).argParser(U)}else X.default(U);return this.addOption(X)}option($,_,J,U){return this._optionEx({},$,_,J,U)}requiredOption($,_,J,U){return this._optionEx({mandatory:!0},$,_,J,U)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,_){return this.setOptionValueWithSource($,_,void 0)}setOptionValueWithSource($,_,J){if(this._storeOptionsAsProperties)this[$]=_;else this._optionValues[$]=_;return this._optionValueSources[$]=J,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let _;return this._getCommandAndAncestors().forEach((J)=>{if(J.getOptionValueSource($)!==void 0)_=J.getOptionValueSource($)}),_}_prepareUserArgs($,_){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(_=_||{},$===void 0&&_.from===void 0){if(c$.versions?.electron)_.from="electron";let U=c$.execArgv??[];if(U.includes("-e")||U.includes("--eval")||U.includes("-p")||U.includes("--print"))_.from="eval"}if($===void 0)$=c$.argv;this.rawArgs=$.slice();let J;switch(_.from){case void 0:case"node":this._scriptPath=$[1],J=$.slice(2);break;case"electron":if(c$.defaultApp)this._scriptPath=$[1],J=$.slice(2);else J=$.slice(1);break;case"user":J=$.slice(0);break;case"eval":J=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${_.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",J}parse($,_){this._prepareForParse();let J=this._prepareUserArgs($,_);return this._parseCommand([],J),this}async parseAsync($,_){this._prepareForParse();let J=this._prepareUserArgs($,_);return await this._parseCommand([],J),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true. -- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,_,J){if($Q.existsSync($))return;let U=_?`searched for local subcommand relative to directory '${_}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",W=`'${$}' does not exist +(Did you mean ${U[0]}?)`;return""}Wp.suggestSimilar=Jp});var dM=t0((jp)=>{var Xp=i$("events").EventEmitter,OB=i$("child_process"),U0=i$("path"),YY=i$("fs"),n$=i$("process"),{Argument:Gp,humanReadableArgName:Yp}=GY(),{CommanderError:LB}=Y9(),{Help:Qp,stripColor:qp}=jB(),{Option:mM,DualOptions:zp}=DB(),{suggestSimilar:xM}=hM();class HB extends Xp{constructor($){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=$||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(_)=>n$.stdout.write(_),writeErr:(_)=>n$.stderr.write(_),outputError:(_,J)=>J(_),getOutHelpWidth:()=>n$.stdout.isTTY?n$.stdout.columns:void 0,getErrHelpWidth:()=>n$.stderr.isTTY?n$.stderr.columns:void 0,getOutHasColors:()=>BB()??(n$.stdout.isTTY&&n$.stdout.hasColors?.()),getErrHasColors:()=>BB()??(n$.stderr.isTTY&&n$.stderr.hasColors?.()),stripColor:(_)=>qp(_)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let _=this;_;_=_.parent)$.push(_);return $}command($,_,J){let U=_,W=J;if(typeof U==="object"&&U!==null)W=U,U=null;W=W||{};let[,X,G]=$.match(/([^ ]+) *(.*)/),Y=this.createCommand(X);if(U)Y.description(U),Y._executableHandler=!0;if(W.isDefault)this._defaultCommandName=Y._name;if(Y._hidden=!!(W.noHelp||W.hidden),Y._executableFile=W.executableFile||null,G)Y.arguments(G);if(this._registerCommand(Y),Y.parent=this,Y.copyInheritedSettings(this),U)return this;return Y}createCommand($){return new HB($)}createHelp(){return Object.assign(new Qp,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,$),this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,_){if(!$._name)throw Error(`Command passed to .addCommand() must have a name +- specify the name in Command constructor or using .name()`);if(_=_||{},_.isDefault)this._defaultCommandName=$._name;if(_.noHelp||_.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,_){return new Gp($,_)}argument($,_,J,U){let W=this.createArgument($,_);if(typeof J==="function")W.default(U).argParser(J);else W.default(J);return this.addArgument(W),this}arguments($){return $.trim().split(/ +/).forEach((_)=>{this.argument(_)}),this}addArgument($){let _=this.registeredArguments.slice(-1)[0];if(_&&_.variadic)throw Error(`only the last argument can be variadic '${_.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,_){if(typeof $==="boolean")return this._addImplicitHelpCommand=$,this;$=$??"help [command]";let[,J,U]=$.match(/([^ ]+) *(.*)/),W=_??"display help for command",X=this.createCommand(J);if(X.helpOption(!1),U)X.arguments(U);if(W)X.description(W);return this._addImplicitHelpCommand=!0,this._helpCommand=X,this}addHelpCommand($,_){if(typeof $!=="object")return this.helpCommand($,_),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook($,_){let J=["preSubcommand","preAction","postAction"];if(!J.includes($))throw Error(`Unexpected value for event passed to hook : '${$}'. +Expecting one of '${J.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(_);else this._lifeCycleHooks[$]=[_];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(_)=>{if(_.code!=="commander.executeSubCommandAsync")throw _};return this}_exit($,_,J){if(this._exitCallback)this._exitCallback(new LB($,_,J));n$.exit($)}action($){let _=(J)=>{let U=this.registeredArguments.length,W=J.slice(0,U);if(this._storeOptionsAsProperties)W[U]=this;else W[U]=this.opts();return W.push(this),$.apply(this,W)};return this._actionHandler=_,this}createOption($,_){return new mM($,_)}_callParseArg($,_,J,U){try{return $.parseArg(_,J)}catch(W){if(W.code==="commander.invalidArgument"){let X=`${U} ${W.message}`;this.error(X,{exitCode:W.exitCode,code:W.code})}throw W}}_registerOption($){let _=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(_){let J=$.long&&this._findOption($.long)?$.long:$.short;throw Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${J}' +- already used by option '${_.flags}'`)}this.options.push($)}_registerCommand($){let _=(U)=>{return[U.name()].concat(U.aliases())},J=_($).find((U)=>this._findCommand(U));if(J){let U=_(this._findCommand(J)).join("|"),W=_($).join("|");throw Error(`cannot add command '${W}' as already have command '${U}'`)}this.commands.push($)}addOption($){this._registerOption($);let _=$.name(),J=$.attributeName();if($.negate){let W=$.long.replace(/^--no-/,"--");if(!this._findOption(W))this.setOptionValueWithSource(J,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(J,$.defaultValue,"default");let U=(W,X,G)=>{if(W==null&&$.presetArg!==void 0)W=$.presetArg;let Y=this.getOptionValue(J);if(W!==null&&$.parseArg)W=this._callParseArg($,W,Y,X);else if(W!==null&&$.variadic)W=$._concatValue(W,Y);if(W==null)if($.negate)W=!1;else if($.isBoolean()||$.optional)W=!0;else W="";this.setOptionValueWithSource(J,W,G)};if(this.on("option:"+_,(W)=>{let X=`error: option '${$.flags}' argument '${W}' is invalid.`;U(W,X,"cli")}),$.envVar)this.on("optionEnv:"+_,(W)=>{let X=`error: option '${$.flags}' value '${W}' from env '${$.envVar}' is invalid.`;U(W,X,"env")});return this}_optionEx($,_,J,U,W){if(typeof _==="object"&&_ instanceof mM)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let X=this.createOption(_,J);if(X.makeOptionMandatory(!!$.mandatory),typeof U==="function")X.default(W).argParser(U);else if(U instanceof RegExp){let G=U;U=(Y,Q)=>{let q=G.exec(Y);return q?q[0]:Q},X.default(W).argParser(U)}else X.default(U);return this.addOption(X)}option($,_,J,U){return this._optionEx({},$,_,J,U)}requiredOption($,_,J,U){return this._optionEx({mandatory:!0},$,_,J,U)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties($=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,_){return this.setOptionValueWithSource($,_,void 0)}setOptionValueWithSource($,_,J){if(this._storeOptionsAsProperties)this[$]=_;else this._optionValues[$]=_;return this._optionValueSources[$]=J,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let _;return this._getCommandAndAncestors().forEach((J)=>{if(J.getOptionValueSource($)!==void 0)_=J.getOptionValueSource($)}),_}_prepareUserArgs($,_){if($!==void 0&&!Array.isArray($))throw Error("first parameter to parse must be array or undefined");if(_=_||{},$===void 0&&_.from===void 0){if(n$.versions?.electron)_.from="electron";let U=n$.execArgv??[];if(U.includes("-e")||U.includes("--eval")||U.includes("-p")||U.includes("--print"))_.from="eval"}if($===void 0)$=n$.argv;this.rawArgs=$.slice();let J;switch(_.from){case void 0:case"node":this._scriptPath=$[1],J=$.slice(2);break;case"electron":if(n$.defaultApp)this._scriptPath=$[1],J=$.slice(2);else J=$.slice(1);break;case"user":J=$.slice(0);break;case"eval":J=$.slice(1);break;default:throw Error(`unexpected parse option { from: '${_.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",J}parse($,_){this._prepareForParse();let J=this._prepareUserArgs($,_);return this._parseCommand([],J),this}async parseAsync($,_){this._prepareForParse();let J=this._prepareUserArgs($,_);return await this._parseCommand([],J),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true. +- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable($,_,J){if(YY.existsSync($))return;let U=_?`searched for local subcommand relative to directory '${_}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",W=`'${$}' does not exist - if '${J}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - - ${U}`;throw Error(W)}_executeSubCommand($,_){_=_.slice();let J=!1,U=[".js",".ts",".tsx",".mjs",".cjs"];function W(q,L){let N=J1.resolve(q,L);if($Q.existsSync(N))return N;if(U.includes(J1.extname(L)))return;let F=U.find((B)=>$Q.existsSync(`${N}${B}`));if(F)return`${N}${F}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=$._executableFile||`${this._name}-${$._name}`,G=this._executableDir||"";if(this._scriptPath){let q;try{q=$Q.realpathSync(this._scriptPath)}catch{q=this._scriptPath}G=J1.resolve(J1.dirname(q),G)}if(G){let q=W(G,X);if(!q&&!$._executableFile&&this._scriptPath){let L=J1.basename(this._scriptPath,J1.extname(this._scriptPath));if(L!==this._name)q=W(G,`${L}-${$._name}`)}X=q||X}J=U.includes(J1.extname(X));let Q;if(c$.platform!=="win32")if(J)_.unshift(X),_=RA(c$.execArgv).concat(_),Q=_B.spawn(c$.argv[0],_,{stdio:"inherit"});else Q=_B.spawn(X,_,{stdio:"inherit"});else this._checkForMissingExecutable(X,G,$._name),_.unshift(X),_=RA(c$.execArgv).concat(_),Q=_B.spawn(c$.execPath,_,{stdio:"inherit"});if(!Q.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((L)=>{c$.on(L,()=>{if(Q.killed===!1&&Q.exitCode===null)Q.kill(L)})});let Y=this._exitCallback;Q.on("close",(q)=>{if(q=q??1,!Y)c$.exit(q);else Y(new JB(q,"commander.executeSubCommandAsync","(close)"))}),Q.on("error",(q)=>{if(q.code==="ENOENT")this._checkForMissingExecutable(X,G,$._name);else if(q.code==="EACCES")throw Error(`'${X}' not executable`);if(!Y)c$.exit(1);else{let L=new JB(1,"commander.executeSubCommandAsync","(error)");L.nestedError=q,Y(L)}}),this.runningCommand=Q}_dispatchSubcommand($,_,J){let U=this._findCommand($);if(!U)this.help({error:!0});U._prepareForParse();let W;return W=this._chainOrCallSubCommandHook(W,U,"preSubcommand"),W=this._chainOrCall(W,()=>{if(U._executableHandler)this._executeSubCommand(U,_.concat(J));else return U._parseCommand(_,J)}),W}_dispatchHelpCommand($){if(!$)this.help();let _=this._findCommand($);if(_&&!_._executableHandler)_.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,_)=>{if($.required&&this.args[_]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(J,U,W)=>{let X=U;if(U!==null&&J.parseArg){let G=`error: command-argument value '${U}' is invalid for argument '${J.name()}'.`;X=this._callParseArg(J,U,W,G)}return X};this._checkNumberOfArguments();let _=[];this.registeredArguments.forEach((J,U)=>{let W=J.defaultValue;if(J.variadic){if(U{return $(J,G,X)},J.defaultValue)}else if(W===void 0)W=[]}else if(U_());return _()}_chainOrCallHooks($,_){let J=$,U=[];if(this._getCommandAndAncestors().reverse().filter((W)=>W._lifeCycleHooks[_]!==void 0).forEach((W)=>{W._lifeCycleHooks[_].forEach((X)=>{U.push({hookedCommand:W,callback:X})})}),_==="postAction")U.reverse();return U.forEach((W)=>{J=this._chainOrCall(J,()=>{return W.callback(W.hookedCommand,this)})}),J}_chainOrCallSubCommandHook($,_,J){let U=$;if(this._lifeCycleHooks[J]!==void 0)this._lifeCycleHooks[J].forEach((W)=>{U=this._chainOrCall(U,()=>{return W(this,_)})});return U}_parseCommand($,_){let J=this.parseOptions(_);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(J.operands),_=J.unknown,this.args=$.concat(_),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),_);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(_),this._dispatchSubcommand(this._defaultCommandName,$,_);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(J.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let U=()=>{if(J.unknown.length>0)this.unknownOption(J.unknown[0])},W=`command:${this.name()}`;if(this._actionHandler){U(),this._processArguments();let X;if(X=this._chainOrCallHooks(X,"preAction"),X=this._chainOrCall(X,()=>this._actionHandler(this.processedArgs)),this.parent)X=this._chainOrCall(X,()=>{this.parent.emit(W,$,_)});return X=this._chainOrCallHooks(X,"postAction"),X}if(this.parent&&this.parent.listenerCount(W))U(),this._processArguments(),this.parent.emit(W,$,_);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,_);if(this.listenerCount("command:*"))this.emit("command:*",$,_);else if(this.commands.length)this.unknownCommand();else U(),this._processArguments()}else if(this.commands.length)U(),this.help({error:!0});else U(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((_)=>_._name===$||_._aliases.includes($))}_findOption($){return this.options.find((_)=>_.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((_)=>{if(_.mandatory&&$.getOptionValue(_.attributeName())===void 0)$.missingMandatoryOptionValue(_)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((J)=>{let U=J.attributeName();if(this.getOptionValue(U)===void 0)return!1;return this.getOptionValueSource(U)!=="default"});$.filter((J)=>J.conflictsWith.length>0).forEach((J)=>{let U=$.find((W)=>J.conflictsWith.includes(W.attributeName()));if(U)this._conflictingOption(J,U)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let _=[],J=[],U=_,W=$.slice();function X(Q){return Q.length>1&&Q[0]==="-"}let G=null;while(W.length){let Q=W.shift();if(Q==="--"){if(U===J)U.push(Q);U.push(...W);break}if(G&&!X(Q)){this.emit(`option:${G.name()}`,Q);continue}if(G=null,X(Q)){let Y=this._findOption(Q);if(Y){if(Y.required){let q=W.shift();if(q===void 0)this.optionMissingArgument(Y);this.emit(`option:${Y.name()}`,q)}else if(Y.optional){let q=null;if(W.length>0&&!X(W[0]))q=W.shift();this.emit(`option:${Y.name()}`,q)}else this.emit(`option:${Y.name()}`);G=Y.variadic?Y:null;continue}}if(Q.length>2&&Q[0]==="-"&&Q[1]!=="-"){let Y=this._findOption(`-${Q[1]}`);if(Y){if(Y.required||Y.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${Y.name()}`,Q.slice(2));else this.emit(`option:${Y.name()}`),W.unshift(`-${Q.slice(2)}`);continue}}if(/^--[^=]+=/.test(Q)){let Y=Q.indexOf("="),q=this._findOption(Q.slice(0,Y));if(q&&(q.required||q.optional)){this.emit(`option:${q.name()}`,Q.slice(Y+1));continue}}if(X(Q))U=J;if((this._enablePositionalOptions||this._passThroughOptions)&&_.length===0&&J.length===0){if(this._findCommand(Q)){if(_.push(Q),W.length>0)J.push(...W);break}else if(this._getHelpCommand()&&Q===this._getHelpCommand().name()){if(_.push(Q),W.length>0)_.push(...W);break}else if(this._defaultCommandName){if(J.push(Q),W.length>0)J.push(...W);break}}if(this._passThroughOptions){if(U.push(Q),W.length>0)U.push(...W);break}U.push(Q)}return{operands:_,unknown:J}}opts(){if(this._storeOptionsAsProperties){let $={},_=this.options.length;for(let J=0;J<_;J++){let U=this.options[J].attributeName();$[U]=U===this._versionOptionName?this._version:this[U]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,_)=>Object.assign($,_.opts()),{})}error($,_){if(this._outputConfiguration.outputError(`${$} + - ${U}`;throw Error(W)}_executeSubCommand($,_){_=_.slice();let J=!1,U=[".js",".ts",".tsx",".mjs",".cjs"];function W(q,L){let N=U0.resolve(q,L);if(YY.existsSync(N))return N;if(U.includes(U0.extname(L)))return;let R=U.find((B)=>YY.existsSync(`${N}${B}`));if(R)return`${N}${R}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=$._executableFile||`${this._name}-${$._name}`,G=this._executableDir||"";if(this._scriptPath){let q;try{q=YY.realpathSync(this._scriptPath)}catch{q=this._scriptPath}G=U0.resolve(U0.dirname(q),G)}if(G){let q=W(G,X);if(!q&&!$._executableFile&&this._scriptPath){let L=U0.basename(this._scriptPath,U0.extname(this._scriptPath));if(L!==this._name)q=W(G,`${L}-${$._name}`)}X=q||X}J=U.includes(U0.extname(X));let Y;if(n$.platform!=="win32")if(J)_.unshift(X),_=uM(n$.execArgv).concat(_),Y=OB.spawn(n$.argv[0],_,{stdio:"inherit"});else Y=OB.spawn(X,_,{stdio:"inherit"});else this._checkForMissingExecutable(X,G,$._name),_.unshift(X),_=uM(n$.execArgv).concat(_),Y=OB.spawn(n$.execPath,_,{stdio:"inherit"});if(!Y.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((L)=>{n$.on(L,()=>{if(Y.killed===!1&&Y.exitCode===null)Y.kill(L)})});let Q=this._exitCallback;Y.on("close",(q)=>{if(q=q??1,!Q)n$.exit(q);else Q(new LB(q,"commander.executeSubCommandAsync","(close)"))}),Y.on("error",(q)=>{if(q.code==="ENOENT")this._checkForMissingExecutable(X,G,$._name);else if(q.code==="EACCES")throw Error(`'${X}' not executable`);if(!Q)n$.exit(1);else{let L=new LB(1,"commander.executeSubCommandAsync","(error)");L.nestedError=q,Q(L)}}),this.runningCommand=Y}_dispatchSubcommand($,_,J){let U=this._findCommand($);if(!U)this.help({error:!0});U._prepareForParse();let W;return W=this._chainOrCallSubCommandHook(W,U,"preSubcommand"),W=this._chainOrCall(W,()=>{if(U._executableHandler)this._executeSubCommand(U,_.concat(J));else return U._parseCommand(_,J)}),W}_dispatchHelpCommand($){if(!$)this.help();let _=this._findCommand($);if(_&&!_._executableHandler)_.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,_)=>{if($.required&&this.args[_]==null)this.missingArgument($.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let $=(J,U,W)=>{let X=U;if(U!==null&&J.parseArg){let G=`error: command-argument value '${U}' is invalid for argument '${J.name()}'.`;X=this._callParseArg(J,U,W,G)}return X};this._checkNumberOfArguments();let _=[];this.registeredArguments.forEach((J,U)=>{let W=J.defaultValue;if(J.variadic){if(U{return $(J,G,X)},J.defaultValue)}else if(W===void 0)W=[]}else if(U_());return _()}_chainOrCallHooks($,_){let J=$,U=[];if(this._getCommandAndAncestors().reverse().filter((W)=>W._lifeCycleHooks[_]!==void 0).forEach((W)=>{W._lifeCycleHooks[_].forEach((X)=>{U.push({hookedCommand:W,callback:X})})}),_==="postAction")U.reverse();return U.forEach((W)=>{J=this._chainOrCall(J,()=>{return W.callback(W.hookedCommand,this)})}),J}_chainOrCallSubCommandHook($,_,J){let U=$;if(this._lifeCycleHooks[J]!==void 0)this._lifeCycleHooks[J].forEach((W)=>{U=this._chainOrCall(U,()=>{return W(this,_)})});return U}_parseCommand($,_){let J=this.parseOptions(_);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(J.operands),_=J.unknown,this.args=$.concat(_),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),_);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(_),this._dispatchSubcommand(this._defaultCommandName,$,_);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(J.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let U=()=>{if(J.unknown.length>0)this.unknownOption(J.unknown[0])},W=`command:${this.name()}`;if(this._actionHandler){U(),this._processArguments();let X;if(X=this._chainOrCallHooks(X,"preAction"),X=this._chainOrCall(X,()=>this._actionHandler(this.processedArgs)),this.parent)X=this._chainOrCall(X,()=>{this.parent.emit(W,$,_)});return X=this._chainOrCallHooks(X,"postAction"),X}if(this.parent&&this.parent.listenerCount(W))U(),this._processArguments(),this.parent.emit(W,$,_);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,_);if(this.listenerCount("command:*"))this.emit("command:*",$,_);else if(this.commands.length)this.unknownCommand();else U(),this._processArguments()}else if(this.commands.length)U(),this.help({error:!0});else U(),this._processArguments()}_findCommand($){if(!$)return;return this.commands.find((_)=>_._name===$||_._aliases.includes($))}_findOption($){return this.options.find((_)=>_.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((_)=>{if(_.mandatory&&$.getOptionValue(_.attributeName())===void 0)$.missingMandatoryOptionValue(_)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((J)=>{let U=J.attributeName();if(this.getOptionValue(U)===void 0)return!1;return this.getOptionValueSource(U)!=="default"});$.filter((J)=>J.conflictsWith.length>0).forEach((J)=>{let U=$.find((W)=>J.conflictsWith.includes(W.attributeName()));if(U)this._conflictingOption(J,U)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let _=[],J=[],U=_,W=$.slice();function X(Y){return Y.length>1&&Y[0]==="-"}let G=null;while(W.length){let Y=W.shift();if(Y==="--"){if(U===J)U.push(Y);U.push(...W);break}if(G&&!X(Y)){this.emit(`option:${G.name()}`,Y);continue}if(G=null,X(Y)){let Q=this._findOption(Y);if(Q){if(Q.required){let q=W.shift();if(q===void 0)this.optionMissingArgument(Q);this.emit(`option:${Q.name()}`,q)}else if(Q.optional){let q=null;if(W.length>0&&!X(W[0]))q=W.shift();this.emit(`option:${Q.name()}`,q)}else this.emit(`option:${Q.name()}`);G=Q.variadic?Q:null;continue}}if(Y.length>2&&Y[0]==="-"&&Y[1]!=="-"){let Q=this._findOption(`-${Y[1]}`);if(Q){if(Q.required||Q.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${Q.name()}`,Y.slice(2));else this.emit(`option:${Q.name()}`),W.unshift(`-${Y.slice(2)}`);continue}}if(/^--[^=]+=/.test(Y)){let Q=Y.indexOf("="),q=this._findOption(Y.slice(0,Q));if(q&&(q.required||q.optional)){this.emit(`option:${q.name()}`,Y.slice(Q+1));continue}}if(X(Y))U=J;if((this._enablePositionalOptions||this._passThroughOptions)&&_.length===0&&J.length===0){if(this._findCommand(Y)){if(_.push(Y),W.length>0)J.push(...W);break}else if(this._getHelpCommand()&&Y===this._getHelpCommand().name()){if(_.push(Y),W.length>0)_.push(...W);break}else if(this._defaultCommandName){if(J.push(Y),W.length>0)J.push(...W);break}}if(this._passThroughOptions){if(U.push(Y),W.length>0)U.push(...W);break}U.push(Y)}return{operands:_,unknown:J}}opts(){if(this._storeOptionsAsProperties){let $={},_=this.options.length;for(let J=0;J<_;J++){let U=this.options[J].attributeName();$[U]=U===this._versionOptionName?this._version:this[U]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,_)=>Object.assign($,_.opts()),{})}error($,_){if(this._outputConfiguration.outputError(`${$} `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError} `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(` -`),this.outputHelp({error:!0});let J=_||{},U=J.exitCode||1,W=J.code||"commander.error";this._exit(U,W,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in c$.env){let _=$.attributeName();if(this.getOptionValue(_)===void 0||["default","config","env"].includes(this.getOptionValueSource(_)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,c$.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new Tr(this.options),_=(J)=>{return this.getOptionValue(J)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(J))};this.options.filter((J)=>J.implied!==void 0&&_(J.attributeName())&&$.valueFromOption(this.getOptionValue(J.attributeName()),J)).forEach((J)=>{Object.keys(J.implied).filter((U)=>!_(U)).forEach((U)=>{this.setOptionValueWithSource(U,J.implied[U],"implied")})})}missingArgument($){let _=`error: missing required argument '${$}'`;this.error(_,{code:"commander.missingArgument"})}optionMissingArgument($){let _=`error: option '${$.flags}' argument missing`;this.error(_,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let _=`error: required option '${$.flags}' not specified`;this.error(_,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,_){let J=(X)=>{let G=X.attributeName(),Q=this.getOptionValue(G),Y=this.options.find((L)=>L.negate&&G===L.attributeName()),q=this.options.find((L)=>!L.negate&&G===L.attributeName());if(Y&&(Y.presetArg===void 0&&Q===!1||Y.presetArg!==void 0&&Q===Y.presetArg))return Y;return q||X},U=(X)=>{let G=J(X),Q=G.attributeName();if(this.getOptionValueSource(Q)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},W=`error: ${U($)} cannot be used with ${U(_)}`;this.error(W,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let _="";if($.startsWith("--")&&this._showSuggestionAfterError){let U=[],W=this;do{let X=W.createHelp().visibleOptions(W).filter((G)=>G.long).map((G)=>G.long);U=U.concat(X),W=W.parent}while(W&&!W._enablePositionalOptions);_=FA($,U)}let J=`error: unknown option '${$}'${_}`;this.error(J,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let _=this.registeredArguments.length,J=_===1?"":"s",W=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${_} argument${J} but got ${$.length}.`;this.error(W,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],_="";if(this._showSuggestionAfterError){let U=[];this.createHelp().visibleCommands(this).forEach((W)=>{if(U.push(W.name()),W.alias())U.push(W.alias())}),_=FA($,U)}let J=`error: unknown command '${$}'${_}`;this.error(J,{code:"commander.unknownCommand"})}version($,_,J){if($===void 0)return this._version;this._version=$,_=_||"-V, --version",J=J||"output the version number";let U=this.createOption(_,J);return this._versionOptionName=U.attributeName(),this._registerOption(U),this.on("option:"+U.name(),()=>{this._outputConfiguration.writeOut(`${$} -`),this._exit(0,"commander.version",$)}),this}description($,_){if($===void 0&&_===void 0)return this._description;if(this._description=$,_)this._argsDescription=_;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let _=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)_=this.commands[this.commands.length-1];if($===_._name)throw Error("Command alias can't be the same as its name");let J=this.parent?._findCommand($);if(J){let U=[J.name()].concat(J.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${U}'`)}return _._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((_)=>this.alias(_)),this}usage($){if($===void 0){if(this._usage)return this._usage;let _=this.registeredArguments.map((J)=>{return fr(J)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?_:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=J1.basename($,J1.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let _=this.createHelp(),J=this._getOutputContext($);_.prepareContext({error:J.error,helpWidth:J.helpWidth,outputHasColors:J.hasColors});let U=_.formatHelp(this,_);if(J.hasColors)return U;return this._outputConfiguration.stripColor(U)}_getOutputContext($){$=$||{};let _=!!$.error,J,U,W;if(_)J=(G)=>this._outputConfiguration.writeErr(G),U=this._outputConfiguration.getErrHasColors(),W=this._outputConfiguration.getErrHelpWidth();else J=(G)=>this._outputConfiguration.writeOut(G),U=this._outputConfiguration.getOutHasColors(),W=this._outputConfiguration.getOutHelpWidth();return{error:_,write:(G)=>{if(!U)G=this._outputConfiguration.stripColor(G);return J(G)},hasColors:U,helpWidth:W}}outputHelp($){let _;if(typeof $==="function")_=$,$=void 0;let J=this._getOutputContext($),U={error:J.error,write:J.write,command:this};this._getCommandAndAncestors().reverse().forEach((X)=>X.emit("beforeAllHelp",U)),this.emit("beforeHelp",U);let W=this.helpInformation({error:J.error});if(_){if(W=_(W),typeof W!=="string"&&!Buffer.isBuffer(W))throw Error("outputHelp callback must return a string or a Buffer")}if(J.write(W),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",U),this._getCommandAndAncestors().forEach((X)=>X.emit("afterAllHelp",U))}helpOption($,_){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",_=_??"display help for command",this._helpOption=this.createOption($,_),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let _=Number(c$.exitCode??0);if(_===0&&$&&typeof $!=="function"&&$.error)_=1;this._exit(_,"commander.help","(outputHelp)")}addHelpText($,_){let J=["beforeAll","before","after","afterAll"];if(!J.includes($))throw Error(`Unexpected value for position to addHelpText. +`),this.outputHelp({error:!0});let J=_||{},U=J.exitCode||1,W=J.code||"commander.error";this._exit(U,W,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in n$.env){let _=$.attributeName();if(this.getOptionValue(_)===void 0||["default","config","env"].includes(this.getOptionValueSource(_)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,n$.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new zp(this.options),_=(J)=>{return this.getOptionValue(J)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(J))};this.options.filter((J)=>J.implied!==void 0&&_(J.attributeName())&&$.valueFromOption(this.getOptionValue(J.attributeName()),J)).forEach((J)=>{Object.keys(J.implied).filter((U)=>!_(U)).forEach((U)=>{this.setOptionValueWithSource(U,J.implied[U],"implied")})})}missingArgument($){let _=`error: missing required argument '${$}'`;this.error(_,{code:"commander.missingArgument"})}optionMissingArgument($){let _=`error: option '${$.flags}' argument missing`;this.error(_,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let _=`error: required option '${$.flags}' not specified`;this.error(_,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,_){let J=(X)=>{let G=X.attributeName(),Y=this.getOptionValue(G),Q=this.options.find((L)=>L.negate&&G===L.attributeName()),q=this.options.find((L)=>!L.negate&&G===L.attributeName());if(Q&&(Q.presetArg===void 0&&Y===!1||Q.presetArg!==void 0&&Y===Q.presetArg))return Q;return q||X},U=(X)=>{let G=J(X),Y=G.attributeName();if(this.getOptionValueSource(Y)==="env")return`environment variable '${G.envVar}'`;return`option '${G.flags}'`},W=`error: ${U($)} cannot be used with ${U(_)}`;this.error(W,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let _="";if($.startsWith("--")&&this._showSuggestionAfterError){let U=[],W=this;do{let X=W.createHelp().visibleOptions(W).filter((G)=>G.long).map((G)=>G.long);U=U.concat(X),W=W.parent}while(W&&!W._enablePositionalOptions);_=xM($,U)}let J=`error: unknown option '${$}'${_}`;this.error(J,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let _=this.registeredArguments.length,J=_===1?"":"s",W=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${_} argument${J} but got ${$.length}.`;this.error(W,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],_="";if(this._showSuggestionAfterError){let U=[];this.createHelp().visibleCommands(this).forEach((W)=>{if(U.push(W.name()),W.alias())U.push(W.alias())}),_=xM($,U)}let J=`error: unknown command '${$}'${_}`;this.error(J,{code:"commander.unknownCommand"})}version($,_,J){if($===void 0)return this._version;this._version=$,_=_||"-V, --version",J=J||"output the version number";let U=this.createOption(_,J);return this._versionOptionName=U.attributeName(),this._registerOption(U),this.on("option:"+U.name(),()=>{this._outputConfiguration.writeOut(`${$} +`),this._exit(0,"commander.version",$)}),this}description($,_){if($===void 0&&_===void 0)return this._description;if(this._description=$,_)this._argsDescription=_;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let _=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)_=this.commands[this.commands.length-1];if($===_._name)throw Error("Command alias can't be the same as its name");let J=this.parent?._findCommand($);if(J){let U=[J.name()].concat(J.aliases()).join("|");throw Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${U}'`)}return _._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((_)=>this.alias(_)),this}usage($){if($===void 0){if(this._usage)return this._usage;let _=this.registeredArguments.map((J)=>{return Yp(J)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?_:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}nameFromFilename($){return this._name=U0.basename($,U0.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let _=this.createHelp(),J=this._getOutputContext($);_.prepareContext({error:J.error,helpWidth:J.helpWidth,outputHasColors:J.hasColors});let U=_.formatHelp(this,_);if(J.hasColors)return U;return this._outputConfiguration.stripColor(U)}_getOutputContext($){$=$||{};let _=!!$.error,J,U,W;if(_)J=(G)=>this._outputConfiguration.writeErr(G),U=this._outputConfiguration.getErrHasColors(),W=this._outputConfiguration.getErrHelpWidth();else J=(G)=>this._outputConfiguration.writeOut(G),U=this._outputConfiguration.getOutHasColors(),W=this._outputConfiguration.getOutHelpWidth();return{error:_,write:(G)=>{if(!U)G=this._outputConfiguration.stripColor(G);return J(G)},hasColors:U,helpWidth:W}}outputHelp($){let _;if(typeof $==="function")_=$,$=void 0;let J=this._getOutputContext($),U={error:J.error,write:J.write,command:this};this._getCommandAndAncestors().reverse().forEach((X)=>X.emit("beforeAllHelp",U)),this.emit("beforeHelp",U);let W=this.helpInformation({error:J.error});if(_){if(W=_(W),typeof W!=="string"&&!Buffer.isBuffer(W))throw Error("outputHelp callback must return a string or a Buffer")}if(J.write(W),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",U),this._getCommandAndAncestors().forEach((X)=>X.emit("afterAllHelp",U))}helpOption($,_){if(typeof $==="boolean"){if($)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return $=$??"-h, --help",_=_??"display help for command",this._helpOption=this.createOption($,_),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this}help($){this.outputHelp($);let _=Number(n$.exitCode??0);if(_===0&&$&&typeof $!=="function"&&$.error)_=1;this._exit(_,"commander.help","(outputHelp)")}addHelpText($,_){let J=["beforeAll","before","after","afterAll"];if(!J.includes($))throw Error(`Unexpected value for position to addHelpText. Expecting one of '${J.join("', '")}'`);let U=`${$}Help`;return this.on(U,(W)=>{let X;if(typeof _==="function")X=_({error:W.error,command:W.command});else X=_;if(X)W.write(`${X} -`)}),this}_outputHelpIfRequested($){let _=this._getHelpOption();if(_&&$.find((U)=>_.is(U)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function RA($){return $.map((_)=>{if(!_.startsWith("--inspect"))return _;let J,U="127.0.0.1",W="9229",X;if((X=_.match(/^(--inspect(-brk)?)$/))!==null)J=X[1];else if((X=_.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(J=X[1],/^\d+$/.test(X[3]))W=X[3];else U=X[3];else if((X=_.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)J=X[1],U=X[3],W=X[4];if(J&&W!=="0")return`${J}=${U}:${parseInt(W)+1}`;return _})}function WB(){if(c$.env.NO_COLOR||c$.env.FORCE_COLOR==="0"||c$.env.FORCE_COLOR==="false")return!1;if(c$.env.FORCE_COLOR||c$.env.CLICOLOR_FORCE!==void 0)return!0;return}Sr.Command=UB;Sr.useColor=WB});var EA=i1((mr)=>{var{Argument:MA}=e5(),{Command:XB}=KA(),{CommanderError:yr,InvalidArgumentError:AA}=J9(),{Help:hr}=eL(),{Option:bA}=$B();mr.program=new XB;mr.createCommand=($)=>new XB($);mr.createOption=($,_)=>new bA($,_);mr.createArgument=($,_)=>new MA($,_);mr.Command=XB;mr.Option=bA;mr.Argument=MA;mr.Help=hr;mr.CommanderError=yr;mr.InvalidArgumentError=AA;mr.InvalidOptionArgumentError=AA});import{chmodSync as bB,closeSync as hW,existsSync as M_,fsyncSync as NQ,lstatSync as Vb,openSync as VQ,readFileSync as mW,renameSync as EB,unlinkSync as FQ,writeFileSync as RQ}from"fs";import{randomUUID as xW}from"crypto";import{basename as Fb,dirname as wB,join as HQ}from"path";import{chmodSync as BB,existsSync as Db,mkdirSync as qQ,readFileSync as Lb,writeFileSync as HB}from"fs";import{homedir as zQ}from"os";import{dirname as Bb,join as g6,resolve as NB}from"path";var F0=g6(".hasna","knowledge"),VB=g6(".hasna","apps","knowledge"),r$={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:F0,s3:{bucket:"example-knowledge-prod",region:"us-east-1",profile:"example-infra",prefix:".hasna/knowledge",server_side_encryption:"AES256"},secrets:{env:"example/knowledge/prod/env",aws:"example/knowledge/prod/aws",s3:"example/knowledge/prod/s3",rds:null,future_rds:"example/knowledge/prod/rds"},source_owner:"open-files",evidence_doc:"docs/canonical-secrets-bootstrap-2026-06-08.md"};function FB(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:r$.s3.bucket,prefix:r$.s3.prefix,region:r$.s3.region,profile:r$.s3.profile,server_side_encryption:r$.s3.server_side_encryption}}}function vW(){return g6(zQ(),".open-knowledge","db.json")}function Q9(){return g6(zQ(),".hasna","knowledge")}function jQ($=process.cwd()){return NB($,F0)}function Hb(){return g6(zQ(),VB)}function Nb($=process.cwd()){return NB($,VB)}function OQ($,_=process.cwd()){if($==="project"||$==="local")return a6(Nb(_));return a6(Hb())}function a6($){return{home:$,configPath:g6($,"config.json"),jsonStorePath:g6($,"db.json"),knowledgeDbPath:g6($,"knowledge.db"),artifactsDir:g6($,"artifacts"),cacheDir:g6($,"cache"),exportsDir:g6($,"exports"),indexesDir:g6($,"indexes"),logsDir:g6($,"logs"),runsDir:g6($,"runs"),schemasDir:g6($,"schemas"),wikiDir:g6($,"wiki")}}function yW(){return{version:1,mode:"local",hosted:{api_url:"https://knowledge.md"},storage:{type:"local",artifacts_root:"artifacts"},sources:{preferred_ref:"open-files",allowed_schemes:["open-files","s3","file","https","http"]},providers:{default_model:"openai:gpt-5.2",aliases:{fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"},openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},embeddings:{default_model:"openai:text-embedding-3-small",dimensions:1536,batch_size:64,max_parallel_calls:4},safety:{network:{web_search_enabled:!1,s3_reads_enabled:!1,allowed_s3_buckets:[]},redaction:{enabled:!0},approvals:{generated_writes_require_approval:!0}}}}function K_($){let _=a6($);qQ(_.home,{recursive:!0,mode:448});for(let J of[_.artifactsDir,_.cacheDir,_.exportsDir,_.indexesDir,_.logsDir,_.runsDir,_.schemasDir,_.wikiDir])qQ(J,{recursive:!0,mode:448});if(!Db(_.configPath))HB(_.configPath,`${JSON.stringify(yW(),null,2)} -`,{mode:384}),BB(_.configPath,384);return _}function Y9($,_=process.cwd()){if($==="project"||$==="local")return a6(jQ(_));return a6(Q9())}function U1($){qQ(Bb($),{recursive:!0})}function DQ($){let _=Lb($,"utf8");return JSON.parse(_)}function RB($,_){U1($),HB($,`${JSON.stringify(_,null,2)} -`,{mode:384}),BB($,384)}function z9(){return a6(Q9()).jsonStorePath}function uW($){if($===z9()&&M_(vW()))MQ();if(!M_($))U1($),kB($,`${JSON.stringify({items:[]},null,2)} -`)}function Rb($){return $.toISOString().replace(/[:.]/g,"-")}function KQ($){let _=[`id:${$.id}`];if(typeof $.short_id==="string"&&$.short_id.length>0)_.push(`short_id:${$.short_id}`);return _}function Kb($){let _=new Set;for(let J of $)for(let U of KQ(J))_.add(U);return _}function Mb($,_){return KQ(_).some((J)=>$.has(J))}function LQ($,_){U1($),RQ($,`${JSON.stringify(_,null,2)} -`,{mode:384}),bB($,384)}function KB($){let _=JSON.parse(mW($,"utf8"));if(!_||typeof _!=="object"||!Array.isArray(_.items))return{store:{items:[]},skippedInvalid:0};let J={items:[]},U=0;for(let W of _.items)if(W&&typeof W==="object"&&typeof W.id==="string"&&W.id.length>0)J.items.push(W);else U+=1;return{store:J,skippedInvalid:U}}function MQ($={}){if($.dryRun===!0)return MB($);return e4(z9(),()=>MB($),{createParent:!0})}function MB($={}){let _=$.dryRun===!0,J=$.now??new Date,U=a6(Q9()),W=vW(),X=U.jsonStorePath,G=M_(W),Q=M_(X),Y={ok:!0,dry_run:_,legacy_path:W,canonical_path:X,legacy_exists:G,canonical_existed:Q,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:G?"Legacy global store already imported":"No legacy global store found"};if(!G)return Y;let q;try{let H=KB(W);q=H.store,Y.skipped_invalid=H.skippedInvalid}catch(H){return Y.ok=!1,Y.errors.push(`Could not read legacy store: ${H instanceof Error?H.message:String(H)}`),Y.message="Legacy global store import failed",Y}let L={items:[]};if(Q)try{L=KB(X).store}catch(H){return Y.ok=!1,Y.errors.push(`Could not read canonical store: ${H instanceof Error?H.message:String(H)}`),Y.message="Legacy global store import failed",Y}let N=Kb(L.items),F={items:[...L.items]};for(let H of q.items){if(!H?.id){Y.skipped_invalid+=1;continue}if(Mb(N,H)){Y.skipped_existing+=1;continue}F.items.push(H);for(let V of KQ(H))N.add(V);Y.imported+=1}if(Y.would_create_canonical=!Q&&Y.imported>0,Y.canonical_created=!_&&Y.would_create_canonical,Y.message=Y.imported>0?`Imported ${Y.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",_||Y.imported===0)return Y;let B=`${Rb(J)}-${xW().slice(0,8)}`;if(Q)Y.backup_path=HQ(U.exportsDir,`legacy-open-knowledge-db-before-import-${B}.json`),LQ(Y.backup_path,L);return LQ(X,F),Y.report_path=HQ(U.runsDir,`legacy-open-knowledge-import-${B}.json`),LQ(Y.report_path,Y),Y}function A_($){if(!M_($))return{exists:!1,items:[]};let _=mW($,"utf8"),J=JSON.parse(_);if(!J||!Array.isArray(J.items))return{exists:!0,items:[]};return{exists:!0,items:J.items}}function Ab($){return`${$}.lock`}var q9=1e4,IB=25,AB=120000,bb=new Int32Array(new SharedArrayBuffer(4));function AQ($){return typeof $==="object"&&$!==null&&"code"in $?String($.code):void 0}function gB($){let _=null;try{_=VQ(wB($),"r"),NQ(_)}catch{}finally{if(_!==null)try{hW(_)}catch{}}}var BQ=new Set;function kB($,_){U1($);let J=HQ(wB($),`.${Fb($)}.tmp.${xW()}`),U=null;try{U=VQ(J,"wx",384),RQ(U,_),NQ(U),hW(U),U=null,EB(J,$);try{bB($,384)}catch{}gB($)}catch(W){if(U!==null)try{hW(U)}catch{}try{FQ(J)}catch{}throw W}}function fB($){Atomics.wait(bb,0,0,$)}function Eb($){if(typeof $!=="number"||!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch(_){return AQ(_)!=="ESRCH"}}function CB($,_){try{let J=mW($,"utf8"),U=JSON.parse(J);if(typeof U.ts==="number")return _-U.ts>AB&&!Eb(U.pid)}catch{}try{return _-Vb($).mtimeMs>AB}catch{return!1}}function wb($){let _=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),J=`${$}.stale.${_}.${xW()}`;try{EB($,J)}catch(U){if(AQ(U)!=="ENOENT")throw U;return}}function Ib($){let _=xW(),J=`${$}.breaker`,U=Date.now();while(Date.now()-U$;function Cb($,_){this[$]=fb.bind(null,_)}var Pb=($,_)=>{for(var J in _)kb($,J,{get:_[J],enumerable:!0,configurable:!0,set:Cb.bind(_,J)})},z={};Pb(z,{void:()=>HE,util:()=>y$,unknown:()=>LE,union:()=>RE,undefined:()=>jE,tuple:()=>AE,transformer:()=>hB,symbol:()=>zE,string:()=>pB,strictObject:()=>FE,setErrorMap:()=>Zb,set:()=>wE,record:()=>bE,quotelessJson:()=>Tb,promise:()=>PE,preprocess:()=>ZE,pipeline:()=>vE,ostring:()=>yE,optional:()=>TE,onumber:()=>hE,oboolean:()=>mE,objectUtil:()=>gQ,object:()=>VE,number:()=>oB,nullable:()=>SE,null:()=>OE,never:()=>BE,nativeEnum:()=>CE,nan:()=>QE,map:()=>EE,makeIssue:()=>D9,literal:()=>kE,lazy:()=>gE,late:()=>XE,isValid:()=>r1,isDirty:()=>fQ,isAsync:()=>cW,isAborted:()=>kQ,intersection:()=>ME,instanceof:()=>GE,getParsedType:()=>M0,getErrorMap:()=>O9,function:()=>IE,enum:()=>fE,effect:()=>hB,discriminatedUnion:()=>KE,defaultErrorMap:()=>I_,datetimeRegex:()=>nB,date:()=>qE,custom:()=>rB,coerce:()=>xE,boolean:()=>tB,bigint:()=>YE,array:()=>NE,any:()=>DE,addIssueToContext:()=>u,ZodVoid:()=>nW,ZodUnknown:()=>X1,ZodUnion:()=>C_,ZodUndefined:()=>k_,ZodType:()=>g$,ZodTuple:()=>_0,ZodTransformer:()=>j4,ZodSymbol:()=>lW,ZodString:()=>M4,ZodSet:()=>t1,ZodSchema:()=>g$,ZodRecord:()=>iW,ZodReadonly:()=>h_,ZodPromise:()=>a1,ZodPipeline:()=>oW,ZodParsedType:()=>r,ZodOptional:()=>b4,ZodObject:()=>D6,ZodNumber:()=>G1,ZodNullable:()=>A0,ZodNull:()=>f_,ZodNever:()=>$0,ZodNativeEnum:()=>Z_,ZodNaN:()=>pW,ZodMap:()=>rW,ZodLiteral:()=>S_,ZodLazy:()=>T_,ZodIssueCode:()=>P,ZodIntersection:()=>P_,ZodFunction:()=>w_,ZodFirstPartyTypeKind:()=>O$,ZodError:()=>s6,ZodEnum:()=>Y1,ZodEffects:()=>j4,ZodDiscriminatedUnion:()=>B9,ZodDefault:()=>v_,ZodDate:()=>p1,ZodCatch:()=>y_,ZodBranded:()=>H9,ZodBoolean:()=>g_,ZodBigInt:()=>Q1,ZodArray:()=>A4,ZodAny:()=>o1,Schema:()=>g$,ParseStatus:()=>k6,OK:()=>m6,NEVER:()=>uE,INVALID:()=>Y$,EMPTY_PATH:()=>vb,DIRTY:()=>E_,BRAND:()=>UE});var y$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Q)=>typeof W[W[Q]]!=="number"),G={};for(let Q of X)G[Q]=W[Q];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(y$||(y$={}));var gQ;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(gQ||(gQ={}));var r=y$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),M0=($)=>{switch(typeof $){case"undefined":return r.undefined;case"string":return r.string;case"number":return Number.isNaN($)?r.nan:r.number;case"boolean":return r.boolean;case"function":return r.function;case"bigint":return r.bigint;case"symbol":return r.symbol;case"object":if(Array.isArray($))return r.array;if($===null)return r.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return r.promise;if(typeof Map<"u"&&$ instanceof Map)return r.map;if(typeof Set<"u"&&$ instanceof Set)return r.set;if(typeof Date<"u"&&$ instanceof Date)return r.date;return r.object;default:return r.unknown}},P=y$.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"]),Tb=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class s6 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Q=0;while(Q_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}s6.create=($)=>{return new s6($)};var Sb=($,_)=>{let J;switch($.code){case P.invalid_type:if($.received===r.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case P.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,y$.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:J=`Unrecognized key(s) in object: ${y$.joinValues($.keys,", ")}`;break;case P.invalid_union:J="Invalid input";break;case P.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${y$.joinValues($.options)}`;break;case P.invalid_enum_value:J=`Invalid enum value. Expected ${y$.joinValues($.options)}, received '${$.received}'`;break;case P.invalid_arguments:J="Invalid function arguments";break;case P.invalid_return_type:J="Invalid function return type";break;case P.invalid_date:J="Invalid date";break;case P.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else y$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case P.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case P.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case P.custom:J="Invalid input";break;case P.invalid_intersection_types:J="Intersection results could not be merged";break;case P.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case P.not_finite:J="Number must be finite";break;default:J=_.defaultError,y$.assertNever($)}return{message:J}},I_=Sb,dB=I_;function Zb($){dB=$}function O9(){return dB}var D9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Q="",Y=U.filter((q)=>!!q).slice().reverse();for(let q of Y)Q=q(G,{data:_,defaultError:Q}).message;return{...W,path:X,message:Q}},vb=[];function u($,_){let J=O9(),U=D9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===I_?void 0:I_].filter((W)=>!!W)});$.common.issues.push(U)}class k6{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return Y$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return k6.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return Y$;if(X.status==="aborted")return Y$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var Y$=Object.freeze({status:"aborted"}),E_=($)=>({status:"dirty",value:$}),m6=($)=>({status:"valid",value:$}),kQ=($)=>$.status==="aborted",fQ=($)=>$.status==="dirty",r1=($)=>$.status==="valid",cW=($)=>typeof Promise<"u"&&$ instanceof Promise,$$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})($$||($$={}));class E4{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var vB=($,_)=>{if(r1(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new s6($.common.issues);return this._error=J,this._error}}}};function A$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Q)=>{let{message:Y}=$;if(G.code==="invalid_enum_value")return{message:Y??Q.defaultError};if(typeof Q.data>"u")return{message:Y??U??Q.defaultError};if(G.code!=="invalid_type")return{message:Q.defaultError};return{message:Y??J??Q.defaultError}},description:W}}class g${get description(){return this._def.description}_getType($){return M0($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:M0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new k6,ctx:{common:$.parent.common,data:$.data,parsedType:M0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(cW(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M0($)},U=this._parseSync({data:$,path:J.path,parent:J});return vB(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M0($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return r1(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>r1(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M0($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(cW(U)?U:Promise.resolve(U));return vB(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:P.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Q)=>{if(!Q)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new j4({schema:this,typeName:O$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return b4.create(this,this._def)}nullable(){return A0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return A4.create(this)}promise(){return a1.create(this,this._def)}or($){return C_.create([this,$],this._def)}and($){return P_.create(this,$,this._def)}transform($){return new j4({...A$(this._def),schema:this,typeName:O$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new v_({...A$(this._def),innerType:this,defaultValue:_,typeName:O$.ZodDefault})}brand(){return new H9({typeName:O$.ZodBranded,type:this,...A$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new y_({...A$(this._def),innerType:this,catchValue:_,typeName:O$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return oW.create(this,$)}readonly(){return h_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var yb=/^c[^\s-]{8,}$/i,hb=/^[0-9a-z]+$/,mb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xb=/^[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,ub=/^[a-z0-9_-]{21}$/i,db=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cb=/^[-+]?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)?)??$/,lb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nb="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",bQ,ib=/^(?:(?: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])$/,rb=/^(?:(?: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])$/,pb=/^(([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]))$/,ob=/^(([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])$/,tb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ab=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cB="((\\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])))",sb=new RegExp(`^${cB}$`);function lB($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function eb($){return new RegExp(`^${lB($)}$`)}function nB($){let _=`${cB}T${lB($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function $E($,_){if((_==="v4"||!_)&&ib.test($))return!0;if((_==="v6"||!_)&&pb.test($))return!0;return!1}function _E($,_){if(!db.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function JE($,_){if((_==="v4"||!_)&&rb.test($))return!0;if((_==="v6"||!_)&&ob.test($))return!0;return!1}class M4 extends g${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==r.string){let W=this._getOrReturnCtx($);return u(W,{code:P.invalid_type,expected:r.string,received:W.parsedType}),Y$}let J=new k6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),u(U,{code:P.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:P.invalid_string,...$$.errToObj(J)})}_addCheck($){return new M4({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...$$.errToObj($)})}url($){return this._addCheck({kind:"url",...$$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...$$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...$$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...$$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...$$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...$$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...$$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...$$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...$$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...$$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...$$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...$$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...$$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...$$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...$$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...$$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...$$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...$$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...$$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...$$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...$$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...$$.errToObj(_)})}nonempty($){return this.min(1,$$.errToObj($))}trim(){return new M4({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new M4({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new M4({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}M4.create=($)=>{return new M4({checks:[],typeName:O$.ZodString,coerce:$?.coerce??!1,...A$($)})};function WE($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class G1 extends g${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==r.number){let W=this._getOrReturnCtx($);return u(W,{code:P.invalid_type,expected:r.number,received:W.parsedType}),Y$}let J=void 0,U=new k6;for(let W of this._def.checks)if(W.kind==="int"){if(!y$.isInteger($.data))J=this._getOrReturnCtx($,J),u(J,{code:P.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),u(J,{code:P.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(WE($.data,W.value)!==0)J=this._getOrReturnCtx($,J),u(J,{code:P.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),u(J,{code:P.not_finite,message:W.message}),U.dirty()}else y$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,$$.toString(_))}gt($,_){return this.setLimit("min",$,!1,$$.toString(_))}lte($,_){return this.setLimit("max",$,!0,$$.toString(_))}lt($,_){return this.setLimit("max",$,!1,$$.toString(_))}setLimit($,_,J,U){return new G1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:$$.toString(U)}]})}_addCheck($){return new G1({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:$$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:$$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:$$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&y$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}G1.create=($)=>{return new G1({checks:[],typeName:O$.ZodNumber,coerce:$?.coerce||!1,...A$($)})};class Q1 extends g${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==r.bigint)return this._getInvalidInput($);let J=void 0,U=new k6;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),u(J,{code:P.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),u(J,{code:P.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else y$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return u(_,{code:P.invalid_type,expected:r.bigint,received:_.parsedType}),Y$}gte($,_){return this.setLimit("min",$,!0,$$.toString(_))}gt($,_){return this.setLimit("min",$,!1,$$.toString(_))}lte($,_){return this.setLimit("max",$,!0,$$.toString(_))}lt($,_){return this.setLimit("max",$,!1,$$.toString(_))}setLimit($,_,J,U){return new Q1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:$$.toString(U)}]})}_addCheck($){return new Q1({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:$$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}Q1.create=($)=>{return new Q1({checks:[],typeName:O$.ZodBigInt,coerce:$?.coerce??!1,...A$($)})};class g_ extends g${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==r.boolean){let J=this._getOrReturnCtx($);return u(J,{code:P.invalid_type,expected:r.boolean,received:J.parsedType}),Y$}return m6($.data)}}g_.create=($)=>{return new g_({typeName:O$.ZodBoolean,coerce:$?.coerce||!1,...A$($)})};class p1 extends g${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==r.date){let W=this._getOrReturnCtx($);return u(W,{code:P.invalid_type,expected:r.date,received:W.parsedType}),Y$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return u(W,{code:P.invalid_date}),Y$}let J=new k6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),u(U,{code:P.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else y$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new p1({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:$$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:$$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}p1.create=($)=>{return new p1({checks:[],coerce:$?.coerce||!1,typeName:O$.ZodDate,...A$($)})};class lW extends g${_parse($){if(this._getType($)!==r.symbol){let J=this._getOrReturnCtx($);return u(J,{code:P.invalid_type,expected:r.symbol,received:J.parsedType}),Y$}return m6($.data)}}lW.create=($)=>{return new lW({typeName:O$.ZodSymbol,...A$($)})};class k_ extends g${_parse($){if(this._getType($)!==r.undefined){let J=this._getOrReturnCtx($);return u(J,{code:P.invalid_type,expected:r.undefined,received:J.parsedType}),Y$}return m6($.data)}}k_.create=($)=>{return new k_({typeName:O$.ZodUndefined,...A$($)})};class f_ extends g${_parse($){if(this._getType($)!==r.null){let J=this._getOrReturnCtx($);return u(J,{code:P.invalid_type,expected:r.null,received:J.parsedType}),Y$}return m6($.data)}}f_.create=($)=>{return new f_({typeName:O$.ZodNull,...A$($)})};class o1 extends g${constructor(){super(...arguments);this._any=!0}_parse($){return m6($.data)}}o1.create=($)=>{return new o1({typeName:O$.ZodAny,...A$($)})};class X1 extends g${constructor(){super(...arguments);this._unknown=!0}_parse($){return m6($.data)}}X1.create=($)=>{return new X1({typeName:O$.ZodUnknown,...A$($)})};class $0 extends g${_parse($){let _=this._getOrReturnCtx($);return u(_,{code:P.invalid_type,expected:r.never,received:_.parsedType}),Y$}}$0.create=($)=>{return new $0({typeName:O$.ZodNever,...A$($)})};class nW extends g${_parse($){if(this._getType($)!==r.undefined){let J=this._getOrReturnCtx($);return u(J,{code:P.invalid_type,expected:r.void,received:J.parsedType}),Y$}return m6($.data)}}nW.create=($)=>{return new nW({typeName:O$.ZodVoid,...A$($)})};class A4 extends g${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==r.array)return u(_,{code:P.invalid_type,expected:r.array,received:_.parsedType}),Y$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)u(_,{code:P.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new E4(_,X,_.path,G))})).then((X)=>{return k6.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new E4(_,X,_.path,G))});return k6.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new A4({...this._def,minLength:{value:$,message:$$.toString(_)}})}max($,_){return new A4({...this._def,maxLength:{value:$,message:$$.toString(_)}})}length($,_){return new A4({...this._def,exactLength:{value:$,message:$$.toString(_)}})}nonempty($){return this.min(1,$)}}A4.create=($,_)=>{return new A4({type:$,minLength:null,maxLength:null,exactLength:null,typeName:O$.ZodArray,...A$(_)})};function b_($){if($ instanceof D6){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=b4.create(b_(U))}return new D6({...$._def,shape:()=>_})}else if($ instanceof A4)return new A4({...$._def,type:b_($.element)});else if($ instanceof b4)return b4.create(b_($.unwrap()));else if($ instanceof A0)return A0.create(b_($.unwrap()));else if($ instanceof _0)return _0.create($.items.map((_)=>b_(_)));else return $}class D6 extends g${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=y$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==r.object){let Y=this._getOrReturnCtx($);return u(Y,{code:P.invalid_type,expected:r.object,received:Y.parsedType}),Y$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof $0&&this._def.unknownKeys==="strip")){for(let Y in U.data)if(!X.includes(Y))G.push(Y)}let Q=[];for(let Y of X){let q=W[Y],L=U.data[Y];Q.push({key:{status:"valid",value:Y},value:q._parse(new E4(U,L,U.path,Y)),alwaysSet:Y in U.data})}if(this._def.catchall instanceof $0){let Y=this._def.unknownKeys;if(Y==="passthrough")for(let q of G)Q.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Y==="strict"){if(G.length>0)u(U,{code:P.unrecognized_keys,keys:G}),J.dirty()}else if(Y==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Y=this._def.catchall;for(let q of G){let L=U.data[q];Q.push({key:{status:"valid",value:q},value:Y._parse(new E4(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Y=[];for(let q of Q){let L=await q.key,N=await q.value;Y.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Y}).then((Y)=>{return k6.mergeObjectSync(J,Y)});else return k6.mergeObjectSync(J,Q)}get shape(){return this._def.shape()}strict($){return $$.errToObj,new D6({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:$$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new D6({...this._def,unknownKeys:"strip"})}passthrough(){return new D6({...this._def,unknownKeys:"passthrough"})}extend($){return new D6({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new D6({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:O$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new D6({...this._def,catchall:$})}pick($){let _={};for(let J of y$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new D6({...this._def,shape:()=>_})}omit($){let _={};for(let J of y$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new D6({...this._def,shape:()=>_})}deepPartial(){return b_(this)}partial($){let _={};for(let J of y$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new D6({...this._def,shape:()=>_})}required($){let _={};for(let J of y$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof b4)W=W._def.innerType;_[J]=W}return new D6({...this._def,shape:()=>_})}keyof(){return iB(y$.objectKeys(this.shape))}}D6.create=($,_)=>{return new D6({shape:()=>$,unknownKeys:"strip",catchall:$0.create(),typeName:O$.ZodObject,...A$(_)})};D6.strictCreate=($,_)=>{return new D6({shape:()=>$,unknownKeys:"strict",catchall:$0.create(),typeName:O$.ZodObject,...A$(_)})};D6.lazycreate=($,_)=>{return new D6({shape:$,unknownKeys:"strip",catchall:$0.create(),typeName:O$.ZodObject,...A$(_)})};class C_ extends g${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new s6(G.ctx.common.issues));return u(_,{code:P.invalid_union,unionErrors:X}),Y$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Q of J){let Y={..._,common:{..._.common,issues:[]},parent:null},q=Q._parseSync({data:_.data,path:_.path,parent:Y});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Y};if(Y.common.issues.length)X.push(Y.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Q)=>new s6(Q));return u(_,{code:P.invalid_union,unionErrors:G}),Y$}}get options(){return this._def.options}}C_.create=($,_)=>{return new C_({options:$,typeName:O$.ZodUnion,...A$(_)})};var K0=($)=>{if($ instanceof T_)return K0($.schema);else if($ instanceof j4)return K0($.innerType());else if($ instanceof S_)return[$.value];else if($ instanceof Y1)return $.options;else if($ instanceof Z_)return y$.objectValues($.enum);else if($ instanceof v_)return K0($._def.innerType);else if($ instanceof k_)return[void 0];else if($ instanceof f_)return[null];else if($ instanceof b4)return[void 0,...K0($.unwrap())];else if($ instanceof A0)return[null,...K0($.unwrap())];else if($ instanceof H9)return K0($.unwrap());else if($ instanceof h_)return K0($.unwrap());else if($ instanceof y_)return K0($._def.innerType);else return[]};class B9 extends g${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.object)return u(_,{code:P.invalid_type,expected:r.object,received:_.parsedType}),Y$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return u(_,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),Y$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=K0(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new B9({typeName:O$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...A$(J)})}}function CQ($,_){let J=M0($),U=M0(_);if($===_)return{valid:!0,data:$};else if(J===r.object&&U===r.object){let W=y$.objectKeys(_),X=y$.objectKeys($).filter((Q)=>W.indexOf(Q)!==-1),G={...$,..._};for(let Q of X){let Y=CQ($[Q],_[Q]);if(!Y.valid)return{valid:!1};G[Q]=Y.data}return{valid:!0,data:G}}else if(J===r.array&&U===r.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Q=_[X],Y=CQ(G,Q);if(!Y.valid)return{valid:!1};W.push(Y.data)}return{valid:!0,data:W}}else if(J===r.date&&U===r.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class P_ extends g${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(kQ(W)||kQ(X))return Y$;let G=CQ(W.value,X.value);if(!G.valid)return u(J,{code:P.invalid_intersection_types}),Y$;if(fQ(W)||fQ(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}P_.create=($,_,J)=>{return new P_({left:$,right:_,typeName:O$.ZodIntersection,...A$(J)})};class _0 extends g${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.array)return u(J,{code:P.invalid_type,expected:r.array,received:J.parsedType}),Y$;if(J.data.lengththis._def.items.length)u(J,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Q=this._def.items[G]||this._def.rest;if(!Q)return null;return Q._parse(new E4(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return k6.mergeArray(_,X)});else return k6.mergeArray(_,W)}get items(){return this._def.items}rest($){return new _0({...this._def,rest:$})}}_0.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new _0({items:$,typeName:O$.ZodTuple,rest:null,...A$(_)})};class iW extends g${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.object)return u(J,{code:P.invalid_type,expected:r.object,received:J.parsedType}),Y$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new E4(J,G,J.path,G)),value:X._parse(new E4(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return k6.mergeObjectAsync(_,U);else return k6.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof g$)return new iW({keyType:$,valueType:_,typeName:O$.ZodRecord,...A$(J)});return new iW({keyType:M4.create(),valueType:$,typeName:O$.ZodRecord,...A$(_)})}}class rW extends g${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.map)return u(J,{code:P.invalid_type,expected:r.map,received:J.parsedType}),Y$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Q],Y)=>{return{key:U._parse(new E4(J,G,J.path,[Y,"key"])),value:W._parse(new E4(J,Q,J.path,[Y,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Q of X){let Y=await Q.key,q=await Q.value;if(Y.status==="aborted"||q.status==="aborted")return Y$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Q of X){let{key:Y,value:q}=Q;if(Y.status==="aborted"||q.status==="aborted")return Y$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}}}}rW.create=($,_,J)=>{return new rW({valueType:_,keyType:$,typeName:O$.ZodMap,...A$(J)})};class t1 extends g${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.set)return u(J,{code:P.invalid_type,expected:r.set,received:J.parsedType}),Y$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)u(J,{code:P.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Q){let Y=new Set;for(let q of Q){if(q.status==="aborted")return Y$;if(q.status==="dirty")_.dirty();Y.add(q.value)}return{status:_.value,value:Y}}let G=[...J.data.values()].map((Q,Y)=>W._parse(new E4(J,Q,J.path,Y)));if(J.common.async)return Promise.all(G).then((Q)=>X(Q));else return X(G)}min($,_){return new t1({...this._def,minSize:{value:$,message:$$.toString(_)}})}max($,_){return new t1({...this._def,maxSize:{value:$,message:$$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}t1.create=($,_)=>{return new t1({valueType:$,minSize:null,maxSize:null,typeName:O$.ZodSet,...A$(_)})};class w_ extends g${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.function)return u(_,{code:P.invalid_type,expected:r.function,received:_.parsedType}),Y$;function J(G,Q){return D9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,O9(),I_].filter((Y)=>!!Y),issueData:{code:P.invalid_arguments,argumentsError:Q}})}function U(G,Q){return D9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,O9(),I_].filter((Y)=>!!Y),issueData:{code:P.invalid_return_type,returnTypeError:Q}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof a1){let G=this;return m6(async function(...Q){let Y=new s6([]),q=await G._def.args.parseAsync(Q,W).catch((F)=>{throw Y.addIssue(J(Q,F)),Y}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((F)=>{throw Y.addIssue(U(L,F)),Y})})}else{let G=this;return m6(function(...Q){let Y=G._def.args.safeParse(Q,W);if(!Y.success)throw new s6([J(Q,Y.error)]);let q=Reflect.apply(X,this,Y.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new s6([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new w_({...this._def,args:_0.create($).rest(X1.create())})}returns($){return new w_({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new w_({args:$?$:_0.create([]).rest(X1.create()),returns:_||X1.create(),typeName:O$.ZodFunction,...A$(J)})}}class T_ extends g${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}T_.create=($,_)=>{return new T_({getter:$,typeName:O$.ZodLazy,...A$(_)})};class S_ extends g${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return u(_,{received:_.data,code:P.invalid_literal,expected:this._def.value}),Y$}return{status:"valid",value:$.data}}get value(){return this._def.value}}S_.create=($,_)=>{return new S_({value:$,typeName:O$.ZodLiteral,...A$(_)})};function iB($,_){return new Y1({values:$,typeName:O$.ZodEnum,...A$(_)})}class Y1 extends g${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return u(_,{expected:y$.joinValues(J),received:_.parsedType,code:P.invalid_type}),Y$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return u(_,{received:_.data,code:P.invalid_enum_value,options:J}),Y$}return m6($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return Y1.create($,{...this._def,..._})}exclude($,_=this._def){return Y1.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}Y1.create=iB;class Z_ extends g${_parse($){let _=y$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==r.string&&J.parsedType!==r.number){let U=y$.objectValues(_);return u(J,{expected:y$.joinValues(U),received:J.parsedType,code:P.invalid_type}),Y$}if(!this._cache)this._cache=new Set(y$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=y$.objectValues(_);return u(J,{received:J.data,code:P.invalid_enum_value,options:U}),Y$}return m6($.data)}get enum(){return this._def.values}}Z_.create=($,_)=>{return new Z_({values:$,typeName:O$.ZodNativeEnum,...A$(_)})};class a1 extends g${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.promise&&_.common.async===!1)return u(_,{code:P.invalid_type,expected:r.promise,received:_.parsedType}),Y$;let J=_.parsedType===r.promise?_.data:Promise.resolve(_.data);return m6(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}a1.create=($,_)=>{return new a1({type:$,typeName:O$.ZodPromise,...A$(_)})};class j4 extends g${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(u(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return Y$;let Q=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Q.status==="aborted")return Y$;if(Q.status==="dirty")return E_(Q.value);if(_.value==="dirty")return E_(Q.value);return Q});else{if(_.value==="aborted")return Y$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return Y$;if(G.status==="dirty")return E_(G.value);if(_.value==="dirty")return E_(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Q=U.refinement(G,W);if(J.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return Y$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return Y$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!r1(X))return Y$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!r1(X))return Y$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});y$.assertNever(U)}}j4.create=($,_,J)=>{return new j4({schema:$,typeName:O$.ZodEffects,effect:_,...A$(J)})};j4.createWithPreprocess=($,_,J)=>{return new j4({schema:_,effect:{type:"preprocess",transform:$},typeName:O$.ZodEffects,...A$(J)})};class b4 extends g${_parse($){if(this._getType($)===r.undefined)return m6(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}b4.create=($,_)=>{return new b4({innerType:$,typeName:O$.ZodOptional,...A$(_)})};class A0 extends g${_parse($){if(this._getType($)===r.null)return m6(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}A0.create=($,_)=>{return new A0({innerType:$,typeName:O$.ZodNullable,...A$(_)})};class v_ extends g${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===r.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}v_.create=($,_)=>{return new v_({innerType:$,typeName:O$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...A$(_)})};class y_ extends g${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(cW(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new s6(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new s6(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}y_.create=($,_)=>{return new y_({innerType:$,typeName:O$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...A$(_)})};class pW extends g${_parse($){if(this._getType($)!==r.nan){let J=this._getOrReturnCtx($);return u(J,{code:P.invalid_type,expected:r.nan,received:J.parsedType}),Y$}return{status:"valid",value:$.data}}}pW.create=($)=>{return new pW({typeName:O$.ZodNaN,...A$($)})};var UE=Symbol("zod_brand");class H9 extends g${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class oW extends g${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return Y$;if(W.status==="dirty")return _.dirty(),E_(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return Y$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new oW({in:$,out:_,typeName:O$.ZodPipeline})}}class h_ extends g${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(r1(U))U.value=Object.freeze(U.value);return U};return cW(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}h_.create=($,_)=>{return new h_({innerType:$,typeName:O$.ZodReadonly,...A$(_)})};function yB($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function rB($,_={},J){if($)return o1.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Q=yB(_,U),Y=Q.fatal??J??!0;W.addIssue({code:"custom",...Q,fatal:Y})}});if(!X){let G=yB(_,U),Q=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Q})}return});return o1.create()}var XE={object:D6.lazycreate},O$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(O$||(O$={}));var GE=($,_={message:`Input not instance of ${$.name}`})=>rB((J)=>J instanceof $,_),pB=M4.create,oB=G1.create,QE=pW.create,YE=Q1.create,tB=g_.create,qE=p1.create,zE=lW.create,jE=k_.create,OE=f_.create,DE=o1.create,LE=X1.create,BE=$0.create,HE=nW.create,NE=A4.create,VE=D6.create,FE=D6.strictCreate,RE=C_.create,KE=B9.create,ME=P_.create,AE=_0.create,bE=iW.create,EE=rW.create,wE=t1.create,IE=w_.create,gE=T_.create,kE=S_.create,fE=Y1.create,CE=Z_.create,PE=a1.create,hB=j4.create,TE=b4.create,SE=A0.create,ZE=j4.createWithPreprocess,vE=oW.create,yE=()=>pB().optional(),hE=()=>oB().optional(),mE=()=>tB().optional(),xE={string:($)=>M4.create({...$,coerce:!0}),number:($)=>G1.create({...$,coerce:!0}),boolean:($)=>g_.create({...$,coerce:!0}),bigint:($)=>Q1.create({...$,coerce:!0}),date:($)=>p1.create({...$,coerce:!0})},uE=Y$;var e={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},aB=z.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),e6=z.string().datetime(),H$=z.string().trim().min(1),b0=H$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),sB=z.string().regex(/^[a-fA-F0-9]{64}$/),eB=z.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),E0=z.record(z.unknown()),u_=z.array(z.string().min(1)).default([]),s1=e6.nullable().optional(),dE=new Set(["succeeded","failed","cancelled","blocked","skipped"]),$2=z.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function p$($){return z.object({schema:z.literal($),id:z.string().min(1),createdAt:e6,updatedAt:s1,metadata:E0.optional()}).strict()}var ko=z.object({schema:aB,id:z.string().min(1),createdAt:e6,updatedAt:s1,metadata:E0.optional()}).strict(),$H=z.enum(["agent","human","service","model","workflow","system"]),cE=p$(e.actorRef).extend({kind:$H,name:z.string().min(1).optional(),provider:z.string().min(1).optional(),accountId:z.string().min(1).optional(),machineId:z.string().min(1).optional(),capabilities:z.array(z.string().min(1)).default([])}).strict(),J0=z.object({kind:$H,id:z.string().min(1),name:z.string().min(1).optional(),provider:z.string().min(1).optional(),accountId:z.string().min(1).optional(),machineId:z.string().min(1).optional()}).strict(),_H=z.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),lE=p$(e.resourceRef).extend({kind:_H,name:z.string().min(1).optional(),uri:b0.optional(),externalId:H$.optional(),sourcePackage:H$.optional(),tags:u_}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:z.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),I$=z.object({kind:_H,id:z.string().min(1),name:z.string().min(1).optional(),uri:b0.optional(),externalId:H$.optional(),sourcePackage:H$.optional(),tags:u_}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:z.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),TQ=z.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),nE=z.enum(["none","partial","full","unknown"]),iE=p$(e.evidenceRef).extend({kind:TQ,uri:b0,sha256:sB.optional(),summary:z.string().min(1).optional(),contentType:z.string().min(1).optional(),sizeBytes:z.number().int().nonnegative().optional(),redaction:nE.default("unknown"),producer:J0.optional(),resourceRefs:z.array(I$).default([]),tags:u_}).strict(),U6=z.object({id:z.string().min(1),kind:TQ.optional(),uri:b0.optional(),sha256:sB.optional(),summary:z.string().min(1).optional()}).strict(),tW=p$(e.costEstimate).extend({currency:z.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:z.number().int().nonnegative(),provider:z.string().min(1).optional(),model:z.string().min(1).optional(),accountId:z.string().min(1).optional(),promptTokens:z.number().int().nonnegative().optional(),completionTokens:z.number().int().nonnegative().optional(),totalTokens:z.number().int().nonnegative().optional(),basis:z.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:z.array(I$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:z.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),rE=z.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),JH=p$(e.decisionEnvelope).extend({decisionType:z.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:rE,actor:J0.optional(),traceId:z.string().min(1).optional(),inputHash:eB.optional(),policyBundleId:z.string().min(1).optional(),selected:z.array(I$).default([]),skipped:z.array(I$).default([]),reason:z.string().min(1),obligations:z.array(z.string().min(1)).default([]),redactions:z.array(z.string().min(1)).default([]),costEstimate:tW.optional(),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),pE=p$(e.capabilityCard).extend({kind:z.enum(["model","tool","machine","agent","lane","connector","service"]),name:z.string().min(1),version:z.string().min(1).optional(),status:z.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:z.array(z.string().min(1)).default([]),limitations:z.array(z.string().min(1)).default([]),riskLevel:z.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:tW.optional(),evidenceRefs:z.array(U6).default([])}).strict(),m_=z.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),oE=z.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),tE=z.object({refName:H$,requiredForModes:z.array(m_).min(1),allowedSecretInputs:z.array(z.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:H$,revocationCheck:z.boolean().default(!0)}).strict(),aE=z.object({operation:H$,supportedModes:z.array(m_).min(1),sideEffectClass:oE,requiresApproval:z.boolean().default(!1),requiresIdempotencyKey:z.boolean().default(!1),requiresSandboxEvidence:z.boolean().default(!1),requiresRollbackOrRevocation:z.boolean().default(!1),rollbackOrRevocation:H$.optional(),noSideEffectSmoke:H$.optional(),reconciliation:H$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),sE=z.object({providerId:H$,appId:H$,adapterId:H$,ownerPackage:H$,modes:z.array(m_).min(1),defaultMode:m_,credentialRequirements:z.array(tE).default([]),operations:z.array(aE).min(1),rateLimitPosture:H$,costPosture:H$.optional(),auditEvents:z.array(H$).default([]),redactionRules:z.array(H$).default([]),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:z.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),eE=z.object({appId:H$,repo:H$,priority:z.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:z.array(H$).min(1),firstOperations:z.array(H$).min(1),blockedUntil:z.array(H$).default([])}).strict(),$w=p$(e.providerLiveModeStandard).extend({name:H$,version:H$,modes:z.array(m_).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:z.array(H$).min(1),liveMutationGate:z.object({requiredMode:z.literal("live_mutating"),requiredChecks:z.array(H$).min(1),forbiddenBypassSignals:z.array(H$).min(1),disabledLiveSmoke:H$}).strict(),noSideEffectSmoke:z.object({requiredForModes:z.array(m_).min(1),commandEvidence:z.array(H$).min(1),secretOutputScan:z.boolean().default(!0)}).strict(),credentialPolicy:z.object({acceptedInputs:z.array(z.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:z.literal(!1),missingCredentialBehavior:z.literal("fail_closed"),revocationCheckRequired:z.boolean().default(!0)}).strict(),operationCards:z.array(sE).min(1),firstAdoptionTargets:z.array(eE).min(1),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:z.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),_w=z.object({id:z.string().min(1),title:z.string().min(1).optional(),summary:z.string().min(1),text:z.string().optional(),tokens:z.number().int().nonnegative().optional(),source:U6,resourceRefs:z.array(I$).default([])}).strict(),WH=p$(e.contextPack).extend({objective:z.string().min(1),budget:z.object({maxTokens:z.number().int().positive().optional(),maxBytes:z.number().int().positive().optional()}).strict().optional(),items:z.array(_w).default([]),citations:z.array(U6).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),permissions:z.array(z.string().min(1)).default([]),redactions:z.array(z.string().min(1)).default([]),conflicts:z.array(z.string().min(1)).default([]),uncertainty:z.string().min(1).optional()}).strict(),K4=H$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),e1=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),Jw=z.enum(["public","internal","private","sensitive"]),Ww=z.enum(["draft","active","paused","archived"]),SQ=z.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),UH=p$(e.integrationRef).extend({kind:SQ,name:z.string().min(1),projectId:e1.optional(),sourcePackage:H$.optional(),externalId:H$.optional(),uri:b0.optional(),enabled:z.boolean().default(!0),readOnly:z.boolean().default(!0),capabilities:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:I$.optional(),evidenceRefs:z.array(U6).default([]),config:E0.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:z.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),Uw=z.object({schemaRoot:K4.default(".hasna/project"),dashboardManifest:K4.default(".hasna/project/dashboard.render.json"),snapshotsDir:K4.default(".hasna/project/snapshots"),documentsDir:K4.default("documents"),reportsDir:K4.default("reports"),evidenceDir:K4.default(".hasna/project/evidence"),privateDir:K4.default(".hasna/project/private")}).strict(),Xw=p$(e.projectManifest).extend({projectId:e1,slug:e1,name:z.string().min(1),summary:z.string().min(1).optional(),status:Ww.default("active"),classification:Jw.default("private"),owner:J0.optional(),layout:Uw.default({}),integrations:z.array(UH).default([]),renderManifests:z.array(I$).default([]),resourceRefs:z.array(I$).default([]),evidenceRefs:z.array(U6).default([]),tags:u_}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:z.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:z.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:z.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),Gw=z.enum(["local","package","provider","url"]),ZQ=z.object({id:z.string().min(1),kind:Gw,specifier:z.string().min(1),path:K4.optional(),packageName:z.string().min(1).optional(),uri:b0.optional(),provider:SQ.optional(),schemaId:aB.optional(),integrity:eB.optional(),resourceRef:I$.optional(),optional:z.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:z.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:z.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:z.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:z.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),Qw=z.enum(["dashboard","canvas","panel","report","document","custom"]),Yw=z.object({id:z.string().min(1),title:z.string().min(1),kind:Qw,default:z.boolean().default(!1),entry:K4.optional(),imports:z.array(ZQ).default([]),panelRefs:z.array(I$).default([]),dataRefs:z.array(I$).default([]),layout:E0.optional()}).strict(),qw=p$(e.renderManifest).extend({projectId:e1,name:z.string().min(1),version:z.string().min(1),manifestPath:K4.default(".hasna/project/dashboard.render.json"),renderer:z.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:z.array(Yw).min(1),imports:z.array(ZQ).default([]),theme:E0.optional(),compatibility:z.object({minProjectsVersion:z.string().min(1).optional(),minContractsVersion:z.string().min(1).optional()}).strict().optional(),resourceRefs:z.array(I$).default([]),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Q=new Set;for(let[Y,q]of G.imports.entries()){if(Q.has(q.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Y,"id"]});Q.add(q.id)}for(let[Y,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:z.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Y,"kind"]})}}),zw=z.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),jw=z.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Ow=z.object({id:z.string().min(1),label:z.string().min(1),value:z.union([z.string(),z.number(),z.boolean()]),unit:z.string().min(1).optional(),status:z.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:z.array(I$).default([])}).strict(),Dw=z.object({id:z.string().min(1),title:z.string().min(1),summary:z.string().min(1).optional(),status:z.string().min(1).optional(),priority:z.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:e6.optional(),resourceRefs:z.array(I$).default([]),evidenceRefs:z.array(U6).default([]),metadata:E0.optional()}).strict(),Lw=z.object({renderer:z.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:z.string().min(1).optional(),entry:K4.optional(),imports:z.array(ZQ).default([]),spec:E0.default({})}).strict(),XH=p$(e.projectPanel).extend({projectId:e1,provider:z.object({kind:SQ,id:z.string().min(1),name:z.string().min(1).optional(),sourcePackage:H$.optional(),externalId:H$.optional()}).strict(),kind:jw,title:z.string().min(1),summary:z.string().min(1).optional(),state:zw.default("ready"),stateReason:z.string().min(1).optional(),generatedAt:e6,freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),metrics:z.array(Ow).default([]),items:z.array(Dw).default([]),actions:z.array(I$).default([]),resourceRefs:z.array(I$).default([]),evidenceRefs:z.array(U6).default([]),renderFragment:Lw.optional(),warnings:z.array(z.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:z.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:z.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),Bw=p$(e.projectSnapshot).extend({projectId:e1,generatedAt:e6,status:$2.default("unknown"),manifestRef:I$,renderManifestRef:I$.optional(),panels:z.array(XH).default([]),contextPacks:z.array(WH).default([]),proofBundleRefs:z.array(I$).default([]),resourceRefs:z.array(I$).default([]),evidenceRefs:z.array(U6).default([]),warnings:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:z.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),GH=z.object({id:z.string().min(1),kind:z.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:z.boolean().default(!0),command:z.string().min(1).optional(),expected:z.string().min(1).optional(),timeoutMs:z.number().int().positive().optional(),resourceRefs:z.array(I$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:z.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),Hw=p$(e.validationPlan).extend({objective:z.string().min(1),subject:I$.optional(),checks:z.array(GH).min(1),verifier:J0.optional(),requiredEvidenceKinds:z.array(TQ).default([])}).strict(),Nw=z.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),Vw=z.enum(["draft","active","deprecated","archived"]),Fw=z.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Rw=z.object({key:z.string().regex(/^[A-Z][A-Z0-9_]*$/),description:z.string().min(1),required:z.boolean().default(!1),["secret"]:z.boolean().default(!1),group:z.string().min(1).optional(),default:z.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Kw=z.object({name:z.string().min(1),command:z.string().min(1),description:z.string().min(1).optional(),required:z.boolean().default(!1)}).strict(),Mw=z.object({packageManager:z.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:z.array(z.string().min(1)).default([]),requiredFiles:z.array(z.string().min(1)).default([]),requiredDirectories:z.array(z.string().min(1)).default([]),optionalDirectories:z.array(z.string().min(1)).default([])}).strict(),Aw=p$(e.scaffoldManifest).extend({name:z.string().min(1),version:z.string().min(1),summary:z.string().min(1),type:Nw,status:Vw.default("draft"),capabilities:z.array(Fw).default([]),techStack:z.array(z.string().min(1)).default([]),tags:u_,source:I$.optional(),output:Mw,env:z.array(Rw).default([]),scripts:z.array(Kw).default([]),validationChecks:z.array(GH).default([]),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:z.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),bw=z.enum(["installed","failed","cancelled","partial","unknown"]),Ew=p$(e.scaffoldInstallRecord).extend({scaffoldId:z.string().min(1),scaffoldVersion:z.string().min(1).optional(),manifestRef:I$.optional(),target:I$,status:bw,installedAt:e6.optional(),installer:J0.optional(),packageManager:z.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:E0.optional(),generatedFiles:z.array(I$).default([]),evidenceRefs:z.array(U6).default([]),proofBundleRefs:z.array(I$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:z.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),x_=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),vQ=z.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),QH=z.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),ww=z.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),Iw=H$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),gw=z.enum(["active","stub","deprecated","archived"]),kw=z.enum(["stable","beta","canary","internal"]),fw=z.object({transport:z.enum(["http","stdio"]).default("http"),bin:z.string().min(1).optional(),url:b0.optional()}).strict(),Cw=z.object({healthPath:z.string().min(1).default("/health"),port:z.number().int().positive().optional(),baseUrl:b0.optional()}).strict(),Pw=z.object({bins:z.array(z.string().min(1)).default([]),mcp:fw.optional(),http:Cw.optional()}).strict(),Tw=p$(e.app).extend({appId:x_,npmName:vQ,repoFolder:x_,githubUrl:Iw,projectSlug:e1,surfaces:Pw.default({}),lifecycle:gw,releaseChannel:kw.default("stable"),summary:z.string().min(1).optional(),tags:u_}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:z.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),Sw=z.enum(["skill","ci","backfilled"]),Zw=p$(e.release).extend({appId:x_,package:vQ,version:QH,gitSha:ww,publishedAt:e6,publishPath:Sw,changelogRef:I$.optional(),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),vw=z.enum(["install","update","rollback","freeze-blocked"]),yw=z.object({cliVersion:z.string().min(1).optional(),mcpHealth:z.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),hw=p$(e.rolloutRecord).extend({appId:x_,package:vQ,version:QH,machine:H$,action:vw,result:$2,verifiedBy:yw.optional(),at:e6,evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:z.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),mw=z.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),xw=z.enum(["pending","queued","sent","failed","skipped","suppressed"]),uw=z.object({channel:mw,status:xw,deliveredAt:e6.optional(),detail:z.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:z.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),dw=p$(e.announcement).extend({campaignId:H$,appId:x_.optional(),releaseRef:I$.optional(),channels:z.array(uw).min(1),audienceRef:I$,sentAt:e6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:z.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:z.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),cw=z.enum(["tag","attribute","group"]),lw=z.enum(["eq","neq","in","not_in","exists","not_exists"]),mB=z.union([z.string(),z.number(),z.boolean()]),nw=z.object({kind:cw,key:z.string().min(1).optional(),op:lw.default("eq"),value:mB.optional(),values:z.array(mB).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:z.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),iw=z.object({match:z.enum(["all","any"]).default("all"),predicates:z.array(nw).min(1)}).strict(),rw=z.enum(["opt_in","opt_out","transactional","none"]),pw=p$(e.audience).extend({audienceId:x_,name:H$,definition:iw,consentPolicy:rw,suppressionSyncedAt:s1}).strict(),EQ=["@hasna/cloud","open-cloud"],ow=z.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),tw=z.object({id:z.string().min(1),provider:ow,kind:z.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:z.string().min(1),region:z.string().min(1).optional(),accountId:z.string().min(1).optional(),uri:b0.optional(),machineScoped:z.boolean().default(!1)}).strict(),YH=p$(e.appCloudManifest).extend({packageName:z.string().min(1),packageVersion:z.string().min(1).optional(),appId:z.string().min(1),repository:I$.optional(),storageMode:z.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:z.enum(["none","app_owned","external_service","local_cache"]),cloudResources:z.array(tw).default([]),localCache:z.object({path:z.string().min(1).optional(),pullMode:z.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:z.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:z.array(z.string().min(1)).default([...EQ]),dependencies:z.array(z.string().min(1)).default([]),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{let J=new Set([...EQ,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:z.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of EQ)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:z.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:z.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:z.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:z.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:z.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:z.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),qH=z.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),aw=z.enum(["low","medium","high","critical"]),zH=z.object({id:z.string().min(1),kind:qH,severity:aw,path:z.string().min(1).optional(),packageName:z.string().min(1).optional(),pattern:z.string().min(1),message:z.string().min(1),evidenceRefs:z.array(U6).default([])}).strict(),sw=z.object({id:z.string().min(1),kind:qH,status:$2,target:z.string().min(1),command:z.string().min(1).optional(),evidenceRefs:z.array(U6).default([]),findings:z.array(zH).default([])}).strict(),ew=p$(e.noCloudEvidencePack).extend({subject:I$,packageName:z.string().min(1).optional(),packageVersion:z.string().min(1).optional(),generatedBy:J0.optional(),scanMode:z.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:$2,verdict:z.enum(["passed","failed","warning","not_run"]),appCloudManifest:YH.optional(),checks:z.array(sw).min(1),findings:z.array(zH).default([]),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Q)=>Q.severity==="high"||Q.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),$I=z.object({checkId:z.string().min(1),status:$2,summary:z.string().min(1).optional(),startedAt:s1,finishedAt:s1,evidenceRefs:z.array(U6).default([])}).strict(),_I=p$(e.proofBundle).extend({subject:I$,validationPlanRef:I$.optional(),status:$2,verdict:z.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:z.array($I).default([]),verifier:J0.optional(),evidenceRefs:z.array(U6).default([]),residualRisks:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),JI=p$(e.workRun).extend({objective:z.string().min(1),status:$2,actor:J0,traceId:z.string().min(1).optional(),startedAt:s1,finishedAt:s1,constraints:z.array(z.string().min(1)).default([]),resourceRefs:z.array(I$).default([]),decisions:z.array(JH).default([]),costEstimates:z.array(tW).default([]),evidenceRefs:z.array(U6).default([]),validationPlanRefs:z.array(I$).default([]),proofBundleRefs:z.array(I$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),WI=z.object({id:z.string().min(1),at:e6,kind:z.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:z.string().min(1),resourceRefs:z.array(I$).default([]),evidenceRefs:z.array(U6).default([]),costEstimate:tW.optional()}).strict(),UI=p$(e.agentTrajectory).extend({actor:J0,workRunRef:I$.optional(),events:z.array(WI).default([]),outcome:z.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:I$.optional()}).strict(),XI="v1",GI=z.enum(["library","cli-with-store","service","saas"]),QI=["local","self-hosted","cloud"],jH=z.enum(QI),YI=z.enum(["supported","deferred","unsupported"]),qI=z.enum(["none","local-only","api-key","session","service-token","custom"]),wQ=z.object({method:z.enum(["GET","POST","PUT","PATCH","DELETE"]),path:z.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:z.boolean().default(!1),description:z.string().min(1).optional()}).strict(),zI=z.object({id:z.string().min(1),kind:z.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:z.boolean().default(!0),command:z.string().min(1).optional(),evidenceRef:U6.optional(),status:z.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:z.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:z.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),jI=z.object({name:z.string().min(1),status:YI,bin:z.string().min(1).optional(),mcpBin:z.string().min(1).optional(),authMode:qI,deploymentModes:z.array(jH).min(1),health:wQ.optional(),readiness:wQ.optional(),version:wQ.optional(),apiBasePath:z.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:z.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:z.string().min(1).optional(),readinessGates:z.array(zI).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:z.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:z.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:z.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:z.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),OI=["local","cloud"],OH=z.enum(OI),DI=["remote","hybrid","self_hosted"],LI=z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),BI=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function HI($){return BI.map((_)=>`${$}${_}`)}function xB($){return`hasna/oss/${$}/database-url`}var NI=z.object({mode:OH,envPrefix:z.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:z.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:z.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:z.string().min(1).optional()}).strict(),VI=z.object({$schema:z.string().min(1).optional(),schema:z.literal(e.serviceContract),name:LI,class:GI,contractVersion:z.literal(XI),kitVersion:z.string().min(1),description:z.string().min(1).optional(),bins:z.array(z.string().min(1)).default([]),storage:NI.optional(),deploymentModes:z.array(jH).default(["local"]),serviceSurfaces:z.array(jI).default([]),metadata:E0.optional()}).strict().superRefine(($,_)=>{let J=new Set(HI($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:z.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:z.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:z.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==xB($.name))_.addIssue({code:z.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${xB($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:z.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:z.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:z.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:z.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:z.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:z.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Q,Y]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Y))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface deployment mode "${Y}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Q]})}}),fo=z.object({status:z.enum(["ok","degraded","unavailable"]),version:z.string().min(1),mode:OH}).strict(),Co=z.object({ready:z.boolean(),reason:z.string().min(1).optional()}).strict(),Po=z.object({version:z.string().min(1)}).strict(),FI=z.enum(["info","notice","breaking","critical"]),RI=z.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),KI=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],MI=z.enum(KI);var AI=z.enum(["fleet","package","machine"]),DH=p$(e.commsEventEnvelope).extend({type:RI,severity:FI,scope:AI,summary:z.string().min(1).optional(),source:J0.optional(),affected_packages:z.array(H$).default([]),affected_machines:z.array(H$).default([]),action_required:z.boolean().default(!1),ack_by:e6.optional(),dedupe_key:H$,resourceRefs:z.array(I$).default([]),evidenceRefs:z.array(U6).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:z.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),bI=z.enum(["fleet","package","product","loop-lane","initiative","personal"]),EI=z.enum(["quiet","work","firehose"]),wI=H$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),II=p$(e.commsChannelMetadata).extend({class:bI,noise:EI.optional(),owner:H$.optional(),until:wI.optional(),successor:H$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:z.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:z.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),uB={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},gI=p$(e.commsMessageMetadata).extend({tag:MI,envelope:DH}).strict().superRefine(($,_)=>{let J=uB[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:z.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:z.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(uB))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:z.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var To={[e.actorRef]:cE,[e.resourceRef]:lE,[e.evidenceRef]:iE,[e.workRun]:JI,[e.decisionEnvelope]:JH,[e.costEstimate]:tW,[e.capabilityCard]:pE,[e.providerLiveModeStandard]:$w,[e.contextPack]:WH,[e.integrationRef]:UH,[e.projectManifest]:Xw,[e.projectPanel]:XH,[e.projectSnapshot]:Bw,[e.renderManifest]:qw,[e.agentTrajectory]:UI,[e.validationPlan]:Hw,[e.proofBundle]:_I,[e.scaffoldManifest]:Aw,[e.scaffoldInstallRecord]:Ew,[e.appCloudManifest]:YH,[e.noCloudEvidencePack]:ew,[e.serviceContract]:VI,[e.commsEventEnvelope]:DH,[e.commsChannelMetadata]:II,[e.commsMessageMetadata]:gI,[e.app]:Tw,[e.release]:Zw,[e.rolloutRecord]:hw,[e.announcement]:dw,[e.audience]:pw};function kI($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(DI.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}function fI($){return $.toUpperCase().replace(/-/g,"_")}function CI($){return`https://${$}.hasna.xyz`}function LH($){let _=fI($);return{modeKeys:[`HASNA_${_}_STORAGE_MODE`,`HASNA_${_}_MODE`,`${_}_STORAGE_MODE`,`${_}_MODE`],apiUrlKeys:[`HASNA_${_}_API_URL`,`${_}_API_URL`],apiKeyKeys:[`HASNA_${_}_API_KEY`,`${_}_API_KEY`]}}function j9($,_){for(let J of _){let U=$[J]?.trim();if(U)return{key:J,value:U}}return null}function PI($){let _=new URL($);if(_.protocol!=="http:"&&_.protocol!=="https:")throw Error("API URL must use http or https.");let J=_.pathname.replace(/\/+$/,"");if(J.endsWith("/v1"))J=J.slice(0,-3);return _.pathname=`${J}/v1`,_.search="",_.hash="",_.toString().replace(/\/+$/,"")}function TI($,_=process.env){let J=LH($),U=j9(_,J.modeKeys),W=j9(_,J.apiUrlKeys),X=j9(_,J.apiKeyKeys),G="local",Q=null,Y="default",q=[];if(U){let B=kI(U.value);if(G=B.mode,Q=B.deprecatedAlias,Y=U.key,Q)q.push(`Deprecated mode '${Q}' from ${U.key} is treated as 'cloud'. Prefer ${J.modeKeys[0]}=cloud.`)}else if(W&&X)G="cloud",Y=`${W.key}+${X.key}`;if(G==="local")return{transport:"local",mode:G,deprecatedAlias:Q,modeSource:Y,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(X),apiKeySource:X?X.key:null,misconfigured:!1,warning:q.length>0?q.join(" "):null};if(!X)return q.push(`${Y}=cloud but no API key is set (${J.apiKeyKeys[0]}). Refusing to route to cloud; using local store. Set ${J.apiKeyKeys[0]} to enable the cloud client.`),{transport:"local",mode:G,deprecatedAlias:Q,modeSource:Y,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,misconfigured:!0,warning:q.join(" ")};let L=W?.value??CI($),N=W?W.key:"default",F;try{F=PI(L)}catch(B){let H=B instanceof Error?B.message:String(B);return q.push(`Invalid API URL from ${N}: ${H}. Using local store.`),{transport:"local",mode:G,deprecatedAlias:Q,modeSource:Y,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:X.key,misconfigured:!0,warning:q.join(" ")}}return{transport:"cloud-http",mode:G,deprecatedAlias:Q,modeSource:Y,baseUrl:F,apiUrlSource:N,apiKeyPresent:!0,apiKeySource:X.key,misconfigured:!1,warning:q.length>0?q.join(" "):null}}class L9 extends Error{status;method;path;body;constructor($,_,J,U){super(`Hasna cloud request failed: ${$} ${_} -> ${J}`);this.name="HasnaHttpError",this.status=J,this.method=$,this.path=_,this.body=U}}var SI=[408,425,429,500,502,503,504],ZI=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]);function vI($,_){if(!_)return $;let J=_ instanceof URLSearchParams?_:new URLSearchParams;if(!(_ instanceof URLSearchParams))for(let[W,X]of Object.entries(_)){if(X===null||X===void 0)continue;if(Array.isArray(X))for(let G of X)J.append(W,String(G));else J.append(W,String(X))}let U=J.toString();if(!U)return $;return`${$}${$.includes("?")?"&":"?"}${U}`}var yI=($)=>new Promise((_)=>setTimeout(_,$));function hI($){let _=$.fetchImpl??((q,L)=>fetch(q,L)),J=$.baseUrl.replace(/\/+$/,""),U=$.timeoutMs??30000,W=$.sleepImpl??yI,X=$.retry;function G(q){let L=q!==void 0?q:X;if(L===!1)return null;let N=L??{};return{retries:N.retries??2,baseDelayMs:N.baseDelayMs??200,maxDelayMs:N.maxDelayMs??2000,retryStatuses:N.retryStatuses??[...SI]}}async function Q(q,L,N,F,B){let H={"x-api-key":$.apiKey,Authorization:`Bearer ${$.apiKey}`,Accept:"application/json",...$.headers??{},...B.headers??{}};if(B.idempotencyKey)H["Idempotency-Key"]=B.idempotencyKey;let V={method:q,headers:H};if(F!==void 0)H["Content-Type"]="application/json",V.body=JSON.stringify(F);let R=new AbortController,M=()=>R.abort();if(B.signal)if(B.signal.aborted)R.abort();else B.signal.addEventListener("abort",M,{once:!0});let K=setTimeout(()=>R.abort(),B.timeoutMs??U);V.signal=R.signal;let w;try{w=await _(N,V)}catch(v){let g=v instanceof Error?v:Error(String(v));if(B.signal?.aborted)return{ok:!1,retryable:!1,error:g};return{ok:!1,retryable:!0,error:g}}finally{if(clearTimeout(K),B.signal)B.signal.removeEventListener("abort",M)}let b=await w.text(),I=void 0;if(b.length>0)try{I=JSON.parse(b)}catch{I=b}if(!w.ok){let v=G(B.retry);return{ok:!1,retryable:v?v.retryStatuses.includes(w.status):!1,error:new L9(q,L,w.status,I)}}return{ok:!0,value:I}}async function Y(q,L,N,F={}){let B=q.toUpperCase(),H=vI(L.startsWith("/")?L:`/${L}`,F.query),V=`${J}${H}`,R=G(F.retry),M=ZI.has(B)||Boolean(F.idempotencyKey),K=R&&M?R.retries+1:1,w=null;for(let b=1;b<=K;b++){let I=await Q(B,H,V,N,F);if(I.ok)return I.value;if(w=I,!(R!==null&&M&&I.retryable&&bY("GET",q,void 0,L),post:(q,L,N)=>Y("POST",q,L,N),put:(q,L,N)=>Y("PUT",q,L,N),patch:(q,L,N)=>Y("PATCH",q,L,N),del:(q,L,N)=>Y("DELETE",q,L,N)}}function mI($,_=process.env,J){let U=TI($,_);if(U.misconfigured)throw Error(U.warning??`Client for '${$}' is misconfigured for cloud mode.`);if(U.transport==="local"||!U.baseUrl)return{transport:"local",client:null,resolution:U};let W=LH($),X=j9(_,W.apiKeyKeys)?.value;if(!X)throw Error(`Client for '${$}' resolved to cloud-http without an API key.`);return{transport:"cloud-http",client:hI({name:$,baseUrl:U.baseUrl,apiKey:X,...J?.fetchImpl?{fetchImpl:J.fetchImpl}:{},...J?.headers?{headers:J.headers}:{},...J?.timeoutMs?{timeoutMs:J.timeoutMs}:{},...J?.retry!==void 0?{retry:J.retry}:{},...J?.sleepImpl?{sleepImpl:J.sleepImpl}:{}}),resolution:U}}function PQ($){let _=$.replace(/^\/+|\/+$/g,"");if(!_)throw Error("resource must be a non-empty path segment");return`/${_}`}function IQ($,_){if(_===void 0||_===null||`${_}`.length===0)throw Error("id must be a non-empty string");return`${PQ($)}/${encodeURIComponent(String(_))}`}function xI(){let $=globalThis;if($.crypto?.randomUUID)return $.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function uI($){if(Array.isArray($))return $;if($&&typeof $==="object"){let _=$;for(let J of["items","data","results","rows","records"])if(Array.isArray(_[J]))return _[J]}return[]}function dI($){if($&&typeof $==="object"){let _=$;for(let J of["total","count","totalCount","total_count"])if(typeof _[J]==="number")return _[J]}return null}function cI($){if($&&typeof $==="object"){let _=$;for(let J of["cursor","nextCursor","next_cursor","next"])if(typeof _[J]==="string")return _[J]}return null}function lI($,_){return{name:$,baseUrl:_.baseUrl,transport:_,async list(J,U={}){let W=await _.get(PQ(J),U);return{items:uI(W),total:dI(W),cursor:cI(W),raw:W}},async get(J,U,W={}){try{return await _.get(IQ(J,U),W)}catch(X){if(X instanceof L9&&X.status===404)return null;throw X}},async create(J,U,W={}){let{idempotencyKey:X,...G}=W;return _.post(PQ(J),U,{...G,idempotencyKey:X??xI()})},async update(J,U,W,X={}){let{method:G="PATCH",idempotencyKey:Q,...Y}=X;return(G==="PUT"?_.put:_.patch)(IQ(J,U),W,{...Y,...Q?{idempotencyKey:Q}:{}})},async delete(J,U,W={}){try{await _.del(IQ(J,U),void 0,W)}catch(X){if(X instanceof L9&&X.status===404)return;throw X}}}}function yQ($,_=process.env,J){let U=mI($,_,J);if(U.transport==="cloud-http")return{transport:"cloud-http",client:lI($,U.client)};return{transport:"local",client:null}}var nI=Object.defineProperty,iI=($)=>$;function rI($,_){this[$]=iI.bind(null,_)}var pI=($,_)=>{for(var J in _)nI($,J,{get:_[J],enumerable:!0,configurable:!0,set:rI.bind(_,J)})},j={};pI(j,{void:()=>Pg,util:()=>h$,unknown:()=>fg,union:()=>vg,undefined:()=>Ig,tuple:()=>mg,transformer:()=>NH,symbol:()=>wg,string:()=>IH,strictObject:()=>Zg,setErrorMap:()=>aI,set:()=>dg,record:()=>xg,quotelessJson:()=>oI,promise:()=>pg,preprocess:()=>ag,pipeline:()=>sg,ostring:()=>eg,optional:()=>og,onumber:()=>$k,oboolean:()=>_k,objectUtil:()=>uQ,object:()=>Sg,number:()=>gH,nullable:()=>tg,null:()=>gg,never:()=>Cg,nativeEnum:()=>rg,nan:()=>Ag,map:()=>ug,makeIssue:()=>V9,literal:()=>ng,lazy:()=>lg,late:()=>Kg,isValid:()=>_2,isDirty:()=>cQ,isAsync:()=>aW,isAborted:()=>dQ,intersection:()=>hg,instanceof:()=>Mg,getParsedType:()=>I0,getErrorMap:()=>N9,function:()=>cg,enum:()=>ig,effect:()=>NH,discriminatedUnion:()=>yg,defaultErrorMap:()=>n_,datetimeRegex:()=>bH,date:()=>Eg,custom:()=>wH,coerce:()=>Jk,boolean:()=>kH,bigint:()=>bg,array:()=>Tg,any:()=>kg,addIssueToContext:()=>d,ZodVoid:()=>eW,ZodUnknown:()=>q1,ZodUnion:()=>o_,ZodUndefined:()=>r_,ZodType:()=>f$,ZodTuple:()=>U0,ZodTransformer:()=>O4,ZodSymbol:()=>sW,ZodString:()=>I4,ZodSet:()=>U2,ZodSchema:()=>f$,ZodRecord:()=>$U,ZodReadonly:()=>JJ,ZodPromise:()=>X2,ZodPipeline:()=>WU,ZodParsedType:()=>p,ZodOptional:()=>k4,ZodObject:()=>L6,ZodNumber:()=>z1,ZodNullable:()=>g0,ZodNull:()=>p_,ZodNever:()=>W0,ZodNativeEnum:()=>e_,ZodNaN:()=>JU,ZodMap:()=>_U,ZodLiteral:()=>s_,ZodLazy:()=>a_,ZodIssueCode:()=>T,ZodIntersection:()=>t_,ZodFunction:()=>l_,ZodFirstPartyTypeKind:()=>D$,ZodError:()=>$4,ZodEnum:()=>O1,ZodEffects:()=>O4,ZodDiscriminatedUnion:()=>F9,ZodDefault:()=>$J,ZodDate:()=>J2,ZodCatch:()=>_J,ZodBranded:()=>R9,ZodBoolean:()=>i_,ZodBigInt:()=>j1,ZodArray:()=>g4,ZodAny:()=>W2,Schema:()=>f$,ParseStatus:()=>f6,OK:()=>x6,NEVER:()=>Wk,INVALID:()=>q$,EMPTY_PATH:()=>sI,DIRTY:()=>c_,BRAND:()=>Rg});var h$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Q)=>typeof W[W[Q]]!=="number"),G={};for(let Q of X)G[Q]=W[Q];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(h$||(h$={}));var uQ;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(uQ||(uQ={}));var p=h$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I0=($)=>{switch(typeof $){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN($)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":if(Array.isArray($))return p.array;if($===null)return p.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return p.promise;if(typeof Map<"u"&&$ instanceof Map)return p.map;if(typeof Set<"u"&&$ instanceof Set)return p.set;if(typeof Date<"u"&&$ instanceof Date)return p.date;return p.object;default:return p.unknown}},T=h$.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"]),oI=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class $4 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Q=0;while(Q_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}$4.create=($)=>{return new $4($)};var tI=($,_)=>{let J;switch($.code){case T.invalid_type:if($.received===p.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case T.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,h$.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:J=`Unrecognized key(s) in object: ${h$.joinValues($.keys,", ")}`;break;case T.invalid_union:J="Invalid input";break;case T.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${h$.joinValues($.options)}`;break;case T.invalid_enum_value:J=`Invalid enum value. Expected ${h$.joinValues($.options)}, received '${$.received}'`;break;case T.invalid_arguments:J="Invalid function arguments";break;case T.invalid_return_type:J="Invalid function return type";break;case T.invalid_date:J="Invalid date";break;case T.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else h$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case T.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case T.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case T.custom:J="Invalid input";break;case T.invalid_intersection_types:J="Intersection results could not be merged";break;case T.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case T.not_finite:J="Number must be finite";break;default:J=_.defaultError,h$.assertNever($)}return{message:J}},n_=tI,KH=n_;function aI($){KH=$}function N9(){return KH}var V9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Q="",Y=U.filter((q)=>!!q).slice().reverse();for(let q of Y)Q=q(G,{data:_,defaultError:Q}).message;return{...W,path:X,message:Q}},sI=[];function d($,_){let J=N9(),U=V9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===n_?void 0:n_].filter((W)=>!!W)});$.common.issues.push(U)}class f6{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return q$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return f6.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return q$;if(X.status==="aborted")return q$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var q$=Object.freeze({status:"aborted"}),c_=($)=>({status:"dirty",value:$}),x6=($)=>({status:"valid",value:$}),dQ=($)=>$.status==="aborted",cQ=($)=>$.status==="dirty",_2=($)=>$.status==="valid",aW=($)=>typeof Promise<"u"&&$ instanceof Promise,J$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(J$||(J$={}));class f4{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var BH=($,_)=>{if(_2(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new $4($.common.issues);return this._error=J,this._error}}}};function b$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Q)=>{let{message:Y}=$;if(G.code==="invalid_enum_value")return{message:Y??Q.defaultError};if(typeof Q.data>"u")return{message:Y??U??Q.defaultError};if(G.code!=="invalid_type")return{message:Q.defaultError};return{message:Y??J??Q.defaultError}},description:W}}class f${get description(){return this._def.description}_getType($){return I0($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:I0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new f6,ctx:{common:$.parent.common,data:$.data,parsedType:I0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(aW(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)},U=this._parseSync({data:$,path:J.path,parent:J});return BH(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return _2(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>_2(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(aW(U)?U:Promise.resolve(U));return BH(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:T.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Q)=>{if(!Q)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new O4({schema:this,typeName:D$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return k4.create(this,this._def)}nullable(){return g0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return g4.create(this)}promise(){return X2.create(this,this._def)}or($){return o_.create([this,$],this._def)}and($){return t_.create(this,$,this._def)}transform($){return new O4({...b$(this._def),schema:this,typeName:D$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new $J({...b$(this._def),innerType:this,defaultValue:_,typeName:D$.ZodDefault})}brand(){return new R9({typeName:D$.ZodBranded,type:this,...b$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new _J({...b$(this._def),innerType:this,catchValue:_,typeName:D$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return WU.create(this,$)}readonly(){return JJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var eI=/^c[^\s-]{8,}$/i,$g=/^[0-9a-z]+$/,_g=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Jg=/^[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,Wg=/^[a-z0-9_-]{21}$/i,Ug=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Xg=/^[-+]?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)?)??$/,Gg=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Qg="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hQ,Yg=/^(?:(?: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])$/,qg=/^(?:(?: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])$/,zg=/^(([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]))$/,jg=/^(([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])$/,Og=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Dg=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,MH="((\\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])))",Lg=new RegExp(`^${MH}$`);function AH($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function Bg($){return new RegExp(`^${AH($)}$`)}function bH($){let _=`${MH}T${AH($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function Hg($,_){if((_==="v4"||!_)&&Yg.test($))return!0;if((_==="v6"||!_)&&zg.test($))return!0;return!1}function Ng($,_){if(!Ug.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function Vg($,_){if((_==="v4"||!_)&&qg.test($))return!0;if((_==="v6"||!_)&&jg.test($))return!0;return!1}class I4 extends f${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==p.string){let W=this._getOrReturnCtx($);return d(W,{code:T.invalid_type,expected:p.string,received:W.parsedType}),q$}let J=new f6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),d(U,{code:T.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:T.invalid_string,...J$.errToObj(J)})}_addCheck($){return new I4({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...J$.errToObj($)})}url($){return this._addCheck({kind:"url",...J$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...J$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...J$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...J$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...J$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...J$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...J$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...J$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...J$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...J$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...J$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...J$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...J$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...J$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...J$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...J$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...J$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...J$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...J$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...J$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...J$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...J$.errToObj(_)})}nonempty($){return this.min(1,J$.errToObj($))}trim(){return new I4({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new I4({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new I4({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}I4.create=($)=>{return new I4({checks:[],typeName:D$.ZodString,coerce:$?.coerce??!1,...b$($)})};function Fg($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class z1 extends f${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==p.number){let W=this._getOrReturnCtx($);return d(W,{code:T.invalid_type,expected:p.number,received:W.parsedType}),q$}let J=void 0,U=new f6;for(let W of this._def.checks)if(W.kind==="int"){if(!h$.isInteger($.data))J=this._getOrReturnCtx($,J),d(J,{code:T.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),d(J,{code:T.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(Fg($.data,W.value)!==0)J=this._getOrReturnCtx($,J),d(J,{code:T.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),d(J,{code:T.not_finite,message:W.message}),U.dirty()}else h$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,J$.toString(_))}gt($,_){return this.setLimit("min",$,!1,J$.toString(_))}lte($,_){return this.setLimit("max",$,!0,J$.toString(_))}lt($,_){return this.setLimit("max",$,!1,J$.toString(_))}setLimit($,_,J,U){return new z1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:J$.toString(U)}]})}_addCheck($){return new z1({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:J$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:J$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:J$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&h$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}z1.create=($)=>{return new z1({checks:[],typeName:D$.ZodNumber,coerce:$?.coerce||!1,...b$($)})};class j1 extends f${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==p.bigint)return this._getInvalidInput($);let J=void 0,U=new f6;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),d(J,{code:T.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),d(J,{code:T.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else h$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return d(_,{code:T.invalid_type,expected:p.bigint,received:_.parsedType}),q$}gte($,_){return this.setLimit("min",$,!0,J$.toString(_))}gt($,_){return this.setLimit("min",$,!1,J$.toString(_))}lte($,_){return this.setLimit("max",$,!0,J$.toString(_))}lt($,_){return this.setLimit("max",$,!1,J$.toString(_))}setLimit($,_,J,U){return new j1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:J$.toString(U)}]})}_addCheck($){return new j1({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:J$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}j1.create=($)=>{return new j1({checks:[],typeName:D$.ZodBigInt,coerce:$?.coerce??!1,...b$($)})};class i_ extends f${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==p.boolean){let J=this._getOrReturnCtx($);return d(J,{code:T.invalid_type,expected:p.boolean,received:J.parsedType}),q$}return x6($.data)}}i_.create=($)=>{return new i_({typeName:D$.ZodBoolean,coerce:$?.coerce||!1,...b$($)})};class J2 extends f${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==p.date){let W=this._getOrReturnCtx($);return d(W,{code:T.invalid_type,expected:p.date,received:W.parsedType}),q$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return d(W,{code:T.invalid_date}),q$}let J=new f6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),d(U,{code:T.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else h$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new J2({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:J$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:J$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}J2.create=($)=>{return new J2({checks:[],coerce:$?.coerce||!1,typeName:D$.ZodDate,...b$($)})};class sW extends f${_parse($){if(this._getType($)!==p.symbol){let J=this._getOrReturnCtx($);return d(J,{code:T.invalid_type,expected:p.symbol,received:J.parsedType}),q$}return x6($.data)}}sW.create=($)=>{return new sW({typeName:D$.ZodSymbol,...b$($)})};class r_ extends f${_parse($){if(this._getType($)!==p.undefined){let J=this._getOrReturnCtx($);return d(J,{code:T.invalid_type,expected:p.undefined,received:J.parsedType}),q$}return x6($.data)}}r_.create=($)=>{return new r_({typeName:D$.ZodUndefined,...b$($)})};class p_ extends f${_parse($){if(this._getType($)!==p.null){let J=this._getOrReturnCtx($);return d(J,{code:T.invalid_type,expected:p.null,received:J.parsedType}),q$}return x6($.data)}}p_.create=($)=>{return new p_({typeName:D$.ZodNull,...b$($)})};class W2 extends f${constructor(){super(...arguments);this._any=!0}_parse($){return x6($.data)}}W2.create=($)=>{return new W2({typeName:D$.ZodAny,...b$($)})};class q1 extends f${constructor(){super(...arguments);this._unknown=!0}_parse($){return x6($.data)}}q1.create=($)=>{return new q1({typeName:D$.ZodUnknown,...b$($)})};class W0 extends f${_parse($){let _=this._getOrReturnCtx($);return d(_,{code:T.invalid_type,expected:p.never,received:_.parsedType}),q$}}W0.create=($)=>{return new W0({typeName:D$.ZodNever,...b$($)})};class eW extends f${_parse($){if(this._getType($)!==p.undefined){let J=this._getOrReturnCtx($);return d(J,{code:T.invalid_type,expected:p.void,received:J.parsedType}),q$}return x6($.data)}}eW.create=($)=>{return new eW({typeName:D$.ZodVoid,...b$($)})};class g4 extends f${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==p.array)return d(_,{code:T.invalid_type,expected:p.array,received:_.parsedType}),q$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)d(_,{code:T.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new f4(_,X,_.path,G))})).then((X)=>{return f6.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new f4(_,X,_.path,G))});return f6.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new g4({...this._def,minLength:{value:$,message:J$.toString(_)}})}max($,_){return new g4({...this._def,maxLength:{value:$,message:J$.toString(_)}})}length($,_){return new g4({...this._def,exactLength:{value:$,message:J$.toString(_)}})}nonempty($){return this.min(1,$)}}g4.create=($,_)=>{return new g4({type:$,minLength:null,maxLength:null,exactLength:null,typeName:D$.ZodArray,...b$(_)})};function d_($){if($ instanceof L6){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=k4.create(d_(U))}return new L6({...$._def,shape:()=>_})}else if($ instanceof g4)return new g4({...$._def,type:d_($.element)});else if($ instanceof k4)return k4.create(d_($.unwrap()));else if($ instanceof g0)return g0.create(d_($.unwrap()));else if($ instanceof U0)return U0.create($.items.map((_)=>d_(_)));else return $}class L6 extends f${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=h$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==p.object){let Y=this._getOrReturnCtx($);return d(Y,{code:T.invalid_type,expected:p.object,received:Y.parsedType}),q$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof W0&&this._def.unknownKeys==="strip")){for(let Y in U.data)if(!X.includes(Y))G.push(Y)}let Q=[];for(let Y of X){let q=W[Y],L=U.data[Y];Q.push({key:{status:"valid",value:Y},value:q._parse(new f4(U,L,U.path,Y)),alwaysSet:Y in U.data})}if(this._def.catchall instanceof W0){let Y=this._def.unknownKeys;if(Y==="passthrough")for(let q of G)Q.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Y==="strict"){if(G.length>0)d(U,{code:T.unrecognized_keys,keys:G}),J.dirty()}else if(Y==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Y=this._def.catchall;for(let q of G){let L=U.data[q];Q.push({key:{status:"valid",value:q},value:Y._parse(new f4(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Y=[];for(let q of Q){let L=await q.key,N=await q.value;Y.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Y}).then((Y)=>{return f6.mergeObjectSync(J,Y)});else return f6.mergeObjectSync(J,Q)}get shape(){return this._def.shape()}strict($){return J$.errToObj,new L6({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:J$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new L6({...this._def,unknownKeys:"strip"})}passthrough(){return new L6({...this._def,unknownKeys:"passthrough"})}extend($){return new L6({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new L6({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:D$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new L6({...this._def,catchall:$})}pick($){let _={};for(let J of h$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new L6({...this._def,shape:()=>_})}omit($){let _={};for(let J of h$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new L6({...this._def,shape:()=>_})}deepPartial(){return d_(this)}partial($){let _={};for(let J of h$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new L6({...this._def,shape:()=>_})}required($){let _={};for(let J of h$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof k4)W=W._def.innerType;_[J]=W}return new L6({...this._def,shape:()=>_})}keyof(){return EH(h$.objectKeys(this.shape))}}L6.create=($,_)=>{return new L6({shape:()=>$,unknownKeys:"strip",catchall:W0.create(),typeName:D$.ZodObject,...b$(_)})};L6.strictCreate=($,_)=>{return new L6({shape:()=>$,unknownKeys:"strict",catchall:W0.create(),typeName:D$.ZodObject,...b$(_)})};L6.lazycreate=($,_)=>{return new L6({shape:$,unknownKeys:"strip",catchall:W0.create(),typeName:D$.ZodObject,...b$(_)})};class o_ extends f${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new $4(G.ctx.common.issues));return d(_,{code:T.invalid_union,unionErrors:X}),q$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Q of J){let Y={..._,common:{..._.common,issues:[]},parent:null},q=Q._parseSync({data:_.data,path:_.path,parent:Y});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Y};if(Y.common.issues.length)X.push(Y.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Q)=>new $4(Q));return d(_,{code:T.invalid_union,unionErrors:G}),q$}}get options(){return this._def.options}}o_.create=($,_)=>{return new o_({options:$,typeName:D$.ZodUnion,...b$(_)})};var w0=($)=>{if($ instanceof a_)return w0($.schema);else if($ instanceof O4)return w0($.innerType());else if($ instanceof s_)return[$.value];else if($ instanceof O1)return $.options;else if($ instanceof e_)return h$.objectValues($.enum);else if($ instanceof $J)return w0($._def.innerType);else if($ instanceof r_)return[void 0];else if($ instanceof p_)return[null];else if($ instanceof k4)return[void 0,...w0($.unwrap())];else if($ instanceof g0)return[null,...w0($.unwrap())];else if($ instanceof R9)return w0($.unwrap());else if($ instanceof JJ)return w0($.unwrap());else if($ instanceof _J)return w0($._def.innerType);else return[]};class F9 extends f${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.object)return d(_,{code:T.invalid_type,expected:p.object,received:_.parsedType}),q$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return d(_,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),q$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=w0(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new F9({typeName:D$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...b$(J)})}}function lQ($,_){let J=I0($),U=I0(_);if($===_)return{valid:!0,data:$};else if(J===p.object&&U===p.object){let W=h$.objectKeys(_),X=h$.objectKeys($).filter((Q)=>W.indexOf(Q)!==-1),G={...$,..._};for(let Q of X){let Y=lQ($[Q],_[Q]);if(!Y.valid)return{valid:!1};G[Q]=Y.data}return{valid:!0,data:G}}else if(J===p.array&&U===p.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Q=_[X],Y=lQ(G,Q);if(!Y.valid)return{valid:!1};W.push(Y.data)}return{valid:!0,data:W}}else if(J===p.date&&U===p.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class t_ extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(dQ(W)||dQ(X))return q$;let G=lQ(W.value,X.value);if(!G.valid)return d(J,{code:T.invalid_intersection_types}),q$;if(cQ(W)||cQ(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}t_.create=($,_,J)=>{return new t_({left:$,right:_,typeName:D$.ZodIntersection,...b$(J)})};class U0 extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.array)return d(J,{code:T.invalid_type,expected:p.array,received:J.parsedType}),q$;if(J.data.lengththis._def.items.length)d(J,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Q=this._def.items[G]||this._def.rest;if(!Q)return null;return Q._parse(new f4(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return f6.mergeArray(_,X)});else return f6.mergeArray(_,W)}get items(){return this._def.items}rest($){return new U0({...this._def,rest:$})}}U0.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new U0({items:$,typeName:D$.ZodTuple,rest:null,...b$(_)})};class $U extends f${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.object)return d(J,{code:T.invalid_type,expected:p.object,received:J.parsedType}),q$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new f4(J,G,J.path,G)),value:X._parse(new f4(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return f6.mergeObjectAsync(_,U);else return f6.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof f$)return new $U({keyType:$,valueType:_,typeName:D$.ZodRecord,...b$(J)});return new $U({keyType:I4.create(),valueType:$,typeName:D$.ZodRecord,...b$(_)})}}class _U extends f${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.map)return d(J,{code:T.invalid_type,expected:p.map,received:J.parsedType}),q$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Q],Y)=>{return{key:U._parse(new f4(J,G,J.path,[Y,"key"])),value:W._parse(new f4(J,Q,J.path,[Y,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Q of X){let Y=await Q.key,q=await Q.value;if(Y.status==="aborted"||q.status==="aborted")return q$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Q of X){let{key:Y,value:q}=Q;if(Y.status==="aborted"||q.status==="aborted")return q$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}}}}_U.create=($,_,J)=>{return new _U({valueType:_,keyType:$,typeName:D$.ZodMap,...b$(J)})};class U2 extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.set)return d(J,{code:T.invalid_type,expected:p.set,received:J.parsedType}),q$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)d(J,{code:T.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Q){let Y=new Set;for(let q of Q){if(q.status==="aborted")return q$;if(q.status==="dirty")_.dirty();Y.add(q.value)}return{status:_.value,value:Y}}let G=[...J.data.values()].map((Q,Y)=>W._parse(new f4(J,Q,J.path,Y)));if(J.common.async)return Promise.all(G).then((Q)=>X(Q));else return X(G)}min($,_){return new U2({...this._def,minSize:{value:$,message:J$.toString(_)}})}max($,_){return new U2({...this._def,maxSize:{value:$,message:J$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}U2.create=($,_)=>{return new U2({valueType:$,minSize:null,maxSize:null,typeName:D$.ZodSet,...b$(_)})};class l_ extends f${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.function)return d(_,{code:T.invalid_type,expected:p.function,received:_.parsedType}),q$;function J(G,Q){return V9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,N9(),n_].filter((Y)=>!!Y),issueData:{code:T.invalid_arguments,argumentsError:Q}})}function U(G,Q){return V9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,N9(),n_].filter((Y)=>!!Y),issueData:{code:T.invalid_return_type,returnTypeError:Q}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof X2){let G=this;return x6(async function(...Q){let Y=new $4([]),q=await G._def.args.parseAsync(Q,W).catch((F)=>{throw Y.addIssue(J(Q,F)),Y}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((F)=>{throw Y.addIssue(U(L,F)),Y})})}else{let G=this;return x6(function(...Q){let Y=G._def.args.safeParse(Q,W);if(!Y.success)throw new $4([J(Q,Y.error)]);let q=Reflect.apply(X,this,Y.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new $4([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new l_({...this._def,args:U0.create($).rest(q1.create())})}returns($){return new l_({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new l_({args:$?$:U0.create([]).rest(q1.create()),returns:_||q1.create(),typeName:D$.ZodFunction,...b$(J)})}}class a_ extends f${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}a_.create=($,_)=>{return new a_({getter:$,typeName:D$.ZodLazy,...b$(_)})};class s_ extends f${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return d(_,{received:_.data,code:T.invalid_literal,expected:this._def.value}),q$}return{status:"valid",value:$.data}}get value(){return this._def.value}}s_.create=($,_)=>{return new s_({value:$,typeName:D$.ZodLiteral,...b$(_)})};function EH($,_){return new O1({values:$,typeName:D$.ZodEnum,...b$(_)})}class O1 extends f${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return d(_,{expected:h$.joinValues(J),received:_.parsedType,code:T.invalid_type}),q$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return d(_,{received:_.data,code:T.invalid_enum_value,options:J}),q$}return x6($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return O1.create($,{...this._def,..._})}exclude($,_=this._def){return O1.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}O1.create=EH;class e_ extends f${_parse($){let _=h$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==p.string&&J.parsedType!==p.number){let U=h$.objectValues(_);return d(J,{expected:h$.joinValues(U),received:J.parsedType,code:T.invalid_type}),q$}if(!this._cache)this._cache=new Set(h$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=h$.objectValues(_);return d(J,{received:J.data,code:T.invalid_enum_value,options:U}),q$}return x6($.data)}get enum(){return this._def.values}}e_.create=($,_)=>{return new e_({values:$,typeName:D$.ZodNativeEnum,...b$(_)})};class X2 extends f${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.promise&&_.common.async===!1)return d(_,{code:T.invalid_type,expected:p.promise,received:_.parsedType}),q$;let J=_.parsedType===p.promise?_.data:Promise.resolve(_.data);return x6(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}X2.create=($,_)=>{return new X2({type:$,typeName:D$.ZodPromise,...b$(_)})};class O4 extends f${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(d(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return q$;let Q=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Q.status==="aborted")return q$;if(Q.status==="dirty")return c_(Q.value);if(_.value==="dirty")return c_(Q.value);return Q});else{if(_.value==="aborted")return q$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return q$;if(G.status==="dirty")return c_(G.value);if(_.value==="dirty")return c_(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Q=U.refinement(G,W);if(J.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return q$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return q$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!_2(X))return q$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!_2(X))return q$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});h$.assertNever(U)}}O4.create=($,_,J)=>{return new O4({schema:$,typeName:D$.ZodEffects,effect:_,...b$(J)})};O4.createWithPreprocess=($,_,J)=>{return new O4({schema:_,effect:{type:"preprocess",transform:$},typeName:D$.ZodEffects,...b$(J)})};class k4 extends f${_parse($){if(this._getType($)===p.undefined)return x6(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}k4.create=($,_)=>{return new k4({innerType:$,typeName:D$.ZodOptional,...b$(_)})};class g0 extends f${_parse($){if(this._getType($)===p.null)return x6(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}g0.create=($,_)=>{return new g0({innerType:$,typeName:D$.ZodNullable,...b$(_)})};class $J extends f${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===p.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}$J.create=($,_)=>{return new $J({innerType:$,typeName:D$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...b$(_)})};class _J extends f${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(aW(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new $4(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new $4(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}_J.create=($,_)=>{return new _J({innerType:$,typeName:D$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...b$(_)})};class JU extends f${_parse($){if(this._getType($)!==p.nan){let J=this._getOrReturnCtx($);return d(J,{code:T.invalid_type,expected:p.nan,received:J.parsedType}),q$}return{status:"valid",value:$.data}}}JU.create=($)=>{return new JU({typeName:D$.ZodNaN,...b$($)})};var Rg=Symbol("zod_brand");class R9 extends f${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class WU extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return q$;if(W.status==="dirty")return _.dirty(),c_(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return q$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new WU({in:$,out:_,typeName:D$.ZodPipeline})}}class JJ extends f${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(_2(U))U.value=Object.freeze(U.value);return U};return aW(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}JJ.create=($,_)=>{return new JJ({innerType:$,typeName:D$.ZodReadonly,...b$(_)})};function HH($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function wH($,_={},J){if($)return W2.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Q=HH(_,U),Y=Q.fatal??J??!0;W.addIssue({code:"custom",...Q,fatal:Y})}});if(!X){let G=HH(_,U),Q=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Q})}return});return W2.create()}var Kg={object:L6.lazycreate},D$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(D$||(D$={}));var Mg=($,_={message:`Input not instance of ${$.name}`})=>wH((J)=>J instanceof $,_),IH=I4.create,gH=z1.create,Ag=JU.create,bg=j1.create,kH=i_.create,Eg=J2.create,wg=sW.create,Ig=r_.create,gg=p_.create,kg=W2.create,fg=q1.create,Cg=W0.create,Pg=eW.create,Tg=g4.create,Sg=L6.create,Zg=L6.strictCreate,vg=o_.create,yg=F9.create,hg=t_.create,mg=U0.create,xg=$U.create,ug=_U.create,dg=U2.create,cg=l_.create,lg=a_.create,ng=s_.create,ig=O1.create,rg=e_.create,pg=X2.create,NH=O4.create,og=k4.create,tg=g0.create,ag=O4.createWithPreprocess,sg=WU.create,eg=()=>IH().optional(),$k=()=>gH().optional(),_k=()=>kH().optional(),Jk={string:($)=>I4.create({...$,coerce:!0}),number:($)=>z1.create({...$,coerce:!0}),boolean:($)=>i_.create({...$,coerce:!0}),bigint:($)=>j1.create({...$,coerce:!0}),date:($)=>J2.create({...$,coerce:!0})},Wk=q$;var _$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},fH=j.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),_4=j.string().datetime(),N$=j.string().trim().min(1),k0=N$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),CH=j.string().regex(/^[a-fA-F0-9]{64}$/),PH=j.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),f0=j.record(j.unknown()),XJ=j.array(j.string().min(1)).default([]),G2=_4.nullable().optional(),Uk=new Set(["succeeded","failed","cancelled","blocked","skipped"]),Y2=j.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function o$($){return j.object({schema:j.literal($),id:j.string().min(1),createdAt:_4,updatedAt:G2,metadata:f0.optional()}).strict()}var Zo=j.object({schema:fH,id:j.string().min(1),createdAt:_4,updatedAt:G2,metadata:f0.optional()}).strict(),TH=j.enum(["agent","human","service","model","workflow","system"]),Xk=o$(_$.actorRef).extend({kind:TH,name:j.string().min(1).optional(),provider:j.string().min(1).optional(),accountId:j.string().min(1).optional(),machineId:j.string().min(1).optional(),capabilities:j.array(j.string().min(1)).default([])}).strict(),X0=j.object({kind:TH,id:j.string().min(1),name:j.string().min(1).optional(),provider:j.string().min(1).optional(),accountId:j.string().min(1).optional(),machineId:j.string().min(1).optional()}).strict(),SH=j.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),Gk=o$(_$.resourceRef).extend({kind:SH,name:j.string().min(1).optional(),uri:k0.optional(),externalId:N$.optional(),sourcePackage:N$.optional(),tags:XJ}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:j.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),k$=j.object({kind:SH,id:j.string().min(1),name:j.string().min(1).optional(),uri:k0.optional(),externalId:N$.optional(),sourcePackage:N$.optional(),tags:XJ}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:j.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),nQ=j.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),Qk=j.enum(["none","partial","full","unknown"]),Yk=o$(_$.evidenceRef).extend({kind:nQ,uri:k0,sha256:CH.optional(),summary:j.string().min(1).optional(),contentType:j.string().min(1).optional(),sizeBytes:j.number().int().nonnegative().optional(),redaction:Qk.default("unknown"),producer:X0.optional(),resourceRefs:j.array(k$).default([]),tags:XJ}).strict(),X6=j.object({id:j.string().min(1),kind:nQ.optional(),uri:k0.optional(),sha256:CH.optional(),summary:j.string().min(1).optional()}).strict(),UU=o$(_$.costEstimate).extend({currency:j.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:j.number().int().nonnegative(),provider:j.string().min(1).optional(),model:j.string().min(1).optional(),accountId:j.string().min(1).optional(),promptTokens:j.number().int().nonnegative().optional(),completionTokens:j.number().int().nonnegative().optional(),totalTokens:j.number().int().nonnegative().optional(),basis:j.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:j.array(k$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:j.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),qk=j.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),ZH=o$(_$.decisionEnvelope).extend({decisionType:j.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:qk,actor:X0.optional(),traceId:j.string().min(1).optional(),inputHash:PH.optional(),policyBundleId:j.string().min(1).optional(),selected:j.array(k$).default([]),skipped:j.array(k$).default([]),reason:j.string().min(1),obligations:j.array(j.string().min(1)).default([]),redactions:j.array(j.string().min(1)).default([]),costEstimate:UU.optional(),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),zk=o$(_$.capabilityCard).extend({kind:j.enum(["model","tool","machine","agent","lane","connector","service"]),name:j.string().min(1),version:j.string().min(1).optional(),status:j.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:j.array(j.string().min(1)).default([]),limitations:j.array(j.string().min(1)).default([]),riskLevel:j.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:UU.optional(),evidenceRefs:j.array(X6).default([])}).strict(),WJ=j.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),jk=j.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),Ok=j.object({refName:N$,requiredForModes:j.array(WJ).min(1),allowedSecretInputs:j.array(j.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:N$,revocationCheck:j.boolean().default(!0)}).strict(),Dk=j.object({operation:N$,supportedModes:j.array(WJ).min(1),sideEffectClass:jk,requiresApproval:j.boolean().default(!1),requiresIdempotencyKey:j.boolean().default(!1),requiresSandboxEvidence:j.boolean().default(!1),requiresRollbackOrRevocation:j.boolean().default(!1),rollbackOrRevocation:N$.optional(),noSideEffectSmoke:N$.optional(),reconciliation:N$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),Lk=j.object({providerId:N$,appId:N$,adapterId:N$,ownerPackage:N$,modes:j.array(WJ).min(1),defaultMode:WJ,credentialRequirements:j.array(Ok).default([]),operations:j.array(Dk).min(1),rateLimitPosture:N$,costPosture:N$.optional(),auditEvents:j.array(N$).default([]),redactionRules:j.array(N$).default([]),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:j.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),Bk=j.object({appId:N$,repo:N$,priority:j.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:j.array(N$).min(1),firstOperations:j.array(N$).min(1),blockedUntil:j.array(N$).default([])}).strict(),Hk=o$(_$.providerLiveModeStandard).extend({name:N$,version:N$,modes:j.array(WJ).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:j.array(N$).min(1),liveMutationGate:j.object({requiredMode:j.literal("live_mutating"),requiredChecks:j.array(N$).min(1),forbiddenBypassSignals:j.array(N$).min(1),disabledLiveSmoke:N$}).strict(),noSideEffectSmoke:j.object({requiredForModes:j.array(WJ).min(1),commandEvidence:j.array(N$).min(1),secretOutputScan:j.boolean().default(!0)}).strict(),credentialPolicy:j.object({acceptedInputs:j.array(j.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:j.literal(!1),missingCredentialBehavior:j.literal("fail_closed"),revocationCheckRequired:j.boolean().default(!0)}).strict(),operationCards:j.array(Lk).min(1),firstAdoptionTargets:j.array(Bk).min(1),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:j.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),Nk=j.object({id:j.string().min(1),title:j.string().min(1).optional(),summary:j.string().min(1),text:j.string().optional(),tokens:j.number().int().nonnegative().optional(),source:X6,resourceRefs:j.array(k$).default([])}).strict(),vH=o$(_$.contextPack).extend({objective:j.string().min(1),budget:j.object({maxTokens:j.number().int().positive().optional(),maxBytes:j.number().int().positive().optional()}).strict().optional(),items:j.array(Nk).default([]),citations:j.array(X6).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),permissions:j.array(j.string().min(1)).default([]),redactions:j.array(j.string().min(1)).default([]),conflicts:j.array(j.string().min(1)).default([]),uncertainty:j.string().min(1).optional()}).strict(),w4=N$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),Q2=j.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),Vk=j.enum(["public","internal","private","sensitive"]),Fk=j.enum(["draft","active","paused","archived"]),iQ=j.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),yH=o$(_$.integrationRef).extend({kind:iQ,name:j.string().min(1),projectId:Q2.optional(),sourcePackage:N$.optional(),externalId:N$.optional(),uri:k0.optional(),enabled:j.boolean().default(!0),readOnly:j.boolean().default(!0),capabilities:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:k$.optional(),evidenceRefs:j.array(X6).default([]),config:f0.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:j.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),Rk=j.object({schemaRoot:w4.default(".hasna/project"),dashboardManifest:w4.default(".hasna/project/dashboard.render.json"),snapshotsDir:w4.default(".hasna/project/snapshots"),documentsDir:w4.default("documents"),reportsDir:w4.default("reports"),evidenceDir:w4.default(".hasna/project/evidence"),privateDir:w4.default(".hasna/project/private")}).strict(),Kk=o$(_$.projectManifest).extend({projectId:Q2,slug:Q2,name:j.string().min(1),summary:j.string().min(1).optional(),status:Fk.default("active"),classification:Vk.default("private"),owner:X0.optional(),layout:Rk.default({}),integrations:j.array(yH).default([]),renderManifests:j.array(k$).default([]),resourceRefs:j.array(k$).default([]),evidenceRefs:j.array(X6).default([]),tags:XJ}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:j.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:j.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:j.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),Mk=j.enum(["local","package","provider","url"]),rQ=j.object({id:j.string().min(1),kind:Mk,specifier:j.string().min(1),path:w4.optional(),packageName:j.string().min(1).optional(),uri:k0.optional(),provider:iQ.optional(),schemaId:fH.optional(),integrity:PH.optional(),resourceRef:k$.optional(),optional:j.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:j.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:j.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:j.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:j.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),Ak=j.enum(["dashboard","canvas","panel","report","document","custom"]),bk=j.object({id:j.string().min(1),title:j.string().min(1),kind:Ak,default:j.boolean().default(!1),entry:w4.optional(),imports:j.array(rQ).default([]),panelRefs:j.array(k$).default([]),dataRefs:j.array(k$).default([]),layout:f0.optional()}).strict(),Ek=o$(_$.renderManifest).extend({projectId:Q2,name:j.string().min(1),version:j.string().min(1),manifestPath:w4.default(".hasna/project/dashboard.render.json"),renderer:j.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:j.array(bk).min(1),imports:j.array(rQ).default([]),theme:f0.optional(),compatibility:j.object({minProjectsVersion:j.string().min(1).optional(),minContractsVersion:j.string().min(1).optional()}).strict().optional(),resourceRefs:j.array(k$).default([]),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Q=new Set;for(let[Y,q]of G.imports.entries()){if(Q.has(q.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Y,"id"]});Q.add(q.id)}for(let[Y,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:j.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Y,"kind"]})}}),wk=j.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),Ik=j.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),gk=j.object({id:j.string().min(1),label:j.string().min(1),value:j.union([j.string(),j.number(),j.boolean()]),unit:j.string().min(1).optional(),status:j.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:j.array(k$).default([])}).strict(),kk=j.object({id:j.string().min(1),title:j.string().min(1),summary:j.string().min(1).optional(),status:j.string().min(1).optional(),priority:j.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:_4.optional(),resourceRefs:j.array(k$).default([]),evidenceRefs:j.array(X6).default([]),metadata:f0.optional()}).strict(),fk=j.object({renderer:j.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:j.string().min(1).optional(),entry:w4.optional(),imports:j.array(rQ).default([]),spec:f0.default({})}).strict(),hH=o$(_$.projectPanel).extend({projectId:Q2,provider:j.object({kind:iQ,id:j.string().min(1),name:j.string().min(1).optional(),sourcePackage:N$.optional(),externalId:N$.optional()}).strict(),kind:Ik,title:j.string().min(1),summary:j.string().min(1).optional(),state:wk.default("ready"),stateReason:j.string().min(1).optional(),generatedAt:_4,freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),metrics:j.array(gk).default([]),items:j.array(kk).default([]),actions:j.array(k$).default([]),resourceRefs:j.array(k$).default([]),evidenceRefs:j.array(X6).default([]),renderFragment:fk.optional(),warnings:j.array(j.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:j.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:j.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),Ck=o$(_$.projectSnapshot).extend({projectId:Q2,generatedAt:_4,status:Y2.default("unknown"),manifestRef:k$,renderManifestRef:k$.optional(),panels:j.array(hH).default([]),contextPacks:j.array(vH).default([]),proofBundleRefs:j.array(k$).default([]),resourceRefs:j.array(k$).default([]),evidenceRefs:j.array(X6).default([]),warnings:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:j.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),mH=j.object({id:j.string().min(1),kind:j.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:j.boolean().default(!0),command:j.string().min(1).optional(),expected:j.string().min(1).optional(),timeoutMs:j.number().int().positive().optional(),resourceRefs:j.array(k$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:j.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),Pk=o$(_$.validationPlan).extend({objective:j.string().min(1),subject:k$.optional(),checks:j.array(mH).min(1),verifier:X0.optional(),requiredEvidenceKinds:j.array(nQ).default([])}).strict(),Tk=j.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),Sk=j.enum(["draft","active","deprecated","archived"]),Zk=j.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),vk=j.object({key:j.string().regex(/^[A-Z][A-Z0-9_]*$/),description:j.string().min(1),required:j.boolean().default(!1),["secret"]:j.boolean().default(!1),group:j.string().min(1).optional(),default:j.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),yk=j.object({name:j.string().min(1),command:j.string().min(1),description:j.string().min(1).optional(),required:j.boolean().default(!1)}).strict(),hk=j.object({packageManager:j.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:j.array(j.string().min(1)).default([]),requiredFiles:j.array(j.string().min(1)).default([]),requiredDirectories:j.array(j.string().min(1)).default([]),optionalDirectories:j.array(j.string().min(1)).default([])}).strict(),mk=o$(_$.scaffoldManifest).extend({name:j.string().min(1),version:j.string().min(1),summary:j.string().min(1),type:Tk,status:Sk.default("draft"),capabilities:j.array(Zk).default([]),techStack:j.array(j.string().min(1)).default([]),tags:XJ,source:k$.optional(),output:hk,env:j.array(vk).default([]),scripts:j.array(yk).default([]),validationChecks:j.array(mH).default([]),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:j.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),xk=j.enum(["installed","failed","cancelled","partial","unknown"]),uk=o$(_$.scaffoldInstallRecord).extend({scaffoldId:j.string().min(1),scaffoldVersion:j.string().min(1).optional(),manifestRef:k$.optional(),target:k$,status:xk,installedAt:_4.optional(),installer:X0.optional(),packageManager:j.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:f0.optional(),generatedFiles:j.array(k$).default([]),evidenceRefs:j.array(X6).default([]),proofBundleRefs:j.array(k$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:j.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),UJ=j.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),pQ=j.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),xH=j.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),dk=j.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),ck=N$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),lk=j.enum(["active","stub","deprecated","archived"]),nk=j.enum(["stable","beta","canary","internal"]),ik=j.object({transport:j.enum(["http","stdio"]).default("http"),bin:j.string().min(1).optional(),url:k0.optional()}).strict(),rk=j.object({healthPath:j.string().min(1).default("/health"),port:j.number().int().positive().optional(),baseUrl:k0.optional()}).strict(),pk=j.object({bins:j.array(j.string().min(1)).default([]),mcp:ik.optional(),http:rk.optional()}).strict(),ok=o$(_$.app).extend({appId:UJ,npmName:pQ,repoFolder:UJ,githubUrl:ck,projectSlug:Q2,surfaces:pk.default({}),lifecycle:lk,releaseChannel:nk.default("stable"),summary:j.string().min(1).optional(),tags:XJ}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:j.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),tk=j.enum(["skill","ci","backfilled"]),ak=o$(_$.release).extend({appId:UJ,package:pQ,version:xH,gitSha:dk,publishedAt:_4,publishPath:tk,changelogRef:k$.optional(),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),sk=j.enum(["install","update","rollback","freeze-blocked"]),ek=j.object({cliVersion:j.string().min(1).optional(),mcpHealth:j.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),$f=o$(_$.rolloutRecord).extend({appId:UJ,package:pQ,version:xH,machine:N$,action:sk,result:Y2,verifiedBy:ek.optional(),at:_4,evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:j.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),_f=j.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),Jf=j.enum(["pending","queued","sent","failed","skipped","suppressed"]),Wf=j.object({channel:_f,status:Jf,deliveredAt:_4.optional(),detail:j.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:j.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),Uf=o$(_$.announcement).extend({campaignId:N$,appId:UJ.optional(),releaseRef:k$.optional(),channels:j.array(Wf).min(1),audienceRef:k$,sentAt:_4}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:j.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:j.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),Xf=j.enum(["tag","attribute","group"]),Gf=j.enum(["eq","neq","in","not_in","exists","not_exists"]),VH=j.union([j.string(),j.number(),j.boolean()]),Qf=j.object({kind:Xf,key:j.string().min(1).optional(),op:Gf.default("eq"),value:VH.optional(),values:j.array(VH).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:j.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),Yf=j.object({match:j.enum(["all","any"]).default("all"),predicates:j.array(Qf).min(1)}).strict(),qf=j.enum(["opt_in","opt_out","transactional","none"]),zf=o$(_$.audience).extend({audienceId:UJ,name:N$,definition:Yf,consentPolicy:qf,suppressionSyncedAt:G2}).strict(),mQ=["@hasna/cloud","open-cloud"],jf=j.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),Of=j.object({id:j.string().min(1),provider:jf,kind:j.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:j.string().min(1),region:j.string().min(1).optional(),accountId:j.string().min(1).optional(),uri:k0.optional(),machineScoped:j.boolean().default(!1)}).strict(),uH=o$(_$.appCloudManifest).extend({packageName:j.string().min(1),packageVersion:j.string().min(1).optional(),appId:j.string().min(1),repository:k$.optional(),storageMode:j.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:j.enum(["none","app_owned","external_service","local_cache"]),cloudResources:j.array(Of).default([]),localCache:j.object({path:j.string().min(1).optional(),pullMode:j.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:j.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:j.array(j.string().min(1)).default([...mQ]),dependencies:j.array(j.string().min(1)).default([]),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{let J=new Set([...mQ,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:j.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of mQ)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:j.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:j.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:j.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:j.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:j.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:j.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),dH=j.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),Df=j.enum(["low","medium","high","critical"]),cH=j.object({id:j.string().min(1),kind:dH,severity:Df,path:j.string().min(1).optional(),packageName:j.string().min(1).optional(),pattern:j.string().min(1),message:j.string().min(1),evidenceRefs:j.array(X6).default([])}).strict(),Lf=j.object({id:j.string().min(1),kind:dH,status:Y2,target:j.string().min(1),command:j.string().min(1).optional(),evidenceRefs:j.array(X6).default([]),findings:j.array(cH).default([])}).strict(),Bf=o$(_$.noCloudEvidencePack).extend({subject:k$,packageName:j.string().min(1).optional(),packageVersion:j.string().min(1).optional(),generatedBy:X0.optional(),scanMode:j.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:Y2,verdict:j.enum(["passed","failed","warning","not_run"]),appCloudManifest:uH.optional(),checks:j.array(Lf).min(1),findings:j.array(cH).default([]),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Q)=>Q.severity==="high"||Q.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),Hf=j.object({checkId:j.string().min(1),status:Y2,summary:j.string().min(1).optional(),startedAt:G2,finishedAt:G2,evidenceRefs:j.array(X6).default([])}).strict(),Nf=o$(_$.proofBundle).extend({subject:k$,validationPlanRef:k$.optional(),status:Y2,verdict:j.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:j.array(Hf).default([]),verifier:X0.optional(),evidenceRefs:j.array(X6).default([]),residualRisks:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),Vf=o$(_$.workRun).extend({objective:j.string().min(1),status:Y2,actor:X0,traceId:j.string().min(1).optional(),startedAt:G2,finishedAt:G2,constraints:j.array(j.string().min(1)).default([]),resourceRefs:j.array(k$).default([]),decisions:j.array(ZH).default([]),costEstimates:j.array(UU).default([]),evidenceRefs:j.array(X6).default([]),validationPlanRefs:j.array(k$).default([]),proofBundleRefs:j.array(k$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),Ff=j.object({id:j.string().min(1),at:_4,kind:j.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:j.string().min(1),resourceRefs:j.array(k$).default([]),evidenceRefs:j.array(X6).default([]),costEstimate:UU.optional()}).strict(),Rf=o$(_$.agentTrajectory).extend({actor:X0,workRunRef:k$.optional(),events:j.array(Ff).default([]),outcome:j.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:k$.optional()}).strict(),Kf="v1",Mf=j.enum(["library","cli-with-store","service","saas"]),Af=["local","self-hosted","cloud"],lH=j.enum(Af),bf=j.enum(["supported","deferred","unsupported"]),Ef=j.enum(["none","local-only","api-key","session","service-token","custom"]),xQ=j.object({method:j.enum(["GET","POST","PUT","PATCH","DELETE"]),path:j.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:j.boolean().default(!1),description:j.string().min(1).optional()}).strict(),wf=j.object({id:j.string().min(1),kind:j.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:j.boolean().default(!0),command:j.string().min(1).optional(),evidenceRef:X6.optional(),status:j.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:j.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:j.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),If=j.object({name:j.string().min(1),status:bf,bin:j.string().min(1).optional(),mcpBin:j.string().min(1).optional(),authMode:Ef,deploymentModes:j.array(lH).min(1),health:xQ.optional(),readiness:xQ.optional(),version:xQ.optional(),apiBasePath:j.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:j.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:j.string().min(1).optional(),readinessGates:j.array(wf).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:j.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:j.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:j.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:j.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),gf=["local","cloud"],nH=j.enum(gf);var kf=j.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),ff=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function Cf($){return ff.map((_)=>`${$}${_}`)}function FH($){return`hasna/oss/${$}/database-url`}var Pf=j.object({mode:nH,envPrefix:j.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:j.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:j.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:j.string().min(1).optional()}).strict(),Tf=j.object({$schema:j.string().min(1).optional(),schema:j.literal(_$.serviceContract),name:kf,class:Mf,contractVersion:j.literal(Kf),kitVersion:j.string().min(1),description:j.string().min(1).optional(),bins:j.array(j.string().min(1)).default([]),storage:Pf.optional(),deploymentModes:j.array(lH).default(["local"]),serviceSurfaces:j.array(If).default([]),metadata:f0.optional()}).strict().superRefine(($,_)=>{let J=new Set(Cf($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:j.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:j.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:j.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==FH($.name))_.addIssue({code:j.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${FH($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:j.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:j.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:j.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:j.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:j.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:j.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Q,Y]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Y))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface deployment mode "${Y}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Q]})}}),vo=j.object({status:j.enum(["ok","degraded","unavailable"]),version:j.string().min(1),mode:nH}).strict(),yo=j.object({ready:j.boolean(),reason:j.string().min(1).optional()}).strict(),ho=j.object({version:j.string().min(1)}).strict(),Sf=j.enum(["info","notice","breaking","critical"]),Zf=j.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),vf=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],yf=j.enum(vf);var hf=j.enum(["fleet","package","machine"]),iH=o$(_$.commsEventEnvelope).extend({type:Zf,severity:Sf,scope:hf,summary:j.string().min(1).optional(),source:X0.optional(),affected_packages:j.array(N$).default([]),affected_machines:j.array(N$).default([]),action_required:j.boolean().default(!1),ack_by:_4.optional(),dedupe_key:N$,resourceRefs:j.array(k$).default([]),evidenceRefs:j.array(X6).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:j.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),mf=j.enum(["fleet","package","product","loop-lane","initiative","personal"]),xf=j.enum(["quiet","work","firehose"]),uf=N$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),df=o$(_$.commsChannelMetadata).extend({class:mf,noise:xf.optional(),owner:N$.optional(),until:uf.optional(),successor:N$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:j.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:j.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),RH={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},cf=o$(_$.commsMessageMetadata).extend({tag:yf,envelope:iH}).strict().superRefine(($,_)=>{let J=RH[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:j.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:j.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(RH))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:j.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var mo={[_$.actorRef]:Xk,[_$.resourceRef]:Gk,[_$.evidenceRef]:Yk,[_$.workRun]:Vf,[_$.decisionEnvelope]:ZH,[_$.costEstimate]:UU,[_$.capabilityCard]:zk,[_$.providerLiveModeStandard]:Hk,[_$.contextPack]:vH,[_$.integrationRef]:yH,[_$.projectManifest]:Kk,[_$.projectPanel]:hH,[_$.projectSnapshot]:Ck,[_$.renderManifest]:Ek,[_$.agentTrajectory]:Rf,[_$.validationPlan]:Pk,[_$.proofBundle]:Nf,[_$.scaffoldManifest]:mk,[_$.scaffoldInstallRecord]:uk,[_$.appCloudManifest]:uH,[_$.noCloudEvidencePack]:Bf,[_$.serviceContract]:Tf,[_$.commsEventEnvelope]:iH,[_$.commsChannelMetadata]:df,[_$.commsMessageMetadata]:cf,[_$.app]:ok,[_$.release]:ak,[_$.rolloutRecord]:$f,[_$.announcement]:Uf,[_$.audience]:zf};function lf($){return $.toUpperCase().replace(/-/g,"_")}function rH($){let _=lf($);return{modeKeys:[`HASNA_${_}_STORAGE_MODE`,`HASNA_${_}_MODE`,`${_}_STORAGE_MODE`,`${_}_MODE`],apiUrlKeys:[`HASNA_${_}_API_URL`,`${_}_API_URL`],apiKeyKeys:[`HASNA_${_}_API_KEY`,`${_}_API_KEY`]}}var nf=Object.defineProperty,rf=($)=>$;function pf($,_){this[$]=rf.bind(null,_)}var of=($,_)=>{for(var J in _)nf($,J,{get:_[J],enumerable:!0,configurable:!0,set:pf.bind(_,J)})},O={};of(O,{void:()=>TC,util:()=>m$,unknown:()=>CC,union:()=>yC,undefined:()=>gC,tuple:()=>xC,transformer:()=>tH,symbol:()=>IC,string:()=>GN,strictObject:()=>vC,setErrorMap:()=>sf,set:()=>cC,record:()=>uC,quotelessJson:()=>tf,promise:()=>oC,preprocess:()=>sC,pipeline:()=>eC,ostring:()=>$P,optional:()=>tC,onumber:()=>_P,oboolean:()=>JP,objectUtil:()=>sQ,object:()=>ZC,number:()=>QN,nullable:()=>aC,null:()=>kC,never:()=>PC,nativeEnum:()=>pC,nan:()=>bC,map:()=>dC,makeIssue:()=>M9,literal:()=>iC,lazy:()=>nC,late:()=>MC,isValid:()=>q2,isDirty:()=>$Y,isAsync:()=>XU,isAborted:()=>eQ,intersection:()=>mC,instanceof:()=>AC,getParsedType:()=>P0,getErrorMap:()=>K9,function:()=>lC,enum:()=>rC,effect:()=>tH,discriminatedUnion:()=>hC,defaultErrorMap:()=>qJ,datetimeRegex:()=>WN,date:()=>wC,custom:()=>XN,coerce:()=>WP,boolean:()=>YN,bigint:()=>EC,array:()=>SC,any:()=>fC,addIssueToContext:()=>c,ZodVoid:()=>QU,ZodUnknown:()=>D1,ZodUnion:()=>DJ,ZodUndefined:()=>jJ,ZodType:()=>P$,ZodTuple:()=>Q0,ZodTransformer:()=>D4,ZodSymbol:()=>GU,ZodString:()=>P4,ZodSet:()=>O2,ZodSchema:()=>P$,ZodRecord:()=>YU,ZodReadonly:()=>RJ,ZodPromise:()=>D2,ZodPipeline:()=>jU,ZodParsedType:()=>o,ZodOptional:()=>S4,ZodObject:()=>B6,ZodNumber:()=>L1,ZodNullable:()=>T0,ZodNull:()=>OJ,ZodNever:()=>G0,ZodNativeEnum:()=>NJ,ZodNaN:()=>zU,ZodMap:()=>qU,ZodLiteral:()=>HJ,ZodLazy:()=>BJ,ZodIssueCode:()=>S,ZodIntersection:()=>LJ,ZodFunction:()=>YJ,ZodFirstPartyTypeKind:()=>L$,ZodError:()=>J4,ZodEnum:()=>H1,ZodEffects:()=>D4,ZodDiscriminatedUnion:()=>A9,ZodDefault:()=>VJ,ZodDate:()=>z2,ZodCatch:()=>FJ,ZodBranded:()=>b9,ZodBoolean:()=>zJ,ZodBigInt:()=>B1,ZodArray:()=>T4,ZodAny:()=>j2,Schema:()=>P$,ParseStatus:()=>C6,OK:()=>u6,NEVER:()=>UP,INVALID:()=>z$,EMPTY_PATH:()=>ef,DIRTY:()=>QJ,BRAND:()=>KC});var m$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Q)=>typeof W[W[Q]]!=="number"),G={};for(let Q of X)G[Q]=W[Q];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(m$||(m$={}));var sQ;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(sQ||(sQ={}));var o=m$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),P0=($)=>{switch(typeof $){case"undefined":return o.undefined;case"string":return o.string;case"number":return Number.isNaN($)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":if(Array.isArray($))return o.array;if($===null)return o.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return o.promise;if(typeof Map<"u"&&$ instanceof Map)return o.map;if(typeof Set<"u"&&$ instanceof Set)return o.set;if(typeof Date<"u"&&$ instanceof Date)return o.date;return o.object;default:return o.unknown}},S=m$.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"]),tf=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class J4 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Q=0;while(Q_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}J4.create=($)=>{return new J4($)};var af=($,_)=>{let J;switch($.code){case S.invalid_type:if($.received===o.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case S.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,m$.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:J=`Unrecognized key(s) in object: ${m$.joinValues($.keys,", ")}`;break;case S.invalid_union:J="Invalid input";break;case S.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${m$.joinValues($.options)}`;break;case S.invalid_enum_value:J=`Invalid enum value. Expected ${m$.joinValues($.options)}, received '${$.received}'`;break;case S.invalid_arguments:J="Invalid function arguments";break;case S.invalid_return_type:J="Invalid function return type";break;case S.invalid_date:J="Invalid date";break;case S.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else m$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case S.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case S.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case S.custom:J="Invalid input";break;case S.invalid_intersection_types:J="Intersection results could not be merged";break;case S.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case S.not_finite:J="Number must be finite";break;default:J=_.defaultError,m$.assertNever($)}return{message:J}},qJ=af,$N=qJ;function sf($){$N=$}function K9(){return $N}var M9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Q="",Y=U.filter((q)=>!!q).slice().reverse();for(let q of Y)Q=q(G,{data:_,defaultError:Q}).message;return{...W,path:X,message:Q}},ef=[];function c($,_){let J=K9(),U=M9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===qJ?void 0:qJ].filter((W)=>!!W)});$.common.issues.push(U)}class C6{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return z$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return C6.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return z$;if(X.status==="aborted")return z$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var z$=Object.freeze({status:"aborted"}),QJ=($)=>({status:"dirty",value:$}),u6=($)=>({status:"valid",value:$}),eQ=($)=>$.status==="aborted",$Y=($)=>$.status==="dirty",q2=($)=>$.status==="valid",XU=($)=>typeof Promise<"u"&&$ instanceof Promise,U$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(U$||(U$={}));class Z4{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var pH=($,_)=>{if(q2(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new J4($.common.issues);return this._error=J,this._error}}}};function E$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Q)=>{let{message:Y}=$;if(G.code==="invalid_enum_value")return{message:Y??Q.defaultError};if(typeof Q.data>"u")return{message:Y??U??Q.defaultError};if(G.code!=="invalid_type")return{message:Q.defaultError};return{message:Y??J??Q.defaultError}},description:W}}class P${get description(){return this._def.description}_getType($){return P0($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:P0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new C6,ctx:{common:$.parent.common,data:$.data,parsedType:P0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(XU(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:P0($)},U=this._parseSync({data:$,path:J.path,parent:J});return pH(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:P0($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return q2(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>q2(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:P0($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(XU(U)?U:Promise.resolve(U));return pH(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:S.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Q)=>{if(!Q)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new D4({schema:this,typeName:L$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return S4.create(this,this._def)}nullable(){return T0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return T4.create(this)}promise(){return D2.create(this,this._def)}or($){return DJ.create([this,$],this._def)}and($){return LJ.create(this,$,this._def)}transform($){return new D4({...E$(this._def),schema:this,typeName:L$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new VJ({...E$(this._def),innerType:this,defaultValue:_,typeName:L$.ZodDefault})}brand(){return new b9({typeName:L$.ZodBranded,type:this,...E$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new FJ({...E$(this._def),innerType:this,catchValue:_,typeName:L$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return jU.create(this,$)}readonly(){return RJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var $C=/^c[^\s-]{8,}$/i,_C=/^[0-9a-z]+$/,JC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,WC=/^[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,UC=/^[a-z0-9_-]{21}$/i,XC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,GC=/^[-+]?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)?)??$/,QC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,YC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oQ,qC=/^(?:(?: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])$/,zC=/^(?:(?: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])$/,jC=/^(([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]))$/,OC=/^(([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])$/,DC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,LC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_N="((\\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])))",BC=new RegExp(`^${_N}$`);function JN($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function HC($){return new RegExp(`^${JN($)}$`)}function WN($){let _=`${_N}T${JN($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function NC($,_){if((_==="v4"||!_)&&qC.test($))return!0;if((_==="v6"||!_)&&jC.test($))return!0;return!1}function VC($,_){if(!XC.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function FC($,_){if((_==="v4"||!_)&&zC.test($))return!0;if((_==="v6"||!_)&&OC.test($))return!0;return!1}class P4 extends P${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==o.string){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.string,received:W.parsedType}),z$}let J=new C6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),c(U,{code:S.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:S.invalid_string,...U$.errToObj(J)})}_addCheck($){return new P4({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...U$.errToObj($)})}url($){return this._addCheck({kind:"url",...U$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...U$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...U$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...U$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...U$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...U$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...U$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...U$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...U$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...U$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...U$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...U$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...U$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...U$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...U$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...U$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...U$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...U$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...U$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...U$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...U$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...U$.errToObj(_)})}nonempty($){return this.min(1,U$.errToObj($))}trim(){return new P4({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new P4({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new P4({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}P4.create=($)=>{return new P4({checks:[],typeName:L$.ZodString,coerce:$?.coerce??!1,...E$($)})};function RC($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class L1 extends P${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==o.number){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.number,received:W.parsedType}),z$}let J=void 0,U=new C6;for(let W of this._def.checks)if(W.kind==="int"){if(!m$.isInteger($.data))J=this._getOrReturnCtx($,J),c(J,{code:S.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),c(J,{code:S.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(RC($.data,W.value)!==0)J=this._getOrReturnCtx($,J),c(J,{code:S.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),c(J,{code:S.not_finite,message:W.message}),U.dirty()}else m$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,U$.toString(_))}gt($,_){return this.setLimit("min",$,!1,U$.toString(_))}lte($,_){return this.setLimit("max",$,!0,U$.toString(_))}lt($,_){return this.setLimit("max",$,!1,U$.toString(_))}setLimit($,_,J,U){return new L1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:U$.toString(U)}]})}_addCheck($){return new L1({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:U$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:U$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:U$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&m$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}L1.create=($)=>{return new L1({checks:[],typeName:L$.ZodNumber,coerce:$?.coerce||!1,...E$($)})};class B1 extends P${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==o.bigint)return this._getInvalidInput($);let J=void 0,U=new C6;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),c(J,{code:S.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),c(J,{code:S.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else m$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return c(_,{code:S.invalid_type,expected:o.bigint,received:_.parsedType}),z$}gte($,_){return this.setLimit("min",$,!0,U$.toString(_))}gt($,_){return this.setLimit("min",$,!1,U$.toString(_))}lte($,_){return this.setLimit("max",$,!0,U$.toString(_))}lt($,_){return this.setLimit("max",$,!1,U$.toString(_))}setLimit($,_,J,U){return new B1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:U$.toString(U)}]})}_addCheck($){return new B1({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:U$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}B1.create=($)=>{return new B1({checks:[],typeName:L$.ZodBigInt,coerce:$?.coerce??!1,...E$($)})};class zJ extends P${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==o.boolean){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.boolean,received:J.parsedType}),z$}return u6($.data)}}zJ.create=($)=>{return new zJ({typeName:L$.ZodBoolean,coerce:$?.coerce||!1,...E$($)})};class z2 extends P${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==o.date){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.date,received:W.parsedType}),z$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_date}),z$}let J=new C6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),c(U,{code:S.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else m$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new z2({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:U$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:U$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}z2.create=($)=>{return new z2({checks:[],coerce:$?.coerce||!1,typeName:L$.ZodDate,...E$($)})};class GU extends P${_parse($){if(this._getType($)!==o.symbol){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.symbol,received:J.parsedType}),z$}return u6($.data)}}GU.create=($)=>{return new GU({typeName:L$.ZodSymbol,...E$($)})};class jJ extends P${_parse($){if(this._getType($)!==o.undefined){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.undefined,received:J.parsedType}),z$}return u6($.data)}}jJ.create=($)=>{return new jJ({typeName:L$.ZodUndefined,...E$($)})};class OJ extends P${_parse($){if(this._getType($)!==o.null){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.null,received:J.parsedType}),z$}return u6($.data)}}OJ.create=($)=>{return new OJ({typeName:L$.ZodNull,...E$($)})};class j2 extends P${constructor(){super(...arguments);this._any=!0}_parse($){return u6($.data)}}j2.create=($)=>{return new j2({typeName:L$.ZodAny,...E$($)})};class D1 extends P${constructor(){super(...arguments);this._unknown=!0}_parse($){return u6($.data)}}D1.create=($)=>{return new D1({typeName:L$.ZodUnknown,...E$($)})};class G0 extends P${_parse($){let _=this._getOrReturnCtx($);return c(_,{code:S.invalid_type,expected:o.never,received:_.parsedType}),z$}}G0.create=($)=>{return new G0({typeName:L$.ZodNever,...E$($)})};class QU extends P${_parse($){if(this._getType($)!==o.undefined){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.void,received:J.parsedType}),z$}return u6($.data)}}QU.create=($)=>{return new QU({typeName:L$.ZodVoid,...E$($)})};class T4 extends P${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==o.array)return c(_,{code:S.invalid_type,expected:o.array,received:_.parsedType}),z$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)c(_,{code:S.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new Z4(_,X,_.path,G))})).then((X)=>{return C6.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new Z4(_,X,_.path,G))});return C6.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new T4({...this._def,minLength:{value:$,message:U$.toString(_)}})}max($,_){return new T4({...this._def,maxLength:{value:$,message:U$.toString(_)}})}length($,_){return new T4({...this._def,exactLength:{value:$,message:U$.toString(_)}})}nonempty($){return this.min(1,$)}}T4.create=($,_)=>{return new T4({type:$,minLength:null,maxLength:null,exactLength:null,typeName:L$.ZodArray,...E$(_)})};function GJ($){if($ instanceof B6){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=S4.create(GJ(U))}return new B6({...$._def,shape:()=>_})}else if($ instanceof T4)return new T4({...$._def,type:GJ($.element)});else if($ instanceof S4)return S4.create(GJ($.unwrap()));else if($ instanceof T0)return T0.create(GJ($.unwrap()));else if($ instanceof Q0)return Q0.create($.items.map((_)=>GJ(_)));else return $}class B6 extends P${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=m$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==o.object){let Y=this._getOrReturnCtx($);return c(Y,{code:S.invalid_type,expected:o.object,received:Y.parsedType}),z$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof G0&&this._def.unknownKeys==="strip")){for(let Y in U.data)if(!X.includes(Y))G.push(Y)}let Q=[];for(let Y of X){let q=W[Y],L=U.data[Y];Q.push({key:{status:"valid",value:Y},value:q._parse(new Z4(U,L,U.path,Y)),alwaysSet:Y in U.data})}if(this._def.catchall instanceof G0){let Y=this._def.unknownKeys;if(Y==="passthrough")for(let q of G)Q.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Y==="strict"){if(G.length>0)c(U,{code:S.unrecognized_keys,keys:G}),J.dirty()}else if(Y==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Y=this._def.catchall;for(let q of G){let L=U.data[q];Q.push({key:{status:"valid",value:q},value:Y._parse(new Z4(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Y=[];for(let q of Q){let L=await q.key,N=await q.value;Y.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Y}).then((Y)=>{return C6.mergeObjectSync(J,Y)});else return C6.mergeObjectSync(J,Q)}get shape(){return this._def.shape()}strict($){return U$.errToObj,new B6({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:U$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new B6({...this._def,unknownKeys:"strip"})}passthrough(){return new B6({...this._def,unknownKeys:"passthrough"})}extend($){return new B6({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new B6({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:L$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new B6({...this._def,catchall:$})}pick($){let _={};for(let J of m$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new B6({...this._def,shape:()=>_})}omit($){let _={};for(let J of m$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new B6({...this._def,shape:()=>_})}deepPartial(){return GJ(this)}partial($){let _={};for(let J of m$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new B6({...this._def,shape:()=>_})}required($){let _={};for(let J of m$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof S4)W=W._def.innerType;_[J]=W}return new B6({...this._def,shape:()=>_})}keyof(){return UN(m$.objectKeys(this.shape))}}B6.create=($,_)=>{return new B6({shape:()=>$,unknownKeys:"strip",catchall:G0.create(),typeName:L$.ZodObject,...E$(_)})};B6.strictCreate=($,_)=>{return new B6({shape:()=>$,unknownKeys:"strict",catchall:G0.create(),typeName:L$.ZodObject,...E$(_)})};B6.lazycreate=($,_)=>{return new B6({shape:$,unknownKeys:"strip",catchall:G0.create(),typeName:L$.ZodObject,...E$(_)})};class DJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new J4(G.ctx.common.issues));return c(_,{code:S.invalid_union,unionErrors:X}),z$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Q of J){let Y={..._,common:{..._.common,issues:[]},parent:null},q=Q._parseSync({data:_.data,path:_.path,parent:Y});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Y};if(Y.common.issues.length)X.push(Y.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Q)=>new J4(Q));return c(_,{code:S.invalid_union,unionErrors:G}),z$}}get options(){return this._def.options}}DJ.create=($,_)=>{return new DJ({options:$,typeName:L$.ZodUnion,...E$(_)})};var C0=($)=>{if($ instanceof BJ)return C0($.schema);else if($ instanceof D4)return C0($.innerType());else if($ instanceof HJ)return[$.value];else if($ instanceof H1)return $.options;else if($ instanceof NJ)return m$.objectValues($.enum);else if($ instanceof VJ)return C0($._def.innerType);else if($ instanceof jJ)return[void 0];else if($ instanceof OJ)return[null];else if($ instanceof S4)return[void 0,...C0($.unwrap())];else if($ instanceof T0)return[null,...C0($.unwrap())];else if($ instanceof b9)return C0($.unwrap());else if($ instanceof RJ)return C0($.unwrap());else if($ instanceof FJ)return C0($._def.innerType);else return[]};class A9 extends P${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.object)return c(_,{code:S.invalid_type,expected:o.object,received:_.parsedType}),z$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return c(_,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),z$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=C0(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new A9({typeName:L$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...E$(J)})}}function _Y($,_){let J=P0($),U=P0(_);if($===_)return{valid:!0,data:$};else if(J===o.object&&U===o.object){let W=m$.objectKeys(_),X=m$.objectKeys($).filter((Q)=>W.indexOf(Q)!==-1),G={...$,..._};for(let Q of X){let Y=_Y($[Q],_[Q]);if(!Y.valid)return{valid:!1};G[Q]=Y.data}return{valid:!0,data:G}}else if(J===o.array&&U===o.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Q=_[X],Y=_Y(G,Q);if(!Y.valid)return{valid:!1};W.push(Y.data)}return{valid:!0,data:W}}else if(J===o.date&&U===o.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class LJ extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(eQ(W)||eQ(X))return z$;let G=_Y(W.value,X.value);if(!G.valid)return c(J,{code:S.invalid_intersection_types}),z$;if($Y(W)||$Y(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}LJ.create=($,_,J)=>{return new LJ({left:$,right:_,typeName:L$.ZodIntersection,...E$(J)})};class Q0 extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.array)return c(J,{code:S.invalid_type,expected:o.array,received:J.parsedType}),z$;if(J.data.lengththis._def.items.length)c(J,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Q=this._def.items[G]||this._def.rest;if(!Q)return null;return Q._parse(new Z4(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return C6.mergeArray(_,X)});else return C6.mergeArray(_,W)}get items(){return this._def.items}rest($){return new Q0({...this._def,rest:$})}}Q0.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Q0({items:$,typeName:L$.ZodTuple,rest:null,...E$(_)})};class YU extends P${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.object)return c(J,{code:S.invalid_type,expected:o.object,received:J.parsedType}),z$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new Z4(J,G,J.path,G)),value:X._parse(new Z4(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return C6.mergeObjectAsync(_,U);else return C6.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof P$)return new YU({keyType:$,valueType:_,typeName:L$.ZodRecord,...E$(J)});return new YU({keyType:P4.create(),valueType:$,typeName:L$.ZodRecord,...E$(_)})}}class qU extends P${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.map)return c(J,{code:S.invalid_type,expected:o.map,received:J.parsedType}),z$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Q],Y)=>{return{key:U._parse(new Z4(J,G,J.path,[Y,"key"])),value:W._parse(new Z4(J,Q,J.path,[Y,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Q of X){let Y=await Q.key,q=await Q.value;if(Y.status==="aborted"||q.status==="aborted")return z$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Q of X){let{key:Y,value:q}=Q;if(Y.status==="aborted"||q.status==="aborted")return z$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}}}}qU.create=($,_,J)=>{return new qU({valueType:_,keyType:$,typeName:L$.ZodMap,...E$(J)})};class O2 extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.set)return c(J,{code:S.invalid_type,expected:o.set,received:J.parsedType}),z$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)c(J,{code:S.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Q){let Y=new Set;for(let q of Q){if(q.status==="aborted")return z$;if(q.status==="dirty")_.dirty();Y.add(q.value)}return{status:_.value,value:Y}}let G=[...J.data.values()].map((Q,Y)=>W._parse(new Z4(J,Q,J.path,Y)));if(J.common.async)return Promise.all(G).then((Q)=>X(Q));else return X(G)}min($,_){return new O2({...this._def,minSize:{value:$,message:U$.toString(_)}})}max($,_){return new O2({...this._def,maxSize:{value:$,message:U$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}O2.create=($,_)=>{return new O2({valueType:$,minSize:null,maxSize:null,typeName:L$.ZodSet,...E$(_)})};class YJ extends P${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.function)return c(_,{code:S.invalid_type,expected:o.function,received:_.parsedType}),z$;function J(G,Q){return M9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,K9(),qJ].filter((Y)=>!!Y),issueData:{code:S.invalid_arguments,argumentsError:Q}})}function U(G,Q){return M9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,K9(),qJ].filter((Y)=>!!Y),issueData:{code:S.invalid_return_type,returnTypeError:Q}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof D2){let G=this;return u6(async function(...Q){let Y=new J4([]),q=await G._def.args.parseAsync(Q,W).catch((F)=>{throw Y.addIssue(J(Q,F)),Y}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((F)=>{throw Y.addIssue(U(L,F)),Y})})}else{let G=this;return u6(function(...Q){let Y=G._def.args.safeParse(Q,W);if(!Y.success)throw new J4([J(Q,Y.error)]);let q=Reflect.apply(X,this,Y.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new J4([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new YJ({...this._def,args:Q0.create($).rest(D1.create())})}returns($){return new YJ({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new YJ({args:$?$:Q0.create([]).rest(D1.create()),returns:_||D1.create(),typeName:L$.ZodFunction,...E$(J)})}}class BJ extends P${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}BJ.create=($,_)=>{return new BJ({getter:$,typeName:L$.ZodLazy,...E$(_)})};class HJ extends P${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return c(_,{received:_.data,code:S.invalid_literal,expected:this._def.value}),z$}return{status:"valid",value:$.data}}get value(){return this._def.value}}HJ.create=($,_)=>{return new HJ({value:$,typeName:L$.ZodLiteral,...E$(_)})};function UN($,_){return new H1({values:$,typeName:L$.ZodEnum,...E$(_)})}class H1 extends P${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return c(_,{expected:m$.joinValues(J),received:_.parsedType,code:S.invalid_type}),z$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return c(_,{received:_.data,code:S.invalid_enum_value,options:J}),z$}return u6($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return H1.create($,{...this._def,..._})}exclude($,_=this._def){return H1.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}H1.create=UN;class NJ extends P${_parse($){let _=m$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==o.string&&J.parsedType!==o.number){let U=m$.objectValues(_);return c(J,{expected:m$.joinValues(U),received:J.parsedType,code:S.invalid_type}),z$}if(!this._cache)this._cache=new Set(m$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=m$.objectValues(_);return c(J,{received:J.data,code:S.invalid_enum_value,options:U}),z$}return u6($.data)}get enum(){return this._def.values}}NJ.create=($,_)=>{return new NJ({values:$,typeName:L$.ZodNativeEnum,...E$(_)})};class D2 extends P${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.promise&&_.common.async===!1)return c(_,{code:S.invalid_type,expected:o.promise,received:_.parsedType}),z$;let J=_.parsedType===o.promise?_.data:Promise.resolve(_.data);return u6(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}D2.create=($,_)=>{return new D2({type:$,typeName:L$.ZodPromise,...E$(_)})};class D4 extends P${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(c(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return z$;let Q=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Q.status==="aborted")return z$;if(Q.status==="dirty")return QJ(Q.value);if(_.value==="dirty")return QJ(Q.value);return Q});else{if(_.value==="aborted")return z$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return z$;if(G.status==="dirty")return QJ(G.value);if(_.value==="dirty")return QJ(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Q=U.refinement(G,W);if(J.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return z$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return z$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!q2(X))return z$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!q2(X))return z$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});m$.assertNever(U)}}D4.create=($,_,J)=>{return new D4({schema:$,typeName:L$.ZodEffects,effect:_,...E$(J)})};D4.createWithPreprocess=($,_,J)=>{return new D4({schema:_,effect:{type:"preprocess",transform:$},typeName:L$.ZodEffects,...E$(J)})};class S4 extends P${_parse($){if(this._getType($)===o.undefined)return u6(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}S4.create=($,_)=>{return new S4({innerType:$,typeName:L$.ZodOptional,...E$(_)})};class T0 extends P${_parse($){if(this._getType($)===o.null)return u6(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}T0.create=($,_)=>{return new T0({innerType:$,typeName:L$.ZodNullable,...E$(_)})};class VJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===o.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}VJ.create=($,_)=>{return new VJ({innerType:$,typeName:L$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...E$(_)})};class FJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(XU(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new J4(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new J4(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}FJ.create=($,_)=>{return new FJ({innerType:$,typeName:L$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...E$(_)})};class zU extends P${_parse($){if(this._getType($)!==o.nan){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.nan,received:J.parsedType}),z$}return{status:"valid",value:$.data}}}zU.create=($)=>{return new zU({typeName:L$.ZodNaN,...E$($)})};var KC=Symbol("zod_brand");class b9 extends P${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class jU extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return z$;if(W.status==="dirty")return _.dirty(),QJ(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return z$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new jU({in:$,out:_,typeName:L$.ZodPipeline})}}class RJ extends P${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(q2(U))U.value=Object.freeze(U.value);return U};return XU(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}RJ.create=($,_)=>{return new RJ({innerType:$,typeName:L$.ZodReadonly,...E$(_)})};function oH($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function XN($,_={},J){if($)return j2.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Q=oH(_,U),Y=Q.fatal??J??!0;W.addIssue({code:"custom",...Q,fatal:Y})}});if(!X){let G=oH(_,U),Q=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Q})}return});return j2.create()}var MC={object:B6.lazycreate},L$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(L$||(L$={}));var AC=($,_={message:`Input not instance of ${$.name}`})=>XN((J)=>J instanceof $,_),GN=P4.create,QN=L1.create,bC=zU.create,EC=B1.create,YN=zJ.create,wC=z2.create,IC=GU.create,gC=jJ.create,kC=OJ.create,fC=j2.create,CC=D1.create,PC=G0.create,TC=QU.create,SC=T4.create,ZC=B6.create,vC=B6.strictCreate,yC=DJ.create,hC=A9.create,mC=LJ.create,xC=Q0.create,uC=YU.create,dC=qU.create,cC=O2.create,lC=YJ.create,nC=BJ.create,iC=HJ.create,rC=H1.create,pC=NJ.create,oC=D2.create,tH=D4.create,tC=S4.create,aC=T0.create,sC=D4.createWithPreprocess,eC=jU.create,$P=()=>GN().optional(),_P=()=>QN().optional(),JP=()=>YN().optional(),WP={string:($)=>P4.create({...$,coerce:!0}),number:($)=>L1.create({...$,coerce:!0}),boolean:($)=>zJ.create({...$,coerce:!0}),bigint:($)=>B1.create({...$,coerce:!0}),date:($)=>z2.create({...$,coerce:!0})},UP=z$;var W$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},qN=O.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),W4=O.string().datetime(),V$=O.string().trim().min(1),S0=V$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),zN=O.string().regex(/^[a-fA-F0-9]{64}$/),jN=O.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),Z0=O.record(O.unknown()),AJ=O.array(O.string().min(1)).default([]),L2=W4.nullable().optional(),XP=new Set(["succeeded","failed","cancelled","blocked","skipped"]),H2=O.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function t$($){return O.object({schema:O.literal($),id:O.string().min(1),createdAt:W4,updatedAt:L2,metadata:Z0.optional()}).strict()}var uo=O.object({schema:qN,id:O.string().min(1),createdAt:W4,updatedAt:L2,metadata:Z0.optional()}).strict(),ON=O.enum(["agent","human","service","model","workflow","system"]),GP=t$(W$.actorRef).extend({kind:ON,name:O.string().min(1).optional(),provider:O.string().min(1).optional(),accountId:O.string().min(1).optional(),machineId:O.string().min(1).optional(),capabilities:O.array(O.string().min(1)).default([])}).strict(),Y0=O.object({kind:ON,id:O.string().min(1),name:O.string().min(1).optional(),provider:O.string().min(1).optional(),accountId:O.string().min(1).optional(),machineId:O.string().min(1).optional()}).strict(),DN=O.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),QP=t$(W$.resourceRef).extend({kind:DN,name:O.string().min(1).optional(),uri:S0.optional(),externalId:V$.optional(),sourcePackage:V$.optional(),tags:AJ}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:O.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),C$=O.object({kind:DN,id:O.string().min(1),name:O.string().min(1).optional(),uri:S0.optional(),externalId:V$.optional(),sourcePackage:V$.optional(),tags:AJ}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:O.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),JY=O.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),YP=O.enum(["none","partial","full","unknown"]),qP=t$(W$.evidenceRef).extend({kind:JY,uri:S0,sha256:zN.optional(),summary:O.string().min(1).optional(),contentType:O.string().min(1).optional(),sizeBytes:O.number().int().nonnegative().optional(),redaction:YP.default("unknown"),producer:Y0.optional(),resourceRefs:O.array(C$).default([]),tags:AJ}).strict(),G6=O.object({id:O.string().min(1),kind:JY.optional(),uri:S0.optional(),sha256:zN.optional(),summary:O.string().min(1).optional()}).strict(),OU=t$(W$.costEstimate).extend({currency:O.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:O.number().int().nonnegative(),provider:O.string().min(1).optional(),model:O.string().min(1).optional(),accountId:O.string().min(1).optional(),promptTokens:O.number().int().nonnegative().optional(),completionTokens:O.number().int().nonnegative().optional(),totalTokens:O.number().int().nonnegative().optional(),basis:O.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:O.array(C$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:O.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),zP=O.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),LN=t$(W$.decisionEnvelope).extend({decisionType:O.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:zP,actor:Y0.optional(),traceId:O.string().min(1).optional(),inputHash:jN.optional(),policyBundleId:O.string().min(1).optional(),selected:O.array(C$).default([]),skipped:O.array(C$).default([]),reason:O.string().min(1),obligations:O.array(O.string().min(1)).default([]),redactions:O.array(O.string().min(1)).default([]),costEstimate:OU.optional(),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),jP=t$(W$.capabilityCard).extend({kind:O.enum(["model","tool","machine","agent","lane","connector","service"]),name:O.string().min(1),version:O.string().min(1).optional(),status:O.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:O.array(O.string().min(1)).default([]),limitations:O.array(O.string().min(1)).default([]),riskLevel:O.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:OU.optional(),evidenceRefs:O.array(G6).default([])}).strict(),KJ=O.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),OP=O.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),DP=O.object({refName:V$,requiredForModes:O.array(KJ).min(1),allowedSecretInputs:O.array(O.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:V$,revocationCheck:O.boolean().default(!0)}).strict(),LP=O.object({operation:V$,supportedModes:O.array(KJ).min(1),sideEffectClass:OP,requiresApproval:O.boolean().default(!1),requiresIdempotencyKey:O.boolean().default(!1),requiresSandboxEvidence:O.boolean().default(!1),requiresRollbackOrRevocation:O.boolean().default(!1),rollbackOrRevocation:V$.optional(),noSideEffectSmoke:V$.optional(),reconciliation:V$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),BP=O.object({providerId:V$,appId:V$,adapterId:V$,ownerPackage:V$,modes:O.array(KJ).min(1),defaultMode:KJ,credentialRequirements:O.array(DP).default([]),operations:O.array(LP).min(1),rateLimitPosture:V$,costPosture:V$.optional(),auditEvents:O.array(V$).default([]),redactionRules:O.array(V$).default([]),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:O.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),HP=O.object({appId:V$,repo:V$,priority:O.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:O.array(V$).min(1),firstOperations:O.array(V$).min(1),blockedUntil:O.array(V$).default([])}).strict(),NP=t$(W$.providerLiveModeStandard).extend({name:V$,version:V$,modes:O.array(KJ).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:O.array(V$).min(1),liveMutationGate:O.object({requiredMode:O.literal("live_mutating"),requiredChecks:O.array(V$).min(1),forbiddenBypassSignals:O.array(V$).min(1),disabledLiveSmoke:V$}).strict(),noSideEffectSmoke:O.object({requiredForModes:O.array(KJ).min(1),commandEvidence:O.array(V$).min(1),secretOutputScan:O.boolean().default(!0)}).strict(),credentialPolicy:O.object({acceptedInputs:O.array(O.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:O.literal(!1),missingCredentialBehavior:O.literal("fail_closed"),revocationCheckRequired:O.boolean().default(!0)}).strict(),operationCards:O.array(BP).min(1),firstAdoptionTargets:O.array(HP).min(1),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:O.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),VP=O.object({id:O.string().min(1),title:O.string().min(1).optional(),summary:O.string().min(1),text:O.string().optional(),tokens:O.number().int().nonnegative().optional(),source:G6,resourceRefs:O.array(C$).default([])}).strict(),BN=t$(W$.contextPack).extend({objective:O.string().min(1),budget:O.object({maxTokens:O.number().int().positive().optional(),maxBytes:O.number().int().positive().optional()}).strict().optional(),items:O.array(VP).default([]),citations:O.array(G6).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),permissions:O.array(O.string().min(1)).default([]),redactions:O.array(O.string().min(1)).default([]),conflicts:O.array(O.string().min(1)).default([]),uncertainty:O.string().min(1).optional()}).strict(),C4=V$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),B2=O.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),FP=O.enum(["public","internal","private","sensitive"]),RP=O.enum(["draft","active","paused","archived"]),WY=O.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),HN=t$(W$.integrationRef).extend({kind:WY,name:O.string().min(1),projectId:B2.optional(),sourcePackage:V$.optional(),externalId:V$.optional(),uri:S0.optional(),enabled:O.boolean().default(!0),readOnly:O.boolean().default(!0),capabilities:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:C$.optional(),evidenceRefs:O.array(G6).default([]),config:Z0.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:O.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),KP=O.object({schemaRoot:C4.default(".hasna/project"),dashboardManifest:C4.default(".hasna/project/dashboard.render.json"),snapshotsDir:C4.default(".hasna/project/snapshots"),documentsDir:C4.default("documents"),reportsDir:C4.default("reports"),evidenceDir:C4.default(".hasna/project/evidence"),privateDir:C4.default(".hasna/project/private")}).strict(),MP=t$(W$.projectManifest).extend({projectId:B2,slug:B2,name:O.string().min(1),summary:O.string().min(1).optional(),status:RP.default("active"),classification:FP.default("private"),owner:Y0.optional(),layout:KP.default({}),integrations:O.array(HN).default([]),renderManifests:O.array(C$).default([]),resourceRefs:O.array(C$).default([]),evidenceRefs:O.array(G6).default([]),tags:AJ}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:O.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:O.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:O.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),AP=O.enum(["local","package","provider","url"]),UY=O.object({id:O.string().min(1),kind:AP,specifier:O.string().min(1),path:C4.optional(),packageName:O.string().min(1).optional(),uri:S0.optional(),provider:WY.optional(),schemaId:qN.optional(),integrity:jN.optional(),resourceRef:C$.optional(),optional:O.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:O.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:O.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:O.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:O.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),bP=O.enum(["dashboard","canvas","panel","report","document","custom"]),EP=O.object({id:O.string().min(1),title:O.string().min(1),kind:bP,default:O.boolean().default(!1),entry:C4.optional(),imports:O.array(UY).default([]),panelRefs:O.array(C$).default([]),dataRefs:O.array(C$).default([]),layout:Z0.optional()}).strict(),wP=t$(W$.renderManifest).extend({projectId:B2,name:O.string().min(1),version:O.string().min(1),manifestPath:C4.default(".hasna/project/dashboard.render.json"),renderer:O.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:O.array(EP).min(1),imports:O.array(UY).default([]),theme:Z0.optional(),compatibility:O.object({minProjectsVersion:O.string().min(1).optional(),minContractsVersion:O.string().min(1).optional()}).strict().optional(),resourceRefs:O.array(C$).default([]),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Q=new Set;for(let[Y,q]of G.imports.entries()){if(Q.has(q.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Y,"id"]});Q.add(q.id)}for(let[Y,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:O.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Y,"kind"]})}}),IP=O.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),gP=O.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),kP=O.object({id:O.string().min(1),label:O.string().min(1),value:O.union([O.string(),O.number(),O.boolean()]),unit:O.string().min(1).optional(),status:O.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:O.array(C$).default([])}).strict(),fP=O.object({id:O.string().min(1),title:O.string().min(1),summary:O.string().min(1).optional(),status:O.string().min(1).optional(),priority:O.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:W4.optional(),resourceRefs:O.array(C$).default([]),evidenceRefs:O.array(G6).default([]),metadata:Z0.optional()}).strict(),CP=O.object({renderer:O.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:O.string().min(1).optional(),entry:C4.optional(),imports:O.array(UY).default([]),spec:Z0.default({})}).strict(),NN=t$(W$.projectPanel).extend({projectId:B2,provider:O.object({kind:WY,id:O.string().min(1),name:O.string().min(1).optional(),sourcePackage:V$.optional(),externalId:V$.optional()}).strict(),kind:gP,title:O.string().min(1),summary:O.string().min(1).optional(),state:IP.default("ready"),stateReason:O.string().min(1).optional(),generatedAt:W4,freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),metrics:O.array(kP).default([]),items:O.array(fP).default([]),actions:O.array(C$).default([]),resourceRefs:O.array(C$).default([]),evidenceRefs:O.array(G6).default([]),renderFragment:CP.optional(),warnings:O.array(O.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:O.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:O.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),PP=t$(W$.projectSnapshot).extend({projectId:B2,generatedAt:W4,status:H2.default("unknown"),manifestRef:C$,renderManifestRef:C$.optional(),panels:O.array(NN).default([]),contextPacks:O.array(BN).default([]),proofBundleRefs:O.array(C$).default([]),resourceRefs:O.array(C$).default([]),evidenceRefs:O.array(G6).default([]),warnings:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:O.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),VN=O.object({id:O.string().min(1),kind:O.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:O.boolean().default(!0),command:O.string().min(1).optional(),expected:O.string().min(1).optional(),timeoutMs:O.number().int().positive().optional(),resourceRefs:O.array(C$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:O.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),TP=t$(W$.validationPlan).extend({objective:O.string().min(1),subject:C$.optional(),checks:O.array(VN).min(1),verifier:Y0.optional(),requiredEvidenceKinds:O.array(JY).default([])}).strict(),SP=O.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),ZP=O.enum(["draft","active","deprecated","archived"]),vP=O.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),yP=O.object({key:O.string().regex(/^[A-Z][A-Z0-9_]*$/),description:O.string().min(1),required:O.boolean().default(!1),["secret"]:O.boolean().default(!1),group:O.string().min(1).optional(),default:O.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),hP=O.object({name:O.string().min(1),command:O.string().min(1),description:O.string().min(1).optional(),required:O.boolean().default(!1)}).strict(),mP=O.object({packageManager:O.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:O.array(O.string().min(1)).default([]),requiredFiles:O.array(O.string().min(1)).default([]),requiredDirectories:O.array(O.string().min(1)).default([]),optionalDirectories:O.array(O.string().min(1)).default([])}).strict(),xP=t$(W$.scaffoldManifest).extend({name:O.string().min(1),version:O.string().min(1),summary:O.string().min(1),type:SP,status:ZP.default("draft"),capabilities:O.array(vP).default([]),techStack:O.array(O.string().min(1)).default([]),tags:AJ,source:C$.optional(),output:mP,env:O.array(yP).default([]),scripts:O.array(hP).default([]),validationChecks:O.array(VN).default([]),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:O.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),uP=O.enum(["installed","failed","cancelled","partial","unknown"]),dP=t$(W$.scaffoldInstallRecord).extend({scaffoldId:O.string().min(1),scaffoldVersion:O.string().min(1).optional(),manifestRef:C$.optional(),target:C$,status:uP,installedAt:W4.optional(),installer:Y0.optional(),packageManager:O.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:Z0.optional(),generatedFiles:O.array(C$).default([]),evidenceRefs:O.array(G6).default([]),proofBundleRefs:O.array(C$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:O.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),MJ=O.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),XY=O.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),FN=O.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),cP=O.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),lP=V$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),nP=O.enum(["active","stub","deprecated","archived"]),iP=O.enum(["stable","beta","canary","internal"]),rP=O.object({transport:O.enum(["http","stdio"]).default("http"),bin:O.string().min(1).optional(),url:S0.optional()}).strict(),pP=O.object({healthPath:O.string().min(1).default("/health"),port:O.number().int().positive().optional(),baseUrl:S0.optional()}).strict(),oP=O.object({bins:O.array(O.string().min(1)).default([]),mcp:rP.optional(),http:pP.optional()}).strict(),tP=t$(W$.app).extend({appId:MJ,npmName:XY,repoFolder:MJ,githubUrl:lP,projectSlug:B2,surfaces:oP.default({}),lifecycle:nP,releaseChannel:iP.default("stable"),summary:O.string().min(1).optional(),tags:AJ}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:O.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),aP=O.enum(["skill","ci","backfilled"]),sP=t$(W$.release).extend({appId:MJ,package:XY,version:FN,gitSha:cP,publishedAt:W4,publishPath:aP,changelogRef:C$.optional(),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),eP=O.enum(["install","update","rollback","freeze-blocked"]),$T=O.object({cliVersion:O.string().min(1).optional(),mcpHealth:O.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),_T=t$(W$.rolloutRecord).extend({appId:MJ,package:XY,version:FN,machine:V$,action:eP,result:H2,verifiedBy:$T.optional(),at:W4,evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:O.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),JT=O.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),WT=O.enum(["pending","queued","sent","failed","skipped","suppressed"]),UT=O.object({channel:JT,status:WT,deliveredAt:W4.optional(),detail:O.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:O.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),XT=t$(W$.announcement).extend({campaignId:V$,appId:MJ.optional(),releaseRef:C$.optional(),channels:O.array(UT).min(1),audienceRef:C$,sentAt:W4}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:O.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:O.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),GT=O.enum(["tag","attribute","group"]),QT=O.enum(["eq","neq","in","not_in","exists","not_exists"]),aH=O.union([O.string(),O.number(),O.boolean()]),YT=O.object({kind:GT,key:O.string().min(1).optional(),op:QT.default("eq"),value:aH.optional(),values:O.array(aH).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:O.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),qT=O.object({match:O.enum(["all","any"]).default("all"),predicates:O.array(YT).min(1)}).strict(),zT=O.enum(["opt_in","opt_out","transactional","none"]),jT=t$(W$.audience).extend({audienceId:MJ,name:V$,definition:qT,consentPolicy:zT,suppressionSyncedAt:L2}).strict(),tQ=["@hasna/cloud","open-cloud"],OT=O.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),DT=O.object({id:O.string().min(1),provider:OT,kind:O.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:O.string().min(1),region:O.string().min(1).optional(),accountId:O.string().min(1).optional(),uri:S0.optional(),machineScoped:O.boolean().default(!1)}).strict(),RN=t$(W$.appCloudManifest).extend({packageName:O.string().min(1),packageVersion:O.string().min(1).optional(),appId:O.string().min(1),repository:C$.optional(),storageMode:O.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:O.enum(["none","app_owned","external_service","local_cache"]),cloudResources:O.array(DT).default([]),localCache:O.object({path:O.string().min(1).optional(),pullMode:O.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:O.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:O.array(O.string().min(1)).default([...tQ]),dependencies:O.array(O.string().min(1)).default([]),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{let J=new Set([...tQ,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:O.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of tQ)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:O.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:O.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:O.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:O.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:O.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:O.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),KN=O.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),LT=O.enum(["low","medium","high","critical"]),MN=O.object({id:O.string().min(1),kind:KN,severity:LT,path:O.string().min(1).optional(),packageName:O.string().min(1).optional(),pattern:O.string().min(1),message:O.string().min(1),evidenceRefs:O.array(G6).default([])}).strict(),BT=O.object({id:O.string().min(1),kind:KN,status:H2,target:O.string().min(1),command:O.string().min(1).optional(),evidenceRefs:O.array(G6).default([]),findings:O.array(MN).default([])}).strict(),HT=t$(W$.noCloudEvidencePack).extend({subject:C$,packageName:O.string().min(1).optional(),packageVersion:O.string().min(1).optional(),generatedBy:Y0.optional(),scanMode:O.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:H2,verdict:O.enum(["passed","failed","warning","not_run"]),appCloudManifest:RN.optional(),checks:O.array(BT).min(1),findings:O.array(MN).default([]),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Q)=>Q.severity==="high"||Q.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),NT=O.object({checkId:O.string().min(1),status:H2,summary:O.string().min(1).optional(),startedAt:L2,finishedAt:L2,evidenceRefs:O.array(G6).default([])}).strict(),VT=t$(W$.proofBundle).extend({subject:C$,validationPlanRef:C$.optional(),status:H2,verdict:O.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:O.array(NT).default([]),verifier:Y0.optional(),evidenceRefs:O.array(G6).default([]),residualRisks:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),FT=t$(W$.workRun).extend({objective:O.string().min(1),status:H2,actor:Y0,traceId:O.string().min(1).optional(),startedAt:L2,finishedAt:L2,constraints:O.array(O.string().min(1)).default([]),resourceRefs:O.array(C$).default([]),decisions:O.array(LN).default([]),costEstimates:O.array(OU).default([]),evidenceRefs:O.array(G6).default([]),validationPlanRefs:O.array(C$).default([]),proofBundleRefs:O.array(C$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),RT=O.object({id:O.string().min(1),at:W4,kind:O.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:O.string().min(1),resourceRefs:O.array(C$).default([]),evidenceRefs:O.array(G6).default([]),costEstimate:OU.optional()}).strict(),KT=t$(W$.agentTrajectory).extend({actor:Y0,workRunRef:C$.optional(),events:O.array(RT).default([]),outcome:O.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:C$.optional()}).strict(),MT="v1",AT=O.enum(["library","cli-with-store","service","saas"]),bT=["local","self-hosted","cloud"],AN=O.enum(bT),ET=O.enum(["supported","deferred","unsupported"]),wT=O.enum(["none","local-only","api-key","session","service-token","custom"]),aQ=O.object({method:O.enum(["GET","POST","PUT","PATCH","DELETE"]),path:O.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:O.boolean().default(!1),description:O.string().min(1).optional()}).strict(),IT=O.object({id:O.string().min(1),kind:O.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:O.boolean().default(!0),command:O.string().min(1).optional(),evidenceRef:G6.optional(),status:O.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:O.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:O.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),gT=O.object({name:O.string().min(1),status:ET,bin:O.string().min(1).optional(),mcpBin:O.string().min(1).optional(),authMode:wT,deploymentModes:O.array(AN).min(1),health:aQ.optional(),readiness:aQ.optional(),version:aQ.optional(),apiBasePath:O.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:O.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:O.string().min(1).optional(),readinessGates:O.array(IT).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:O.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:O.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:O.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:O.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),kT=["local","cloud"],bN=O.enum(kT),fT=["remote","hybrid","self_hosted"],CT=O.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),PT=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function TT($){return PT.map((_)=>`${$}${_}`)}function sH($){return`hasna/oss/${$}/database-url`}var ST=O.object({mode:bN,envPrefix:O.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:O.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:O.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:O.string().min(1).optional()}).strict(),ZT=O.object({$schema:O.string().min(1).optional(),schema:O.literal(W$.serviceContract),name:CT,class:AT,contractVersion:O.literal(MT),kitVersion:O.string().min(1),description:O.string().min(1).optional(),bins:O.array(O.string().min(1)).default([]),storage:ST.optional(),deploymentModes:O.array(AN).default(["local"]),serviceSurfaces:O.array(gT).default([]),metadata:Z0.optional()}).strict().superRefine(($,_)=>{let J=new Set(TT($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:O.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:O.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:O.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==sH($.name))_.addIssue({code:O.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${sH($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:O.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:O.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:O.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:O.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:O.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:O.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Q,Y]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Y))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface deployment mode "${Y}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Q]})}}),co=O.object({status:O.enum(["ok","degraded","unavailable"]),version:O.string().min(1),mode:bN}).strict(),lo=O.object({ready:O.boolean(),reason:O.string().min(1).optional()}).strict(),no=O.object({version:O.string().min(1)}).strict(),vT=O.enum(["info","notice","breaking","critical"]),yT=O.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),hT=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],mT=O.enum(hT);var xT=O.enum(["fleet","package","machine"]),EN=t$(W$.commsEventEnvelope).extend({type:yT,severity:vT,scope:xT,summary:O.string().min(1).optional(),source:Y0.optional(),affected_packages:O.array(V$).default([]),affected_machines:O.array(V$).default([]),action_required:O.boolean().default(!1),ack_by:W4.optional(),dedupe_key:V$,resourceRefs:O.array(C$).default([]),evidenceRefs:O.array(G6).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:O.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),uT=O.enum(["fleet","package","product","loop-lane","initiative","personal"]),dT=O.enum(["quiet","work","firehose"]),cT=V$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),lT=t$(W$.commsChannelMetadata).extend({class:uT,noise:dT.optional(),owner:V$.optional(),until:cT.optional(),successor:V$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:O.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:O.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),eH={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},nT=t$(W$.commsMessageMetadata).extend({tag:mT,envelope:EN}).strict().superRefine(($,_)=>{let J=eH[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:O.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:O.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(eH))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:O.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var io={[W$.actorRef]:GP,[W$.resourceRef]:QP,[W$.evidenceRef]:qP,[W$.workRun]:FT,[W$.decisionEnvelope]:LN,[W$.costEstimate]:OU,[W$.capabilityCard]:jP,[W$.providerLiveModeStandard]:NP,[W$.contextPack]:BN,[W$.integrationRef]:HN,[W$.projectManifest]:MP,[W$.projectPanel]:NN,[W$.projectSnapshot]:PP,[W$.renderManifest]:wP,[W$.agentTrajectory]:KT,[W$.validationPlan]:TP,[W$.proofBundle]:VT,[W$.scaffoldManifest]:xP,[W$.scaffoldInstallRecord]:dP,[W$.appCloudManifest]:RN,[W$.noCloudEvidencePack]:HT,[W$.serviceContract]:ZT,[W$.commsEventEnvelope]:EN,[W$.commsChannelMetadata]:lT,[W$.commsMessageMetadata]:nT,[W$.app]:tP,[W$.release]:sP,[W$.rolloutRecord]:_T,[W$.announcement]:XT,[W$.audience]:jT};function DU($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(fT.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}var iT=["remote","hybrid","self_hosted"];function GY($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(iT.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}import eo from"pg";class E9 extends Error{scheme;port;constructor($,_){super($);this.name="KnowledgeNetworkGuardError",this.scheme=_.scheme,this.port=_.port}}function bJ($=process.env){return($.NODE_ENV??"").trim().toLowerCase()==="test"}function wN($){let _=$.split(".");if(_.length!==4)return!1;if(!_.every((J)=>/^\d{1,3}$/.test(J)&&Number(J)<=255))return!1;return _[0]==="127"}function aT($){let _=$.trim().toLowerCase();if(_.length===0)return!1;if(_==="localhost"||_.endsWith(".localhost"))return!0;if(wN(_))return!0;if(!_.startsWith("[")||!_.endsWith("]"))return!1;let J=_.slice(1,-1);if(J==="::1"||/^(0:){7}1$/.test(J))return!0;let U=J.split(":").pop()??"";if(/^(::ffff:|::)/.test(J)&&wN(U))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(J)}function kN($){if(typeof $==="string")return $;if($ instanceof URL)return $.href;return $.url}function IN($,_=process.env){if(!bJ(_))return;let J=kN($),U;try{U=new URL(J)}catch{throw new E9("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(aT(U.hostname))return;throw new E9(`knowledge: refused a non-loopback ${U.protocol.replace(":","")} request while NODE_ENV=test (target host withheld on purpose). This process resolved to the cloud backend under test, which means a read or write was about to leave the machine and reach the live store. Select the mode explicitly (HASNA_KNOWLEDGE_STORAGE_MODE=local) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:U.protocol.replace(":",""),port:U.port})}var sT=new Set([301,302,303,307,308]),gN=5;function eT($,_){if(_?.method)return _.method.toUpperCase();if(typeof $!=="string"&&!($ instanceof URL))return $.method.toUpperCase();return"GET"}async function w9($,_){if(IN($),!bJ()||_?.redirect!==void 0)return fetch($,_);let J=kN($),U=eT($,_),W=_?.body,X=await fetch($,{..._??{},redirect:"manual"});for(let G=0;sT.has(X.status);G++){let Q=X.headers.get("location");if(!Q)return X;let Y=new URL(Q,J).href;if(IN(Y),G>=gN){let L=new URL(Y);throw new E9(`knowledge: refused to follow more than ${gN} redirects while NODE_ENV=test (target host withheld on purpose). Under test the guard follows redirects itself so every hop is checked, and a chain this long is a loop, not a route.`,{scheme:L.protocol.replace(":",""),port:L.port})}if(X.status===303||(X.status===301||X.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",W=void 0;let q={..._??{},method:U,redirect:"manual"};if(W===void 0)delete q.body;else q.body=W;X=await fetch(Y,q),J=Y}return X}var g9="knowledge",QY=rH(g9),v0=QY.modeKeys,k9=QY.apiUrlKeys,f9=QY.apiKeyKeys;function I9($,_){return _.filter((J)=>($[J]??"").trim().length>0)}function LU($=process.env){let _=[...I9($,k9),...I9($,f9)],J=v0[0];for(let U of v0){let W=$[U]?.trim();if(!W)continue;let X;try{X=GY(W)}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);throw Error(`knowledge: ${U}=${W} is not a valid mode. ${Y}`)}let G=[];if(X.deprecatedAlias)G.push(`Deprecated mode '${X.deprecatedAlias}' from ${U} is treated as 'cloud'. Prefer ${J}=cloud.`);if(U!==J)G.push(`Using alias env ${U}; the canonical key is ${J}.`);if(X.mode==="local"&&_.length>0)G.push(`${U}=local pins the on-box store; ${_.join(", ")} are set but ignored.`);return{mode:X.mode,source:{kind:"env",name:U,value:W},pointer_env_present:_,pointer_ignored:X.mode==="local"&&_.length>0,warning:G.length>0?G.join(" "):null}}return{mode:"local",source:{kind:"default",name:null,value:null},pointer_env_present:_,pointer_ignored:_.length>0,warning:_.length>0?`${_.join(", ")} are set but do NOT select a backend: mode is local by default. Set ${J}=cloud to route reads and writes to the API, or unset those vars to silence this note.`:null}}var $S=["postgres","cloud","self_hosted"],_S=["sqlite","local"],fN=new Map;function CN($,_,J){let U=_===DU;if(U){let W=fN.get($);if(W!==void 0)return W}for(let W of $)try{if(_(W),U)fN.set($,W);return W}catch{}throw Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts (tried ${$.join(", ")}). The storage-mode enum has changed; add the new token to ${J} in src/knowledge-mode.ts.`)}function JS($=DU){return CN($S,$,"SERVER_MODE_CANDIDATES")}function WS($=DU){return CN(_S,$,"LOCAL_MODE_CANDIDATES")}function US($,_=DU){return $==="cloud"?JS(_):WS(_)}function YY($,_){return{...$,[v0[0]]:US(_)}}class PN extends Error{code="knowledge_mode_unset_with_api_url";constructor($){let _=v0[0];super(`knowledge: ${$.join(", ")} names an API store, but no mode variable says to use it, so this command would silently read and write the on-box store instead. Set ${_}=cloud to use the API, or ${_}=local to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function TN($=process.env,_={}){let J=LU($);if(_.storePathOverridden)return J;if(J.source.kind!=="default")return J;let U=I9($,k9);if(U.length===0)return J;throw new PN(U)}function SN($=process.env){let _=LU($);return{..._,store_transport:_.mode==="cloud"?"api":"local",api_key_present:I9($,f9).length>0,network_guard_active:bJ($)}}function ZN($){return{fetchImpl:w9,...bJ($)?{retry:!1}:{}}}var N1="notes";class vN extends Error{expected;current;code="version_conflict";constructor($,_){super(`version_conflict: this edit was written against version ${$} but the stored entry is now at version ${_}. Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions.`);this.expected=$;this.current=_;this.name="KnowledgeVersionConflictError"}}function XS($){let _={};if($.search)_.search=$.search;if($.limit!==void 0)_.limit=$.limit;if($.offset!==void 0)_.offset=$.offset;if($.includeArchived||$.archivedOnly)_.includeArchived=!0;return _}function GS($){return{baseUrl:$.baseUrl,async list(_={}){let J=_.limit??200,U=XS({..._,limit:Math.min(Math.max(J,1),200)}),W=await $.list(N1,{query:U}),X=W.items;if(_.archivedOnly)X=X.filter((G)=>G.archived===!0);if(_.tag){let G=_.tag.toLowerCase();X=X.filter((Q)=>(Q.tags??[]).some((Y)=>Y.toLowerCase()===G))}return{items:X,total:W.total}},async get(_){return $.get(N1,_)},async create(_){return $.create(N1,{..._.id?{id:_.id}:{},title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],..._.metadata?{metadata:_.metadata}:{}})},async update(_,J,U={}){try{return await $.update(N1,_,J,{...U.expectedVersion!==void 0?{headers:{"if-match":String(U.expectedVersion)}}:{}})}catch(W){if(qY(W))return null;let X=QS(W);if(X)throw X;throw W}},async delete(_){let J=await $.get(N1,_);if(!J)return!1;return await $.delete(N1,J.id),!0},async listVersions(_,J={}){try{return await $.transport.get(`/${N1}/${encodeURIComponent(_)}/versions`,{query:{limit:J.limit,offset:J.offset}})}catch(U){if(qY(U))return null;throw U}},async getVersion(_,J){try{return await $.transport.get(`/${N1}/${encodeURIComponent(_)}/versions/${J}`)}catch(U){if(qY(U))return null;throw U}}}}function QS($){if(!$||typeof $!=="object")return null;if($.status!==409)return null;let _=$.body,U=(typeof _==="string"?YS(_):_)??{};if(U.error!=="version_conflict")return null;return new vN(Number(U.expected??0),Number(U.current??0))}function YS($){try{return JSON.parse($)}catch{return null}}function qY($){return Boolean($&&typeof $==="object"&&$.status===404)}function BU($=process.env){if(LU($).mode!=="cloud")return null;let _=yQ(g9,YY($,"cloud"),ZN($));if(_.transport!=="cloud-http")return null;return GS(_.client)}function V1($=process.env){if(LU($).mode!=="cloud")return!1;return yQ(g9,YY($,"cloud"),ZN($)).transport==="cloud-http"}async function C9($){let J=[];for(let U=0;;U+=200){let{items:W}=await $.list({includeArchived:!0,limit:200,offset:U});if(J.push(...W),W.length<200)break;if(U>1e5)break}return J}class jY extends Error{location;code="version_history_unsupported";constructor($){super(`Version history is not kept by the local JSON knowledge store (${$}). It has no version line, so an empty history here would be a claim, not a measurement. Entry versioning lives in the Postgres-backed store: point this CLI at it (HASNA_KNOWLEDGE_STORAGE_MODE=cloud plus the API url/key) and re-run.`);this.location=$;this.name="VersionHistoryUnsupportedError"}}function zY($,_){return $.id===_||$.short_id===_}class yN{storePath;kind="local";supportsVersions=!1;constructor($){this.storePath=$}async listVersions(){throw new jY(this.storePath)}async getVersion(){throw new jY(this.storePath)}get location(){return this.storePath}get exists(){return qS(this.storePath)}async listAll(){let $=A_(this.storePath);return{items:$.items,exists:$.exists}}async get($){return A_(this.storePath).items.find((J)=>zY(J,$))??null}async create($){return e4(this.storePath,()=>{let _=dW(this.storePath),J=new Date().toISOString(),U=$.id??SB(),W={id:U,short_id:ZB(U),title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],metadata:$.metadata??{},archived:!1,created_at:J,updated_at:J};return _.items.push(W),R0(this.storePath,_),W},{createParent:!0})}async update($,_){return e4(this.storePath,()=>{let J=dW(this.storePath),U=J.items.findIndex((X)=>zY(X,$));if(U===-1)return null;let W=J.items[U];if(_.title!==void 0)W.title=_.title;if(_.content!==void 0)W.content=_.content;if(_.url!==void 0)W.url=_.url;if(_.tags!==void 0)W.tags=_.tags;if(_.metadata!==void 0)W.metadata=_.metadata;if(_.archived!==void 0)W.archived=_.archived;return W.updated_at=new Date().toISOString(),J.items[U]=W,R0(this.storePath,J),W},{createParent:!0})}async delete($){return e4(this.storePath,()=>{let _=dW(this.storePath),J=_.items.length;_.items=_.items.filter((W)=>!zY(W,$));let U=J!==_.items.length;if(U)R0(this.storePath,_);return U},{createParent:!0})}async deleteMany($){if($.length===0)return 0;let _=new Set($);return e4(this.storePath,()=>{let J=dW(this.storePath),U=J.items.length;J.items=J.items.filter((X)=>!_.has(X.id)&&!(X.short_id!=null&&_.has(X.short_id)));let W=U-J.items.length;if(W>0)R0(this.storePath,J);return W},{createParent:!0})}}class hN{cloud;kind="api";exists=!0;supportsVersions=!0;constructor($){this.cloud=$}async listVersions($,_={}){return this.cloud.listVersions($,_)}async getVersion($,_){return this.cloud.getVersion($,_)}get location(){return this.cloud.baseUrl}async listAll(){return{items:await C9(this.cloud),exists:!0}}async get($){return this.cloud.get($)}async create($){return this.cloud.create({...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})}async update($,_,J={}){return this.cloud.update($,_,{expectedVersion:J.expectedVersion})}async delete($){return this.cloud.delete($)}async deleteMany($){let _=0;for(let J of $)if(await this.cloud.delete(J))_+=1;return _}}function P9($){let _=$.storePathOverridden?null:BU($.env??process.env);if(_)return new hN(_);return new yN($.storePath)}function mN($){let _=$??"";if(_==="")return[];return _.replace(/\n$/,"").split(` -`)}var OY=5000;function zS($,_){let J=mN($),U=mN(_);if(J.length>OY||U.length>OY)throw Error(`Refusing to line-diff ${Math.max(J.length,U.length)} lines (limit ${OY}). Fetch the two versions and diff them with a dedicated tool.`);let W=Array.from({length:J.length+1},()=>Array(U.length+1).fill(0));for(let Y=J.length-1;Y>=0;Y-=1)for(let q=U.length-1;q>=0;q-=1)W[Y][q]=J[Y]===U[q]?W[Y+1][q+1]+1:Math.max(W[Y+1][q],W[Y][q+1]);let X=[],G=0,Q=0;while(G=W[G][Q+1])X.push({op:"remove",from_line:G+1,to_line:null,text:J[G]}),G+=1;else X.push({op:"add",from_line:null,to_line:Q+1,text:U[Q]}),Q+=1;while(G{if(!jS($[Q],_[Q]))J.push({field:Q,from:$[Q]??null,to:_[Q]??null})};U("title"),U("url"),U("tags"),U("metadata"),U("archived");let W=zS($.content,_.content),X=W.filter((Q)=>Q.op==="add").length,G=W.filter((Q)=>Q.op==="remove").length;return{identical:J.length===0&&X===0&&G===0,fields:J,content:W,added:X,removed:G}}function uN($,_,J){let U=[`--- ${_}`,`+++ ${J}`];if($.identical)return U.push("(no changes)"),U.join(` +`)}),this}_outputHelpIfRequested($){let _=this._getHelpOption();if(_&&$.find((U)=>_.is(U)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function uM($){return $.map((_)=>{if(!_.startsWith("--inspect"))return _;let J,U="127.0.0.1",W="9229",X;if((X=_.match(/^(--inspect(-brk)?)$/))!==null)J=X[1];else if((X=_.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(J=X[1],/^\d+$/.test(X[3]))W=X[3];else U=X[3];else if((X=_.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)J=X[1],U=X[3],W=X[4];if(J&&W!=="0")return`${J}=${U}:${parseInt(W)+1}`;return _})}function BB(){if(n$.env.NO_COLOR||n$.env.FORCE_COLOR==="0"||n$.env.FORCE_COLOR==="false")return!1;if(n$.env.FORCE_COLOR||n$.env.CLICOLOR_FORCE!==void 0)return!0;return}jp.Command=HB;jp.useColor=BB});var lM=t0((Hp)=>{var{Argument:nM}=GY(),{Command:NB}=dM(),{CommanderError:Lp,InvalidArgumentError:cM}=Y9(),{Help:Bp}=jB(),{Option:iM}=DB();Hp.program=new NB;Hp.createCommand=($)=>new NB($);Hp.createOption=($,_)=>new iM($,_);Hp.createArgument=($,_)=>new nM($,_);Hp.Command=NB;Hp.Option=iM;Hp.Argument=nM;Hp.Help=Bp;Hp.CommanderError=Lp;Hp.InvalidArgumentError=cM;Hp.InvalidOptionArgumentError=cM});import{chmodSync as vB,closeSync as nW,existsSync as w2,fsyncSync as AY,lstatSync as mA,openSync as bY,readFileSync as cW,renameSync as yB,unlinkSync as wY,writeFileSync as gY}from"fs";import{randomUUID as iW}from"crypto";import{basename as xA,dirname as hB,join as MY}from"path";import{chmodSync as gB,existsSync as SA,mkdirSync as HY,readFileSync as ZA,writeFileSync as kB}from"fs";import{homedir as NY}from"os";import{dirname as vA,join as I_,resolve as IB}from"path";var K4=I_(".hasna","knowledge"),fB=I_(".hasna","apps","knowledge"),r$={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:K4,s3:{bucket:"example-knowledge-prod",region:"us-east-1",profile:"example-infra",prefix:".hasna/knowledge",server_side_encryption:"AES256"},secrets:{env:"example/knowledge/prod/env",aws:"example/knowledge/prod/aws",s3:"example/knowledge/prod/s3",rds:null,future_rds:"example/knowledge/prod/rds"},source_owner:"open-files",evidence_doc:"docs/canonical-secrets-bootstrap-2026-06-08.md"};function CB(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:r$.s3.bucket,prefix:r$.s3.prefix,region:r$.s3.region,profile:r$.s3.profile,server_side_encryption:r$.s3.server_side_encryption}}}function uW(){return I_(NY(),".open-knowledge","db.json")}function D9(){return I_(NY(),".hasna","knowledge")}function VY($=process.cwd()){return IB($,K4)}function yA(){return I_(NY(),fB)}function hA($=process.cwd()){return IB($,fB)}function RY($,_=process.cwd()){if($==="project"||$==="local")return s_(hA(_));return s_(yA())}function s_($){return{home:$,configPath:I_($,"config.json"),jsonStorePath:I_($,"db.json"),knowledgeDbPath:I_($,"knowledge.db"),artifactsDir:I_($,"artifacts"),cacheDir:I_($,"cache"),exportsDir:I_($,"exports"),indexesDir:I_($,"indexes"),logsDir:I_($,"logs"),runsDir:I_($,"runs"),schemasDir:I_($,"schemas"),wikiDir:I_($,"wiki")}}function dW(){return{version:1,mode:"local",hosted:{api_url:"https://knowledge.md"},storage:{type:"local",artifacts_root:"artifacts"},sources:{preferred_ref:"open-files",allowed_schemes:["open-files","s3","file","https","http"]},providers:{default_model:"openai:gpt-5.2",aliases:{fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"},openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},embeddings:{default_model:"openai:text-embedding-3-small",dimensions:1536,batch_size:64,max_parallel_calls:4},safety:{network:{web_search_enabled:!1,s3_reads_enabled:!1,allowed_s3_buckets:[]},redaction:{enabled:!0},approvals:{generated_writes_require_approval:!0}}}}function b2($){let _=s_($);HY(_.home,{recursive:!0,mode:448});for(let J of[_.artifactsDir,_.cacheDir,_.exportsDir,_.indexesDir,_.logsDir,_.runsDir,_.schemasDir,_.wikiDir])HY(J,{recursive:!0,mode:448});if(!SA(_.configPath))kB(_.configPath,`${JSON.stringify(dW(),null,2)} +`,{mode:384}),gB(_.configPath,384);return _}function O9($,_=process.cwd()){if($==="project"||$==="local")return s_(VY(_));return s_(D9())}function G0($){HY(vA($),{recursive:!0})}function KY($){let _=ZA($,"utf8");return JSON.parse(_)}function PB($,_){G0($),kB($,`${JSON.stringify(_,null,2)} +`,{mode:384}),gB($,384)}function B9(){return s_(D9()).jsonStorePath}function lW($){if($===B9()&&w2(uW()))IY();if(!w2($))G0($),uB($,`${JSON.stringify({items:[]},null,2)} +`)}function uA($){return $.toISOString().replace(/[:.]/g,"-")}function kY($){let _=[`id:${$.id}`];if(typeof $.short_id==="string"&&$.short_id.length>0)_.push(`short_id:${$.short_id}`);return _}function dA($){let _=new Set;for(let J of $)for(let U of kY(J))_.add(U);return _}function nA($,_){return kY(_).some((J)=>$.has(J))}function FY($,_){G0($),gY($,`${JSON.stringify(_,null,2)} +`,{mode:384}),vB($,384)}function TB($){let _=JSON.parse(cW($,"utf8"));if(!_||typeof _!=="object"||!Array.isArray(_.items))return{store:{items:[]},skippedInvalid:0};let J={items:[]},U=0;for(let W of _.items)if(W&&typeof W==="object"&&typeof W.id==="string"&&W.id.length>0)J.items.push(W);else U+=1;return{store:J,skippedInvalid:U}}function IY($={}){if($.dryRun===!0)return SB($);return $4(B9(),()=>SB($),{createParent:!0})}function SB($={}){let _=$.dryRun===!0,J=$.now??new Date,U=s_(D9()),W=uW(),X=U.jsonStorePath,G=w2(W),Y=w2(X),Q={ok:!0,dry_run:_,legacy_path:W,canonical_path:X,legacy_exists:G,canonical_existed:Y,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:G?"Legacy global store already imported":"No legacy global store found"};if(!G)return Q;let q;try{let H=TB(W);q=H.store,Q.skipped_invalid=H.skippedInvalid}catch(H){return Q.ok=!1,Q.errors.push(`Could not read legacy store: ${H instanceof Error?H.message:String(H)}`),Q.message="Legacy global store import failed",Q}let L={items:[]};if(Y)try{L=TB(X).store}catch(H){return Q.ok=!1,Q.errors.push(`Could not read canonical store: ${H instanceof Error?H.message:String(H)}`),Q.message="Legacy global store import failed",Q}let N=dA(L.items),R={items:[...L.items]};for(let H of q.items){if(!H?.id){Q.skipped_invalid+=1;continue}if(nA(N,H)){Q.skipped_existing+=1;continue}R.items.push(H);for(let V of kY(H))N.add(V);Q.imported+=1}if(Q.would_create_canonical=!Y&&Q.imported>0,Q.canonical_created=!_&&Q.would_create_canonical,Q.message=Q.imported>0?`Imported ${Q.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",_||Q.imported===0)return Q;let B=`${uA(J)}-${iW().slice(0,8)}`;if(Y)Q.backup_path=MY(U.exportsDir,`legacy-open-knowledge-db-before-import-${B}.json`),FY(Q.backup_path,L);return FY(X,R),Q.report_path=MY(U.runsDir,`legacy-open-knowledge-import-${B}.json`),FY(Q.report_path,Q),Q}function g2($){if(!w2($))return{exists:!1,items:[]};let _=cW($,"utf8"),J=JSON.parse(_);if(!J||!Array.isArray(J.items))return{exists:!0,items:[]};return{exists:!0,items:J.items}}function cA($){return`${$}.lock`}var L9=1e4,mB=25,ZB=120000,iA=new Int32Array(new SharedArrayBuffer(4));function fY($){return typeof $==="object"&&$!==null&&"code"in $?String($.code):void 0}function xB($){let _=null;try{_=bY(hB($),"r"),AY(_)}catch{}finally{if(_!==null)try{nW(_)}catch{}}}var EY=new Set;function uB($,_){G0($);let J=MY(hB($),`.${xA($)}.tmp.${iW()}`),U=null;try{U=bY(J,"wx",384),gY(U,_),AY(U),nW(U),U=null,yB(J,$);try{vB($,384)}catch{}xB($)}catch(W){if(U!==null)try{nW(U)}catch{}try{wY(J)}catch{}throw W}}function dB($){Atomics.wait(iA,0,0,$)}function lA($){if(typeof $!=="number"||!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch(_){return fY(_)!=="ESRCH"}}function nB($,_){try{let J=cW($,"utf8"),U=JSON.parse(J);if(typeof U.ts==="number")return _-U.ts>ZB&&!lA(U.pid)}catch{}try{return _-mA($).mtimeMs>ZB}catch{return!1}}function rA($){let _=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),J=`${$}.stale.${_}.${iW()}`;try{yB($,J)}catch(U){if(fY(U)!=="ENOENT")throw U;return}}function pA($){let _=iW(),J=`${$}.breaker`,U=Date.now();while(Date.now()-U$;function sA($,_){this[$]=aA.bind(null,_)}var eA=($,_)=>{for(var J in _)tA($,J,{get:_[J],enumerable:!0,configurable:!0,set:sA.bind(_,J)})},z={};eA(z,{void:()=>yb,util:()=>y$,unknown:()=>Zb,union:()=>ub,undefined:()=>Pb,tuple:()=>cb,transformer:()=>tB,symbol:()=>Cb,string:()=>GH,strictObject:()=>xb,setErrorMap:()=>Jb,set:()=>rb,record:()=>ib,quotelessJson:()=>$b,promise:()=>eb,preprocess:()=>Jw,pipeline:()=>Ww,ostring:()=>Uw,optional:()=>$w,onumber:()=>Xw,oboolean:()=>Gw,objectUtil:()=>ZY,object:()=>mb,number:()=>YH,nullable:()=>_w,null:()=>Tb,never:()=>vb,nativeEnum:()=>sb,nan:()=>kb,map:()=>lb,makeIssue:()=>V9,literal:()=>tb,lazy:()=>ob,late:()=>wb,isValid:()=>a0,isDirty:()=>yY,isAsync:()=>pW,isAborted:()=>vY,intersection:()=>nb,instanceof:()=>gb,getParsedType:()=>M4,getErrorMap:()=>N9,function:()=>pb,enum:()=>ab,effect:()=>tB,discriminatedUnion:()=>db,defaultErrorMap:()=>C2,datetimeRegex:()=>WH,date:()=>fb,custom:()=>XH,coerce:()=>Yw,boolean:()=>QH,bigint:()=>Ib,array:()=>hb,any:()=>Sb,addIssueToContext:()=>d,ZodVoid:()=>tW,ZodUnknown:()=>Y0,ZodUnion:()=>Z2,ZodUndefined:()=>T2,ZodType:()=>k$,ZodTuple:()=>J4,ZodTransformer:()=>D6,ZodSymbol:()=>oW,ZodString:()=>M6,ZodSet:()=>$1,ZodSchema:()=>k$,ZodRecord:()=>aW,ZodReadonly:()=>d2,ZodPromise:()=>_1,ZodPipeline:()=>$U,ZodParsedType:()=>r,ZodOptional:()=>b6,ZodObject:()=>O_,ZodNumber:()=>Q0,ZodNullable:()=>A4,ZodNull:()=>S2,ZodNever:()=>_4,ZodNativeEnum:()=>m2,ZodNaN:()=>eW,ZodMap:()=>sW,ZodLiteral:()=>h2,ZodLazy:()=>y2,ZodIssueCode:()=>P,ZodIntersection:()=>v2,ZodFunction:()=>f2,ZodFirstPartyTypeKind:()=>D$,ZodError:()=>e_,ZodEnum:()=>z0,ZodEffects:()=>D6,ZodDiscriminatedUnion:()=>K9,ZodDefault:()=>x2,ZodDate:()=>s0,ZodCatch:()=>u2,ZodBranded:()=>F9,ZodBoolean:()=>P2,ZodBigInt:()=>q0,ZodArray:()=>A6,ZodAny:()=>e0,Schema:()=>k$,ParseStatus:()=>f_,OK:()=>x_,NEVER:()=>Qw,INVALID:()=>Q$,EMPTY_PATH:()=>Wb,DIRTY:()=>I2,BRAND:()=>bb});var y$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(y$||(y$={}));var ZY;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(ZY||(ZY={}));var r=y$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),M4=($)=>{switch(typeof $){case"undefined":return r.undefined;case"string":return r.string;case"number":return Number.isNaN($)?r.nan:r.number;case"boolean":return r.boolean;case"function":return r.function;case"bigint":return r.bigint;case"symbol":return r.symbol;case"object":if(Array.isArray($))return r.array;if($===null)return r.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return r.promise;if(typeof Map<"u"&&$ instanceof Map)return r.map;if(typeof Set<"u"&&$ instanceof Set)return r.set;if(typeof Date<"u"&&$ instanceof Date)return r.date;return r.object;default:return r.unknown}},P=y$.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"]),$b=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class e_ extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}e_.create=($)=>{return new e_($)};var _b=($,_)=>{let J;switch($.code){case P.invalid_type:if($.received===r.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case P.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,y$.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:J=`Unrecognized key(s) in object: ${y$.joinValues($.keys,", ")}`;break;case P.invalid_union:J="Invalid input";break;case P.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${y$.joinValues($.options)}`;break;case P.invalid_enum_value:J=`Invalid enum value. Expected ${y$.joinValues($.options)}, received '${$.received}'`;break;case P.invalid_arguments:J="Invalid function arguments";break;case P.invalid_return_type:J="Invalid function return type";break;case P.invalid_date:J="Invalid date";break;case P.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else y$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case P.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case P.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case P.custom:J="Invalid input";break;case P.invalid_intersection_types:J="Intersection results could not be merged";break;case P.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case P.not_finite:J="Number must be finite";break;default:J=_.defaultError,y$.assertNever($)}return{message:J}},C2=_b,$H=C2;function Jb($){$H=$}function N9(){return $H}var V9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},Wb=[];function d($,_){let J=N9(),U=V9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===C2?void 0:C2].filter((W)=>!!W)});$.common.issues.push(U)}class f_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return Q$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return f_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return Q$;if(X.status==="aborted")return Q$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var Q$=Object.freeze({status:"aborted"}),I2=($)=>({status:"dirty",value:$}),x_=($)=>({status:"valid",value:$}),vY=($)=>$.status==="aborted",yY=($)=>$.status==="dirty",a0=($)=>$.status==="valid",pW=($)=>typeof Promise<"u"&&$ instanceof Promise,_$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(_$||(_$={}));class w6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var pB=($,_)=>{if(a0(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new e_($.common.issues);return this._error=J,this._error}}}};function M$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class k${get description(){return this._def.description}_getType($){return M4($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:M4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new f_,ctx:{common:$.parent.common,data:$.data,parsedType:M4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(pW(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M4($)},U=this._parseSync({data:$,path:J.path,parent:J});return pB(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M4($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return a0(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>a0(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:M4($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(pW(U)?U:Promise.resolve(U));return pB(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:P.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new D6({schema:this,typeName:D$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return b6.create(this,this._def)}nullable(){return A4.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return A6.create(this)}promise(){return _1.create(this,this._def)}or($){return Z2.create([this,$],this._def)}and($){return v2.create(this,$,this._def)}transform($){return new D6({...M$(this._def),schema:this,typeName:D$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new x2({...M$(this._def),innerType:this,defaultValue:_,typeName:D$.ZodDefault})}brand(){return new F9({typeName:D$.ZodBranded,type:this,...M$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new u2({...M$(this._def),innerType:this,catchValue:_,typeName:D$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return $U.create(this,$)}readonly(){return d2.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Ub=/^c[^\s-]{8,}$/i,Xb=/^[0-9a-z]+$/,Gb=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yb=/^[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,Qb=/^[a-z0-9_-]{21}$/i,qb=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,zb=/^[-+]?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)?)??$/,jb=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Db="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",CY,Ob=/^(?:(?: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])$/,Lb=/^(?:(?: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])$/,Bb=/^(([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]))$/,Hb=/^(([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])$/,Nb=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vb=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_H="((\\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])))",Rb=new RegExp(`^${_H}$`);function JH($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function Kb($){return new RegExp(`^${JH($)}$`)}function WH($){let _=`${_H}T${JH($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function Fb($,_){if((_==="v4"||!_)&&Ob.test($))return!0;if((_==="v6"||!_)&&Bb.test($))return!0;return!1}function Eb($,_){if(!qb.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function Mb($,_){if((_==="v4"||!_)&&Lb.test($))return!0;if((_==="v6"||!_)&&Hb.test($))return!0;return!1}class M6 extends k${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==r.string){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_type,expected:r.string,received:W.parsedType}),Q$}let J=new f_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),d(U,{code:P.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:P.invalid_string,..._$.errToObj(J)})}_addCheck($){return new M6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",..._$.errToObj($)})}url($){return this._addCheck({kind:"url",..._$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",..._$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",..._$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",..._$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",..._$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",..._$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",..._$.errToObj($)})}base64($){return this._addCheck({kind:"base64",..._$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",..._$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",..._$.errToObj($)})}ip($){return this._addCheck({kind:"ip",..._$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",..._$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,..._$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,..._$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",..._$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,..._$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,..._$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,..._$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,..._$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,..._$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,..._$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,..._$.errToObj(_)})}nonempty($){return this.min(1,_$.errToObj($))}trim(){return new M6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new M6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new M6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}M6.create=($)=>{return new M6({checks:[],typeName:D$.ZodString,coerce:$?.coerce??!1,...M$($)})};function Ab($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class Q0 extends k${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==r.number){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_type,expected:r.number,received:W.parsedType}),Q$}let J=void 0,U=new f_;for(let W of this._def.checks)if(W.kind==="int"){if(!y$.isInteger($.data))J=this._getOrReturnCtx($,J),d(J,{code:P.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),d(J,{code:P.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(Ab($.data,W.value)!==0)J=this._getOrReturnCtx($,J),d(J,{code:P.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),d(J,{code:P.not_finite,message:W.message}),U.dirty()}else y$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,_$.toString(_))}gt($,_){return this.setLimit("min",$,!1,_$.toString(_))}lte($,_){return this.setLimit("max",$,!0,_$.toString(_))}lt($,_){return this.setLimit("max",$,!1,_$.toString(_))}setLimit($,_,J,U){return new Q0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:_$.toString(U)}]})}_addCheck($){return new Q0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:_$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:_$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:_$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&y$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}Q0.create=($)=>{return new Q0({checks:[],typeName:D$.ZodNumber,coerce:$?.coerce||!1,...M$($)})};class q0 extends k${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==r.bigint)return this._getInvalidInput($);let J=void 0,U=new f_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),d(J,{code:P.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),d(J,{code:P.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else y$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return d(_,{code:P.invalid_type,expected:r.bigint,received:_.parsedType}),Q$}gte($,_){return this.setLimit("min",$,!0,_$.toString(_))}gt($,_){return this.setLimit("min",$,!1,_$.toString(_))}lte($,_){return this.setLimit("max",$,!0,_$.toString(_))}lt($,_){return this.setLimit("max",$,!1,_$.toString(_))}setLimit($,_,J,U){return new q0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:_$.toString(U)}]})}_addCheck($){return new q0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:_$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}q0.create=($)=>{return new q0({checks:[],typeName:D$.ZodBigInt,coerce:$?.coerce??!1,...M$($)})};class P2 extends k${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==r.boolean){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.boolean,received:J.parsedType}),Q$}return x_($.data)}}P2.create=($)=>{return new P2({typeName:D$.ZodBoolean,coerce:$?.coerce||!1,...M$($)})};class s0 extends k${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==r.date){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_type,expected:r.date,received:W.parsedType}),Q$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return d(W,{code:P.invalid_date}),Q$}let J=new f_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),d(U,{code:P.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else y$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new s0({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:_$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:_$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}s0.create=($)=>{return new s0({checks:[],coerce:$?.coerce||!1,typeName:D$.ZodDate,...M$($)})};class oW extends k${_parse($){if(this._getType($)!==r.symbol){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.symbol,received:J.parsedType}),Q$}return x_($.data)}}oW.create=($)=>{return new oW({typeName:D$.ZodSymbol,...M$($)})};class T2 extends k${_parse($){if(this._getType($)!==r.undefined){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.undefined,received:J.parsedType}),Q$}return x_($.data)}}T2.create=($)=>{return new T2({typeName:D$.ZodUndefined,...M$($)})};class S2 extends k${_parse($){if(this._getType($)!==r.null){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.null,received:J.parsedType}),Q$}return x_($.data)}}S2.create=($)=>{return new S2({typeName:D$.ZodNull,...M$($)})};class e0 extends k${constructor(){super(...arguments);this._any=!0}_parse($){return x_($.data)}}e0.create=($)=>{return new e0({typeName:D$.ZodAny,...M$($)})};class Y0 extends k${constructor(){super(...arguments);this._unknown=!0}_parse($){return x_($.data)}}Y0.create=($)=>{return new Y0({typeName:D$.ZodUnknown,...M$($)})};class _4 extends k${_parse($){let _=this._getOrReturnCtx($);return d(_,{code:P.invalid_type,expected:r.never,received:_.parsedType}),Q$}}_4.create=($)=>{return new _4({typeName:D$.ZodNever,...M$($)})};class tW extends k${_parse($){if(this._getType($)!==r.undefined){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.void,received:J.parsedType}),Q$}return x_($.data)}}tW.create=($)=>{return new tW({typeName:D$.ZodVoid,...M$($)})};class A6 extends k${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==r.array)return d(_,{code:P.invalid_type,expected:r.array,received:_.parsedType}),Q$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)d(_,{code:P.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new w6(_,X,_.path,G))})).then((X)=>{return f_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new w6(_,X,_.path,G))});return f_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new A6({...this._def,minLength:{value:$,message:_$.toString(_)}})}max($,_){return new A6({...this._def,maxLength:{value:$,message:_$.toString(_)}})}length($,_){return new A6({...this._def,exactLength:{value:$,message:_$.toString(_)}})}nonempty($){return this.min(1,$)}}A6.create=($,_)=>{return new A6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:D$.ZodArray,...M$(_)})};function k2($){if($ instanceof O_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=b6.create(k2(U))}return new O_({...$._def,shape:()=>_})}else if($ instanceof A6)return new A6({...$._def,type:k2($.element)});else if($ instanceof b6)return b6.create(k2($.unwrap()));else if($ instanceof A4)return A4.create(k2($.unwrap()));else if($ instanceof J4)return J4.create($.items.map((_)=>k2(_)));else return $}class O_ extends k${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=y$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==r.object){let Q=this._getOrReturnCtx($);return d(Q,{code:P.invalid_type,expected:r.object,received:Q.parsedType}),Q$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof _4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new w6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof _4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)d(U,{code:P.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new w6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return f_.mergeObjectSync(J,Q)});else return f_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return _$.errToObj,new O_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:_$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new O_({...this._def,unknownKeys:"strip"})}passthrough(){return new O_({...this._def,unknownKeys:"passthrough"})}extend($){return new O_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new O_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:D$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new O_({...this._def,catchall:$})}pick($){let _={};for(let J of y$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new O_({...this._def,shape:()=>_})}omit($){let _={};for(let J of y$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new O_({...this._def,shape:()=>_})}deepPartial(){return k2(this)}partial($){let _={};for(let J of y$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new O_({...this._def,shape:()=>_})}required($){let _={};for(let J of y$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof b6)W=W._def.innerType;_[J]=W}return new O_({...this._def,shape:()=>_})}keyof(){return UH(y$.objectKeys(this.shape))}}O_.create=($,_)=>{return new O_({shape:()=>$,unknownKeys:"strip",catchall:_4.create(),typeName:D$.ZodObject,...M$(_)})};O_.strictCreate=($,_)=>{return new O_({shape:()=>$,unknownKeys:"strict",catchall:_4.create(),typeName:D$.ZodObject,...M$(_)})};O_.lazycreate=($,_)=>{return new O_({shape:$,unknownKeys:"strip",catchall:_4.create(),typeName:D$.ZodObject,...M$(_)})};class Z2 extends k${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new e_(G.ctx.common.issues));return d(_,{code:P.invalid_union,unionErrors:X}),Q$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new e_(Y));return d(_,{code:P.invalid_union,unionErrors:G}),Q$}}get options(){return this._def.options}}Z2.create=($,_)=>{return new Z2({options:$,typeName:D$.ZodUnion,...M$(_)})};var E4=($)=>{if($ instanceof y2)return E4($.schema);else if($ instanceof D6)return E4($.innerType());else if($ instanceof h2)return[$.value];else if($ instanceof z0)return $.options;else if($ instanceof m2)return y$.objectValues($.enum);else if($ instanceof x2)return E4($._def.innerType);else if($ instanceof T2)return[void 0];else if($ instanceof S2)return[null];else if($ instanceof b6)return[void 0,...E4($.unwrap())];else if($ instanceof A4)return[null,...E4($.unwrap())];else if($ instanceof F9)return E4($.unwrap());else if($ instanceof d2)return E4($.unwrap());else if($ instanceof u2)return E4($._def.innerType);else return[]};class K9 extends k${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.object)return d(_,{code:P.invalid_type,expected:r.object,received:_.parsedType}),Q$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return d(_,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),Q$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=E4(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new K9({typeName:D$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...M$(J)})}}function hY($,_){let J=M4($),U=M4(_);if($===_)return{valid:!0,data:$};else if(J===r.object&&U===r.object){let W=y$.objectKeys(_),X=y$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=hY($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===r.array&&U===r.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=hY(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===r.date&&U===r.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class v2 extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(vY(W)||vY(X))return Q$;let G=hY(W.value,X.value);if(!G.valid)return d(J,{code:P.invalid_intersection_types}),Q$;if(yY(W)||yY(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}v2.create=($,_,J)=>{return new v2({left:$,right:_,typeName:D$.ZodIntersection,...M$(J)})};class J4 extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.array)return d(J,{code:P.invalid_type,expected:r.array,received:J.parsedType}),Q$;if(J.data.lengththis._def.items.length)d(J,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new w6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return f_.mergeArray(_,X)});else return f_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new J4({...this._def,rest:$})}}J4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new J4({items:$,typeName:D$.ZodTuple,rest:null,...M$(_)})};class aW extends k${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.object)return d(J,{code:P.invalid_type,expected:r.object,received:J.parsedType}),Q$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new w6(J,G,J.path,G)),value:X._parse(new w6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return f_.mergeObjectAsync(_,U);else return f_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof k$)return new aW({keyType:$,valueType:_,typeName:D$.ZodRecord,...M$(J)});return new aW({keyType:M6.create(),valueType:$,typeName:D$.ZodRecord,...M$(_)})}}class sW extends k${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.map)return d(J,{code:P.invalid_type,expected:r.map,received:J.parsedType}),Q$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new w6(J,G,J.path,[Q,"key"])),value:W._parse(new w6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return Q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return Q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}sW.create=($,_,J)=>{return new sW({valueType:_,keyType:$,typeName:D$.ZodMap,...M$(J)})};class $1 extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==r.set)return d(J,{code:P.invalid_type,expected:r.set,received:J.parsedType}),Q$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)d(J,{code:P.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return Q$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new w6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new $1({...this._def,minSize:{value:$,message:_$.toString(_)}})}max($,_){return new $1({...this._def,maxSize:{value:$,message:_$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}$1.create=($,_)=>{return new $1({valueType:$,minSize:null,maxSize:null,typeName:D$.ZodSet,...M$(_)})};class f2 extends k${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.function)return d(_,{code:P.invalid_type,expected:r.function,received:_.parsedType}),Q$;function J(G,Y){return V9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,N9(),C2].filter((Q)=>!!Q),issueData:{code:P.invalid_arguments,argumentsError:Y}})}function U(G,Y){return V9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,N9(),C2].filter((Q)=>!!Q),issueData:{code:P.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof _1){let G=this;return x_(async function(...Y){let Q=new e_([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return x_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new e_([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new e_([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new f2({...this._def,args:J4.create($).rest(Y0.create())})}returns($){return new f2({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new f2({args:$?$:J4.create([]).rest(Y0.create()),returns:_||Y0.create(),typeName:D$.ZodFunction,...M$(J)})}}class y2 extends k${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}y2.create=($,_)=>{return new y2({getter:$,typeName:D$.ZodLazy,...M$(_)})};class h2 extends k${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return d(_,{received:_.data,code:P.invalid_literal,expected:this._def.value}),Q$}return{status:"valid",value:$.data}}get value(){return this._def.value}}h2.create=($,_)=>{return new h2({value:$,typeName:D$.ZodLiteral,...M$(_)})};function UH($,_){return new z0({values:$,typeName:D$.ZodEnum,...M$(_)})}class z0 extends k${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return d(_,{expected:y$.joinValues(J),received:_.parsedType,code:P.invalid_type}),Q$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return d(_,{received:_.data,code:P.invalid_enum_value,options:J}),Q$}return x_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return z0.create($,{...this._def,..._})}exclude($,_=this._def){return z0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}z0.create=UH;class m2 extends k${_parse($){let _=y$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==r.string&&J.parsedType!==r.number){let U=y$.objectValues(_);return d(J,{expected:y$.joinValues(U),received:J.parsedType,code:P.invalid_type}),Q$}if(!this._cache)this._cache=new Set(y$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=y$.objectValues(_);return d(J,{received:J.data,code:P.invalid_enum_value,options:U}),Q$}return x_($.data)}get enum(){return this._def.values}}m2.create=($,_)=>{return new m2({values:$,typeName:D$.ZodNativeEnum,...M$(_)})};class _1 extends k${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==r.promise&&_.common.async===!1)return d(_,{code:P.invalid_type,expected:r.promise,received:_.parsedType}),Q$;let J=_.parsedType===r.promise?_.data:Promise.resolve(_.data);return x_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}_1.create=($,_)=>{return new _1({type:$,typeName:D$.ZodPromise,...M$(_)})};class D6 extends k${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(d(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return Q$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return Q$;if(Y.status==="dirty")return I2(Y.value);if(_.value==="dirty")return I2(Y.value);return Y});else{if(_.value==="aborted")return Q$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return Q$;if(G.status==="dirty")return I2(G.value);if(_.value==="dirty")return I2(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return Q$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return Q$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!a0(X))return Q$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!a0(X))return Q$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});y$.assertNever(U)}}D6.create=($,_,J)=>{return new D6({schema:$,typeName:D$.ZodEffects,effect:_,...M$(J)})};D6.createWithPreprocess=($,_,J)=>{return new D6({schema:_,effect:{type:"preprocess",transform:$},typeName:D$.ZodEffects,...M$(J)})};class b6 extends k${_parse($){if(this._getType($)===r.undefined)return x_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}b6.create=($,_)=>{return new b6({innerType:$,typeName:D$.ZodOptional,...M$(_)})};class A4 extends k${_parse($){if(this._getType($)===r.null)return x_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}A4.create=($,_)=>{return new A4({innerType:$,typeName:D$.ZodNullable,...M$(_)})};class x2 extends k${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===r.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}x2.create=($,_)=>{return new x2({innerType:$,typeName:D$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...M$(_)})};class u2 extends k${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(pW(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new e_(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new e_(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}u2.create=($,_)=>{return new u2({innerType:$,typeName:D$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...M$(_)})};class eW extends k${_parse($){if(this._getType($)!==r.nan){let J=this._getOrReturnCtx($);return d(J,{code:P.invalid_type,expected:r.nan,received:J.parsedType}),Q$}return{status:"valid",value:$.data}}}eW.create=($)=>{return new eW({typeName:D$.ZodNaN,...M$($)})};var bb=Symbol("zod_brand");class F9 extends k${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class $U extends k${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return Q$;if(W.status==="dirty")return _.dirty(),I2(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return Q$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new $U({in:$,out:_,typeName:D$.ZodPipeline})}}class d2 extends k${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(a0(U))U.value=Object.freeze(U.value);return U};return pW(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}d2.create=($,_)=>{return new d2({innerType:$,typeName:D$.ZodReadonly,...M$(_)})};function oB($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function XH($,_={},J){if($)return e0.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=oB(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=oB(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return e0.create()}var wb={object:O_.lazycreate},D$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(D$||(D$={}));var gb=($,_={message:`Input not instance of ${$.name}`})=>XH((J)=>J instanceof $,_),GH=M6.create,YH=Q0.create,kb=eW.create,Ib=q0.create,QH=P2.create,fb=s0.create,Cb=oW.create,Pb=T2.create,Tb=S2.create,Sb=e0.create,Zb=Y0.create,vb=_4.create,yb=tW.create,hb=A6.create,mb=O_.create,xb=O_.strictCreate,ub=Z2.create,db=K9.create,nb=v2.create,cb=J4.create,ib=aW.create,lb=sW.create,rb=$1.create,pb=f2.create,ob=y2.create,tb=h2.create,ab=z0.create,sb=m2.create,eb=_1.create,tB=D6.create,$w=b6.create,_w=A4.create,Jw=D6.createWithPreprocess,Ww=$U.create,Uw=()=>GH().optional(),Xw=()=>YH().optional(),Gw=()=>QH().optional(),Yw={string:($)=>M6.create({...$,coerce:!0}),number:($)=>Q0.create({...$,coerce:!0}),boolean:($)=>P2.create({...$,coerce:!0}),bigint:($)=>q0.create({...$,coerce:!0}),date:($)=>s0.create({...$,coerce:!0})},Qw=Q$;var $$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},qH=z.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),$6=z.string().datetime(),H$=z.string().trim().min(1),b4=H$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),zH=z.string().regex(/^[a-fA-F0-9]{64}$/),jH=z.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),w4=z.record(z.unknown()),i2=z.array(z.string().min(1)).default([]),J1=$6.nullable().optional(),qw=new Set(["succeeded","failed","cancelled","blocked","skipped"]),U1=z.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function p$($){return z.object({schema:z.literal($),id:z.string().min(1),createdAt:$6,updatedAt:J1,metadata:w4.optional()}).strict()}var Yt=z.object({schema:qH,id:z.string().min(1),createdAt:$6,updatedAt:J1,metadata:w4.optional()}).strict(),DH=z.enum(["agent","human","service","model","workflow","system"]),zw=p$($$.actorRef).extend({kind:DH,name:z.string().min(1).optional(),provider:z.string().min(1).optional(),accountId:z.string().min(1).optional(),machineId:z.string().min(1).optional(),capabilities:z.array(z.string().min(1)).default([])}).strict(),W4=z.object({kind:DH,id:z.string().min(1),name:z.string().min(1).optional(),provider:z.string().min(1).optional(),accountId:z.string().min(1).optional(),machineId:z.string().min(1).optional()}).strict(),OH=z.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),jw=p$($$.resourceRef).extend({kind:OH,name:z.string().min(1).optional(),uri:b4.optional(),externalId:H$.optional(),sourcePackage:H$.optional(),tags:i2}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:z.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),g$=z.object({kind:OH,id:z.string().min(1),name:z.string().min(1).optional(),uri:b4.optional(),externalId:H$.optional(),sourcePackage:H$.optional(),tags:i2}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:z.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),xY=z.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),Dw=z.enum(["none","partial","full","unknown"]),Ow=p$($$.evidenceRef).extend({kind:xY,uri:b4,sha256:zH.optional(),summary:z.string().min(1).optional(),contentType:z.string().min(1).optional(),sizeBytes:z.number().int().nonnegative().optional(),redaction:Dw.default("unknown"),producer:W4.optional(),resourceRefs:z.array(g$).default([]),tags:i2}).strict(),G_=z.object({id:z.string().min(1),kind:xY.optional(),uri:b4.optional(),sha256:zH.optional(),summary:z.string().min(1).optional()}).strict(),_U=p$($$.costEstimate).extend({currency:z.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:z.number().int().nonnegative(),provider:z.string().min(1).optional(),model:z.string().min(1).optional(),accountId:z.string().min(1).optional(),promptTokens:z.number().int().nonnegative().optional(),completionTokens:z.number().int().nonnegative().optional(),totalTokens:z.number().int().nonnegative().optional(),basis:z.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:z.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),Lw=z.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),LH=p$($$.decisionEnvelope).extend({decisionType:z.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:Lw,actor:W4.optional(),traceId:z.string().min(1).optional(),inputHash:jH.optional(),policyBundleId:z.string().min(1).optional(),selected:z.array(g$).default([]),skipped:z.array(g$).default([]),reason:z.string().min(1),obligations:z.array(z.string().min(1)).default([]),redactions:z.array(z.string().min(1)).default([]),costEstimate:_U.optional(),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),Bw=p$($$.capabilityCard).extend({kind:z.enum(["model","tool","machine","agent","lane","connector","service"]),name:z.string().min(1),version:z.string().min(1).optional(),status:z.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:z.array(z.string().min(1)).default([]),limitations:z.array(z.string().min(1)).default([]),riskLevel:z.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:_U.optional(),evidenceRefs:z.array(G_).default([])}).strict(),n2=z.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),Hw=z.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),Nw=z.object({refName:H$,requiredForModes:z.array(n2).min(1),allowedSecretInputs:z.array(z.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:H$,revocationCheck:z.boolean().default(!0)}).strict(),Vw=z.object({operation:H$,supportedModes:z.array(n2).min(1),sideEffectClass:Hw,requiresApproval:z.boolean().default(!1),requiresIdempotencyKey:z.boolean().default(!1),requiresSandboxEvidence:z.boolean().default(!1),requiresRollbackOrRevocation:z.boolean().default(!1),rollbackOrRevocation:H$.optional(),noSideEffectSmoke:H$.optional(),reconciliation:H$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),Rw=z.object({providerId:H$,appId:H$,adapterId:H$,ownerPackage:H$,modes:z.array(n2).min(1),defaultMode:n2,credentialRequirements:z.array(Nw).default([]),operations:z.array(Vw).min(1),rateLimitPosture:H$,costPosture:H$.optional(),auditEvents:z.array(H$).default([]),redactionRules:z.array(H$).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:z.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),Kw=z.object({appId:H$,repo:H$,priority:z.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:z.array(H$).min(1),firstOperations:z.array(H$).min(1),blockedUntil:z.array(H$).default([])}).strict(),Fw=p$($$.providerLiveModeStandard).extend({name:H$,version:H$,modes:z.array(n2).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:z.array(H$).min(1),liveMutationGate:z.object({requiredMode:z.literal("live_mutating"),requiredChecks:z.array(H$).min(1),forbiddenBypassSignals:z.array(H$).min(1),disabledLiveSmoke:H$}).strict(),noSideEffectSmoke:z.object({requiredForModes:z.array(n2).min(1),commandEvidence:z.array(H$).min(1),secretOutputScan:z.boolean().default(!0)}).strict(),credentialPolicy:z.object({acceptedInputs:z.array(z.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:z.literal(!1),missingCredentialBehavior:z.literal("fail_closed"),revocationCheckRequired:z.boolean().default(!0)}).strict(),operationCards:z.array(Rw).min(1),firstAdoptionTargets:z.array(Kw).min(1),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:z.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),Ew=z.object({id:z.string().min(1),title:z.string().min(1).optional(),summary:z.string().min(1),text:z.string().optional(),tokens:z.number().int().nonnegative().optional(),source:G_,resourceRefs:z.array(g$).default([])}).strict(),BH=p$($$.contextPack).extend({objective:z.string().min(1),budget:z.object({maxTokens:z.number().int().positive().optional(),maxBytes:z.number().int().positive().optional()}).strict().optional(),items:z.array(Ew).default([]),citations:z.array(G_).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),permissions:z.array(z.string().min(1)).default([]),redactions:z.array(z.string().min(1)).default([]),conflicts:z.array(z.string().min(1)).default([]),uncertainty:z.string().min(1).optional()}).strict(),E6=H$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),W1=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),Mw=z.enum(["public","internal","private","sensitive"]),Aw=z.enum(["draft","active","paused","archived"]),uY=z.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),HH=p$($$.integrationRef).extend({kind:uY,name:z.string().min(1),projectId:W1.optional(),sourcePackage:H$.optional(),externalId:H$.optional(),uri:b4.optional(),enabled:z.boolean().default(!0),readOnly:z.boolean().default(!0),capabilities:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:g$.optional(),evidenceRefs:z.array(G_).default([]),config:w4.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:z.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),bw=z.object({schemaRoot:E6.default(".hasna/project"),dashboardManifest:E6.default(".hasna/project/dashboard.render.json"),snapshotsDir:E6.default(".hasna/project/snapshots"),documentsDir:E6.default("documents"),reportsDir:E6.default("reports"),evidenceDir:E6.default(".hasna/project/evidence"),privateDir:E6.default(".hasna/project/private")}).strict(),ww=p$($$.projectManifest).extend({projectId:W1,slug:W1,name:z.string().min(1),summary:z.string().min(1).optional(),status:Aw.default("active"),classification:Mw.default("private"),owner:W4.optional(),layout:bw.default({}),integrations:z.array(HH).default([]),renderManifests:z.array(g$).default([]),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),tags:i2}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:z.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:z.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:z.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),gw=z.enum(["local","package","provider","url"]),dY=z.object({id:z.string().min(1),kind:gw,specifier:z.string().min(1),path:E6.optional(),packageName:z.string().min(1).optional(),uri:b4.optional(),provider:uY.optional(),schemaId:qH.optional(),integrity:jH.optional(),resourceRef:g$.optional(),optional:z.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:z.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:z.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:z.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:z.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),kw=z.enum(["dashboard","canvas","panel","report","document","custom"]),Iw=z.object({id:z.string().min(1),title:z.string().min(1),kind:kw,default:z.boolean().default(!1),entry:E6.optional(),imports:z.array(dY).default([]),panelRefs:z.array(g$).default([]),dataRefs:z.array(g$).default([]),layout:w4.optional()}).strict(),fw=p$($$.renderManifest).extend({projectId:W1,name:z.string().min(1),version:z.string().min(1),manifestPath:E6.default(".hasna/project/dashboard.render.json"),renderer:z.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:z.array(Iw).min(1),imports:z.array(dY).default([]),theme:w4.optional(),compatibility:z.object({minProjectsVersion:z.string().min(1).optional(),minContractsVersion:z.string().min(1).optional()}).strict().optional(),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:z.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),Cw=z.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),Pw=z.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Tw=z.object({id:z.string().min(1),label:z.string().min(1),value:z.union([z.string(),z.number(),z.boolean()]),unit:z.string().min(1).optional(),status:z.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:z.array(g$).default([])}).strict(),Sw=z.object({id:z.string().min(1),title:z.string().min(1),summary:z.string().min(1).optional(),status:z.string().min(1).optional(),priority:z.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:$6.optional(),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),metadata:w4.optional()}).strict(),Zw=z.object({renderer:z.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:z.string().min(1).optional(),entry:E6.optional(),imports:z.array(dY).default([]),spec:w4.default({})}).strict(),NH=p$($$.projectPanel).extend({projectId:W1,provider:z.object({kind:uY,id:z.string().min(1),name:z.string().min(1).optional(),sourcePackage:H$.optional(),externalId:H$.optional()}).strict(),kind:Pw,title:z.string().min(1),summary:z.string().min(1).optional(),state:Cw.default("ready"),stateReason:z.string().min(1).optional(),generatedAt:$6,freshness:z.enum(["fresh","stale","unknown"]).default("unknown"),metrics:z.array(Tw).default([]),items:z.array(Sw).default([]),actions:z.array(g$).default([]),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),renderFragment:Zw.optional(),warnings:z.array(z.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:z.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:z.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:z.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),vw=p$($$.projectSnapshot).extend({projectId:W1,generatedAt:$6,status:U1.default("unknown"),manifestRef:g$,renderManifestRef:g$.optional(),panels:z.array(NH).default([]),contextPacks:z.array(BH).default([]),proofBundleRefs:z.array(g$).default([]),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),warnings:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:z.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:z.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),VH=z.object({id:z.string().min(1),kind:z.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:z.boolean().default(!0),command:z.string().min(1).optional(),expected:z.string().min(1).optional(),timeoutMs:z.number().int().positive().optional(),resourceRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:z.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),yw=p$($$.validationPlan).extend({objective:z.string().min(1),subject:g$.optional(),checks:z.array(VH).min(1),verifier:W4.optional(),requiredEvidenceKinds:z.array(xY).default([])}).strict(),hw=z.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),mw=z.enum(["draft","active","deprecated","archived"]),xw=z.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),uw=z.object({key:z.string().regex(/^[A-Z][A-Z0-9_]*$/),description:z.string().min(1),required:z.boolean().default(!1),["secret"]:z.boolean().default(!1),group:z.string().min(1).optional(),default:z.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),dw=z.object({name:z.string().min(1),command:z.string().min(1),description:z.string().min(1).optional(),required:z.boolean().default(!1)}).strict(),nw=z.object({packageManager:z.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:z.array(z.string().min(1)).default([]),requiredFiles:z.array(z.string().min(1)).default([]),requiredDirectories:z.array(z.string().min(1)).default([]),optionalDirectories:z.array(z.string().min(1)).default([])}).strict(),cw=p$($$.scaffoldManifest).extend({name:z.string().min(1),version:z.string().min(1),summary:z.string().min(1),type:hw,status:mw.default("draft"),capabilities:z.array(xw).default([]),techStack:z.array(z.string().min(1)).default([]),tags:i2,source:g$.optional(),output:nw,env:z.array(uw).default([]),scripts:z.array(dw).default([]),validationChecks:z.array(VH).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:z.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),iw=z.enum(["installed","failed","cancelled","partial","unknown"]),lw=p$($$.scaffoldInstallRecord).extend({scaffoldId:z.string().min(1),scaffoldVersion:z.string().min(1).optional(),manifestRef:g$.optional(),target:g$,status:iw,installedAt:$6.optional(),installer:W4.optional(),packageManager:z.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:w4.optional(),generatedFiles:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),proofBundleRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:z.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),c2=z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),nY=z.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),RH=z.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),rw=z.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),pw=H$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),ow=z.enum(["active","stub","deprecated","archived"]),tw=z.enum(["stable","beta","canary","internal"]),aw=z.object({transport:z.enum(["http","stdio"]).default("http"),bin:z.string().min(1).optional(),url:b4.optional()}).strict(),sw=z.object({healthPath:z.string().min(1).default("/health"),port:z.number().int().positive().optional(),baseUrl:b4.optional()}).strict(),ew=z.object({bins:z.array(z.string().min(1)).default([]),mcp:aw.optional(),http:sw.optional()}).strict(),$g=p$($$.app).extend({appId:c2,npmName:nY,repoFolder:c2,githubUrl:pw,projectSlug:W1,surfaces:ew.default({}),lifecycle:ow,releaseChannel:tw.default("stable"),summary:z.string().min(1).optional(),tags:i2}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:z.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),_g=z.enum(["skill","ci","backfilled"]),Jg=p$($$.release).extend({appId:c2,package:nY,version:RH,gitSha:rw,publishedAt:$6,publishPath:_g,changelogRef:g$.optional(),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Wg=z.enum(["install","update","rollback","freeze-blocked"]),Ug=z.object({cliVersion:z.string().min(1).optional(),mcpHealth:z.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),Xg=p$($$.rolloutRecord).extend({appId:c2,package:nY,version:RH,machine:H$,action:Wg,result:U1,verifiedBy:Ug.optional(),at:$6,evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:z.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),Gg=z.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),Yg=z.enum(["pending","queued","sent","failed","skipped","suppressed"]),Qg=z.object({channel:Gg,status:Yg,deliveredAt:$6.optional(),detail:z.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:z.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),qg=p$($$.announcement).extend({campaignId:H$,appId:c2.optional(),releaseRef:g$.optional(),channels:z.array(Qg).min(1),audienceRef:g$,sentAt:$6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:z.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:z.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),zg=z.enum(["tag","attribute","group"]),jg=z.enum(["eq","neq","in","not_in","exists","not_exists"]),aB=z.union([z.string(),z.number(),z.boolean()]),Dg=z.object({kind:zg,key:z.string().min(1).optional(),op:jg.default("eq"),value:aB.optional(),values:z.array(aB).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:z.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:z.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),Og=z.object({match:z.enum(["all","any"]).default("all"),predicates:z.array(Dg).min(1)}).strict(),Lg=z.enum(["opt_in","opt_out","transactional","none"]),Bg=p$($$.audience).extend({audienceId:c2,name:H$,definition:Og,consentPolicy:Lg,suppressionSyncedAt:J1}).strict(),PY=["@hasna/cloud","open-cloud"],Hg=z.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),Ng=z.object({id:z.string().min(1),provider:Hg,kind:z.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:z.string().min(1),region:z.string().min(1).optional(),accountId:z.string().min(1).optional(),uri:b4.optional(),machineScoped:z.boolean().default(!1)}).strict(),KH=p$($$.appCloudManifest).extend({packageName:z.string().min(1),packageVersion:z.string().min(1).optional(),appId:z.string().min(1),repository:g$.optional(),storageMode:z.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:z.enum(["none","app_owned","external_service","local_cache"]),cloudResources:z.array(Ng).default([]),localCache:z.object({path:z.string().min(1).optional(),pullMode:z.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:z.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:z.array(z.string().min(1)).default([...PY]),dependencies:z.array(z.string().min(1)).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...PY,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:z.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of PY)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:z.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:z.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:z.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:z.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:z.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:z.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:z.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),FH=z.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),Vg=z.enum(["low","medium","high","critical"]),EH=z.object({id:z.string().min(1),kind:FH,severity:Vg,path:z.string().min(1).optional(),packageName:z.string().min(1).optional(),pattern:z.string().min(1),message:z.string().min(1),evidenceRefs:z.array(G_).default([])}).strict(),Rg=z.object({id:z.string().min(1),kind:FH,status:U1,target:z.string().min(1),command:z.string().min(1).optional(),evidenceRefs:z.array(G_).default([]),findings:z.array(EH).default([])}).strict(),Kg=p$($$.noCloudEvidencePack).extend({subject:g$,packageName:z.string().min(1).optional(),packageVersion:z.string().min(1).optional(),generatedBy:W4.optional(),scanMode:z.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:U1,verdict:z.enum(["passed","failed","warning","not_run"]),appCloudManifest:KH.optional(),checks:z.array(Rg).min(1),findings:z.array(EH).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:z.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),Fg=z.object({checkId:z.string().min(1),status:U1,summary:z.string().min(1).optional(),startedAt:J1,finishedAt:J1,evidenceRefs:z.array(G_).default([])}).strict(),Eg=p$($$.proofBundle).extend({subject:g$,validationPlanRef:g$.optional(),status:U1,verdict:z.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:z.array(Fg).default([]),verifier:W4.optional(),evidenceRefs:z.array(G_).default([]),residualRisks:z.array(z.string().min(1)).default([]),freshness:z.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:z.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:z.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),Mg=p$($$.workRun).extend({objective:z.string().min(1),status:U1,actor:W4,traceId:z.string().min(1).optional(),startedAt:J1,finishedAt:J1,constraints:z.array(z.string().min(1)).default([]),resourceRefs:z.array(g$).default([]),decisions:z.array(LH).default([]),costEstimates:z.array(_U).default([]),evidenceRefs:z.array(G_).default([]),validationPlanRefs:z.array(g$).default([]),proofBundleRefs:z.array(g$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:z.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),Ag=z.object({id:z.string().min(1),at:$6,kind:z.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:z.string().min(1),resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([]),costEstimate:_U.optional()}).strict(),bg=p$($$.agentTrajectory).extend({actor:W4,workRunRef:g$.optional(),events:z.array(Ag).default([]),outcome:z.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:g$.optional()}).strict(),wg="v1",gg=z.enum(["library","cli-with-store","service","saas"]),kg=["local","self-hosted","cloud"],MH=z.enum(kg),Ig=z.enum(["supported","deferred","unsupported"]),fg=z.enum(["none","local-only","api-key","session","service-token","custom"]),TY=z.object({method:z.enum(["GET","POST","PUT","PATCH","DELETE"]),path:z.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:z.boolean().default(!1),description:z.string().min(1).optional()}).strict(),Cg=z.object({id:z.string().min(1),kind:z.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:z.boolean().default(!0),command:z.string().min(1).optional(),evidenceRef:G_.optional(),status:z.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:z.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:z.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),Pg=z.object({name:z.string().min(1),status:Ig,bin:z.string().min(1).optional(),mcpBin:z.string().min(1).optional(),authMode:fg,deploymentModes:z.array(MH).min(1),health:TY.optional(),readiness:TY.optional(),version:TY.optional(),apiBasePath:z.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:z.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:z.string().min(1).optional(),readinessGates:z.array(Cg).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:z.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:z.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:z.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:z.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:z.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),Tg=["local","cloud"],AH=z.enum(Tg),Sg=["remote","hybrid","self_hosted"],Zg=z.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),vg=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function yg($){return vg.map((_)=>`${$}${_}`)}function sB($){return`hasna/oss/${$}/database-url`}var hg=z.object({mode:AH,envPrefix:z.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:z.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:z.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:z.string().min(1).optional()}).strict(),mg=z.object({$schema:z.string().min(1).optional(),schema:z.literal($$.serviceContract),name:Zg,class:gg,contractVersion:z.literal(wg),kitVersion:z.string().min(1),description:z.string().min(1).optional(),bins:z.array(z.string().min(1)).default([]),storage:hg.optional(),deploymentModes:z.array(MH).default(["local"]),serviceSurfaces:z.array(Pg).default([]),metadata:w4.optional()}).strict().superRefine(($,_)=>{let J=new Set(yg($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:z.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:z.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:z.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==sB($.name))_.addIssue({code:z.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${sB($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:z.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:z.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:z.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:z.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:z.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:z.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:z.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),Qt=z.object({status:z.enum(["ok","degraded","unavailable"]),version:z.string().min(1),mode:AH}).strict(),qt=z.object({ready:z.boolean(),reason:z.string().min(1).optional()}).strict(),zt=z.object({version:z.string().min(1)}).strict(),xg=z.enum(["info","notice","breaking","critical"]),ug=z.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),dg=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],ng=z.enum(dg);var cg=z.enum(["fleet","package","machine"]),bH=p$($$.commsEventEnvelope).extend({type:ug,severity:xg,scope:cg,summary:z.string().min(1).optional(),source:W4.optional(),affected_packages:z.array(H$).default([]),affected_machines:z.array(H$).default([]),action_required:z.boolean().default(!1),ack_by:$6.optional(),dedupe_key:H$,resourceRefs:z.array(g$).default([]),evidenceRefs:z.array(G_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:z.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:z.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:z.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),ig=z.enum(["fleet","package","product","loop-lane","initiative","personal"]),lg=z.enum(["quiet","work","firehose"]),rg=H$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),pg=p$($$.commsChannelMetadata).extend({class:ig,noise:lg.optional(),owner:H$.optional(),until:rg.optional(),successor:H$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:z.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:z.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),eB={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},og=p$($$.commsMessageMetadata).extend({tag:ng,envelope:bH}).strict().superRefine(($,_)=>{let J=eB[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:z.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:z.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(eB))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:z.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var jt={[$$.actorRef]:zw,[$$.resourceRef]:jw,[$$.evidenceRef]:Ow,[$$.workRun]:Mg,[$$.decisionEnvelope]:LH,[$$.costEstimate]:_U,[$$.capabilityCard]:Bw,[$$.providerLiveModeStandard]:Fw,[$$.contextPack]:BH,[$$.integrationRef]:HH,[$$.projectManifest]:ww,[$$.projectPanel]:NH,[$$.projectSnapshot]:vw,[$$.renderManifest]:fw,[$$.agentTrajectory]:bg,[$$.validationPlan]:yw,[$$.proofBundle]:Eg,[$$.scaffoldManifest]:cw,[$$.scaffoldInstallRecord]:lw,[$$.appCloudManifest]:KH,[$$.noCloudEvidencePack]:Kg,[$$.serviceContract]:mg,[$$.commsEventEnvelope]:bH,[$$.commsChannelMetadata]:pg,[$$.commsMessageMetadata]:og,[$$.app]:$g,[$$.release]:Jg,[$$.rolloutRecord]:Xg,[$$.announcement]:qg,[$$.audience]:Bg};function tg($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(Sg.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}function ag($){return $.toUpperCase().replace(/-/g,"_")}function sg($){return`https://${$}.hasna.xyz`}function wH($){let _=ag($);return{modeKeys:[`HASNA_${_}_STORAGE_MODE`,`HASNA_${_}_MODE`,`${_}_STORAGE_MODE`,`${_}_MODE`],apiUrlKeys:[`HASNA_${_}_API_URL`,`${_}_API_URL`],apiKeyKeys:[`HASNA_${_}_API_KEY`,`${_}_API_KEY`]}}function H9($,_){for(let J of _){let U=$[J]?.trim();if(U)return{key:J,value:U}}return null}function eg($){let _=new URL($);if(_.protocol!=="http:"&&_.protocol!=="https:")throw Error("API URL must use http or https.");let J=_.pathname.replace(/\/+$/,"");if(J.endsWith("/v1"))J=J.slice(0,-3);return _.pathname=`${J}/v1`,_.search="",_.hash="",_.toString().replace(/\/+$/,"")}function $k($,_=process.env){let J=wH($),U=H9(_,J.modeKeys),W=H9(_,J.apiUrlKeys),X=H9(_,J.apiKeyKeys),G="local",Y=null,Q="default",q=[];if(U){let B=tg(U.value);if(G=B.mode,Y=B.deprecatedAlias,Q=U.key,Y)q.push(`Deprecated mode '${Y}' from ${U.key} is treated as 'cloud'. Prefer ${J.modeKeys[0]}=cloud.`)}else if(W&&X)G="cloud",Q=`${W.key}+${X.key}`;if(G==="local")return{transport:"local",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(X),apiKeySource:X?X.key:null,misconfigured:!1,warning:q.length>0?q.join(" "):null};if(!X)return q.push(`${Q}=cloud but no API key is set (${J.apiKeyKeys[0]}). Refusing to route to cloud; using local store. Set ${J.apiKeyKeys[0]} to enable the cloud client.`),{transport:"local",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,misconfigured:!0,warning:q.join(" ")};let L=W?.value??sg($),N=W?W.key:"default",R;try{R=eg(L)}catch(B){let H=B instanceof Error?B.message:String(B);return q.push(`Invalid API URL from ${N}: ${H}. Using local store.`),{transport:"local",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:X.key,misconfigured:!0,warning:q.join(" ")}}return{transport:"cloud-http",mode:G,deprecatedAlias:Y,modeSource:Q,baseUrl:R,apiUrlSource:N,apiKeyPresent:!0,apiKeySource:X.key,misconfigured:!1,warning:q.length>0?q.join(" "):null}}class R9 extends Error{status;method;path;body;constructor($,_,J,U){super(`Hasna cloud request failed: ${$} ${_} -> ${J}`);this.name="HasnaHttpError",this.status=J,this.method=$,this.path=_,this.body=U}}var _k=[408,425,429,500,502,503,504],Jk=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]);function Wk($,_){if(!_)return $;let J=_ instanceof URLSearchParams?_:new URLSearchParams;if(!(_ instanceof URLSearchParams))for(let[W,X]of Object.entries(_)){if(X===null||X===void 0)continue;if(Array.isArray(X))for(let G of X)J.append(W,String(G));else J.append(W,String(X))}let U=J.toString();if(!U)return $;return`${$}${$.includes("?")?"&":"?"}${U}`}var Uk=($)=>new Promise((_)=>setTimeout(_,$));function Xk($){let _=$.fetchImpl??((q,L)=>fetch(q,L)),J=$.baseUrl.replace(/\/+$/,""),U=$.timeoutMs??30000,W=$.sleepImpl??Uk,X=$.retry;function G(q){let L=q!==void 0?q:X;if(L===!1)return null;let N=L??{};return{retries:N.retries??2,baseDelayMs:N.baseDelayMs??200,maxDelayMs:N.maxDelayMs??2000,retryStatuses:N.retryStatuses??[..._k]}}async function Y(q,L,N,R,B){let H={"x-api-key":$.apiKey,Authorization:`Bearer ${$.apiKey}`,Accept:"application/json",...$.headers??{},...B.headers??{}};if(B.idempotencyKey)H["Idempotency-Key"]=B.idempotencyKey;let V={method:q,headers:H};if(R!==void 0)H["Content-Type"]="application/json",V.body=JSON.stringify(R);let K=new AbortController,E=()=>K.abort();if(B.signal)if(B.signal.aborted)K.abort();else B.signal.addEventListener("abort",E,{once:!0});let F=setTimeout(()=>K.abort(),B.timeoutMs??U);V.signal=K.signal;let w;try{w=await _(N,V)}catch(v){let k=v instanceof Error?v:Error(String(v));if(B.signal?.aborted)return{ok:!1,retryable:!1,error:k};return{ok:!1,retryable:!0,error:k}}finally{if(clearTimeout(F),B.signal)B.signal.removeEventListener("abort",E)}let A=await w.text(),g=void 0;if(A.length>0)try{g=JSON.parse(A)}catch{g=A}if(!w.ok){let v=G(B.retry);return{ok:!1,retryable:v?v.retryStatuses.includes(w.status):!1,error:new R9(q,L,w.status,g)}}return{ok:!0,value:g}}async function Q(q,L,N,R={}){let B=q.toUpperCase(),H=Wk(L.startsWith("/")?L:`/${L}`,R.query),V=`${J}${H}`,K=G(R.retry),E=Jk.has(B)||Boolean(R.idempotencyKey),F=K&&E?K.retries+1:1,w=null;for(let A=1;A<=F;A++){let g=await Y(B,H,V,N,R);if(g.ok)return g.value;if(w=g,!(K!==null&&E&&g.retryable&&AQ("GET",q,void 0,L),post:(q,L,N)=>Q("POST",q,L,N),put:(q,L,N)=>Q("PUT",q,L,N),patch:(q,L,N)=>Q("PATCH",q,L,N),del:(q,L,N)=>Q("DELETE",q,L,N)}}function Gk($,_=process.env,J){let U=$k($,_);if(U.misconfigured)throw Error(U.warning??`Client for '${$}' is misconfigured for cloud mode.`);if(U.transport==="local"||!U.baseUrl)return{transport:"local",client:null,resolution:U};let W=wH($),X=H9(_,W.apiKeyKeys)?.value;if(!X)throw Error(`Client for '${$}' resolved to cloud-http without an API key.`);return{transport:"cloud-http",client:Xk({name:$,baseUrl:U.baseUrl,apiKey:X,...J?.fetchImpl?{fetchImpl:J.fetchImpl}:{},...J?.headers?{headers:J.headers}:{},...J?.timeoutMs?{timeoutMs:J.timeoutMs}:{},...J?.retry!==void 0?{retry:J.retry}:{},...J?.sleepImpl?{sleepImpl:J.sleepImpl}:{}}),resolution:U}}function mY($){let _=$.replace(/^\/+|\/+$/g,"");if(!_)throw Error("resource must be a non-empty path segment");return`/${_}`}function SY($,_){if(_===void 0||_===null||`${_}`.length===0)throw Error("id must be a non-empty string");return`${mY($)}/${encodeURIComponent(String(_))}`}function Yk(){let $=globalThis;if($.crypto?.randomUUID)return $.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function Qk($){if(Array.isArray($))return $;if($&&typeof $==="object"){let _=$;for(let J of["items","data","results","rows","records"])if(Array.isArray(_[J]))return _[J]}return[]}function qk($){if($&&typeof $==="object"){let _=$;for(let J of["total","count","totalCount","total_count"])if(typeof _[J]==="number")return _[J]}return null}function zk($){if($&&typeof $==="object"){let _=$;for(let J of["cursor","nextCursor","next_cursor","next"])if(typeof _[J]==="string")return _[J]}return null}function jk($,_){return{name:$,baseUrl:_.baseUrl,transport:_,async list(J,U={}){let W=await _.get(mY(J),U);return{items:Qk(W),total:qk(W),cursor:zk(W),raw:W}},async get(J,U,W={}){try{return await _.get(SY(J,U),W)}catch(X){if(X instanceof R9&&X.status===404)return null;throw X}},async create(J,U,W={}){let{idempotencyKey:X,...G}=W;return _.post(mY(J),U,{...G,idempotencyKey:X??Yk()})},async update(J,U,W,X={}){let{method:G="PATCH",idempotencyKey:Y,...Q}=X;return(G==="PUT"?_.put:_.patch)(SY(J,U),W,{...Q,...Y?{idempotencyKey:Y}:{}})},async delete(J,U,W={}){try{await _.del(SY(J,U),void 0,W)}catch(X){if(X instanceof R9&&X.status===404)return;throw X}}}}function cY($,_=process.env,J){let U=Gk($,_,J);if(U.transport==="cloud-http")return{transport:"cloud-http",client:jk($,U.client)};return{transport:"local",client:null}}var Dk=Object.defineProperty,Ok=($)=>$;function Lk($,_){this[$]=Ok.bind(null,_)}var Bk=($,_)=>{for(var J in _)Dk($,J,{get:_[J],enumerable:!0,configurable:!0,set:Lk.bind(_,J)})},j={};Bk(j,{void:()=>ek,util:()=>h$,unknown:()=>ak,union:()=>WI,undefined:()=>pk,tuple:()=>GI,transformer:()=>IH,symbol:()=>rk,string:()=>mH,strictObject:()=>JI,setErrorMap:()=>Vk,set:()=>qI,record:()=>YI,quotelessJson:()=>Hk,promise:()=>BI,preprocess:()=>VI,pipeline:()=>RI,ostring:()=>KI,optional:()=>HI,onumber:()=>FI,oboolean:()=>EI,objectUtil:()=>pY,object:()=>_I,number:()=>xH,nullable:()=>NI,null:()=>ok,never:()=>sk,nativeEnum:()=>LI,nan:()=>ck,map:()=>QI,makeIssue:()=>M9,literal:()=>DI,lazy:()=>jI,late:()=>dk,isValid:()=>X1,isDirty:()=>tY,isAsync:()=>JU,isAborted:()=>oY,intersection:()=>XI,instanceof:()=>nk,getParsedType:()=>k4,getErrorMap:()=>E9,function:()=>zI,enum:()=>OI,effect:()=>IH,discriminatedUnion:()=>UI,defaultErrorMap:()=>o2,datetimeRegex:()=>vH,date:()=>lk,custom:()=>hH,coerce:()=>MI,boolean:()=>uH,bigint:()=>ik,array:()=>$I,any:()=>tk,addIssueToContext:()=>n,ZodVoid:()=>UU,ZodUnknown:()=>j0,ZodUnion:()=>e2,ZodUndefined:()=>a2,ZodType:()=>f$,ZodTuple:()=>X4,ZodTransformer:()=>O6,ZodSymbol:()=>WU,ZodString:()=>k6,ZodSet:()=>Q1,ZodSchema:()=>f$,ZodRecord:()=>XU,ZodReadonly:()=>GJ,ZodPromise:()=>q1,ZodPipeline:()=>QU,ZodParsedType:()=>p,ZodOptional:()=>f6,ZodObject:()=>L_,ZodNumber:()=>D0,ZodNullable:()=>I4,ZodNull:()=>s2,ZodNever:()=>U4,ZodNativeEnum:()=>WJ,ZodNaN:()=>YU,ZodMap:()=>GU,ZodLiteral:()=>JJ,ZodLazy:()=>_J,ZodIssueCode:()=>T,ZodIntersection:()=>$J,ZodFunction:()=>p2,ZodFirstPartyTypeKind:()=>O$,ZodError:()=>_6,ZodEnum:()=>L0,ZodEffects:()=>O6,ZodDiscriminatedUnion:()=>A9,ZodDefault:()=>UJ,ZodDate:()=>G1,ZodCatch:()=>XJ,ZodBranded:()=>b9,ZodBoolean:()=>t2,ZodBigInt:()=>O0,ZodArray:()=>I6,ZodAny:()=>Y1,Schema:()=>f$,ParseStatus:()=>C_,OK:()=>u_,NEVER:()=>AI,INVALID:()=>q$,EMPTY_PATH:()=>Rk,DIRTY:()=>r2,BRAND:()=>uk});var h$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(h$||(h$={}));var pY;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(pY||(pY={}));var p=h$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),k4=($)=>{switch(typeof $){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN($)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":if(Array.isArray($))return p.array;if($===null)return p.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return p.promise;if(typeof Map<"u"&&$ instanceof Map)return p.map;if(typeof Set<"u"&&$ instanceof Set)return p.set;if(typeof Date<"u"&&$ instanceof Date)return p.date;return p.object;default:return p.unknown}},T=h$.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"]),Hk=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class _6 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}_6.create=($)=>{return new _6($)};var Nk=($,_)=>{let J;switch($.code){case T.invalid_type:if($.received===p.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case T.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,h$.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:J=`Unrecognized key(s) in object: ${h$.joinValues($.keys,", ")}`;break;case T.invalid_union:J="Invalid input";break;case T.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${h$.joinValues($.options)}`;break;case T.invalid_enum_value:J=`Invalid enum value. Expected ${h$.joinValues($.options)}, received '${$.received}'`;break;case T.invalid_arguments:J="Invalid function arguments";break;case T.invalid_return_type:J="Invalid function return type";break;case T.invalid_date:J="Invalid date";break;case T.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else h$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case T.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case T.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case T.custom:J="Invalid input";break;case T.invalid_intersection_types:J="Intersection results could not be merged";break;case T.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case T.not_finite:J="Number must be finite";break;default:J=_.defaultError,h$.assertNever($)}return{message:J}},o2=Nk,TH=o2;function Vk($){TH=$}function E9(){return TH}var M9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},Rk=[];function n($,_){let J=E9(),U=M9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===o2?void 0:o2].filter((W)=>!!W)});$.common.issues.push(U)}class C_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return q$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return C_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return q$;if(X.status==="aborted")return q$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var q$=Object.freeze({status:"aborted"}),r2=($)=>({status:"dirty",value:$}),u_=($)=>({status:"valid",value:$}),oY=($)=>$.status==="aborted",tY=($)=>$.status==="dirty",X1=($)=>$.status==="valid",JU=($)=>typeof Promise<"u"&&$ instanceof Promise,W$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(W$||(W$={}));class C6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var gH=($,_)=>{if(X1(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new _6($.common.issues);return this._error=J,this._error}}}};function A$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class f${get description(){return this._def.description}_getType($){return k4($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:k4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new C_,ctx:{common:$.parent.common,data:$.data,parsedType:k4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(JU(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:k4($)},U=this._parseSync({data:$,path:J.path,parent:J});return gH(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:k4($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return X1(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>X1(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:k4($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(JU(U)?U:Promise.resolve(U));return gH(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:T.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new O6({schema:this,typeName:O$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return f6.create(this,this._def)}nullable(){return I4.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return I6.create(this)}promise(){return q1.create(this,this._def)}or($){return e2.create([this,$],this._def)}and($){return $J.create(this,$,this._def)}transform($){return new O6({...A$(this._def),schema:this,typeName:O$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new UJ({...A$(this._def),innerType:this,defaultValue:_,typeName:O$.ZodDefault})}brand(){return new b9({typeName:O$.ZodBranded,type:this,...A$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new XJ({...A$(this._def),innerType:this,catchValue:_,typeName:O$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return QU.create(this,$)}readonly(){return GJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Kk=/^c[^\s-]{8,}$/i,Fk=/^[0-9a-z]+$/,Ek=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Mk=/^[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,Ak=/^[a-z0-9_-]{21}$/i,bk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wk=/^[-+]?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)?)??$/,gk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",iY,Ik=/^(?:(?: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])$/,fk=/^(?:(?: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])$/,Ck=/^(([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]))$/,Pk=/^(([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])$/,Tk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,SH="((\\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])))",Zk=new RegExp(`^${SH}$`);function ZH($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function vk($){return new RegExp(`^${ZH($)}$`)}function vH($){let _=`${SH}T${ZH($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function yk($,_){if((_==="v4"||!_)&&Ik.test($))return!0;if((_==="v6"||!_)&&Ck.test($))return!0;return!1}function hk($,_){if(!bk.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function mk($,_){if((_==="v4"||!_)&&fk.test($))return!0;if((_==="v6"||!_)&&Pk.test($))return!0;return!1}class k6 extends f${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==p.string){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_type,expected:p.string,received:W.parsedType}),q$}let J=new C_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),n(U,{code:T.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:T.invalid_string,...W$.errToObj(J)})}_addCheck($){return new k6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...W$.errToObj($)})}url($){return this._addCheck({kind:"url",...W$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...W$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...W$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...W$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...W$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...W$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...W$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...W$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...W$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...W$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...W$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...W$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...W$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...W$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...W$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...W$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...W$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...W$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...W$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...W$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...W$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...W$.errToObj(_)})}nonempty($){return this.min(1,W$.errToObj($))}trim(){return new k6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new k6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new k6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}k6.create=($)=>{return new k6({checks:[],typeName:O$.ZodString,coerce:$?.coerce??!1,...A$($)})};function xk($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class D0 extends f${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==p.number){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_type,expected:p.number,received:W.parsedType}),q$}let J=void 0,U=new C_;for(let W of this._def.checks)if(W.kind==="int"){if(!h$.isInteger($.data))J=this._getOrReturnCtx($,J),n(J,{code:T.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),n(J,{code:T.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(xk($.data,W.value)!==0)J=this._getOrReturnCtx($,J),n(J,{code:T.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),n(J,{code:T.not_finite,message:W.message}),U.dirty()}else h$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,W$.toString(_))}gt($,_){return this.setLimit("min",$,!1,W$.toString(_))}lte($,_){return this.setLimit("max",$,!0,W$.toString(_))}lt($,_){return this.setLimit("max",$,!1,W$.toString(_))}setLimit($,_,J,U){return new D0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:W$.toString(U)}]})}_addCheck($){return new D0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:W$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:W$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:W$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&h$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}D0.create=($)=>{return new D0({checks:[],typeName:O$.ZodNumber,coerce:$?.coerce||!1,...A$($)})};class O0 extends f${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==p.bigint)return this._getInvalidInput($);let J=void 0,U=new C_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),n(J,{code:T.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),n(J,{code:T.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else h$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return n(_,{code:T.invalid_type,expected:p.bigint,received:_.parsedType}),q$}gte($,_){return this.setLimit("min",$,!0,W$.toString(_))}gt($,_){return this.setLimit("min",$,!1,W$.toString(_))}lte($,_){return this.setLimit("max",$,!0,W$.toString(_))}lt($,_){return this.setLimit("max",$,!1,W$.toString(_))}setLimit($,_,J,U){return new O0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:W$.toString(U)}]})}_addCheck($){return new O0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:W$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}O0.create=($)=>{return new O0({checks:[],typeName:O$.ZodBigInt,coerce:$?.coerce??!1,...A$($)})};class t2 extends f${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==p.boolean){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.boolean,received:J.parsedType}),q$}return u_($.data)}}t2.create=($)=>{return new t2({typeName:O$.ZodBoolean,coerce:$?.coerce||!1,...A$($)})};class G1 extends f${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==p.date){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_type,expected:p.date,received:W.parsedType}),q$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return n(W,{code:T.invalid_date}),q$}let J=new C_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),n(U,{code:T.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else h$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new G1({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:W$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:W$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}G1.create=($)=>{return new G1({checks:[],coerce:$?.coerce||!1,typeName:O$.ZodDate,...A$($)})};class WU extends f${_parse($){if(this._getType($)!==p.symbol){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.symbol,received:J.parsedType}),q$}return u_($.data)}}WU.create=($)=>{return new WU({typeName:O$.ZodSymbol,...A$($)})};class a2 extends f${_parse($){if(this._getType($)!==p.undefined){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.undefined,received:J.parsedType}),q$}return u_($.data)}}a2.create=($)=>{return new a2({typeName:O$.ZodUndefined,...A$($)})};class s2 extends f${_parse($){if(this._getType($)!==p.null){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.null,received:J.parsedType}),q$}return u_($.data)}}s2.create=($)=>{return new s2({typeName:O$.ZodNull,...A$($)})};class Y1 extends f${constructor(){super(...arguments);this._any=!0}_parse($){return u_($.data)}}Y1.create=($)=>{return new Y1({typeName:O$.ZodAny,...A$($)})};class j0 extends f${constructor(){super(...arguments);this._unknown=!0}_parse($){return u_($.data)}}j0.create=($)=>{return new j0({typeName:O$.ZodUnknown,...A$($)})};class U4 extends f${_parse($){let _=this._getOrReturnCtx($);return n(_,{code:T.invalid_type,expected:p.never,received:_.parsedType}),q$}}U4.create=($)=>{return new U4({typeName:O$.ZodNever,...A$($)})};class UU extends f${_parse($){if(this._getType($)!==p.undefined){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.void,received:J.parsedType}),q$}return u_($.data)}}UU.create=($)=>{return new UU({typeName:O$.ZodVoid,...A$($)})};class I6 extends f${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==p.array)return n(_,{code:T.invalid_type,expected:p.array,received:_.parsedType}),q$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)n(_,{code:T.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new C6(_,X,_.path,G))})).then((X)=>{return C_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new C6(_,X,_.path,G))});return C_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new I6({...this._def,minLength:{value:$,message:W$.toString(_)}})}max($,_){return new I6({...this._def,maxLength:{value:$,message:W$.toString(_)}})}length($,_){return new I6({...this._def,exactLength:{value:$,message:W$.toString(_)}})}nonempty($){return this.min(1,$)}}I6.create=($,_)=>{return new I6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:O$.ZodArray,...A$(_)})};function l2($){if($ instanceof L_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=f6.create(l2(U))}return new L_({...$._def,shape:()=>_})}else if($ instanceof I6)return new I6({...$._def,type:l2($.element)});else if($ instanceof f6)return f6.create(l2($.unwrap()));else if($ instanceof I4)return I4.create(l2($.unwrap()));else if($ instanceof X4)return X4.create($.items.map((_)=>l2(_)));else return $}class L_ extends f${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=h$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==p.object){let Q=this._getOrReturnCtx($);return n(Q,{code:T.invalid_type,expected:p.object,received:Q.parsedType}),q$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof U4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new C6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof U4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)n(U,{code:T.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new C6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return C_.mergeObjectSync(J,Q)});else return C_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return W$.errToObj,new L_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:W$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new L_({...this._def,unknownKeys:"strip"})}passthrough(){return new L_({...this._def,unknownKeys:"passthrough"})}extend($){return new L_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new L_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:O$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new L_({...this._def,catchall:$})}pick($){let _={};for(let J of h$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new L_({...this._def,shape:()=>_})}omit($){let _={};for(let J of h$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new L_({...this._def,shape:()=>_})}deepPartial(){return l2(this)}partial($){let _={};for(let J of h$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new L_({...this._def,shape:()=>_})}required($){let _={};for(let J of h$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof f6)W=W._def.innerType;_[J]=W}return new L_({...this._def,shape:()=>_})}keyof(){return yH(h$.objectKeys(this.shape))}}L_.create=($,_)=>{return new L_({shape:()=>$,unknownKeys:"strip",catchall:U4.create(),typeName:O$.ZodObject,...A$(_)})};L_.strictCreate=($,_)=>{return new L_({shape:()=>$,unknownKeys:"strict",catchall:U4.create(),typeName:O$.ZodObject,...A$(_)})};L_.lazycreate=($,_)=>{return new L_({shape:$,unknownKeys:"strip",catchall:U4.create(),typeName:O$.ZodObject,...A$(_)})};class e2 extends f${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new _6(G.ctx.common.issues));return n(_,{code:T.invalid_union,unionErrors:X}),q$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new _6(Y));return n(_,{code:T.invalid_union,unionErrors:G}),q$}}get options(){return this._def.options}}e2.create=($,_)=>{return new e2({options:$,typeName:O$.ZodUnion,...A$(_)})};var g4=($)=>{if($ instanceof _J)return g4($.schema);else if($ instanceof O6)return g4($.innerType());else if($ instanceof JJ)return[$.value];else if($ instanceof L0)return $.options;else if($ instanceof WJ)return h$.objectValues($.enum);else if($ instanceof UJ)return g4($._def.innerType);else if($ instanceof a2)return[void 0];else if($ instanceof s2)return[null];else if($ instanceof f6)return[void 0,...g4($.unwrap())];else if($ instanceof I4)return[null,...g4($.unwrap())];else if($ instanceof b9)return g4($.unwrap());else if($ instanceof GJ)return g4($.unwrap());else if($ instanceof XJ)return g4($._def.innerType);else return[]};class A9 extends f${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.object)return n(_,{code:T.invalid_type,expected:p.object,received:_.parsedType}),q$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return n(_,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),q$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=g4(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new A9({typeName:O$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...A$(J)})}}function aY($,_){let J=k4($),U=k4(_);if($===_)return{valid:!0,data:$};else if(J===p.object&&U===p.object){let W=h$.objectKeys(_),X=h$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=aY($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===p.array&&U===p.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=aY(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===p.date&&U===p.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class $J extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(oY(W)||oY(X))return q$;let G=aY(W.value,X.value);if(!G.valid)return n(J,{code:T.invalid_intersection_types}),q$;if(tY(W)||tY(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}$J.create=($,_,J)=>{return new $J({left:$,right:_,typeName:O$.ZodIntersection,...A$(J)})};class X4 extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.array)return n(J,{code:T.invalid_type,expected:p.array,received:J.parsedType}),q$;if(J.data.lengththis._def.items.length)n(J,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new C6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return C_.mergeArray(_,X)});else return C_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new X4({...this._def,rest:$})}}X4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new X4({items:$,typeName:O$.ZodTuple,rest:null,...A$(_)})};class XU extends f${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.object)return n(J,{code:T.invalid_type,expected:p.object,received:J.parsedType}),q$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new C6(J,G,J.path,G)),value:X._parse(new C6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return C_.mergeObjectAsync(_,U);else return C_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof f$)return new XU({keyType:$,valueType:_,typeName:O$.ZodRecord,...A$(J)});return new XU({keyType:k6.create(),valueType:$,typeName:O$.ZodRecord,...A$(_)})}}class GU extends f${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.map)return n(J,{code:T.invalid_type,expected:p.map,received:J.parsedType}),q$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new C6(J,G,J.path,[Q,"key"])),value:W._parse(new C6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return q$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}GU.create=($,_,J)=>{return new GU({valueType:_,keyType:$,typeName:O$.ZodMap,...A$(J)})};class Q1 extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==p.set)return n(J,{code:T.invalid_type,expected:p.set,received:J.parsedType}),q$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)n(J,{code:T.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return q$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new C6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new Q1({...this._def,minSize:{value:$,message:W$.toString(_)}})}max($,_){return new Q1({...this._def,maxSize:{value:$,message:W$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}Q1.create=($,_)=>{return new Q1({valueType:$,minSize:null,maxSize:null,typeName:O$.ZodSet,...A$(_)})};class p2 extends f${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.function)return n(_,{code:T.invalid_type,expected:p.function,received:_.parsedType}),q$;function J(G,Y){return M9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,E9(),o2].filter((Q)=>!!Q),issueData:{code:T.invalid_arguments,argumentsError:Y}})}function U(G,Y){return M9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,E9(),o2].filter((Q)=>!!Q),issueData:{code:T.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof q1){let G=this;return u_(async function(...Y){let Q=new _6([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return u_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new _6([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new _6([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new p2({...this._def,args:X4.create($).rest(j0.create())})}returns($){return new p2({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new p2({args:$?$:X4.create([]).rest(j0.create()),returns:_||j0.create(),typeName:O$.ZodFunction,...A$(J)})}}class _J extends f${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}_J.create=($,_)=>{return new _J({getter:$,typeName:O$.ZodLazy,...A$(_)})};class JJ extends f${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return n(_,{received:_.data,code:T.invalid_literal,expected:this._def.value}),q$}return{status:"valid",value:$.data}}get value(){return this._def.value}}JJ.create=($,_)=>{return new JJ({value:$,typeName:O$.ZodLiteral,...A$(_)})};function yH($,_){return new L0({values:$,typeName:O$.ZodEnum,...A$(_)})}class L0 extends f${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return n(_,{expected:h$.joinValues(J),received:_.parsedType,code:T.invalid_type}),q$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return n(_,{received:_.data,code:T.invalid_enum_value,options:J}),q$}return u_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return L0.create($,{...this._def,..._})}exclude($,_=this._def){return L0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}L0.create=yH;class WJ extends f${_parse($){let _=h$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==p.string&&J.parsedType!==p.number){let U=h$.objectValues(_);return n(J,{expected:h$.joinValues(U),received:J.parsedType,code:T.invalid_type}),q$}if(!this._cache)this._cache=new Set(h$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=h$.objectValues(_);return n(J,{received:J.data,code:T.invalid_enum_value,options:U}),q$}return u_($.data)}get enum(){return this._def.values}}WJ.create=($,_)=>{return new WJ({values:$,typeName:O$.ZodNativeEnum,...A$(_)})};class q1 extends f${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==p.promise&&_.common.async===!1)return n(_,{code:T.invalid_type,expected:p.promise,received:_.parsedType}),q$;let J=_.parsedType===p.promise?_.data:Promise.resolve(_.data);return u_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}q1.create=($,_)=>{return new q1({type:$,typeName:O$.ZodPromise,...A$(_)})};class O6 extends f${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(n(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return q$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return q$;if(Y.status==="dirty")return r2(Y.value);if(_.value==="dirty")return r2(Y.value);return Y});else{if(_.value==="aborted")return q$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return q$;if(G.status==="dirty")return r2(G.value);if(_.value==="dirty")return r2(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return q$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return q$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!X1(X))return q$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!X1(X))return q$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});h$.assertNever(U)}}O6.create=($,_,J)=>{return new O6({schema:$,typeName:O$.ZodEffects,effect:_,...A$(J)})};O6.createWithPreprocess=($,_,J)=>{return new O6({schema:_,effect:{type:"preprocess",transform:$},typeName:O$.ZodEffects,...A$(J)})};class f6 extends f${_parse($){if(this._getType($)===p.undefined)return u_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}f6.create=($,_)=>{return new f6({innerType:$,typeName:O$.ZodOptional,...A$(_)})};class I4 extends f${_parse($){if(this._getType($)===p.null)return u_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}I4.create=($,_)=>{return new I4({innerType:$,typeName:O$.ZodNullable,...A$(_)})};class UJ extends f${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===p.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}UJ.create=($,_)=>{return new UJ({innerType:$,typeName:O$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...A$(_)})};class XJ extends f${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(JU(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new _6(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new _6(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}XJ.create=($,_)=>{return new XJ({innerType:$,typeName:O$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...A$(_)})};class YU extends f${_parse($){if(this._getType($)!==p.nan){let J=this._getOrReturnCtx($);return n(J,{code:T.invalid_type,expected:p.nan,received:J.parsedType}),q$}return{status:"valid",value:$.data}}}YU.create=($)=>{return new YU({typeName:O$.ZodNaN,...A$($)})};var uk=Symbol("zod_brand");class b9 extends f${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class QU extends f${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return q$;if(W.status==="dirty")return _.dirty(),r2(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return q$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new QU({in:$,out:_,typeName:O$.ZodPipeline})}}class GJ extends f${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(X1(U))U.value=Object.freeze(U.value);return U};return JU(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}GJ.create=($,_)=>{return new GJ({innerType:$,typeName:O$.ZodReadonly,...A$(_)})};function kH($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function hH($,_={},J){if($)return Y1.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=kH(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=kH(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return Y1.create()}var dk={object:L_.lazycreate},O$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(O$||(O$={}));var nk=($,_={message:`Input not instance of ${$.name}`})=>hH((J)=>J instanceof $,_),mH=k6.create,xH=D0.create,ck=YU.create,ik=O0.create,uH=t2.create,lk=G1.create,rk=WU.create,pk=a2.create,ok=s2.create,tk=Y1.create,ak=j0.create,sk=U4.create,ek=UU.create,$I=I6.create,_I=L_.create,JI=L_.strictCreate,WI=e2.create,UI=A9.create,XI=$J.create,GI=X4.create,YI=XU.create,QI=GU.create,qI=Q1.create,zI=p2.create,jI=_J.create,DI=JJ.create,OI=L0.create,LI=WJ.create,BI=q1.create,IH=O6.create,HI=f6.create,NI=I4.create,VI=O6.createWithPreprocess,RI=QU.create,KI=()=>mH().optional(),FI=()=>xH().optional(),EI=()=>uH().optional(),MI={string:($)=>k6.create({...$,coerce:!0}),number:($)=>D0.create({...$,coerce:!0}),boolean:($)=>t2.create({...$,coerce:!0}),bigint:($)=>O0.create({...$,coerce:!0}),date:($)=>G1.create({...$,coerce:!0})},AI=q$;var J$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},dH=j.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),J6=j.string().datetime(),N$=j.string().trim().min(1),f4=N$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),nH=j.string().regex(/^[a-fA-F0-9]{64}$/),cH=j.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),C4=j.record(j.unknown()),qJ=j.array(j.string().min(1)).default([]),z1=J6.nullable().optional(),bI=new Set(["succeeded","failed","cancelled","blocked","skipped"]),D1=j.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function o$($){return j.object({schema:j.literal($),id:j.string().min(1),createdAt:J6,updatedAt:z1,metadata:C4.optional()}).strict()}var Ot=j.object({schema:dH,id:j.string().min(1),createdAt:J6,updatedAt:z1,metadata:C4.optional()}).strict(),iH=j.enum(["agent","human","service","model","workflow","system"]),wI=o$(J$.actorRef).extend({kind:iH,name:j.string().min(1).optional(),provider:j.string().min(1).optional(),accountId:j.string().min(1).optional(),machineId:j.string().min(1).optional(),capabilities:j.array(j.string().min(1)).default([])}).strict(),G4=j.object({kind:iH,id:j.string().min(1),name:j.string().min(1).optional(),provider:j.string().min(1).optional(),accountId:j.string().min(1).optional(),machineId:j.string().min(1).optional()}).strict(),lH=j.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),gI=o$(J$.resourceRef).extend({kind:lH,name:j.string().min(1).optional(),uri:f4.optional(),externalId:N$.optional(),sourcePackage:N$.optional(),tags:qJ}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:j.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),I$=j.object({kind:lH,id:j.string().min(1),name:j.string().min(1).optional(),uri:f4.optional(),externalId:N$.optional(),sourcePackage:N$.optional(),tags:qJ}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:j.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),sY=j.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),kI=j.enum(["none","partial","full","unknown"]),II=o$(J$.evidenceRef).extend({kind:sY,uri:f4,sha256:nH.optional(),summary:j.string().min(1).optional(),contentType:j.string().min(1).optional(),sizeBytes:j.number().int().nonnegative().optional(),redaction:kI.default("unknown"),producer:G4.optional(),resourceRefs:j.array(I$).default([]),tags:qJ}).strict(),Y_=j.object({id:j.string().min(1),kind:sY.optional(),uri:f4.optional(),sha256:nH.optional(),summary:j.string().min(1).optional()}).strict(),qU=o$(J$.costEstimate).extend({currency:j.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:j.number().int().nonnegative(),provider:j.string().min(1).optional(),model:j.string().min(1).optional(),accountId:j.string().min(1).optional(),promptTokens:j.number().int().nonnegative().optional(),completionTokens:j.number().int().nonnegative().optional(),totalTokens:j.number().int().nonnegative().optional(),basis:j.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:j.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),fI=j.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),rH=o$(J$.decisionEnvelope).extend({decisionType:j.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:fI,actor:G4.optional(),traceId:j.string().min(1).optional(),inputHash:cH.optional(),policyBundleId:j.string().min(1).optional(),selected:j.array(I$).default([]),skipped:j.array(I$).default([]),reason:j.string().min(1),obligations:j.array(j.string().min(1)).default([]),redactions:j.array(j.string().min(1)).default([]),costEstimate:qU.optional(),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),CI=o$(J$.capabilityCard).extend({kind:j.enum(["model","tool","machine","agent","lane","connector","service"]),name:j.string().min(1),version:j.string().min(1).optional(),status:j.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:j.array(j.string().min(1)).default([]),limitations:j.array(j.string().min(1)).default([]),riskLevel:j.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:qU.optional(),evidenceRefs:j.array(Y_).default([])}).strict(),YJ=j.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),PI=j.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),TI=j.object({refName:N$,requiredForModes:j.array(YJ).min(1),allowedSecretInputs:j.array(j.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:N$,revocationCheck:j.boolean().default(!0)}).strict(),SI=j.object({operation:N$,supportedModes:j.array(YJ).min(1),sideEffectClass:PI,requiresApproval:j.boolean().default(!1),requiresIdempotencyKey:j.boolean().default(!1),requiresSandboxEvidence:j.boolean().default(!1),requiresRollbackOrRevocation:j.boolean().default(!1),rollbackOrRevocation:N$.optional(),noSideEffectSmoke:N$.optional(),reconciliation:N$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),ZI=j.object({providerId:N$,appId:N$,adapterId:N$,ownerPackage:N$,modes:j.array(YJ).min(1),defaultMode:YJ,credentialRequirements:j.array(TI).default([]),operations:j.array(SI).min(1),rateLimitPosture:N$,costPosture:N$.optional(),auditEvents:j.array(N$).default([]),redactionRules:j.array(N$).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:j.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),vI=j.object({appId:N$,repo:N$,priority:j.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:j.array(N$).min(1),firstOperations:j.array(N$).min(1),blockedUntil:j.array(N$).default([])}).strict(),yI=o$(J$.providerLiveModeStandard).extend({name:N$,version:N$,modes:j.array(YJ).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:j.array(N$).min(1),liveMutationGate:j.object({requiredMode:j.literal("live_mutating"),requiredChecks:j.array(N$).min(1),forbiddenBypassSignals:j.array(N$).min(1),disabledLiveSmoke:N$}).strict(),noSideEffectSmoke:j.object({requiredForModes:j.array(YJ).min(1),commandEvidence:j.array(N$).min(1),secretOutputScan:j.boolean().default(!0)}).strict(),credentialPolicy:j.object({acceptedInputs:j.array(j.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:j.literal(!1),missingCredentialBehavior:j.literal("fail_closed"),revocationCheckRequired:j.boolean().default(!0)}).strict(),operationCards:j.array(ZI).min(1),firstAdoptionTargets:j.array(vI).min(1),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:j.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),hI=j.object({id:j.string().min(1),title:j.string().min(1).optional(),summary:j.string().min(1),text:j.string().optional(),tokens:j.number().int().nonnegative().optional(),source:Y_,resourceRefs:j.array(I$).default([])}).strict(),pH=o$(J$.contextPack).extend({objective:j.string().min(1),budget:j.object({maxTokens:j.number().int().positive().optional(),maxBytes:j.number().int().positive().optional()}).strict().optional(),items:j.array(hI).default([]),citations:j.array(Y_).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),permissions:j.array(j.string().min(1)).default([]),redactions:j.array(j.string().min(1)).default([]),conflicts:j.array(j.string().min(1)).default([]),uncertainty:j.string().min(1).optional()}).strict(),g6=N$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),j1=j.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),mI=j.enum(["public","internal","private","sensitive"]),xI=j.enum(["draft","active","paused","archived"]),eY=j.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),oH=o$(J$.integrationRef).extend({kind:eY,name:j.string().min(1),projectId:j1.optional(),sourcePackage:N$.optional(),externalId:N$.optional(),uri:f4.optional(),enabled:j.boolean().default(!0),readOnly:j.boolean().default(!0),capabilities:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:I$.optional(),evidenceRefs:j.array(Y_).default([]),config:C4.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:j.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),uI=j.object({schemaRoot:g6.default(".hasna/project"),dashboardManifest:g6.default(".hasna/project/dashboard.render.json"),snapshotsDir:g6.default(".hasna/project/snapshots"),documentsDir:g6.default("documents"),reportsDir:g6.default("reports"),evidenceDir:g6.default(".hasna/project/evidence"),privateDir:g6.default(".hasna/project/private")}).strict(),dI=o$(J$.projectManifest).extend({projectId:j1,slug:j1,name:j.string().min(1),summary:j.string().min(1).optional(),status:xI.default("active"),classification:mI.default("private"),owner:G4.optional(),layout:uI.default({}),integrations:j.array(oH).default([]),renderManifests:j.array(I$).default([]),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),tags:qJ}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:j.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:j.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:j.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),nI=j.enum(["local","package","provider","url"]),$Q=j.object({id:j.string().min(1),kind:nI,specifier:j.string().min(1),path:g6.optional(),packageName:j.string().min(1).optional(),uri:f4.optional(),provider:eY.optional(),schemaId:dH.optional(),integrity:cH.optional(),resourceRef:I$.optional(),optional:j.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:j.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:j.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:j.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:j.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),cI=j.enum(["dashboard","canvas","panel","report","document","custom"]),iI=j.object({id:j.string().min(1),title:j.string().min(1),kind:cI,default:j.boolean().default(!1),entry:g6.optional(),imports:j.array($Q).default([]),panelRefs:j.array(I$).default([]),dataRefs:j.array(I$).default([]),layout:C4.optional()}).strict(),lI=o$(J$.renderManifest).extend({projectId:j1,name:j.string().min(1),version:j.string().min(1),manifestPath:g6.default(".hasna/project/dashboard.render.json"),renderer:j.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:j.array(iI).min(1),imports:j.array($Q).default([]),theme:C4.optional(),compatibility:j.object({minProjectsVersion:j.string().min(1).optional(),minContractsVersion:j.string().min(1).optional()}).strict().optional(),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:j.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),rI=j.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),pI=j.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),oI=j.object({id:j.string().min(1),label:j.string().min(1),value:j.union([j.string(),j.number(),j.boolean()]),unit:j.string().min(1).optional(),status:j.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:j.array(I$).default([])}).strict(),tI=j.object({id:j.string().min(1),title:j.string().min(1),summary:j.string().min(1).optional(),status:j.string().min(1).optional(),priority:j.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:J6.optional(),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),metadata:C4.optional()}).strict(),aI=j.object({renderer:j.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:j.string().min(1).optional(),entry:g6.optional(),imports:j.array($Q).default([]),spec:C4.default({})}).strict(),tH=o$(J$.projectPanel).extend({projectId:j1,provider:j.object({kind:eY,id:j.string().min(1),name:j.string().min(1).optional(),sourcePackage:N$.optional(),externalId:N$.optional()}).strict(),kind:pI,title:j.string().min(1),summary:j.string().min(1).optional(),state:rI.default("ready"),stateReason:j.string().min(1).optional(),generatedAt:J6,freshness:j.enum(["fresh","stale","unknown"]).default("unknown"),metrics:j.array(oI).default([]),items:j.array(tI).default([]),actions:j.array(I$).default([]),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),renderFragment:aI.optional(),warnings:j.array(j.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:j.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:j.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:j.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),sI=o$(J$.projectSnapshot).extend({projectId:j1,generatedAt:J6,status:D1.default("unknown"),manifestRef:I$,renderManifestRef:I$.optional(),panels:j.array(tH).default([]),contextPacks:j.array(pH).default([]),proofBundleRefs:j.array(I$).default([]),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),warnings:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:j.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:j.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),aH=j.object({id:j.string().min(1),kind:j.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:j.boolean().default(!0),command:j.string().min(1).optional(),expected:j.string().min(1).optional(),timeoutMs:j.number().int().positive().optional(),resourceRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:j.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),eI=o$(J$.validationPlan).extend({objective:j.string().min(1),subject:I$.optional(),checks:j.array(aH).min(1),verifier:G4.optional(),requiredEvidenceKinds:j.array(sY).default([])}).strict(),$f=j.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),_f=j.enum(["draft","active","deprecated","archived"]),Jf=j.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Wf=j.object({key:j.string().regex(/^[A-Z][A-Z0-9_]*$/),description:j.string().min(1),required:j.boolean().default(!1),["secret"]:j.boolean().default(!1),group:j.string().min(1).optional(),default:j.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Uf=j.object({name:j.string().min(1),command:j.string().min(1),description:j.string().min(1).optional(),required:j.boolean().default(!1)}).strict(),Xf=j.object({packageManager:j.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:j.array(j.string().min(1)).default([]),requiredFiles:j.array(j.string().min(1)).default([]),requiredDirectories:j.array(j.string().min(1)).default([]),optionalDirectories:j.array(j.string().min(1)).default([])}).strict(),Gf=o$(J$.scaffoldManifest).extend({name:j.string().min(1),version:j.string().min(1),summary:j.string().min(1),type:$f,status:_f.default("draft"),capabilities:j.array(Jf).default([]),techStack:j.array(j.string().min(1)).default([]),tags:qJ,source:I$.optional(),output:Xf,env:j.array(Wf).default([]),scripts:j.array(Uf).default([]),validationChecks:j.array(aH).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:j.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),Yf=j.enum(["installed","failed","cancelled","partial","unknown"]),Qf=o$(J$.scaffoldInstallRecord).extend({scaffoldId:j.string().min(1),scaffoldVersion:j.string().min(1).optional(),manifestRef:I$.optional(),target:I$,status:Yf,installedAt:J6.optional(),installer:G4.optional(),packageManager:j.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:C4.optional(),generatedFiles:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),proofBundleRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:j.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),QJ=j.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),_Q=j.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),sH=j.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),qf=j.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),zf=N$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),jf=j.enum(["active","stub","deprecated","archived"]),Df=j.enum(["stable","beta","canary","internal"]),Of=j.object({transport:j.enum(["http","stdio"]).default("http"),bin:j.string().min(1).optional(),url:f4.optional()}).strict(),Lf=j.object({healthPath:j.string().min(1).default("/health"),port:j.number().int().positive().optional(),baseUrl:f4.optional()}).strict(),Bf=j.object({bins:j.array(j.string().min(1)).default([]),mcp:Of.optional(),http:Lf.optional()}).strict(),Hf=o$(J$.app).extend({appId:QJ,npmName:_Q,repoFolder:QJ,githubUrl:zf,projectSlug:j1,surfaces:Bf.default({}),lifecycle:jf,releaseChannel:Df.default("stable"),summary:j.string().min(1).optional(),tags:qJ}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:j.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),Nf=j.enum(["skill","ci","backfilled"]),Vf=o$(J$.release).extend({appId:QJ,package:_Q,version:sH,gitSha:qf,publishedAt:J6,publishPath:Nf,changelogRef:I$.optional(),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Rf=j.enum(["install","update","rollback","freeze-blocked"]),Kf=j.object({cliVersion:j.string().min(1).optional(),mcpHealth:j.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),Ff=o$(J$.rolloutRecord).extend({appId:QJ,package:_Q,version:sH,machine:N$,action:Rf,result:D1,verifiedBy:Kf.optional(),at:J6,evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:j.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),Ef=j.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),Mf=j.enum(["pending","queued","sent","failed","skipped","suppressed"]),Af=j.object({channel:Ef,status:Mf,deliveredAt:J6.optional(),detail:j.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:j.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),bf=o$(J$.announcement).extend({campaignId:N$,appId:QJ.optional(),releaseRef:I$.optional(),channels:j.array(Af).min(1),audienceRef:I$,sentAt:J6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:j.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:j.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),wf=j.enum(["tag","attribute","group"]),gf=j.enum(["eq","neq","in","not_in","exists","not_exists"]),fH=j.union([j.string(),j.number(),j.boolean()]),kf=j.object({kind:wf,key:j.string().min(1).optional(),op:gf.default("eq"),value:fH.optional(),values:j.array(fH).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:j.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:j.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),If=j.object({match:j.enum(["all","any"]).default("all"),predicates:j.array(kf).min(1)}).strict(),ff=j.enum(["opt_in","opt_out","transactional","none"]),Cf=o$(J$.audience).extend({audienceId:QJ,name:N$,definition:If,consentPolicy:ff,suppressionSyncedAt:z1}).strict(),lY=["@hasna/cloud","open-cloud"],Pf=j.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),Tf=j.object({id:j.string().min(1),provider:Pf,kind:j.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:j.string().min(1),region:j.string().min(1).optional(),accountId:j.string().min(1).optional(),uri:f4.optional(),machineScoped:j.boolean().default(!1)}).strict(),eH=o$(J$.appCloudManifest).extend({packageName:j.string().min(1),packageVersion:j.string().min(1).optional(),appId:j.string().min(1),repository:I$.optional(),storageMode:j.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:j.enum(["none","app_owned","external_service","local_cache"]),cloudResources:j.array(Tf).default([]),localCache:j.object({path:j.string().min(1).optional(),pullMode:j.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:j.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:j.array(j.string().min(1)).default([...lY]),dependencies:j.array(j.string().min(1)).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...lY,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:j.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of lY)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:j.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:j.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:j.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:j.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:j.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:j.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:j.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),$N=j.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),Sf=j.enum(["low","medium","high","critical"]),_N=j.object({id:j.string().min(1),kind:$N,severity:Sf,path:j.string().min(1).optional(),packageName:j.string().min(1).optional(),pattern:j.string().min(1),message:j.string().min(1),evidenceRefs:j.array(Y_).default([])}).strict(),Zf=j.object({id:j.string().min(1),kind:$N,status:D1,target:j.string().min(1),command:j.string().min(1).optional(),evidenceRefs:j.array(Y_).default([]),findings:j.array(_N).default([])}).strict(),vf=o$(J$.noCloudEvidencePack).extend({subject:I$,packageName:j.string().min(1).optional(),packageVersion:j.string().min(1).optional(),generatedBy:G4.optional(),scanMode:j.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:D1,verdict:j.enum(["passed","failed","warning","not_run"]),appCloudManifest:eH.optional(),checks:j.array(Zf).min(1),findings:j.array(_N).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:j.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),yf=j.object({checkId:j.string().min(1),status:D1,summary:j.string().min(1).optional(),startedAt:z1,finishedAt:z1,evidenceRefs:j.array(Y_).default([])}).strict(),hf=o$(J$.proofBundle).extend({subject:I$,validationPlanRef:I$.optional(),status:D1,verdict:j.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:j.array(yf).default([]),verifier:G4.optional(),evidenceRefs:j.array(Y_).default([]),residualRisks:j.array(j.string().min(1)).default([]),freshness:j.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:j.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:j.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),mf=o$(J$.workRun).extend({objective:j.string().min(1),status:D1,actor:G4,traceId:j.string().min(1).optional(),startedAt:z1,finishedAt:z1,constraints:j.array(j.string().min(1)).default([]),resourceRefs:j.array(I$).default([]),decisions:j.array(rH).default([]),costEstimates:j.array(qU).default([]),evidenceRefs:j.array(Y_).default([]),validationPlanRefs:j.array(I$).default([]),proofBundleRefs:j.array(I$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:j.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),xf=j.object({id:j.string().min(1),at:J6,kind:j.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:j.string().min(1),resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([]),costEstimate:qU.optional()}).strict(),uf=o$(J$.agentTrajectory).extend({actor:G4,workRunRef:I$.optional(),events:j.array(xf).default([]),outcome:j.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:I$.optional()}).strict(),df="v1",nf=j.enum(["library","cli-with-store","service","saas"]),cf=["local","self-hosted","cloud"],JN=j.enum(cf),lf=j.enum(["supported","deferred","unsupported"]),rf=j.enum(["none","local-only","api-key","session","service-token","custom"]),rY=j.object({method:j.enum(["GET","POST","PUT","PATCH","DELETE"]),path:j.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:j.boolean().default(!1),description:j.string().min(1).optional()}).strict(),pf=j.object({id:j.string().min(1),kind:j.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:j.boolean().default(!0),command:j.string().min(1).optional(),evidenceRef:Y_.optional(),status:j.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:j.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:j.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),of=j.object({name:j.string().min(1),status:lf,bin:j.string().min(1).optional(),mcpBin:j.string().min(1).optional(),authMode:rf,deploymentModes:j.array(JN).min(1),health:rY.optional(),readiness:rY.optional(),version:rY.optional(),apiBasePath:j.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:j.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:j.string().min(1).optional(),readinessGates:j.array(pf).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:j.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:j.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:j.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:j.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:j.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),tf=["local","cloud"],WN=j.enum(tf);var af=j.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),sf=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function ef($){return sf.map((_)=>`${$}${_}`)}function CH($){return`hasna/oss/${$}/database-url`}var $C=j.object({mode:WN,envPrefix:j.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:j.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:j.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:j.string().min(1).optional()}).strict(),_C=j.object({$schema:j.string().min(1).optional(),schema:j.literal(J$.serviceContract),name:af,class:nf,contractVersion:j.literal(df),kitVersion:j.string().min(1),description:j.string().min(1).optional(),bins:j.array(j.string().min(1)).default([]),storage:$C.optional(),deploymentModes:j.array(JN).default(["local"]),serviceSurfaces:j.array(of).default([]),metadata:C4.optional()}).strict().superRefine(($,_)=>{let J=new Set(ef($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:j.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:j.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:j.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==CH($.name))_.addIssue({code:j.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${CH($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:j.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:j.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:j.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:j.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:j.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:j.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:j.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),Lt=j.object({status:j.enum(["ok","degraded","unavailable"]),version:j.string().min(1),mode:WN}).strict(),Bt=j.object({ready:j.boolean(),reason:j.string().min(1).optional()}).strict(),Ht=j.object({version:j.string().min(1)}).strict(),JC=j.enum(["info","notice","breaking","critical"]),WC=j.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),UC=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],XC=j.enum(UC);var GC=j.enum(["fleet","package","machine"]),UN=o$(J$.commsEventEnvelope).extend({type:WC,severity:JC,scope:GC,summary:j.string().min(1).optional(),source:G4.optional(),affected_packages:j.array(N$).default([]),affected_machines:j.array(N$).default([]),action_required:j.boolean().default(!1),ack_by:J6.optional(),dedupe_key:N$,resourceRefs:j.array(I$).default([]),evidenceRefs:j.array(Y_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:j.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:j.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:j.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),YC=j.enum(["fleet","package","product","loop-lane","initiative","personal"]),QC=j.enum(["quiet","work","firehose"]),qC=N$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),zC=o$(J$.commsChannelMetadata).extend({class:YC,noise:QC.optional(),owner:N$.optional(),until:qC.optional(),successor:N$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:j.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:j.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),PH={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},jC=o$(J$.commsMessageMetadata).extend({tag:XC,envelope:UN}).strict().superRefine(($,_)=>{let J=PH[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:j.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:j.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(PH))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:j.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var Nt={[J$.actorRef]:wI,[J$.resourceRef]:gI,[J$.evidenceRef]:II,[J$.workRun]:mf,[J$.decisionEnvelope]:rH,[J$.costEstimate]:qU,[J$.capabilityCard]:CI,[J$.providerLiveModeStandard]:yI,[J$.contextPack]:pH,[J$.integrationRef]:oH,[J$.projectManifest]:dI,[J$.projectPanel]:tH,[J$.projectSnapshot]:sI,[J$.renderManifest]:lI,[J$.agentTrajectory]:uf,[J$.validationPlan]:eI,[J$.proofBundle]:hf,[J$.scaffoldManifest]:Gf,[J$.scaffoldInstallRecord]:Qf,[J$.appCloudManifest]:eH,[J$.noCloudEvidencePack]:vf,[J$.serviceContract]:_C,[J$.commsEventEnvelope]:UN,[J$.commsChannelMetadata]:zC,[J$.commsMessageMetadata]:jC,[J$.app]:Hf,[J$.release]:Vf,[J$.rolloutRecord]:Ff,[J$.announcement]:bf,[J$.audience]:Cf};function DC($){return $.toUpperCase().replace(/-/g,"_")}function XN($){let _=DC($);return{modeKeys:[`HASNA_${_}_STORAGE_MODE`,`HASNA_${_}_MODE`,`${_}_STORAGE_MODE`,`${_}_MODE`],apiUrlKeys:[`HASNA_${_}_API_URL`,`${_}_API_URL`],apiKeyKeys:[`HASNA_${_}_API_KEY`,`${_}_API_KEY`]}}var OC=Object.defineProperty,LC=($)=>$;function BC($,_){this[$]=LC.bind(null,_)}var HC=($,_)=>{for(var J in _)OC($,J,{get:_[J],enumerable:!0,configurable:!0,set:BC.bind(_,J)})},D={};HC(D,{void:()=>$P,util:()=>m$,unknown:()=>sC,union:()=>UP,undefined:()=>oC,tuple:()=>YP,transformer:()=>QN,symbol:()=>pC,string:()=>VN,strictObject:()=>WP,setErrorMap:()=>RC,set:()=>zP,record:()=>QP,quotelessJson:()=>NC,promise:()=>HP,preprocess:()=>RP,pipeline:()=>KP,ostring:()=>FP,optional:()=>NP,onumber:()=>EP,oboolean:()=>MP,objectUtil:()=>XQ,object:()=>JP,number:()=>RN,nullable:()=>VP,null:()=>tC,never:()=>eC,nativeEnum:()=>BP,nan:()=>iC,map:()=>qP,makeIssue:()=>g9,literal:()=>OP,lazy:()=>DP,late:()=>nC,isValid:()=>O1,isDirty:()=>YQ,isAsync:()=>zU,isAborted:()=>GQ,intersection:()=>GP,instanceof:()=>cC,getParsedType:()=>T4,getErrorMap:()=>w9,function:()=>jP,enum:()=>LP,effect:()=>QN,discriminatedUnion:()=>XP,defaultErrorMap:()=>OJ,datetimeRegex:()=>BN,date:()=>rC,custom:()=>NN,coerce:()=>AP,boolean:()=>KN,bigint:()=>lC,array:()=>_P,any:()=>aC,addIssueToContext:()=>c,ZodVoid:()=>DU,ZodUnknown:()=>B0,ZodUnion:()=>NJ,ZodUndefined:()=>BJ,ZodType:()=>P$,ZodTuple:()=>Q4,ZodTransformer:()=>L6,ZodSymbol:()=>jU,ZodString:()=>T6,ZodSet:()=>H1,ZodSchema:()=>P$,ZodRecord:()=>OU,ZodReadonly:()=>AJ,ZodPromise:()=>N1,ZodPipeline:()=>HU,ZodParsedType:()=>o,ZodOptional:()=>Z6,ZodObject:()=>B_,ZodNumber:()=>H0,ZodNullable:()=>S4,ZodNull:()=>HJ,ZodNever:()=>Y4,ZodNativeEnum:()=>FJ,ZodNaN:()=>BU,ZodMap:()=>LU,ZodLiteral:()=>KJ,ZodLazy:()=>RJ,ZodIssueCode:()=>S,ZodIntersection:()=>VJ,ZodFunction:()=>DJ,ZodFirstPartyTypeKind:()=>L$,ZodError:()=>W6,ZodEnum:()=>V0,ZodEffects:()=>L6,ZodDiscriminatedUnion:()=>k9,ZodDefault:()=>EJ,ZodDate:()=>L1,ZodCatch:()=>MJ,ZodBranded:()=>I9,ZodBoolean:()=>LJ,ZodBigInt:()=>N0,ZodArray:()=>S6,ZodAny:()=>B1,Schema:()=>P$,ParseStatus:()=>P_,OK:()=>d_,NEVER:()=>bP,INVALID:()=>z$,EMPTY_PATH:()=>KC,DIRTY:()=>jJ,BRAND:()=>dC});var m$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(m$||(m$={}));var XQ;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(XQ||(XQ={}));var o=m$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T4=($)=>{switch(typeof $){case"undefined":return o.undefined;case"string":return o.string;case"number":return Number.isNaN($)?o.nan:o.number;case"boolean":return o.boolean;case"function":return o.function;case"bigint":return o.bigint;case"symbol":return o.symbol;case"object":if(Array.isArray($))return o.array;if($===null)return o.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return o.promise;if(typeof Map<"u"&&$ instanceof Map)return o.map;if(typeof Set<"u"&&$ instanceof Set)return o.set;if(typeof Date<"u"&&$ instanceof Date)return o.date;return o.object;default:return o.unknown}},S=m$.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"]),NC=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class W6 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}W6.create=($)=>{return new W6($)};var VC=($,_)=>{let J;switch($.code){case S.invalid_type:if($.received===o.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case S.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,m$.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:J=`Unrecognized key(s) in object: ${m$.joinValues($.keys,", ")}`;break;case S.invalid_union:J="Invalid input";break;case S.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${m$.joinValues($.options)}`;break;case S.invalid_enum_value:J=`Invalid enum value. Expected ${m$.joinValues($.options)}, received '${$.received}'`;break;case S.invalid_arguments:J="Invalid function arguments";break;case S.invalid_return_type:J="Invalid function return type";break;case S.invalid_date:J="Invalid date";break;case S.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else m$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case S.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case S.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case S.custom:J="Invalid input";break;case S.invalid_intersection_types:J="Intersection results could not be merged";break;case S.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case S.not_finite:J="Number must be finite";break;default:J=_.defaultError,m$.assertNever($)}return{message:J}},OJ=VC,DN=OJ;function RC($){DN=$}function w9(){return DN}var g9=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},KC=[];function c($,_){let J=w9(),U=g9({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===OJ?void 0:OJ].filter((W)=>!!W)});$.common.issues.push(U)}class P_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return z$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return P_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return z$;if(X.status==="aborted")return z$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var z$=Object.freeze({status:"aborted"}),jJ=($)=>({status:"dirty",value:$}),d_=($)=>({status:"valid",value:$}),GQ=($)=>$.status==="aborted",YQ=($)=>$.status==="dirty",O1=($)=>$.status==="valid",zU=($)=>typeof Promise<"u"&&$ instanceof Promise,X$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(X$||(X$={}));class v6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var GN=($,_)=>{if(O1(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new W6($.common.issues);return this._error=J,this._error}}}};function b$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class P${get description(){return this._def.description}_getType($){return T4($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:T4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new P_,ctx:{common:$.parent.common,data:$.data,parsedType:T4($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(zU(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T4($)},U=this._parseSync({data:$,path:J.path,parent:J});return GN(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T4($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return O1(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>O1(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T4($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(zU(U)?U:Promise.resolve(U));return GN(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:S.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new L6({schema:this,typeName:L$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return Z6.create(this,this._def)}nullable(){return S4.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return S6.create(this)}promise(){return N1.create(this,this._def)}or($){return NJ.create([this,$],this._def)}and($){return VJ.create(this,$,this._def)}transform($){return new L6({...b$(this._def),schema:this,typeName:L$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new EJ({...b$(this._def),innerType:this,defaultValue:_,typeName:L$.ZodDefault})}brand(){return new I9({typeName:L$.ZodBranded,type:this,...b$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new MJ({...b$(this._def),innerType:this,catchValue:_,typeName:L$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return HU.create(this,$)}readonly(){return AJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var FC=/^c[^\s-]{8,}$/i,EC=/^[0-9a-z]+$/,MC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,AC=/^[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,bC=/^[a-z0-9_-]{21}$/i,wC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,gC=/^[-+]?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)?)??$/,kC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,IC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",JQ,fC=/^(?:(?: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])$/,CC=/^(?:(?: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])$/,PC=/^(([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]))$/,TC=/^(([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])$/,SC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ZC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ON="((\\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])))",vC=new RegExp(`^${ON}$`);function LN($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function yC($){return new RegExp(`^${LN($)}$`)}function BN($){let _=`${ON}T${LN($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function hC($,_){if((_==="v4"||!_)&&fC.test($))return!0;if((_==="v6"||!_)&&PC.test($))return!0;return!1}function mC($,_){if(!wC.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function xC($,_){if((_==="v4"||!_)&&CC.test($))return!0;if((_==="v6"||!_)&&TC.test($))return!0;return!1}class T6 extends P${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==o.string){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.string,received:W.parsedType}),z$}let J=new P_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),c(U,{code:S.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:S.invalid_string,...X$.errToObj(J)})}_addCheck($){return new T6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...X$.errToObj($)})}url($){return this._addCheck({kind:"url",...X$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...X$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...X$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...X$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...X$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...X$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...X$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...X$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...X$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...X$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...X$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...X$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...X$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...X$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...X$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...X$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...X$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...X$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...X$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...X$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...X$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...X$.errToObj(_)})}nonempty($){return this.min(1,X$.errToObj($))}trim(){return new T6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}T6.create=($)=>{return new T6({checks:[],typeName:L$.ZodString,coerce:$?.coerce??!1,...b$($)})};function uC($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class H0 extends P${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==o.number){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.number,received:W.parsedType}),z$}let J=void 0,U=new P_;for(let W of this._def.checks)if(W.kind==="int"){if(!m$.isInteger($.data))J=this._getOrReturnCtx($,J),c(J,{code:S.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),c(J,{code:S.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(uC($.data,W.value)!==0)J=this._getOrReturnCtx($,J),c(J,{code:S.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),c(J,{code:S.not_finite,message:W.message}),U.dirty()}else m$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,X$.toString(_))}gt($,_){return this.setLimit("min",$,!1,X$.toString(_))}lte($,_){return this.setLimit("max",$,!0,X$.toString(_))}lt($,_){return this.setLimit("max",$,!1,X$.toString(_))}setLimit($,_,J,U){return new H0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:X$.toString(U)}]})}_addCheck($){return new H0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:X$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:X$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:X$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&m$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}H0.create=($)=>{return new H0({checks:[],typeName:L$.ZodNumber,coerce:$?.coerce||!1,...b$($)})};class N0 extends P${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==o.bigint)return this._getInvalidInput($);let J=void 0,U=new P_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),c(J,{code:S.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),c(J,{code:S.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else m$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return c(_,{code:S.invalid_type,expected:o.bigint,received:_.parsedType}),z$}gte($,_){return this.setLimit("min",$,!0,X$.toString(_))}gt($,_){return this.setLimit("min",$,!1,X$.toString(_))}lte($,_){return this.setLimit("max",$,!0,X$.toString(_))}lt($,_){return this.setLimit("max",$,!1,X$.toString(_))}setLimit($,_,J,U){return new N0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:X$.toString(U)}]})}_addCheck($){return new N0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:X$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}N0.create=($)=>{return new N0({checks:[],typeName:L$.ZodBigInt,coerce:$?.coerce??!1,...b$($)})};class LJ extends P${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==o.boolean){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.boolean,received:J.parsedType}),z$}return d_($.data)}}LJ.create=($)=>{return new LJ({typeName:L$.ZodBoolean,coerce:$?.coerce||!1,...b$($)})};class L1 extends P${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==o.date){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_type,expected:o.date,received:W.parsedType}),z$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return c(W,{code:S.invalid_date}),z$}let J=new P_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),c(U,{code:S.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else m$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new L1({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:X$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:X$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}L1.create=($)=>{return new L1({checks:[],coerce:$?.coerce||!1,typeName:L$.ZodDate,...b$($)})};class jU extends P${_parse($){if(this._getType($)!==o.symbol){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.symbol,received:J.parsedType}),z$}return d_($.data)}}jU.create=($)=>{return new jU({typeName:L$.ZodSymbol,...b$($)})};class BJ extends P${_parse($){if(this._getType($)!==o.undefined){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.undefined,received:J.parsedType}),z$}return d_($.data)}}BJ.create=($)=>{return new BJ({typeName:L$.ZodUndefined,...b$($)})};class HJ extends P${_parse($){if(this._getType($)!==o.null){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.null,received:J.parsedType}),z$}return d_($.data)}}HJ.create=($)=>{return new HJ({typeName:L$.ZodNull,...b$($)})};class B1 extends P${constructor(){super(...arguments);this._any=!0}_parse($){return d_($.data)}}B1.create=($)=>{return new B1({typeName:L$.ZodAny,...b$($)})};class B0 extends P${constructor(){super(...arguments);this._unknown=!0}_parse($){return d_($.data)}}B0.create=($)=>{return new B0({typeName:L$.ZodUnknown,...b$($)})};class Y4 extends P${_parse($){let _=this._getOrReturnCtx($);return c(_,{code:S.invalid_type,expected:o.never,received:_.parsedType}),z$}}Y4.create=($)=>{return new Y4({typeName:L$.ZodNever,...b$($)})};class DU extends P${_parse($){if(this._getType($)!==o.undefined){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.void,received:J.parsedType}),z$}return d_($.data)}}DU.create=($)=>{return new DU({typeName:L$.ZodVoid,...b$($)})};class S6 extends P${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==o.array)return c(_,{code:S.invalid_type,expected:o.array,received:_.parsedType}),z$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)c(_,{code:S.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new v6(_,X,_.path,G))})).then((X)=>{return P_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new v6(_,X,_.path,G))});return P_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new S6({...this._def,minLength:{value:$,message:X$.toString(_)}})}max($,_){return new S6({...this._def,maxLength:{value:$,message:X$.toString(_)}})}length($,_){return new S6({...this._def,exactLength:{value:$,message:X$.toString(_)}})}nonempty($){return this.min(1,$)}}S6.create=($,_)=>{return new S6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:L$.ZodArray,...b$(_)})};function zJ($){if($ instanceof B_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=Z6.create(zJ(U))}return new B_({...$._def,shape:()=>_})}else if($ instanceof S6)return new S6({...$._def,type:zJ($.element)});else if($ instanceof Z6)return Z6.create(zJ($.unwrap()));else if($ instanceof S4)return S4.create(zJ($.unwrap()));else if($ instanceof Q4)return Q4.create($.items.map((_)=>zJ(_)));else return $}class B_ extends P${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=m$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==o.object){let Q=this._getOrReturnCtx($);return c(Q,{code:S.invalid_type,expected:o.object,received:Q.parsedType}),z$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof Y4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new v6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof Y4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)c(U,{code:S.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new v6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return P_.mergeObjectSync(J,Q)});else return P_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return X$.errToObj,new B_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:X$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new B_({...this._def,unknownKeys:"strip"})}passthrough(){return new B_({...this._def,unknownKeys:"passthrough"})}extend($){return new B_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new B_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:L$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new B_({...this._def,catchall:$})}pick($){let _={};for(let J of m$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new B_({...this._def,shape:()=>_})}omit($){let _={};for(let J of m$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new B_({...this._def,shape:()=>_})}deepPartial(){return zJ(this)}partial($){let _={};for(let J of m$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new B_({...this._def,shape:()=>_})}required($){let _={};for(let J of m$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof Z6)W=W._def.innerType;_[J]=W}return new B_({...this._def,shape:()=>_})}keyof(){return HN(m$.objectKeys(this.shape))}}B_.create=($,_)=>{return new B_({shape:()=>$,unknownKeys:"strip",catchall:Y4.create(),typeName:L$.ZodObject,...b$(_)})};B_.strictCreate=($,_)=>{return new B_({shape:()=>$,unknownKeys:"strict",catchall:Y4.create(),typeName:L$.ZodObject,...b$(_)})};B_.lazycreate=($,_)=>{return new B_({shape:$,unknownKeys:"strip",catchall:Y4.create(),typeName:L$.ZodObject,...b$(_)})};class NJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new W6(G.ctx.common.issues));return c(_,{code:S.invalid_union,unionErrors:X}),z$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new W6(Y));return c(_,{code:S.invalid_union,unionErrors:G}),z$}}get options(){return this._def.options}}NJ.create=($,_)=>{return new NJ({options:$,typeName:L$.ZodUnion,...b$(_)})};var P4=($)=>{if($ instanceof RJ)return P4($.schema);else if($ instanceof L6)return P4($.innerType());else if($ instanceof KJ)return[$.value];else if($ instanceof V0)return $.options;else if($ instanceof FJ)return m$.objectValues($.enum);else if($ instanceof EJ)return P4($._def.innerType);else if($ instanceof BJ)return[void 0];else if($ instanceof HJ)return[null];else if($ instanceof Z6)return[void 0,...P4($.unwrap())];else if($ instanceof S4)return[null,...P4($.unwrap())];else if($ instanceof I9)return P4($.unwrap());else if($ instanceof AJ)return P4($.unwrap());else if($ instanceof MJ)return P4($._def.innerType);else return[]};class k9 extends P${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.object)return c(_,{code:S.invalid_type,expected:o.object,received:_.parsedType}),z$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return c(_,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),z$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=P4(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new k9({typeName:L$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...b$(J)})}}function QQ($,_){let J=T4($),U=T4(_);if($===_)return{valid:!0,data:$};else if(J===o.object&&U===o.object){let W=m$.objectKeys(_),X=m$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=QQ($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===o.array&&U===o.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=QQ(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===o.date&&U===o.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class VJ extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(GQ(W)||GQ(X))return z$;let G=QQ(W.value,X.value);if(!G.valid)return c(J,{code:S.invalid_intersection_types}),z$;if(YQ(W)||YQ(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}VJ.create=($,_,J)=>{return new VJ({left:$,right:_,typeName:L$.ZodIntersection,...b$(J)})};class Q4 extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.array)return c(J,{code:S.invalid_type,expected:o.array,received:J.parsedType}),z$;if(J.data.lengththis._def.items.length)c(J,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new v6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return P_.mergeArray(_,X)});else return P_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new Q4({...this._def,rest:$})}}Q4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Q4({items:$,typeName:L$.ZodTuple,rest:null,...b$(_)})};class OU extends P${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.object)return c(J,{code:S.invalid_type,expected:o.object,received:J.parsedType}),z$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new v6(J,G,J.path,G)),value:X._parse(new v6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return P_.mergeObjectAsync(_,U);else return P_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof P$)return new OU({keyType:$,valueType:_,typeName:L$.ZodRecord,...b$(J)});return new OU({keyType:T6.create(),valueType:$,typeName:L$.ZodRecord,...b$(_)})}}class LU extends P${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.map)return c(J,{code:S.invalid_type,expected:o.map,received:J.parsedType}),z$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new v6(J,G,J.path,[Q,"key"])),value:W._parse(new v6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return z$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return z$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}LU.create=($,_,J)=>{return new LU({valueType:_,keyType:$,typeName:L$.ZodMap,...b$(J)})};class H1 extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==o.set)return c(J,{code:S.invalid_type,expected:o.set,received:J.parsedType}),z$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)c(J,{code:S.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return z$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new v6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new H1({...this._def,minSize:{value:$,message:X$.toString(_)}})}max($,_){return new H1({...this._def,maxSize:{value:$,message:X$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}H1.create=($,_)=>{return new H1({valueType:$,minSize:null,maxSize:null,typeName:L$.ZodSet,...b$(_)})};class DJ extends P${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.function)return c(_,{code:S.invalid_type,expected:o.function,received:_.parsedType}),z$;function J(G,Y){return g9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,w9(),OJ].filter((Q)=>!!Q),issueData:{code:S.invalid_arguments,argumentsError:Y}})}function U(G,Y){return g9({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,w9(),OJ].filter((Q)=>!!Q),issueData:{code:S.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof N1){let G=this;return d_(async function(...Y){let Q=new W6([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return d_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new W6([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new W6([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new DJ({...this._def,args:Q4.create($).rest(B0.create())})}returns($){return new DJ({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new DJ({args:$?$:Q4.create([]).rest(B0.create()),returns:_||B0.create(),typeName:L$.ZodFunction,...b$(J)})}}class RJ extends P${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}RJ.create=($,_)=>{return new RJ({getter:$,typeName:L$.ZodLazy,...b$(_)})};class KJ extends P${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return c(_,{received:_.data,code:S.invalid_literal,expected:this._def.value}),z$}return{status:"valid",value:$.data}}get value(){return this._def.value}}KJ.create=($,_)=>{return new KJ({value:$,typeName:L$.ZodLiteral,...b$(_)})};function HN($,_){return new V0({values:$,typeName:L$.ZodEnum,...b$(_)})}class V0 extends P${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return c(_,{expected:m$.joinValues(J),received:_.parsedType,code:S.invalid_type}),z$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return c(_,{received:_.data,code:S.invalid_enum_value,options:J}),z$}return d_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return V0.create($,{...this._def,..._})}exclude($,_=this._def){return V0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}V0.create=HN;class FJ extends P${_parse($){let _=m$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==o.string&&J.parsedType!==o.number){let U=m$.objectValues(_);return c(J,{expected:m$.joinValues(U),received:J.parsedType,code:S.invalid_type}),z$}if(!this._cache)this._cache=new Set(m$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=m$.objectValues(_);return c(J,{received:J.data,code:S.invalid_enum_value,options:U}),z$}return d_($.data)}get enum(){return this._def.values}}FJ.create=($,_)=>{return new FJ({values:$,typeName:L$.ZodNativeEnum,...b$(_)})};class N1 extends P${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==o.promise&&_.common.async===!1)return c(_,{code:S.invalid_type,expected:o.promise,received:_.parsedType}),z$;let J=_.parsedType===o.promise?_.data:Promise.resolve(_.data);return d_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}N1.create=($,_)=>{return new N1({type:$,typeName:L$.ZodPromise,...b$(_)})};class L6 extends P${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(c(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return z$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return z$;if(Y.status==="dirty")return jJ(Y.value);if(_.value==="dirty")return jJ(Y.value);return Y});else{if(_.value==="aborted")return z$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return z$;if(G.status==="dirty")return jJ(G.value);if(_.value==="dirty")return jJ(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return z$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return z$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!O1(X))return z$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!O1(X))return z$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});m$.assertNever(U)}}L6.create=($,_,J)=>{return new L6({schema:$,typeName:L$.ZodEffects,effect:_,...b$(J)})};L6.createWithPreprocess=($,_,J)=>{return new L6({schema:_,effect:{type:"preprocess",transform:$},typeName:L$.ZodEffects,...b$(J)})};class Z6 extends P${_parse($){if(this._getType($)===o.undefined)return d_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}Z6.create=($,_)=>{return new Z6({innerType:$,typeName:L$.ZodOptional,...b$(_)})};class S4 extends P${_parse($){if(this._getType($)===o.null)return d_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}S4.create=($,_)=>{return new S4({innerType:$,typeName:L$.ZodNullable,...b$(_)})};class EJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===o.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}EJ.create=($,_)=>{return new EJ({innerType:$,typeName:L$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...b$(_)})};class MJ extends P${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(zU(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new W6(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new W6(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}MJ.create=($,_)=>{return new MJ({innerType:$,typeName:L$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...b$(_)})};class BU extends P${_parse($){if(this._getType($)!==o.nan){let J=this._getOrReturnCtx($);return c(J,{code:S.invalid_type,expected:o.nan,received:J.parsedType}),z$}return{status:"valid",value:$.data}}}BU.create=($)=>{return new BU({typeName:L$.ZodNaN,...b$($)})};var dC=Symbol("zod_brand");class I9 extends P${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class HU extends P${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return z$;if(W.status==="dirty")return _.dirty(),jJ(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return z$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new HU({in:$,out:_,typeName:L$.ZodPipeline})}}class AJ extends P${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(O1(U))U.value=Object.freeze(U.value);return U};return zU(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}AJ.create=($,_)=>{return new AJ({innerType:$,typeName:L$.ZodReadonly,...b$(_)})};function YN($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function NN($,_={},J){if($)return B1.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=YN(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=YN(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return B1.create()}var nC={object:B_.lazycreate},L$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(L$||(L$={}));var cC=($,_={message:`Input not instance of ${$.name}`})=>NN((J)=>J instanceof $,_),VN=T6.create,RN=H0.create,iC=BU.create,lC=N0.create,KN=LJ.create,rC=L1.create,pC=jU.create,oC=BJ.create,tC=HJ.create,aC=B1.create,sC=B0.create,eC=Y4.create,$P=DU.create,_P=S6.create,JP=B_.create,WP=B_.strictCreate,UP=NJ.create,XP=k9.create,GP=VJ.create,YP=Q4.create,QP=OU.create,qP=LU.create,zP=H1.create,jP=DJ.create,DP=RJ.create,OP=KJ.create,LP=V0.create,BP=FJ.create,HP=N1.create,QN=L6.create,NP=Z6.create,VP=S4.create,RP=L6.createWithPreprocess,KP=HU.create,FP=()=>VN().optional(),EP=()=>RN().optional(),MP=()=>KN().optional(),AP={string:($)=>T6.create({...$,coerce:!0}),number:($)=>H0.create({...$,coerce:!0}),boolean:($)=>LJ.create({...$,coerce:!0}),bigint:($)=>N0.create({...$,coerce:!0}),date:($)=>L1.create({...$,coerce:!0})},bP=z$;var U$={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},FN=D.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),U6=D.string().datetime(),V$=D.string().trim().min(1),Z4=V$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),EN=D.string().regex(/^[a-fA-F0-9]{64}$/),MN=D.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),v4=D.record(D.unknown()),gJ=D.array(D.string().min(1)).default([]),V1=U6.nullable().optional(),wP=new Set(["succeeded","failed","cancelled","blocked","skipped"]),K1=D.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function t$($){return D.object({schema:D.literal($),id:D.string().min(1),createdAt:U6,updatedAt:V1,metadata:v4.optional()}).strict()}var Rt=D.object({schema:FN,id:D.string().min(1),createdAt:U6,updatedAt:V1,metadata:v4.optional()}).strict(),AN=D.enum(["agent","human","service","model","workflow","system"]),gP=t$(U$.actorRef).extend({kind:AN,name:D.string().min(1).optional(),provider:D.string().min(1).optional(),accountId:D.string().min(1).optional(),machineId:D.string().min(1).optional(),capabilities:D.array(D.string().min(1)).default([])}).strict(),q4=D.object({kind:AN,id:D.string().min(1),name:D.string().min(1).optional(),provider:D.string().min(1).optional(),accountId:D.string().min(1).optional(),machineId:D.string().min(1).optional()}).strict(),bN=D.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),kP=t$(U$.resourceRef).extend({kind:bN,name:D.string().min(1).optional(),uri:Z4.optional(),externalId:V$.optional(),sourcePackage:V$.optional(),tags:gJ}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:D.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),C$=D.object({kind:bN,id:D.string().min(1),name:D.string().min(1).optional(),uri:Z4.optional(),externalId:V$.optional(),sourcePackage:V$.optional(),tags:gJ}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:D.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),qQ=D.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),IP=D.enum(["none","partial","full","unknown"]),fP=t$(U$.evidenceRef).extend({kind:qQ,uri:Z4,sha256:EN.optional(),summary:D.string().min(1).optional(),contentType:D.string().min(1).optional(),sizeBytes:D.number().int().nonnegative().optional(),redaction:IP.default("unknown"),producer:q4.optional(),resourceRefs:D.array(C$).default([]),tags:gJ}).strict(),Q_=D.object({id:D.string().min(1),kind:qQ.optional(),uri:Z4.optional(),sha256:EN.optional(),summary:D.string().min(1).optional()}).strict(),NU=t$(U$.costEstimate).extend({currency:D.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:D.number().int().nonnegative(),provider:D.string().min(1).optional(),model:D.string().min(1).optional(),accountId:D.string().min(1).optional(),promptTokens:D.number().int().nonnegative().optional(),completionTokens:D.number().int().nonnegative().optional(),totalTokens:D.number().int().nonnegative().optional(),basis:D.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:D.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),CP=D.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),wN=t$(U$.decisionEnvelope).extend({decisionType:D.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:CP,actor:q4.optional(),traceId:D.string().min(1).optional(),inputHash:MN.optional(),policyBundleId:D.string().min(1).optional(),selected:D.array(C$).default([]),skipped:D.array(C$).default([]),reason:D.string().min(1),obligations:D.array(D.string().min(1)).default([]),redactions:D.array(D.string().min(1)).default([]),costEstimate:NU.optional(),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),PP=t$(U$.capabilityCard).extend({kind:D.enum(["model","tool","machine","agent","lane","connector","service"]),name:D.string().min(1),version:D.string().min(1).optional(),status:D.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:D.array(D.string().min(1)).default([]),limitations:D.array(D.string().min(1)).default([]),riskLevel:D.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:NU.optional(),evidenceRefs:D.array(Q_).default([])}).strict(),bJ=D.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),TP=D.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),SP=D.object({refName:V$,requiredForModes:D.array(bJ).min(1),allowedSecretInputs:D.array(D.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:V$,revocationCheck:D.boolean().default(!0)}).strict(),ZP=D.object({operation:V$,supportedModes:D.array(bJ).min(1),sideEffectClass:TP,requiresApproval:D.boolean().default(!1),requiresIdempotencyKey:D.boolean().default(!1),requiresSandboxEvidence:D.boolean().default(!1),requiresRollbackOrRevocation:D.boolean().default(!1),rollbackOrRevocation:V$.optional(),noSideEffectSmoke:V$.optional(),reconciliation:V$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),vP=D.object({providerId:V$,appId:V$,adapterId:V$,ownerPackage:V$,modes:D.array(bJ).min(1),defaultMode:bJ,credentialRequirements:D.array(SP).default([]),operations:D.array(ZP).min(1),rateLimitPosture:V$,costPosture:V$.optional(),auditEvents:D.array(V$).default([]),redactionRules:D.array(V$).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:D.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),yP=D.object({appId:V$,repo:V$,priority:D.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:D.array(V$).min(1),firstOperations:D.array(V$).min(1),blockedUntil:D.array(V$).default([])}).strict(),hP=t$(U$.providerLiveModeStandard).extend({name:V$,version:V$,modes:D.array(bJ).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:D.array(V$).min(1),liveMutationGate:D.object({requiredMode:D.literal("live_mutating"),requiredChecks:D.array(V$).min(1),forbiddenBypassSignals:D.array(V$).min(1),disabledLiveSmoke:V$}).strict(),noSideEffectSmoke:D.object({requiredForModes:D.array(bJ).min(1),commandEvidence:D.array(V$).min(1),secretOutputScan:D.boolean().default(!0)}).strict(),credentialPolicy:D.object({acceptedInputs:D.array(D.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:D.literal(!1),missingCredentialBehavior:D.literal("fail_closed"),revocationCheckRequired:D.boolean().default(!0)}).strict(),operationCards:D.array(vP).min(1),firstAdoptionTargets:D.array(yP).min(1),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:D.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),mP=D.object({id:D.string().min(1),title:D.string().min(1).optional(),summary:D.string().min(1),text:D.string().optional(),tokens:D.number().int().nonnegative().optional(),source:Q_,resourceRefs:D.array(C$).default([])}).strict(),gN=t$(U$.contextPack).extend({objective:D.string().min(1),budget:D.object({maxTokens:D.number().int().positive().optional(),maxBytes:D.number().int().positive().optional()}).strict().optional(),items:D.array(mP).default([]),citations:D.array(Q_).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),permissions:D.array(D.string().min(1)).default([]),redactions:D.array(D.string().min(1)).default([]),conflicts:D.array(D.string().min(1)).default([]),uncertainty:D.string().min(1).optional()}).strict(),P6=V$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),R1=D.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),xP=D.enum(["public","internal","private","sensitive"]),uP=D.enum(["draft","active","paused","archived"]),zQ=D.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),kN=t$(U$.integrationRef).extend({kind:zQ,name:D.string().min(1),projectId:R1.optional(),sourcePackage:V$.optional(),externalId:V$.optional(),uri:Z4.optional(),enabled:D.boolean().default(!0),readOnly:D.boolean().default(!0),capabilities:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:C$.optional(),evidenceRefs:D.array(Q_).default([]),config:v4.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:D.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),dP=D.object({schemaRoot:P6.default(".hasna/project"),dashboardManifest:P6.default(".hasna/project/dashboard.render.json"),snapshotsDir:P6.default(".hasna/project/snapshots"),documentsDir:P6.default("documents"),reportsDir:P6.default("reports"),evidenceDir:P6.default(".hasna/project/evidence"),privateDir:P6.default(".hasna/project/private")}).strict(),nP=t$(U$.projectManifest).extend({projectId:R1,slug:R1,name:D.string().min(1),summary:D.string().min(1).optional(),status:uP.default("active"),classification:xP.default("private"),owner:q4.optional(),layout:dP.default({}),integrations:D.array(kN).default([]),renderManifests:D.array(C$).default([]),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),tags:gJ}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:D.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:D.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:D.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),cP=D.enum(["local","package","provider","url"]),jQ=D.object({id:D.string().min(1),kind:cP,specifier:D.string().min(1),path:P6.optional(),packageName:D.string().min(1).optional(),uri:Z4.optional(),provider:zQ.optional(),schemaId:FN.optional(),integrity:MN.optional(),resourceRef:C$.optional(),optional:D.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:D.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:D.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:D.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:D.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),iP=D.enum(["dashboard","canvas","panel","report","document","custom"]),lP=D.object({id:D.string().min(1),title:D.string().min(1),kind:iP,default:D.boolean().default(!1),entry:P6.optional(),imports:D.array(jQ).default([]),panelRefs:D.array(C$).default([]),dataRefs:D.array(C$).default([]),layout:v4.optional()}).strict(),rP=t$(U$.renderManifest).extend({projectId:R1,name:D.string().min(1),version:D.string().min(1),manifestPath:P6.default(".hasna/project/dashboard.render.json"),renderer:D.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:D.array(lP).min(1),imports:D.array(jQ).default([]),theme:v4.optional(),compatibility:D.object({minProjectsVersion:D.string().min(1).optional(),minContractsVersion:D.string().min(1).optional()}).strict().optional(),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:D.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),pP=D.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),oP=D.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),tP=D.object({id:D.string().min(1),label:D.string().min(1),value:D.union([D.string(),D.number(),D.boolean()]),unit:D.string().min(1).optional(),status:D.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:D.array(C$).default([])}).strict(),aP=D.object({id:D.string().min(1),title:D.string().min(1),summary:D.string().min(1).optional(),status:D.string().min(1).optional(),priority:D.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:U6.optional(),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),metadata:v4.optional()}).strict(),sP=D.object({renderer:D.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:D.string().min(1).optional(),entry:P6.optional(),imports:D.array(jQ).default([]),spec:v4.default({})}).strict(),IN=t$(U$.projectPanel).extend({projectId:R1,provider:D.object({kind:zQ,id:D.string().min(1),name:D.string().min(1).optional(),sourcePackage:V$.optional(),externalId:V$.optional()}).strict(),kind:oP,title:D.string().min(1),summary:D.string().min(1).optional(),state:pP.default("ready"),stateReason:D.string().min(1).optional(),generatedAt:U6,freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),metrics:D.array(tP).default([]),items:D.array(aP).default([]),actions:D.array(C$).default([]),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),renderFragment:sP.optional(),warnings:D.array(D.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:D.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:D.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),eP=t$(U$.projectSnapshot).extend({projectId:R1,generatedAt:U6,status:K1.default("unknown"),manifestRef:C$,renderManifestRef:C$.optional(),panels:D.array(IN).default([]),contextPacks:D.array(gN).default([]),proofBundleRefs:D.array(C$).default([]),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),warnings:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:D.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),fN=D.object({id:D.string().min(1),kind:D.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:D.boolean().default(!0),command:D.string().min(1).optional(),expected:D.string().min(1).optional(),timeoutMs:D.number().int().positive().optional(),resourceRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:D.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),$T=t$(U$.validationPlan).extend({objective:D.string().min(1),subject:C$.optional(),checks:D.array(fN).min(1),verifier:q4.optional(),requiredEvidenceKinds:D.array(qQ).default([])}).strict(),_T=D.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),JT=D.enum(["draft","active","deprecated","archived"]),WT=D.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),UT=D.object({key:D.string().regex(/^[A-Z][A-Z0-9_]*$/),description:D.string().min(1),required:D.boolean().default(!1),["secret"]:D.boolean().default(!1),group:D.string().min(1).optional(),default:D.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),XT=D.object({name:D.string().min(1),command:D.string().min(1),description:D.string().min(1).optional(),required:D.boolean().default(!1)}).strict(),GT=D.object({packageManager:D.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:D.array(D.string().min(1)).default([]),requiredFiles:D.array(D.string().min(1)).default([]),requiredDirectories:D.array(D.string().min(1)).default([]),optionalDirectories:D.array(D.string().min(1)).default([])}).strict(),YT=t$(U$.scaffoldManifest).extend({name:D.string().min(1),version:D.string().min(1),summary:D.string().min(1),type:_T,status:JT.default("draft"),capabilities:D.array(WT).default([]),techStack:D.array(D.string().min(1)).default([]),tags:gJ,source:C$.optional(),output:GT,env:D.array(UT).default([]),scripts:D.array(XT).default([]),validationChecks:D.array(fN).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:D.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),QT=D.enum(["installed","failed","cancelled","partial","unknown"]),qT=t$(U$.scaffoldInstallRecord).extend({scaffoldId:D.string().min(1),scaffoldVersion:D.string().min(1).optional(),manifestRef:C$.optional(),target:C$,status:QT,installedAt:U6.optional(),installer:q4.optional(),packageManager:D.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:v4.optional(),generatedFiles:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),proofBundleRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:D.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),wJ=D.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),DQ=D.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),CN=D.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),zT=D.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),jT=V$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),DT=D.enum(["active","stub","deprecated","archived"]),OT=D.enum(["stable","beta","canary","internal"]),LT=D.object({transport:D.enum(["http","stdio"]).default("http"),bin:D.string().min(1).optional(),url:Z4.optional()}).strict(),BT=D.object({healthPath:D.string().min(1).default("/health"),port:D.number().int().positive().optional(),baseUrl:Z4.optional()}).strict(),HT=D.object({bins:D.array(D.string().min(1)).default([]),mcp:LT.optional(),http:BT.optional()}).strict(),NT=t$(U$.app).extend({appId:wJ,npmName:DQ,repoFolder:wJ,githubUrl:jT,projectSlug:R1,surfaces:HT.default({}),lifecycle:DT,releaseChannel:OT.default("stable"),summary:D.string().min(1).optional(),tags:gJ}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:D.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),VT=D.enum(["skill","ci","backfilled"]),RT=t$(U$.release).extend({appId:wJ,package:DQ,version:CN,gitSha:zT,publishedAt:U6,publishPath:VT,changelogRef:C$.optional(),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),KT=D.enum(["install","update","rollback","freeze-blocked"]),FT=D.object({cliVersion:D.string().min(1).optional(),mcpHealth:D.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),ET=t$(U$.rolloutRecord).extend({appId:wJ,package:DQ,version:CN,machine:V$,action:KT,result:K1,verifiedBy:FT.optional(),at:U6,evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:D.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),MT=D.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),AT=D.enum(["pending","queued","sent","failed","skipped","suppressed"]),bT=D.object({channel:MT,status:AT,deliveredAt:U6.optional(),detail:D.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:D.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),wT=t$(U$.announcement).extend({campaignId:V$,appId:wJ.optional(),releaseRef:C$.optional(),channels:D.array(bT).min(1),audienceRef:C$,sentAt:U6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:D.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:D.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),gT=D.enum(["tag","attribute","group"]),kT=D.enum(["eq","neq","in","not_in","exists","not_exists"]),qN=D.union([D.string(),D.number(),D.boolean()]),IT=D.object({kind:gT,key:D.string().min(1).optional(),op:kT.default("eq"),value:qN.optional(),values:D.array(qN).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:D.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),fT=D.object({match:D.enum(["all","any"]).default("all"),predicates:D.array(IT).min(1)}).strict(),CT=D.enum(["opt_in","opt_out","transactional","none"]),PT=t$(U$.audience).extend({audienceId:wJ,name:V$,definition:fT,consentPolicy:CT,suppressionSyncedAt:V1}).strict(),WQ=["@hasna/cloud","open-cloud"],TT=D.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),ST=D.object({id:D.string().min(1),provider:TT,kind:D.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:D.string().min(1),region:D.string().min(1).optional(),accountId:D.string().min(1).optional(),uri:Z4.optional(),machineScoped:D.boolean().default(!1)}).strict(),PN=t$(U$.appCloudManifest).extend({packageName:D.string().min(1),packageVersion:D.string().min(1).optional(),appId:D.string().min(1),repository:C$.optional(),storageMode:D.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:D.enum(["none","app_owned","external_service","local_cache"]),cloudResources:D.array(ST).default([]),localCache:D.object({path:D.string().min(1).optional(),pullMode:D.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:D.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:D.array(D.string().min(1)).default([...WQ]),dependencies:D.array(D.string().min(1)).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...WQ,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:D.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of WQ)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:D.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:D.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:D.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:D.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:D.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:D.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),TN=D.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),ZT=D.enum(["low","medium","high","critical"]),SN=D.object({id:D.string().min(1),kind:TN,severity:ZT,path:D.string().min(1).optional(),packageName:D.string().min(1).optional(),pattern:D.string().min(1),message:D.string().min(1),evidenceRefs:D.array(Q_).default([])}).strict(),vT=D.object({id:D.string().min(1),kind:TN,status:K1,target:D.string().min(1),command:D.string().min(1).optional(),evidenceRefs:D.array(Q_).default([]),findings:D.array(SN).default([])}).strict(),yT=t$(U$.noCloudEvidencePack).extend({subject:C$,packageName:D.string().min(1).optional(),packageVersion:D.string().min(1).optional(),generatedBy:q4.optional(),scanMode:D.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:K1,verdict:D.enum(["passed","failed","warning","not_run"]),appCloudManifest:PN.optional(),checks:D.array(vT).min(1),findings:D.array(SN).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),hT=D.object({checkId:D.string().min(1),status:K1,summary:D.string().min(1).optional(),startedAt:V1,finishedAt:V1,evidenceRefs:D.array(Q_).default([])}).strict(),mT=t$(U$.proofBundle).extend({subject:C$,validationPlanRef:C$.optional(),status:K1,verdict:D.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:D.array(hT).default([]),verifier:q4.optional(),evidenceRefs:D.array(Q_).default([]),residualRisks:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),xT=t$(U$.workRun).extend({objective:D.string().min(1),status:K1,actor:q4,traceId:D.string().min(1).optional(),startedAt:V1,finishedAt:V1,constraints:D.array(D.string().min(1)).default([]),resourceRefs:D.array(C$).default([]),decisions:D.array(wN).default([]),costEstimates:D.array(NU).default([]),evidenceRefs:D.array(Q_).default([]),validationPlanRefs:D.array(C$).default([]),proofBundleRefs:D.array(C$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),uT=D.object({id:D.string().min(1),at:U6,kind:D.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:D.string().min(1),resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([]),costEstimate:NU.optional()}).strict(),dT=t$(U$.agentTrajectory).extend({actor:q4,workRunRef:C$.optional(),events:D.array(uT).default([]),outcome:D.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:C$.optional()}).strict(),nT="v1",cT=D.enum(["library","cli-with-store","service","saas"]),iT=["local","self-hosted","cloud"],ZN=D.enum(iT),lT=D.enum(["supported","deferred","unsupported"]),rT=D.enum(["none","local-only","api-key","session","service-token","custom"]),UQ=D.object({method:D.enum(["GET","POST","PUT","PATCH","DELETE"]),path:D.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:D.boolean().default(!1),description:D.string().min(1).optional()}).strict(),pT=D.object({id:D.string().min(1),kind:D.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:D.boolean().default(!0),command:D.string().min(1).optional(),evidenceRef:Q_.optional(),status:D.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:D.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:D.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),oT=D.object({name:D.string().min(1),status:lT,bin:D.string().min(1).optional(),mcpBin:D.string().min(1).optional(),authMode:rT,deploymentModes:D.array(ZN).min(1),health:UQ.optional(),readiness:UQ.optional(),version:UQ.optional(),apiBasePath:D.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:D.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:D.string().min(1).optional(),readinessGates:D.array(pT).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:D.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:D.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:D.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:D.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),tT=["local","cloud"],vN=D.enum(tT),aT=["remote","hybrid","self_hosted"],sT=D.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),eT=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function $S($){return eT.map((_)=>`${$}${_}`)}function zN($){return`hasna/oss/${$}/database-url`}var _S=D.object({mode:vN,envPrefix:D.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:D.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:D.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:D.string().min(1).optional()}).strict(),JS=D.object({$schema:D.string().min(1).optional(),schema:D.literal(U$.serviceContract),name:sT,class:cT,contractVersion:D.literal(nT),kitVersion:D.string().min(1),description:D.string().min(1).optional(),bins:D.array(D.string().min(1)).default([]),storage:_S.optional(),deploymentModes:D.array(ZN).default(["local"]),serviceSurfaces:D.array(oT).default([]),metadata:v4.optional()}).strict().superRefine(($,_)=>{let J=new Set($S($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:D.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:D.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:D.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==zN($.name))_.addIssue({code:D.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${zN($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:D.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:D.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:D.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:D.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:D.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:D.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),Kt=D.object({status:D.enum(["ok","degraded","unavailable"]),version:D.string().min(1),mode:vN}).strict(),Ft=D.object({ready:D.boolean(),reason:D.string().min(1).optional()}).strict(),Et=D.object({version:D.string().min(1)}).strict(),WS=D.enum(["info","notice","breaking","critical"]),US=D.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),XS=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],GS=D.enum(XS);var YS=D.enum(["fleet","package","machine"]),yN=t$(U$.commsEventEnvelope).extend({type:US,severity:WS,scope:YS,summary:D.string().min(1).optional(),source:q4.optional(),affected_packages:D.array(V$).default([]),affected_machines:D.array(V$).default([]),action_required:D.boolean().default(!1),ack_by:U6.optional(),dedupe_key:V$,resourceRefs:D.array(C$).default([]),evidenceRefs:D.array(Q_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:D.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),QS=D.enum(["fleet","package","product","loop-lane","initiative","personal"]),qS=D.enum(["quiet","work","firehose"]),zS=V$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),jS=t$(U$.commsChannelMetadata).extend({class:QS,noise:qS.optional(),owner:V$.optional(),until:zS.optional(),successor:V$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:D.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:D.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),jN={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},DS=t$(U$.commsMessageMetadata).extend({tag:GS,envelope:yN}).strict().superRefine(($,_)=>{let J=jN[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:D.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:D.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(jN))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:D.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var Mt={[U$.actorRef]:gP,[U$.resourceRef]:kP,[U$.evidenceRef]:fP,[U$.workRun]:xT,[U$.decisionEnvelope]:wN,[U$.costEstimate]:NU,[U$.capabilityCard]:PP,[U$.providerLiveModeStandard]:hP,[U$.contextPack]:gN,[U$.integrationRef]:kN,[U$.projectManifest]:nP,[U$.projectPanel]:IN,[U$.projectSnapshot]:eP,[U$.renderManifest]:rP,[U$.agentTrajectory]:dT,[U$.validationPlan]:$T,[U$.proofBundle]:mT,[U$.scaffoldManifest]:YT,[U$.scaffoldInstallRecord]:qT,[U$.appCloudManifest]:PN,[U$.noCloudEvidencePack]:yT,[U$.serviceContract]:JS,[U$.commsEventEnvelope]:yN,[U$.commsChannelMetadata]:jS,[U$.commsMessageMetadata]:DS,[U$.app]:NT,[U$.release]:RT,[U$.rolloutRecord]:ET,[U$.announcement]:wT,[U$.audience]:PT};function VU($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(aT.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}var OS=["remote","hybrid","self_hosted"];function OQ($){let _=$.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return{mode:"local",deprecatedAlias:null};if(_==="cloud")return{mode:"cloud",deprecatedAlias:null};if(OS.includes(_))return{mode:"cloud",deprecatedAlias:_};throw Error(`Unknown storage mode: ${$}. Use local or cloud.`)}import ft from"pg";class f9 extends Error{scheme;port;constructor($,_){super($);this.name="KnowledgeNetworkGuardError",this.scheme=_.scheme,this.port=_.port}}function kJ($=process.env){return($.NODE_ENV??"").trim().toLowerCase()==="test"}function hN($){let _=$.split(".");if(_.length!==4)return!1;if(!_.every((J)=>/^\d{1,3}$/.test(J)&&Number(J)<=255))return!1;return _[0]==="127"}function VS($){let _=$.trim().toLowerCase();if(_.length===0)return!1;if(_==="localhost"||_.endsWith(".localhost"))return!0;if(hN(_))return!0;if(!_.startsWith("[")||!_.endsWith("]"))return!1;let J=_.slice(1,-1);if(J==="::1"||/^(0:){7}1$/.test(J))return!0;let U=J.split(":").pop()??"";if(/^(::ffff:|::)/.test(J)&&hN(U))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(J)}function uN($){if(typeof $==="string")return $;if($ instanceof URL)return $.href;return $.url}function mN($,_=process.env){if(!kJ(_))return;let J=uN($),U;try{U=new URL(J)}catch{throw new f9("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(VS(U.hostname))return;throw new f9(`knowledge: refused a non-loopback ${U.protocol.replace(":","")} request while NODE_ENV=test (target host withheld on purpose). This process resolved to the cloud backend under test, which means a read or write was about to leave the machine and reach the live store. Select the mode explicitly (HASNA_KNOWLEDGE_STORAGE_MODE=local) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:U.protocol.replace(":",""),port:U.port})}var RS=new Set([301,302,303,307,308]),xN=5;function KS($,_){if(_?.method)return _.method.toUpperCase();if(typeof $!=="string"&&!($ instanceof URL))return $.method.toUpperCase();return"GET"}async function C9($,_){if(mN($),!kJ()||_?.redirect!==void 0)return fetch($,_);let J=uN($),U=KS($,_),W=_?.body,X=await fetch($,{..._??{},redirect:"manual"});for(let G=0;RS.has(X.status);G++){let Y=X.headers.get("location");if(!Y)return X;let Q=new URL(Y,J).href;if(mN(Q),G>=xN){let L=new URL(Q);throw new f9(`knowledge: refused to follow more than ${xN} redirects while NODE_ENV=test (target host withheld on purpose). Under test the guard follows redirects itself so every hop is checked, and a chain this long is a loop, not a route.`,{scheme:L.protocol.replace(":",""),port:L.port})}if(X.status===303||(X.status===301||X.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",W=void 0;let q={..._??{},method:U,redirect:"manual"};if(W===void 0)delete q.body;else q.body=W;X=await fetch(Q,q),J=Q}return X}var T9="knowledge",LQ=XN(T9),y4=LQ.modeKeys,S9=LQ.apiUrlKeys,Z9=LQ.apiKeyKeys;function P9($,_){return _.filter((J)=>($[J]??"").trim().length>0)}function RU($=process.env){let _=[...P9($,S9),...P9($,Z9)],J=y4[0];for(let U of y4){let W=$[U]?.trim();if(!W)continue;let X;try{X=OQ(W)}catch(Y){let Q=Y instanceof Error?Y.message:String(Y);throw Error(`knowledge: ${U}=${W} is not a valid mode. ${Q}`)}let G=[];if(X.deprecatedAlias)G.push(`Deprecated mode '${X.deprecatedAlias}' from ${U} is treated as 'cloud'. Prefer ${J}=cloud.`);if(U!==J)G.push(`Using alias env ${U}; the canonical key is ${J}.`);if(X.mode==="local"&&_.length>0)G.push(`${U}=local pins the on-box store; ${_.join(", ")} are set but ignored.`);return{mode:X.mode,source:{kind:"env",name:U,value:W},pointer_env_present:_,pointer_ignored:X.mode==="local"&&_.length>0,warning:G.length>0?G.join(" "):null}}return{mode:"local",source:{kind:"default",name:null,value:null},pointer_env_present:_,pointer_ignored:_.length>0,warning:_.length>0?`${_.join(", ")} are set but do NOT select a backend: mode is local by default. Set ${J}=cloud to route reads and writes to the API, or unset those vars to silence this note.`:null}}var FS=["postgres","cloud","self_hosted"],ES=["sqlite","local"],dN=new Map;function nN($,_,J){let U=_===VU;if(U){let W=dN.get($);if(W!==void 0)return W}for(let W of $)try{if(_(W),U)dN.set($,W);return W}catch{}throw Error(`knowledge: no known storage token is accepted by the installed @hasna/contracts (tried ${$.join(", ")}). The storage-mode enum has changed; add the new token to ${J} in src/knowledge-mode.ts.`)}function MS($=VU){return nN(FS,$,"SERVER_MODE_CANDIDATES")}function AS($=VU){return nN(ES,$,"LOCAL_MODE_CANDIDATES")}function bS($,_=VU){return $==="cloud"?MS(_):AS(_)}function BQ($,_){return{...$,[y4[0]]:bS(_)}}class cN extends Error{code="knowledge_mode_unset_with_api_url";constructor($){let _=y4[0];super(`knowledge: ${$.join(", ")} names an API store, but no mode variable says to use it, so this command would silently read and write the on-box store instead. Set ${_}=cloud to use the API, or ${_}=local to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function iN($=process.env,_={}){let J=RU($);if(_.storePathOverridden)return J;if(J.source.kind!=="default")return J;let U=P9($,S9);if(U.length===0)return J;throw new cN(U)}function lN($=process.env){let _=RU($);return{..._,store_transport:_.mode==="cloud"?"api":"local",api_key_present:P9($,Z9).length>0,network_guard_active:kJ($)}}function rN($){return{fetchImpl:C9,...kJ($)?{retry:!1}:{}}}var R0="notes";class pN extends Error{expected;current;code="version_conflict";constructor($,_){super(`version_conflict: this edit was written against version ${$} but the stored entry is now at version ${_}. Nothing was written. Re-read the entry and re-apply only if the fields you are changing are untouched between the two versions.`);this.expected=$;this.current=_;this.name="KnowledgeVersionConflictError"}}function wS($){let _={};if($.search)_.search=$.search;if($.limit!==void 0)_.limit=$.limit;if($.offset!==void 0)_.offset=$.offset;if($.includeArchived||$.archivedOnly)_.includeArchived=!0;return _}function gS($){return{baseUrl:$.baseUrl,async list(_={}){let J=_.limit??200,U=wS({..._,limit:Math.min(Math.max(J,1),200)}),W=await $.list(R0,{query:U}),X=W.items;if(_.archivedOnly)X=X.filter((G)=>G.archived===!0);if(_.tag){let G=_.tag.toLowerCase();X=X.filter((Y)=>(Y.tags??[]).some((Q)=>Q.toLowerCase()===G))}return{items:X,total:W.total}},async get(_){return $.get(R0,_)},async create(_){return $.create(R0,{..._.id?{id:_.id}:{},title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],..._.metadata?{metadata:_.metadata}:{}})},async update(_,J,U={}){try{return await $.update(R0,_,J,{...U.expectedVersion!==void 0?{headers:{"if-match":String(U.expectedVersion)}}:{}})}catch(W){if(HQ(W))return null;let X=kS(W);if(X)throw X;throw W}},async delete(_){let J=await $.get(R0,_);if(!J)return!1;return await $.delete(R0,J.id),!0},async listVersions(_,J={}){try{return await $.transport.get(`/${R0}/${encodeURIComponent(_)}/versions`,{query:{limit:J.limit,offset:J.offset}})}catch(U){if(HQ(U))return null;throw U}},async getVersion(_,J){try{return await $.transport.get(`/${R0}/${encodeURIComponent(_)}/versions/${J}`)}catch(U){if(HQ(U))return null;throw U}}}}function kS($){if(!$||typeof $!=="object")return null;if($.status!==409)return null;let _=$.body,U=(typeof _==="string"?IS(_):_)??{};if(U.error!=="version_conflict")return null;return new pN(Number(U.expected??0),Number(U.current??0))}function IS($){try{return JSON.parse($)}catch{return null}}function HQ($){return Boolean($&&typeof $==="object"&&$.status===404)}function KU($=process.env){if(RU($).mode!=="cloud")return null;let _=cY(T9,BQ($,"cloud"),rN($));if(_.transport!=="cloud-http")return null;return gS(_.client)}function K0($=process.env){if(RU($).mode!=="cloud")return!1;return cY(T9,BQ($,"cloud"),rN($)).transport==="cloud-http"}async function v9($){let J=[];for(let U=0;;U+=200){let{items:W}=await $.list({includeArchived:!0,limit:200,offset:U});if(J.push(...W),W.length<200)break;if(U>1e5)break}return J}class VQ extends Error{location;code="version_history_unsupported";constructor($){super(`Version history is not kept by the local JSON knowledge store (${$}). It has no version line, so an empty history here would be a claim, not a measurement. Entry versioning lives in the Postgres-backed store: point this CLI at it (HASNA_KNOWLEDGE_STORAGE_MODE=cloud plus the API url/key) and re-run.`);this.location=$;this.name="VersionHistoryUnsupportedError"}}function NQ($,_){return $.id===_||$.short_id===_}class oN{storePath;kind="local";supportsVersions=!1;constructor($){this.storePath=$}async listVersions(){throw new VQ(this.storePath)}async getVersion(){throw new VQ(this.storePath)}get location(){return this.storePath}get exists(){return fS(this.storePath)}async listAll(){let $=g2(this.storePath);return{items:$.items,exists:$.exists}}async get($){return g2(this.storePath).items.find((J)=>NQ(J,$))??null}async create($){return $4(this.storePath,()=>{let _=rW(this.storePath),J=new Date().toISOString(),U=$.id??lB(),W={id:U,short_id:rB(U),title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],metadata:$.metadata??{},archived:!1,created_at:J,updated_at:J};return _.items.push(W),F4(this.storePath,_),W},{createParent:!0})}async update($,_){return $4(this.storePath,()=>{let J=rW(this.storePath),U=J.items.findIndex((X)=>NQ(X,$));if(U===-1)return null;let W=J.items[U];if(_.title!==void 0)W.title=_.title;if(_.content!==void 0)W.content=_.content;if(_.url!==void 0)W.url=_.url;if(_.tags!==void 0)W.tags=_.tags;if(_.metadata!==void 0)W.metadata=_.metadata;if(_.archived!==void 0)W.archived=_.archived;return W.updated_at=new Date().toISOString(),J.items[U]=W,F4(this.storePath,J),W},{createParent:!0})}async delete($){return $4(this.storePath,()=>{let _=rW(this.storePath),J=_.items.length;_.items=_.items.filter((W)=>!NQ(W,$));let U=J!==_.items.length;if(U)F4(this.storePath,_);return U},{createParent:!0})}async deleteMany($){if($.length===0)return 0;let _=new Set($);return $4(this.storePath,()=>{let J=rW(this.storePath),U=J.items.length;J.items=J.items.filter((X)=>!_.has(X.id)&&!(X.short_id!=null&&_.has(X.short_id)));let W=U-J.items.length;if(W>0)F4(this.storePath,J);return W},{createParent:!0})}}class tN{cloud;kind="api";exists=!0;supportsVersions=!0;constructor($){this.cloud=$}async listVersions($,_={}){return this.cloud.listVersions($,_)}async getVersion($,_){return this.cloud.getVersion($,_)}get location(){return this.cloud.baseUrl}async listAll(){return{items:await v9(this.cloud),exists:!0}}async get($){return this.cloud.get($)}async create($){return this.cloud.create({...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})}async update($,_,J={}){return this.cloud.update($,_,{expectedVersion:J.expectedVersion})}async delete($){return this.cloud.delete($)}async deleteMany($){let _=0;for(let J of $)if(await this.cloud.delete(J))_+=1;return _}}function y9($){let _=$.storePathOverridden?null:KU($.env??process.env);if(_)return new tN(_);return new oN($.storePath)}function aN($){let _=$??"";if(_==="")return[];return _.replace(/\n$/,"").split(` +`)}var RQ=5000;function CS($,_){let J=aN($),U=aN(_);if(J.length>RQ||U.length>RQ)throw Error(`Refusing to line-diff ${Math.max(J.length,U.length)} lines (limit ${RQ}). Fetch the two versions and diff them with a dedicated tool.`);let W=Array.from({length:J.length+1},()=>Array(U.length+1).fill(0));for(let Q=J.length-1;Q>=0;Q-=1)for(let q=U.length-1;q>=0;q-=1)W[Q][q]=J[Q]===U[q]?W[Q+1][q+1]+1:Math.max(W[Q+1][q],W[Q][q+1]);let X=[],G=0,Y=0;while(G=W[G][Y+1])X.push({op:"remove",from_line:G+1,to_line:null,text:J[G]}),G+=1;else X.push({op:"add",from_line:null,to_line:Y+1,text:U[Y]}),Y+=1;while(G{if(!PS($[Y],_[Y]))J.push({field:Y,from:$[Y]??null,to:_[Y]??null})};U("title"),U("url"),U("tags"),U("metadata"),U("archived");let W=CS($.content,_.content),X=W.filter((Y)=>Y.op==="add").length,G=W.filter((Y)=>Y.op==="remove").length;return{identical:J.length===0&&X===0&&G===0,fields:J,content:W,added:X,removed:G}}function eN($,_,J){let U=[`--- ${_}`,`+++ ${J}`];if($.identical)return U.push("(no changes)"),U.join(` `);for(let W of $.fields)U.push(`~ ${W.field}: ${JSON.stringify(W.from)} -> ${JSON.stringify(W.to)}`);if($.added===0&&$.removed===0){if($.fields.length>0)U.push("(content unchanged)")}else{U.push(`@@ content +${$.added} -${$.removed} @@`);for(let W of $.content){let X=W.op==="add"?"+":W.op==="remove"?"-":" ";U.push(`${X}${W.text}`)}}return U.join(` -`)}import{Database as dN}from"bun:sqlite";function T9($="catalog"){if(V1()){let _=v0[0];throw Error(`knowledge: ${$} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${_}=local `+"(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see "+"which variable selected the current backend.")}}var OS="porter unicode61 remove_diacritics 2",cN=` +`)}import{Database as $3}from"bun:sqlite";function h9($="catalog"){if(K0()){let _=y4[0];throw Error(`knowledge: ${$} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${_}=local `+"(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see "+"which variable selected the current backend.")}}var TS="porter unicode61 remove_diacritics 2",_3=` PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; @@ -265,7 +265,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (1, datetime('now')); -`,DS=` +`,SS=` DROP TABLE IF EXISTS chunks_fts; CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( @@ -278,7 +278,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (2, datetime('now')); -`,LS=` +`,ZS=` CREATE TABLE IF NOT EXISTS audit_events ( id TEXT PRIMARY KEY, event_type TEXT NOT NULL, @@ -309,7 +309,7 @@ CREATE INDEX IF NOT EXISTS idx_approval_gates_status ON approval_gates(status); INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (3, datetime('now')); -`,BS=` +`,vS=` CREATE TABLE IF NOT EXISTS vector_index_entries ( id TEXT PRIMARY KEY, chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, @@ -340,7 +340,7 @@ CREATE INDEX IF NOT EXISTS idx_vector_index_status ON vector_index_entries(statu INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (4, datetime('now')); -`,HS=` +`,yS=` CREATE TABLE IF NOT EXISTS reindex_queue ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, @@ -361,7 +361,7 @@ CREATE INDEX IF NOT EXISTS idx_reindex_queue_source_uri ON reindex_queue(source_ INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (5, datetime('now')); -`,lN=` +`,J3=` CREATE TABLE IF NOT EXISTS knowledge_machines ( machine_id TEXT PRIMARY KEY, hostname TEXT, @@ -436,7 +436,7 @@ CREATE INDEX IF NOT EXISTS idx_sync_conflicts_entity ON knowledge_sync_conflicts INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (6, datetime('now')); -`,NS=` +`,hS=` CREATE TABLE IF NOT EXISTS knowledge_sync_table_clocks ( table_name TEXT NOT NULL, machine_id TEXT NOT NULL, @@ -476,7 +476,7 @@ CREATE INDEX IF NOT EXISTS idx_sync_imports_status ON knowledge_sync_imports(sta INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (7, datetime('now')); -`,VS=` +`,mS=` CREATE INDEX IF NOT EXISTS idx_wiki_pages_lifecycle_status ON wiki_pages(status, valid_to); CREATE INDEX IF NOT EXISTS idx_wiki_pages_last_verified ON wiki_pages(last_verified_at); CREATE INDEX IF NOT EXISTS idx_wiki_pages_supersedes ON wiki_pages(supersedes); @@ -484,7 +484,7 @@ CREATE INDEX IF NOT EXISTS idx_wiki_pages_superseded_by ON wiki_pages(superseded INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (8, datetime('now')); -`,FS=` +`,xS=` BEGIN; CREATE TEMP TABLE _chunks_fts_backup AS @@ -497,7 +497,7 @@ CREATE VIRTUAL TABLE chunks_fts USING fts5( text, title, source_uri, - tokenize='${OS}' + tokenize='${TS}' ); INSERT INTO chunks_fts (chunk_id, text, title, source_uri) @@ -509,14 +509,75 @@ INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now')); COMMIT; -`;function i($){T9("opening the local knowledge.db catalog"),U1($);let _=new dN($);return _.exec("PRAGMA foreign_keys = ON;"),_.exec("PRAGMA busy_timeout = 5000;"),_}function nN($){return T9("reading the local knowledge.db catalog"),new dN($,{readonly:!0})}function G$($){let _=i($);try{if(_.exec(cN),I6(_)<2)_.exec(DS);if(I6(_)<3)_.exec(LS);if(I6(_)<4)_.exec(BS);if(I6(_)<5)_.exec(HS);if(I6(_)<6)_.exec(lN);if(RS(_))KS(_);if(MS(_))AS(_);if(bS(_))ES(_);return{path:$,schema_version:I6(_)}}finally{_.close()}}function I6($){return $.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function K6($,_){return $.query(`SELECT COUNT(*) AS n FROM ${_}`).get()?.n??0}function DY($){return`"${$.replaceAll('"','""')}"`}function N2($,_){let J=$.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get(_);return Boolean(J)}function y0($,_,J){if(!N2($,_))return!1;return $.query(`PRAGMA table_info(${DY(_)})`).all().some((W)=>W.name===J)}function F1($,_,J,U){if(!y0($,_,J))$.exec(`ALTER TABLE ${DY(_)} ADD COLUMN ${DY(J)} ${U};`)}function RS($){return I6($)<7||!y0($,"knowledge_sync_changes","logical_clock")||!y0($,"knowledge_sync_changes","bundle_id")||!N2($,"knowledge_sync_table_clocks")||!N2($,"knowledge_sync_imports")}function KS($){if(!N2($,"knowledge_sync_changes"))$.exec(lN);F1($,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),F1($,"knowledge_sync_changes","bundle_id","TEXT"),$.exec(NS)}function MS($){return I6($)<8||!y0($,"wiki_pages","valid_from")||!y0($,"wiki_pages","valid_to")||!y0($,"wiki_pages","supersedes")||!y0($,"wiki_pages","superseded_by")||!y0($,"wiki_pages","confidence")||!y0($,"wiki_pages","last_verified_at")}function AS($){if(!N2($,"wiki_pages"))$.exec(cN);F1($,"wiki_pages","valid_from","TEXT"),F1($,"wiki_pages","valid_to","TEXT"),F1($,"wiki_pages","supersedes","TEXT"),F1($,"wiki_pages","superseded_by","TEXT"),F1($,"wiki_pages","confidence","REAL"),F1($,"wiki_pages","last_verified_at","TEXT"),$.exec(` +`,uS=` +CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + source_kind TEXT NOT NULL, + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'pending', + requires_approval INTEGER NOT NULL DEFAULT 0, + checks_json TEXT NOT NULL DEFAULT '{}', + idempotency_key TEXT NOT NULL UNIQUE, + duplicate_of TEXT, + approved_by TEXT, + promoted_record_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + reviewed_at TEXT, + promoted_at TEXT +); + +CREATE TABLE IF NOT EXISTS durable_knowledge_records ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + confidence REAL, + valid_from TEXT NOT NULL, + valid_to TEXT, + promoted_from_candidate_id TEXT NOT NULL UNIQUE + REFERENCES knowledge_promotion_candidates(id) ON DELETE RESTRICT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_status + ON knowledge_promotion_candidates(status, updated_at); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_kind_key + ON knowledge_promotion_candidates(record_kind, canonical_key); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_hash + ON knowledge_promotion_candidates(record_kind, content_hash); +CREATE INDEX IF NOT EXISTS idx_durable_records_kind_key + ON durable_knowledge_records(record_kind, canonical_key, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_hash + ON durable_knowledge_records(record_kind, content_hash, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_validity + ON durable_knowledge_records(status, valid_to); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (10, datetime('now')); +`;function m($){h9("opening the local knowledge.db catalog"),G0($);let _=new $3($);return _.exec("PRAGMA foreign_keys = ON;"),_.exec("PRAGMA busy_timeout = 5000;"),_}function W3($){return h9("reading the local knowledge.db catalog"),new $3($,{readonly:!0})}function a($){let _=m($);try{if(_.exec(_3),b_(_)<2)_.exec(SS);if(b_(_)<3)_.exec(ZS);if(b_(_)<4)_.exec(vS);if(b_(_)<5)_.exec(yS);if(b_(_)<6)_.exec(J3);if(dS(_))nS(_);if(cS(_))iS(_);if(lS(_))rS(_);if(pS(_))oS(_);return{path:$,schema_version:b_(_)}}finally{_.close()}}function b_($){return $.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function H_($,_){return $.query(`SELECT COUNT(*) AS n FROM ${_}`).get()?.n??0}function KQ($){return`"${$.replaceAll('"','""')}"`}function m4($,_){let J=$.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get(_);return Boolean(J)}function h4($,_,J){if(!m4($,_))return!1;return $.query(`PRAGMA table_info(${KQ(_)})`).all().some((W)=>W.name===J)}function F0($,_,J,U){if(!h4($,_,J))$.exec(`ALTER TABLE ${KQ(_)} ADD COLUMN ${KQ(J)} ${U};`)}function dS($){return b_($)<7||!h4($,"knowledge_sync_changes","logical_clock")||!h4($,"knowledge_sync_changes","bundle_id")||!m4($,"knowledge_sync_table_clocks")||!m4($,"knowledge_sync_imports")}function nS($){if(!m4($,"knowledge_sync_changes"))$.exec(J3);F0($,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),F0($,"knowledge_sync_changes","bundle_id","TEXT"),$.exec(hS)}function cS($){return b_($)<8||!h4($,"wiki_pages","valid_from")||!h4($,"wiki_pages","valid_to")||!h4($,"wiki_pages","supersedes")||!h4($,"wiki_pages","superseded_by")||!h4($,"wiki_pages","confidence")||!h4($,"wiki_pages","last_verified_at")}function iS($){if(!m4($,"wiki_pages"))$.exec(_3);F0($,"wiki_pages","valid_from","TEXT"),F0($,"wiki_pages","valid_to","TEXT"),F0($,"wiki_pages","supersedes","TEXT"),F0($,"wiki_pages","superseded_by","TEXT"),F0($,"wiki_pages","confidence","REAL"),F0($,"wiki_pages","last_verified_at","TEXT"),$.exec(` UPDATE wiki_pages SET valid_from = COALESCE(valid_from, created_at), last_verified_at = COALESCE(last_verified_at, updated_at), confidence = COALESCE(confidence, 0.8) WHERE valid_from IS NULL OR last_verified_at IS NULL OR confidence IS NULL; - `),$.exec(VS)}function iN($){let _=$.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean(_?.sql&&_.sql.includes("remove_diacritics"))}function bS($){if(!N2($,"chunks_fts"))return!1;return I6($)<9||!iN($)}function ES($){if(!N2($,"chunks_fts"))return;if(iN($)){$.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}$.exec(FS)}function LY($){let _=i($);try{return{schema_version:I6(_),sources:K6(_,"sources"),source_revisions:K6(_,"source_revisions"),chunks:K6(_,"chunks"),wiki_pages:K6(_,"wiki_pages"),citations:K6(_,"citations"),indexes:K6(_,"knowledge_indexes"),runs:K6(_,"runs"),run_events:K6(_,"run_events"),redaction_findings:K6(_,"redaction_findings"),audit_events:K6(_,"audit_events"),approval_gates:K6(_,"approval_gates"),storage_objects:K6(_,"storage_objects"),embeddings:K6(_,"chunk_embeddings"),vector_entries:K6(_,"vector_index_entries"),reindex_queue:K6(_,"reindex_queue"),knowledge_machines:K6(_,"knowledge_machines"),sync_snapshots:K6(_,"knowledge_sync_snapshots"),sync_changes:K6(_,"knowledge_sync_changes"),sync_conflicts:K6(_,"knowledge_sync_conflicts"),sync_table_clocks:K6(_,"knowledge_sync_table_clocks"),sync_imports:K6(_,"knowledge_sync_imports")}}finally{_.close()}}import{chmodSync as wS,existsSync as IS,mkdirSync as rN,readFileSync as gS,statSync as kS,writeFileSync as fS}from"fs";import{dirname as CS,join as BY,relative as PS,sep as TS}from"path";import{pathToFileURL as SS}from"url";function q0($){let _=$.replace(/\\/g,"/").trim();if(!_||_.startsWith("/"))throw Error(`Invalid artifact key: ${$}`);let J=_.split("/").filter(Boolean);if(J.length===0||J.some((U)=>U==="."||U===".."))throw Error(`Invalid artifact key: ${$}`);return J.join("/")}function HY($,_){let J=PS($,_);if(J.startsWith("..")||J===".."||J.startsWith(`..${TS}`))throw Error(`Artifact path escapes root: ${_}`)}function ZS($){if(!$)return;let _={};for(let[J,U]of Object.entries($))if(typeof U==="string")_[J]=U;else if(typeof U==="number"||typeof U==="boolean")_[J]=String(U);return Object.keys(_).length>0?_:void 0}class pN{root;type="local";canRead=!0;canWrite=!0;constructor($){this.root=$;rN($,{recursive:!0,mode:448})}async put($){let _=q0($.key),J=BY(this.root,_);return HY(this.root,J),rN(CS(J),{recursive:!0,mode:448}),fS(J,$.body,{mode:384}),wS(J,384),{key:_,uri:SS(J).href,modified_at:kS(J).mtime.toISOString()}}async getText($){let _=q0($),J=BY(this.root,_);return HY(this.root,J),gS(J,"utf8")}async exists($){let _=q0($),J=BY(this.root,_);return HY(this.root,J),IS(J)}}class oN{options;type="s3";canRead=!0;canWrite=!0;client;constructor($){this.options=$;this.client=$.client}async getClient(){if(this.client)return this.client;let[{S3Client:$},{fromIni:_}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]);return this.client=new $({region:this.options.region,credentials:this.options.profile?_({profile:this.options.profile}):void 0,maxAttempts:this.options.max_attempts}),this.client}objectKey($){let _=q0($),J=this.options.prefix?q0(this.options.prefix):"";return J?`${J}/${_}`:_}async put($){let[{PutObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=q0($.key),W=this.objectKey(U);return await J.send(new _({Bucket:this.options.bucket,Key:W,Body:$.body,ContentType:$.content_type,Metadata:ZS($.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:U,uri:`s3://${this.options.bucket}/${W}`,modified_at:new Date().toISOString()}}async getText($){let[{GetObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey($),W=await J.send(new _({Bucket:this.options.bucket,Key:U}));if(!W.Body)return"";return await W.Body.transformToString()}async exists($){let[{HeadObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey($);try{return await J.send(new _({Bucket:this.options.bucket,Key:U})),!0}catch(W){let X=W instanceof Error?W.name:"";if(X==="NotFound"||X==="NoSuchKey"||X==="NotFoundError")return!1;throw W}}}function NY($,_){if($.storage.type==="s3"){if(!$.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new oN({bucket:$.storage.s3.bucket,prefix:$.storage.s3.prefix,region:$.storage.s3.region,profile:$.storage.s3.profile,max_attempts:$.storage.s3.max_attempts,server_side_encryption:$.storage.s3.server_side_encryption,kms_key_id:$.storage.s3.kms_key_id})}return new pN(_.artifactsDir)}import{createHash as cX}from"crypto";import{spawnSync as Ac}from"child_process";import{existsSync as e$,readFileSync as bc}from"fs";import{hostname as Ec}from"os";import{join as $M,resolve as LM}from"path";import{createHash as Qv,randomUUID as Yv}from"crypto";import{createHash as lS,randomUUID as nS}from"crypto";import{existsSync as FY,readdirSync as iS}from"fs";import{join as W3}from"path";import{pathToFileURL as rS}from"url";import{existsSync as vS,mkdirSync as yS,readFileSync as hS,unlinkSync as mS,writeFileSync as xS}from"fs";import{homedir as uS}from"os";import{dirname as dS,join as tN}from"path";var VY="https://knowledge.md";function h0($){let _=new URL($);if(_.protocol!=="http:"&&_.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let J=_.pathname.replace(/\/+$/,"");if(J==="/api"||J==="/api/v1")_.pathname="/";else if(J.endsWith("/api/v1"))_.pathname=J.slice(0,-7)||"/";else if(J.endsWith("/api"))_.pathname=J.slice(0,-4)||"/";return _.toString().replace(/\/+$/,"")}function S9($=process.env){if($.HASNA_KNOWLEDGE_AUTH_PATH)return $.HASNA_KNOWLEDGE_AUTH_PATH;let _=$.HASNA_KNOWLEDGE_AUTH_DIR??tN(uS(),".hasna","knowledge");return tN(_,"auth.json")}function aN($,_=process.env){return h0(_.KNOWLEDGE_API_URL??$?.hosted?.api_url??VY)}function sN($=process.env){try{let _=S9($);if(!vS(_))return null;let J=JSON.parse(hS(_,"utf8"));return typeof J.api_key==="string"&&J.api_key.length>0?J:null}catch{return null}}function eN($,_=process.env){let J=S9(_),U={...$,api_url:$.api_url?h0($.api_url):void 0,created_at:$.created_at??new Date().toISOString()};return yS(dS(J),{recursive:!0,mode:448}),xS(J,`${JSON.stringify(U,null,2)} -`,{mode:384}),U}function $3($=process.env){try{return mS(S9($)),!0}catch{return!1}}function cS($=process.env){if($.KNOWLEDGE_API_KEY)return{apiKey:$.KNOWLEDGE_API_KEY,source:"env"};if($.HASNA_KNOWLEDGE_API_KEY)return{apiKey:$.HASNA_KNOWLEDGE_API_KEY,source:"env"};let _=sN($);return _?.api_key?{apiKey:_.api_key,source:"file"}:{apiKey:null,source:"none"}}function _3($,_=process.env){let J=sN(_),U=cS(_),W=_.KNOWLEDGE_API_URL?aN($,_):J?.api_url?h0(J.api_url):aN($,_);return{authenticated:Boolean(U.apiKey),source:U.source,api_url:W,auth_path:S9(_),email:U.source==="file"?J?.email??null:null,org_id:U.source==="file"?J?.org_id??null:null,org_slug:U.source==="file"?J?.org_slug??null:null,user_id:U.source==="file"?J?.user_id??null:null,api_key_present:Boolean(U.apiKey)}}var J3=2;var U3=[{kind:"schema",prefix:"schemas/",description:"Machine-readable agent schemas and source rules."},{kind:"index",prefix:"indexes/",description:"Small orientation indexes and future shard manifests."},{kind:"log",prefix:"logs/",description:"Append-only JSONL run and wiki-maintenance log partitions."},{kind:"run",prefix:"runs/",description:"Prompt/tool/cost ledgers and generated output records."},{kind:"wiki_page",prefix:"wiki/",description:"Generated cited Markdown pages, not raw source files."},{kind:"export",prefix:"exports/",description:"Portable exports and snapshots of derived knowledge state."}],pS=["cloud.env","knowledge.db.pre-cloud-*.bak","db.json.pre-cloud-*.bak","migration-exports"];function X3($){let _=[];if(FY(W3($.home,"cloud.env")))_.push("cloud.env");if(FY(W3($.home,"migration-exports")))_.push("migration-exports");if(FY($.home)){for(let J of iS($.home))if(/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(J))_.push(J)}return _}function EJ($){let _=typeof $==="string"?Buffer.from($):Buffer.from($);return{hash:`sha256:${lS("sha256").update(_).digest("hex")}`,size_bytes:_.byteLength}}function G3($){return U3.find((J)=>$.startsWith(J.prefix))?.kind??"artifact"}function Z9($,_,J="global"){let U=RY($,_),W=$.storage.s3??null,X=W?.prefix?.replace(/^\/+|\/+$/g,"")??"",G=W?`s3://${W.bucket}/${X?`${X}/`:""}`:"",Q=r$.s3.prefix.replace(/^\/+|\/+$/g,""),Y=`s3://${r$.s3.bucket}/${Q}/`,q=$.storage.type==="s3"&&W?.bucket===r$.s3.bucket&&(W.region??null)===r$.s3.region;return{scope:J,mode:$.mode,storage_type:$.storage.type,workspace_home:_.home,local_layout:{app_path:F0,config_path:_.configPath,json_store_path:_.jsonStorePath,knowledge_db_path:_.knowledgeDbPath,directories:{artifacts:_.artifactsDir,cache:_.cacheDir,exports:_.exportsDir,indexes:_.indexesDir,logs:_.logsDir,runs:_.runsDir,schemas:_.schemasDir,wiki:_.wikiDir}},artifact_store:{type:$.storage.type,artifacts_root:$.storage.artifacts_root,uri_prefix:$.storage.type==="s3"?G:rS(`${_.artifactsDir}/`).href,s3:W?{bucket:W.bucket,prefix:X,region:W.region??null,profile:W.profile??null,server_side_encryption:W.server_side_encryption??null,kms_key_configured:Boolean(W.kms_key_id)}:null},canonical_example:{division:r$.division,app_type:r$.app_type,app:r$.app,env:r$.env,active:q,local_path:r$.local_path,s3:{bucket:r$.s3.bucket,region:r$.s3.region,profile:r$.s3.profile,prefix:Q,uri_prefix:Y,server_side_encryption:r$.s3.server_side_encryption},secrets:{env:r$.secrets.env,aws:r$.secrets.aws,s3:r$.secrets.s3,rds:r$.secrets.rds,future_rds:r$.secrets.future_rds},evidence_doc:r$.evidence_doc},hosted:{enabled:$.mode==="hosted",api_url:h0($.hosted?.api_url??VY),api_url_env:"KNOWLEDGE_API_URL",api_key_env:"KNOWLEDGE_API_KEY",auth_storage:"~/.hasna/knowledge/auth.json",registry_contract_version:J3,requires_hosted_account_for_local_use:!1},secret_handling:{workspace_env_files_supported:!1,forbidden_workspace_files:pS,forbidden_workspace_files_present:X3(_),runtime_env_keys:["HASNA_KNOWLEDGE_STORAGE_MODE","KNOWLEDGE_STORAGE_MODE","HASNA_KNOWLEDGE_DATABASE_URL","KNOWLEDGE_DATABASE_URL"],secret_ref_authority:"open-secrets",approved_secret_refs:{env:r$.secrets.env,aws:r$.secrets.aws,s3:r$.secrets.s3,rds:r$.secrets.rds},db_url_rotation_decision:{status:"blocked_without_secret_authority",reason:"No live secret mutation authority is available in @hasna/knowledge. Rotate the DB URL only through the approved secret authority if separate evidence proves the URL propagated to backups, exports, sync bundles, reports, or copied artifacts.",authority_required:!0}},source_ownership:{owner:"open-files",preferred_ref:$.sources.preferred_ref,allowed_schemes:$.sources.allowed_schemes,raw_source_bytes_stored_in_open_knowledge:!1,stores:["source refs","source revisions and hashes","citation spans","redacted extracted chunks","embeddings","generated wiki artifacts","indexes","run ledgers"],does_not_store:["raw open-files bytes","S3 object credentials","connector secrets","hosted tenant ownership state"]},private_fleet_boundary:{manifest_authority:"open-machines",source_ref_authority:"open-files",secret_ref_authority:"open-secrets",raw_private_manifest_bytes_stored_in_open_knowledge:!1,accepted_source_ref_schemes:$.sources.allowed_schemes.filter((L)=>["open-files","s3","file"].includes(L)),stores:["source refs for private manifests","redacted setup decisions","runbook summaries","citation spans into approved knowledge sources","machine setup evidence hashes"],does_not_store:["private fleet manifests","machine hostnames","machine serial numbers","sudo passwords","VNC passwords","SSH private keys","GitHub App private keys","secret values"],example_manifest_ref:"open-files://source/private-fleet-manifest/path/machines.json"},generated_artifacts:U3,scalability:{catalog:"knowledge.db tracks sources, revisions, chunks, citations, indexes, runs, and storage_objects.",indexes:"Indexes are cataloged DB rows plus sharded artifacts, not one giant index.md.",logs:"Logs use dated JSONL partitions under logs/yyyy/mm/dd.jsonl.",markdown:"Markdown pages are the readable wiki layer over DB/object-store state."},warnings:U.warnings}}function RY($,_){let J=[],U=[],W=X3(_);for(let X of W)J.push(`Forbidden Knowledge workspace file present: ${X}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`);if(!_.home.endsWith(F0))U.push(`Workspace home does not end with ${F0}: ${_.home}`);if($.storage.type==="s3"){if(!$.storage.s3?.bucket)J.push("storage.s3.bucket is required when storage.type is s3.");if(!$.storage.s3?.prefix)U.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root.");if($.mode==="local")U.push("storage.type is s3 while mode is local; this is valid for BYO S3, but hosted wrappers should set mode to hosted.")}if($.storage.type==="local"&&$.storage.s3)U.push("storage.s3 is configured but ignored while storage.type is local.");if($.sources.preferred_ref!=="open-files")U.push("sources.preferred_ref should stay open-files for durable company knowledge.");if(!$.sources.allowed_schemes.includes("open-files"))J.push("sources.allowed_schemes must include open-files.");if($.mode==="hosted"&&$.hosted?.api_url)try{h0($.hosted.api_url)}catch{J.push("hosted.api_url must be an http(s) URL when mode is hosted.")}return{ok:J.length===0,errors:J,warnings:U}}function m0($,_,J=new Date){let U=J.toISOString(),W=$.prepare(` + `),$.exec(mS)}function U3($){let _=$.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean(_?.sql&&_.sql.includes("remove_diacritics"))}function lS($){if(!m4($,"chunks_fts"))return!1;return b_($)<9||!U3($)}function rS($){if(!m4($,"chunks_fts"))return;if(U3($)){$.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}$.exec(xS)}function pS($){return b_($)<10||!m4($,"knowledge_promotion_candidates")||!m4($,"durable_knowledge_records")}function oS($){$.exec(uS)}function FQ($){let _=m($);try{return{schema_version:b_(_),sources:H_(_,"sources"),source_revisions:H_(_,"source_revisions"),chunks:H_(_,"chunks"),wiki_pages:H_(_,"wiki_pages"),citations:H_(_,"citations"),indexes:H_(_,"knowledge_indexes"),runs:H_(_,"runs"),run_events:H_(_,"run_events"),redaction_findings:H_(_,"redaction_findings"),audit_events:H_(_,"audit_events"),approval_gates:H_(_,"approval_gates"),storage_objects:H_(_,"storage_objects"),embeddings:H_(_,"chunk_embeddings"),vector_entries:H_(_,"vector_index_entries"),reindex_queue:H_(_,"reindex_queue"),knowledge_machines:H_(_,"knowledge_machines"),sync_snapshots:H_(_,"knowledge_sync_snapshots"),sync_changes:H_(_,"knowledge_sync_changes"),sync_conflicts:H_(_,"knowledge_sync_conflicts"),sync_table_clocks:H_(_,"knowledge_sync_table_clocks"),sync_imports:H_(_,"knowledge_sync_imports"),promotion_candidates:H_(_,"knowledge_promotion_candidates"),durable_records:H_(_,"durable_knowledge_records")}}finally{_.close()}}import{chmodSync as tS,existsSync as aS,mkdirSync as X3,readFileSync as sS,statSync as eS,writeFileSync as $Z}from"fs";import{dirname as _Z,join as EQ,relative as JZ,sep as WZ}from"path";import{pathToFileURL as UZ}from"url";function z4($){let _=$.replace(/\\/g,"/").trim();if(!_||_.startsWith("/"))throw Error(`Invalid artifact key: ${$}`);let J=_.split("/").filter(Boolean);if(J.length===0||J.some((U)=>U==="."||U===".."))throw Error(`Invalid artifact key: ${$}`);return J.join("/")}function MQ($,_){let J=JZ($,_);if(J.startsWith("..")||J===".."||J.startsWith(`..${WZ}`))throw Error(`Artifact path escapes root: ${_}`)}function XZ($){if(!$)return;let _={};for(let[J,U]of Object.entries($))if(typeof U==="string")_[J]=U;else if(typeof U==="number"||typeof U==="boolean")_[J]=String(U);return Object.keys(_).length>0?_:void 0}class G3{root;type="local";canRead=!0;canWrite=!0;constructor($){this.root=$;X3($,{recursive:!0,mode:448})}async put($){let _=z4($.key),J=EQ(this.root,_);return MQ(this.root,J),X3(_Z(J),{recursive:!0,mode:448}),$Z(J,$.body,{mode:384}),tS(J,384),{key:_,uri:UZ(J).href,modified_at:eS(J).mtime.toISOString()}}async getText($){let _=z4($),J=EQ(this.root,_);return MQ(this.root,J),sS(J,"utf8")}async exists($){let _=z4($),J=EQ(this.root,_);return MQ(this.root,J),aS(J)}}class Y3{options;type="s3";canRead=!0;canWrite=!0;client;constructor($){this.options=$;this.client=$.client}async getClient(){if(this.client)return this.client;let[{S3Client:$},{fromIni:_}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]);return this.client=new $({region:this.options.region,credentials:this.options.profile?_({profile:this.options.profile}):void 0,maxAttempts:this.options.max_attempts}),this.client}objectKey($){let _=z4($),J=this.options.prefix?z4(this.options.prefix):"";return J?`${J}/${_}`:_}async put($){let[{PutObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=z4($.key),W=this.objectKey(U);return await J.send(new _({Bucket:this.options.bucket,Key:W,Body:$.body,ContentType:$.content_type,Metadata:XZ($.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:U,uri:`s3://${this.options.bucket}/${W}`,modified_at:new Date().toISOString()}}async getText($){let[{GetObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey($),W=await J.send(new _({Bucket:this.options.bucket,Key:U}));if(!W.Body)return"";return await W.Body.transformToString()}async exists($){let[{HeadObjectCommand:_},J]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),U=this.objectKey($);try{return await J.send(new _({Bucket:this.options.bucket,Key:U})),!0}catch(W){let X=W instanceof Error?W.name:"";if(X==="NotFound"||X==="NoSuchKey"||X==="NotFoundError")return!1;throw W}}}function AQ($,_){if($.storage.type==="s3"){if(!$.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new Y3({bucket:$.storage.s3.bucket,prefix:$.storage.s3.prefix,region:$.storage.s3.region,profile:$.storage.s3.profile,max_attempts:$.storage.s3.max_attempts,server_side_encryption:$.storage.s3.server_side_encryption,kms_key_id:$.storage.s3.kms_key_id})}return new G3(_.artifactsDir)}import{createHash as pX}from"crypto";import{spawnSync as en}from"child_process";import{existsSync as e$,readFileSync as $c}from"fs";import{hostname as _c}from"os";import{join as FE,resolve as ZE}from"path";import{createHash as Cv,randomUUID as Pv}from"crypto";import{createHash as LZ,randomUUID as BZ}from"crypto";import{existsSync as wQ,readdirSync as HZ}from"fs";import{join as B3}from"path";import{pathToFileURL as NZ}from"url";import{existsSync as GZ,mkdirSync as YZ,readFileSync as QZ,unlinkSync as qZ,writeFileSync as zZ}from"fs";import{homedir as jZ}from"os";import{dirname as DZ,join as Q3}from"path";var bQ="https://knowledge.md";function x4($){let _=new URL($);if(_.protocol!=="http:"&&_.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let J=_.pathname.replace(/\/+$/,"");if(J==="/api"||J==="/api/v1")_.pathname="/";else if(J.endsWith("/api/v1"))_.pathname=J.slice(0,-7)||"/";else if(J.endsWith("/api"))_.pathname=J.slice(0,-4)||"/";return _.toString().replace(/\/+$/,"")}function m9($=process.env){if($.HASNA_KNOWLEDGE_AUTH_PATH)return $.HASNA_KNOWLEDGE_AUTH_PATH;let _=$.HASNA_KNOWLEDGE_AUTH_DIR??Q3(jZ(),".hasna","knowledge");return Q3(_,"auth.json")}function q3($,_=process.env){return x4(_.KNOWLEDGE_API_URL??$?.hosted?.api_url??bQ)}function z3($=process.env){try{let _=m9($);if(!GZ(_))return null;let J=JSON.parse(QZ(_,"utf8"));return typeof J.api_key==="string"&&J.api_key.length>0?J:null}catch{return null}}function j3($,_=process.env){let J=m9(_),U={...$,api_url:$.api_url?x4($.api_url):void 0,created_at:$.created_at??new Date().toISOString()};return YZ(DZ(J),{recursive:!0,mode:448}),zZ(J,`${JSON.stringify(U,null,2)} +`,{mode:384}),U}function D3($=process.env){try{return qZ(m9($)),!0}catch{return!1}}function OZ($=process.env){if($.KNOWLEDGE_API_KEY)return{apiKey:$.KNOWLEDGE_API_KEY,source:"env"};if($.HASNA_KNOWLEDGE_API_KEY)return{apiKey:$.HASNA_KNOWLEDGE_API_KEY,source:"env"};let _=z3($);return _?.api_key?{apiKey:_.api_key,source:"file"}:{apiKey:null,source:"none"}}function O3($,_=process.env){let J=z3(_),U=OZ(_),W=_.KNOWLEDGE_API_URL?q3($,_):J?.api_url?x4(J.api_url):q3($,_);return{authenticated:Boolean(U.apiKey),source:U.source,api_url:W,auth_path:m9(_),email:U.source==="file"?J?.email??null:null,org_id:U.source==="file"?J?.org_id??null:null,org_slug:U.source==="file"?J?.org_slug??null:null,user_id:U.source==="file"?J?.user_id??null:null,api_key_present:Boolean(U.apiKey)}}var L3=2;var H3=[{kind:"schema",prefix:"schemas/",description:"Machine-readable agent schemas and source rules."},{kind:"index",prefix:"indexes/",description:"Small orientation indexes and future shard manifests."},{kind:"log",prefix:"logs/",description:"Append-only JSONL run and wiki-maintenance log partitions."},{kind:"run",prefix:"runs/",description:"Prompt/tool/cost ledgers and generated output records."},{kind:"wiki_page",prefix:"wiki/",description:"Generated cited Markdown pages, not raw source files."},{kind:"export",prefix:"exports/",description:"Portable exports and snapshots of derived knowledge state."}],VZ=["cloud.env","knowledge.db.pre-cloud-*.bak","db.json.pre-cloud-*.bak","migration-exports"];function N3($){let _=[];if(wQ(B3($.home,"cloud.env")))_.push("cloud.env");if(wQ(B3($.home,"migration-exports")))_.push("migration-exports");if(wQ($.home)){for(let J of HZ($.home))if(/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(J))_.push(J)}return _}function IJ($){let _=typeof $==="string"?Buffer.from($):Buffer.from($);return{hash:`sha256:${LZ("sha256").update(_).digest("hex")}`,size_bytes:_.byteLength}}function V3($){return H3.find((J)=>$.startsWith(J.prefix))?.kind??"artifact"}function x9($,_,J="global"){let U=gQ($,_),W=$.storage.s3??null,X=W?.prefix?.replace(/^\/+|\/+$/g,"")??"",G=W?`s3://${W.bucket}/${X?`${X}/`:""}`:"",Y=r$.s3.prefix.replace(/^\/+|\/+$/g,""),Q=`s3://${r$.s3.bucket}/${Y}/`,q=$.storage.type==="s3"&&W?.bucket===r$.s3.bucket&&(W.region??null)===r$.s3.region;return{scope:J,mode:$.mode,storage_type:$.storage.type,workspace_home:_.home,local_layout:{app_path:K4,config_path:_.configPath,json_store_path:_.jsonStorePath,knowledge_db_path:_.knowledgeDbPath,directories:{artifacts:_.artifactsDir,cache:_.cacheDir,exports:_.exportsDir,indexes:_.indexesDir,logs:_.logsDir,runs:_.runsDir,schemas:_.schemasDir,wiki:_.wikiDir}},artifact_store:{type:$.storage.type,artifacts_root:$.storage.artifacts_root,uri_prefix:$.storage.type==="s3"?G:NZ(`${_.artifactsDir}/`).href,s3:W?{bucket:W.bucket,prefix:X,region:W.region??null,profile:W.profile??null,server_side_encryption:W.server_side_encryption??null,kms_key_configured:Boolean(W.kms_key_id)}:null},canonical_example:{division:r$.division,app_type:r$.app_type,app:r$.app,env:r$.env,active:q,local_path:r$.local_path,s3:{bucket:r$.s3.bucket,region:r$.s3.region,profile:r$.s3.profile,prefix:Y,uri_prefix:Q,server_side_encryption:r$.s3.server_side_encryption},secrets:{env:r$.secrets.env,aws:r$.secrets.aws,s3:r$.secrets.s3,rds:r$.secrets.rds,future_rds:r$.secrets.future_rds},evidence_doc:r$.evidence_doc},hosted:{enabled:$.mode==="hosted",api_url:x4($.hosted?.api_url??bQ),api_url_env:"KNOWLEDGE_API_URL",api_key_env:"KNOWLEDGE_API_KEY",auth_storage:"~/.hasna/knowledge/auth.json",registry_contract_version:L3,requires_hosted_account_for_local_use:!1},secret_handling:{workspace_env_files_supported:!1,forbidden_workspace_files:VZ,forbidden_workspace_files_present:N3(_),runtime_env_keys:["HASNA_KNOWLEDGE_STORAGE_MODE","KNOWLEDGE_STORAGE_MODE","HASNA_KNOWLEDGE_DATABASE_URL","KNOWLEDGE_DATABASE_URL"],secret_ref_authority:"open-secrets",approved_secret_refs:{env:r$.secrets.env,aws:r$.secrets.aws,s3:r$.secrets.s3,rds:r$.secrets.rds},db_url_rotation_decision:{status:"blocked_without_secret_authority",reason:"No live secret mutation authority is available in @hasna/knowledge. Rotate the DB URL only through the approved secret authority if separate evidence proves the URL propagated to backups, exports, sync bundles, reports, or copied artifacts.",authority_required:!0}},source_ownership:{owner:"open-files",preferred_ref:$.sources.preferred_ref,allowed_schemes:$.sources.allowed_schemes,raw_source_bytes_stored_in_open_knowledge:!1,stores:["source refs","source revisions and hashes","citation spans","redacted extracted chunks","embeddings","generated wiki artifacts","indexes","run ledgers"],does_not_store:["raw open-files bytes","S3 object credentials","connector secrets","hosted tenant ownership state"]},private_fleet_boundary:{manifest_authority:"open-machines",source_ref_authority:"open-files",secret_ref_authority:"open-secrets",raw_private_manifest_bytes_stored_in_open_knowledge:!1,accepted_source_ref_schemes:$.sources.allowed_schemes.filter((L)=>["open-files","s3","file"].includes(L)),stores:["source refs for private manifests","redacted setup decisions","runbook summaries","citation spans into approved knowledge sources","machine setup evidence hashes"],does_not_store:["private fleet manifests","machine hostnames","machine serial numbers","sudo passwords","VNC passwords","SSH private keys","GitHub App private keys","secret values"],example_manifest_ref:"open-files://source/private-fleet-manifest/path/machines.json"},generated_artifacts:H3,scalability:{catalog:"knowledge.db tracks sources, revisions, chunks, citations, indexes, runs, and storage_objects.",indexes:"Indexes are cataloged DB rows plus sharded artifacts, not one giant index.md.",logs:"Logs use dated JSONL partitions under logs/yyyy/mm/dd.jsonl.",markdown:"Markdown pages are the readable wiki layer over DB/object-store state."},warnings:U.warnings}}function gQ($,_){let J=[],U=[],W=N3(_);for(let X of W)J.push(`Forbidden Knowledge workspace file present: ${X}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`);if(!_.home.endsWith(K4))U.push(`Workspace home does not end with ${K4}: ${_.home}`);if($.storage.type==="s3"){if(!$.storage.s3?.bucket)J.push("storage.s3.bucket is required when storage.type is s3.");if(!$.storage.s3?.prefix)U.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root.");if($.mode==="local")U.push("storage.type is s3 while mode is local; this is valid for BYO S3, but hosted wrappers should set mode to hosted.")}if($.storage.type==="local"&&$.storage.s3)U.push("storage.s3 is configured but ignored while storage.type is local.");if($.sources.preferred_ref!=="open-files")U.push("sources.preferred_ref should stay open-files for durable company knowledge.");if(!$.sources.allowed_schemes.includes("open-files"))J.push("sources.allowed_schemes must include open-files.");if($.mode==="hosted"&&$.hosted?.api_url)try{x4($.hosted.api_url)}catch{J.push("hosted.api_url must be an http(s) URL when mode is hosted.")}return{ok:J.length===0,errors:J,warnings:U}}function u4($,_,J=new Date){let U=J.toISOString(),W=$.prepare(` INSERT INTO storage_objects ( id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at ) @@ -528,49 +589,49 @@ COMMIT; size_bytes = excluded.size_bytes, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);$.transaction((G)=>{for(let Q of G){let Y={key:Q.key,...Q.modified_at?{artifact_modified_at:Q.modified_at}:{},...Q.metadata??{}};W.run(nS(),Q.uri,Q.kind,Q.content_type??null,Q.hash??null,Q.size_bytes??null,JSON.stringify(Y),U,U)}})(_)}function KY($){return["deleted","stale","invalidated","reindex_required"].includes(($??"").toLowerCase())}function R1($){let _=$.status??null;return{source_owner:"open-files",source_ref:$.source_ref??null,source_uri:$.source_uri??null,source_kind:$.source_kind??null,source_revision_id:$.source_revision_id??null,revision:$.revision??null,hash:$.hash??null,chunk_id:$.chunk_id??null,start_offset:$.start_offset??null,end_offset:$.end_offset??null,status:_,read_only:!0,citation_required:!0,resolver:$.resolver??null,stale:KY(_)}}function v4($){return{source_owner:"open-files",generated_from:$.generated_from,artifact_key:$.artifact_key,source_refs:$.source_refs??[],read_only_sources:!0,citation_required:$.citation_required??!0,raw_source_bytes_stored_in_open_knowledge:!1}}function Q3($,_){return{...$,provenance:_}}import{createHash as sZ}from"crypto";import{existsSync as eZ,readFileSync as $v}from"fs";import{basename as m9}from"path";import{createHash as KZ}from"crypto";import{existsSync as MZ,readFileSync as AZ}from"fs";import{basename as bZ}from"path";import{fileURLToPath as oS}from"url";function Y3($,_){if(!$)throw Error(_);return $}function tS($){let J=$.slice(13).split("/").filter(Boolean),U=J[0];if(U!=="file"&&U!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let W=Y3(J[1],"Invalid open-files ref. Missing id.");if(U==="file"){if(J.length===2)return{kind:"open-files",uri:$,entity:U,id:W};if(J[2]==="revision"&&J[3]&&J.length===4)return{kind:"open-files",uri:$,entity:U,id:W,revision_id:decodeURIComponent(J[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let X=J.indexOf("path"),G=X>=0?decodeURIComponent(J.slice(X+1).join("/")):void 0;return{kind:"open-files",uri:$,entity:U,id:W,path:G}}function aS($){let _=new URL($),J=Y3(_.hostname,"Invalid s3 ref. Missing bucket."),U=decodeURIComponent(_.pathname.replace(/^\/+/,""));if(!U)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:$,bucket:J,key:U}}function sS($){return{kind:"file",uri:$,path:oS($)}}function eS($){let _=new URL($);return{kind:"web",uri:$,url:_.toString()}}function L4($){if($.startsWith("open-files://"))return tS($);if($.startsWith("s3://"))return aS($);if($.startsWith("file://"))return sS($);if($.startsWith("https://")||$.startsWith("http://"))return eS($);throw Error(`Unsupported source ref scheme: ${$}`)}function q3($,_=L4($)){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function z3($){let _=L4($);return _.kind==="open-files"&&_.entity==="file"?_.revision_id??null:null}import{createHash as $Z,randomUUID as AY}from"crypto";import{relative as _Z,resolve as O3,sep as JZ}from"path";function j3($){let _=process.env[$];return _==="1"||_==="true"||_==="yes"}function D3($,_){let J=$,U=new Set(J.safety?.network?.allowed_s3_buckets??[]);if($.storage.type==="s3"&&$.storage.s3?.bucket)U.add($.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let W of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((X)=>X.trim()).filter(Boolean))U.add(W);return{mode:$.mode,allowWriteRoots:[_.home,_.artifactsDir,_.cacheDir,_.exportsDir,_.indexesDir,_.logsDir,_.runsDir,_.schemasDir,_.wikiDir].map((W)=>O3(W)),readOnlySourceAccess:!0,network:{webSearchEnabled:J.safety?.network?.web_search_enabled??j3("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:J.safety?.network?.s3_reads_enabled??j3("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...U].sort()},redaction:{enabled:J.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:J.safety?.approvals?.generated_writes_require_approval??!0}}}function WZ($,_){let J=_Z($,_);return J===""||!J.startsWith("..")&&J!==".."&&!J.startsWith(`..${JZ}`)}function x0($,_){let J=O3($);if(!_.allowWriteRoots.some((U)=>WZ(U,J)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${$}`)}function K1($,_){let U=new URL($).hostname;if(!_.network.s3ReadsEnabled)throw Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1.");if(!_.network.allowedS3Buckets.includes(U))throw Error(`Safety policy denied S3 bucket "${U}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function wJ($){if(!$.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var L3=[{type:"private_key_block",severity:"high",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,replacement:"[REDACTED:private_key_block]"},{type:"secret_assignment",severity:"high",regex:/\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi,replacement:"[REDACTED:secret_assignment]"},{type:"openai_api_key",severity:"high",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:openai_api_key]"},{type:"anthropic_api_key",severity:"high",regex:new RegExp(`\\b${["sk","ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`,"g"),replacement:"[REDACTED:anthropic_api_key]"},{type:"aws_access_key_id",severity:"high",regex:/\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g,replacement:"[REDACTED:aws_access_key_id]"}];function i6($,_){if(_&&!_.redaction.enabled)return{text:$,findings:[]};let J=$,U=[];for(let W of L3)J=J.replace(W.regex,(X,...G)=>{let Q=typeof G.at(-2)==="number"?G.at(-2):J.indexOf(X);return U.push({type:W.type,severity:W.severity,start:Math.max(0,Q),end:Math.max(0,Q+X.length)}),W.replacement});return{text:J,findings:U}}function UZ($){return`audit_${$Z("sha256").update(`${$.event_type}\x00${$.action}\x00${$.target_uri??""}\x00${$.created_at??""}\x00${JSON.stringify($.metadata??{})}\x00${AY()}`).digest("hex").slice(0,24)}`}function MY($,_=0){if(_>6)return"[Truncated:depth]";if(typeof $==="string")return $.length>1000?`${$.slice(0,1000)}...[Truncated:${$.length-1000} chars]`:$;if(typeof $==="number"||typeof $==="boolean"||$===null||$===void 0)return $;if(Array.isArray($)){let J=$.slice(0,25).map((U)=>MY(U,_+1));if($.length>25)J.push(`[Truncated:${$.length-25} items]`);return J}if(typeof $==="object"){let J={},U=Object.entries($).slice(0,50);for(let[X,G]of U)J[X]=MY(G,_+1);let W=Object.keys($).length;if(W>U.length)J.__truncated_keys=W-U.length;return J}return String($)}function O6($,_){let J=_.created_at??new Date().toISOString(),U=MY(_.metadata??{}),W=UZ({..._,metadata:U,created_at:J});return $.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`,[W,_.event_type,_.action,_.target_uri??null,_.decision,JSON.stringify(U),J]),W}function v9($,_){let J=_.created_at??new Date().toISOString();for(let U of _.findings)$.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`,[`redact_${AY()}`,_.source_uri??null,_.run_id??null,U.severity,U.type,JSON.stringify({..._.metadata??{},start:U.start,end:U.end}),J]);return _.findings.length}function B3($,_){let J=_.created_at??new Date().toISOString(),U=`approval_${AY()}`;return $.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.action,_.target_uri??null,"approved",_.reason??null,_.approved_by??"local-cli",JSON.stringify(_.metadata??{}),J,J]),{id:U,status:"approved"}}var XZ=[{type:"github_token",severity:"high",regex:/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_token]"},{type:"github_pat_token",severity:"high",regex:/\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_pat_token]"},{type:"package_registry_token",severity:"high",regex:/\bnpm_[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:package_registry_token]"},{type:"context7_token",severity:"high",regex:/\bctx7sk[-][A-Za-z0-9_-]{10,}\b/g,replacement:"[REDACTED:context7_token]"},{type:"xai_api_key",severity:"high",regex:/\bxai[-][A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:xai_api_key]"},{type:"google_api_key",severity:"high",regex:/\bAIza[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:google_api_key]"}];L3.push(...XZ);function GZ($,_,J){let U=$.query(`SELECT id FROM approval_gates + `);$.transaction((G)=>{for(let Y of G){let Q={key:Y.key,...Y.modified_at?{artifact_modified_at:Y.modified_at}:{},...Y.metadata??{}};W.run(BZ(),Y.uri,Y.kind,Y.content_type??null,Y.hash??null,Y.size_bytes??null,JSON.stringify(Q),U,U)}})(_)}function kQ($){return["deleted","stale","invalidated","reindex_required"].includes(($??"").toLowerCase())}function E0($){let _=$.status??null;return{source_owner:"open-files",source_ref:$.source_ref??null,source_uri:$.source_uri??null,source_kind:$.source_kind??null,source_revision_id:$.source_revision_id??null,revision:$.revision??null,hash:$.hash??null,chunk_id:$.chunk_id??null,start_offset:$.start_offset??null,end_offset:$.end_offset??null,status:_,read_only:!0,citation_required:!0,resolver:$.resolver??null,stale:kQ(_)}}function X6($){return{source_owner:"open-files",generated_from:$.generated_from,artifact_key:$.artifact_key,source_refs:$.source_refs??[],read_only_sources:!0,citation_required:$.citation_required??!0,raw_source_bytes_stored_in_open_knowledge:!1}}function R3($,_){return{...$,provenance:_}}import{createHash as Ev}from"crypto";import{existsSync as Mv,readFileSync as Av}from"fs";import{basename as c9}from"path";import{createHash as iZ}from"crypto";import{existsSync as lZ,readFileSync as rZ}from"fs";import{basename as pZ}from"path";import{fileURLToPath as RZ}from"url";function K3($,_){if(!$)throw Error(_);return $}function KZ($){let J=$.slice(13).split("/").filter(Boolean),U=J[0];if(U!=="file"&&U!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let W=K3(J[1],"Invalid open-files ref. Missing id.");if(U==="file"){if(J.length===2)return{kind:"open-files",uri:$,entity:U,id:W};if(J[2]==="revision"&&J[3]&&J.length===4)return{kind:"open-files",uri:$,entity:U,id:W,revision_id:decodeURIComponent(J[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let X=J.indexOf("path"),G=X>=0?decodeURIComponent(J.slice(X+1).join("/")):void 0;return{kind:"open-files",uri:$,entity:U,id:W,path:G}}function FZ($){let _=new URL($),J=K3(_.hostname,"Invalid s3 ref. Missing bucket."),U=decodeURIComponent(_.pathname.replace(/^\/+/,""));if(!U)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:$,bucket:J,key:U}}function EZ($){return{kind:"file",uri:$,path:RZ($)}}function MZ($){let _=new URL($);return{kind:"web",uri:$,url:_.toString()}}function B6($){if($.startsWith("open-files://"))return KZ($);if($.startsWith("s3://"))return FZ($);if($.startsWith("file://"))return EZ($);if($.startsWith("https://")||$.startsWith("http://"))return MZ($);throw Error(`Unsupported source ref scheme: ${$}`)}function F3($,_=B6($)){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function E3($){let _=B6($);return _.kind==="open-files"&&_.entity==="file"?_.revision_id??null:null}import{createHash as AZ,randomUUID as fQ}from"crypto";import{relative as bZ,resolve as A3,sep as wZ}from"path";function M3($){let _=process.env[$];return _==="1"||_==="true"||_==="yes"}function b3($,_){let J=$,U=new Set(J.safety?.network?.allowed_s3_buckets??[]);if($.storage.type==="s3"&&$.storage.s3?.bucket)U.add($.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let W of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((X)=>X.trim()).filter(Boolean))U.add(W);return{mode:$.mode,allowWriteRoots:[_.home,_.artifactsDir,_.cacheDir,_.exportsDir,_.indexesDir,_.logsDir,_.runsDir,_.schemasDir,_.wikiDir].map((W)=>A3(W)),readOnlySourceAccess:!0,network:{webSearchEnabled:J.safety?.network?.web_search_enabled??M3("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:J.safety?.network?.s3_reads_enabled??M3("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...U].sort()},redaction:{enabled:J.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:J.safety?.approvals?.generated_writes_require_approval??!0}}}function gZ($,_){let J=bZ($,_);return J===""||!J.startsWith("..")&&J!==".."&&!J.startsWith(`..${wZ}`)}function d4($,_){let J=A3($);if(!_.allowWriteRoots.some((U)=>gZ(U,J)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${$}`)}function M0($,_){let U=new URL($).hostname;if(!_.network.s3ReadsEnabled)throw Error("Safety policy denied S3 read. Set safety.network.s3_reads_enabled=true or HASNA_KNOWLEDGE_ALLOW_S3_READS=1.");if(!_.network.allowedS3Buckets.includes(U))throw Error(`Safety policy denied S3 bucket "${U}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function fJ($){if(!$.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var w3=[{type:"private_key_block",severity:"high",regex:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,replacement:"[REDACTED:private_key_block]"},{type:"secret_assignment",severity:"high",regex:/\b(?:api[_-]?key|secret|token|password)\s*[:=]\s*['"]?[^'"\s]{8,}/gi,replacement:"[REDACTED:secret_assignment]"},{type:"openai_api_key",severity:"high",regex:/\bsk-[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:openai_api_key]"},{type:"anthropic_api_key",severity:"high",regex:new RegExp(`\\b${["sk","ant"].join("-")}-[A-Za-z0-9_-]{20,}\\b`,"g"),replacement:"[REDACTED:anthropic_api_key]"},{type:"aws_access_key_id",severity:"high",regex:/\bA(?:KIA|SIA)[A-Z0-9]{16}\b/g,replacement:"[REDACTED:aws_access_key_id]"}];function k_($,_){if(_&&!_.redaction.enabled)return{text:$,findings:[]};let J=$,U=[];for(let W of w3)J=J.replace(W.regex,(X,...G)=>{let Y=typeof G.at(-2)==="number"?G.at(-2):J.indexOf(X);return U.push({type:W.type,severity:W.severity,start:Math.max(0,Y),end:Math.max(0,Y+X.length)}),W.replacement});return{text:J,findings:U}}function kZ($){return`audit_${AZ("sha256").update(`${$.event_type}\x00${$.action}\x00${$.target_uri??""}\x00${$.created_at??""}\x00${JSON.stringify($.metadata??{})}\x00${fQ()}`).digest("hex").slice(0,24)}`}function IQ($,_=0){if(_>6)return"[Truncated:depth]";if(typeof $==="string")return $.length>1000?`${$.slice(0,1000)}...[Truncated:${$.length-1000} chars]`:$;if(typeof $==="number"||typeof $==="boolean"||$===null||$===void 0)return $;if(Array.isArray($)){let J=$.slice(0,25).map((U)=>IQ(U,_+1));if($.length>25)J.push(`[Truncated:${$.length-25} items]`);return J}if(typeof $==="object"){let J={},U=Object.entries($).slice(0,50);for(let[X,G]of U)J[X]=IQ(G,_+1);let W=Object.keys($).length;if(W>U.length)J.__truncated_keys=W-U.length;return J}return String($)}function __($,_){let J=_.created_at??new Date().toISOString(),U=IQ(_.metadata??{}),W=kZ({..._,metadata:U,created_at:J});return $.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`,[W,_.event_type,_.action,_.target_uri??null,_.decision,JSON.stringify(U),J]),W}function CJ($,_){let J=_.created_at??new Date().toISOString();for(let U of _.findings)$.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`,[`redact_${fQ()}`,_.source_uri??null,_.run_id??null,U.severity,U.type,JSON.stringify({..._.metadata??{},start:U.start,end:U.end}),J]);return _.findings.length}function u9($,_){let J=_.created_at??new Date().toISOString(),U=`approval_${fQ()}`;return $.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.action,_.target_uri??null,"approved",_.reason??null,_.approved_by??"local-cli",JSON.stringify(_.metadata??{}),J,J]),{id:U,status:"approved"}}var IZ=[{type:"github_token",severity:"high",regex:/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_token]"},{type:"github_pat_token",severity:"high",regex:/\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g,replacement:"[REDACTED:github_pat_token]"},{type:"package_registry_token",severity:"high",regex:/\bnpm_[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:package_registry_token]"},{type:"context7_token",severity:"high",regex:/\bctx7sk[-][A-Za-z0-9_-]{10,}\b/g,replacement:"[REDACTED:context7_token]"},{type:"xai_api_key",severity:"high",regex:/\bxai[-][A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:xai_api_key]"},{type:"google_api_key",severity:"high",regex:/\bAIza[A-Za-z0-9_-]{20,}\b/g,replacement:"[REDACTED:google_api_key]"}];w3.push(...IZ);function fZ($,_,J){let U=$.query(`SELECT id FROM approval_gates WHERE action = ? AND status = 'approved' AND (target_uri IS NULL OR target_uri = ? OR ? IS NULL) - ORDER BY updated_at DESC LIMIT 1`).get(_,J??null,J??null);return Boolean(U)}function H3($,_,J,U){let W=J==="generated_write"&&_.approvals.generatedWritesRequireApproval,X=!W||GZ($,J,U);return{action:J,target_uri:U??null,approval_required:W,approved:X,decision:X?"allow":"requires_approval"}}import{createHash as QZ}from"crypto";import{realpathSync as YZ}from"fs";import{homedir as qZ,tmpdir as zZ}from"os";var V2=String.raw`[^\s"'<>),\]}]`,EY=String.raw`[^/\\\s"'<>]+`,F3=/file:\/\/[^\s"'<>),\]}]+/gi,jZ=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,R3=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,K3=new RegExp(String.raw`/(?:home|Users)/${EY}/(?:workspace|Workspace)/${V2}*`,"g"),OZ=[new RegExp(String.raw`/(?:home|Users)/${EY}(?:/${V2}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${V2}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${V2}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,A3=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,DZ=new Set(["content_base64"]);function LZ($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function BZ($){return $.length>=4&&$!=="/"&&!/^[A-Za-z]:[\\/]?$/.test($)}var N3=null,bY=[];function HZ(){let $=new Set;for(let J of[qZ(),zZ()]){if(!J)continue;$.add(J);try{$.add(YZ(J))}catch{}}let _=[...$].sort().join("\x00");if(_===N3)return bY;return N3=_,bY=[...$].filter(BZ).sort((J,U)=>U.length-J.length).map((J)=>new RegExp(`${LZ(J)}(?:[/\\\\]${V2}*)?`,"g")),bY}function B4($){return QZ("sha256").update($).digest("hex").slice(0,12)}function NZ($){return $.length<=80?$:`${$.slice(0,77)}...`}function V3($){return/(?:^|\/)\.hasna(?:\/|$)/i.test($)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test($)||/\bmigration-exports\//i.test($)}function VZ($,_,J,U){for(let W of $.matchAll(F3)){let X=W[0];if(!J.allowFileSourceRefs||V3(X))U.push({type:V3(X)?"private_file_uri":"local_file_uri",severity:"high",path:_,preview:NZ(X.replace(/^file:\/\/.*/,`[redacted:file-uri:${B4(X)}]`))})}for(let W of $.matchAll(R3))U.push({type:"private_hasna_path",severity:"high",path:_,preview:`[redacted:.hasna:${B4(W[0])}]`});for(let W of $.matchAll(M3))U.push({type:W[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:_,preview:`[redacted:${B4(W[0])}]`});for(let W of $.matchAll(A3))U.push({type:"database_url",severity:"high",path:_,preview:`[redacted:database-url:${B4(W[0])}]`});if(!J.allowPrivateWorkspaceRefs)for(let W of $.matchAll(K3))U.push({type:"private_workspace_path",severity:"medium",path:_,preview:`[redacted:workspace:${B4(W[0])}]`})}function FZ($,_={},J="$"){let U=[],W=(X,G)=>{if(typeof X==="string"){VZ(X,G,_,U);return}if(!X||typeof X!=="object")return;if(Array.isArray(X)){X.forEach((Q,Y)=>W(Q,`${G}[${Y}]`));return}for(let[Q,Y]of Object.entries(X))W(Y,`${G}.${Q}`)};return W($,J),U}function F2($,_={}){let J=FZ($,_);if(J.length===0)return;let U=new Map;for(let X of J)U.set(X.type,(U.get(X.type)??0)+1);let W=[...U.entries()].map(([X,G])=>`${X}:${G}`).join(", ");throw Error(`Knowledge private-ref lint failed (${W}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function RZ($){let _=i6($).text.replace(A3,(J)=>`[REDACTED:database-url:${B4(J)}]`).replace(F3,(J)=>`[REDACTED:local-file-uri:${B4(J)}]`).replace(jZ,(J)=>`[REDACTED:local-hasna-path:${B4(J)}]`).replace(K3,(J)=>`[REDACTED:private-workspace:${B4(J)}]`);for(let J of[...HZ(),...OZ])_=_.replace(J,(U)=>`[REDACTED:local-path:${B4(U)}]`);return _.replace(R3,(J)=>`[REDACTED:hasna-path:${B4(J)}]`).replace(M3,(J)=>`[REDACTED:private-artifact:${B4(J)}]`)}function z6($){if(typeof $==="string")return RZ($);if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((J)=>z6(J));let _={};for(let[J,U]of Object.entries($))_[J]=DZ.has(J)?U:z6(U);return _}var EZ=20971520,b3=1e4,wZ=10;function IY($,_){return`${$}_${KZ("sha256").update(_).digest("hex").slice(0,20)}`}function R2($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function d$($){return typeof $==="string"&&$.length>0?$:void 0}function IZ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function gZ($){let _=d$($.source_ref)??d$($.source_uri)??d$($.uri);if(_)return _;let J=d$($.file_id);if(J){let X=d$($.revision_id)??d$($.revision),G=`open-files://file/${encodeURIComponent(J)}`;return X?`${G}/revision/${encodeURIComponent(X)}`:G}let U=d$($.source_id),W=d$($.path);if(U&&W)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(W)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function kZ($,_){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function fZ($){let _=d$($.extracted_text)??d$($.text)??d$($.content_text)??d$($.markdown);if(_!==void 0)return _;let J=$.content;return typeof J==="string"?J:null}function CZ($){let _=d$($.extracted_text_ref)??d$($.extracted_text_uri)??d$($.text_ref);if(_)return _;let J=R2($.content);return d$(J?.extracted_text_ref)??d$(J?.extracted_text_uri)??null}function PZ($){let _=d$($.path);return d$($.title)??d$($.name)??(_?bZ(_):null)}function TZ($){return d$($.hash)??d$($.checksum)??d$($.sha256)??null}var E3=new Set(["text","content","content_text","extracted_text","markdown","raw","raw_text","raw_bytes","raw_content","raw_body","raw_file","source_raw","source_raw_bytes","source_bytes","source_content","source_body","file_bytes","file_content","content_bytes","content_base64","document_bytes","document_content","document_base64","binary","binary_content","binary_base64","bytes","body","blob","data","payload"]);function w3($){return $.toLowerCase().replace(/[\s-]+/g,"_")}function wY($){if(Array.isArray($))return $.map((U)=>wY(U));let _=R2($);if(!_)return $;let J={};for(let[U,W]of Object.entries(_)){if(E3.has(w3(U)))continue;J[U]=wY(W)}return J}function SZ($,_,J){return d$($.revision_id)??d$($.revision)??d$($.version_id)??(_.kind==="open-files"?_.revision_id:void 0)??J??d$($.updated_at)??"current"}function ZZ($,_){let J={};for(let[U,W]of Object.entries($)){if(E3.has(w3(U)))continue;J[U]=z6(wY(W))}return J.source_ref=_.sourceRef,J.source_uri=_.sourceUri,J.status=_.status,J}function vZ($,_,J={}){let U=gZ($);F2(U,{allowFileSourceRefs:J.allowFileSourceRefs===!0});let W=L4(U),X=kZ(U,W),G=TZ($),Q=d$($.status)??"active";return{raw:$,sourceRef:U,sourceUri:X,kind:W.kind,title:PZ($),revision:SZ($,W,G),hash:G,extractedTextUri:CZ($),text:fZ($),metadata:ZZ($,{sourceRef:U,sourceUri:X,status:Q}),acl:$.permissions??$.acl??{},status:Q,updatedAt:d$($.updated_at)??_}}function yZ($){let _=$.trim();if(!_)return[];if(_.startsWith("[")){let J=JSON.parse(_);if(!Array.isArray(J))throw Error("Manifest array parse failed.");return J.map((U)=>{let W=R2(U);if(!W)throw Error("Manifest array entries must be objects.");return W})}if(_.startsWith("{"))try{let J=JSON.parse(_),U=R2(J);if(!U)throw Error("Manifest object parse failed.");if(Array.isArray(U.items))return U.items.map((W)=>{let X=R2(W);if(!X)throw Error("Manifest items entries must be objects.");return X});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(J){let U=_.split(/\r?\n/).filter((W)=>W.trim().length>0);if(U.length<=1)throw J;return U.map((W)=>{let X=R2(JSON.parse(W));if(!X)throw Error("Manifest JSONL entries must be objects.");return X})}return _.split(/\r?\n/).filter((J)=>J.trim().length>0).map((J)=>{let U=R2(JSON.parse(J));if(!U)throw Error("Manifest JSONL entries must be objects.");return U})}async function hZ($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 manifest URI: ${$}`);if(J)K1($,J);let[{S3Client:G,GetObjectCommand:Q},{fromIni:Y}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Y({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Q({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function mZ($,_,J,U=EZ){let W=$.startsWith("s3://")?await hZ($,_,J):(()=>{if(!MZ($))throw Error(`Manifest not found: ${$}`);return AZ($,"utf8")})(),X=Buffer.byteLength(W);if(X>U)throw Error(`Manifest input is too large: ${X} bytes exceeds ${U} byte limit.`);return W}function xZ($,_,J){let U=$.replace(/\r\n/g,` -`);if(!U.trim())return[];let W=[],X=0;while(X),\]}]`,PQ=String.raw`[^/\\\s"'<>]+`,f3=/file:\/\/[^\s"'<>),\]}]+/gi,ZZ=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,C3=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,P3=new RegExp(String.raw`/(?:home|Users)/${PQ}/(?:workspace|Workspace)/${F1}*`,"g"),vZ=[new RegExp(String.raw`/(?:home|Users)/${PQ}(?:/${F1}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${F1}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${F1}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,S3=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,yZ=new Set(["content_base64"]);function hZ($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mZ($){return $.length>=4&&$!=="/"&&!/^[A-Za-z]:[\\/]?$/.test($)}var k3=null,CQ=[];function xZ(){let $=new Set;for(let J of[TZ(),SZ()]){if(!J)continue;$.add(J);try{$.add(PZ(J))}catch{}}let _=[...$].sort().join("\x00");if(_===k3)return CQ;return k3=_,CQ=[...$].filter(mZ).sort((J,U)=>U.length-J.length).map((J)=>new RegExp(`${hZ(J)}(?:[/\\\\]${F1}*)?`,"g")),CQ}function H6($){return CZ("sha256").update($).digest("hex").slice(0,12)}function uZ($){return $.length<=80?$:`${$.slice(0,77)}...`}function I3($){return/(?:^|\/)\.hasna(?:\/|$)/i.test($)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test($)||/\bmigration-exports\//i.test($)}function dZ($,_,J,U){for(let W of $.matchAll(f3)){let X=W[0];if(!J.allowFileSourceRefs||I3(X))U.push({type:I3(X)?"private_file_uri":"local_file_uri",severity:"high",path:_,preview:uZ(X.replace(/^file:\/\/.*/,`[redacted:file-uri:${H6(X)}]`))})}for(let W of $.matchAll(C3))U.push({type:"private_hasna_path",severity:"high",path:_,preview:`[redacted:.hasna:${H6(W[0])}]`});for(let W of $.matchAll(T3))U.push({type:W[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:_,preview:`[redacted:${H6(W[0])}]`});for(let W of $.matchAll(S3))U.push({type:"database_url",severity:"high",path:_,preview:`[redacted:database-url:${H6(W[0])}]`});if(!J.allowPrivateWorkspaceRefs)for(let W of $.matchAll(P3))U.push({type:"private_workspace_path",severity:"medium",path:_,preview:`[redacted:workspace:${H6(W[0])}]`})}function nZ($,_={},J="$"){let U=[],W=(X,G)=>{if(typeof X==="string"){dZ(X,G,_,U);return}if(!X||typeof X!=="object")return;if(Array.isArray(X)){X.forEach((Y,Q)=>W(Y,`${G}[${Q}]`));return}for(let[Y,Q]of Object.entries(X))W(Q,`${G}.${Y}`)};return W($,J),U}function E1($,_={}){let J=nZ($,_);if(J.length===0)return;let U=new Map;for(let X of J)U.set(X.type,(U.get(X.type)??0)+1);let W=[...U.entries()].map(([X,G])=>`${X}:${G}`).join(", ");throw Error(`Knowledge private-ref lint failed (${W}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function cZ($){let _=k_($).text.replace(S3,(J)=>`[REDACTED:database-url:${H6(J)}]`).replace(f3,(J)=>`[REDACTED:local-file-uri:${H6(J)}]`).replace(ZZ,(J)=>`[REDACTED:local-hasna-path:${H6(J)}]`).replace(P3,(J)=>`[REDACTED:private-workspace:${H6(J)}]`);for(let J of[...xZ(),...vZ])_=_.replace(J,(U)=>`[REDACTED:local-path:${H6(U)}]`);return _.replace(C3,(J)=>`[REDACTED:hasna-path:${H6(J)}]`).replace(T3,(J)=>`[REDACTED:private-artifact:${H6(J)}]`)}function j_($){if(typeof $==="string")return cZ($);if(!$||typeof $!=="object")return $;if(Array.isArray($))return $.map((J)=>j_(J));let _={};for(let[J,U]of Object.entries($))_[J]=yZ.has(J)?U:j_(U);return _}var oZ=20971520,Z3=1e4,tZ=10;function SQ($,_){return`${$}_${iZ("sha256").update(_).digest("hex").slice(0,20)}`}function M1($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function d$($){return typeof $==="string"&&$.length>0?$:void 0}function aZ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function sZ($){let _=d$($.source_ref)??d$($.source_uri)??d$($.uri);if(_)return _;let J=d$($.file_id);if(J){let X=d$($.revision_id)??d$($.revision),G=`open-files://file/${encodeURIComponent(J)}`;return X?`${G}/revision/${encodeURIComponent(X)}`:G}let U=d$($.source_id),W=d$($.path);if(U&&W)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(W)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function eZ($,_){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function $v($){let _=d$($.extracted_text)??d$($.text)??d$($.content_text)??d$($.markdown);if(_!==void 0)return _;let J=$.content;return typeof J==="string"?J:null}function _v($){let _=d$($.extracted_text_ref)??d$($.extracted_text_uri)??d$($.text_ref);if(_)return _;let J=M1($.content);return d$(J?.extracted_text_ref)??d$(J?.extracted_text_uri)??null}function Jv($){let _=d$($.path);return d$($.title)??d$($.name)??(_?pZ(_):null)}function Wv($){return d$($.hash)??d$($.checksum)??d$($.sha256)??null}var v3=new Set(["text","content","content_text","extracted_text","markdown","raw","raw_text","raw_bytes","raw_content","raw_body","raw_file","source_raw","source_raw_bytes","source_bytes","source_content","source_body","file_bytes","file_content","content_bytes","content_base64","document_bytes","document_content","document_base64","binary","binary_content","binary_base64","bytes","body","blob","data","payload"]);function y3($){return $.toLowerCase().replace(/[\s-]+/g,"_")}function TQ($){if(Array.isArray($))return $.map((U)=>TQ(U));let _=M1($);if(!_)return $;let J={};for(let[U,W]of Object.entries(_)){if(v3.has(y3(U)))continue;J[U]=TQ(W)}return J}function Uv($,_,J){return d$($.revision_id)??d$($.revision)??d$($.version_id)??(_.kind==="open-files"?_.revision_id:void 0)??J??d$($.updated_at)??"current"}function Xv($,_){let J={};for(let[U,W]of Object.entries($)){if(v3.has(y3(U)))continue;J[U]=j_(TQ(W))}return J.source_ref=_.sourceRef,J.source_uri=_.sourceUri,J.status=_.status,J}function Gv($,_,J={}){let U=sZ($);E1(U,{allowFileSourceRefs:J.allowFileSourceRefs===!0});let W=B6(U),X=eZ(U,W),G=Wv($),Y=d$($.status)??"active";return{raw:$,sourceRef:U,sourceUri:X,kind:W.kind,title:Jv($),revision:Uv($,W,G),hash:G,extractedTextUri:_v($),text:$v($),metadata:Xv($,{sourceRef:U,sourceUri:X,status:Y}),acl:$.permissions??$.acl??{},status:Y,updatedAt:d$($.updated_at)??_}}function Yv($){let _=$.trim();if(!_)return[];if(_.startsWith("[")){let J=JSON.parse(_);if(!Array.isArray(J))throw Error("Manifest array parse failed.");return J.map((U)=>{let W=M1(U);if(!W)throw Error("Manifest array entries must be objects.");return W})}if(_.startsWith("{"))try{let J=JSON.parse(_),U=M1(J);if(!U)throw Error("Manifest object parse failed.");if(Array.isArray(U.items))return U.items.map((W)=>{let X=M1(W);if(!X)throw Error("Manifest items entries must be objects.");return X});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(J){let U=_.split(/\r?\n/).filter((W)=>W.trim().length>0);if(U.length<=1)throw J;return U.map((W)=>{let X=M1(JSON.parse(W));if(!X)throw Error("Manifest JSONL entries must be objects.");return X})}return _.split(/\r?\n/).filter((J)=>J.trim().length>0).map((J)=>{let U=M1(JSON.parse(J));if(!U)throw Error("Manifest JSONL entries must be objects.");return U})}async function Qv($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 manifest URI: ${$}`);if(J)M0($,J);let[{S3Client:G,GetObjectCommand:Y},{fromIni:Q}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Q({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Y({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function qv($,_,J,U=oZ){let W=$.startsWith("s3://")?await Qv($,_,J):(()=>{if(!lZ($))throw Error(`Manifest not found: ${$}`);return rZ($,"utf8")})(),X=Buffer.byteLength(W);if(X>U)throw Error(`Manifest input is too large: ${X} bytes exceeds ${U} byte limit.`);return W}function zv($,_,J){let U=$.replace(/\r\n/g,` +`);if(!U.trim())return[];let W=[],X=0;while(XX+Math.floor(_*0.5))Q=N+(N===q?2:1)}let Y=U.slice(X,Q).trim();if(Y)W.push({ordinal:W.length,text:Y,startOffset:X,endOffset:Q});if(Q>=U.length)break;X=Math.max(0,Q-J)}return W}function uZ($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function dZ($,_){let J=$.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(_);for(let U of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);return $.run("DELETE FROM chunks WHERE source_revision_id = ?",[_]),J.length}function cZ($,_,J){let U=IY("src",_.sourceUri);$.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) +`,G),L=U.lastIndexOf(". ",G),N=Math.max(q,L);if(N>X+Math.floor(_*0.5))Y=N+(N===q?2:1)}let Q=U.slice(X,Y).trim();if(Q)W.push({ordinal:W.length,text:Q,startOffset:X,endOffset:Y});if(Y>=U.length)break;X=Math.max(0,Y-J)}return W}function jv($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function Dv($,_){let J=$.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(_);for(let U of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);return $.run("DELETE FROM chunks WHERE source_revision_id = ?",[_]),J.length}function Ov($,_,J){let U=SQ("src",_.sourceUri);$.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(uri) DO UPDATE SET kind = excluded.kind, title = excluded.title, metadata_json = excluded.metadata_json, acl_json = excluded.acl_json, - updated_at = excluded.updated_at`,[U,_.sourceUri,_.kind,_.title,JSON.stringify(_.metadata),JSON.stringify(_.acl??{}),J,_.updatedAt]);let W=$.query("SELECT id FROM sources WHERE uri = ?").get(_.sourceUri);if(!W)throw Error(`Failed to upsert source: ${_.sourceUri}`);return W.id}function lZ($,_,J,U){let W=IY("rev",`${_}\x00${J.revision}`);$.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) + updated_at = excluded.updated_at`,[U,_.sourceUri,_.kind,_.title,JSON.stringify(_.metadata),JSON.stringify(_.acl??{}),J,_.updatedAt]);let W=$.query("SELECT id FROM sources WHERE uri = ?").get(_.sourceUri);if(!W)throw Error(`Failed to upsert source: ${_.sourceUri}`);return W.id}function Lv($,_,J,U){let W=SQ("rev",`${_}\x00${J.revision}`);$.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(source_id, revision) DO UPDATE SET hash = excluded.hash, extracted_text_uri = excluded.extracted_text_uri, - metadata_json = excluded.metadata_json`,[W,_,J.revision,J.hash,J.extractedTextUri,JSON.stringify(J.metadata),U]);let X=$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(_,J.revision);if(!X)throw Error(`Failed to upsert source revision: ${J.sourceRef}`);return X.id}function nZ($,_,J,U,W,X,G){if(!J.text||J.status.toLowerCase()==="deleted")return{chunksInserted:0,redactions:0};let Q=i6(J.text,G);if(Q.findings.length>0)v9($,{source_uri:J.sourceUri,findings:Q.findings,metadata:{source_ref:J.sourceRef,revision:J.revision},created_at:U}),O6($,{event_type:"redaction",action:"source_text_redact",target_uri:J.sourceUri,decision:"redacted",metadata:{findings:Q.findings.length,source_ref:J.sourceRef,revision:J.revision},created_at:U});let Y=xZ(Q.text,W,X);for(let q of Y){let L=IY("chk",`${_}\x00${q.ordinal}\x00${q.text}`),N=R1({source_ref:J.sourceRef,source_uri:J.sourceUri,source_kind:J.kind,source_revision_id:_,revision:J.revision,hash:J.hash,chunk_id:L,start_offset:q.startOffset,end_offset:q.endOffset,status:J.status,resolver:"open-files-read-only"}),F=Q3({source_ref:J.sourceRef,source_uri:J.sourceUri,source_kind:J.kind,source_revision_id:_,revision:J.revision,hash:J.hash,status:J.status,path:d$(J.raw.path)??null,mime:d$(J.raw.mime)??d$(J.raw.content_type)??null,size:IZ(J.raw.size)??null},N);$.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[L,_,"source",q.ordinal,q.text,uZ(q.text),q.startOffset,q.endOffset,JSON.stringify(F),U]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[L,q.text,J.title??"",J.sourceUri])}return{chunksInserted:Y.length,redactions:Q.findings.length}}async function I3($){let _=$.now??new Date;if($.safetyPolicy)x0($.dbPath,$.safetyPolicy);G$($.dbPath);let J=await mZ($.input,$.config,$.safetyPolicy,$.maxInputBytes),U=yZ(J),W=$.maxItems??b3;if(U.length>W)throw Error(`Manifest contains too many items: ${U.length} exceeds ${W} item limit.`);return K2({dbPath:$.dbPath,items:U,sourceLabel:$.input,allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")===!0,safetyPolicy:$.safetyPolicy,now:_,maxChunkChars:$.maxChunkChars,chunkOverlapChars:$.chunkOverlapChars,maxItems:$.maxItems})}async function K2($){let _=($.now??new Date).toISOString(),J=$.maxChunkChars??4000,U=$.chunkOverlapChars??200,W=$.maxItems??b3;if(J<500)throw Error("maxChunkChars must be at least 500.");if(U<0||U>=J)throw Error("chunkOverlapChars must be less than maxChunkChars.");if($.items.length>W)throw Error(`Manifest contains too many items: ${$.items.length} exceeds ${W} item limit.`);if($.safetyPolicy)x0($.dbPath,$.safetyPolicy);G$($.dbPath);let X=i($.dbPath);try{return X.transaction(()=>{let Q=new Set,Y=new Set,q=0,L=0,N=0,F=0,B=[];O6(X,{event_type:"source_read",action:$.readAction??($.sourceLabel.startsWith("s3://")?"s3_manifest_read":"local_manifest_read"),target_uri:$.sourceLabel,decision:"allow",metadata:{items:$.items.length,read_only:!0},created_at:_});for(let H of $.items){let V=vZ(H,_,{allowFileSourceRefs:$.allowFileSourceRefs});if(B.length0)return U}return null}function g3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function iZ($,_){let J=$.mode;if(typeof J==="string"&&J!=="read_only")throw Error(`Source resolver denied ${_}. Permission mode is ${J}, expected read_only.`);let U=$.denied_purposes;if(Array.isArray(U)&&U.includes(_))throw Error(`Source resolver denied ${_}. Purpose is explicitly denied.`);let W=$.allowed_purposes;if(Array.isArray(W)&&W.length>0&&!W.includes(_))throw Error(`Source resolver denied ${_}. Allowed purposes: ${W.join(", ")}`)}function rZ($,_,J){if(!_)return J;try{let U=L4($);if(U.kind==="open-files"&&U.entity==="file")return`${$}/revision/${encodeURIComponent(_.revision)}`}catch{return J}return J}function pZ($,_,J){return $.query(`SELECT id, uri, kind, title, metadata_json, acl_json, updated_at + metadata_json = excluded.metadata_json`,[W,_,J.revision,J.hash,J.extractedTextUri,JSON.stringify(J.metadata),U]);let X=$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(_,J.revision);if(!X)throw Error(`Failed to upsert source revision: ${J.sourceRef}`);return X.id}function Bv($,_,J,U,W,X,G){if(!J.text||J.status.toLowerCase()==="deleted")return{chunksInserted:0,redactions:0};let Y=k_(J.text,G);if(Y.findings.length>0)CJ($,{source_uri:J.sourceUri,findings:Y.findings,metadata:{source_ref:J.sourceRef,revision:J.revision},created_at:U}),__($,{event_type:"redaction",action:"source_text_redact",target_uri:J.sourceUri,decision:"redacted",metadata:{findings:Y.findings.length,source_ref:J.sourceRef,revision:J.revision},created_at:U});let Q=zv(Y.text,W,X);for(let q of Q){let L=SQ("chk",`${_}\x00${q.ordinal}\x00${q.text}`),N=E0({source_ref:J.sourceRef,source_uri:J.sourceUri,source_kind:J.kind,source_revision_id:_,revision:J.revision,hash:J.hash,chunk_id:L,start_offset:q.startOffset,end_offset:q.endOffset,status:J.status,resolver:"open-files-read-only"}),R=R3({source_ref:J.sourceRef,source_uri:J.sourceUri,source_kind:J.kind,source_revision_id:_,revision:J.revision,hash:J.hash,status:J.status,path:d$(J.raw.path)??null,mime:d$(J.raw.mime)??d$(J.raw.content_type)??null,size:aZ(J.raw.size)??null},N);$.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[L,_,"source",q.ordinal,q.text,jv(q.text),q.startOffset,q.endOffset,JSON.stringify(R),U]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[L,q.text,J.title??"",J.sourceUri])}return{chunksInserted:Q.length,redactions:Y.findings.length}}async function h3($){let _=$.now??new Date;if($.safetyPolicy)d4($.dbPath,$.safetyPolicy);a($.dbPath);let J=await qv($.input,$.config,$.safetyPolicy,$.maxInputBytes),U=Yv(J),W=$.maxItems??Z3;if(U.length>W)throw Error(`Manifest contains too many items: ${U.length} exceeds ${W} item limit.`);return A1({dbPath:$.dbPath,items:U,sourceLabel:$.input,allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")===!0,safetyPolicy:$.safetyPolicy,now:_,maxChunkChars:$.maxChunkChars,chunkOverlapChars:$.chunkOverlapChars,maxItems:$.maxItems})}async function A1($){let _=($.now??new Date).toISOString(),J=$.maxChunkChars??4000,U=$.chunkOverlapChars??200,W=$.maxItems??Z3;if(J<500)throw Error("maxChunkChars must be at least 500.");if(U<0||U>=J)throw Error("chunkOverlapChars must be less than maxChunkChars.");if($.items.length>W)throw Error(`Manifest contains too many items: ${$.items.length} exceeds ${W} item limit.`);if($.safetyPolicy)d4($.dbPath,$.safetyPolicy);a($.dbPath);let X=m($.dbPath);try{return X.transaction(()=>{let Y=new Set,Q=new Set,q=0,L=0,N=0,R=0,B=[];__(X,{event_type:"source_read",action:$.readAction??($.sourceLabel.startsWith("s3://")?"s3_manifest_read":"local_manifest_read"),target_uri:$.sourceLabel,decision:"allow",metadata:{items:$.items.length,read_only:!0},created_at:_});for(let H of $.items){let V=Gv(H,_,{allowFileSourceRefs:$.allowFileSourceRefs});if(B.length0)return U}return null}function m3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function Hv($,_){let J=$.mode;if(typeof J==="string"&&J!=="read_only")throw Error(`Source resolver denied ${_}. Permission mode is ${J}, expected read_only.`);let U=$.denied_purposes;if(Array.isArray(U)&&U.includes(_))throw Error(`Source resolver denied ${_}. Purpose is explicitly denied.`);let W=$.allowed_purposes;if(Array.isArray(W)&&W.length>0&&!W.includes(_))throw Error(`Source resolver denied ${_}. Allowed purposes: ${W.join(", ")}`)}function Nv($,_,J){if(!_)return J;try{let U=B6($);if(U.kind==="open-files"&&U.entity==="file")return`${$}/revision/${encodeURIComponent(_.revision)}`}catch{return J}return J}function Vv($,_,J){return $.query(`SELECT id, uri, kind, title, metadata_json, acl_json, updated_at FROM sources WHERE uri = ? OR uri = ? ORDER BY CASE WHEN uri = ? THEN 0 ELSE 1 END - LIMIT 1`).get(_,J,_)??null}function oZ($,_,J){if(J)return $.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at + LIMIT 1`).get(_,J,_)??null}function Rv($,_,J){if(J)return $.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at FROM source_revisions WHERE source_id = ? AND revision = ? LIMIT 1`).get(_,J)??null;return $.query(`SELECT id, revision, hash, extracted_text_uri, metadata_json, created_at FROM source_revisions WHERE source_id = ? ORDER BY created_at DESC, revision DESC - LIMIT 1`).get(_)??null}function tZ($,_){if(!_)return 0;return $.query("SELECT COUNT(*) AS n FROM chunks WHERE source_revision_id = ?").get(_)?.n??0}function aZ($,_,J){if(!_||J<=0)return[];return $.query(`SELECT id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json + LIMIT 1`).get(_)??null}function Kv($,_){if(!_)return 0;return $.query("SELECT COUNT(*) AS n FROM chunks WHERE source_revision_id = ?").get(_)?.n??0}function Fv($,_,J){if(!_||J<=0)return[];return $.query(`SELECT id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json FROM chunks WHERE source_revision_id = ? ORDER BY ordinal ASC - LIMIT ?`).all(_,J)}async function h9($){let _=$.purpose??"knowledge_answer",J=Math.max(0,Math.min($.limit??10,100)),U=($.now??new Date).toISOString(),W=L4($.sourceRef),X=q3($.sourceRef,W),G=z3($.sourceRef);if($.safetyPolicy){if(!$.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");x0($.dbPath,$.safetyPolicy)}G$($.dbPath);let Q=i($.dbPath);try{return Q.transaction(()=>{let Y=pZ(Q,X,$.sourceRef);if(!Y)return O6(Q,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:$.sourceRef,decision:"allow",metadata:{purpose:_,read_only:!0,source_uri:X},created_at:U}),{source_ref:$.sourceRef,source_uri:X,purpose:_,read_only:!0,resolved:!1,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:null,revision:null,content:{mime:null,size:null,hash:null,text_available:!1,chunks_total:0,chunks_returned:0,char_count_returned:0,extracted_text_ref:null,bytes_available:!1,bytes_exposed:!1},chunks:[],citations:[]};let q=y9(Y.metadata_json),L=y9(Y.acl_json);try{iZ(L,_)}catch(b){throw O6(Q,{event_type:"source_read",action:"open_files_resolve",target_uri:$.sourceRef,decision:"deny",metadata:{purpose:_,read_only:!0,source_uri:Y.uri,error:b instanceof Error?b.message:String(b)},created_at:U}),b}let N=oZ(Q,Y.id,G),F=y9(N?.metadata_json),B=tZ(Q,N?.id??null),H=aZ(Q,N?.id??null,J),V=rZ(Y.uri,N,$.sourceRef),R=H.map((b)=>{let I=y9(b.metadata_json),v={resolver:"open-files-read-only",mode:"local_catalog",purpose:_,read_only:!0,source_ref:M2(I,["source_ref"])??V,source_uri:Y.uri,source_revision_id:N?.id??null,revision:N?.revision??null,hash:N?.hash??M2(I,["hash"]),chunk_id:b.id,start_offset:b.start_offset,end_offset:b.end_offset,resolved_at:U},g=R1({source_ref:v.source_ref,source_uri:v.source_uri,source_kind:Y.kind,source_revision_id:v.source_revision_id,revision:v.revision,hash:v.hash,chunk_id:b.id,start_offset:b.start_offset,end_offset:b.end_offset,status:M2(I,["status"]),resolver:v.resolver});return{id:b.id,kind:b.kind,ordinal:b.ordinal,text:b.text,token_count:b.token_count,start_offset:b.start_offset,end_offset:b.end_offset,metadata:I,evidence:v,provenance:g}}),M=R.map((b)=>({source_ref:b.evidence.source_ref,source_uri:Y.uri,chunk_id:b.id,quote:b.text.slice(0,500),start_offset:b.start_offset,end_offset:b.end_offset,evidence:b.evidence,provenance:b.provenance}));O6(Q,{event_type:"source_read",action:"open_files_resolve",target_uri:$.sourceRef,decision:"allow",metadata:{purpose:_,read_only:!0,source_uri:Y.uri,revision:N?.revision??null,chunks_returned:R.length,chunks_total:B},created_at:U});let K=M2(q,["mime","content_type"])??M2(F,["mime","content_type"]),w=g3(q,["size","size_bytes"])??g3(F,["size","size_bytes"]);return{source_ref:V,source_uri:Y.uri,purpose:_,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:Y.id,uri:Y.uri,kind:Y.kind,title:Y.title,metadata:q,permissions:L,updated_at:Y.updated_at},revision:N?{id:N.id,revision:N.revision,hash:N.hash,extracted_text_uri:N.extracted_text_uri,metadata:F,created_at:N.created_at,reindex_required:F.reindex_required===!0}:null,content:{mime:K,size:w,hash:N?.hash??M2(q,["hash","checksum","sha256"]),text_available:B>0,chunks_total:B,chunks_returned:R.length,char_count_returned:R.reduce((b,I)=>b+I.text.length,0),extracted_text_ref:N?.extracted_text_uri??M2(F,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:R,citations:M}})()}finally{Q.close()}}function IJ($){return`sha256:${sZ("sha256").update($).digest("hex")}`}function _v($){return $.replace(//gi," ").replace(//gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+\n/g,` + LIMIT ?`).all(_,J)}async function n9($){let _=$.purpose??"knowledge_answer",J=Math.max(0,Math.min($.limit??10,100)),U=($.now??new Date).toISOString(),W=B6($.sourceRef),X=F3($.sourceRef,W),G=E3($.sourceRef);if($.safetyPolicy){if(!$.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");d4($.dbPath,$.safetyPolicy)}a($.dbPath);let Y=m($.dbPath);try{return Y.transaction(()=>{let Q=Vv(Y,X,$.sourceRef);if(!Q)return __(Y,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:$.sourceRef,decision:"allow",metadata:{purpose:_,read_only:!0,source_uri:X},created_at:U}),{source_ref:$.sourceRef,source_uri:X,purpose:_,read_only:!0,resolved:!1,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:null,revision:null,content:{mime:null,size:null,hash:null,text_available:!1,chunks_total:0,chunks_returned:0,char_count_returned:0,extracted_text_ref:null,bytes_available:!1,bytes_exposed:!1},chunks:[],citations:[]};let q=d9(Q.metadata_json),L=d9(Q.acl_json);try{Hv(L,_)}catch(A){throw __(Y,{event_type:"source_read",action:"open_files_resolve",target_uri:$.sourceRef,decision:"deny",metadata:{purpose:_,read_only:!0,source_uri:Q.uri,error:A instanceof Error?A.message:String(A)},created_at:U}),A}let N=Rv(Y,Q.id,G),R=d9(N?.metadata_json),B=Kv(Y,N?.id??null),H=Fv(Y,N?.id??null,J),V=Nv(Q.uri,N,$.sourceRef),K=H.map((A)=>{let g=d9(A.metadata_json),v={resolver:"open-files-read-only",mode:"local_catalog",purpose:_,read_only:!0,source_ref:b1(g,["source_ref"])??V,source_uri:Q.uri,source_revision_id:N?.id??null,revision:N?.revision??null,hash:N?.hash??b1(g,["hash"]),chunk_id:A.id,start_offset:A.start_offset,end_offset:A.end_offset,resolved_at:U},k=E0({source_ref:v.source_ref,source_uri:v.source_uri,source_kind:Q.kind,source_revision_id:v.source_revision_id,revision:v.revision,hash:v.hash,chunk_id:A.id,start_offset:A.start_offset,end_offset:A.end_offset,status:b1(g,["status"]),resolver:v.resolver});return{id:A.id,kind:A.kind,ordinal:A.ordinal,text:A.text,token_count:A.token_count,start_offset:A.start_offset,end_offset:A.end_offset,metadata:g,evidence:v,provenance:k}}),E=K.map((A)=>({source_ref:A.evidence.source_ref,source_uri:Q.uri,chunk_id:A.id,quote:A.text.slice(0,500),start_offset:A.start_offset,end_offset:A.end_offset,evidence:A.evidence,provenance:A.provenance}));__(Y,{event_type:"source_read",action:"open_files_resolve",target_uri:$.sourceRef,decision:"allow",metadata:{purpose:_,read_only:!0,source_uri:Q.uri,revision:N?.revision??null,chunks_returned:K.length,chunks_total:B},created_at:U});let F=b1(q,["mime","content_type"])??b1(R,["mime","content_type"]),w=m3(q,["size","size_bytes"])??m3(R,["size","size_bytes"]);return{source_ref:V,source_uri:Q.uri,purpose:_,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:Q.id,uri:Q.uri,kind:Q.kind,title:Q.title,metadata:q,permissions:L,updated_at:Q.updated_at},revision:N?{id:N.id,revision:N.revision,hash:N.hash,extracted_text_uri:N.extracted_text_uri,metadata:R,created_at:N.created_at,reindex_required:R.reindex_required===!0}:null,content:{mime:F,size:w,hash:N?.hash??b1(q,["hash","checksum","sha256"]),text_available:B>0,chunks_total:B,chunks_returned:K.length,char_count_returned:K.reduce((A,g)=>A+g.text.length,0),extracted_text_ref:N?.extracted_text_uri??b1(R,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:K,citations:E}})()}finally{Y.close()}}function PJ($){return`sha256:${Ev("sha256").update($).digest("hex")}`}function bv($){return $.replace(//gi," ").replace(//gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+\n/g,` `).replace(/\n\s+/g,` -`).replace(/[ \t]{2,}/g," ").trim()}async function Jv($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 source URI: ${$}`);if(J)K1($,J);let[{S3Client:G,GetObjectCommand:Q},{fromIni:Y}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Y({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Q({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function Wv($,_){if(_)wJ(_);let J=await w9($,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!J.ok)throw Error(`Web source read failed ${J.status}: ${$}`);let U=J.headers.get("content-type"),W=await J.text();return{text:U?.includes("html")?_v(W):W,mime:U}}function x9($){if($.kind==="file")return m9($.path);if($.kind==="s3")return m9($.key);if($.kind==="web")return m9(new URL($.url).pathname)||$.url;return $.path?m9($.path):$.id}async function k3($,_,J){if($.kind==="file"){if(!eZ($.path))throw Error(`Source file not found: ${$.path}`);let U=$v($.path,"utf8");return{text:U,contentSource:"file",title:x9($),mime:"text/plain",size:U.length,hash:IJ(U),revision:null,extractedTextRef:null,metadata:{path:$.path},permissions:{mode:"read_only"}}}if($.kind==="s3"){let U=await Jv($.uri,_,J);return{text:U,contentSource:"s3",title:x9($),mime:"text/plain",size:U.length,hash:IJ(U),revision:null,extractedTextRef:null,metadata:{bucket:$.bucket,key:$.key},permissions:{mode:"read_only"}}}if($.kind==="web"){let U=await Wv($.url,J);return{text:U.text,contentSource:"web",title:x9($),mime:U.mime,size:U.text.length,hash:IJ(U.text),revision:null,extractedTextRef:null,metadata:{url:$.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${$.uri}`)}async function Uv($,_,J){if($.startsWith("open-files://"))throw Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://.");let U=L4($);return{text:(await k3(U,_,J)).text,contentSource:"extracted_text_ref"}}async function Xv($){let _=await h9({dbPath:$.dbPath,sourceRef:$.sourceRef,purpose:$.purpose??"knowledge_index",limit:100,safetyPolicy:$.safetyPolicy,now:$.now});if(!_.resolved)throw Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API.");if(_.revision?.extracted_text_uri&&!_.content.text_available){let U=await Uv(_.revision.extracted_text_uri,$.config,$.safetyPolicy);return{text:U.text,contentSource:U.contentSource,title:_.source?.title??null,mime:_.content.mime,size:U.text.length,hash:_.revision.hash??IJ(U.text),revision:_.revision.revision,extractedTextRef:_.revision.extracted_text_uri,metadata:_.source?.metadata??{},permissions:_.source?.permissions??{mode:"read_only"}}}if(_.chunks.length===0)throw Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first.");let J=_.chunks.map((U)=>U.text).join(` +`).replace(/[ \t]{2,}/g," ").trim()}async function wv($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 source URI: ${$}`);if(J)M0($,J);let[{S3Client:G,GetObjectCommand:Y},{fromIni:Q}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Q({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Y({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function gv($,_){if(_)fJ(_);let J=await C9($,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!J.ok)throw Error(`Web source read failed ${J.status}: ${$}`);let U=J.headers.get("content-type"),W=await J.text();return{text:U?.includes("html")?bv(W):W,mime:U}}function i9($){if($.kind==="file")return c9($.path);if($.kind==="s3")return c9($.key);if($.kind==="web")return c9(new URL($.url).pathname)||$.url;return $.path?c9($.path):$.id}async function x3($,_,J){if($.kind==="file"){if(!Mv($.path))throw Error(`Source file not found: ${$.path}`);let U=Av($.path,"utf8");return{text:U,contentSource:"file",title:i9($),mime:"text/plain",size:U.length,hash:PJ(U),revision:null,extractedTextRef:null,metadata:{path:$.path},permissions:{mode:"read_only"}}}if($.kind==="s3"){let U=await wv($.uri,_,J);return{text:U,contentSource:"s3",title:i9($),mime:"text/plain",size:U.length,hash:PJ(U),revision:null,extractedTextRef:null,metadata:{bucket:$.bucket,key:$.key},permissions:{mode:"read_only"}}}if($.kind==="web"){let U=await gv($.url,J);return{text:U.text,contentSource:"web",title:i9($),mime:U.mime,size:U.text.length,hash:PJ(U.text),revision:null,extractedTextRef:null,metadata:{url:$.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${$.uri}`)}async function kv($,_,J){if($.startsWith("open-files://"))throw Error("Open-files extracted text refs require an open-files resolver API. Ingest an open-files manifest with extracted_text or an extracted_text_ref using file://, s3://, or https://.");let U=B6($);return{text:(await x3(U,_,J)).text,contentSource:"extracted_text_ref"}}async function Iv($){let _=await n9({dbPath:$.dbPath,sourceRef:$.sourceRef,purpose:$.purpose??"knowledge_index",limit:100,safetyPolicy:$.safetyPolicy,now:$.now});if(!_.resolved)throw Error("Open-files source is not in the local knowledge catalog. Ingest an open-files manifest first or use the open-files resolver API.");if(_.revision?.extracted_text_uri&&!_.content.text_available){let U=await kv(_.revision.extracted_text_uri,$.config,$.safetyPolicy);return{text:U.text,contentSource:U.contentSource,title:_.source?.title??null,mime:_.content.mime,size:U.text.length,hash:_.revision.hash??PJ(U.text),revision:_.revision.revision,extractedTextRef:_.revision.extracted_text_uri,metadata:_.source?.metadata??{},permissions:_.source?.permissions??{mode:"read_only"}}}if(_.chunks.length===0)throw Error("Open-files source has no extracted text chunks yet. Ingest an open-files manifest with extracted_text or extracted_text_ref first.");let J=_.chunks.map((U)=>U.text).join(` -`);return{text:J,contentSource:"catalog_chunks",title:_.source?.title??null,mime:_.content.mime,size:J.length,hash:_.revision?.hash??IJ(J),revision:_.revision?.revision??null,extractedTextRef:_.revision?.extracted_text_uri??null,metadata:_.source?.metadata??{},permissions:_.source?.permissions??{mode:"read_only"}}}function Gv($,_,J,U){let W=J.hash??IJ(J.text),X={...z6(J.metadata),source_ref:$,content_source:J.contentSource,read_only:!0},G={source_ref:$,name:J.title??x9(_),mime:J.mime??"text/plain",size:J.size??J.text.length,hash:W,revision:J.revision??W,status:"active",updated_at:new Date().toISOString(),permissions:{mode:"read_only",allowed_purposes:[U],...J.permissions},metadata:X,extracted_text_ref:J.extractedTextRef,extracted_text:J.text};if(_.kind==="open-files"){if(_.entity==="file")G.file_id=_.id;if(_.entity==="source")G.source_id=_.id,G.path=_.path}if(_.kind==="file")G.path=_.path;if(_.kind==="s3")G.path=_.key;if(_.kind==="web")G.url=_.url;return G}async function u9($){let _=$.purpose??"knowledge_index";F2($.sourceRef,{allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1});let J=L4($.sourceRef),U=J.kind==="open-files"?await Xv($):await k3(J,$.config,$.safetyPolicy),W=Gv($.sourceRef,J,U,_);return{...await K2({dbPath:$.dbPath,items:[W],sourceLabel:$.sourceRef,readAction:"source_ref_ingest_read",allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1,safetyPolicy:$.safetyPolicy,now:$.now}),source_ref:$.sourceRef,content_source:U.contentSource,read_only:!0,hash:String(W.hash)}}function d9($,_){return`${$}_${Qv("sha256").update(_).digest("hex").slice(0,20)}`}function qv($){return $.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"note"}function gY($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function zv($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function f3($){return Array.from(new Set(($??[]).map((_)=>_.trim()).filter(Boolean)))}function jv($){let _=$.path?.trim()||`wiki/notes/${qv($.title)}.md`,J=_.replace(/\\/g,"/");if(!J.startsWith("wiki/notes/")||!J.endsWith(".md"))throw Error("App wiki note paths must be relative wiki/notes/*.md artifact keys.");if(J.startsWith("/")||J.split("/").some((U)=>U===".."||U==="."))throw Error(`Invalid app wiki note path: ${_}`);return J}function Ov($){let _=[`# ${$.title}`,"",$.content.trim(),"",`Updated: ${$.now}`];if($.tags.length>0)_.push("","Tags:",...$.tags.map((J)=>`- ${J}`));if($.sourceRefs.length>0)_.push("","Source refs:",...$.sourceRefs.map((J)=>`- ${J}`));return _.push(""),_.join(` -`)}async function C3($,_){let J=await $.put(_);return{key:J.key,uri:J.uri,kind:_.key.startsWith("logs/")?"log":"wiki_page",content_type:_.content_type,modified_at:J.modified_at,...EJ(_.body),metadata:{..._.metadata??{}}}}async function Dv($,_,J){let U=String(J.getUTCFullYear()),W=String(J.getUTCMonth()+1).padStart(2,"0"),X=String(J.getUTCDate()).padStart(2,"0"),G=`logs/${U}/${W}/${X}.jsonl`,Q="";try{Q=await $.getText(G)}catch{Q=""}return C3($,{key:G,body:`${Q}${JSON.stringify(_)} -`,content_type:"application/x-ndjson",metadata:{provenance:v4({generated_from:String(_.event??"app_wiki_log"),artifact_key:G})}})}function Lv($){return{...z6($.metadata??{}),app_wiki:!0,note:!0,artifact_key:$.path,tags:$.tags,source_refs:$.sourceRefs,provenance:$.provenance}}function kY($){let _=gY($.metadata_json);return{id:$.id,path:$.path,title:$.title,artifact_uri:$.artifact_uri,content_hash:$.content_hash,tags:Array.isArray(_.tags)?_.tags.filter((J)=>typeof J==="string"):[],source_refs:Array.isArray(_.source_refs)?_.source_refs.filter((J)=>typeof J==="string"):[],created_at:$.created_at,updated_at:$.updated_at}}function Bv($,_){return _.map((J)=>{let U=$.query(`SELECT +`);return{text:J,contentSource:"catalog_chunks",title:_.source?.title??null,mime:_.content.mime,size:J.length,hash:_.revision?.hash??PJ(J),revision:_.revision?.revision??null,extractedTextRef:_.revision?.extracted_text_uri??null,metadata:_.source?.metadata??{},permissions:_.source?.permissions??{mode:"read_only"}}}function fv($,_,J,U){let W=J.hash??PJ(J.text),X={...j_(J.metadata),source_ref:$,content_source:J.contentSource,read_only:!0},G={source_ref:$,name:J.title??i9(_),mime:J.mime??"text/plain",size:J.size??J.text.length,hash:W,revision:J.revision??W,status:"active",updated_at:new Date().toISOString(),permissions:{mode:"read_only",allowed_purposes:[U],...J.permissions},metadata:X,extracted_text_ref:J.extractedTextRef,extracted_text:J.text};if(_.kind==="open-files"){if(_.entity==="file")G.file_id=_.id;if(_.entity==="source")G.source_id=_.id,G.path=_.path}if(_.kind==="file")G.path=_.path;if(_.kind==="s3")G.path=_.key;if(_.kind==="web")G.url=_.url;return G}async function l9($){let _=$.purpose??"knowledge_index";E1($.sourceRef,{allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1});let J=B6($.sourceRef),U=J.kind==="open-files"?await Iv($):await x3(J,$.config,$.safetyPolicy),W=fv($.sourceRef,J,U,_);return{...await A1({dbPath:$.dbPath,items:[W],sourceLabel:$.sourceRef,readAction:"source_ref_ingest_read",allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1,safetyPolicy:$.safetyPolicy,now:$.now}),source_ref:$.sourceRef,content_source:U.contentSource,read_only:!0,hash:String(W.hash)}}function r9($,_){return`${$}_${Cv("sha256").update(_).digest("hex").slice(0,20)}`}function Tv($){return $.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"note"}function ZQ($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function Sv($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function u3($){return Array.from(new Set(($??[]).map((_)=>_.trim()).filter(Boolean)))}function Zv($){let _=$.path?.trim()||`wiki/notes/${Tv($.title)}.md`,J=_.replace(/\\/g,"/");if(!J.startsWith("wiki/notes/")||!J.endsWith(".md"))throw Error("App wiki note paths must be relative wiki/notes/*.md artifact keys.");if(J.startsWith("/")||J.split("/").some((U)=>U===".."||U==="."))throw Error(`Invalid app wiki note path: ${_}`);return J}function vv($){let _=[`# ${$.title}`,"",$.content.trim(),"",`Updated: ${$.now}`];if($.tags.length>0)_.push("","Tags:",...$.tags.map((J)=>`- ${J}`));if($.sourceRefs.length>0)_.push("","Source refs:",...$.sourceRefs.map((J)=>`- ${J}`));return _.push(""),_.join(` +`)}async function d3($,_){let J=await $.put(_);return{key:J.key,uri:J.uri,kind:_.key.startsWith("logs/")?"log":"wiki_page",content_type:_.content_type,modified_at:J.modified_at,...IJ(_.body),metadata:{..._.metadata??{}}}}async function yv($,_,J){let U=String(J.getUTCFullYear()),W=String(J.getUTCMonth()+1).padStart(2,"0"),X=String(J.getUTCDate()).padStart(2,"0"),G=`logs/${U}/${W}/${X}.jsonl`,Y="";try{Y=await $.getText(G)}catch{Y=""}return d3($,{key:G,body:`${Y}${JSON.stringify(_)} +`,content_type:"application/x-ndjson",metadata:{provenance:X6({generated_from:String(_.event??"app_wiki_log"),artifact_key:G})}})}function hv($){return{...j_($.metadata??{}),app_wiki:!0,note:!0,artifact_key:$.path,tags:$.tags,source_refs:$.sourceRefs,provenance:$.provenance}}function vQ($){let _=ZQ($.metadata_json);return{id:$.id,path:$.path,title:$.title,artifact_uri:$.artifact_uri,content_hash:$.content_hash,tags:Array.isArray(_.tags)?_.tags.filter((J)=>typeof J==="string"):[],source_refs:Array.isArray(_.source_refs)?_.source_refs.filter((J)=>typeof J==="string"):[],created_at:$.created_at,updated_at:$.updated_at}}function mv($,_){return _.map((J)=>{let U=$.query(`SELECT s.uri AS source_uri, c.id AS chunk_id, c.text, @@ -584,13 +645,13 @@ COMMIT; LEFT JOIN chunks c ON c.source_revision_id = sr.id WHERE s.uri = ? OR s.metadata_json LIKE ? ORDER BY sr.created_at DESC, c.ordinal ASC - LIMIT 1`).get(J,`%${J}%`),W=gY(U?.metadata_json);return{source_ref:J,source_uri:U?.source_uri??J,chunk_id:U?.chunk_id??null,quote:U?.text?U.text.replace(/\s+/g," ").slice(0,240):null,start_offset:U?.start_offset??null,end_offset:U?.end_offset??null,metadata:{source_ref:J,revision:U?.revision??W.revision,hash:U?.hash??W.hash}}})}function Hv($,_,J,U){$.run("DELETE FROM citations WHERE wiki_page_id = ?",[_]);let W=Bv($,J);for(let X of W)$.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[d9("cit",`${_}\x00${X.source_uri}\x00${X.chunk_id??Yv()}`),_,X.chunk_id,X.source_uri,X.quote,X.start_offset,X.end_offset,JSON.stringify(X.metadata),U]);return W.length}function Nv($,_){$.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + LIMIT 1`).get(J,`%${J}%`),W=ZQ(U?.metadata_json);return{source_ref:J,source_uri:U?.source_uri??J,chunk_id:U?.chunk_id??null,quote:U?.text?U.text.replace(/\s+/g," ").slice(0,240):null,start_offset:U?.start_offset??null,end_offset:U?.end_offset??null,metadata:{source_ref:J,revision:U?.revision??W.revision,hash:U?.hash??W.hash}}})}function xv($,_,J,U){$.run("DELETE FROM citations WHERE wiki_page_id = ?",[_]);let W=mv($,J);for(let X of W)$.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r9("cit",`${_}\x00${X.source_uri}\x00${X.chunk_id??Pv()}`),_,X.chunk_id,X.source_uri,X.quote,X.start_offset,X.end_offset,JSON.stringify(X.metadata),U]);return W.length}function uv($,_){$.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[d9("idx",`app-wiki-note\x00${_.path}`),"app_wiki_note",_.title,_.artifactUri,_.path,JSON.stringify({artifact_key:_.path,content_hash:_.contentHash,tags:_.tags,source_refs:_.sourceRefs}),_.now,_.now])}function Vv($,_){$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + updated_at = excluded.updated_at`,[r9("idx",`app-wiki-note\x00${_.path}`),"app_wiki_note",_.title,_.artifactUri,_.path,JSON.stringify({artifact_key:_.path,content_hash:_.contentHash,tags:_.tags,source_refs:_.sourceRefs}),_.now,_.now])}function dv($,_){$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title = excluded.title, @@ -598,22 +659,22 @@ COMMIT; content_hash = excluded.content_hash, status = excluded.status, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[_.pageId,_.path,_.title,_.artifactUri,_.contentHash,"active",JSON.stringify(_.metadata),_.now,_.now]);let J=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_.pageId);for(let W of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[W.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_.pageId]);let U=d9("chk",`${_.pageId}\x00${_.contentHash}`);$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.pageId,"wiki",0,_.body,zv(_.body),0,_.body.length,JSON.stringify({..._.metadata,artifact_uri:_.artifactUri,content_hash:_.contentHash}),_.now]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,_.body,_.title,_.artifactUri])}function HU($){if($.scope==="global"&&$.allowGlobal!==!0)throw Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global.");if($.workspace.home.includes("/.husna/")||$.workspace.home.endsWith("/.husna"))throw Error(`Refusing app-wiki writes to legacy .husna path: ${$.workspace.home}`);if($.workspace.home.includes("/.hasna/apps/knowledge"))throw Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${$.workspace.home}`);if($.safetyPolicy)x0($.workspace.knowledgeDbPath,$.safetyPolicy)}async function P3($){HU($);let _=G$($.workspace.knowledgeDbPath),J=i($.workspace.knowledgeDbPath);try{O6(J,{event_type:"write",action:"app_wiki_init",target_uri:$.workspace.home,decision:"allow",metadata:{scope:$.scope,store_type:$.store.type,app_path:".hasna/knowledge"},created_at:($.now??new Date).toISOString()})}finally{J.close()}return{ok:!0,scope:$.scope,workspace_home:$.workspace.home,knowledge_db_path:$.workspace.knowledgeDbPath,schema_version:_.schema_version,store_type:$.store.type,global_write_allowed:$.scope==="global"&&$.allowGlobal===!0,message:`Initialized app wiki scope at ${$.workspace.home}`}}async function T3($){HU($);let _=$.now??new Date,J=_.toISOString(),U=f3($.tags),W=f3($.sourceRefs);for(let N of W)F2(N,{allowFileSourceRefs:$.safetyPolicy?.readOnlySourceAccess===!0});let X=jv($),G=Ov({title:$.title,content:$.content,tags:U,sourceRefs:W,now:J}),Q=v4({generated_from:"app_wiki_note",artifact_key:X,source_refs:W}),Y=await C3($.store,{key:X,body:G,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:Q,scope:$.scope,tags:U.join(","),source_refs:W.join(",")}}),q=await Dv($.store,{ts:J,event:"app_wiki_note_written",page_key:X,source_refs:W,tags:U},_);G$($.workspace.knowledgeDbPath);let L=i($.workspace.knowledgeDbPath);try{let N=d9("wiki",X),F=Lv({path:X,tags:U,sourceRefs:W,provenance:Q,metadata:$.metadata});m0(L,[Y,q],_),Vv(L,{pageId:N,path:X,title:$.title,artifactUri:Y.uri,contentHash:Y.hash??"",body:G,metadata:F,now:J});let B=Hv(L,N,W,J);Nv(L,{title:$.title,path:X,artifactUri:Y.uri,contentHash:Y.hash??"",tags:U,sourceRefs:W,now:J}),O6(L,{event_type:"write",action:"app_wiki_note_write",target_uri:Y.uri,decision:"allow",metadata:{scope:$.scope,path:X,source_refs:W,tags:U},created_at:J});let H=L.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(N);if(!H)throw Error(`Failed to write app wiki note: ${X}`);return{ok:!0,scope:$.scope,workspace_home:$.workspace.home,note:kY(H),artifact_uri:Y.uri,content_hash:Y.hash??"",citations_written:B,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${X}`}}finally{L.close()}}function S3($){let _=Math.max(1,Math.min($.limit??50,200));if(!$.dbPath)return[];G$($.dbPath);let J=i($.dbPath);try{return J.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + updated_at = excluded.updated_at`,[_.pageId,_.path,_.title,_.artifactUri,_.contentHash,"active",JSON.stringify(_.metadata),_.now,_.now]);let J=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_.pageId);for(let W of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[W.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_.pageId]);let U=r9("chk",`${_.pageId}\x00${_.contentHash}`);$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.pageId,"wiki",0,_.body,Sv(_.body),0,_.body.length,JSON.stringify({..._.metadata,artifact_uri:_.artifactUri,content_hash:_.contentHash}),_.now]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,_.body,_.title,_.artifactUri])}function FU($){if($.scope==="global"&&$.allowGlobal!==!0)throw Error("Global app-wiki writes require allowGlobal=true or CLI --allow-global.");if($.workspace.home.includes("/.husna/")||$.workspace.home.endsWith("/.husna"))throw Error(`Refusing app-wiki writes to legacy .husna path: ${$.workspace.home}`);if($.workspace.home.includes("/.hasna/apps/knowledge"))throw Error(`Refusing app-wiki writes to legacy .hasna/apps/knowledge path: ${$.workspace.home}`);if($.safetyPolicy)d4($.workspace.knowledgeDbPath,$.safetyPolicy)}async function n3($){FU($);let _=a($.workspace.knowledgeDbPath),J=m($.workspace.knowledgeDbPath);try{__(J,{event_type:"write",action:"app_wiki_init",target_uri:$.workspace.home,decision:"allow",metadata:{scope:$.scope,store_type:$.store.type,app_path:".hasna/knowledge"},created_at:($.now??new Date).toISOString()})}finally{J.close()}return{ok:!0,scope:$.scope,workspace_home:$.workspace.home,knowledge_db_path:$.workspace.knowledgeDbPath,schema_version:_.schema_version,store_type:$.store.type,global_write_allowed:$.scope==="global"&&$.allowGlobal===!0,message:`Initialized app wiki scope at ${$.workspace.home}`}}async function c3($){FU($);let _=$.now??new Date,J=_.toISOString(),U=u3($.tags),W=u3($.sourceRefs);for(let N of W)E1(N,{allowFileSourceRefs:$.safetyPolicy?.readOnlySourceAccess===!0});let X=Zv($),G=vv({title:$.title,content:$.content,tags:U,sourceRefs:W,now:J}),Y=X6({generated_from:"app_wiki_note",artifact_key:X,source_refs:W}),Q=await d3($.store,{key:X,body:G,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:Y,scope:$.scope,tags:U.join(","),source_refs:W.join(",")}}),q=await yv($.store,{ts:J,event:"app_wiki_note_written",page_key:X,source_refs:W,tags:U},_);a($.workspace.knowledgeDbPath);let L=m($.workspace.knowledgeDbPath);try{let N=r9("wiki",X),R=hv({path:X,tags:U,sourceRefs:W,provenance:Y,metadata:$.metadata});u4(L,[Q,q],_),dv(L,{pageId:N,path:X,title:$.title,artifactUri:Q.uri,contentHash:Q.hash??"",body:G,metadata:R,now:J});let B=xv(L,N,W,J);uv(L,{title:$.title,path:X,artifactUri:Q.uri,contentHash:Q.hash??"",tags:U,sourceRefs:W,now:J}),__(L,{event_type:"write",action:"app_wiki_note_write",target_uri:Q.uri,decision:"allow",metadata:{scope:$.scope,path:X,source_refs:W,tags:U},created_at:J});let H=L.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(N);if(!H)throw Error(`Failed to write app wiki note: ${X}`);return{ok:!0,scope:$.scope,workspace_home:$.workspace.home,note:vQ(H),artifact_uri:Q.uri,content_hash:Q.hash??"",citations_written:B,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${X}`}}finally{L.close()}}function i3($){let _=Math.max(1,Math.min($.limit??50,200));if(!$.dbPath)return[];a($.dbPath);let J=m($.dbPath);try{return J.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE status = 'active' AND path LIKE 'wiki/notes/%' AND metadata_json LIKE '%"app_wiki":true%' ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(_).map(kY)}finally{J.close()}}async function Z3($){G$($.dbPath);let _=i($.dbPath);try{let J=_.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + LIMIT ?`).all(_).map(vQ)}finally{J.close()}}async function l3($){a($.dbPath);let _=m($.dbPath);try{let J=_.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE (id = ? OR path = ?) AND path LIKE 'wiki/notes/%' AND metadata_json LIKE '%"app_wiki":true%'`).get($.id,$.id);if(!J)return null;let U=_.query(`SELECT id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at FROM citations WHERE wiki_page_id = ? - ORDER BY created_at ASC`).all(J.id).map((X)=>({...X,metadata:gY(X.metadata_json),metadata_json:void 0})),W=null;if($.includeContent!==!1)try{W=await $.store.getText(J.path)}catch{W=null}return{ok:!0,note:kY(J),citations:U,content:W}}finally{_.close()}}async function v3($){return HU($),F2($.sourceRef,{allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1}),u9({dbPath:$.workspace.knowledgeDbPath,sourceRef:$.sourceRef,purpose:$.purpose??"knowledge_index",config:$.config,safetyPolicy:$.safetyPolicy})}import{randomUUID as hY}from"crypto";import{randomUUID as Fv}from"crypto";var fY={openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},Rv={openai:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!0,reasoning:!0,embeddings:!0},anthropic:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!1,reasoning:!0,embeddings:!1},deepseek:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!1,native_web_search:!1,reasoning:!0,embeddings:!1}},Kv={default:"openai:gpt-5.2",fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"};function h3($){return $?.providers??{}}function u0($,_){let J=h3($)[_]??{};return{...fY[_],...J}}function m3($){let _=h3($);return{...Kv,..._.default_model?{default:_.default_model}:{},..._.aliases??{}}}function E6($){let[_,...J]=$.split(":"),U=J.join(":");if(_!=="openai"&&_!=="anthropic"&&_!=="deepseek")throw Error(`Unsupported AI provider: ${_}`);if(!U)throw Error(`Invalid model ref: ${$}. Expected provider:model.`);return{provider:_,model:U}}function y4($,_){return m3(_)[$]??$}function CY($){let _=m3($);return Object.entries(_).map(([J,U])=>{let W=E6(U);return{alias:J,model_ref:U,provider:W.provider,model:W.model,default:J==="default",capabilities:Rv[W.provider]}})}function x3($,_=process.env){return Object.keys(fY).map((J)=>{let U=u0($,J),W=Boolean(_[U.api_key_env]);return{provider:J,api_key_env:U.api_key_env,configured:W,source:W?"env":"missing",base_url:U.base_url??null,default_model:U.default_model}})}function u3($,_=process.env){return{default_model:y4("default",$),providers:x3($,_),models:CY($)}}function A2($,_,J=process.env){let U=x3(_,J).find((W)=>W.provider===$);if(!U)throw Error(`Unsupported AI provider: ${$}`);if(!U.configured)throw Error(`Missing ${U.api_key_env} for ${$}. Set the env var to use this provider.`);return U}async function Mv($){if($==="openai"){let{createOpenAI:J}=await import("@ai-sdk/openai");return J}if($==="anthropic"){let{createAnthropic:J}=await import("@ai-sdk/anthropic");return J}let{createDeepSeek:_}=await import("@ai-sdk/deepseek");return _}async function Av($={}){let{createProviderRegistry:_}=await import("ai"),J=$.env??process.env,U={};for(let W of Object.keys(fY)){let X=u0($.config,W),G=J[X.api_key_env];if(!G)continue;let Q=$.factories?.[W]??await Mv(W);U[W]=Q({apiKey:G,baseURL:X.base_url})}return _(U)}async function NU($,_={}){let J=y4($,_.config),U=E6(J);return A2(U.provider,_.config,_.env),(await Av(_)).languageModel(J)}function y3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return 0}function b2($){let _=$.usage??{};return{provider:$.provider,model:$.model,input_tokens:y3(_,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:y3(_,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:$.costUsd??0,metadata:{usage:_,provider_metadata:$.providerMetadata??{}}}}function gJ($,_){let J=`usage_${Fv()}`;return $.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[J,_.run_id??null,_.provider,_.model,_.input_tokens,_.output_tokens,_.cost_usd,JSON.stringify(_.metadata),_.created_at??new Date().toISOString()]),J}import{createHash as pv}from"crypto";import{existsSync as Cv,readFileSync as Pv}from"fs";import{createHash as l3}from"crypto";var bv="openai:text-embedding-3-small",n3=1536;function c9($){return $?.embeddings??{}}function d3($,_){return`${$}_${l3("sha256").update(_).digest("hex").slice(0,20)}`}function TY($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function h4($,_){for(let J of _){let U=$[J];if(typeof U==="string"&&U.length>0)return U}return null}function c3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function PY($){return Math.sqrt($.reduce((_,J)=>_+J*J,0))}function Ev($,_,J=PY(_)){let U=PY($);if(U===0||J===0)return 0;let W=Math.min($.length,_.length),X=0;for(let G=0;G{let X=J[W%J.length]/255;return Number((X*2-1).toFixed(6))})}async function Iv($,_,J=process.env){A2("openai",_,J);let U=u0(_,"openai"),{createOpenAI:W}=await import("@ai-sdk/openai"),X=W({apiKey:J[U.api_key_env],baseURL:U.base_url});if(X.embeddingModel)return X.embeddingModel($);if(X.textEmbedding)return X.textEmbedding($);if(X.textEmbeddingModel)return X.textEmbeddingModel($);throw Error("OpenAI provider does not expose an embedding model factory.")}function E2($,_){if(!$||$==="default"||$==="embedding")return c9(_).default_model??bv;return $}async function i3($,_={}){let J=E2(_.modelRef,_.config),U=E6(J);if(U.provider!=="openai")throw Error(`Embedding provider ${U.provider} is not supported yet. Use openai:text-embedding-3-small.`);let W=_.dimensions??c9(_.config).dimensions??n3;if(_.fake)return{provider:U.provider,model:U.model,dimensions:W,vectors:$.map((q)=>wv(q,W)),usage:{input_tokens:$.reduce((q,L)=>q+Math.max(1,Math.ceil(L.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:X}=await import("ai"),G=await Iv(U.model,_.config,_.env),Q=await X({model:G,values:$,maxParallelCalls:_.maxParallelCalls??c9(_.config).max_parallel_calls,providerOptions:{openai:{dimensions:W}}}),Y=Q.embeddings;return{provider:U.provider,model:U.model,dimensions:Y[0]?.length??W,vectors:Y,usage:{input_tokens:Q.usage?.tokens??0}}}function gv($,_){if(_.sourceRevisionId)return $.query(`SELECT + ORDER BY created_at ASC`).all(J.id).map((X)=>({...X,metadata:ZQ(X.metadata_json),metadata_json:void 0})),W=null;if($.includeContent!==!1)try{W=await $.store.getText(J.path)}catch{W=null}return{ok:!0,note:vQ(J),citations:U,content:W}}finally{_.close()}}async function r3($){return FU($),E1($.sourceRef,{allowFileSourceRefs:$.config?.sources.allowed_schemes.includes("file")!==!1}),l9({dbPath:$.workspace.knowledgeDbPath,sourceRef:$.sourceRef,purpose:$.purpose??"knowledge_index",config:$.config,safetyPolicy:$.safetyPolicy})}import{randomUUID as iQ}from"crypto";import{randomUUID as nv}from"crypto";var yQ={openai:{api_key_env:"OPENAI_API_KEY",default_model:"gpt-5.2"},anthropic:{api_key_env:"ANTHROPIC_API_KEY",default_model:"claude-sonnet-4-6"},deepseek:{api_key_env:"DEEPSEEK_API_KEY",default_model:"deepseek-chat"}},cv={openai:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!0,reasoning:!0,embeddings:!0},anthropic:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!0,native_web_search:!1,reasoning:!0,embeddings:!1},deepseek:{text_generation:!0,structured_output:!0,tool_usage:!0,tool_streaming:!0,image_input:!1,native_web_search:!1,reasoning:!0,embeddings:!1}},iv={default:"openai:gpt-5.2",fast:"openai:gpt-5-mini",reasoning:"anthropic:claude-opus-4-6",sonnet:"anthropic:claude-sonnet-4-6",deepseek:"deepseek:deepseek-chat","deepseek-reasoning":"deepseek:deepseek-reasoner"};function o3($){return $?.providers??{}}function n4($,_){let J=o3($)[_]??{};return{...yQ[_],...J}}function t3($){let _=o3($);return{...iv,..._.default_model?{default:_.default_model}:{},..._.aliases??{}}}function w_($){let[_,...J]=$.split(":"),U=J.join(":");if(_!=="openai"&&_!=="anthropic"&&_!=="deepseek")throw Error(`Unsupported AI provider: ${_}`);if(!U)throw Error(`Invalid model ref: ${$}. Expected provider:model.`);return{provider:_,model:U}}function y6($,_){return t3(_)[$]??$}function hQ($){let _=t3($);return Object.entries(_).map(([J,U])=>{let W=w_(U);return{alias:J,model_ref:U,provider:W.provider,model:W.model,default:J==="default",capabilities:cv[W.provider]}})}function a3($,_=process.env){return Object.keys(yQ).map((J)=>{let U=n4($,J),W=Boolean(_[U.api_key_env]);return{provider:J,api_key_env:U.api_key_env,configured:W,source:W?"env":"missing",base_url:U.base_url??null,default_model:U.default_model}})}function s3($,_=process.env){return{default_model:y6("default",$),providers:a3($,_),models:hQ($)}}function w1($,_,J=process.env){let U=a3(_,J).find((W)=>W.provider===$);if(!U)throw Error(`Unsupported AI provider: ${$}`);if(!U.configured)throw Error(`Missing ${U.api_key_env} for ${$}. Set the env var to use this provider.`);return U}async function lv($){if($==="openai"){let{createOpenAI:J}=await import("@ai-sdk/openai");return J}if($==="anthropic"){let{createAnthropic:J}=await import("@ai-sdk/anthropic");return J}let{createDeepSeek:_}=await import("@ai-sdk/deepseek");return _}async function rv($={}){let{createProviderRegistry:_}=await import("ai"),J=$.env??process.env,U={};for(let W of Object.keys(yQ)){let X=n4($.config,W),G=J[X.api_key_env];if(!G)continue;let Y=$.factories?.[W]??await lv(W);U[W]=Y({apiKey:G,baseURL:X.base_url})}return _(U)}async function EU($,_={}){let J=y6($,_.config),U=w_(J);return w1(U.provider,_.config,_.env),(await rv(_)).languageModel(J)}function p3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return 0}function g1($){let _=$.usage??{};return{provider:$.provider,model:$.model,input_tokens:p3(_,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:p3(_,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:$.costUsd??0,metadata:{usage:_,provider_metadata:$.providerMetadata??{}}}}function TJ($,_){let J=`usage_${nv()}`;return $.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[J,_.run_id??null,_.provider,_.model,_.input_tokens,_.output_tokens,_.cost_usd,JSON.stringify(_.metadata),_.created_at??new Date().toISOString()]),J}import{createHash as Vy}from"crypto";import{existsSync as _y,readFileSync as Jy}from"fs";import{createHash as _V}from"crypto";var pv="openai:text-embedding-3-small",JV=1536;function p9($){return $?.embeddings??{}}function e3($,_){return`${$}_${_V("sha256").update(_).digest("hex").slice(0,20)}`}function xQ($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function h6($,_){for(let J of _){let U=$[J];if(typeof U==="string"&&U.length>0)return U}return null}function $V($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function mQ($){return Math.sqrt($.reduce((_,J)=>_+J*J,0))}function ov($,_,J=mQ(_)){let U=mQ($);if(U===0||J===0)return 0;let W=Math.min($.length,_.length),X=0;for(let G=0;G{let X=J[W%J.length]/255;return Number((X*2-1).toFixed(6))})}async function av($,_,J=process.env){w1("openai",_,J);let U=n4(_,"openai"),{createOpenAI:W}=await import("@ai-sdk/openai"),X=W({apiKey:J[U.api_key_env],baseURL:U.base_url});if(X.embeddingModel)return X.embeddingModel($);if(X.textEmbedding)return X.textEmbedding($);if(X.textEmbeddingModel)return X.textEmbeddingModel($);throw Error("OpenAI provider does not expose an embedding model factory.")}function k1($,_){if(!$||$==="default"||$==="embedding")return p9(_).default_model??pv;return $}async function WV($,_={}){let J=k1(_.modelRef,_.config),U=w_(J);if(U.provider!=="openai")throw Error(`Embedding provider ${U.provider} is not supported yet. Use openai:text-embedding-3-small.`);let W=_.dimensions??p9(_.config).dimensions??JV;if(_.fake)return{provider:U.provider,model:U.model,dimensions:W,vectors:$.map((q)=>tv(q,W)),usage:{input_tokens:$.reduce((q,L)=>q+Math.max(1,Math.ceil(L.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:X}=await import("ai"),G=await av(U.model,_.config,_.env),Y=await X({model:G,values:$,maxParallelCalls:_.maxParallelCalls??p9(_.config).max_parallel_calls,providerOptions:{openai:{dimensions:W}}}),Q=Y.embeddings;return{provider:U.provider,model:U.model,dimensions:Q[0]?.length??W,vectors:Q,usage:{input_tokens:Y.usage?.tokens??0}}}function sv($,_){if(_.sourceRevisionId)return $.query(`SELECT c.id, c.text, c.token_count, @@ -651,7 +712,7 @@ COMMIT; ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? WHERE v.id IS NULL ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`).all(_.provider,_.model,_.limit)}function kv($){let _=TY($.metadata_json),J=_.provenance;if(J&&typeof J==="object"&&!Array.isArray(J))return J;return R1({source_ref:h4(_,["source_ref"]),source_uri:$.source_uri??h4(_,["source_uri"]),source_kind:$.source_kind??h4(_,["source_kind"]),source_revision_id:$.source_revision_id,revision:$.revision??h4(_,["revision"]),hash:$.hash??h4(_,["hash"]),chunk_id:$.id,start_offset:$.start_offset??c3(_,["start_offset"]),end_offset:$.end_offset??c3(_,["end_offset"]),status:h4(_,["status"]),resolver:"open-files-read-only"})}function fv($,_,J,U){let W=$.prepare(` + LIMIT ?`).all(_.provider,_.model,_.limit)}function ev($){let _=xQ($.metadata_json),J=_.provenance;if(J&&typeof J==="object"&&!Array.isArray(J))return J;return E0({source_ref:h6(_,["source_ref"]),source_uri:$.source_uri??h6(_,["source_uri"]),source_kind:$.source_kind??h6(_,["source_kind"]),source_revision_id:$.source_revision_id,revision:$.revision??h6(_,["revision"]),hash:$.hash??h6(_,["hash"]),chunk_id:$.id,start_offset:$.start_offset??$V(_,["start_offset"]),end_offset:$.end_offset??$V(_,["end_offset"]),status:h6(_,["status"]),resolver:"open-files-read-only"})}function $y($,_,J,U){let W=$.prepare(` INSERT INTO chunk_embeddings (id, chunk_id, provider, model, dimensions, vector_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(chunk_id, provider, model) DO UPDATE SET @@ -680,10 +741,10 @@ COMMIT; status = excluded.status, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);return $.transaction(()=>{for(let Q=0;Q<_.length;Q+=1){let Y=_[Q],q=J.vectors[Q];if(!q)continue;let L=TY(Y.metadata_json),N=kv(Y),F=N.source_ref??h4(L,["source_ref"]),B=N.source_uri??Y.source_uri??h4(L,["source_uri"]),H=N.revision??Y.revision??h4(L,["revision"]),V=N.hash??Y.hash??h4(L,["hash"]),R=N.status??h4(L,["status"])??"active",M=JSON.stringify(q);W.run(d3("emb",`${Y.id}\x00${J.provider}\x00${J.model}`),Y.id,J.provider,J.model,J.dimensions,M,U),X.run(d3("vec",`${Y.id}\x00${J.provider}\x00${J.model}`),Y.id,Y.source_revision_id,J.provider,J.model,J.dimensions,M,PY(q),B,F,H,V,N.start_offset,N.end_offset,Y.token_count,R,JSON.stringify({...L,provenance:N,embedded_at:U}),U,U)}})(),_.length}async function l9($){let _=E2($.modelRef,$.config),J=E6(_);if(J.provider!=="openai")throw Error(`Embedding provider ${J.provider} is not supported yet.`);let U=($.now??new Date).toISOString(),W=Math.max(1,Math.min($.limit??100,1000));G$($.dbPath);let X=i($.dbPath),G;try{G=gv(X,{provider:J.provider,model:J.model,limit:W,sourceRevisionId:$.sourceRevisionId})}finally{X.close()}if(G.length===0)return{provider:J.provider,model:J.model,dimensions:$.dimensions??c9($.config).dimensions??n3,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let Q=await i3(G.map((q)=>q.text),$),Y=i($.dbPath);try{let q=fv(Y,G,Q,U);return{provider:Q.provider,model:Q.model,dimensions:Q.dimensions,chunks_seen:G.length,chunks_embedded:G.length,embeddings_upserted:q,vector_entries_upserted:q,usage:Q.usage}}finally{Y.close()}}function r3($){G$($);let _=i($);try{let J=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,W=_.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at + `);return $.transaction(()=>{for(let Y=0;Y<_.length;Y+=1){let Q=_[Y],q=J.vectors[Y];if(!q)continue;let L=xQ(Q.metadata_json),N=ev(Q),R=N.source_ref??h6(L,["source_ref"]),B=N.source_uri??Q.source_uri??h6(L,["source_uri"]),H=N.revision??Q.revision??h6(L,["revision"]),V=N.hash??Q.hash??h6(L,["hash"]),K=N.status??h6(L,["status"])??"active",E=JSON.stringify(q);W.run(e3("emb",`${Q.id}\x00${J.provider}\x00${J.model}`),Q.id,J.provider,J.model,J.dimensions,E,U),X.run(e3("vec",`${Q.id}\x00${J.provider}\x00${J.model}`),Q.id,Q.source_revision_id,J.provider,J.model,J.dimensions,E,mQ(q),B,R,H,V,N.start_offset,N.end_offset,Q.token_count,K,JSON.stringify({...L,provenance:N,embedded_at:U}),U,U)}})(),_.length}async function o9($){let _=k1($.modelRef,$.config),J=w_(_);if(J.provider!=="openai")throw Error(`Embedding provider ${J.provider} is not supported yet.`);let U=($.now??new Date).toISOString(),W=Math.max(1,Math.min($.limit??100,1000));a($.dbPath);let X=m($.dbPath),G;try{G=sv(X,{provider:J.provider,model:J.model,limit:W,sourceRevisionId:$.sourceRevisionId})}finally{X.close()}if(G.length===0)return{provider:J.provider,model:J.model,dimensions:$.dimensions??p9($.config).dimensions??JV,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let Y=await WV(G.map((q)=>q.text),$),Q=m($.dbPath);try{let q=$y(Q,G,Y,U);return{provider:Y.provider,model:Y.model,dimensions:Y.dimensions,chunks_seen:G.length,chunks_embedded:G.length,embeddings_upserted:q,vector_entries_upserted:q,usage:Y.usage}}finally{Q.close()}}function UV($){a($);let _=m($);try{let J=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,W=_.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at FROM vector_index_entries GROUP BY provider, model, dimensions - ORDER BY provider, model`).all();return{total_embeddings:J,total_vector_entries:U,indexes:W}}finally{_.close()}}async function n9($){let _=E2($.modelRef,$.config),J=E6(_),U=Math.max(1,Math.min($.limit??10,100)),W=await i3([$.query],$),X=W.vectors[0]??[];G$($.dbPath);let G=i($.dbPath);try{let Y=G.query(`SELECT + ORDER BY provider, model`).all();return{total_embeddings:J,total_vector_entries:U,indexes:W}}finally{_.close()}}async function t9($){let _=k1($.modelRef,$.config),J=w_(_),U=Math.max(1,Math.min($.limit??10,100)),W=await WV([$.query],$),X=W.vectors[0]??[];a($.dbPath);let G=m($.dbPath);try{let Q=G.query(`SELECT v.chunk_id, c.text, v.vector_json, @@ -695,7 +756,7 @@ COMMIT; v.metadata_json FROM vector_index_entries v JOIN chunks c ON c.id = v.chunk_id - WHERE v.provider = ? AND v.model = ? AND v.status = 'active'`).all(J.provider,J.model).map((q)=>{let L=JSON.parse(q.vector_json),N=TY(q.metadata_json),F=N.provenance&&typeof N.provenance==="object"&&!Array.isArray(N.provenance)?N.provenance:null;return{chunk_id:q.chunk_id,score:Ev(X,L,q.vector_norm),text:q.text,source_uri:q.source_uri,source_ref:q.source_ref,revision:q.revision,hash:q.hash,provenance:F}}).sort((q,L)=>L.score-q.score).slice(0,U);return{provider:J.provider,model:J.model,dimensions:W.dimensions,query:$.query,results:Y}}finally{G.close()}}function i9($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function U4($,_){for(let J of _){let U=$[J];if(typeof U==="string"&&U.length>0)return U}return null}function p3($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function a3($){return Array.from(new Set($))}function s3($){let _=$.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];return a3(_.filter((J)=>J.length>0)).slice(0,16)}function o3($){return $.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]}function Tv($){let _=[],J=/"([^"]*)"|(\S+)/g,U,W=!1;while((U=J.exec($))!==null){if(U[1]!==void 0){let q=o3(U[1]);if(q.length>0)_.push({type:"phrase",value:q.join(" "),negate:W,prefix:!1});W=!1;continue}let X=U[2]??"";if(X==="OR"||X==="||"||X==="|"){_.push({type:"or",value:"",negate:!1,prefix:!1});continue}if(X==="AND"||X==="&&")continue;if(X==="NOT"){W=!0;continue}let G=W;if(W=!1,X.startsWith("-")&&X.length>1)G=!0,X=X.slice(1);let Q=!1;if(X.endsWith("*"))Q=!0,X=X.slice(0,-1);let Y=o3(X);if(Y.length===0)continue;_.push({type:Y.length>1?"phrase":"term",value:Y.join(" "),negate:G,prefix:Q})}return _.slice(0,24)}function Sv($){if($.type==="phrase")return`"${$.value}"`;return`"${$.value}"*`}function Zv($){let _=Tv($);if(_.filter((G)=>G.type!=="or"&&!G.negate).length===0)return{and:null,or:null};let U=(G)=>{let Q="",Y=!1,q=[];for(let L of _){if(L.type==="or"){Y=!0;continue}let N=Sv(L);if(L.negate){q.push(N);continue}if(Q.length===0)Q=N;else Q=Y?`${Q} OR ${N}`:`${Q} ${G} ${N}`;Y=!1}for(let L of q)Q=`(${Q}) NOT ${L}`;return Q.length>0?Q:null},W=U("AND"),X=U("OR");return{and:W,or:X!==W?X:null}}function vv($){return $.replace(/[\\%_]/g,(_)=>`\\${_}`)}function e3($,_){return $.flatMap((J)=>Array.from({length:_},()=>`%${vv(J)}%`))}function yv($,_){let J=Number.isFinite($)?1/(1+Math.abs($)):0,U=1/(1+_);return r9(Math.max(J,U))}function SY($,_){if(_.length===0)return 0;let J=_.filter((U)=>$.includes(U)).length;if(J===0)return 0;return r9(Math.min(0.85,0.35+J/_.length*0.5))}function hv($){return r9(Math.max(0,Math.min(1,($+1)/2)))}function r9($){return Number($.toFixed(6))}function fJ($,_){let J=$.keyword??0,U=$.semantic??0,W=$.catalog??0,X=_?.chunk_id?0.05:0;return r9(Math.min(1,J*0.55+U*0.4+W*0.35+X))}function ZY($){let _=$.provenance;return _&&typeof _==="object"&&!Array.isArray(_)?_:null}function mv($){let _=i9($.chunk_metadata_json),J=ZY(_);if(J)return J;if(!$.source_revision_id&&!$.source_uri)return null;return R1({source_ref:U4(_,["source_ref"]),source_uri:$.source_uri??U4(_,["source_uri"]),source_kind:$.source_kind??U4(_,["source_kind"]),source_revision_id:$.source_revision_id,revision:$.revision??U4(_,["revision"]),hash:$.hash??U4(_,["hash"]),chunk_id:$.chunk_id,start_offset:$.start_offset??p3(_,["start_offset"]),end_offset:$.end_offset??p3(_,["end_offset"]),status:U4(_,["status"]),resolver:"open-files-read-only"})}function t3($,_,J){if(!_)return[];try{return xv($,_,J)}catch{return[]}}function xv($,_,J){return $.query(`SELECT + WHERE v.provider = ? AND v.model = ? AND v.status = 'active'`).all(J.provider,J.model).map((q)=>{let L=JSON.parse(q.vector_json),N=xQ(q.metadata_json),R=N.provenance&&typeof N.provenance==="object"&&!Array.isArray(N.provenance)?N.provenance:null;return{chunk_id:q.chunk_id,score:ov(X,L,q.vector_norm),text:q.text,source_uri:q.source_uri,source_ref:q.source_ref,revision:q.revision,hash:q.hash,provenance:R}}).sort((q,L)=>L.score-q.score).slice(0,U);return{provider:J.provider,model:J.model,dimensions:W.dimensions,query:$.query,results:Q}}finally{G.close()}}function a9($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function G6($,_){for(let J of _){let U=$[J];if(typeof U==="string"&&U.length>0)return U}return null}function XV($,_){for(let J of _){let U=$[J];if(typeof U==="number"&&Number.isFinite(U))return U}return null}function QV($){return Array.from(new Set($))}function qV($){let _=$.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];return QV(_.filter((J)=>J.length>0)).slice(0,16)}function GV($){return $.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]}function Wy($){let _=[],J=/"([^"]*)"|(\S+)/g,U,W=!1;while((U=J.exec($))!==null){if(U[1]!==void 0){let q=GV(U[1]);if(q.length>0)_.push({type:"phrase",value:q.join(" "),negate:W,prefix:!1});W=!1;continue}let X=U[2]??"";if(X==="OR"||X==="||"||X==="|"){_.push({type:"or",value:"",negate:!1,prefix:!1});continue}if(X==="AND"||X==="&&")continue;if(X==="NOT"){W=!0;continue}let G=W;if(W=!1,X.startsWith("-")&&X.length>1)G=!0,X=X.slice(1);let Y=!1;if(X.endsWith("*"))Y=!0,X=X.slice(0,-1);let Q=GV(X);if(Q.length===0)continue;_.push({type:Q.length>1?"phrase":"term",value:Q.join(" "),negate:G,prefix:Y})}return _.slice(0,24)}function Uy($){if($.type==="phrase")return`"${$.value}"`;return`"${$.value}"*`}function Xy($){let _=Wy($);if(_.filter((G)=>G.type!=="or"&&!G.negate).length===0)return{and:null,or:null};let U=(G)=>{let Y="",Q=!1,q=[];for(let L of _){if(L.type==="or"){Q=!0;continue}let N=Uy(L);if(L.negate){q.push(N);continue}if(Y.length===0)Y=N;else Y=Q?`${Y} OR ${N}`:`${Y} ${G} ${N}`;Q=!1}for(let L of q)Y=`(${Y}) NOT ${L}`;return Y.length>0?Y:null},W=U("AND"),X=U("OR");return{and:W,or:X!==W?X:null}}function Gy($){return $.replace(/[\\%_]/g,(_)=>`\\${_}`)}function zV($,_){return $.flatMap((J)=>Array.from({length:_},()=>`%${Gy(J)}%`))}function Yy($,_){let J=Number.isFinite($)?1/(1+Math.abs($)):0,U=1/(1+_);return s9(Math.max(J,U))}function uQ($,_){if(_.length===0)return 0;let J=_.filter((U)=>$.includes(U)).length;if(J===0)return 0;return s9(Math.min(0.85,0.35+J/_.length*0.5))}function Qy($){return s9(Math.max(0,Math.min(1,($+1)/2)))}function s9($){return Number($.toFixed(6))}function ZJ($,_){let J=$.keyword??0,U=$.semantic??0,W=$.catalog??0,X=_?.chunk_id?0.05:0;return s9(Math.min(1,J*0.55+U*0.4+W*0.35+X))}function dQ($){let _=$.provenance;return _&&typeof _==="object"&&!Array.isArray(_)?_:null}function qy($){let _=a9($.chunk_metadata_json),J=dQ(_);if(J)return J;if(!$.source_revision_id&&!$.source_uri)return null;return E0({source_ref:G6(_,["source_ref"]),source_uri:$.source_uri??G6(_,["source_uri"]),source_kind:$.source_kind??G6(_,["source_kind"]),source_revision_id:$.source_revision_id,revision:$.revision??G6(_,["revision"]),hash:$.hash??G6(_,["hash"]),chunk_id:$.chunk_id,start_offset:$.start_offset??XV(_,["start_offset"]),end_offset:$.end_offset??XV(_,["end_offset"]),status:G6(_,["status"]),resolver:"open-files-read-only"})}function YV($,_,J){if(!_)return[];try{return zy($,_,J)}catch{return[]}}function zy($,_,J){return $.query(`SELECT chunks_fts.chunk_id, c.kind AS chunk_kind, c.wiki_page_id, @@ -724,49 +785,49 @@ COMMIT; LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id WHERE chunks_fts MATCH ? ORDER BY rank ASC - LIMIT ?`).all(_,J)}function $V($,_){if(_.length===0)return"1 = 0";return _.map(()=>`(${$.map((U)=>`lower(COALESCE(${U}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`).join(" OR ")}function uv($,_,J){let U=["path","title","artifact_uri","metadata_json"];return $.query(`SELECT id, path, title, artifact_uri, content_hash, status, metadata_json + LIMIT ?`).all(_,J)}function jV($,_){if(_.length===0)return"1 = 0";return _.map(()=>`(${$.map((U)=>`lower(COALESCE(${U}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`).join(" OR ")}function jy($,_,J){let U=["path","title","artifact_uri","metadata_json"];return $.query(`SELECT id, path, title, artifact_uri, content_hash, status, metadata_json FROM wiki_pages - WHERE status = 'active' AND (${$V(U,_)}) + WHERE status = 'active' AND (${jV(U,_)}) ORDER BY updated_at DESC - LIMIT ?`).all(...e3(_,U.length),J)}function dv($,_,J){let U=["kind","name","shard_key","artifact_uri","metadata_json"];return $.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json + LIMIT ?`).all(...zV(_,U.length),J)}function Dy($,_,J){let U=["kind","name","shard_key","artifact_uri","metadata_json"];return $.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json FROM knowledge_indexes - WHERE ${$V(U,_)} + WHERE ${jV(U,_)} ORDER BY updated_at DESC - LIMIT ?`).all(...e3(_,U.length),J)}function _V($){if(!$||!Cv($))return[];try{let _=JSON.parse(Pv($,"utf8"));if(!_||!Array.isArray(_.items))return[];return _.items.filter((J)=>{return Boolean(J&&typeof J==="object"&&typeof J.id==="string"&&typeof J.title==="string"&&typeof J.content==="string")})}catch{return[]}}function cv($){return[$.id,$.short_id,$.title,$.content,$.url,...$.tags??[]].filter((_)=>typeof _==="string"&&_.length>0).join(" ").toLowerCase()}function JV($,_,J){if(_.length===0)return[];return $.filter((U)=>U.archived!==!0).map((U)=>({item:U,haystack:cv(U)})).filter(({haystack:U})=>_.some((W)=>U.includes(W))).map(({item:U,haystack:W})=>({item:U,score:SY(W,_)})).sort((U,W)=>W.score-U.score||U.item.id.localeCompare(W.item.id)).slice(0,J)}function lv($,_,J){return JV(_V($),_,J)}function nv($,_){let J=i9($.chunk_metadata_json),U=mv($),W=U4(J,["source_ref"]),X=$.source_uri??U4(J,["source_uri"]),G=Boolean($.wiki_page_id),Q={kind:G?"wiki_chunk":"source_chunk",id:$.chunk_id,title:G?$.wiki_title:$.source_title,text:$.text,score:0,scores:{keyword:_},source:X||W?{uri:X,ref:W,kind:$.source_kind??U4(J,["source_kind"]),revision:$.revision??U4(J,["revision"]),hash:$.hash??U4(J,["hash"])}:null,citation:{chunk_id:$.chunk_id,start_offset:$.start_offset,end_offset:$.end_offset},artifact:G?{uri:$.wiki_artifact_uri,path:$.wiki_path,hash:$.wiki_content_hash,shard_key:$.wiki_path}:null,provenance:U,reasons:["keyword_match"]};return Q.score=fJ(Q.scores,Q.citation),Q}function WV($,_){let J=`knowledge://item/${encodeURIComponent($.id)}`,U={kind:"legacy_item",id:$.id,title:$.title,text:$.content,score:0,scores:{keyword:_},source:{uri:J,ref:J,kind:"legacy_item",revision:null,hash:null},citation:null,artifact:null,provenance:null,reasons:["legacy_note_match","keyword_match"]};return U.score=fJ(U.scores,U.citation),U}function iv($,_){let J=i9($.metadata_json),U=SY(`${$.path} ${$.title} ${$.artifact_uri??""} ${$.metadata_json}`.toLowerCase(),_),W={kind:"wiki_page",id:$.id,title:$.title,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:$.artifact_uri,path:$.path,hash:$.content_hash,shard_key:$.path},provenance:ZY(J),reasons:["wiki_catalog_match"]};return W.score=fJ(W.scores,W.citation),W}function rv($,_){let J=i9($.metadata_json),U=SY(`${$.kind} ${$.name} ${$.shard_key??""} ${$.artifact_uri??""} ${$.metadata_json}`.toLowerCase(),_),W={kind:"knowledge_index",id:$.id,title:$.name,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:$.artifact_uri,path:U4(J,["artifact_key"]),hash:U4(J,["content_hash"]),shard_key:$.shard_key},provenance:ZY(J),reasons:["index_catalog_match"]};return W.score=fJ(W.scores,W.citation),W}function kJ($,_){let J=`${_.kind}:${_.id}`,U=$.get(J);if(!U){$.set(J,_);return}U.scores={keyword:Math.max(U.scores.keyword??0,_.scores.keyword??0)||void 0,semantic:Math.max(U.scores.semantic??0,_.scores.semantic??0)||void 0,catalog:Math.max(U.scores.catalog??0,_.scores.catalog??0)||void 0},U.reasons=a3([...U.reasons,..._.reasons]),U.text=U.text??_.text,U.title=U.title??_.title,U.source=U.source??_.source,U.citation=U.citation??_.citation,U.artifact=U.artifact??_.artifact,U.provenance=U.provenance??_.provenance,U.score=fJ(U.scores,U.citation)}function UV($){let _={source_chunk:0,wiki_chunk:1,legacy_item:2,wiki_page:3,knowledge_index:4};return $.sort((J,U)=>{if(U.score!==J.score)return U.score-J.score;return _[J.kind]-_[U.kind]||J.id.localeCompare(U.id)})}async function p9($){let _=$.query.trim();if(!_)throw Error("Search query is required.");let J=Math.max(1,Math.min($.limit??10,100)),U=Math.max(0,Math.floor($.offset??0)),W=U+J,X=s3(_),G=Zv(_),Q=$.semantic===!0||$.fake===!0||Boolean($.modelRef),Y=[],q=null,L=null,N=null,F=0,B=0,H=0,V=new Map;G$($.dbPath);let R=i($.dbPath);try{let w=Math.max(W*3,20),b=t3(R,G.and,w);if(b.length===0&&G.or)b=t3(R,G.or,w);F=b.length,b.forEach((x,Y6)=>kJ(V,nv(x,yv(x.rank,Y6))));let I=uv(R,X,Math.max(W,10)),v=dv(R,X,Math.max(W,10)),g=lv($.legacyStorePath,X,Math.max(W,10));B=I.length+v.length,F+=g.length,g.forEach(({item:x,score:Y6})=>kJ(V,WV(x,Y6))),I.forEach((x)=>kJ(V,iv(x,X))),v.forEach((x)=>kJ(V,rv(x,X)))}finally{R.close()}if(Q)try{let w=await n9({dbPath:$.dbPath,query:_,limit:Math.max(W*3,20),config:$.config,env:$.env,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake,batchSize:$.batchSize,maxParallelCalls:$.maxParallelCalls});q=w.provider,L=w.model,N=w.dimensions,H=w.results.length;for(let b of w.results){let I={kind:"source_chunk",id:b.chunk_id,title:null,text:b.text,score:0,scores:{semantic:hv(b.score)},source:{uri:b.source_uri,ref:b.source_ref,kind:b.provenance?.source_kind??null,revision:b.revision,hash:b.hash},citation:{chunk_id:b.chunk_id,start_offset:b.provenance?.start_offset??null,end_offset:b.provenance?.end_offset??null},artifact:null,provenance:b.provenance,reasons:["semantic_match"]};I.score=fJ(I.scores,I.citation),kJ(V,I)}}catch(w){Y.push(`semantic_search_failed: ${w instanceof Error?w.message:String(w)}`)}let K=UV(Array.from(V.values())).slice(U,U+J);return{query:_,limit:J,offset:U,mode:{keyword:!0,catalog:!0,semantic:Q},semantic_provider:q,semantic_model:L,semantic_dimensions:N,counts:{keyword_results:F,catalog_results:B,semantic_results:H,merged_results:K.length},warnings:Y,results:K}}async function o9($){return w2(_V($.legacyStorePath),$,["knowledge_db_missing"])}async function w2($,_,J=[]){let U=_.query.trim();if(!U)throw Error("Search query is required.");let W=Math.max(1,Math.min(_.limit??10,100)),X=Math.max(0,Math.floor(_.offset??0)),G=s3(U),Q=_.semantic===!0||_.fake===!0||Boolean(_.modelRef),Y=new Map,q=JV($,G,Math.max(X+W,10));q.forEach(({item:F,score:B})=>kJ(Y,WV(F,B)));let L=[...J];if(Q)L.push("semantic_search_requires_local_catalog");let N=UV(Array.from(Y.values())).slice(X,X+W);return{query:U,limit:W,offset:X,mode:{keyword:!0,catalog:!0,semantic:Q},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:q.length,catalog_results:0,semantic_results:0,merged_results:N.length},warnings:L,results:N}}function XV($,_){return`${$}_${pv("sha256").update(_).digest("hex").slice(0,20)}`}function GV($){return $.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function ov($){return Array.from(new Set(GV($).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,16)}function tv($){return[$.title,$.text].filter(Boolean).join(" ").toLowerCase()}function av($,_){if(_.length===0)return 0;let J=tv($),U=_.filter((W)=>J.includes(W)).length;return Number((U/_.length).toFixed(6))}function sv($){if(!$)return!0;if("read_only"in $)return $.read_only===!0;if("read_only_sources"in $)return $.read_only_sources===!0;return!0}function QV($){if(!$)return!1;if("stale"in $&&$.stale)return!0;if("status"in $)return KY($.status);return!1}function ev($){if(QV($.provenance))return 0;if($.source?.hash||$.source?.revision)return 1;if($.artifact?.hash)return 0.85;if($.provenance&&"source_refs"in $.provenance&&$.provenance.source_refs.length>0)return 0.75;return 0.55}function $y($){if($.citation?.chunk_id&&($.source?.uri||$.artifact?.uri))return 1;if($.provenance&&"citation_required"in $.provenance&&$.provenance.citation_required)return 0.75;if($.artifact?.uri)return 0.65;return 0.35}function _y($){if($.kind==="wiki_chunk")return 0.85;if($.kind==="source_chunk")return 0.8;if($.kind==="legacy_item")return 0.6;if($.kind==="wiki_page")return 0.65;return 0.55}function Jy($,_){let J={base_score:$.score,exact_score:av($,_),citation_score:$y($),freshness_score:ev($),authority_score:_y($)},U=Math.min(1,J.base_score*0.65+J.exact_score*0.1+J.citation_score*0.1+J.freshness_score*0.1+J.authority_score*0.05),W=new Set($.reasons);if(J.exact_score>0.5)W.add("exact_term");if(J.citation_score>=0.75)W.add("cited_source");if(J.freshness_score>=0.85)W.add("fresh_source");return{...$,score:Number(U.toFixed(6)),reasons:Array.from(W),rerank:{...J,final_score:Number(U.toFixed(6))}}}function YV($,_){let J=$.text??$.title;if(!J)return null;let U=J.replace(/\s+/g," ").trim();return U.length<=_?U:`${U.slice(0,Math.max(0,_-1)).trim()}...`}function Wy($){return{id:XV("cite",`${$.kind}\x00${$.id}\x00${$.source?.uri??""}\x00${$.artifact?.uri??""}`),result_id:$.id,kind:$.kind,source_uri:$.source?.uri??null,source_ref:$.source?.ref??null,artifact_uri:$.artifact?.uri??null,artifact_path:$.artifact?.path??null,revision:$.source?.revision??null,hash:$.source?.hash??$.artifact?.hash??null,chunk_id:$.citation?.chunk_id??null,start_offset:$.citation?.start_offset??null,end_offset:$.citation?.end_offset??null,quote:YV($,500),provenance:$.provenance}}function Uy($,_,J){let U=YV($,J);if(!U)return null;return{id:XV("excerpt",`${$.kind}\x00${$.id}`),result_id:$.id,citation_id:_.id,kind:$.kind,text:U,score:$.score}}function t9($){return $.map(()=>"?").join(", ")}function Xy($,_){let J=_.map((Q)=>Q.citation?.chunk_id).filter((Q)=>Boolean(Q)),U=_.filter((Q)=>Q.kind==="wiki_page").map((Q)=>Q.id),W=[],X=[];if(J.length===0&&U.length===0)return{citations:W,backlinks:X};let G=i($);try{if(J.length>0)W.push(...G.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset + LIMIT ?`).all(...zV(_,U.length),J)}function DV($){if(!$||!_y($))return[];try{let _=JSON.parse(Jy($,"utf8"));if(!_||!Array.isArray(_.items))return[];return _.items.filter((J)=>{return Boolean(J&&typeof J==="object"&&typeof J.id==="string"&&typeof J.title==="string"&&typeof J.content==="string")})}catch{return[]}}function Oy($){return[$.id,$.short_id,$.title,$.content,$.url,...$.tags??[]].filter((_)=>typeof _==="string"&&_.length>0).join(" ").toLowerCase()}function OV($,_,J){if(_.length===0)return[];return $.filter((U)=>U.archived!==!0).map((U)=>({item:U,haystack:Oy(U)})).filter(({haystack:U})=>_.some((W)=>U.includes(W))).map(({item:U,haystack:W})=>({item:U,score:uQ(W,_)})).sort((U,W)=>W.score-U.score||U.item.id.localeCompare(W.item.id)).slice(0,J)}function Ly($,_,J){return OV(DV($),_,J)}function By($,_){let J=a9($.chunk_metadata_json),U=qy($),W=G6(J,["source_ref"]),X=$.source_uri??G6(J,["source_uri"]),G=Boolean($.wiki_page_id),Y={kind:G?"wiki_chunk":"source_chunk",id:$.chunk_id,title:G?$.wiki_title:$.source_title,text:$.text,score:0,scores:{keyword:_},source:X||W?{uri:X,ref:W,kind:$.source_kind??G6(J,["source_kind"]),revision:$.revision??G6(J,["revision"]),hash:$.hash??G6(J,["hash"])}:null,citation:{chunk_id:$.chunk_id,start_offset:$.start_offset,end_offset:$.end_offset},artifact:G?{uri:$.wiki_artifact_uri,path:$.wiki_path,hash:$.wiki_content_hash,shard_key:$.wiki_path}:null,provenance:U,reasons:["keyword_match"]};return Y.score=ZJ(Y.scores,Y.citation),Y}function LV($,_){let J=`knowledge://item/${encodeURIComponent($.id)}`,U={kind:"legacy_item",id:$.id,title:$.title,text:$.content,score:0,scores:{keyword:_},source:{uri:J,ref:J,kind:"legacy_item",revision:null,hash:null},citation:null,artifact:null,provenance:null,reasons:["legacy_note_match","keyword_match"]};return U.score=ZJ(U.scores,U.citation),U}function Hy($,_){let J=a9($.metadata_json),U=uQ(`${$.path} ${$.title} ${$.artifact_uri??""} ${$.metadata_json}`.toLowerCase(),_),W={kind:"wiki_page",id:$.id,title:$.title,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:$.artifact_uri,path:$.path,hash:$.content_hash,shard_key:$.path},provenance:dQ(J),reasons:["wiki_catalog_match"]};return W.score=ZJ(W.scores,W.citation),W}function Ny($,_){let J=a9($.metadata_json),U=uQ(`${$.kind} ${$.name} ${$.shard_key??""} ${$.artifact_uri??""} ${$.metadata_json}`.toLowerCase(),_),W={kind:"knowledge_index",id:$.id,title:$.name,text:null,score:0,scores:{catalog:U},source:null,citation:null,artifact:{uri:$.artifact_uri,path:G6(J,["artifact_key"]),hash:G6(J,["content_hash"]),shard_key:$.shard_key},provenance:dQ(J),reasons:["index_catalog_match"]};return W.score=ZJ(W.scores,W.citation),W}function SJ($,_){let J=`${_.kind}:${_.id}`,U=$.get(J);if(!U){$.set(J,_);return}U.scores={keyword:Math.max(U.scores.keyword??0,_.scores.keyword??0)||void 0,semantic:Math.max(U.scores.semantic??0,_.scores.semantic??0)||void 0,catalog:Math.max(U.scores.catalog??0,_.scores.catalog??0)||void 0},U.reasons=QV([...U.reasons,..._.reasons]),U.text=U.text??_.text,U.title=U.title??_.title,U.source=U.source??_.source,U.citation=U.citation??_.citation,U.artifact=U.artifact??_.artifact,U.provenance=U.provenance??_.provenance,U.score=ZJ(U.scores,U.citation)}function BV($){let _={source_chunk:0,wiki_chunk:1,legacy_item:2,wiki_page:3,knowledge_index:4};return $.sort((J,U)=>{if(U.score!==J.score)return U.score-J.score;return _[J.kind]-_[U.kind]||J.id.localeCompare(U.id)})}async function e9($){let _=$.query.trim();if(!_)throw Error("Search query is required.");let J=Math.max(1,Math.min($.limit??10,100)),U=Math.max(0,Math.floor($.offset??0)),W=U+J,X=qV(_),G=Xy(_),Y=$.semantic===!0||$.fake===!0||Boolean($.modelRef),Q=[],q=null,L=null,N=null,R=0,B=0,H=0,V=new Map;a($.dbPath);let K=m($.dbPath);try{let w=Math.max(W*3,20),A=YV(K,G.and,w);if(A.length===0&&G.or)A=YV(K,G.or,w);R=A.length,A.forEach((u,W_)=>SJ(V,By(u,Yy(u.rank,W_))));let g=jy(K,X,Math.max(W,10)),v=Dy(K,X,Math.max(W,10)),k=Ly($.legacyStorePath,X,Math.max(W,10));B=g.length+v.length,R+=k.length,k.forEach(({item:u,score:W_})=>SJ(V,LV(u,W_))),g.forEach((u)=>SJ(V,Hy(u,X))),v.forEach((u)=>SJ(V,Ny(u,X)))}finally{K.close()}if(Y)try{let w=await t9({dbPath:$.dbPath,query:_,limit:Math.max(W*3,20),config:$.config,env:$.env,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake,batchSize:$.batchSize,maxParallelCalls:$.maxParallelCalls});q=w.provider,L=w.model,N=w.dimensions,H=w.results.length;for(let A of w.results){let g={kind:"source_chunk",id:A.chunk_id,title:null,text:A.text,score:0,scores:{semantic:Qy(A.score)},source:{uri:A.source_uri,ref:A.source_ref,kind:A.provenance?.source_kind??null,revision:A.revision,hash:A.hash},citation:{chunk_id:A.chunk_id,start_offset:A.provenance?.start_offset??null,end_offset:A.provenance?.end_offset??null},artifact:null,provenance:A.provenance,reasons:["semantic_match"]};g.score=ZJ(g.scores,g.citation),SJ(V,g)}}catch(w){Q.push(`semantic_search_failed: ${w instanceof Error?w.message:String(w)}`)}let F=BV(Array.from(V.values())).slice(U,U+J);return{query:_,limit:J,offset:U,mode:{keyword:!0,catalog:!0,semantic:Y},semantic_provider:q,semantic_model:L,semantic_dimensions:N,counts:{keyword_results:R,catalog_results:B,semantic_results:H,merged_results:F.length},warnings:Q,results:F}}async function $8($){return I1(DV($.legacyStorePath),$,["knowledge_db_missing"])}async function I1($,_,J=[]){let U=_.query.trim();if(!U)throw Error("Search query is required.");let W=Math.max(1,Math.min(_.limit??10,100)),X=Math.max(0,Math.floor(_.offset??0)),G=qV(U),Y=_.semantic===!0||_.fake===!0||Boolean(_.modelRef),Q=new Map,q=OV($,G,Math.max(X+W,10));q.forEach(({item:R,score:B})=>SJ(Q,LV(R,B)));let L=[...J];if(Y)L.push("semantic_search_requires_local_catalog");let N=BV(Array.from(Q.values())).slice(X,X+W);return{query:U,limit:W,offset:X,mode:{keyword:!0,catalog:!0,semantic:Y},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:q.length,catalog_results:0,semantic_results:0,merged_results:N.length},warnings:L,results:N}}function HV($,_){return`${$}_${Vy("sha256").update(_).digest("hex").slice(0,20)}`}function NV($){return $.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function Ry($){return Array.from(new Set(NV($).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,16)}function Ky($){return[$.title,$.text].filter(Boolean).join(" ").toLowerCase()}function Fy($,_){if(_.length===0)return 0;let J=Ky($),U=_.filter((W)=>J.includes(W)).length;return Number((U/_.length).toFixed(6))}function Ey($){if(!$)return!0;if("read_only"in $)return $.read_only===!0;if("read_only_sources"in $)return $.read_only_sources===!0;return!0}function VV($){if(!$)return!1;if("stale"in $&&$.stale)return!0;if("status"in $)return kQ($.status);return!1}function My($){if(VV($.provenance))return 0;if($.source?.hash||$.source?.revision)return 1;if($.artifact?.hash)return 0.85;if($.provenance&&"source_refs"in $.provenance&&$.provenance.source_refs.length>0)return 0.75;return 0.55}function Ay($){if($.citation?.chunk_id&&($.source?.uri||$.artifact?.uri))return 1;if($.provenance&&"citation_required"in $.provenance&&$.provenance.citation_required)return 0.75;if($.artifact?.uri)return 0.65;return 0.35}function by($){if($.kind==="wiki_chunk")return 0.85;if($.kind==="source_chunk")return 0.8;if($.kind==="legacy_item")return 0.6;if($.kind==="wiki_page")return 0.65;return 0.55}function wy($,_){let J={base_score:$.score,exact_score:Fy($,_),citation_score:Ay($),freshness_score:My($),authority_score:by($)},U=Math.min(1,J.base_score*0.65+J.exact_score*0.1+J.citation_score*0.1+J.freshness_score*0.1+J.authority_score*0.05),W=new Set($.reasons);if(J.exact_score>0.5)W.add("exact_term");if(J.citation_score>=0.75)W.add("cited_source");if(J.freshness_score>=0.85)W.add("fresh_source");return{...$,score:Number(U.toFixed(6)),reasons:Array.from(W),rerank:{...J,final_score:Number(U.toFixed(6))}}}function RV($,_){let J=$.text??$.title;if(!J)return null;let U=J.replace(/\s+/g," ").trim();return U.length<=_?U:`${U.slice(0,Math.max(0,_-1)).trim()}...`}function gy($){return{id:HV("cite",`${$.kind}\x00${$.id}\x00${$.source?.uri??""}\x00${$.artifact?.uri??""}`),result_id:$.id,kind:$.kind,source_uri:$.source?.uri??null,source_ref:$.source?.ref??null,artifact_uri:$.artifact?.uri??null,artifact_path:$.artifact?.path??null,revision:$.source?.revision??null,hash:$.source?.hash??$.artifact?.hash??null,chunk_id:$.citation?.chunk_id??null,start_offset:$.citation?.start_offset??null,end_offset:$.citation?.end_offset??null,quote:RV($,500),provenance:$.provenance}}function ky($,_,J){let U=RV($,J);if(!U)return null;return{id:HV("excerpt",`${$.kind}\x00${$.id}`),result_id:$.id,citation_id:_.id,kind:$.kind,text:U,score:$.score}}function _8($){return $.map(()=>"?").join(", ")}function Iy($,_){let J=_.map((Y)=>Y.citation?.chunk_id).filter((Y)=>Boolean(Y)),U=_.filter((Y)=>Y.kind==="wiki_page").map((Y)=>Y.id),W=[],X=[];if(J.length===0&&U.length===0)return{citations:W,backlinks:X};let G=m($);try{if(J.length>0)W.push(...G.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset FROM citations - WHERE chunk_id IN (${t9(J)}) + WHERE chunk_id IN (${_8(J)}) ORDER BY created_at DESC LIMIT 50`).all(...J));if(U.length>0)W.push(...G.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset FROM citations - WHERE wiki_page_id IN (${t9(U)}) + WHERE wiki_page_id IN (${_8(U)}) ORDER BY created_at DESC LIMIT 50`).all(...U)),X.push(...G.query(`SELECT from_page_id, to_page_id, label FROM wiki_backlinks - WHERE from_page_id IN (${t9(U)}) OR to_page_id IN (${t9(U)}) - LIMIT 50`).all(...U,...U))}finally{G.close()}return{citations:W,backlinks:X}}function CJ($,_={}){let J=Math.max(200,Math.min(_.contextChars??1200,4000)),U=ov($.query),W=[...$.warnings],X=new Set,G=new Set,Y=$.results.filter((N)=>{if(!sv(N.provenance))return W.push(`permission_filtered: ${N.kind}:${N.id}`),X.add("Dropped a result because provenance was not read-only."),!1;if(QV(N.provenance))return W.push(`stale_filtered: ${N.kind}:${N.id}`),G.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((N)=>Jy(N,U)).sort((N,F)=>F.score-N.score||N.id.localeCompare(F.id)).slice(0,$.limit),q=Y.map(Wy),L=Y.map((N,F)=>Uy(N,q[F],J)).filter((N)=>Boolean(N));for(let N of Y){if(N.provenance&&"read_only"in N.provenance&&N.provenance.read_only)X.add("All source-backed excerpts are read-only and citation-required.");if(N.rerank.freshness_score>=0.85)G.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:$.query,normalized_query:GV($.query),created_at:new Date().toISOString(),mode:$.mode,warnings:W,search_counts:$.counts,results:Y,citations:q,excerpts:L,graph:_.dbPath?Xy(_.dbPath,Y):{citations:[],backlinks:[]},notes:{permissions:Array.from(X),freshness:Array.from(G)}}}async function PJ($){let _=await p9($);return CJ(_,{dbPath:$.dbPath,contextChars:$.contextChars})}async function a9($,_){let J=await w2($,_);return CJ(J,{contextChars:_.contextChars})}function TJ($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function yY($){return`C${$+1}`}function zV($,_){if(_.excerpts.length===0)return`No indexed knowledge matched the prompt: ${$}`;return[`Found ${_.excerpts.length} relevant knowledge excerpt(s) for: ${$}`,"",..._.excerpts.slice(0,5).map((U,W)=>{let X=_.citations.find((Q)=>Q.id===U.citation_id),G=X?.source_ref??X?.source_uri??X?.artifact_path??X?.artifact_uri??"unknown source";return`[${yY(W)}] ${U.text} (${G})`})].join(` -`)}function jV($,_){let J=_.citations.map((W,X)=>({id:yY(X),source_ref:W.source_ref,source_uri:W.source_uri,artifact_path:W.artifact_path,revision:W.revision,hash:W.hash,quote:W.quote})),U=_.excerpts.map((W,X)=>({id:yY(X),kind:W.kind,text:W.text,score:W.score}));return[`Prompt: ${$}`,"","Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.","",`Context excerpts: + WHERE from_page_id IN (${_8(U)}) OR to_page_id IN (${_8(U)}) + LIMIT 50`).all(...U,...U))}finally{G.close()}return{citations:W,backlinks:X}}function vJ($,_={}){let J=Math.max(200,Math.min(_.contextChars??1200,4000)),U=Ry($.query),W=[...$.warnings],X=new Set,G=new Set,Q=$.results.filter((N)=>{if(!Ey(N.provenance))return W.push(`permission_filtered: ${N.kind}:${N.id}`),X.add("Dropped a result because provenance was not read-only."),!1;if(VV(N.provenance))return W.push(`stale_filtered: ${N.kind}:${N.id}`),G.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((N)=>wy(N,U)).sort((N,R)=>R.score-N.score||N.id.localeCompare(R.id)).slice(0,$.limit),q=Q.map(gy),L=Q.map((N,R)=>ky(N,q[R],J)).filter((N)=>Boolean(N));for(let N of Q){if(N.provenance&&"read_only"in N.provenance&&N.provenance.read_only)X.add("All source-backed excerpts are read-only and citation-required.");if(N.rerank.freshness_score>=0.85)G.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:$.query,normalized_query:NV($.query),created_at:new Date().toISOString(),mode:$.mode,warnings:W,search_counts:$.counts,results:Q,citations:q,excerpts:L,graph:_.dbPath?Iy(_.dbPath,Q):{citations:[],backlinks:[]},notes:{permissions:Array.from(X),freshness:Array.from(G)}}}async function yJ($){let _=await e9($);return vJ(_,{dbPath:$.dbPath,contextChars:$.contextChars})}async function J8($,_){let J=await I1($,_);return vJ(J,{contextChars:_.contextChars})}function hJ($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function cQ($){return`C${$+1}`}function FV($,_){if(_.excerpts.length===0)return`No indexed knowledge matched the prompt: ${$}`;return[`Found ${_.excerpts.length} relevant knowledge excerpt(s) for: ${$}`,"",..._.excerpts.slice(0,5).map((U,W)=>{let X=_.citations.find((Y)=>Y.id===U.citation_id),G=X?.source_ref??X?.source_uri??X?.artifact_path??X?.artifact_uri??"unknown source";return`[${cQ(W)}] ${U.text} (${G})`})].join(` +`)}function EV($,_){let J=_.citations.map((W,X)=>({id:cQ(X),source_ref:W.source_ref,source_uri:W.source_uri,artifact_path:W.artifact_path,revision:W.revision,hash:W.hash,quote:W.quote})),U=_.excerpts.map((W,X)=>({id:cQ(X),kind:W.kind,text:W.text,score:W.score}));return[`Prompt: ${$}`,"","Use only the provided context. Cite claims with citation ids like [C1]. If context is insufficient, say what is missing.","",`Context excerpts: ${JSON.stringify(U,null,2)}`,"",`Citations: ${JSON.stringify(J,null,2)}`].join(` -`)}function OV($,_){if(_.citations.length===0)return[];return[{kind:"answer_note",title:$.length>80?`${$.slice(0,77)}...`:$,citations:_.citations.map((J)=>J.id),requires_approval:!0}]}function Gy($,_){let J=i($);try{J.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[_.runId,"knowledge-prompt",_.prompt,_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.now])}finally{J.close()}}function vY($,_){let J=i($);try{J.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${hY()}`,_.runId,_.level,_.event,JSON.stringify(_.metadata),_.now])}finally{J.close()}}function qV($,_){let J=i($);try{J.run(`UPDATE runs +`)}function MV($,_){if(_.citations.length===0)return[];return[{kind:"answer_note",title:$.length>80?`${$.slice(0,77)}...`:$,citations:_.citations.map((J)=>J.id),requires_approval:!0}]}function fy($,_){let J=m($);try{J.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[_.runId,"knowledge-prompt",_.prompt,_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.now])}finally{J.close()}}function nQ($,_){let J=m($);try{J.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${iQ()}`,_.runId,_.level,_.event,JSON.stringify(_.metadata),_.now])}finally{J.close()}}function KV($,_){let J=m($);try{J.run(`UPDATE runs SET status = ?, provider = ?, model = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`,[_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.runId])}finally{J.close()}}function Qy($,_,J,U,W,X,G={}){let Q=i($);try{gJ(Q,{run_id:_,provider:U,model:W,input_tokens:J.input_tokens,output_tokens:J.output_tokens,cost_usd:J.cost_usd,metadata:G,created_at:X})}finally{Q.close()}}async function DV($){let _=$.prompt.trim();if(!_)throw Error("Knowledge prompt is required.");let J=($.now??new Date).toISOString(),U=`run_${hY()}`,W=y4($.modelRef??"default",$.config),X=E6(W);G$($.dbPath),Gy($.dbPath,{runId:U,prompt:_,status:$.generate?"running":"dry_run",provider:$.generate?X.provider:"local",model:$.generate?X.model:"context-draft",metadata:{semantic:$.semantic===!0||$.fake===!0||Boolean($.modelRef),approve_write:$.approveWrite===!0,generated:$.generate===!0},now:J});let{prompt:G,generate:Q,approveWrite:Y,now:q,...L}=$,N=await PJ({...L,query:_});vY($.dbPath,{runId:U,level:"info",event:"context_retrieved",metadata:{results:N.results.length,citations:N.citations.length,warnings:N.warnings},now:J});let F=zV(_,N),B=!1,H="local",V="context-draft",R={input_tokens:TJ(_)+N.excerpts.reduce((b,I)=>b+TJ(I.text),0),output_tokens:TJ(F),cost_usd:0},M=[...N.warnings];if($.generate)try{if($.fake)B=!0,H=X.provider,V=X.model,F=`Fake generated answer for: ${_} + WHERE id = ?`,[_.status,_.provider,_.model,JSON.stringify(_.metadata),_.now,_.runId])}finally{J.close()}}function Cy($,_,J,U,W,X,G={}){let Y=m($);try{TJ(Y,{run_id:_,provider:U,model:W,input_tokens:J.input_tokens,output_tokens:J.output_tokens,cost_usd:J.cost_usd,metadata:G,created_at:X})}finally{Y.close()}}async function AV($){let _=$.prompt.trim();if(!_)throw Error("Knowledge prompt is required.");let J=($.now??new Date).toISOString(),U=`run_${iQ()}`,W=y6($.modelRef??"default",$.config),X=w_(W);a($.dbPath),fy($.dbPath,{runId:U,prompt:_,status:$.generate?"running":"dry_run",provider:$.generate?X.provider:"local",model:$.generate?X.model:"context-draft",metadata:{semantic:$.semantic===!0||$.fake===!0||Boolean($.modelRef),approve_write:$.approveWrite===!0,generated:$.generate===!0},now:J});let{prompt:G,generate:Y,approveWrite:Q,now:q,...L}=$,N=await yJ({...L,query:_});nQ($.dbPath,{runId:U,level:"info",event:"context_retrieved",metadata:{results:N.results.length,citations:N.citations.length,warnings:N.warnings},now:J});let R=FV(_,N),B=!1,H="local",V="context-draft",K={input_tokens:hJ(_)+N.excerpts.reduce((A,g)=>A+hJ(g.text),0),output_tokens:hJ(R),cost_usd:0},E=[...N.warnings];if($.generate)try{if($.fake)B=!0,H=X.provider,V=X.model,R=`Fake generated answer for: ${_} -${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:$.config,env:$.env}),v=await b({model:I,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:jV(_,N)});B=!0,H=X.provider,V=X.model,F=v.text;let g=b2({provider:H,model:V,usage:v.usage,providerMetadata:v.providerMetadata});R={input_tokens:g.input_tokens,output_tokens:g.output_tokens,cost_usd:g.cost_usd}}}catch(b){throw vY($.dbPath,{runId:U,level:"error",event:"answer_generation_failed",metadata:{message:b instanceof Error?b.message:String(b)},now:J}),qV($.dbPath,{runId:U,status:"failed",provider:X.provider,model:X.model,metadata:{generated:!1,error:b instanceof Error?b.message:String(b)},now:J}),b}let K=OV(_,N),w={approved:$.approveWrite===!0,durable_writes_performed:!1,reason:$.approveWrite?"Approval flag recorded; durable wiki writing is deferred to the wiki compile task.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return vY($.dbPath,{runId:U,level:"info",event:B?"answer_generated":"answer_drafted",metadata:{provider:H,model:V,proposed_updates:K.length,durable_writes_performed:!1},now:J}),Qy($.dbPath,U,R,H,V,J,{generated:B,citations:N.citations.length}),qV($.dbPath,{runId:U,status:B?"completed":"dry_run",provider:H,model:V,metadata:{generated:B,citations:N.citations.length,proposed_updates:K.length,approve_write:$.approveWrite===!0},now:J}),{run_id:U,prompt:_,generated:B,provider:H,model:V,answer:F,context:N,citations:N.citations,proposed_wiki_updates:K,write_policy:w,usage:R,warnings:M}}async function LV($,_){let J=_.prompt.trim();if(!J)throw Error("Knowledge prompt is required.");let U=`run_${hY()}`,W=y4(_.modelRef??"default",_.config),X=E6(W),{prompt:G,generate:Q,approveWrite:Y,now:q,...L}=_,N=await a9($,{...L,query:J}),F=zV(J,N),B=!1,H="local",V="context-draft",R={input_tokens:TJ(J)+N.excerpts.reduce((b,I)=>b+TJ(I.text),0),output_tokens:TJ(F),cost_usd:0},M=[...N.warnings];if(_.generate)if(_.fake)B=!0,H=X.provider,V=X.model,F=`Fake generated answer for: ${J} +${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:$.config,env:$.env}),v=await A({model:g,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:EV(_,N)});B=!0,H=X.provider,V=X.model,R=v.text;let k=g1({provider:H,model:V,usage:v.usage,providerMetadata:v.providerMetadata});K={input_tokens:k.input_tokens,output_tokens:k.output_tokens,cost_usd:k.cost_usd}}}catch(A){throw nQ($.dbPath,{runId:U,level:"error",event:"answer_generation_failed",metadata:{message:A instanceof Error?A.message:String(A)},now:J}),KV($.dbPath,{runId:U,status:"failed",provider:X.provider,model:X.model,metadata:{generated:!1,error:A instanceof Error?A.message:String(A)},now:J}),A}let F=MV(_,N),w={approved:$.approveWrite===!0,durable_writes_performed:!1,reason:$.approveWrite?"Approval flag recorded; durable wiki writing is deferred to the wiki compile task.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return nQ($.dbPath,{runId:U,level:"info",event:B?"answer_generated":"answer_drafted",metadata:{provider:H,model:V,proposed_updates:F.length,durable_writes_performed:!1},now:J}),Cy($.dbPath,U,K,H,V,J,{generated:B,citations:N.citations.length}),KV($.dbPath,{runId:U,status:B?"completed":"dry_run",provider:H,model:V,metadata:{generated:B,citations:N.citations.length,proposed_updates:F.length,approve_write:$.approveWrite===!0},now:J}),{run_id:U,prompt:_,generated:B,provider:H,model:V,answer:R,context:N,citations:N.citations,proposed_wiki_updates:F,write_policy:w,usage:K,warnings:E}}async function bV($,_){let J=_.prompt.trim();if(!J)throw Error("Knowledge prompt is required.");let U=`run_${iQ()}`,W=y6(_.modelRef??"default",_.config),X=w_(W),{prompt:G,generate:Y,approveWrite:Q,now:q,...L}=_,N=await J8($,{...L,query:J}),R=FV(J,N),B=!1,H="local",V="context-draft",K={input_tokens:hJ(J)+N.excerpts.reduce((A,g)=>A+hJ(g.text),0),output_tokens:hJ(R),cost_usd:0},E=[...N.warnings];if(_.generate)if(_.fake)B=!0,H=X.provider,V=X.model,R=`Fake generated answer for: ${J} -${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:_.config,env:_.env}),v=await b({model:I,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:jV(J,N)});B=!0,H=X.provider,V=X.model,F=v.text;let g=b2({provider:H,model:V,usage:v.usage,providerMetadata:v.providerMetadata});R={input_tokens:g.input_tokens,output_tokens:g.output_tokens,cost_usd:g.cost_usd}}let K=OV(J,N),w={approved:_.approveWrite===!0,durable_writes_performed:!1,reason:_.approveWrite?"Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return{run_id:U,prompt:J,generated:B,provider:H,model:V,answer:F,context:N,citations:N.citations,proposed_wiki_updates:K,write_policy:w,usage:R,warnings:M}}import{createHash as Yy}from"crypto";var qy=1200,zy=6,jy=12000,Oy=50,BV=800;function ZJ($,_,J=16){return`${$}_${Yy("sha256").update(_).digest("hex").slice(0,J)}`}function xY($){return $.normalize("NFKC").trim().replace(/\s+/g," ")}function uY($){return xY($).toLowerCase()}function Dy($){return Array.from(new Set(uY($).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function d0($,_){let J=xY($);if(J.length<=_)return J;let U="...";if(_<=U.length)return J.slice(0,Math.max(0,_));return`${J.slice(0,_-U.length).trim()}${U}`}function HV($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function dY($){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test($)}function mY($){return Object.keys($).filter((_)=>!dY(_)).sort().slice(0,12)}function Ly($,_){for(let J of _){if(dY(J))continue;let U=$[J];if(typeof U==="string"&&U.trim())return U.trim()}return null}function VU($,_){if(!$)return null;let J=i6($,_).text;try{let U=new URL(J),W=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let X of W)U.searchParams.delete(X);for(let[X]of U.searchParams)if(dY(X))U.searchParams.delete(X);return U.toString()}catch{return J}}function z0($,_,J){return VU(Ly($,_),J)}function s9($){let _=[];for(let J of mY($).slice(0,6)){let U=$[J];if(typeof U==="string"&&U.trim())_.push(`${J}=${d0(U,80)}`);else if(typeof U==="number"||typeof U==="boolean")_.push(`${J}=${String(U)}`);else if(U&&typeof U==="object")_.push(`${J}={...}`)}return _.join("; ")}function By($){if(!$.trim())return 0;return Math.max(1,Math.ceil($.length/4))}function NV($){return By(JSON.stringify($))}function Hy($){if(!Number.isFinite($??NaN))return qy;let _=Math.floor($);if(_J.includes(W)).length;return Number((U/_.length).toFixed(6))}function Vy($){return["This pack is read-only and performs no durable writes.","Use citation ids and refs instead of pasting raw artifacts into prompts.","Resolve source or artifact refs explicitly only when raw content is needed and allowed.","Run generated knowledge writes through approval-gated commands before applying.",$==="loops"||$==="runs"?"Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded.":"Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata."]}function Fy($,_,J){let U=VU(_.source_ref,J),W=VU(_.source_uri,J),X=VU(_.artifact_uri,J),G=VU(_.artifact_path,J),Q=U??W??G??X??_.id,Y=_.quote?SJ(_.quote,J,$<3?220:140):null;return{citation:{id:ZJ("cite",`${_.id}\x00${Q}`,12),kind:_.artifact_uri||_.artifact_path?"artifact":"source",ref:Q,source_ref:U,source_uri:W,artifact_uri:X,artifact_path:G,run_id:null,run_event_id:null,revision:_.revision??null,hash:_.hash??null,chunk_id:_.chunk_id??null,offsets:{start:_.start_offset??null,end:_.end_offset??null},quote_preview:Y?.text??null},redactions:Y?.redactions??0}}async function Ry($,_){let J=($.query??$.topic??"").trim();if(!J)throw Error("Context pack query is required for search source.");let{config:U,dbPath:W,limit:X,semantic:G,modelRef:Q,dimensions:Y,fake:q,env:L,batchSize:N,maxParallelCalls:F,legacyStorePath:B}=$,H=await PJ({dbPath:W,config:U,legacyStorePath:B,query:J,limit:Math.max(_,X??_),semantic:G,modelRef:Q,dimensions:Y,fake:q,env:L,batchSize:N,maxParallelCalls:F,contextChars:Math.min($.contextChars??700,1200)}),V=new Map,R=0;H.citations.forEach((b,I)=>{let v=Fy(I,b,$.safetyPolicy);R+=v.redactions,V.set(b.id,v.citation)});let M=H.excerpts.slice(0,Math.max(_*2,_)).map((b)=>{let I=H.results.find((Y6)=>Y6.id===b.result_id),v=b.citation_id?V.get(b.citation_id):null,g=SJ(b.text,$.safetyPolicy,520);R+=g.redactions;let x=I?.title??v?.ref??b.kind;return{id:ZJ("ev",`${b.kind}\x00${b.result_id}\x00${b.citation_id??""}`,14),kind:b.kind,title:d0(x,100),text_preview:g.text,score:Number(b.score.toFixed(6)),citation_ids:v?[v.id]:[],provenance:{source:"search",record_ref:`${b.kind}:${b.result_id}`,created_at:H.created_at,updated_at:null,metadata_keys:[]}}}),K=new Set(M.flatMap((b)=>b.citation_ids));return{citations:Array.from(V.values()).filter((b)=>K.has(b.id)),evidence:M,duplicateCandidates:[],redactions:R,warnings:H.warnings,available:H.excerpts.length}}function Ky($,_,J){if(_)return $.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at +${R}`;else{let{generateText:A}=await import("ai"),g=await EU(W,{config:_.config,env:_.env}),v=await A({model:g,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:EV(J,N)});B=!0,H=X.provider,V=X.model,R=v.text;let k=g1({provider:H,model:V,usage:v.usage,providerMetadata:v.providerMetadata});K={input_tokens:k.input_tokens,output_tokens:k.output_tokens,cost_usd:k.cost_usd}}let F=MV(J,N),w={approved:_.approveWrite===!0,durable_writes_performed:!1,reason:_.approveWrite?"Approval flag recorded; durable wiki writes require the local catalog (wiki compile) and are not available in cloud mode.":"Dry-run mode: proposed wiki updates require approval before durable writes."};return{run_id:U,prompt:J,generated:B,provider:H,model:V,answer:R,context:N,citations:N.citations,proposed_wiki_updates:F,write_policy:w,usage:K,warnings:E}}import{createHash as Py}from"crypto";var Ty=1200,Sy=6,Zy=12000,vy=50,wV=800;function xJ($,_,J=16){return`${$}_${Py("sha256").update(_).digest("hex").slice(0,J)}`}function rQ($){return $.normalize("NFKC").trim().replace(/\s+/g," ")}function pQ($){return rQ($).toLowerCase()}function yy($){return Array.from(new Set(pQ($).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function c4($,_){let J=rQ($);if(J.length<=_)return J;let U="...";if(_<=U.length)return J.slice(0,Math.max(0,_));return`${J.slice(0,_-U.length).trim()}${U}`}function gV($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function oQ($){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test($)}function lQ($){return Object.keys($).filter((_)=>!oQ(_)).sort().slice(0,12)}function hy($,_){for(let J of _){if(oQ(J))continue;let U=$[J];if(typeof U==="string"&&U.trim())return U.trim()}return null}function MU($,_){if(!$)return null;let J=k_($,_).text;try{let U=new URL(J),W=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let X of W)U.searchParams.delete(X);for(let[X]of U.searchParams)if(oQ(X))U.searchParams.delete(X);return U.toString()}catch{return J}}function j4($,_,J){return MU(hy($,_),J)}function W8($){let _=[];for(let J of lQ($).slice(0,6)){let U=$[J];if(typeof U==="string"&&U.trim())_.push(`${J}=${c4(U,80)}`);else if(typeof U==="number"||typeof U==="boolean")_.push(`${J}=${String(U)}`);else if(U&&typeof U==="object")_.push(`${J}={...}`)}return _.join("; ")}function my($){if(!$.trim())return 0;return Math.max(1,Math.ceil($.length/4))}function kV($){return my(JSON.stringify($))}function xy($){if(!Number.isFinite($??NaN))return Ty;let _=Math.floor($);if(_J.includes(W)).length;return Number((U/_.length).toFixed(6))}function dy($){return["This pack is read-only and performs no durable writes.","Use citation ids and refs instead of pasting raw artifacts into prompts.","Resolve source or artifact refs explicitly only when raw content is needed and allowed.","Run generated knowledge writes through approval-gated commands before applying.",$==="loops"||$==="runs"?"Run evidence is summarized from knowledge run ledgers; raw run artifacts remain referenced, not embedded.":"Search evidence is derived from indexed chunks/wiki catalog rows with citation metadata."]}function ny($,_,J){let U=MU(_.source_ref,J),W=MU(_.source_uri,J),X=MU(_.artifact_uri,J),G=MU(_.artifact_path,J),Y=U??W??G??X??_.id,Q=_.quote?mJ(_.quote,J,$<3?220:140):null;return{citation:{id:xJ("cite",`${_.id}\x00${Y}`,12),kind:_.artifact_uri||_.artifact_path?"artifact":"source",ref:Y,source_ref:U,source_uri:W,artifact_uri:X,artifact_path:G,run_id:null,run_event_id:null,revision:_.revision??null,hash:_.hash??null,chunk_id:_.chunk_id??null,offsets:{start:_.start_offset??null,end:_.end_offset??null},quote_preview:Q?.text??null},redactions:Q?.redactions??0}}async function cy($,_){let J=($.query??$.topic??"").trim();if(!J)throw Error("Context pack query is required for search source.");let{config:U,dbPath:W,limit:X,semantic:G,modelRef:Y,dimensions:Q,fake:q,env:L,batchSize:N,maxParallelCalls:R,legacyStorePath:B}=$,H=await yJ({dbPath:W,config:U,legacyStorePath:B,query:J,limit:Math.max(_,X??_),semantic:G,modelRef:Y,dimensions:Q,fake:q,env:L,batchSize:N,maxParallelCalls:R,contextChars:Math.min($.contextChars??700,1200)}),V=new Map,K=0;H.citations.forEach((A,g)=>{let v=ny(g,A,$.safetyPolicy);K+=v.redactions,V.set(A.id,v.citation)});let E=H.excerpts.slice(0,Math.max(_*2,_)).map((A)=>{let g=H.results.find((W_)=>W_.id===A.result_id),v=A.citation_id?V.get(A.citation_id):null,k=mJ(A.text,$.safetyPolicy,520);K+=k.redactions;let u=g?.title??v?.ref??A.kind;return{id:xJ("ev",`${A.kind}\x00${A.result_id}\x00${A.citation_id??""}`,14),kind:A.kind,title:c4(u,100),text_preview:k.text,score:Number(A.score.toFixed(6)),citation_ids:v?[v.id]:[],provenance:{source:"search",record_ref:`${A.kind}:${A.result_id}`,created_at:H.created_at,updated_at:null,metadata_keys:[]}}}),F=new Set(E.flatMap((A)=>A.citation_ids));return{citations:Array.from(V.values()).filter((A)=>F.has(A.id)),evidence:E,duplicateCandidates:[],redactions:K,warnings:H.warnings,available:H.excerpts.length}}function iy($,_,J){if(_)return $.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at FROM runs WHERE updated_at >= ? OR created_at >= ? ORDER BY updated_at DESC, created_at DESC LIMIT ?`).all(_,_,J);return $.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at FROM runs ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(J)}function My($,_,J){if(_.length===0)return[];let U=_.map(()=>"?").join(", ");return $.query(`SELECT id, run_id, level, event, metadata_json, created_at + LIMIT ?`).all(J)}function ly($,_,J){if(_.length===0)return[];let U=_.map(()=>"?").join(", ");return $.query(`SELECT id, run_id, level, event, metadata_json, created_at FROM run_events WHERE run_id IN (${U}) ORDER BY created_at DESC - LIMIT ?`).all(..._,J)}function Ay($,_){return`${$.type} ${$.metadata_json} ${_.map((U)=>`${U.event} ${U.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function by($,_,J){let U=z0(_,["source_ref","source_uri","evidence_uri","receipt_uri"],J),W=z0(_,["artifact_uri"],J),X=z0(_,["artifact_path","artifact_key"],J),G=U??W??X??`knowledge://project/runs/${$.id}`,Q=$.prompt?SJ($.prompt,J,180).text:null;return{id:ZJ("cite",`run\x00${$.id}\x00${G}`,12),kind:W||X?"artifact":"run",ref:G,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:W,artifact_path:X,run_id:$.id,run_event_id:null,revision:z0(_,["revision"],J),hash:z0(_,["hash","content_hash"],J),chunk_id:null,offsets:{start:null,end:null},quote_preview:Q}}function Ey($,_,J){let U=z0(_,["source_ref","source_uri","evidence_uri","receipt_uri"],J),W=z0(_,["artifact_uri"],J),X=z0(_,["artifact_path","artifact_key"],J),G=U??W??X??`knowledge://project/runs/${$.run_id}`,Q=SJ($.event,J,160).text;return{id:ZJ("cite",`event\x00${$.id}\x00${G}`,12),kind:W||X?"artifact":"run_event",ref:G,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:W,artifact_path:X,run_id:$.run_id,run_event_id:$.id,revision:z0(_,["revision"],J),hash:z0(_,["hash","content_hash"],J),chunk_id:null,offsets:{start:null,end:null},quote_preview:Q}}function KV($){let _=new Map;for(let J of $){let U=uY(`${J.title} ${J.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g,"").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g,"").replace(/[^a-z0-9 ]+/g,"").replace(/\b(?:run|event|completed|dry_run|pending)\b/g,"").replace(/\s+/g," ").trim().slice(0,220);if(!U)continue;_.set(U,[..._.get(U)??[],J.id])}return Array.from(_.entries()).filter(([,J])=>J.length>1).map(([J,U])=>({id:ZJ("dup",J,12),reason:"normalized_text_match",evidence_ids:U,confidence:U.length>2?"high":"medium"}))}async function wy($,_,J){let U=$.source==="loops"?"loops":"runs",W=($.topic??$.query??"").trim(),X=Dy(W),G=RV($.since,J),Q=G.warning?[G.warning]:[];G$($.dbPath);let Y=i($.dbPath);try{let q=Ky(Y,G.cutoff,Math.max(_*8,40)),L=My(Y,q.map((M)=>M.id),Math.max(_*12,80)),N=new Map;for(let M of L)N.set(M.run_id,[...N.get(M.run_id)??[],M]);let B=(U==="loops"?q.filter((M)=>Ay(M,N.get(M.id)??[])):q).map((M)=>{let K=HV(M.metadata_json),w=`${M.type} ${M.status} ${M.prompt??""} ${s9(K)} ${(N.get(M.id)??[]).map((b)=>`${b.event} ${b.metadata_json}`).join(" ")}`;return{row:M,metadata:K,score:VV(w,X),text:w}}).filter((M)=>X.length===0||M.score>0).sort((M,K)=>K.score-M.score||K.row.updated_at.localeCompare(M.row.updated_at)||M.row.id.localeCompare(K.row.id)),H=[],V=[],R=0;for(let M of B.slice(0,Math.max(_*2,_))){let K=by(M.row,M.metadata,$.safetyPolicy);H.push(K);let w=s9(M.metadata),b=[M.row.prompt,w].filter(Boolean).join(" | ")||`${M.row.type} ${M.row.status}`,I=SJ(b,$.safetyPolicy,420);R+=I.redactions,V.push({id:`run:${M.row.id}`,kind:M.row.type,title:d0(`${M.row.type}: ${M.row.status}`,100),text_preview:I.text,score:M.score,citation_ids:[K.id],provenance:{source:U,record_ref:`knowledge://project/runs/${M.row.id}`,created_at:M.row.created_at,updated_at:M.row.updated_at,metadata_keys:mY(M.metadata)}});let v=(N.get(M.row.id)??[]).map((g)=>{let x=HV(g.metadata_json),Y6=`${g.event} ${s9(x)} ${g.metadata_json}`;return{event:g,metadata:x,score:VV(Y6,X),text:Y6}}).filter((g)=>X.length===0||g.score>0).sort((g,x)=>x.score-g.score||x.event.created_at.localeCompare(g.event.created_at)||g.event.id.localeCompare(x.event.id)).slice(0,2);for(let g of v){let x=Ey(g.event,g.metadata,$.safetyPolicy);H.push(x);let Y6=SJ(`${g.event}: ${s9(g.metadata)}`,$.safetyPolicy,320);R+=Y6.redactions,V.push({id:`event:${g.event.id}`,kind:`run_event:${g.event.level}`,title:d0(g.event.event,100),text_preview:Y6.text,score:g.score,citation_ids:[x.id],provenance:{source:U,record_ref:`knowledge://project/runs/${g.event.run_id}`,created_at:g.event.created_at,updated_at:null,metadata_keys:mY(g.metadata)}})}}return{citations:H,evidence:V,duplicateCandidates:$.dedupe?KV(V):[],redactions:R,warnings:Q,available:B.length}}finally{Y.close()}}function Iy($){let _=$.purpose==="proposal"?`Proposal context: ${d0($.query||"loop evidence",80)}`:`Knowledge context: ${d0($.query,80)}`,J=$.evidence.slice(0,8).map((X)=>X.id),U=$.duplicates.slice(0,5).map((X)=>X.id),W=$.evidence.slice(0,5).map((X)=>`${X.id}: ${X.title}`);if($.evidence.length===0)W.push("No matching bounded evidence was found.");return{title:_,bullets:W,evidence_ids:J,duplicate_candidate_ids:U,next_actions:$.source==="loops"?["Review duplicate_candidates before drafting a new proposal.","Use cited run refs for provenance; inspect a run only when more detail is needed.","Keep proposal writes approval-gated and idempotent."]:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]}}function MV($){let _=new Set($.evidence.flatMap((J)=>J.citation_ids));$.citations=$.citations.filter((J)=>_.has(J.id))}function FV($){$.outline.evidence_ids=$.evidence.slice(0,8).map((_)=>_.id),$.outline.bullets=$.evidence.length>0?$.evidence.slice(0,5).map((_)=>`${_.id}: ${_.title}`):["No matching bounded evidence was found."],$.outline.duplicate_candidate_ids=$.duplicate_candidates.slice(0,5).map((_)=>_.id)}function gy($){let _=$.budgets.max_tokens,J=new Set($.warnings);while(NV($)>_){let U=$.evidence.map((X,G)=>({entry:X,index:G})).filter(({entry:X})=>X.text_preview.length>180).sort((X,G)=>G.entry.text_preview.length-X.entry.text_preview.length)[0];if(U){U.entry.text_preview=d0(U.entry.text_preview,180),J.add("text_preview_truncated_for_token_budget");continue}let W=$.citations.filter((X)=>(X.quote_preview?.length??0)>120).sort((X,G)=>(G.quote_preview?.length??0)-(X.quote_preview?.length??0))[0];if(W?.quote_preview){W.quote_preview=d0(W.quote_preview,120),J.add("citation_quote_truncated_for_token_budget");continue}if($.evidence.length>0){$.evidence.pop(),$.budgets.items_truncated+=1,$.duplicate_candidates=$.duplicate_candidates.map((X)=>({...X,evidence_ids:X.evidence_ids.filter((G)=>$.evidence.some((Q)=>Q.id===G))})).filter((X)=>X.evidence_ids.length>1),FV($),J.add("evidence_truncated_for_token_budget"),MV($);continue}if($.outline.next_actions.length>1){$.outline.next_actions.pop(),J.add("outline_truncated_for_token_budget");continue}J.add("token_budget_floor_exceeded");break}if($.warnings=Array.from(J).sort(),$.budgets.items_included=$.evidence.length,FV($),$.budgets.estimated_tokens=NV($),$.budgets.token_budget_exceeded=$.budgets.estimated_tokens>_,$.budgets.token_budget_exceeded)throw Error(`Unable to build context pack within ${_} token budget; increase --max-tokens.`);return $.message=`${$.evidence.length} bounded evidence item(s), estimated ${$.budgets.estimated_tokens}/${_} token(s)`,$}async function AV($){let _=$.now??new Date,J=$.source??"search",U=$.purpose??(J==="loops"||J==="runs"?"proposal":"agent_context"),W=Hy($.maxTokens),X=Ny($.maxItems,$.limit),G=xY($.query??$.topic??"");if(U==="proposal"&&J!=="search"&&!G)throw Error("Proposal context requires --topic or a positional topic.");if(J!=="search")G$($.dbPath);let Q=RV($.since,_).cutoff??$.since??"",Y=J==="search"?await Ry($,X):await wy($,X,_),q=Y.evidence.sort((H,V)=>V.score-H.score||H.id.localeCompare(V.id)).slice(0,X),L=Y.citations.filter((H,V,R)=>R.findIndex((M)=>M.id===H.id)===V).sort((H,V)=>H.id.localeCompare(V.id)),N=$.dedupe?KV(q):Y.duplicateCandidates.filter((H)=>H.evidence_ids.every((V)=>q.some((R)=>R.id===V))),F=Iy({source:J,purpose:U,query:G,evidence:q,duplicates:N}),B={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:_.toISOString(),source:J,purpose:U,query:G,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:ZJ("ctx",[J,U,G,Q,$.dedupe===!0?"dedupe":"no-dedupe",$.semantic===!0?"semantic":"keyword",$.modelRef??"",$.limit??"",W,X,q.map((H)=>H.id).join(","),L.map((H)=>H.id).join(",")].join("\x00"),20),budgets:{max_tokens:W,estimated_tokens:0,max_items:X,items_included:q.length,items_available:Y.available,items_truncated:Math.max(0,Y.available-q.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:Y.redactions,reminders:Vy(J)},citations:L,evidence:q,duplicate_candidates:N,outline:F,warnings:Y.warnings,message:`${q.length} bounded evidence item(s), estimated under ${W} token(s)`};return MV(B),gy(B)}import{randomUUID as rR}from"crypto";import{createHash as ky,randomUUID as fy}from"crypto";import{existsSync as Cy,readFileSync as Py}from"fs";import{hostname as kV}from"os";import{fileURLToPath as fV}from"url";import{extname as Ty,relative as CV,resolve as bV,sep as Sy}from"path";var _8=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"],b1=2,E1=1,AU={sources:["id"],wiki_pages:["id"],source_revisions:["id"],chunks:["id"],chunk_embeddings:["id"],wiki_backlinks:["from_page_id","to_page_id"],citations:["id"],knowledge_indexes:["id"],runs:["id"],run_events:["id"],provider_usage:["id"],redaction_findings:["id"],storage_objects:["id"],audit_events:["id"],approval_gates:["id"],vector_index_entries:["id"],reindex_queue:["id"],knowledge_machines:["machine_id"],knowledge_sync_snapshots:["id"],knowledge_sync_changes:["id"],knowledge_sync_conflicts:["id"],knowledge_sync_table_clocks:["table_name","machine_id"],knowledge_sync_imports:["bundle_id"]},bU=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function j0($=new Date){return $.toISOString()}function pY($){return`${$}_${Date.now().toString(36)}_${fy().slice(0,8)}`}function PV($){let _=$?.trim();if(_)return _;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??kV()}function yJ($){if(Array.isArray($))return`[${$.map(yJ).join(",")}]`;if($&&typeof $==="object"){let _=$;return`{${Object.keys(_).sort().map((J)=>`${JSON.stringify(J)}:${yJ(_[J])}`).join(",")}}`}return JSON.stringify($)}function RU($){return`sha256:${ky("sha256").update($).digest("hex")}`}function e9($,_){return $.query(`SELECT COUNT(*) AS n FROM ${_}`).get()?.n??0}function W8($,_){try{return JSON.parse($)}catch{return _}}function X4($){return`"${$.replace(/"/g,'""')}"`}function Zy($){if($===void 0||$===null)return null;if(typeof $==="string"||typeof $==="number"||typeof $==="bigint"||typeof $==="boolean")return $;if($ instanceof Date)return $.toISOString();if(Buffer.isBuffer($)||$ instanceof Uint8Array)return $;if(typeof $==="object")return JSON.stringify($);return String($)}function TV($,_){return _.filter((J)=>H4($,J))}function H4($,_){let J=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(_);return Boolean(J)}function vy($,_){let J=$.query(`PRAGMA table_info(${X4(_)})`).all();return new Set(J.map((U)=>U.name))}function yy($,_,J){let U=vy($,_);return J.filter((W)=>U.has(W))}function SV($){if(!$||$.length===0)return[..._8];let _=new Set(_8),J=$.map((W)=>W.trim()).filter(Boolean),U=J.filter((W)=>!_.has(W));if(U.length>0)throw Error(`Unknown knowledge sync table(s): ${U.join(", ")}`);return J}function g2($,_){return AU[$].map((U)=>`${U}=${JSON.stringify(_[U]??null)}`).join("&")}var hy=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function KU($,_=0){if(_>8)return"[truncated-depth]";if(typeof $==="string")return $.length>4000?`${$.slice(0,4000)}...[truncated]`:$;if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.slice(0,50).map((U)=>KU(U,_+1));let J={};for(let[U,W]of Object.entries($)){if(hy.has(U.toLowerCase()))continue;J[U]=KU(W,_+1)}return J}function FU($){if(!$)return null;return KU($)}function oY($){return RU(yJ($))}function my($,_){let J={};for(let[U,W]of Object.entries($))if(U==="artifact_uri"&&typeof W==="string"&&_.has(W))J[U]=`artifact:${_.get(W)}`;else J[U]=W;return J}function I2($,_=new Map){return oY(my($,_))}function ZV($,_){if(!H4($,_))return[];return $.query(`SELECT * FROM ${X4(_)} ORDER BY rowid ASC`).all()}function J8($,_,J=new Map){return oY(_.map((U)=>({key:g2($,U),hash:I2(U,J)})).sort((U,W)=>U.key.localeCompare(W.key)))}function MU($,_,J){return $.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get(_,J)??null}function xy($){if(!H4($,"knowledge_sync_table_clocks"))return[];return $.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function U8($,_){let J=_.now??j0(),W=MU($,_.table,_.machineId)?.created_at??J;$.query(` + LIMIT ?`).all(..._,J)}function ry($,_){return`${$.type} ${$.metadata_json} ${_.map((U)=>`${U.event} ${U.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function py($,_,J){let U=j4(_,["source_ref","source_uri","evidence_uri","receipt_uri"],J),W=j4(_,["artifact_uri"],J),X=j4(_,["artifact_path","artifact_key"],J),G=U??W??X??`knowledge://project/runs/${$.id}`,Y=$.prompt?mJ($.prompt,J,180).text:null;return{id:xJ("cite",`run\x00${$.id}\x00${G}`,12),kind:W||X?"artifact":"run",ref:G,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:W,artifact_path:X,run_id:$.id,run_event_id:null,revision:j4(_,["revision"],J),hash:j4(_,["hash","content_hash"],J),chunk_id:null,offsets:{start:null,end:null},quote_preview:Y}}function oy($,_,J){let U=j4(_,["source_ref","source_uri","evidence_uri","receipt_uri"],J),W=j4(_,["artifact_uri"],J),X=j4(_,["artifact_path","artifact_key"],J),G=U??W??X??`knowledge://project/runs/${$.run_id}`,Y=mJ($.event,J,160).text;return{id:xJ("cite",`event\x00${$.id}\x00${G}`,12),kind:W||X?"artifact":"run_event",ref:G,source_ref:U?.startsWith("open-files://")?U:null,source_uri:U&&!U.startsWith("open-files://")?U:null,artifact_uri:W,artifact_path:X,run_id:$.run_id,run_event_id:$.id,revision:j4(_,["revision"],J),hash:j4(_,["hash","content_hash"],J),chunk_id:null,offsets:{start:null,end:null},quote_preview:Y}}function PV($){let _=new Map;for(let J of $){let U=pQ(`${J.title} ${J.text_preview}`).replace(/\b(?:file|https?|s3):\/\/\S+/g,"").replace(/\b(?:run|evt|task|loop)_[a-z0-9_]+\b/g,"").replace(/[^a-z0-9 ]+/g,"").replace(/\b(?:run|event|completed|dry_run|pending)\b/g,"").replace(/\s+/g," ").trim().slice(0,220);if(!U)continue;_.set(U,[..._.get(U)??[],J.id])}return Array.from(_.entries()).filter(([,J])=>J.length>1).map(([J,U])=>({id:xJ("dup",J,12),reason:"normalized_text_match",evidence_ids:U,confidence:U.length>2?"high":"medium"}))}async function ty($,_,J){let U=$.source==="loops"?"loops":"runs",W=($.topic??$.query??"").trim(),X=yy(W),G=CV($.since,J),Y=G.warning?[G.warning]:[];a($.dbPath);let Q=m($.dbPath);try{let q=iy(Q,G.cutoff,Math.max(_*8,40)),L=ly(Q,q.map((E)=>E.id),Math.max(_*12,80)),N=new Map;for(let E of L)N.set(E.run_id,[...N.get(E.run_id)??[],E]);let B=(U==="loops"?q.filter((E)=>ry(E,N.get(E.id)??[])):q).map((E)=>{let F=gV(E.metadata_json),w=`${E.type} ${E.status} ${E.prompt??""} ${W8(F)} ${(N.get(E.id)??[]).map((A)=>`${A.event} ${A.metadata_json}`).join(" ")}`;return{row:E,metadata:F,score:IV(w,X),text:w}}).filter((E)=>X.length===0||E.score>0).sort((E,F)=>F.score-E.score||F.row.updated_at.localeCompare(E.row.updated_at)||E.row.id.localeCompare(F.row.id)),H=[],V=[],K=0;for(let E of B.slice(0,Math.max(_*2,_))){let F=py(E.row,E.metadata,$.safetyPolicy);H.push(F);let w=W8(E.metadata),A=[E.row.prompt,w].filter(Boolean).join(" | ")||`${E.row.type} ${E.row.status}`,g=mJ(A,$.safetyPolicy,420);K+=g.redactions,V.push({id:`run:${E.row.id}`,kind:E.row.type,title:c4(`${E.row.type}: ${E.row.status}`,100),text_preview:g.text,score:E.score,citation_ids:[F.id],provenance:{source:U,record_ref:`knowledge://project/runs/${E.row.id}`,created_at:E.row.created_at,updated_at:E.row.updated_at,metadata_keys:lQ(E.metadata)}});let v=(N.get(E.row.id)??[]).map((k)=>{let u=gV(k.metadata_json),W_=`${k.event} ${W8(u)} ${k.metadata_json}`;return{event:k,metadata:u,score:IV(W_,X),text:W_}}).filter((k)=>X.length===0||k.score>0).sort((k,u)=>u.score-k.score||u.event.created_at.localeCompare(k.event.created_at)||k.event.id.localeCompare(u.event.id)).slice(0,2);for(let k of v){let u=oy(k.event,k.metadata,$.safetyPolicy);H.push(u);let W_=mJ(`${k.event}: ${W8(k.metadata)}`,$.safetyPolicy,320);K+=W_.redactions,V.push({id:`event:${k.event.id}`,kind:`run_event:${k.event.level}`,title:c4(k.event.event,100),text_preview:W_.text,score:k.score,citation_ids:[u.id],provenance:{source:U,record_ref:`knowledge://project/runs/${k.event.run_id}`,created_at:k.event.created_at,updated_at:null,metadata_keys:lQ(k.metadata)}})}}return{citations:H,evidence:V,duplicateCandidates:$.dedupe?PV(V):[],redactions:K,warnings:Y,available:B.length}}finally{Q.close()}}function ay($){let _=$.purpose==="proposal"?`Proposal context: ${c4($.query||"loop evidence",80)}`:`Knowledge context: ${c4($.query,80)}`,J=$.evidence.slice(0,8).map((X)=>X.id),U=$.duplicates.slice(0,5).map((X)=>X.id),W=$.evidence.slice(0,5).map((X)=>`${X.id}: ${X.title}`);if($.evidence.length===0)W.push("No matching bounded evidence was found.");return{title:_,bullets:W,evidence_ids:J,duplicate_candidate_ids:U,next_actions:$.source==="loops"?["Review duplicate_candidates before drafting a new proposal.","Use cited run refs for provenance; inspect a run only when more detail is needed.","Keep proposal writes approval-gated and idempotent."]:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]}}function TV($){let _=new Set($.evidence.flatMap((J)=>J.citation_ids));$.citations=$.citations.filter((J)=>_.has(J.id))}function fV($){$.outline.evidence_ids=$.evidence.slice(0,8).map((_)=>_.id),$.outline.bullets=$.evidence.length>0?$.evidence.slice(0,5).map((_)=>`${_.id}: ${_.title}`):["No matching bounded evidence was found."],$.outline.duplicate_candidate_ids=$.duplicate_candidates.slice(0,5).map((_)=>_.id)}function sy($){let _=$.budgets.max_tokens,J=new Set($.warnings);while(kV($)>_){let U=$.evidence.map((X,G)=>({entry:X,index:G})).filter(({entry:X})=>X.text_preview.length>180).sort((X,G)=>G.entry.text_preview.length-X.entry.text_preview.length)[0];if(U){U.entry.text_preview=c4(U.entry.text_preview,180),J.add("text_preview_truncated_for_token_budget");continue}let W=$.citations.filter((X)=>(X.quote_preview?.length??0)>120).sort((X,G)=>(G.quote_preview?.length??0)-(X.quote_preview?.length??0))[0];if(W?.quote_preview){W.quote_preview=c4(W.quote_preview,120),J.add("citation_quote_truncated_for_token_budget");continue}if($.evidence.length>0){$.evidence.pop(),$.budgets.items_truncated+=1,$.duplicate_candidates=$.duplicate_candidates.map((X)=>({...X,evidence_ids:X.evidence_ids.filter((G)=>$.evidence.some((Y)=>Y.id===G))})).filter((X)=>X.evidence_ids.length>1),fV($),J.add("evidence_truncated_for_token_budget"),TV($);continue}if($.outline.next_actions.length>1){$.outline.next_actions.pop(),J.add("outline_truncated_for_token_budget");continue}J.add("token_budget_floor_exceeded");break}if($.warnings=Array.from(J).sort(),$.budgets.items_included=$.evidence.length,fV($),$.budgets.estimated_tokens=kV($),$.budgets.token_budget_exceeded=$.budgets.estimated_tokens>_,$.budgets.token_budget_exceeded)throw Error(`Unable to build context pack within ${_} token budget; increase --max-tokens.`);return $.message=`${$.evidence.length} bounded evidence item(s), estimated ${$.budgets.estimated_tokens}/${_} token(s)`,$}async function SV($){let _=$.now??new Date,J=$.source??"search",U=$.purpose??(J==="loops"||J==="runs"?"proposal":"agent_context"),W=xy($.maxTokens),X=uy($.maxItems,$.limit),G=rQ($.query??$.topic??"");if(U==="proposal"&&J!=="search"&&!G)throw Error("Proposal context requires --topic or a positional topic.");if(J!=="search")a($.dbPath);let Y=CV($.since,_).cutoff??$.since??"",Q=J==="search"?await cy($,X):await ty($,X,_),q=Q.evidence.sort((H,V)=>V.score-H.score||H.id.localeCompare(V.id)).slice(0,X),L=Q.citations.filter((H,V,K)=>K.findIndex((E)=>E.id===H.id)===V).sort((H,V)=>H.id.localeCompare(V.id)),N=$.dedupe?PV(q):Q.duplicateCandidates.filter((H)=>H.evidence_ids.every((V)=>q.some((K)=>K.id===V))),R=ay({source:J,purpose:U,query:G,evidence:q,duplicates:N}),B={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:_.toISOString(),source:J,purpose:U,query:G,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:xJ("ctx",[J,U,G,Y,$.dedupe===!0?"dedupe":"no-dedupe",$.semantic===!0?"semantic":"keyword",$.modelRef??"",$.limit??"",W,X,q.map((H)=>H.id).join(","),L.map((H)=>H.id).join(",")].join("\x00"),20),budgets:{max_tokens:W,estimated_tokens:0,max_items:X,items_included:q.length,items_available:Q.available,items_truncated:Math.max(0,Q.available-q.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:Q.redactions,reminders:dy(J)},citations:L,evidence:q,duplicate_candidates:N,outline:R,warnings:Q.warnings,message:`${q.length} bounded evidence item(s), estimated under ${W} token(s)`};return TV(B),sy(B)}import{randomUUID as UF}from"crypto";import{createHash as ey,randomUUID as $h}from"crypto";import{existsSync as _h,readFileSync as Jh}from"fs";import{hostname as xV}from"os";import{fileURLToPath as uV}from"url";import{extname as Wh,relative as dV,resolve as ZV,sep as Uh}from"path";var G8=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"],w0=2,g0=1,kU={sources:["id"],wiki_pages:["id"],source_revisions:["id"],chunks:["id"],chunk_embeddings:["id"],wiki_backlinks:["from_page_id","to_page_id"],citations:["id"],knowledge_indexes:["id"],runs:["id"],run_events:["id"],provider_usage:["id"],redaction_findings:["id"],storage_objects:["id"],audit_events:["id"],approval_gates:["id"],vector_index_entries:["id"],reindex_queue:["id"],knowledge_machines:["machine_id"],knowledge_sync_snapshots:["id"],knowledge_sync_changes:["id"],knowledge_sync_conflicts:["id"],knowledge_sync_table_clocks:["table_name","machine_id"],knowledge_sync_imports:["bundle_id"]},IU=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function D4($=new Date){return $.toISOString()}function _q($){return`${$}_${Date.now().toString(36)}_${$h().slice(0,8)}`}function nV($){let _=$?.trim();if(_)return _;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??xV()}function dJ($){if(Array.isArray($))return`[${$.map(dJ).join(",")}]`;if($&&typeof $==="object"){let _=$;return`{${Object.keys(_).sort().map((J)=>`${JSON.stringify(J)}:${dJ(_[J])}`).join(",")}}`}return JSON.stringify($)}function bU($){return`sha256:${ey("sha256").update($).digest("hex")}`}function U8($,_){return $.query(`SELECT COUNT(*) AS n FROM ${_}`).get()?.n??0}function Q8($,_){try{return JSON.parse($)}catch{return _}}function Y6($){return`"${$.replace(/"/g,'""')}"`}function Xh($){if($===void 0||$===null)return null;if(typeof $==="string"||typeof $==="number"||typeof $==="bigint"||typeof $==="boolean")return $;if($ instanceof Date)return $.toISOString();if(Buffer.isBuffer($)||$ instanceof Uint8Array)return $;if(typeof $==="object")return JSON.stringify($);return String($)}function cV($,_){return _.filter((J)=>N6($,J))}function N6($,_){let J=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(_);return Boolean(J)}function Gh($,_){let J=$.query(`PRAGMA table_info(${Y6(_)})`).all();return new Set(J.map((U)=>U.name))}function Yh($,_,J){let U=Gh($,_);return J.filter((W)=>U.has(W))}function iV($){if(!$||$.length===0)return[...G8];let _=new Set(G8),J=$.map((W)=>W.trim()).filter(Boolean),U=J.filter((W)=>!_.has(W));if(U.length>0)throw Error(`Unknown knowledge sync table(s): ${U.join(", ")}`);return J}function C1($,_){return kU[$].map((U)=>`${U}=${JSON.stringify(_[U]??null)}`).join("&")}var Qh=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function wU($,_=0){if(_>8)return"[truncated-depth]";if(typeof $==="string")return $.length>4000?`${$.slice(0,4000)}...[truncated]`:$;if($===null||typeof $!=="object")return $;if(Array.isArray($))return $.slice(0,50).map((U)=>wU(U,_+1));let J={};for(let[U,W]of Object.entries($)){if(Qh.has(U.toLowerCase()))continue;J[U]=wU(W,_+1)}return J}function AU($){if(!$)return null;return wU($)}function Jq($){return bU(dJ($))}function qh($,_){let J={};for(let[U,W]of Object.entries($))if(U==="artifact_uri"&&typeof W==="string"&&_.has(W))J[U]=`artifact:${_.get(W)}`;else J[U]=W;return J}function f1($,_=new Map){return Jq(qh($,_))}function lV($,_){if(!N6($,_))return[];return $.query(`SELECT * FROM ${Y6(_)} ORDER BY rowid ASC`).all()}function Y8($,_,J=new Map){return Jq(_.map((U)=>({key:C1($,U),hash:f1(U,J)})).sort((U,W)=>U.key.localeCompare(W.key)))}function gU($,_,J){return $.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get(_,J)??null}function zh($){if(!N6($,"knowledge_sync_table_clocks"))return[];return $.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function q8($,_){let J=_.now??D4(),W=gU($,_.table,_.machineId)?.created_at??J;$.query(` INSERT INTO knowledge_sync_table_clocks ( table_name, machine_id, logical_clock, high_water_hash, high_water_bundle_id, origin_machine_id, updated_by_machine_id, last_applied_at, metadata_json, @@ -781,17 +842,17 @@ ${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:_.config, last_applied_at = excluded.last_applied_at, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `).run(_.table,_.machineId,_.logicalClock,_.highWaterHash,_.highWaterBundleId??null,_.originMachineId??_.machineId,_.updatedByMachineId??_.machineId,_.lastAppliedAt??J,JSON.stringify(_.metadata??{}),W,J);let X=MU($,_.table,_.machineId);if(!X)throw Error(`Failed to record sync clock for ${_.table}:${_.machineId}`);return X}function uy($,_){let J=MU($,_.table,_.machineId),U=J?.high_water_hash===_.highWaterHash?J.logical_clock:(J?.logical_clock??0)+1,W=_.record?U8($,{table:_.table,machineId:_.machineId,logicalClock:U,highWaterHash:_.highWaterHash,highWaterBundleId:null,originMachineId:J?.origin_machine_id??_.machineId,updatedByMachineId:_.machineId,lastAppliedAt:_.now,metadata:{source:"export",row_count:_.rowCount},now:_.now}):{table_name:_.table,machine_id:_.machineId,logical_clock:U,high_water_hash:_.highWaterHash,high_water_bundle_id:J?.high_water_bundle_id??null,origin_machine_id:J?.origin_machine_id??_.machineId,updated_by_machine_id:_.machineId,last_applied_at:_.now,metadata_json:"{}",created_at:J?.created_at??_.now,updated_at:_.now};return{table:_.table,machine_id:_.machineId,logical_clock:W.logical_clock,high_water_hash:_.highWaterHash,high_water_bundle_id:W.high_water_bundle_id,row_count:_.rowCount,updated_at:W.updated_at}}function dy($,_,J,U,W){if(_.high_water_bundle_id=J,!U)return;U8($,{table:_.table,machineId:_.machine_id,logicalClock:_.logical_clock,highWaterHash:_.high_water_hash,highWaterBundleId:J,originMachineId:_.machine_id,updatedByMachineId:_.machine_id,lastAppliedAt:W,metadata:{source:"export",row_count:_.row_count},now:W})}function vV($,_){return $.table_clocks?.find((J)=>J.table===_)??null}function cy($,_){if(!$||!_)return!1;return _.logical_clock<$.logical_clock}function ly($,_,J){if(J.length===0)return 0;let U=yy($,_,Object.keys(J[0]));if(U.length===0)return 0;let W=AU[_],X=U.map(X4).join(", "),G=U.map(()=>"?").join(", "),Q=W.map(X4).join(", "),Y=U.filter((B)=>!W.includes(B)),q=W[0],L=Y.length>0?Y.map((B)=>`${X4(B)} = excluded.${X4(B)}`).join(", "):`${X4(q)} = excluded.${X4(q)}`,N=$.query(`INSERT INTO ${X4(_)} (${X}) VALUES (${G}) - ON CONFLICT (${Q}) DO UPDATE SET ${L}`);return $.transaction((B)=>{for(let H of B)N.run(...U.map((V)=>Zy(H[V])))})(J),J.length}function yV($,_){let J=AU[$],U=[],W=_;for(let X=0;X=0?Y.slice(0,N):Y;try{U.push(JSON.parse(F))}catch{return null}W=N>=0&&L?Y.slice(N+1):""}return W.length===0?U:null}function hV($){return AU[$].map((_)=>`${X4(_)} = ?`).join(" AND ")}function ny($,_,J){if(!H4($,"knowledge_sync_changes"))return new Map;let U=$.query(`SELECT entity_id, next_hash + `).run(_.table,_.machineId,_.logicalClock,_.highWaterHash,_.highWaterBundleId??null,_.originMachineId??_.machineId,_.updatedByMachineId??_.machineId,_.lastAppliedAt??J,JSON.stringify(_.metadata??{}),W,J);let X=gU($,_.table,_.machineId);if(!X)throw Error(`Failed to record sync clock for ${_.table}:${_.machineId}`);return X}function jh($,_){let J=gU($,_.table,_.machineId),U=J?.high_water_hash===_.highWaterHash?J.logical_clock:(J?.logical_clock??0)+1,W=_.record?q8($,{table:_.table,machineId:_.machineId,logicalClock:U,highWaterHash:_.highWaterHash,highWaterBundleId:null,originMachineId:J?.origin_machine_id??_.machineId,updatedByMachineId:_.machineId,lastAppliedAt:_.now,metadata:{source:"export",row_count:_.rowCount},now:_.now}):{table_name:_.table,machine_id:_.machineId,logical_clock:U,high_water_hash:_.highWaterHash,high_water_bundle_id:J?.high_water_bundle_id??null,origin_machine_id:J?.origin_machine_id??_.machineId,updated_by_machine_id:_.machineId,last_applied_at:_.now,metadata_json:"{}",created_at:J?.created_at??_.now,updated_at:_.now};return{table:_.table,machine_id:_.machineId,logical_clock:W.logical_clock,high_water_hash:_.highWaterHash,high_water_bundle_id:W.high_water_bundle_id,row_count:_.rowCount,updated_at:W.updated_at}}function Dh($,_,J,U,W){if(_.high_water_bundle_id=J,!U)return;q8($,{table:_.table,machineId:_.machine_id,logicalClock:_.logical_clock,highWaterHash:_.high_water_hash,highWaterBundleId:J,originMachineId:_.machine_id,updatedByMachineId:_.machine_id,lastAppliedAt:W,metadata:{source:"export",row_count:_.row_count},now:W})}function rV($,_){return $.table_clocks?.find((J)=>J.table===_)??null}function Oh($,_){if(!$||!_)return!1;return _.logical_clock<$.logical_clock}function Lh($,_,J){if(J.length===0)return 0;let U=Yh($,_,Object.keys(J[0]));if(U.length===0)return 0;let W=kU[_],X=U.map(Y6).join(", "),G=U.map(()=>"?").join(", "),Y=W.map(Y6).join(", "),Q=U.filter((B)=>!W.includes(B)),q=W[0],L=Q.length>0?Q.map((B)=>`${Y6(B)} = excluded.${Y6(B)}`).join(", "):`${Y6(q)} = excluded.${Y6(q)}`,N=$.query(`INSERT INTO ${Y6(_)} (${X}) VALUES (${G}) + ON CONFLICT (${Y}) DO UPDATE SET ${L}`);return $.transaction((B)=>{for(let H of B)N.run(...U.map((V)=>Xh(H[V])))})(J),J.length}function pV($,_){let J=kU[$],U=[],W=_;for(let X=0;X=0?Q.slice(0,N):Q;try{U.push(JSON.parse(R))}catch{return null}W=N>=0&&L?Q.slice(N+1):""}return W.length===0?U:null}function oV($){return kU[$].map((_)=>`${Y6(_)} = ?`).join(" AND ")}function Bh($,_,J){if(!N6($,"knowledge_sync_changes"))return new Map;let U=$.query(`SELECT entity_id, next_hash FROM knowledge_sync_changes WHERE origin_machine_id = ? AND entity_kind = ? - ORDER BY created_at ASC, id ASC`).all(J,_),W=new Map;for(let X of U)W.set(X.entity_id,X.next_hash);return W}function iy($,_){if(H4($,"chunks_fts"))$.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(_);if(H4($,"chunk_embeddings"))$.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run(_);if(H4($,"vector_index_entries"))$.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run(_);if(H4($,"citations"))$.query("DELETE FROM citations WHERE chunk_id = ?").run(_)}function ry($,_,J){let U=yV(_,J);if(!U)return!1;let W=hV(_),X=$.query(`SELECT * FROM ${X4(_)} WHERE ${W} LIMIT 1`).get(...U);if(!X)return!1;if(_==="chunks"&&typeof X.id==="string")iy($,X.id);return $.query(`DELETE FROM ${X4(_)} WHERE ${W}`).run(...U),!0}function py($,_){if(!H4($,"chunks_fts"))return;for(let J of _){let U=typeof J.id==="string"?J.id:null,W=typeof J.text==="string"?J.text:null;if(!U||W===null)continue;let X="",G="",Q=typeof J.source_revision_id==="string"?J.source_revision_id:null;if(Q){let Y=$.query(`SELECT s.title, s.uri + ORDER BY created_at ASC, id ASC`).all(J,_),W=new Map;for(let X of U)W.set(X.entity_id,X.next_hash);return W}function Hh($,_){if(N6($,"chunks_fts"))$.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(_);if(N6($,"chunk_embeddings"))$.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run(_);if(N6($,"vector_index_entries"))$.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run(_);if(N6($,"citations"))$.query("DELETE FROM citations WHERE chunk_id = ?").run(_)}function Nh($,_,J){let U=pV(_,J);if(!U)return!1;let W=oV(_),X=$.query(`SELECT * FROM ${Y6(_)} WHERE ${W} LIMIT 1`).get(...U);if(!X)return!1;if(_==="chunks"&&typeof X.id==="string")Hh($,X.id);return $.query(`DELETE FROM ${Y6(_)} WHERE ${W}`).run(...U),!0}function Vh($,_){if(!N6($,"chunks_fts"))return;for(let J of _){let U=typeof J.id==="string"?J.id:null,W=typeof J.text==="string"?J.text:null;if(!U||W===null)continue;let X="",G="",Y=typeof J.source_revision_id==="string"?J.source_revision_id:null;if(Y){let Q=$.query(`SELECT s.title, s.uri FROM source_revisions sr JOIN sources s ON s.id = sr.source_id WHERE sr.id = ? - LIMIT 1`).get(Q);X=Y?.title??"",G=Y?.uri??""}if(!G&&typeof J.metadata_json==="string"){let Y=W8(J.metadata_json,{});G=typeof Y.source_uri==="string"?Y.source_uri:""}$.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(U),$.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(U,W,X,G)}}function oy($,_,J){if(_==="chunks")py($,J)}function ty($,_){let J=CV($,_);return J!==".."&&!J.startsWith("..")&&!J.startsWith(`..${Sy}`)}function ay($,_){let J=W8($.metadata_json,{});if(typeof J.key==="string")return J.key;if(!$.artifact_uri.startsWith("file://"))return null;try{let U=fV($.artifact_uri),W=bV(_),X=bV(U);if(!ty(W,X))return null;let G=CV(W,X).replace(/\\/g,"/");return G?q0(G):null}catch{return null}}var sy=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function ey($,_){let J=$?.toLowerCase()??"";if(J.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(J))return!0;return _?sy.has(Ty(_).toLowerCase()):!1}function k2($){let _=new Map;for(let J of $)if(J.key)_.set(J.artifact_uri,J.key);return _}function M1($){return oY({key:$.key,kind:$.kind,hash:$.hash,size_bytes:$.size_bytes})}function X8($){return $.key??$.artifact_uri}function $h($,_){return $.artifact_uri.startsWith("s3://")&&_.artifact_store.type==="s3"&&$.artifact_uri.startsWith(_.artifact_store.uri_prefix)}function mV($){return Object.fromEntries(_8.map((_)=>[_,H4($,_)?e9($,_):0]))}function _h($){return $.query(`SELECT artifact_uri, kind, hash, size_bytes + LIMIT 1`).get(Y);X=Q?.title??"",G=Q?.uri??""}if(!G&&typeof J.metadata_json==="string"){let Q=Q8(J.metadata_json,{});G=typeof Q.source_uri==="string"?Q.source_uri:""}$.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(U),$.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(U,W,X,G)}}function Rh($,_,J){if(_==="chunks")Vh($,J)}function Kh($,_){let J=dV($,_);return J!==".."&&!J.startsWith("..")&&!J.startsWith(`..${Uh}`)}function Fh($,_){let J=Q8($.metadata_json,{});if(typeof J.key==="string")return J.key;if(!$.artifact_uri.startsWith("file://"))return null;try{let U=uV($.artifact_uri),W=ZV(_),X=ZV(U);if(!Kh(W,X))return null;let G=dV(W,X).replace(/\\/g,"/");return G?z4(G):null}catch{return null}}var Eh=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function Mh($,_){let J=$?.toLowerCase()??"";if(J.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(J))return!0;return _?Eh.has(Wh(_).toLowerCase()):!1}function P1($){let _=new Map;for(let J of $)if(J.key)_.set(J.artifact_uri,J.key);return _}function A0($){return Jq({key:$.key,kind:$.kind,hash:$.hash,size_bytes:$.size_bytes})}function z8($){return $.key??$.artifact_uri}function Ah($,_){return $.artifact_uri.startsWith("s3://")&&_.artifact_store.type==="s3"&&$.artifact_uri.startsWith(_.artifact_store.uri_prefix)}function tV($){return Object.fromEntries(G8.map((_)=>[_,N6($,_)?U8($,_):0]))}function bh($){return $.query(`SELECT artifact_uri, kind, hash, size_bytes FROM storage_objects - ORDER BY artifact_uri ASC`).all()}function Jh($,_){return{machine_id:$.machine_id,hostname:$.hostname,platform:$.platform,user_label:$.user,workspace_home:$.workspace_path,tailscale_dns:$.tailscale.dns_name,tailscale_ips_json:JSON.stringify($.tailscale.ips),ssh_target:$.ssh.command_target,last_seen_at:$.local||$.tailscale.online===!0||$.heartbeat_status==="online"?_:$.last_heartbeat_at,capabilities_json:JSON.stringify({route_hints:$.route_hints,heartbeat_status:$.heartbeat_status,manifest_declared:$.manifest_declared}),metadata_json:JSON.stringify({...$.metadata,source:$.source,tags:$.tags,tailscale:$.tailscale,ssh:$.ssh}),created_at:_,updated_at:_}}function cY($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function Wh($){if(!$)return[];try{let _=JSON.parse($);return Array.isArray(_)?_:[]}catch{return[]}}function A1($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function $8($){return Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))}function vJ($){if(Array.isArray($))return`[${$.map(vJ).join(",")}]`;if($&&typeof $==="object")return`{${Object.entries($).filter(([,_])=>_!==void 0).sort(([_],[J])=>_.localeCompare(J)).map(([_,J])=>`${JSON.stringify(_)}:${vJ(J)}`).join(",")}}`;return JSON.stringify($)}function EV($){let{recorded_at:_,...J}=$;return J}function H6($){return typeof $==="string"&&$.length>0?$:null}function Uh($){return typeof $==="number"&&Number.isFinite($)?$:null}function wV($){return typeof $==="boolean"?$:null}function Xh($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function xV($){let _=A1($),J=H6(_.observed_at),U=H6(_.source_authority);if(!J||!U)return null;return{observed_at:J,verified_at:H6(_.verified_at),expires_at:H6(_.expires_at),ttl_ms:Uh(_.ttl_ms),source_authority:U,confidence:H6(_.confidence),cacheable:_.cacheable===!0,stale:_.stale===!0,reasons:Xh(_.reasons)}}function uV($,_){if(!$||$.stale)return!1;if(!$.expires_at)return!0;let J=Date.parse($.expires_at),U=Date.parse(_);return Number.isNaN(J)||Number.isNaN(U)||J>U}function Gh($,_){return H6(_.source)===$.source&&H6(_.target)===$.target&&H6(_.route)===$.route&&H6(_.target_kind)===$.targetKind&&H6(_.confidence)===$.confidence}function Qh($,_){return H6(_.source)===$.source&&H6(_.requested_machine_id)===$.requested_machine_id&&H6(_.machine_id)===$.machine_id&&H6(_.project_id)===$.project_id&&H6(_.repo_name)===$.repo_name&&H6(_.project_root)===$.project_root&&H6(_.project_root_source)===$.project_root_source&&H6(_.workspace_root)===$.workspace_root&&H6(_.workspace_root_source)===$.workspace_root_source&&H6(_.open_files_root)===$.open_files_root&&H6(_.open_files_root_source)===$.open_files_root_source&&H6(_.trust_status)===$.trust_status&&H6(_.auth_status)===$.auth_status&&wV(_.current)===$.current&&wV(_.primary)===$.primary}function Yh($,_,J){if(!$)return null;let U=xV(_.cacheability);if(U&&uV(U,J)&&Gh($,_))return{...$,cacheability:U};return $}function qh($,_,J){if(!$)return null;let U=xV(_.cacheability);if(U&&uV(U,J)&&Qh($,_))return{...$,cacheability:U};return $}function zh($){return $.workspace?.machine_id??$.workspace?.requested_machine_id??$.machineId??$.route?.target??kV()}function jh($,_){let J=new Set,U=Array.isArray(_.sources)?_.sources:[];for(let W of U)if(typeof W==="string")J.add(W);if(typeof _.source==="string")J.add(_.source);if($.route?.source)J.add($.route.source);if($.workspace?.source)J.add($.workspace.source);return J.add("knowledge"),[...J].sort()}function IV($,_){if(_?.target&&(_.route==="tailscale"||_.targetKind==="tailscale"))return _.target;return $?.tailscale_dns??null}function Oh($,_,J){let U=A1(_.resolver_evidence),W=$.route?$8({source:$.route.source,target:$.route.target,route:$.route.route,target_kind:$.route.targetKind,confidence:$.route.confidence,adapter:$.route.adapter,evidence:$.route.evidence,cacheability:$.route.cacheability,warnings:$.route.warnings}):A1(U.route),X=$.workspace?$8({source:$.workspace.source,requested_machine_id:$.workspace.requested_machine_id,machine_id:$.workspace.machine_id,project_id:$.workspace.project_id,repo_name:$.workspace.repo_name,project_root:$.workspace.project_root,project_root_source:$.workspace.project_root_source,workspace_root:$.workspace.workspace_root,workspace_root_source:$.workspace.workspace_root_source,open_files_root:$.workspace.open_files_root,open_files_root_source:$.workspace.open_files_root_source,trust_status:$.workspace.trust_status,auth_status:$.workspace.auth_status,current:$.workspace.current,primary:$.workspace.primary,diagnostics:$.workspace.diagnostics,repair_hints:$.workspace.repair_hints,evidence:$.workspace.evidence,cacheability:$.workspace.cacheability,warnings:$.workspace.warnings}):A1(U.workspace);return $8({...U,recorded_at:J,route:W,workspace:X})}function dV($,_){G$($);let J=i($);try{let U=zh(_),W=J.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(U)??null,X=j0(_.now),G=cY(W?.capabilities_json),Q=cY(W?.metadata_json),Y=A1(G.resolver),q=A1(Q.resolver_evidence),L=A1(q.route),N=A1(q.workspace),F=Yh(_.route?.source==="registry"?null:_.route??null,L,X),B=qh(_.workspace?.source==="registry"?null:_.workspace??null,N,X),H={..._,route:F,workspace:B},V={...G,resolver:$8({...Y,route_source:F?.source??Y.route_source,route_kind:F?.route??Y.route_kind,route_target_kind:F?.targetKind??Y.route_target_kind,route_confidence:F?.confidence??Y.route_confidence,route_cacheable:F?.cacheability?.cacheable??Y.route_cacheable,route_stale:F?.cacheability?.stale??Y.route_stale,route_expires_at:F?.cacheability?.expires_at??Y.route_expires_at,route_observed_at:F?.cacheability?.observed_at??Y.route_observed_at,route_source_authority:F?.cacheability?.source_authority??Y.route_source_authority,workspace_source:B?.source??Y.workspace_source,project_root_source:B?.project_root_source??Y.project_root_source,workspace_root_source:B?.workspace_root_source??Y.workspace_root_source,open_files_root_source:B?.open_files_root_source??Y.open_files_root_source,trust_status:B?.trust_status??Y.trust_status,auth_status:B?.auth_status??Y.auth_status,workspace_cacheable:B?.cacheability?.cacheable??Y.workspace_cacheable,workspace_stale:B?.cacheability?.stale??Y.workspace_stale,workspace_expires_at:B?.cacheability?.expires_at??Y.workspace_expires_at,workspace_observed_at:B?.cacheability?.observed_at??Y.workspace_observed_at,workspace_source_authority:B?.cacheability?.source_authority??Y.workspace_source_authority}),route_fallback:Boolean(F?.target??W?.ssh_target),workspace_fallback:Boolean(B?.project_root??W?.workspace_home)},R=Oh(H,Q,X);if(W){let K=q;if(W.workspace_home===(B?.project_root??W.workspace_home??null)&&W.tailscale_dns===IV(W,F)&&W.ssh_target===(F?.target??W.ssh_target??null)&&vJ(cY(W.capabilities_json))===vJ(V)&&vJ(EV(K))===vJ(EV(R)))return W}let M={machine_id:U,hostname:W?.hostname??null,platform:W?.platform??null,user_label:W?.user_label??null,workspace_home:B?.project_root??W?.workspace_home??null,tailscale_dns:IV(W,F),tailscale_ips_json:JSON.stringify(Wh(W?.tailscale_ips_json)),ssh_target:F?.target??W?.ssh_target??null,last_seen_at:X,capabilities_json:JSON.stringify(V),metadata_json:JSON.stringify({...Q,source:"knowledge",sources:jh(H,Q),resolver_evidence:R}),created_at:W?.created_at??X,updated_at:X};return cV(J,M),M}finally{J.close()}}function cV($,_){$.query(` + ORDER BY artifact_uri ASC`).all()}function wh($,_){return{machine_id:$.machine_id,hostname:$.hostname,platform:$.platform,user_label:$.user,workspace_home:$.workspace_path,tailscale_dns:$.tailscale.dns_name,tailscale_ips_json:JSON.stringify($.tailscale.ips),ssh_target:$.ssh.command_target,last_seen_at:$.local||$.tailscale.online===!0||$.heartbeat_status==="online"?_:$.last_heartbeat_at,capabilities_json:JSON.stringify({route_hints:$.route_hints,heartbeat_status:$.heartbeat_status,manifest_declared:$.manifest_declared}),metadata_json:JSON.stringify({...$.metadata,source:$.source,tags:$.tags,tailscale:$.tailscale,ssh:$.ssh}),created_at:_,updated_at:_}}function tQ($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function gh($){if(!$)return[];try{let _=JSON.parse($);return Array.isArray(_)?_:[]}catch{return[]}}function b0($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function X8($){return Object.fromEntries(Object.entries($).filter(([,_])=>_!==void 0))}function uJ($){if(Array.isArray($))return`[${$.map(uJ).join(",")}]`;if($&&typeof $==="object")return`{${Object.entries($).filter(([,_])=>_!==void 0).sort(([_],[J])=>_.localeCompare(J)).map(([_,J])=>`${JSON.stringify(_)}:${uJ(J)}`).join(",")}}`;return JSON.stringify($)}function vV($){let{recorded_at:_,...J}=$;return J}function N_($){return typeof $==="string"&&$.length>0?$:null}function kh($){return typeof $==="number"&&Number.isFinite($)?$:null}function yV($){return typeof $==="boolean"?$:null}function Ih($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function aV($){let _=b0($),J=N_(_.observed_at),U=N_(_.source_authority);if(!J||!U)return null;return{observed_at:J,verified_at:N_(_.verified_at),expires_at:N_(_.expires_at),ttl_ms:kh(_.ttl_ms),source_authority:U,confidence:N_(_.confidence),cacheable:_.cacheable===!0,stale:_.stale===!0,reasons:Ih(_.reasons)}}function sV($,_){if(!$||$.stale)return!1;if(!$.expires_at)return!0;let J=Date.parse($.expires_at),U=Date.parse(_);return Number.isNaN(J)||Number.isNaN(U)||J>U}function fh($,_){return N_(_.source)===$.source&&N_(_.target)===$.target&&N_(_.route)===$.route&&N_(_.target_kind)===$.targetKind&&N_(_.confidence)===$.confidence}function Ch($,_){return N_(_.source)===$.source&&N_(_.requested_machine_id)===$.requested_machine_id&&N_(_.machine_id)===$.machine_id&&N_(_.project_id)===$.project_id&&N_(_.repo_name)===$.repo_name&&N_(_.project_root)===$.project_root&&N_(_.project_root_source)===$.project_root_source&&N_(_.workspace_root)===$.workspace_root&&N_(_.workspace_root_source)===$.workspace_root_source&&N_(_.open_files_root)===$.open_files_root&&N_(_.open_files_root_source)===$.open_files_root_source&&N_(_.trust_status)===$.trust_status&&N_(_.auth_status)===$.auth_status&&yV(_.current)===$.current&&yV(_.primary)===$.primary}function Ph($,_,J){if(!$)return null;let U=aV(_.cacheability);if(U&&sV(U,J)&&fh($,_))return{...$,cacheability:U};return $}function Th($,_,J){if(!$)return null;let U=aV(_.cacheability);if(U&&sV(U,J)&&Ch($,_))return{...$,cacheability:U};return $}function Sh($){return $.workspace?.machine_id??$.workspace?.requested_machine_id??$.machineId??$.route?.target??xV()}function Zh($,_){let J=new Set,U=Array.isArray(_.sources)?_.sources:[];for(let W of U)if(typeof W==="string")J.add(W);if(typeof _.source==="string")J.add(_.source);if($.route?.source)J.add($.route.source);if($.workspace?.source)J.add($.workspace.source);return J.add("knowledge"),[...J].sort()}function hV($,_){if(_?.target&&(_.route==="tailscale"||_.targetKind==="tailscale"))return _.target;return $?.tailscale_dns??null}function vh($,_,J){let U=b0(_.resolver_evidence),W=$.route?X8({source:$.route.source,target:$.route.target,route:$.route.route,target_kind:$.route.targetKind,confidence:$.route.confidence,adapter:$.route.adapter,evidence:$.route.evidence,cacheability:$.route.cacheability,warnings:$.route.warnings}):b0(U.route),X=$.workspace?X8({source:$.workspace.source,requested_machine_id:$.workspace.requested_machine_id,machine_id:$.workspace.machine_id,project_id:$.workspace.project_id,repo_name:$.workspace.repo_name,project_root:$.workspace.project_root,project_root_source:$.workspace.project_root_source,workspace_root:$.workspace.workspace_root,workspace_root_source:$.workspace.workspace_root_source,open_files_root:$.workspace.open_files_root,open_files_root_source:$.workspace.open_files_root_source,trust_status:$.workspace.trust_status,auth_status:$.workspace.auth_status,current:$.workspace.current,primary:$.workspace.primary,diagnostics:$.workspace.diagnostics,repair_hints:$.workspace.repair_hints,evidence:$.workspace.evidence,cacheability:$.workspace.cacheability,warnings:$.workspace.warnings}):b0(U.workspace);return X8({...U,recorded_at:J,route:W,workspace:X})}function eV($,_){a($);let J=m($);try{let U=Sh(_),W=J.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(U)??null,X=D4(_.now),G=tQ(W?.capabilities_json),Y=tQ(W?.metadata_json),Q=b0(G.resolver),q=b0(Y.resolver_evidence),L=b0(q.route),N=b0(q.workspace),R=Ph(_.route?.source==="registry"?null:_.route??null,L,X),B=Th(_.workspace?.source==="registry"?null:_.workspace??null,N,X),H={..._,route:R,workspace:B},V={...G,resolver:X8({...Q,route_source:R?.source??Q.route_source,route_kind:R?.route??Q.route_kind,route_target_kind:R?.targetKind??Q.route_target_kind,route_confidence:R?.confidence??Q.route_confidence,route_cacheable:R?.cacheability?.cacheable??Q.route_cacheable,route_stale:R?.cacheability?.stale??Q.route_stale,route_expires_at:R?.cacheability?.expires_at??Q.route_expires_at,route_observed_at:R?.cacheability?.observed_at??Q.route_observed_at,route_source_authority:R?.cacheability?.source_authority??Q.route_source_authority,workspace_source:B?.source??Q.workspace_source,project_root_source:B?.project_root_source??Q.project_root_source,workspace_root_source:B?.workspace_root_source??Q.workspace_root_source,open_files_root_source:B?.open_files_root_source??Q.open_files_root_source,trust_status:B?.trust_status??Q.trust_status,auth_status:B?.auth_status??Q.auth_status,workspace_cacheable:B?.cacheability?.cacheable??Q.workspace_cacheable,workspace_stale:B?.cacheability?.stale??Q.workspace_stale,workspace_expires_at:B?.cacheability?.expires_at??Q.workspace_expires_at,workspace_observed_at:B?.cacheability?.observed_at??Q.workspace_observed_at,workspace_source_authority:B?.cacheability?.source_authority??Q.workspace_source_authority}),route_fallback:Boolean(R?.target??W?.ssh_target),workspace_fallback:Boolean(B?.project_root??W?.workspace_home)},K=vh(H,Y,X);if(W){let F=q;if(W.workspace_home===(B?.project_root??W.workspace_home??null)&&W.tailscale_dns===hV(W,R)&&W.ssh_target===(R?.target??W.ssh_target??null)&&uJ(tQ(W.capabilities_json))===uJ(V)&&uJ(vV(F))===uJ(vV(K)))return W}let E={machine_id:U,hostname:W?.hostname??null,platform:W?.platform??null,user_label:W?.user_label??null,workspace_home:B?.project_root??W?.workspace_home??null,tailscale_dns:hV(W,R),tailscale_ips_json:JSON.stringify(gh(W?.tailscale_ips_json)),ssh_target:R?.target??W?.ssh_target??null,last_seen_at:X,capabilities_json:JSON.stringify(V),metadata_json:JSON.stringify({...Y,source:"knowledge",sources:Zh(H,Y),resolver_evidence:K}),created_at:W?.created_at??X,updated_at:X};return $R(J,E),E}finally{J.close()}}function $R($,_){$.query(` INSERT INTO knowledge_machines ( machine_id, hostname, platform, user_label, workspace_home, tailscale_dns, tailscale_ips_json, ssh_target, last_seen_at, capabilities_json, @@ -809,15 +870,15 @@ ${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:_.config, capabilities_json = excluded.capabilities_json, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `).run(_.machine_id,_.hostname,_.platform,_.user_label,_.workspace_home,_.tailscale_dns,_.tailscale_ips_json,_.ssh_target,_.last_seen_at,_.capabilities_json,_.metadata_json,_.created_at,_.updated_at)}function Dh($,_,J=j0()){for(let U of _.machines)cV($,Jh(U,J));return _.machines.length}function tY($){G$($);let _=i($);try{return _.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{_.close()}}function EU($){G$($.dbPath);let _=i($.dbPath),J=[],U=j0($.now),W=PV($.machineId),X=$.recordClocks!==!1;try{let G=TV(_,SV($.tables)),Y=_.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json + `).run(_.machine_id,_.hostname,_.platform,_.user_label,_.workspace_home,_.tailscale_dns,_.tailscale_ips_json,_.ssh_target,_.last_seen_at,_.capabilities_json,_.metadata_json,_.created_at,_.updated_at)}function yh($,_,J=D4()){for(let U of _.machines)$R($,wh(U,J));return _.machines.length}function Wq($){a($);let _=m($);try{return _.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{_.close()}}function fU($){a($.dbPath);let _=m($.dbPath),J=[],U=D4($.now),W=nV($.machineId),X=$.recordClocks!==!1;try{let G=cV(_,iV($.tables)),Q=_.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all().map((H)=>{let V=ay(H,$.storage.local_layout.directories.artifacts),R={...H,key:V};if($.includeArtifactContent!==!1&&V&&H.artifact_uri.startsWith("file://"))try{let M=fV(H.artifact_uri);if(Cy(M))if(!ey(H.content_type,V))J.push(`artifact_content_not_embedded_binary:${H.id}`);else{let K=Py(M,"utf8"),w=z6(K);if(w!==K)J.push(`artifact_content_redacted:${H.id}`);R.content_base64=Buffer.from(w,"utf8").toString("base64"),R.hash=RU(w),R.size_bytes=Buffer.byteLength(w)}else J.push(`artifact_missing:${H.artifact_uri}`)}catch(M){J.push(`artifact_read_failed:${H.artifact_uri}:${M instanceof Error?M.message:String(M)}`)}else if($.includeArtifactContent!==!1&&H.artifact_uri.startsWith("s3://"))J.push(`artifact_content_not_embedded:${H.artifact_uri}`);return R=z6(R),R}),q=k2(Y),L=G.filter((H)=>!bU.has(H)).map((H)=>({table:H,primary_keys:AU[H],rows:ZV(_,H).map((V)=>z6(V))})),N=L.map((H)=>uy(_,{table:H.table,machineId:W,highWaterHash:J8(H.table,H.rows,q),rowCount:H.rows.length,record:X,now:U})),F=RU(yJ({source:{scope:$.scope,workspace_home:z6($.workspaceHome),sqlite_schema_version:I6(_),machine_id:W,artifact_root_uri:z6($.storage.artifact_store.uri_prefix)},tables:L.map((H)=>({table:H.table,primary_keys:H.primary_keys,rows:H.rows.map((V)=>({key:g2(H.table,V),hash:I2(V,q)})).sort((V,R)=>V.key.localeCompare(R.key))})),table_clocks:N.map((H)=>({table:H.table,machine_id:H.machine_id,logical_clock:H.logical_clock,high_water_hash:H.high_water_hash,row_count:H.row_count})),artifacts:Y.map((H)=>({identity:X8(H),fingerprint:M1(H)})).sort((H,V)=>H.identity.localeCompare(V.identity))})),B=`syncbundle_${F.replace("sha256:","").slice(0,32)}`;for(let H of N)dy(_,H,B,X,U);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:b1,min_protocol_version:E1,bundle_id:B,content_hash:F,generated_at:U,source:{scope:$.scope,workspace_home:z6($.workspaceHome),sqlite_schema_version:I6(_),machine_id:W,artifact_root_uri:z6($.storage.artifact_store.uri_prefix)},table_clocks:N,tables:L,artifacts:Y,warnings:z6(J),message:`${L.reduce((H,V)=>H+V.rows.length,0)} row(s), ${Y.length} artifact(s) exported`}}finally{_.close()}}function Lh($,_){let J=typeof $.protocol_version==="number"?$.protocol_version:null,U=typeof $.min_protocol_version==="number"?$.min_protocol_version:null;if(J===null||U===null||Jb1)throw Error(`Unsupported ${_} protocol. Expected knowledge sync protocol v${b1} with min v${E1}.`)}function Bh($){if(!$||$.format!=="knowledge-sync-bundle"||$.version!==1)throw Error("Invalid knowledge sync bundle.");Lh($,"knowledge sync bundle")}function aY($,_){return $.tables.find((J)=>J.table===_)??null}function lV($){if(typeof $.content_hash==="string"&&$.content_hash.length>0)return $.content_hash;return RU(yJ({source:$.source,tables:$.tables.map((_)=>({table:_.table,rows:_.rows.map((J)=>({key:g2(_.table,J),hash:I2(J,k2($.artifacts))})).sort((J,U)=>J.key.localeCompare(U.key))})),artifacts:$.artifacts.map((_)=>({identity:X8(_),fingerprint:M1(_)})).sort((_,J)=>_.identity.localeCompare(J.identity))}))}function Hh($){if(typeof $.bundle_id==="string"&&$.bundle_id.length>0)return $.bundle_id;return`syncbundle_${lV($).replace("sha256:","").slice(0,32)}`}function Nh($,_){return new Map(_.map((J)=>[g2($,J),J]))}function Vh($){return new Map($.artifacts.map((_)=>[X8(_),_]))}async function Fh($){let _=Vh($.targetBundle),J=new Map,U=[],W={source_artifacts:$.bundle.artifacts.length,target_artifacts:$.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let X of $.bundle.artifacts){let G=X8(X),Q=_.get(G);if(Q&&M1(Q)===M1(X)){if(Q.artifact_uri)J.set(X.artifact_uri,Q.artifact_uri);W.skipped+=1;continue}if(Q&&M1(Q)!==M1(X)){let H={entityKind:"storage_object",entityId:G,localMachineId:$.localMachineId,remoteMachineId:$.bundle.source.machine_id??"unknown",localHash:M1(Q),remoteHash:M1(X),metadata:{direction:$.direction,target_artifact_uri:Q.artifact_uri,source_artifact_uri:X.artifact_uri,local_artifact:KU(Q),remote_artifact:KU(X)}};if(iY($.db,H)){W.skipped+=1;continue}W.conflicts+=1,U.push(H);continue}let Y=Boolean(X.key&&X.content_base64),q=$h(X,$.targetStorage);if(!Y&&!q){W.missing_content+=1,$.warnings.push(`artifact_content_missing:${X.artifact_uri}`);continue}if($.dryRun){W.copied+=1;continue}let L=X.artifact_uri;if(Y&&X.key&&X.content_base64)L=(await $.targetStore.put({key:X.key,body:Buffer.from(X.content_base64,"base64"),content_type:X.content_type??void 0})).uri,J.set(X.artifact_uri,L);else if(q)J.set(X.artifact_uri,L);let N=W8(X.metadata_json,{}),F=typeof N.artifact_modified_at==="string"?N.artifact_modified_at:void 0,B={uri:L,key:X.key??N.key??X.artifact_uri,kind:X.kind,content_type:X.content_type??void 0,hash:X.hash??void 0,size_bytes:X.size_bytes??void 0,modified_at:F,metadata:{...N,synced_from_artifact_uri:X.artifact_uri,synced_from_machine_id:$.bundle.source.machine_id??void 0}};m0($.db,[B]),W.copied+=1}return{result:W,uriMap:J,conflicts:U}}function lY($,_){let J={...$};if(typeof J.artifact_uri==="string"&&_.has(J.artifact_uri))J.artifact_uri=_.get(J.artifact_uri);return J}function Rh($,_){let J=j0();$.query(` + ORDER BY artifact_uri ASC`).all().map((H)=>{let V=Fh(H,$.storage.local_layout.directories.artifacts),K={...H,key:V};if($.includeArtifactContent!==!1&&V&&H.artifact_uri.startsWith("file://"))try{let E=uV(H.artifact_uri);if(_h(E))if(!Mh(H.content_type,V))J.push(`artifact_content_not_embedded_binary:${H.id}`);else{let F=Jh(E,"utf8"),w=j_(F);if(w!==F)J.push(`artifact_content_redacted:${H.id}`);K.content_base64=Buffer.from(w,"utf8").toString("base64"),K.hash=bU(w),K.size_bytes=Buffer.byteLength(w)}else J.push(`artifact_missing:${H.artifact_uri}`)}catch(E){J.push(`artifact_read_failed:${H.artifact_uri}:${E instanceof Error?E.message:String(E)}`)}else if($.includeArtifactContent!==!1&&H.artifact_uri.startsWith("s3://"))J.push(`artifact_content_not_embedded:${H.artifact_uri}`);return K=j_(K),K}),q=P1(Q),L=G.filter((H)=>!IU.has(H)).map((H)=>({table:H,primary_keys:kU[H],rows:lV(_,H).map((V)=>j_(V))})),N=L.map((H)=>jh(_,{table:H.table,machineId:W,highWaterHash:Y8(H.table,H.rows,q),rowCount:H.rows.length,record:X,now:U})),R=bU(dJ({source:{scope:$.scope,workspace_home:j_($.workspaceHome),sqlite_schema_version:b_(_),machine_id:W,artifact_root_uri:j_($.storage.artifact_store.uri_prefix)},tables:L.map((H)=>({table:H.table,primary_keys:H.primary_keys,rows:H.rows.map((V)=>({key:C1(H.table,V),hash:f1(V,q)})).sort((V,K)=>V.key.localeCompare(K.key))})),table_clocks:N.map((H)=>({table:H.table,machine_id:H.machine_id,logical_clock:H.logical_clock,high_water_hash:H.high_water_hash,row_count:H.row_count})),artifacts:Q.map((H)=>({identity:z8(H),fingerprint:A0(H)})).sort((H,V)=>H.identity.localeCompare(V.identity))})),B=`syncbundle_${R.replace("sha256:","").slice(0,32)}`;for(let H of N)Dh(_,H,B,X,U);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:w0,min_protocol_version:g0,bundle_id:B,content_hash:R,generated_at:U,source:{scope:$.scope,workspace_home:j_($.workspaceHome),sqlite_schema_version:b_(_),machine_id:W,artifact_root_uri:j_($.storage.artifact_store.uri_prefix)},table_clocks:N,tables:L,artifacts:Q,warnings:j_(J),message:`${L.reduce((H,V)=>H+V.rows.length,0)} row(s), ${Q.length} artifact(s) exported`}}finally{_.close()}}function hh($,_){let J=typeof $.protocol_version==="number"?$.protocol_version:null,U=typeof $.min_protocol_version==="number"?$.min_protocol_version:null;if(J===null||U===null||Jw0)throw Error(`Unsupported ${_} protocol. Expected knowledge sync protocol v${w0} with min v${g0}.`)}function mh($){if(!$||$.format!=="knowledge-sync-bundle"||$.version!==1)throw Error("Invalid knowledge sync bundle.");hh($,"knowledge sync bundle")}function Uq($,_){return $.tables.find((J)=>J.table===_)??null}function _R($){if(typeof $.content_hash==="string"&&$.content_hash.length>0)return $.content_hash;return bU(dJ({source:$.source,tables:$.tables.map((_)=>({table:_.table,rows:_.rows.map((J)=>({key:C1(_.table,J),hash:f1(J,P1($.artifacts))})).sort((J,U)=>J.key.localeCompare(U.key))})),artifacts:$.artifacts.map((_)=>({identity:z8(_),fingerprint:A0(_)})).sort((_,J)=>_.identity.localeCompare(J.identity))}))}function xh($){if(typeof $.bundle_id==="string"&&$.bundle_id.length>0)return $.bundle_id;return`syncbundle_${_R($).replace("sha256:","").slice(0,32)}`}function uh($,_){return new Map(_.map((J)=>[C1($,J),J]))}function dh($){return new Map($.artifacts.map((_)=>[z8(_),_]))}async function nh($){let _=dh($.targetBundle),J=new Map,U=[],W={source_artifacts:$.bundle.artifacts.length,target_artifacts:$.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let X of $.bundle.artifacts){let G=z8(X),Y=_.get(G);if(Y&&A0(Y)===A0(X)){if(Y.artifact_uri)J.set(X.artifact_uri,Y.artifact_uri);W.skipped+=1;continue}if(Y&&A0(Y)!==A0(X)){let H={entityKind:"storage_object",entityId:G,localMachineId:$.localMachineId,remoteMachineId:$.bundle.source.machine_id??"unknown",localHash:A0(Y),remoteHash:A0(X),metadata:{direction:$.direction,target_artifact_uri:Y.artifact_uri,source_artifact_uri:X.artifact_uri,local_artifact:wU(Y),remote_artifact:wU(X)}};if(eQ($.db,H)){W.skipped+=1;continue}W.conflicts+=1,U.push(H);continue}let Q=Boolean(X.key&&X.content_base64),q=Ah(X,$.targetStorage);if(!Q&&!q){W.missing_content+=1,$.warnings.push(`artifact_content_missing:${X.artifact_uri}`);continue}if($.dryRun){W.copied+=1;continue}let L=X.artifact_uri;if(Q&&X.key&&X.content_base64)L=(await $.targetStore.put({key:X.key,body:Buffer.from(X.content_base64,"base64"),content_type:X.content_type??void 0})).uri,J.set(X.artifact_uri,L);else if(q)J.set(X.artifact_uri,L);let N=Q8(X.metadata_json,{}),R=typeof N.artifact_modified_at==="string"?N.artifact_modified_at:void 0,B={uri:L,key:X.key??N.key??X.artifact_uri,kind:X.kind,content_type:X.content_type??void 0,hash:X.hash??void 0,size_bytes:X.size_bytes??void 0,modified_at:R,metadata:{...N,synced_from_artifact_uri:X.artifact_uri,synced_from_machine_id:$.bundle.source.machine_id??void 0}};u4($.db,[B]),W.copied+=1}return{result:W,uriMap:J,conflicts:U}}function aQ($,_){let J={...$};if(typeof J.artifact_uri==="string"&&_.has(J.artifact_uri))J.artifact_uri=_.get(J.artifact_uri);return J}function ch($,_){let J=D4();$.query(` INSERT INTO knowledge_sync_changes ( id, origin_machine_id, updated_by_machine_id, entity_kind, entity_id, operation, base_hash, next_hash, source_ref, source_revision_id, artifact_uri, logical_clock, bundle_id, metadata_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(pY("syncchg"),_.sourceMachineId,_.localMachineId,_.entityKind,_.entityId,_.direction,null,_.nextHash,typeof _.row?.source_ref==="string"?_.row.source_ref:typeof _.row?.source_uri==="string"?_.row.source_uri:null,typeof _.row?.source_revision_id==="string"?_.row.source_revision_id:null,typeof _.row?.artifact_uri==="string"?_.row.artifact_uri:null,_.logicalClock,_.bundleId,JSON.stringify({source_machine_id:_.sourceMachineId,bundle_id:_.bundleId}),J)}function iY($,_){let J=_.localHash??"",U=_.remoteHash??"";if($.query(` + `).run(_q("syncchg"),_.sourceMachineId,_.localMachineId,_.entityKind,_.entityId,_.direction,null,_.nextHash,typeof _.row?.source_ref==="string"?_.row.source_ref:typeof _.row?.source_uri==="string"?_.row.source_uri:null,typeof _.row?.source_revision_id==="string"?_.row.source_revision_id:null,typeof _.row?.artifact_uri==="string"?_.row.artifact_uri:null,_.logicalClock,_.bundleId,JSON.stringify({source_machine_id:_.sourceMachineId,bundle_id:_.bundleId}),J)}function eQ($,_){let J=_.localHash??"",U=_.remoteHash??"";if($.query(` SELECT id FROM knowledge_sync_conflicts WHERE entity_kind = ? AND entity_id = ? @@ -839,7 +900,7 @@ ${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:_.config, AND status IN ('resolved', 'ignored') AND resolved_at IS NOT NULL LIMIT 1 - `).get(_.entityKind,_.entityId,_.remoteMachineId,_.localMachineId,U,J);return Boolean(X)}function nY($,_){if($.query(` + `).get(_.entityKind,_.entityId,_.remoteMachineId,_.localMachineId,U,J);return Boolean(X)}function sQ($,_){if($.query(` SELECT id FROM knowledge_sync_conflicts WHERE entity_kind = ? AND entity_id = ? @@ -850,13 +911,13 @@ ${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:_.config, AND COALESCE(base_hash, '') = COALESCE(?, '') AND status = 'open' LIMIT 1 - `).get(_.entityKind,_.entityId,_.localMachineId,_.remoteMachineId,_.localHash??null,_.remoteHash??null,_.baseHash??null))return!1;let U=j0();return $.query(` + `).get(_.entityKind,_.entityId,_.localMachineId,_.remoteMachineId,_.localHash??null,_.remoteHash??null,_.baseHash??null))return!1;let U=D4();return $.query(` INSERT INTO knowledge_sync_conflicts ( id, entity_kind, entity_id, local_machine_id, remote_machine_id, local_hash, remote_hash, base_hash, status, resolution_strategy, proposed_patch_uri, approved_by, resolved_at, metadata_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(pY("syncconf"),_.entityKind,_.entityId,_.localMachineId,_.remoteMachineId,_.localHash??null,_.remoteHash??null,_.baseHash??null,_.status??"open",_.resolutionStrategy??null,_.proposedPatchUri??null,_.approvedBy??null,_.resolvedAt??null,JSON.stringify(_.metadata??{}),U),!0}function Kh($,_){return $.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get(_)??null}function Mh($,_){let J=_.now??j0();$.query(` + `).run(_q("syncconf"),_.entityKind,_.entityId,_.localMachineId,_.remoteMachineId,_.localHash??null,_.remoteHash??null,_.baseHash??null,_.status??"open",_.resolutionStrategy??null,_.proposedPatchUri??null,_.approvedBy??null,_.resolvedAt??null,JSON.stringify(_.metadata??{}),U),!0}function ih($,_){return $.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get(_)??null}function lh($,_){let J=_.now??D4();$.query(` INSERT INTO knowledge_sync_imports ( bundle_id, source_machine_id, target_machine_id, direction, status, content_hash, table_clocks_json, tables_json, generated_at, applied_at, @@ -866,13 +927,13 @@ ${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:_.config, status = excluded.status, applied_at = excluded.applied_at, metadata_json = excluded.metadata_json - `).run(_.bundleId,_.sourceMachineId,_.targetMachineId,_.direction,_.status,_.contentHash,JSON.stringify(_.bundle.table_clocks??[]),JSON.stringify(_.tableResults),_.bundle.generated_at,J,JSON.stringify({conflicts:_.conflicts,artifacts:_.artifacts,source_workspace_home:_.bundle.source.workspace_home}))}function Ah($){return{ok:!0,protocol_version:b1,min_protocol_version:E1,dry_run:!1,direction:$.direction,source:$.bundle.source,target:{scope:$.targetScope,workspace_home:$.targetWorkspaceHome,sqlite_schema_version:$.targetBundle.source.sqlite_schema_version,artifact_root_uri:$.targetStorage.artifact_store.uri_prefix},tables:$.bundle.tables.filter((_)=>!bU.has(_.table)).map((_)=>({table:_.table,source_rows:_.rows.length,target_rows:aY($.targetBundle,_.table)?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:_.rows.length,conflicts:0,stale_skipped:0})),artifacts:{source_artifacts:$.bundle.artifacts.length,target_artifacts:$.targetBundle.artifacts.length,copied:0,skipped:$.bundle.artifacts.length,conflicts:0,missing_content:0},conflicts_created:0,bundle_id:$.bundleId,replayed:!0,clocks:{advanced:0,stale_tables:0},warnings:[...$.warnings,`bundle_replay_skipped:${$.bundleId}`],message:`Skipped already-applied bundle ${$.bundleId}`}}function bh($,_){let J=k2($.artifacts),U=k2(_.artifacts);for(let W of $.tables){if(bU.has(W.table))continue;let X=aY(_,W.table),Q=vV($,W.table)?.high_water_hash??J8(W.table,W.rows,J);if(J8(W.table,X?.rows??[],U)!==Q)return!1}return!0}async function G8($){Bh($.bundle),G$($.targetDbPath);let _=[...$.bundle.warnings],J=$.dryRun===!0,U=PV($.localMachineId),W=$.bundle.source.machine_id??"unknown",X=Hh($.bundle),G=lV($.bundle),Q=$.targetBundle??EU({dbPath:$.targetDbPath,scope:$.targetScope,workspaceHome:$.targetWorkspaceHome,storage:$.targetStorage,machineId:U,includeArtifactContent:!1,recordClocks:!J}),Y=i($.targetDbPath);try{if(!J&&Kh(Y,X)&&bh($.bundle,Q))return Ah({bundle:$.bundle,targetBundle:Q,targetScope:$.targetScope,targetWorkspaceHome:$.targetWorkspaceHome,targetStorage:$.targetStorage,direction:$.direction,warnings:_,bundleId:X});let q=await Fh({db:Y,bundle:$.bundle,targetBundle:Q,targetStorage:$.targetStorage,targetStore:$.targetStore,dryRun:J,direction:$.direction,localMachineId:U,warnings:_}),L=k2($.bundle.artifacts),N=k2(Q.artifacts),F=[],B=0,H=0,V=0;for(let K of $.bundle.tables){if(K.table==="storage_objects"||bU.has(K.table))continue;if(!H4(Y,K.table))continue;let w=vV($.bundle,K.table),b=MU(Y,K.table,W),I=aY(Q,K.table),v=Nh(K.table,I?.rows??[]),g=new Set(K.rows.map((q6)=>g2(K.table,q6))),x=ny(Y,K.table,W),Y6=[],l$={table:K.table,source_rows:K.rows.length,target_rows:I?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!w)_.push(`legacy_clock_missing:${K.table}`);else if(cy(b,w)){V+=1,l$.skipped+=K.rows.length,l$.stale_skipped=K.rows.length,_.push(`stale_table_skipped:${K.table}:${W}:${w.logical_clock}`),F.push(l$);continue}for(let q6 of K.rows){let F6=g2(K.table,q6),M$=v.get(F6),b6=I2(q6,L);if(!M$){l$.inserted+=1,Y6.push(lY(q6,q.uriMap));continue}let j6=I2(M$,N);if(j6===b6){l$.skipped+=1;continue}let J6=x.get(F6);if(x.has(F6)&&J6===j6){l$.updated+=1,Y6.push(lY(q6,q.uriMap));continue}let R6={entityKind:K.table,entityId:F6,localMachineId:U,remoteMachineId:W,localHash:j6,remoteHash:b6,baseHash:b?.high_water_hash??null,metadata:{direction:$.direction,bundle_id:X,incoming_logical_clock:w?.logical_clock??null,current_logical_clock:b?.logical_clock??null,source_workspace_home:$.bundle.source.workspace_home,target_workspace_home:$.targetWorkspaceHome,local_row:FU(M$),remote_row:FU(q6)}};if(iY(Y,R6)){l$.skipped+=1;continue}if(l$.conflicts+=1,!J&&nY(Y,R6))B+=1}if(!J&&Y6.length>0){let q6=Y6.map((F6)=>lY(F6,q.uriMap));ly(Y,K.table,q6),oy(Y,K.table,q6);for(let F6 of q6)Rh(Y,{direction:$.direction,sourceMachineId:$.bundle.source.machine_id??"unknown",localMachineId:U,entityKind:K.table,entityId:g2(K.table,F6),nextHash:I2(F6,k2($.bundle.artifacts)),logicalClock:w?.logical_clock??0,bundleId:X,row:F6})}for(let[q6,F6]of x){if(g.has(q6))continue;let M$=v.get(q6);if(!M$)continue;let b6=I2(M$,N);if(F6&&b6!==F6){let j6={entityKind:K.table,entityId:q6,localMachineId:U,remoteMachineId:W,localHash:b6,remoteHash:null,baseHash:F6,metadata:{direction:$.direction,bundle_id:X,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:$.bundle.source.workspace_home,target_workspace_home:$.targetWorkspaceHome,local_row:FU(M$),remote_row:null}};if(iY(Y,j6)){l$.skipped+=1;continue}if(l$.conflicts+=1,!J&&nY(Y,j6))B+=1;continue}if(l$.deleted+=1,!J)ry(Y,K.table,q6)}if(!J&&w)U8(Y,{table:K.table,machineId:W,logicalClock:w.logical_clock,highWaterHash:w.high_water_hash,highWaterBundleId:X,originMachineId:W,updatedByMachineId:U,lastAppliedAt:j0(),metadata:{source:"import",direction:$.direction,row_count:K.rows.length,inserted:l$.inserted,updated:l$.updated,deleted:l$.deleted,skipped:l$.skipped,conflicts:l$.conflicts}}),H+=1;F.push(l$)}for(let K of q.conflicts)if(!J){if(nY(Y,{...K,baseHash:K.baseHash??null,metadata:{...K.metadata,bundle_id:X}}))B+=1}let R=F.reduce((K,w)=>K+w.inserted,0),M=F.reduce((K,w)=>K+w.conflicts,0)+q.result.conflicts;if(!J)Mh(Y,{bundle:$.bundle,bundleId:X,contentHash:G,sourceMachineId:W,targetMachineId:U,direction:$.direction,status:M===0?"applied":"conflicted",tableResults:F,conflicts:M,artifacts:q.result});return{ok:M===0,protocol_version:b1,min_protocol_version:E1,dry_run:J,direction:$.direction,source:$.bundle.source,target:{scope:$.targetScope,workspace_home:$.targetWorkspaceHome,sqlite_schema_version:I6(Y),artifact_root_uri:$.targetStorage.artifact_store.uri_prefix},tables:F,artifacts:q.result,conflicts_created:B,bundle_id:X,replayed:!1,clocks:{advanced:H,stale_tables:V},warnings:_,message:`${$.dryRun?"Would import":"Imported"} ${R} row(s), copied ${q.result.copied} artifact(s), ${M} conflict(s)`}}finally{Y.close()}}function nV($){G$($.dbPath);let _=i($.dbPath),J=j0($.now);try{let U=$.topology?Dh(_,$.topology,J):0,W=mV(_),X=z6(_h(_)),G=$.machineId??$.topology?.local_machine_id??"unknown",Q=z6($.storage.artifact_store.uri_prefix),Y=z6($.workspaceHome),q=RU(yJ({machine_id:G,scope:$.scope,workspace_home:Y,sqlite_schema_version:I6(_),artifact_root_uri:Q,tables:W,artifacts:X})),L={id:pY("syncsnap"),machine_id:G,scope:$.scope,workspace_home:Y,sqlite_schema_version:I6(_),artifact_root_uri:Q,content_hash:q,tables_json:JSON.stringify(W),artifact_hashes_json:JSON.stringify(X),created_at:J};_.query(` + `).run(_.bundleId,_.sourceMachineId,_.targetMachineId,_.direction,_.status,_.contentHash,JSON.stringify(_.bundle.table_clocks??[]),JSON.stringify(_.tableResults),_.bundle.generated_at,J,JSON.stringify({conflicts:_.conflicts,artifacts:_.artifacts,source_workspace_home:_.bundle.source.workspace_home}))}function rh($){return{ok:!0,protocol_version:w0,min_protocol_version:g0,dry_run:!1,direction:$.direction,source:$.bundle.source,target:{scope:$.targetScope,workspace_home:$.targetWorkspaceHome,sqlite_schema_version:$.targetBundle.source.sqlite_schema_version,artifact_root_uri:$.targetStorage.artifact_store.uri_prefix},tables:$.bundle.tables.filter((_)=>!IU.has(_.table)).map((_)=>({table:_.table,source_rows:_.rows.length,target_rows:Uq($.targetBundle,_.table)?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:_.rows.length,conflicts:0,stale_skipped:0})),artifacts:{source_artifacts:$.bundle.artifacts.length,target_artifacts:$.targetBundle.artifacts.length,copied:0,skipped:$.bundle.artifacts.length,conflicts:0,missing_content:0},conflicts_created:0,bundle_id:$.bundleId,replayed:!0,clocks:{advanced:0,stale_tables:0},warnings:[...$.warnings,`bundle_replay_skipped:${$.bundleId}`],message:`Skipped already-applied bundle ${$.bundleId}`}}function ph($,_){let J=P1($.artifacts),U=P1(_.artifacts);for(let W of $.tables){if(IU.has(W.table))continue;let X=Uq(_,W.table),Y=rV($,W.table)?.high_water_hash??Y8(W.table,W.rows,J);if(Y8(W.table,X?.rows??[],U)!==Y)return!1}return!0}async function j8($){mh($.bundle),a($.targetDbPath);let _=[...$.bundle.warnings],J=$.dryRun===!0,U=nV($.localMachineId),W=$.bundle.source.machine_id??"unknown",X=xh($.bundle),G=_R($.bundle),Y=$.targetBundle??fU({dbPath:$.targetDbPath,scope:$.targetScope,workspaceHome:$.targetWorkspaceHome,storage:$.targetStorage,machineId:U,includeArtifactContent:!1,recordClocks:!J}),Q=m($.targetDbPath);try{if(!J&&ih(Q,X)&&ph($.bundle,Y))return rh({bundle:$.bundle,targetBundle:Y,targetScope:$.targetScope,targetWorkspaceHome:$.targetWorkspaceHome,targetStorage:$.targetStorage,direction:$.direction,warnings:_,bundleId:X});let q=await nh({db:Q,bundle:$.bundle,targetBundle:Y,targetStorage:$.targetStorage,targetStore:$.targetStore,dryRun:J,direction:$.direction,localMachineId:U,warnings:_}),L=P1($.bundle.artifacts),N=P1(Y.artifacts),R=[],B=0,H=0,V=0;for(let F of $.bundle.tables){if(F.table==="storage_objects"||IU.has(F.table))continue;if(!N6(Q,F.table))continue;let w=rV($.bundle,F.table),A=gU(Q,F.table,W),g=Uq(Y,F.table),v=uh(F.table,g?.rows??[]),k=new Set(F.rows.map((z_)=>C1(F.table,z_))),u=Bh(Q,F.table,W),W_=[],c$={table:F.table,source_rows:F.rows.length,target_rows:g?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!w)_.push(`legacy_clock_missing:${F.table}`);else if(Oh(A,w)){V+=1,c$.skipped+=F.rows.length,c$.stale_skipped=F.rows.length,_.push(`stale_table_skipped:${F.table}:${W}:${w.logical_clock}`),R.push(c$);continue}for(let z_ of F.rows){let K_=C1(F.table,z_),E$=v.get(K_),A_=f1(z_,L);if(!E$){c$.inserted+=1,W_.push(aQ(z_,q.uriMap));continue}let D_=f1(E$,N);if(D_===A_){c$.skipped+=1;continue}let U_=u.get(K_);if(u.has(K_)&&U_===D_){c$.updated+=1,W_.push(aQ(z_,q.uriMap));continue}let F_={entityKind:F.table,entityId:K_,localMachineId:U,remoteMachineId:W,localHash:D_,remoteHash:A_,baseHash:A?.high_water_hash??null,metadata:{direction:$.direction,bundle_id:X,incoming_logical_clock:w?.logical_clock??null,current_logical_clock:A?.logical_clock??null,source_workspace_home:$.bundle.source.workspace_home,target_workspace_home:$.targetWorkspaceHome,local_row:AU(E$),remote_row:AU(z_)}};if(eQ(Q,F_)){c$.skipped+=1;continue}if(c$.conflicts+=1,!J&&sQ(Q,F_))B+=1}if(!J&&W_.length>0){let z_=W_.map((K_)=>aQ(K_,q.uriMap));Lh(Q,F.table,z_),Rh(Q,F.table,z_);for(let K_ of z_)ch(Q,{direction:$.direction,sourceMachineId:$.bundle.source.machine_id??"unknown",localMachineId:U,entityKind:F.table,entityId:C1(F.table,K_),nextHash:f1(K_,P1($.bundle.artifacts)),logicalClock:w?.logical_clock??0,bundleId:X,row:K_})}for(let[z_,K_]of u){if(k.has(z_))continue;let E$=v.get(z_);if(!E$)continue;let A_=f1(E$,N);if(K_&&A_!==K_){let D_={entityKind:F.table,entityId:z_,localMachineId:U,remoteMachineId:W,localHash:A_,remoteHash:null,baseHash:K_,metadata:{direction:$.direction,bundle_id:X,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:$.bundle.source.workspace_home,target_workspace_home:$.targetWorkspaceHome,local_row:AU(E$),remote_row:null}};if(eQ(Q,D_)){c$.skipped+=1;continue}if(c$.conflicts+=1,!J&&sQ(Q,D_))B+=1;continue}if(c$.deleted+=1,!J)Nh(Q,F.table,z_)}if(!J&&w)q8(Q,{table:F.table,machineId:W,logicalClock:w.logical_clock,highWaterHash:w.high_water_hash,highWaterBundleId:X,originMachineId:W,updatedByMachineId:U,lastAppliedAt:D4(),metadata:{source:"import",direction:$.direction,row_count:F.rows.length,inserted:c$.inserted,updated:c$.updated,deleted:c$.deleted,skipped:c$.skipped,conflicts:c$.conflicts}}),H+=1;R.push(c$)}for(let F of q.conflicts)if(!J){if(sQ(Q,{...F,baseHash:F.baseHash??null,metadata:{...F.metadata,bundle_id:X}}))B+=1}let K=R.reduce((F,w)=>F+w.inserted,0),E=R.reduce((F,w)=>F+w.conflicts,0)+q.result.conflicts;if(!J)lh(Q,{bundle:$.bundle,bundleId:X,contentHash:G,sourceMachineId:W,targetMachineId:U,direction:$.direction,status:E===0?"applied":"conflicted",tableResults:R,conflicts:E,artifacts:q.result});return{ok:E===0,protocol_version:w0,min_protocol_version:g0,dry_run:J,direction:$.direction,source:$.bundle.source,target:{scope:$.targetScope,workspace_home:$.targetWorkspaceHome,sqlite_schema_version:b_(Q),artifact_root_uri:$.targetStorage.artifact_store.uri_prefix},tables:R,artifacts:q.result,conflicts_created:B,bundle_id:X,replayed:!1,clocks:{advanced:H,stale_tables:V},warnings:_,message:`${$.dryRun?"Would import":"Imported"} ${K} row(s), copied ${q.result.copied} artifact(s), ${E} conflict(s)`}}finally{Q.close()}}function JR($){a($.dbPath);let _=m($.dbPath),J=D4($.now);try{let U=$.topology?yh(_,$.topology,J):0,W=tV(_),X=j_(bh(_)),G=$.machineId??$.topology?.local_machine_id??"unknown",Y=j_($.storage.artifact_store.uri_prefix),Q=j_($.workspaceHome),q=bU(dJ({machine_id:G,scope:$.scope,workspace_home:Q,sqlite_schema_version:b_(_),artifact_root_uri:Y,tables:W,artifacts:X})),L={id:_q("syncsnap"),machine_id:G,scope:$.scope,workspace_home:Q,sqlite_schema_version:b_(_),artifact_root_uri:Y,content_hash:q,tables_json:JSON.stringify(W),artifact_hashes_json:JSON.stringify(X),created_at:J};_.query(` INSERT INTO knowledge_sync_snapshots ( id, machine_id, scope, workspace_home, sqlite_schema_version, artifact_root_uri, content_hash, tables_json, artifact_hashes_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(L.id,L.machine_id,L.scope,L.workspace_home,L.sqlite_schema_version,L.artifact_root_uri,L.content_hash,L.tables_json,L.artifact_hashes_json,L.created_at);let N=new Map;for(let F of TV(_,SV()).filter((B)=>!bU.has(B))){let B=ZV(_,F).map((M)=>z6(M)),H=J8(F,B,N),V=MU(_,F,G),R=V?.high_water_hash===H?V.logical_clock:(V?.logical_clock??0)+1;U8(_,{table:F,machineId:G,logicalClock:R,highWaterHash:H,highWaterBundleId:L.id,originMachineId:V?.origin_machine_id??G,updatedByMachineId:G,lastAppliedAt:J,metadata:{source:"snapshot",row_count:B.length},now:J})}return{ok:!0,snapshot:{...L,tables:W,artifact_hashes:X},machines_upserted:U,message:`Recorded sync snapshot ${L.id}`}}finally{_.close()}}function iV($){G$($.dbPath);let _=i($.dbPath);try{let J=_.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(),U=_.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get()??null,W=_.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(),X=_.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(),G=xy(_),Q=_.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get()??null,Y=W.reduce((L,N)=>L+N.count,0),q=W.filter((L)=>L.status!=="resolved"&&L.status!=="ignored").reduce((L,N)=>L+N.count,0);return{ok:!0,scope:$.scope,workspace_home:z6($.workspaceHome),sqlite_schema_version:I6(_),local_machine_id:$.localMachineId??null,machines:{total:J.length,rows:z6(J)},snapshots:{total:e9(_,"knowledge_sync_snapshots"),latest:z6(U)},changes:{total:e9(_,"knowledge_sync_changes"),by_operation:X},clocks:{total:G.length,rows:G},imports:{total:e9(_,"knowledge_sync_imports"),latest:z6(Q)},conflicts:{total:Y,by_status:W,open:q},table_counts:mV(_),message:`${J.length} machine(s), ${q} open sync conflict(s)`}}finally{_.close()}}function sY($){return{...$,metadata:W8($.metadata_json,{})}}function Q8($,_){G$($);let J=i($);try{let U=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_);return U?sY(U):null}finally{J.close()}}function rV($,_={}){G$($);let J=i($),U=Math.max(1,Math.min(_.limit??50,200));try{return(_.status?J.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all(_.status,U):J.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(U)).map(sY)}finally{J.close()}}function Eh($){return _8.includes($)?$:null}function wh($,_){let J=Eh(_.entity_kind);if(!J||!H4($,J))return null;let U=yV(J,_.entity_id);if(!U)return null;let W=hV(J);return $.query(`SELECT * FROM ${X4(J)} WHERE ${W} LIMIT 1`).get(...U)}function Ih($,_){for(let J of _){let U=$[J];if(U&&typeof U==="object"&&!Array.isArray(U))return FU(U)}return null}function gV($,_){if(typeof _!=="string")return;let J=_.trim();if(!J)return;if(J.startsWith("open-files://")||J.startsWith("s3://")||J.startsWith("file://")||J.startsWith("https://")||J.startsWith("http://"))$.add(J)}function rY($,_=new Set,J=0){if(J>8||$===null||$===void 0)return _;if(typeof $==="string")return gV(_,$),_;if(Array.isArray($)){for(let U of $)rY(U,_,J+1);return _}if(typeof $==="object")for(let[U,W]of Object.entries($)){if(U==="source_ref"||U==="source_uri"||U==="artifact_uri"||U.endsWith("_uri"))gV(_,W);rY(W,_,J+1)}return _}function pV($){let _=[{id:"conflict",kind:"metadata",ref:`knowledge-sync-conflict://${$.conflict.id}`,hash:$.conflict.base_hash,quote:`Conflict on ${$.conflict.entity_kind}:${$.conflict.entity_id}`}];if($.localRow)_.push({id:"local-row",kind:"row",ref:`${$.conflict.entity_kind}:${$.conflict.entity_id}:local`,hash:$.conflict.local_hash,quote:JSON.stringify($.localRow).slice(0,300)});if($.remoteRow)_.push({id:"remote-row",kind:"row",ref:`${$.conflict.entity_kind}:${$.conflict.entity_id}:remote`,hash:$.conflict.remote_hash,quote:JSON.stringify($.remoteRow).slice(0,300)});return $.sourceRefs.slice(0,10).forEach((J,U)=>{_.push({id:`source-${U+1}`,kind:J.startsWith("file://")||J.startsWith("s3://")?"artifact":"source_ref",ref:J,hash:null,quote:null})}),_}function oV($,_){let J=Q8($,_);if(!J)throw Error(`Sync conflict not found: ${_}`);G$($);let U=i($);try{let W=FU(wh(U,J)),X=Ih(J.metadata,["remote_row","source_row","incoming_row"]),Q=[...rY({conflict:{entity_kind:J.entity_kind,entity_id:J.entity_id,metadata:J.metadata},local_row:W,remote_row:X})].slice(0,25),Y=[{name:"knowledge_sync_conflict_get",input:{id:_},output_summary:`${J.entity_kind}:${J.entity_id} status=${J.status}`},{name:"knowledge_catalog_row_get",input:{table:J.entity_kind,key:J.entity_id},output_summary:W?"local row found":"local row unavailable"},{name:"knowledge_source_ref_extract",input:{id:_},output_summary:`${Q.length} source/artifact ref(s) found`}];return{conflict:J,local_row:W,remote_row:X,source_refs:Q,citations:pV({conflict:J,localRow:W,remoteRow:X,sourceRefs:Q}),read_only_tools:Y}}finally{U.close()}}function wU($,_){let J=Q8($,_);if(!J)throw Error(`Sync conflict not found: ${_}`);let U=J.entity_kind==="wiki_pages"?"manual-merge":"review-and-select",W=[`Conflict ${J.id} affects ${J.entity_kind}:${J.entity_id}.`,`Local machine ${J.local_machine_id} has ${J.local_hash??"unknown hash"}.`,`Remote machine ${J.remote_machine_id} has ${J.remote_hash??"unknown hash"}.`].join(" "),X=["Review this knowledge sync conflict before any durable write.",`Entity: ${J.entity_kind}:${J.entity_id}`,`Local machine/hash: ${J.local_machine_id} / ${J.local_hash??"unknown"}`,`Remote machine/hash: ${J.remote_machine_id} / ${J.remote_hash??"unknown"}`,`Base hash: ${J.base_hash??"unknown"}`,`Metadata: ${JSON.stringify(J.metadata)}`,"Return a concise merge recommendation with citations to the competing records. Do not write changes without approval."].join(` -`);return{ok:!0,conflict:J,requires_approval:!0,mode:"deterministic",proposed_strategy:U,summary:W,merge_prompt:X,proposed_patch:null,citations:pV({conflict:J,localRow:null,remoteRow:null,sourceRefs:[]}),confidence:null,agent:null,warnings:J.status==="resolved"?["conflict_already_resolved"]:[],message:`Prepared approval-gated merge proposal for ${J.id}`}}function tV($,_){G$($);let J=i($),U=j0();try{let W=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_.id);if(!W)throw Error(`Sync conflict not found: ${_.id}`);J.query(` + `).run(L.id,L.machine_id,L.scope,L.workspace_home,L.sqlite_schema_version,L.artifact_root_uri,L.content_hash,L.tables_json,L.artifact_hashes_json,L.created_at);let N=new Map;for(let R of cV(_,iV()).filter((B)=>!IU.has(B))){let B=lV(_,R).map((E)=>j_(E)),H=Y8(R,B,N),V=gU(_,R,G),K=V?.high_water_hash===H?V.logical_clock:(V?.logical_clock??0)+1;q8(_,{table:R,machineId:G,logicalClock:K,highWaterHash:H,highWaterBundleId:L.id,originMachineId:V?.origin_machine_id??G,updatedByMachineId:G,lastAppliedAt:J,metadata:{source:"snapshot",row_count:B.length},now:J})}return{ok:!0,snapshot:{...L,tables:W,artifact_hashes:X},machines_upserted:U,message:`Recorded sync snapshot ${L.id}`}}finally{_.close()}}function WR($){a($.dbPath);let _=m($.dbPath);try{let J=_.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(),U=_.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get()??null,W=_.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(),X=_.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(),G=zh(_),Y=_.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get()??null,Q=W.reduce((L,N)=>L+N.count,0),q=W.filter((L)=>L.status!=="resolved"&&L.status!=="ignored").reduce((L,N)=>L+N.count,0);return{ok:!0,scope:$.scope,workspace_home:j_($.workspaceHome),sqlite_schema_version:b_(_),local_machine_id:$.localMachineId??null,machines:{total:J.length,rows:j_(J)},snapshots:{total:U8(_,"knowledge_sync_snapshots"),latest:j_(U)},changes:{total:U8(_,"knowledge_sync_changes"),by_operation:X},clocks:{total:G.length,rows:G},imports:{total:U8(_,"knowledge_sync_imports"),latest:j_(Y)},conflicts:{total:Q,by_status:W,open:q},table_counts:tV(_),message:`${J.length} machine(s), ${q} open sync conflict(s)`}}finally{_.close()}}function Xq($){return{...$,metadata:Q8($.metadata_json,{})}}function D8($,_){a($);let J=m($);try{let U=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_);return U?Xq(U):null}finally{J.close()}}function UR($,_={}){a($);let J=m($),U=Math.max(1,Math.min(_.limit??50,200));try{return(_.status?J.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all(_.status,U):J.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(U)).map(Xq)}finally{J.close()}}function oh($){return G8.includes($)?$:null}function th($,_){let J=oh(_.entity_kind);if(!J||!N6($,J))return null;let U=pV(J,_.entity_id);if(!U)return null;let W=oV(J);return $.query(`SELECT * FROM ${Y6(J)} WHERE ${W} LIMIT 1`).get(...U)}function ah($,_){for(let J of _){let U=$[J];if(U&&typeof U==="object"&&!Array.isArray(U))return AU(U)}return null}function mV($,_){if(typeof _!=="string")return;let J=_.trim();if(!J)return;if(J.startsWith("open-files://")||J.startsWith("s3://")||J.startsWith("file://")||J.startsWith("https://")||J.startsWith("http://"))$.add(J)}function $q($,_=new Set,J=0){if(J>8||$===null||$===void 0)return _;if(typeof $==="string")return mV(_,$),_;if(Array.isArray($)){for(let U of $)$q(U,_,J+1);return _}if(typeof $==="object")for(let[U,W]of Object.entries($)){if(U==="source_ref"||U==="source_uri"||U==="artifact_uri"||U.endsWith("_uri"))mV(_,W);$q(W,_,J+1)}return _}function XR($){let _=[{id:"conflict",kind:"metadata",ref:`knowledge-sync-conflict://${$.conflict.id}`,hash:$.conflict.base_hash,quote:`Conflict on ${$.conflict.entity_kind}:${$.conflict.entity_id}`}];if($.localRow)_.push({id:"local-row",kind:"row",ref:`${$.conflict.entity_kind}:${$.conflict.entity_id}:local`,hash:$.conflict.local_hash,quote:JSON.stringify($.localRow).slice(0,300)});if($.remoteRow)_.push({id:"remote-row",kind:"row",ref:`${$.conflict.entity_kind}:${$.conflict.entity_id}:remote`,hash:$.conflict.remote_hash,quote:JSON.stringify($.remoteRow).slice(0,300)});return $.sourceRefs.slice(0,10).forEach((J,U)=>{_.push({id:`source-${U+1}`,kind:J.startsWith("file://")||J.startsWith("s3://")?"artifact":"source_ref",ref:J,hash:null,quote:null})}),_}function GR($,_){let J=D8($,_);if(!J)throw Error(`Sync conflict not found: ${_}`);a($);let U=m($);try{let W=AU(th(U,J)),X=ah(J.metadata,["remote_row","source_row","incoming_row"]),Y=[...$q({conflict:{entity_kind:J.entity_kind,entity_id:J.entity_id,metadata:J.metadata},local_row:W,remote_row:X})].slice(0,25),Q=[{name:"knowledge_sync_conflict_get",input:{id:_},output_summary:`${J.entity_kind}:${J.entity_id} status=${J.status}`},{name:"knowledge_catalog_row_get",input:{table:J.entity_kind,key:J.entity_id},output_summary:W?"local row found":"local row unavailable"},{name:"knowledge_source_ref_extract",input:{id:_},output_summary:`${Y.length} source/artifact ref(s) found`}];return{conflict:J,local_row:W,remote_row:X,source_refs:Y,citations:XR({conflict:J,localRow:W,remoteRow:X,sourceRefs:Y}),read_only_tools:Q}}finally{U.close()}}function CU($,_){let J=D8($,_);if(!J)throw Error(`Sync conflict not found: ${_}`);let U=J.entity_kind==="wiki_pages"?"manual-merge":"review-and-select",W=[`Conflict ${J.id} affects ${J.entity_kind}:${J.entity_id}.`,`Local machine ${J.local_machine_id} has ${J.local_hash??"unknown hash"}.`,`Remote machine ${J.remote_machine_id} has ${J.remote_hash??"unknown hash"}.`].join(" "),X=["Review this knowledge sync conflict before any durable write.",`Entity: ${J.entity_kind}:${J.entity_id}`,`Local machine/hash: ${J.local_machine_id} / ${J.local_hash??"unknown"}`,`Remote machine/hash: ${J.remote_machine_id} / ${J.remote_hash??"unknown"}`,`Base hash: ${J.base_hash??"unknown"}`,`Metadata: ${JSON.stringify(J.metadata)}`,"Return a concise merge recommendation with citations to the competing records. Do not write changes without approval."].join(` +`);return{ok:!0,conflict:J,requires_approval:!0,mode:"deterministic",proposed_strategy:U,summary:W,merge_prompt:X,proposed_patch:null,citations:XR({conflict:J,localRow:null,remoteRow:null,sourceRefs:[]}),confidence:null,agent:null,warnings:J.status==="resolved"?["conflict_already_resolved"]:[],message:`Prepared approval-gated merge proposal for ${J.id}`}}function YR($,_){a($);let J=m($),U=D4();try{let W=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_.id);if(!W)throw Error(`Sync conflict not found: ${_.id}`);J.query(` UPDATE knowledge_sync_conflicts SET status = 'resolved', resolution_strategy = ?, @@ -880,35 +941,75 @@ ${F}`;else{let{generateText:b}=await import("ai"),I=await NU(W,{config:_.config, approved_by = ?, resolved_at = ? WHERE id = ? - `).run(_.strategy,_.proposedPatchUri??W.proposed_patch_uri,_.approvedBy,U,_.id);let X=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_.id);if(!X)throw Error(`Sync conflict not found after resolve: ${_.id}`);return sY(X)}finally{J.close()}}function jL($){let J=(typeof $==="string"?$:JSON.stringify($)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(J*1.25))}function Bu($){let _=i($.dbPath);try{_.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.runId,"sync-conflict-proposal",$.prompt,$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.now])}finally{_.close()}}function iR($){let _=i($.dbPath);try{_.run(`UPDATE runs + `).run(_.strategy,_.proposedPatchUri??W.proposed_patch_uri,_.approvedBy,U,_.id);let X=J.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get(_.id);if(!X)throw Error(`Sync conflict not found after resolve: ${_.id}`);return Xq(X)}finally{J.close()}}function VL($){let J=(typeof $==="string"?$:JSON.stringify($)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(J*1.25))}function mu($){let _=m($.dbPath);try{_.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.runId,"sync-conflict-proposal",$.prompt,$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.now])}finally{_.close()}}function WF($){let _=m($.dbPath);try{_.run(`UPDATE runs SET status = ?, provider = ?, model = ?, cost_tokens = ?, cost_usd = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`,[$.status,$.provider,$.model,$.usage.input_tokens+$.usage.output_tokens,$.usage.cost_usd,JSON.stringify($.metadata),$.now,$.runId])}finally{_.close()}}function OL($){let _=i($.dbPath);try{_.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`event_${rR()}`,$.runId,$.level,$.event,JSON.stringify($.metadata),$.now])}finally{_.close()}}function Hu($,_,J,U){let W=i($);try{gJ(W,{...J,run_id:_,created_at:U})}finally{W.close()}}function Nu($){return["Build an approval-gated merge proposal for this knowledge sync conflict.","Use only the supplied JSON evidence. Do not claim to inspect external files or write changes.","Return a patch recommendation that a human can review before approval.","",`Deterministic proposal: + WHERE id = ?`,[$.status,$.provider,$.model,$.usage.input_tokens+$.usage.output_tokens,$.usage.cost_usd,JSON.stringify($.metadata),$.now,$.runId])}finally{_.close()}}function RL($){let _=m($.dbPath);try{_.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`event_${UF()}`,$.runId,$.level,$.event,JSON.stringify($.metadata),$.now])}finally{_.close()}}function xu($,_,J,U){let W=m($);try{TJ(W,{...J,run_id:_,created_at:U})}finally{W.close()}}function uu($){return["Build an approval-gated merge proposal for this knowledge sync conflict.","Use only the supplied JSON evidence. Do not claim to inspect external files or write changes.","Return a patch recommendation that a human can review before approval.","",`Deterministic proposal: ${JSON.stringify({proposed_strategy:$.deterministic.proposed_strategy,summary:$.deterministic.summary,warnings:$.deterministic.warnings},null,2)}`,"",`Conflict evidence: ${JSON.stringify($.evidence,null,2)}`].join(` -`)}function Vu($){let _=typeof $==="number"&&Number.isFinite($)?$:0.5;return Math.max(0,Math.min(1,_))}function Fu($,_){let J=$.kind==="choose_local"||$.kind==="choose_remote"||$.kind==="no_op"||$.kind==="custom"||$.kind==="manual_merge"?$.kind:"manual_merge";return{kind:J,target:typeof $.target==="string"&&$.target?$.target:_,strategy:typeof $.strategy==="string"&&$.strategy?$.strategy:J.replace("_","-"),summary:typeof $.summary==="string"&&$.summary?$.summary:"Review both sides before applying a merge.",diff:typeof $.diff==="string"&&$.diff?$.diff:null,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:{}}}function Ru($){let _=`${$.conflict.entity_kind}:${$.conflict.entity_id}`,J=Boolean($.local_row&&$.remote_row);return{kind:J?"manual_merge":"custom",target:_,strategy:J?"manual-merge":"review-and-select",summary:J?`Fake AI proposal: compare local and remote ${_} row snapshots, then apply a reviewed manual merge.`:`Fake AI proposal: inspect ${_} with available conflict metadata before selecting a side.`,diff:J?[`--- ${_} local`,`+++ ${_} remote`,"@@ review-required @@",JSON.stringify({local:$.local_row,remote:$.remote_row},null,2).slice(0,1200)].join(` -`):null,metadata:{fake:!0,local_hash:$.conflict.local_hash,remote_hash:$.conflict.remote_hash,source_refs:$.source_refs}}}async function pR($){let _=($.now??new Date).toISOString();G$($.dbPath);let J=wU($.dbPath,$.id),U=oV($.dbPath,$.id),W=y4($.modelRef??"default",$.config),X=E6(W),G=`run_${rR()}`,Q=Nu({deterministic:J,evidence:U});Bu({dbPath:$.dbPath,runId:G,prompt:Q,provider:X.provider,model:X.model,status:$.fake?"dry_run":"running",metadata:{conflict_id:$.id,mode:"ai",fake:$.fake===!0,read_only_tools:U.read_only_tools.map((F)=>F.name)},now:_}),OL({dbPath:$.dbPath,runId:G,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:U.citations.length,source_refs:U.source_refs.length,read_only_tools:U.read_only_tools},now:_});let Y,q,L=0.5,N={input_tokens:jL(Q),output_tokens:0,cost_usd:0};if($.fake)Y=Ru(U),q=Y.summary,N.output_tokens=jL(q)+jL(Y.diff??"");else try{let{generateObject:F}=await import("ai"),{z:B}=await Promise.resolve().then(() => (nR(),lR)),H=await NU(W,{config:$.config,env:$.env}),V=B.object({summary:B.string(),confidence:B.number().min(0).max(1),proposed_patch:B.object({kind:B.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:B.string(),strategy:B.string(),summary:B.string(),diff:B.string().nullable(),metadata:B.record(B.string(),B.unknown()).default({})})}),R=await F({model:H,schema:V,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:Q});q=R.object.summary,L=Vu(R.object.confidence),Y=Fu(R.object.proposed_patch,`${U.conflict.entity_kind}:${U.conflict.entity_id}`);let M=b2({provider:X.provider,model:X.model,usage:R.usage,providerMetadata:R.providerMetadata});N={input_tokens:M.input_tokens,output_tokens:M.output_tokens,cost_usd:M.cost_usd},Hu($.dbPath,G,M,_)}catch(F){throw OL({dbPath:$.dbPath,runId:G,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:F instanceof Error?F.message:String(F)},now:_}),iR({dbPath:$.dbPath,runId:G,status:"failed",provider:X.provider,model:X.model,usage:N,metadata:{conflict_id:$.id,mode:"ai",error:F instanceof Error?F.message:String(F)},now:_}),F}return iR({dbPath:$.dbPath,runId:G,status:$.fake?"dry_run":"completed",provider:X.provider,model:X.model,usage:N,metadata:{conflict_id:$.id,mode:"ai",fake:$.fake===!0,confidence:L,proposed_strategy:Y.strategy,citation_count:U.citations.length},now:_}),OL({dbPath:$.dbPath,runId:G,level:"info",event:$.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:Y.strategy,confidence:L,patch_kind:Y.kind},now:_}),{...J,mode:"ai",proposed_strategy:Y.strategy,summary:q,proposed_patch:Y,citations:U.citations,confidence:L,agent:{generated:!0,provider:X.provider,model:X.model,run_id:G,read_only_tools:U.read_only_tools,usage:N},warnings:[...J.warnings,...U.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${$.id}`}}import{createHash as Ku,randomUUID as Mu}from"crypto";import{existsSync as Au,readFileSync as bu}from"fs";import{basename as Eu}from"path";function R5($,_){return`${$}_${Ku("sha256").update(_).digest("hex").slice(0,20)}`}function zW($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function s$($){return typeof $==="string"&&$.length>0?$:void 0}function wu($){let _=s$($.source_ref)??s$($.source_uri)??s$($.uri);if(_)return _;let J=s$($.file_id);if(J){let X=s$($.revision_id)??s$($.revision),G=`open-files://file/${encodeURIComponent(J)}`;return X?`${G}/revision/${encodeURIComponent(X)}`:G}let U=s$($.source_id),W=s$($.path);if(U&&W)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(W)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function Iu($,_){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function gu($){return s$($.hash)??s$($.checksum)??s$($.sha256)??null}function ku($,_,J){return s$($.revision_id)??s$($.revision)??s$($.version_id)??(_.kind==="open-files"?_.revision_id:void 0)??J??null}function fu($){return s$($.previous_revision_id)??s$($.previous_revision)??s$($.previous_version_id)??null}function Cu($){return(s$($.event_type)??s$($.event)??s$($.type)??s$($.action)??s$($.change_type)??"changed").toLowerCase()}function Pu($){let _=s$($.path);return s$($.title)??s$($.name)??(_?Eu(_):null)}function Tu($,_){let J=wu($),U=L4(J),W=gu($);return{raw:$,eventType:Cu($),sourceRef:J,sourceUri:Iu(J,U),kind:U.kind,title:Pu($),revision:ku($,U,W),previousRevision:fu($),hash:W,status:s$($.status)?.toLowerCase()??null,updatedAt:s$($.updated_at)??_,acl:$.permissions??$.acl??void 0}}function Su($){let _=$.trim();if(!_)return[];if(_.startsWith("[")){let J=JSON.parse(_);if(!Array.isArray(J))throw Error("Outbox array parse failed.");return J.map((U)=>{let W=zW(U);if(!W)throw Error("Outbox array entries must be objects.");return W})}if(_.startsWith("{"))try{let J=JSON.parse(_),U=zW(J);if(!U)throw Error("Outbox object parse failed.");if(Array.isArray(U.events))return U.events.map((W)=>{let X=zW(W);if(!X)throw Error("Outbox events entries must be objects.");return X});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(J){let U=_.split(/\r?\n/).filter((W)=>W.trim().length>0);if(U.length<=1)throw J;return U.map((W)=>{let X=zW(JSON.parse(W));if(!X)throw Error("Outbox JSONL entries must be objects.");return X})}return _.split(/\r?\n/).filter((J)=>J.trim().length>0).map((J)=>{let U=zW(JSON.parse(J));if(!U)throw Error("Outbox JSONL entries must be objects.");return U})}async function Zu($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 outbox URI: ${$}`);if(J)K1($,J);let[{S3Client:G,GetObjectCommand:Q},{fromIni:Y}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Y({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Q({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function vu($,_,J){if($.startsWith("s3://"))return Zu($,_,J);if(!Au($))throw Error(`Outbox not found: ${$}`);return bu($,"utf8")}function oR($,_){let J={};if($)try{J=zW(JSON.parse($))??{}}catch{J={}}return JSON.stringify({...J,..._})}function yu($,_,J){let U=R5("src",_.sourceUri);$.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) +`)}function du($){let _=typeof $==="number"&&Number.isFinite($)?$:0.5;return Math.max(0,Math.min(1,_))}function nu($,_){let J=$.kind==="choose_local"||$.kind==="choose_remote"||$.kind==="no_op"||$.kind==="custom"||$.kind==="manual_merge"?$.kind:"manual_merge";return{kind:J,target:typeof $.target==="string"&&$.target?$.target:_,strategy:typeof $.strategy==="string"&&$.strategy?$.strategy:J.replace("_","-"),summary:typeof $.summary==="string"&&$.summary?$.summary:"Review both sides before applying a merge.",diff:typeof $.diff==="string"&&$.diff?$.diff:null,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:{}}}function cu($){let _=`${$.conflict.entity_kind}:${$.conflict.entity_id}`,J=Boolean($.local_row&&$.remote_row);return{kind:J?"manual_merge":"custom",target:_,strategy:J?"manual-merge":"review-and-select",summary:J?`Fake AI proposal: compare local and remote ${_} row snapshots, then apply a reviewed manual merge.`:`Fake AI proposal: inspect ${_} with available conflict metadata before selecting a side.`,diff:J?[`--- ${_} local`,`+++ ${_} remote`,"@@ review-required @@",JSON.stringify({local:$.local_row,remote:$.remote_row},null,2).slice(0,1200)].join(` +`):null,metadata:{fake:!0,local_hash:$.conflict.local_hash,remote_hash:$.conflict.remote_hash,source_refs:$.source_refs}}}async function XF($){let _=($.now??new Date).toISOString();a($.dbPath);let J=CU($.dbPath,$.id),U=GR($.dbPath,$.id),W=y6($.modelRef??"default",$.config),X=w_(W),G=`run_${UF()}`,Y=uu({deterministic:J,evidence:U});mu({dbPath:$.dbPath,runId:G,prompt:Y,provider:X.provider,model:X.model,status:$.fake?"dry_run":"running",metadata:{conflict_id:$.id,mode:"ai",fake:$.fake===!0,read_only_tools:U.read_only_tools.map((R)=>R.name)},now:_}),RL({dbPath:$.dbPath,runId:G,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:U.citations.length,source_refs:U.source_refs.length,read_only_tools:U.read_only_tools},now:_});let Q,q,L=0.5,N={input_tokens:VL(Y),output_tokens:0,cost_usd:0};if($.fake)Q=cu(U),q=Q.summary,N.output_tokens=VL(q)+VL(Q.diff??"");else try{let{generateObject:R}=await import("ai"),{z:B}=await Promise.resolve().then(() => (JF(),_F)),H=await EU(W,{config:$.config,env:$.env}),V=B.object({summary:B.string(),confidence:B.number().min(0).max(1),proposed_patch:B.object({kind:B.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:B.string(),strategy:B.string(),summary:B.string(),diff:B.string().nullable(),metadata:B.record(B.string(),B.unknown()).default({})})}),K=await R({model:H,schema:V,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:Y});q=K.object.summary,L=du(K.object.confidence),Q=nu(K.object.proposed_patch,`${U.conflict.entity_kind}:${U.conflict.entity_id}`);let E=g1({provider:X.provider,model:X.model,usage:K.usage,providerMetadata:K.providerMetadata});N={input_tokens:E.input_tokens,output_tokens:E.output_tokens,cost_usd:E.cost_usd},xu($.dbPath,G,E,_)}catch(R){throw RL({dbPath:$.dbPath,runId:G,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:R instanceof Error?R.message:String(R)},now:_}),WF({dbPath:$.dbPath,runId:G,status:"failed",provider:X.provider,model:X.model,usage:N,metadata:{conflict_id:$.id,mode:"ai",error:R instanceof Error?R.message:String(R)},now:_}),R}return WF({dbPath:$.dbPath,runId:G,status:$.fake?"dry_run":"completed",provider:X.provider,model:X.model,usage:N,metadata:{conflict_id:$.id,mode:"ai",fake:$.fake===!0,confidence:L,proposed_strategy:Q.strategy,citation_count:U.citations.length},now:_}),RL({dbPath:$.dbPath,runId:G,level:"info",event:$.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:Q.strategy,confidence:L,patch_kind:Q.kind},now:_}),{...J,mode:"ai",proposed_strategy:Q.strategy,summary:q,proposed_patch:Q,citations:U.citations,confidence:L,agent:{generated:!0,provider:X.provider,model:X.model,run_id:G,read_only_tools:U.read_only_tools,usage:N},warnings:[...J.warnings,...U.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${$.id}`}}import{createHash as iu,randomUUID as lu}from"crypto";import{existsSync as ru,readFileSync as pu}from"fs";import{basename as ou}from"path";function bG($,_){return`${$}_${iu("sha256").update(_).digest("hex").slice(0,20)}`}function BW($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function s$($){return typeof $==="string"&&$.length>0?$:void 0}function tu($){let _=s$($.source_ref)??s$($.source_uri)??s$($.uri);if(_)return _;let J=s$($.file_id);if(J){let X=s$($.revision_id)??s$($.revision),G=`open-files://file/${encodeURIComponent(J)}`;return X?`${G}/revision/${encodeURIComponent(X)}`:G}let U=s$($.source_id),W=s$($.path);if(U&&W)return`open-files://source/${encodeURIComponent(U)}/path/${encodeURIComponent(W)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function au($,_){if(_.kind==="open-files"&&_.entity==="file"&&_.revision_id)return $.replace(/\/revision\/[^/]+$/,"");return $}function su($){return s$($.hash)??s$($.checksum)??s$($.sha256)??null}function eu($,_,J){return s$($.revision_id)??s$($.revision)??s$($.version_id)??(_.kind==="open-files"?_.revision_id:void 0)??J??null}function $d($){return s$($.previous_revision_id)??s$($.previous_revision)??s$($.previous_version_id)??null}function _d($){return(s$($.event_type)??s$($.event)??s$($.type)??s$($.action)??s$($.change_type)??"changed").toLowerCase()}function Jd($){let _=s$($.path);return s$($.title)??s$($.name)??(_?ou(_):null)}function Wd($,_){let J=tu($),U=B6(J),W=su($);return{raw:$,eventType:_d($),sourceRef:J,sourceUri:au(J,U),kind:U.kind,title:Jd($),revision:eu($,U,W),previousRevision:$d($),hash:W,status:s$($.status)?.toLowerCase()??null,updatedAt:s$($.updated_at)??_,acl:$.permissions??$.acl??void 0}}function Ud($){let _=$.trim();if(!_)return[];if(_.startsWith("[")){let J=JSON.parse(_);if(!Array.isArray(J))throw Error("Outbox array parse failed.");return J.map((U)=>{let W=BW(U);if(!W)throw Error("Outbox array entries must be objects.");return W})}if(_.startsWith("{"))try{let J=JSON.parse(_),U=BW(J);if(!U)throw Error("Outbox object parse failed.");if(Array.isArray(U.events))return U.events.map((W)=>{let X=BW(W);if(!X)throw Error("Outbox events entries must be objects.");return X});if("source_ref"in U||"source_uri"in U||"file_id"in U)return[U]}catch(J){let U=_.split(/\r?\n/).filter((W)=>W.trim().length>0);if(U.length<=1)throw J;return U.map((W)=>{let X=BW(JSON.parse(W));if(!X)throw Error("Outbox JSONL entries must be objects.");return X})}return _.split(/\r?\n/).filter((J)=>J.trim().length>0).map((J)=>{let U=BW(JSON.parse(J));if(!U)throw Error("Outbox JSONL entries must be objects.");return U})}async function Xd($,_,J){let U=new URL($),W=U.hostname,X=decodeURIComponent(U.pathname.replace(/^\/+/,""));if(!W||!X)throw Error(`Invalid S3 outbox URI: ${$}`);if(J)M0($,J);let[{S3Client:G,GetObjectCommand:Y},{fromIni:Q}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),q=_?.storage.type==="s3"&&_.storage.s3?.bucket===W?_.storage.s3:void 0,N=await new G({region:q?.region,credentials:q?.profile?Q({profile:q.profile}):void 0,maxAttempts:q?.max_attempts}).send(new Y({Bucket:W,Key:X}));if(!N.Body)return"";return await N.Body.transformToString()}async function Gd($,_,J){if($.startsWith("s3://"))return Xd($,_,J);if(!ru($))throw Error(`Outbox not found: ${$}`);return pu($,"utf8")}function GF($,_){let J={};if($)try{J=BW(JSON.parse($))??{}}catch{J={}}return JSON.stringify({...J,..._})}function Yd($,_,J){let U=bG("src",_.sourceUri);$.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(uri) DO UPDATE SET kind = excluded.kind, title = COALESCE(excluded.title, sources.title), - updated_at = excluded.updated_at`,[U,_.sourceUri,_.kind,_.title,JSON.stringify({source_ref:_.sourceRef,source_uri:_.sourceUri,status:_.status,last_outbox_event:_.eventType}),JSON.stringify(_.acl??{}),J,_.updatedAt]);let W=$.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get(_.sourceUri);if(!W)throw Error(`Failed to upsert source for outbox event: ${_.sourceUri}`);let X={source_ref:_.sourceRef,source_uri:_.sourceUri,last_outbox_event:_.eventType,last_outbox_at:_.updatedAt};if(_.status)X.status=_.status;if(s$(_.raw.path))X.path=_.raw.path;return $.run("UPDATE sources SET metadata_json = ?, acl_json = CASE WHEN ? IS NULL THEN acl_json ELSE ? END, updated_at = ? WHERE id = ?",[oR(W.metadata_json,X),_.acl===void 0?null:JSON.stringify(_.acl),_.acl===void 0?null:JSON.stringify(_.acl),_.updatedAt,W.id]),W.id}function hu($,_,J,U){if(!J.revision)return null;let W=R5("rev",`${_}\x00${J.revision}`),X={source_ref:J.sourceRef,source_uri:J.sourceUri,status:J.status,last_outbox_event:J.eventType,reindex_required:!0};return $.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) + updated_at = excluded.updated_at`,[U,_.sourceUri,_.kind,_.title,JSON.stringify({source_ref:_.sourceRef,source_uri:_.sourceUri,status:_.status,last_outbox_event:_.eventType}),JSON.stringify(_.acl??{}),J,_.updatedAt]);let W=$.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get(_.sourceUri);if(!W)throw Error(`Failed to upsert source for outbox event: ${_.sourceUri}`);let X={source_ref:_.sourceRef,source_uri:_.sourceUri,last_outbox_event:_.eventType,last_outbox_at:_.updatedAt};if(_.status)X.status=_.status;if(s$(_.raw.path))X.path=_.raw.path;return $.run("UPDATE sources SET metadata_json = ?, acl_json = CASE WHEN ? IS NULL THEN acl_json ELSE ? END, updated_at = ? WHERE id = ?",[GF(W.metadata_json,X),_.acl===void 0?null:JSON.stringify(_.acl),_.acl===void 0?null:JSON.stringify(_.acl),_.updatedAt,W.id]),W.id}function Qd($,_,J,U){if(!J.revision)return null;let W=bG("rev",`${_}\x00${J.revision}`),X={source_ref:J.sourceRef,source_uri:J.sourceUri,status:J.status,last_outbox_event:J.eventType,reindex_required:!0};return $.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(source_id, revision) DO UPDATE SET hash = COALESCE(excluded.hash, source_revisions.hash), - metadata_json = excluded.metadata_json`,[W,_,J.revision,J.hash,s$(J.raw.extracted_text_ref)??null,JSON.stringify(X),U]),$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(_,J.revision)?.id??null}function mu($,_,J){if(J.previousRevision){let U=$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(_,J.previousRevision).map((W)=>W.id);if(U.length>0)return U}if(J.revision)return $.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(_,J.revision).map((U)=>U.id);if(J.hash)return $.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all(_,J.hash).map((U)=>U.id);return $.query("SELECT id FROM source_revisions WHERE source_id = ?").all(_).map((U)=>U.id)}function xu($,_){let J=$.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(_),U=0,W=0;for(let G of J){let Q=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(G.id);U+=Q?.n??0;let Y=$.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(G.id);W+=Y?.n??0,$.run("DELETE FROM vector_index_entries WHERE chunk_id = ?",[G.id]),$.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?",[G.id]),$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[G.id])}$.run("DELETE FROM chunks WHERE source_revision_id = ?",[_]);let X=$.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get(_);return $.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?",[oR(X?.metadata_json,{reindex_required:!0,invalidated_at:new Date().toISOString()}),_]),{chunksDeleted:J.length,embeddingsDeleted:U,vectorEntriesDeleted:W}}function uu($,_){return _==="deleted"||["delete","deleted","remove","removed"].includes($)}function du($){return["move","moved","rename","renamed","path_changed","canonical_key_changed"].includes($)}function cu($){return["permission","permissions","permission_changed","acl_changed","acl_revoked"].includes($)}async function tR($){let _=($.now??new Date).toISOString();if($.safetyPolicy)x0($.dbPath,$.safetyPolicy);G$($.dbPath);let J=await vu($.input,$.config,$.safetyPolicy),U=Su(J),W=i($.dbPath),X=`run_${Mu()}`;try{return W.transaction(()=>{W.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[X,"open-files-outbox",$.input,"completed","local","open-files-outbox",JSON.stringify({path:$.input,events:U.length}),_,_]);let G=new Set,Q=new Set,Y=0,q=0,L=0,N=0,F=0,B=0,H=0;return O6(W,{event_type:"source_read",action:$.input.startsWith("s3://")?"s3_outbox_read":"local_outbox_read",target_uri:$.input,decision:"allow",metadata:{events:U.length,read_only:!0},created_at:_}),U.forEach((V,R)=>{let M=Tu(V,_),K=yu(W,M,_);G.add(K);let w=hu(W,K,M,_);if(w)Q.add(w);let b=mu(W,K,M);for(let I of b){Q.add(I);let v=xu(W,I);Y+=v.chunksDeleted,q+=v.embeddingsDeleted,L+=v.vectorEntriesDeleted,N+=1}if(uu(M.eventType,M.status))F+=1;if(du(M.eventType))B+=1;if(cu(M.eventType)||M.acl!==void 0)H+=1;W.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[R5("evt",`${X}\x00${R}\x00${M.sourceRef}\x00${M.eventType}`),X,"info",M.eventType,JSON.stringify({source_ref:M.sourceRef,source_uri:M.sourceUri,revision:M.revision,hash:M.hash,status:M.status,affected_revisions:b.length}),M.updatedAt])}),W.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[R5("usage",X),X,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),_]),O6(W,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:$.dbPath,decision:"allow",metadata:{run_id:X,events:U.length,sources:G.size,revisions:Q.size,chunks_deleted:Y,embeddings_deleted:q,vector_entries_deleted:L},created_at:_}),{path:$.input,db_path:$.dbPath,run_id:X,events_seen:U.length,sources_touched:G.size,revisions_touched:Q.size,chunks_deleted:Y,embeddings_deleted:q,vector_entries_deleted:L,stale_revisions:N,deleted_sources:F,moved_sources:B,permission_updates:H}})()}finally{W.close()}}import{spawnSync as eR}from"child_process";import{hostname as U_,platform as $K,userInfo as lu}from"os";var nu=1,iu="@hasna/machines",ru="@hasna/machines/consumer";function Q$($){return typeof $==="string"&&$.length>0?$:null}function h1($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function Z6($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function w5($){return typeof $==="boolean"?$:null}function pu($){return typeof $==="number"&&Number.isFinite($)?$:null}function I5($=$K()){let _=$.toLowerCase();if(_==="darwin"||_==="macos")return"macos";if(_==="win32"||_==="windows")return"windows";if(_==="linux")return"linux";return $}function vX($){let _=eR("bash",["-c",$],{encoding:"utf8",env:process.env});return{stdout:_.stdout||"",stderr:_.stderr||"",exitCode:_.status??1}}async function jW($,_){return await $(_)}async function yX($,_){return(await jW(_,`command -v ${$} >/dev/null 2>&1`)).exitCode===0}function ou($){try{let _=JSON.parse($);if(!_||typeof _!=="object")return null;return _}catch{return null}}function aR($){if(!$)return null;return $.HostName??$.DNSName?.split(".")[0]??null}async function tu($,_){let J=new Map;if(!await yX("tailscale",$))return _.push("tailscale_not_available"),{peers:J,selfKey:null};let U=await jW($,"tailscale status --json");if(U.exitCode!==0)return _.push(`tailscale_status_failed:${U.stderr.trim()||U.exitCode}`),{peers:J,selfKey:null};let W=ou(U.stdout);if(!W)return _.push("tailscale_status_invalid_json"),{peers:J,selfKey:null};let X=(G)=>{let Q=aR(G);if(Q&&G)J.set(Q,G)};X(W.Self);for(let G of Object.values(W.Peer??{}))X(G);return{peers:J,selfKey:aR(W.Self)}}function au($){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??$??U_()}function su($){let _=$.machineId===$.localMachineId||$.machineId===U_(),J=$.peer?.DNSName?.replace(/\.$/,"")??null,U=J??$.peer?.TailscaleIPs?.[0]??null,W=[];if(_)W.push({kind:"local",target:"localhost",reachable:!0});if(U)W.push({kind:"tailscale",target:U,reachable:$.peer?.Online??null});let X=W.find((G)=>G.kind==="local")??W.find((G)=>G.kind==="tailscale")??null;return{machine_id:$.machineId,hostname:$.peer?.HostName??(_?U_():$.machineId),local:_,platform:$.peer?.OS?I5($.peer.OS):_?I5():null,os:$.peer?.OS??(_?$K():null),user:_?lu().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:J,ips:$.peer?.TailscaleIPs??[],online:$.peer?.Online??null,active:$.peer?.Active??null,last_seen:$.peer?.LastSeen??null},ssh:{address:null,route:X?.kind==="local"?"local":X?.kind==="tailscale"?"tailscale":"unknown",command_target:X?.target??null},route_hints:W,tags:[],metadata:{},source:"local"}}function eu($){if(!Array.isArray($))return[];return $.map((_)=>{let J=Z6(_),U=Q$(J.kind)??"unknown";return{kind:U==="local"||U==="lan"||U==="tailscale"||U==="ssh"?U:"unknown",target:Q$(J.target)??"",reachable:w5(J.reachable)}}).filter((_)=>_.target.length>0)}function $d($,_){let J=Q$($.machine_id)??Q$($.hostname)??"unknown",U=Z6($.tailscale),W=Z6($.ssh),X=Q$($.heartbeat_status),G=Q$(W.route);return{machine_id:J,hostname:Q$($.hostname),local:J===_,platform:Q$($.platform),os:Q$($.os),user:Q$($.user),workspace_path:Q$($.workspace_path),manifest_declared:$.manifest_declared===!0,heartbeat_status:X==="online"||X==="offline"?X:"unknown",last_heartbeat_at:Q$($.last_heartbeat_at),tailscale:{dns_name:Q$(U.dns_name),ips:h1(U.ips),online:w5(U.online),active:w5(U.active),last_seen:Q$(U.last_seen)},ssh:{address:Q$(W.address),route:G==="local"||G==="lan"||G==="tailscale"?G:"unknown",command_target:Q$(W.command_target)},route_hints:eu($.route_hints),tags:h1($.tags),metadata:Z6($.metadata),source:"open-machines"}}function _d($,_){return`${_} machine${_===1?"":"s"} discovered via ${$}`}function Q4($){let _=$ instanceof Error?$.message:String($);return _.includes("Cannot find module '@hasna/machines'")||_.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":_}function hX($){return $.adapterMode??"auto"}function _K($){let _=$?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof _==="number")return _;let J=$?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof J==="number"?J:null}function g5($){return typeof $.schema_version==="number"?$.schema_version:null}function mX($){return typeof $==="number"&&$>nu?$:null}function k5($){return{package:iu,entrypoint:ru,mode:$.mode,implementation:$.implementation,contract_version:$.contractVersion??null,available:$.available,error:$.error??null}}function u$($,_="adapter_disabled"){return k5({mode:$,implementation:"disabled",available:!1,error:_})}function f5($,_){let J=mX(_K(_));if(!J)return null;return k5({mode:$,implementation:"disabled",available:!1,error:`unsupported_contract_version:${J}`,contractVersion:J})}function C5($){return k5({mode:$,implementation:"cli",available:!0})}function P5($,_){return k5({mode:$,implementation:"sdk",available:!0,contractVersion:_K(_)})}function T5($){try{return JSON.parse($)}catch{return null}}function X_($){return`'${$.replace(/'/g,"'\\''")}'`}function S5($){return["machines",...$].map(X_).join(" ")}function Z5($){return $==="local"||$==="localhost"||$===U_()||$===process.env.HASNA_MACHINE_ID||$===process.env.OPEN_MACHINES_MACHINE_ID||$===process.env.MACHINE_ID}function Jd($,_){let J=Z5($),U=J?_:`ssh ${X_($)} ${X_(_)}`,W=eR("bash",["-c",U],{encoding:"utf8",env:process.env});return{stdout:W.stdout||"",stderr:W.stderr||"",exitCode:W.status??1,source:J?"local":"ssh"}}async function JK($,_,J){return await $(_,J)}function J_($,_){if(_)return"ok";return $===!1?"warn":"fail"}function W_($){return $.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function Wd($){if($==="@hasna/knowledge")return"knowledge";if($==="@hasna/machines")return"machines";return $.split("/").pop()??$}function Ud($){return $.trim().split(/\r?\n/).find(Boolean)??""}function WK($){return $.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function UK($){let _={};for(let J of $.split(/\r?\n/)){let U=J.indexOf("=");if(U<=0)continue;_[J.slice(0,U)]=J.slice(U+1)}return _}function t0($){return{id:$.id,kind:$.kind,status:$.status,target:$.target,expected:$.expected??null,actual:$.actual??null,detail:$.detail,source:$.source}}async function XK($,_,J){let U=[`cmd=${X_(_.command)}`,'path="$(command -v "$cmd" 2>/dev/null || true)"','printf "path=%s\\n" "$path"',`if [ -n "$path" ]; then version="$("$cmd" ${_.versionArgs??"--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi`].join("; "),W=await JK(J,$,U),X=UK(W.stdout);return{path:X.path||null,version:X.version?Ud(X.version):null,stderr:W.stderr,source:W.source??(Z5($)?"local":"ssh")}}function sR($){let _=$==="name"?String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`:String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`;return[`if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${$} ?? '')" "$pkg" 2>/dev/null`,`elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${$} || '')" "$pkg" 2>/dev/null`,`else sed -n '${_}' "$pkg" | head -n 1`,"fi"].join("; ")}async function Xd($,_,J){let U=[`path=${X_(_.path)}`,'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"','pkg="$path/package.json"','printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"',`if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${sR("name")})"; printf "version=%s\\n" "$(${sR("version")})"; fi`].join("; "),W=await JK(J,$,U),X=UK(W.stdout);return{exists:X.exists==="yes",packageJson:X.package_json==="yes",packageName:X.package_name||null,version:X.version||null,stderr:W.stderr,source:W.source??(Z5($)?"local":"ssh")}}async function Gd($,_,J){let U=await XK($,_,J),W=Boolean(U.path),X=[t0({id:`command:${W_(_.command)}:path`,kind:"command",status:J_(_.required,W),target:_.command,expected:"available",actual:U.path??"missing",detail:W?`found at ${U.path}`:U.stderr||"command missing",source:U.source})];if(_.expectedVersion){let G=WK(U.version??"");X.push(t0({id:`command:${W_(_.command)}:version`,kind:"command",status:G===_.expectedVersion?"ok":J_(_.required,!1),target:_.command,expected:_.expectedVersion,actual:G??U.version??"missing",detail:G?`version output: ${U.version}`:"version unavailable",source:U.source}))}return X}async function Qd($,_,J){let U=_.command??Wd(_.name),W=await XK($,{command:U,expectedVersion:_.expectedVersion,required:_.required},J),X=Boolean(W.path),G=[t0({id:`package:${W_(_.name)}:command`,kind:"package",status:J_(_.required,X),target:_.name,expected:U,actual:W.path??"missing",detail:X?`${U} found at ${W.path}`:`${U} command missing`,source:W.source})];if(_.expectedVersion){let Q=WK(W.version??"");G.push(t0({id:`package:${W_(_.name)}:version`,kind:"package",status:Q===_.expectedVersion?"ok":J_(_.required,!1),target:_.name,expected:_.expectedVersion,actual:Q??W.version??"missing",detail:Q?`version output: ${W.version}`:"version unavailable",source:W.source}))}return G}async function Yd($,_,J){let U=await Xd($,_,J),W=_.label??_.path,X=[t0({id:`workspace:${W_(W)}:path`,kind:"workspace",status:J_(_.required,U.exists),target:W,expected:_.path,actual:U.exists?"exists":"missing",detail:U.exists?`workspace exists at ${_.path}`:U.stderr||`workspace missing at ${_.path}`,source:U.source})];if(_.expectedPackageName)X.push(t0({id:`workspace:${W_(W)}:package-name`,kind:"workspace",status:U.packageName===_.expectedPackageName?"ok":J_(_.required,!1),target:W,expected:_.expectedPackageName,actual:U.packageName??(U.packageJson?"missing-name":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));if(_.expectedVersion)X.push(t0({id:`workspace:${W_(W)}:version`,kind:"workspace",status:U.version===_.expectedVersion?"ok":J_(_.required,!1),target:W,expected:_.expectedVersion,actual:U.version??(U.packageJson?"missing-version":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));return X}function GK($,_){return{...$,knowledge:{scope:_.knowledge?.scope??"global",app_path:F0,workspace_home:_.knowledge?.workspace_home??null},message:_d($.source,$.machines.length)}}async function v5(){try{return await import("@hasna/machines/consumer")}catch($){if(Q4($)!=="module_not_found")throw $;return await import("@hasna/machines")}}function QK($,_,J){let U=Z6($);if(mX(g5(U)))return null;let W=Array.isArray(U.machines)?U.machines:null,X=Q$(U.local_machine_id);if(!W||!X)return null;let G={ok:!0,source:"open-machines",generated_at:Q$(U.generated_at)??(_.now??new Date).toISOString(),local_machine_id:X,local_hostname:Q$(U.local_hostname)??U_(),current_platform:Q$(U.current_platform)??I5(),machines:W.map((Q)=>$d(Q,X)),warnings:h1(U.warnings),adapter:J};return GK(G,_)}function K5($){return $==="local"||$==="lan"||$==="tailscale"||$==="ssh"||$==="unknown"?$:null}function YK($){let _=Z6($),J=Q$(_.observed_at),U=Q$(_.source_authority);if(!J||!U)return null;return{observed_at:J,verified_at:Q$(_.verified_at),expires_at:Q$(_.expires_at),ttl_ms:pu(_.ttl_ms),source_authority:U,confidence:Q$(_.confidence),cacheable:_.cacheable===!0,stale:_.stale===!0,reasons:h1(_.reasons)}}function qK($,_){let J=Z6($);if(mX(g5(J)))return null;let U=Q$(J.target)??Q$(J.command_target);if(J.ok!==!0||!U)return null;let W=typeof J.evidence==="object"&&J.evidence!==null?J.evidence:null,X=typeof W?.selected_hint==="object"&&W.selected_hint!==null?W.selected_hint:null;return{target:U,route:K5(J.route),targetKind:K5(X?.kind)??K5(J.source)??K5(J.route),confidence:Q$(J.confidence),source:"open-machines",adapter:_,evidence:W,cacheability:YK(J.cacheability),warnings:h1(J.warnings)}}function DL($){let _=Z6($);return{path:Q$(_.path),source:Q$(_.source)??"unresolved"}}function qd($){if(!Array.isArray($))return[];return $.flatMap((_)=>{let J=Z6(_),U=Q$(J.id),W=Q$(J.status),X=Q$(J.severity),G=Q$(J.message);if(!U||!W||!X||!G)return[];return[{id:U,status:W,severity:X,message:G,path:Q$(J.path),source:Q$(J.source)??"unknown",path_exists:w5(J.path_exists)}]})}function zd($){if(!Array.isArray($))return[];return $.flatMap((_)=>{let J=Z6(_),U=Q$(J.id),W=Q$(J.reason),X=h1(J.command),G=Q$(J.shell_command),Q=h1(J.apply_command),Y=Q$(J.apply_shell_command);if(!U||!W||!X.length||!G||!Q.length||!Y)return[];return[{id:U,reason:W,command:X,shell_command:G,apply_command:Q,apply_shell_command:Y}]})}function jd($){if(!($.projectRootSource==="inferred"||$.openFilesRootSource==="inferred"||$.trustStatus==="untrusted"||$.authStatus==="unknown"||$.warnings.some((W)=>W.includes("inferred")||W.includes("untrusted")||W.includes("unknown_auth")||W.includes("missing"))))return[];let J=["machines","workspace","repair","--machine",$.requestedMachineId,"--project",$.projectId,"--repo",$.repoName,"--open-files-repo",$.openFilesRepoName??"open-files","--json"],U=[...J,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:J,shell_command:J.map(X_).join(" "),apply_command:U,apply_shell_command:U.map(X_).join(" ")}]}function zK($,_,J){let U=Z6($);if(mX(g5(U)))return null;let W=Z6(U.paths),X=Z6(U.project),G=Z6(U.machine),Q=DL(W.project_root),Y=DL(W.workspace_root),q=DL(W.open_files_root);if(U.ok!==!0||!Q.path)return null;let L=typeof U.evidence==="object"&&U.evidence!==null?U.evidence:null,N=Q$(U.requested_machine_id)??_.machineId,F=Q$(X.project_id)??_.projectId??"open-knowledge",B=Q$(X.repo_name)??_.repoName??_.projectId??"open-knowledge",H=Q$(G.trust_status)??"unknown",V=Q$(G.auth_status)??"unknown",R=h1(U.warnings),M=qd(U.diagnostics),K=zd(U.repair_hints);return{ok:!0,source:"open-machines",adapter:J,requested_machine_id:N,machine_id:Q$(U.machine_id),project_id:F,repo_name:B,project_root:Q.path,project_root_source:Q.source,workspace_root:Y.path,workspace_root_source:Y.source,open_files_root:q.path,open_files_root_source:q.source,trust_status:H,auth_status:V,current:G.current===!0,primary:G.primary===!0,diagnostics:M,repair_hints:K.length?K:jd({requestedMachineId:N,projectId:F,repoName:B,openFilesRepoName:_.openFilesRepoName,warnings:R,projectRootSource:Q.source,openFilesRootSource:q.source,trustStatus:H,authStatus:V}),evidence:L,cacheability:YK(U.cacheability),warnings:R}}async function M5($,_){let J=$.runner??vX;if(!await yX("machines",J))return null;let U=["topology","--json"];if($.includeTailscale===!1)U.push("--no-tailscale");let W=await jW(J,S5(U));if(W.exitCode!==0)return null;return QK(T5(W.stdout),$,_)}async function i0($,_){let J=[];if(_.error)J.push(`open_machines_unavailable:${_.error}`);let U=$.runner??vX,W=$.includeTailscale===!1?{peers:new Map,selfKey:null}:await tu(U,J),X=au(W.selfKey),Q=[...new Set([X,...W.peers.keys()])].sort().map((Y)=>su({machineId:Y,localMachineId:X,peer:W.peers.get(Y)}));return GK({ok:!0,source:"local",generated_at:($.now??new Date).toISOString(),local_machine_id:X,local_hostname:U_(),current_platform:I5(),machines:Q,warnings:J,adapter:_},$)}async function jK($={}){let _=hX($);if(_==="disabled")return await i0($,u$(_));let J=C5(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??v5)(),X=f5(_,W);if(X)return await i0($,X);let G=P5(_,W);if(W?.discoverMachineTopology){let Q=W.discoverMachineTopology({includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),Y=QK(Q,$,G);if(Y)return Y;if(_==="sdk")return await i0($,u$(_,"invalid_topology_shape"));return await M5($,J)??await i0($,u$(_,"invalid_topology_shape"))}if(_==="sdk")return await i0($,u$(_,"missing_discoverMachineTopology"));return await M5($,J)??await i0($,u$(_,"missing_discoverMachineTopology"))}return await M5($,J)??await i0($,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return await i0($,u$(_,Q4(U)));return await M5($,J)??await i0($,u$(_,Q4(U)))}}async function A5($,_){let J=$.runner??vX;if(!await yX("machines",J))return null;let U=["route","--machine",$.machineId,"--json"];if($.includeTailscale===!1)U.push("--no-tailscale");let W=await jW(J,S5(U));if(W.exitCode!==0)return null;return qK(T5(W.stdout),_)}function r0($,_){return{target:$,route:null,targetKind:null,confidence:null,source:"raw",adapter:_,evidence:null,cacheability:null,warnings:[]}}async function LL($){let _=hX($);if(_==="disabled")return r0($.machineId,u$(_));let J=C5(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??v5)(),X=f5(_,W);if(X)return r0($.machineId,X);let G=P5(_,W);if(W?.resolveMachineRoute){let Q=qK(W.resolveMachineRoute($.machineId,{includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),G);if(Q)return Q;if(_==="sdk")return r0($.machineId,u$(_,"invalid_route_shape"));return await A5($,J)??r0($.machineId,u$(_,"invalid_route_shape"))}if(_==="sdk")return r0($.machineId,u$(_,"missing_resolveMachineRoute"));return await A5($,J)??r0($.machineId,u$(_,"missing_resolveMachineRoute"))}return await A5($,J)??r0($.machineId,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return{...r0($.machineId,u$(_,Q4(U))),warnings:[Q4(U)]};return await A5($,J)??{...r0($.machineId,u$(_,Q4(U))),warnings:[Q4(U)]}}}async function b5($,_){let J=$.runner??vX;if(!await yX("machines",J))return null;let U=$.projectId??"open-knowledge",W=$.repoName??"open-knowledge",X=["workspace","resolve","--machine",$.machineId,"--project",U,"--repo",W,"--open-files-repo",$.openFilesRepoName??"open-files","--json"];if($.includeTailscale===!1)X.push("--no-tailscale");let G=await jW(J,S5(X));if(G.exitCode!==0)return null;return zK(T5(G.stdout),$,_)}function Od($){let _=$.peerWorkspace?.trim();if(!_)return null;return{ok:!0,source:"argument",adapter:u$(hX($),"argument_override"),requested_machine_id:$.machineId,machine_id:$.machineId,project_id:$.projectId??"open-knowledge",repo_name:$.repoName??"open-knowledge",project_root:_,project_root_source:"argument",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:[]}}function p0($,_,J){return{ok:!1,source:"raw",adapter:J,requested_machine_id:$.machineId,machine_id:null,project_id:$.projectId??"open-knowledge",repo_name:$.repoName??"open-knowledge",project_root:null,project_root_source:"unresolved",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:_}}async function y5($){let _=Od($);if(_)return _;let J=hX($);if(J==="disabled")return p0($,["adapter_disabled"],u$(J));let U=C5(J);try{if(J!=="cli"){let X=await($.loadOpenMachines??v5)(),G=f5(J,X);if(G)return p0($,[`unsupported_contract_version:${G.contract_version}`],G);let Q=P5(J,X);if(X?.resolveMachineWorkspace){let Y=zK(X.resolveMachineWorkspace({machineId:$.machineId,projectId:$.projectId??"open-knowledge",repoName:$.repoName??"open-knowledge",openFilesRepoName:$.openFilesRepoName??"open-files",includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),$,Q);if(Y)return Y;if(J==="sdk")return p0($,["invalid_workspace_shape"],u$(J,"invalid_workspace_shape"));return await b5($,U)??p0($,["invalid_workspace_shape"],u$(J,"invalid_workspace_shape"))}if(J==="sdk")return p0($,["missing_resolveMachineWorkspace"],u$(J,"missing_resolveMachineWorkspace"));return await b5($,U)??p0($,["missing_resolveMachineWorkspace"],u$(J,"missing_resolveMachineWorkspace"))}return await b5($,U)??p0($,["machines_cli_unavailable"],u$(J,"machines_cli_unavailable"))}catch(W){if(J==="sdk")return p0($,[Q4(W)],u$(J,Q4(W)));return await b5($,U)??p0($,[Q4(W)],u$(J,Q4(W)))}}function OK($,_){return{...$,knowledge:{scope:_.knowledge?.scope??"global",app_path:F0,workspace_home:_.knowledge?.workspace_home??null},message:$.ok?`Machine ${$.machine_id} passed knowledge preflight`:`Machine ${$.machine_id} failed knowledge preflight: ${$.summary.fail} failing check(s)`}}function DK($,_,J){let U=Z6($);if(mX(g5(U)))return null;let W=Array.isArray(U.checks)?U.checks:null,X=Q$(U.machine_id)??Q$(U.machineId);if(!W||!X)return null;let G=W.map((Y)=>{let q=Z6(Y),L=Q$(q.status),N=Q$(q.kind),F=Q$(q.source);return t0({id:Q$(q.id)??"unknown",kind:N==="command"||N==="package"||N==="workspace"?N:"command",status:L==="ok"||L==="warn"||L==="fail"?L:"fail",target:Q$(q.target)??"unknown",expected:Q$(q.expected),actual:Q$(q.actual),detail:Q$(q.detail)??"",source:F==="local"||F==="ssh"||F==="open-machines"?F:"open-machines"})}),Q={ok:G.filter((Y)=>Y.status==="ok").length,warn:G.filter((Y)=>Y.status==="warn").length,fail:G.filter((Y)=>Y.status==="fail").length};return OK({ok:Q.fail===0,source:"open-machines",machine_id:X,generated_at:Q$(U.generated_at)??(_.now??new Date).toISOString(),checks:G,summary:Q,adapter:J},_)}function Dd($){if(!$.runner)return vX;return async(_)=>{let J=await $.runner?.("local",_);return{stdout:J?.stdout??"",stderr:J?.stderr??"",exitCode:J?.exitCode??1}}}function Ld($){return[$.name,$.command,$.expectedVersion].filter((_)=>Boolean(_)).join(":")}function Bd($){let _=[$.expectedPackageName,$.expectedVersion].filter((U)=>Boolean(U)).join(":"),J=_?`${$.path}:${_}`:$.path;return $.label?`${$.label}=${J}`:J}async function E5($,_){let J=Dd($);if(!await yX("machines",J))return null;let U=["compatibility","--json","--machine",$.machineId??"local"];for(let X of $.commands??[])U.push("--command",X.expectedVersion?`${X.command}:${X.expectedVersion}`:X.command);for(let X of $.packages??[])U.push("--package",Ld(X));for(let X of $.workspaces??[])U.push("--workspace",Bd(X));let W=await jW(J,S5(U));if(W.exitCode!==0)return null;return DK(T5(W.stdout),$,_)}async function o0($,_){let J=$.machineId??U_(),U=$.runner??Jd,W=$.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],X=$.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],G=$.workspaces??[],Q=[];for(let q of W)Q.push(...await Gd(J,q,U));for(let q of X)Q.push(...await Qd(J,q,U));for(let q of G)Q.push(...await Yd(J,q,U));if(_.error)Q.push(t0({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:_.error,detail:"Using knowledge local/ssh compatibility fallback",source:Z5(J)?"local":"ssh"}));let Y={ok:Q.filter((q)=>q.status==="ok").length,warn:Q.filter((q)=>q.status==="warn").length,fail:Q.filter((q)=>q.status==="fail").length};return OK({ok:Y.fail===0,source:"local",machine_id:J,generated_at:($.now??new Date).toISOString(),checks:Q,summary:Y,adapter:_},$)}async function LK($={}){let _=hX($);if(_==="disabled")return await o0($,u$(_));let J=C5(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??v5)(),X=f5(_,W);if(X)return await o0($,X);let G=P5(_,W);if(W?.checkMachineCompatibility){let Q=W.checkMachineCompatibility({machineId:$.machineId,commands:$.commands,packages:$.packages,workspaces:$.workspaces,runner:$.runner,now:$.now}),Y=DK(Q,$,G);if(Y)return Y;if(_==="sdk")return await o0($,u$(_,"invalid_compatibility_shape"));return await E5($,J)??await o0($,u$(_,"invalid_compatibility_shape"))}if(_==="sdk")return await o0($,u$(_,"missing_checkMachineCompatibility"));return await E5($,J)??await o0($,u$(_,"missing_checkMachineCompatibility"))}return await E5($,J)??await o0($,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return await o0($,u$(_,Q4(U)));return await E5($,J)??await o0($,u$(_,Q4(U)))}}import{createHash as Hd,randomUUID as BK}from"crypto";function Nd($,_){return`${$}_${Hd("sha256").update(_).digest("hex").slice(0,20)}`}function Vd($){let _=i($);try{let J=_.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(J.map((U)=>[U.status,U.n]))}finally{_.close()}}function HK($,_){let J=E2(_.modelRef,_.config),U=E6(J),W=i($);try{return W.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri + metadata_json = excluded.metadata_json`,[W,_,J.revision,J.hash,s$(J.raw.extracted_text_ref)??null,JSON.stringify(X),U]),$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get(_,J.revision)?.id??null}function qd($,_,J){if(J.previousRevision){let U=$.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(_,J.previousRevision).map((W)=>W.id);if(U.length>0)return U}if(J.revision)return $.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all(_,J.revision).map((U)=>U.id);if(J.hash)return $.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all(_,J.hash).map((U)=>U.id);return $.query("SELECT id FROM source_revisions WHERE source_id = ?").all(_).map((U)=>U.id)}function zd($,_){let J=$.query("SELECT id FROM chunks WHERE source_revision_id = ?").all(_),U=0,W=0;for(let G of J){let Y=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(G.id);U+=Y?.n??0;let Q=$.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(G.id);W+=Q?.n??0,$.run("DELETE FROM vector_index_entries WHERE chunk_id = ?",[G.id]),$.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?",[G.id]),$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[G.id])}$.run("DELETE FROM chunks WHERE source_revision_id = ?",[_]);let X=$.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get(_);return $.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?",[GF(X?.metadata_json,{reindex_required:!0,invalidated_at:new Date().toISOString()}),_]),{chunksDeleted:J.length,embeddingsDeleted:U,vectorEntriesDeleted:W}}function jd($,_){return _==="deleted"||["delete","deleted","remove","removed"].includes($)}function Dd($){return["move","moved","rename","renamed","path_changed","canonical_key_changed"].includes($)}function Od($){return["permission","permissions","permission_changed","acl_changed","acl_revoked"].includes($)}async function YF($){let _=($.now??new Date).toISOString();if($.safetyPolicy)d4($.dbPath,$.safetyPolicy);a($.dbPath);let J=await Gd($.input,$.config,$.safetyPolicy),U=Ud(J),W=m($.dbPath),X=`run_${lu()}`;try{return W.transaction(()=>{W.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[X,"open-files-outbox",$.input,"completed","local","open-files-outbox",JSON.stringify({path:$.input,events:U.length}),_,_]);let G=new Set,Y=new Set,Q=0,q=0,L=0,N=0,R=0,B=0,H=0;return __(W,{event_type:"source_read",action:$.input.startsWith("s3://")?"s3_outbox_read":"local_outbox_read",target_uri:$.input,decision:"allow",metadata:{events:U.length,read_only:!0},created_at:_}),U.forEach((V,K)=>{let E=Wd(V,_),F=Yd(W,E,_);G.add(F);let w=Qd(W,F,E,_);if(w)Y.add(w);let A=qd(W,F,E);for(let g of A){Y.add(g);let v=zd(W,g);Q+=v.chunksDeleted,q+=v.embeddingsDeleted,L+=v.vectorEntriesDeleted,N+=1}if(jd(E.eventType,E.status))R+=1;if(Dd(E.eventType))B+=1;if(Od(E.eventType)||E.acl!==void 0)H+=1;W.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[bG("evt",`${X}\x00${K}\x00${E.sourceRef}\x00${E.eventType}`),X,"info",E.eventType,JSON.stringify({source_ref:E.sourceRef,source_uri:E.sourceUri,revision:E.revision,hash:E.hash,status:E.status,affected_revisions:A.length}),E.updatedAt])}),W.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[bG("usage",X),X,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),_]),__(W,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:$.dbPath,decision:"allow",metadata:{run_id:X,events:U.length,sources:G.size,revisions:Y.size,chunks_deleted:Q,embeddings_deleted:q,vector_entries_deleted:L},created_at:_}),{path:$.input,db_path:$.dbPath,run_id:X,events_seen:U.length,sources_touched:G.size,revisions_touched:Y.size,chunks_deleted:Q,embeddings_deleted:q,vector_entries_deleted:L,stale_revisions:N,deleted_sources:R,moved_sources:B,permission_updates:H}})()}finally{W.close()}}import{spawnSync as zF}from"child_process";import{hostname as Y2,platform as jF,userInfo as Ld}from"os";var Bd=1,Hd="@hasna/machines",Nd="@hasna/machines/consumer";function Y$($){return typeof $==="string"&&$.length>0?$:null}function x0($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function v_($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function CG($){return typeof $==="boolean"?$:null}function Vd($){return typeof $==="number"&&Number.isFinite($)?$:null}function PG($=jF()){let _=$.toLowerCase();if(_==="darwin"||_==="macos")return"macos";if(_==="win32"||_==="windows")return"windows";if(_==="linux")return"linux";return $}function uX($){let _=zF("bash",["-c",$],{encoding:"utf8",env:process.env});return{stdout:_.stdout||"",stderr:_.stderr||"",exitCode:_.status??1}}async function HW($,_){return await $(_)}async function dX($,_){return(await HW(_,`command -v ${$} >/dev/null 2>&1`)).exitCode===0}function Rd($){try{let _=JSON.parse($);if(!_||typeof _!=="object")return null;return _}catch{return null}}function QF($){if(!$)return null;return $.HostName??$.DNSName?.split(".")[0]??null}async function Kd($,_){let J=new Map;if(!await dX("tailscale",$))return _.push("tailscale_not_available"),{peers:J,selfKey:null};let U=await HW($,"tailscale status --json");if(U.exitCode!==0)return _.push(`tailscale_status_failed:${U.stderr.trim()||U.exitCode}`),{peers:J,selfKey:null};let W=Rd(U.stdout);if(!W)return _.push("tailscale_status_invalid_json"),{peers:J,selfKey:null};let X=(G)=>{let Y=QF(G);if(Y&&G)J.set(Y,G)};X(W.Self);for(let G of Object.values(W.Peer??{}))X(G);return{peers:J,selfKey:QF(W.Self)}}function Fd($){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??$??Y2()}function Ed($){let _=$.machineId===$.localMachineId||$.machineId===Y2(),J=$.peer?.DNSName?.replace(/\.$/,"")??null,U=J??$.peer?.TailscaleIPs?.[0]??null,W=[];if(_)W.push({kind:"local",target:"localhost",reachable:!0});if(U)W.push({kind:"tailscale",target:U,reachable:$.peer?.Online??null});let X=W.find((G)=>G.kind==="local")??W.find((G)=>G.kind==="tailscale")??null;return{machine_id:$.machineId,hostname:$.peer?.HostName??(_?Y2():$.machineId),local:_,platform:$.peer?.OS?PG($.peer.OS):_?PG():null,os:$.peer?.OS??(_?jF():null),user:_?Ld().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:J,ips:$.peer?.TailscaleIPs??[],online:$.peer?.Online??null,active:$.peer?.Active??null,last_seen:$.peer?.LastSeen??null},ssh:{address:null,route:X?.kind==="local"?"local":X?.kind==="tailscale"?"tailscale":"unknown",command_target:X?.target??null},route_hints:W,tags:[],metadata:{},source:"local"}}function Md($){if(!Array.isArray($))return[];return $.map((_)=>{let J=v_(_),U=Y$(J.kind)??"unknown";return{kind:U==="local"||U==="lan"||U==="tailscale"||U==="ssh"?U:"unknown",target:Y$(J.target)??"",reachable:CG(J.reachable)}}).filter((_)=>_.target.length>0)}function Ad($,_){let J=Y$($.machine_id)??Y$($.hostname)??"unknown",U=v_($.tailscale),W=v_($.ssh),X=Y$($.heartbeat_status),G=Y$(W.route);return{machine_id:J,hostname:Y$($.hostname),local:J===_,platform:Y$($.platform),os:Y$($.os),user:Y$($.user),workspace_path:Y$($.workspace_path),manifest_declared:$.manifest_declared===!0,heartbeat_status:X==="online"||X==="offline"?X:"unknown",last_heartbeat_at:Y$($.last_heartbeat_at),tailscale:{dns_name:Y$(U.dns_name),ips:x0(U.ips),online:CG(U.online),active:CG(U.active),last_seen:Y$(U.last_seen)},ssh:{address:Y$(W.address),route:G==="local"||G==="lan"||G==="tailscale"?G:"unknown",command_target:Y$(W.command_target)},route_hints:Md($.route_hints),tags:x0($.tags),metadata:v_($.metadata),source:"open-machines"}}function bd($,_){return`${_} machine${_===1?"":"s"} discovered via ${$}`}function q6($){let _=$ instanceof Error?$.message:String($);return _.includes("Cannot find module '@hasna/machines'")||_.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":_}function nX($){return $.adapterMode??"auto"}function DF($){let _=$?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof _==="number")return _;let J=$?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof J==="number"?J:null}function TG($){return typeof $.schema_version==="number"?$.schema_version:null}function cX($){return typeof $==="number"&&$>Bd?$:null}function SG($){return{package:Hd,entrypoint:Nd,mode:$.mode,implementation:$.implementation,contract_version:$.contractVersion??null,available:$.available,error:$.error??null}}function u$($,_="adapter_disabled"){return SG({mode:$,implementation:"disabled",available:!1,error:_})}function ZG($,_){let J=cX(DF(_));if(!J)return null;return SG({mode:$,implementation:"disabled",available:!1,error:`unsupported_contract_version:${J}`,contractVersion:J})}function vG($){return SG({mode:$,implementation:"cli",available:!0})}function yG($,_){return SG({mode:$,implementation:"sdk",available:!0,contractVersion:DF(_)})}function hG($){try{return JSON.parse($)}catch{return null}}function Q2($){return`'${$.replace(/'/g,"'\\''")}'`}function mG($){return["machines",...$].map(Q2).join(" ")}function xG($){return $==="local"||$==="localhost"||$===Y2()||$===process.env.HASNA_MACHINE_ID||$===process.env.OPEN_MACHINES_MACHINE_ID||$===process.env.MACHINE_ID}function wd($,_){let J=xG($),U=J?_:`ssh ${Q2($)} ${Q2(_)}`,W=zF("bash",["-c",U],{encoding:"utf8",env:process.env});return{stdout:W.stdout||"",stderr:W.stderr||"",exitCode:W.status??1,source:J?"local":"ssh"}}async function OF($,_,J){return await $(_,J)}function X2($,_){if(_)return"ok";return $===!1?"warn":"fail"}function G2($){return $.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function gd($){if($==="@hasna/knowledge")return"knowledge";if($==="@hasna/machines")return"machines";return $.split("/").pop()??$}function kd($){return $.trim().split(/\r?\n/).find(Boolean)??""}function LF($){return $.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function BF($){let _={};for(let J of $.split(/\r?\n/)){let U=J.indexOf("=");if(U<=0)continue;_[J.slice(0,U)]=J.slice(U+1)}return _}function s4($){return{id:$.id,kind:$.kind,status:$.status,target:$.target,expected:$.expected??null,actual:$.actual??null,detail:$.detail,source:$.source}}async function HF($,_,J){let U=[`cmd=${Q2(_.command)}`,'path="$(command -v "$cmd" 2>/dev/null || true)"','printf "path=%s\\n" "$path"',`if [ -n "$path" ]; then version="$("$cmd" ${_.versionArgs??"--version"} 2>/dev/null || true)"; printf "version=%s\\n" "$version"; fi`].join("; "),W=await OF(J,$,U),X=BF(W.stdout);return{path:X.path||null,version:X.version?kd(X.version):null,stderr:W.stderr,source:W.source??(xG($)?"local":"ssh")}}function qF($){let _=$==="name"?String.raw`s/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`:String.raw`s/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p`;return[`if command -v bun >/dev/null 2>&1; then bun -e "const p=JSON.parse(await Bun.file(process.argv[1]).text()); console.log(p.${$} ?? '')" "$pkg" 2>/dev/null`,`elif command -v node >/dev/null 2>&1; then node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync(process.argv[1], 'utf8')); console.log(p.${$} || '')" "$pkg" 2>/dev/null`,`else sed -n '${_}' "$pkg" | head -n 1`,"fi"].join("; ")}async function Id($,_,J){let U=[`path=${Q2(_.path)}`,'printf "exists=%s\\n" "$(test -d "$path" && printf yes || printf no)"','pkg="$path/package.json"','printf "package_json=%s\\n" "$(test -f "$pkg" && printf yes || printf no)"',`if [ -f "$pkg" ]; then printf "package_name=%s\\n" "$(${qF("name")})"; printf "version=%s\\n" "$(${qF("version")})"; fi`].join("; "),W=await OF(J,$,U),X=BF(W.stdout);return{exists:X.exists==="yes",packageJson:X.package_json==="yes",packageName:X.package_name||null,version:X.version||null,stderr:W.stderr,source:W.source??(xG($)?"local":"ssh")}}async function fd($,_,J){let U=await HF($,_,J),W=Boolean(U.path),X=[s4({id:`command:${G2(_.command)}:path`,kind:"command",status:X2(_.required,W),target:_.command,expected:"available",actual:U.path??"missing",detail:W?`found at ${U.path}`:U.stderr||"command missing",source:U.source})];if(_.expectedVersion){let G=LF(U.version??"");X.push(s4({id:`command:${G2(_.command)}:version`,kind:"command",status:G===_.expectedVersion?"ok":X2(_.required,!1),target:_.command,expected:_.expectedVersion,actual:G??U.version??"missing",detail:G?`version output: ${U.version}`:"version unavailable",source:U.source}))}return X}async function Cd($,_,J){let U=_.command??gd(_.name),W=await HF($,{command:U,expectedVersion:_.expectedVersion,required:_.required},J),X=Boolean(W.path),G=[s4({id:`package:${G2(_.name)}:command`,kind:"package",status:X2(_.required,X),target:_.name,expected:U,actual:W.path??"missing",detail:X?`${U} found at ${W.path}`:`${U} command missing`,source:W.source})];if(_.expectedVersion){let Y=LF(W.version??"");G.push(s4({id:`package:${G2(_.name)}:version`,kind:"package",status:Y===_.expectedVersion?"ok":X2(_.required,!1),target:_.name,expected:_.expectedVersion,actual:Y??W.version??"missing",detail:Y?`version output: ${W.version}`:"version unavailable",source:W.source}))}return G}async function Pd($,_,J){let U=await Id($,_,J),W=_.label??_.path,X=[s4({id:`workspace:${G2(W)}:path`,kind:"workspace",status:X2(_.required,U.exists),target:W,expected:_.path,actual:U.exists?"exists":"missing",detail:U.exists?`workspace exists at ${_.path}`:U.stderr||`workspace missing at ${_.path}`,source:U.source})];if(_.expectedPackageName)X.push(s4({id:`workspace:${G2(W)}:package-name`,kind:"workspace",status:U.packageName===_.expectedPackageName?"ok":X2(_.required,!1),target:W,expected:_.expectedPackageName,actual:U.packageName??(U.packageJson?"missing-name":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));if(_.expectedVersion)X.push(s4({id:`workspace:${G2(W)}:version`,kind:"workspace",status:U.version===_.expectedVersion?"ok":X2(_.required,!1),target:W,expected:_.expectedVersion,actual:U.version??(U.packageJson?"missing-version":"missing-package-json"),detail:U.packageJson?"package.json inspected":"package.json missing",source:U.source}));return X}function NF($,_){return{...$,knowledge:{scope:_.knowledge?.scope??"global",app_path:K4,workspace_home:_.knowledge?.workspace_home??null},message:bd($.source,$.machines.length)}}async function uG(){try{return await import("@hasna/machines/consumer")}catch($){if(q6($)!=="module_not_found")throw $;return await import("@hasna/machines")}}function VF($,_,J){let U=v_($);if(cX(TG(U)))return null;let W=Array.isArray(U.machines)?U.machines:null,X=Y$(U.local_machine_id);if(!W||!X)return null;let G={ok:!0,source:"open-machines",generated_at:Y$(U.generated_at)??(_.now??new Date).toISOString(),local_machine_id:X,local_hostname:Y$(U.local_hostname)??Y2(),current_platform:Y$(U.current_platform)??PG(),machines:W.map((Y)=>Ad(Y,X)),warnings:x0(U.warnings),adapter:J};return NF(G,_)}function wG($){return $==="local"||$==="lan"||$==="tailscale"||$==="ssh"||$==="unknown"?$:null}function RF($){let _=v_($),J=Y$(_.observed_at),U=Y$(_.source_authority);if(!J||!U)return null;return{observed_at:J,verified_at:Y$(_.verified_at),expires_at:Y$(_.expires_at),ttl_ms:Vd(_.ttl_ms),source_authority:U,confidence:Y$(_.confidence),cacheable:_.cacheable===!0,stale:_.stale===!0,reasons:x0(_.reasons)}}function KF($,_){let J=v_($);if(cX(TG(J)))return null;let U=Y$(J.target)??Y$(J.command_target);if(J.ok!==!0||!U)return null;let W=typeof J.evidence==="object"&&J.evidence!==null?J.evidence:null,X=typeof W?.selected_hint==="object"&&W.selected_hint!==null?W.selected_hint:null;return{target:U,route:wG(J.route),targetKind:wG(X?.kind)??wG(J.source)??wG(J.route),confidence:Y$(J.confidence),source:"open-machines",adapter:_,evidence:W,cacheability:RF(J.cacheability),warnings:x0(J.warnings)}}function KL($){let _=v_($);return{path:Y$(_.path),source:Y$(_.source)??"unresolved"}}function Td($){if(!Array.isArray($))return[];return $.flatMap((_)=>{let J=v_(_),U=Y$(J.id),W=Y$(J.status),X=Y$(J.severity),G=Y$(J.message);if(!U||!W||!X||!G)return[];return[{id:U,status:W,severity:X,message:G,path:Y$(J.path),source:Y$(J.source)??"unknown",path_exists:CG(J.path_exists)}]})}function Sd($){if(!Array.isArray($))return[];return $.flatMap((_)=>{let J=v_(_),U=Y$(J.id),W=Y$(J.reason),X=x0(J.command),G=Y$(J.shell_command),Y=x0(J.apply_command),Q=Y$(J.apply_shell_command);if(!U||!W||!X.length||!G||!Y.length||!Q)return[];return[{id:U,reason:W,command:X,shell_command:G,apply_command:Y,apply_shell_command:Q}]})}function Zd($){if(!($.projectRootSource==="inferred"||$.openFilesRootSource==="inferred"||$.trustStatus==="untrusted"||$.authStatus==="unknown"||$.warnings.some((W)=>W.includes("inferred")||W.includes("untrusted")||W.includes("unknown_auth")||W.includes("missing"))))return[];let J=["machines","workspace","repair","--machine",$.requestedMachineId,"--project",$.projectId,"--repo",$.repoName,"--open-files-repo",$.openFilesRepoName??"open-files","--json"],U=[...J,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:J,shell_command:J.map(Q2).join(" "),apply_command:U,apply_shell_command:U.map(Q2).join(" ")}]}function FF($,_,J){let U=v_($);if(cX(TG(U)))return null;let W=v_(U.paths),X=v_(U.project),G=v_(U.machine),Y=KL(W.project_root),Q=KL(W.workspace_root),q=KL(W.open_files_root);if(U.ok!==!0||!Y.path)return null;let L=typeof U.evidence==="object"&&U.evidence!==null?U.evidence:null,N=Y$(U.requested_machine_id)??_.machineId,R=Y$(X.project_id)??_.projectId??"open-knowledge",B=Y$(X.repo_name)??_.repoName??_.projectId??"open-knowledge",H=Y$(G.trust_status)??"unknown",V=Y$(G.auth_status)??"unknown",K=x0(U.warnings),E=Td(U.diagnostics),F=Sd(U.repair_hints);return{ok:!0,source:"open-machines",adapter:J,requested_machine_id:N,machine_id:Y$(U.machine_id),project_id:R,repo_name:B,project_root:Y.path,project_root_source:Y.source,workspace_root:Q.path,workspace_root_source:Q.source,open_files_root:q.path,open_files_root_source:q.source,trust_status:H,auth_status:V,current:G.current===!0,primary:G.primary===!0,diagnostics:E,repair_hints:F.length?F:Zd({requestedMachineId:N,projectId:R,repoName:B,openFilesRepoName:_.openFilesRepoName,warnings:K,projectRootSource:Y.source,openFilesRootSource:q.source,trustStatus:H,authStatus:V}),evidence:L,cacheability:RF(U.cacheability),warnings:K}}async function gG($,_){let J=$.runner??uX;if(!await dX("machines",J))return null;let U=["topology","--json"];if($.includeTailscale===!1)U.push("--no-tailscale");let W=await HW(J,mG(U));if(W.exitCode!==0)return null;return VF(hG(W.stdout),$,_)}async function p4($,_){let J=[];if(_.error)J.push(`open_machines_unavailable:${_.error}`);let U=$.runner??uX,W=$.includeTailscale===!1?{peers:new Map,selfKey:null}:await Kd(U,J),X=Fd(W.selfKey),Y=[...new Set([X,...W.peers.keys()])].sort().map((Q)=>Ed({machineId:Q,localMachineId:X,peer:W.peers.get(Q)}));return NF({ok:!0,source:"local",generated_at:($.now??new Date).toISOString(),local_machine_id:X,local_hostname:Y2(),current_platform:PG(),machines:Y,warnings:J,adapter:_},$)}async function EF($={}){let _=nX($);if(_==="disabled")return await p4($,u$(_));let J=vG(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??uG)(),X=ZG(_,W);if(X)return await p4($,X);let G=yG(_,W);if(W?.discoverMachineTopology){let Y=W.discoverMachineTopology({includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),Q=VF(Y,$,G);if(Q)return Q;if(_==="sdk")return await p4($,u$(_,"invalid_topology_shape"));return await gG($,J)??await p4($,u$(_,"invalid_topology_shape"))}if(_==="sdk")return await p4($,u$(_,"missing_discoverMachineTopology"));return await gG($,J)??await p4($,u$(_,"missing_discoverMachineTopology"))}return await gG($,J)??await p4($,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return await p4($,u$(_,q6(U)));return await gG($,J)??await p4($,u$(_,q6(U)))}}async function kG($,_){let J=$.runner??uX;if(!await dX("machines",J))return null;let U=["route","--machine",$.machineId,"--json"];if($.includeTailscale===!1)U.push("--no-tailscale");let W=await HW(J,mG(U));if(W.exitCode!==0)return null;return KF(hG(W.stdout),_)}function o4($,_){return{target:$,route:null,targetKind:null,confidence:null,source:"raw",adapter:_,evidence:null,cacheability:null,warnings:[]}}async function FL($){let _=nX($);if(_==="disabled")return o4($.machineId,u$(_));let J=vG(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??uG)(),X=ZG(_,W);if(X)return o4($.machineId,X);let G=yG(_,W);if(W?.resolveMachineRoute){let Y=KF(W.resolveMachineRoute($.machineId,{includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),G);if(Y)return Y;if(_==="sdk")return o4($.machineId,u$(_,"invalid_route_shape"));return await kG($,J)??o4($.machineId,u$(_,"invalid_route_shape"))}if(_==="sdk")return o4($.machineId,u$(_,"missing_resolveMachineRoute"));return await kG($,J)??o4($.machineId,u$(_,"missing_resolveMachineRoute"))}return await kG($,J)??o4($.machineId,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return{...o4($.machineId,u$(_,q6(U))),warnings:[q6(U)]};return await kG($,J)??{...o4($.machineId,u$(_,q6(U))),warnings:[q6(U)]}}}async function IG($,_){let J=$.runner??uX;if(!await dX("machines",J))return null;let U=$.projectId??"open-knowledge",W=$.repoName??"open-knowledge",X=["workspace","resolve","--machine",$.machineId,"--project",U,"--repo",W,"--open-files-repo",$.openFilesRepoName??"open-files","--json"];if($.includeTailscale===!1)X.push("--no-tailscale");let G=await HW(J,mG(X));if(G.exitCode!==0)return null;return FF(hG(G.stdout),$,_)}function vd($){let _=$.peerWorkspace?.trim();if(!_)return null;return{ok:!0,source:"argument",adapter:u$(nX($),"argument_override"),requested_machine_id:$.machineId,machine_id:$.machineId,project_id:$.projectId??"open-knowledge",repo_name:$.repoName??"open-knowledge",project_root:_,project_root_source:"argument",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:[]}}function t4($,_,J){return{ok:!1,source:"raw",adapter:J,requested_machine_id:$.machineId,machine_id:null,project_id:$.projectId??"open-knowledge",repo_name:$.repoName??"open-knowledge",project_root:null,project_root_source:"unresolved",workspace_root:null,workspace_root_source:"unresolved",open_files_root:null,open_files_root_source:"unresolved",trust_status:"unknown",auth_status:"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:null,cacheability:null,warnings:_}}async function dG($){let _=vd($);if(_)return _;let J=nX($);if(J==="disabled")return t4($,["adapter_disabled"],u$(J));let U=vG(J);try{if(J!=="cli"){let X=await($.loadOpenMachines??uG)(),G=ZG(J,X);if(G)return t4($,[`unsupported_contract_version:${G.contract_version}`],G);let Y=yG(J,X);if(X?.resolveMachineWorkspace){let Q=FF(X.resolveMachineWorkspace({machineId:$.machineId,projectId:$.projectId??"open-knowledge",repoName:$.repoName??"open-knowledge",openFilesRepoName:$.openFilesRepoName??"open-files",includeTailscale:$.includeTailscale,runner:$.runner,now:$.now}),$,Y);if(Q)return Q;if(J==="sdk")return t4($,["invalid_workspace_shape"],u$(J,"invalid_workspace_shape"));return await IG($,U)??t4($,["invalid_workspace_shape"],u$(J,"invalid_workspace_shape"))}if(J==="sdk")return t4($,["missing_resolveMachineWorkspace"],u$(J,"missing_resolveMachineWorkspace"));return await IG($,U)??t4($,["missing_resolveMachineWorkspace"],u$(J,"missing_resolveMachineWorkspace"))}return await IG($,U)??t4($,["machines_cli_unavailable"],u$(J,"machines_cli_unavailable"))}catch(W){if(J==="sdk")return t4($,[q6(W)],u$(J,q6(W)));return await IG($,U)??t4($,[q6(W)],u$(J,q6(W)))}}function MF($,_){return{...$,knowledge:{scope:_.knowledge?.scope??"global",app_path:K4,workspace_home:_.knowledge?.workspace_home??null},message:$.ok?`Machine ${$.machine_id} passed knowledge preflight`:`Machine ${$.machine_id} failed knowledge preflight: ${$.summary.fail} failing check(s)`}}function AF($,_,J){let U=v_($);if(cX(TG(U)))return null;let W=Array.isArray(U.checks)?U.checks:null,X=Y$(U.machine_id)??Y$(U.machineId);if(!W||!X)return null;let G=W.map((Q)=>{let q=v_(Q),L=Y$(q.status),N=Y$(q.kind),R=Y$(q.source);return s4({id:Y$(q.id)??"unknown",kind:N==="command"||N==="package"||N==="workspace"?N:"command",status:L==="ok"||L==="warn"||L==="fail"?L:"fail",target:Y$(q.target)??"unknown",expected:Y$(q.expected),actual:Y$(q.actual),detail:Y$(q.detail)??"",source:R==="local"||R==="ssh"||R==="open-machines"?R:"open-machines"})}),Y={ok:G.filter((Q)=>Q.status==="ok").length,warn:G.filter((Q)=>Q.status==="warn").length,fail:G.filter((Q)=>Q.status==="fail").length};return MF({ok:Y.fail===0,source:"open-machines",machine_id:X,generated_at:Y$(U.generated_at)??(_.now??new Date).toISOString(),checks:G,summary:Y,adapter:J},_)}function yd($){if(!$.runner)return uX;return async(_)=>{let J=await $.runner?.("local",_);return{stdout:J?.stdout??"",stderr:J?.stderr??"",exitCode:J?.exitCode??1}}}function hd($){return[$.name,$.command,$.expectedVersion].filter((_)=>Boolean(_)).join(":")}function md($){let _=[$.expectedPackageName,$.expectedVersion].filter((U)=>Boolean(U)).join(":"),J=_?`${$.path}:${_}`:$.path;return $.label?`${$.label}=${J}`:J}async function fG($,_){let J=yd($);if(!await dX("machines",J))return null;let U=["compatibility","--json","--machine",$.machineId??"local"];for(let X of $.commands??[])U.push("--command",X.expectedVersion?`${X.command}:${X.expectedVersion}`:X.command);for(let X of $.packages??[])U.push("--package",hd(X));for(let X of $.workspaces??[])U.push("--workspace",md(X));let W=await HW(J,mG(U));if(W.exitCode!==0)return null;return AF(hG(W.stdout),$,_)}async function a4($,_){let J=$.machineId??Y2(),U=$.runner??wd,W=$.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],X=$.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],G=$.workspaces??[],Y=[];for(let q of W)Y.push(...await fd(J,q,U));for(let q of X)Y.push(...await Cd(J,q,U));for(let q of G)Y.push(...await Pd(J,q,U));if(_.error)Y.push(s4({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:_.error,detail:"Using knowledge local/ssh compatibility fallback",source:xG(J)?"local":"ssh"}));let Q={ok:Y.filter((q)=>q.status==="ok").length,warn:Y.filter((q)=>q.status==="warn").length,fail:Y.filter((q)=>q.status==="fail").length};return MF({ok:Q.fail===0,source:"local",machine_id:J,generated_at:($.now??new Date).toISOString(),checks:Y,summary:Q,adapter:_},$)}async function bF($={}){let _=nX($);if(_==="disabled")return await a4($,u$(_));let J=vG(_);try{if(_!=="cli"){let W=await($.loadOpenMachines??uG)(),X=ZG(_,W);if(X)return await a4($,X);let G=yG(_,W);if(W?.checkMachineCompatibility){let Y=W.checkMachineCompatibility({machineId:$.machineId,commands:$.commands,packages:$.packages,workspaces:$.workspaces,runner:$.runner,now:$.now}),Q=AF(Y,$,G);if(Q)return Q;if(_==="sdk")return await a4($,u$(_,"invalid_compatibility_shape"));return await fG($,J)??await a4($,u$(_,"invalid_compatibility_shape"))}if(_==="sdk")return await a4($,u$(_,"missing_checkMachineCompatibility"));return await fG($,J)??await a4($,u$(_,"missing_checkMachineCompatibility"))}return await fG($,J)??await a4($,u$(_,"machines_cli_unavailable"))}catch(U){if(_==="sdk")return await a4($,u$(_,q6(U)));return await fG($,J)??await a4($,u$(_,q6(U)))}}import{createHash as wF}from"crypto";function ML($,_,J=24){return`${$}_${wF("sha256").update(_).digest("hex").slice(0,J)}`}function NW($){return $.normalize("NFKC").trim().replace(/\s+/g," ")}function xd($){return NW($).toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")}function n6($,_){try{return JSON.parse($)}catch{return _}}function u0($){return{...$,record_kind:$.record_kind,source_kind:$.source_kind,status:$.status,source_refs:n6($.source_refs_json,[]),evidence_refs:n6($.evidence_refs_json,[]),requires_approval:$.requires_approval===1,checks:n6($.checks_json,gF()),metadata:n6($.metadata_json,{})}}function AL($){return{...$,record_kind:$.record_kind,source_refs:n6($.source_refs_json,[]),evidence_refs:n6($.evidence_refs_json,[]),metadata:n6($.metadata_json,{})}}function gF(){return{citations:{provided:0,valid:0,invalid:0,entries:[]},invalid_source_refs:[],stale_refs:[],duplicate_record_ids:[],duplicate_candidate_ids:[],conflicting_record_ids:[],conflicting_candidate_ids:[],approval_reasons:[]}}function ud($){let _=typeof $==="string"?{ref:$}:$;return{ref:NW(_.ref),citation_id:_.citation_id??null,chunk_id:_.chunk_id??null,revision:_.revision??null,hash:_.hash??null,observed_at:_.observed_at??null,expires_at:_.expires_at??null,status:_.status??null}}function kF($){try{let _=new URL($);return _.protocol.length>1&&(_.hostname.length>0||_.pathname.length>0)}catch{return/^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test($)}}function nG($){return["deleted","stale","invalidated","reindex_required","expired","superseded"].includes(($??"").toLowerCase())}function EL($){if(!$)return null;let _=n6($,{});if(_.stale===!0)return"stale";return typeof _.status==="string"?_.status:null}function dd($){if($.citation_id)return $.citation_id;return $.ref.match(/^(?:cite|citation):(.+)$/)?.[1]??null}function nd($){if($.chunk_id)return $.chunk_id;return $.ref.match(/^chunk:(.+)$/)?.[1]??null}function cd($,_,J){let U=nG(_.status)||Boolean(_.expires_at&&_.expires_at<=J);if(!_.ref||!kF(_.ref))return{ref:_.ref,valid:!1,resolved_by:"none",stale:U,reason:"invalid_reference"};let W=dd(_),X=$.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, + sr.source_id, sr.created_at AS revision_created_at, + (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at + FROM citations c + LEFT JOIN chunks ch ON ch.id = c.chunk_id + LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE c.id = ? OR c.source_uri = ? + ORDER BY c.created_at DESC + LIMIT 1`).get(W,_.ref);if(X){let q=Boolean(_.hash&&X.revision_hash&&_.hash!==X.revision_hash),L=Boolean(_.revision&&X.revision&&_.revision!==X.revision),N=Boolean(X.revision_created_at&&X.latest_revision_at&&X.revision_created_at!kF(N)),G.citations.entries=U.map((N)=>cd($,N,J)),G.citations.provided=U.length,G.citations.valid=G.citations.entries.filter((N)=>N.valid).length,G.citations.invalid=G.citations.entries.length-G.citations.valid,G.stale_refs=G.citations.entries.filter((N)=>N.stale).map((N)=>N.ref),G.duplicate_record_ids=$.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND content_hash = ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(_.record_kind,_.content_hash).map((N)=>N.id),G.duplicate_candidate_ids=$.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND content_hash = ? AND status NOT IN ('rejected') + ORDER BY created_at`).all(_.id,_.record_kind,_.content_hash).map((N)=>N.id),G.conflicting_record_ids=$.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(_.record_kind,_.canonical_key,_.content_hash).map((N)=>N.id),G.conflicting_candidate_ids=$.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND canonical_key = ? AND content_hash <> ? + AND status IN ('ready', 'needs_approval', 'promoted') + ORDER BY created_at`).all(_.id,_.record_kind,_.canonical_key,_.content_hash).map((N)=>N.id);let Y=G.duplicate_record_ids[0]??G.duplicate_candidate_ids[0]??null,Q=W.length===0||U.length===0||G.invalid_source_refs.length>0||G.citations.invalid>0;if(_.record_kind==="decision"||_.record_kind==="claim")G.approval_reasons.push(`${_.record_kind}_requires_review`);if(X.requested_approval===!0)G.approval_reasons.push("explicit_approval_request");if(G.stale_refs.length>0)G.approval_reasons.push("stale_evidence");if(G.conflicting_record_ids.length>0||G.conflicting_candidate_ids.length>0)G.approval_reasons.push("conflicting_knowledge");let q=G.approval_reasons.length>0,L=Y?"duplicate":Q?"blocked":q?"needs_approval":"ready";return $.run(`UPDATE knowledge_promotion_candidates + SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`,[L,q?1:0,JSON.stringify(G),Y,J,J,_.id]),u0(d0($,_.id))}function IF($,_){let J=["lesson","decision","claim"],U=["memento","session","report"];if(!J.includes(_.kind))throw Error("Promotion kind must be lesson, decision, or claim.");if(!U.includes(_.sourceKind))throw Error("Promotion source kind must be memento, session, or report.");let W=k_(NW(_.title)),X=k_(NW(_.content));if(!W.text)throw Error("Promotion title is required.");if(!X.text)throw Error("Promotion content is required.");let G=Array.from(new Set(_.sourceRefs.map(NW).filter(Boolean))).sort(),Y=_.evidenceRefs.map(ud).filter((V)=>V.ref.length>0).sort((V,K)=>V.ref.localeCompare(K.ref)),Q=xd(_.canonicalKey??W.text);if(!Q)throw Error("Promotion canonical key is empty after normalization.");let q=`sha256:${wF("sha256").update(`${_.kind}\x00${NW(X.text).toLowerCase()}`).digest("hex")}`,L=ML("promote",[_.sourceKind,_.kind,Q,q,...G].join("\x00")),N=ML("promotion",L),R=(_.now??new Date).toISOString(),B={..._.metadata??{},requested_approval:_.requiresApproval===!0,confidence:_.confidence??null,valid_from:_.validFrom??R,valid_to:_.validTo??null,redactions:W.findings.length+X.findings.length};a($);let H=m($);try{let V=H.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(L);if(V)return{created:!1,candidate:u0(V)};H.run(`INSERT INTO knowledge_promotion_candidates ( + id, record_kind, title, content, canonical_key, content_hash, source_kind, + source_refs_json, evidence_refs_json, status, requires_approval, checks_json, + idempotency_key, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`,[N,_.kind,W.text,X.text,Q,q,_.sourceKind,JSON.stringify(G),JSON.stringify(Y),L,JSON.stringify(B),R,R]);let K=[...W.findings,...X.findings];if(K.length>0)CJ(H,{source_uri:G[0]??`knowledge://promotion/${N}`,findings:K,metadata:{promotion_candidate_id:N},created_at:R});return __(H,{event_type:"knowledge_promotion",action:"enqueue_promotion",target_uri:`knowledge://promotion/${N}`,decision:"info",metadata:{record_kind:_.kind,source_kind:_.sourceKind,source_refs:G},created_at:R}),{created:!0,candidate:bL(H,d0(H,N),R)}}finally{H.close()}}function fF($,_){a($);let J=m($);try{let U=d0(J,_);return U?u0(U):null}finally{J.close()}}function CF($,_={}){a($);let J=Math.max(1,Math.min(_.limit??50,200)),U=[],W=[];if(_.status==="inbox"||!_.status)U.push("status IN ('ready', 'needs_approval', 'blocked')");else U.push("status = ?"),W.push(_.status);if(_.kind)U.push("record_kind = ?"),W.push(_.kind);let X=m($);try{return X.query(`SELECT * FROM knowledge_promotion_candidates + WHERE ${U.join(" AND ")} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...W,J).map(u0)}finally{X.close()}}function PF($,_,J=new Date){a($);let U=m($);try{let W=d0(U,_);if(!W)throw Error(`Promotion candidate not found: ${_}`);if(W.status==="promoted"||W.status==="rejected")return u0(W);return bL(U,W,J.toISOString())}finally{U.close()}}function TF($,_,J={}){a($);let U=m($),W=(J.now??new Date).toISOString();try{let X=d0(U,_);if(!X)throw Error(`Promotion candidate not found: ${_}`);if(X.status==="promoted"&&X.promoted_record_id){let B=U.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(X.promoted_record_id);return{ok:!0,promoted:!1,requires_approval:X.requires_approval===1,candidate:u0(X),record:B?AL(B):null,approval_id:null,reason:"already_promoted"}}if(X.status==="rejected")throw Error(`Promotion candidate ${_} was rejected.`);let G=bL(U,X,W);if(G.status==="duplicate")return{ok:!0,promoted:!1,requires_approval:!1,candidate:G,record:null,approval_id:null,reason:"duplicate"};if(G.status==="blocked")return{ok:!1,promoted:!1,requires_approval:!1,candidate:G,record:null,approval_id:null,reason:"citation_check_failed"};if(G.requires_approval&&!J.approveWrite)return{ok:!1,promoted:!1,requires_approval:!0,candidate:G,record:null,approval_id:null,reason:"approval_required"};if(G.requires_approval&&!J.approvedBy?.trim())throw Error("Promotion approval requires --approved-by .");let Y=G.requires_approval?J.approvedBy.trim():null,Q=null;if(G.requires_approval)Q=u9(U,{action:"promote_durable_knowledge",target_uri:`knowledge://promotion/${G.id}`,reason:G.checks.approval_reasons.join(", "),approved_by:Y,metadata:{promotion_candidate_id:G.id,checks:G.checks},created_at:W}).id;let q=ML("durable",G.id),L={...G.metadata,promotion_candidate_id:G.id,source_kind:G.source_kind,checks:G.checks,approval_id:Q,provenance:X6({generated_from:`knowledge://promotion/${G.id}`,artifact_key:`durable/${G.record_kind}/${G.canonical_key}`,source_refs:G.source_refs,citation_required:!0})};U.run(`INSERT INTO durable_knowledge_records ( + id, record_kind, title, content, canonical_key, content_hash, status, + source_refs_json, evidence_refs_json, confidence, valid_from, valid_to, + promoted_from_candidate_id, approved_by, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[q,G.record_kind,G.title,G.content,G.canonical_key,G.content_hash,G.checks.conflicting_record_ids.length>0?"conflicted":"active",JSON.stringify(G.source_refs),JSON.stringify(G.evidence_refs),typeof G.metadata.confidence==="number"?G.metadata.confidence:null,typeof G.metadata.valid_from==="string"?G.metadata.valid_from:W,typeof G.metadata.valid_to==="string"?G.metadata.valid_to:null,G.id,Y,JSON.stringify(L),W,W]),U.run(`UPDATE knowledge_promotion_candidates + SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? + WHERE id = ?`,[Y,q,W,W,G.id]),__(U,{event_type:"knowledge_promotion",action:"promote_durable_knowledge",target_uri:`knowledge://durable/${q}`,decision:"allow",metadata:{promotion_candidate_id:G.id,approval_id:Q,source_refs:G.source_refs},created_at:W});let N=u0(d0(U,G.id)),R=U.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(q);return{ok:!0,promoted:!0,requires_approval:G.requires_approval,candidate:N,record:AL(R),approval_id:Q,reason:null}}finally{U.close()}}function SF($,_,J={}){a($);let U=m($),W=(J.now??new Date).toISOString();try{let X=d0(U,_);if(!X)throw Error(`Promotion candidate not found: ${_}`);if(X.status==="promoted")throw Error(`Promotion candidate ${_} is already promoted.`);return U.run(`UPDATE knowledge_promotion_candidates + SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`,[J.rejectedBy?.trim()||null,W,W,_]),__(U,{event_type:"knowledge_promotion",action:"reject_promotion",target_uri:`knowledge://promotion/${_}`,decision:"deny",metadata:{rejected_by:J.rejectedBy??null},created_at:W}),u0(d0(U,_))}finally{U.close()}}function ZF($,_={}){a($);let J=[],U=[];if(_.kind)J.push("record_kind = ?"),U.push(_.kind);if(_.status)J.push("status = ?"),U.push(_.status);let W=Math.max(1,Math.min(_.limit??50,200)),X=m($);try{return X.query(`SELECT * FROM durable_knowledge_records + ${J.length?`WHERE ${J.join(" AND ")}`:""} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...U,W).map(AL)}finally{X.close()}}import{createHash as id,randomUUID as vF}from"crypto";function ld($,_){return`${$}_${id("sha256").update(_).digest("hex").slice(0,20)}`}function rd($){let _=m($);try{let J=_.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(J.map((U)=>[U.status,U.n]))}finally{_.close()}}function yF($,_){let J=k1(_.modelRef,_.config),U=w_(J),W=m($);try{return W.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri FROM chunks c LEFT JOIN source_revisions sr ON sr.id = c.source_revision_id LEFT JOIN sources s ON s.id = sr.source_id LEFT JOIN vector_index_entries v ON v.chunk_id = c.id AND v.provider = ? AND v.model = ? WHERE v.id IS NULL - ORDER BY c.created_at ASC, c.ordinal ASC`).all(U.provider,U.model)}finally{W.close()}}function NK($){G$($.dbPath);let _=i($.dbPath);try{let J=_.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0,U=_.query("SELECT COUNT(*) AS n FROM chunks").get()?.n??0,W=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,X=HK($.dbPath,$).length,G=_.query(`SELECT COUNT(*) AS n FROM source_revisions - WHERE metadata_json LIKE '%"reindex_required":true%' OR metadata_json LIKE '%"status":"stale"%'`).get()?.n??0;return{schema_version:J,chunks:U,vector_entries:W,missing_embeddings:X,queued:Vd($.dbPath),stale_revisions:G}}finally{_.close()}}function BL($){G$($.dbPath);let _=($.now??new Date).toISOString(),J=$.reason??"missing_embedding",U=HK($.dbPath,$),W=i($.dbPath),X=0,G=0;try{W.transaction(()=>{for(let Y of U){let q=Nd("rq",`embedding\x00${Y.chunk_id}\x00${J}`);if(W.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding",Y.chunk_id,J)){G+=1;continue}W.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[q,"embedding",Y.chunk_id,Y.source_uri,J,"pending",JSON.stringify({source_revision_id:Y.source_revision_id}),_,_]),X+=1}})()}finally{W.close()}return{enqueued:X,already_queued:G,reason:J}}function Fd($){let _=i($);try{let J=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0;return _.run("DELETE FROM vector_index_entries"),_.run("DELETE FROM chunk_embeddings"),{embeddings:J,vectorEntries:U}}finally{_.close()}}function Rd($,_,J){let U=E2(_.modelRef,_.config),W=E6(U),X=i($);try{return X.run(`UPDATE reindex_queue + ORDER BY c.created_at ASC, c.ordinal ASC`).all(U.provider,U.model)}finally{W.close()}}function hF($){a($.dbPath);let _=m($.dbPath);try{let J=_.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0,U=_.query("SELECT COUNT(*) AS n FROM chunks").get()?.n??0,W=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,X=yF($.dbPath,$).length,G=_.query(`SELECT COUNT(*) AS n FROM source_revisions + WHERE metadata_json LIKE '%"reindex_required":true%' OR metadata_json LIKE '%"status":"stale"%'`).get()?.n??0;return{schema_version:J,chunks:U,vector_entries:W,missing_embeddings:X,queued:rd($.dbPath),stale_revisions:G}}finally{_.close()}}function wL($){a($.dbPath);let _=($.now??new Date).toISOString(),J=$.reason??"missing_embedding",U=yF($.dbPath,$),W=m($.dbPath),X=0,G=0;try{W.transaction(()=>{for(let Q of U){let q=ld("rq",`embedding\x00${Q.chunk_id}\x00${J}`);if(W.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding",Q.chunk_id,J)){G+=1;continue}W.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[q,"embedding",Q.chunk_id,Q.source_uri,J,"pending",JSON.stringify({source_revision_id:Q.source_revision_id}),_,_]),X+=1}})()}finally{W.close()}return{enqueued:X,already_queued:G,reason:J}}function pd($){let _=m($);try{let J=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,U=_.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0;return _.run("DELETE FROM vector_index_entries"),_.run("DELETE FROM chunk_embeddings"),{embeddings:J,vectorEntries:U}}finally{_.close()}}function od($,_,J){let U=k1(_.modelRef,_.config),W=w_(U),X=m($);try{return X.run(`UPDATE reindex_queue SET status = ?, updated_at = ? WHERE kind = ? AND status = ? @@ -917,13 +1018,13 @@ ${JSON.stringify($.evidence,null,2)}`].join(` WHERE v.chunk_id = reindex_queue.target_id AND v.provider = ? AND v.model = ? - )`,["completed",J,"embedding","pending",W.provider,W.model]).changes}finally{X.close()}}async function VK($){G$($.dbPath);let _=($.now??new Date).toISOString(),J=`run_${BK()}`,U=$.full?Fd($.dbPath):{embeddings:0,vectorEntries:0},W=BL({...$,reason:$.full?"full_embedding_rebuild":"missing_embedding"}),X=i($.dbPath);try{X.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[J,"embedding-refresh",$.full?"full":"incremental","running","local",E2($.modelRef,$.config),JSON.stringify({full:$.full===!0,queued:W}),_,_])}finally{X.close()}let G=await l9({dbPath:$.dbPath,config:$.config,env:$.env,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake,limit:$.limit,now:$.now}),Q=Rd($.dbPath,$,_),Y=i($.dbPath);try{Y.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({full:$.full===!0,queued:W,indexed:G,completed_queue_items:Q}),_,J]),Y.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${BK()}`,J,"info","embedding_refresh_completed",JSON.stringify({queued:W,indexed:G,completed_queue_items:Q}),_])}finally{Y.close()}return{run_id:J,full:$.full===!0,deleted_embeddings:U.embeddings,deleted_vector_entries:U.vectorEntries,queued:W,indexed:G,completed_queue_items:Q}}import{createHash as KK}from"crypto";import{existsSync as MK,lstatSync as Kd,readdirSync as Md,readFileSync as Ad,statSync as bd}from"fs";import{basename as OW,extname as Ed,join as wd,relative as Id,resolve as FL,sep as gd}from"path";import{pathToFileURL as FK}from"url";var kd=100,fd=25,Cd=262144,Pd=5,Td=new Set([".md",".mdx",".txt",".json",".jsonc",".toml",".yaml",".yml"]),HL=new Set(["CODEWITH.md","AGENTS.md","CLAUDE.md","RULES.md","INSTRUCTIONS.md"]),Sd=new Set([".git","node_modules","dist","build",".codewith-worktrees",".connect",".secrets",".tmp","tmp","auth_profiles","profiles","preserved","backup","backups","cache","logs","runs"]),Zd=/(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i,h5=/(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i;function NL($){return`sha256:${KK("sha256").update($).digest("hex")}`}function vd($){return`sha256:${KK("sha256").update($).digest("hex")}`}function xX($){return $.split(gd).join("/")}function VL($,_){let J=Id($,_);return J?xX(J):OW(_)}function m1($){return Td.has(Ed($).toLowerCase())}function RK($){return xX($).split("/").some((_)=>Zd.test(_))}function AK($,_=220){let J=$.normalize("NFKC").trim().replace(/\s+/g," ");if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-1)).trim()}...`}function bK($){if(!$)return 0;return $.split(/\r\n|\n|\r/).length}function EK($){return{source_ref:$.sourceRef,source_path:$.sourcePath,line_start:$.lineCount>0?1:0,line_end:$.lineCount,content_hash:$.contentHash}}function yd(){return[{base:".",maxDepth:0,spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:10,label:"root-rule-doc"},tags:["global-rules","rule-doc"],include:($)=>HL.has($)}},{base:".codewith",spec:{family:"codewith",owner:"codewith",scope:"global",precedence:{rank:20,label:"codewith"},tags:["global-rules","codewith","agent-instructions"],include:($)=>{let _=xX($),J=OW(_);if(HL.has(J)||_==="config.toml")return!0;if(_.endsWith("/SKILL.md"))return!0;if(/^(rules|instructions|prompts|plans)\//.test(_)&&m1(_))return!0;return!1}}},{base:".claude",spec:{family:"claude",owner:"claude",scope:"global",precedence:{rank:30,label:"claude-rules"},tags:["global-rules","claude","agent-instructions"],include:($)=>{let _=xX($);return _==="CLAUDE.md"||/^rules\//.test(_)&&m1(_)}}},{base:".codex",spec:{family:"codex",owner:"codex",scope:"global",precedence:{rank:40,label:"codex"},tags:["global-rules","codex","agent-instructions"],include:($)=>{let _=xX($),J=OW(_);if(HL.has(J)||J==="config.toml")return!0;return/^(rules|instructions|prompts)\//.test(_)&&m1(_)}}},{base:".opencode",spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode"},tags:["global-rules","opencode","agent-instructions"],include:($)=>h5.test($)&&m1($)}},{base:".",maxDepth:0,spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode-config"},tags:["global-rules","opencode","config"],include:($)=>["opencode.json","opencode.jsonc","opencode.toml","opencode.yaml","opencode.yml"].includes($)}},{base:".hasna/prompts",spec:{family:"prompt",owner:"hasna",scope:"global",precedence:{rank:60,label:"selected-prompts"},tags:["global-rules","prompt"],include:($)=>h5.test($)&&m1($)}},{base:".hasna/plans",spec:{family:"plan",owner:"hasna",scope:"global",precedence:{rank:65,label:"selected-plans"},tags:["global-rules","plan"],include:($)=>h5.test($)&&m1($)}},{base:"docs",spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:70,label:"rule-docs"},tags:["global-rules","rule-doc"],include:($)=>h5.test($)&&m1($)}}]}function hd($,_){let J=new Map;for(let U of yd()){let W=FL($,U.base);if(!MK(W))continue;if(bd(W).isFile()){let G=OW(W);if(U.spec.include(G))J.set(W,{...U.spec,absPath:W});continue}wK({basePath:W,depth:0,maxDepth:U.maxDepth??Pd,spec:U.spec,candidates:J,skipped:_})}return[...J.values()].sort((U,W)=>{if(U.precedence.rank!==W.precedence.rank)return U.precedence.rank-W.precedence.rank;return U.absPath.localeCompare(W.absPath)})}function wK($){let _=$.rootBasePath??$.basePath;if($.depth>$.maxDepth)return;for(let J of Md($.basePath,{withFileTypes:!0})){let U=wd($.basePath,J.name),W=VL(_,U);if(J.isSymbolicLink())continue;if(J.isDirectory()){if(Sd.has(J.name))continue;if(RK(W)){$.skipped.push({source_family:$.spec.family,source_path:U,reason:"sensitive_path"});continue}wK({...$,rootBasePath:_,basePath:U,depth:$.depth+1});continue}if(!J.isFile())continue;let X=VL(FL(_),U);if(RK(X)){$.skipped.push({source_family:$.spec.family,source_path:U,reason:"sensitive_path"});continue}if(!$.spec.include(X))continue;if(!m1(U))continue;$.candidates.set(U,{...$.spec,absPath:U})}}function md($){if(($.tags??[]).map((U)=>U.toLowerCase()).some((U)=>["rule","rules","agent","instructions","global-rules","global-agent-rules"].includes(U)))return!0;let J=`${$.title} -${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(J)}function IK($,_){let J={source_path:$.source_path,source_path_ref:$.source_path_ref,source_ref:$.source_ref,owner:$.owner,scope:$.scope,precedence:$.precedence,source_hash:$.source_hash,content_hash:$.content_hash,discovered_at:$.discovered_at,tags:$.tags,redaction_status:$.redaction_status,citations:$.citations};return{source_ref:$.source_ref,name:$.title,mime:"text/markdown",size:Buffer.byteLength(_),hash:$.content_hash,revision:$.content_hash,status:"active",updated_at:$.discovered_at,permissions:{mode:"read_only",allowed_purposes:["knowledge_index","knowledge_answer","agent_context"]},rule_provenance:J,source_family:$.source_family,source_path_ref:$.source_path_ref,owner:$.owner,scope:$.scope,precedence:$.precedence,tags:$.tags,redaction_status:$.redaction_status,legacy_json_id:$.legacy_json_id??null,extracted_text:_}}function xd($){let _=Kd($.candidate.absPath),J=$.candidate.absPath,U=VL($.root,J);if(_.size>$.maxBytesPerFile){let B=FK(J).href;return{evidence:{source_family:$.candidate.family,title:OW(J),source_path:J,source_path_ref:U,source_ref:B,owner:$.candidate.owner,scope:$.candidate.scope,precedence:$.candidate.precedence,source_hash:"sha256:skipped-too-large",content_hash:"sha256:skipped-too-large",discovered_at:$.discoveredAt,tags:[...$.candidate.tags,"skipped"],redaction_status:"refused",redactions:[],citations:[],bytes:_.size,line_count:0,importable:!1,skipped_reason:"max_bytes_exceeded",preview:null},text:"",manifest:null}}let W=Ad(J),X=W.toString("utf8"),G=i6(X,$.safetyPolicy),Y=G.findings.some((B)=>B.severity==="high")?"refused":G.findings.length>0?"redacted":"clean",q=NL(G.text),L=FK(J).href,N=bK(G.text),F={source_family:$.candidate.family,title:OW(J),source_path:J,source_path_ref:U,source_ref:L,owner:$.candidate.owner,scope:$.candidate.scope,precedence:$.candidate.precedence,source_hash:vd(W),content_hash:q,discovered_at:$.discoveredAt,tags:[...$.candidate.tags],redaction_status:Y,redactions:G.findings.map((B)=>({type:B.type,severity:B.severity})),citations:[EK({sourceRef:L,sourcePath:J,lineCount:N,contentHash:q})],bytes:W.byteLength,line_count:N,importable:Y!=="refused",skipped_reason:Y==="refused"?"secret_refused":null,preview:Y==="refused"?null:AK(G.text)};return{evidence:F,text:G.text,manifest:F.importable?IK(F,G.text):null}}function ud($){let _=i6($.item.content,$.safetyPolicy),U=_.findings.some((q)=>q.severity==="high")?"refused":_.findings.length>0?"redacted":"clean",W=`open-files://source/legacy-json/path/${encodeURIComponent($.item.id)}`,X=NL(_.text),G=NL($.item.content),Q=bK(_.text),Y={source_family:"legacy_json",title:$.item.title,source_path:$.legacyStorePath,source_path_ref:`legacy-json:${$.item.id}`,source_ref:W,owner:"legacy-json",scope:$.scope,precedence:{rank:90,label:"legacy-json-note"},source_hash:G,content_hash:X,discovered_at:$.discoveredAt,tags:[...new Set(["global-rules","legacy-json",...$.item.tags??[]])],redaction_status:U,redactions:_.findings.map((q)=>({type:q.type,severity:q.severity})),citations:[EK({sourceRef:W,sourcePath:$.legacyStorePath,lineCount:Q,contentHash:X})],bytes:Buffer.byteLength($.item.content),line_count:Q,importable:U!=="refused",skipped_reason:U==="refused"?"secret_refused":null,preview:U==="refused"?null:AK(_.text),legacy_json_id:$.item.id};return{evidence:Y,text:_.text,manifest:Y.importable?IK(Y,_.text):null}}function dd($){if(!$.legacyStorePath||!MK($.legacyStorePath))return 0;let _=new Map($.records.filter((J)=>J.legacy_json_id&&J.importable).map((J)=>[J.legacy_json_id,J]));if(_.size===0)return 0;return e4($.legacyStorePath,()=>{let J=A_($.legacyStorePath);if(!J.exists)return 0;let U=0;for(let W of J.items){let X=_.get(W.id);if(!X)continue;let G=W.metadata??{};W.archived=!0,W.metadata={...G,knowledge_rules_import:{status:"deprecated_after_source_backed_promotion",deprecated_at:$.now,source_ref:X.source_ref,source_hash:X.source_hash,content_hash:X.content_hash,data_loss:!1}},W.tags=[...new Set([...W.tags??[],"deprecated:knowledge-rules-import"])],W.updated_at=$.now,U+=1}if(U>0)R0($.legacyStorePath,{items:J.items});return U})}async function gK($={}){let _=FL($.root??process.cwd()),J=$.scope??"global",U=$.owner??"global-agent-rules-standard",W=$.dryRun!==!1,X=($.now??new Date).toISOString(),G=Math.max(1,Math.min($.maxItems??kd,1000)),Q=Math.max(1,Math.min($.limit??fd,100)),Y=Math.max(1024,Math.min($.maxBytesPerFile??Cd,2097152)),q=[],N=hd(_,q).slice(0,G).map((x)=>xd({root:_,candidate:{...x,owner:x.owner==="repository"?U:x.owner,scope:J},discoveredAt:X,maxBytesPerFile:Y,safetyPolicy:$.safetyPolicy})),B=($.includeLegacy===!1||!$.legacyStorePath?{exists:!1,items:[]}:A_($.legacyStorePath)).items.filter((x)=>x.archived!==!0&&md(x)).slice(0,G),H=B.map((x)=>ud({item:x,legacyStorePath:$.legacyStorePath,discoveredAt:X,scope:J,safetyPolicy:$.safetyPolicy})),V=[...N,...H].slice(0,G),R=V.map((x)=>x.evidence),K=V.filter((x)=>x.manifest).map((x)=>x.manifest),w=R.filter((x)=>x.redaction_status==="refused").length,b=R.slice(0,Q),I=q.slice(0,Q),v=null,g=0;if(!W){if(!$.dbPath)throw Error("rules provenance apply mode requires dbPath.");if(K.length>0)v=await K2({dbPath:$.dbPath,items:K,sourceLabel:"knowledge://rules-provenance/global-agent-rules",readAction:"rules_provenance_import",allowFileSourceRefs:!0,safetyPolicy:$.safetyPolicy,now:$.now,maxItems:G});if($.deprecateLegacy!==!1)g=dd({legacyStorePath:$.legacyStorePath,records:R,now:X})}return{ok:w===0||K.length>0||W,workflow:"global-rules-provenance-import",dry_run:W,writes_performed:!W,root:_,scope:J,owner:U,discovered_at:X,max_items:G,evidence_limit:Q,records_seen:R.length,records_importable:K.length,records_refused:w,records_skipped:q.length,evidence_truncated:R.length>b.length,skipped_truncated:q.length>I.length,evidence:b,skipped:I,import_result:v,legacy:{store_path:$.legacyStorePath??null,candidates:B.length,promoted:H.filter((x)=>x.manifest).length,deprecated:g,data_loss:!1},message:W?`Discovered ${R.length} rule source(s); ${K.length} importable, ${w} refused`:`Imported ${v?.items_seen??0} rule source(s); ${g} legacy note(s) deprecated`}}import{createHash as cd,randomUUID as kK}from"crypto";function ld($){return`sha256:${cd("sha256").update($).digest("hex")}`}function fK($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function CK($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function x1($){return typeof $==="string"&&$.length>0?$:null}function nd($){let _=CK($),J=x1(_.url)??x1(_.uri)??x1(_.sourceUrl);if(!J)return null;return{url:J,title:x1(_.title)??x1(_.name),snippet:x1(_.snippet)??x1(_.text)??x1(_.description),provider_metadata:_}}function m5($,_){if(Array.isArray($)){for(let W of $)m5(W,_);return}let J=nd($);if(J)_.set(J.url,J);let U=CK($);for(let W of["sources","results","citations","annotations","output"])if(U[W])m5(U[W],_)}function id($,_){return Array.from({length:Math.min(_,3)},(J,U)=>({url:`https://example.com/knowledge-web-${U+1}`,title:`Fake web source ${U+1}`,snippet:`Deterministic web-search fixture for "${$}"`,provider_metadata:{fake:!0,rank:U+1}}))}async function rd($){let{generateText:_}=await import("ai"),{createOpenAI:J}=await import("@ai-sdk/openai"),U=u0($.config,"openai"),W=J({apiKey:$.env[U.api_key_env],baseURL:U.base_url}),X=W.tools?.webSearch;if(!X)throw Error("OpenAI provider does not expose tools.webSearch.");return _({model:W($.model),prompt:$.query,tools:{web_search:X({externalWebAccess:!0,searchContextSize:"medium",...$.domains.length>0?{allowedDomains:$.domains}:{}})},toolChoice:{type:"tool",toolName:"web_search"}})}async function pd($){let{generateText:_}=await import("ai"),{createAnthropic:J}=await import("@ai-sdk/anthropic"),U=u0($.config,"anthropic"),W=J({apiKey:$.env[U.api_key_env],baseURL:U.base_url}),X=W.tools?.webSearch_20250305??W.tools?.webSearch;if(!X)throw Error("Anthropic provider does not expose a web search tool.");return _({model:W($.model),prompt:$.query,tools:{web_search:X({maxUses:$.maxUses,...$.domains.length>0?{allowedDomains:$.domains}:{}})}})}async function od($,_,J){if(!$.fileResults||_.length===0)return 0;let U=_.map((X)=>{let G=[X.title,X.snippet,X.url].filter(Boolean).join(` -`),Q=ld(G);return{source_ref:X.url,name:X.title??X.url,url:X.url,mime:"text/plain",hash:Q,revision:Q,status:"active",updated_at:J,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:X.url,content_source:"provider_web_search",provider_metadata:X.provider_metadata},extracted_text:G}});return(await K2({dbPath:$.dbPath,items:U,sourceLabel:`web-search:${$.query}`,readAction:"provider_web_search_file_results",safetyPolicy:$.safetyPolicy,now:new Date(J)})).sources_upserted}async function PK($){let _=$.query.trim();if(!_)throw Error("Web search query is required.");let J=$.env??process.env,U=($.now??new Date).toISOString(),W=Math.max(1,Math.min($.limit??5,20)),X=Math.max(1,Math.min($.maxUses??3,10)),G=$.domains??[],Q=y4($.modelRef??($.provider?`${$.provider}:${u0($.config,$.provider).default_model}`:"default"),$.config),Y=E6(Q),q=$.provider??Y.provider,L=Y.provider===q?Y.model:u0($.config,q).default_model,N=`run_${kK()}`;if(!$.fake&&$.safetyPolicy)wJ($.safetyPolicy);if(!$.fake&&q!=="openai"&&q!=="anthropic")throw Error(`Provider ${q} does not expose native web search yet.`);if(!$.fake)A2(q,$.config,J);G$($.dbPath);let F=i($.dbPath);try{F.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,"provider-web-search",_,"running",q,L,JSON.stringify({domains:G,max_uses:X,fake:$.fake===!0}),U,U]),O6(F,{event_type:"source_read",action:$.fake?"fake_provider_web_search":"provider_web_search",target_uri:_,decision:"allow",metadata:{provider:q,model:L,domains:G,max_uses:X},created_at:U})}finally{F.close()}let B="",H=[],V={input_tokens:fK(_),output_tokens:0,cost_usd:0},R=[];if($.fake)H=id(_,W),B=`Fake web search answer for: ${_}`,V.output_tokens=fK(B);else{let w=q==="openai"?await rd({query:_,model:L,config:$.config,env:J,maxUses:X,domains:G}):await pd({query:_,model:L,config:$.config,env:J,maxUses:X,domains:G});B=w.text;let b=new Map;m5(w.sources,b),m5(w.toolResults,b),H=Array.from(b.values()).slice(0,W);let I=b2({provider:q,model:L,usage:w.usage,providerMetadata:w.providerMetadata});V={input_tokens:I.input_tokens,output_tokens:I.output_tokens,cost_usd:I.cost_usd}}let M=await od($,H,U),K=i($.dbPath);try{K.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({domains:G,max_uses:X,sources:H.length,filed_sources:M,fake:$.fake===!0}),U,N]),K.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${kK()}`,N,"info","provider_web_search_completed",JSON.stringify({sources:H.length,filed_sources:M}),U]),gJ(K,{run_id:N,provider:q,model:L,input_tokens:V.input_tokens,output_tokens:V.output_tokens,cost_usd:V.cost_usd,metadata:{web_search:!0,sources:H.length,filed_sources:M},created_at:U})}finally{K.close()}if(H.length===0)R.push("no_web_sources_returned");return{run_id:N,query:_,provider:q,model:L,answer:B,sources:H,filed_sources:M,usage:V,warnings:R}}import{createHash as td,randomUUID as ad}from"crypto";function DW($,_){return`${$}_${td("sha256").update(_).digest("hex").slice(0,20)}`}function RL($){return $.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"knowledge-page"}function sd($){return{year:String($.getUTCFullYear()),month:String($.getUTCMonth()+1).padStart(2,"0"),day:String($.getUTCDate()).padStart(2,"0")}}function ed($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function TK($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function $c($){return Array.from(new Set(($??"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,12)}function SK($){return $.replace(/[\\%_]/g,(_)=>`\\${_}`)}function _c($,_){let J=Math.max(1,Math.min(_.limit??10,50)),U=_.sourceRefs??[],W=$c(_.query),X=["c.kind = 'source'"],G=[];if(U.length>0){X.push(`(${U.map(()=>"(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`);for(let Q of U)G.push(Q,`%${SK(Q)}%`)}if(W.length>0){X.push(`(${W.map(()=>"lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`);for(let Q of W)G.push(`%${SK(Q)}%`)}return G.push(J),$.query(`SELECT + )`,["completed",J,"embedding","pending",W.provider,W.model]).changes}finally{X.close()}}async function mF($){a($.dbPath);let _=($.now??new Date).toISOString(),J=`run_${vF()}`,U=$.full?pd($.dbPath):{embeddings:0,vectorEntries:0},W=wL({...$,reason:$.full?"full_embedding_rebuild":"missing_embedding"}),X=m($.dbPath);try{X.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[J,"embedding-refresh",$.full?"full":"incremental","running","local",k1($.modelRef,$.config),JSON.stringify({full:$.full===!0,queued:W}),_,_])}finally{X.close()}let G=await o9({dbPath:$.dbPath,config:$.config,env:$.env,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake,limit:$.limit,now:$.now}),Y=od($.dbPath,$,_),Q=m($.dbPath);try{Q.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({full:$.full===!0,queued:W,indexed:G,completed_queue_items:Y}),_,J]),Q.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${vF()}`,J,"info","embedding_refresh_completed",JSON.stringify({queued:W,indexed:G,completed_queue_items:Y}),_])}finally{Q.close()}return{run_id:J,full:$.full===!0,deleted_embeddings:U.embeddings,deleted_vector_entries:U.vectorEntries,queued:W,indexed:G,completed_queue_items:Y}}import{createHash as dF}from"crypto";import{existsSync as nF,lstatSync as td,readdirSync as ad,readFileSync as sd,statSync as ed}from"fs";import{basename as VW,extname as $n,join as _n,relative as Jn,resolve as fL,sep as Wn}from"path";import{pathToFileURL as xF}from"url";var Un=100,Xn=25,Gn=262144,Yn=5,Qn=new Set([".md",".mdx",".txt",".json",".jsonc",".toml",".yaml",".yml"]),gL=new Set(["CODEWITH.md","AGENTS.md","CLAUDE.md","RULES.md","INSTRUCTIONS.md"]),qn=new Set([".git","node_modules","dist","build",".codewith-worktrees",".connect",".secrets",".tmp","tmp","auth_profiles","profiles","preserved","backup","backups","cache","logs","runs"]),zn=/(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i,cG=/(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i;function kL($){return`sha256:${dF("sha256").update($).digest("hex")}`}function jn($){return`sha256:${dF("sha256").update($).digest("hex")}`}function iX($){return $.split(Wn).join("/")}function IL($,_){let J=Jn($,_);return J?iX(J):VW(_)}function n0($){return Qn.has($n($).toLowerCase())}function uF($){return iX($).split("/").some((_)=>zn.test(_))}function cF($,_=220){let J=$.normalize("NFKC").trim().replace(/\s+/g," ");if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-1)).trim()}...`}function iF($){if(!$)return 0;return $.split(/\r\n|\n|\r/).length}function lF($){return{source_ref:$.sourceRef,source_path:$.sourcePath,line_start:$.lineCount>0?1:0,line_end:$.lineCount,content_hash:$.contentHash}}function Dn(){return[{base:".",maxDepth:0,spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:10,label:"root-rule-doc"},tags:["global-rules","rule-doc"],include:($)=>gL.has($)}},{base:".codewith",spec:{family:"codewith",owner:"codewith",scope:"global",precedence:{rank:20,label:"codewith"},tags:["global-rules","codewith","agent-instructions"],include:($)=>{let _=iX($),J=VW(_);if(gL.has(J)||_==="config.toml")return!0;if(_.endsWith("/SKILL.md"))return!0;if(/^(rules|instructions|prompts|plans)\//.test(_)&&n0(_))return!0;return!1}}},{base:".claude",spec:{family:"claude",owner:"claude",scope:"global",precedence:{rank:30,label:"claude-rules"},tags:["global-rules","claude","agent-instructions"],include:($)=>{let _=iX($);return _==="CLAUDE.md"||/^rules\//.test(_)&&n0(_)}}},{base:".codex",spec:{family:"codex",owner:"codex",scope:"global",precedence:{rank:40,label:"codex"},tags:["global-rules","codex","agent-instructions"],include:($)=>{let _=iX($),J=VW(_);if(gL.has(J)||J==="config.toml")return!0;return/^(rules|instructions|prompts)\//.test(_)&&n0(_)}}},{base:".opencode",spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode"},tags:["global-rules","opencode","agent-instructions"],include:($)=>cG.test($)&&n0($)}},{base:".",maxDepth:0,spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode-config"},tags:["global-rules","opencode","config"],include:($)=>["opencode.json","opencode.jsonc","opencode.toml","opencode.yaml","opencode.yml"].includes($)}},{base:".hasna/prompts",spec:{family:"prompt",owner:"hasna",scope:"global",precedence:{rank:60,label:"selected-prompts"},tags:["global-rules","prompt"],include:($)=>cG.test($)&&n0($)}},{base:".hasna/plans",spec:{family:"plan",owner:"hasna",scope:"global",precedence:{rank:65,label:"selected-plans"},tags:["global-rules","plan"],include:($)=>cG.test($)&&n0($)}},{base:"docs",spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:70,label:"rule-docs"},tags:["global-rules","rule-doc"],include:($)=>cG.test($)&&n0($)}}]}function On($,_){let J=new Map;for(let U of Dn()){let W=fL($,U.base);if(!nF(W))continue;if(ed(W).isFile()){let G=VW(W);if(U.spec.include(G))J.set(W,{...U.spec,absPath:W});continue}rF({basePath:W,depth:0,maxDepth:U.maxDepth??Yn,spec:U.spec,candidates:J,skipped:_})}return[...J.values()].sort((U,W)=>{if(U.precedence.rank!==W.precedence.rank)return U.precedence.rank-W.precedence.rank;return U.absPath.localeCompare(W.absPath)})}function rF($){let _=$.rootBasePath??$.basePath;if($.depth>$.maxDepth)return;for(let J of ad($.basePath,{withFileTypes:!0})){let U=_n($.basePath,J.name),W=IL(_,U);if(J.isSymbolicLink())continue;if(J.isDirectory()){if(qn.has(J.name))continue;if(uF(W)){$.skipped.push({source_family:$.spec.family,source_path:U,reason:"sensitive_path"});continue}rF({...$,rootBasePath:_,basePath:U,depth:$.depth+1});continue}if(!J.isFile())continue;let X=IL(fL(_),U);if(uF(X)){$.skipped.push({source_family:$.spec.family,source_path:U,reason:"sensitive_path"});continue}if(!$.spec.include(X))continue;if(!n0(U))continue;$.candidates.set(U,{...$.spec,absPath:U})}}function Ln($){if(($.tags??[]).map((U)=>U.toLowerCase()).some((U)=>["rule","rules","agent","instructions","global-rules","global-agent-rules"].includes(U)))return!0;let J=`${$.title} +${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(J)}function pF($,_){let J={source_path:$.source_path,source_path_ref:$.source_path_ref,source_ref:$.source_ref,owner:$.owner,scope:$.scope,precedence:$.precedence,source_hash:$.source_hash,content_hash:$.content_hash,discovered_at:$.discovered_at,tags:$.tags,redaction_status:$.redaction_status,citations:$.citations};return{source_ref:$.source_ref,name:$.title,mime:"text/markdown",size:Buffer.byteLength(_),hash:$.content_hash,revision:$.content_hash,status:"active",updated_at:$.discovered_at,permissions:{mode:"read_only",allowed_purposes:["knowledge_index","knowledge_answer","agent_context"]},rule_provenance:J,source_family:$.source_family,source_path_ref:$.source_path_ref,owner:$.owner,scope:$.scope,precedence:$.precedence,tags:$.tags,redaction_status:$.redaction_status,legacy_json_id:$.legacy_json_id??null,extracted_text:_}}function Bn($){let _=td($.candidate.absPath),J=$.candidate.absPath,U=IL($.root,J);if(_.size>$.maxBytesPerFile){let B=xF(J).href;return{evidence:{source_family:$.candidate.family,title:VW(J),source_path:J,source_path_ref:U,source_ref:B,owner:$.candidate.owner,scope:$.candidate.scope,precedence:$.candidate.precedence,source_hash:"sha256:skipped-too-large",content_hash:"sha256:skipped-too-large",discovered_at:$.discoveredAt,tags:[...$.candidate.tags,"skipped"],redaction_status:"refused",redactions:[],citations:[],bytes:_.size,line_count:0,importable:!1,skipped_reason:"max_bytes_exceeded",preview:null},text:"",manifest:null}}let W=sd(J),X=W.toString("utf8"),G=k_(X,$.safetyPolicy),Q=G.findings.some((B)=>B.severity==="high")?"refused":G.findings.length>0?"redacted":"clean",q=kL(G.text),L=xF(J).href,N=iF(G.text),R={source_family:$.candidate.family,title:VW(J),source_path:J,source_path_ref:U,source_ref:L,owner:$.candidate.owner,scope:$.candidate.scope,precedence:$.candidate.precedence,source_hash:jn(W),content_hash:q,discovered_at:$.discoveredAt,tags:[...$.candidate.tags],redaction_status:Q,redactions:G.findings.map((B)=>({type:B.type,severity:B.severity})),citations:[lF({sourceRef:L,sourcePath:J,lineCount:N,contentHash:q})],bytes:W.byteLength,line_count:N,importable:Q!=="refused",skipped_reason:Q==="refused"?"secret_refused":null,preview:Q==="refused"?null:cF(G.text)};return{evidence:R,text:G.text,manifest:R.importable?pF(R,G.text):null}}function Hn($){let _=k_($.item.content,$.safetyPolicy),U=_.findings.some((q)=>q.severity==="high")?"refused":_.findings.length>0?"redacted":"clean",W=`open-files://source/legacy-json/path/${encodeURIComponent($.item.id)}`,X=kL(_.text),G=kL($.item.content),Y=iF(_.text),Q={source_family:"legacy_json",title:$.item.title,source_path:$.legacyStorePath,source_path_ref:`legacy-json:${$.item.id}`,source_ref:W,owner:"legacy-json",scope:$.scope,precedence:{rank:90,label:"legacy-json-note"},source_hash:G,content_hash:X,discovered_at:$.discoveredAt,tags:[...new Set(["global-rules","legacy-json",...$.item.tags??[]])],redaction_status:U,redactions:_.findings.map((q)=>({type:q.type,severity:q.severity})),citations:[lF({sourceRef:W,sourcePath:$.legacyStorePath,lineCount:Y,contentHash:X})],bytes:Buffer.byteLength($.item.content),line_count:Y,importable:U!=="refused",skipped_reason:U==="refused"?"secret_refused":null,preview:U==="refused"?null:cF(_.text),legacy_json_id:$.item.id};return{evidence:Q,text:_.text,manifest:Q.importable?pF(Q,_.text):null}}function Nn($){if(!$.legacyStorePath||!nF($.legacyStorePath))return 0;let _=new Map($.records.filter((J)=>J.legacy_json_id&&J.importable).map((J)=>[J.legacy_json_id,J]));if(_.size===0)return 0;return $4($.legacyStorePath,()=>{let J=g2($.legacyStorePath);if(!J.exists)return 0;let U=0;for(let W of J.items){let X=_.get(W.id);if(!X)continue;let G=W.metadata??{};W.archived=!0,W.metadata={...G,knowledge_rules_import:{status:"deprecated_after_source_backed_promotion",deprecated_at:$.now,source_ref:X.source_ref,source_hash:X.source_hash,content_hash:X.content_hash,data_loss:!1}},W.tags=[...new Set([...W.tags??[],"deprecated:knowledge-rules-import"])],W.updated_at=$.now,U+=1}if(U>0)F4($.legacyStorePath,{items:J.items});return U})}async function oF($={}){let _=fL($.root??process.cwd()),J=$.scope??"global",U=$.owner??"global-agent-rules-standard",W=$.dryRun!==!1,X=($.now??new Date).toISOString(),G=Math.max(1,Math.min($.maxItems??Un,1000)),Y=Math.max(1,Math.min($.limit??Xn,100)),Q=Math.max(1024,Math.min($.maxBytesPerFile??Gn,2097152)),q=[],N=On(_,q).slice(0,G).map((u)=>Bn({root:_,candidate:{...u,owner:u.owner==="repository"?U:u.owner,scope:J},discoveredAt:X,maxBytesPerFile:Q,safetyPolicy:$.safetyPolicy})),B=($.includeLegacy===!1||!$.legacyStorePath?{exists:!1,items:[]}:g2($.legacyStorePath)).items.filter((u)=>u.archived!==!0&&Ln(u)).slice(0,G),H=B.map((u)=>Hn({item:u,legacyStorePath:$.legacyStorePath,discoveredAt:X,scope:J,safetyPolicy:$.safetyPolicy})),V=[...N,...H].slice(0,G),K=V.map((u)=>u.evidence),F=V.filter((u)=>u.manifest).map((u)=>u.manifest),w=K.filter((u)=>u.redaction_status==="refused").length,A=K.slice(0,Y),g=q.slice(0,Y),v=null,k=0;if(!W){if(!$.dbPath)throw Error("rules provenance apply mode requires dbPath.");if(F.length>0)v=await A1({dbPath:$.dbPath,items:F,sourceLabel:"knowledge://rules-provenance/global-agent-rules",readAction:"rules_provenance_import",allowFileSourceRefs:!0,safetyPolicy:$.safetyPolicy,now:$.now,maxItems:G});if($.deprecateLegacy!==!1)k=Nn({legacyStorePath:$.legacyStorePath,records:K,now:X})}return{ok:w===0||F.length>0||W,workflow:"global-rules-provenance-import",dry_run:W,writes_performed:!W,root:_,scope:J,owner:U,discovered_at:X,max_items:G,evidence_limit:Y,records_seen:K.length,records_importable:F.length,records_refused:w,records_skipped:q.length,evidence_truncated:K.length>A.length,skipped_truncated:q.length>g.length,evidence:A,skipped:g,import_result:v,legacy:{store_path:$.legacyStorePath??null,candidates:B.length,promoted:H.filter((u)=>u.manifest).length,deprecated:k,data_loss:!1},message:W?`Discovered ${K.length} rule source(s); ${F.length} importable, ${w} refused`:`Imported ${v?.items_seen??0} rule source(s); ${k} legacy note(s) deprecated`}}import{createHash as Vn,randomUUID as tF}from"crypto";function Rn($){return`sha256:${Vn("sha256").update($).digest("hex")}`}function aF($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function sF($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function c0($){return typeof $==="string"&&$.length>0?$:null}function Kn($){let _=sF($),J=c0(_.url)??c0(_.uri)??c0(_.sourceUrl);if(!J)return null;return{url:J,title:c0(_.title)??c0(_.name),snippet:c0(_.snippet)??c0(_.text)??c0(_.description),provider_metadata:_}}function iG($,_){if(Array.isArray($)){for(let W of $)iG(W,_);return}let J=Kn($);if(J)_.set(J.url,J);let U=sF($);for(let W of["sources","results","citations","annotations","output"])if(U[W])iG(U[W],_)}function Fn($,_){return Array.from({length:Math.min(_,3)},(J,U)=>({url:`https://example.com/knowledge-web-${U+1}`,title:`Fake web source ${U+1}`,snippet:`Deterministic web-search fixture for "${$}"`,provider_metadata:{fake:!0,rank:U+1}}))}async function En($){let{generateText:_}=await import("ai"),{createOpenAI:J}=await import("@ai-sdk/openai"),U=n4($.config,"openai"),W=J({apiKey:$.env[U.api_key_env],baseURL:U.base_url}),X=W.tools?.webSearch;if(!X)throw Error("OpenAI provider does not expose tools.webSearch.");return _({model:W($.model),prompt:$.query,tools:{web_search:X({externalWebAccess:!0,searchContextSize:"medium",...$.domains.length>0?{allowedDomains:$.domains}:{}})},toolChoice:{type:"tool",toolName:"web_search"}})}async function Mn($){let{generateText:_}=await import("ai"),{createAnthropic:J}=await import("@ai-sdk/anthropic"),U=n4($.config,"anthropic"),W=J({apiKey:$.env[U.api_key_env],baseURL:U.base_url}),X=W.tools?.webSearch_20250305??W.tools?.webSearch;if(!X)throw Error("Anthropic provider does not expose a web search tool.");return _({model:W($.model),prompt:$.query,tools:{web_search:X({maxUses:$.maxUses,...$.domains.length>0?{allowedDomains:$.domains}:{}})}})}async function An($,_,J){if(!$.fileResults||_.length===0)return 0;let U=_.map((X)=>{let G=[X.title,X.snippet,X.url].filter(Boolean).join(` +`),Y=Rn(G);return{source_ref:X.url,name:X.title??X.url,url:X.url,mime:"text/plain",hash:Y,revision:Y,status:"active",updated_at:J,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:X.url,content_source:"provider_web_search",provider_metadata:X.provider_metadata},extracted_text:G}});return(await A1({dbPath:$.dbPath,items:U,sourceLabel:`web-search:${$.query}`,readAction:"provider_web_search_file_results",safetyPolicy:$.safetyPolicy,now:new Date(J)})).sources_upserted}async function eF($){let _=$.query.trim();if(!_)throw Error("Web search query is required.");let J=$.env??process.env,U=($.now??new Date).toISOString(),W=Math.max(1,Math.min($.limit??5,20)),X=Math.max(1,Math.min($.maxUses??3,10)),G=$.domains??[],Y=y6($.modelRef??($.provider?`${$.provider}:${n4($.config,$.provider).default_model}`:"default"),$.config),Q=w_(Y),q=$.provider??Q.provider,L=Q.provider===q?Q.model:n4($.config,q).default_model,N=`run_${tF()}`;if(!$.fake&&$.safetyPolicy)fJ($.safetyPolicy);if(!$.fake&&q!=="openai"&&q!=="anthropic")throw Error(`Provider ${q} does not expose native web search yet.`);if(!$.fake)w1(q,$.config,J);a($.dbPath);let R=m($.dbPath);try{R.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,"provider-web-search",_,"running",q,L,JSON.stringify({domains:G,max_uses:X,fake:$.fake===!0}),U,U]),__(R,{event_type:"source_read",action:$.fake?"fake_provider_web_search":"provider_web_search",target_uri:_,decision:"allow",metadata:{provider:q,model:L,domains:G,max_uses:X},created_at:U})}finally{R.close()}let B="",H=[],V={input_tokens:aF(_),output_tokens:0,cost_usd:0},K=[];if($.fake)H=Fn(_,W),B=`Fake web search answer for: ${_}`,V.output_tokens=aF(B);else{let w=q==="openai"?await En({query:_,model:L,config:$.config,env:J,maxUses:X,domains:G}):await Mn({query:_,model:L,config:$.config,env:J,maxUses:X,domains:G});B=w.text;let A=new Map;iG(w.sources,A),iG(w.toolResults,A),H=Array.from(A.values()).slice(0,W);let g=g1({provider:q,model:L,usage:w.usage,providerMetadata:w.providerMetadata});V={input_tokens:g.input_tokens,output_tokens:g.output_tokens,cost_usd:g.cost_usd}}let E=await An($,H,U),F=m($.dbPath);try{F.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({domains:G,max_uses:X,sources:H.length,filed_sources:E,fake:$.fake===!0}),U,N]),F.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${tF()}`,N,"info","provider_web_search_completed",JSON.stringify({sources:H.length,filed_sources:E}),U]),TJ(F,{run_id:N,provider:q,model:L,input_tokens:V.input_tokens,output_tokens:V.output_tokens,cost_usd:V.cost_usd,metadata:{web_search:!0,sources:H.length,filed_sources:E},created_at:U})}finally{F.close()}if(H.length===0)K.push("no_web_sources_returned");return{run_id:N,query:_,provider:q,model:L,answer:B,sources:H,filed_sources:E,usage:V,warnings:K}}import{createHash as bn,randomUUID as wn}from"crypto";function RW($,_){return`${$}_${bn("sha256").update(_).digest("hex").slice(0,20)}`}function CL($){return $.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"knowledge-page"}function gn($){return{year:String($.getUTCFullYear()),month:String($.getUTCMonth()+1).padStart(2,"0"),day:String($.getUTCDate()).padStart(2,"0")}}function kn($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function $E($){if(!$)return{};try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function In($){return Array.from(new Set(($??"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,12)}function _E($){return $.replace(/[\\%_]/g,(_)=>`\\${_}`)}function fn($,_){let J=Math.max(1,Math.min(_.limit??10,50)),U=_.sourceRefs??[],W=In(_.query),X=["c.kind = 'source'"],G=[];if(U.length>0){X.push(`(${U.map(()=>"(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`);for(let Y of U)G.push(Y,`%${_E(Y)}%`)}if(W.length>0){X.push(`(${W.map(()=>"lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`);for(let Y of W)G.push(`%${_E(Y)}%`)}return G.push(J),$.query(`SELECT c.id AS chunk_id, c.text, c.start_offset, @@ -939,10 +1040,10 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| JOIN sources s ON s.id = sr.source_id WHERE ${X.join(" AND ")} ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`).all(...G)}function ZK($,_=420){let J=$.replace(/\s+/g," ").trim();return J.length<=_?J:`${J.slice(0,_-1).trim()}...`}function Jc($,_){if($.title?.trim())return $.title.trim();if($.query?.trim())return $.query.trim();return _[0]?.source_title??"Compiled Knowledge"}function Wc($,_,J){let U=_.map((X,G)=>{return`- [${`S${G+1}`}] ${X.source_title??X.source_uri??"Source"} (${X.source_uri??"unknown"}, revision ${X.revision??"unknown"}, hash ${X.hash??"unknown"})`}),W=_.map((X,G)=>{let Q=`S${G+1}`;return[`## ${X.source_title??`Source ${G+1}`}`,"",ZK(X.text),"",`Citation: [${Q}]`].join(` + LIMIT ?`).all(...G)}function JE($,_=420){let J=$.replace(/\s+/g," ").trim();return J.length<=_?J:`${J.slice(0,_-1).trim()}...`}function Cn($,_){if($.title?.trim())return $.title.trim();if($.query?.trim())return $.query.trim();return _[0]?.source_title??"Compiled Knowledge"}function Pn($,_,J){let U=_.map((X,G)=>{return`- [${`S${G+1}`}] ${X.source_title??X.source_uri??"Source"} (${X.source_uri??"unknown"}, revision ${X.revision??"unknown"}, hash ${X.hash??"unknown"})`}),W=_.map((X,G)=>{let Y=`S${G+1}`;return[`## ${X.source_title??`Source ${G+1}`}`,"",JE(X.text),"",`Citation: [${Y}]`].join(` `)});return[`# ${$}`,"",`Generated at: ${J}`,"","## Sources","",...U,"",...W,""].join(` -`)}async function x5($,_){let J=await $.put(_);return{key:J.key,uri:J.uri,kind:_.key.startsWith("logs/")?"log":"wiki_page",content_type:_.content_type,modified_at:J.modified_at,...EJ(_.body),metadata:{..._.metadata??{}}}}async function vK($,_,J){let{year:U,month:W,day:X}=sd(J),G=`logs/${U}/${W}/${X}.jsonl`,Q="";try{Q=await $.getText(G)}catch{Q=""}return x5($,{key:G,body:`${Q}${JSON.stringify(_)} -`,content_type:"application/x-ndjson",metadata:{provenance:v4({generated_from:String(_.event??"wiki_log"),artifact_key:G})}})}function KL($,_){$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) +`)}async function lG($,_){let J=await $.put(_);return{key:J.key,uri:J.uri,kind:_.key.startsWith("logs/")?"log":"wiki_page",content_type:_.content_type,modified_at:J.modified_at,...IJ(_.body),metadata:{..._.metadata??{}}}}async function WE($,_,J){let{year:U,month:W,day:X}=gn(J),G=`logs/${U}/${W}/${X}.jsonl`,Y="";try{Y=await $.getText(G)}catch{Y=""}return lG($,{key:G,body:`${Y}${JSON.stringify(_)} +`,content_type:"application/x-ndjson",metadata:{provenance:X6({generated_from:String(_.event??"wiki_log"),artifact_key:G})}})}function PL($,_){$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title = excluded.title, @@ -950,41 +1051,41 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| content_hash = excluded.content_hash, status = excluded.status, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[_.pageId,_.path,_.title,_.artifactUri,_.contentHash,"active",JSON.stringify({artifact_key:_.path,provenance:_.provenance}),_.now,_.now]);let J=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_.pageId);for(let W of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[W.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_.pageId]);let U=DW("chk",`${_.pageId}\x00${_.contentHash}`);$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.pageId,"wiki",0,_.body,ed(_.body),0,_.body.length,JSON.stringify({artifact_key:_.path,artifact_uri:_.artifactUri,content_hash:_.contentHash,provenance:_.provenance}),_.now]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,_.body,_.title,_.artifactUri])}function yK($,_,J,U){$.run("DELETE FROM citations WHERE wiki_page_id = ?",[_]);for(let W of J)$.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[DW("cit",`${_}\x00${W.source_uri}\x00${W.chunk_id??ad()}`),_,W.chunk_id,W.source_uri,W.quote,W.start_offset,W.end_offset,JSON.stringify(W.metadata),U]);return J.length}function hK($,_){return $.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + updated_at = excluded.updated_at`,[_.pageId,_.path,_.title,_.artifactUri,_.contentHash,"active",JSON.stringify({artifact_key:_.path,provenance:_.provenance}),_.now,_.now]);let J=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_.pageId);for(let W of J)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[W.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_.pageId]);let U=RW("chk",`${_.pageId}\x00${_.contentHash}`);$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[U,_.pageId,"wiki",0,_.body,kn(_.body),0,_.body.length,JSON.stringify({artifact_key:_.path,artifact_uri:_.artifactUri,content_hash:_.contentHash,provenance:_.provenance}),_.now]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[U,_.body,_.title,_.artifactUri])}function UE($,_,J,U){$.run("DELETE FROM citations WHERE wiki_page_id = ?",[_]);for(let W of J)$.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[RW("cit",`${_}\x00${W.source_uri}\x00${W.chunk_id??wn()}`),_,W.chunk_id,W.source_uri,W.quote,W.start_offset,W.end_offset,JSON.stringify(W.metadata),U]);return J.length}function XE($,_){return $.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[DW("idx",`wiki-topic\x00${_.path}`),"wiki_topic",_.title,_.artifactUri,_.path,JSON.stringify({artifact_key:_.path,content_hash:_.contentHash}),_.now,_.now]),1}function Uc($){return $.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0]??"knowledge"}async function mK($){let _=$.now??new Date,J=_.toISOString();G$($.dbPath);let U=i($.dbPath),W;try{W=_c(U,$)}finally{U.close()}if(W.length===0)throw Error("No source chunks matched wiki compile input.");let X=Jc($,W),Q=`wiki/generated/${RL(X)}.md`,Y=Wc(X,W,J),q=W.map((v)=>{let g=TK(v.metadata_json);return typeof g.source_ref==="string"?g.source_ref:v.source_uri}).filter((v)=>Boolean(v)),L=v4({generated_from:"wiki_compile",artifact_key:Q,source_refs:q}),N=await x5($.store,{key:Q,body:Y,content_type:"text/markdown",metadata:{generated_from:"wiki_compile"}}),F=DW("wiki",Q),B=W.map((v)=>({chunk_id:v.chunk_id,source_uri:v.source_uri??"unknown",quote:ZK(v.text,240),start_offset:v.start_offset,end_offset:v.end_offset,metadata:{source_revision_id:v.source_revision_id,revision:v.revision,hash:v.hash,source_ref:TK(v.metadata_json).source_ref??v.source_uri}})),H=Uc(X),V=`wiki/concepts/${RL(H)}.md`,R=[`# ${H}`,"",`Related page: [[${Q}]]`,""].join(` -`),M=v4({generated_from:"wiki_compile_concept",artifact_key:V,source_refs:q}),K=await x5($.store,{key:V,body:R,content_type:"text/markdown",metadata:{generated_from:"wiki_compile_concept"}}),w=DW("wiki",V),b=await vK($.store,{ts:J,event:"wiki_compile_completed",page_key:Q,source_refs:q,chunks_seen:W.length},_),I=i($.dbPath);try{m0(I,[N,K,b],_),KL(I,{pageId:F,path:Q,title:X,artifactUri:N.uri,contentHash:N.hash??"",body:Y,provenance:L,now:J}),KL(I,{pageId:w,path:V,title:H,artifactUri:K.uri,contentHash:K.hash??"",body:R,provenance:M,now:J}),I.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) - VALUES (?, ?, ?, ?)`,[F,w,"concept",J]);let v=yK(I,F,B,J),g=hK(I,{title:X,path:Q,artifactUri:N.uri,contentHash:N.hash??"",now:J});return{page_id:F,path:Q,artifact_uri:N.uri,content_hash:N.hash??"",chunks_seen:W.length,citations_written:v,concept_page_id:w,indexes_updated:g,log_key:b.key,warnings:[]}}finally{I.close()}}async function xK($){if(!$.approveWrite)return{approved:!1,durable_writes_performed:!1,page_id:null,path:null,artifact_uri:null,citations_written:0,log_key:null,message:"Dry-run: answer filing requires --approve-write."};let _=$.now??new Date,J=_.toISOString(),U=$.prompt.length>80?`${$.prompt.slice(0,77)}...`:$.prompt,X=`wiki/answers/${RL(U)}.md`,G=$.context.citations,Q=[`# ${U}`,"",$.answer,"","## Citations","",...G.map((H,V)=>`- [C${V+1}] ${H.source_ref??H.source_uri??H.artifact_path??H.artifact_uri??"unknown"} ${H.hash?`(hash ${H.hash})`:""}`),""].join(` -`),Y=G.map((H)=>H.source_ref??H.source_uri).filter((H)=>Boolean(H)),q=v4({generated_from:"knowledge_answer",artifact_key:X,source_refs:Y}),L=await x5($.store,{key:X,body:Q,content_type:"text/markdown",metadata:{generated_from:"knowledge_answer"}}),N=await vK($.store,{ts:J,event:"wiki_answer_filed",page_key:X,prompt:$.prompt,citations:G.length},_),F=DW("wiki",X),B=i($.dbPath);try{m0(B,[L,N],_),KL(B,{pageId:F,path:X,title:U,artifactUri:L.uri,contentHash:L.hash??"",body:Q,provenance:q,now:J});let H=yK(B,F,G.map((V)=>({chunk_id:V.chunk_id,source_uri:V.source_uri??V.artifact_uri??"unknown",quote:V.quote,start_offset:V.start_offset,end_offset:V.end_offset,metadata:{source_ref:V.source_ref,artifact_path:V.artifact_path,revision:V.revision,hash:V.hash}})),J);return hK(B,{title:U,path:X,artifactUri:L.uri,contentHash:L.hash??"",now:J}),{approved:!0,durable_writes_performed:!0,page_id:F,path:X,artifact_uri:L.uri,citations_written:H,log_key:N.key,message:`Filed answer to ${X}`}}finally{B.close()}}function G_($,_){$.push(_)}function uK($){G$($.dbPath);let _=i($.dbPath),J=[];try{let U=_.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n??0,W=_.query("SELECT COUNT(*) AS n FROM citations").get()?.n??0,X=_.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n??0,G=_.query(`SELECT wp.id, wp.path + updated_at = excluded.updated_at`,[RW("idx",`wiki-topic\x00${_.path}`),"wiki_topic",_.title,_.artifactUri,_.path,JSON.stringify({artifact_key:_.path,content_hash:_.contentHash}),_.now,_.now]),1}function Tn($){return $.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0]??"knowledge"}async function GE($){let _=$.now??new Date,J=_.toISOString();a($.dbPath);let U=m($.dbPath),W;try{W=fn(U,$)}finally{U.close()}if(W.length===0)throw Error("No source chunks matched wiki compile input.");let X=Cn($,W),Y=`wiki/generated/${CL(X)}.md`,Q=Pn(X,W,J),q=W.map((v)=>{let k=$E(v.metadata_json);return typeof k.source_ref==="string"?k.source_ref:v.source_uri}).filter((v)=>Boolean(v)),L=X6({generated_from:"wiki_compile",artifact_key:Y,source_refs:q}),N=await lG($.store,{key:Y,body:Q,content_type:"text/markdown",metadata:{generated_from:"wiki_compile"}}),R=RW("wiki",Y),B=W.map((v)=>({chunk_id:v.chunk_id,source_uri:v.source_uri??"unknown",quote:JE(v.text,240),start_offset:v.start_offset,end_offset:v.end_offset,metadata:{source_revision_id:v.source_revision_id,revision:v.revision,hash:v.hash,source_ref:$E(v.metadata_json).source_ref??v.source_uri}})),H=Tn(X),V=`wiki/concepts/${CL(H)}.md`,K=[`# ${H}`,"",`Related page: [[${Y}]]`,""].join(` +`),E=X6({generated_from:"wiki_compile_concept",artifact_key:V,source_refs:q}),F=await lG($.store,{key:V,body:K,content_type:"text/markdown",metadata:{generated_from:"wiki_compile_concept"}}),w=RW("wiki",V),A=await WE($.store,{ts:J,event:"wiki_compile_completed",page_key:Y,source_refs:q,chunks_seen:W.length},_),g=m($.dbPath);try{u4(g,[N,F,A],_),PL(g,{pageId:R,path:Y,title:X,artifactUri:N.uri,contentHash:N.hash??"",body:Q,provenance:L,now:J}),PL(g,{pageId:w,path:V,title:H,artifactUri:F.uri,contentHash:F.hash??"",body:K,provenance:E,now:J}),g.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) + VALUES (?, ?, ?, ?)`,[R,w,"concept",J]);let v=UE(g,R,B,J),k=XE(g,{title:X,path:Y,artifactUri:N.uri,contentHash:N.hash??"",now:J});return{page_id:R,path:Y,artifact_uri:N.uri,content_hash:N.hash??"",chunks_seen:W.length,citations_written:v,concept_page_id:w,indexes_updated:k,log_key:A.key,warnings:[]}}finally{g.close()}}async function YE($){if(!$.approveWrite)return{approved:!1,durable_writes_performed:!1,page_id:null,path:null,artifact_uri:null,citations_written:0,log_key:null,message:"Dry-run: answer filing requires --approve-write."};let _=$.now??new Date,J=_.toISOString(),U=$.prompt.length>80?`${$.prompt.slice(0,77)}...`:$.prompt,X=`wiki/answers/${CL(U)}.md`,G=$.context.citations,Y=[`# ${U}`,"",$.answer,"","## Citations","",...G.map((H,V)=>`- [C${V+1}] ${H.source_ref??H.source_uri??H.artifact_path??H.artifact_uri??"unknown"} ${H.hash?`(hash ${H.hash})`:""}`),""].join(` +`),Q=G.map((H)=>H.source_ref??H.source_uri).filter((H)=>Boolean(H)),q=X6({generated_from:"knowledge_answer",artifact_key:X,source_refs:Q}),L=await lG($.store,{key:X,body:Y,content_type:"text/markdown",metadata:{generated_from:"knowledge_answer"}}),N=await WE($.store,{ts:J,event:"wiki_answer_filed",page_key:X,prompt:$.prompt,citations:G.length},_),R=RW("wiki",X),B=m($.dbPath);try{u4(B,[L,N],_),PL(B,{pageId:R,path:X,title:U,artifactUri:L.uri,contentHash:L.hash??"",body:Y,provenance:q,now:J});let H=UE(B,R,G.map((V)=>({chunk_id:V.chunk_id,source_uri:V.source_uri??V.artifact_uri??"unknown",quote:V.quote,start_offset:V.start_offset,end_offset:V.end_offset,metadata:{source_ref:V.source_ref,artifact_path:V.artifact_path,revision:V.revision,hash:V.hash}})),J);return XE(B,{title:U,path:X,artifactUri:L.uri,contentHash:L.hash??"",now:J}),{approved:!0,durable_writes_performed:!0,page_id:R,path:X,artifact_uri:L.uri,citations_written:H,log_key:N.key,message:`Filed answer to ${X}`}}finally{B.close()}}function q2($,_){$.push(_)}function QE($){a($.dbPath);let _=m($.dbPath),J=[];try{let U=_.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n??0,W=_.query("SELECT COUNT(*) AS n FROM citations").get()?.n??0,X=_.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n??0,G=_.query(`SELECT wp.id, wp.path FROM wiki_pages wp LEFT JOIN citations c ON c.wiki_page_id = wp.id WHERE wp.status = 'active' AND wp.path LIKE 'wiki/generated/%' GROUP BY wp.id - HAVING COUNT(c.id) = 0`).all();for(let B of G)G_(J,{type:"missing_citation",severity:"error",page_id:B.id,path:B.path,message:"Generated wiki page has no citations."});let Q=_.query(`SELECT wp.id AS page_id, wp.path, c.source_uri, c.chunk_id + HAVING COUNT(c.id) = 0`).all();for(let B of G)q2(J,{type:"missing_citation",severity:"error",page_id:B.id,path:B.path,message:"Generated wiki page has no citations."});let Y=_.query(`SELECT wp.id AS page_id, wp.path, c.source_uri, c.chunk_id FROM citations c JOIN wiki_pages wp ON wp.id = c.wiki_page_id LEFT JOIN chunks ch ON ch.id = c.chunk_id - WHERE ch.metadata_json LIKE '%"stale":true%' OR ch.metadata_json LIKE '%"status":"stale"%' OR ch.metadata_json LIKE '%"status":"deleted"%'`).all();for(let B of Q)G_(J,{type:"stale_citation",severity:"warn",page_id:B.page_id,path:B.path,source_uri:B.source_uri,chunk_id:B.chunk_id??void 0,message:"Page cites a stale or deleted source chunk."});let Y=_.query(`SELECT lower(title) AS title, COUNT(*) AS n + WHERE ch.metadata_json LIKE '%"stale":true%' OR ch.metadata_json LIKE '%"status":"stale"%' OR ch.metadata_json LIKE '%"status":"deleted"%'`).all();for(let B of Y)q2(J,{type:"stale_citation",severity:"warn",page_id:B.page_id,path:B.path,source_uri:B.source_uri,chunk_id:B.chunk_id??void 0,message:"Page cites a stale or deleted source chunk."});let Q=_.query(`SELECT lower(title) AS title, COUNT(*) AS n FROM wiki_pages WHERE status = 'active' GROUP BY lower(title) - HAVING COUNT(*) > 1`).all();for(let B of Y)G_(J,{type:"duplicate_page",severity:"warn",message:`Duplicate active wiki title: ${B.title} (${B.n} pages).`});let q=_.query(`SELECT wp.id, wp.path + HAVING COUNT(*) > 1`).all();for(let B of Q)q2(J,{type:"duplicate_page",severity:"warn",message:`Duplicate active wiki title: ${B.title} (${B.n} pages).`});let q=_.query(`SELECT wp.id, wp.path FROM wiki_pages wp LEFT JOIN wiki_backlinks wb1 ON wb1.from_page_id = wp.id LEFT JOIN wiki_backlinks wb2 ON wb2.to_page_id = wp.id WHERE wp.status = 'active' AND wp.path NOT IN ('wiki/README.md') GROUP BY wp.id - HAVING COUNT(wb1.to_page_id) = 0 AND COUNT(wb2.from_page_id) = 0`).all();for(let B of q)G_(J,{type:"orphan_page",severity:"info",page_id:B.id,path:B.path,message:"Wiki page has no backlinks."});let L=_.query(`SELECT wp.id AS page_id, wp.path, c.source_uri + HAVING COUNT(wb1.to_page_id) = 0 AND COUNT(wb2.from_page_id) = 0`).all();for(let B of q)q2(J,{type:"orphan_page",severity:"info",page_id:B.id,path:B.path,message:"Wiki page has no backlinks."});let L=_.query(`SELECT wp.id AS page_id, wp.path, c.source_uri FROM citations c JOIN wiki_pages wp ON wp.id = c.wiki_page_id LEFT JOIN sources s ON s.uri = c.source_uri - WHERE s.id IS NULL AND c.source_uri NOT LIKE 'file://%' AND c.source_uri NOT LIKE 's3://%' AND c.source_uri NOT LIKE 'https://%' AND c.source_uri NOT LIKE 'open-files://%'`).all();for(let B of L)G_(J,{type:"unresolved_source_ref",severity:"error",page_id:B.page_id,path:B.path,source_uri:B.source_uri,message:"Citation source URI cannot be resolved to a known or allowed source ref."});let N=_.query("SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'").all();for(let B of N)G_(J,{type:"contradiction_marker",severity:"warn",page_id:B.id,path:B.path,message:"Page metadata contains a contradiction marker."});let F=_.query(`SELECT c.id AS chunk_id, s.uri AS source_uri + WHERE s.id IS NULL AND c.source_uri NOT LIKE 'file://%' AND c.source_uri NOT LIKE 's3://%' AND c.source_uri NOT LIKE 'https://%' AND c.source_uri NOT LIKE 'open-files://%'`).all();for(let B of L)q2(J,{type:"unresolved_source_ref",severity:"error",page_id:B.page_id,path:B.path,source_uri:B.source_uri,message:"Citation source URI cannot be resolved to a known or allowed source ref."});let N=_.query("SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'").all();for(let B of N)q2(J,{type:"contradiction_marker",severity:"warn",page_id:B.id,path:B.path,message:"Page metadata contains a contradiction marker."});let R=_.query(`SELECT c.id AS chunk_id, s.uri AS source_uri FROM chunks c JOIN source_revisions sr ON sr.id = c.source_revision_id JOIN sources s ON s.id = sr.source_id @@ -992,7 +1093,7 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| WHERE c.kind = 'source' GROUP BY c.id HAVING COUNT(cit.id) = 0 - LIMIT 25`).all();for(let B of F)G_(J,{type:"new_article_candidate",severity:"info",chunk_id:B.chunk_id,source_uri:B.source_uri??void 0,message:"Source chunk is indexed but not cited by any wiki page yet."});return{ok:J.every((B)=>B.severity!=="error"),issue_count:J.length,issues:J,counts:{active_pages:U,citations:W,backlinks:X,new_article_candidates:F.length}}}finally{_.close()}}import{createHash as Xc}from"crypto";function Gc($){let _=String($.getUTCFullYear()),J=String($.getUTCMonth()+1).padStart(2,"0"),U=String($.getUTCDate()).padStart(2,"0");return{year:_,month:J,day:U}}function ML($,_){return`${$}_${Xc("sha256").update(_).digest("hex").slice(0,20)}`}function Qc($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function Yc(){return`# Knowledge Agent Schema v1 + LIMIT 25`).all();for(let B of R)q2(J,{type:"new_article_candidate",severity:"info",chunk_id:B.chunk_id,source_uri:B.source_uri??void 0,message:"Source chunk is indexed but not cited by any wiki page yet."});return{ok:J.every((B)=>B.severity!=="error"),issue_count:J.length,issues:J,counts:{active_pages:U,citations:W,backlinks:X,new_article_candidates:R.length}}}finally{_.close()}}import{createHash as Sn}from"crypto";function Zn($){let _=String($.getUTCFullYear()),J=String($.getUTCMonth()+1).padStart(2,"0"),U=String($.getUTCDate()).padStart(2,"0");return{year:_,month:J,day:U}}function TL($,_){return`${$}_${Sn("sha256").update(_).digest("hex").slice(0,20)}`}function vn($){let _=$.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(_*1.25))}function yn(){return`# Knowledge Agent Schema v1 ## Source Rules @@ -1017,7 +1118,7 @@ ${$.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| ## Lint Rules - Flag stale pages, missing citations, contradictions, orphan pages, duplicate pages, and unresolved source refs. -`}function qc(){return`# Knowledge Index +`}function hn(){return`# Knowledge Index This is a compact orientation index for agents. It is not the full search index. @@ -1032,19 +1133,19 @@ This is a compact orientation index for agents. It is not the full search index. Raw source files are resolved through open-files. This app stores source refs, citations, chunks, generated wiki artifacts, indexes, and run records. -`}function dK(){return`# Wiki +`}function qE(){return`# Wiki Generated durable knowledge pages live here. Pages should be concise, cited, and organized for both humans and agents. -`}async function cK($,_=new Date){let{year:J,month:U,day:W}=Gc(_),X="schemas/v1.md",G="indexes/root.md",Q="wiki/README.md",Y=`logs/${J}/${U}/${W}.jsonl`,q={ts:_.toISOString(),event:"wiki_layout_initialized",schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md"},L=[{key:"schemas/v1.md",body:Yc(),content_type:"text/markdown"},{key:"indexes/root.md",body:qc(),content_type:"text/markdown"},{key:"wiki/README.md",body:dK(),content_type:"text/markdown"},{key:Y,body:`${JSON.stringify(q)} -`,content_type:"application/x-ndjson"}],N=await Promise.all(L.map(async(F)=>{let B=await $.put(F);return{key:B.key,uri:B.uri,kind:G3(F.key),content_type:F.content_type,modified_at:B.modified_at,metadata:{provenance:v4({generated_from:"wiki_layout_init",artifact_key:F.key,citation_required:F.key.startsWith("wiki/")||F.key.startsWith("indexes/")})},...EJ(F.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:Y,artifacts:N,written:["schemas/v1.md","indexes/root.md","wiki/README.md",Y]}}function AL($){let _=$.metadata?.provenance;if(_&&typeof _==="object"&&!Array.isArray(_))return _;return v4({generated_from:"wiki_layout_init",artifact_key:$.key})}function zc($,_,J,U,W,X){let G=AL(U),Q=ML("chk",`${_}\x00${U.hash??U.uri}`),Y=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_);for(let q of Y)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[q.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_]),$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[Q,_,"wiki",0,W,Qc(W),0,W.length,JSON.stringify({artifact_key:U.key,artifact_uri:U.uri,content_hash:U.hash??null,provenance:G}),X]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[Q,W,J,U.uri])}function lK($,_,J=new Date){let U=J.toISOString(),W=_.find((G)=>G.key.endsWith("indexes/root.md")),X=_.find((G)=>G.key.endsWith("wiki/README.md"));if(W)$.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) +`}async function zE($,_=new Date){let{year:J,month:U,day:W}=Zn(_),X="schemas/v1.md",G="indexes/root.md",Y="wiki/README.md",Q=`logs/${J}/${U}/${W}.jsonl`,q={ts:_.toISOString(),event:"wiki_layout_initialized",schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md"},L=[{key:"schemas/v1.md",body:yn(),content_type:"text/markdown"},{key:"indexes/root.md",body:hn(),content_type:"text/markdown"},{key:"wiki/README.md",body:qE(),content_type:"text/markdown"},{key:Q,body:`${JSON.stringify(q)} +`,content_type:"application/x-ndjson"}],N=await Promise.all(L.map(async(R)=>{let B=await $.put(R);return{key:B.key,uri:B.uri,kind:V3(R.key),content_type:R.content_type,modified_at:B.modified_at,metadata:{provenance:X6({generated_from:"wiki_layout_init",artifact_key:R.key,citation_required:R.key.startsWith("wiki/")||R.key.startsWith("indexes/")})},...IJ(R.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:Q,artifacts:N,written:["schemas/v1.md","indexes/root.md","wiki/README.md",Q]}}function SL($){let _=$.metadata?.provenance;if(_&&typeof _==="object"&&!Array.isArray(_))return _;return X6({generated_from:"wiki_layout_init",artifact_key:$.key})}function mn($,_,J,U,W,X){let G=SL(U),Y=TL("chk",`${_}\x00${U.hash??U.uri}`),Q=$.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(_);for(let q of Q)$.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[q.id]);$.run("DELETE FROM chunks WHERE wiki_page_id = ?",[_]),$.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[Y,_,"wiki",0,W,vn(W),0,W.length,JSON.stringify({artifact_key:U.key,artifact_uri:U.uri,content_hash:U.hash??null,provenance:G}),X]),$.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[Y,W,J,U.uri])}function jE($,_,J=new Date){let U=J.toISOString(),W=_.find((G)=>G.key.endsWith("indexes/root.md")),X=_.find((G)=>G.key.endsWith("wiki/README.md"));if(W)$.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(kind, name, shard_key) DO UPDATE SET artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[ML("idx","root:indexes/root.md"),"root","root",W.uri,"root",JSON.stringify({artifact_key:W.key,content_hash:W.hash??null,provenance:AL(W)}),U,U]);if(X){let G=ML("wiki","wiki/README.md");$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + updated_at = excluded.updated_at`,[TL("idx","root:indexes/root.md"),"root","root",W.uri,"root",JSON.stringify({artifact_key:W.key,content_hash:W.hash??null,provenance:SL(W)}),U,U]);if(X){let G=TL("wiki","wiki/README.md");$.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET title = excluded.title, @@ -1052,13 +1153,13 @@ Pages should be concise, cited, and organized for both humans and agents. content_hash = excluded.content_hash, status = excluded.status, metadata_json = excluded.metadata_json, - updated_at = excluded.updated_at`,[G,"wiki/README.md","Wiki",X.uri,X.hash??null,"active",JSON.stringify({artifact_key:X.key,provenance:AL(X)}),U,U]),zc($,G,"Wiki",X,dK(),U)}}import{createHash as nK}from"crypto";import{cpSync as fL,chmodSync as EL,existsSync as c4,lstatSync as tK,mkdirSync as u5,readdirSync as CL,readFileSync as uX,renameSync as jc,rmSync as c5,writeFileSync as iK}from"fs";import{dirname as wL,join as a0,relative as Oc}from"path";function IL($,_=$){if(!c4($))return[];let J=tK($);if(J.isFile())return[Oc(_,$)||"."];if(!J.isDirectory())return[];return CL($).flatMap((U)=>IL(a0($,U),_)).sort()}function rK($,_){if(_.length===0)return{sha256:null,bytes:0};let J=nK("sha256"),U=0;for(let W of _){let X=a0($,W),G=uX(X),Q=nK("sha256").update(G).digest("hex");U+=G.byteLength,J.update(W),J.update("\x00"),J.update(Q),J.update("\x00")}return{sha256:J.digest("hex"),bytes:U}}function Dc($){if(!c4($))return null;let _=JSON.parse(uX($,"utf8"));return Array.isArray(_.items)?_.items.length:null}function Lc($){if(!c4($))return{exists:!1,integrity_check:null,table_counts:{}};let _=nN($);try{let J=_.query("PRAGMA integrity_check").get(),U=J?Object.values(J)[0]??null:null,W=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),X={};for(let G of W){let Q=`"${G.name.replaceAll('"','""')}"`,Y=_.query(`SELECT COUNT(*) AS n FROM ${Q}`).get();X[G.name]=Y?.n??0}return{exists:!0,integrity_check:U,table_counts:X}}finally{_.close()}}function v6($,_={}){let J=IL($.home),U=rK($.home,J),W=IL($.artifactsDir),X=rK($.artifactsDir,W),G=c4($.knowledgeDbPath);return{path:$.home,exists:c4($.home),file_count:J.length,total_bytes:U.bytes,tree_sha256:U.sha256,json_items:Dc($.jsonStorePath),sqlite:_.includeSqlite===!1?{exists:G,integrity_check:null,table_counts:{}}:Lc($.knowledgeDbPath),artifacts:{exists:c4($.artifactsDir),file_count:W.length,total_bytes:X.bytes,tree_sha256:X.sha256},files:J}}function Bc($,_){if(!_.exists)return!0;if(_.files.filter((U)=>U!=="config.json").length>0)return!1;if(!_.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(uX($.configPath,"utf8")))===JSON.stringify(yW())}catch{return!1}}function gL($,_){return $.file_count===_.file_count&&$.total_bytes===_.total_bytes&&$.tree_sha256===_.tree_sha256&&$.json_items===_.json_items&&$.sqlite.integrity_check===_.sqlite.integrity_check&&JSON.stringify($.sqlite.table_counts)===JSON.stringify(_.sqlite.table_counts)&&$.artifacts.file_count===_.artifacts.file_count&&$.artifacts.total_bytes===_.artifacts.total_bytes&&$.artifacts.tree_sha256===_.artifacts.tree_sha256}function d5($){return $.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function kL($){if(Array.isArray($))return`[${$.map(kL).join(",")}]`;if($&&typeof $==="object")return`{${Object.entries($).sort(([_],[J])=>_.localeCompare(J)).map(([_,J])=>`${JSON.stringify(_)}:${kL(J)}`).join(",")}}`;return JSON.stringify($)}function pK($){return kL($)}function bL($){return typeof $.short_id==="string"&&$.short_id.trim().length>0?$.short_id:null}function Q_($){if(!c4($))return{items:[]};let _=JSON.parse(uX($,"utf8"));if(!_||!Array.isArray(_.items))throw Error(`Invalid knowledge JSON store shape at ${$}`);return{items:_.items}}function oK($,_){let J=new Map($.items.map((L)=>[L.id,L])),U=new Map;for(let L of $.items){let N=U.get(L.id);if(N&&N.item.id!==L.id);U.set(L.id,{item:L,keyKind:"id",source:"current"});let F=bL(L);if(F&&!U.has(F))U.set(F,{item:L,keyKind:"short_id",source:"current"})}let W=[],X=0,G=0,Q=0,Y=[];for(let L of _.items){let N=J.get(L.id);if(N){if(pK(N)===pK(L))X+=1;else G+=1,W.push({type:"id_conflict",id:L.id,legacy_title:L.title,current_title:N.title});continue}let F=[{key:L.id,keyKind:"id"},...bL(L)?[{key:bL(L),keyKind:"short_id"}]:[]],B=!1;for(let{key:H,keyKind:V}of F){let R=U.get(H);if(!R)continue;if(V==="id"&&R.keyKind==="id")G+=1,W.push({type:"id_conflict",id:H,legacy_id:L.id,current_id:R.item.id,legacy_title:L.title,current_title:R.item.title});else Q+=1,W.push({type:"short_id_conflict",id:H,legacy_id:L.id,current_id:R.item.id,legacy_title:L.title,current_title:R.item.title});B=!0}if(B)continue;Y.push(L);for(let{key:H,keyKind:V}of F)U.set(H,{item:L,keyKind:V,source:"legacy"})}let q={items:[...$.items,...Y]};return{stats:{current_items:$.items.length,legacy_items:_.items.length,duplicate_ids_identical:X,duplicate_ids_conflicting:G,short_id_conflicts:Q,stranded_items:Y.length,merged_items:W.length===0?Y.length:0,expected_total_items:$.items.length+Y.length,final_items:null},conflicts:W,mergedStore:q}}function Hc($,_){let J=[...new Set($)].sort(),U=(W)=>{if(W>=J.length)return _();return e4(J[W],()=>U(W+1),{createParent:!0})};return U(0)}function aK($){let _=$.now??new Date,J=$.approveWrite!==!0,U=v6($.legacy),W=v6($.current),X={legacy_exists:U.exists,legacy_store_exists:c4($.legacy.jsonStorePath),current_store_exists:c4($.current.jsonStorePath),approval_present:$.approveWrite===!0&&Boolean($.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},G=[];if(!U.exists||!X.legacy_store_exists)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:U,current_before:W,backup_after:null,current_after:W,merge:{current_items:Q_($.current.jsonStorePath).items.length,legacy_items:0,duplicate_ids_identical:0,duplicate_ids_conflicting:0,short_id_conflicts:0,stranded_items:0,merged_items:0,expected_total_items:Q_($.current.jsonStorePath).items.length,final_items:W.json_items},conflicts:[],checks:{...X,no_conflicts:!0,final_count_matches_expected:!0},warnings:G,message:`No legacy knowledge JSON store found at ${$.legacy.jsonStorePath}`};let Q=Q_($.current.jsonStorePath),Y=Q_($.legacy.jsonStorePath),q=oK(Q,Y);if(X.no_conflicts=q.conflicts.length===0,q.conflicts.length>0)G.push("merge_conflicts_detected");if(!X.approval_present)G.push("write_approval_required");if(J||!X.approval_present||q.conflicts.length>0)return{ok:q.conflicts.length===0,dry_run:!0,approval_required:!X.approval_present,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:`${$.legacy.home}.merge-backup-${d5(_)}`,legacy_before:U,current_before:W,backup_after:null,current_after:null,merge:q.stats,conflicts:q.conflicts,checks:X,warnings:G,message:q.conflicts.length===0?`Dry run: would merge ${q.stats.stranded_items} legacy item(s) into ${$.current.jsonStorePath}`:`Refusing legacy merge with ${q.conflicts.length} conflict(s)`};return Hc([$.current.jsonStorePath,$.legacy.jsonStorePath],()=>{let L=Q_($.current.jsonStorePath),N=Q_($.legacy.jsonStorePath),F=oK(L,N);if(X.no_conflicts=F.conflicts.length===0,F.conflicts.length>0)return{ok:!1,dry_run:!0,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:v6($.legacy),current_before:v6($.current),backup_after:null,current_after:null,merge:F.stats,conflicts:F.conflicts,checks:X,warnings:[...G,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${F.conflicts.length} conflict(s)`};if(F.stats.stranded_items===0)return F.stats.final_items=L.items.length,X.final_count_matches_expected=L.items.length===F.stats.expected_total_items,{ok:X.no_conflicts&&X.final_count_matches_expected,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:v6($.legacy),current_before:v6($.current),backup_after:null,current_after:v6($.current),merge:F.stats,conflicts:[],checks:X,warnings:G,message:`Legacy merge already up to date for ${$.current.jsonStorePath}`};let B=`${$.legacy.home}.merge-backup-${d5(_)}`;u5(wL(B),{recursive:!0}),fL($.legacy.home,B,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let H=a6(B),V=v6(H);if(X.legacy_backup_written=gL(v6($.legacy),V),!X.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${B}`);R0($.current.jsonStorePath,F.mergedStore);let R=Q_($.current.jsonStorePath);F.stats.final_items=R.items.length,X.final_count_matches_expected=R.items.length===F.stats.expected_total_items;let M=v6($.current),K=X.legacy_backup_written&&X.no_conflicts&&X.final_count_matches_expected;return{ok:K,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:B,legacy_before:U,current_before:W,backup_after:V,current_after:M,merge:F.stats,conflicts:[],checks:X,warnings:G,message:K?`Merged ${F.stats.merged_items} legacy item(s) into ${$.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${$.current.jsonStorePath}`}})}function Nc($){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,$)}function PL($){return $ instanceof Error&&/\b(EBUSY|EPERM)\b/.test($.message)}function Vc($){let _;for(let J=0;J<8;J+=1)try{c5($,{recursive:!0,force:!1});return}catch(U){if(_=U,!PL(U))throw U;Nc(50*(J+1))}throw _}function sK($){if(!c4($))return;let _=tK($);if(EL($,_.isDirectory()?448:384),!_.isDirectory())return;for(let J of CL($))sK(a0($,J))}function Fc($){return $==="TOMBSTONE.md"||$==="migration.json"||$==="knowledge.db"||$==="knowledge.db-shm"||$==="knowledge.db-wal"||$==="knowledge.db-journal"}function Rc($){for(let _ of CL($)){if(_==="TOMBSTONE.md"||_==="migration.json")continue;try{c5(a0($,_),{recursive:!0,force:!1})}catch(J){if(!PL(J)||!_.startsWith("knowledge.db"))throw J}}}function Kc($,_){try{jc($,_);return}catch(J){fL($,_,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{Vc($)}catch(U){if(PL(U)){Rc($);return}throw c5(_,{recursive:!0,force:!0}),U}if(J instanceof Error&&J.message.includes("EXDEV"))return}}function Mc($,_,J){if(!_.exists)return!1;if(!_.files.includes("TOMBSTONE.md")||!_.files.includes("migration.json"))return!1;if(_.files.some((U)=>!Fc(U)))return!1;try{let U=JSON.parse(uX(a0($.home,"migration.json"),"utf8"));return U.new_path===J&&typeof U.backup_path==="string"}catch{return!1}}function eK($){let _=$.now??new Date,J=$.approveWrite!==!0,U=v6($.current),W=Bc($.current,U),X=$.approveWrite===!0&&Boolean($.approvedBy)&&(!U.exists||W),G=v6($.legacy,{includeSqlite:!X}),Q={legacy_exists:G.exists,current_absent_or_default_scaffold:!U.exists||W,approval_present:$.approveWrite===!0&&Boolean($.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},Y=[];if(!G.exists)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,tombstone_path:null,legacy_before:G,current_before:U,backup_after:null,current_after:null,checks:Q,warnings:Y,message:`No legacy knowledge workspace found at ${$.legacy.home}`};if(Q.legacy_is_tombstone=Mc($.legacy,G,$.current.home),Q.legacy_is_tombstone)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,tombstone_path:a0($.legacy.home,"TOMBSTONE.md"),legacy_before:G,current_before:U,backup_after:null,current_after:U,checks:{...Q,tombstone_written:!0},warnings:Y,message:`Legacy knowledge workspace already migrated to ${$.current.home}`};if(!Q.current_absent_or_default_scaffold)Y.push("current_workspace_contains_data");if(!Q.approval_present)Y.push("write_approval_required");if(J||!Q.current_absent_or_default_scaffold||!Q.approval_present)return{ok:Q.current_absent_or_default_scaffold,dry_run:!0,approval_required:!0,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:`${$.legacy.home}.backup-${d5(_)}`,tombstone_path:a0($.legacy.home,"TOMBSTONE.md"),legacy_before:G,current_before:U,backup_after:null,current_after:null,checks:Q,warnings:Y,message:Q.current_absent_or_default_scaffold?`Dry run: would migrate ${$.legacy.home} to ${$.current.home}`:`Cannot migrate while ${$.current.home} contains data`};let q=`${$.legacy.home}.backup-${d5(_)}`;u5(wL($.current.home),{recursive:!0}),u5(wL(q),{recursive:!0}),fL($.legacy.home,q,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),sK(q);let L=a6(q),N=v6(L,{includeSqlite:!1});if(Q.backup_matches_legacy=gL(G,N),!Q.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${q}`);if(U.exists&&W)c5($.current.home,{recursive:!0,force:!0});Kc($.legacy.home,$.current.home);let F=v6($.current,{includeSqlite:!1});Q.migrated_matches_backup=gL(N,F);let B=v6(L),H=v6($.current),V={...B,path:$.legacy.home};u5($.legacy.home,{recursive:!0});let R=a0($.legacy.home,"TOMBSTONE.md");iK(R,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${_.toISOString()}`,`Approved by: ${$.approvedBy}`,`New path: ${$.current.home}`,`Backup path: ${q}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` -`),{mode:384}),EL(R,384);let M=a0($.legacy.home,"migration.json");iK(M,`${JSON.stringify({migrated_at:_.toISOString(),approved_by:$.approvedBy,new_path:$.current.home,backup_path:q,legacy_before:V,backup_after:B,current_after:H},null,2)} -`,{mode:384}),EL(M,384),Q.tombstone_written=c4(R);let K=Q.backup_matches_legacy&&Q.migrated_matches_backup&&Q.tombstone_written;return{ok:K,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:q,tombstone_path:R,legacy_before:V,current_before:U,backup_after:B,current_after:H,checks:Q,warnings:Y,message:K?`Migrated legacy knowledge workspace to ${$.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${$.current.home}`}}function wc($){let _=LM($);if(e$($M(_,"knowledge.db"))||e$($M(_,"config.json")))return K_(_);return K_(a6(jQ(_)).home)}function TL($){return`${Ec()}:${cX("sha256").update($.home).digest("hex").slice(0,12)}`}function vL($){return`'${$.replace(/'/g,"'\\''")}'`}function Ic($){return["knowledge",...$].map(vL).join(" ")}function _M($,_){return`cd ${vL($)} && knowledge ${_.map(vL).join(" ")}`}function BM($){return!$||$==="local"||$==="localhost"}function dX($,_){return{source:$.source,adapter:$.adapter,project_root:_,project_root_source:$.project_root_source,workspace_root:$.workspace_root,workspace_root_source:$.workspace_root_source,open_files_root:$.open_files_root,open_files_root_source:$.open_files_root_source,trust_status:$.trust_status,auth_status:$.auth_status,current:$.current,primary:$.primary,diagnostics:$.diagnostics,repair_hints:$.repair_hints,evidence:$.evidence,cacheability:$.cacheability,warnings:$.warnings}}function SL($){return{source:$.source,adapter:$.adapter,target:$.target,route:$.route,target_kind:$.targetKind,confidence:$.confidence,evidence:$.evidence,cacheability:$.cacheability}}function gc($){try{let _=JSON.parse($);return Array.isArray(_)?_.filter((J)=>typeof J==="string"):[]}catch{return[]}}function lX($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function M6($){return typeof $==="string"&&$.length>0?$:null}function kc($){return typeof $==="number"&&Number.isFinite($)?$:null}function l5($){return typeof $==="boolean"?$:null}function fc($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function HM($,_,J){let U=lX($),W=M6(U.observed_at)??M6(_[`${J}_observed_at`]),X=M6(U.source_authority)??M6(_[`${J}_source_authority`]);if(!W||!X)return null;return{observed_at:W,verified_at:M6(U.verified_at),expires_at:M6(U.expires_at)??M6(_[`${J}_expires_at`]),ttl_ms:kc(U.ttl_ms),source_authority:X,confidence:M6(U.confidence)??(J==="route"?M6(_.route_confidence):null),cacheable:l5(U.cacheable)??l5(_[`${J}_cacheable`])??!1,stale:l5(U.stale)??l5(_[`${J}_stale`])??!1,reasons:fc(U.reasons)}}function Cc($,_){return $.machine_id===_||$.hostname===_||$.ssh_target===_||$.tailscale_dns===_||gc($.tailscale_ips_json).includes(_)}function JM($,_){return tY($).find((J)=>Cc(J,_))??null}function NM($){return lX(LW($.metadata_json).resolver_evidence)}function nX($){return lX(LW($.capabilities_json).resolver)}function VM($){let _=nX($),J=M6(_.route_kind);if(J==="local"||J==="lan"||J==="tailscale"||J==="ssh"||J==="unknown")return J;if($.tailscale_dns&&$.ssh_target===$.tailscale_dns)return"tailscale";return $.ssh_target?"ssh":"unknown"}function Pc($){let _=nX($),J=M6(_.route_target_kind);if(J==="local"||J==="lan"||J==="tailscale"||J==="ssh"||J==="unknown")return J;return VM($)}function Tc($){return M6(nX($).route_confidence)??"medium"}function WM($,_,J){let U=NM($),W=lX(U.route),X=nX($);return{target:$.ssh_target??$.tailscale_dns??$.hostname??$.machine_id,route:VM($),targetKind:Pc($),confidence:Tc($),source:"registry",adapter:J.adapter,evidence:{registry:!0,requested_machine_id:_,machine_id:$.machine_id,recorded_at:$.updated_at,route:W},cacheability:HM(W.cacheability,X,"route")??J.cacheability,warnings:[...new Set([...J.warnings,"registry_route_fallback"])]}}function UM($,_,J){if(!$.workspace_home)return null;let U=NM($),W=lX(U.workspace),X=nX($);return{ok:!0,source:"registry",adapter:J.adapter,requested_machine_id:_,machine_id:$.machine_id,project_id:M6(W.project_id)??J.project_id,repo_name:M6(W.repo_name)??J.repo_name,project_root:$.workspace_home,project_root_source:M6(X.project_root_source)??"registry",workspace_root:M6(W.workspace_root),workspace_root_source:M6(X.workspace_root_source)??"registry",open_files_root:M6(W.open_files_root),open_files_root_source:M6(X.open_files_root_source)??"registry",trust_status:M6(X.trust_status)??"unknown",auth_status:M6(X.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:_,machine_id:$.machine_id,recorded_at:$.updated_at,workspace:W},cacheability:HM(W.cacheability,X,"workspace")??J.cacheability,warnings:[...new Set([...J.warnings,"registry_workspace_fallback"])]}}function XM($){if(!$)return null;let _=$.diagnostics.filter((U)=>U.severity!=="ok"),J=$.repair_hints[0];if(!_.length&&!$.warnings.length&&!J)return null;return[_.length?`workspace diagnostics: ${_.map((U)=>`${U.id}=${U.status}`).join(", ")}`:null,$.warnings.length?`warnings: ${$.warnings.join(", ")}`:null,J?`repair: ${J.shell_command}`:null].filter(Boolean).join("; ")}function n5($){return{id:$.id,reason:$.reason,command:["knowledge",...$.args],shell_command:Ic($.args)}}function i5($,_){let J=i($);try{return Number(J.query(_).get()?.count??0)}finally{J.close()}}function Sc($,_){let J=i5($,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),U=i5($,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),W=i5($,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),X=i5($,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),G=X===0;return{ok:G,source_of_truth:"open-files",configured_root:_?.open_files_root??null,configured_root_source:_?.open_files_root_source??null,source_refs:{open_files:J,metadata_mentions:U},extracted_text_artifacts:W,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:X,message:G?`${J} open-files source ref(s); raw source bytes remain owned by open-files`:`${X} raw source payload metadata sentinel(s) found`}}var Zc=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function yL($,_=0){if(_>8)return!1;if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some((J)=>yL(J,_+1));for(let[J,U]of Object.entries($)){if(Zc.has(J.toLowerCase()))return!0;if(yL(U,_+1))return!0}return!1}function LW($){try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function GM($,_=20,J=200){if(!Number.isFinite($)||$<=0)return _;return Math.min(Math.floor($),J)}function vc($,_=220){let J=$??"";return J.length>_?`${J.slice(0,_)}...`:J}function F4($,_=["metadata_json"]){return $.map((J)=>{let U={...J};for(let W of _){let X=U[W];if(typeof X==="string"){let G=W.endsWith("_json")?W.slice(0,-5):W;U[G]=LW(X),delete U[W]}}return U})}function Y4($,_,J=[]){return $.query(_).all(...J)}function yc($){if(!e$($))return{exists:!1,read_error:null,items:[]};try{let _=JSON.parse(bc($,"utf8"));if(!_||!Array.isArray(_.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:_.items}}catch(_){return{exists:!0,read_error:_ instanceof Error?_.message:String(_),items:[]}}}function QM($){return{id:$.id,short_id:$.short_id??null,title:$.title,content_preview:vc($.content),url:$.url??null,tags:$.tags??[],metadata:$.metadata??{},archived:$.archived===!0,created_at:$.created_at,updated_at:$.updated_at}}function YM(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0}}function FM($,_,J=!1){return{query:$,limit:_,offset:0,mode:{keyword:!0,catalog:!0,semantic:J},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function hc($){return $.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function mc($,_,J=!1){let U=FM($,_,J);return{query:$,normalized_query:hc($),created_at:new Date().toISOString(),mode:U.mode,warnings:U.warnings,search_counts:U.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function ZL($,_,J){let U=J??_.jsonStorePath;if(e$(U))return U;if($==="global"){let W=vW();if(e$(W))return W}return U}function xc($){let _=JSON.stringify($);return Math.max(1,Math.ceil(_.length/4))}function hL($,_){let J=($??"").normalize("NFKC").trim().replace(/\s+/g," ");if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-1)).trim()}...`}function qM($,_,J){let U=i6(hL($,J),_);return{text:U.text,redactions:U.findings.length}}function zM($,_,J){let U=$.now??new Date,W=$.source??"search",X=$.purpose??(W==="loops"||W==="runs"?"proposal":"agent_context"),G=($.query??$.topic??_.query).normalize("NFKC").trim().replace(/\s+/g," "),Q=Math.max(1,Math.min($.maxItems??$.limit??8,50)),Y=Math.max(500,Math.min($.maxTokens??6000,1e5)),q=0,L=_.citations.slice(0,Math.max(Q*2,Q)).map((K,w)=>{let b=qM(K.quote,J,w<3?220:140);q+=b.redactions;let I=K.source_ref??K.source_uri??K.artifact_path??K.artifact_uri??K.id;return{id:`cite_${cX("sha256").update(`${K.id}\x00${I}`).digest("hex").slice(0,12)}`,kind:K.artifact_uri||K.artifact_path?"artifact":"source",ref:I,source_ref:K.source_ref,source_uri:K.source_uri,artifact_uri:K.artifact_uri,artifact_path:K.artifact_path,run_id:null,run_event_id:null,revision:K.revision,hash:K.hash,chunk_id:K.chunk_id,offsets:{start:K.start_offset,end:K.end_offset},quote_preview:b.text}}),N=new Map(_.citations.map((K,w)=>[K.id,L[w]])),F=_.excerpts.slice(0,Math.max(Q*2,Q)).map((K)=>{let w=_.results.find((v)=>v.id===K.result_id),b=K.citation_id?N.get(K.citation_id):void 0,I=qM(K.text,J,520);return q+=I.redactions,{id:`ev_${cX("sha256").update(`${K.kind}\x00${K.result_id}\x00${K.citation_id??""}`).digest("hex").slice(0,14)}`,kind:K.kind,title:hL(w?.title??b?.ref??K.kind,100),text_preview:I.text,score:Number(K.score.toFixed(6)),citation_ids:b?[b.id]:[],provenance:{source:W,record_ref:`${K.kind}:${K.result_id}`,created_at:_.created_at,updated_at:null,metadata_keys:[]}}}).sort((K,w)=>w.score-K.score||K.id.localeCompare(w.id)).slice(0,Q),B=new Set(F.flatMap((K)=>K.citation_ids)),H=L.filter((K)=>B.has(K.id)),V=Array.from(new Set(_.warnings)),R=`ctx_${cX("sha256").update([W,X,G,V.join(","),F.map((K)=>K.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,M={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:U.toISOString(),source:W,purpose:X,query:G,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:R,budgets:{max_tokens:Y,estimated_tokens:0,max_items:Q,items_included:F.length,items_available:_.excerpts.length,items_truncated:Math.max(0,_.excerpts.length-F.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:q,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:H,evidence:F,duplicate_candidates:[],outline:{title:G?`Knowledge context: ${hL(G,80)}`:"Knowledge context",bullets:F.length>0?F.slice(0,5).map((K)=>`${K.id}: ${K.title}`):["No matching bounded evidence was found."],evidence_ids:F.slice(0,8).map((K)=>K.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:V,message:`${F.length} bounded evidence item(s), estimated under ${Y} token(s)`};return M.budgets.estimated_tokens=xc(M),M.budgets.token_budget_exceeded=M.budgets.estimated_tokens>Y,M.message=`${M.evidence.length} bounded evidence item(s), estimated ${M.budgets.estimated_tokens}/${Y} token(s)`,M}function uc(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function dc(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function cc($){return{ok:!0,scope:$.scope,workspace_home:$.workspaceHome,sqlite_schema_version:0,local_machine_id:$.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function jM($){let _=$.now??new Date,J=$.source??"search",U=$.purpose??(J==="loops"||J==="runs"?"proposal":"agent_context"),W=($.query??$.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),X=Math.max(1,Math.min($.maxItems??$.limit??8,50)),G=Math.max(500,Math.min($.maxTokens??6000,1e5)),Q=`ctx_${cX("sha256").update(["empty",J,U,W,$.topic??"",$.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:_.toISOString(),source:J,purpose:U,query:W,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:Q,budgets:{max_tokens:G,estimated_tokens:0,max_items:X,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:W?`Context for ${W}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${G} token(s)`}}function mL($){let _=$.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return _?`${_}/`:null}function lc($,_){let J=i($);try{let U=J.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json + updated_at = excluded.updated_at`,[G,"wiki/README.md","Wiki",X.uri,X.hash??null,"active",JSON.stringify({artifact_key:X.key,provenance:SL(X)}),U,U]),mn($,G,"Wiki",X,qE(),U)}}import{createHash as DE}from"crypto";import{cpSync as uL,chmodSync as vL,existsSync as c6,lstatSync as NE,mkdirSync as rG,readdirSync as dL,readFileSync as lX,renameSync as xn,rmSync as oG,writeFileSync as OE}from"fs";import{dirname as yL,join as e4,relative as un}from"path";function hL($,_=$){if(!c6($))return[];let J=NE($);if(J.isFile())return[un(_,$)||"."];if(!J.isDirectory())return[];return dL($).flatMap((U)=>hL(e4($,U),_)).sort()}function LE($,_){if(_.length===0)return{sha256:null,bytes:0};let J=DE("sha256"),U=0;for(let W of _){let X=e4($,W),G=lX(X),Y=DE("sha256").update(G).digest("hex");U+=G.byteLength,J.update(W),J.update("\x00"),J.update(Y),J.update("\x00")}return{sha256:J.digest("hex"),bytes:U}}function dn($){if(!c6($))return null;let _=JSON.parse(lX($,"utf8"));return Array.isArray(_.items)?_.items.length:null}function nn($){if(!c6($))return{exists:!1,integrity_check:null,table_counts:{}};let _=W3($);try{let J=_.query("PRAGMA integrity_check").get(),U=J?Object.values(J)[0]??null:null,W=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),X={};for(let G of W){let Y=`"${G.name.replaceAll('"','""')}"`,Q=_.query(`SELECT COUNT(*) AS n FROM ${Y}`).get();X[G.name]=Q?.n??0}return{exists:!0,integrity_check:U,table_counts:X}}finally{_.close()}}function y_($,_={}){let J=hL($.home),U=LE($.home,J),W=hL($.artifactsDir),X=LE($.artifactsDir,W),G=c6($.knowledgeDbPath);return{path:$.home,exists:c6($.home),file_count:J.length,total_bytes:U.bytes,tree_sha256:U.sha256,json_items:dn($.jsonStorePath),sqlite:_.includeSqlite===!1?{exists:G,integrity_check:null,table_counts:{}}:nn($.knowledgeDbPath),artifacts:{exists:c6($.artifactsDir),file_count:W.length,total_bytes:X.bytes,tree_sha256:X.sha256},files:J}}function cn($,_){if(!_.exists)return!0;if(_.files.filter((U)=>U!=="config.json").length>0)return!1;if(!_.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(lX($.configPath,"utf8")))===JSON.stringify(dW())}catch{return!1}}function mL($,_){return $.file_count===_.file_count&&$.total_bytes===_.total_bytes&&$.tree_sha256===_.tree_sha256&&$.json_items===_.json_items&&$.sqlite.integrity_check===_.sqlite.integrity_check&&JSON.stringify($.sqlite.table_counts)===JSON.stringify(_.sqlite.table_counts)&&$.artifacts.file_count===_.artifacts.file_count&&$.artifacts.total_bytes===_.artifacts.total_bytes&&$.artifacts.tree_sha256===_.artifacts.tree_sha256}function pG($){return $.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function xL($){if(Array.isArray($))return`[${$.map(xL).join(",")}]`;if($&&typeof $==="object")return`{${Object.entries($).sort(([_],[J])=>_.localeCompare(J)).map(([_,J])=>`${JSON.stringify(_)}:${xL(J)}`).join(",")}}`;return JSON.stringify($)}function BE($){return xL($)}function ZL($){return typeof $.short_id==="string"&&$.short_id.trim().length>0?$.short_id:null}function z2($){if(!c6($))return{items:[]};let _=JSON.parse(lX($,"utf8"));if(!_||!Array.isArray(_.items))throw Error(`Invalid knowledge JSON store shape at ${$}`);return{items:_.items}}function HE($,_){let J=new Map($.items.map((L)=>[L.id,L])),U=new Map;for(let L of $.items){let N=U.get(L.id);if(N&&N.item.id!==L.id);U.set(L.id,{item:L,keyKind:"id",source:"current"});let R=ZL(L);if(R&&!U.has(R))U.set(R,{item:L,keyKind:"short_id",source:"current"})}let W=[],X=0,G=0,Y=0,Q=[];for(let L of _.items){let N=J.get(L.id);if(N){if(BE(N)===BE(L))X+=1;else G+=1,W.push({type:"id_conflict",id:L.id,legacy_title:L.title,current_title:N.title});continue}let R=[{key:L.id,keyKind:"id"},...ZL(L)?[{key:ZL(L),keyKind:"short_id"}]:[]],B=!1;for(let{key:H,keyKind:V}of R){let K=U.get(H);if(!K)continue;if(V==="id"&&K.keyKind==="id")G+=1,W.push({type:"id_conflict",id:H,legacy_id:L.id,current_id:K.item.id,legacy_title:L.title,current_title:K.item.title});else Y+=1,W.push({type:"short_id_conflict",id:H,legacy_id:L.id,current_id:K.item.id,legacy_title:L.title,current_title:K.item.title});B=!0}if(B)continue;Q.push(L);for(let{key:H,keyKind:V}of R)U.set(H,{item:L,keyKind:V,source:"legacy"})}let q={items:[...$.items,...Q]};return{stats:{current_items:$.items.length,legacy_items:_.items.length,duplicate_ids_identical:X,duplicate_ids_conflicting:G,short_id_conflicts:Y,stranded_items:Q.length,merged_items:W.length===0?Q.length:0,expected_total_items:$.items.length+Q.length,final_items:null},conflicts:W,mergedStore:q}}function ln($,_){let J=[...new Set($)].sort(),U=(W)=>{if(W>=J.length)return _();return $4(J[W],()=>U(W+1),{createParent:!0})};return U(0)}function VE($){let _=$.now??new Date,J=$.approveWrite!==!0,U=y_($.legacy),W=y_($.current),X={legacy_exists:U.exists,legacy_store_exists:c6($.legacy.jsonStorePath),current_store_exists:c6($.current.jsonStorePath),approval_present:$.approveWrite===!0&&Boolean($.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},G=[];if(!U.exists||!X.legacy_store_exists)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:U,current_before:W,backup_after:null,current_after:W,merge:{current_items:z2($.current.jsonStorePath).items.length,legacy_items:0,duplicate_ids_identical:0,duplicate_ids_conflicting:0,short_id_conflicts:0,stranded_items:0,merged_items:0,expected_total_items:z2($.current.jsonStorePath).items.length,final_items:W.json_items},conflicts:[],checks:{...X,no_conflicts:!0,final_count_matches_expected:!0},warnings:G,message:`No legacy knowledge JSON store found at ${$.legacy.jsonStorePath}`};let Y=z2($.current.jsonStorePath),Q=z2($.legacy.jsonStorePath),q=HE(Y,Q);if(X.no_conflicts=q.conflicts.length===0,q.conflicts.length>0)G.push("merge_conflicts_detected");if(!X.approval_present)G.push("write_approval_required");if(J||!X.approval_present||q.conflicts.length>0)return{ok:q.conflicts.length===0,dry_run:!0,approval_required:!X.approval_present,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:`${$.legacy.home}.merge-backup-${pG(_)}`,legacy_before:U,current_before:W,backup_after:null,current_after:null,merge:q.stats,conflicts:q.conflicts,checks:X,warnings:G,message:q.conflicts.length===0?`Dry run: would merge ${q.stats.stranded_items} legacy item(s) into ${$.current.jsonStorePath}`:`Refusing legacy merge with ${q.conflicts.length} conflict(s)`};return ln([$.current.jsonStorePath,$.legacy.jsonStorePath],()=>{let L=z2($.current.jsonStorePath),N=z2($.legacy.jsonStorePath),R=HE(L,N);if(X.no_conflicts=R.conflicts.length===0,R.conflicts.length>0)return{ok:!1,dry_run:!0,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:y_($.legacy),current_before:y_($.current),backup_after:null,current_after:null,merge:R.stats,conflicts:R.conflicts,checks:X,warnings:[...G,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${R.conflicts.length} conflict(s)`};if(R.stats.stranded_items===0)return R.stats.final_items=L.items.length,X.final_count_matches_expected=L.items.length===R.stats.expected_total_items,{ok:X.no_conflicts&&X.final_count_matches_expected,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,legacy_before:y_($.legacy),current_before:y_($.current),backup_after:null,current_after:y_($.current),merge:R.stats,conflicts:[],checks:X,warnings:G,message:`Legacy merge already up to date for ${$.current.jsonStorePath}`};let B=`${$.legacy.home}.merge-backup-${pG(_)}`;rG(yL(B),{recursive:!0}),uL($.legacy.home,B,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let H=s_(B),V=y_(H);if(X.legacy_backup_written=mL(y_($.legacy),V),!X.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${B}`);F4($.current.jsonStorePath,R.mergedStore);let K=z2($.current.jsonStorePath);R.stats.final_items=K.items.length,X.final_count_matches_expected=K.items.length===R.stats.expected_total_items;let E=y_($.current),F=X.legacy_backup_written&&X.no_conflicts&&X.final_count_matches_expected;return{ok:F,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:B,legacy_before:U,current_before:W,backup_after:V,current_after:E,merge:R.stats,conflicts:[],checks:X,warnings:G,message:F?`Merged ${R.stats.merged_items} legacy item(s) into ${$.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${$.current.jsonStorePath}`}})}function rn($){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,$)}function nL($){return $ instanceof Error&&/\b(EBUSY|EPERM)\b/.test($.message)}function pn($){let _;for(let J=0;J<8;J+=1)try{oG($,{recursive:!0,force:!1});return}catch(U){if(_=U,!nL(U))throw U;rn(50*(J+1))}throw _}function RE($){if(!c6($))return;let _=NE($);if(vL($,_.isDirectory()?448:384),!_.isDirectory())return;for(let J of dL($))RE(e4($,J))}function on($){return $==="TOMBSTONE.md"||$==="migration.json"||$==="knowledge.db"||$==="knowledge.db-shm"||$==="knowledge.db-wal"||$==="knowledge.db-journal"}function tn($){for(let _ of dL($)){if(_==="TOMBSTONE.md"||_==="migration.json")continue;try{oG(e4($,_),{recursive:!0,force:!1})}catch(J){if(!nL(J)||!_.startsWith("knowledge.db"))throw J}}}function an($,_){try{xn($,_);return}catch(J){uL($,_,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{pn($)}catch(U){if(nL(U)){tn($);return}throw oG(_,{recursive:!0,force:!0}),U}if(J instanceof Error&&J.message.includes("EXDEV"))return}}function sn($,_,J){if(!_.exists)return!1;if(!_.files.includes("TOMBSTONE.md")||!_.files.includes("migration.json"))return!1;if(_.files.some((U)=>!on(U)))return!1;try{let U=JSON.parse(lX(e4($.home,"migration.json"),"utf8"));return U.new_path===J&&typeof U.backup_path==="string"}catch{return!1}}function KE($){let _=$.now??new Date,J=$.approveWrite!==!0,U=y_($.current),W=cn($.current,U),X=$.approveWrite===!0&&Boolean($.approvedBy)&&(!U.exists||W),G=y_($.legacy,{includeSqlite:!X}),Y={legacy_exists:G.exists,current_absent_or_default_scaffold:!U.exists||W,approval_present:$.approveWrite===!0&&Boolean($.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},Q=[];if(!G.exists)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,tombstone_path:null,legacy_before:G,current_before:U,backup_after:null,current_after:null,checks:Y,warnings:Q,message:`No legacy knowledge workspace found at ${$.legacy.home}`};if(Y.legacy_is_tombstone=sn($.legacy,G,$.current.home),Y.legacy_is_tombstone)return{ok:!0,dry_run:J,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:null,tombstone_path:e4($.legacy.home,"TOMBSTONE.md"),legacy_before:G,current_before:U,backup_after:null,current_after:U,checks:{...Y,tombstone_written:!0},warnings:Q,message:`Legacy knowledge workspace already migrated to ${$.current.home}`};if(!Y.current_absent_or_default_scaffold)Q.push("current_workspace_contains_data");if(!Y.approval_present)Q.push("write_approval_required");if(J||!Y.current_absent_or_default_scaffold||!Y.approval_present)return{ok:Y.current_absent_or_default_scaffold,dry_run:!0,approval_required:!0,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:`${$.legacy.home}.backup-${pG(_)}`,tombstone_path:e4($.legacy.home,"TOMBSTONE.md"),legacy_before:G,current_before:U,backup_after:null,current_after:null,checks:Y,warnings:Q,message:Y.current_absent_or_default_scaffold?`Dry run: would migrate ${$.legacy.home} to ${$.current.home}`:`Cannot migrate while ${$.current.home} contains data`};let q=`${$.legacy.home}.backup-${pG(_)}`;rG(yL($.current.home),{recursive:!0}),rG(yL(q),{recursive:!0}),uL($.legacy.home,q,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),RE(q);let L=s_(q),N=y_(L,{includeSqlite:!1});if(Y.backup_matches_legacy=mL(G,N),!Y.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${q}`);if(U.exists&&W)oG($.current.home,{recursive:!0,force:!0});an($.legacy.home,$.current.home);let R=y_($.current,{includeSqlite:!1});Y.migrated_matches_backup=mL(N,R);let B=y_(L),H=y_($.current),V={...B,path:$.legacy.home};rG($.legacy.home,{recursive:!0});let K=e4($.legacy.home,"TOMBSTONE.md");OE(K,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${_.toISOString()}`,`Approved by: ${$.approvedBy}`,`New path: ${$.current.home}`,`Backup path: ${q}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` +`),{mode:384}),vL(K,384);let E=e4($.legacy.home,"migration.json");OE(E,`${JSON.stringify({migrated_at:_.toISOString(),approved_by:$.approvedBy,new_path:$.current.home,backup_path:q,legacy_before:V,backup_after:B,current_after:H},null,2)} +`,{mode:384}),vL(E,384),Y.tombstone_written=c6(K);let F=Y.backup_matches_legacy&&Y.migrated_matches_backup&&Y.tombstone_written;return{ok:F,dry_run:!1,approval_required:!1,scope:$.scope,current_home:$.current.home,legacy_home:$.legacy.home,backup_home:q,tombstone_path:K,legacy_before:V,current_before:U,backup_after:B,current_after:H,checks:Y,warnings:Q,message:F?`Migrated legacy knowledge workspace to ${$.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${$.current.home}`}}function Jc($){let _=ZE($);if(e$(FE(_,"knowledge.db"))||e$(FE(_,"config.json")))return b2(_);return b2(s_(VY(_)).home)}function cL($){return`${_c()}:${pX("sha256").update($.home).digest("hex").slice(0,12)}`}function rL($){return`'${$.replace(/'/g,"'\\''")}'`}function Wc($){return["knowledge",...$].map(rL).join(" ")}function EE($,_){return`cd ${rL($)} && knowledge ${_.map(rL).join(" ")}`}function vE($){return!$||$==="local"||$==="localhost"}function rX($,_){return{source:$.source,adapter:$.adapter,project_root:_,project_root_source:$.project_root_source,workspace_root:$.workspace_root,workspace_root_source:$.workspace_root_source,open_files_root:$.open_files_root,open_files_root_source:$.open_files_root_source,trust_status:$.trust_status,auth_status:$.auth_status,current:$.current,primary:$.primary,diagnostics:$.diagnostics,repair_hints:$.repair_hints,evidence:$.evidence,cacheability:$.cacheability,warnings:$.warnings}}function iL($){return{source:$.source,adapter:$.adapter,target:$.target,route:$.route,target_kind:$.targetKind,confidence:$.confidence,evidence:$.evidence,cacheability:$.cacheability}}function Uc($){try{let _=JSON.parse($);return Array.isArray(_)?_.filter((J)=>typeof J==="string"):[]}catch{return[]}}function oX($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function E_($){return typeof $==="string"&&$.length>0?$:null}function Xc($){return typeof $==="number"&&Number.isFinite($)?$:null}function tG($){return typeof $==="boolean"?$:null}function Gc($){return Array.isArray($)?$.filter((_)=>typeof _==="string"):[]}function yE($,_,J){let U=oX($),W=E_(U.observed_at)??E_(_[`${J}_observed_at`]),X=E_(U.source_authority)??E_(_[`${J}_source_authority`]);if(!W||!X)return null;return{observed_at:W,verified_at:E_(U.verified_at),expires_at:E_(U.expires_at)??E_(_[`${J}_expires_at`]),ttl_ms:Xc(U.ttl_ms),source_authority:X,confidence:E_(U.confidence)??(J==="route"?E_(_.route_confidence):null),cacheable:tG(U.cacheable)??tG(_[`${J}_cacheable`])??!1,stale:tG(U.stale)??tG(_[`${J}_stale`])??!1,reasons:Gc(U.reasons)}}function Yc($,_){return $.machine_id===_||$.hostname===_||$.ssh_target===_||$.tailscale_dns===_||Uc($.tailscale_ips_json).includes(_)}function ME($,_){return Wq($).find((J)=>Yc(J,_))??null}function hE($){return oX(j2($.metadata_json).resolver_evidence)}function tX($){return oX(j2($.capabilities_json).resolver)}function mE($){let _=tX($),J=E_(_.route_kind);if(J==="local"||J==="lan"||J==="tailscale"||J==="ssh"||J==="unknown")return J;if($.tailscale_dns&&$.ssh_target===$.tailscale_dns)return"tailscale";return $.ssh_target?"ssh":"unknown"}function Qc($){let _=tX($),J=E_(_.route_target_kind);if(J==="local"||J==="lan"||J==="tailscale"||J==="ssh"||J==="unknown")return J;return mE($)}function qc($){return E_(tX($).route_confidence)??"medium"}function AE($,_,J){let U=hE($),W=oX(U.route),X=tX($);return{target:$.ssh_target??$.tailscale_dns??$.hostname??$.machine_id,route:mE($),targetKind:Qc($),confidence:qc($),source:"registry",adapter:J.adapter,evidence:{registry:!0,requested_machine_id:_,machine_id:$.machine_id,recorded_at:$.updated_at,route:W},cacheability:yE(W.cacheability,X,"route")??J.cacheability,warnings:[...new Set([...J.warnings,"registry_route_fallback"])]}}function bE($,_,J){if(!$.workspace_home)return null;let U=hE($),W=oX(U.workspace),X=tX($);return{ok:!0,source:"registry",adapter:J.adapter,requested_machine_id:_,machine_id:$.machine_id,project_id:E_(W.project_id)??J.project_id,repo_name:E_(W.repo_name)??J.repo_name,project_root:$.workspace_home,project_root_source:E_(X.project_root_source)??"registry",workspace_root:E_(W.workspace_root),workspace_root_source:E_(X.workspace_root_source)??"registry",open_files_root:E_(W.open_files_root),open_files_root_source:E_(X.open_files_root_source)??"registry",trust_status:E_(X.trust_status)??"unknown",auth_status:E_(X.auth_status)??"unknown",current:!1,primary:!1,diagnostics:[],repair_hints:[],evidence:{registry:!0,requested_machine_id:_,machine_id:$.machine_id,recorded_at:$.updated_at,workspace:W},cacheability:yE(W.cacheability,X,"workspace")??J.cacheability,warnings:[...new Set([...J.warnings,"registry_workspace_fallback"])]}}function wE($){if(!$)return null;let _=$.diagnostics.filter((U)=>U.severity!=="ok"),J=$.repair_hints[0];if(!_.length&&!$.warnings.length&&!J)return null;return[_.length?`workspace diagnostics: ${_.map((U)=>`${U.id}=${U.status}`).join(", ")}`:null,$.warnings.length?`warnings: ${$.warnings.join(", ")}`:null,J?`repair: ${J.shell_command}`:null].filter(Boolean).join("; ")}function aG($){return{id:$.id,reason:$.reason,command:["knowledge",...$.args],shell_command:Wc($.args)}}function sG($,_){let J=m($);try{return Number(J.query(_).get()?.count??0)}finally{J.close()}}function zc($,_){let J=sG($,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),U=sG($,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),W=sG($,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),X=sG($,["SELECT COUNT(*) AS count FROM sources","WHERE metadata_json LIKE '%raw_bytes%'","OR metadata_json LIKE '%raw_content%'","OR metadata_json LIKE '%content_base64%'","OR metadata_json LIKE '%source_bytes%'"].join(" ")),G=X===0;return{ok:G,source_of_truth:"open-files",configured_root:_?.open_files_root??null,configured_root_source:_?.open_files_root_source??null,source_refs:{open_files:J,metadata_mentions:U},extracted_text_artifacts:W,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:X,message:G?`${J} open-files source ref(s); raw source bytes remain owned by open-files`:`${X} raw source payload metadata sentinel(s) found`}}var jc=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function pL($,_=0){if(_>8)return!1;if(!$||typeof $!=="object")return!1;if(Array.isArray($))return $.some((J)=>pL(J,_+1));for(let[J,U]of Object.entries($)){if(jc.has(J.toLowerCase()))return!0;if(pL(U,_+1))return!0}return!1}function j2($){try{let _=JSON.parse($);return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}catch{return{}}}function gE($,_=20,J=200){if(!Number.isFinite($)||$<=0)return _;return Math.min(Math.floor($),J)}function Dc($,_=220){let J=$??"";return J.length>_?`${J.slice(0,_)}...`:J}function K6($,_=["metadata_json"]){return $.map((J)=>{let U={...J};for(let W of _){let X=U[W];if(typeof X==="string"){let G=W.endsWith("_json")?W.slice(0,-5):W;U[G]=j2(X),delete U[W]}}return U})}function eG($){if(typeof $!=="string")return[];try{let _=JSON.parse($);return Array.isArray(_)?_:[]}catch{return[]}}function oL($){if(typeof $!=="string")return{};return j2($)}function Oc($){let _={...$};return _.source_refs=eG(_.source_refs_json),_.evidence_refs=eG(_.evidence_refs_json),_.requires_approval=_.requires_approval===1||_.requires_approval===!0,_.checks=oL(_.checks_json),_.metadata=oL(_.metadata_json),delete _.source_refs_json,delete _.evidence_refs_json,delete _.checks_json,delete _.metadata_json,_}function Lc($){let _={...$};return _.source_refs=eG(_.source_refs_json),_.evidence_refs=eG(_.evidence_refs_json),_.metadata=oL(_.metadata_json),delete _.source_refs_json,delete _.evidence_refs_json,delete _.metadata_json,_}function l_($,_,J=[]){return $.query(_).all(...J)}function Bc($){if(!e$($))return{exists:!1,read_error:null,items:[]};try{let _=JSON.parse($c($,"utf8"));if(!_||!Array.isArray(_.items))return{exists:!0,read_error:"invalid_store_shape",items:[]};return{exists:!0,read_error:null,items:_.items}}catch(_){return{exists:!0,read_error:_ instanceof Error?_.message:String(_),items:[]}}}function kE($){return{id:$.id,short_id:$.short_id??null,title:$.title,content_preview:Dc($.content),url:$.url??null,tags:$.tags??[],metadata:$.metadata??{},archived:$.archived===!0,created_at:$.created_at,updated_at:$.updated_at}}function IE(){return{schema_version:0,sources:0,source_revisions:0,chunks:0,wiki_pages:0,citations:0,indexes:0,runs:0,run_events:0,redaction_findings:0,audit_events:0,approval_gates:0,storage_objects:0,embeddings:0,vector_entries:0,reindex_queue:0,knowledge_machines:0,sync_snapshots:0,sync_changes:0,sync_conflicts:0,sync_table_clocks:0,sync_imports:0,promotion_candidates:0,durable_records:0}}function xE($,_,J=!1){return{query:$,limit:_,offset:0,mode:{keyword:!0,catalog:!0,semantic:J},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:0,catalog_results:0,semantic_results:0,merged_results:0},warnings:["knowledge_db_missing"],results:[]}}function Hc($){return $.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function Nc($,_,J=!1){let U=xE($,_,J);return{query:$,normalized_query:Hc($),created_at:new Date().toISOString(),mode:U.mode,warnings:U.warnings,search_counts:U.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function lL($,_,J){let U=J??_.jsonStorePath;if(e$(U))return U;if($==="global"){let W=uW();if(e$(W))return W}return U}function Vc($){let _=JSON.stringify($);return Math.max(1,Math.ceil(_.length/4))}function tL($,_){let J=($??"").normalize("NFKC").trim().replace(/\s+/g," ");if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-1)).trim()}...`}function fE($,_,J){let U=k_(tL($,J),_);return{text:U.text,redactions:U.findings.length}}function CE($,_,J){let U=$.now??new Date,W=$.source??"search",X=$.purpose??(W==="loops"||W==="runs"?"proposal":"agent_context"),G=($.query??$.topic??_.query).normalize("NFKC").trim().replace(/\s+/g," "),Y=Math.max(1,Math.min($.maxItems??$.limit??8,50)),Q=Math.max(500,Math.min($.maxTokens??6000,1e5)),q=0,L=_.citations.slice(0,Math.max(Y*2,Y)).map((F,w)=>{let A=fE(F.quote,J,w<3?220:140);q+=A.redactions;let g=F.source_ref??F.source_uri??F.artifact_path??F.artifact_uri??F.id;return{id:`cite_${pX("sha256").update(`${F.id}\x00${g}`).digest("hex").slice(0,12)}`,kind:F.artifact_uri||F.artifact_path?"artifact":"source",ref:g,source_ref:F.source_ref,source_uri:F.source_uri,artifact_uri:F.artifact_uri,artifact_path:F.artifact_path,run_id:null,run_event_id:null,revision:F.revision,hash:F.hash,chunk_id:F.chunk_id,offsets:{start:F.start_offset,end:F.end_offset},quote_preview:A.text}}),N=new Map(_.citations.map((F,w)=>[F.id,L[w]])),R=_.excerpts.slice(0,Math.max(Y*2,Y)).map((F)=>{let w=_.results.find((v)=>v.id===F.result_id),A=F.citation_id?N.get(F.citation_id):void 0,g=fE(F.text,J,520);return q+=g.redactions,{id:`ev_${pX("sha256").update(`${F.kind}\x00${F.result_id}\x00${F.citation_id??""}`).digest("hex").slice(0,14)}`,kind:F.kind,title:tL(w?.title??A?.ref??F.kind,100),text_preview:g.text,score:Number(F.score.toFixed(6)),citation_ids:A?[A.id]:[],provenance:{source:W,record_ref:`${F.kind}:${F.result_id}`,created_at:_.created_at,updated_at:null,metadata_keys:[]}}}).sort((F,w)=>w.score-F.score||F.id.localeCompare(w.id)).slice(0,Y),B=new Set(R.flatMap((F)=>F.citation_ids)),H=L.filter((F)=>B.has(F.id)),V=Array.from(new Set(_.warnings)),K=`ctx_${pX("sha256").update([W,X,G,V.join(","),R.map((F)=>F.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,E={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:U.toISOString(),source:W,purpose:X,query:G,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:K,budgets:{max_tokens:Q,estimated_tokens:0,max_items:Y,items_included:R.length,items_available:_.excerpts.length,items_truncated:Math.max(0,_.excerpts.length-R.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:q,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:H,evidence:R,duplicate_candidates:[],outline:{title:G?`Knowledge context: ${tL(G,80)}`:"Knowledge context",bullets:R.length>0?R.slice(0,5).map((F)=>`${F.id}: ${F.title}`):["No matching bounded evidence was found."],evidence_ids:R.slice(0,8).map((F)=>F.id),duplicate_candidate_ids:[],next_actions:["Use evidence_ids and citation_ids in prompts instead of raw excerpts when possible.","Inspect cited refs only if the bounded preview is insufficient.","Use knowledge build/file-answer only with explicit approval for durable writes."]},warnings:V,message:`${R.length} bounded evidence item(s), estimated under ${Q} token(s)`};return E.budgets.estimated_tokens=Vc(E),E.budgets.token_budget_exceeded=E.budgets.estimated_tokens>Q,E.message=`${E.evidence.length} bounded evidence item(s), estimated ${E.budgets.estimated_tokens}/${Q} token(s)`,E}function Rc(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function Kc(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function Fc($){return{ok:!0,scope:$.scope,workspace_home:$.workspaceHome,sqlite_schema_version:0,local_machine_id:$.localMachineId??null,machines:{total:0,rows:[]},snapshots:{total:0,latest:null},changes:{total:0,by_operation:[]},clocks:{total:0,rows:[]},imports:{total:0,latest:null},conflicts:{total:0,by_status:[],open:0},table_counts:{},message:"0 machine(s), 0 open sync conflict(s)"}}function PE($){let _=$.now??new Date,J=$.source??"search",U=$.purpose??(J==="loops"||J==="runs"?"proposal":"agent_context"),W=($.query??$.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),X=Math.max(1,Math.min($.maxItems??$.limit??8,50)),G=Math.max(500,Math.min($.maxTokens??6000,1e5)),Y=`ctx_${pX("sha256").update(["empty",J,U,W,$.topic??"",$.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:_.toISOString(),source:J,purpose:U,query:W,topic:$.topic??null,since:$.since??null,dry_run:!0,idempotency_key:Y,budgets:{max_tokens:G,estimated_tokens:0,max_items:X,items_included:0,items_available:0,items_truncated:0,token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:0,reminders:["This pack is read-only and performs no durable writes.","No knowledge.db exists for this scope yet."]},citations:[],evidence:[],duplicate_candidates:[],outline:{title:W?`Context for ${W}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${G} token(s)`}}function aL($){let _=$.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return _?`${_}/`:null}function Ec($,_){let J=m($);try{let U=J.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all(),W=new Map,X=0,G=0,Q=0,Y=0,q=0,L=0,N=0,F=0,B=0,H=0,V=0,R=0,M=new Map,K=[],w=[],b=[],I=[],v=_.artifact_store.uri_prefix,g=mL(_);for(let J6 of U){if(W.set(J6.kind,(W.get(J6.kind)??0)+1),J6.hash?.startsWith("sha256:"))X+=1;if(typeof J6.size_bytes==="number"&&J6.size_bytes>=0)G+=1,Q+=J6.size_bytes;if(J6.artifact_uri.startsWith(v))Y+=1;else if(K.length<5)K.push(J6.artifact_uri);let R6=LW(J6.metadata_json);if(yL(R6))N+=1;let R_=typeof R6.key==="string"?R6.key:null;if(!R_)q+=1;else if(g&&R_.startsWith(g)){if(L+=1,w.length<5)w.push(R_)}let DB=typeof R6.artifact_modified_at==="string"?R6.artifact_modified_at:null;if(DB)if(Number.isNaN(Date.parse(DB))){if(B+=1,b.length<5)b.push(J6.artifact_uri)}else F+=1;let ZW=R6.provenance&&typeof R6.provenance==="object"&&!Array.isArray(R6.provenance)?R6.provenance:null;if(ZW){H+=1;let QQ=typeof ZW.artifact_key==="string"?ZW.artifact_key:null,LB=typeof ZW.generated_from==="string"?ZW.generated_from:"unknown";if(M.set(LB,(M.get(LB)??0)+1),QQ){if(V+=1,R_&&QQ!==R_){if(R+=1,I.length<5)I.push(`${J6.artifact_uri}:provenance.artifact_key=${QQ}:key=${R_}`)}}else if(I.length<5)I.push(`${J6.artifact_uri}:missing_provenance_artifact_key`)}else if(I.length<5)I.push(`${J6.artifact_uri}:missing_provenance`)}let x=U.length-X,Y6=U.length-G,l$=U.length-F-B,q6=U.length-H,F6=H-V,M$=U.length-Y,b6=[x>0?`artifact_manifest_missing_hash:${x}`:null,Y6>0?`artifact_manifest_missing_size:${Y6}`:null,q>0?`artifact_manifest_missing_key:${q}`:null,M$>0?`artifact_manifest_uri_prefix_mismatch:${M$}`:null,L>0?`artifact_manifest_s3_key_contains_storage_prefix:${L}`:null,B>0?`artifact_manifest_invalid_modified_at:${B}`:null,q6>0?`artifact_manifest_missing_provenance:${q6}`:null,F6>0?`artifact_manifest_missing_provenance_artifact_key:${F6}`:null,R>0?`artifact_manifest_provenance_key_mismatch:${R}`:null,N>0?`artifact_manifest_raw_payload_sentinels:${N}`:null].filter((J6)=>Boolean(J6)),j6=b6.length===0;return{ok:j6,read_only:!0,storage_type:_.storage_type,artifact_uri_prefix:v,s3:_.artifact_store.s3,artifacts:{total:U.length,by_kind:[...W.entries()].map(([J6,R6])=>({kind:J6,count:R6})).sort((J6,R6)=>J6.kind.localeCompare(R6.kind)),with_hash:X,missing_hash:x,with_size:G,missing_size:Y6,total_size_bytes:Q},modified_time:{with_modified_at:F,missing_modified_at:l$,invalid_modified_at:B,examples:b},provenance:{with_provenance:H,missing_provenance:q6,with_artifact_key:V,missing_artifact_key:F6,artifact_key_mismatches:R,generated_from:[...M.entries()].map(([J6,R6])=>({value:J6,count:R6})).sort((J6,R6)=>J6.value.localeCompare(R6.value)),examples:I},uri_prefix:{matching:Y,mismatched:M$,examples:K},keys:{with_key:U.length-q,missing_key:q,prefixed_with_storage_prefix:L,prefixed_examples:w},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:L===0&&q===0,tracks_modified_time:F>0&&B===0,preserves_provenance:q6===0&&F6===0&&R===0},raw_payload_sentinel_hits:N,warnings:b6,message:j6?`${U.length} generated artifact manifest row(s) ready for ${_.storage_type} sync`:`Generated artifact manifest needs attention: ${b6.join(", ")}`}}finally{J.close()}}function nc($,_){let J=mL(_);if(!J)return[];let U=i($);try{let W=U.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json + ORDER BY artifact_uri ASC`).all(),W=new Map,X=0,G=0,Y=0,Q=0,q=0,L=0,N=0,R=0,B=0,H=0,V=0,K=0,E=new Map,F=[],w=[],A=[],g=[],v=_.artifact_store.uri_prefix,k=aL(_);for(let U_ of U){if(W.set(U_.kind,(W.get(U_.kind)??0)+1),U_.hash?.startsWith("sha256:"))X+=1;if(typeof U_.size_bytes==="number"&&U_.size_bytes>=0)G+=1,Y+=U_.size_bytes;if(U_.artifact_uri.startsWith(v))Q+=1;else if(F.length<5)F.push(U_.artifact_uri);let F_=j2(U_.metadata_json);if(pL(F_))N+=1;let A2=typeof F_.key==="string"?F_.key:null;if(!A2)q+=1;else if(k&&A2.startsWith(k)){if(L+=1,w.length<5)w.push(A2)}let bB=typeof F_.artifact_modified_at==="string"?F_.artifact_modified_at:null;if(bB)if(Number.isNaN(Date.parse(bB))){if(B+=1,A.length<5)A.push(U_.artifact_uri)}else R+=1;let xW=F_.provenance&&typeof F_.provenance==="object"&&!Array.isArray(F_.provenance)?F_.provenance:null;if(xW){H+=1;let LY=typeof xW.artifact_key==="string"?xW.artifact_key:null,wB=typeof xW.generated_from==="string"?xW.generated_from:"unknown";if(E.set(wB,(E.get(wB)??0)+1),LY){if(V+=1,A2&&LY!==A2){if(K+=1,g.length<5)g.push(`${U_.artifact_uri}:provenance.artifact_key=${LY}:key=${A2}`)}}else if(g.length<5)g.push(`${U_.artifact_uri}:missing_provenance_artifact_key`)}else if(g.length<5)g.push(`${U_.artifact_uri}:missing_provenance`)}let u=U.length-X,W_=U.length-G,c$=U.length-R-B,z_=U.length-H,K_=H-V,E$=U.length-Q,A_=[u>0?`artifact_manifest_missing_hash:${u}`:null,W_>0?`artifact_manifest_missing_size:${W_}`:null,q>0?`artifact_manifest_missing_key:${q}`:null,E$>0?`artifact_manifest_uri_prefix_mismatch:${E$}`:null,L>0?`artifact_manifest_s3_key_contains_storage_prefix:${L}`:null,B>0?`artifact_manifest_invalid_modified_at:${B}`:null,z_>0?`artifact_manifest_missing_provenance:${z_}`:null,K_>0?`artifact_manifest_missing_provenance_artifact_key:${K_}`:null,K>0?`artifact_manifest_provenance_key_mismatch:${K}`:null,N>0?`artifact_manifest_raw_payload_sentinels:${N}`:null].filter((U_)=>Boolean(U_)),D_=A_.length===0;return{ok:D_,read_only:!0,storage_type:_.storage_type,artifact_uri_prefix:v,s3:_.artifact_store.s3,artifacts:{total:U.length,by_kind:[...W.entries()].map(([U_,F_])=>({kind:U_,count:F_})).sort((U_,F_)=>U_.kind.localeCompare(F_.kind)),with_hash:X,missing_hash:u,with_size:G,missing_size:W_,total_size_bytes:Y},modified_time:{with_modified_at:R,missing_modified_at:c$,invalid_modified_at:B,examples:A},provenance:{with_provenance:H,missing_provenance:z_,with_artifact_key:V,missing_artifact_key:K_,artifact_key_mismatches:K,generated_from:[...E.entries()].map(([U_,F_])=>({value:U_,count:F_})).sort((U_,F_)=>U_.value.localeCompare(F_.value)),examples:g},uri_prefix:{matching:Q,mismatched:E$,examples:F},keys:{with_key:U.length-q,missing_key:q,prefixed_with_storage_prefix:L,prefixed_examples:w},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:L===0&&q===0,tracks_modified_time:R>0&&B===0,preserves_provenance:z_===0&&K_===0&&K===0},raw_payload_sentinel_hits:N,warnings:A_,message:D_?`${U.length} generated artifact manifest row(s) ready for ${_.storage_type} sync`:`Generated artifact manifest needs attention: ${A_.join(", ")}`}}finally{J.close()}}function Mc($,_){let J=aL(_);if(!J)return[];let U=m($);try{let W=U.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all(),X=[];for(let G of W){let Q=LW(G.metadata_json),Y=typeof Q.key==="string"?Q.key:null;if(!Y?.startsWith(J))continue;let q=Y.slice(J.length);if(!q)continue;X.push({id:G.id,artifact_uri:G.artifact_uri,kind:G.kind,current_key:Y,repaired_key:q0(q),hash:G.hash,size_bytes:G.size_bytes})}return X}finally{U.close()}}function ic($){let _=["--scope",$.scope,"--json"],J=$.tables?.length?["--tables",$.tables.join(",")]:[],U=[n5({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",..._]})];if($.machine&&!BM($.machine))U.push(n5({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",$.machine,...$.peerWorkspace?["--peer-workspace",$.peerWorkspace]:[],...J,..._]}));else if($.peerWorkspace)U.push(n5({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",$.peerWorkspace,...J,..._]}));for(let W of $.resolvedWorkspace?.repair_hints??[])U.push({id:W.id,reason:W.reason,command:W.command,shell_command:W.shell_command});if($.openConflicts>0)U.push(n5({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",..._]}));return U}function rc(){let $=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",_=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!_)return{command:$,argsPrefix:[]};let J;try{J=JSON.parse(_)}catch(U){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${U instanceof Error?U.message:String(U)}`)}if(!Array.isArray(J)||!J.every((U)=>typeof U==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:$,argsPrefix:J}}function OM($,_,J,U){let W=rc(),X=Ac(W.command,[...W.argsPrefix,U.target,_],{encoding:"utf8",env:process.env,input:J,maxBuffer:67108864});if((X.status??1)!==0){let G=U.source==="open-machines"?` via ${U.route??"resolved"}:${U.target}`:"";throw Error(`ssh ${$}${G} failed: ${(X.stderr||X.stdout||String(X.status)).trim()}`)}return X.stdout||""}function DM($,_,J){try{return JSON.parse(J)}catch(U){let W=J.trim().slice(0,240);throw Error(`Remote knowledge ${_} on ${$} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${W||String(U)}`)}}function pc($,_){if(typeof _!=="object"||_===null||!("format"in _)||_.format!=="knowledge-sync-bundle")throw Error(`Remote knowledge sync export on ${$} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:J,min_protocol_version:U}=_;if(typeof J!=="number"||typeof U!=="number"||Jb1)throw Error(`Remote knowledge sync export on ${$} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function oc($,_){if(typeof _!=="object"||_===null||!("ok"in _)||!("target"in _)||!("tables"in _)||!("artifacts"in _)||!("conflicts_created"in _))throw Error(`Remote knowledge sync import on ${$} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:J,min_protocol_version:U}=_;if(typeof J!=="number"||typeof U!=="number"||Jb1)throw Error(`Remote knowledge sync import on ${$} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function tc($){if(!$)return;let _=$.trim().toLowerCase();if(_==="local"||_==="offline")return"local";if(_==="hosted"||_==="remote"||_==="knowledge.md")return"hosted";throw Error("Invalid setup mode. Use hosted or local.")}class RM{options;ensuredWorkspace;cachedConfig;constructor($={}){this.options=$}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??Y9(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=K_(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let $=this.ensureWorkspace();return P9({storePath:$.jsonStorePath,storePathOverridden:!1})}async listItems(){return this.itemStore().listAll()}async getItem($){return this.itemStore().get($)}async createItem($){return this.itemStore().create($)}async updateItem($,_){return this.itemStore().update($,_)}async deleteItem($){return this.itemStore().delete($)}async deleteItems($){return this.itemStore().deleteMany($)}async resolveInventory($={}){if(this.isApiMode())return this.cloudInventory($);return this.inventory($)}config($={}){let _=$.ensure?this.ensureWorkspace():this.workspace;if(!this.cachedConfig||$.ensure||e$(_.configPath))this.cachedConfig=e$(_.configPath)?DQ(_.configPath):yW();return this.cachedConfig}safetyPolicy(){return D3(this.config(),this.workspace)}artifactStore(){return NY(this.config(),this.ensureWorkspace())}storageContract(){return Z9(this.config(),this.workspace,this.scope)}validateStorage(){return RY(this.config(),this.workspace)}assertStorageValid($){let _=this.validateStorage();if(!_.ok)throw Error(`Storage contract invalid before ${$}: ${_.errors.join("; ")}`)}migrateLegacyPath($={}){let _=this.workspace,J=OQ(this.options.scope,this.options.cwd),U=eK({scope:this.scope,current:_,legacy:J,approveWrite:$.approveWrite,approvedBy:$.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}mergeLegacyPath($={}){let _=this.workspace,J=OQ(this.options.scope,this.options.cwd),U=aK({scope:this.scope,current:_,legacy:J,approveWrite:$.approveWrite,approvedBy:$.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}setup($={}){let _=this.ensureWorkspace(),J=this.config({ensure:!0}),U=tc($.mode)??J.mode,W=$.apiUrl?h0($.apiUrl):J.hosted?.api_url?h0(J.hosted.api_url):null,X={...J,mode:U,hosted:{...J.hosted??{},...W?{api_url:W}:{}},storage:$.canonicalExample?FB():J.storage};RB(_.configPath,X),this.cachedConfig=X;let G=Z9(X,_,this.scope);return{ok:!0,mode:U,api_url:X.hosted?.api_url??null,storage_type:X.storage.type,artifact_uri_prefix:G.artifact_store.uri_prefix,canonical_example:G.canonical_example,config_path:_.configPath,next:U==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${U}`}}authStatus($=process.env){return _3(this.config(),$)}saveAuth($,_=process.env){let J=$.apiUrl??this.config().hosted?.api_url;return eN({api_key:$.apiKey,email:$.email,org_id:$.orgId,org_slug:$.orgSlug,user_id:$.userId,api_url:J},_)}clearAuth($=process.env){return $3($)}paths(){let $=this.workspace;return{ok:!0,scope:this.scope,home:$.home,exists:e$($.home),config_path:$.configPath,config_exists:e$($.configPath),json_store_path:$.jsonStorePath,json_store_exists:e$($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:e$($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,runs_dir:$.runsDir,schemas_dir:$.schemasDir,wiki_dir:$.wikiDir,config:this.config(),message:$.home}}initDb(){return G$(this.ensureWorkspace().knowledgeDbPath)}dbStats(){T9("reading knowledge.db stats");let $=this.workspace;if(!e$($.knowledgeDbPath))return YM();return LY($.knowledgeDbPath)}itemOnlyInventory($){let _=this.workspace,{items:J,limit:U,includeArchived:W,storePath:X,storeExists:G,storeReadError:Q}=$,Y=J.filter((F)=>F.archived!==!0),q=W?J:Y,L=YM(),N={legacy_items:J.length,active_items:Y.length,archived_items:J.length-Y.length,schema_version:L.schema_version,sources:L.sources,source_revisions:L.source_revisions,chunks:L.chunks,wiki_pages:L.wiki_pages,citations:L.citations,indexes:L.indexes,runs:L.runs,run_events:L.run_events,storage_objects:L.storage_objects,embeddings:L.embeddings,vector_entries:L.vector_entries,reindex_queue:L.reindex_queue,redaction_findings:L.redaction_findings,audit_events:L.audit_events,approval_gates:L.approval_gates,knowledge_machines:L.knowledge_machines,sync_snapshots:L.sync_snapshots,sync_changes:L.sync_changes,sync_conflicts:L.sync_conflicts,sync_table_clocks:L.sync_table_clocks,sync_imports:L.sync_imports};return{ok:!0,scope:this.scope,home:_.home,limit:U,paths:{json_store_path:_.jsonStorePath,json_store_exists:e$(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:e$(_.knowledgeDbPath),artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,wiki_dir:_.wikiDir},summary:N,legacy_store:{path:X,exists:G,read_error:Q,total_items:J.length,active_items:Y.length,archived_items:J.length-Y.length,items_returned:Math.min(q.length,U)},items:q.slice(0,U).map(QM),sources:[],source_revisions:[],chunks:[],wiki_pages:[],indexes:[],storage_objects:[],runs:[],vector_indexes:[],reindex_queue:[],machines:[],sync_conflicts:[],approval_gates:[],audit_events:[],message:`${J.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory($={}){let _=GM($.limit),J=await this.fetchCloudItems(),U=BU();return this.itemOnlyInventory({items:J,limit:_,includeArchived:$.includeArchived??!1,storePath:U?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory($={}){let _=this.workspace,J=GM($.limit),U=$.storePath??_.jsonStorePath,W=yc(U),X=W.items.filter((L)=>L.archived!==!0),G=$.includeArchived?W.items:X;if(!e$(_.knowledgeDbPath))return this.itemOnlyInventory({items:W.items,limit:J,includeArchived:$.includeArchived??!1,storePath:U,storeExists:W.exists,storeReadError:W.read_error});G$(_.knowledgeDbPath);let Y=LY(_.knowledgeDbPath),q=i(_.knowledgeDbPath);try{let L=F4(Y4(q,` + ORDER BY artifact_uri ASC`).all(),X=[];for(let G of W){let Y=j2(G.metadata_json),Q=typeof Y.key==="string"?Y.key:null;if(!Q?.startsWith(J))continue;let q=Q.slice(J.length);if(!q)continue;X.push({id:G.id,artifact_uri:G.artifact_uri,kind:G.kind,current_key:Q,repaired_key:z4(q),hash:G.hash,size_bytes:G.size_bytes})}return X}finally{U.close()}}function Ac($){let _=["--scope",$.scope,"--json"],J=$.tables?.length?["--tables",$.tables.join(",")]:[],U=[aG({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",..._]})];if($.machine&&!vE($.machine))U.push(aG({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",$.machine,...$.peerWorkspace?["--peer-workspace",$.peerWorkspace]:[],...J,..._]}));else if($.peerWorkspace)U.push(aG({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",$.peerWorkspace,...J,..._]}));for(let W of $.resolvedWorkspace?.repair_hints??[])U.push({id:W.id,reason:W.reason,command:W.command,shell_command:W.shell_command});if($.openConflicts>0)U.push(aG({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",..._]}));return U}function bc(){let $=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",_=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!_)return{command:$,argsPrefix:[]};let J;try{J=JSON.parse(_)}catch(U){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${U instanceof Error?U.message:String(U)}`)}if(!Array.isArray(J)||!J.every((U)=>typeof U==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:$,argsPrefix:J}}function TE($,_,J,U){let W=bc(),X=en(W.command,[...W.argsPrefix,U.target,_],{encoding:"utf8",env:process.env,input:J,maxBuffer:67108864});if((X.status??1)!==0){let G=U.source==="open-machines"?` via ${U.route??"resolved"}:${U.target}`:"";throw Error(`ssh ${$}${G} failed: ${(X.stderr||X.stdout||String(X.status)).trim()}`)}return X.stdout||""}function SE($,_,J){try{return JSON.parse(J)}catch(U){let W=J.trim().slice(0,240);throw Error(`Remote knowledge ${_} on ${$} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${W||String(U)}`)}}function wc($,_){if(typeof _!=="object"||_===null||!("format"in _)||_.format!=="knowledge-sync-bundle")throw Error(`Remote knowledge sync export on ${$} did not return a knowledge sync bundle. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:J,min_protocol_version:U}=_;if(typeof J!=="number"||typeof U!=="number"||Jw0)throw Error(`Remote knowledge sync export on ${$} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function gc($,_){if(typeof _!=="object"||_===null||!("ok"in _)||!("target"in _)||!("tables"in _)||!("artifacts"in _)||!("conflicts_created"in _))throw Error(`Remote knowledge sync import on ${$} did not return a sync import result. Install @hasna/knowledge 0.2.32 or newer on the remote machine.`);let{protocol_version:J,min_protocol_version:U}=_;if(typeof J!=="number"||typeof U!=="number"||Jw0)throw Error(`Remote knowledge sync import on ${$} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function kc($){if(!$)return;let _=$.trim().toLowerCase();if(_==="local"||_==="offline")return"local";if(_==="hosted"||_==="remote"||_==="knowledge.md")return"hosted";throw Error("Invalid setup mode. Use hosted or local.")}class uE{options;ensuredWorkspace;cachedConfig;constructor($={}){this.options=$}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??O9(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=b2(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let $=this.ensureWorkspace();return y9({storePath:$.jsonStorePath,storePathOverridden:!1})}async listItems(){return this.itemStore().listAll()}async getItem($){return this.itemStore().get($)}async createItem($){return this.itemStore().create($)}async updateItem($,_){return this.itemStore().update($,_)}async deleteItem($){return this.itemStore().delete($)}async deleteItems($){return this.itemStore().deleteMany($)}async resolveInventory($={}){if(this.isApiMode())return this.cloudInventory($);return this.inventory($)}config($={}){let _=$.ensure?this.ensureWorkspace():this.workspace;if(!this.cachedConfig||$.ensure||e$(_.configPath))this.cachedConfig=e$(_.configPath)?KY(_.configPath):dW();return this.cachedConfig}safetyPolicy(){return b3(this.config(),this.workspace)}artifactStore(){return AQ(this.config(),this.ensureWorkspace())}storageContract(){return x9(this.config(),this.workspace,this.scope)}validateStorage(){return gQ(this.config(),this.workspace)}assertStorageValid($){let _=this.validateStorage();if(!_.ok)throw Error(`Storage contract invalid before ${$}: ${_.errors.join("; ")}`)}migrateLegacyPath($={}){let _=this.workspace,J=RY(this.options.scope,this.options.cwd),U=KE({scope:this.scope,current:_,legacy:J,approveWrite:$.approveWrite,approvedBy:$.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}mergeLegacyPath($={}){let _=this.workspace,J=RY(this.options.scope,this.options.cwd),U=VE({scope:this.scope,current:_,legacy:J,approveWrite:$.approveWrite,approvedBy:$.approvedBy});if(!U.dry_run&&U.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return U}setup($={}){let _=this.ensureWorkspace(),J=this.config({ensure:!0}),U=kc($.mode)??J.mode,W=$.apiUrl?x4($.apiUrl):J.hosted?.api_url?x4(J.hosted.api_url):null,X={...J,mode:U,hosted:{...J.hosted??{},...W?{api_url:W}:{}},storage:$.canonicalExample?CB():J.storage};PB(_.configPath,X),this.cachedConfig=X;let G=x9(X,_,this.scope);return{ok:!0,mode:U,api_url:X.hosted?.api_url??null,storage_type:X.storage.type,artifact_uri_prefix:G.artifact_store.uri_prefix,canonical_example:G.canonical_example,config_path:_.configPath,next:U==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${U}`}}authStatus($=process.env){return O3(this.config(),$)}saveAuth($,_=process.env){let J=$.apiUrl??this.config().hosted?.api_url;return j3({api_key:$.apiKey,email:$.email,org_id:$.orgId,org_slug:$.orgSlug,user_id:$.userId,api_url:J},_)}clearAuth($=process.env){return D3($)}paths(){let $=this.workspace;return{ok:!0,scope:this.scope,home:$.home,exists:e$($.home),config_path:$.configPath,config_exists:e$($.configPath),json_store_path:$.jsonStorePath,json_store_exists:e$($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:e$($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,runs_dir:$.runsDir,schemas_dir:$.schemasDir,wiki_dir:$.wikiDir,config:this.config(),message:$.home}}initDb(){return a(this.ensureWorkspace().knowledgeDbPath)}dbStats(){h9("reading knowledge.db stats");let $=this.workspace;if(!e$($.knowledgeDbPath))return IE();return FQ($.knowledgeDbPath)}enqueuePromotion($){return IF(this.ensureWorkspace().knowledgeDbPath,$)}promotionInbox($={}){return CF(this.ensureWorkspace().knowledgeDbPath,$)}getPromotion($){return fF(this.ensureWorkspace().knowledgeDbPath,$)}reviewPromotion($,_){return PF(this.ensureWorkspace().knowledgeDbPath,$,_)}promoteCandidate($,_={}){return TF(this.ensureWorkspace().knowledgeDbPath,$,_)}rejectPromotion($,_={}){return SF(this.ensureWorkspace().knowledgeDbPath,$,_)}durableRecords($={}){return ZF(this.ensureWorkspace().knowledgeDbPath,$)}itemOnlyInventory($){let _=this.workspace,{items:J,limit:U,includeArchived:W,storePath:X,storeExists:G,storeReadError:Y}=$,Q=J.filter((R)=>R.archived!==!0),q=W?J:Q,L=IE(),N={legacy_items:J.length,active_items:Q.length,archived_items:J.length-Q.length,schema_version:L.schema_version,sources:L.sources,source_revisions:L.source_revisions,chunks:L.chunks,wiki_pages:L.wiki_pages,citations:L.citations,indexes:L.indexes,runs:L.runs,run_events:L.run_events,storage_objects:L.storage_objects,embeddings:L.embeddings,vector_entries:L.vector_entries,reindex_queue:L.reindex_queue,redaction_findings:L.redaction_findings,audit_events:L.audit_events,approval_gates:L.approval_gates,knowledge_machines:L.knowledge_machines,sync_snapshots:L.sync_snapshots,sync_changes:L.sync_changes,sync_conflicts:L.sync_conflicts,sync_table_clocks:L.sync_table_clocks,sync_imports:L.sync_imports,promotion_candidates:L.promotion_candidates,durable_records:L.durable_records};return{ok:!0,scope:this.scope,home:_.home,limit:U,paths:{json_store_path:_.jsonStorePath,json_store_exists:e$(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:e$(_.knowledgeDbPath),artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,wiki_dir:_.wikiDir},summary:N,legacy_store:{path:X,exists:G,read_error:Y,total_items:J.length,active_items:Q.length,archived_items:J.length-Q.length,items_returned:Math.min(q.length,U)},items:q.slice(0,U).map(kE),sources:[],source_revisions:[],chunks:[],wiki_pages:[],indexes:[],storage_objects:[],runs:[],vector_indexes:[],reindex_queue:[],machines:[],sync_conflicts:[],approval_gates:[],audit_events:[],promotion_candidates:[],durable_records:[],message:`${J.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory($={}){let _=gE($.limit),J=await this.fetchCloudItems(),U=KU();return this.itemOnlyInventory({items:J,limit:_,includeArchived:$.includeArchived??!1,storePath:U?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory($={}){let _=this.workspace,J=gE($.limit),U=$.storePath??_.jsonStorePath,W=Bc(U),X=W.items.filter((L)=>L.archived!==!0),G=$.includeArchived?W.items:X;if(!e$(_.knowledgeDbPath))return this.itemOnlyInventory({items:W.items,limit:J,includeArchived:$.includeArchived??!1,storePath:U,storeExists:W.exists,storeReadError:W.read_error});a(_.knowledgeDbPath);let Q=FQ(_.knowledgeDbPath),q=m(_.knowledgeDbPath);try{let L=K6(l_(q,` SELECT s.id, s.uri, @@ -1076,7 +1177,7 @@ Pages should be concise, cited, and organized for both humans and agents. GROUP BY s.id ORDER BY s.updated_at DESC, s.created_at DESC LIMIT ? - `,[J]),["metadata_json","acl_json"]),N=F4(Y4(q,` + `,[J]),["metadata_json","acl_json"]),N=K6(l_(q,` SELECT sr.id, s.uri AS source_uri, @@ -1089,7 +1190,7 @@ Pages should be concise, cited, and organized for both humans and agents. JOIN sources s ON s.id = sr.source_id ORDER BY sr.created_at DESC LIMIT ? - `,[J])),F=F4(Y4(q,` + `,[J])),R=K6(l_(q,` SELECT c.id, c.kind, @@ -1110,22 +1211,22 @@ Pages should be concise, cited, and organized for both humans and agents. LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id ORDER BY c.created_at DESC, c.ordinal ASC LIMIT ? - `,[J])),B=F4(Y4(q,` + `,[J])),B=K6(l_(q,` SELECT id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at FROM wiki_pages ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),H=F4(Y4(q,` + `,[J])),H=K6(l_(q,` SELECT id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at FROM knowledge_indexes ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),V=F4(Y4(q,` + `,[J])),V=K6(l_(q,` SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at FROM storage_objects ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),R=F4(Y4(q,` + `,[J])),K=K6(l_(q,` SELECT id, type, @@ -1141,18 +1242,18 @@ Pages should be concise, cited, and organized for both humans and agents. FROM runs ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),M=Y4(q,` + `,[J])),E=l_(q,` SELECT provider, model, dimensions, status, COUNT(*) AS entries FROM vector_index_entries GROUP BY provider, model, dimensions, status ORDER BY entries DESC LIMIT ? - `,[J]),K=F4(Y4(q,` + `,[J]),F=K6(l_(q,` SELECT id, kind, target_id, source_uri, reason, status, attempts, metadata_json, created_at, updated_at FROM reindex_queue ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),w=F4(Y4(q,` + `,[J])),w=K6(l_(q,` SELECT machine_id, hostname, @@ -1170,7 +1271,7 @@ Pages should be concise, cited, and organized for both humans and agents. FROM knowledge_machines ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J]),["tailscale_ips_json","capabilities_json","metadata_json"]),b=F4(Y4(q,` + `,[J]),["tailscale_ips_json","capabilities_json","metadata_json"]),A=K6(l_(q,` SELECT id, entity_kind, @@ -1187,27 +1288,74 @@ Pages should be concise, cited, and organized for both humans and agents. FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ? - `,[J])),I=F4(Y4(q,` + `,[J])),g=K6(l_(q,` SELECT id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at FROM approval_gates ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[J])),v=F4(Y4(q,` + `,[J])),v=K6(l_(q,` SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT ? - `,[J])),g={legacy_items:W.items.length,active_items:X.length,archived_items:W.items.length-X.length,schema_version:Y.schema_version,sources:Y.sources,source_revisions:Y.source_revisions,chunks:Y.chunks,wiki_pages:Y.wiki_pages,citations:Y.citations,indexes:Y.indexes,runs:Y.runs,run_events:Y.run_events,storage_objects:Y.storage_objects,embeddings:Y.embeddings,vector_entries:Y.vector_entries,reindex_queue:Y.reindex_queue,redaction_findings:Y.redaction_findings,audit_events:Y.audit_events,approval_gates:Y.approval_gates,knowledge_machines:Y.knowledge_machines,sync_snapshots:Y.sync_snapshots,sync_changes:Y.sync_changes,sync_conflicts:Y.sync_conflicts,sync_table_clocks:Y.sync_table_clocks,sync_imports:Y.sync_imports};return{ok:!0,scope:this.scope,home:_.home,limit:J,paths:{json_store_path:U,json_store_exists:W.exists,knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,wiki_dir:_.wikiDir},summary:g,legacy_store:{path:U,exists:W.exists,read_error:W.read_error,total_items:W.items.length,active_items:X.length,archived_items:W.items.length-X.length,items_returned:Math.min(G.length,J)},items:G.slice(0,J).map(QM),sources:L,source_revisions:N,chunks:F,wiki_pages:B,indexes:H,storage_objects:V,runs:R,vector_indexes:M,reindex_queue:K,machines:w,sync_conflicts:b,approval_gates:I,audit_events:v,message:`${W.items.length} item(s), ${Y.sources} source(s), ${Y.chunks} chunk(s), ${Y.wiki_pages} wiki page(s), ${Y.storage_objects} artifact(s)`}}finally{q.close()}}assertAppWikiWrite($){HU({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:$})}async initAppWiki($={}){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return P3({scope:this.scope,workspace:_,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal})}async addAppWikiNote($){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return T3({scope:this.scope,workspace:_,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal,title:$.title,content:$.content,tags:$.tags,sourceRefs:$.sourceRefs,path:$.path,metadata:$.metadata})}listAppWikiNotes($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return[];return S3({dbPath:_.knowledgeDbPath,limit:$.limit})}async getAppWikiNote($,_={}){let J=this.workspace;if(!e$(J.knowledgeDbPath))return null;return Z3({dbPath:J.knowledgeDbPath,store:this.artifactStore(),id:$,includeContent:_.includeContent})}async addAppWikiSourceRef($){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return v3({scope:this.scope,workspace:_,sourceRef:$.sourceRef,purpose:$.purpose,config:this.config(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal})}async searchAppWiki($){return this.search($)}async queryAppWiki($){return this.retrieveContext($)}async initWiki(){let $=this.ensureWorkspace();G$($.knowledgeDbPath);let _=await cK(this.artifactStore()),J=i($.knowledgeDbPath);try{m0(J,_.artifacts),lK(J,_.artifacts)}finally{J.close()}return _}async compileWiki($={}){let _=this.ensureWorkspace();return mK({...$,dbPath:_.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer($){let _=this.ensureWorkspace(),J=await this.retrieveContext({query:$.prompt,limit:$.limit,semantic:$.semantic,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake});return xK({dbPath:_.knowledgeDbPath,store:this.artifactStore(),prompt:$.prompt,answer:$.answer,context:J,approveWrite:$.approveWrite})}lintWiki(){let $=this.ensureWorkspace();return uK({dbPath:$.knowledgeDbPath})}async ingestManifest($){let _=this.ensureWorkspace();return I3({dbPath:_.knowledgeDbPath,input:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource($,_){let J=this.ensureWorkspace();return u9({dbPath:J.knowledgeDbPath,sourceRef:$,purpose:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance($={}){let _=$.dryRun!==!1,J=_?this.workspace:this.ensureWorkspace();return gK({root:$.root??this.options.cwd??process.cwd(),scope:this.scope,owner:$.owner,dryRun:_,deprecateLegacy:$.deprecateLegacy,includeLegacy:$.includeLegacy,legacyStorePath:J.jsonStorePath,dbPath:J.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:$.maxItems,limit:$.limit})}async resolveSource($,_={}){let J=this.ensureWorkspace();return h9({dbPath:J.knowledgeDbPath,sourceRef:$,purpose:_.purpose,limit:_.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox($){let _=this.ensureWorkspace();return tR({dbPath:_.knowledgeDbPath,input:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return uc();return NK({...$,dbPath:_.knowledgeDbPath,config:this.config()})}enqueueReindex($={}){let _=this.ensureWorkspace();return BL({...$,dbPath:_.knowledgeDbPath,config:this.config()})}async refreshEmbeddings($={}){let _=this.ensureWorkspace();return VK({...$,dbPath:_.knowledgeDbPath,config:this.config()})}providerStatus($=process.env){return u3(this.config(),$)}modelRegistry(){return CY(this.config())}embeddingStatus(){let $=this.workspace;if(!e$($.knowledgeDbPath))return dc();return r3($.knowledgeDbPath)}async indexEmbeddings($={}){let _=this.ensureWorkspace();return l9({...$,dbPath:_.knowledgeDbPath,config:this.config()})}isApiMode(){return V1()}async fetchCloudItems(){let $=BU();if(!$)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return C9($)}async semanticSearch($){let _=this.workspace;if(this.isApiMode()){let J=await this.fetchCloudItems(),U=await w2(J,{...$},["semantic_search_requires_local_catalog"]);return{provider:"openai",model:"text-embedding-3-small",dimensions:$.dimensions??1536,query:$.query,results:U.results}}if(!e$(_.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:$.dimensions??1536,query:$.query,results:[]};return n9({...$,dbPath:_.knowledgeDbPath,config:this.config()})}async search($){let _=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return w2(U,$)}let J=ZL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){if(e$(J))return o9({...$,legacyStorePath:J,config:this.config()});return FM($.query,Math.max(1,Math.min($.limit??10,100)),$.semantic===!0||$.fake===!0||Boolean($.modelRef))}return p9({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async retrieveContext($){let _=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return a9(U,$)}let J=ZL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){if(e$(J)){let U=await o9({...$,legacyStorePath:J,config:this.config()});return CJ(U,{contextChars:$.contextChars})}return mc($.query,Math.max(1,Math.min($.limit??10,100)),$.semantic===!0||$.fake===!0||Boolean($.modelRef))}return PJ({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async contextPack($){let _=this.workspace;if(this.isApiMode()){let U=($.query??$.topic??"").trim();if(U&&$.source!=="loops"&&$.source!=="runs"){let W=await this.fetchCloudItems(),X=await w2(W,{...$,query:U}),G=CJ(X,{contextChars:$.contextChars});return zM($,G,this.safetyPolicy())}return jM($)}let J=ZL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){let U=($.query??$.topic??"").trim();if(U&&$.source!=="loops"&&$.source!=="runs"&&e$(J)){let W=await o9({...$,query:U,legacyStorePath:J,config:this.config()}),X=CJ(W,{contextChars:$.contextChars});return zM($,X,this.safetyPolicy())}return jM($)}return AV({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt($){if(this.isApiMode()){let U=await this.fetchCloudItems();return LV(U,{...$,config:this.config()})}let _=this.ensureWorkspace(),J=$.legacyStorePath??_.jsonStorePath;if(!$.legacyStorePath)uW(J);return DV({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async webSearch($){let _=this.ensureWorkspace();return PK({...$,dbPath:_.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology($={}){let _=this.workspace;return jK({...$,knowledge:{scope:this.scope,workspace_home:_.home}})}async machinePreflight($={}){let _=this.workspace;return LK({...$,knowledge:{scope:this.scope,workspace_home:_.home}})}syncStatus(){let $=this.workspace;if(!e$($.knowledgeDbPath))return cc({scope:this.scope,workspaceHome:$.home});return iV({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home})}async syncDoctor($={}){let _=this.ensureWorkspace();G$(_.knowledgeDbPath);let J=this.syncStatus(),U=this.storageContract(),W=this.validateStorage(),X=lc(_.knowledgeDbPath,U),G=$.machine?.trim()||null,Q=$.peerWorkspace?.trim()||null,Y=[],q=null,L=null;if(G&&!BM(G)){let V=await LL({machineId:G,includeTailscale:$.includeTailscale});q=SL(V),Y.push(...V.warnings)}if(G||Q){let V=await y5({machineId:G??TL(_),peerWorkspace:Q,includeTailscale:$.includeTailscale});if(G&&!Q&&(q?.source==="raw"||!V.ok||!V.project_root)){let R=JM(_.knowledgeDbPath,G);if(R){if(q?.source==="raw"&&R.ssh_target)q=SL(WM(R,G,{target:q.target,route:q.route,targetKind:q.target_kind,confidence:q.confidence,source:q.source,adapter:q.adapter,evidence:q.evidence,cacheability:q.cacheability,warnings:[]}));if(!V.ok||!V.project_root){let M=UM(R,G,V);if(M)L=dX(M,M.project_root),Y.push(...M.warnings)}}}L=V.ok&&V.project_root?dX(V,V.project_root):L??{...dX(V,Q??""),project_root:V.project_root??Q??""},Y.push(...V.warnings)}if(!W.ok)Y.push(...W.errors.map((V)=>`storage:${V}`));let N=Sc(_.knowledgeDbPath,L);if(!N.ok)Y.push("open_files_boundary_raw_payload_sentinels");if(!X.ok)Y.push(...X.warnings);let F=L?.diagnostics.filter((V)=>V.severity==="fail")??[],B=W.ok&&X.ok&&N.ok&&F.length===0&&(L?.project_root!==""||!L),H=ic({scope:this.scope,machine:G,peerWorkspace:Q,tables:$.tables,resolvedWorkspace:L,openConflicts:J.conflicts.open});return{ok:B,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:_.home,database:{sqlite_schema_version:J.sqlite_schema_version,table_counts:J.table_counts},storage:{contract:U,validation:W,artifact_manifest:X},sync:{machines:J.machines.total,snapshots:J.snapshots.total,clocks:J.clocks.total,imports:J.imports.total,open_conflicts:J.conflicts.open,table_clocks:J.clocks.rows},open_files:N,resolved_route:q,resolved_workspace:L,recommended_commands:H,warnings:[...new Set(Y)],message:B?`Sync readiness ok: ${J.clocks.total} table clock(s), ${J.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(Y)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys($={}){let _=this.ensureWorkspace();G$(_.knowledgeDbPath);let J=this.storageContract(),U=mL(J),W=nc(_.knowledgeDbPath,J),X=$.dryRun===!0||$.approveWrite!==!0;if(W.length===0)return{ok:!0,dry_run:X,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:"No legacy S3 artifact manifest keys found"};if($.dryRun===!0)return{ok:!0,dry_run:!0,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:`Would repair ${W.length} legacy S3 artifact manifest key(s)`};if($.approveWrite!==!0||!$.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let G=i(_.knowledgeDbPath);try{let Q=new Date().toISOString();G.transaction((L)=>{let N=G.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),F=G.query("SELECT id, metadata_json FROM storage_objects").all(),B=new Map(F.map((H)=>[H.id,LW(H.metadata_json)]));for(let H of L){let V=B.get(H.id)??{};V.key=H.repaired_key,N.run(JSON.stringify(V),Q,H.id)}})(W);let q=O6(G,{event_type:"artifact_manifest_key_repair",action:"storage.artifact_manifest.repair_keys",target_uri:`knowledge-storage://${_.home}/storage_objects`,decision:"allow",metadata:{approved_by:$.approvedBy,repaired:W.length,storage_type:J.storage_type,storage_prefix:U,artifact_uris:W.map((L)=>L.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:W.length,audit_event_id:q,message:`Repaired ${W.length} legacy S3 artifact manifest key(s)`}}finally{G.close()}}async createSyncSnapshot($={}){let _=this.ensureWorkspace(),J=await this.machineTopology({includeTailscale:$.includeTailscale!==!1});return nV({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home,storage:this.storageContract(),topology:J,machineId:$.machineId})}syncConflicts($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return[];return rV(_.knowledgeDbPath,$)}syncConflict($){let _=this.ensureWorkspace(),J=Q8(_.knowledgeDbPath,$);if(!J)throw Error(`Sync conflict not found: ${$}`);return J}proposeSyncConflictResolution($){let _=this.ensureWorkspace();return wU(_.knowledgeDbPath,$)}async proposeSyncConflictResolutionWithAi($){let _=this.ensureWorkspace();return pR({dbPath:_.knowledgeDbPath,id:$.id,config:this.config(),modelRef:$.modelRef,fake:$.fake,env:$.env})}resolveSyncConflict($){let _=this.ensureWorkspace(),J=wU(_.knowledgeDbPath,$.id);if($.approveWrite!==!0||!$.approvedBy)return{ok:!1,approval_required:!0,conflict:J.conflict,proposal:J,message:"Sync conflict resolution requires --approve-write and --approved-by "};let U=tV(_.knowledgeDbPath,{id:$.id,strategy:$.strategy??J.proposed_strategy,approvedBy:$.approvedBy,proposedPatchUri:$.proposedPatchUri}),W=i(_.knowledgeDbPath);try{let X=O6(W,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${$.id}`,decision:"allow",metadata:{conflict_id:$.id,entity_kind:U.entity_kind,entity_id:U.entity_id,strategy:U.resolution_strategy,approved_by:U.approved_by,proposed_patch_uri:U.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:U,audit_event_id:X,message:`Resolved sync conflict ${$.id}`}}finally{W.close()}}syncMachines(){let $=this.workspace;if(!e$($.knowledgeDbPath))return[];return tY($.knowledgeDbPath)}exportSyncBundle($={}){let _=this.ensureWorkspace();return this.assertStorageValid("sync export"),G$(_.knowledgeDbPath),EU({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home,storage:this.storageContract(),machineId:$.machineId??null,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.recordClocks!==!1})}async importSyncBundle($){let _=this.ensureWorkspace();return this.assertStorageValid("sync import"),G$(_.knowledgeDbPath),G8({targetDbPath:_.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:_.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:$.bundle,direction:$.direction??"import",dryRun:$.dryRun,localMachineId:$.machineId??null})}async syncRemotePeer($){let _=$.direction??"both",J=$.dryRun===!0,U=this.ensureWorkspace();G$(U.knowledgeDbPath);let W=$.tables?.length?["--tables",$.tables.join(",")]:[],X=$.includeArtifactContent===!1?["--no-artifact-content"]:[],G=["--scope",this.scope,"--json"],Q=await LL({machineId:$.machine,includeTailscale:$.includeTailscale}),Y=await y5({machineId:$.machine,peerWorkspace:$.peerWorkspace,includeTailscale:$.includeTailscale});if(!$.peerWorkspace&&Q.source==="raw"||!Y.ok||!Y.project_root){let B=JM(U.knowledgeDbPath,$.machine);if(B){if(!$.peerWorkspace&&Q.source==="raw"&&B.ssh_target)Q=WM(B,$.machine,Q);if(!Y.ok||!Y.project_root){let H=UM(B,$.machine,Y);if(H)Y=H}}}if(!Y.ok||!Y.project_root)throw Error([`Unable to resolve peer workspace for ${$.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",Y.warnings.length?`Warnings: ${Y.warnings.join(", ")}`:null].filter(Boolean).join(" "));let q=Y.project_root,L={ok:!0,dry_run:J,direction:_,transport:"ssh",machine:$.machine,resolved_machine:Q.target,resolved_route:SL(Q),resolved_workspace:dX(Y,Y.project_root),peer_workspace:q,message:""},N=!1,F=()=>{if(J||N)return;dV(U.knowledgeDbPath,{machineId:$.machine,route:Q,workspace:Y}),N=!0};if(_==="pull"||_==="both"){let B=_M(q,["sync","export",...G,...W,...X]),H=OM($.machine,B,void 0,Q),V=DM($.machine,"sync export",H);pc($.machine,V),L.pull=await this.importSyncBundle({bundle:V,dryRun:J,direction:"pull",machineId:$.machineId??null})}if(_==="push"||_==="both"){F();let B=this.exportSyncBundle({machineId:$.machineId??null,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:!J}),H=_M(q,["sync","import",...G,...J?["--dry-run"]:[]]),V=DM($.machine,"sync import",OM($.machine,H,JSON.stringify(B),Q));oc($.machine,V),L.push=V}return L.ok=(L.pull?.ok??!0)&&(L.push?.ok??!0),F(),L.message=[XM(L.resolved_workspace),L.pull?`pull: ${L.pull.message}`:null,L.push?`push: ${L.push.message}`:null].filter(Boolean).join("; "),L}async syncPeer($){let _=$.direction??"both",J=this.ensureWorkspace();G$(J.knowledgeDbPath);let U=LM($.peerWorkspace),W=wc(U);G$(W.knowledgeDbPath);let X=DQ(W.configPath),G=Z9(X,W,this.scope),Q=NY(X,W),Y=$.machineId??TL(J),q=TL(W),L=await y5({machineId:$.machineId??q,peerWorkspace:U,includeTailscale:!1}),N=()=>EU({dbPath:J.knowledgeDbPath,scope:this.scope,workspaceHome:J.home,storage:this.storageContract(),machineId:Y,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.dryRun!==!0}),F=()=>EU({dbPath:W.knowledgeDbPath,scope:this.scope,workspaceHome:W.home,storage:G,machineId:q,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.dryRun!==!0}),B={ok:!0,dry_run:$.dryRun===!0,direction:_,resolved_workspace:dX(L,L.project_root??U),message:""};if(_==="pull"||_==="both")B.pull=await G8({targetDbPath:J.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:J.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:F(),targetBundle:N(),direction:"pull",dryRun:$.dryRun,localMachineId:Y});if(_==="push"||_==="both")B.push=await G8({targetDbPath:W.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:W.home,targetStorage:G,targetStore:Q,bundle:N(),targetBundle:F(),direction:"push",dryRun:$.dryRun,localMachineId:q});return B.ok=(B.pull?.ok??!0)&&(B.push?.ok??!0),B.message=[XM(B.resolved_workspace),B.pull?`pull: ${B.pull.message}`:null,B.push?`push: ${B.push.message}`:null].filter(Boolean).join("; "),B}}function r5($={}){return new RM($)}var ac=Object.defineProperty,sc=($)=>$;function ec($,_){this[$]=sc.bind(null,_)}var $l=($,_)=>{for(var J in _)ac($,J,{get:_[J],enumerable:!0,configurable:!0,set:ec.bind(_,J)})},D={};$l(D,{void:()=>hl,util:()=>x$,unknown:()=>vl,union:()=>dl,undefined:()=>Tl,tuple:()=>nl,transformer:()=>AM,symbol:()=>Pl,string:()=>TM,strictObject:()=>ul,setErrorMap:()=>Wl,set:()=>pl,record:()=>il,quotelessJson:()=>_l,promise:()=>$n,preprocess:()=>Wn,pipeline:()=>Un,ostring:()=>Xn,optional:()=>_n,onumber:()=>Gn,oboolean:()=>Qn,objectUtil:()=>cL,object:()=>xl,number:()=>SM,nullable:()=>Jn,null:()=>Sl,never:()=>yl,nativeEnum:()=>el,nan:()=>kl,map:()=>rl,makeIssue:()=>o5,literal:()=>al,lazy:()=>tl,late:()=>Il,isValid:()=>Y_,isDirty:()=>nL,isAsync:()=>iX,isAborted:()=>lL,intersection:()=>ll,instanceof:()=>gl,getParsedType:()=>e0,getErrorMap:()=>p5,function:()=>ol,enum:()=>sl,effect:()=>AM,discriminatedUnion:()=>cl,defaultErrorMap:()=>VW,datetimeRegex:()=>fM,date:()=>Cl,custom:()=>PM,coerce:()=>Yn,boolean:()=>ZM,bigint:()=>fl,array:()=>ml,any:()=>Zl,addIssueToContext:()=>n,ZodVoid:()=>pX,ZodUnknown:()=>u1,ZodUnion:()=>MW,ZodUndefined:()=>RW,ZodType:()=>S$,ZodTuple:()=>H0,ZodTransformer:()=>R4,ZodSymbol:()=>rX,ZodString:()=>n4,ZodSet:()=>j_,ZodSchema:()=>S$,ZodRecord:()=>oX,ZodReadonly:()=>kW,ZodPromise:()=>O_,ZodPipeline:()=>sX,ZodParsedType:()=>t,ZodOptional:()=>r4,ZodObject:()=>V6,ZodNumber:()=>d1,ZodNullable:()=>$1,ZodNull:()=>KW,ZodNever:()=>B0,ZodNativeEnum:()=>wW,ZodNaN:()=>aX,ZodMap:()=>tX,ZodLiteral:()=>EW,ZodLazy:()=>bW,ZodIssueCode:()=>Z,ZodIntersection:()=>AW,ZodFunction:()=>NW,ZodFirstPartyTypeKind:()=>B$,ZodError:()=>q4,ZodEnum:()=>l1,ZodEffects:()=>R4,ZodDiscriminatedUnion:()=>t5,ZodDefault:()=>IW,ZodDate:()=>q_,ZodCatch:()=>gW,ZodBranded:()=>a5,ZodBoolean:()=>FW,ZodBigInt:()=>c1,ZodArray:()=>i4,ZodAny:()=>z_,Schema:()=>S$,ParseStatus:()=>y6,OK:()=>n6,NEVER:()=>qn,INVALID:()=>j$,EMPTY_PATH:()=>Ul,DIRTY:()=>HW,BRAND:()=>wl});var x$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Q)=>typeof W[W[Q]]!=="number"),G={};for(let Q of X)G[Q]=W[Q];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(x$||(x$={}));var cL;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(cL||(cL={}));var t=x$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),e0=($)=>{switch(typeof $){case"undefined":return t.undefined;case"string":return t.string;case"number":return Number.isNaN($)?t.nan:t.number;case"boolean":return t.boolean;case"function":return t.function;case"bigint":return t.bigint;case"symbol":return t.symbol;case"object":if(Array.isArray($))return t.array;if($===null)return t.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return t.promise;if(typeof Map<"u"&&$ instanceof Map)return t.map;if(typeof Set<"u"&&$ instanceof Set)return t.set;if(typeof Date<"u"&&$ instanceof Date)return t.date;return t.object;default:return t.unknown}},Z=x$.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"]),_l=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class q4 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Q=0;while(Q_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}q4.create=($)=>{return new q4($)};var Jl=($,_)=>{let J;switch($.code){case Z.invalid_type:if($.received===t.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case Z.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,x$.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:J=`Unrecognized key(s) in object: ${x$.joinValues($.keys,", ")}`;break;case Z.invalid_union:J="Invalid input";break;case Z.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${x$.joinValues($.options)}`;break;case Z.invalid_enum_value:J=`Invalid enum value. Expected ${x$.joinValues($.options)}, received '${$.received}'`;break;case Z.invalid_arguments:J="Invalid function arguments";break;case Z.invalid_return_type:J="Invalid function return type";break;case Z.invalid_date:J="Invalid date";break;case Z.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else x$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case Z.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case Z.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case Z.custom:J="Invalid input";break;case Z.invalid_intersection_types:J="Intersection results could not be merged";break;case Z.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case Z.not_finite:J="Number must be finite";break;default:J=_.defaultError,x$.assertNever($)}return{message:J}},VW=Jl,IM=VW;function Wl($){IM=$}function p5(){return IM}var o5=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Q="",Y=U.filter((q)=>!!q).slice().reverse();for(let q of Y)Q=q(G,{data:_,defaultError:Q}).message;return{...W,path:X,message:Q}},Ul=[];function n($,_){let J=p5(),U=o5({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===VW?void 0:VW].filter((W)=>!!W)});$.common.issues.push(U)}class y6{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return j$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return y6.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return j$;if(X.status==="aborted")return j$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var j$=Object.freeze({status:"aborted"}),HW=($)=>({status:"dirty",value:$}),n6=($)=>({status:"valid",value:$}),lL=($)=>$.status==="aborted",nL=($)=>$.status==="dirty",Y_=($)=>$.status==="valid",iX=($)=>typeof Promise<"u"&&$ instanceof Promise,X$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(X$||(X$={}));class p4{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var KM=($,_)=>{if(Y_(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new q4($.common.issues);return this._error=J,this._error}}}};function w$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Q)=>{let{message:Y}=$;if(G.code==="invalid_enum_value")return{message:Y??Q.defaultError};if(typeof Q.data>"u")return{message:Y??U??Q.defaultError};if(G.code!=="invalid_type")return{message:Q.defaultError};return{message:Y??J??Q.defaultError}},description:W}}class S${get description(){return this._def.description}_getType($){return e0($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:e0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new y6,ctx:{common:$.parent.common,data:$.data,parsedType:e0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(iX(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:e0($)},U=this._parseSync({data:$,path:J.path,parent:J});return KM(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:e0($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return Y_(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>Y_(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:e0($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(iX(U)?U:Promise.resolve(U));return KM(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:Z.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Q)=>{if(!Q)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new R4({schema:this,typeName:B$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return r4.create(this,this._def)}nullable(){return $1.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return i4.create(this)}promise(){return O_.create(this,this._def)}or($){return MW.create([this,$],this._def)}and($){return AW.create(this,$,this._def)}transform($){return new R4({...w$(this._def),schema:this,typeName:B$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new IW({...w$(this._def),innerType:this,defaultValue:_,typeName:B$.ZodDefault})}brand(){return new a5({typeName:B$.ZodBranded,type:this,...w$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new gW({...w$(this._def),innerType:this,catchValue:_,typeName:B$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return sX.create(this,$)}readonly(){return kW.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Xl=/^c[^\s-]{8,}$/i,Gl=/^[0-9a-z]+$/,Ql=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yl=/^[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,ql=/^[a-z0-9_-]{21}$/i,zl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,jl=/^[-+]?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)?)??$/,Ol=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Dl="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xL,Ll=/^(?:(?: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])$/,Bl=/^(?:(?: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])$/,Hl=/^(([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]))$/,Nl=/^(([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])$/,Vl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gM="((\\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])))",Rl=new RegExp(`^${gM}$`);function kM($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function Kl($){return new RegExp(`^${kM($)}$`)}function fM($){let _=`${gM}T${kM($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function Ml($,_){if((_==="v4"||!_)&&Ll.test($))return!0;if((_==="v6"||!_)&&Hl.test($))return!0;return!1}function Al($,_){if(!zl.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function bl($,_){if((_==="v4"||!_)&&Bl.test($))return!0;if((_==="v6"||!_)&&Nl.test($))return!0;return!1}class n4 extends S${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==t.string){let W=this._getOrReturnCtx($);return n(W,{code:Z.invalid_type,expected:t.string,received:W.parsedType}),j$}let J=new y6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),n(U,{code:Z.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:Z.invalid_string,...X$.errToObj(J)})}_addCheck($){return new n4({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...X$.errToObj($)})}url($){return this._addCheck({kind:"url",...X$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...X$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...X$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...X$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...X$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...X$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...X$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...X$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...X$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...X$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...X$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...X$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...X$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...X$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...X$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...X$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...X$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...X$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...X$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...X$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...X$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...X$.errToObj(_)})}nonempty($){return this.min(1,X$.errToObj($))}trim(){return new n4({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n4({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n4({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}n4.create=($)=>{return new n4({checks:[],typeName:B$.ZodString,coerce:$?.coerce??!1,...w$($)})};function El($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class d1 extends S${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==t.number){let W=this._getOrReturnCtx($);return n(W,{code:Z.invalid_type,expected:t.number,received:W.parsedType}),j$}let J=void 0,U=new y6;for(let W of this._def.checks)if(W.kind==="int"){if(!x$.isInteger($.data))J=this._getOrReturnCtx($,J),n(J,{code:Z.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),n(J,{code:Z.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(El($.data,W.value)!==0)J=this._getOrReturnCtx($,J),n(J,{code:Z.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),n(J,{code:Z.not_finite,message:W.message}),U.dirty()}else x$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,X$.toString(_))}gt($,_){return this.setLimit("min",$,!1,X$.toString(_))}lte($,_){return this.setLimit("max",$,!0,X$.toString(_))}lt($,_){return this.setLimit("max",$,!1,X$.toString(_))}setLimit($,_,J,U){return new d1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:X$.toString(U)}]})}_addCheck($){return new d1({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:X$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:X$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:X$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&x$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}d1.create=($)=>{return new d1({checks:[],typeName:B$.ZodNumber,coerce:$?.coerce||!1,...w$($)})};class c1 extends S${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==t.bigint)return this._getInvalidInput($);let J=void 0,U=new y6;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),n(J,{code:Z.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),n(J,{code:Z.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else x$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return n(_,{code:Z.invalid_type,expected:t.bigint,received:_.parsedType}),j$}gte($,_){return this.setLimit("min",$,!0,X$.toString(_))}gt($,_){return this.setLimit("min",$,!1,X$.toString(_))}lte($,_){return this.setLimit("max",$,!0,X$.toString(_))}lt($,_){return this.setLimit("max",$,!1,X$.toString(_))}setLimit($,_,J,U){return new c1({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:X$.toString(U)}]})}_addCheck($){return new c1({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:X$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}c1.create=($)=>{return new c1({checks:[],typeName:B$.ZodBigInt,coerce:$?.coerce??!1,...w$($)})};class FW extends S${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==t.boolean){let J=this._getOrReturnCtx($);return n(J,{code:Z.invalid_type,expected:t.boolean,received:J.parsedType}),j$}return n6($.data)}}FW.create=($)=>{return new FW({typeName:B$.ZodBoolean,coerce:$?.coerce||!1,...w$($)})};class q_ extends S${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==t.date){let W=this._getOrReturnCtx($);return n(W,{code:Z.invalid_type,expected:t.date,received:W.parsedType}),j$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return n(W,{code:Z.invalid_date}),j$}let J=new y6,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),n(U,{code:Z.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else x$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new q_({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:X$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:X$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}q_.create=($)=>{return new q_({checks:[],coerce:$?.coerce||!1,typeName:B$.ZodDate,...w$($)})};class rX extends S${_parse($){if(this._getType($)!==t.symbol){let J=this._getOrReturnCtx($);return n(J,{code:Z.invalid_type,expected:t.symbol,received:J.parsedType}),j$}return n6($.data)}}rX.create=($)=>{return new rX({typeName:B$.ZodSymbol,...w$($)})};class RW extends S${_parse($){if(this._getType($)!==t.undefined){let J=this._getOrReturnCtx($);return n(J,{code:Z.invalid_type,expected:t.undefined,received:J.parsedType}),j$}return n6($.data)}}RW.create=($)=>{return new RW({typeName:B$.ZodUndefined,...w$($)})};class KW extends S${_parse($){if(this._getType($)!==t.null){let J=this._getOrReturnCtx($);return n(J,{code:Z.invalid_type,expected:t.null,received:J.parsedType}),j$}return n6($.data)}}KW.create=($)=>{return new KW({typeName:B$.ZodNull,...w$($)})};class z_ extends S${constructor(){super(...arguments);this._any=!0}_parse($){return n6($.data)}}z_.create=($)=>{return new z_({typeName:B$.ZodAny,...w$($)})};class u1 extends S${constructor(){super(...arguments);this._unknown=!0}_parse($){return n6($.data)}}u1.create=($)=>{return new u1({typeName:B$.ZodUnknown,...w$($)})};class B0 extends S${_parse($){let _=this._getOrReturnCtx($);return n(_,{code:Z.invalid_type,expected:t.never,received:_.parsedType}),j$}}B0.create=($)=>{return new B0({typeName:B$.ZodNever,...w$($)})};class pX extends S${_parse($){if(this._getType($)!==t.undefined){let J=this._getOrReturnCtx($);return n(J,{code:Z.invalid_type,expected:t.void,received:J.parsedType}),j$}return n6($.data)}}pX.create=($)=>{return new pX({typeName:B$.ZodVoid,...w$($)})};class i4 extends S${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==t.array)return n(_,{code:Z.invalid_type,expected:t.array,received:_.parsedType}),j$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)n(_,{code:Z.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new p4(_,X,_.path,G))})).then((X)=>{return y6.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new p4(_,X,_.path,G))});return y6.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new i4({...this._def,minLength:{value:$,message:X$.toString(_)}})}max($,_){return new i4({...this._def,maxLength:{value:$,message:X$.toString(_)}})}length($,_){return new i4({...this._def,exactLength:{value:$,message:X$.toString(_)}})}nonempty($){return this.min(1,$)}}i4.create=($,_)=>{return new i4({type:$,minLength:null,maxLength:null,exactLength:null,typeName:B$.ZodArray,...w$(_)})};function BW($){if($ instanceof V6){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=r4.create(BW(U))}return new V6({...$._def,shape:()=>_})}else if($ instanceof i4)return new i4({...$._def,type:BW($.element)});else if($ instanceof r4)return r4.create(BW($.unwrap()));else if($ instanceof $1)return $1.create(BW($.unwrap()));else if($ instanceof H0)return H0.create($.items.map((_)=>BW(_)));else return $}class V6 extends S${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=x$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==t.object){let Y=this._getOrReturnCtx($);return n(Y,{code:Z.invalid_type,expected:t.object,received:Y.parsedType}),j$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof B0&&this._def.unknownKeys==="strip")){for(let Y in U.data)if(!X.includes(Y))G.push(Y)}let Q=[];for(let Y of X){let q=W[Y],L=U.data[Y];Q.push({key:{status:"valid",value:Y},value:q._parse(new p4(U,L,U.path,Y)),alwaysSet:Y in U.data})}if(this._def.catchall instanceof B0){let Y=this._def.unknownKeys;if(Y==="passthrough")for(let q of G)Q.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Y==="strict"){if(G.length>0)n(U,{code:Z.unrecognized_keys,keys:G}),J.dirty()}else if(Y==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Y=this._def.catchall;for(let q of G){let L=U.data[q];Q.push({key:{status:"valid",value:q},value:Y._parse(new p4(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Y=[];for(let q of Q){let L=await q.key,N=await q.value;Y.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Y}).then((Y)=>{return y6.mergeObjectSync(J,Y)});else return y6.mergeObjectSync(J,Q)}get shape(){return this._def.shape()}strict($){return X$.errToObj,new V6({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:X$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new V6({...this._def,unknownKeys:"strip"})}passthrough(){return new V6({...this._def,unknownKeys:"passthrough"})}extend($){return new V6({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new V6({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:B$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new V6({...this._def,catchall:$})}pick($){let _={};for(let J of x$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new V6({...this._def,shape:()=>_})}omit($){let _={};for(let J of x$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new V6({...this._def,shape:()=>_})}deepPartial(){return BW(this)}partial($){let _={};for(let J of x$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new V6({...this._def,shape:()=>_})}required($){let _={};for(let J of x$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof r4)W=W._def.innerType;_[J]=W}return new V6({...this._def,shape:()=>_})}keyof(){return CM(x$.objectKeys(this.shape))}}V6.create=($,_)=>{return new V6({shape:()=>$,unknownKeys:"strip",catchall:B0.create(),typeName:B$.ZodObject,...w$(_)})};V6.strictCreate=($,_)=>{return new V6({shape:()=>$,unknownKeys:"strict",catchall:B0.create(),typeName:B$.ZodObject,...w$(_)})};V6.lazycreate=($,_)=>{return new V6({shape:$,unknownKeys:"strip",catchall:B0.create(),typeName:B$.ZodObject,...w$(_)})};class MW extends S${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new q4(G.ctx.common.issues));return n(_,{code:Z.invalid_union,unionErrors:X}),j$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Q of J){let Y={..._,common:{..._.common,issues:[]},parent:null},q=Q._parseSync({data:_.data,path:_.path,parent:Y});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Y};if(Y.common.issues.length)X.push(Y.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Q)=>new q4(Q));return n(_,{code:Z.invalid_union,unionErrors:G}),j$}}get options(){return this._def.options}}MW.create=($,_)=>{return new MW({options:$,typeName:B$.ZodUnion,...w$(_)})};var s0=($)=>{if($ instanceof bW)return s0($.schema);else if($ instanceof R4)return s0($.innerType());else if($ instanceof EW)return[$.value];else if($ instanceof l1)return $.options;else if($ instanceof wW)return x$.objectValues($.enum);else if($ instanceof IW)return s0($._def.innerType);else if($ instanceof RW)return[void 0];else if($ instanceof KW)return[null];else if($ instanceof r4)return[void 0,...s0($.unwrap())];else if($ instanceof $1)return[null,...s0($.unwrap())];else if($ instanceof a5)return s0($.unwrap());else if($ instanceof kW)return s0($.unwrap());else if($ instanceof gW)return s0($._def.innerType);else return[]};class t5 extends S${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.object)return n(_,{code:Z.invalid_type,expected:t.object,received:_.parsedType}),j$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return n(_,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),j$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=s0(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new t5({typeName:B$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...w$(J)})}}function iL($,_){let J=e0($),U=e0(_);if($===_)return{valid:!0,data:$};else if(J===t.object&&U===t.object){let W=x$.objectKeys(_),X=x$.objectKeys($).filter((Q)=>W.indexOf(Q)!==-1),G={...$,..._};for(let Q of X){let Y=iL($[Q],_[Q]);if(!Y.valid)return{valid:!1};G[Q]=Y.data}return{valid:!0,data:G}}else if(J===t.array&&U===t.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Q=_[X],Y=iL(G,Q);if(!Y.valid)return{valid:!1};W.push(Y.data)}return{valid:!0,data:W}}else if(J===t.date&&U===t.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class AW extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(lL(W)||lL(X))return j$;let G=iL(W.value,X.value);if(!G.valid)return n(J,{code:Z.invalid_intersection_types}),j$;if(nL(W)||nL(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}AW.create=($,_,J)=>{return new AW({left:$,right:_,typeName:B$.ZodIntersection,...w$(J)})};class H0 extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.array)return n(J,{code:Z.invalid_type,expected:t.array,received:J.parsedType}),j$;if(J.data.lengththis._def.items.length)n(J,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Q=this._def.items[G]||this._def.rest;if(!Q)return null;return Q._parse(new p4(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return y6.mergeArray(_,X)});else return y6.mergeArray(_,W)}get items(){return this._def.items}rest($){return new H0({...this._def,rest:$})}}H0.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new H0({items:$,typeName:B$.ZodTuple,rest:null,...w$(_)})};class oX extends S${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.object)return n(J,{code:Z.invalid_type,expected:t.object,received:J.parsedType}),j$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new p4(J,G,J.path,G)),value:X._parse(new p4(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return y6.mergeObjectAsync(_,U);else return y6.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof S$)return new oX({keyType:$,valueType:_,typeName:B$.ZodRecord,...w$(J)});return new oX({keyType:n4.create(),valueType:$,typeName:B$.ZodRecord,...w$(_)})}}class tX extends S${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.map)return n(J,{code:Z.invalid_type,expected:t.map,received:J.parsedType}),j$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Q],Y)=>{return{key:U._parse(new p4(J,G,J.path,[Y,"key"])),value:W._parse(new p4(J,Q,J.path,[Y,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Q of X){let Y=await Q.key,q=await Q.value;if(Y.status==="aborted"||q.status==="aborted")return j$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Q of X){let{key:Y,value:q}=Q;if(Y.status==="aborted"||q.status==="aborted")return j$;if(Y.status==="dirty"||q.status==="dirty")_.dirty();G.set(Y.value,q.value)}return{status:_.value,value:G}}}}tX.create=($,_,J)=>{return new tX({valueType:_,keyType:$,typeName:B$.ZodMap,...w$(J)})};class j_ extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.set)return n(J,{code:Z.invalid_type,expected:t.set,received:J.parsedType}),j$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)n(J,{code:Z.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Q){let Y=new Set;for(let q of Q){if(q.status==="aborted")return j$;if(q.status==="dirty")_.dirty();Y.add(q.value)}return{status:_.value,value:Y}}let G=[...J.data.values()].map((Q,Y)=>W._parse(new p4(J,Q,J.path,Y)));if(J.common.async)return Promise.all(G).then((Q)=>X(Q));else return X(G)}min($,_){return new j_({...this._def,minSize:{value:$,message:X$.toString(_)}})}max($,_){return new j_({...this._def,maxSize:{value:$,message:X$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}j_.create=($,_)=>{return new j_({valueType:$,minSize:null,maxSize:null,typeName:B$.ZodSet,...w$(_)})};class NW extends S${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.function)return n(_,{code:Z.invalid_type,expected:t.function,received:_.parsedType}),j$;function J(G,Q){return o5({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,p5(),VW].filter((Y)=>!!Y),issueData:{code:Z.invalid_arguments,argumentsError:Q}})}function U(G,Q){return o5({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,p5(),VW].filter((Y)=>!!Y),issueData:{code:Z.invalid_return_type,returnTypeError:Q}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof O_){let G=this;return n6(async function(...Q){let Y=new q4([]),q=await G._def.args.parseAsync(Q,W).catch((F)=>{throw Y.addIssue(J(Q,F)),Y}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((F)=>{throw Y.addIssue(U(L,F)),Y})})}else{let G=this;return n6(function(...Q){let Y=G._def.args.safeParse(Q,W);if(!Y.success)throw new q4([J(Q,Y.error)]);let q=Reflect.apply(X,this,Y.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new q4([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new NW({...this._def,args:H0.create($).rest(u1.create())})}returns($){return new NW({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new NW({args:$?$:H0.create([]).rest(u1.create()),returns:_||u1.create(),typeName:B$.ZodFunction,...w$(J)})}}class bW extends S${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}bW.create=($,_)=>{return new bW({getter:$,typeName:B$.ZodLazy,...w$(_)})};class EW extends S${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return n(_,{received:_.data,code:Z.invalid_literal,expected:this._def.value}),j$}return{status:"valid",value:$.data}}get value(){return this._def.value}}EW.create=($,_)=>{return new EW({value:$,typeName:B$.ZodLiteral,...w$(_)})};function CM($,_){return new l1({values:$,typeName:B$.ZodEnum,...w$(_)})}class l1 extends S${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return n(_,{expected:x$.joinValues(J),received:_.parsedType,code:Z.invalid_type}),j$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return n(_,{received:_.data,code:Z.invalid_enum_value,options:J}),j$}return n6($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return l1.create($,{...this._def,..._})}exclude($,_=this._def){return l1.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}l1.create=CM;class wW extends S${_parse($){let _=x$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==t.string&&J.parsedType!==t.number){let U=x$.objectValues(_);return n(J,{expected:x$.joinValues(U),received:J.parsedType,code:Z.invalid_type}),j$}if(!this._cache)this._cache=new Set(x$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=x$.objectValues(_);return n(J,{received:J.data,code:Z.invalid_enum_value,options:U}),j$}return n6($.data)}get enum(){return this._def.values}}wW.create=($,_)=>{return new wW({values:$,typeName:B$.ZodNativeEnum,...w$(_)})};class O_ extends S${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.promise&&_.common.async===!1)return n(_,{code:Z.invalid_type,expected:t.promise,received:_.parsedType}),j$;let J=_.parsedType===t.promise?_.data:Promise.resolve(_.data);return n6(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}O_.create=($,_)=>{return new O_({type:$,typeName:B$.ZodPromise,...w$(_)})};class R4 extends S${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(n(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return j$;let Q=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Q.status==="aborted")return j$;if(Q.status==="dirty")return HW(Q.value);if(_.value==="dirty")return HW(Q.value);return Q});else{if(_.value==="aborted")return j$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return j$;if(G.status==="dirty")return HW(G.value);if(_.value==="dirty")return HW(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Q=U.refinement(G,W);if(J.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return j$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return j$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!Y_(X))return j$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!Y_(X))return j$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});x$.assertNever(U)}}R4.create=($,_,J)=>{return new R4({schema:$,typeName:B$.ZodEffects,effect:_,...w$(J)})};R4.createWithPreprocess=($,_,J)=>{return new R4({schema:_,effect:{type:"preprocess",transform:$},typeName:B$.ZodEffects,...w$(J)})};class r4 extends S${_parse($){if(this._getType($)===t.undefined)return n6(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}r4.create=($,_)=>{return new r4({innerType:$,typeName:B$.ZodOptional,...w$(_)})};class $1 extends S${_parse($){if(this._getType($)===t.null)return n6(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}$1.create=($,_)=>{return new $1({innerType:$,typeName:B$.ZodNullable,...w$(_)})};class IW extends S${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===t.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}IW.create=($,_)=>{return new IW({innerType:$,typeName:B$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...w$(_)})};class gW extends S${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(iX(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new q4(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new q4(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}gW.create=($,_)=>{return new gW({innerType:$,typeName:B$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...w$(_)})};class aX extends S${_parse($){if(this._getType($)!==t.nan){let J=this._getOrReturnCtx($);return n(J,{code:Z.invalid_type,expected:t.nan,received:J.parsedType}),j$}return{status:"valid",value:$.data}}}aX.create=($)=>{return new aX({typeName:B$.ZodNaN,...w$($)})};var wl=Symbol("zod_brand");class a5 extends S${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class sX extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return j$;if(W.status==="dirty")return _.dirty(),HW(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return j$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new sX({in:$,out:_,typeName:B$.ZodPipeline})}}class kW extends S${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(Y_(U))U.value=Object.freeze(U.value);return U};return iX(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}kW.create=($,_)=>{return new kW({innerType:$,typeName:B$.ZodReadonly,...w$(_)})};function MM($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function PM($,_={},J){if($)return z_.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Q=MM(_,U),Y=Q.fatal??J??!0;W.addIssue({code:"custom",...Q,fatal:Y})}});if(!X){let G=MM(_,U),Q=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Q})}return});return z_.create()}var Il={object:V6.lazycreate},B$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(B$||(B$={}));var gl=($,_={message:`Input not instance of ${$.name}`})=>PM((J)=>J instanceof $,_),TM=n4.create,SM=d1.create,kl=aX.create,fl=c1.create,ZM=FW.create,Cl=q_.create,Pl=rX.create,Tl=RW.create,Sl=KW.create,Zl=z_.create,vl=u1.create,yl=B0.create,hl=pX.create,ml=i4.create,xl=V6.create,ul=V6.strictCreate,dl=MW.create,cl=t5.create,ll=AW.create,nl=H0.create,il=oX.create,rl=tX.create,pl=j_.create,ol=NW.create,tl=bW.create,al=EW.create,sl=l1.create,el=wW.create,$n=O_.create,AM=R4.create,_n=r4.create,Jn=$1.create,Wn=R4.createWithPreprocess,Un=sX.create,Xn=()=>TM().optional(),Gn=()=>SM().optional(),Qn=()=>ZM().optional(),Yn={string:($)=>n4.create({...$,coerce:!0}),number:($)=>d1.create({...$,coerce:!0}),boolean:($)=>FW.create({...$,coerce:!0}),bigint:($)=>c1.create({...$,coerce:!0}),date:($)=>q_.create({...$,coerce:!0})},qn=j$;var a={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},vM=D.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),z4=D.string().datetime(),R$=D.string().trim().min(1),o4=R$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),yM=D.string().regex(/^[a-fA-F0-9]{64}$/),hM=D.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),_1=D.record(D.unknown()),PW=D.array(D.string().min(1)).default([]),D_=z4.nullable().optional(),zn=new Set(["succeeded","failed","cancelled","blocked","skipped"]),B_=D.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function $6($){return D.object({schema:D.literal($),id:D.string().min(1),createdAt:z4,updatedAt:D_,metadata:_1.optional()}).strict()}var t4$=D.object({schema:vM,id:D.string().min(1),createdAt:z4,updatedAt:D_,metadata:_1.optional()}).strict(),mM=D.enum(["agent","human","service","model","workflow","system"]),jn=$6(a.actorRef).extend({kind:mM,name:D.string().min(1).optional(),provider:D.string().min(1).optional(),accountId:D.string().min(1).optional(),machineId:D.string().min(1).optional(),capabilities:D.array(D.string().min(1)).default([])}).strict(),N0=D.object({kind:mM,id:D.string().min(1),name:D.string().min(1).optional(),provider:D.string().min(1).optional(),accountId:D.string().min(1).optional(),machineId:D.string().min(1).optional()}).strict(),xM=D.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),On=$6(a.resourceRef).extend({kind:xM,name:D.string().min(1).optional(),uri:o4.optional(),externalId:R$.optional(),sourcePackage:R$.optional(),tags:PW}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:D.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),T$=D.object({kind:xM,id:D.string().min(1),name:D.string().min(1).optional(),uri:o4.optional(),externalId:R$.optional(),sourcePackage:R$.optional(),tags:PW}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:D.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),rL=D.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),Dn=D.enum(["none","partial","full","unknown"]),Ln=$6(a.evidenceRef).extend({kind:rL,uri:o4,sha256:yM.optional(),summary:D.string().min(1).optional(),contentType:D.string().min(1).optional(),sizeBytes:D.number().int().nonnegative().optional(),redaction:Dn.default("unknown"),producer:N0.optional(),resourceRefs:D.array(T$).default([]),tags:PW}).strict(),Q6=D.object({id:D.string().min(1),kind:rL.optional(),uri:o4.optional(),sha256:yM.optional(),summary:D.string().min(1).optional()}).strict(),eX=$6(a.costEstimate).extend({currency:D.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:D.number().int().nonnegative(),provider:D.string().min(1).optional(),model:D.string().min(1).optional(),accountId:D.string().min(1).optional(),promptTokens:D.number().int().nonnegative().optional(),completionTokens:D.number().int().nonnegative().optional(),totalTokens:D.number().int().nonnegative().optional(),basis:D.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:D.array(T$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:D.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),Bn=D.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),uM=$6(a.decisionEnvelope).extend({decisionType:D.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:Bn,actor:N0.optional(),traceId:D.string().min(1).optional(),inputHash:hM.optional(),policyBundleId:D.string().min(1).optional(),selected:D.array(T$).default([]),skipped:D.array(T$).default([]),reason:D.string().min(1),obligations:D.array(D.string().min(1)).default([]),redactions:D.array(D.string().min(1)).default([]),costEstimate:eX.optional(),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),Hn=$6(a.capabilityCard).extend({kind:D.enum(["model","tool","machine","agent","lane","connector","service"]),name:D.string().min(1),version:D.string().min(1).optional(),status:D.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:D.array(D.string().min(1)).default([]),limitations:D.array(D.string().min(1)).default([]),riskLevel:D.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:eX.optional(),evidenceRefs:D.array(Q6).default([])}).strict(),fW=D.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),Nn=D.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),Vn=D.object({refName:R$,requiredForModes:D.array(fW).min(1),allowedSecretInputs:D.array(D.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:R$,revocationCheck:D.boolean().default(!0)}).strict(),Fn=D.object({operation:R$,supportedModes:D.array(fW).min(1),sideEffectClass:Nn,requiresApproval:D.boolean().default(!1),requiresIdempotencyKey:D.boolean().default(!1),requiresSandboxEvidence:D.boolean().default(!1),requiresRollbackOrRevocation:D.boolean().default(!1),rollbackOrRevocation:R$.optional(),noSideEffectSmoke:R$.optional(),reconciliation:R$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),Rn=D.object({providerId:R$,appId:R$,adapterId:R$,ownerPackage:R$,modes:D.array(fW).min(1),defaultMode:fW,credentialRequirements:D.array(Vn).default([]),operations:D.array(Fn).min(1),rateLimitPosture:R$,costPosture:R$.optional(),auditEvents:D.array(R$).default([]),redactionRules:D.array(R$).default([]),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:D.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),Kn=D.object({appId:R$,repo:R$,priority:D.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:D.array(R$).min(1),firstOperations:D.array(R$).min(1),blockedUntil:D.array(R$).default([])}).strict(),Mn=$6(a.providerLiveModeStandard).extend({name:R$,version:R$,modes:D.array(fW).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:D.array(R$).min(1),liveMutationGate:D.object({requiredMode:D.literal("live_mutating"),requiredChecks:D.array(R$).min(1),forbiddenBypassSignals:D.array(R$).min(1),disabledLiveSmoke:R$}).strict(),noSideEffectSmoke:D.object({requiredForModes:D.array(fW).min(1),commandEvidence:D.array(R$).min(1),secretOutputScan:D.boolean().default(!0)}).strict(),credentialPolicy:D.object({acceptedInputs:D.array(D.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:D.literal(!1),missingCredentialBehavior:D.literal("fail_closed"),revocationCheckRequired:D.boolean().default(!0)}).strict(),operationCards:D.array(Rn).min(1),firstAdoptionTargets:D.array(Kn).min(1),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:D.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),An=D.object({id:D.string().min(1),title:D.string().min(1).optional(),summary:D.string().min(1),text:D.string().optional(),tokens:D.number().int().nonnegative().optional(),source:Q6,resourceRefs:D.array(T$).default([])}).strict(),dM=$6(a.contextPack).extend({objective:D.string().min(1),budget:D.object({maxTokens:D.number().int().positive().optional(),maxBytes:D.number().int().positive().optional()}).strict().optional(),items:D.array(An).default([]),citations:D.array(Q6).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),permissions:D.array(D.string().min(1)).default([]),redactions:D.array(D.string().min(1)).default([]),conflicts:D.array(D.string().min(1)).default([]),uncertainty:D.string().min(1).optional()}).strict(),l4=R$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),L_=D.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),bn=D.enum(["public","internal","private","sensitive"]),En=D.enum(["draft","active","paused","archived"]),pL=D.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),cM=$6(a.integrationRef).extend({kind:pL,name:D.string().min(1),projectId:L_.optional(),sourcePackage:R$.optional(),externalId:R$.optional(),uri:o4.optional(),enabled:D.boolean().default(!0),readOnly:D.boolean().default(!0),capabilities:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:T$.optional(),evidenceRefs:D.array(Q6).default([]),config:_1.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:D.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),wn=D.object({schemaRoot:l4.default(".hasna/project"),dashboardManifest:l4.default(".hasna/project/dashboard.render.json"),snapshotsDir:l4.default(".hasna/project/snapshots"),documentsDir:l4.default("documents"),reportsDir:l4.default("reports"),evidenceDir:l4.default(".hasna/project/evidence"),privateDir:l4.default(".hasna/project/private")}).strict(),In=$6(a.projectManifest).extend({projectId:L_,slug:L_,name:D.string().min(1),summary:D.string().min(1).optional(),status:En.default("active"),classification:bn.default("private"),owner:N0.optional(),layout:wn.default({}),integrations:D.array(cM).default([]),renderManifests:D.array(T$).default([]),resourceRefs:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([]),tags:PW}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:D.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:D.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:D.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),gn=D.enum(["local","package","provider","url"]),oL=D.object({id:D.string().min(1),kind:gn,specifier:D.string().min(1),path:l4.optional(),packageName:D.string().min(1).optional(),uri:o4.optional(),provider:pL.optional(),schemaId:vM.optional(),integrity:hM.optional(),resourceRef:T$.optional(),optional:D.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:D.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:D.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:D.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:D.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),kn=D.enum(["dashboard","canvas","panel","report","document","custom"]),fn=D.object({id:D.string().min(1),title:D.string().min(1),kind:kn,default:D.boolean().default(!1),entry:l4.optional(),imports:D.array(oL).default([]),panelRefs:D.array(T$).default([]),dataRefs:D.array(T$).default([]),layout:_1.optional()}).strict(),Cn=$6(a.renderManifest).extend({projectId:L_,name:D.string().min(1),version:D.string().min(1),manifestPath:l4.default(".hasna/project/dashboard.render.json"),renderer:D.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:D.array(fn).min(1),imports:D.array(oL).default([]),theme:_1.optional(),compatibility:D.object({minProjectsVersion:D.string().min(1).optional(),minContractsVersion:D.string().min(1).optional()}).strict().optional(),resourceRefs:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Q=new Set;for(let[Y,q]of G.imports.entries()){if(Q.has(q.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Y,"id"]});Q.add(q.id)}for(let[Y,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:D.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Y,"kind"]})}}),Pn=D.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),Tn=D.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Sn=D.object({id:D.string().min(1),label:D.string().min(1),value:D.union([D.string(),D.number(),D.boolean()]),unit:D.string().min(1).optional(),status:D.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:D.array(T$).default([])}).strict(),Zn=D.object({id:D.string().min(1),title:D.string().min(1),summary:D.string().min(1).optional(),status:D.string().min(1).optional(),priority:D.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:z4.optional(),resourceRefs:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([]),metadata:_1.optional()}).strict(),vn=D.object({renderer:D.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:D.string().min(1).optional(),entry:l4.optional(),imports:D.array(oL).default([]),spec:_1.default({})}).strict(),lM=$6(a.projectPanel).extend({projectId:L_,provider:D.object({kind:pL,id:D.string().min(1),name:D.string().min(1).optional(),sourcePackage:R$.optional(),externalId:R$.optional()}).strict(),kind:Tn,title:D.string().min(1),summary:D.string().min(1).optional(),state:Pn.default("ready"),stateReason:D.string().min(1).optional(),generatedAt:z4,freshness:D.enum(["fresh","stale","unknown"]).default("unknown"),metrics:D.array(Sn).default([]),items:D.array(Zn).default([]),actions:D.array(T$).default([]),resourceRefs:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([]),renderFragment:vn.optional(),warnings:D.array(D.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:D.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:D.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:D.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),yn=$6(a.projectSnapshot).extend({projectId:L_,generatedAt:z4,status:B_.default("unknown"),manifestRef:T$,renderManifestRef:T$.optional(),panels:D.array(lM).default([]),contextPacks:D.array(dM).default([]),proofBundleRefs:D.array(T$).default([]),resourceRefs:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([]),warnings:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:D.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:D.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),nM=D.object({id:D.string().min(1),kind:D.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:D.boolean().default(!0),command:D.string().min(1).optional(),expected:D.string().min(1).optional(),timeoutMs:D.number().int().positive().optional(),resourceRefs:D.array(T$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:D.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),hn=$6(a.validationPlan).extend({objective:D.string().min(1),subject:T$.optional(),checks:D.array(nM).min(1),verifier:N0.optional(),requiredEvidenceKinds:D.array(rL).default([])}).strict(),mn=D.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),xn=D.enum(["draft","active","deprecated","archived"]),un=D.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),dn=D.object({key:D.string().regex(/^[A-Z][A-Z0-9_]*$/),description:D.string().min(1),required:D.boolean().default(!1),["secret"]:D.boolean().default(!1),group:D.string().min(1).optional(),default:D.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),cn=D.object({name:D.string().min(1),command:D.string().min(1),description:D.string().min(1).optional(),required:D.boolean().default(!1)}).strict(),ln=D.object({packageManager:D.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:D.array(D.string().min(1)).default([]),requiredFiles:D.array(D.string().min(1)).default([]),requiredDirectories:D.array(D.string().min(1)).default([]),optionalDirectories:D.array(D.string().min(1)).default([])}).strict(),nn=$6(a.scaffoldManifest).extend({name:D.string().min(1),version:D.string().min(1),summary:D.string().min(1),type:mn,status:xn.default("draft"),capabilities:D.array(un).default([]),techStack:D.array(D.string().min(1)).default([]),tags:PW,source:T$.optional(),output:ln,env:D.array(dn).default([]),scripts:D.array(cn).default([]),validationChecks:D.array(nM).default([]),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:D.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),rn=D.enum(["installed","failed","cancelled","partial","unknown"]),pn=$6(a.scaffoldInstallRecord).extend({scaffoldId:D.string().min(1),scaffoldVersion:D.string().min(1).optional(),manifestRef:T$.optional(),target:T$,status:rn,installedAt:z4.optional(),installer:N0.optional(),packageManager:D.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:_1.optional(),generatedFiles:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([]),proofBundleRefs:D.array(T$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:D.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),CW=D.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),tL=D.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),iM=D.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),on=D.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),tn=R$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),an=D.enum(["active","stub","deprecated","archived"]),sn=D.enum(["stable","beta","canary","internal"]),en=D.object({transport:D.enum(["http","stdio"]).default("http"),bin:D.string().min(1).optional(),url:o4.optional()}).strict(),$i=D.object({healthPath:D.string().min(1).default("/health"),port:D.number().int().positive().optional(),baseUrl:o4.optional()}).strict(),_i=D.object({bins:D.array(D.string().min(1)).default([]),mcp:en.optional(),http:$i.optional()}).strict(),Ji=$6(a.app).extend({appId:CW,npmName:tL,repoFolder:CW,githubUrl:tn,projectSlug:L_,surfaces:_i.default({}),lifecycle:an,releaseChannel:sn.default("stable"),summary:D.string().min(1).optional(),tags:PW}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:D.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),Wi=D.enum(["skill","ci","backfilled"]),Ui=$6(a.release).extend({appId:CW,package:tL,version:iM,gitSha:on,publishedAt:z4,publishPath:Wi,changelogRef:T$.optional(),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),Xi=D.enum(["install","update","rollback","freeze-blocked"]),Gi=D.object({cliVersion:D.string().min(1).optional(),mcpHealth:D.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),Qi=$6(a.rolloutRecord).extend({appId:CW,package:tL,version:iM,machine:R$,action:Xi,result:B_,verifiedBy:Gi.optional(),at:z4,evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:D.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),Yi=D.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),qi=D.enum(["pending","queued","sent","failed","skipped","suppressed"]),zi=D.object({channel:Yi,status:qi,deliveredAt:z4.optional(),detail:D.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:D.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),ji=$6(a.announcement).extend({campaignId:R$,appId:CW.optional(),releaseRef:T$.optional(),channels:D.array(zi).min(1),audienceRef:T$,sentAt:z4}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:D.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:D.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),Oi=D.enum(["tag","attribute","group"]),Di=D.enum(["eq","neq","in","not_in","exists","not_exists"]),bM=D.union([D.string(),D.number(),D.boolean()]),Li=D.object({kind:Oi,key:D.string().min(1).optional(),op:Di.default("eq"),value:bM.optional(),values:D.array(bM).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:D.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:D.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),Bi=D.object({match:D.enum(["all","any"]).default("all"),predicates:D.array(Li).min(1)}).strict(),Hi=D.enum(["opt_in","opt_out","transactional","none"]),Ni=$6(a.audience).extend({audienceId:CW,name:R$,definition:Bi,consentPolicy:Hi,suppressionSyncedAt:D_}).strict(),uL=["@hasna/cloud","open-cloud"],Vi=D.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),Fi=D.object({id:D.string().min(1),provider:Vi,kind:D.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:D.string().min(1),region:D.string().min(1).optional(),accountId:D.string().min(1).optional(),uri:o4.optional(),machineScoped:D.boolean().default(!1)}).strict(),rM=$6(a.appCloudManifest).extend({packageName:D.string().min(1),packageVersion:D.string().min(1).optional(),appId:D.string().min(1),repository:T$.optional(),storageMode:D.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:D.enum(["none","app_owned","external_service","local_cache"]),cloudResources:D.array(Fi).default([]),localCache:D.object({path:D.string().min(1).optional(),pullMode:D.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:D.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:D.array(D.string().min(1)).default([...uL]),dependencies:D.array(D.string().min(1)).default([]),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{let J=new Set([...uL,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:D.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of uL)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:D.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:D.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:D.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:D.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:D.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:D.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:D.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),pM=D.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),Ri=D.enum(["low","medium","high","critical"]),oM=D.object({id:D.string().min(1),kind:pM,severity:Ri,path:D.string().min(1).optional(),packageName:D.string().min(1).optional(),pattern:D.string().min(1),message:D.string().min(1),evidenceRefs:D.array(Q6).default([])}).strict(),Ki=D.object({id:D.string().min(1),kind:pM,status:B_,target:D.string().min(1),command:D.string().min(1).optional(),evidenceRefs:D.array(Q6).default([]),findings:D.array(oM).default([])}).strict(),Mi=$6(a.noCloudEvidencePack).extend({subject:T$,packageName:D.string().min(1).optional(),packageVersion:D.string().min(1).optional(),generatedBy:N0.optional(),scanMode:D.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:B_,verdict:D.enum(["passed","failed","warning","not_run"]),appCloudManifest:rM.optional(),checks:D.array(Ki).min(1),findings:D.array(oM).default([]),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:D.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Q)=>Q.severity==="high"||Q.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),Ai=D.object({checkId:D.string().min(1),status:B_,summary:D.string().min(1).optional(),startedAt:D_,finishedAt:D_,evidenceRefs:D.array(Q6).default([])}).strict(),bi=$6(a.proofBundle).extend({subject:T$,validationPlanRef:T$.optional(),status:B_,verdict:D.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:D.array(Ai).default([]),verifier:N0.optional(),evidenceRefs:D.array(Q6).default([]),residualRisks:D.array(D.string().min(1)).default([]),freshness:D.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:D.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:D.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),Ei=$6(a.workRun).extend({objective:D.string().min(1),status:B_,actor:N0,traceId:D.string().min(1).optional(),startedAt:D_,finishedAt:D_,constraints:D.array(D.string().min(1)).default([]),resourceRefs:D.array(T$).default([]),decisions:D.array(uM).default([]),costEstimates:D.array(eX).default([]),evidenceRefs:D.array(Q6).default([]),validationPlanRefs:D.array(T$).default([]),proofBundleRefs:D.array(T$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:D.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),wi=D.object({id:D.string().min(1),at:z4,kind:D.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:D.string().min(1),resourceRefs:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([]),costEstimate:eX.optional()}).strict(),Ii=$6(a.agentTrajectory).extend({actor:N0,workRunRef:T$.optional(),events:D.array(wi).default([]),outcome:D.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:T$.optional()}).strict(),gi="v1",ki=D.enum(["library","cli-with-store","service","saas"]),fi=["local","self-hosted","cloud"],tM=D.enum(fi),Ci=D.enum(["supported","deferred","unsupported"]),Pi=D.enum(["none","local-only","api-key","session","service-token","custom"]),dL=D.object({method:D.enum(["GET","POST","PUT","PATCH","DELETE"]),path:D.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:D.boolean().default(!1),description:D.string().min(1).optional()}).strict(),Ti=D.object({id:D.string().min(1),kind:D.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:D.boolean().default(!0),command:D.string().min(1).optional(),evidenceRef:Q6.optional(),status:D.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:D.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:D.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),Si=D.object({name:D.string().min(1),status:Ci,bin:D.string().min(1).optional(),mcpBin:D.string().min(1).optional(),authMode:Pi,deploymentModes:D.array(tM).min(1),health:dL.optional(),readiness:dL.optional(),version:dL.optional(),apiBasePath:D.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:D.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:D.string().min(1).optional(),readinessGates:D.array(Ti).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:D.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:D.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:D.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:D.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:D.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),Zi=["local","cloud"],aM=D.enum(Zi);var vi=D.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),yi=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function hi($){return yi.map((_)=>`${$}${_}`)}function EM($){return`hasna/oss/${$}/database-url`}var mi=D.object({mode:aM,envPrefix:D.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:D.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:D.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:D.string().min(1).optional()}).strict(),xi=D.object({$schema:D.string().min(1).optional(),schema:D.literal(a.serviceContract),name:vi,class:ki,contractVersion:D.literal(gi),kitVersion:D.string().min(1),description:D.string().min(1).optional(),bins:D.array(D.string().min(1)).default([]),storage:mi.optional(),deploymentModes:D.array(tM).default(["local"]),serviceSurfaces:D.array(Si).default([]),metadata:_1.optional()}).strict().superRefine(($,_)=>{let J=new Set(hi($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:D.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:D.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:D.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==EM($.name))_.addIssue({code:D.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${EM($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:D.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:D.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:D.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:D.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:D.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:D.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Q,Y]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Y))_.addIssue({code:D.ZodIssueCode.custom,message:`Service surface deployment mode "${Y}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Q]})}}),a4$=D.object({status:D.enum(["ok","degraded","unavailable"]),version:D.string().min(1),mode:aM}).strict(),s4$=D.object({ready:D.boolean(),reason:D.string().min(1).optional()}).strict(),e4$=D.object({version:D.string().min(1)}).strict(),ui=D.enum(["info","notice","breaking","critical"]),di=D.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),ci=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],li=D.enum(ci);var ni=D.enum(["fleet","package","machine"]),sM=$6(a.commsEventEnvelope).extend({type:di,severity:ui,scope:ni,summary:D.string().min(1).optional(),source:N0.optional(),affected_packages:D.array(R$).default([]),affected_machines:D.array(R$).default([]),action_required:D.boolean().default(!1),ack_by:z4.optional(),dedupe_key:R$,resourceRefs:D.array(T$).default([]),evidenceRefs:D.array(Q6).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:D.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:D.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:D.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),ii=D.enum(["fleet","package","product","loop-lane","initiative","personal"]),ri=D.enum(["quiet","work","firehose"]),pi=R$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),oi=$6(a.commsChannelMetadata).extend({class:ii,noise:ri.optional(),owner:R$.optional(),until:pi.optional(),successor:R$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:D.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:D.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),wM={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},ti=$6(a.commsMessageMetadata).extend({tag:li,envelope:sM}).strict().superRefine(($,_)=>{let J=wM[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:D.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:D.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(wM))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:D.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var ai={[a.actorRef]:jn,[a.resourceRef]:On,[a.evidenceRef]:Ln,[a.workRun]:Ei,[a.decisionEnvelope]:uM,[a.costEstimate]:eX,[a.capabilityCard]:Hn,[a.providerLiveModeStandard]:Mn,[a.contextPack]:dM,[a.integrationRef]:cM,[a.projectManifest]:In,[a.projectPanel]:lM,[a.projectSnapshot]:yn,[a.renderManifest]:Cn,[a.agentTrajectory]:Ii,[a.validationPlan]:hn,[a.proofBundle]:bi,[a.scaffoldManifest]:nn,[a.scaffoldInstallRecord]:pn,[a.appCloudManifest]:rM,[a.noCloudEvidencePack]:Mi,[a.serviceContract]:xi,[a.commsEventEnvelope]:sM,[a.commsChannelMetadata]:oi,[a.commsMessageMetadata]:ti,[a.app]:Ji,[a.release]:Ui,[a.rolloutRecord]:Qi,[a.announcement]:ji,[a.audience]:Ni};class eM extends Error{schemaId;issues;constructor($,_){super(`Contract validation failed for ${$}`);this.name="ContractValidationError",this.schemaId=$,this.issues=_}}function $A($,_){let U=ai[$].safeParse(_);if(!U.success)throw new eM($,U.error.issues);return U.data}var $0$={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/hasna/contracts/schema/hasna.service_contract.v1.json",title:"Hasna Service Contract v1",description:"Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Storage runtime enum is local|cloud ONLY per Amendment A1 (PURE REMOTE).",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:a.serviceContract},name:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",description:"Lowercase dashed app short-name, e.g. todos, mailery, loops."},class:{enum:["library","cli-with-store","service","saas"]},contractVersion:{const:"v1"},kitVersion:{type:"string",minLength:1,description:"Version of @hasna/contracts (the contract kit) the repo tracks."},description:{type:"string",minLength:1},bins:{type:"array",items:{type:"string",minLength:1},description:"Declared bins. Allowlisted: , -cli, -mcp, -serve, -worker, -runner, -daemon, -migrate, -doctor."},deploymentModes:{type:"array",items:{enum:["local","self-hosted","cloud"]},description:"Supported deployment modes. local = this machine, self-hosted = Hasna-owned AWS, cloud = multi-tenant SaaS for outside users."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode","deploymentModes"],properties:{name:{type:"string",minLength:1},status:{enum:["supported","deferred","unsupported"]},bin:{type:"string",minLength:1},mcpBin:{type:"string",minLength:1},authMode:{enum:["none","local-only","api-key","session","service-token","custom"]},deploymentModes:{type:"array",items:{enum:["local","self-hosted","cloud"]},minItems:1},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},readiness:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},version:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},apiBasePath:{type:"string",pattern:"^/v[0-9]+$"},openApiPath:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$"},deferReason:{type:"string",minLength:1},readinessGates:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1},kind:{enum:["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]},required:{type:"boolean"},command:{type:"string",minLength:1},evidenceRef:{type:"object"},status:{enum:["pending","passed","failed","blocked","deferred"]},summary:{type:"string",minLength:1}}}}}},description:"Declared HTTP/MCP service surfaces. Supported surfaces name lifecycle endpoints; unsafe or unfinished surfaces use deferred/unsupported with a reason."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["local","cloud"],description:"Runtime storage enum. local|cloud ONLY (Amendment A1: PURE REMOTE)."},envPrefix:{type:"string",pattern:"^HASNA_[A-Z][A-Z0-9]*_$",description:"Primary env prefix, e.g. HASNA_TODOS_."},aliasEnvPrefix:{type:"string",pattern:"^[A-Z][A-Z0-9]*_$",description:"Optional short alias env prefix, e.g. TODOS_."},databaseUrlSecretRef:{type:"string",pattern:"^hasna/oss/[a-z0-9-]+/database-url$",description:"Secret Manager ref for the cloud database URL."},sqlitePath:{type:"string",minLength:1,description:"Local sqlite path (~/.hasna//.db)."}}},metadata:{type:"object"}}};var _A="@hasna/knowledge";function si($){if(!Number.isFinite($??0))return 20;return Math.max(1,Math.min(100,Math.trunc($??20)))}function ei($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function $9($,_=180){let J=String($??"").replace(/\s+/g," ").trim();if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-3))}...`}function A6($,_=""){return typeof $==="string"&&$.length>0?$:_}function _9($){return typeof $==="number"&&Number.isFinite($)?$:0}function TW($){if(typeof $!=="string"||$.length===0)return;let _=$.includes("T")?$:`${$.replace(" ","T")}Z`,J=new Date(_);return Number.isNaN(J.valueOf())?void 0:J.toISOString()}function s5($){return o4.safeParse($).success}function t4($,_,J,U,W=[]){return{kind:$,id:_,name:J,uri:U&&s5(U)?U:void 0,externalId:_,sourcePackage:_A,tags:W}}function $r($){return[...$.items.flatMap((J)=>[J.updated_at,J.created_at]),...$.sources.flatMap((J)=>[J.updated_at,J.created_at]),...$.chunks.map((J)=>J.created_at),...$.wiki_pages.flatMap((J)=>[J.updated_at,J.created_at]),...$.storage_objects.flatMap((J)=>[J.updated_at,J.created_at]),...$.runs.flatMap((J)=>[J.updated_at,J.created_at]),...$.reindex_queue.flatMap((J)=>[J.updated_at,J.created_at]),...$.sync_conflicts.map((J)=>J.created_at),...$.approval_gates.flatMap((J)=>[J.updated_at,J.created_at])].map(TW).filter(Boolean).sort((J,U)=>U.localeCompare(J))[0]}function _r($){if(!$)return"unknown";let _=Date.now()-new Date($).valueOf();if(!Number.isFinite(_))return"unknown";return _>2592000000?"stale":"fresh"}function Jr($){let _=(J)=>{let U=String(J??"").toLowerCase();return U!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(U)};return $.reindex_queue.filter((J)=>_(J.status)).length+$.sync_conflicts.filter((J)=>_(J.status)).length+$.approval_gates.filter((J)=>_(J.status)).length}function Wr($,_){let J=[];for(let U of $.items.slice(0,_))J.push({id:`item_${U.id}`,title:U.title,summary:$9(U.content_preview),status:U.archived?"archived":"active",priority:"medium",timestamp:TW(U.updated_at??U.created_at),resourceRefs:[t4("knowledge",U.id,U.title,`knowledge://item/${encodeURIComponent(U.id)}`,U.tags)],evidenceRefs:U.url&&s5(U.url)?[{id:`url_${U.id}`,kind:"url",uri:U.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:U.archived,tags:U.tags,url:U.url||void 0}});for(let U of $.sources.slice(0,Math.max(0,_-J.length))){let W=A6(U.id,A6(U.uri,"source")),X=A6(U.title,A6(U.uri,W)),G=A6(U.uri,`knowledge://source/${encodeURIComponent(W)}`);J.push({id:`source_${W}`,title:X,summary:$9(`${_9(U.chunks)} chunk(s), ${_9(U.revisions)} revision(s)`),status:_9(U.chunks)>0?"indexed":"source",priority:"medium",timestamp:TW(U.updated_at??U.created_at),resourceRefs:[t4("document",W,X,G)],evidenceRefs:s5(G)?[{id:`source_${W}`,kind:"url",uri:G,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:U.kind,chunks:_9(U.chunks),revisions:_9(U.revisions)}})}for(let U of $.chunks.slice(0,Math.max(0,_-J.length))){let W=A6(U.id,"chunk"),X=A6(U.source_uri);J.push({id:`chunk_${W}`,title:A6(U.wiki_title,X?`Chunk from ${X}`:`Knowledge chunk ${W}`),summary:$9(U.text_preview),status:"chunk",priority:"low",timestamp:TW(U.created_at),resourceRefs:[t4("context_pack",W,A6(U.wiki_title,W),`knowledge://chunk/${encodeURIComponent(W)}`)],evidenceRefs:X&&s5(X)?[{id:`chunk_source_${W}`,kind:"url",uri:X,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:X||void 0,token_count:U.token_count,ordinal:U.ordinal}})}for(let U of $.sync_conflicts.slice(0,Math.max(0,_-J.length))){let W=A6(U.id,"sync_conflict");J.push({id:`sync_conflict_${W}`,title:`Sync conflict: ${A6(U.entity_kind,"entity")}/${A6(U.entity_id,W)}`,summary:$9(`Status ${A6(U.status,"unknown")}; strategy ${A6(U.resolution_strategy,"none")}.`),status:A6(U.status,"unknown"),priority:"critical",timestamp:TW(U.created_at),resourceRefs:[t4("finding",W,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(W)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:U.local_machine_id,remote_machine_id:U.remote_machine_id}})}for(let U of $.reindex_queue.slice(0,Math.max(0,_-J.length))){let W=A6(U.id,"reindex");J.push({id:`reindex_${W}`,title:`Reindex ${A6(U.kind,"item")}: ${A6(U.target_id,W)}`,summary:$9(U.reason),status:A6(U.status,"unknown"),priority:A6(U.status).toLowerCase()==="failed"?"high":"medium",timestamp:TW(U.updated_at??U.created_at),resourceRefs:[t4("action",W,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(W)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:U.attempts,source_uri:U.source_uri}})}return J.slice(0,_)}async function JA($,_={}){let J=si(_.limit),U=new Date().toISOString(),W=ei($),G=await(_.service??r5({scope:_.scope??"project",cwd:_.cwd})).resolveInventory({limit:J,storePath:_.storePath,includeArchived:_.includeArchived}),Q=$r(G),Y=_r(Q),q=G.summary.active_items+G.summary.sources+G.summary.chunks+G.summary.wiki_pages+G.summary.storage_objects,L=Jr(G),N=q===0?"empty":Y==="stale"?"stale":"ready",F=Wr(G,J),B={schema:a.projectPanel,id:`knowledge_panel_${W}`,createdAt:U,projectId:W,provider:{kind:"knowledge",id:`knowledge_${W}`,name:"Knowledge",sourcePackage:_A,externalId:G.home},kind:"knowledge",title:"Knowledge",summary:N==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${G.summary.active_items} active note(s), ${G.summary.sources} source(s), ${G.summary.chunks} chunk(s), and ${G.summary.wiki_pages} wiki page(s).`,state:N,stateReason:N==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:U,freshness:Y,metrics:[{id:"active_items",label:"Active notes",value:G.summary.active_items,status:G.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:G.summary.sources,status:G.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:G.summary.chunks,status:G.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:G.summary.wiki_pages,status:G.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:G.summary.storage_objects,status:G.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:G.summary.vector_entries,status:G.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:L,status:L>0?"warning":"good"}],items:F,actions:[t4("action","knowledge:inventory","Inspect knowledge inventory"),t4("action","knowledge:context-pack","Build cited context pack"),t4("action","knowledge:ingest","Ingest project source")],resourceRefs:[t4("project",W,$,`project://${W}`),t4("knowledge",`home_${W}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(W)}`),t4("artifact",`db_${W}`,"Knowledge database",`knowledge://db/${encodeURIComponent(W)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:J}},metadata:{scope:G.scope,home:G.home,json_store_exists:G.paths.json_store_exists,latest_activity_at:Q}};return $A(a.projectPanel,B)}function WA($){let _=[`${$.title}: ${$.state}`,$.summary??"",...$.metrics.map((J)=>`${J.label}: ${J.value}`)].filter(Boolean);if($.items.length>0){_.push("Items:");for(let J of $.items.slice(0,10))if(_.push(`- ${J.title}${J.status?` [${J.status}]`:""}`),J.summary)_.push(` ${J.summary}`)}return _.join(` -`)}var GA=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"];var Ur=["remote","hybrid","self_hosted"],QA="HASNA_KNOWLEDGE_STORAGE_MODE",YA="KNOWLEDGE_STORAGE_MODE";function UA($){return process.env[$]?.trim()||void 0}function XA($){let _=$?.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return"local";if(_==="cloud")return"cloud";if(_&&Ur.includes(_))return"cloud";return}function Xr($={}){let _=K_(Y9($.scope,$.cwd).home);return G$(_.knowledgeDbPath),{db:i(_.knowledgeDbPath),path:_.knowledgeDbPath,scope:$.scope??"global"}}function qA(){let $=XA(UA(QA))??XA(UA(YA));if($)return $;return"local"}function aL($={}){let _=Xr($);try{Gr(_.db);let J=_.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all();return{mode:qA(),service:"knowledge",scope:_.scope,databasePath:_.path,tables:GA,sync:J}}finally{_.db.close()}}function Gr($){$.exec(` + `,[J])),k=l_(q,` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + source_kind, + source_refs_json, + evidence_refs_json, + status, + requires_approval, + checks_json, + duplicate_of, + approved_by, + promoted_record_id, + metadata_json, + created_at, + updated_at, + reviewed_at, + promoted_at + FROM knowledge_promotion_candidates + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `,[J]).map(Oc),u=l_(q,` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + status, + source_refs_json, + evidence_refs_json, + confidence, + valid_from, + valid_to, + promoted_from_candidate_id, + approved_by, + metadata_json, + created_at, + updated_at + FROM durable_knowledge_records + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `,[J]).map(Lc),W_={legacy_items:W.items.length,active_items:X.length,archived_items:W.items.length-X.length,schema_version:Q.schema_version,sources:Q.sources,source_revisions:Q.source_revisions,chunks:Q.chunks,wiki_pages:Q.wiki_pages,citations:Q.citations,indexes:Q.indexes,runs:Q.runs,run_events:Q.run_events,storage_objects:Q.storage_objects,embeddings:Q.embeddings,vector_entries:Q.vector_entries,reindex_queue:Q.reindex_queue,redaction_findings:Q.redaction_findings,audit_events:Q.audit_events,approval_gates:Q.approval_gates,knowledge_machines:Q.knowledge_machines,sync_snapshots:Q.sync_snapshots,sync_changes:Q.sync_changes,sync_conflicts:Q.sync_conflicts,sync_table_clocks:Q.sync_table_clocks,sync_imports:Q.sync_imports,promotion_candidates:Q.promotion_candidates,durable_records:Q.durable_records};return{ok:!0,scope:this.scope,home:_.home,limit:J,paths:{json_store_path:U,json_store_exists:W.exists,knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:_.artifactsDir,indexes_dir:_.indexesDir,logs_dir:_.logsDir,wiki_dir:_.wikiDir},summary:W_,legacy_store:{path:U,exists:W.exists,read_error:W.read_error,total_items:W.items.length,active_items:X.length,archived_items:W.items.length-X.length,items_returned:Math.min(G.length,J)},items:G.slice(0,J).map(kE),sources:L,source_revisions:N,chunks:R,wiki_pages:B,indexes:H,storage_objects:V,runs:K,vector_indexes:E,reindex_queue:F,machines:w,sync_conflicts:A,approval_gates:g,audit_events:v,promotion_candidates:k,durable_records:u,message:`${W.items.length} item(s), ${Q.sources} source(s), ${Q.chunks} chunk(s), ${Q.wiki_pages} wiki page(s), ${Q.storage_objects} artifact(s)`}}finally{q.close()}}assertAppWikiWrite($){FU({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:$})}async initAppWiki($={}){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return n3({scope:this.scope,workspace:_,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal})}async addAppWikiNote($){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return c3({scope:this.scope,workspace:_,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal,title:$.title,content:$.content,tags:$.tags,sourceRefs:$.sourceRefs,path:$.path,metadata:$.metadata})}listAppWikiNotes($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return[];return i3({dbPath:_.knowledgeDbPath,limit:$.limit})}async getAppWikiNote($,_={}){let J=this.workspace;if(!e$(J.knowledgeDbPath))return null;return l3({dbPath:J.knowledgeDbPath,store:this.artifactStore(),id:$,includeContent:_.includeContent})}async addAppWikiSourceRef($){this.assertAppWikiWrite($.allowGlobal);let _=this.ensureWorkspace();return r3({scope:this.scope,workspace:_,sourceRef:$.sourceRef,purpose:$.purpose,config:this.config(),safetyPolicy:this.safetyPolicy(),allowGlobal:$.allowGlobal})}async searchAppWiki($){return this.search($)}async queryAppWiki($){return this.retrieveContext($)}async initWiki(){let $=this.ensureWorkspace();a($.knowledgeDbPath);let _=await zE(this.artifactStore()),J=m($.knowledgeDbPath);try{u4(J,_.artifacts),jE(J,_.artifacts)}finally{J.close()}return _}async compileWiki($={}){let _=this.ensureWorkspace();return GE({...$,dbPath:_.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer($){let _=this.ensureWorkspace(),J=await this.retrieveContext({query:$.prompt,limit:$.limit,semantic:$.semantic,modelRef:$.modelRef,dimensions:$.dimensions,fake:$.fake});return YE({dbPath:_.knowledgeDbPath,store:this.artifactStore(),prompt:$.prompt,answer:$.answer,context:J,approveWrite:$.approveWrite})}lintWiki(){let $=this.ensureWorkspace();return QE({dbPath:$.knowledgeDbPath})}async ingestManifest($){let _=this.ensureWorkspace();return h3({dbPath:_.knowledgeDbPath,input:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource($,_){let J=this.ensureWorkspace();return l9({dbPath:J.knowledgeDbPath,sourceRef:$,purpose:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance($={}){let _=$.dryRun!==!1,J=_?this.workspace:this.ensureWorkspace();return oF({root:$.root??this.options.cwd??process.cwd(),scope:this.scope,owner:$.owner,dryRun:_,deprecateLegacy:$.deprecateLegacy,includeLegacy:$.includeLegacy,legacyStorePath:J.jsonStorePath,dbPath:J.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:$.maxItems,limit:$.limit})}async resolveSource($,_={}){let J=this.ensureWorkspace();return n9({dbPath:J.knowledgeDbPath,sourceRef:$,purpose:_.purpose,limit:_.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox($){let _=this.ensureWorkspace();return YF({dbPath:_.knowledgeDbPath,input:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return Rc();return hF({...$,dbPath:_.knowledgeDbPath,config:this.config()})}enqueueReindex($={}){let _=this.ensureWorkspace();return wL({...$,dbPath:_.knowledgeDbPath,config:this.config()})}async refreshEmbeddings($={}){let _=this.ensureWorkspace();return mF({...$,dbPath:_.knowledgeDbPath,config:this.config()})}providerStatus($=process.env){return s3(this.config(),$)}modelRegistry(){return hQ(this.config())}embeddingStatus(){let $=this.workspace;if(!e$($.knowledgeDbPath))return Kc();return UV($.knowledgeDbPath)}async indexEmbeddings($={}){let _=this.ensureWorkspace();return o9({...$,dbPath:_.knowledgeDbPath,config:this.config()})}isApiMode(){return K0()}async fetchCloudItems(){let $=KU();if(!$)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return v9($)}async semanticSearch($){let _=this.workspace;if(this.isApiMode()){let J=await this.fetchCloudItems(),U=await I1(J,{...$},["semantic_search_requires_local_catalog"]);return{provider:"openai",model:"text-embedding-3-small",dimensions:$.dimensions??1536,query:$.query,results:U.results}}if(!e$(_.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:$.dimensions??1536,query:$.query,results:[]};return t9({...$,dbPath:_.knowledgeDbPath,config:this.config()})}async search($){let _=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return I1(U,$)}let J=lL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){if(e$(J))return $8({...$,legacyStorePath:J,config:this.config()});return xE($.query,Math.max(1,Math.min($.limit??10,100)),$.semantic===!0||$.fake===!0||Boolean($.modelRef))}return e9({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async retrieveContext($){let _=this.workspace;if(this.isApiMode()){let U=await this.fetchCloudItems();return J8(U,$)}let J=lL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){if(e$(J)){let U=await $8({...$,legacyStorePath:J,config:this.config()});return vJ(U,{contextChars:$.contextChars})}return Nc($.query,Math.max(1,Math.min($.limit??10,100)),$.semantic===!0||$.fake===!0||Boolean($.modelRef))}return yJ({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async contextPack($){let _=this.workspace;if(this.isApiMode()){let U=($.query??$.topic??"").trim();if(U&&$.source!=="loops"&&$.source!=="runs"){let W=await this.fetchCloudItems(),X=await I1(W,{...$,query:U}),G=vJ(X,{contextChars:$.contextChars});return CE($,G,this.safetyPolicy())}return PE($)}let J=lL(this.scope,_,$.legacyStorePath);if(!e$(_.knowledgeDbPath)){let U=($.query??$.topic??"").trim();if(U&&$.source!=="loops"&&$.source!=="runs"&&e$(J)){let W=await $8({...$,query:U,legacyStorePath:J,config:this.config()}),X=vJ(W,{contextChars:$.contextChars});return CE($,X,this.safetyPolicy())}return PE($)}return SV({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt($){if(this.isApiMode()){let U=await this.fetchCloudItems();return bV(U,{...$,config:this.config()})}let _=this.ensureWorkspace(),J=$.legacyStorePath??_.jsonStorePath;if(!$.legacyStorePath)lW(J);return AV({...$,dbPath:_.knowledgeDbPath,legacyStorePath:J,config:this.config()})}async webSearch($){let _=this.ensureWorkspace();return eF({...$,dbPath:_.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology($={}){let _=this.workspace;return EF({...$,knowledge:{scope:this.scope,workspace_home:_.home}})}async machinePreflight($={}){let _=this.workspace;return bF({...$,knowledge:{scope:this.scope,workspace_home:_.home}})}syncStatus(){let $=this.workspace;if(!e$($.knowledgeDbPath))return Fc({scope:this.scope,workspaceHome:$.home});return WR({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home})}async syncDoctor($={}){let _=this.ensureWorkspace();a(_.knowledgeDbPath);let J=this.syncStatus(),U=this.storageContract(),W=this.validateStorage(),X=Ec(_.knowledgeDbPath,U),G=$.machine?.trim()||null,Y=$.peerWorkspace?.trim()||null,Q=[],q=null,L=null;if(G&&!vE(G)){let V=await FL({machineId:G,includeTailscale:$.includeTailscale});q=iL(V),Q.push(...V.warnings)}if(G||Y){let V=await dG({machineId:G??cL(_),peerWorkspace:Y,includeTailscale:$.includeTailscale});if(G&&!Y&&(q?.source==="raw"||!V.ok||!V.project_root)){let K=ME(_.knowledgeDbPath,G);if(K){if(q?.source==="raw"&&K.ssh_target)q=iL(AE(K,G,{target:q.target,route:q.route,targetKind:q.target_kind,confidence:q.confidence,source:q.source,adapter:q.adapter,evidence:q.evidence,cacheability:q.cacheability,warnings:[]}));if(!V.ok||!V.project_root){let E=bE(K,G,V);if(E)L=rX(E,E.project_root),Q.push(...E.warnings)}}}L=V.ok&&V.project_root?rX(V,V.project_root):L??{...rX(V,Y??""),project_root:V.project_root??Y??""},Q.push(...V.warnings)}if(!W.ok)Q.push(...W.errors.map((V)=>`storage:${V}`));let N=zc(_.knowledgeDbPath,L);if(!N.ok)Q.push("open_files_boundary_raw_payload_sentinels");if(!X.ok)Q.push(...X.warnings);let R=L?.diagnostics.filter((V)=>V.severity==="fail")??[],B=W.ok&&X.ok&&N.ok&&R.length===0&&(L?.project_root!==""||!L),H=Ac({scope:this.scope,machine:G,peerWorkspace:Y,tables:$.tables,resolvedWorkspace:L,openConflicts:J.conflicts.open});return{ok:B,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:_.home,database:{sqlite_schema_version:J.sqlite_schema_version,table_counts:J.table_counts},storage:{contract:U,validation:W,artifact_manifest:X},sync:{machines:J.machines.total,snapshots:J.snapshots.total,clocks:J.clocks.total,imports:J.imports.total,open_conflicts:J.conflicts.open,table_clocks:J.clocks.rows},open_files:N,resolved_route:q,resolved_workspace:L,recommended_commands:H,warnings:[...new Set(Q)],message:B?`Sync readiness ok: ${J.clocks.total} table clock(s), ${J.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(Q)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys($={}){let _=this.ensureWorkspace();a(_.knowledgeDbPath);let J=this.storageContract(),U=aL(J),W=Mc(_.knowledgeDbPath,J),X=$.dryRun===!0||$.approveWrite!==!0;if(W.length===0)return{ok:!0,dry_run:X,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:"No legacy S3 artifact manifest keys found"};if($.dryRun===!0)return{ok:!0,dry_run:!0,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:`Would repair ${W.length} legacy S3 artifact manifest key(s)`};if($.approveWrite!==!0||!$.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let G=m(_.knowledgeDbPath);try{let Y=new Date().toISOString();G.transaction((L)=>{let N=G.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),R=G.query("SELECT id, metadata_json FROM storage_objects").all(),B=new Map(R.map((H)=>[H.id,j2(H.metadata_json)]));for(let H of L){let V=B.get(H.id)??{};V.key=H.repaired_key,N.run(JSON.stringify(V),Y,H.id)}})(W);let q=__(G,{event_type:"artifact_manifest_key_repair",action:"storage.artifact_manifest.repair_keys",target_uri:`knowledge-storage://${_.home}/storage_objects`,decision:"allow",metadata:{approved_by:$.approvedBy,repaired:W.length,storage_type:J.storage_type,storage_prefix:U,artifact_uris:W.map((L)=>L.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:J.storage_type,storage_prefix:U,candidates:W,repaired:W.length,audit_event_id:q,message:`Repaired ${W.length} legacy S3 artifact manifest key(s)`}}finally{G.close()}}async createSyncSnapshot($={}){let _=this.ensureWorkspace(),J=await this.machineTopology({includeTailscale:$.includeTailscale!==!1});return JR({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home,storage:this.storageContract(),topology:J,machineId:$.machineId})}syncConflicts($={}){let _=this.workspace;if(!e$(_.knowledgeDbPath))return[];return UR(_.knowledgeDbPath,$)}syncConflict($){let _=this.ensureWorkspace(),J=D8(_.knowledgeDbPath,$);if(!J)throw Error(`Sync conflict not found: ${$}`);return J}proposeSyncConflictResolution($){let _=this.ensureWorkspace();return CU(_.knowledgeDbPath,$)}async proposeSyncConflictResolutionWithAi($){let _=this.ensureWorkspace();return XF({dbPath:_.knowledgeDbPath,id:$.id,config:this.config(),modelRef:$.modelRef,fake:$.fake,env:$.env})}resolveSyncConflict($){let _=this.ensureWorkspace(),J=CU(_.knowledgeDbPath,$.id);if($.approveWrite!==!0||!$.approvedBy)return{ok:!1,approval_required:!0,conflict:J.conflict,proposal:J,message:"Sync conflict resolution requires --approve-write and --approved-by "};let U=YR(_.knowledgeDbPath,{id:$.id,strategy:$.strategy??J.proposed_strategy,approvedBy:$.approvedBy,proposedPatchUri:$.proposedPatchUri}),W=m(_.knowledgeDbPath);try{let X=__(W,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${$.id}`,decision:"allow",metadata:{conflict_id:$.id,entity_kind:U.entity_kind,entity_id:U.entity_id,strategy:U.resolution_strategy,approved_by:U.approved_by,proposed_patch_uri:U.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:U,audit_event_id:X,message:`Resolved sync conflict ${$.id}`}}finally{W.close()}}syncMachines(){let $=this.workspace;if(!e$($.knowledgeDbPath))return[];return Wq($.knowledgeDbPath)}exportSyncBundle($={}){let _=this.ensureWorkspace();return this.assertStorageValid("sync export"),a(_.knowledgeDbPath),fU({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home,storage:this.storageContract(),machineId:$.machineId??null,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.recordClocks!==!1})}async importSyncBundle($){let _=this.ensureWorkspace();return this.assertStorageValid("sync import"),a(_.knowledgeDbPath),j8({targetDbPath:_.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:_.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:$.bundle,direction:$.direction??"import",dryRun:$.dryRun,localMachineId:$.machineId??null})}async syncRemotePeer($){let _=$.direction??"both",J=$.dryRun===!0,U=this.ensureWorkspace();a(U.knowledgeDbPath);let W=$.tables?.length?["--tables",$.tables.join(",")]:[],X=$.includeArtifactContent===!1?["--no-artifact-content"]:[],G=["--scope",this.scope,"--json"],Y=await FL({machineId:$.machine,includeTailscale:$.includeTailscale}),Q=await dG({machineId:$.machine,peerWorkspace:$.peerWorkspace,includeTailscale:$.includeTailscale});if(!$.peerWorkspace&&Y.source==="raw"||!Q.ok||!Q.project_root){let B=ME(U.knowledgeDbPath,$.machine);if(B){if(!$.peerWorkspace&&Y.source==="raw"&&B.ssh_target)Y=AE(B,$.machine,Y);if(!Q.ok||!Q.project_root){let H=bE(B,$.machine,Q);if(H)Q=H}}}if(!Q.ok||!Q.project_root)throw Error([`Unable to resolve peer workspace for ${$.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",Q.warnings.length?`Warnings: ${Q.warnings.join(", ")}`:null].filter(Boolean).join(" "));let q=Q.project_root,L={ok:!0,dry_run:J,direction:_,transport:"ssh",machine:$.machine,resolved_machine:Y.target,resolved_route:iL(Y),resolved_workspace:rX(Q,Q.project_root),peer_workspace:q,message:""},N=!1,R=()=>{if(J||N)return;eV(U.knowledgeDbPath,{machineId:$.machine,route:Y,workspace:Q}),N=!0};if(_==="pull"||_==="both"){let B=EE(q,["sync","export",...G,...W,...X]),H=TE($.machine,B,void 0,Y),V=SE($.machine,"sync export",H);wc($.machine,V),L.pull=await this.importSyncBundle({bundle:V,dryRun:J,direction:"pull",machineId:$.machineId??null})}if(_==="push"||_==="both"){R();let B=this.exportSyncBundle({machineId:$.machineId??null,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:!J}),H=EE(q,["sync","import",...G,...J?["--dry-run"]:[]]),V=SE($.machine,"sync import",TE($.machine,H,JSON.stringify(B),Y));gc($.machine,V),L.push=V}return L.ok=(L.pull?.ok??!0)&&(L.push?.ok??!0),R(),L.message=[wE(L.resolved_workspace),L.pull?`pull: ${L.pull.message}`:null,L.push?`push: ${L.push.message}`:null].filter(Boolean).join("; "),L}async syncPeer($){let _=$.direction??"both",J=this.ensureWorkspace();a(J.knowledgeDbPath);let U=ZE($.peerWorkspace),W=Jc(U);a(W.knowledgeDbPath);let X=KY(W.configPath),G=x9(X,W,this.scope),Y=AQ(X,W),Q=$.machineId??cL(J),q=cL(W),L=await dG({machineId:$.machineId??q,peerWorkspace:U,includeTailscale:!1}),N=()=>fU({dbPath:J.knowledgeDbPath,scope:this.scope,workspaceHome:J.home,storage:this.storageContract(),machineId:Q,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.dryRun!==!0}),R=()=>fU({dbPath:W.knowledgeDbPath,scope:this.scope,workspaceHome:W.home,storage:G,machineId:q,tables:$.tables,includeArtifactContent:$.includeArtifactContent,recordClocks:$.dryRun!==!0}),B={ok:!0,dry_run:$.dryRun===!0,direction:_,resolved_workspace:rX(L,L.project_root??U),message:""};if(_==="pull"||_==="both")B.pull=await j8({targetDbPath:J.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:J.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:R(),targetBundle:N(),direction:"pull",dryRun:$.dryRun,localMachineId:Q});if(_==="push"||_==="both")B.push=await j8({targetDbPath:W.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:W.home,targetStorage:G,targetStore:Y,bundle:N(),targetBundle:R(),direction:"push",dryRun:$.dryRun,localMachineId:q});return B.ok=(B.pull?.ok??!0)&&(B.push?.ok??!0),B.message=[wE(B.resolved_workspace),B.pull?`pull: ${B.pull.message}`:null,B.push?`push: ${B.push.message}`:null].filter(Boolean).join("; "),B}}function $Y($={}){return new uE($)}var Ic=Object.defineProperty,fc=($)=>$;function Cc($,_){this[$]=fc.bind(null,_)}var Pc=($,_)=>{for(var J in _)Ic($,J,{get:_[J],enumerable:!0,configurable:!0,set:Cc.bind(_,J)})},O={};Pc(O,{void:()=>Hi,util:()=>x$,unknown:()=>Li,union:()=>Ki,undefined:()=>ji,tuple:()=>Mi,transformer:()=>cE,symbol:()=>zi,string:()=>$M,strictObject:()=>Ri,setErrorMap:()=>Zc,set:()=>wi,record:()=>Ai,quotelessJson:()=>Tc,promise:()=>Pi,preprocess:()=>Zi,pipeline:()=>vi,ostring:()=>yi,optional:()=>Ti,onumber:()=>hi,oboolean:()=>mi,objectUtil:()=>_B,object:()=>Vi,number:()=>_M,nullable:()=>Si,null:()=>Di,never:()=>Bi,nativeEnum:()=>Ci,nan:()=>Yi,map:()=>bi,makeIssue:()=>JY,literal:()=>Ii,lazy:()=>ki,late:()=>Xi,isValid:()=>D2,isDirty:()=>WB,isAsync:()=>aX,isAborted:()=>JB,intersection:()=>Ei,instanceof:()=>Gi,getParsedType:()=>_0,getErrorMap:()=>_Y,function:()=>gi,enum:()=>fi,effect:()=>cE,discriminatedUnion:()=>Fi,defaultErrorMap:()=>MW,datetimeRegex:()=>aE,date:()=>qi,custom:()=>eE,coerce:()=>xi,boolean:()=>JM,bigint:()=>Qi,array:()=>Ni,any:()=>Oi,addIssueToContext:()=>l,ZodVoid:()=>eX,ZodUnknown:()=>i0,ZodUnion:()=>gW,ZodUndefined:()=>bW,ZodType:()=>S$,ZodTuple:()=>N4,ZodTransformer:()=>F6,ZodSymbol:()=>sX,ZodString:()=>l6,ZodSet:()=>B2,ZodSchema:()=>S$,ZodRecord:()=>$9,ZodReadonly:()=>SW,ZodPromise:()=>H2,ZodPipeline:()=>W9,ZodParsedType:()=>t,ZodOptional:()=>p6,ZodObject:()=>R_,ZodNumber:()=>l0,ZodNullable:()=>J0,ZodNull:()=>wW,ZodNever:()=>H4,ZodNativeEnum:()=>CW,ZodNaN:()=>J9,ZodMap:()=>_9,ZodLiteral:()=>fW,ZodLazy:()=>IW,ZodIssueCode:()=>Z,ZodIntersection:()=>kW,ZodFunction:()=>EW,ZodFirstPartyTypeKind:()=>B$,ZodError:()=>z6,ZodEnum:()=>p0,ZodEffects:()=>F6,ZodDiscriminatedUnion:()=>WY,ZodDefault:()=>PW,ZodDate:()=>O2,ZodCatch:()=>TW,ZodBranded:()=>UY,ZodBoolean:()=>AW,ZodBigInt:()=>r0,ZodArray:()=>r6,ZodAny:()=>L2,Schema:()=>S$,ParseStatus:()=>h_,OK:()=>r_,NEVER:()=>ui,INVALID:()=>j$,EMPTY_PATH:()=>vc,DIRTY:()=>FW,BRAND:()=>Ui});var x$;(function($){$.assertEqual=(W)=>{};function _(W){}$.assertIs=_;function J(W){throw Error()}$.assertNever=J,$.arrayToEnum=(W)=>{let X={};for(let G of W)X[G]=G;return X},$.getValidEnumValues=(W)=>{let X=$.objectKeys(W).filter((Y)=>typeof W[W[Y]]!=="number"),G={};for(let Y of X)G[Y]=W[Y];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(X){return W[X]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let X=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))X.push(G);return X},$.find=(W,X)=>{for(let G of W)if(X(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function U(W,X=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(X)}$.joinValues=U,$.jsonStringifyReplacer=(W,X)=>{if(typeof X==="bigint")return X.toString();return X}})(x$||(x$={}));var _B;(function($){$.mergeShapes=(_,J)=>{return{..._,...J}}})(_B||(_B={}));var t=x$.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),_0=($)=>{switch(typeof $){case"undefined":return t.undefined;case"string":return t.string;case"number":return Number.isNaN($)?t.nan:t.number;case"boolean":return t.boolean;case"function":return t.function;case"bigint":return t.bigint;case"symbol":return t.symbol;case"object":if(Array.isArray($))return t.array;if($===null)return t.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return t.promise;if(typeof Map<"u"&&$ instanceof Map)return t.map;if(typeof Set<"u"&&$ instanceof Set)return t.set;if(typeof Date<"u"&&$ instanceof Date)return t.date;return t.object;default:return t.unknown}},Z=x$.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"]),Tc=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class z6 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(J)=>{this.issues=[...this.issues,J]},this.addIssues=(J=[])=>{this.issues=[...this.issues,...J]};let _=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,_);else this.__proto__=_;this.name="ZodError",this.issues=$}format($){let _=$||function(W){return W.message},J={_errors:[]},U=(W)=>{for(let X of W.issues)if(X.code==="invalid_union")X.unionErrors.map(U);else if(X.code==="invalid_return_type")U(X.returnTypeError);else if(X.code==="invalid_arguments")U(X.argumentsError);else if(X.path.length===0)J._errors.push(_(X));else{let G=J,Y=0;while(Y_.message){let _={},J=[];for(let U of this.issues)if(U.path.length>0){let W=U.path[0];_[W]=_[W]||[],_[W].push($(U))}else J.push($(U));return{formErrors:J,fieldErrors:_}}get formErrors(){return this.flatten()}}z6.create=($)=>{return new z6($)};var Sc=($,_)=>{let J;switch($.code){case Z.invalid_type:if($.received===t.undefined)J="Required";else J=`Expected ${$.expected}, received ${$.received}`;break;case Z.invalid_literal:J=`Invalid literal value, expected ${JSON.stringify($.expected,x$.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:J=`Unrecognized key(s) in object: ${x$.joinValues($.keys,", ")}`;break;case Z.invalid_union:J="Invalid input";break;case Z.invalid_union_discriminator:J=`Invalid discriminator value. Expected ${x$.joinValues($.options)}`;break;case Z.invalid_enum_value:J=`Invalid enum value. Expected ${x$.joinValues($.options)}, received '${$.received}'`;break;case Z.invalid_arguments:J="Invalid function arguments";break;case Z.invalid_return_type:J="Invalid function return type";break;case Z.invalid_date:J="Invalid date";break;case Z.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(J=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")J=`${J} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)J=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)J=`Invalid input: must end with "${$.validation.endsWith}"`;else x$.assertNever($.validation);else if($.validation!=="regex")J=`Invalid ${$.validation}`;else J="Invalid";break;case Z.too_small:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")J=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else J="Invalid input";break;case Z.too_big:if($.type==="array")J=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")J=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")J=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")J=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")J=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else J="Invalid input";break;case Z.custom:J="Invalid input";break;case Z.invalid_intersection_types:J="Intersection results could not be merged";break;case Z.not_multiple_of:J=`Number must be a multiple of ${$.multipleOf}`;break;case Z.not_finite:J="Number must be finite";break;default:J=_.defaultError,x$.assertNever($)}return{message:J}},MW=Sc,pE=MW;function Zc($){pE=$}function _Y(){return pE}var JY=($)=>{let{data:_,path:J,errorMaps:U,issueData:W}=$,X=[...J,...W.path||[]],G={...W,path:X};if(W.message!==void 0)return{...W,path:X,message:W.message};let Y="",Q=U.filter((q)=>!!q).slice().reverse();for(let q of Q)Y=q(G,{data:_,defaultError:Y}).message;return{...W,path:X,message:Y}},vc=[];function l($,_){let J=_Y(),U=JY({issueData:_,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,J,J===MW?void 0:MW].filter((W)=>!!W)});$.common.issues.push(U)}class h_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,_){let J=[];for(let U of _){if(U.status==="aborted")return j$;if(U.status==="dirty")$.dirty();J.push(U.value)}return{status:$.value,value:J}}static async mergeObjectAsync($,_){let J=[];for(let U of _){let W=await U.key,X=await U.value;J.push({key:W,value:X})}return h_.mergeObjectSync($,J)}static mergeObjectSync($,_){let J={};for(let U of _){let{key:W,value:X}=U;if(W.status==="aborted")return j$;if(X.status==="aborted")return j$;if(W.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof X.value<"u"||U.alwaysSet))J[W.value]=X.value}return{status:$.value,value:J}}}var j$=Object.freeze({status:"aborted"}),FW=($)=>({status:"dirty",value:$}),r_=($)=>({status:"valid",value:$}),JB=($)=>$.status==="aborted",WB=($)=>$.status==="dirty",D2=($)=>$.status==="valid",aX=($)=>typeof Promise<"u"&&$ instanceof Promise,G$;(function($){$.errToObj=(_)=>typeof _==="string"?{message:_}:_||{},$.toString=(_)=>typeof _==="string"?_:_?.message})(G$||(G$={}));class o6{constructor($,_,J,U){this._cachedPath=[],this.parent=$,this.data=_,this._path=J,this._key=U}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}}var dE=($,_)=>{if(D2(_))return{success:!0,data:_.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let J=new z6($.common.issues);return this._error=J,this._error}}}};function w$($){if(!$)return{};let{errorMap:_,invalid_type_error:J,required_error:U,description:W}=$;if(_&&(J||U))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(_)return{errorMap:_,description:W};return{errorMap:(G,Y)=>{let{message:Q}=$;if(G.code==="invalid_enum_value")return{message:Q??Y.defaultError};if(typeof Y.data>"u")return{message:Q??U??Y.defaultError};if(G.code!=="invalid_type")return{message:Y.defaultError};return{message:Q??J??Y.defaultError}},description:W}}class S${get description(){return this._def.description}_getType($){return _0($.data)}_getOrReturnCtx($,_){return _||{common:$.parent.common,data:$.data,parsedType:_0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new h_,ctx:{common:$.parent.common,data:$.data,parsedType:_0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let _=this._parse($);if(aX(_))throw Error("Synchronous parse encountered promise.");return _}_parseAsync($){let _=this._parse($);return Promise.resolve(_)}parse($,_){let J=this.safeParse($,_);if(J.success)return J.data;throw J.error}safeParse($,_){let J={common:{issues:[],async:_?.async??!1,contextualErrorMap:_?.errorMap},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:_0($)},U=this._parseSync({data:$,path:J.path,parent:J});return dE(J,U)}"~validate"($){let _={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:_0($)};if(!this["~standard"].async)try{let J=this._parseSync({data:$,path:[],parent:_});return D2(J)?{value:J.value}:{issues:_.common.issues}}catch(J){if(J?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;_.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:_}).then((J)=>D2(J)?{value:J.value}:{issues:_.common.issues})}async parseAsync($,_){let J=await this.safeParseAsync($,_);if(J.success)return J.data;throw J.error}async safeParseAsync($,_){let J={common:{issues:[],contextualErrorMap:_?.errorMap,async:!0},path:_?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:_0($)},U=this._parse({data:$,path:J.path,parent:J}),W=await(aX(U)?U:Promise.resolve(U));return dE(J,W)}refine($,_){let J=(U)=>{if(typeof _==="string"||typeof _>"u")return{message:_};else if(typeof _==="function")return _(U);else return _};return this._refinement((U,W)=>{let X=$(U),G=()=>W.addIssue({code:Z.custom,...J(U)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((Y)=>{if(!Y)return G(),!1;else return!0});if(!X)return G(),!1;else return!0})}refinement($,_){return this._refinement((J,U)=>{if(!$(J))return U.addIssue(typeof _==="function"?_(J,U):_),!1;else return!0})}_refinement($){return new F6({schema:this,typeName:B$.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._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:(_)=>this["~validate"](_)}}optional(){return p6.create(this,this._def)}nullable(){return J0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return r6.create(this)}promise(){return H2.create(this,this._def)}or($){return gW.create([this,$],this._def)}and($){return kW.create(this,$,this._def)}transform($){return new F6({...w$(this._def),schema:this,typeName:B$.ZodEffects,effect:{type:"transform",transform:$}})}default($){let _=typeof $==="function"?$:()=>$;return new PW({...w$(this._def),innerType:this,defaultValue:_,typeName:B$.ZodDefault})}brand(){return new UY({typeName:B$.ZodBranded,type:this,...w$(this._def)})}catch($){let _=typeof $==="function"?$:()=>$;return new TW({...w$(this._def),innerType:this,catchValue:_,typeName:B$.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return W9.create(this,$)}readonly(){return SW.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var yc=/^c[^\s-]{8,}$/i,hc=/^[0-9a-z]+$/,mc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xc=/^[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,uc=/^[a-z0-9_-]{21}$/i,dc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nc=/^[-+]?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)?)??$/,cc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ic="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",sL,lc=/^(?:(?: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])$/,rc=/^(?:(?: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])$/,pc=/^(([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]))$/,oc=/^(([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])$/,tc=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ac=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oE="((\\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])))",sc=new RegExp(`^${oE}$`);function tE($){let _="[0-5]\\d";if($.precision)_=`${_}\\.\\d{${$.precision}}`;else if($.precision==null)_=`${_}(\\.\\d+)?`;let J=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${_})${J}`}function ec($){return new RegExp(`^${tE($)}$`)}function aE($){let _=`${oE}T${tE($)}`,J=[];if(J.push($.local?"Z?":"Z"),$.offset)J.push("([+-]\\d{2}:?\\d{2})");return _=`${_}(${J.join("|")})`,new RegExp(`^${_}$`)}function $i($,_){if((_==="v4"||!_)&&lc.test($))return!0;if((_==="v6"||!_)&&pc.test($))return!0;return!1}function _i($,_){if(!dc.test($))return!1;try{let[J]=$.split(".");if(!J)return!1;let U=J.replace(/-/g,"+").replace(/_/g,"/").padEnd(J.length+(4-J.length%4)%4,"="),W=JSON.parse(atob(U));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(_&&W.alg!==_)return!1;return!0}catch{return!1}}function Ji($,_){if((_==="v4"||!_)&&rc.test($))return!0;if((_==="v6"||!_)&&oc.test($))return!0;return!1}class l6 extends S${_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==t.string){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_type,expected:t.string,received:W.parsedType}),j$}let J=new h_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.lengthW.value)U=this._getOrReturnCtx($,U),l(U,{code:Z.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),J.dirty()}else if(W.kind==="length"){let X=$.data.length>W.value,G=$.data.length$.test(U),{validation:_,code:Z.invalid_string,...G$.errToObj(J)})}_addCheck($){return new l6({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...G$.errToObj($)})}url($){return this._addCheck({kind:"url",...G$.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...G$.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...G$.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...G$.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...G$.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...G$.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...G$.errToObj($)})}base64($){return this._addCheck({kind:"base64",...G$.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...G$.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...G$.errToObj($)})}ip($){return this._addCheck({kind:"ip",...G$.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...G$.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...G$.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...G$.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...G$.errToObj($)})}regex($,_){return this._addCheck({kind:"regex",regex:$,...G$.errToObj(_)})}includes($,_){return this._addCheck({kind:"includes",value:$,position:_?.position,...G$.errToObj(_?.message)})}startsWith($,_){return this._addCheck({kind:"startsWith",value:$,...G$.errToObj(_)})}endsWith($,_){return this._addCheck({kind:"endsWith",value:$,...G$.errToObj(_)})}min($,_){return this._addCheck({kind:"min",value:$,...G$.errToObj(_)})}max($,_){return this._addCheck({kind:"max",value:$,...G$.errToObj(_)})}length($,_){return this._addCheck({kind:"length",value:$,...G$.errToObj(_)})}nonempty($){return this.min(1,G$.errToObj($))}trim(){return new l6({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new l6({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new l6({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxLength(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}l6.create=($)=>{return new l6({checks:[],typeName:B$.ZodString,coerce:$?.coerce??!1,...w$($)})};function Wi($,_){let J=($.toString().split(".")[1]||"").length,U=(_.toString().split(".")[1]||"").length,W=J>U?J:U,X=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(_.toFixed(W).replace(".",""));return X%G/10**W}class l0 extends S${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==t.number){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_type,expected:t.number,received:W.parsedType}),j$}let J=void 0,U=new h_;for(let W of this._def.checks)if(W.kind==="int"){if(!x$.isInteger($.data))J=this._getOrReturnCtx($,J),l(J,{code:Z.invalid_type,expected:"integer",received:"float",message:W.message}),U.dirty()}else if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),l(J,{code:Z.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if(Wi($.data,W.value)!==0)J=this._getOrReturnCtx($,J),l(J,{code:Z.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))J=this._getOrReturnCtx($,J),l(J,{code:Z.not_finite,message:W.message}),U.dirty()}else x$.assertNever(W);return{status:U.value,value:$.data}}gte($,_){return this.setLimit("min",$,!0,G$.toString(_))}gt($,_){return this.setLimit("min",$,!1,G$.toString(_))}lte($,_){return this.setLimit("max",$,!0,G$.toString(_))}lt($,_){return this.setLimit("max",$,!1,G$.toString(_))}setLimit($,_,J,U){return new l0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:G$.toString(U)}]})}_addCheck($){return new l0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:G$.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G$.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:G$.toString(_)})}finite($){return this._addCheck({kind:"finite",message:G$.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G$.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G$.toString($)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&x$.isInteger($.value))}get isFinite(){let $=null,_=null;for(let J of this._def.checks)if(J.kind==="finite"||J.kind==="int"||J.kind==="multipleOf")return!0;else if(J.kind==="min"){if(_===null||J.value>_)_=J.value}else if(J.kind==="max"){if($===null||J.value<$)$=J.value}return Number.isFinite(_)&&Number.isFinite($)}}l0.create=($)=>{return new l0({checks:[],typeName:B$.ZodNumber,coerce:$?.coerce||!1,...w$($)})};class r0 extends S${constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==t.bigint)return this._getInvalidInput($);let J=void 0,U=new h_;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.dataW.value:$.data>=W.value)J=this._getOrReturnCtx($,J),l(J,{code:Z.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),U.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))J=this._getOrReturnCtx($,J),l(J,{code:Z.not_multiple_of,multipleOf:W.value,message:W.message}),U.dirty()}else x$.assertNever(W);return{status:U.value,value:$.data}}_getInvalidInput($){let _=this._getOrReturnCtx($);return l(_,{code:Z.invalid_type,expected:t.bigint,received:_.parsedType}),j$}gte($,_){return this.setLimit("min",$,!0,G$.toString(_))}gt($,_){return this.setLimit("min",$,!1,G$.toString(_))}lte($,_){return this.setLimit("max",$,!0,G$.toString(_))}lt($,_){return this.setLimit("max",$,!1,G$.toString(_))}setLimit($,_,J,U){return new r0({...this._def,checks:[...this._def.checks,{kind:$,value:_,inclusive:J,message:G$.toString(U)}]})}_addCheck($){return new r0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:G$.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G$.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G$.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G$.toString($)})}multipleOf($,_){return this._addCheck({kind:"multipleOf",value:$,message:G$.toString(_)})}get minValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $}get maxValue(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $}}r0.create=($)=>{return new r0({checks:[],typeName:B$.ZodBigInt,coerce:$?.coerce??!1,...w$($)})};class AW extends S${_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==t.boolean){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.boolean,received:J.parsedType}),j$}return r_($.data)}}AW.create=($)=>{return new AW({typeName:B$.ZodBoolean,coerce:$?.coerce||!1,...w$($)})};class O2 extends S${_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==t.date){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_type,expected:t.date,received:W.parsedType}),j$}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return l(W,{code:Z.invalid_date}),j$}let J=new h_,U=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()W.value)U=this._getOrReturnCtx($,U),l(U,{code:Z.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),J.dirty()}else x$.assertNever(W);return{status:J.value,value:new Date($.data.getTime())}}_addCheck($){return new O2({...this._def,checks:[...this._def.checks,$]})}min($,_){return this._addCheck({kind:"min",value:$.getTime(),message:G$.toString(_)})}max($,_){return this._addCheck({kind:"max",value:$.getTime(),message:G$.toString(_)})}get minDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="min"){if($===null||_.value>$)$=_.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let _ of this._def.checks)if(_.kind==="max"){if($===null||_.value<$)$=_.value}return $!=null?new Date($):null}}O2.create=($)=>{return new O2({checks:[],coerce:$?.coerce||!1,typeName:B$.ZodDate,...w$($)})};class sX extends S${_parse($){if(this._getType($)!==t.symbol){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.symbol,received:J.parsedType}),j$}return r_($.data)}}sX.create=($)=>{return new sX({typeName:B$.ZodSymbol,...w$($)})};class bW extends S${_parse($){if(this._getType($)!==t.undefined){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.undefined,received:J.parsedType}),j$}return r_($.data)}}bW.create=($)=>{return new bW({typeName:B$.ZodUndefined,...w$($)})};class wW extends S${_parse($){if(this._getType($)!==t.null){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.null,received:J.parsedType}),j$}return r_($.data)}}wW.create=($)=>{return new wW({typeName:B$.ZodNull,...w$($)})};class L2 extends S${constructor(){super(...arguments);this._any=!0}_parse($){return r_($.data)}}L2.create=($)=>{return new L2({typeName:B$.ZodAny,...w$($)})};class i0 extends S${constructor(){super(...arguments);this._unknown=!0}_parse($){return r_($.data)}}i0.create=($)=>{return new i0({typeName:B$.ZodUnknown,...w$($)})};class H4 extends S${_parse($){let _=this._getOrReturnCtx($);return l(_,{code:Z.invalid_type,expected:t.never,received:_.parsedType}),j$}}H4.create=($)=>{return new H4({typeName:B$.ZodNever,...w$($)})};class eX extends S${_parse($){if(this._getType($)!==t.undefined){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.void,received:J.parsedType}),j$}return r_($.data)}}eX.create=($)=>{return new eX({typeName:B$.ZodVoid,...w$($)})};class r6 extends S${_parse($){let{ctx:_,status:J}=this._processInputParams($),U=this._def;if(_.parsedType!==t.array)return l(_,{code:Z.invalid_type,expected:t.array,received:_.parsedType}),j$;if(U.exactLength!==null){let X=_.data.length>U.exactLength.value,G=_.data.lengthU.maxLength.value)l(_,{code:Z.too_big,maximum:U.maxLength.value,type:"array",inclusive:!0,exact:!1,message:U.maxLength.message}),J.dirty()}if(_.common.async)return Promise.all([..._.data].map((X,G)=>{return U.type._parseAsync(new o6(_,X,_.path,G))})).then((X)=>{return h_.mergeArray(J,X)});let W=[..._.data].map((X,G)=>{return U.type._parseSync(new o6(_,X,_.path,G))});return h_.mergeArray(J,W)}get element(){return this._def.type}min($,_){return new r6({...this._def,minLength:{value:$,message:G$.toString(_)}})}max($,_){return new r6({...this._def,maxLength:{value:$,message:G$.toString(_)}})}length($,_){return new r6({...this._def,exactLength:{value:$,message:G$.toString(_)}})}nonempty($){return this.min(1,$)}}r6.create=($,_)=>{return new r6({type:$,minLength:null,maxLength:null,exactLength:null,typeName:B$.ZodArray,...w$(_)})};function KW($){if($ instanceof R_){let _={};for(let J in $.shape){let U=$.shape[J];_[J]=p6.create(KW(U))}return new R_({...$._def,shape:()=>_})}else if($ instanceof r6)return new r6({...$._def,type:KW($.element)});else if($ instanceof p6)return p6.create(KW($.unwrap()));else if($ instanceof J0)return J0.create(KW($.unwrap()));else if($ instanceof N4)return N4.create($.items.map((_)=>KW(_)));else return $}class R_ extends S${constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),_=x$.objectKeys($);return this._cached={shape:$,keys:_},this._cached}_parse($){if(this._getType($)!==t.object){let Q=this._getOrReturnCtx($);return l(Q,{code:Z.invalid_type,expected:t.object,received:Q.parsedType}),j$}let{status:J,ctx:U}=this._processInputParams($),{shape:W,keys:X}=this._getCached(),G=[];if(!(this._def.catchall instanceof H4&&this._def.unknownKeys==="strip")){for(let Q in U.data)if(!X.includes(Q))G.push(Q)}let Y=[];for(let Q of X){let q=W[Q],L=U.data[Q];Y.push({key:{status:"valid",value:Q},value:q._parse(new o6(U,L,U.path,Q)),alwaysSet:Q in U.data})}if(this._def.catchall instanceof H4){let Q=this._def.unknownKeys;if(Q==="passthrough")for(let q of G)Y.push({key:{status:"valid",value:q},value:{status:"valid",value:U.data[q]}});else if(Q==="strict"){if(G.length>0)l(U,{code:Z.unrecognized_keys,keys:G}),J.dirty()}else if(Q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Q=this._def.catchall;for(let q of G){let L=U.data[q];Y.push({key:{status:"valid",value:q},value:Q._parse(new o6(U,L,U.path,q)),alwaysSet:q in U.data})}}if(U.common.async)return Promise.resolve().then(async()=>{let Q=[];for(let q of Y){let L=await q.key,N=await q.value;Q.push({key:L,value:N,alwaysSet:q.alwaysSet})}return Q}).then((Q)=>{return h_.mergeObjectSync(J,Q)});else return h_.mergeObjectSync(J,Y)}get shape(){return this._def.shape()}strict($){return G$.errToObj,new R_({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(_,J)=>{let U=this._def.errorMap?.(_,J).message??J.defaultError;if(_.code==="unrecognized_keys")return{message:G$.errToObj($).message??U};return{message:U}}}:{}})}strip(){return new R_({...this._def,unknownKeys:"strip"})}passthrough(){return new R_({...this._def,unknownKeys:"passthrough"})}extend($){return new R_({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new R_({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:B$.ZodObject})}setKey($,_){return this.augment({[$]:_})}catchall($){return new R_({...this._def,catchall:$})}pick($){let _={};for(let J of x$.objectKeys($))if($[J]&&this.shape[J])_[J]=this.shape[J];return new R_({...this._def,shape:()=>_})}omit($){let _={};for(let J of x$.objectKeys(this.shape))if(!$[J])_[J]=this.shape[J];return new R_({...this._def,shape:()=>_})}deepPartial(){return KW(this)}partial($){let _={};for(let J of x$.objectKeys(this.shape)){let U=this.shape[J];if($&&!$[J])_[J]=U;else _[J]=U.optional()}return new R_({...this._def,shape:()=>_})}required($){let _={};for(let J of x$.objectKeys(this.shape))if($&&!$[J])_[J]=this.shape[J];else{let W=this.shape[J];while(W instanceof p6)W=W._def.innerType;_[J]=W}return new R_({...this._def,shape:()=>_})}keyof(){return sE(x$.objectKeys(this.shape))}}R_.create=($,_)=>{return new R_({shape:()=>$,unknownKeys:"strip",catchall:H4.create(),typeName:B$.ZodObject,...w$(_)})};R_.strictCreate=($,_)=>{return new R_({shape:()=>$,unknownKeys:"strict",catchall:H4.create(),typeName:B$.ZodObject,...w$(_)})};R_.lazycreate=($,_)=>{return new R_({shape:$,unknownKeys:"strip",catchall:H4.create(),typeName:B$.ZodObject,...w$(_)})};class gW extends S${_parse($){let{ctx:_}=this._processInputParams($),J=this._def.options;function U(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return _.common.issues.push(...G.ctx.common.issues),G.result;let X=W.map((G)=>new z6(G.ctx.common.issues));return l(_,{code:Z.invalid_union,unionErrors:X}),j$}if(_.common.async)return Promise.all(J.map(async(W)=>{let X={..._,common:{..._.common,issues:[]},parent:null};return{result:await W._parseAsync({data:_.data,path:_.path,parent:X}),ctx:X}})).then(U);else{let W=void 0,X=[];for(let Y of J){let Q={..._,common:{..._.common,issues:[]},parent:null},q=Y._parseSync({data:_.data,path:_.path,parent:Q});if(q.status==="valid")return q;else if(q.status==="dirty"&&!W)W={result:q,ctx:Q};if(Q.common.issues.length)X.push(Q.common.issues)}if(W)return _.common.issues.push(...W.ctx.common.issues),W.result;let G=X.map((Y)=>new z6(Y));return l(_,{code:Z.invalid_union,unionErrors:G}),j$}}get options(){return this._def.options}}gW.create=($,_)=>{return new gW({options:$,typeName:B$.ZodUnion,...w$(_)})};var $0=($)=>{if($ instanceof IW)return $0($.schema);else if($ instanceof F6)return $0($.innerType());else if($ instanceof fW)return[$.value];else if($ instanceof p0)return $.options;else if($ instanceof CW)return x$.objectValues($.enum);else if($ instanceof PW)return $0($._def.innerType);else if($ instanceof bW)return[void 0];else if($ instanceof wW)return[null];else if($ instanceof p6)return[void 0,...$0($.unwrap())];else if($ instanceof J0)return[null,...$0($.unwrap())];else if($ instanceof UY)return $0($.unwrap());else if($ instanceof SW)return $0($.unwrap());else if($ instanceof TW)return $0($._def.innerType);else return[]};class WY extends S${_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.object)return l(_,{code:Z.invalid_type,expected:t.object,received:_.parsedType}),j$;let J=this.discriminator,U=_.data[J],W=this.optionsMap.get(U);if(!W)return l(_,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[J]}),j$;if(_.common.async)return W._parseAsync({data:_.data,path:_.path,parent:_});else return W._parseSync({data:_.data,path:_.path,parent:_})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,_,J){let U=new Map;for(let W of _){let X=$0(W.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of X){if(U.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);U.set(G,W)}}return new WY({typeName:B$.ZodDiscriminatedUnion,discriminator:$,options:_,optionsMap:U,...w$(J)})}}function UB($,_){let J=_0($),U=_0(_);if($===_)return{valid:!0,data:$};else if(J===t.object&&U===t.object){let W=x$.objectKeys(_),X=x$.objectKeys($).filter((Y)=>W.indexOf(Y)!==-1),G={...$,..._};for(let Y of X){let Q=UB($[Y],_[Y]);if(!Q.valid)return{valid:!1};G[Y]=Q.data}return{valid:!0,data:G}}else if(J===t.array&&U===t.array){if($.length!==_.length)return{valid:!1};let W=[];for(let X=0;X<$.length;X++){let G=$[X],Y=_[X],Q=UB(G,Y);if(!Q.valid)return{valid:!1};W.push(Q.data)}return{valid:!0,data:W}}else if(J===t.date&&U===t.date&&+$===+_)return{valid:!0,data:$};else return{valid:!1}}class kW extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($),U=(W,X)=>{if(JB(W)||JB(X))return j$;let G=UB(W.value,X.value);if(!G.valid)return l(J,{code:Z.invalid_intersection_types}),j$;if(WB(W)||WB(X))_.dirty();return{status:_.value,value:G.data}};if(J.common.async)return Promise.all([this._def.left._parseAsync({data:J.data,path:J.path,parent:J}),this._def.right._parseAsync({data:J.data,path:J.path,parent:J})]).then(([W,X])=>U(W,X));else return U(this._def.left._parseSync({data:J.data,path:J.path,parent:J}),this._def.right._parseSync({data:J.data,path:J.path,parent:J}))}}kW.create=($,_,J)=>{return new kW({left:$,right:_,typeName:B$.ZodIntersection,...w$(J)})};class N4 extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.array)return l(J,{code:Z.invalid_type,expected:t.array,received:J.parsedType}),j$;if(J.data.lengththis._def.items.length)l(J,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_.dirty();let W=[...J.data].map((X,G)=>{let Y=this._def.items[G]||this._def.rest;if(!Y)return null;return Y._parse(new o6(J,X,J.path,G))}).filter((X)=>!!X);if(J.common.async)return Promise.all(W).then((X)=>{return h_.mergeArray(_,X)});else return h_.mergeArray(_,W)}get items(){return this._def.items}rest($){return new N4({...this._def,rest:$})}}N4.create=($,_)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new N4({items:$,typeName:B$.ZodTuple,rest:null,...w$(_)})};class $9 extends S${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.object)return l(J,{code:Z.invalid_type,expected:t.object,received:J.parsedType}),j$;let U=[],W=this._def.keyType,X=this._def.valueType;for(let G in J.data)U.push({key:W._parse(new o6(J,G,J.path,G)),value:X._parse(new o6(J,J.data[G],J.path,G)),alwaysSet:G in J.data});if(J.common.async)return h_.mergeObjectAsync(_,U);else return h_.mergeObjectSync(_,U)}get element(){return this._def.valueType}static create($,_,J){if(_ instanceof S$)return new $9({keyType:$,valueType:_,typeName:B$.ZodRecord,...w$(J)});return new $9({keyType:l6.create(),valueType:$,typeName:B$.ZodRecord,...w$(_)})}}class _9 extends S${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.map)return l(J,{code:Z.invalid_type,expected:t.map,received:J.parsedType}),j$;let U=this._def.keyType,W=this._def.valueType,X=[...J.data.entries()].map(([G,Y],Q)=>{return{key:U._parse(new o6(J,G,J.path,[Q,"key"])),value:W._parse(new o6(J,Y,J.path,[Q,"value"]))}});if(J.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let Y of X){let Q=await Y.key,q=await Y.value;if(Q.status==="aborted"||q.status==="aborted")return j$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}})}else{let G=new Map;for(let Y of X){let{key:Q,value:q}=Y;if(Q.status==="aborted"||q.status==="aborted")return j$;if(Q.status==="dirty"||q.status==="dirty")_.dirty();G.set(Q.value,q.value)}return{status:_.value,value:G}}}}_9.create=($,_,J)=>{return new _9({valueType:_,keyType:$,typeName:B$.ZodMap,...w$(J)})};class B2 extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.parsedType!==t.set)return l(J,{code:Z.invalid_type,expected:t.set,received:J.parsedType}),j$;let U=this._def;if(U.minSize!==null){if(J.data.sizeU.maxSize.value)l(J,{code:Z.too_big,maximum:U.maxSize.value,type:"set",inclusive:!0,exact:!1,message:U.maxSize.message}),_.dirty()}let W=this._def.valueType;function X(Y){let Q=new Set;for(let q of Y){if(q.status==="aborted")return j$;if(q.status==="dirty")_.dirty();Q.add(q.value)}return{status:_.value,value:Q}}let G=[...J.data.values()].map((Y,Q)=>W._parse(new o6(J,Y,J.path,Q)));if(J.common.async)return Promise.all(G).then((Y)=>X(Y));else return X(G)}min($,_){return new B2({...this._def,minSize:{value:$,message:G$.toString(_)}})}max($,_){return new B2({...this._def,maxSize:{value:$,message:G$.toString(_)}})}size($,_){return this.min($,_).max($,_)}nonempty($){return this.min(1,$)}}B2.create=($,_)=>{return new B2({valueType:$,minSize:null,maxSize:null,typeName:B$.ZodSet,...w$(_)})};class EW extends S${constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.function)return l(_,{code:Z.invalid_type,expected:t.function,received:_.parsedType}),j$;function J(G,Y){return JY({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,_Y(),MW].filter((Q)=>!!Q),issueData:{code:Z.invalid_arguments,argumentsError:Y}})}function U(G,Y){return JY({data:G,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,_Y(),MW].filter((Q)=>!!Q),issueData:{code:Z.invalid_return_type,returnTypeError:Y}})}let W={errorMap:_.common.contextualErrorMap},X=_.data;if(this._def.returns instanceof H2){let G=this;return r_(async function(...Y){let Q=new z6([]),q=await G._def.args.parseAsync(Y,W).catch((R)=>{throw Q.addIssue(J(Y,R)),Q}),L=await Reflect.apply(X,this,q);return await G._def.returns._def.type.parseAsync(L,W).catch((R)=>{throw Q.addIssue(U(L,R)),Q})})}else{let G=this;return r_(function(...Y){let Q=G._def.args.safeParse(Y,W);if(!Q.success)throw new z6([J(Y,Q.error)]);let q=Reflect.apply(X,this,Q.data),L=G._def.returns.safeParse(q,W);if(!L.success)throw new z6([U(q,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new EW({...this._def,args:N4.create($).rest(i0.create())})}returns($){return new EW({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,_,J){return new EW({args:$?$:N4.create([]).rest(i0.create()),returns:_||i0.create(),typeName:B$.ZodFunction,...w$(J)})}}class IW extends S${get schema(){return this._def.getter()}_parse($){let{ctx:_}=this._processInputParams($);return this._def.getter()._parse({data:_.data,path:_.path,parent:_})}}IW.create=($,_)=>{return new IW({getter:$,typeName:B$.ZodLazy,...w$(_)})};class fW extends S${_parse($){if($.data!==this._def.value){let _=this._getOrReturnCtx($);return l(_,{received:_.data,code:Z.invalid_literal,expected:this._def.value}),j$}return{status:"valid",value:$.data}}get value(){return this._def.value}}fW.create=($,_)=>{return new fW({value:$,typeName:B$.ZodLiteral,...w$(_)})};function sE($,_){return new p0({values:$,typeName:B$.ZodEnum,...w$(_)})}class p0 extends S${_parse($){if(typeof $.data!=="string"){let _=this._getOrReturnCtx($),J=this._def.values;return l(_,{expected:x$.joinValues(J),received:_.parsedType,code:Z.invalid_type}),j$}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let _=this._getOrReturnCtx($),J=this._def.values;return l(_,{received:_.data,code:Z.invalid_enum_value,options:J}),j$}return r_($.data)}get options(){return this._def.values}get enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Values(){let $={};for(let _ of this._def.values)$[_]=_;return $}get Enum(){let $={};for(let _ of this._def.values)$[_]=_;return $}extract($,_=this._def){return p0.create($,{...this._def,..._})}exclude($,_=this._def){return p0.create(this.options.filter((J)=>!$.includes(J)),{...this._def,..._})}}p0.create=sE;class CW extends S${_parse($){let _=x$.getValidEnumValues(this._def.values),J=this._getOrReturnCtx($);if(J.parsedType!==t.string&&J.parsedType!==t.number){let U=x$.objectValues(_);return l(J,{expected:x$.joinValues(U),received:J.parsedType,code:Z.invalid_type}),j$}if(!this._cache)this._cache=new Set(x$.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let U=x$.objectValues(_);return l(J,{received:J.data,code:Z.invalid_enum_value,options:U}),j$}return r_($.data)}get enum(){return this._def.values}}CW.create=($,_)=>{return new CW({values:$,typeName:B$.ZodNativeEnum,...w$(_)})};class H2 extends S${unwrap(){return this._def.type}_parse($){let{ctx:_}=this._processInputParams($);if(_.parsedType!==t.promise&&_.common.async===!1)return l(_,{code:Z.invalid_type,expected:t.promise,received:_.parsedType}),j$;let J=_.parsedType===t.promise?_.data:Promise.resolve(_.data);return r_(J.then((U)=>{return this._def.type.parseAsync(U,{path:_.path,errorMap:_.common.contextualErrorMap})}))}}H2.create=($,_)=>{return new H2({type:$,typeName:B$.ZodPromise,...w$(_)})};class F6 extends S${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===B$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:_,ctx:J}=this._processInputParams($),U=this._def.effect||null,W={addIssue:(X)=>{if(l(J,X),X.fatal)_.abort();else _.dirty()},get path(){return J.path}};if(W.addIssue=W.addIssue.bind(W),U.type==="preprocess"){let X=U.transform(J.data,W);if(J.common.async)return Promise.resolve(X).then(async(G)=>{if(_.value==="aborted")return j$;let Y=await this._def.schema._parseAsync({data:G,path:J.path,parent:J});if(Y.status==="aborted")return j$;if(Y.status==="dirty")return FW(Y.value);if(_.value==="dirty")return FW(Y.value);return Y});else{if(_.value==="aborted")return j$;let G=this._def.schema._parseSync({data:X,path:J.path,parent:J});if(G.status==="aborted")return j$;if(G.status==="dirty")return FW(G.value);if(_.value==="dirty")return FW(G.value);return G}}if(U.type==="refinement"){let X=(G)=>{let Y=U.refinement(G,W);if(J.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(J.common.async===!1){let G=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(G.status==="aborted")return j$;if(G.status==="dirty")_.dirty();return X(G.value),{status:_.value,value:G.value}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((G)=>{if(G.status==="aborted")return j$;if(G.status==="dirty")_.dirty();return X(G.value).then(()=>{return{status:_.value,value:G.value}})})}if(U.type==="transform")if(J.common.async===!1){let X=this._def.schema._parseSync({data:J.data,path:J.path,parent:J});if(!D2(X))return j$;let G=U.transform(X.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:_.value,value:G}}else return this._def.schema._parseAsync({data:J.data,path:J.path,parent:J}).then((X)=>{if(!D2(X))return j$;return Promise.resolve(U.transform(X.value,W)).then((G)=>({status:_.value,value:G}))});x$.assertNever(U)}}F6.create=($,_,J)=>{return new F6({schema:$,typeName:B$.ZodEffects,effect:_,...w$(J)})};F6.createWithPreprocess=($,_,J)=>{return new F6({schema:_,effect:{type:"preprocess",transform:$},typeName:B$.ZodEffects,...w$(J)})};class p6 extends S${_parse($){if(this._getType($)===t.undefined)return r_(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}p6.create=($,_)=>{return new p6({innerType:$,typeName:B$.ZodOptional,...w$(_)})};class J0 extends S${_parse($){if(this._getType($)===t.null)return r_(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}J0.create=($,_)=>{return new J0({innerType:$,typeName:B$.ZodNullable,...w$(_)})};class PW extends S${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;if(_.parsedType===t.undefined)J=this._def.defaultValue();return this._def.innerType._parse({data:J,path:_.path,parent:_})}removeDefault(){return this._def.innerType}}PW.create=($,_)=>{return new PW({innerType:$,typeName:B$.ZodDefault,defaultValue:typeof _.default==="function"?_.default:()=>_.default,...w$(_)})};class TW extends S${_parse($){let{ctx:_}=this._processInputParams($),J={..._,common:{..._.common,issues:[]}},U=this._def.innerType._parse({data:J.data,path:J.path,parent:{...J}});if(aX(U))return U.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new z6(J.common.issues)},input:J.data})}});else return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new z6(J.common.issues)},input:J.data})}}removeCatch(){return this._def.innerType}}TW.create=($,_)=>{return new TW({innerType:$,typeName:B$.ZodCatch,catchValue:typeof _.catch==="function"?_.catch:()=>_.catch,...w$(_)})};class J9 extends S${_parse($){if(this._getType($)!==t.nan){let J=this._getOrReturnCtx($);return l(J,{code:Z.invalid_type,expected:t.nan,received:J.parsedType}),j$}return{status:"valid",value:$.data}}}J9.create=($)=>{return new J9({typeName:B$.ZodNaN,...w$($)})};var Ui=Symbol("zod_brand");class UY extends S${_parse($){let{ctx:_}=this._processInputParams($),J=_.data;return this._def.type._parse({data:J,path:_.path,parent:_})}unwrap(){return this._def.type}}class W9 extends S${_parse($){let{status:_,ctx:J}=this._processInputParams($);if(J.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:J.data,path:J.path,parent:J});if(W.status==="aborted")return j$;if(W.status==="dirty")return _.dirty(),FW(W.value);else return this._def.out._parseAsync({data:W.value,path:J.path,parent:J})})();else{let U=this._def.in._parseSync({data:J.data,path:J.path,parent:J});if(U.status==="aborted")return j$;if(U.status==="dirty")return _.dirty(),{status:"dirty",value:U.value};else return this._def.out._parseSync({data:U.value,path:J.path,parent:J})}}static create($,_){return new W9({in:$,out:_,typeName:B$.ZodPipeline})}}class SW extends S${_parse($){let _=this._def.innerType._parse($),J=(U)=>{if(D2(U))U.value=Object.freeze(U.value);return U};return aX(_)?_.then((U)=>J(U)):J(_)}unwrap(){return this._def.innerType}}SW.create=($,_)=>{return new SW({innerType:$,typeName:B$.ZodReadonly,...w$(_)})};function nE($,_){let J=typeof $==="function"?$(_):typeof $==="string"?{message:$}:$;return typeof J==="string"?{message:J}:J}function eE($,_={},J){if($)return L2.create().superRefine((U,W)=>{let X=$(U);if(X instanceof Promise)return X.then((G)=>{if(!G){let Y=nE(_,U),Q=Y.fatal??J??!0;W.addIssue({code:"custom",...Y,fatal:Q})}});if(!X){let G=nE(_,U),Y=G.fatal??J??!0;W.addIssue({code:"custom",...G,fatal:Y})}return});return L2.create()}var Xi={object:R_.lazycreate},B$;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(B$||(B$={}));var Gi=($,_={message:`Input not instance of ${$.name}`})=>eE((J)=>J instanceof $,_),$M=l6.create,_M=l0.create,Yi=J9.create,Qi=r0.create,JM=AW.create,qi=O2.create,zi=sX.create,ji=bW.create,Di=wW.create,Oi=L2.create,Li=i0.create,Bi=H4.create,Hi=eX.create,Ni=r6.create,Vi=R_.create,Ri=R_.strictCreate,Ki=gW.create,Fi=WY.create,Ei=kW.create,Mi=N4.create,Ai=$9.create,bi=_9.create,wi=B2.create,gi=EW.create,ki=IW.create,Ii=fW.create,fi=p0.create,Ci=CW.create,Pi=H2.create,cE=F6.create,Ti=p6.create,Si=J0.create,Zi=F6.createWithPreprocess,vi=W9.create,yi=()=>$M().optional(),hi=()=>_M().optional(),mi=()=>JM().optional(),xi={string:($)=>l6.create({...$,coerce:!0}),number:($)=>l0.create({...$,coerce:!0}),boolean:($)=>AW.create({...$,coerce:!0}),bigint:($)=>r0.create({...$,coerce:!0}),date:($)=>O2.create({...$,coerce:!0})},ui=j$;var s={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",decisionEnvelope:"hasna.decision_envelope.v1",costEstimate:"hasna.cost_estimate.v1",capabilityCard:"hasna.capability_card.v1",providerLiveModeStandard:"hasna.provider_live_mode_standard.v1",contextPack:"hasna.context_pack.v1",integrationRef:"hasna.integration_ref.v1",projectManifest:"hasna.project_manifest.v1",projectPanel:"hasna.project_panel.v1",projectSnapshot:"hasna.project_snapshot.v1",renderManifest:"hasna.render_manifest.v1",agentTrajectory:"hasna.agent_trajectory.v1",validationPlan:"hasna.validation_plan.v1",proofBundle:"hasna.proof_bundle.v1",scaffoldManifest:"hasna.scaffold_manifest.v1",scaffoldInstallRecord:"hasna.scaffold_install_record.v1",appCloudManifest:"hasna.app_cloud_manifest.v1",noCloudEvidencePack:"hasna.no_cloud_evidence_pack.v1",serviceContract:"hasna.service_contract.v1",commsEventEnvelope:"hasna.comms_event_envelope.v1",commsChannelMetadata:"hasna.comms_channel_metadata.v1",commsMessageMetadata:"hasna.comms_message_metadata.v1",app:"hasna.app.v1",release:"hasna.release.v1",rolloutRecord:"hasna.rollout_record.v1",announcement:"hasna.announcement.v1",audience:"hasna.audience.v1"},WM=O.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),j6=O.string().datetime(),K$=O.string().trim().min(1),t6=K$.refine(($)=>$.startsWith("artifact://")||$.startsWith("repo://")||$.startsWith("project://")||$.startsWith("dashboard://")||$.startsWith("render://")||$.startsWith("integration://")||$.startsWith("task://")||$.startsWith("todo://")||$.startsWith("file://")||$.startsWith("files://")||$.startsWith("mailery://")||$.startsWith("conversation://")||$.startsWith("knowledge://")||$.startsWith("memento://")||$.startsWith("https://")||$.startsWith("http://")||$.startsWith("git+https://"),"URI must use artifact://, repo://, project://, dashboard://, render://, integration://, task://, todo://, file://, files://, mailery://, conversation://, knowledge://, memento://, http(s)://, or git+https://"),UM=O.string().regex(/^[a-fA-F0-9]{64}$/),XM=O.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),W0=O.record(O.unknown()),yW=O.array(O.string().min(1)).default([]),N2=j6.nullable().optional(),di=new Set(["succeeded","failed","cancelled","blocked","skipped"]),R2=O.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function $_($){return O.object({schema:O.literal($),id:O.string().min(1),createdAt:j6,updatedAt:N2,metadata:W0.optional()}).strict()}var T4$=O.object({schema:WM,id:O.string().min(1),createdAt:j6,updatedAt:N2,metadata:W0.optional()}).strict(),GM=O.enum(["agent","human","service","model","workflow","system"]),ni=$_(s.actorRef).extend({kind:GM,name:O.string().min(1).optional(),provider:O.string().min(1).optional(),accountId:O.string().min(1).optional(),machineId:O.string().min(1).optional(),capabilities:O.array(O.string().min(1)).default([])}).strict(),V4=O.object({kind:GM,id:O.string().min(1),name:O.string().min(1).optional(),provider:O.string().min(1).optional(),accountId:O.string().min(1).optional(),machineId:O.string().min(1).optional()}).strict(),YM=O.enum(["task","project","repo","run","loop","workflow","action","event","integration","session","machine","model","tool","file","document","url","artifact","knowledge","email","conversation","dashboard","render","panel","report","commit","branch","pull_request","issue","comment","verification","finding","context_pack","proof_bundle","memento","eval","budget","cost","alert","incident","app","release","rollout","announcement","audience","feedback","unknown"]),ci=$_(s.resourceRef).extend({kind:YM,name:O.string().min(1).optional(),uri:t6.optional(),externalId:K$.optional(),sourcePackage:K$.optional(),tags:yW}).strict().superRefine(($,_)=>{if(!$.uri&&!($.externalId&&$.sourcePackage))_.addIssue({code:O.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),T$=O.object({kind:YM,id:O.string().min(1),name:O.string().min(1).optional(),uri:t6.optional(),externalId:K$.optional(),sourcePackage:K$.optional(),tags:yW}).strict().superRefine(($,_)=>{if(!$.uri&&Boolean($.externalId)!==Boolean($.sourcePackage))_.addIssue({code:O.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:$.externalId?["sourcePackage"]:["externalId"]})}),XB=O.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),ii=O.enum(["none","partial","full","unknown"]),li=$_(s.evidenceRef).extend({kind:XB,uri:t6,sha256:UM.optional(),summary:O.string().min(1).optional(),contentType:O.string().min(1).optional(),sizeBytes:O.number().int().nonnegative().optional(),redaction:ii.default("unknown"),producer:V4.optional(),resourceRefs:O.array(T$).default([]),tags:yW}).strict(),q_=O.object({id:O.string().min(1),kind:XB.optional(),uri:t6.optional(),sha256:UM.optional(),summary:O.string().min(1).optional()}).strict(),U9=$_(s.costEstimate).extend({currency:O.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:O.number().int().nonnegative(),provider:O.string().min(1).optional(),model:O.string().min(1).optional(),accountId:O.string().min(1).optional(),promptTokens:O.number().int().nonnegative().optional(),completionTokens:O.number().int().nonnegative().optional(),totalTokens:O.number().int().nonnegative().optional(),basis:O.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if($.promptTokens!==void 0&&$.completionTokens!==void 0&&$.totalTokens!==void 0&&$.totalTokens!==$.promptTokens+$.completionTokens)_.addIssue({code:O.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),ri=O.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),QM=$_(s.decisionEnvelope).extend({decisionType:O.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:ri,actor:V4.optional(),traceId:O.string().min(1).optional(),inputHash:XM.optional(),policyBundleId:O.string().min(1).optional(),selected:O.array(T$).default([]),skipped:O.array(T$).default([]),reason:O.string().min(1),obligations:O.array(O.string().min(1)).default([]),redactions:O.array(O.string().min(1)).default([]),costEstimate:U9.optional(),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.status==="selected"&&$.selected.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if($.status==="skipped"&&$.skipped.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if($.status==="denied"){if($.selected.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!$.policyBundleId&&$.evidenceRefs.length===0&&$.obligations.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if($.status==="approval_required"&&$.obligations.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),pi=$_(s.capabilityCard).extend({kind:O.enum(["model","tool","machine","agent","lane","connector","service"]),name:O.string().min(1),version:O.string().min(1).optional(),status:O.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:O.array(O.string().min(1)).default([]),limitations:O.array(O.string().min(1)).default([]),riskLevel:O.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:U9.optional(),evidenceRefs:O.array(q_).default([])}).strict(),ZW=O.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),oi=O.enum(["none","read_only","external_notification","external_mutation","money_movement","dns_or_domain_change","bulk_message_or_call","legal_or_filing","compute_or_infra_mutation","irreversible"]),ti=O.object({refName:K$,requiredForModes:O.array(ZW).min(1),allowedSecretInputs:O.array(O.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:K$,revocationCheck:O.boolean().default(!0)}).strict(),ai=O.object({operation:K$,supportedModes:O.array(ZW).min(1),sideEffectClass:oi,requiresApproval:O.boolean().default(!1),requiresIdempotencyKey:O.boolean().default(!1),requiresSandboxEvidence:O.boolean().default(!1),requiresRollbackOrRevocation:O.boolean().default(!1),rollbackOrRevocation:K$.optional(),noSideEffectSmoke:K$.optional(),reconciliation:K$.optional()}).strict().superRefine(($,_)=>{if($.supportedModes.includes("live_mutating")){if($.sideEffectClass==="none"||$.sideEffectClass==="read_only")_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!$.requiresApproval)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!$.requiresIdempotencyKey)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!$.requiresSandboxEvidence)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!$.requiresRollbackOrRevocation||!$.rollbackOrRevocation)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!$.reconciliation)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),si=O.object({providerId:K$,appId:K$,adapterId:K$,ownerPackage:K$,modes:O.array(ZW).min(1),defaultMode:ZW,credentialRequirements:O.array(ti).default([]),operations:O.array(ai).min(1),rateLimitPosture:K$,costPosture:K$.optional(),auditEvents:O.array(K$).default([]),redactionRules:O.array(K$).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if(!$.modes.includes($.defaultMode))_.addIssue({code:O.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let J=new Set($.operations.flatMap((U)=>U.supportedModes));for(let U of J)if(!$.modes.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`operation mode ${U} is not declared in provider modes`,path:["operations"]});if(J.has("live_mutating")){if(!$.credentialRequirements.some((W)=>W.requiredForModes.includes("live_mutating")))_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if($.auditEvents.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),ei=O.object({appId:K$,repo:K$,priority:O.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:O.array(K$).min(1),firstOperations:O.array(K$).min(1),blockedUntil:O.array(K$).default([])}).strict(),$l=$_(s.providerLiveModeStandard).extend({name:K$,version:K$,modes:O.array(ZW).refine(($)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every((_)=>$.includes(_)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:O.array(K$).min(1),liveMutationGate:O.object({requiredMode:O.literal("live_mutating"),requiredChecks:O.array(K$).min(1),forbiddenBypassSignals:O.array(K$).min(1),disabledLiveSmoke:K$}).strict(),noSideEffectSmoke:O.object({requiredForModes:O.array(ZW).min(1),commandEvidence:O.array(K$).min(1),secretOutputScan:O.boolean().default(!0)}).strict(),credentialPolicy:O.object({acceptedInputs:O.array(O.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:O.literal(!1),missingCredentialBehavior:O.literal("fail_closed"),revocationCheckRequired:O.boolean().default(!0)}).strict(),operationCards:O.array(si).min(1),firstAdoptionTargets:O.array(ei).min(1),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=new Set($.firstAdoptionTargets.map((W)=>W.appId)),U=new Set($.operationCards.map((W)=>W.appId));for(let W of J)if(!U.has(W))_.addIssue({code:O.ZodIssueCode.custom,message:`first adoption target ${W} requires a provider capability card`,path:["firstAdoptionTargets"]})}),_l=O.object({id:O.string().min(1),title:O.string().min(1).optional(),summary:O.string().min(1),text:O.string().optional(),tokens:O.number().int().nonnegative().optional(),source:q_,resourceRefs:O.array(T$).default([])}).strict(),qM=$_(s.contextPack).extend({objective:O.string().min(1),budget:O.object({maxTokens:O.number().int().positive().optional(),maxBytes:O.number().int().positive().optional()}).strict().optional(),items:O.array(_l).default([]),citations:O.array(q_).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),permissions:O.array(O.string().min(1)).default([]),redactions:O.array(O.string().min(1)).default([]),conflicts:O.array(O.string().min(1)).default([]),uncertainty:O.string().min(1).optional()}).strict(),i6=K$.refine(($)=>!$.startsWith("/")&&!$.includes("\\")&&!$.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),V2=O.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),Jl=O.enum(["public","internal","private","sensitive"]),Wl=O.enum(["draft","active","paused","archived"]),GB=O.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),zM=$_(s.integrationRef).extend({kind:GB,name:O.string().min(1),projectId:V2.optional(),sourcePackage:K$.optional(),externalId:K$.optional(),uri:t6.optional(),enabled:O.boolean().default(!0),readOnly:O.boolean().default(!0),capabilities:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:T$.optional(),evidenceRefs:O.array(q_).default([]),config:W0.optional()}).strict().superRefine(($,_)=>{if(!$.uri&&!($.sourcePackage&&$.externalId)&&!$.resourceRef)_.addIssue({code:O.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),Ul=O.object({schemaRoot:i6.default(".hasna/project"),dashboardManifest:i6.default(".hasna/project/dashboard.render.json"),snapshotsDir:i6.default(".hasna/project/snapshots"),documentsDir:i6.default("documents"),reportsDir:i6.default("reports"),evidenceDir:i6.default(".hasna/project/evidence"),privateDir:i6.default(".hasna/project/private")}).strict(),Xl=$_(s.projectManifest).extend({projectId:V2,slug:V2,name:O.string().min(1),summary:O.string().min(1).optional(),status:Wl.default("active"),classification:Jl.default("private"),owner:V4.optional(),layout:Ul.default({}),integrations:O.array(zM).default([]),renderManifests:O.array(T$).default([]),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),tags:yW}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.projectId!==$.slug)_.addIssue({code:O.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[W,X]of $.integrations.entries()){if(J.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",W,"id"]});if(J.add(X.id),X.projectId&&X.projectId!==$.projectId)_.addIssue({code:O.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",W,"projectId"]})}for(let[W,X]of $.renderManifests.entries()){if(X.kind!=="render")_.addIssue({code:O.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",W,"kind"]});if(U.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",W,"id"]});U.add(X.id)}}),Gl=O.enum(["local","package","provider","url"]),YB=O.object({id:O.string().min(1),kind:Gl,specifier:O.string().min(1),path:i6.optional(),packageName:O.string().min(1).optional(),uri:t6.optional(),provider:GB.optional(),schemaId:WM.optional(),integrity:XM.optional(),resourceRef:T$.optional(),optional:O.boolean().default(!1)}).strict().superRefine(($,_)=>{if($.kind==="local"&&!$.path)_.addIssue({code:O.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if($.kind==="package"&&!$.packageName)_.addIssue({code:O.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if($.kind==="provider"&&!$.provider)_.addIssue({code:O.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if($.kind==="url"&&!$.uri)_.addIssue({code:O.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),Yl=O.enum(["dashboard","canvas","panel","report","document","custom"]),Ql=O.object({id:O.string().min(1),title:O.string().min(1),kind:Yl,default:O.boolean().default(!1),entry:i6.optional(),imports:O.array(YB).default([]),panelRefs:O.array(T$).default([]),dataRefs:O.array(T$).default([]),layout:W0.optional()}).strict(),ql=$_(s.renderManifest).extend({projectId:V2,name:O.string().min(1),version:O.string().min(1),manifestPath:i6.default(".hasna/project/dashboard.render.json"),renderer:O.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:O.array(Ql).min(1),imports:O.array(YB).default([]),theme:W0.optional(),compatibility:O.object({minProjectsVersion:O.string().min(1).optional(),minContractsVersion:O.string().min(1).optional()}).strict().optional(),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=$.views.filter((X)=>X.default),U=new Set,W=new Set;if(J.length>1)_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[X,G]of $.imports.entries()){if(W.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",X,"id"]});W.add(G.id)}for(let[X,G]of $.views.entries()){if(U.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",X,"id"]});U.add(G.id);let Y=new Set;for(let[Q,q]of G.imports.entries()){if(Y.has(q.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",X,"imports",Q,"id"]});Y.add(q.id)}for(let[Q,q]of G.panelRefs.entries())if(q.kind!=="panel")_.addIssue({code:O.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",X,"panelRefs",Q,"kind"]})}}),zl=O.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),jl=O.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),Dl=O.object({id:O.string().min(1),label:O.string().min(1),value:O.union([O.string(),O.number(),O.boolean()]),unit:O.string().min(1).optional(),status:O.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:O.array(T$).default([])}).strict(),Ol=O.object({id:O.string().min(1),title:O.string().min(1),summary:O.string().min(1).optional(),status:O.string().min(1).optional(),priority:O.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:j6.optional(),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),metadata:W0.optional()}).strict(),Ll=O.object({renderer:O.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:O.string().min(1).optional(),entry:i6.optional(),imports:O.array(YB).default([]),spec:W0.default({})}).strict(),jM=$_(s.projectPanel).extend({projectId:V2,provider:O.object({kind:GB,id:O.string().min(1),name:O.string().min(1).optional(),sourcePackage:K$.optional(),externalId:K$.optional()}).strict(),kind:jl,title:O.string().min(1),summary:O.string().min(1).optional(),state:zl.default("ready"),stateReason:O.string().min(1).optional(),generatedAt:j6,freshness:O.enum(["fresh","stale","unknown"]).default("unknown"),metrics:O.array(Dl).default([]),items:O.array(Ol).default([]),actions:O.array(T$).default([]),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),renderFragment:Ll.optional(),warnings:O.array(O.string().min(1)).default([])}).strict().superRefine(($,_)=>{let J=new Set(["error","auth_required","unavailable","stale"]),U=new Set,W=new Set;if(J.has($.state)&&!$.stateReason)_.addIssue({code:O.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if($.state==="ready"&&$.metrics.length===0&&$.items.length===0&&!$.renderFragment)_.addIssue({code:O.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[X,G]of $.metrics.entries()){if(U.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",X,"id"]});U.add(G.id)}for(let[X,G]of $.items.entries()){if(W.has(G.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",X,"id"]});W.add(G.id)}for(let[X,G]of $.actions.entries())if(G.kind!=="action")_.addIssue({code:O.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",X,"kind"]})}),Bl=$_(s.projectSnapshot).extend({projectId:V2,generatedAt:j6,status:R2.default("unknown"),manifestRef:T$,renderManifestRef:T$.optional(),panels:O.array(jM).default([]),contextPacks:O.array(qM).default([]),proofBundleRefs:O.array(T$).default([]),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),warnings:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{let J=new Set,U=new Set;if($.manifestRef.kind!=="project")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if($.renderManifestRef&&$.renderManifestRef.kind!=="render")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[W,X]of $.proofBundleRefs.entries())if(X.kind!=="proof_bundle")_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",W,"kind"]});for(let[W,X]of $.panels.entries()){if(X.projectId!==$.projectId)_.addIssue({code:O.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",W,"projectId"]});if(J.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",W,"id"]});J.add(X.id)}for(let[W,X]of $.contextPacks.entries()){if(U.has(X.id))_.addIssue({code:O.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",W,"id"]});U.add(X.id)}}),DM=O.object({id:O.string().min(1),kind:O.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:O.boolean().default(!0),command:O.string().min(1).optional(),expected:O.string().min(1).optional(),timeoutMs:O.number().int().positive().optional(),resourceRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has($.kind)&&!$.command&&!$.expected)_.addIssue({code:O.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),Hl=$_(s.validationPlan).extend({objective:O.string().min(1),subject:T$.optional(),checks:O.array(DM).min(1),verifier:V4.optional(),requiredEvidenceKinds:O.array(XB).default([])}).strict(),Nl=O.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),Vl=O.enum(["draft","active","deprecated","archived"]),Rl=O.enum(["cli","mcp","library","sdk","rest_api","dashboard","database","auth","billing","worker","daemon","native","browser_extension","ai_provider","media_pipeline","data_pipeline","tests","ci","deployment","docs","other"]),Kl=O.object({key:O.string().regex(/^[A-Z][A-Z0-9_]*$/),description:O.string().min(1),required:O.boolean().default(!1),["secret"]:O.boolean().default(!1),group:O.string().min(1).optional(),default:O.string().optional()}).strict().superRefine(($,_)=>{if($.secret&&$.default!==void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),Fl=O.object({name:O.string().min(1),command:O.string().min(1),description:O.string().min(1).optional(),required:O.boolean().default(!1)}).strict(),El=O.object({packageManager:O.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:O.array(O.string().min(1)).default([]),requiredFiles:O.array(O.string().min(1)).default([]),requiredDirectories:O.array(O.string().min(1)).default([]),optionalDirectories:O.array(O.string().min(1)).default([])}).strict(),Ml=$_(s.scaffoldManifest).extend({name:O.string().min(1),version:O.string().min(1),summary:O.string().min(1),type:Nl,status:Vl.default("draft"),capabilities:O.array(Rl).default([]),techStack:O.array(O.string().min(1)).default([]),tags:yW,source:T$.optional(),output:El,env:O.array(Kl).default([]),scripts:O.array(Fl).default([]),validationChecks:O.array(DM).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.source?.uri?.startsWith("file://"))_.addIssue({code:O.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if($.status==="active"&&$.validationChecks.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if($.status==="active"&&$.output.requiredFiles.length===0&&$.output.requiredDirectories.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),Al=O.enum(["installed","failed","cancelled","partial","unknown"]),bl=$_(s.scaffoldInstallRecord).extend({scaffoldId:O.string().min(1),scaffoldVersion:O.string().min(1).optional(),manifestRef:T$.optional(),target:T$,status:Al,installedAt:j6.optional(),installer:V4.optional(),packageManager:O.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:W0.optional(),generatedFiles:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),proofBundleRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if($.status==="installed"&&!$.installedAt)_.addIssue({code:O.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if($.status==="installed"&&$.generatedFiles.length===0&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Installed scaffold records require generated files, evidence, or proof bundle refs",path:["generatedFiles"]});if(($.status==="failed"||$.status==="partial")&&$.evidenceRefs.length===0&&$.proofBundleRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),vW=O.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),QB=O.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),OM=O.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,"Must be a semver version"),wl=O.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),gl=K$.refine(($)=>$.startsWith("https://github.com/")||$.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),kl=O.enum(["active","stub","deprecated","archived"]),Il=O.enum(["stable","beta","canary","internal"]),fl=O.object({transport:O.enum(["http","stdio"]).default("http"),bin:O.string().min(1).optional(),url:t6.optional()}).strict(),Cl=O.object({healthPath:O.string().min(1).default("/health"),port:O.number().int().positive().optional(),baseUrl:t6.optional()}).strict(),Pl=O.object({bins:O.array(O.string().min(1)).default([]),mcp:fl.optional(),http:Cl.optional()}).strict(),Tl=$_(s.app).extend({appId:vW,npmName:QB,repoFolder:vW,githubUrl:gl,projectSlug:V2,surfaces:Pl.default({}),lifecycle:kl,releaseChannel:Il.default("stable"),summary:O.string().min(1).optional(),tags:yW}).strict().superRefine(($,_)=>{let J=new Set;for(let[U,W]of $.surfaces.bins.entries()){if(J.has(W))_.addIssue({code:O.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",U]});J.add(W)}}),Sl=O.enum(["skill","ci","backfilled"]),Zl=$_(s.release).extend({appId:vW,package:QB,version:OM,gitSha:wl,publishedAt:j6,publishPath:Sl,changelogRef:T$.optional(),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.publishPath!=="backfilled"&&$.evidenceRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),vl=O.enum(["install","update","rollback","freeze-blocked"]),yl=O.object({cliVersion:O.string().min(1).optional(),mcpHealth:O.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine(($,_)=>{if(!$.cliVersion&&$.mcpHealth===void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),hl=$_(s.rolloutRecord).extend({appId:vW,package:QB,version:OM,machine:K$,action:vl,result:R2,verifiedBy:yl.optional(),at:j6,evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.action==="freeze-blocked"&&$.result!=="blocked"&&$.result!=="skipped")_.addIssue({code:O.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let J=Boolean($.verifiedBy?.cliVersion)||$.verifiedBy?.mcpHealth!==void 0&&$.verifiedBy.mcpHealth!=="not_checked",U=$.verifiedBy?Object.keys($.verifiedBy).length>0:!1;if(($.action==="install"||$.action==="update")&&$.result==="succeeded"&&(!$.verifiedBy||U&&!J))_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),ml=O.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),xl=O.enum(["pending","queued","sent","failed","skipped","suppressed"]),ul=O.object({channel:ml,status:xl,deliveredAt:j6.optional(),detail:O.string().min(1).optional()}).strict().superRefine(($,_)=>{if($.status==="sent"&&!$.deliveredAt)_.addIssue({code:O.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if($.status==="failed"&&!$.detail)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),dl=$_(s.announcement).extend({campaignId:K$,appId:vW.optional(),releaseRef:T$.optional(),channels:O.array(ul).min(1),audienceRef:T$,sentAt:j6}).strict().superRefine(($,_)=>{if($.releaseRef&&$.releaseRef.kind!=="release")_.addIssue({code:O.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if($.audienceRef.kind!=="audience")_.addIssue({code:O.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),nl=O.enum(["tag","attribute","group"]),cl=O.enum(["eq","neq","in","not_in","exists","not_exists"]),iE=O.union([O.string(),O.number(),O.boolean()]),il=O.object({kind:nl,key:O.string().min(1).optional(),op:cl.default("eq"),value:iE.optional(),values:O.array(iE).default([])}).strict().superRefine(($,_)=>{if($.kind==="attribute"&&!$.key)_.addIssue({code:O.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if(($.op==="eq"||$.op==="neq")&&$.value===void 0)_.addIssue({code:O.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if(($.op==="in"||$.op==="not_in")&&$.values.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),ll=O.object({match:O.enum(["all","any"]).default("all"),predicates:O.array(il).min(1)}).strict(),rl=O.enum(["opt_in","opt_out","transactional","none"]),pl=$_(s.audience).extend({audienceId:vW,name:K$,definition:ll,consentPolicy:rl,suppressionSyncedAt:N2}).strict(),eL=["@hasna/cloud","open-cloud"],ol=O.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),tl=O.object({id:O.string().min(1),provider:ol,kind:O.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:O.string().min(1),region:O.string().min(1).optional(),accountId:O.string().min(1).optional(),uri:t6.optional(),machineScoped:O.boolean().default(!1)}).strict(),LM=$_(s.appCloudManifest).extend({packageName:O.string().min(1),packageVersion:O.string().min(1).optional(),appId:O.string().min(1),repository:T$.optional(),storageMode:O.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:O.enum(["none","app_owned","external_service","local_cache"]),cloudResources:O.array(tl).default([]),localCache:O.object({path:O.string().min(1).optional(),pullMode:O.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:O.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:O.array(O.string().min(1)).default([...eL]),dependencies:O.array(O.string().min(1)).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=new Set([...eL,...$.forbiddenSharedRuntimes]);if(J.has($.packageName))_.addIssue({code:O.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let U of eL)if(!$.forbiddenSharedRuntimes.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${U}`,path:["forbiddenSharedRuntimes"]});for(let U of J)if($.dependencies.includes(U))_.addIssue({code:O.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${U}`,path:["dependencies"]});if($.storageMode==="local_only"&&$.cloudBoundary!=="none")_.addIssue({code:O.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if($.storageMode==="app_owned_cloud"&&$.cloudBoundary!=="app_owned")_.addIssue({code:O.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if($.storageMode==="hybrid_local_cache"){if($.cloudBoundary!=="local_cache")_.addIssue({code:O.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!$.localCache)_.addIssue({code:O.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if($.storageMode==="external_service"){if($.cloudBoundary!=="external_service")_.addIssue({code:O.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if($.cloudResources.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"external_service storage must not declare app-owned cloudResources",path:["cloudResources"]})}if(($.storageMode==="app_owned_cloud"||$.storageMode==="hybrid_local_cache")&&$.cloudResources.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if($.cloudBoundary==="none"&&$.cloudResources.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});$.cloudResources.forEach((U,W)=>{if(U.ownerPackage!==$.packageName)_.addIssue({code:O.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",W,"ownerPackage"]})})}),BM=O.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),al=O.enum(["low","medium","high","critical"]),HM=O.object({id:O.string().min(1),kind:BM,severity:al,path:O.string().min(1).optional(),packageName:O.string().min(1).optional(),pattern:O.string().min(1),message:O.string().min(1),evidenceRefs:O.array(q_).default([])}).strict(),sl=O.object({id:O.string().min(1),kind:BM,status:R2,target:O.string().min(1),command:O.string().min(1).optional(),evidenceRefs:O.array(q_).default([]),findings:O.array(HM).default([])}).strict(),el=$_(s.noCloudEvidencePack).extend({subject:T$,packageName:O.string().min(1).optional(),packageVersion:O.string().min(1).optional(),generatedBy:V4.optional(),scanMode:O.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:R2,verdict:O.enum(["passed","failed","warning","not_run"]),appCloudManifest:LM.optional(),checks:O.array(sl).min(1),findings:O.array(HM).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{let J=[...$.findings,...$.checks.flatMap((W)=>W.findings)],U=J.filter((W)=>W.severity==="high"||W.severity==="critical");if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(U.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if($.checks.some((W)=>W.status!=="succeeded"))_.addIssue({code:O.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if($.verdict==="failed"&&J.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if($.status==="succeeded"&&$.checks.some((W)=>W.status==="failed"))_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});$.checks.forEach((W,X)=>{let G=W.findings.filter((Y)=>Y.severity==="high"||Y.severity==="critical");if(W.status==="succeeded"&&G.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",X,"findings"]})})}),$r=O.object({checkId:O.string().min(1),status:R2,summary:O.string().min(1).optional(),startedAt:N2,finishedAt:N2,evidenceRefs:O.array(q_).default([])}).strict(),_r=$_(s.proofBundle).extend({subject:T$,validationPlanRef:T$.optional(),status:R2,verdict:O.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:O.array($r).default([]),verifier:V4.optional(),evidenceRefs:O.array(q_).default([]),residualRisks:O.array(O.string().min(1)).default([]),freshness:O.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine(($,_)=>{if($.verdict==="passed"){if($.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if($.checks.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if($.checks.forEach((U,W)=>{if(U.status!=="succeeded")_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",W,"status"]})}),!($.evidenceRefs.length>0||$.checks.some((U)=>U.evidenceRefs.length>0)))_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!$.verifier)_.addIssue({code:O.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if($.verdict==="not_run"&&$.checks.length>0)_.addIssue({code:O.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if($.verdict==="failed"&&!$.checks.some((J)=>J.status==="failed")&&$.evidenceRefs.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),Jr=$_(s.workRun).extend({objective:O.string().min(1),status:R2,actor:V4,traceId:O.string().min(1).optional(),startedAt:N2,finishedAt:N2,constraints:O.array(O.string().min(1)).default([]),resourceRefs:O.array(T$).default([]),decisions:O.array(QM).default([]),costEstimates:O.array(U9).default([]),evidenceRefs:O.array(q_).default([]),validationPlanRefs:O.array(T$).default([]),proofBundleRefs:O.array(T$).default([])}).strict().superRefine(($,_)=>{if($.startedAt&&$.finishedAt&&Date.parse($.finishedAt)0||$.proofBundleRefs.length>0;if($.status==="succeeded"&&!J)_.addIssue({code:O.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if(($.status==="failed"||$.status==="blocked")&&!J&&$.decisions.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),Wr=O.object({id:O.string().min(1),at:j6,kind:O.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:O.string().min(1),resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([]),costEstimate:U9.optional()}).strict(),Ur=$_(s.agentTrajectory).extend({actor:V4,workRunRef:T$.optional(),events:O.array(Wr).default([]),outcome:O.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:T$.optional()}).strict(),Xr="v1",Gr=O.enum(["library","cli-with-store","service","saas"]),Yr=["local","self-hosted","cloud"],NM=O.enum(Yr),Qr=O.enum(["supported","deferred","unsupported"]),qr=O.enum(["none","local-only","api-key","session","service-token","custom"]),$B=O.object({method:O.enum(["GET","POST","PUT","PATCH","DELETE"]),path:O.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:O.boolean().default(!1),description:O.string().min(1).optional()}).strict(),zr=O.object({id:O.string().min(1),kind:O.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:O.boolean().default(!0),command:O.string().min(1).optional(),evidenceRef:q_.optional(),status:O.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:O.string().min(1).optional()}).strict().superRefine(($,_)=>{if(($.status==="passed"||$.status==="failed"||$.status==="blocked")&&!$.command&&!$.evidenceRef&&!$.summary)_.addIssue({code:O.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),jr=O.object({name:O.string().min(1),status:Qr,bin:O.string().min(1).optional(),mcpBin:O.string().min(1).optional(),authMode:qr,deploymentModes:O.array(NM).min(1),health:$B.optional(),readiness:$B.optional(),version:$B.optional(),apiBasePath:O.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:O.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),deferReason:O.string().min(1).optional(),readinessGates:O.array(zr).default([])}).strict().superRefine(($,_)=>{if($.status==="supported"){if(!$.bin)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a serve bin",path:["bin"]});if(!$.health)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a health endpoint",path:["health"]});if(!$.version)_.addIssue({code:O.ZodIssueCode.custom,message:"Supported service surfaces require a version endpoint",path:["version"]})}if(($.status==="deferred"||$.status==="unsupported")&&!$.deferReason)_.addIssue({code:O.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if($.health&&$.health.path!=="/health")_.addIssue({code:O.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if($.readiness&&$.readiness.path!=="/ready")_.addIssue({code:O.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if($.version&&$.version.path!=="/version")_.addIssue({code:O.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]})}),Dr=["local","cloud"],VM=O.enum(Dr);var Or=O.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),Lr=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function Br($){return Lr.map((_)=>`${$}${_}`)}function lE($){return`hasna/oss/${$}/database-url`}var Hr=O.object({mode:VM,envPrefix:O.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:O.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:O.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:O.string().min(1).optional()}).strict(),Nr=O.object({$schema:O.string().min(1).optional(),schema:O.literal(s.serviceContract),name:Or,class:Gr,contractVersion:O.literal(Xr),kitVersion:O.string().min(1),description:O.string().min(1).optional(),bins:O.array(O.string().min(1)).default([]),storage:Hr.optional(),deploymentModes:O.array(NM).default(["local"]),serviceSurfaces:O.array(jr).default([]),metadata:W0.optional()}).strict().superRefine(($,_)=>{let J=new Set(Br($.name)),U=new Set;for(let[X,G]of $.bins.entries()){if(U.has(G))_.addIssue({code:O.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",X]});if(U.add(G),!J.has(G))_.addIssue({code:O.ZodIssueCode.custom,message:`Bin "${G}" is not allowlisted for app "${$.name}"; allowed: ${[...J].join(", ")}`,path:["bins",X]})}let W=(X)=>U.has(`${$.name}${X}`);if($.storage){let X=$.name.toUpperCase().replace(/-/g,"_");if($.storage.envPrefix&&$.storage.envPrefix!==`HASNA_${X}_`)_.addIssue({code:O.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${X}_`,path:["storage","envPrefix"]});if($.storage.databaseUrlSecretRef&&$.storage.databaseUrlSecretRef!==lE($.name))_.addIssue({code:O.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${lE($.name)}`,path:["storage","databaseUrlSecretRef"]});if($.storage.mode==="cloud"&&!$.storage.databaseUrlSecretRef)_.addIssue({code:O.ZodIssueCode.custom,message:"cloud storage requires a databaseUrlSecretRef (PURE REMOTE: reads and writes go to cloud Postgres)",path:["storage","databaseUrlSecretRef"]})}if($.class==="library"){if($.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(W("-serve")||W("-mcp"))_.addIssue({code:O.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if($.class==="cli-with-store"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else if($.storage.mode==="local"&&!$.storage.sqlitePath)_.addIssue({code:O.ZodIssueCode.custom,message:"local cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(!U.has($.name))_.addIssue({code:O.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${$.name}" bin`,path:["bins"]})}if($.class==="service"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});if(!W("-serve"))_.addIssue({code:O.ZodIssueCode.custom,message:`service repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if($.class==="saas"){if(!$.storage)_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else if($.storage.mode!=="cloud")_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must use cloud storage mode",path:["storage","mode"]});if(!W("-serve"))_.addIssue({code:O.ZodIssueCode.custom,message:`saas repos must ship the "${$.name}-serve" bin`,path:["bins"]});if($.serviceSurfaces.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[X,G]of $.serviceSurfaces.entries()){if(G.bin&&!U.has(G.bin))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface bin "${G.bin}" must be declared in bins`,path:["serviceSurfaces",X,"bin"]});if(G.mcpBin&&!U.has(G.mcpBin))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface MCP bin "${G.mcpBin}" must be declared in bins`,path:["serviceSurfaces",X,"mcpBin"]});for(let[Y,Q]of G.deploymentModes.entries())if(!$.deploymentModes.includes(Q))_.addIssue({code:O.ZodIssueCode.custom,message:`Service surface deployment mode "${Q}" must be declared in deploymentModes`,path:["serviceSurfaces",X,"deploymentModes",Y]})}}),S4$=O.object({status:O.enum(["ok","degraded","unavailable"]),version:O.string().min(1),mode:VM}).strict(),Z4$=O.object({ready:O.boolean(),reason:O.string().min(1).optional()}).strict(),v4$=O.object({version:O.string().min(1)}).strict(),Vr=O.enum(["info","notice","breaking","critical"]),Rr=O.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,"Comms event types must be 2-4 lowercase dot-separated segments (..)"),Kr=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],Fr=O.enum(Kr);var Er=O.enum(["fleet","package","machine"]),RM=$_(s.commsEventEnvelope).extend({type:Rr,severity:Vr,scope:Er,summary:O.string().min(1).optional(),source:V4.optional(),affected_packages:O.array(K$).default([]),affected_machines:O.array(K$).default([]),action_required:O.boolean().default(!1),ack_by:j6.optional(),dedupe_key:K$,resourceRefs:O.array(T$).default([]),evidenceRefs:O.array(q_).default([])}).strict().superRefine(($,_)=>{if($.scope==="package"&&$.affected_packages.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if($.scope==="machine"&&$.affected_machines.length===0)_.addIssue({code:O.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if($.ack_by&&!$.action_required)_.addIssue({code:O.ZodIssueCode.custom,message:"Comms events with an ack_by deadline require action_required",path:["action_required"]});if($.type==="fleet.freeze"||$.type==="fleet.unfreeze"){if($.severity!=="critical")_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events are always critical`,path:["severity"]});if($.scope!=="fleet")_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events are always fleet-scoped`,path:["scope"]});if(!$.action_required)_.addIssue({code:O.ZodIssueCode.custom,message:`${$.type} events require action_required`,path:["action_required"]})}}),Mr=O.enum(["fleet","package","product","loop-lane","initiative","personal"]),Ar=O.enum(["quiet","work","firehose"]),br=K$.refine(($)=>/^(?:\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?|gate:[0-9a-f][0-9a-f-]{7,35})$/.test($),"until must be an ISO date (YYYY-MM-DD), a UTC timestamp, or a gate id (gate:)"),wr=$_(s.commsChannelMetadata).extend({class:Mr,noise:Ar.optional(),owner:K$.optional(),until:br.optional(),successor:K$.optional()}).strict().superRefine(($,_)=>{if($.class==="initiative"){if(!$.owner)_.addIssue({code:O.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!$.until)_.addIssue({code:O.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),rE={FREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.freeze"},UNFREEZE:{defaultSeverity:"critical",allowedSeverities:["critical"],requiredEventType:"fleet.unfreeze"},BREAKING:{defaultSeverity:"breaking",allowedSeverities:["breaking"],requiredEventType:null},CUTOVER:{defaultSeverity:"notice",allowedSeverities:["notice","breaking"],requiredEventType:null},POLICY:{defaultSeverity:"breaking",allowedSeverities:["notice","breaking"],requiredEventType:null},RELEASE:{defaultSeverity:"info",allowedSeverities:["info","notice"],requiredEventType:null}},gr=$_(s.commsMessageMetadata).extend({tag:Fr,envelope:RM}).strict().superRefine(($,_)=>{let J=rE[$.tag];if(!J.allowedSeverities.includes($.envelope.severity))_.addIssue({code:O.ZodIssueCode.custom,message:`[${$.tag}] posts allow severities ${J.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(J.requiredEventType&&$.envelope.type!==J.requiredEventType)_.addIssue({code:O.ZodIssueCode.custom,message:`[${$.tag}] posts require event type ${J.requiredEventType}`,path:["envelope","type"]});for(let[U,W]of Object.entries(rE))if(W.requiredEventType===$.envelope.type&&$.tag!==U)_.addIssue({code:O.ZodIssueCode.custom,message:`${$.envelope.type} events must use the [${U}] tag`,path:["tag"]})});var kr={[s.actorRef]:ni,[s.resourceRef]:ci,[s.evidenceRef]:li,[s.workRun]:Jr,[s.decisionEnvelope]:QM,[s.costEstimate]:U9,[s.capabilityCard]:pi,[s.providerLiveModeStandard]:$l,[s.contextPack]:qM,[s.integrationRef]:zM,[s.projectManifest]:Xl,[s.projectPanel]:jM,[s.projectSnapshot]:Bl,[s.renderManifest]:ql,[s.agentTrajectory]:Ur,[s.validationPlan]:Hl,[s.proofBundle]:_r,[s.scaffoldManifest]:Ml,[s.scaffoldInstallRecord]:bl,[s.appCloudManifest]:LM,[s.noCloudEvidencePack]:el,[s.serviceContract]:Nr,[s.commsEventEnvelope]:RM,[s.commsChannelMetadata]:wr,[s.commsMessageMetadata]:gr,[s.app]:Tl,[s.release]:Zl,[s.rolloutRecord]:hl,[s.announcement]:dl,[s.audience]:pl};class KM extends Error{schemaId;issues;constructor($,_){super(`Contract validation failed for ${$}`);this.name="ContractValidationError",this.schemaId=$,this.issues=_}}function FM($,_){let U=kr[$].safeParse(_);if(!U.success)throw new KM($,U.error.issues);return U.data}var y4$={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://github.com/hasna/contracts/schema/hasna.service_contract.v1.json",title:"Hasna Service Contract v1",description:"Repo self-description (hasna.contract.json) for the Hasna Service Contract v1. Storage runtime enum is local|cloud ONLY per Amendment A1 (PURE REMOTE).",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:s.serviceContract},name:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$",description:"Lowercase dashed app short-name, e.g. todos, mailery, loops."},class:{enum:["library","cli-with-store","service","saas"]},contractVersion:{const:"v1"},kitVersion:{type:"string",minLength:1,description:"Version of @hasna/contracts (the contract kit) the repo tracks."},description:{type:"string",minLength:1},bins:{type:"array",items:{type:"string",minLength:1},description:"Declared bins. Allowlisted: , -cli, -mcp, -serve, -worker, -runner, -daemon, -migrate, -doctor."},deploymentModes:{type:"array",items:{enum:["local","self-hosted","cloud"]},description:"Supported deployment modes. local = this machine, self-hosted = Hasna-owned AWS, cloud = multi-tenant SaaS for outside users."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode","deploymentModes"],properties:{name:{type:"string",minLength:1},status:{enum:["supported","deferred","unsupported"]},bin:{type:"string",minLength:1},mcpBin:{type:"string",minLength:1},authMode:{enum:["none","local-only","api-key","session","service-token","custom"]},deploymentModes:{type:"array",items:{enum:["local","self-hosted","cloud"]},minItems:1},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},readiness:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},version:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{enum:["GET","POST","PUT","PATCH","DELETE"]},path:{type:"string",pattern:"^/[A-Za-z0-9_./:*-]*$"},public:{type:"boolean"},description:{type:"string",minLength:1}}},apiBasePath:{type:"string",pattern:"^/v[0-9]+$"},openApiPath:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$"},deferReason:{type:"string",minLength:1},readinessGates:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1},kind:{enum:["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]},required:{type:"boolean"},command:{type:"string",minLength:1},evidenceRef:{type:"object"},status:{enum:["pending","passed","failed","blocked","deferred"]},summary:{type:"string",minLength:1}}}}}},description:"Declared HTTP/MCP service surfaces. Supported surfaces name lifecycle endpoints; unsafe or unfinished surfaces use deferred/unsupported with a reason."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["local","cloud"],description:"Runtime storage enum. local|cloud ONLY (Amendment A1: PURE REMOTE)."},envPrefix:{type:"string",pattern:"^HASNA_[A-Z][A-Z0-9]*_$",description:"Primary env prefix, e.g. HASNA_TODOS_."},aliasEnvPrefix:{type:"string",pattern:"^[A-Z][A-Z0-9]*_$",description:"Optional short alias env prefix, e.g. TODOS_."},databaseUrlSecretRef:{type:"string",pattern:"^hasna/oss/[a-z0-9-]+/database-url$",description:"Secret Manager ref for the cloud database URL."},sqlitePath:{type:"string",minLength:1,description:"Local sqlite path (~/.hasna//.db)."}}},metadata:{type:"object"}}};var EM="@hasna/knowledge";function Ir($){if(!Number.isFinite($??0))return 20;return Math.max(1,Math.min(100,Math.trunc($??20)))}function fr($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function X9($,_=180){let J=String($??"").replace(/\s+/g," ").trim();if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-3))}...`}function M_($,_=""){return typeof $==="string"&&$.length>0?$:_}function G9($){return typeof $==="number"&&Number.isFinite($)?$:0}function hW($){if(typeof $!=="string"||$.length===0)return;let _=$.includes("T")?$:`${$.replace(" ","T")}Z`,J=new Date(_);return Number.isNaN(J.valueOf())?void 0:J.toISOString()}function XY($){return t6.safeParse($).success}function a6($,_,J,U,W=[]){return{kind:$,id:_,name:J,uri:U&&XY(U)?U:void 0,externalId:_,sourcePackage:EM,tags:W}}function Cr($){return[...$.items.flatMap((J)=>[J.updated_at,J.created_at]),...$.sources.flatMap((J)=>[J.updated_at,J.created_at]),...$.chunks.map((J)=>J.created_at),...$.wiki_pages.flatMap((J)=>[J.updated_at,J.created_at]),...$.storage_objects.flatMap((J)=>[J.updated_at,J.created_at]),...$.runs.flatMap((J)=>[J.updated_at,J.created_at]),...$.reindex_queue.flatMap((J)=>[J.updated_at,J.created_at]),...$.sync_conflicts.map((J)=>J.created_at),...$.approval_gates.flatMap((J)=>[J.updated_at,J.created_at])].map(hW).filter(Boolean).sort((J,U)=>U.localeCompare(J))[0]}function Pr($){if(!$)return"unknown";let _=Date.now()-new Date($).valueOf();if(!Number.isFinite(_))return"unknown";return _>2592000000?"stale":"fresh"}function Tr($){let _=(J)=>{let U=String(J??"").toLowerCase();return U!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(U)};return $.reindex_queue.filter((J)=>_(J.status)).length+$.sync_conflicts.filter((J)=>_(J.status)).length+$.approval_gates.filter((J)=>_(J.status)).length}function Sr($,_){let J=[];for(let U of $.items.slice(0,_))J.push({id:`item_${U.id}`,title:U.title,summary:X9(U.content_preview),status:U.archived?"archived":"active",priority:"medium",timestamp:hW(U.updated_at??U.created_at),resourceRefs:[a6("knowledge",U.id,U.title,`knowledge://item/${encodeURIComponent(U.id)}`,U.tags)],evidenceRefs:U.url&&XY(U.url)?[{id:`url_${U.id}`,kind:"url",uri:U.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:U.archived,tags:U.tags,url:U.url||void 0}});for(let U of $.sources.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,M_(U.uri,"source")),X=M_(U.title,M_(U.uri,W)),G=M_(U.uri,`knowledge://source/${encodeURIComponent(W)}`);J.push({id:`source_${W}`,title:X,summary:X9(`${G9(U.chunks)} chunk(s), ${G9(U.revisions)} revision(s)`),status:G9(U.chunks)>0?"indexed":"source",priority:"medium",timestamp:hW(U.updated_at??U.created_at),resourceRefs:[a6("document",W,X,G)],evidenceRefs:XY(G)?[{id:`source_${W}`,kind:"url",uri:G,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:U.kind,chunks:G9(U.chunks),revisions:G9(U.revisions)}})}for(let U of $.chunks.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,"chunk"),X=M_(U.source_uri);J.push({id:`chunk_${W}`,title:M_(U.wiki_title,X?`Chunk from ${X}`:`Knowledge chunk ${W}`),summary:X9(U.text_preview),status:"chunk",priority:"low",timestamp:hW(U.created_at),resourceRefs:[a6("context_pack",W,M_(U.wiki_title,W),`knowledge://chunk/${encodeURIComponent(W)}`)],evidenceRefs:X&&XY(X)?[{id:`chunk_source_${W}`,kind:"url",uri:X,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:X||void 0,token_count:U.token_count,ordinal:U.ordinal}})}for(let U of $.sync_conflicts.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,"sync_conflict");J.push({id:`sync_conflict_${W}`,title:`Sync conflict: ${M_(U.entity_kind,"entity")}/${M_(U.entity_id,W)}`,summary:X9(`Status ${M_(U.status,"unknown")}; strategy ${M_(U.resolution_strategy,"none")}.`),status:M_(U.status,"unknown"),priority:"critical",timestamp:hW(U.created_at),resourceRefs:[a6("finding",W,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(W)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:U.local_machine_id,remote_machine_id:U.remote_machine_id}})}for(let U of $.reindex_queue.slice(0,Math.max(0,_-J.length))){let W=M_(U.id,"reindex");J.push({id:`reindex_${W}`,title:`Reindex ${M_(U.kind,"item")}: ${M_(U.target_id,W)}`,summary:X9(U.reason),status:M_(U.status,"unknown"),priority:M_(U.status).toLowerCase()==="failed"?"high":"medium",timestamp:hW(U.updated_at??U.created_at),resourceRefs:[a6("action",W,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(W)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:U.attempts,source_uri:U.source_uri}})}return J.slice(0,_)}async function MM($,_={}){let J=Ir(_.limit),U=new Date().toISOString(),W=fr($),G=await(_.service??$Y({scope:_.scope??"project",cwd:_.cwd})).resolveInventory({limit:J,storePath:_.storePath,includeArchived:_.includeArchived}),Y=Cr(G),Q=Pr(Y),q=G.summary.active_items+G.summary.sources+G.summary.chunks+G.summary.wiki_pages+G.summary.storage_objects,L=Tr(G),N=q===0?"empty":Q==="stale"?"stale":"ready",R=Sr(G,J),B={schema:s.projectPanel,id:`knowledge_panel_${W}`,createdAt:U,projectId:W,provider:{kind:"knowledge",id:`knowledge_${W}`,name:"Knowledge",sourcePackage:EM,externalId:G.home},kind:"knowledge",title:"Knowledge",summary:N==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${G.summary.active_items} active note(s), ${G.summary.sources} source(s), ${G.summary.chunks} chunk(s), and ${G.summary.wiki_pages} wiki page(s).`,state:N,stateReason:N==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:U,freshness:Q,metrics:[{id:"active_items",label:"Active notes",value:G.summary.active_items,status:G.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:G.summary.sources,status:G.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:G.summary.chunks,status:G.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:G.summary.wiki_pages,status:G.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:G.summary.storage_objects,status:G.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:G.summary.vector_entries,status:G.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:L,status:L>0?"warning":"good"}],items:R,actions:[a6("action","knowledge:inventory","Inspect knowledge inventory"),a6("action","knowledge:context-pack","Build cited context pack"),a6("action","knowledge:ingest","Ingest project source")],resourceRefs:[a6("project",W,$,`project://${W}`),a6("knowledge",`home_${W}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(W)}`),a6("artifact",`db_${W}`,"Knowledge database",`knowledge://db/${encodeURIComponent(W)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:J}},metadata:{scope:G.scope,home:G.home,json_store_exists:G.paths.json_store_exists,latest_activity_at:Y}};return FM(s.projectPanel,B)}function AM($){let _=[`${$.title}: ${$.state}`,$.summary??"",...$.metrics.map((J)=>`${J.label}: ${J.value}`)].filter(Boolean);if($.items.length>0){_.push("Items:");for(let J of $.items.slice(0,10))if(_.push(`- ${J.title}${J.status?` [${J.status}]`:""}`),J.summary)_.push(` ${J.summary}`)}return _.join(` +`)}var gM=["sources","wiki_pages","source_revisions","chunks","chunk_embeddings","wiki_backlinks","citations","knowledge_indexes","runs","run_events","provider_usage","redaction_findings","storage_objects","audit_events","approval_gates","vector_index_entries","reindex_queue","knowledge_machines","knowledge_sync_snapshots","knowledge_sync_changes","knowledge_sync_conflicts","knowledge_sync_table_clocks","knowledge_sync_imports"];var Zr=["remote","hybrid","self_hosted"],kM="HASNA_KNOWLEDGE_STORAGE_MODE",IM="KNOWLEDGE_STORAGE_MODE";function bM($){return process.env[$]?.trim()||void 0}function wM($){let _=$?.trim().toLowerCase().replace(/-/g,"_");if(_==="local")return"local";if(_==="cloud")return"cloud";if(_&&Zr.includes(_))return"cloud";return}function vr($={}){let _=b2(O9($.scope,$.cwd).home);return a(_.knowledgeDbPath),{db:m(_.knowledgeDbPath),path:_.knowledgeDbPath,scope:$.scope??"global"}}function fM(){let $=wM(bM(kM))??wM(bM(IM));if($)return $;return"local"}function qB($={}){let _=vr($);try{yr(_.db);let J=_.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all();return{mode:fM(),service:"knowledge",scope:_.scope,databasePath:_.path,tables:gM,sync:J}}finally{_.db.close()}}function yr($){$.exec(` CREATE TABLE IF NOT EXISTS _knowledge_sync_meta ( table_name TEXT NOT NULL, last_synced_at TEXT, direction TEXT NOT NULL CHECK(direction IN ('push', 'pull')), PRIMARY KEY (table_name, direction) ) - `)}var wA=zb(EA(),1),{program:x0$,createCommand:u0$,createArgument:d0$,createOption:c0$,CommanderError:l0$,InvalidArgumentError:n0$,InvalidOptionArgumentError:i0$,Command:IA,Argument:r0$,Option:p0$,Help:o0$}=wA.default;import{chmod as GB,mkdir as Xp,readFile as Gp,rename as Qp,writeFile as CA}from"fs/promises";import{Buffer as mA}from"buffer";import{existsSync as xA}from"fs";import{homedir as Yp}from"os";import{join as X9}from"path";import{createHmac as Lp,timingSafeEqual as W1$}from"crypto";import{randomUUID as Np}from"crypto";import{spawn as Vp}from"child_process";import{randomUUID as bp}from"crypto";function ar($,_){return _.split(".").reduce((J,U)=>{if(J&&typeof J==="object"&&U in J)return J[U];return},$)}function sr($,_){let J=[],U=(X)=>{if(!J.some((G)=>Object.is(G,X)))J.push(X)};if(_.includes(".")&&_ in $)U($[_]);let W=ar($,_);if(W!==void 0||!_.includes("."))U(W);return J}function er($,_={}){let J="";for(let U=0;U<$.length;U+=1){let W=$[U];if(W==="*")if($[U+1]==="*")J+=".*",U+=1;else J+=_.segmentSafe?"[^/]*":".*";else J+=W.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${J}$`)}function W9($,_,J={}){if(_===void 0)return!0;if($===void 0)return!1;return(Array.isArray(_)?_:[_]).some((W)=>er(W,J).test($))}function gA($,_){if(!_)return!0;return Object.entries(_).every(([J,U])=>{let W=sr($,J);return $p(W,U,J)})}function $p($,_,J){if(Wp(_))return!$.some((U)=>kA(U,_.not,J));return $.some((U)=>kA(U,_,J))}function kA($,_,J){if(typeof _==="string"||Array.isArray(_))return _p($).some((U)=>W9(U,_,{segmentSafe:J.endsWith("_path")||J.endsWith(".path")}));if(Array.isArray($))return $.some((U)=>U===_);return $===_}function _p($){if($===void 0)return[];if(Array.isArray($))return $.flatMap((_)=>Jp(_)?[String(_)]:[]);return[String($)]}function Jp($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function Wp($){return Boolean($&&typeof $==="object"&&!Array.isArray($)&&"not"in $)}function Up($,_){return W9($.source,_.source)&&W9($.type,_.type)&&W9($.subject,_.subject)&&W9($.severity,_.severity)&&gA($.data,_.data)&&gA($.metadata,_.metadata)}function fA($,_){if(!$.enabled)return!1;if(!$.filters||$.filters.length===0)return!0;return $.filters.some((J)=>Up(_,J))}var JQ="HASNA_EVENTS_DIR",WQ="HASNA_EVENTS_HOME",zB="local-json-v1:",qp=100,zp=1000;function uA($){return $||process.env[JQ]||process.env[WQ]||X9(Yp(),".hasna","events")}function jp(){if(process.env[JQ])return JQ;if(process.env[WQ])return WQ;return null}class UQ{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor($=uA()){this.dataDir=$,this.runtime=Op($),this.channelsPath=X9($,"channels.json"),this.eventsPath=X9($,"events.json"),this.deliveriesPath=X9($,"deliveries.json")}async init(){await Xp(this.dataDir,{recursive:!0,mode:448}),await GB(this.dataDir,448).catch(()=>{return}),await this.ensureArrayFile(this.channelsPath),await this.ensureArrayFile(this.eventsPath),await this.ensureArrayFile(this.deliveriesPath)}async addChannel($){await this.init();let _=await this.readJson(this.channelsPath,[]),J=_.findIndex((U)=>U.id===$.id);if(J>=0)_[J]={...$,createdAt:_[J].createdAt,updatedAt:new Date().toISOString()};else _.push($);return await this.writeJson(this.channelsPath,_),J>=0?_[J]:$}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel($){return(await this.listChannels()).find((J)=>J.id===$)}async removeChannel($){await this.init();let _=await this.readJson(this.channelsPath,[]),J=_.filter((U)=>U.id!==$);return await this.writeJson(this.channelsPath,J),J.length!==_.length}async appendEvent($){await this.init();let _=await this.readJson(this.eventsPath,[]);return _.push($),await this.writeJson(this.eventsPath,_),$}async appendEventOnce($,_={}){await this.init();let J=await this.readJson(this.eventsPath,[]);if(_.dedupe!==!1){let W=TA(J,{id:$.id,dedupeKey:$.dedupeKey});if(W)return{event:W,stored:!1,deduped:!0,identity:{id:W.id,dedupeKey:W.dedupeKey}}}return J.push($),await this.writeJson(this.eventsPath,J),{event:$,stored:!0,deduped:!1,identity:{id:$.id,dedupeKey:$.dedupeKey}}}async listEvents($={}){await this.init();let _=await this.readJson(this.eventsPath,[]);return PA(_,$)}async listEventsPage($={}){await this.init();let _=await this.readJson(this.eventsPath,[]),J=PA(_,{eventId:$.eventId,source:$.source,type:$.type}),U=XQ($.cursor,$),W=GQ($.limit),X=J.slice(U,U+W),G=U+X.length,Q=G{return})}async readJson($,_){try{let J=await Gp($,"utf-8");if(!J.trim())return _;return JSON.parse(J)}catch(J){if(J.code==="ENOENT")return _;throw J}}async writeJson($,_){let J=`${$}.${process.pid}.${Date.now()}.tmp`;await CA(J,`${JSON.stringify(_,null,2)} -`,{encoding:"utf-8",mode:384}),await Qp(J,$),await GB($,384).catch(()=>{return})}}function Op($=uA()){return{mode:"local-files",name:"json-events-store",remote:!1,localFiles:!0,localSqlite:!1,postgres:!1,s3:!1,aws:!1,durable:!0,idempotency:"best-effort-local",replayCursors:!0,description:`Local JSON files in ${$}; no SQLite, Postgres, S3, or AWS runtime is configured by this store.`}}function dA($,_={}){if(!Number.isInteger($)||$<0)throw Error(`Invalid event cursor offset: ${$}`);let J={offset:$,eventId:_.eventId,source:_.source,type:_.type};return`${zB}${mA.from(JSON.stringify(J),"utf-8").toString("base64url")}`}function XQ($,_={}){if(!$)return 0;if(!$.startsWith(zB))throw Error(`Invalid local JSON event cursor: ${$}`);let J=$.slice(zB.length),U;try{U=JSON.parse(mA.from(J,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${$}`)}let W=U.offset;if(!Number.isInteger(W)||W<0)throw Error(`Invalid local JSON event cursor: ${$}`);return QB("eventId",U.eventId,_.eventId),QB("source",U.source,_.source),QB("type",U.type,_.type),W}function GQ($){if($===void 0)return qp;if(!Number.isInteger($)||$<1)throw Error(`Event page limit must be a positive integer, got ${$}`);return Math.min($,zp)}function PA($,_){let J=$;if(_.eventId)J=J.filter((U)=>U.id===_.eventId);if(_.source)J=J.filter((U)=>U.source===_.source);if(_.type)J=J.filter((U)=>U.type===_.type);if(_.cursor){let U=XQ(_.cursor,_);J=J.slice(U)}if(_.limit!==void 0)J=J.slice(0,GQ(_.limit));return J}function QB($,_,J){if(_!==J)throw Error(`Local JSON event cursor ${$} filter mismatch`)}function TA($,_){return $.find((J)=>_.id!==void 0&&J.id===_.id||_.dedupeKey!==void 0&&J.dedupeKey===_.dedupeKey)}async function Dp($){let _=new UQ($);await _.init();let[J,U,W]=await Promise.all([_.listChannels(),_.listEvents(),_.listDeliveries()]),X=J.reduce((G,Q)=>{return G[Q.transport]=(G[Q.transport]??0)+1,G},{});return{service:"events",schemaVersion:"1.0",dataDir:_.dataDir,storage:_.runtime,env:{primary:JQ,fallback:WQ,active:jp()},files:{channels:YB(_.dataDir,"channels.json",J.length),events:YB(_.dataDir,"events.json",U.length),deliveries:YB(_.dataDir,"deliveries.json",W.length)},counts:{channels:J.length,enabledChannels:J.filter((G)=>G.enabled).length,disabledChannels:J.filter((G)=>!G.enabled).length,events:U.length,deliveries:W.length},transports:X,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function YB($,_,J){let U=X9($,_);return{path:U,exists:xA(U),records:J}}function Bp($,_){return`${$}.${_}`}function Hp($,_,J){return`sha256=${Lp("sha256",$).update(Bp(_,J)).digest("hex")}`}function V0(){return new Date().toISOString()}function U9($,_=4096){return $.length>_?`${$.slice(0,_)}...`:$}function Fp($,_){if(!_.webhook)throw Error(`Channel ${_.id} has no webhook config`);let J=JSON.stringify($),U=$.time,W={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":$.id,"X-Hasna-Event-Type":$.type,"X-Hasna-Timestamp":U,..._.webhook.headers};if(_.webhook.secret)W["X-Hasna-Signature"]=Hp(_.webhook.secret,U,J);return{body:J,headers:W}}async function Rp($,_,J={}){if(!_.webhook)throw Error(`Channel ${_.id} has no webhook config`);let U=V0(),{body:W,headers:X}=Fp($,_),G=new AbortController,Q=setTimeout(()=>G.abort(),_.webhook.timeoutMs??15000);try{let Y=await(J.fetchImpl??fetch)(_.webhook.url,{method:"POST",headers:X,body:W,signal:G.signal}),q=U9(await Y.text());return{attempt:1,status:Y.ok?"success":"failed",startedAt:U,completedAt:V0(),responseStatus:Y.status,responseBody:q,error:Y.ok?void 0:`Webhook returned HTTP ${Y.status}`}}catch(Y){return{attempt:1,status:"failed",startedAt:U,completedAt:V0(),error:Y instanceof Error?Y.message:String(Y)}}finally{clearTimeout(Q)}}async function Kp($,_){if(!_.command)throw Error(`Channel ${_.id} has no command config`);let J=V0(),U=JSON.stringify($),W={...process.env,..._.command.env,HASNA_CHANNEL_ID:_.id,HASNA_EVENT_ID:$.id,HASNA_EVENT_TYPE:$.type,HASNA_EVENT_SOURCE:$.source,HASNA_EVENT_SUBJECT:$.subject??"",HASNA_EVENT_SEVERITY:$.severity,HASNA_EVENT_TIME:$.time,HASNA_EVENT_DEDUPE_KEY:$.dedupeKey??"",HASNA_EVENT_SCHEMA_VERSION:$.schemaVersion,HASNA_EVENT_JSON:U};return new Promise((X)=>{let G=Vp(_.command.command,_.command.args??[],{cwd:_.command.cwd,env:W,stdio:["pipe","pipe","pipe"]}),Q="",Y="",q=setTimeout(()=>G.kill("SIGTERM"),_.command.timeoutMs??15000);G.stdin.end(U),G.stdout.on("data",(L)=>{Q+=L.toString()}),G.stderr.on("data",(L)=>{Y+=L.toString()}),G.on("error",(L)=>{clearTimeout(q),X({attempt:1,status:"failed",startedAt:J,completedAt:V0(),stdout:U9(Q),stderr:U9(Y),error:L.message})}),G.on("close",(L,N)=>{clearTimeout(q);let F=L===0;X({attempt:1,status:F?"success":"failed",startedAt:J,completedAt:V0(),stdout:U9(Q),stderr:U9(Y),error:F?void 0:`Command exited with ${N?`signal ${N}`:`code ${L}`}`})})})}async function Mp($,_,J={}){if(_.transport==="webhook")return Rp($,_,J);if(_.transport==="command")return Kp($,_);return{attempt:1,status:"skipped",startedAt:V0(),completedAt:V0(),error:`Unsupported transport: ${_.transport}`}}function SA($,_,J){let U=J.some((W)=>W.status==="success")?"success":J.every((W)=>W.status==="skipped")?"skipped":"failed";return{id:Np(),eventId:$.id,channelId:_.id,transport:_.transport,status:U,attempts:J,createdAt:J[0]?.startedAt??V0(),completedAt:J.at(-1)?.completedAt??V0()}}class cA extends Error{eventType;issues;constructor($,_){let J=_.map((U)=>`${U.path||""}: ${U.message}`).join("; ");super(`Event validation failed for type "${$}": ${J}`);this.name="EventValidationError",this.eventType=$,this.issues=_}}class lA{definitions=new Map;register($){return this.definitions.set($.type,$),this}unregister($){return this.definitions.delete($)}has($){return this.definitions.has($)}get($){return this.definitions.get($)}list(){return[...this.definitions.values()]}validateEvent($){let _=this.definitions.get($.type);if(!_)return{ok:!0};return _.validate($.data,$)}assertEventValid($){let _=this.validateEvent($);if(!_.ok)throw new cA($.type,_.issues)}}var Ap=new lA;function qB($){return{id:$.id??bp(),source:$.source,type:$.type,time:kp($.time),subject:$.subject,severity:$.severity??"info",data:$.data??{},message:$.message,dedupeKey:$.dedupeKey,schemaVersion:$.schemaVersion??"1.0",metadata:$.metadata??{}}}class nA{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor($={}){this.store=$.store??new UQ($.dataDir),this.redactors=$.redactors??[],this.transportOptions={fetchImpl:$.fetchImpl},this.catalog=$.catalog??Ap,this.validateCatalogTypes=$.validateCatalogTypes??!1}async addChannel($){let _=new Date().toISOString();return this.store.addChannel({...$,createdAt:$.createdAt??_,updatedAt:$.updatedAt??_})}async listChannels(){return this.store.listChannels()}async removeChannel($){return this.store.removeChannel($)}async emit($,_={}){let J=_.redactSensitiveData===!1?qB($):Ip(qB($));if(_.validate??this.validateCatalogTypes)this.catalog.assertEventValid(J);let U=await this.appendEvent(J,{dedupe:_.dedupe!==!1});if(U.deduped)return{event:U.event,deliveries:[],deduped:!0};let W=_.deliver===!1?[]:await this.deliver(U.event);return{event:U.event,deliveries:W,deduped:!1}}async listEvents($={}){if(Object.keys($).length===0)return this.store.listEvents();return ZA(await this.store.listEvents(),$)}async listEventsPage($={}){if(this.store.listEventsPage)return this.store.listEventsPage($);let _=ZA(await this.store.listEvents(),{eventId:$.eventId,source:$.source,type:$.type}),J=XQ($.cursor,$),U=GQ($.limit),W=_.slice(J,J+U),X=J+W.length,G=X<_.length;return{events:W,cursor:$.cursor,nextCursor:G?dA(X,$):void 0,hasMore:G}}async listDeliveries(){return this.store.listDeliveries()}async deliver($){let J=(await this.store.listChannels()).filter((W)=>fA(W,$)),U=[];for(let W of J){let X=await this.applyRedaction($,W),G=await this.deliverWithRetry(X,W);await this.store.appendDelivery(G),U.push(G)}return U}async matchChannel($,_={}){let J=await this.store.getChannel($);if(!J)throw Error(`Channel not found: ${$}`);let U=qB({source:_.source??"hasna.events",type:_.type??"events.test",subject:_.subject??$,severity:_.severity??"info",data:_.data??{test:!0},message:_.message??"Hasna events test delivery",dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion,metadata:_.metadata,time:_.time,id:_.id}),W=fA(J,U);return{channelId:J.id,matched:W,event:U,filters:J.filters,reason:W?void 0:J.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel($,_={},J={}){let U=await this.store.getChannel($);if(!U)throw Error(`Channel not found: ${$}`);let W=await this.matchChannel($,_),X=W.event;if(J.honorFilters&&!W.matched){let Y=new Date().toISOString(),q=SA(X,U,[{attempt:1,status:"skipped",startedAt:Y,completedAt:Y,error:W.reason}]);return q.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(q),q}let G=await this.applyRedaction(X,U),Q=await this.deliverWithRetry(G,U);return await this.store.appendDelivery(Q),Q}async replay($={}){let _=$.cursor||$.limit!==void 0?await this.listEventsPage($):{events:await this.listEvents($),hasMore:!1};if($.dryRun)return{events:_.events,deliveries:[],cursor:_.cursor,nextCursor:_.nextCursor,hasMore:_.hasMore};let J=[];for(let U of _.events)J.push(...await this.deliver(U));return{events:_.events,deliveries:J,cursor:_.cursor,nextCursor:_.nextCursor,hasMore:_.hasMore}}async appendEvent($,_){if(this.store.appendEventOnce)return this.store.appendEventOnce($,{dedupe:_.dedupe});if(_.dedupe){let U=await this.store.findEventByIdentity({id:$.id,dedupeKey:$.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}let J=await this.store.appendEvent($);return{event:J,stored:!0,deduped:!1,identity:{id:J.id,dedupeKey:J.dedupeKey}}}async applyRedaction($,_){let J=Ep($,_.redact?.paths??[],_.redact?.replacement??"[REDACTED]");for(let U of this.redactors)J=await U(J,_);return J}async deliverWithRetry($,_){let J=fp(_.retry),U=[];for(let W=0;W[J,rA(J)?"[REDACTED]":U]));return _}function wp($){return $.map(iA)}function Ip($,_="[REDACTED]"){return jB($,_)}function rA($){return/secret|token|password|api[_-]?key|authorization/i.test($)}function jB($,_){if(Array.isArray($))return $.map((J)=>jB(J,_));if(!$||typeof $!=="object")return $;return Object.fromEntries(Object.entries($).map(([J,U])=>[J,rA(J)?_:jB(U,_)]))}function gp($,_,J){let U=_.split("."),W=$;for(let G of U.slice(0,-1)){let Q=W[G];if(!Q||typeof Q!=="object")return;W=Q}let X=U.at(-1);if(X&&X in W)W[X]=J}function ZA($,_){let J=$;if(_.eventId)J=J.filter((U)=>U.id===_.eventId);if(_.source)J=J.filter((U)=>U.source===_.source);if(_.type)J=J.filter((U)=>U.type===_.type);if(_.cursor)J=J.slice(XQ(_.cursor,_));if(_.limit!==void 0)J=J.slice(0,GQ(_.limit));return J}function kp($){if(!$)return new Date().toISOString();return $ instanceof Date?$.toISOString():$}function fp($){return{maxAttempts:Math.max(1,$?.maxAttempts??1),backoffMs:Math.max(0,$?.backoffMs??250),multiplier:Math.max(1,$?.multiplier??2)}}function _Q($,_,J=!1){if(!$?.length)return;let U={};for(let W of $){let X=Tp(W,_),G=X.path;if(G in U)throw Error(`Duplicate ${_} filter path: ${G}`);let Q=J?Pp(X.rawValue,_):X.rawValue;U[G]=X.negated?{not:Q}:Q}return U}function Cp($){let _={};if($.source)_.source=$.source;if($.type)_.type=$.type;if($.subject)_.subject=$.subject;if($.severity)_.severity=$.severity;let J=vA(_Q($.data,"data"),_Q($.dataJson,"data-json",!0)),U=vA(_Q($.metadata,"metadata"),_Q($.metadataJson,"metadata-json",!0));if(Object.keys(J).length>0)_.data=J;if(Object.keys(U).length>0)_.metadata=U;return Object.keys(_).length>0?[_]:void 0}function vA(...$){let _={};for(let J of $){if(!J)continue;for(let[U,W]of Object.entries(J)){if(U in _)throw Error(`Duplicate filter path: ${U}`);_[U]=W}}return _}function Pp($,_){let J=JSON.parse($);if(J===null||typeof J==="string"||typeof J==="number"||typeof J==="boolean"||Array.isArray(J)&&J.every((U)=>typeof U==="string"))return J;throw Error(`${_} filter JSON values must be string, string[], number, boolean, or null`)}function Tp($,_){let J=$.indexOf("!=");if(J>0)return{path:$.slice(0,J),rawValue:$.slice(J+2),negated:!0};let U=$.indexOf("=");if(U<=0)throw Error(`Invalid ${_} filter, expected path=value or path!=value: ${$}`);return{path:$.slice(0,U),rawValue:$.slice(U+1),negated:!1}}var Sp=100;function SW($,_){if(!$)return _;let J=JSON.parse($);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Expected a JSON object");return J}function Zp($){if(!$?.length)return;let _={};for(let J of $){let U=J.indexOf("=");if(U===-1)throw Error(`Invalid header, expected name=value: ${J}`);_[J.slice(0,U)]=J.slice(U+1)}return _}function n1($){if($.createClient)return $.createClient();return new nA({store:new UQ($.dataDir)})}function N_($,_,J){if(_)console.log(JSON.stringify($,null,2));else console.log(J)}function yA($,_){let J=$ instanceof Error?$.message:String($);if(_)console.log(JSON.stringify({error:J},null,2));else console.error(J);process.exitCode=1}function hA($){return Boolean($?.json||$?.opts?.().json||$?.optsWithGlobals?.().json||$?.parent?.opts?.().json||$?.parent?.optsWithGlobals?.().json)}function W1($,_){return hA($)||hA(_)}function vp($,_){let J=$.command(_.channelsCommandName??"channels").description("Manage Hasna event channels");return J.command("add").description("Add or replace a channel").argument("","Webhook URL or command binary").requiredOption("--id ","Channel identifier").option("--transport ","Transport kind: webhook or command","webhook").option("--name ","Display name").option("--type ","Event type filter, e.g. todos.task.*").option("--source ","Event source filter").option("--subject ","Event subject filter").option("--severity ","Event severity filter").option("--data ","Event data field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",H_,[]).option("--metadata ","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",H_,[]).option("--data-json ","Event data field filter with typed JSON value; path!=json negatives supported",H_,[]).option("--metadata-json ","Event metadata field filter with typed JSON value; path!=json negatives supported",H_,[]).option("--secret ","Webhook HMAC secret").option("--header ","Webhook header",H_,[]).option("--arg ","Command argument",H_,[]).option("--timeout-ms ","Transport timeout in milliseconds",G9).option("--retry-attempts ","Maximum delivery attempts",G9).option("--retry-backoff-ms ","Initial retry backoff in milliseconds",G9).option("--redact ","Event field path to redact before delivery",H_,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=new Date().toISOString(),Q={id:W.id,name:W.name,enabled:!W.disabled,transport:W.transport,filters:Cp(W),retry:W.retryAttempts||W.retryBackoffMs?{maxAttempts:W.retryAttempts,backoffMs:W.retryBackoffMs}:void 0,redact:W.redact?.length?{paths:W.redact}:void 0,createdAt:G,updatedAt:G};if(W.transport==="webhook")Q.webhook={url:U,secret:W.secret,headers:Zp(W.header),timeoutMs:W.timeoutMs};else if(W.transport==="command")Q.command={command:U,args:W.arg??[],timeoutMs:W.timeoutMs};else throw Error(`Transport ${W.transport} is reserved for future use and cannot be added yet`);let Y=await n1(_).addChannel(Q);N_(iA(Y),W1(W,X),`Added ${Y.transport} channel ${Y.id}`)}),J.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(U,W)=>{let X=await n1(_).listChannels();if(W1(U,W)){console.log(JSON.stringify(wp(X),null,2));return}if(!X.length){console.log("No channels configured.");return}for(let G of X)console.log(`${G.id} ${G.enabled?"enabled":"disabled"} ${G.transport} ${G.webhook?.url??G.command?.command??G.transport}`)}),J.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(U,W)=>{let X=await Dp(_.dataDir);N_(X,W1(U,W),`events dataDir: ${X.dataDir}`)}),J.command("remove").description("Remove a channel").argument("","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=await n1(_).removeChannel(U);N_({removed:G},W1(W,X),G?`Removed ${U}`:`Channel not found: ${U}`)}),J.command("test").description("Send a test event to one channel").argument("","Channel identifier").option("--source ","Event source override").option("--type ","Event type","events.test").option("--subject ","Event subject").option("--message ","Event message","Hasna events test delivery").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("--honor-filters","Skip delivery when the sample event does not match channel filters",!1).option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=W1(W,X);try{let Q=await n1(_).testChannel(U,{source:W.source??_.source,type:W.type,subject:W.subject??U,message:W.message,data:SW(W.data,{test:!0}),metadata:SW(W.metadata,{})},{honorFilters:W.honorFilters});N_(Q,G,`${Q.status}: ${Q.channelId}`)}catch(Q){yA(Q,G)}}),J.command("match").description("Check whether a sample event matches one channel without delivering").argument("","Channel identifier").option("--source ","Event source override").option("--type ","Event type","events.test").option("--subject ","Event subject").option("--message ","Event message","Hasna events match preview").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=W1(W,X);try{let Q=await n1(_).matchChannel(U,{source:W.source??_.source,type:W.type,subject:W.subject??U,message:W.message,data:SW(W.data,{test:!0}),metadata:SW(W.metadata,{})});N_(Q,G,`${Q.matched?"matched":"skipped"}: ${Q.channelId}`)}catch(Q){yA(Q,G)}}),J}function yp($,_){let J=$.command(_.eventsCommandName??"events").description("Emit, list, and replay Hasna events");J.command("emit").description("Emit an event from this app").argument("","Event type").option("--source ","Event source override").option("--subject ","Event subject").option("--severity ","Event severity","info").option("--message ","Event message").option("--dedupe-key ","Dedupe key").option("--data ","Event data JSON object").option("--metadata ","Event metadata JSON object").option("--no-deliver","Record without delivering").option("--no-dedupe","Allow duplicate id/dedupeKey events").option("-j, --json","Print JSON output",!1).action(async(W,X,G)=>{let Q=await n1(_).emit({source:X.source??_.source,type:W,subject:X.subject,severity:X.severity,message:X.message,dedupeKey:X.dedupeKey,data:SW(X.data,{}),metadata:SW(X.metadata,{})},{deliver:X.deliver,dedupe:X.dedupe});N_(Q,W1(X,G),`${Q.deduped?"Deduped":"Emitted"} ${Q.event.id} to ${Q.deliveries.length} channel(s)`)});let U=_.defaultEventListLimit??Sp;return J.command("list").description("List recorded events").option("--source ","Filter by source").option("--type ","Filter by type").option("--limit ",`Limit to the most recent events (default ${U}; use 0 for all)`,G9,U).option("-j, --json","Print JSON output",!1).action(async(W,X)=>{let G=await n1(_).listEvents();if(W.source)G=G.filter((Q)=>Q.source===W.source);if(W.type)G=G.filter((Q)=>Q.type===W.type);if(W.limit)G=G.slice(-W.limit);if(W1(W,X)){console.log(JSON.stringify(G,null,2));return}if(!G.length){console.log("No events recorded.");return}for(let Q of G)console.log(`${Q.time} ${Q.id} ${Q.source} ${Q.type} ${Q.severity}`)}),J.command("replay").description("Replay recorded events").option("--id ","Replay one event id").option("--source ","Filter by source").option("--type ","Filter by type").option("--cursor ","Opaque replay cursor from a previous page").option("--limit ","Maximum events to replay",G9).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(W,X)=>{let G=await n1(_).replay({eventId:W.id,source:W.source,type:W.type,cursor:W.cursor,limit:W.limit,dryRun:W.dryRun});N_(G,W1(W,X),hp(G.events.length,G.deliveries.length,G.nextCursor))}),J}function pA($,_){vp($,_),yp($,_)}function G9($){let _=Number($);if(!Number.isFinite(_))throw Error(`Expected a number, got ${$}`);return _}function H_($,_){return _.push($),_}function hp($,_,J){let U=J?`, next cursor: ${J}`:"";return`Replayed ${$} event(s), ${_} delivery result(s)${U}`}import{basename as xp}from"path";var a4={name:"@hasna/knowledge",version:"0.2.93",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. ",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.5.2","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};var oA={debug:0,info:1,warn:2,error:3},up=()=>{if(process.env.DEBUG)return"debug";if(process.env.LOG_LEVEL==="debug")return"debug";if(process.env.LOG_LEVEL==="warn")return"warn";if(process.env.LOG_LEVEL==="error")return"error";return"info"};function F_($,_,J){if(oA[$]U.toLowerCase()));return _.filter((U)=>!J.has(U.toLowerCase()))}function OB($,_,J){if(J===void 0)return{...$,message:_};return{...$,added:J.length,message:`${_} (added ${J.length} tag${J.length===1?"":"s"})`}}function cp($,_){if(_===void 0)throw Error("Missing value for --tag. Example: knowledge add <content> -t <tag> -t <tag>");let J=_.split(",").map((U)=>U.trim()).filter((U)=>U.length>0);if(J.length===0)throw Error(`Invalid --tag value ${JSON.stringify(_)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return dp([...$??[],...J])}function lp($){let _=[],J={},U=!1;for(let W=0;W<$.length;W+=1){let X=$[W];if(U){_.push(X);continue}if(X==="--"){U=!0;continue}if(!X.startsWith("-")||_[0]==="add"&&_.length===2&&X.startsWith("---")){_.push(X);continue}switch(X){case"--json":J.json=!0;break;case"--verbose":J.verbose=!0;break;case"--yes":case"-y":J.yes=!0;break;case"--help":case"-h":J.help=!0;break;case"--version":case"-v":J.version=!0;break;case"--desc":J.desc=!0;break;case"--page":case"-p":J.page=Number($[W+1]),W+=1;break;case"--limit":case"-l":J.limit=Number($[W+1]),W+=1;break;case"--search":case"-s":J.search=$[W+1],W+=1;break;case"--sort":J.sort=$[W+1],W+=1;break;case"--id":J.id=$[W+1],W+=1;break;case"--store":J.store=$[W+1],W+=1;break;case"--title":J.title=$[W+1],W+=1;break;case"--content":J.content=$[W+1],W+=1;break;case"--url":J.url=$[W+1],W+=1;break;case"--tag":case"-t":J.tag=cp(J.tag,$[W+1]),J.tagRaw=[...J.tagRaw??[],$[W+1]],W+=1;break;case"--format":J.format=$[W+1],W+=1;break;case"--completions":J.completions=$[W+1],W+=1;break;case"--purpose":J.purpose=$[W+1],W+=1;break;case"--model":J.model=$[W+1],W+=1;break;case"--strategy":J.strategy=$[W+1],W+=1;break;case"--dimensions":J.dimensions=Number($[W+1]),W+=1;break;case"--semantic":J.semantic=!0;break;case"--context":J.context=!0;break;case"--max-tokens":J.maxTokens=Number($[W+1]),W+=1;break;case"--max-items":J.maxItems=Number($[W+1]),W+=1;break;case"--from":J.from=$[W+1],W+=1;break;case"--to":J.to=$[W+1],W+=1;break;case"--rev":J.rev=Number($[W+1]),W+=1;break;case"--since":J.since=$[W+1],W+=1;break;case"--topic":J.topic=$[W+1],W+=1;break;case"--dedupe":J.dedupe=!0;break;case"--generate":J.generate=!0;break;case"--approve-write":J.approveWrite=!0;break;case"--provider":J.provider=$[W+1],W+=1;break;case"--mode":J.mode=$[W+1],W+=1;break;case"--machine":J.machine=$[W+1],W+=1;break;case"--workspace":J.workspace=$[W+1],W+=1;break;case"--api-url":J.apiUrl=$[W+1],W+=1;break;case"--canonical-example":J.canonicalExample=!0;break;case"--api-key":J.apiKey=$[W+1],W+=1;break;case"--email":J.email=$[W+1],W+=1;break;case"--org":J.org=$[W+1],W+=1;break;case"--org-id":J.orgId=$[W+1],W+=1;break;case"--user-id":J.userId=$[W+1],W+=1;break;case"--owner":J.owner=$[W+1],W+=1;break;case"--approved-by":J.approvedBy=$[W+1],W+=1;break;case"--patch-uri":J.patchUri=$[W+1],W+=1;break;case"--domain":J.domain=[...J.domain??[],$[W+1]],W+=1;break;case"--file-results":J.fileResults=!0;break;case"--full":J.full=!0;break;case"--dry-run":J.dryRun=!0;break;case"--fake":J.fake=!0;break;case"--no-tailscale":J.tailscale=!1;break;case"--no-artifact-content":J.artifactContent=!1;break;case"--no-color":J.noColor=!0;break;case"--scope":J.scope=$[W+1],W+=1;break;case"--tables":J.tables=$[W+1],W+=1;break;case"--peer-workspace":J.peerWorkspace=$[W+1],W+=1;break;case"--older-than":J.olderThan=Number($[W+1]),W+=1;break;case"--empty":J.empty=!0;break;case"--archived":J.archived=!0;break;case"--include-archived":J.includeArchived=!0;break;case"--project":J.project=$[W+1],W+=1;break;case"--contract":J.contract=!0;break;case"--source-ref":J.sourceRef=[...J.sourceRef??[],$[W+1]],W+=1;break;case"--allow-global":J.allowGlobal=!0;break;default:throw Error(`Unknown flag: ${X}. Run 'knowledge --help' for valid options.`)}}return{positional:_,flags:J}}function np($){if(!$)return"";return Jb[$]??$}function ip($,_){let J=Array.from({length:$.length+1},()=>Array(_.length+1).fill(0));for(let U=0;U<=$.length;U+=1)J[U][0]=U;for(let U=0;U<=_.length;U+=1)J[0][U]=U;for(let U=1;U<=$.length;U+=1)for(let W=1;W<=_.length;W+=1){let X=$[U-1]===_[W-1]?0:1;J[U][W]=Math.min(J[U-1][W]+1,J[U][W-1]+1,J[U-1][W-1]+X)}return J[$.length][_.length]}function rp($){if(!$)return"";let _=[..._b,...Object.keys(Jb)],J="",U=Number.POSITIVE_INFINITY;for(let W of _){let X=ip($,W);if(X<U)U=X,J=W}return U<=3?J:""}function pp(){return xp(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function op($){if(!$b.includes($[0]??""))return!1;let _=new IA;return _.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),pA(_,{source:"knowledge"}),await _.parseAsync($,{from:"user"}),!0}function tp(){console.log(`knowledge - local agent knowledge store + `)}var rM=CA(lM(),1),{program:M0$,createCommand:A0$,createArgument:b0$,createOption:w0$,CommanderError:g0$,InvalidArgumentError:k0$,InvalidOptionArgumentError:I0$,Command:pM,Argument:f0$,Option:C0$,Help:P0$}=rM.default;import{chmod as VB,mkdir as vp,readFile as yp,rename as hp,writeFile as sM}from"fs/promises";import{Buffer as GA}from"buffer";import{existsSync as YA}from"fs";import{homedir as mp}from"os";import{join as z9}from"path";import{createHmac as ip,timingSafeEqual as x0$}from"crypto";import{randomUUID as pp}from"crypto";import{spawn as op}from"child_process";import{randomUUID as _o}from"crypto";function kp($,_){return _.split(".").reduce((J,U)=>{if(J&&typeof J==="object"&&U in J)return J[U];return},$)}function Ip($,_){let J=[],U=(X)=>{if(!J.some((G)=>Object.is(G,X)))J.push(X)};if(_.includes(".")&&_ in $)U($[_]);let W=kp($,_);if(W!==void 0||!_.includes("."))U(W);return J}function fp($,_={}){let J="";for(let U=0;U<$.length;U+=1){let W=$[U];if(W==="*")if($[U+1]==="*")J+=".*",U+=1;else J+=_.segmentSafe?"[^/]*":".*";else J+=W.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${J}$`)}function Q9($,_,J={}){if(_===void 0)return!0;if($===void 0)return!1;return(Array.isArray(_)?_:[_]).some((W)=>fp(W,J).test($))}function oM($,_){if(!_)return!0;return Object.entries(_).every(([J,U])=>{let W=Ip($,J);return Cp(W,U,J)})}function Cp($,_,J){if(Sp(_))return!$.some((U)=>tM(U,_.not,J));return $.some((U)=>tM(U,_,J))}function tM($,_,J){if(typeof _==="string"||Array.isArray(_))return Pp($).some((U)=>Q9(U,_,{segmentSafe:J.endsWith("_path")||J.endsWith(".path")}));if(Array.isArray($))return $.some((U)=>U===_);return $===_}function Pp($){if($===void 0)return[];if(Array.isArray($))return $.flatMap((_)=>Tp(_)?[String(_)]:[]);return[String($)]}function Tp($){return $===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean"}function Sp($){return Boolean($&&typeof $==="object"&&!Array.isArray($)&&"not"in $)}function Zp($,_){return Q9($.source,_.source)&&Q9($.type,_.type)&&Q9($.subject,_.subject)&&Q9($.severity,_.severity)&&oM($.data,_.data)&&oM($.metadata,_.metadata)}function aM($,_){if(!$.enabled)return!1;if(!$.filters||$.filters.length===0)return!0;return $.filters.some((J)=>Zp(_,J))}var qY="HASNA_EVENTS_DIR",zY="HASNA_EVENTS_HOME",EB="local-json-v1:",xp=100,up=1000;function QA($){return $||process.env[qY]||process.env[zY]||z9(mp(),".hasna","events")}function dp(){if(process.env[qY])return qY;if(process.env[zY])return zY;return null}class jY{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor($=QA()){this.dataDir=$,this.runtime=np($),this.channelsPath=z9($,"channels.json"),this.eventsPath=z9($,"events.json"),this.deliveriesPath=z9($,"deliveries.json")}async init(){await vp(this.dataDir,{recursive:!0,mode:448}),await VB(this.dataDir,448).catch(()=>{return}),await this.ensureArrayFile(this.channelsPath),await this.ensureArrayFile(this.eventsPath),await this.ensureArrayFile(this.deliveriesPath)}async addChannel($){await this.init();let _=await this.readJson(this.channelsPath,[]),J=_.findIndex((U)=>U.id===$.id);if(J>=0)_[J]={...$,createdAt:_[J].createdAt,updatedAt:new Date().toISOString()};else _.push($);return await this.writeJson(this.channelsPath,_),J>=0?_[J]:$}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel($){return(await this.listChannels()).find((J)=>J.id===$)}async removeChannel($){await this.init();let _=await this.readJson(this.channelsPath,[]),J=_.filter((U)=>U.id!==$);return await this.writeJson(this.channelsPath,J),J.length!==_.length}async appendEvent($){await this.init();let _=await this.readJson(this.eventsPath,[]);return _.push($),await this.writeJson(this.eventsPath,_),$}async appendEventOnce($,_={}){await this.init();let J=await this.readJson(this.eventsPath,[]);if(_.dedupe!==!1){let W=$A(J,{id:$.id,dedupeKey:$.dedupeKey});if(W)return{event:W,stored:!1,deduped:!0,identity:{id:W.id,dedupeKey:W.dedupeKey}}}return J.push($),await this.writeJson(this.eventsPath,J),{event:$,stored:!0,deduped:!1,identity:{id:$.id,dedupeKey:$.dedupeKey}}}async listEvents($={}){await this.init();let _=await this.readJson(this.eventsPath,[]);return eM(_,$)}async listEventsPage($={}){await this.init();let _=await this.readJson(this.eventsPath,[]),J=eM(_,{eventId:$.eventId,source:$.source,type:$.type}),U=DY($.cursor,$),W=OY($.limit),X=J.slice(U,U+W),G=U+X.length,Y=G<J.length;return{events:X,cursor:$.cursor,nextCursor:Y?qA(G,$):void 0,hasMore:Y}}async findEventByIdentity($){let _=await this.listEvents();return $A(_,$)}async appendDelivery($){await this.init();let _=await this.readJson(this.deliveriesPath,[]);return _.push($),await this.writeJson(this.deliveriesPath,_),$}async listDeliveries(){return await this.init(),this.readJson(this.deliveriesPath,[])}async exportData(){return{channels:await this.listChannels(),events:await this.listEvents(),deliveries:await this.listDeliveries()}}async ensureArrayFile($){if(!YA($))await sM($,`[] +`,{encoding:"utf-8",mode:384});await VB($,384).catch(()=>{return})}async readJson($,_){try{let J=await yp($,"utf-8");if(!J.trim())return _;return JSON.parse(J)}catch(J){if(J.code==="ENOENT")return _;throw J}}async writeJson($,_){let J=`${$}.${process.pid}.${Date.now()}.tmp`;await sM(J,`${JSON.stringify(_,null,2)} +`,{encoding:"utf-8",mode:384}),await hp(J,$),await VB($,384).catch(()=>{return})}}function np($=QA()){return{mode:"local-files",name:"json-events-store",remote:!1,localFiles:!0,localSqlite:!1,postgres:!1,s3:!1,aws:!1,durable:!0,idempotency:"best-effort-local",replayCursors:!0,description:`Local JSON files in ${$}; no SQLite, Postgres, S3, or AWS runtime is configured by this store.`}}function qA($,_={}){if(!Number.isInteger($)||$<0)throw Error(`Invalid event cursor offset: ${$}`);let J={offset:$,eventId:_.eventId,source:_.source,type:_.type};return`${EB}${GA.from(JSON.stringify(J),"utf-8").toString("base64url")}`}function DY($,_={}){if(!$)return 0;if(!$.startsWith(EB))throw Error(`Invalid local JSON event cursor: ${$}`);let J=$.slice(EB.length),U;try{U=JSON.parse(GA.from(J,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${$}`)}let W=U.offset;if(!Number.isInteger(W)||W<0)throw Error(`Invalid local JSON event cursor: ${$}`);return RB("eventId",U.eventId,_.eventId),RB("source",U.source,_.source),RB("type",U.type,_.type),W}function OY($){if($===void 0)return xp;if(!Number.isInteger($)||$<1)throw Error(`Event page limit must be a positive integer, got ${$}`);return Math.min($,up)}function eM($,_){let J=$;if(_.eventId)J=J.filter((U)=>U.id===_.eventId);if(_.source)J=J.filter((U)=>U.source===_.source);if(_.type)J=J.filter((U)=>U.type===_.type);if(_.cursor){let U=DY(_.cursor,_);J=J.slice(U)}if(_.limit!==void 0)J=J.slice(0,OY(_.limit));return J}function RB($,_,J){if(_!==J)throw Error(`Local JSON event cursor ${$} filter mismatch`)}function $A($,_){return $.find((J)=>_.id!==void 0&&J.id===_.id||_.dedupeKey!==void 0&&J.dedupeKey===_.dedupeKey)}async function cp($){let _=new jY($);await _.init();let[J,U,W]=await Promise.all([_.listChannels(),_.listEvents(),_.listDeliveries()]),X=J.reduce((G,Y)=>{return G[Y.transport]=(G[Y.transport]??0)+1,G},{});return{service:"events",schemaVersion:"1.0",dataDir:_.dataDir,storage:_.runtime,env:{primary:qY,fallback:zY,active:dp()},files:{channels:KB(_.dataDir,"channels.json",J.length),events:KB(_.dataDir,"events.json",U.length),deliveries:KB(_.dataDir,"deliveries.json",W.length)},counts:{channels:J.length,enabledChannels:J.filter((G)=>G.enabled).length,disabledChannels:J.filter((G)=>!G.enabled).length,events:U.length,deliveries:W.length},transports:X,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function KB($,_,J){let U=z9($,_);return{path:U,exists:YA(U),records:J}}function lp($,_){return`${$}.${_}`}function rp($,_,J){return`sha256=${ip("sha256",$).update(lp(_,J)).digest("hex")}`}function R4(){return new Date().toISOString()}function q9($,_=4096){return $.length>_?`${$.slice(0,_)}...`:$}function tp($,_){if(!_.webhook)throw Error(`Channel ${_.id} has no webhook config`);let J=JSON.stringify($),U=$.time,W={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":$.id,"X-Hasna-Event-Type":$.type,"X-Hasna-Timestamp":U,..._.webhook.headers};if(_.webhook.secret)W["X-Hasna-Signature"]=rp(_.webhook.secret,U,J);return{body:J,headers:W}}async function ap($,_,J={}){if(!_.webhook)throw Error(`Channel ${_.id} has no webhook config`);let U=R4(),{body:W,headers:X}=tp($,_),G=new AbortController,Y=setTimeout(()=>G.abort(),_.webhook.timeoutMs??15000);try{let Q=await(J.fetchImpl??fetch)(_.webhook.url,{method:"POST",headers:X,body:W,signal:G.signal}),q=q9(await Q.text());return{attempt:1,status:Q.ok?"success":"failed",startedAt:U,completedAt:R4(),responseStatus:Q.status,responseBody:q,error:Q.ok?void 0:`Webhook returned HTTP ${Q.status}`}}catch(Q){return{attempt:1,status:"failed",startedAt:U,completedAt:R4(),error:Q instanceof Error?Q.message:String(Q)}}finally{clearTimeout(Y)}}async function sp($,_){if(!_.command)throw Error(`Channel ${_.id} has no command config`);let J=R4(),U=JSON.stringify($),W={...process.env,..._.command.env,HASNA_CHANNEL_ID:_.id,HASNA_EVENT_ID:$.id,HASNA_EVENT_TYPE:$.type,HASNA_EVENT_SOURCE:$.source,HASNA_EVENT_SUBJECT:$.subject??"",HASNA_EVENT_SEVERITY:$.severity,HASNA_EVENT_TIME:$.time,HASNA_EVENT_DEDUPE_KEY:$.dedupeKey??"",HASNA_EVENT_SCHEMA_VERSION:$.schemaVersion,HASNA_EVENT_JSON:U};return new Promise((X)=>{let G=op(_.command.command,_.command.args??[],{cwd:_.command.cwd,env:W,stdio:["pipe","pipe","pipe"]}),Y="",Q="",q=setTimeout(()=>G.kill("SIGTERM"),_.command.timeoutMs??15000);G.stdin.end(U),G.stdout.on("data",(L)=>{Y+=L.toString()}),G.stderr.on("data",(L)=>{Q+=L.toString()}),G.on("error",(L)=>{clearTimeout(q),X({attempt:1,status:"failed",startedAt:J,completedAt:R4(),stdout:q9(Y),stderr:q9(Q),error:L.message})}),G.on("close",(L,N)=>{clearTimeout(q);let R=L===0;X({attempt:1,status:R?"success":"failed",startedAt:J,completedAt:R4(),stdout:q9(Y),stderr:q9(Q),error:R?void 0:`Command exited with ${N?`signal ${N}`:`code ${L}`}`})})})}async function ep($,_,J={}){if(_.transport==="webhook")return ap($,_,J);if(_.transport==="command")return sp($,_);return{attempt:1,status:"skipped",startedAt:R4(),completedAt:R4(),error:`Unsupported transport: ${_.transport}`}}function _A($,_,J){let U=J.some((W)=>W.status==="success")?"success":J.every((W)=>W.status==="skipped")?"skipped":"failed";return{id:pp(),eventId:$.id,channelId:_.id,transport:_.transport,status:U,attempts:J,createdAt:J[0]?.startedAt??R4(),completedAt:J.at(-1)?.completedAt??R4()}}class zA extends Error{eventType;issues;constructor($,_){let J=_.map((U)=>`${U.path||"<root>"}: ${U.message}`).join("; ");super(`Event validation failed for type "${$}": ${J}`);this.name="EventValidationError",this.eventType=$,this.issues=_}}class jA{definitions=new Map;register($){return this.definitions.set($.type,$),this}unregister($){return this.definitions.delete($)}has($){return this.definitions.has($)}get($){return this.definitions.get($)}list(){return[...this.definitions.values()]}validateEvent($){let _=this.definitions.get($.type);if(!_)return{ok:!0};return _.validate($.data,$)}assertEventValid($){let _=this.validateEvent($);if(!_.ok)throw new zA($.type,_.issues)}}var $o=new jA;function FB($){return{id:$.id??_o(),source:$.source,type:$.type,time:Go($.time),subject:$.subject,severity:$.severity??"info",data:$.data??{},message:$.message,dedupeKey:$.dedupeKey,schemaVersion:$.schemaVersion??"1.0",metadata:$.metadata??{}}}class DA{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor($={}){this.store=$.store??new jY($.dataDir),this.redactors=$.redactors??[],this.transportOptions={fetchImpl:$.fetchImpl},this.catalog=$.catalog??$o,this.validateCatalogTypes=$.validateCatalogTypes??!1}async addChannel($){let _=new Date().toISOString();return this.store.addChannel({...$,createdAt:$.createdAt??_,updatedAt:$.updatedAt??_})}async listChannels(){return this.store.listChannels()}async removeChannel($){return this.store.removeChannel($)}async emit($,_={}){let J=_.redactSensitiveData===!1?FB($):Uo(FB($));if(_.validate??this.validateCatalogTypes)this.catalog.assertEventValid(J);let U=await this.appendEvent(J,{dedupe:_.dedupe!==!1});if(U.deduped)return{event:U.event,deliveries:[],deduped:!0};let W=_.deliver===!1?[]:await this.deliver(U.event);return{event:U.event,deliveries:W,deduped:!1}}async listEvents($={}){if(Object.keys($).length===0)return this.store.listEvents();return JA(await this.store.listEvents(),$)}async listEventsPage($={}){if(this.store.listEventsPage)return this.store.listEventsPage($);let _=JA(await this.store.listEvents(),{eventId:$.eventId,source:$.source,type:$.type}),J=DY($.cursor,$),U=OY($.limit),W=_.slice(J,J+U),X=J+W.length,G=X<_.length;return{events:W,cursor:$.cursor,nextCursor:G?qA(X,$):void 0,hasMore:G}}async listDeliveries(){return this.store.listDeliveries()}async deliver($){let J=(await this.store.listChannels()).filter((W)=>aM(W,$)),U=[];for(let W of J){let X=await this.applyRedaction($,W),G=await this.deliverWithRetry(X,W);await this.store.appendDelivery(G),U.push(G)}return U}async matchChannel($,_={}){let J=await this.store.getChannel($);if(!J)throw Error(`Channel not found: ${$}`);let U=FB({source:_.source??"hasna.events",type:_.type??"events.test",subject:_.subject??$,severity:_.severity??"info",data:_.data??{test:!0},message:_.message??"Hasna events test delivery",dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion,metadata:_.metadata,time:_.time,id:_.id}),W=aM(J,U);return{channelId:J.id,matched:W,event:U,filters:J.filters,reason:W?void 0:J.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel($,_={},J={}){let U=await this.store.getChannel($);if(!U)throw Error(`Channel not found: ${$}`);let W=await this.matchChannel($,_),X=W.event;if(J.honorFilters&&!W.matched){let Q=new Date().toISOString(),q=_A(X,U,[{attempt:1,status:"skipped",startedAt:Q,completedAt:Q,error:W.reason}]);return q.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(q),q}let G=await this.applyRedaction(X,U),Y=await this.deliverWithRetry(G,U);return await this.store.appendDelivery(Y),Y}async replay($={}){let _=$.cursor||$.limit!==void 0?await this.listEventsPage($):{events:await this.listEvents($),hasMore:!1};if($.dryRun)return{events:_.events,deliveries:[],cursor:_.cursor,nextCursor:_.nextCursor,hasMore:_.hasMore};let J=[];for(let U of _.events)J.push(...await this.deliver(U));return{events:_.events,deliveries:J,cursor:_.cursor,nextCursor:_.nextCursor,hasMore:_.hasMore}}async appendEvent($,_){if(this.store.appendEventOnce)return this.store.appendEventOnce($,{dedupe:_.dedupe});if(_.dedupe){let U=await this.store.findEventByIdentity({id:$.id,dedupeKey:$.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}let J=await this.store.appendEvent($);return{event:J,stored:!0,deduped:!1,identity:{id:J.id,dedupeKey:J.dedupeKey}}}async applyRedaction($,_){let J=Jo($,_.redact?.paths??[],_.redact?.replacement??"[REDACTED]");for(let U of this.redactors)J=await U(J,_);return J}async deliverWithRetry($,_){let J=Yo(_.retry),U=[];for(let W=0;W<J.maxAttempts;W+=1){let X=await ep($,_,this.transportOptions);if(X.attempt=W+1,X.status==="failed"&&W+1<J.maxAttempts)X.nextBackoffMs=Math.round(J.backoffMs*J.multiplier**W);if(U.push(X),X.status!=="failed")break;if(X.nextBackoffMs)await Bun.sleep(X.nextBackoffMs)}return _A($,_,U)}}function Jo($,_,J="[REDACTED]"){if(_.length===0)return $;let U=structuredClone($);for(let W of _)Xo(U,W,J);return U}function OA($){let _=structuredClone($);if(_.webhook?.secret)_.webhook.secret="[REDACTED]";if(_.command?.env)_.command.env=Object.fromEntries(Object.entries(_.command.env).map(([J,U])=>[J,LA(J)?"[REDACTED]":U]));return _}function Wo($){return $.map(OA)}function Uo($,_="[REDACTED]"){return MB($,_)}function LA($){return/secret|token|password|api[_-]?key|authorization/i.test($)}function MB($,_){if(Array.isArray($))return $.map((J)=>MB(J,_));if(!$||typeof $!=="object")return $;return Object.fromEntries(Object.entries($).map(([J,U])=>[J,LA(J)?_:MB(U,_)]))}function Xo($,_,J){let U=_.split("."),W=$;for(let G of U.slice(0,-1)){let Y=W[G];if(!Y||typeof Y!=="object")return;W=Y}let X=U.at(-1);if(X&&X in W)W[X]=J}function JA($,_){let J=$;if(_.eventId)J=J.filter((U)=>U.id===_.eventId);if(_.source)J=J.filter((U)=>U.source===_.source);if(_.type)J=J.filter((U)=>U.type===_.type);if(_.cursor)J=J.slice(DY(_.cursor,_));if(_.limit!==void 0)J=J.slice(0,OY(_.limit));return J}function Go($){if(!$)return new Date().toISOString();return $ instanceof Date?$.toISOString():$}function Yo($){return{maxAttempts:Math.max(1,$?.maxAttempts??1),backoffMs:Math.max(0,$?.backoffMs??250),multiplier:Math.max(1,$?.multiplier??2)}}function QY($,_,J=!1){if(!$?.length)return;let U={};for(let W of $){let X=zo(W,_),G=X.path;if(G in U)throw Error(`Duplicate ${_} filter path: ${G}`);let Y=J?qo(X.rawValue,_):X.rawValue;U[G]=X.negated?{not:Y}:Y}return U}function Qo($){let _={};if($.source)_.source=$.source;if($.type)_.type=$.type;if($.subject)_.subject=$.subject;if($.severity)_.severity=$.severity;let J=WA(QY($.data,"data"),QY($.dataJson,"data-json",!0)),U=WA(QY($.metadata,"metadata"),QY($.metadataJson,"metadata-json",!0));if(Object.keys(J).length>0)_.data=J;if(Object.keys(U).length>0)_.metadata=U;return Object.keys(_).length>0?[_]:void 0}function WA(...$){let _={};for(let J of $){if(!J)continue;for(let[U,W]of Object.entries(J)){if(U in _)throw Error(`Duplicate filter path: ${U}`);_[U]=W}}return _}function qo($,_){let J=JSON.parse($);if(J===null||typeof J==="string"||typeof J==="number"||typeof J==="boolean"||Array.isArray(J)&&J.every((U)=>typeof U==="string"))return J;throw Error(`${_} filter JSON values must be string, string[], number, boolean, or null`)}function zo($,_){let J=$.indexOf("!=");if(J>0)return{path:$.slice(0,J),rawValue:$.slice(J+2),negated:!0};let U=$.indexOf("=");if(U<=0)throw Error(`Invalid ${_} filter, expected path=value or path!=value: ${$}`);return{path:$.slice(0,U),rawValue:$.slice(U+1),negated:!1}}var jo=100;function mW($,_){if(!$)return _;let J=JSON.parse($);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Expected a JSON object");return J}function Do($){if(!$?.length)return;let _={};for(let J of $){let U=J.indexOf("=");if(U===-1)throw Error(`Invalid header, expected name=value: ${J}`);_[J.slice(0,U)]=J.slice(U+1)}return _}function o0($){if($.createClient)return $.createClient();return new DA({store:new jY($.dataDir)})}function F2($,_,J){if(_)console.log(JSON.stringify($,null,2));else console.log(J)}function UA($,_){let J=$ instanceof Error?$.message:String($);if(_)console.log(JSON.stringify({error:J},null,2));else console.error(J);process.exitCode=1}function XA($){return Boolean($?.json||$?.opts?.().json||$?.optsWithGlobals?.().json||$?.parent?.opts?.().json||$?.parent?.optsWithGlobals?.().json)}function X0($,_){return XA($)||XA(_)}function Oo($,_){let J=$.command(_.channelsCommandName??"channels").description("Manage Hasna event channels");return J.command("add").description("Add or replace a channel").argument("<target>","Webhook URL or command binary").requiredOption("--id <id>","Channel identifier").option("--transport <kind>","Transport kind: webhook or command","webhook").option("--name <name>","Display name").option("--type <pattern>","Event type filter, e.g. todos.task.*").option("--source <pattern>","Event source filter").option("--subject <pattern>","Event subject filter").option("--severity <pattern>","Event severity filter").option("--data <path=value...>","Event data field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",K2,[]).option("--metadata <path=value...>","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",K2,[]).option("--data-json <path=json...>","Event data field filter with typed JSON value; path!=json negatives supported",K2,[]).option("--metadata-json <path=json...>","Event metadata field filter with typed JSON value; path!=json negatives supported",K2,[]).option("--secret <secret>","Webhook HMAC secret").option("--header <name=value...>","Webhook header",K2,[]).option("--arg <arg...>","Command argument",K2,[]).option("--timeout-ms <ms>","Transport timeout in milliseconds",j9).option("--retry-attempts <n>","Maximum delivery attempts",j9).option("--retry-backoff-ms <ms>","Initial retry backoff in milliseconds",j9).option("--redact <path...>","Event field path to redact before delivery",K2,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=new Date().toISOString(),Y={id:W.id,name:W.name,enabled:!W.disabled,transport:W.transport,filters:Qo(W),retry:W.retryAttempts||W.retryBackoffMs?{maxAttempts:W.retryAttempts,backoffMs:W.retryBackoffMs}:void 0,redact:W.redact?.length?{paths:W.redact}:void 0,createdAt:G,updatedAt:G};if(W.transport==="webhook")Y.webhook={url:U,secret:W.secret,headers:Do(W.header),timeoutMs:W.timeoutMs};else if(W.transport==="command")Y.command={command:U,args:W.arg??[],timeoutMs:W.timeoutMs};else throw Error(`Transport ${W.transport} is reserved for future use and cannot be added yet`);let Q=await o0(_).addChannel(Y);F2(OA(Q),X0(W,X),`Added ${Q.transport} channel ${Q.id}`)}),J.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(U,W)=>{let X=await o0(_).listChannels();if(X0(U,W)){console.log(JSON.stringify(Wo(X),null,2));return}if(!X.length){console.log("No channels configured.");return}for(let G of X)console.log(`${G.id} ${G.enabled?"enabled":"disabled"} ${G.transport} ${G.webhook?.url??G.command?.command??G.transport}`)}),J.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(U,W)=>{let X=await cp(_.dataDir);F2(X,X0(U,W),`events dataDir: ${X.dataDir}`)}),J.command("remove").description("Remove a channel").argument("<id>","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=await o0(_).removeChannel(U);F2({removed:G},X0(W,X),G?`Removed ${U}`:`Channel not found: ${U}`)}),J.command("test").description("Send a test event to one channel").argument("<id>","Channel identifier").option("--source <source>","Event source override").option("--type <type>","Event type","events.test").option("--subject <subject>","Event subject").option("--message <message>","Event message","Hasna events test delivery").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("--honor-filters","Skip delivery when the sample event does not match channel filters",!1).option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=X0(W,X);try{let Y=await o0(_).testChannel(U,{source:W.source??_.source,type:W.type,subject:W.subject??U,message:W.message,data:mW(W.data,{test:!0}),metadata:mW(W.metadata,{})},{honorFilters:W.honorFilters});F2(Y,G,`${Y.status}: ${Y.channelId}`)}catch(Y){UA(Y,G)}}),J.command("match").description("Check whether a sample event matches one channel without delivering").argument("<id>","Channel identifier").option("--source <source>","Event source override").option("--type <type>","Event type","events.test").option("--subject <subject>","Event subject").option("--message <message>","Event message","Hasna events match preview").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("-j, --json","Print JSON output",!1).action(async(U,W,X)=>{let G=X0(W,X);try{let Y=await o0(_).matchChannel(U,{source:W.source??_.source,type:W.type,subject:W.subject??U,message:W.message,data:mW(W.data,{test:!0}),metadata:mW(W.metadata,{})});F2(Y,G,`${Y.matched?"matched":"skipped"}: ${Y.channelId}`)}catch(Y){UA(Y,G)}}),J}function Lo($,_){let J=$.command(_.eventsCommandName??"events").description("Emit, list, and replay Hasna events");J.command("emit").description("Emit an event from this app").argument("<type>","Event type").option("--source <source>","Event source override").option("--subject <subject>","Event subject").option("--severity <severity>","Event severity","info").option("--message <message>","Event message").option("--dedupe-key <key>","Dedupe key").option("--data <json>","Event data JSON object").option("--metadata <json>","Event metadata JSON object").option("--no-deliver","Record without delivering").option("--no-dedupe","Allow duplicate id/dedupeKey events").option("-j, --json","Print JSON output",!1).action(async(W,X,G)=>{let Y=await o0(_).emit({source:X.source??_.source,type:W,subject:X.subject,severity:X.severity,message:X.message,dedupeKey:X.dedupeKey,data:mW(X.data,{}),metadata:mW(X.metadata,{})},{deliver:X.deliver,dedupe:X.dedupe});F2(Y,X0(X,G),`${Y.deduped?"Deduped":"Emitted"} ${Y.event.id} to ${Y.deliveries.length} channel(s)`)});let U=_.defaultEventListLimit??jo;return J.command("list").description("List recorded events").option("--source <source>","Filter by source").option("--type <type>","Filter by type").option("--limit <n>",`Limit to the most recent <n> events (default ${U}; use 0 for all)`,j9,U).option("-j, --json","Print JSON output",!1).action(async(W,X)=>{let G=await o0(_).listEvents();if(W.source)G=G.filter((Y)=>Y.source===W.source);if(W.type)G=G.filter((Y)=>Y.type===W.type);if(W.limit)G=G.slice(-W.limit);if(X0(W,X)){console.log(JSON.stringify(G,null,2));return}if(!G.length){console.log("No events recorded.");return}for(let Y of G)console.log(`${Y.time} ${Y.id} ${Y.source} ${Y.type} ${Y.severity}`)}),J.command("replay").description("Replay recorded events").option("--id <id>","Replay one event id").option("--source <source>","Filter by source").option("--type <type>","Filter by type").option("--cursor <cursor>","Opaque replay cursor from a previous page").option("--limit <n>","Maximum events to replay",j9).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(W,X)=>{let G=await o0(_).replay({eventId:W.id,source:W.source,type:W.type,cursor:W.cursor,limit:W.limit,dryRun:W.dryRun});F2(G,X0(W,X),Bo(G.events.length,G.deliveries.length,G.nextCursor))}),J}function BA($,_){Oo($,_),Lo($,_)}function j9($){let _=Number($);if(!Number.isFinite(_))throw Error(`Expected a number, got ${$}`);return _}function K2($,_){return _.push($),_}function Bo($,_,J){let U=J?`, next cursor: ${J}`:"";return`Replayed ${$} event(s), ${_} delivery result(s)${U}`}import{basename as No}from"path";var s6={name:"@hasna/knowledge",version:"0.2.93",description:"Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions",type:"module",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./storage":{import:"./dist/storage.js",types:"./dist/storage.d.ts"},"./serve":{import:"./dist/serve.js",types:"./dist/serve.d.ts"}},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{knowledge:"bin/knowledge.js","knowledge-mcp":"bin/knowledge-mcp.js","knowledge-serve":"bin/knowledge-serve.js"},files:["bin","dist","scripts/apply-cloud-migrations.mjs","scripts/lib/remote-temp-dir.mjs","scripts/smoke-machine-sync-release.mjs","scripts/smoke-machines-adapter.mjs","scripts/smoke-open-files-installed-boundary.mjs","scripts/strip-generated-trailing-whitespace.mjs","scripts/verify-generated-artifacts.mjs","docs/architecture/ai-native-knowledge-base.md","docs/architecture/hosted-wrapper-responsibilities.md","docs/architecture/hybrid-semantic-search.md","docs/architecture/machine-sync-schema.md","docs/examples/app-project-wiki-standard.md","docs/examples/company-wiki-workflow.md","docs/migration/global-rules-provenance-import.md","docs/migration/json-to-sqlite.md","LICENSE","README.md"],scripts:{test:"bun test","test:cli":"bun test tests/cli.test.ts","test:package":"bun test tests/package-release.test.ts","release:pack:check":"node scripts/validate-public-package.mjs","smoke:machines-adapter":"bun scripts/smoke-machines-adapter.mjs","smoke:machine-sync-release":"bun scripts/smoke-machine-sync-release.mjs","smoke:open-files-installed-boundary":"bun scripts/smoke-open-files-installed-boundary.mjs","migrate:cloud":"bun scripts/apply-cloud-migrations.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs",build:"rm -rf dist && bun build --target=bun --outfile=bin/knowledge.js --minify --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/cli.ts && bun build --target=bun --outfile=bin/knowledge-mcp.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @modelcontextprotocol/sdk --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/mcp.js && bun build --target=bun --outfile=bin/knowledge-serve.js --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek src/serve-entry.ts && bun build ./src/index.ts ./src/storage.ts ./src/serve.ts --outdir ./dist --target bun --external pg --external @hasna/machines --external @hasna/machines/consumer --external @aws-sdk/client-s3 --external @aws-sdk/credential-providers --external ai --external @ai-sdk/openai --external @ai-sdk/anthropic --external @ai-sdk/deepseek && bun scripts/strip-generated-trailing-whitespace.mjs && bunx tsc -p tsconfig.build.json",prepublishOnly:"bun run build && node scripts/validate-public-package.mjs"},keywords:["knowledge","cli","agents","json","notes","local","store"],license:"Apache-2.0",publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/hasna/knowledge.git"},bugs:{url:"https://github.com/hasna/knowledge/issues"},author:"Hasna Inc. <hasna@example.com>",engines:{bun:">=1.0",node:">=18"},dependencies:{"@ai-sdk/anthropic":"^3.0.81","@ai-sdk/deepseek":"^2.0.35","@ai-sdk/openai":"^3.0.68","@aws-sdk/client-s3":"^3.1063.0","@aws-sdk/credential-providers":"^3.1063.0","@hasna/events":"^0.1.3","@modelcontextprotocol/sdk":"^1.29.0","@types/json-schema":"^7.0.15",ai:"^6.0.197",commander:"^13.1.0",pg:"^8.16.3",zod:"^4.3.6"},devDependencies:{"@electric-sql/pglite":"^0.5.4","@hasna/contracts":"0.5.2","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};var HA={debug:0,info:1,warn:2,error:3},Vo=()=>{if(process.env.DEBUG)return"debug";if(process.env.LOG_LEVEL==="debug")return"debug";if(process.env.LOG_LEVEL==="warn")return"warn";if(process.env.LOG_LEVEL==="error")return"error";return"info"};function M2($,_,J){if(HA[$]<HA[Vo()])return;let U={debug:"[DEBUG]",info:"[INFO]",warn:"[WARN]",error:"[ERROR]"}[$],W=J?`${U} ${_} ${JSON.stringify(J)}`:`${U} ${_}`;if($==="error")console.error(W);else console.error(W)}var FA=["events","webhooks"],EA=["add","list","get","delete","update","archive","restore","upsert","untag","versions","diff","export","prune","dedupe","stats","inventory","project-panel","paths","mode","setup","auth","storage","machines","sync","db","wiki","app-wiki","source","ingest","reindex","search","context","proposals","web","ask","build","embeddings","providers","safety","help",...FA],MA={ls:"list",rm:"delete",edit:"update",unarchive:"restore"};function Ro($){let _=new Set,J=[];for(let U of $){let W=U.toLowerCase();if(_.has(W))continue;_.add(W),J.push(U)}return J}function NA($,_){let J=new Set(($??[]).map((U)=>U.toLowerCase()));return _.filter((U)=>!J.has(U.toLowerCase()))}function AB($,_,J){if(J===void 0)return{...$,message:_};return{...$,added:J.length,message:`${_} (added ${J.length} tag${J.length===1?"":"s"})`}}function Ko($,_){if(_===void 0)throw Error("Missing value for --tag. Example: knowledge add <title> <content> -t <tag> -t <tag>");let J=_.split(",").map((U)=>U.trim()).filter((U)=>U.length>0);if(J.length===0)throw Error(`Invalid --tag value ${JSON.stringify(_)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return Ro([...$??[],...J])}function Fo($){let _=[],J={},U=!1;for(let W=0;W<$.length;W+=1){let X=$[W];if(U){_.push(X);continue}if(X==="--"){U=!0;continue}if(!X.startsWith("-")||_[0]==="add"&&_.length===2&&X.startsWith("---")){_.push(X);continue}switch(X){case"--json":J.json=!0;break;case"--verbose":J.verbose=!0;break;case"--yes":case"-y":J.yes=!0;break;case"--help":case"-h":J.help=!0;break;case"--version":case"-v":J.version=!0;break;case"--desc":J.desc=!0;break;case"--page":case"-p":J.page=Number($[W+1]),W+=1;break;case"--limit":case"-l":J.limit=Number($[W+1]),W+=1;break;case"--search":case"-s":J.search=$[W+1],W+=1;break;case"--sort":J.sort=$[W+1],W+=1;break;case"--id":J.id=$[W+1],W+=1;break;case"--store":J.store=$[W+1],W+=1;break;case"--title":J.title=$[W+1],W+=1;break;case"--content":J.content=$[W+1],W+=1;break;case"--url":J.url=$[W+1],W+=1;break;case"--tag":case"-t":J.tag=Ko(J.tag,$[W+1]),J.tagRaw=[...J.tagRaw??[],$[W+1]],W+=1;break;case"--format":J.format=$[W+1],W+=1;break;case"--completions":J.completions=$[W+1],W+=1;break;case"--purpose":J.purpose=$[W+1],W+=1;break;case"--model":J.model=$[W+1],W+=1;break;case"--strategy":J.strategy=$[W+1],W+=1;break;case"--dimensions":J.dimensions=Number($[W+1]),W+=1;break;case"--semantic":J.semantic=!0;break;case"--context":J.context=!0;break;case"--max-tokens":J.maxTokens=Number($[W+1]),W+=1;break;case"--max-items":J.maxItems=Number($[W+1]),W+=1;break;case"--from":J.from=$[W+1],W+=1;break;case"--to":J.to=$[W+1],W+=1;break;case"--rev":J.rev=Number($[W+1]),W+=1;break;case"--since":J.since=$[W+1],W+=1;break;case"--topic":J.topic=$[W+1],W+=1;break;case"--dedupe":J.dedupe=!0;break;case"--generate":J.generate=!0;break;case"--approve-write":J.approveWrite=!0;break;case"--provider":J.provider=$[W+1],W+=1;break;case"--mode":J.mode=$[W+1],W+=1;break;case"--machine":J.machine=$[W+1],W+=1;break;case"--workspace":J.workspace=$[W+1],W+=1;break;case"--api-url":J.apiUrl=$[W+1],W+=1;break;case"--canonical-example":J.canonicalExample=!0;break;case"--api-key":J.apiKey=$[W+1],W+=1;break;case"--email":J.email=$[W+1],W+=1;break;case"--org":J.org=$[W+1],W+=1;break;case"--org-id":J.orgId=$[W+1],W+=1;break;case"--user-id":J.userId=$[W+1],W+=1;break;case"--owner":J.owner=$[W+1],W+=1;break;case"--approved-by":J.approvedBy=$[W+1],W+=1;break;case"--patch-uri":J.patchUri=$[W+1],W+=1;break;case"--domain":J.domain=[...J.domain??[],$[W+1]],W+=1;break;case"--file-results":J.fileResults=!0;break;case"--full":J.full=!0;break;case"--dry-run":J.dryRun=!0;break;case"--fake":J.fake=!0;break;case"--no-tailscale":J.tailscale=!1;break;case"--no-artifact-content":J.artifactContent=!1;break;case"--no-color":J.noColor=!0;break;case"--scope":J.scope=$[W+1],W+=1;break;case"--tables":J.tables=$[W+1],W+=1;break;case"--peer-workspace":J.peerWorkspace=$[W+1],W+=1;break;case"--older-than":J.olderThan=Number($[W+1]),W+=1;break;case"--empty":J.empty=!0;break;case"--archived":J.archived=!0;break;case"--include-archived":J.includeArchived=!0;break;case"--project":J.project=$[W+1],W+=1;break;case"--contract":J.contract=!0;break;case"--source-ref":J.sourceRef=[...J.sourceRef??[],$[W+1]],W+=1;break;case"--allow-global":J.allowGlobal=!0;break;default:throw Error(`Unknown flag: ${X}. Run 'knowledge --help' for valid options.`)}}return{positional:_,flags:J}}function Eo($){if(!$)return"";return MA[$]??$}function Mo($,_){let J=Array.from({length:$.length+1},()=>Array(_.length+1).fill(0));for(let U=0;U<=$.length;U+=1)J[U][0]=U;for(let U=0;U<=_.length;U+=1)J[0][U]=U;for(let U=1;U<=$.length;U+=1)for(let W=1;W<=_.length;W+=1){let X=$[U-1]===_[W-1]?0:1;J[U][W]=Math.min(J[U-1][W]+1,J[U][W-1]+1,J[U-1][W-1]+X)}return J[$.length][_.length]}function Ao($){if(!$)return"";let _=[...EA,...Object.keys(MA)],J="",U=Number.POSITIVE_INFINITY;for(let W of _){let X=Mo($,W);if(X<U)U=X,J=W}return U<=3?J:""}function bo(){return No(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function wo($){if(!FA.includes($[0]??""))return!1;let _=new pM;return _.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),BA(_,{source:"knowledge"}),await _.parseAsync($,{from:"user"}),!0}function go(){console.log(`knowledge - local agent knowledge store Usage: knowledge <command> [options] @@ -1341,7 +1489,7 @@ Export Options: Prune Options: --older-than <days> Remove items older than N days - --empty Remove items with empty content`)}function ap($){if($==="add"){console.log(`Usage: knowledge add <title> <content> [--url <url>] [-t <tag>]... [--json] + --empty Remove items with empty content`)}function ko($){if($==="add"){console.log(`Usage: knowledge add <title> <content> [--url <url>] [-t <tag>]... [--json] -t/--tag is repeatable and accepts comma-separated values: -t a -t b == -t "a,b"`);return}if($==="list"||$==="ls"){console.log(`Usage: knowledge list|ls [--format table|json] [-p <page>] [-l <limit>] [-s <search>] [-t <tag>]... [--sort created|title] [--desc] [--archived] [--include-archived] [--verbose] [--json] -t/--tag is repeatable and accepts comma-separated values; repeated -t narrows (an item must carry every tag). Each value matches an item carrying the whole value OR all of its comma-split names \u2014 a union, so @@ -1371,30 +1519,30 @@ Prune Options: Reports which backend this process would use \u2014 local (on-box store) or cloud (HTTP /v1) \u2014 and which env var selected it. Reads the environment only: no store is opened, no config file is read, and no request is made, so it is safe on a machine with no config and no network. - Selection is EXPLICIT-ONLY: set ${v0[0]}=local|cloud. Setting only - ${k9[0]} / ${f9[0]} does NOT switch backends; + Selection is EXPLICIT-ONLY: set ${y4[0]}=local|cloud. Setting only + ${S9[0]} / ${Z9[0]} does NOT switch backends; those are reported as present-but-ignored pointers. Env var NAMES are printed, never values.`);return}if($==="setup"){console.log("Usage: knowledge setup --mode local|hosted [--api-url https://...] [--canonical-example] [--scope local|global|project] [--json]");return}if($==="auth"){console.log("Usage: knowledge auth login|whoami|logout [--api-key <key>] [--email <email>] [--org <slug>] [--api-url https://...] [--scope local|global|project] [--json]");return}if($==="storage"){console.log(`Usage: knowledge storage status|validate|repair-artifact-keys|migrate-legacy-path|merge-legacy-path [--approve-write --approved-by <name>] [--scope local|global|project] [--json] knowledge storage import-legacy [--dry-run] [--scope global] [--json]`);return}if($==="machines"){console.log("Usage: knowledge machines topology [--no-tailscale] | preflight [machine] [--workspace <repo>] [--scope local|global|project] [--verbose] [--json]");return}if($==="sync"){console.log(`Usage: knowledge sync status|doctor|readiness|snapshot|machines|conflicts [show|propose|resolve] [id] | dry-run|pull|push|sync|export|import [--peer-workspace <path>] [--machine <ssh-alias>] [--tables <names>] [--dry-run] [--limit <n>] [--approve-write] [--approved-by <name>] [--strategy <name>] [--mode deterministic|ai] [--model <alias|provider:model>] [--fake] [--no-tailscale] [--scope local|global|project] [--verbose] [--json] -Remote machine sync resolves peer paths through @hasna/machines when --peer-workspace is omitted.`);return}if($==="db"){console.log("Usage: knowledge db init|stats|storage status [--scope local|global|project] [--json]");return}if($==="wiki"){console.log("Usage: knowledge wiki init|compile|file-answer|lint [query|prompt] [--title <title>] [--content <answer>] [--approve-write] [--limit <n>] [--scope local|global|project] [--json]");return}if($==="app-wiki"){console.log("Usage: knowledge app-wiki init | note add|get|list | source add <source-ref> | search <query> | query <query> [--title <title>] [--content <text>] [--tag <tag>] [--source-ref <uri>] [--scope project|local|global] [--allow-global] [--json]");return}if($==="source"){console.log("Usage: knowledge source resolve <source-ref> [--purpose knowledge_answer|knowledge_index] [--limit <n>] [--scope local|global|project] [--json]");return}if($==="ingest"){console.log("Usage: knowledge ingest manifest <file|s3://bucket/key> | source <source-ref> | rules [--workspace <path>] [--owner <name>] [--dry-run] [--max-items <n>] [--limit <n>] [--purpose knowledge_index] [--scope local|global|project] [--json]");return}if($==="reindex"){console.log("Usage: knowledge reindex status|enqueue|embeddings|outbox [file|s3://bucket/key] [--full] [--fake] [--scope local|global|project] [--json]");return}if($==="search"){console.log("Usage: knowledge search <query> [--context] [--semantic] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="context"){console.log("Usage: knowledge context pack <query> [--from search|runs|loops] [--max-tokens <n>] [--max-items <n>] [--limit <n>] [--semantic] [--model openai:text-embedding-3-small] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="proposals"){console.log("Usage: knowledge proposals context --from loops --topic <text> [--since <duration|ISO>] [--dedupe] [--max-tokens <n>] [--max-items <n>] [--scope local|global|project] [--json]");return}if($==="web"){console.log("Usage: knowledge web search <query> [--provider openai|anthropic] [--model provider:model] [--domain <domain>] [--file-results] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="ask"||$==="build"){console.log("Usage: knowledge ask|build <prompt> [--generate] [--semantic] [--model default|provider:model] [--approve-write] [--scope local|global|project] [--verbose] [--json]");return}if($==="embeddings"){console.log("Usage: knowledge embeddings status|index|search [query] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="providers"){console.log("Usage: knowledge providers status|models|check [provider|model-alias] [--scope local|global|project] [--json]");return}if($==="safety"){console.log("Usage: knowledge safety status|check|approve|audit|redact [args] [--scope local|global|project] [--json]");return}if($==="events"){console.log("Usage: knowledge events emit|list|replay [args] [--json]");return}if($==="webhooks"){console.log("Usage: knowledge webhooks add|list|remove|test [args] [--json]");return}tp()}function sp($){if($.noColor||process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR)return!0;return process.stdout.isTTY===!0}function h($,_,J){if(_){console.log(JSON.stringify($,null,2));return}if(typeof $==="string"){console.log($);return}if(J?.verbose){console.log(JSON.stringify($,null,2));return}let U=$.message;console.log(U?`${U} -${h6()}`:ep($))}function h6($="full details"){return`Hint: use --verbose for ${$}, or --json for machine-readable output.`}function v$($,_=120){let J=$===null||$===void 0?"":String($).replace(/\s+/g," ").trim();if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-3))}...`}function ep($){if(!$||typeof $!=="object")return String($);let _=$,J=[_.ok===!1?"Result: not ok":"Result: ok"];for(let[U,W]of Object.entries(_).slice(0,8)){if(U==="ok"||U==="message")continue;if(Array.isArray(W))J.push(`${U}: ${W.length} item(s)`);else if(W&&typeof W==="object")J.push(`${U}: ${Object.keys(W).length} field(s)`);else J.push(`${U}: ${v$(W,100)}`)}return J.push(h6()),J.join(` -`)}function $o($){let _=$.mode==="cloud"?"cloud (HTTP /v1 API)":"local (on-box store)",J=$.source.kind==="env"?`selected by ${$.source.name}=${$.source.value}`:`default (no mode var set; set ${v0[0]}=cloud to use the API)`,U=[`Knowledge mode: ${_}`,` ${J}`];if($.pointer_env_present.length>0){let W=$.pointer_ignored?"present but IGNORED for mode selection":"present";U.push(` Pointer env ${W}: ${$.pointer_env_present.join(", ")}`)}if($.network_guard_active)U.push(" Outbound guard: ACTIVE (NODE_ENV=test) \u2014 non-loopback requests are refused.");if($.warning)U.push(` Note: ${$.warning}`);return U.join(` -`)}function _o($){return[`Knowledge paths (${$.scope})`,`Home: ${$.home}`,`SQLite: ${$.knowledge_db_path}`,`JSON store: ${$.json_store_path}`,`Wiki: ${$.wiki_dir}`,h6("config and all paths")].join(` -`)}function aA($){console.log(JSON.stringify($))}function Jo($){let _=$.summary,J=[`Knowledge inventory (${$.scope})`,`Home: ${$.home}`,`JSON store: ${$.paths.json_store_path}${$.paths.json_store_exists?"":" (missing)"}`,`SQLite catalog: ${$.paths.knowledge_db_path}`,`Summary: ${_.legacy_items} item(s), ${_.sources} source(s), ${_.chunks} chunk(s), ${_.wiki_pages} wiki page(s), ${_.indexes} index(es), ${_.storage_objects} artifact(s), ${_.runs} run(s)`],U=(W,X,G)=>{if(X.length===0)return;J.push("",`${W}:`);for(let Q of X.slice(0,$.limit))J.push(`- ${G(Q)}`)};return U("Items",$.items,(W)=>`${W.id}: ${W.title}`),U("Sources",$.sources,(W)=>`${W.kind??"source"} ${W.uri} (${W.chunks??0} chunk(s))`),U("Chunks",$.chunks,(W)=>`${W.kind??"chunk"} ${W.id}: ${W.text_preview??""}`),U("Wiki pages",$.wiki_pages,(W)=>`${W.path}: ${W.title}`),U("Indexes",$.indexes,(W)=>`${W.kind??"index"} ${W.name}${W.shard_key?` (${W.shard_key})`:""}`),U("Artifacts",$.storage_objects,(W)=>`${W.kind??"artifact"} ${W.artifact_uri}`),U("Runs",$.runs,(W)=>`${W.type??"run"} ${W.id}: ${W.status??"unknown"}`),U("Machines",$.machines,(W)=>`${W.machine_id}${W.workspace_home?` ${W.workspace_home}`:""}`),U("Sync conflicts",$.sync_conflicts,(W)=>`${W.id}: ${W.entity_kind}/${W.entity_id} ${W.status}`),J.join(` -`)}function Wo($){let _=Array.isArray($.results)?$.results:[],J=[`${_.length} search result(s) for "${v$($.query,80)}"${$.mode?.semantic?" (semantic enabled)":""}`];for(let U of _.slice(0,$.limit??10)){let W=U.source?.uri??U.provenance?.source_uri??U.artifact?.path??U.artifact?.uri??U.id,X=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(J.push(`- ${U.kind??"result"} ${v$(U.title??U.id,80)}${X}`),W)J.push(` source: ${v$(W,120)}`);if(U.text)J.push(` text: ${v$(U.text,180)}`)}if(_.length===0)J.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(J.push(h6("scores, provenance, and full result objects")),!$.context)J.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return J.join(` -`)}function Uo($){let _=Array.isArray($.excerpts)?$.excerpts:[],J=Array.isArray($.citations)?$.citations:[],U=[`${_.length} context excerpt(s) for "${v$($.query??$.normalized_query,80)}"`];for(let W of _.slice(0,10)){let X=J.find((Y)=>Y.id===W.citation_id||Y.result_id===W.result_id),G=X?.source_uri??X?.artifact_path??W.result_id,Q=typeof W.score==="number"?` score=${W.score.toFixed(3)}`:"";if(U.push(`- ${W.kind??"excerpt"} ${v$(W.id,44)}${Q}`),G)U.push(` source: ${v$(G,120)}`);U.push(` text: ${v$(W.text,220)}`)}return U.push(`Citations: ${J.length}`),U.push(h6("citations, graph, notes, and full excerpts")),U.join(` -`)}function Xo($){let _=Array.isArray($.results)?$.results:[],J=[`${_.length} semantic result(s) for "${v$($.query,80)}"`,`Index: ${$.provider??"unknown"}:${$.model??"unknown"} (${$.dimensions??"?"} dimensions)`];for(let U of _.slice(0,$.limit??10)){let W=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(J.push(`- ${v$(U.chunk_id,44)}${W}`),U.source_uri)J.push(` source: ${v$(U.source_uri,120)}`);if(U.text)J.push(` text: ${v$(U.text,180)}`)}return J.push(h6("provenance and full vector result objects")),J.join(` -`)}function Go($){let _=Array.isArray($.sources)?$.sources:[],J=[`${_.length} web source(s) for "${v$($.query,80)}"`,`Provider: ${$.provider??"unknown"}${$.model?` (${$.model})`:""}`];for(let U of _.slice(0,$.limit??10)){J.push(`- ${v$(U.title??U.url??U.uri??"source",100)}`);let W=U.url??U.uri??U.source_ref;if(W)J.push(` url: ${v$(W,140)}`);if(U.snippet)J.push(` snippet: ${v$(U.snippet,180)}`)}return J.push(h6("provider payloads and filed source refs")),J.join(` -`)}function Qo($){let _=Array.isArray($.machines)?$.machines:[],J=[`${_.length} machine(s) discovered via ${$.source??"unknown"}`,`Adapter: ${$.adapter?.package??"@hasna/machines"} ${$.adapter?.available?"available":"unavailable"}`];for(let U of _.slice(0,10)){let W=U.local?" local":"",X=U.tailscale_dns??U.ssh_target??U.hostname??"";J.push(`- ${v$(U.machine_id??U.id??"unknown",48)}${W}${X?` -> ${v$(X,80)}`:""}`)}if(_.length>10)J.push(`... ${_.length-10} more machine(s).`);if(Array.isArray($.warnings)&&$.warnings.length>0)J.push(`Warnings: ${$.warnings.slice(0,3).join("; ")}`);return J.push(h6("full topology, route hints, and adapter evidence")),J.join(` -`)}function Yo($){let _=Array.isArray($.checks)?$.checks:[],J=_.filter((X)=>X.status==="fail"||X.severity==="fail"),U=_.filter((X)=>X.status==="warn"||X.severity==="warn"),W=[`Machine preflight ${$.ok?"passed":"needs attention"} for ${$.machine_id??$.requested_machine_id??"local"}`,`Checks: ${_.length} total, ${J.length} failed, ${U.length} warning(s)`];for(let X of[...J,...U].slice(0,8))W.push(`- ${X.status??X.severity??"check"} ${v$(X.id??X.kind??"check",72)}: ${v$(X.message??X.detail??"",140)}`);return W.push(h6("all checks and repair hints")),W.join(` -`)}function qo($){return[`Sync status (${$.scope??"scope"})`,`Schema: v${$.sqlite_schema_version??"unknown"}`,`Machines: ${$.machines?.total??0}; snapshots: ${$.snapshots?.total??0}; open conflicts: ${$.conflicts?.open??0}`,`Tables: ${Object.entries($.table_counts??{}).slice(0,8).map(([J,U])=>`${J}=${U}`).join(", ")||"none"}`,h6("registry rows, clocks, snapshots, imports, and conflicts")].join(` -`)}function zo($){let _=Array.isArray($.warnings)?$.warnings:[],J=Array.isArray($.recommended_commands)?$.recommended_commands:[],U=[$.message??`Sync readiness ${$.ok?"ok":"needs attention"}`,`Storage: ${$.storage?.validation?.ok?"ok":"needs attention"}; open-files: ${$.open_files?.ok?"ok":"needs attention"}; open conflicts: ${$.sync?.open_conflicts??0}`];if(_.length>0)U.push(`Warnings: ${_.slice(0,5).join("; ")}`);for(let W of J.slice(0,5))U.push(`- next: ${v$(W.shell_command??W.command?.join(" ")??W.id,160)}`);return U.push(h6("diagnostics, route evidence, and all recommended commands")),U.join(` -`)}function jo($){let _=$.snapshot??{};return[`Sync snapshot ${$.ok?"recorded":"failed"}`,`Snapshot: ${v$(_.id??_.snapshot_id??"unknown",80)} ${_.content_hash?`(${v$(_.content_hash,80)})`:""}`,`Machines upserted: ${$.machines_upserted??0}; machine: ${$.machine_id??_.machine_id??"unknown"}`,h6("snapshot payload and topology evidence")].join(` -`)}function Oo($){let _=Array.isArray($.conflicts)?$.conflicts:[],J=[`${_.length} sync conflict(s)`];for(let U of _.slice(0,10))J.push(`- ${v$(U.id,48)} ${U.status??"unknown"} ${U.entity_kind??""}/${v$(U.entity_id,80)}`);return J.push("Next: use `knowledge sync conflicts show <id> --json` for one conflict."),J.push(h6("full conflict objects")),J.join(` -`)}function Do($){let _=Array.isArray($.machines)?$.machines:[],J=[`${_.length} registered sync machine(s)`];for(let U of _.slice(0,10))J.push(`- ${v$(U.machine_id,48)} ${v$(U.hostname??U.workspace_home??"",100)}`);return J.push(h6("machine registry rows")),J.join(` -`)}function sA($,_){let J=[`Sync ${_} ${$.ok===!1?"needs attention":"completed"}${$.dry_run?" (dry run)":""}`],U=(W,X)=>{if(!X)return;let Q=(Array.isArray(X.tables)?X.tables:[]).reduce((L,N)=>L+(N.inserted??0)+(N.updated??0)+(N.deleted??0),0),Y=X.artifacts?.copied??0,q=Array.isArray(X.errors)?X.errors.length:0;J.push(`${W}: ${Q} table row change(s), ${Y} artifact(s), ${q} error(s)`)};if(U("pull",$.pull),U("push",$.push),Array.isArray($.errors)&&$.errors.length>0)J.push(`Errors: ${$.errors.slice(0,3).map((W)=>v$(W,120)).join("; ")}`);return J.push(h6("per-table rows, artifacts, clocks, and errors")),J.join(` -`)}function Lo($){let _=Array.isArray($.citations)?$.citations:[],J=Array.isArray($.context?.excerpts)?$.context.excerpts:Array.isArray($.excerpts)?$.excerpts:[],U=[$.generated?"Generated answer with citations":"Prepared citation context draft",`Citations: ${_.length}; excerpts: ${J.length}`];if($.answer)U.push(`Answer: ${v$($.answer,500)}`);for(let W of _.slice(0,5))U.push(`- ${v$(W.source_uri??W.ref??W.id,120)}`);return U.push(h6("full answer payload, context, citations, and run ledger")),U.join(` -`)}function Bo($,_){return[`Export preview: ${$.length} item(s) available`,"Default output is compact to avoid terminal/context bloat.","Use --verbose or --json for a JSON object, or --format jsonl for newline-delimited records.",_!=="json"?`Requested format: ${_}`:""].filter(Boolean).join(` -`)}function eA($){return!$||$==="local"||$==="localhost"}function V_($){if(!$.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function Ho($,_){let J=_.sort??"created";if(J!=="created"&&J!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let U=[...$].sort((W,X)=>{if(J==="title")return W.title.localeCompare(X.title);return W.created_at.localeCompare(X.created_at)});if(_.desc)U.reverse();return{sorted:U,sort:J,direction:_.desc?"desc":"asc"}}async function No($){if(await op($))return;let{positional:_,flags:J}=lp($);if(F_("debug","CLI invoked",{command:_[0],flags:{json:J.json,store:J.store}}),J.version){console.log(J.json?JSON.stringify({name:a4.name,version:a4.version},null,2):`${a4.name} ${a4.version}`);return}if(J.completions){let B=J.completions;if(B==="bash")console.log('_knowledge() { local cur; cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive --json --verbose --yes --help --version --desc --page --limit --search --sort --id --store --title --content --url --tag --rev --to --format --completions --purpose --model --dimensions --semantic --context --max-tokens --max-items --from --since --topic --dedupe --generate --approve-write --provider --mode --machine --workspace --peer-workspace --api-url --canonical-example --api-key --email --org --org-id --user-id --owner --domain --file-results --full --dry-run --fake --no-tailscale --no-artifact-content --no-color --scope --tables --archived --include-archived --project --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(B==="zsh")console.log(`#compdef knowledge -_knowledge() { _arguments -C "1: :(add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive)" "(--json)--json" "(--verbose)--verbose" "(--yes)-y" "(--help)--help" "(--version)--version" "(--desc)--desc" "(--archived)--archived" "(--include-archived)--include-archived" "(--semantic)--semantic" "(--context)--context" "(--dedupe)--dedupe" "(--generate)--generate" "(--approve-write)--approve-write" "(--canonical-example)--canonical-example" "(--file-results)--file-results" "(--full)--full" "(--dry-run)--dry-run" "(--fake)--fake" "(--no-tailscale)--no-tailscale" "(--no-artifact-content)--no-artifact-content" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(-s --search)"{-s,--search}"[search text]:text:" "(--sort)--sort"{created,title}:" "(--id)--id[item id]:id:" "(--store)--store[store path]:path:" "(--title)--title[new title]:" "(--content)--content[new content]:" "(--url)--url[source url]:" "(-t --tag)"{-t,--tag}"[tag]:tag:" "(--format)--format[json|jsonl]:" "(--completions)--completions[output completions]:shell:(bash zsh fish):" "(--purpose)--purpose[purpose]:" "(--model)--model[model ref]:" "(--dimensions)--dimensions[embedding dimensions]:number:" "(--max-tokens)--max-tokens[token budget]:number:" "(--max-items)--max-items[item budget]:number:" "(--from)--from"{search,loops,runs}:" "(--to)--to[diff target: version number or current]:" "(--rev)--rev[entry version for diff]:number:" "(--since)--since[duration or ISO time]:" "(--topic)--topic[topic text]:" "(--provider)--provider[provider]:" "(--mode)--mode"{local,hosted}:" "(--machine)--machine[machine id or SSH alias]:" "(--workspace)--workspace[repo workspace path]:path:" "(--peer-workspace)--peer-workspace[peer repo or knowledge home path]:path:" "(--api-url)--api-url[hosted API URL]:" "(--api-key)--api-key[hosted API key]:" "(--email)--email[email]:" "(--org)--org[org slug]:" "(--org-id)--org-id[org id]:" "(--user-id)--user-id[user id]:" "(--owner)--owner[provenance owner]:" "(--domain)--domain[domain]:" "(--project)--project[project id/name/slug]:" "(--source-ref)--source-ref[source ref]:" "(--no-color)--no-color[disable color]" "(--scope)--scope"{local,global,project}:" "(--tables)--tables[comma-separated DB sync tables]:" }; _knowledge`);else if(B==="fish")console.log('complete -c knowledge -f; complete -c knowledge -a "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive"; complete -c knowledge -l json; complete -c knowledge -l verbose; complete -c knowledge -l yes -s y; complete -c knowledge -l help -s h; complete -c knowledge -l version -s v; complete -c knowledge -l desc; complete -c knowledge -l archived; complete -c knowledge -l include-archived; complete -c knowledge -l semantic; complete -c knowledge -l context; complete -c knowledge -l max-tokens; complete -c knowledge -l max-items; complete -c knowledge -l from -a "search loops runs"; complete -c knowledge -l to; complete -c knowledge -l rev; complete -c knowledge -l since; complete -c knowledge -l topic; complete -c knowledge -l dedupe; complete -c knowledge -l generate; complete -c knowledge -l approve-write; complete -c knowledge -l allow-global; complete -c knowledge -l canonical-example; complete -c knowledge -l provider; complete -c knowledge -l mode; complete -c knowledge -l machine; complete -c knowledge -l workspace; complete -c knowledge -l peer-workspace; complete -c knowledge -l api-url; complete -c knowledge -l api-key; complete -c knowledge -l email; complete -c knowledge -l org; complete -c knowledge -l org-id; complete -c knowledge -l user-id; complete -c knowledge -l owner; complete -c knowledge -l domain; complete -c knowledge -l project; complete -c knowledge -l contract; complete -c knowledge -l source-ref; complete -c knowledge -l file-results; complete -c knowledge -l full; complete -c knowledge -l dry-run; complete -c knowledge -l fake; complete -c knowledge -l no-tailscale; complete -c knowledge -l no-artifact-content; complete -c knowledge -s p -l page; complete -c knowledge -s l -l limit; complete -c knowledge -s s -l search; complete -c knowledge -l sort; complete -c knowledge -l id; complete -c knowledge -l store; complete -c knowledge -l title; complete -c knowledge -l content; complete -c knowledge -l url; complete -c knowledge -s t -l tag; complete -c knowledge -l format; complete -c knowledge -l completions; complete -c knowledge -l purpose; complete -c knowledge -l model; complete -c knowledge -l dimensions; complete -c knowledge -l no-color; complete -c knowledge -l scope -a "local global project"; complete -c knowledge -l tables');else throw Error("Invalid --completions value. Use 'bash', 'zsh', or 'fish'.");return}let U=np(_[0]),W=1,X=_.length>1||/\s/.test(U);if(pp()&&U&&!_b.includes(U)&&X)U="ask",W=0;if(!U||J.help||U==="help"){let B=U==="help"?_[1]:U||_[1];ap(B);return}if(U==="mode"){let B=SN(process.env);h(J.json||J.verbose?{ok:!0,...B}:$o(B),J.json,J);return}TN(process.env,{storePathOverridden:Boolean(J.store)});let G=U==="project-panel"||U==="app-wiki"?J.scope??"project":J.scope,Q=r5({scope:G});if(U==="storage"){let B=_[1]??"status";if(B==="import-legacy"){if(J.scope&&J.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let H=MQ({dryRun:J.dryRun});if(h(H,J.json),!H.ok)process.exitCode=1;return}if(B==="migrate-legacy-path"||B==="migrate-legacy"||B==="migrate-path"){let H=Q.migrateLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}if(B==="merge-legacy-path"||B==="merge-legacy"||B==="merge-path"){let H=Q.mergeLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}}let Y=Boolean(J.store),q=J.store;if(!q)if(G==="project"||G==="local")q=Q.workspace.jsonStorePath;else q=z9();if(!Y&&(U==="ask"||U==="build")&&!V1())uW(q);let L=P9({storePath:q,storePathOverridden:Y});if(U==="inventory"){let B=await Q.resolveInventory({limit:J.limit,includeArchived:J.includeArchived||J.archived,storePath:V1()?void 0:q});h(J.json||J.verbose?B:Jo(B),J.json,J);return}if(U==="project-panel"){let B=J.project??_[1];if(!B)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let H=await JA(B,{service:Q,limit:J.limit,storePath:V1()?void 0:q,includeArchived:J.includeArchived||J.archived});h(J.json||J.contract?H:WA(H),J.json||J.contract);return}if(U==="paths"){let B=Q.paths();h(J.json||J.verbose?B:_o(B),J.json,J);return}if(U==="setup"){let B=Q.setup({mode:J.mode,apiUrl:J.apiUrl,canonicalExample:J.canonicalExample});h(B,J.json,J);return}if(U==="auth"){let B=_[1]??"whoami";if(B==="whoami"||B==="status"){let H=Q.authStatus(process.env);h({ok:!0,...H,message:H.authenticated?`Authenticated via ${H.source}`:"Not authenticated"},J.json,J);return}if(B==="login"){let H=J.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!H)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let V=Q.saveAuth({apiKey:H,email:J.email,orgSlug:J.org,orgId:J.orgId,userId:J.userId,apiUrl:J.apiUrl},process.env);h({ok:!0,authenticated:!0,email:V.email??null,org_slug:V.org_slug??null,api_url:V.api_url??Q.authStatus(process.env).api_url,auth_path:Q.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${V.email??"API key"}`},J.json,J);return}if(B==="logout"){let H=Q.clearAuth(process.env);h({ok:!0,removed:H,message:H?"Removed hosted credentials":"No hosted credentials found"},J.json,J);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(U==="storage"){let B=_[1]??"status";if(B==="status"){let H=Q.storageContract(),V=Q.validateStorage();h({ok:V.ok,...H,validation:V,message:`${H.storage_type} artifact storage at ${H.artifact_store.uri_prefix}`},J.json,J);return}if(B==="validate"){let H=Q.validateStorage();if(h({ok:H.ok,validation:H,message:H.ok?"Storage contract valid":`Storage contract invalid: ${H.errors.join("; ")}`},J.json,J),!H.ok)process.exitCode=1;return}if(B==="repair-artifact-keys"||B==="repair-keys"){let H=Q.repairArtifactManifestKeys({approveWrite:J.approveWrite,approvedBy:J.approvedBy,dryRun:J.dryRun});h(H,J.json,J);return}if(B==="migrate-legacy-path"||B==="migrate-legacy"||B==="migrate-path"){let H=Q.migrateLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}if(B==="merge-legacy-path"||B==="merge-legacy"||B==="merge-path"){let H=Q.mergeLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid storage action. Use 'status', 'validate', 'repair-artifact-keys', 'migrate-legacy-path', 'merge-legacy-path', or 'import-legacy'.")}if(U==="machines"){let B=_[1]??"topology";if(B==="topology"||B==="status"){let H=await Q.machineTopology({includeTailscale:J.tailscale!==!1});h(J.json||J.verbose?H:Qo(H),J.json,J);return}if(B==="preflight"||B==="check"){let H=_[2]??J.machine??"local",V=J.workspace??process.cwd(),R=await Q.machinePreflight({machineId:H,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:a4.name,command:"knowledge",expectedVersion:a4.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:V,expectedPackageName:a4.name,expectedVersion:a4.version,required:!0}]});if(h(J.json||J.verbose?R:Yo(R),J.json,J),!R.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(U==="sync"){let B=_[1]??"status",H=J.tables?J.tables.split(",").map((V)=>V.trim()).filter(Boolean):void 0;if(B==="status"){let V=Q.syncStatus();h(J.json||J.verbose?V:qo(V),J.json,J);return}if(B==="doctor"||B==="readiness"||B==="preflight"){let V=await Q.syncDoctor({machine:J.machine??null,peerWorkspace:J.peerWorkspace??null,includeTailscale:J.tailscale!==!1,tables:H}),R={package:{name:a4.name,version:a4.version},...V};if(h(J.json||J.verbose?R:zo(R),J.json,J),!V.ok&&!J.json)process.exitCode=1;return}if(B==="snapshot"||B==="record"){let V=await Q.createSyncSnapshot({includeTailscale:J.tailscale!==!1,machineId:J.machine});h(J.json||J.verbose?V:jo(V),J.json,J);return}if(B==="conflicts"||B==="conflict"){let V=_[2];if(V==="show"||V==="get"){let K=_[3]??J.id;if(!K)throw Error("Usage: knowledge sync conflicts show <id>");let w=Q.syncConflict(K);h({ok:!0,conflict:w,message:`Sync conflict ${K}`},J.json,J);return}if(V==="propose"||V==="proposal"){let K=_[3]??J.id;if(!K)throw Error("Usage: knowledge sync conflicts propose <id>");h(J.mode==="ai"?await Q.proposeSyncConflictResolutionWithAi({id:K,modelRef:J.model,fake:J.fake}):Q.proposeSyncConflictResolution(K),J.json,J);return}if(V==="resolve"){let K=_[3]??J.id;if(!K)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let w=Q.resolveSyncConflict({id:K,strategy:J.strategy,approvedBy:J.approvedBy,approveWrite:J.approveWrite,proposedPatchUri:J.patchUri});if(h(w,J.json,J),!w.ok&&!J.json)process.exitCode=1;return}let R=Q.syncConflicts({status:V,limit:J.limit}),M={ok:!0,conflicts:R,message:`${R.length} sync conflict(s)`};h(J.json||J.verbose?M:Oo(M),J.json,J);return}if(B==="machines"||B==="registry"){let V=Q.syncMachines(),R={ok:!0,machines:V,message:`${V.length} registered sync machine(s)`};h(J.json||J.verbose?R:Do(R),J.json,J);return}if(B==="export"){let V=Q.exportSyncBundle({machineId:J.machine??null,tables:H,includeArtifactContent:J.artifactContent!==!1});h(V,!0);return}if(B==="import"){let V=await Bun.stdin.text();if(!V.trim())throw Error("Usage: knowledge sync import < bundle.json");let R=await Q.importSyncBundle({bundle:JSON.parse(V),dryRun:J.dryRun,direction:"import",machineId:J.machine??null});h(J.json||J.verbose?R:sA(R,B),J.json,J);return}if(B==="dry-run"||B==="pull"||B==="push"||B==="sync"){if(!J.peerWorkspace&&eA(J.machine))throw Error(`Usage: knowledge sync ${B} --peer-workspace <repo-or-knowledge-home> [--scope project] -Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let V=B==="dry-run"?"both":B==="sync"?"both":B,R=!eA(J.machine)?await Q.syncRemotePeer({direction:V,machine:J.machine,peerWorkspace:J.peerWorkspace,tables:H,dryRun:J.dryRun===!0||B==="dry-run",includeArtifactContent:J.artifactContent!==!1,includeTailscale:J.tailscale!==!1}):await Q.syncPeer({peerWorkspace:J.peerWorkspace,direction:V,dryRun:J.dryRun===!0||B==="dry-run",tables:H,includeArtifactContent:J.artifactContent!==!1,machineId:J.machine??null});if(h(J.json||J.verbose?R:sA(R,B),J.json,J),!R.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid sync action. Use 'status', 'doctor', 'snapshot', 'conflicts', 'machines', 'dry-run', 'pull', 'push', 'sync', 'export', or 'import'.")}if(U==="db"){let B=_[1]??"init";if(B==="init"){let H=Q.initDb();h({ok:!0,...H,message:`Initialized ${H.path}`},J.json,J);return}if(B==="stats"){let H=Q.dbStats();h({ok:!0,path:Q.workspace.knowledgeDbPath,...H,message:`knowledge.db schema v${H.schema_version}`},J.json,J);return}if(B==="storage"){if((_[2]??"status")==="status"){let V=aL({scope:J.scope});h({ok:!0,...V,message:`knowledge.db storage mode ${V.mode}`},J.json,J);return}throw Error("Invalid db storage action. Only 'status' is supported. The 'push'/'pull'/'sync' Postgres sync commands were removed (DSN-on-client is forbidden); use the cloud API flip instead.")}throw Error("Invalid db action. Use 'init', 'stats', or 'storage'.")}if(U==="app-wiki"){let B=_[1]??"init";if(B==="paths"||B==="status"){h({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...Q.paths()},J.json);return}if(B==="init"||B==="open"){let H=await Q.initAppWiki({allowGlobal:J.allowGlobal});h(H,J.json);return}if(B==="note"||B==="notes"){let H=_[2]??"list";if(H==="add"||H==="create"){let V=J.title??_[3],R=J.content??_.slice(4).join(" ");if(!V||!R)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let M=await Q.addAppWikiNote({title:V,content:R,tags:J.tag,sourceRefs:J.sourceRef,allowGlobal:J.allowGlobal});h(M,J.json);return}if(H==="list"||H==="ls"){let V=Q.listAppWikiNotes({limit:J.limit});h({ok:!0,scope:Q.scope,home:Q.workspace.home,notes:V,message:`${V.length} app wiki note(s)`},J.json);return}if(H==="get"||H==="show"){let V=_[3]??J.id;if(!V)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let R=await Q.getAppWikiNote(V,{includeContent:!0});if(!R)throw Error(`App wiki note not found: ${V}`);h(R,J.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(B==="source"||B==="sources"){let H=_[2]??"add";if(H!=="add"&&H!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let V=_[3]??J.sourceRef?.[0];if(!V)throw Error("Usage: knowledge app-wiki source add <source-ref>");let R=await Q.addAppWikiSourceRef({sourceRef:V,purpose:J.purpose,allowGlobal:J.allowGlobal});h({ok:!0,...R,message:`Added app wiki source ${R.source_ref}`},J.json);return}if(B==="search"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge app-wiki search <query>");let V=await Q.searchAppWiki({query:H,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V,message:`${V.results.length} app wiki result(s)`},J.json);return}if(B==="query"||B==="context"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge app-wiki query <query>");let V=await Q.queryAppWiki({query:H,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V,message:`${V.excerpts.length} app wiki excerpt(s)`},J.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(U==="wiki"){let B=_[1]??"init";if(B==="init"){let H=await Q.initWiki();h({ok:!0,...H,message:`Initialized wiki layout in ${Q.workspace.home}`},J.json,J);return}if(B==="compile"){let H=_.slice(2),V=H.filter((K)=>/^(open-files|file|s3|https?):\/\//.test(K)),R=H.filter((K)=>!/^(open-files|file|s3|https?):\/\//.test(K)).join(" "),M=await Q.compileWiki({title:J.title,query:R||J.search,sourceRefs:V.length>0?V:void 0,limit:J.limit});h({ok:!0,...M,message:`Compiled wiki page ${M.path}`},J.json,J);return}if(B==="file-answer"||B==="answer"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!J.content)throw Error("Missing --content <answer> for wiki file-answer.");let V=await Q.fileAnswer({prompt:H,answer:J.content,approveWrite:J.approveWrite,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V},J.json,J);return}if(B==="lint"){let H=Q.lintWiki();h({ok:H.ok,...H,message:H.ok?"Wiki lint passed":`Wiki lint found ${H.issue_count} issue(s)`},J.json,J);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(U==="safety"){let B=_[1]??"status",H=Q.ensureWorkspace(),V=Q.safetyPolicy();Q.initDb();let R=i(H.knowledgeDbPath);try{if(B==="status"){h({ok:!0,mode:V.mode,workspace:H.home,allow_write_roots:V.allowWriteRoots,read_only_source_access:V.readOnlySourceAccess,network:V.network,redaction:V.redaction,approvals:V.approvals,message:`Safety policy: ${V.mode}`},J.json,J);return}if(B==="check"){let M=_[2]??"generated_write",K=_[3]??null,w;try{if(M==="web_search")wJ(V),w={action:M,target_uri:K,approval_required:!1,approved:!0,decision:"allow"};else if(M==="s3_read"){if(!K)throw Error("safety check s3_read requires an s3:// target.");K1(K,V),w={action:M,target_uri:K,approval_required:!1,approved:!0,decision:"allow"}}else w=H3(R,V,M,K);O6(R,{event_type:"safety_check",action:M,target_uri:K,decision:w.decision==="allow"?"allow":"requires_approval",metadata:w}),h({ok:!0,...w,message:`Safety check ${w.decision}`},J.json,J);return}catch(b){throw O6(R,{event_type:"safety_check",action:M,target_uri:K,decision:"deny",metadata:{error:b instanceof Error?b.message:String(b)}}),b}}if(B==="approve"){let M=_[2]??"generated_write",K=_[3]??null,w=B3(R,{action:M,target_uri:K,reason:"local-cli approval",metadata:{scope:J.scope??"global"}});O6(R,{event_type:"approval",action:M,target_uri:K,decision:"allow",metadata:{approval_id:w.id}}),h({ok:!0,...w,action:M,target_uri:K,message:`Approved ${M}`},J.json,J);return}if(B==="audit"){let M=R.query("SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT 50").all().map((K)=>({id:K.id,event_type:K.event_type,action:K.action,target_uri:K.target_uri,decision:K.decision,metadata:JSON.parse(K.metadata_json),created_at:K.created_at}));h({ok:!0,events:M,message:`${M.length} audit event(s)`},J.json,J);return}if(B==="redact"){let M=_.slice(2).join(" ");if(!M)throw Error("Usage: knowledge safety redact <text>");let K=i6(M,V);if(K.findings.length>0)v9(R,{source_uri:"safety://redact",findings:K.findings,metadata:{command:"safety redact"}});O6(R,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:K.findings.length>0?"redacted":"allow",metadata:{findings:K.findings.length}}),h({ok:!0,text:K.text,findings:K.findings,message:`Redacted ${K.findings.length} finding(s)`},J.json,J);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{R.close()}}if(U==="source"){if((_[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let H=_[2];if(!H)throw Error("Usage: knowledge source resolve <source-ref>");let V=await Q.resolveSource(H,{purpose:J.purpose,limit:J.limit});h({ok:!0,...V,message:V.resolved?`Resolved ${V.source_ref} (${V.content.chunks_returned}/${V.content.chunks_total} chunks)`:`Source not indexed: ${H}`},J.json,J);return}if(U==="ingest"){let B=_[1]??"";if(B==="rules"||B==="global-rules"||B==="agent-rules"){let H=await Q.importRulesProvenance({root:J.workspace??process.cwd(),owner:J.owner,dryRun:J.dryRun===!0,maxItems:J.maxItems,limit:J.limit});h({ok:!0,...H},J.json);return}if(B==="manifest"){let H=_[2];if(!H)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let V=await Q.ingestManifest(H);h({ok:!0,...V,message:`Ingested ${V.items_seen} manifest item(s)`},J.json,J);return}if(B==="source"){let H=_[2];if(!H)throw Error("Usage: knowledge ingest source <source-ref>");let V=await Q.ingestSource(H,J.purpose);h({ok:!0,...V,message:`Ingested source ${V.source_ref} (${V.chunks_inserted} chunks)`},J.json,J);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(U==="reindex"){let B=_[1]??"status";if(B==="status"){let H=Q.reindexHealth({modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`${H.missing_embeddings} chunk(s) missing embeddings`},J.json,J);return}if(B==="enqueue"){let H=Q.enqueueReindex({modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Queued ${H.enqueued} embedding refresh item(s)`},J.json,J);return}if(B==="embeddings"){let H=await Q.refreshEmbeddings({full:J.full,limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Embedded ${H.indexed.chunks_embedded} chunk(s)`},J.json,J);return}if(B==="outbox"){let H=_[2];if(!H)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let V=await Q.consumeOutbox(H);h({ok:!0,...V,message:`Consumed ${V.events_seen} outbox event(s)`},J.json,J);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(U==="embeddings"){let B=_[1]??"status";if(B==="status"){let H=Q.embeddingStatus();h({ok:!0,...H,message:`${H.total_vector_entries} vector index entries`},J.json,J);return}if(B==="index"){let H=await Q.indexEmbeddings({limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Embedded ${H.chunks_embedded} chunk(s)`},J.json,J);return}if(B==="search"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge embeddings search <query>");let V=await Q.semanticSearch({query:H,limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake}),R={ok:!0,...V,message:`${V.results.length} semantic result(s)`};h(J.json||J.verbose?R:Xo(R),J.json,J);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(U==="context"){if((_[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let H=J.from??"search";if(!["search","loops","runs"].includes(H))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let V=_.slice(2).join(" ")||J.topic||"",R=await Q.contextPack({source:H,purpose:H==="loops"||H==="runs"?"proposal":"agent_context",query:V,topic:J.topic,since:J.since,dedupe:J.dedupe,maxTokens:J.maxTokens,maxItems:J.maxItems,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q});aA({ok:!0,...R,message:R.message});return}if(U==="proposals"){if((_[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let H=J.from??"loops";if(!["loops","runs"].includes(H))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let V=J.topic??_.slice(2).join(" ");if(!V.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let R=await Q.contextPack({source:H,purpose:"proposal",query:V,topic:V,since:J.since,dedupe:J.dedupe??!0,maxTokens:J.maxTokens,maxItems:J.maxItems,limit:J.limit});aA({ok:!0,...R,message:R.message});return}if(U==="search"){let B=_.slice(1).join(" ");if(!B)throw Error("Usage: knowledge search <query>");if(J.context){let R=await Q.retrieveContext({query:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q}),M={ok:!0,...R,message:`${R.excerpts.length} context excerpt(s)`};h(J.json||J.verbose?M:Uo(M),J.json,J);return}let H=await Q.search({query:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q}),V={ok:!0,...H,message:`${H.results.length} search result(s)`};h(J.json||J.verbose?V:Wo(V),J.json,J);return}if(U==="web"){if((_[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge web search <query>");let V=await Q.webSearch({query:H,limit:J.limit,modelRef:J.model,provider:J.provider,domains:J.domain,fake:J.fake,fileResults:J.fileResults}),R={ok:!0,...V,message:`${V.sources.length} web source(s)`};h(J.json||J.verbose?R:Go(R),J.json,J);return}if(U==="ask"||U==="build"){let B=_.slice(W).join(" ");if(!B)throw Error("Usage: knowledge ask <prompt>");let H=await Q.runPrompt({prompt:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,generate:J.generate,approveWrite:J.approveWrite,legacyStorePath:q}),V={ok:!0,...H,message:H.generated?"Generated answer with citations":"Prepared citation context draft"};h(J.json||J.verbose?V:Lo(V),J.json,J);return}if(U==="providers"){let B=_[1]??"status";if(B==="status"){let H=Q.providerStatus(),V=H.providers.filter((R)=>R.configured).length;h({ok:!0,...H,message:`${V}/${H.providers.length} provider credential(s) configured`},J.json,J);return}if(B==="models"){let H=Q.modelRegistry();h({ok:!0,models:H,message:`${H.length} model alias(es)`},J.json,J);return}if(B==="check"){let H=_[2]??"default",V=y4(H,Q.config()),R=E6(V),M=A2(R.provider,Q.config());h({ok:!0,target:H,model_ref:V,provider:R.provider,model:R.model,credential:M,message:`${R.provider} credentials configured`},J.json,J);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(U==="add"){let B=_[1],H=_[2];if(!B||!H)throw Error("Usage: knowledge add <title> <content>");let V=await L.create({title:B,content:H,url:J.url??null,tags:J.tag??[]});F_("info","Item added",{id:V.id,title:V.title,tags:V.tags?.length??0,transport:L.kind}),h({ok:!0,item:V,message:`Added ${V.id}`},J.json,J);return}if(U==="list"){if(J.format!==void 0&&J.format!=="table"&&J.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");let B=await L.listAll(),H=Number.isFinite(J.page)&&J.page>0?J.page:1,V=Number.isFinite(J.limit)&&J.limit>0?J.limit:20,R=J.search?String(J.search).toLowerCase():"",M=(J.tagRaw??J.tag??[]).map((M$)=>({whole:M$.trim().toLowerCase(),parts:M$.split(",").map((b6)=>b6.trim().toLowerCase()).filter((b6)=>b6.length>0)})),K=J.tag?.length?J.tag.map((M$)=>M$.toLowerCase()).join(","):"none",w=J.format==="table"||!J.json&&!J.format&&sp(J),b=J.json||J.format==="json",I=B.items;if(J.archived)I=I.filter((M$)=>M$.archived===!0);else if(!J.includeArchived)I=I.filter((M$)=>!M$.archived);if(R)I=I.filter((M$)=>M$.title.toLowerCase().includes(R)||M$.content.toLowerCase().includes(R));if(M.length>0)I=I.filter((M$)=>{let b6=new Set((M$.tags??[]).map((j6)=>j6.toLowerCase()));return M.every(({whole:j6,parts:J6})=>j6.length>0&&b6.has(j6)||J6.every((R6)=>b6.has(R6)))});let{sorted:v,sort:g,direction:x}=Ho(I,J),Y6=(H-1)*V,l$=v.slice(Y6,Y6+V),q6=Math.max(1,Math.ceil(v.length/V)),F6={ok:!0,page:H,limit:V,total:v.length,total_pages:q6,sort:g,direction:x,items:l$,store_exists:B.exists};if(b){h(F6,!0);return}if(J.verbose){h(F6,!1,J);return}if(l$.length===0){h(`No items found (search=${R||"none"}, tag=${K})`,!1);return}if(w){let M$=(j6)=>j6,b6=`${M$("ID")} ${M$("TITLE")} ${M$("CREATED")} ${M$("URL")} ${M$("TAGS")}`;console.log(b6);for(let j6 of l$)console.log(`${j6.id} ${M$(v$(j6.title,80))} ${j6.created_at} ${j6.url?M$(v$(j6.url,90)):""} ${j6.tags?.length?M$(v$(`[${j6.tags.join(", ")}]`,80)):""}`);console.log(`Page ${H}/${q6} | showing ${l$.length} of ${v.length} | sort=${g} ${x} | search=${R||"none"} | tag=${K}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let M$ of l$)console.log(`${M$.id} ${v$(M$.title,80)} ${M$.created_at}${M$.url?` ${v$(M$.url,90)}`:""}${M$.tags?.length?` ${v$(`[${M$.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${H}/${q6} | showing ${l$.length} of ${v.length} | sort=${g} ${x} | search=${R||"none"} | tag=${K}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(U==="get"){V_(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);h({ok:!0,item:B,store_exists:L.exists,message:`${B.id}: ${B.title}`},J.json,J);return}if(U==="versions"){V_(J);let B=Number.isFinite(J.page)&&J.page>0?J.page:1,H=Number.isFinite(J.limit)&&J.limit>0?J.limit:void 0,V=await L.listVersions(J.id,{limit:H,offset:(B-1)*(H??50)});if(!V)throw Error(`Item not found: ${J.id}`);let R={ok:!0,id:V.item_id,current_version:V.current_version,total:V.total,page:B,store:L.location,versions:V.items,message:V.total===0?`${V.item_id} is at version ${V.current_version} with no retained prior versions`:`${V.item_id} is at version ${V.current_version}; ${V.total} prior version(s) retained`};if(J.json||J.verbose){h(R,J.json,J);return}console.log(R.message);for(let M of V.items){let K=M.actor?` by ${M.actor}`:"",w=M.reason?` (${M.reason})`:"";console.log(`v${M.version} ${M.valid_to}${K}${w} ${M.content_bytes} bytes ${M.content_hash.slice(0,12)}`)}if(V.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(U==="diff"){V_(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);if(J.rev!==void 0&&(J.from!==void 0||J.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let H=()=>({title:B.title,content:B.content,url:B.url,tags:B.tags??[],metadata:B.metadata??{},archived:B.archived??!1}),V=`v${B.version??"?"} (current)`,R=async(v)=>{if(v==="current")return{label:V,snapshot:H()};let g=Number(v);if(!Number.isInteger(g)||g<1)throw Error(`Not a version number: ${v}`);if(B.version!==void 0&&g===B.version)return{label:V,snapshot:H()};let x=await L.getVersion(B.id,g);if(!x)throw Error(`No version ${g} retained for ${B.id} (it is at version ${B.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${x.version}`,snapshot:{title:x.title,content:x.content,url:x.url,tags:x.tags,metadata:x.metadata,archived:x.archived}}},M,K;if(J.rev!==void 0){if(!Number.isInteger(J.rev)||J.rev<1)throw Error("--rev must be a positive version number.");if(J.rev===1)throw Error("Version 1 has no predecessor to diff against.");M=String(J.rev-1),K=String(J.rev)}else if(J.from!==void 0||J.to!==void 0){if(J.from===void 0||J.to===void 0)throw Error("--from and --to must be given together.");M=J.from,K=J.to}else{let v=await L.listVersions(B.id,{limit:1});if(!v)throw Error(`Item not found: ${J.id}`);if(v.items.length===0)throw Error(`${B.id} is at version ${v.current_version} with no retained prior versions to diff against.`);M=String(v.items[0].version),K="current"}let w=await R(M),b=await R(K),I=xN(w.snapshot,b.snapshot);if(J.json||J.verbose){h({ok:!0,id:B.id,from:w.label,to:b.label,...I},J.json,J);return}console.log(uN(I,`${B.id} ${w.label}`,`${B.id} ${b.label}`));return}if(U==="update"){V_(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H={};if(J.title!==void 0)H.title=J.title;if(J.content!==void 0)H.content=J.content;if(J.url!==void 0)H.url=J.url;let V;if(J.tag!==void 0){if(V=tA(B.tags,J.tag),V.length>0)H.tags=[...B.tags??[],...V]}let R=await L.update(B.id,H,{expectedVersion:B.version});h(OB({ok:!0,item:R},`Updated ${R?.id??B.id}`,V),J.json,J);return}if(U==="archive"||U==="restore"){V_(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H=await L.update(B.id,{archived:U==="archive"},{expectedVersion:B.version});h({ok:!0,item:H,message:`${U==="archive"?"Archived":"Restored"} ${H?.id??B.id}`},J.json,J);return}if(U==="untag"){if(V_(J),!J.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H=B.tags??[],V=new Set(H.map((g)=>g.toLowerCase())),R=new Set;for(let g of J.tagRaw??J.tag){let x=g.trim().toLowerCase();if(x.length>0&&V.has(x)){R.add(x);continue}for(let Y6 of g.split(",").map((l$)=>l$.trim().toLowerCase()).filter((l$)=>l$.length>0))R.add(Y6)}let M=H.filter((g)=>!R.has(g.toLowerCase())),K=H.length-M.length,w=[...R].filter((g)=>!V.has(g));if(K===0)throw Error(`No matching tag on ${B.id}: ${w.map((g)=>JSON.stringify(g)).join(", ")} not in [${H.map((g)=>JSON.stringify(g)).join(", ")}]`);let b=await L.update(B.id,{tags:M},{expectedVersion:B.version}),I=w.length>0?` (not found: ${w.map((g)=>JSON.stringify(g)).join(", ")})`:"",v={ok:!0,item:b,removed:K,message:`Removed ${K} tag${K===1?"":"s"} from ${b?.id??B.id}${I}`};if(w.length>0)v.not_found=w;h(v,J.json,J);return}if(U==="upsert"){let B=J.title??_[1],H=J.content??_[2],V=J.id?await L.get(J.id):null;if(!V){if(!B||!H)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let w=await L.create({id:J.id,title:B,content:H,url:J.url??null,tags:J.tag??[]});h(OB({ok:!0,created:!0,item:w},`Upserted ${w.id}`,J.tag),J.json,J);return}let R={};if(B!==void 0)R.title=B;if(H!==void 0)R.content=H;if(J.url!==void 0)R.url=J.url;let M;if(J.tag!==void 0){if(M=tA(V.tags,J.tag),M.length>0)R.tags=[...V.tags??[],...M]}let K=await L.update(V.id,R,{expectedVersion:V.version});h(OB({ok:!0,created:!1,item:K},`Upserted ${K?.id??V.id}`,M),J.json,J);return}if(U==="delete"){if(V_(J),!J.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await L.delete(J.id))throw Error(`Item not found: ${J.id}`);F_("info","Item deleted",{id:J.id,transport:L.kind}),h({ok:!0,deleted_id:J.id,message:`Deleted ${J.id}`},J.json,J);return}if(U==="export"){let B=J.format??"json";if(B!=="json"&&B!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let H=await L.listAll();if(B==="jsonl")for(let V of H.items)console.log(JSON.stringify(V));else if(J.json||J.format==="json"||J.verbose)h({ok:!0,items:H.items,store_exists:H.exists},J.json||J.format==="json",J);else h(Bo(H.items,B),!1);return}if(U==="prune"){if(!J.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:B}=await L.listAll(),H=J.olderThan!==void 0?new Date(Date.now()-J.olderThan*86400000):null,V=B.filter((K)=>H!==null&&new Date(K.created_at)<H||J.empty&&K.content.trim().length===0),R=await L.deleteMany(V.map((K)=>K.id)),M=B.length-R;F_("info","Prune completed",{pruned:R,remaining:M,transport:L.kind}),h({ok:!0,pruned:R,remaining:M,message:`Pruned ${R} item(s)`},J.json,J);return}if(U==="dedupe"){if(!J.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:B}=await L.listAll(),H=new Set,V=[];for(let K of B){let w=`${K.title}\x00${K.content}`;if(H.has(w))V.push(K);else H.add(w)}let R=await L.deleteMany(V.map((K)=>K.id)),M=B.length-R;F_("info","Dedupe completed",{removed:R,remaining:M,transport:L.kind}),h({ok:!0,removed:R,remaining:M,message:`Dedupe removed ${R} duplicate(s)`},J.json,J);return}if(U==="stats"){let B=await L.listAll(),H=B.items.filter((g)=>!g.archived),V=H.length,R=B.items.length-V,M=H.filter((g)=>g.url).length,K=H.filter((g)=>g.tags&&g.tags.length>0).length,w=V>0?H.map((g)=>g.created_at).sort()[0]:null,b=V>0?H.map((g)=>g.created_at).sort()[V-1]:null,I={};for(let g of H)for(let x of g.tags||[])I[x]=(I[x]||0)+1;let v=Object.entries(I).sort((g,x)=>x[1]-g[1]).slice(0,5).map(([g,x])=>({tag:g,count:x}));h({ok:!0,total:V,archived:R,with_url:M,with_tags:K,oldest:w,newest:b,top_tags:v,store_exists:B.exists,message:`${V} items | ${M} with URL | ${K} with tags`},J.json,J);return}let N=rp(_[0]),F=N?` Did you mean '${N}'?`:"";throw F_("warn","Unknown command",{input:_[0],suggestion:N}),Error(`Unknown command: ${_[0]}.${F} Run 'knowledge --help' for available commands.`)}function Vo($,_){let J=$ instanceof Error?$.message:String($);if(F_("debug","CLI error",{message:J,stack:$ instanceof Error?$.stack:void 0}),console.error(`Error: ${J}`),_.includes("--json"))h({ok:!1,error:J,message:J},!0);process.exitCode=1}if(import.meta.main){let $=process.argv.slice(2);No($).catch((_)=>Vo(_,$))}export{rp as suggestCommand,Ho as sortItems,No as run,lp as parseArgs,Vo as emitCliError}; +Remote machine sync resolves peer paths through @hasna/machines when --peer-workspace is omitted.`);return}if($==="db"){console.log("Usage: knowledge db init|stats|storage status [--scope local|global|project] [--json]");return}if($==="wiki"){console.log("Usage: knowledge wiki init|compile|file-answer|lint [query|prompt] [--title <title>] [--content <answer>] [--approve-write] [--limit <n>] [--scope local|global|project] [--json]");return}if($==="app-wiki"){console.log("Usage: knowledge app-wiki init | note add|get|list | source add <source-ref> | search <query> | query <query> [--title <title>] [--content <text>] [--tag <tag>] [--source-ref <uri>] [--scope project|local|global] [--allow-global] [--json]");return}if($==="source"){console.log("Usage: knowledge source resolve <source-ref> [--purpose knowledge_answer|knowledge_index] [--limit <n>] [--scope local|global|project] [--json]");return}if($==="ingest"){console.log("Usage: knowledge ingest manifest <file|s3://bucket/key> | source <source-ref> | rules [--workspace <path>] [--owner <name>] [--dry-run] [--max-items <n>] [--limit <n>] [--purpose knowledge_index] [--scope local|global|project] [--json]");return}if($==="reindex"){console.log("Usage: knowledge reindex status|enqueue|embeddings|outbox [file|s3://bucket/key] [--full] [--fake] [--scope local|global|project] [--json]");return}if($==="search"){console.log("Usage: knowledge search <query> [--context] [--semantic] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="context"){console.log("Usage: knowledge context pack <query> [--from search|runs|loops] [--max-tokens <n>] [--max-items <n>] [--limit <n>] [--semantic] [--model openai:text-embedding-3-small] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="proposals"){console.log("Usage: knowledge proposals context --from loops --topic <text> [--since <duration|ISO>] [--dedupe] [--max-tokens <n>] [--max-items <n>] [--scope local|global|project] [--json]");return}if($==="web"){console.log("Usage: knowledge web search <query> [--provider openai|anthropic] [--model provider:model] [--domain <domain>] [--file-results] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="ask"||$==="build"){console.log("Usage: knowledge ask|build <prompt> [--generate] [--semantic] [--model default|provider:model] [--approve-write] [--scope local|global|project] [--verbose] [--json]");return}if($==="embeddings"){console.log("Usage: knowledge embeddings status|index|search [query] [--model openai:text-embedding-3-small] [--limit <n>] [--dimensions <n>] [--fake] [--scope local|global|project] [--verbose] [--json]");return}if($==="providers"){console.log("Usage: knowledge providers status|models|check [provider|model-alias] [--scope local|global|project] [--json]");return}if($==="safety"){console.log("Usage: knowledge safety status|check|approve|audit|redact [args] [--scope local|global|project] [--json]");return}if($==="events"){console.log("Usage: knowledge events emit|list|replay [args] [--json]");return}if($==="webhooks"){console.log("Usage: knowledge webhooks add|list|remove|test [args] [--json]");return}go()}function Io($){if($.noColor||process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR)return!0;return process.stdout.isTTY===!0}function h($,_,J){if(_){console.log(JSON.stringify($,null,2));return}if(typeof $==="string"){console.log($);return}if(J?.verbose){console.log(JSON.stringify($,null,2));return}let U=$.message;console.log(U?`${U} +${m_()}`:fo($))}function m_($="full details"){return`Hint: use --verbose for ${$}, or --json for machine-readable output.`}function v$($,_=120){let J=$===null||$===void 0?"":String($).replace(/\s+/g," ").trim();if(J.length<=_)return J;return`${J.slice(0,Math.max(0,_-3))}...`}function fo($){if(!$||typeof $!=="object")return String($);let _=$,J=[_.ok===!1?"Result: not ok":"Result: ok"];for(let[U,W]of Object.entries(_).slice(0,8)){if(U==="ok"||U==="message")continue;if(Array.isArray(W))J.push(`${U}: ${W.length} item(s)`);else if(W&&typeof W==="object")J.push(`${U}: ${Object.keys(W).length} field(s)`);else J.push(`${U}: ${v$(W,100)}`)}return J.push(m_()),J.join(` +`)}function Co($){let _=$.mode==="cloud"?"cloud (HTTP /v1 API)":"local (on-box store)",J=$.source.kind==="env"?`selected by ${$.source.name}=${$.source.value}`:`default (no mode var set; set ${y4[0]}=cloud to use the API)`,U=[`Knowledge mode: ${_}`,` ${J}`];if($.pointer_env_present.length>0){let W=$.pointer_ignored?"present but IGNORED for mode selection":"present";U.push(` Pointer env ${W}: ${$.pointer_env_present.join(", ")}`)}if($.network_guard_active)U.push(" Outbound guard: ACTIVE (NODE_ENV=test) \u2014 non-loopback requests are refused.");if($.warning)U.push(` Note: ${$.warning}`);return U.join(` +`)}function Po($){return[`Knowledge paths (${$.scope})`,`Home: ${$.home}`,`SQLite: ${$.knowledge_db_path}`,`JSON store: ${$.json_store_path}`,`Wiki: ${$.wiki_dir}`,m_("config and all paths")].join(` +`)}function VA($){console.log(JSON.stringify($))}function To($){let _=$.summary,J=[`Knowledge inventory (${$.scope})`,`Home: ${$.home}`,`JSON store: ${$.paths.json_store_path}${$.paths.json_store_exists?"":" (missing)"}`,`SQLite catalog: ${$.paths.knowledge_db_path}`,`Summary: ${_.legacy_items} item(s), ${_.sources} source(s), ${_.chunks} chunk(s), ${_.wiki_pages} wiki page(s), ${_.indexes} index(es), ${_.storage_objects} artifact(s), ${_.runs} run(s)`],U=(W,X,G)=>{if(X.length===0)return;J.push("",`${W}:`);for(let Y of X.slice(0,$.limit))J.push(`- ${G(Y)}`)};return U("Items",$.items,(W)=>`${W.id}: ${W.title}`),U("Sources",$.sources,(W)=>`${W.kind??"source"} ${W.uri} (${W.chunks??0} chunk(s))`),U("Chunks",$.chunks,(W)=>`${W.kind??"chunk"} ${W.id}: ${W.text_preview??""}`),U("Wiki pages",$.wiki_pages,(W)=>`${W.path}: ${W.title}`),U("Indexes",$.indexes,(W)=>`${W.kind??"index"} ${W.name}${W.shard_key?` (${W.shard_key})`:""}`),U("Artifacts",$.storage_objects,(W)=>`${W.kind??"artifact"} ${W.artifact_uri}`),U("Runs",$.runs,(W)=>`${W.type??"run"} ${W.id}: ${W.status??"unknown"}`),U("Machines",$.machines,(W)=>`${W.machine_id}${W.workspace_home?` ${W.workspace_home}`:""}`),U("Sync conflicts",$.sync_conflicts,(W)=>`${W.id}: ${W.entity_kind}/${W.entity_id} ${W.status}`),J.join(` +`)}function So($){let _=Array.isArray($.results)?$.results:[],J=[`${_.length} search result(s) for "${v$($.query,80)}"${$.mode?.semantic?" (semantic enabled)":""}`];for(let U of _.slice(0,$.limit??10)){let W=U.source?.uri??U.provenance?.source_uri??U.artifact?.path??U.artifact?.uri??U.id,X=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(J.push(`- ${U.kind??"result"} ${v$(U.title??U.id,80)}${X}`),W)J.push(` source: ${v$(W,120)}`);if(U.text)J.push(` text: ${v$(U.text,180)}`)}if(_.length===0)J.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(J.push(m_("scores, provenance, and full result objects")),!$.context)J.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return J.join(` +`)}function Zo($){let _=Array.isArray($.excerpts)?$.excerpts:[],J=Array.isArray($.citations)?$.citations:[],U=[`${_.length} context excerpt(s) for "${v$($.query??$.normalized_query,80)}"`];for(let W of _.slice(0,10)){let X=J.find((Q)=>Q.id===W.citation_id||Q.result_id===W.result_id),G=X?.source_uri??X?.artifact_path??W.result_id,Y=typeof W.score==="number"?` score=${W.score.toFixed(3)}`:"";if(U.push(`- ${W.kind??"excerpt"} ${v$(W.id,44)}${Y}`),G)U.push(` source: ${v$(G,120)}`);U.push(` text: ${v$(W.text,220)}`)}return U.push(`Citations: ${J.length}`),U.push(m_("citations, graph, notes, and full excerpts")),U.join(` +`)}function vo($){let _=Array.isArray($.results)?$.results:[],J=[`${_.length} semantic result(s) for "${v$($.query,80)}"`,`Index: ${$.provider??"unknown"}:${$.model??"unknown"} (${$.dimensions??"?"} dimensions)`];for(let U of _.slice(0,$.limit??10)){let W=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(J.push(`- ${v$(U.chunk_id,44)}${W}`),U.source_uri)J.push(` source: ${v$(U.source_uri,120)}`);if(U.text)J.push(` text: ${v$(U.text,180)}`)}return J.push(m_("provenance and full vector result objects")),J.join(` +`)}function yo($){let _=Array.isArray($.sources)?$.sources:[],J=[`${_.length} web source(s) for "${v$($.query,80)}"`,`Provider: ${$.provider??"unknown"}${$.model?` (${$.model})`:""}`];for(let U of _.slice(0,$.limit??10)){J.push(`- ${v$(U.title??U.url??U.uri??"source",100)}`);let W=U.url??U.uri??U.source_ref;if(W)J.push(` url: ${v$(W,140)}`);if(U.snippet)J.push(` snippet: ${v$(U.snippet,180)}`)}return J.push(m_("provider payloads and filed source refs")),J.join(` +`)}function ho($){let _=Array.isArray($.machines)?$.machines:[],J=[`${_.length} machine(s) discovered via ${$.source??"unknown"}`,`Adapter: ${$.adapter?.package??"@hasna/machines"} ${$.adapter?.available?"available":"unavailable"}`];for(let U of _.slice(0,10)){let W=U.local?" local":"",X=U.tailscale_dns??U.ssh_target??U.hostname??"";J.push(`- ${v$(U.machine_id??U.id??"unknown",48)}${W}${X?` -> ${v$(X,80)}`:""}`)}if(_.length>10)J.push(`... ${_.length-10} more machine(s).`);if(Array.isArray($.warnings)&&$.warnings.length>0)J.push(`Warnings: ${$.warnings.slice(0,3).join("; ")}`);return J.push(m_("full topology, route hints, and adapter evidence")),J.join(` +`)}function mo($){let _=Array.isArray($.checks)?$.checks:[],J=_.filter((X)=>X.status==="fail"||X.severity==="fail"),U=_.filter((X)=>X.status==="warn"||X.severity==="warn"),W=[`Machine preflight ${$.ok?"passed":"needs attention"} for ${$.machine_id??$.requested_machine_id??"local"}`,`Checks: ${_.length} total, ${J.length} failed, ${U.length} warning(s)`];for(let X of[...J,...U].slice(0,8))W.push(`- ${X.status??X.severity??"check"} ${v$(X.id??X.kind??"check",72)}: ${v$(X.message??X.detail??"",140)}`);return W.push(m_("all checks and repair hints")),W.join(` +`)}function xo($){return[`Sync status (${$.scope??"scope"})`,`Schema: v${$.sqlite_schema_version??"unknown"}`,`Machines: ${$.machines?.total??0}; snapshots: ${$.snapshots?.total??0}; open conflicts: ${$.conflicts?.open??0}`,`Tables: ${Object.entries($.table_counts??{}).slice(0,8).map(([J,U])=>`${J}=${U}`).join(", ")||"none"}`,m_("registry rows, clocks, snapshots, imports, and conflicts")].join(` +`)}function uo($){let _=Array.isArray($.warnings)?$.warnings:[],J=Array.isArray($.recommended_commands)?$.recommended_commands:[],U=[$.message??`Sync readiness ${$.ok?"ok":"needs attention"}`,`Storage: ${$.storage?.validation?.ok?"ok":"needs attention"}; open-files: ${$.open_files?.ok?"ok":"needs attention"}; open conflicts: ${$.sync?.open_conflicts??0}`];if(_.length>0)U.push(`Warnings: ${_.slice(0,5).join("; ")}`);for(let W of J.slice(0,5))U.push(`- next: ${v$(W.shell_command??W.command?.join(" ")??W.id,160)}`);return U.push(m_("diagnostics, route evidence, and all recommended commands")),U.join(` +`)}function no($){let _=$.snapshot??{};return[`Sync snapshot ${$.ok?"recorded":"failed"}`,`Snapshot: ${v$(_.id??_.snapshot_id??"unknown",80)} ${_.content_hash?`(${v$(_.content_hash,80)})`:""}`,`Machines upserted: ${$.machines_upserted??0}; machine: ${$.machine_id??_.machine_id??"unknown"}`,m_("snapshot payload and topology evidence")].join(` +`)}function co($){let _=Array.isArray($.conflicts)?$.conflicts:[],J=[`${_.length} sync conflict(s)`];for(let U of _.slice(0,10))J.push(`- ${v$(U.id,48)} ${U.status??"unknown"} ${U.entity_kind??""}/${v$(U.entity_id,80)}`);return J.push("Next: use `knowledge sync conflicts show <id> --json` for one conflict."),J.push(m_("full conflict objects")),J.join(` +`)}function io($){let _=Array.isArray($.machines)?$.machines:[],J=[`${_.length} registered sync machine(s)`];for(let U of _.slice(0,10))J.push(`- ${v$(U.machine_id,48)} ${v$(U.hostname??U.workspace_home??"",100)}`);return J.push(m_("machine registry rows")),J.join(` +`)}function RA($,_){let J=[`Sync ${_} ${$.ok===!1?"needs attention":"completed"}${$.dry_run?" (dry run)":""}`],U=(W,X)=>{if(!X)return;let Y=(Array.isArray(X.tables)?X.tables:[]).reduce((L,N)=>L+(N.inserted??0)+(N.updated??0)+(N.deleted??0),0),Q=X.artifacts?.copied??0,q=Array.isArray(X.errors)?X.errors.length:0;J.push(`${W}: ${Y} table row change(s), ${Q} artifact(s), ${q} error(s)`)};if(U("pull",$.pull),U("push",$.push),Array.isArray($.errors)&&$.errors.length>0)J.push(`Errors: ${$.errors.slice(0,3).map((W)=>v$(W,120)).join("; ")}`);return J.push(m_("per-table rows, artifacts, clocks, and errors")),J.join(` +`)}function lo($){let _=Array.isArray($.citations)?$.citations:[],J=Array.isArray($.context?.excerpts)?$.context.excerpts:Array.isArray($.excerpts)?$.excerpts:[],U=[$.generated?"Generated answer with citations":"Prepared citation context draft",`Citations: ${_.length}; excerpts: ${J.length}`];if($.answer)U.push(`Answer: ${v$($.answer,500)}`);for(let W of _.slice(0,5))U.push(`- ${v$(W.source_uri??W.ref??W.id,120)}`);return U.push(m_("full answer payload, context, citations, and run ledger")),U.join(` +`)}function ro($,_){return[`Export preview: ${$.length} item(s) available`,"Default output is compact to avoid terminal/context bloat.","Use --verbose or --json for a JSON object, or --format jsonl for newline-delimited records.",_!=="json"?`Requested format: ${_}`:""].filter(Boolean).join(` +`)}function KA($){return!$||$==="local"||$==="localhost"}function E2($){if(!$.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function po($,_){let J=_.sort??"created";if(J!=="created"&&J!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let U=[...$].sort((W,X)=>{if(J==="title")return W.title.localeCompare(X.title);return W.created_at.localeCompare(X.created_at)});if(_.desc)U.reverse();return{sorted:U,sort:J,direction:_.desc?"desc":"asc"}}async function oo($){if(await wo($))return;let{positional:_,flags:J}=Fo($);if(M2("debug","CLI invoked",{command:_[0],flags:{json:J.json,store:J.store}}),J.version){console.log(J.json?JSON.stringify({name:s6.name,version:s6.version},null,2):`${s6.name} ${s6.version}`);return}if(J.completions){let B=J.completions;if(B==="bash")console.log('_knowledge() { local cur; cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive --json --verbose --yes --help --version --desc --page --limit --search --sort --id --store --title --content --url --tag --rev --to --format --completions --purpose --model --dimensions --semantic --context --max-tokens --max-items --from --since --topic --dedupe --generate --approve-write --provider --mode --machine --workspace --peer-workspace --api-url --canonical-example --api-key --email --org --org-id --user-id --owner --domain --file-results --full --dry-run --fake --no-tailscale --no-artifact-content --no-color --scope --tables --archived --include-archived --project --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(B==="zsh")console.log(`#compdef knowledge +_knowledge() { _arguments -C "1: :(add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive)" "(--json)--json" "(--verbose)--verbose" "(--yes)-y" "(--help)--help" "(--version)--version" "(--desc)--desc" "(--archived)--archived" "(--include-archived)--include-archived" "(--semantic)--semantic" "(--context)--context" "(--dedupe)--dedupe" "(--generate)--generate" "(--approve-write)--approve-write" "(--canonical-example)--canonical-example" "(--file-results)--file-results" "(--full)--full" "(--dry-run)--dry-run" "(--fake)--fake" "(--no-tailscale)--no-tailscale" "(--no-artifact-content)--no-artifact-content" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(-s --search)"{-s,--search}"[search text]:text:" "(--sort)--sort"{created,title}:" "(--id)--id[item id]:id:" "(--store)--store[store path]:path:" "(--title)--title[new title]:" "(--content)--content[new content]:" "(--url)--url[source url]:" "(-t --tag)"{-t,--tag}"[tag]:tag:" "(--format)--format[json|jsonl]:" "(--completions)--completions[output completions]:shell:(bash zsh fish):" "(--purpose)--purpose[purpose]:" "(--model)--model[model ref]:" "(--dimensions)--dimensions[embedding dimensions]:number:" "(--max-tokens)--max-tokens[token budget]:number:" "(--max-items)--max-items[item budget]:number:" "(--from)--from"{search,loops,runs}:" "(--to)--to[diff target: version number or current]:" "(--rev)--rev[entry version for diff]:number:" "(--since)--since[duration or ISO time]:" "(--topic)--topic[topic text]:" "(--provider)--provider[provider]:" "(--mode)--mode"{local,hosted}:" "(--machine)--machine[machine id or SSH alias]:" "(--workspace)--workspace[repo workspace path]:path:" "(--peer-workspace)--peer-workspace[peer repo or knowledge home path]:path:" "(--api-url)--api-url[hosted API URL]:" "(--api-key)--api-key[hosted API key]:" "(--email)--email[email]:" "(--org)--org[org slug]:" "(--org-id)--org-id[org id]:" "(--user-id)--user-id[user id]:" "(--owner)--owner[provenance owner]:" "(--domain)--domain[domain]:" "(--project)--project[project id/name/slug]:" "(--source-ref)--source-ref[source ref]:" "(--no-color)--no-color[disable color]" "(--scope)--scope"{local,global,project}:" "(--tables)--tables[comma-separated DB sync tables]:" }; _knowledge`);else if(B==="fish")console.log('complete -c knowledge -f; complete -c knowledge -a "add list get update archive restore upsert untag versions diff delete export prune dedupe stats inventory project-panel paths mode setup auth storage machines sync db wiki app-wiki source ingest reindex search context proposals web ask build embeddings providers safety events webhooks help ls rm edit unarchive"; complete -c knowledge -l json; complete -c knowledge -l verbose; complete -c knowledge -l yes -s y; complete -c knowledge -l help -s h; complete -c knowledge -l version -s v; complete -c knowledge -l desc; complete -c knowledge -l archived; complete -c knowledge -l include-archived; complete -c knowledge -l semantic; complete -c knowledge -l context; complete -c knowledge -l max-tokens; complete -c knowledge -l max-items; complete -c knowledge -l from -a "search loops runs"; complete -c knowledge -l to; complete -c knowledge -l rev; complete -c knowledge -l since; complete -c knowledge -l topic; complete -c knowledge -l dedupe; complete -c knowledge -l generate; complete -c knowledge -l approve-write; complete -c knowledge -l allow-global; complete -c knowledge -l canonical-example; complete -c knowledge -l provider; complete -c knowledge -l mode; complete -c knowledge -l machine; complete -c knowledge -l workspace; complete -c knowledge -l peer-workspace; complete -c knowledge -l api-url; complete -c knowledge -l api-key; complete -c knowledge -l email; complete -c knowledge -l org; complete -c knowledge -l org-id; complete -c knowledge -l user-id; complete -c knowledge -l owner; complete -c knowledge -l domain; complete -c knowledge -l project; complete -c knowledge -l contract; complete -c knowledge -l source-ref; complete -c knowledge -l file-results; complete -c knowledge -l full; complete -c knowledge -l dry-run; complete -c knowledge -l fake; complete -c knowledge -l no-tailscale; complete -c knowledge -l no-artifact-content; complete -c knowledge -s p -l page; complete -c knowledge -s l -l limit; complete -c knowledge -s s -l search; complete -c knowledge -l sort; complete -c knowledge -l id; complete -c knowledge -l store; complete -c knowledge -l title; complete -c knowledge -l content; complete -c knowledge -l url; complete -c knowledge -s t -l tag; complete -c knowledge -l format; complete -c knowledge -l completions; complete -c knowledge -l purpose; complete -c knowledge -l model; complete -c knowledge -l dimensions; complete -c knowledge -l no-color; complete -c knowledge -l scope -a "local global project"; complete -c knowledge -l tables');else throw Error("Invalid --completions value. Use 'bash', 'zsh', or 'fish'.");return}let U=Eo(_[0]),W=1,X=_.length>1||/\s/.test(U);if(bo()&&U&&!EA.includes(U)&&X)U="ask",W=0;if(!U||J.help||U==="help"){let B=U==="help"?_[1]:U||_[1];ko(B);return}if(U==="mode"){let B=lN(process.env);h(J.json||J.verbose?{ok:!0,...B}:Co(B),J.json,J);return}iN(process.env,{storePathOverridden:Boolean(J.store)});let G=U==="project-panel"||U==="app-wiki"?J.scope??"project":J.scope,Y=$Y({scope:G});if(U==="storage"){let B=_[1]??"status";if(B==="import-legacy"){if(J.scope&&J.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let H=IY({dryRun:J.dryRun});if(h(H,J.json),!H.ok)process.exitCode=1;return}if(B==="migrate-legacy-path"||B==="migrate-legacy"||B==="migrate-path"){let H=Y.migrateLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}if(B==="merge-legacy-path"||B==="merge-legacy"||B==="merge-path"){let H=Y.mergeLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}}let Q=Boolean(J.store),q=J.store;if(!q)if(G==="project"||G==="local")q=Y.workspace.jsonStorePath;else q=B9();if(!Q&&(U==="ask"||U==="build")&&!K0())lW(q);let L=y9({storePath:q,storePathOverridden:Q});if(U==="inventory"){let B=await Y.resolveInventory({limit:J.limit,includeArchived:J.includeArchived||J.archived,storePath:K0()?void 0:q});h(J.json||J.verbose?B:To(B),J.json,J);return}if(U==="project-panel"){let B=J.project??_[1];if(!B)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let H=await MM(B,{service:Y,limit:J.limit,storePath:K0()?void 0:q,includeArchived:J.includeArchived||J.archived});h(J.json||J.contract?H:AM(H),J.json||J.contract);return}if(U==="paths"){let B=Y.paths();h(J.json||J.verbose?B:Po(B),J.json,J);return}if(U==="setup"){let B=Y.setup({mode:J.mode,apiUrl:J.apiUrl,canonicalExample:J.canonicalExample});h(B,J.json,J);return}if(U==="auth"){let B=_[1]??"whoami";if(B==="whoami"||B==="status"){let H=Y.authStatus(process.env);h({ok:!0,...H,message:H.authenticated?`Authenticated via ${H.source}`:"Not authenticated"},J.json,J);return}if(B==="login"){let H=J.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!H)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let V=Y.saveAuth({apiKey:H,email:J.email,orgSlug:J.org,orgId:J.orgId,userId:J.userId,apiUrl:J.apiUrl},process.env);h({ok:!0,authenticated:!0,email:V.email??null,org_slug:V.org_slug??null,api_url:V.api_url??Y.authStatus(process.env).api_url,auth_path:Y.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${V.email??"API key"}`},J.json,J);return}if(B==="logout"){let H=Y.clearAuth(process.env);h({ok:!0,removed:H,message:H?"Removed hosted credentials":"No hosted credentials found"},J.json,J);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(U==="storage"){let B=_[1]??"status";if(B==="status"){let H=Y.storageContract(),V=Y.validateStorage();h({ok:V.ok,...H,validation:V,message:`${H.storage_type} artifact storage at ${H.artifact_store.uri_prefix}`},J.json,J);return}if(B==="validate"){let H=Y.validateStorage();if(h({ok:H.ok,validation:H,message:H.ok?"Storage contract valid":`Storage contract invalid: ${H.errors.join("; ")}`},J.json,J),!H.ok)process.exitCode=1;return}if(B==="repair-artifact-keys"||B==="repair-keys"){let H=Y.repairArtifactManifestKeys({approveWrite:J.approveWrite,approvedBy:J.approvedBy,dryRun:J.dryRun});h(H,J.json,J);return}if(B==="migrate-legacy-path"||B==="migrate-legacy"||B==="migrate-path"){let H=Y.migrateLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}if(B==="merge-legacy-path"||B==="merge-legacy"||B==="merge-path"){let H=Y.mergeLegacyPath({approveWrite:J.approveWrite,approvedBy:J.approvedBy});if(h(H,J.json),!H.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid storage action. Use 'status', 'validate', 'repair-artifact-keys', 'migrate-legacy-path', 'merge-legacy-path', or 'import-legacy'.")}if(U==="machines"){let B=_[1]??"topology";if(B==="topology"||B==="status"){let H=await Y.machineTopology({includeTailscale:J.tailscale!==!1});h(J.json||J.verbose?H:ho(H),J.json,J);return}if(B==="preflight"||B==="check"){let H=_[2]??J.machine??"local",V=J.workspace??process.cwd(),K=await Y.machinePreflight({machineId:H,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:s6.name,command:"knowledge",expectedVersion:s6.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:V,expectedPackageName:s6.name,expectedVersion:s6.version,required:!0}]});if(h(J.json||J.verbose?K:mo(K),J.json,J),!K.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(U==="sync"){let B=_[1]??"status",H=J.tables?J.tables.split(",").map((V)=>V.trim()).filter(Boolean):void 0;if(B==="status"){let V=Y.syncStatus();h(J.json||J.verbose?V:xo(V),J.json,J);return}if(B==="doctor"||B==="readiness"||B==="preflight"){let V=await Y.syncDoctor({machine:J.machine??null,peerWorkspace:J.peerWorkspace??null,includeTailscale:J.tailscale!==!1,tables:H}),K={package:{name:s6.name,version:s6.version},...V};if(h(J.json||J.verbose?K:uo(K),J.json,J),!V.ok&&!J.json)process.exitCode=1;return}if(B==="snapshot"||B==="record"){let V=await Y.createSyncSnapshot({includeTailscale:J.tailscale!==!1,machineId:J.machine});h(J.json||J.verbose?V:no(V),J.json,J);return}if(B==="conflicts"||B==="conflict"){let V=_[2];if(V==="show"||V==="get"){let F=_[3]??J.id;if(!F)throw Error("Usage: knowledge sync conflicts show <id>");let w=Y.syncConflict(F);h({ok:!0,conflict:w,message:`Sync conflict ${F}`},J.json,J);return}if(V==="propose"||V==="proposal"){let F=_[3]??J.id;if(!F)throw Error("Usage: knowledge sync conflicts propose <id>");h(J.mode==="ai"?await Y.proposeSyncConflictResolutionWithAi({id:F,modelRef:J.model,fake:J.fake}):Y.proposeSyncConflictResolution(F),J.json,J);return}if(V==="resolve"){let F=_[3]??J.id;if(!F)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let w=Y.resolveSyncConflict({id:F,strategy:J.strategy,approvedBy:J.approvedBy,approveWrite:J.approveWrite,proposedPatchUri:J.patchUri});if(h(w,J.json,J),!w.ok&&!J.json)process.exitCode=1;return}let K=Y.syncConflicts({status:V,limit:J.limit}),E={ok:!0,conflicts:K,message:`${K.length} sync conflict(s)`};h(J.json||J.verbose?E:co(E),J.json,J);return}if(B==="machines"||B==="registry"){let V=Y.syncMachines(),K={ok:!0,machines:V,message:`${V.length} registered sync machine(s)`};h(J.json||J.verbose?K:io(K),J.json,J);return}if(B==="export"){let V=Y.exportSyncBundle({machineId:J.machine??null,tables:H,includeArtifactContent:J.artifactContent!==!1});h(V,!0);return}if(B==="import"){let V=await Bun.stdin.text();if(!V.trim())throw Error("Usage: knowledge sync import < bundle.json");let K=await Y.importSyncBundle({bundle:JSON.parse(V),dryRun:J.dryRun,direction:"import",machineId:J.machine??null});h(J.json||J.verbose?K:RA(K,B),J.json,J);return}if(B==="dry-run"||B==="pull"||B==="push"||B==="sync"){if(!J.peerWorkspace&&KA(J.machine))throw Error(`Usage: knowledge sync ${B} --peer-workspace <repo-or-knowledge-home> [--scope project] +Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let V=B==="dry-run"?"both":B==="sync"?"both":B,K=!KA(J.machine)?await Y.syncRemotePeer({direction:V,machine:J.machine,peerWorkspace:J.peerWorkspace,tables:H,dryRun:J.dryRun===!0||B==="dry-run",includeArtifactContent:J.artifactContent!==!1,includeTailscale:J.tailscale!==!1}):await Y.syncPeer({peerWorkspace:J.peerWorkspace,direction:V,dryRun:J.dryRun===!0||B==="dry-run",tables:H,includeArtifactContent:J.artifactContent!==!1,machineId:J.machine??null});if(h(J.json||J.verbose?K:RA(K,B),J.json,J),!K.ok&&!J.json)process.exitCode=1;return}throw Error("Invalid sync action. Use 'status', 'doctor', 'snapshot', 'conflicts', 'machines', 'dry-run', 'pull', 'push', 'sync', 'export', or 'import'.")}if(U==="db"){let B=_[1]??"init";if(B==="init"){let H=Y.initDb();h({ok:!0,...H,message:`Initialized ${H.path}`},J.json,J);return}if(B==="stats"){let H=Y.dbStats();h({ok:!0,path:Y.workspace.knowledgeDbPath,...H,message:`knowledge.db schema v${H.schema_version}`},J.json,J);return}if(B==="storage"){if((_[2]??"status")==="status"){let V=qB({scope:J.scope});h({ok:!0,...V,message:`knowledge.db storage mode ${V.mode}`},J.json,J);return}throw Error("Invalid db storage action. Only 'status' is supported. The 'push'/'pull'/'sync' Postgres sync commands were removed (DSN-on-client is forbidden); use the cloud API flip instead.")}throw Error("Invalid db action. Use 'init', 'stats', or 'storage'.")}if(U==="app-wiki"){let B=_[1]??"init";if(B==="paths"||B==="status"){h({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...Y.paths()},J.json);return}if(B==="init"||B==="open"){let H=await Y.initAppWiki({allowGlobal:J.allowGlobal});h(H,J.json);return}if(B==="note"||B==="notes"){let H=_[2]??"list";if(H==="add"||H==="create"){let V=J.title??_[3],K=J.content??_.slice(4).join(" ");if(!V||!K)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let E=await Y.addAppWikiNote({title:V,content:K,tags:J.tag,sourceRefs:J.sourceRef,allowGlobal:J.allowGlobal});h(E,J.json);return}if(H==="list"||H==="ls"){let V=Y.listAppWikiNotes({limit:J.limit});h({ok:!0,scope:Y.scope,home:Y.workspace.home,notes:V,message:`${V.length} app wiki note(s)`},J.json);return}if(H==="get"||H==="show"){let V=_[3]??J.id;if(!V)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let K=await Y.getAppWikiNote(V,{includeContent:!0});if(!K)throw Error(`App wiki note not found: ${V}`);h(K,J.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(B==="source"||B==="sources"){let H=_[2]??"add";if(H!=="add"&&H!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let V=_[3]??J.sourceRef?.[0];if(!V)throw Error("Usage: knowledge app-wiki source add <source-ref>");let K=await Y.addAppWikiSourceRef({sourceRef:V,purpose:J.purpose,allowGlobal:J.allowGlobal});h({ok:!0,...K,message:`Added app wiki source ${K.source_ref}`},J.json);return}if(B==="search"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge app-wiki search <query>");let V=await Y.searchAppWiki({query:H,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V,message:`${V.results.length} app wiki result(s)`},J.json);return}if(B==="query"||B==="context"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge app-wiki query <query>");let V=await Y.queryAppWiki({query:H,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V,message:`${V.excerpts.length} app wiki excerpt(s)`},J.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(U==="wiki"){let B=_[1]??"init";if(B==="init"){let H=await Y.initWiki();h({ok:!0,...H,message:`Initialized wiki layout in ${Y.workspace.home}`},J.json,J);return}if(B==="compile"){let H=_.slice(2),V=H.filter((F)=>/^(open-files|file|s3|https?):\/\//.test(F)),K=H.filter((F)=>!/^(open-files|file|s3|https?):\/\//.test(F)).join(" "),E=await Y.compileWiki({title:J.title,query:K||J.search,sourceRefs:V.length>0?V:void 0,limit:J.limit});h({ok:!0,...E,message:`Compiled wiki page ${E.path}`},J.json,J);return}if(B==="file-answer"||B==="answer"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!J.content)throw Error("Missing --content <answer> for wiki file-answer.");let V=await Y.fileAnswer({prompt:H,answer:J.content,approveWrite:J.approveWrite,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...V},J.json,J);return}if(B==="lint"){let H=Y.lintWiki();h({ok:H.ok,...H,message:H.ok?"Wiki lint passed":`Wiki lint found ${H.issue_count} issue(s)`},J.json,J);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(U==="safety"){let B=_[1]??"status",H=Y.ensureWorkspace(),V=Y.safetyPolicy();Y.initDb();let K=m(H.knowledgeDbPath);try{if(B==="status"){h({ok:!0,mode:V.mode,workspace:H.home,allow_write_roots:V.allowWriteRoots,read_only_source_access:V.readOnlySourceAccess,network:V.network,redaction:V.redaction,approvals:V.approvals,message:`Safety policy: ${V.mode}`},J.json,J);return}if(B==="check"){let E=_[2]??"generated_write",F=_[3]??null,w;try{if(E==="web_search")fJ(V),w={action:E,target_uri:F,approval_required:!1,approved:!0,decision:"allow"};else if(E==="s3_read"){if(!F)throw Error("safety check s3_read requires an s3:// target.");M0(F,V),w={action:E,target_uri:F,approval_required:!1,approved:!0,decision:"allow"}}else w=g3(K,V,E,F);__(K,{event_type:"safety_check",action:E,target_uri:F,decision:w.decision==="allow"?"allow":"requires_approval",metadata:w}),h({ok:!0,...w,message:`Safety check ${w.decision}`},J.json,J);return}catch(A){throw __(K,{event_type:"safety_check",action:E,target_uri:F,decision:"deny",metadata:{error:A instanceof Error?A.message:String(A)}}),A}}if(B==="approve"){let E=_[2]??"generated_write",F=_[3]??null,w=u9(K,{action:E,target_uri:F,reason:"local-cli approval",metadata:{scope:J.scope??"global"}});__(K,{event_type:"approval",action:E,target_uri:F,decision:"allow",metadata:{approval_id:w.id}}),h({ok:!0,...w,action:E,target_uri:F,message:`Approved ${E}`},J.json,J);return}if(B==="audit"){let E=K.query("SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT 50").all().map((F)=>({id:F.id,event_type:F.event_type,action:F.action,target_uri:F.target_uri,decision:F.decision,metadata:JSON.parse(F.metadata_json),created_at:F.created_at}));h({ok:!0,events:E,message:`${E.length} audit event(s)`},J.json,J);return}if(B==="redact"){let E=_.slice(2).join(" ");if(!E)throw Error("Usage: knowledge safety redact <text>");let F=k_(E,V);if(F.findings.length>0)CJ(K,{source_uri:"safety://redact",findings:F.findings,metadata:{command:"safety redact"}});__(K,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:F.findings.length>0?"redacted":"allow",metadata:{findings:F.findings.length}}),h({ok:!0,text:F.text,findings:F.findings,message:`Redacted ${F.findings.length} finding(s)`},J.json,J);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{K.close()}}if(U==="source"){if((_[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let H=_[2];if(!H)throw Error("Usage: knowledge source resolve <source-ref>");let V=await Y.resolveSource(H,{purpose:J.purpose,limit:J.limit});h({ok:!0,...V,message:V.resolved?`Resolved ${V.source_ref} (${V.content.chunks_returned}/${V.content.chunks_total} chunks)`:`Source not indexed: ${H}`},J.json,J);return}if(U==="ingest"){let B=_[1]??"";if(B==="rules"||B==="global-rules"||B==="agent-rules"){let H=await Y.importRulesProvenance({root:J.workspace??process.cwd(),owner:J.owner,dryRun:J.dryRun===!0,maxItems:J.maxItems,limit:J.limit});h({ok:!0,...H},J.json);return}if(B==="manifest"){let H=_[2];if(!H)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let V=await Y.ingestManifest(H);h({ok:!0,...V,message:`Ingested ${V.items_seen} manifest item(s)`},J.json,J);return}if(B==="source"){let H=_[2];if(!H)throw Error("Usage: knowledge ingest source <source-ref>");let V=await Y.ingestSource(H,J.purpose);h({ok:!0,...V,message:`Ingested source ${V.source_ref} (${V.chunks_inserted} chunks)`},J.json,J);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(U==="reindex"){let B=_[1]??"status";if(B==="status"){let H=Y.reindexHealth({modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`${H.missing_embeddings} chunk(s) missing embeddings`},J.json,J);return}if(B==="enqueue"){let H=Y.enqueueReindex({modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Queued ${H.enqueued} embedding refresh item(s)`},J.json,J);return}if(B==="embeddings"){let H=await Y.refreshEmbeddings({full:J.full,limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Embedded ${H.indexed.chunks_embedded} chunk(s)`},J.json,J);return}if(B==="outbox"){let H=_[2];if(!H)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let V=await Y.consumeOutbox(H);h({ok:!0,...V,message:`Consumed ${V.events_seen} outbox event(s)`},J.json,J);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(U==="embeddings"){let B=_[1]??"status";if(B==="status"){let H=Y.embeddingStatus();h({ok:!0,...H,message:`${H.total_vector_entries} vector index entries`},J.json,J);return}if(B==="index"){let H=await Y.indexEmbeddings({limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake});h({ok:!0,...H,message:`Embedded ${H.chunks_embedded} chunk(s)`},J.json,J);return}if(B==="search"){let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge embeddings search <query>");let V=await Y.semanticSearch({query:H,limit:J.limit,modelRef:J.model,dimensions:J.dimensions,fake:J.fake}),K={ok:!0,...V,message:`${V.results.length} semantic result(s)`};h(J.json||J.verbose?K:vo(K),J.json,J);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(U==="context"){if((_[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let H=J.from??"search";if(!["search","loops","runs"].includes(H))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let V=_.slice(2).join(" ")||J.topic||"",K=await Y.contextPack({source:H,purpose:H==="loops"||H==="runs"?"proposal":"agent_context",query:V,topic:J.topic,since:J.since,dedupe:J.dedupe,maxTokens:J.maxTokens,maxItems:J.maxItems,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q});VA({ok:!0,...K,message:K.message});return}if(U==="proposals"){if((_[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let H=J.from??"loops";if(!["loops","runs"].includes(H))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let V=J.topic??_.slice(2).join(" ");if(!V.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let K=await Y.contextPack({source:H,purpose:"proposal",query:V,topic:V,since:J.since,dedupe:J.dedupe??!0,maxTokens:J.maxTokens,maxItems:J.maxItems,limit:J.limit});VA({ok:!0,...K,message:K.message});return}if(U==="search"){let B=_.slice(1).join(" ");if(!B)throw Error("Usage: knowledge search <query>");if(J.context){let K=await Y.retrieveContext({query:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q}),E={ok:!0,...K,message:`${K.excerpts.length} context excerpt(s)`};h(J.json||J.verbose?E:Zo(E),J.json,J);return}let H=await Y.search({query:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,legacyStorePath:q}),V={ok:!0,...H,message:`${H.results.length} search result(s)`};h(J.json||J.verbose?V:So(V),J.json,J);return}if(U==="web"){if((_[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let H=_.slice(2).join(" ");if(!H)throw Error("Usage: knowledge web search <query>");let V=await Y.webSearch({query:H,limit:J.limit,modelRef:J.model,provider:J.provider,domains:J.domain,fake:J.fake,fileResults:J.fileResults}),K={ok:!0,...V,message:`${V.sources.length} web source(s)`};h(J.json||J.verbose?K:yo(K),J.json,J);return}if(U==="ask"||U==="build"){let B=_.slice(W).join(" ");if(!B)throw Error("Usage: knowledge ask <prompt>");let H=await Y.runPrompt({prompt:B,limit:J.limit,semantic:J.semantic,modelRef:J.model,dimensions:J.dimensions,fake:J.fake,generate:J.generate,approveWrite:J.approveWrite,legacyStorePath:q}),V={ok:!0,...H,message:H.generated?"Generated answer with citations":"Prepared citation context draft"};h(J.json||J.verbose?V:lo(V),J.json,J);return}if(U==="providers"){let B=_[1]??"status";if(B==="status"){let H=Y.providerStatus(),V=H.providers.filter((K)=>K.configured).length;h({ok:!0,...H,message:`${V}/${H.providers.length} provider credential(s) configured`},J.json,J);return}if(B==="models"){let H=Y.modelRegistry();h({ok:!0,models:H,message:`${H.length} model alias(es)`},J.json,J);return}if(B==="check"){let H=_[2]??"default",V=y6(H,Y.config()),K=w_(V),E=w1(K.provider,Y.config());h({ok:!0,target:H,model_ref:V,provider:K.provider,model:K.model,credential:E,message:`${K.provider} credentials configured`},J.json,J);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(U==="add"){let B=_[1],H=_[2];if(!B||!H)throw Error("Usage: knowledge add <title> <content>");let V=await L.create({title:B,content:H,url:J.url??null,tags:J.tag??[]});M2("info","Item added",{id:V.id,title:V.title,tags:V.tags?.length??0,transport:L.kind}),h({ok:!0,item:V,message:`Added ${V.id}`},J.json,J);return}if(U==="list"){if(J.format!==void 0&&J.format!=="table"&&J.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");let B=await L.listAll(),H=Number.isFinite(J.page)&&J.page>0?J.page:1,V=Number.isFinite(J.limit)&&J.limit>0?J.limit:20,K=J.search?String(J.search).toLowerCase():"",E=(J.tagRaw??J.tag??[]).map((E$)=>({whole:E$.trim().toLowerCase(),parts:E$.split(",").map((A_)=>A_.trim().toLowerCase()).filter((A_)=>A_.length>0)})),F=J.tag?.length?J.tag.map((E$)=>E$.toLowerCase()).join(","):"none",w=J.format==="table"||!J.json&&!J.format&&Io(J),A=J.json||J.format==="json",g=B.items;if(J.archived)g=g.filter((E$)=>E$.archived===!0);else if(!J.includeArchived)g=g.filter((E$)=>!E$.archived);if(K)g=g.filter((E$)=>E$.title.toLowerCase().includes(K)||E$.content.toLowerCase().includes(K));if(E.length>0)g=g.filter((E$)=>{let A_=new Set((E$.tags??[]).map((D_)=>D_.toLowerCase()));return E.every(({whole:D_,parts:U_})=>D_.length>0&&A_.has(D_)||U_.every((F_)=>A_.has(F_)))});let{sorted:v,sort:k,direction:u}=po(g,J),W_=(H-1)*V,c$=v.slice(W_,W_+V),z_=Math.max(1,Math.ceil(v.length/V)),K_={ok:!0,page:H,limit:V,total:v.length,total_pages:z_,sort:k,direction:u,items:c$,store_exists:B.exists};if(A){h(K_,!0);return}if(J.verbose){h(K_,!1,J);return}if(c$.length===0){h(`No items found (search=${K||"none"}, tag=${F})`,!1);return}if(w){let E$=(D_)=>D_,A_=`${E$("ID")} ${E$("TITLE")} ${E$("CREATED")} ${E$("URL")} ${E$("TAGS")}`;console.log(A_);for(let D_ of c$)console.log(`${D_.id} ${E$(v$(D_.title,80))} ${D_.created_at} ${D_.url?E$(v$(D_.url,90)):""} ${D_.tags?.length?E$(v$(`[${D_.tags.join(", ")}]`,80)):""}`);console.log(`Page ${H}/${z_} | showing ${c$.length} of ${v.length} | sort=${k} ${u} | search=${K||"none"} | tag=${F}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let E$ of c$)console.log(`${E$.id} ${v$(E$.title,80)} ${E$.created_at}${E$.url?` ${v$(E$.url,90)}`:""}${E$.tags?.length?` ${v$(`[${E$.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${H}/${z_} | showing ${c$.length} of ${v.length} | sort=${k} ${u} | search=${K||"none"} | tag=${F}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(U==="get"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);h({ok:!0,item:B,store_exists:L.exists,message:`${B.id}: ${B.title}`},J.json,J);return}if(U==="versions"){E2(J);let B=Number.isFinite(J.page)&&J.page>0?J.page:1,H=Number.isFinite(J.limit)&&J.limit>0?J.limit:void 0,V=await L.listVersions(J.id,{limit:H,offset:(B-1)*(H??50)});if(!V)throw Error(`Item not found: ${J.id}`);let K={ok:!0,id:V.item_id,current_version:V.current_version,total:V.total,page:B,store:L.location,versions:V.items,message:V.total===0?`${V.item_id} is at version ${V.current_version} with no retained prior versions`:`${V.item_id} is at version ${V.current_version}; ${V.total} prior version(s) retained`};if(J.json||J.verbose){h(K,J.json,J);return}console.log(K.message);for(let E of V.items){let F=E.actor?` by ${E.actor}`:"",w=E.reason?` (${E.reason})`:"";console.log(`v${E.version} ${E.valid_to}${F}${w} ${E.content_bytes} bytes ${E.content_hash.slice(0,12)}`)}if(V.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(U==="diff"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);if(J.rev!==void 0&&(J.from!==void 0||J.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let H=()=>({title:B.title,content:B.content,url:B.url,tags:B.tags??[],metadata:B.metadata??{},archived:B.archived??!1}),V=`v${B.version??"?"} (current)`,K=async(v)=>{if(v==="current")return{label:V,snapshot:H()};let k=Number(v);if(!Number.isInteger(k)||k<1)throw Error(`Not a version number: ${v}`);if(B.version!==void 0&&k===B.version)return{label:V,snapshot:H()};let u=await L.getVersion(B.id,k);if(!u)throw Error(`No version ${k} retained for ${B.id} (it is at version ${B.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${u.version}`,snapshot:{title:u.title,content:u.content,url:u.url,tags:u.tags,metadata:u.metadata,archived:u.archived}}},E,F;if(J.rev!==void 0){if(!Number.isInteger(J.rev)||J.rev<1)throw Error("--rev must be a positive version number.");if(J.rev===1)throw Error("Version 1 has no predecessor to diff against.");E=String(J.rev-1),F=String(J.rev)}else if(J.from!==void 0||J.to!==void 0){if(J.from===void 0||J.to===void 0)throw Error("--from and --to must be given together.");E=J.from,F=J.to}else{let v=await L.listVersions(B.id,{limit:1});if(!v)throw Error(`Item not found: ${J.id}`);if(v.items.length===0)throw Error(`${B.id} is at version ${v.current_version} with no retained prior versions to diff against.`);E=String(v.items[0].version),F="current"}let w=await K(E),A=await K(F),g=sN(w.snapshot,A.snapshot);if(J.json||J.verbose){h({ok:!0,id:B.id,from:w.label,to:A.label,...g},J.json,J);return}console.log(eN(g,`${B.id} ${w.label}`,`${B.id} ${A.label}`));return}if(U==="update"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H={};if(J.title!==void 0)H.title=J.title;if(J.content!==void 0)H.content=J.content;if(J.url!==void 0)H.url=J.url;let V;if(J.tag!==void 0){if(V=NA(B.tags,J.tag),V.length>0)H.tags=[...B.tags??[],...V]}let K=await L.update(B.id,H,{expectedVersion:B.version});h(AB({ok:!0,item:K},`Updated ${K?.id??B.id}`,V),J.json,J);return}if(U==="archive"||U==="restore"){E2(J);let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H=await L.update(B.id,{archived:U==="archive"},{expectedVersion:B.version});h({ok:!0,item:H,message:`${U==="archive"?"Archived":"Restored"} ${H?.id??B.id}`},J.json,J);return}if(U==="untag"){if(E2(J),!J.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let B=await L.get(J.id);if(!B)throw Error(`Item not found: ${J.id}`);let H=B.tags??[],V=new Set(H.map((k)=>k.toLowerCase())),K=new Set;for(let k of J.tagRaw??J.tag){let u=k.trim().toLowerCase();if(u.length>0&&V.has(u)){K.add(u);continue}for(let W_ of k.split(",").map((c$)=>c$.trim().toLowerCase()).filter((c$)=>c$.length>0))K.add(W_)}let E=H.filter((k)=>!K.has(k.toLowerCase())),F=H.length-E.length,w=[...K].filter((k)=>!V.has(k));if(F===0)throw Error(`No matching tag on ${B.id}: ${w.map((k)=>JSON.stringify(k)).join(", ")} not in [${H.map((k)=>JSON.stringify(k)).join(", ")}]`);let A=await L.update(B.id,{tags:E},{expectedVersion:B.version}),g=w.length>0?` (not found: ${w.map((k)=>JSON.stringify(k)).join(", ")})`:"",v={ok:!0,item:A,removed:F,message:`Removed ${F} tag${F===1?"":"s"} from ${A?.id??B.id}${g}`};if(w.length>0)v.not_found=w;h(v,J.json,J);return}if(U==="upsert"){let B=J.title??_[1],H=J.content??_[2],V=J.id?await L.get(J.id):null;if(!V){if(!B||!H)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let w=await L.create({id:J.id,title:B,content:H,url:J.url??null,tags:J.tag??[]});h(AB({ok:!0,created:!0,item:w},`Upserted ${w.id}`,J.tag),J.json,J);return}let K={};if(B!==void 0)K.title=B;if(H!==void 0)K.content=H;if(J.url!==void 0)K.url=J.url;let E;if(J.tag!==void 0){if(E=NA(V.tags,J.tag),E.length>0)K.tags=[...V.tags??[],...E]}let F=await L.update(V.id,K,{expectedVersion:V.version});h(AB({ok:!0,created:!1,item:F},`Upserted ${F?.id??V.id}`,E),J.json,J);return}if(U==="delete"){if(E2(J),!J.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await L.delete(J.id))throw Error(`Item not found: ${J.id}`);M2("info","Item deleted",{id:J.id,transport:L.kind}),h({ok:!0,deleted_id:J.id,message:`Deleted ${J.id}`},J.json,J);return}if(U==="export"){let B=J.format??"json";if(B!=="json"&&B!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let H=await L.listAll();if(B==="jsonl")for(let V of H.items)console.log(JSON.stringify(V));else if(J.json||J.format==="json"||J.verbose)h({ok:!0,items:H.items,store_exists:H.exists},J.json||J.format==="json",J);else h(ro(H.items,B),!1);return}if(U==="prune"){if(!J.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:B}=await L.listAll(),H=J.olderThan!==void 0?new Date(Date.now()-J.olderThan*86400000):null,V=B.filter((F)=>H!==null&&new Date(F.created_at)<H||J.empty&&F.content.trim().length===0),K=await L.deleteMany(V.map((F)=>F.id)),E=B.length-K;M2("info","Prune completed",{pruned:K,remaining:E,transport:L.kind}),h({ok:!0,pruned:K,remaining:E,message:`Pruned ${K} item(s)`},J.json,J);return}if(U==="dedupe"){if(!J.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:B}=await L.listAll(),H=new Set,V=[];for(let F of B){let w=`${F.title}\x00${F.content}`;if(H.has(w))V.push(F);else H.add(w)}let K=await L.deleteMany(V.map((F)=>F.id)),E=B.length-K;M2("info","Dedupe completed",{removed:K,remaining:E,transport:L.kind}),h({ok:!0,removed:K,remaining:E,message:`Dedupe removed ${K} duplicate(s)`},J.json,J);return}if(U==="stats"){let B=await L.listAll(),H=B.items.filter((k)=>!k.archived),V=H.length,K=B.items.length-V,E=H.filter((k)=>k.url).length,F=H.filter((k)=>k.tags&&k.tags.length>0).length,w=V>0?H.map((k)=>k.created_at).sort()[0]:null,A=V>0?H.map((k)=>k.created_at).sort()[V-1]:null,g={};for(let k of H)for(let u of k.tags||[])g[u]=(g[u]||0)+1;let v=Object.entries(g).sort((k,u)=>u[1]-k[1]).slice(0,5).map(([k,u])=>({tag:k,count:u}));h({ok:!0,total:V,archived:K,with_url:E,with_tags:F,oldest:w,newest:A,top_tags:v,store_exists:B.exists,message:`${V} items | ${E} with URL | ${F} with tags`},J.json,J);return}let N=Ao(_[0]),R=N?` Did you mean '${N}'?`:"";throw M2("warn","Unknown command",{input:_[0],suggestion:N}),Error(`Unknown command: ${_[0]}.${R} Run 'knowledge --help' for available commands.`)}function to($,_){let J=$ instanceof Error?$.message:String($);if(M2("debug","CLI error",{message:J,stack:$ instanceof Error?$.stack:void 0}),console.error(`Error: ${J}`),_.includes("--json"))h({ok:!1,error:J,message:J},!0);process.exitCode=1}if(import.meta.main){let $=process.argv.slice(2);oo($).catch((_)=>to(_,$))}export{Ao as suggestCommand,po as sortItems,oo as run,Fo as parseArgs,to as emitCliError}; diff --git a/dist/index.js b/dist/index.js index 6ff0b90..ca41938 100644 --- a/dist/index.js +++ b/dist/index.js @@ -34237,7 +34237,7 @@ function assertLocalCatalogMode(operation = "catalog") { throw new Error(`knowledge: ${operation} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, ` + `wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in ` + `cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item ` + `commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${modeKey}=local ` + `(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see ` + `which variable selected the current backend.`); } } -var CURRENT_SCHEMA_VERSION = 9; +var CURRENT_SCHEMA_VERSION = 10; var CHUNKS_FTS_TOKENIZE = "porter unicode61 remove_diacritics 2"; var MIGRATION_1 = ` PRAGMA journal_mode = WAL; @@ -34659,6 +34659,68 @@ VALUES (9, datetime('now')); COMMIT; `; +var MIGRATION_10_PROMOTION_INBOX = ` +CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + source_kind TEXT NOT NULL, + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'pending', + requires_approval INTEGER NOT NULL DEFAULT 0, + checks_json TEXT NOT NULL DEFAULT '{}', + idempotency_key TEXT NOT NULL UNIQUE, + duplicate_of TEXT, + approved_by TEXT, + promoted_record_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + reviewed_at TEXT, + promoted_at TEXT +); + +CREATE TABLE IF NOT EXISTS durable_knowledge_records ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + confidence REAL, + valid_from TEXT NOT NULL, + valid_to TEXT, + promoted_from_candidate_id TEXT NOT NULL UNIQUE + REFERENCES knowledge_promotion_candidates(id) ON DELETE RESTRICT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_status + ON knowledge_promotion_candidates(status, updated_at); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_kind_key + ON knowledge_promotion_candidates(record_kind, canonical_key); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_hash + ON knowledge_promotion_candidates(record_kind, content_hash); +CREATE INDEX IF NOT EXISTS idx_durable_records_kind_key + ON durable_knowledge_records(record_kind, canonical_key, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_hash + ON durable_knowledge_records(record_kind, content_hash, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_validity + ON durable_knowledge_records(status, valid_to); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (10, datetime('now')); +`; function openKnowledgeDb(path) { assertLocalCatalogMode("opening the local knowledge.db catalog"); ensureParentDir(path); @@ -34691,6 +34753,8 @@ function migrateKnowledgeDb(path) { applyMigration8(db); if (needsMigration9(db)) applyMigration9(db); + if (needsMigration10(db)) + applyMigration10(db); return { path, schema_version: getSchemaVersion(db) }; } finally { db.close(); @@ -34771,6 +34835,12 @@ function applyMigration9(db) { } db.exec(MIGRATION_9_REBUILD_FTS); } +function needsMigration10(db) { + return getSchemaVersion(db) < 10 || !tableExists(db, "knowledge_promotion_candidates") || !tableExists(db, "durable_knowledge_records"); +} +function applyMigration10(db) { + db.exec(MIGRATION_10_PROMOTION_INBOX); +} function getKnowledgeDbStats(path) { const db = openKnowledgeDb(path); try { @@ -34796,7 +34866,9 @@ function getKnowledgeDbStats(path) { sync_changes: count(db, "knowledge_sync_changes"), sync_conflicts: count(db, "knowledge_sync_conflicts"), sync_table_clocks: count(db, "knowledge_sync_table_clocks"), - sync_imports: count(db, "knowledge_sync_imports") + sync_imports: count(db, "knowledge_sync_imports"), + promotion_candidates: count(db, "knowledge_promotion_candidates"), + durable_records: count(db, "durable_knowledge_records") }; } finally { db.close(); @@ -36972,7 +37044,7 @@ function createArtifactStore(config, workspace) { } // src/service.ts -import { createHash as createHash20 } from "crypto"; +import { createHash as createHash21 } from "crypto"; import { spawnSync as spawnSync2 } from "child_process"; import { existsSync as existsSync14, readFileSync as readFileSync14 } from "fs"; import { hostname as hostname5 } from "os"; @@ -37639,6 +37711,23 @@ function recordRedactionFindings(db, input) { } return input.findings.length; } +function createApprovalGate(db, input) { + const now = input.created_at ?? new Date().toISOString(); + const id = `approval_${randomUUID3()}`; + db.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + id, + input.action, + input.target_uri ?? null, + "approved", + input.reason ?? null, + input.approved_by ?? "local-cli", + JSON.stringify(input.metadata ?? {}), + now, + now + ]); + return { id, status: "approved" }; +} var COMMON_BARE_TOKEN_PATTERNS = [ { type: "github_token", severity: "high", regex: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_token]" }, { type: "github_pat_token", severity: "high", regex: /\bgithub[_]pat[_][A-Za-z0-9_]{20,}\b/g, replacement: "[REDACTED:github_pat_token]" }, @@ -45305,10 +45394,503 @@ function createKnowledgeMachinesAdapter(defaults = {}) { }; } +// src/promotion-inbox.ts +import { createHash as createHash14 } from "crypto"; +function stableId7(prefix, value, length = 24) { + return `${prefix}_${createHash14("sha256").update(value).digest("hex").slice(0, length)}`; +} +function normalizedText(value) { + return value.normalize("NFKC").trim().replace(/\s+/g, " "); +} +function normalizedKey(value) { + return normalizedText(value).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, ""); +} +function parseJson3(value, fallback) { + try { + return JSON.parse(value); + } catch { + return fallback; + } +} +function asCandidate(row) { + return { + ...row, + record_kind: row.record_kind, + source_kind: row.source_kind, + status: row.status, + source_refs: parseJson3(row.source_refs_json, []), + evidence_refs: parseJson3(row.evidence_refs_json, []), + requires_approval: row.requires_approval === 1, + checks: parseJson3(row.checks_json, emptyChecks()), + metadata: parseJson3(row.metadata_json, {}) + }; +} +function asDurableRecord(row) { + return { + ...row, + record_kind: row.record_kind, + source_refs: parseJson3(row.source_refs_json, []), + evidence_refs: parseJson3(row.evidence_refs_json, []), + metadata: parseJson3(row.metadata_json, {}) + }; +} +function emptyChecks() { + return { + citations: { provided: 0, valid: 0, invalid: 0, entries: [] }, + invalid_source_refs: [], + stale_refs: [], + duplicate_record_ids: [], + duplicate_candidate_ids: [], + conflicting_record_ids: [], + conflicting_candidate_ids: [], + approval_reasons: [] + }; +} +function normalizeEvidenceRef(input) { + const value = typeof input === "string" ? { ref: input } : input; + return { + ref: normalizedText(value.ref), + citation_id: value.citation_id ?? null, + chunk_id: value.chunk_id ?? null, + revision: value.revision ?? null, + hash: value.hash ?? null, + observed_at: value.observed_at ?? null, + expires_at: value.expires_at ?? null, + status: value.status ?? null + }; +} +function validReference(ref) { + try { + const parsed = new URL(ref); + return parsed.protocol.length > 1 && (parsed.hostname.length > 0 || parsed.pathname.length > 0); + } catch { + return /^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(ref); + } +} +function staleStatus(status) { + return ["deleted", "stale", "invalidated", "reindex_required", "expired", "superseded"].includes((status ?? "").toLowerCase()); +} +function metadataStatus(value) { + if (!value) + return null; + const metadata = parseJson3(value, {}); + if (metadata.stale === true) + return "stale"; + return typeof metadata.status === "string" ? metadata.status : null; +} +function citationIdentifier(evidence) { + if (evidence.citation_id) + return evidence.citation_id; + const match = evidence.ref.match(/^(?:cite|citation):(.+)$/); + return match?.[1] ?? null; +} +function chunkIdentifier(evidence) { + if (evidence.chunk_id) + return evidence.chunk_id; + const match = evidence.ref.match(/^chunk:(.+)$/); + return match?.[1] ?? null; +} +function inspectCitation(db, evidence, now) { + const explicitStale = staleStatus(evidence.status) || Boolean(evidence.expires_at && evidence.expires_at <= now); + if (!evidence.ref || !validReference(evidence.ref)) { + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "invalid_reference" }; + } + const citationId = citationIdentifier(evidence); + const citation = db.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, + sr.source_id, sr.created_at AS revision_created_at, + (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at + FROM citations c + LEFT JOIN chunks ch ON ch.id = c.chunk_id + LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE c.id = ? OR c.source_uri = ? + ORDER BY c.created_at DESC + LIMIT 1`).get(citationId, evidence.ref); + if (citation) { + const hashMismatch = Boolean(evidence.hash && citation.revision_hash && evidence.hash !== citation.revision_hash); + const revisionMismatch = Boolean(evidence.revision && citation.revision && evidence.revision !== citation.revision); + const oldRevision = Boolean(citation.revision_created_at && citation.latest_revision_at && citation.revision_created_at < citation.latest_revision_at); + const stale = explicitStale || staleStatus(metadataStatus(citation.chunk_metadata_json)) || hashMismatch || revisionMismatch || oldRevision; + return { + ref: evidence.ref, + valid: true, + resolved_by: "citation", + stale, + reason: hashMismatch ? "hash_mismatch" : revisionMismatch ? "revision_mismatch" : oldRevision ? "newer_source_revision" : stale ? "stale_citation" : null + }; + } + const chunkId = chunkIdentifier(evidence); + if (chunkId) { + const chunk = db.query(`SELECT ch.metadata_json, sr.hash, sr.revision + FROM chunks ch LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE ch.id = ?`).get(chunkId); + if (!chunk) + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "chunk_not_found" }; + const mismatch = Boolean(evidence.hash && chunk.hash && evidence.hash !== chunk.hash || evidence.revision && chunk.revision && evidence.revision !== chunk.revision); + const stale = explicitStale || staleStatus(metadataStatus(chunk.metadata_json)) || mismatch; + return { ref: evidence.ref, valid: true, resolved_by: "chunk", stale, reason: mismatch ? "source_version_mismatch" : stale ? "stale_chunk" : null }; + } + const source = db.query("SELECT metadata_json FROM sources WHERE uri = ? LIMIT 1").get(evidence.ref); + if (source) { + const stale = explicitStale || staleStatus(metadataStatus(source.metadata_json)); + return { ref: evidence.ref, valid: true, resolved_by: "source", stale, reason: stale ? "stale_source" : null }; + } + const runMatch = evidence.ref.match(/^knowledge:\/\/project\/runs\/([^/?#]+)/); + if (runMatch) { + const run = db.query("SELECT id FROM runs WHERE id = ?").get(decodeURIComponent(runMatch[1])); + if (!run) + return { ref: evidence.ref, valid: false, resolved_by: "none", stale: explicitStale, reason: "run_not_found" }; + return { ref: evidence.ref, valid: true, resolved_by: "run", stale: explicitStale, reason: explicitStale ? "expired_evidence" : null }; + } + return { + ref: evidence.ref, + valid: true, + resolved_by: "external_uri", + stale: explicitStale, + reason: explicitStale ? "expired_evidence" : null + }; +} +function candidateById(db, id) { + return db.query("SELECT * FROM knowledge_promotion_candidates WHERE id = ?").get(id) ?? null; +} +function assessCandidate(db, row, now) { + const evidence = parseJson3(row.evidence_refs_json, []); + const sourceRefs = parseJson3(row.source_refs_json, []); + const metadata = parseJson3(row.metadata_json, {}); + const checks3 = emptyChecks(); + checks3.invalid_source_refs = sourceRefs.filter((ref) => !validReference(ref)); + checks3.citations.entries = evidence.map((entry) => inspectCitation(db, entry, now)); + checks3.citations.provided = evidence.length; + checks3.citations.valid = checks3.citations.entries.filter((entry) => entry.valid).length; + checks3.citations.invalid = checks3.citations.entries.length - checks3.citations.valid; + checks3.stale_refs = checks3.citations.entries.filter((entry) => entry.stale).map((entry) => entry.ref); + checks3.duplicate_record_ids = db.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND content_hash = ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(row.record_kind, row.content_hash).map((entry) => entry.id); + checks3.duplicate_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND content_hash = ? AND status NOT IN ('rejected') + ORDER BY created_at`).all(row.id, row.record_kind, row.content_hash).map((entry) => entry.id); + checks3.conflicting_record_ids = db.query(`SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('active', 'conflicted') + ORDER BY created_at`).all(row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + checks3.conflicting_candidate_ids = db.query(`SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND canonical_key = ? AND content_hash <> ? + AND status IN ('ready', 'needs_approval', 'promoted') + ORDER BY created_at`).all(row.id, row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + const duplicateOf = checks3.duplicate_record_ids[0] ?? checks3.duplicate_candidate_ids[0] ?? null; + const blocked = sourceRefs.length === 0 || evidence.length === 0 || checks3.invalid_source_refs.length > 0 || checks3.citations.invalid > 0; + if (row.record_kind === "decision" || row.record_kind === "claim") + checks3.approval_reasons.push(`${row.record_kind}_requires_review`); + if (metadata.requested_approval === true) + checks3.approval_reasons.push("explicit_approval_request"); + if (checks3.stale_refs.length > 0) + checks3.approval_reasons.push("stale_evidence"); + if (checks3.conflicting_record_ids.length > 0 || checks3.conflicting_candidate_ids.length > 0) { + checks3.approval_reasons.push("conflicting_knowledge"); + } + const requiresApproval = checks3.approval_reasons.length > 0; + const status = duplicateOf ? "duplicate" : blocked ? "blocked" : requiresApproval ? "needs_approval" : "ready"; + db.run(`UPDATE knowledge_promotion_candidates + SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, [status, requiresApproval ? 1 : 0, JSON.stringify(checks3), duplicateOf, now, now, row.id]); + return asCandidate(candidateById(db, row.id)); +} +function enqueueKnowledgePromotion(dbPath, input) { + const kinds = ["lesson", "decision", "claim"]; + const sourceKinds = ["memento", "session", "report"]; + if (!kinds.includes(input.kind)) + throw new Error("Promotion kind must be lesson, decision, or claim."); + if (!sourceKinds.includes(input.sourceKind)) + throw new Error("Promotion source kind must be memento, session, or report."); + const titleResult = redactSecrets(normalizedText(input.title)); + const contentResult = redactSecrets(normalizedText(input.content)); + if (!titleResult.text) + throw new Error("Promotion title is required."); + if (!contentResult.text) + throw new Error("Promotion content is required."); + const sourceRefs = Array.from(new Set(input.sourceRefs.map(normalizedText).filter(Boolean))).sort(); + const evidenceRefs = input.evidenceRefs.map(normalizeEvidenceRef).filter((entry) => entry.ref.length > 0).sort((a, b) => a.ref.localeCompare(b.ref)); + const canonicalKey = normalizedKey(input.canonicalKey ?? titleResult.text); + if (!canonicalKey) + throw new Error("Promotion canonical key is empty after normalization."); + const contentHash = `sha256:${createHash14("sha256").update(`${input.kind}\x00${normalizedText(contentResult.text).toLowerCase()}`).digest("hex")}`; + const idempotencyKey = stableId7("promote", [ + input.sourceKind, + input.kind, + canonicalKey, + contentHash, + ...sourceRefs + ].join("\x00")); + const id = stableId7("promotion", idempotencyKey); + const now = (input.now ?? new Date).toISOString(); + const metadata = { + ...input.metadata ?? {}, + requested_approval: input.requiresApproval === true, + confidence: input.confidence ?? null, + valid_from: input.validFrom ?? now, + valid_to: input.validTo ?? null, + redactions: titleResult.findings.length + contentResult.findings.length + }; + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const existing = db.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(idempotencyKey); + if (existing) + return { created: false, candidate: asCandidate(existing) }; + db.run(`INSERT INTO knowledge_promotion_candidates ( + id, record_kind, title, content, canonical_key, content_hash, source_kind, + source_refs_json, evidence_refs_json, status, requires_approval, checks_json, + idempotency_key, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`, [ + id, + input.kind, + titleResult.text, + contentResult.text, + canonicalKey, + contentHash, + input.sourceKind, + JSON.stringify(sourceRefs), + JSON.stringify(evidenceRefs), + idempotencyKey, + JSON.stringify(metadata), + now, + now + ]); + const findings = [...titleResult.findings, ...contentResult.findings]; + if (findings.length > 0) { + recordRedactionFindings(db, { + source_uri: sourceRefs[0] ?? `knowledge://promotion/${id}`, + findings, + metadata: { promotion_candidate_id: id }, + created_at: now + }); + } + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "enqueue_promotion", + target_uri: `knowledge://promotion/${id}`, + decision: "info", + metadata: { record_kind: input.kind, source_kind: input.sourceKind, source_refs: sourceRefs }, + created_at: now + }); + return { created: true, candidate: assessCandidate(db, candidateById(db, id), now) }; + } finally { + db.close(); + } +} +function getKnowledgePromotion(dbPath, id) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const row = candidateById(db, id); + return row ? asCandidate(row) : null; + } finally { + db.close(); + } +} +function listKnowledgePromotions(dbPath, options = {}) { + migrateKnowledgeDb(dbPath); + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const conditions = []; + const params = []; + if (options.status === "inbox" || !options.status) { + conditions.push("status IN ('ready', 'needs_approval', 'blocked')"); + } else { + conditions.push("status = ?"); + params.push(options.status); + } + if (options.kind) { + conditions.push("record_kind = ?"); + params.push(options.kind); + } + const db = openKnowledgeDb(dbPath); + try { + return db.query(`SELECT * FROM knowledge_promotion_candidates + WHERE ${conditions.join(" AND ")} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...params, limit).map(asCandidate); + } finally { + db.close(); + } +} +function reviewKnowledgePromotion(dbPath, id, now = new Date) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted" || row.status === "rejected") + return asCandidate(row); + return assessCandidate(db, row, now.toISOString()); + } finally { + db.close(); + } +} +function promoteKnowledgeCandidate(dbPath, id, options = {}) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = (options.now ?? new Date).toISOString(); + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted" && row.promoted_record_id) { + const existingRecord = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(row.promoted_record_id); + return { + ok: true, + promoted: false, + requires_approval: row.requires_approval === 1, + candidate: asCandidate(row), + record: existingRecord ? asDurableRecord(existingRecord) : null, + approval_id: null, + reason: "already_promoted" + }; + } + if (row.status === "rejected") + throw new Error(`Promotion candidate ${id} was rejected.`); + const candidate = assessCandidate(db, row, now); + if (candidate.status === "duplicate") { + return { ok: true, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "duplicate" }; + } + if (candidate.status === "blocked") { + return { ok: false, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: "citation_check_failed" }; + } + if (candidate.requires_approval && !options.approveWrite) { + return { ok: false, promoted: false, requires_approval: true, candidate, record: null, approval_id: null, reason: "approval_required" }; + } + if (candidate.requires_approval && !options.approvedBy?.trim()) { + throw new Error("Promotion approval requires --approved-by <name>."); + } + const approvedBy = candidate.requires_approval ? options.approvedBy.trim() : null; + let approvalId = null; + if (candidate.requires_approval) { + approvalId = createApprovalGate(db, { + action: "promote_durable_knowledge", + target_uri: `knowledge://promotion/${candidate.id}`, + reason: candidate.checks.approval_reasons.join(", "), + approved_by: approvedBy, + metadata: { promotion_candidate_id: candidate.id, checks: candidate.checks }, + created_at: now + }).id; + } + const recordId = stableId7("durable", candidate.id); + const metadata = { + ...candidate.metadata, + promotion_candidate_id: candidate.id, + source_kind: candidate.source_kind, + checks: candidate.checks, + approval_id: approvalId, + provenance: generatedArtifactProvenance({ + generated_from: `knowledge://promotion/${candidate.id}`, + artifact_key: `durable/${candidate.record_kind}/${candidate.canonical_key}`, + source_refs: candidate.source_refs, + citation_required: true + }) + }; + db.run(`INSERT INTO durable_knowledge_records ( + id, record_kind, title, content, canonical_key, content_hash, status, + source_refs_json, evidence_refs_json, confidence, valid_from, valid_to, + promoted_from_candidate_id, approved_by, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ + recordId, + candidate.record_kind, + candidate.title, + candidate.content, + candidate.canonical_key, + candidate.content_hash, + candidate.checks.conflicting_record_ids.length > 0 ? "conflicted" : "active", + JSON.stringify(candidate.source_refs), + JSON.stringify(candidate.evidence_refs), + typeof candidate.metadata.confidence === "number" ? candidate.metadata.confidence : null, + typeof candidate.metadata.valid_from === "string" ? candidate.metadata.valid_from : now, + typeof candidate.metadata.valid_to === "string" ? candidate.metadata.valid_to : null, + candidate.id, + approvedBy, + JSON.stringify(metadata), + now, + now + ]); + db.run(`UPDATE knowledge_promotion_candidates + SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? + WHERE id = ?`, [approvedBy, recordId, now, now, candidate.id]); + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "promote_durable_knowledge", + target_uri: `knowledge://durable/${recordId}`, + decision: "allow", + metadata: { promotion_candidate_id: candidate.id, approval_id: approvalId, source_refs: candidate.source_refs }, + created_at: now + }); + const promotedCandidate = asCandidate(candidateById(db, candidate.id)); + const record2 = db.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(recordId); + return { + ok: true, + promoted: true, + requires_approval: candidate.requires_approval, + candidate: promotedCandidate, + record: asDurableRecord(record2), + approval_id: approvalId, + reason: null + }; + } finally { + db.close(); + } +} +function rejectKnowledgePromotion(dbPath, id, options = {}) { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = (options.now ?? new Date).toISOString(); + try { + const row = candidateById(db, id); + if (!row) + throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === "promoted") + throw new Error(`Promotion candidate ${id} is already promoted.`); + db.run(`UPDATE knowledge_promotion_candidates + SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, [options.rejectedBy?.trim() || null, now, now, id]); + recordAuditEvent(db, { + event_type: "knowledge_promotion", + action: "reject_promotion", + target_uri: `knowledge://promotion/${id}`, + decision: "deny", + metadata: { rejected_by: options.rejectedBy ?? null }, + created_at: now + }); + return asCandidate(candidateById(db, id)); + } finally { + db.close(); + } +} +function listDurableKnowledgeRecords(dbPath, options = {}) { + migrateKnowledgeDb(dbPath); + const conditions = []; + const params = []; + if (options.kind) { + conditions.push("record_kind = ?"); + params.push(options.kind); + } + if (options.status) { + conditions.push("status = ?"); + params.push(options.status); + } + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const db = openKnowledgeDb(dbPath); + try { + return db.query(`SELECT * FROM durable_knowledge_records + ${conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`).all(...params, limit).map(asDurableRecord); + } finally { + db.close(); + } +} + // src/reindex.ts -import { createHash as createHash14, randomUUID as randomUUID10 } from "crypto"; -function stableId7(prefix, value) { - return `${prefix}_${createHash14("sha256").update(value).digest("hex").slice(0, 20)}`; +import { createHash as createHash15, randomUUID as randomUUID10 } from "crypto"; +function stableId8(prefix, value) { + return `${prefix}_${createHash15("sha256").update(value).digest("hex").slice(0, 20)}`; } function queueCounts(dbPath) { const db = openKnowledgeDb(dbPath); @@ -45368,7 +45950,7 @@ function enqueueMissingEmbeddings(options) { try { const write = db.transaction(() => { for (const row of rows) { - const id = stableId7("rq", `embedding\x00${row.chunk_id}\x00${reason}`); + const id = stableId8("rq", `embedding\x00${row.chunk_id}\x00${reason}`); const before = db.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding", row.chunk_id, reason); if (before) { alreadyQueued += 1; @@ -45493,7 +46075,7 @@ async function refreshEmbeddingIndex(options) { } // src/rules-provenance.ts -import { createHash as createHash15 } from "crypto"; +import { createHash as createHash16 } from "crypto"; import { existsSync as existsSync11, lstatSync as lstatSync2, readdirSync as readdirSync2, readFileSync as readFileSync12, statSync as statSync2 } from "fs"; import { basename as basename5, extname as extname2, join as join6, relative as relative4, resolve as resolve4, sep as sep4 } from "path"; import { pathToFileURL as pathToFileURL3 } from "url"; @@ -45525,10 +46107,10 @@ var SKIP_DIRECTORIES = new Set([ var SENSITIVE_PATH_RE = /(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i; var SELECTED_PROMPT_OR_PLAN_RE = /(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i; function sha256Text2(text) { - return `sha256:${createHash15("sha256").update(text).digest("hex")}`; + return `sha256:${createHash16("sha256").update(text).digest("hex")}`; } function sha256Bytes(bytes) { - return `sha256:${createHash15("sha256").update(bytes).digest("hex")}`; + return `sha256:${createHash16("sha256").update(bytes).digest("hex")}`; } function normalizePath(value) { return value.split(sep4).join("/"); @@ -46045,9 +46627,9 @@ async function importRulesProvenance(options = {}) { } // src/web-search.ts -import { createHash as createHash16, randomUUID as randomUUID11 } from "crypto"; +import { createHash as createHash17, randomUUID as randomUUID11 } from "crypto"; function stableHash(value) { - return `sha256:${createHash16("sha256").update(value).digest("hex")}`; + return `sha256:${createHash17("sha256").update(value).digest("hex")}`; } function estimateTokens3(text) { const words = text.trim().split(/\s+/).filter(Boolean).length; @@ -46296,9 +46878,9 @@ async function runProviderWebSearch(options) { } // src/wiki-compiler.ts -import { createHash as createHash17, randomUUID as randomUUID12 } from "crypto"; -function stableId8(prefix, value) { - return `${prefix}_${createHash17("sha256").update(value).digest("hex").slice(0, 20)}`; +import { createHash as createHash18, randomUUID as randomUUID12 } from "crypto"; +function stableId9(prefix, value) { + return `${prefix}_${createHash18("sha256").update(value).digest("hex").slice(0, 20)}`; } function slugify3(value) { const slug = value.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80); @@ -46471,7 +47053,7 @@ function upsertWikiPage(db, input) { for (const row of existing) db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); db.run("DELETE FROM chunks WHERE wiki_page_id = ?", [input.pageId]); - const chunkId = stableId8("chk", `${input.pageId}\x00${input.contentHash}`); + const chunkId = stableId9("chk", `${input.pageId}\x00${input.contentHash}`); db.run(`INSERT INTO chunks (id, wiki_page_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ chunkId, @@ -46502,7 +47084,7 @@ function replacePageCitations(db, pageId, citations, now) { for (const citation of citations) { db.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ - stableId8("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID12()}`), + stableId9("cit", `${pageId}\x00${citation.source_uri}\x00${citation.chunk_id ?? randomUUID12()}`), pageId, citation.chunk_id, citation.source_uri, @@ -46522,7 +47104,7 @@ function upsertIndex(db, input) { artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`, [ - stableId8("idx", `wiki-topic\x00${input.path}`), + stableId9("idx", `wiki-topic\x00${input.path}`), "wiki_topic", input.title, input.artifactUri, @@ -46571,7 +47153,7 @@ async function compileWikiPage(options) { content_type: "text/markdown", metadata: { generated_from: "wiki_compile" } }); - const pageId = stableId8("wiki", path); + const pageId = stableId9("wiki", path); const citations = rows.map((row) => ({ chunk_id: row.chunk_id, source_uri: row.source_uri ?? "unknown", @@ -46600,7 +47182,7 @@ async function compileWikiPage(options) { content_type: "text/markdown", metadata: { generated_from: "wiki_compile_concept" } }); - const conceptPageId = stableId8("wiki", conceptPath); + const conceptPageId = stableId9("wiki", conceptPath); const log = await appendLog2(options.store, { ts: now, event: "wiki_compile_completed", @@ -46706,7 +47288,7 @@ async function fileAnswerToWiki(options) { prompt: options.prompt, citations: citations.length }, nowDate); - const pageId = stableId8("wiki", path); + const pageId = stableId9("wiki", path); const db = openKnowledgeDb(options.dbPath); try { recordStorageObjects(db, [artifact, log], nowDate); @@ -47013,15 +47595,15 @@ function resolveItemStore(options) { } // src/wiki-layout.ts -import { createHash as createHash18 } from "crypto"; +import { createHash as createHash19 } from "crypto"; function todayParts2(now) { const year = String(now.getUTCFullYear()); const month = String(now.getUTCMonth() + 1).padStart(2, "0"); const day = String(now.getUTCDate()).padStart(2, "0"); return { year, month, day }; } -function stableId9(prefix, value) { - return `${prefix}_${createHash18("sha256").update(value).digest("hex").slice(0, 20)}`; +function stableId10(prefix, value) { + return `${prefix}_${createHash19("sha256").update(value).digest("hex").slice(0, 20)}`; } function estimateTokenCount4(text) { const words = text.trim().split(/\s+/).filter(Boolean).length; @@ -47140,7 +47722,7 @@ function provenanceFor(artifact) { } function recordWikiChunk(db, pageId, title, artifact, body, now) { const provenance = provenanceFor(artifact); - const chunkId = stableId9("chk", `${pageId}\x00${artifact.hash ?? artifact.uri}`); + const chunkId = stableId10("chk", `${pageId}\x00${artifact.hash ?? artifact.uri}`); const existing = db.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all(pageId); for (const row of existing) db.run("DELETE FROM chunks_fts WHERE chunk_id = ?", [row.id]); @@ -47176,7 +47758,7 @@ function recordWikiLayoutCatalog(db, artifacts, now = new Date) { artifact_uri = excluded.artifact_uri, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at`, [ - stableId9("idx", "root:indexes/root.md"), + stableId10("idx", "root:indexes/root.md"), "root", "root", rootIndex.uri, @@ -47191,7 +47773,7 @@ function recordWikiLayoutCatalog(db, artifacts, now = new Date) { ]); } if (wikiReadme) { - const wikiPageId = stableId9("wiki", "wiki/README.md"); + const wikiPageId = stableId10("wiki", "wiki/README.md"); db.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET @@ -47219,7 +47801,7 @@ function recordWikiLayoutCatalog(db, artifacts, now = new Date) { } // src/workspace-migration.ts -import { createHash as createHash19 } from "crypto"; +import { createHash as createHash20 } from "crypto"; import { cpSync, chmodSync as chmodSync4, @@ -47246,12 +47828,12 @@ function walkFiles(root, base = root) { function hashFiles(root, files) { if (files.length === 0) return { sha256: null, bytes: 0 }; - const tree = createHash19("sha256"); + const tree = createHash20("sha256"); let bytes = 0; for (const file2 of files) { const path = join7(root, file2); const body = readFileSync13(path); - const fileHash = createHash19("sha256").update(body).digest("hex"); + const fileHash = createHash20("sha256").update(body).digest("hex"); bytes += body.byteLength; tree.update(file2); tree.update("\x00"); @@ -47866,7 +48448,7 @@ function resolvePeerWorkspace(input) { return ensureKnowledgeWorkspace(workspaceForHome(projectKnowledgeHome(target)).home); } function workspaceMachineId(workspace) { - return `${hostname5()}:${createHash20("sha256").update(workspace.home).digest("hex").slice(0, 12)}`; + return `${hostname5()}:${createHash21("sha256").update(workspace.home).digest("hex").slice(0, 12)}`; } function shellQuote2(value) { return `'${value.replace(/'/g, "'\\''")}'`; @@ -48156,6 +48738,44 @@ function rowsWithJsonFields(rows, fields = ["metadata_json"]) { return next; }); } +function parseInventoryJsonArray(value) { + if (typeof value !== "string") + return []; + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } +} +function parseInventoryJsonObject(value) { + if (typeof value !== "string") + return {}; + return parseMetadataJson(value); +} +function promotionCandidateInventoryRow(row) { + const next = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.requires_approval = next.requires_approval === 1 || next.requires_approval === true; + next.checks = parseInventoryJsonObject(next.checks_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.checks_json; + delete next.metadata_json; + return next; +} +function durableRecordInventoryRow(row) { + const next = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.metadata_json; + return next; +} function selectInventoryRows(db, sql, params = []) { return db.query(sql).all(...params); } @@ -48213,7 +48833,9 @@ function emptyKnowledgeDbStats() { sync_changes: 0, sync_conflicts: 0, sync_table_clocks: 0, - sync_imports: 0 + sync_imports: 0, + promotion_candidates: 0, + durable_records: 0 }; } function emptySearchResult(query2, limit, semantic = false) { @@ -48302,7 +48924,7 @@ function legacyAgentContextPack(options, context, policy) { redactions += quote.redactions; const ref = citation.source_ref ?? citation.source_uri ?? citation.artifact_path ?? citation.artifact_uri ?? citation.id; return { - id: `cite_${createHash20("sha256").update(`${citation.id}\x00${ref}`).digest("hex").slice(0, 12)}`, + id: `cite_${createHash21("sha256").update(`${citation.id}\x00${ref}`).digest("hex").slice(0, 12)}`, kind: citation.artifact_uri || citation.artifact_path ? "artifact" : "source", ref, source_ref: citation.source_ref, @@ -48328,7 +48950,7 @@ function legacyAgentContextPack(options, context, policy) { const preview2 = redactPreviewForPack(excerpt2.text, policy, 520); redactions += preview2.redactions; return { - id: `ev_${createHash20("sha256").update(`${excerpt2.kind}\x00${excerpt2.result_id}\x00${excerpt2.citation_id ?? ""}`).digest("hex").slice(0, 14)}`, + id: `ev_${createHash21("sha256").update(`${excerpt2.kind}\x00${excerpt2.result_id}\x00${excerpt2.citation_id ?? ""}`).digest("hex").slice(0, 14)}`, kind: excerpt2.kind, title: compactText(result?.title ?? citation?.ref ?? excerpt2.kind, 100), text_preview: preview2.text, @@ -48346,7 +48968,7 @@ function legacyAgentContextPack(options, context, policy) { const usedCitationIds = new Set(evidence.flatMap((entry) => entry.citation_ids)); const usedCitations = citations.filter((citation) => usedCitationIds.has(citation.id)); const warnings = Array.from(new Set(context.warnings)); - const idempotencyKey = `ctx_${createHash20("sha256").update([source, purpose, query2, warnings.join(","), evidence.map((entry) => entry.id).join(",")].join("\x00")).digest("hex").slice(0, 20)}`; + const idempotencyKey = `ctx_${createHash21("sha256").update([source, purpose, query2, warnings.join(","), evidence.map((entry) => entry.id).join(",")].join("\x00")).digest("hex").slice(0, 20)}`; const pack = { ok: true, format: "knowledge-agent-context-pack", @@ -48459,7 +49081,7 @@ function emptyAgentContextPack(options) { const query2 = (options.query ?? options.topic ?? "").normalize("NFKC").trim().replace(/\s+/g, " "); const maxItems = Math.max(1, Math.min(options.maxItems ?? options.limit ?? 8, 50)); const maxTokens = Math.max(500, Math.min(options.maxTokens ?? 6000, 1e5)); - const idempotencyKey = `ctx_${createHash20("sha256").update(["empty", source, purpose, query2, options.topic ?? "", options.since ?? ""].join("\x00")).digest("hex").slice(0, 20)}`; + const idempotencyKey = `ctx_${createHash21("sha256").update(["empty", source, purpose, query2, options.topic ?? "", options.since ?? ""].join("\x00")).digest("hex").slice(0, 20)}`; return { ok: true, format: "knowledge-agent-context-pack", @@ -49002,6 +49624,27 @@ class KnowledgeService { return emptyKnowledgeDbStats(); return getKnowledgeDbStats(workspace.knowledgeDbPath); } + enqueuePromotion(input) { + return enqueueKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, input); + } + promotionInbox(options = {}) { + return listKnowledgePromotions(this.ensureWorkspace().knowledgeDbPath, options); + } + getPromotion(id) { + return getKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id); + } + reviewPromotion(id, now) { + return reviewKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, now); + } + promoteCandidate(id, options = {}) { + return promoteKnowledgeCandidate(this.ensureWorkspace().knowledgeDbPath, id, options); + } + rejectPromotion(id, options = {}) { + return rejectKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, options); + } + durableRecords(options = {}) { + return listDurableKnowledgeRecords(this.ensureWorkspace().knowledgeDbPath, options); + } itemOnlyInventory(params) { const workspace = this.workspace; const { items, limit, includeArchived, storePath, storeExists, storeReadError } = params; @@ -49033,7 +49676,9 @@ class KnowledgeService { sync_changes: stats.sync_changes, sync_conflicts: stats.sync_conflicts, sync_table_clocks: stats.sync_table_clocks, - sync_imports: stats.sync_imports + sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records }; return { ok: true, @@ -49074,6 +49719,8 @@ class KnowledgeService { sync_conflicts: [], approval_gates: [], audit_events: [], + promotion_candidates: [], + durable_records: [], message: `${items.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)` }; } @@ -49264,6 +49911,55 @@ class KnowledgeService { ORDER BY created_at DESC LIMIT ? `, [limit])); + const promotionCandidates = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + source_kind, + source_refs_json, + evidence_refs_json, + status, + requires_approval, + checks_json, + duplicate_of, + approved_by, + promoted_record_id, + metadata_json, + created_at, + updated_at, + reviewed_at, + promoted_at + FROM knowledge_promotion_candidates + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(promotionCandidateInventoryRow); + const durableRecords = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + status, + source_refs_json, + evidence_refs_json, + confidence, + valid_from, + valid_to, + promoted_from_candidate_id, + approved_by, + metadata_json, + created_at, + updated_at + FROM durable_knowledge_records + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(durableRecordInventoryRow); const summary = { legacy_items: legacyStore.items.length, active_items: activeItems.length, @@ -49289,7 +49985,9 @@ class KnowledgeService { sync_changes: stats.sync_changes, sync_conflicts: stats.sync_conflicts, sync_table_clocks: stats.sync_table_clocks, - sync_imports: stats.sync_imports + sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records }; return { ok: true, @@ -49330,6 +50028,8 @@ class KnowledgeService { sync_conflicts: syncConflicts, approval_gates: approvalGates, audit_events: auditEvents, + promotion_candidates: promotionCandidates, + durable_records: durableRecords, message: `${legacyStore.items.length} item(s), ${stats.sources} source(s), ${stats.chunks} chunk(s), ${stats.wiki_pages} wiki page(s), ${stats.storage_objects} artifact(s)` }; } finally { diff --git a/dist/knowledge-db.d.ts b/dist/knowledge-db.d.ts index a2f06e9..61f3e80 100644 --- a/dist/knowledge-db.d.ts +++ b/dist/knowledge-db.d.ts @@ -10,7 +10,7 @@ import { Database } from 'bun:sqlite'; * directly — so this guard applies to CLI/MCP/SDK clients only. */ export declare function assertLocalCatalogMode(operation?: string): void; -export declare const CURRENT_SCHEMA_VERSION = 9; +export declare const CURRENT_SCHEMA_VERSION = 10; /** * FTS5 tokenizer for the chunk index. `porter` keeps English stemming; the * wrapped `unicode61 remove_diacritics 2` folds accents/diacritics fully @@ -41,6 +41,8 @@ export interface KnowledgeDbStats { sync_conflicts: number; sync_table_clocks: number; sync_imports: number; + promotion_candidates: number; + durable_records: number; } export declare function openKnowledgeDb(path: string): Database; /** diff --git a/dist/promotion-inbox.d.ts b/dist/promotion-inbox.d.ts new file mode 100644 index 0000000..62cf132 --- /dev/null +++ b/dist/promotion-inbox.d.ts @@ -0,0 +1,136 @@ +export type KnowledgePromotionKind = 'lesson' | 'decision' | 'claim'; +export type KnowledgePromotionSourceKind = 'memento' | 'session' | 'report'; +export type KnowledgePromotionStatus = 'ready' | 'needs_approval' | 'blocked' | 'duplicate' | 'promoted' | 'rejected'; +export interface KnowledgePromotionEvidenceRefInput { + ref: string; + citation_id?: string | null; + chunk_id?: string | null; + revision?: string | null; + hash?: string | null; + observed_at?: string | null; + expires_at?: string | null; + status?: string | null; +} +export interface KnowledgePromotionEvidenceRef { + ref: string; + citation_id: string | null; + chunk_id: string | null; + revision: string | null; + hash: string | null; + observed_at: string | null; + expires_at: string | null; + status: string | null; +} +export interface KnowledgePromotionCitationCheck { + ref: string; + valid: boolean; + resolved_by: 'citation' | 'chunk' | 'source' | 'run' | 'external_uri' | 'none'; + stale: boolean; + reason: string | null; +} +export interface KnowledgePromotionChecks { + citations: { + provided: number; + valid: number; + invalid: number; + entries: KnowledgePromotionCitationCheck[]; + }; + invalid_source_refs: string[]; + stale_refs: string[]; + duplicate_record_ids: string[]; + duplicate_candidate_ids: string[]; + conflicting_record_ids: string[]; + conflicting_candidate_ids: string[]; + approval_reasons: string[]; +} +export interface KnowledgePromotionCandidate { + id: string; + record_kind: KnowledgePromotionKind; + title: string; + content: string; + canonical_key: string; + content_hash: string; + source_kind: KnowledgePromotionSourceKind; + source_refs: string[]; + evidence_refs: KnowledgePromotionEvidenceRef[]; + status: KnowledgePromotionStatus; + requires_approval: boolean; + checks: KnowledgePromotionChecks; + idempotency_key: string; + duplicate_of: string | null; + approved_by: string | null; + promoted_record_id: string | null; + metadata: Record<string, unknown>; + created_at: string; + updated_at: string; + reviewed_at: string | null; + promoted_at: string | null; +} +export interface DurableKnowledgeRecord { + id: string; + record_kind: KnowledgePromotionKind; + title: string; + content: string; + canonical_key: string; + content_hash: string; + status: string; + source_refs: string[]; + evidence_refs: KnowledgePromotionEvidenceRef[]; + confidence: number | null; + valid_from: string; + valid_to: string | null; + promoted_from_candidate_id: string; + approved_by: string | null; + metadata: Record<string, unknown>; + created_at: string; + updated_at: string; +} +export interface EnqueueKnowledgePromotionInput { + kind: KnowledgePromotionKind; + title: string; + content: string; + sourceKind: KnowledgePromotionSourceKind; + sourceRefs: string[]; + evidenceRefs: Array<string | KnowledgePromotionEvidenceRefInput>; + canonicalKey?: string; + requiresApproval?: boolean; + confidence?: number; + validFrom?: string; + validTo?: string | null; + metadata?: Record<string, unknown>; + now?: Date; +} +export interface PromoteKnowledgeCandidateOptions { + approveWrite?: boolean; + approvedBy?: string; + now?: Date; +} +export declare function enqueueKnowledgePromotion(dbPath: string, input: EnqueueKnowledgePromotionInput): { + created: boolean; + candidate: KnowledgePromotionCandidate; +}; +export declare function getKnowledgePromotion(dbPath: string, id: string): KnowledgePromotionCandidate | null; +export declare function listKnowledgePromotions(dbPath: string, options?: { + status?: KnowledgePromotionStatus | 'inbox'; + kind?: KnowledgePromotionKind; + limit?: number; +}): KnowledgePromotionCandidate[]; +export declare function reviewKnowledgePromotion(dbPath: string, id: string, now?: Date): KnowledgePromotionCandidate; +export declare function promoteKnowledgeCandidate(dbPath: string, id: string, options?: PromoteKnowledgeCandidateOptions): { + ok: boolean; + promoted: boolean; + requires_approval: boolean; + candidate: KnowledgePromotionCandidate; + record: DurableKnowledgeRecord | null; + approval_id: string | null; + reason: string | null; +}; +export declare function rejectKnowledgePromotion(dbPath: string, id: string, options?: { + rejectedBy?: string; + now?: Date; +}): KnowledgePromotionCandidate; +export declare function listDurableKnowledgeRecords(dbPath: string, options?: { + kind?: KnowledgePromotionKind; + status?: string; + limit?: number; +}): DurableKnowledgeRecord[]; diff --git a/dist/service.d.ts b/dist/service.d.ts index dba50f4..faa230b 100644 --- a/dist/service.d.ts +++ b/dist/service.d.ts @@ -6,6 +6,7 @@ import { type KnowledgeSyncConflictAiProposalOptions } from './conflict-agent'; import { type EmbeddingIndexOptions, type EmbeddingSearchOptions } from './embeddings'; import { type KnowledgeMachinePreflightOptions, type KnowledgeMachineRouteResolution, type KnowledgeMachineWorkspaceResolution, type KnowledgeMachineTopologyOptions } from './machines'; import { type ProviderStatusResult, type ModelRegistryEntry } from './providers'; +import { type DurableKnowledgeRecord, type EnqueueKnowledgePromotionInput, type KnowledgePromotionCandidate, type KnowledgePromotionKind, type KnowledgePromotionStatus, type PromoteKnowledgeCandidateOptions } from './promotion-inbox'; import { type ReindexRuntimeOptions } from './reindex'; import { type KnowledgeContextPack, type RetrievalOptions } from './retrieval'; import { type RulesProvenanceImportResult } from './rules-provenance'; @@ -99,6 +100,8 @@ export interface KnowledgeInventoryResult { sync_conflicts: Array<Record<string, unknown>>; approval_gates: Array<Record<string, unknown>>; audit_events: Array<Record<string, unknown>>; + promotion_candidates: Array<Record<string, unknown>>; + durable_records: Array<Record<string, unknown>>; message: string; } export interface KnowledgeSetupResult { @@ -423,6 +426,35 @@ export declare class KnowledgeService { schema_version: number; }; dbStats(): import("./knowledge-db").KnowledgeDbStats; + enqueuePromotion(input: EnqueueKnowledgePromotionInput): { + created: boolean; + candidate: KnowledgePromotionCandidate; + }; + promotionInbox(options?: { + status?: KnowledgePromotionStatus | 'inbox'; + kind?: KnowledgePromotionKind; + limit?: number; + }): KnowledgePromotionCandidate[]; + getPromotion(id: string): KnowledgePromotionCandidate | null; + reviewPromotion(id: string, now?: Date): KnowledgePromotionCandidate; + promoteCandidate(id: string, options?: PromoteKnowledgeCandidateOptions): { + ok: boolean; + promoted: boolean; + requires_approval: boolean; + candidate: KnowledgePromotionCandidate; + record: DurableKnowledgeRecord | null; + approval_id: string | null; + reason: string | null; + }; + rejectPromotion(id: string, options?: { + rejectedBy?: string; + now?: Date; + }): KnowledgePromotionCandidate; + durableRecords(options?: { + kind?: KnowledgePromotionKind; + status?: string; + limit?: number; + }): DurableKnowledgeRecord[]; /** * Build a knowledge inventory from a bare item list (no local sqlite catalog). * Shared by the local no-db path and the cloud path so both produce the exact diff --git a/dist/storage.js b/dist/storage.js index 8543559..9c1362d 100644 --- a/dist/storage.js +++ b/dist/storage.js @@ -19367,7 +19367,7 @@ function assertLocalCatalogMode(operation = "catalog") { throw new Error(`knowledge: ${operation} builds/reads the on-box sqlite RAG catalog (source ingestion, chunk embeddings, ` + `wiki compilation, cross-machine sync, machine registry). That local indexing pipeline is not available in ` + `cloud mode. In cloud mode the shared corpus is the cloud knowledge-items: 'add/list/get/update/delete' item ` + `commands AND 'search/ask/build/context' over that shared corpus all route to the cloud. Set ${modeKey}=local ` + `(or unset it \u2014 local is the default) to use the full local catalog pipeline; run 'knowledge mode' to see ` + `which variable selected the current backend.`); } } -var CURRENT_SCHEMA_VERSION = 9; +var CURRENT_SCHEMA_VERSION = 10; var CHUNKS_FTS_TOKENIZE = "porter unicode61 remove_diacritics 2"; var MIGRATION_1 = ` PRAGMA journal_mode = WAL; @@ -19789,6 +19789,68 @@ VALUES (9, datetime('now')); COMMIT; `; +var MIGRATION_10_PROMOTION_INBOX = ` +CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + source_kind TEXT NOT NULL, + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'pending', + requires_approval INTEGER NOT NULL DEFAULT 0, + checks_json TEXT NOT NULL DEFAULT '{}', + idempotency_key TEXT NOT NULL UNIQUE, + duplicate_of TEXT, + approved_by TEXT, + promoted_record_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + reviewed_at TEXT, + promoted_at TEXT +); + +CREATE TABLE IF NOT EXISTS durable_knowledge_records ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + confidence REAL, + valid_from TEXT NOT NULL, + valid_to TEXT, + promoted_from_candidate_id TEXT NOT NULL UNIQUE + REFERENCES knowledge_promotion_candidates(id) ON DELETE RESTRICT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_status + ON knowledge_promotion_candidates(status, updated_at); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_kind_key + ON knowledge_promotion_candidates(record_kind, canonical_key); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_hash + ON knowledge_promotion_candidates(record_kind, content_hash); +CREATE INDEX IF NOT EXISTS idx_durable_records_kind_key + ON durable_knowledge_records(record_kind, canonical_key, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_hash + ON durable_knowledge_records(record_kind, content_hash, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_validity + ON durable_knowledge_records(status, valid_to); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (10, datetime('now')); +`; function openKnowledgeDb(path) { assertLocalCatalogMode("opening the local knowledge.db catalog"); ensureParentDir(path); @@ -19821,6 +19883,8 @@ function migrateKnowledgeDb(path) { applyMigration8(db); if (needsMigration9(db)) applyMigration9(db); + if (needsMigration10(db)) + applyMigration10(db); return { path, schema_version: getSchemaVersion(db) }; } finally { db.close(); @@ -19901,6 +19965,12 @@ function applyMigration9(db) { } db.exec(MIGRATION_9_REBUILD_FTS); } +function needsMigration10(db) { + return getSchemaVersion(db) < 10 || !tableExists(db, "knowledge_promotion_candidates") || !tableExists(db, "durable_knowledge_records"); +} +function applyMigration10(db) { + db.exec(MIGRATION_10_PROMOTION_INBOX); +} function getKnowledgeDbStats(path) { const db = openKnowledgeDb(path); try { @@ -19926,7 +19996,9 @@ function getKnowledgeDbStats(path) { sync_changes: count(db, "knowledge_sync_changes"), sync_conflicts: count(db, "knowledge_sync_conflicts"), sync_table_clocks: count(db, "knowledge_sync_table_clocks"), - sync_imports: count(db, "knowledge_sync_imports") + sync_imports: count(db, "knowledge_sync_imports"), + promotion_candidates: count(db, "knowledge_promotion_candidates"), + durable_records: count(db, "durable_knowledge_records") }; } finally { db.close(); diff --git a/src/knowledge-db.ts b/src/knowledge-db.ts index b0c7b7e..d5f40ae 100644 --- a/src/knowledge-db.ts +++ b/src/knowledge-db.ts @@ -33,7 +33,7 @@ export function assertLocalCatalogMode(operation = 'catalog'): void { } } -export const CURRENT_SCHEMA_VERSION = 9; +export const CURRENT_SCHEMA_VERSION = 10; /** * FTS5 tokenizer for the chunk index. `porter` keeps English stemming; the @@ -66,6 +66,8 @@ export interface KnowledgeDbStats { sync_conflicts: number; sync_table_clocks: number; sync_imports: number; + promotion_candidates: number; + durable_records: number; } const MIGRATION_1 = ` @@ -504,6 +506,69 @@ VALUES (9, datetime('now')); COMMIT; `; +const MIGRATION_10_PROMOTION_INBOX = ` +CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + source_kind TEXT NOT NULL, + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'pending', + requires_approval INTEGER NOT NULL DEFAULT 0, + checks_json TEXT NOT NULL DEFAULT '{}', + idempotency_key TEXT NOT NULL UNIQUE, + duplicate_of TEXT, + approved_by TEXT, + promoted_record_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + reviewed_at TEXT, + promoted_at TEXT +); + +CREATE TABLE IF NOT EXISTS durable_knowledge_records ( + id TEXT PRIMARY KEY, + record_kind TEXT NOT NULL, + title TEXT NOT NULL, + content TEXT NOT NULL, + canonical_key TEXT NOT NULL, + content_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + source_refs_json TEXT NOT NULL DEFAULT '[]', + evidence_refs_json TEXT NOT NULL DEFAULT '[]', + confidence REAL, + valid_from TEXT NOT NULL, + valid_to TEXT, + promoted_from_candidate_id TEXT NOT NULL UNIQUE + REFERENCES knowledge_promotion_candidates(id) ON DELETE RESTRICT, + approved_by TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_status + ON knowledge_promotion_candidates(status, updated_at); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_kind_key + ON knowledge_promotion_candidates(record_kind, canonical_key); +CREATE INDEX IF NOT EXISTS idx_promotion_candidates_hash + ON knowledge_promotion_candidates(record_kind, content_hash); +CREATE INDEX IF NOT EXISTS idx_durable_records_kind_key + ON durable_knowledge_records(record_kind, canonical_key, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_hash + ON durable_knowledge_records(record_kind, content_hash, status); +CREATE INDEX IF NOT EXISTS idx_durable_records_validity + ON durable_knowledge_records(status, valid_to); + +INSERT OR IGNORE INTO schema_versions(version, applied_at) +VALUES (10, datetime('now')); +`; + export function openKnowledgeDb(path: string): Database { assertLocalCatalogMode('opening the local knowledge.db catalog'); ensureParentDir(path); @@ -537,6 +602,7 @@ export function migrateKnowledgeDb(path: string): { path: string; schema_version if (needsMigration7(db)) applyMigration7(db); if (needsMigration8(db)) applyMigration8(db); if (needsMigration9(db)) applyMigration9(db); + if (needsMigration10(db)) applyMigration10(db); return { path, schema_version: getSchemaVersion(db) }; } finally { db.close(); @@ -640,6 +706,16 @@ function applyMigration9(db: Database): void { db.exec(MIGRATION_9_REBUILD_FTS); } +function needsMigration10(db: Database): boolean { + return getSchemaVersion(db) < 10 + || !tableExists(db, 'knowledge_promotion_candidates') + || !tableExists(db, 'durable_knowledge_records'); +} + +function applyMigration10(db: Database): void { + db.exec(MIGRATION_10_PROMOTION_INBOX); +} + export function getKnowledgeDbStats(path: string): KnowledgeDbStats { const db = openKnowledgeDb(path); try { @@ -666,6 +742,8 @@ export function getKnowledgeDbStats(path: string): KnowledgeDbStats { sync_conflicts: count(db, 'knowledge_sync_conflicts'), sync_table_clocks: count(db, 'knowledge_sync_table_clocks'), sync_imports: count(db, 'knowledge_sync_imports'), + promotion_candidates: count(db, 'knowledge_promotion_candidates'), + durable_records: count(db, 'durable_knowledge_records'), }; } finally { db.close(); diff --git a/src/promotion-inbox.ts b/src/promotion-inbox.ts new file mode 100644 index 0000000..9b1b04e --- /dev/null +++ b/src/promotion-inbox.ts @@ -0,0 +1,746 @@ +import { createHash } from 'node:crypto'; +import type { Database } from 'bun:sqlite'; +import { migrateKnowledgeDb, openKnowledgeDb } from './knowledge-db'; +import { generatedArtifactProvenance } from './provenance'; +import { createApprovalGate, recordAuditEvent, recordRedactionFindings, redactSecrets } from './safety'; + +export type KnowledgePromotionKind = 'lesson' | 'decision' | 'claim'; +export type KnowledgePromotionSourceKind = 'memento' | 'session' | 'report'; +export type KnowledgePromotionStatus = + | 'ready' + | 'needs_approval' + | 'blocked' + | 'duplicate' + | 'promoted' + | 'rejected'; + +export interface KnowledgePromotionEvidenceRefInput { + ref: string; + citation_id?: string | null; + chunk_id?: string | null; + revision?: string | null; + hash?: string | null; + observed_at?: string | null; + expires_at?: string | null; + status?: string | null; +} + +export interface KnowledgePromotionEvidenceRef { + ref: string; + citation_id: string | null; + chunk_id: string | null; + revision: string | null; + hash: string | null; + observed_at: string | null; + expires_at: string | null; + status: string | null; +} + +export interface KnowledgePromotionCitationCheck { + ref: string; + valid: boolean; + resolved_by: 'citation' | 'chunk' | 'source' | 'run' | 'external_uri' | 'none'; + stale: boolean; + reason: string | null; +} + +export interface KnowledgePromotionChecks { + citations: { + provided: number; + valid: number; + invalid: number; + entries: KnowledgePromotionCitationCheck[]; + }; + invalid_source_refs: string[]; + stale_refs: string[]; + duplicate_record_ids: string[]; + duplicate_candidate_ids: string[]; + conflicting_record_ids: string[]; + conflicting_candidate_ids: string[]; + approval_reasons: string[]; +} + +export interface KnowledgePromotionCandidate { + id: string; + record_kind: KnowledgePromotionKind; + title: string; + content: string; + canonical_key: string; + content_hash: string; + source_kind: KnowledgePromotionSourceKind; + source_refs: string[]; + evidence_refs: KnowledgePromotionEvidenceRef[]; + status: KnowledgePromotionStatus; + requires_approval: boolean; + checks: KnowledgePromotionChecks; + idempotency_key: string; + duplicate_of: string | null; + approved_by: string | null; + promoted_record_id: string | null; + metadata: Record<string, unknown>; + created_at: string; + updated_at: string; + reviewed_at: string | null; + promoted_at: string | null; +} + +export interface DurableKnowledgeRecord { + id: string; + record_kind: KnowledgePromotionKind; + title: string; + content: string; + canonical_key: string; + content_hash: string; + status: string; + source_refs: string[]; + evidence_refs: KnowledgePromotionEvidenceRef[]; + confidence: number | null; + valid_from: string; + valid_to: string | null; + promoted_from_candidate_id: string; + approved_by: string | null; + metadata: Record<string, unknown>; + created_at: string; + updated_at: string; +} + +export interface EnqueueKnowledgePromotionInput { + kind: KnowledgePromotionKind; + title: string; + content: string; + sourceKind: KnowledgePromotionSourceKind; + sourceRefs: string[]; + evidenceRefs: Array<string | KnowledgePromotionEvidenceRefInput>; + canonicalKey?: string; + requiresApproval?: boolean; + confidence?: number; + validFrom?: string; + validTo?: string | null; + metadata?: Record<string, unknown>; + now?: Date; +} + +export interface PromoteKnowledgeCandidateOptions { + approveWrite?: boolean; + approvedBy?: string; + now?: Date; +} + +interface CandidateRow { + id: string; + record_kind: string; + title: string; + content: string; + canonical_key: string; + content_hash: string; + source_kind: string; + source_refs_json: string; + evidence_refs_json: string; + status: string; + requires_approval: number; + checks_json: string; + idempotency_key: string; + duplicate_of: string | null; + approved_by: string | null; + promoted_record_id: string | null; + metadata_json: string; + created_at: string; + updated_at: string; + reviewed_at: string | null; + promoted_at: string | null; +} + +interface DurableRow { + id: string; + record_kind: string; + title: string; + content: string; + canonical_key: string; + content_hash: string; + status: string; + source_refs_json: string; + evidence_refs_json: string; + confidence: number | null; + valid_from: string; + valid_to: string | null; + promoted_from_candidate_id: string; + approved_by: string | null; + metadata_json: string; + created_at: string; + updated_at: string; +} + +function stableId(prefix: string, value: string, length = 24): string { + return `${prefix}_${createHash('sha256').update(value).digest('hex').slice(0, length)}`; +} + +function normalizedText(value: string): string { + return value.normalize('NFKC').trim().replace(/\s+/g, ' '); +} + +function normalizedKey(value: string): string { + return normalizedText(value).toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, ''); +} + +function parseJson<T>(value: string, fallback: T): T { + try { + return JSON.parse(value) as T; + } catch { + return fallback; + } +} + +function asCandidate(row: CandidateRow): KnowledgePromotionCandidate { + return { + ...row, + record_kind: row.record_kind as KnowledgePromotionKind, + source_kind: row.source_kind as KnowledgePromotionSourceKind, + status: row.status as KnowledgePromotionStatus, + source_refs: parseJson(row.source_refs_json, []), + evidence_refs: parseJson(row.evidence_refs_json, []), + requires_approval: row.requires_approval === 1, + checks: parseJson(row.checks_json, emptyChecks()), + metadata: parseJson(row.metadata_json, {}), + }; +} + +function asDurableRecord(row: DurableRow): DurableKnowledgeRecord { + return { + ...row, + record_kind: row.record_kind as KnowledgePromotionKind, + source_refs: parseJson(row.source_refs_json, []), + evidence_refs: parseJson(row.evidence_refs_json, []), + metadata: parseJson(row.metadata_json, {}), + }; +} + +function emptyChecks(): KnowledgePromotionChecks { + return { + citations: { provided: 0, valid: 0, invalid: 0, entries: [] }, + invalid_source_refs: [], + stale_refs: [], + duplicate_record_ids: [], + duplicate_candidate_ids: [], + conflicting_record_ids: [], + conflicting_candidate_ids: [], + approval_reasons: [], + }; +} + +function normalizeEvidenceRef(input: string | KnowledgePromotionEvidenceRefInput): KnowledgePromotionEvidenceRef { + const value = typeof input === 'string' ? { ref: input } : input; + return { + ref: normalizedText(value.ref), + citation_id: value.citation_id ?? null, + chunk_id: value.chunk_id ?? null, + revision: value.revision ?? null, + hash: value.hash ?? null, + observed_at: value.observed_at ?? null, + expires_at: value.expires_at ?? null, + status: value.status ?? null, + }; +} + +function validReference(ref: string): boolean { + try { + const parsed = new URL(ref); + return parsed.protocol.length > 1 && (parsed.hostname.length > 0 || parsed.pathname.length > 0); + } catch { + return /^(?:cite|citation|chunk|run):[A-Za-z0-9._:-]+$/.test(ref); + } +} + +function staleStatus(status: string | null | undefined): boolean { + return ['deleted', 'stale', 'invalidated', 'reindex_required', 'expired', 'superseded'].includes((status ?? '').toLowerCase()); +} + +function metadataStatus(value: string | null | undefined): string | null { + if (!value) return null; + const metadata = parseJson<Record<string, unknown>>(value, {}); + if (metadata.stale === true) return 'stale'; + return typeof metadata.status === 'string' ? metadata.status : null; +} + +function citationIdentifier(evidence: KnowledgePromotionEvidenceRef): string | null { + if (evidence.citation_id) return evidence.citation_id; + const match = evidence.ref.match(/^(?:cite|citation):(.+)$/); + return match?.[1] ?? null; +} + +function chunkIdentifier(evidence: KnowledgePromotionEvidenceRef): string | null { + if (evidence.chunk_id) return evidence.chunk_id; + const match = evidence.ref.match(/^chunk:(.+)$/); + return match?.[1] ?? null; +} + +function inspectCitation(db: Database, evidence: KnowledgePromotionEvidenceRef, now: string): KnowledgePromotionCitationCheck { + const explicitStale = staleStatus(evidence.status) + || Boolean(evidence.expires_at && evidence.expires_at <= now); + if (!evidence.ref || !validReference(evidence.ref)) { + return { ref: evidence.ref, valid: false, resolved_by: 'none', stale: explicitStale, reason: 'invalid_reference' }; + } + + const citationId = citationIdentifier(evidence); + const citation = db.query<{ + id: string; + source_uri: string; + chunk_id: string | null; + chunk_metadata_json: string | null; + revision_hash: string | null; + revision: string | null; + source_revision_id: string | null; + source_id: string | null; + revision_created_at: string | null; + latest_revision_at: string | null; + }, [string | null, string]>( + `SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + sr.hash AS revision_hash, sr.revision, sr.id AS source_revision_id, + sr.source_id, sr.created_at AS revision_created_at, + (SELECT MAX(newest.created_at) FROM source_revisions newest WHERE newest.source_id = sr.source_id) AS latest_revision_at + FROM citations c + LEFT JOIN chunks ch ON ch.id = c.chunk_id + LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE c.id = ? OR c.source_uri = ? + ORDER BY c.created_at DESC + LIMIT 1`, + ).get(citationId, evidence.ref); + if (citation) { + const hashMismatch = Boolean(evidence.hash && citation.revision_hash && evidence.hash !== citation.revision_hash); + const revisionMismatch = Boolean(evidence.revision && citation.revision && evidence.revision !== citation.revision); + const oldRevision = Boolean(citation.revision_created_at && citation.latest_revision_at && citation.revision_created_at < citation.latest_revision_at); + const stale = explicitStale || staleStatus(metadataStatus(citation.chunk_metadata_json)) || hashMismatch || revisionMismatch || oldRevision; + return { + ref: evidence.ref, + valid: true, + resolved_by: 'citation', + stale, + reason: hashMismatch ? 'hash_mismatch' : revisionMismatch ? 'revision_mismatch' : oldRevision ? 'newer_source_revision' : stale ? 'stale_citation' : null, + }; + } + + const chunkId = chunkIdentifier(evidence); + if (chunkId) { + const chunk = db.query<{ metadata_json: string; hash: string | null; revision: string | null }, [string]>( + `SELECT ch.metadata_json, sr.hash, sr.revision + FROM chunks ch LEFT JOIN source_revisions sr ON sr.id = ch.source_revision_id + WHERE ch.id = ?`, + ).get(chunkId); + if (!chunk) return { ref: evidence.ref, valid: false, resolved_by: 'none', stale: explicitStale, reason: 'chunk_not_found' }; + const mismatch = Boolean((evidence.hash && chunk.hash && evidence.hash !== chunk.hash) + || (evidence.revision && chunk.revision && evidence.revision !== chunk.revision)); + const stale = explicitStale || staleStatus(metadataStatus(chunk.metadata_json)) || mismatch; + return { ref: evidence.ref, valid: true, resolved_by: 'chunk', stale, reason: mismatch ? 'source_version_mismatch' : stale ? 'stale_chunk' : null }; + } + + const source = db.query<{ metadata_json: string }, [string]>( + 'SELECT metadata_json FROM sources WHERE uri = ? LIMIT 1', + ).get(evidence.ref); + if (source) { + const stale = explicitStale || staleStatus(metadataStatus(source.metadata_json)); + return { ref: evidence.ref, valid: true, resolved_by: 'source', stale, reason: stale ? 'stale_source' : null }; + } + + const runMatch = evidence.ref.match(/^knowledge:\/\/project\/runs\/([^/?#]+)/); + if (runMatch) { + const run = db.query<{ id: string }, [string]>('SELECT id FROM runs WHERE id = ?',).get(decodeURIComponent(runMatch[1])); + if (!run) return { ref: evidence.ref, valid: false, resolved_by: 'none', stale: explicitStale, reason: 'run_not_found' }; + return { ref: evidence.ref, valid: true, resolved_by: 'run', stale: explicitStale, reason: explicitStale ? 'expired_evidence' : null }; + } + + return { + ref: evidence.ref, + valid: true, + resolved_by: 'external_uri', + stale: explicitStale, + reason: explicitStale ? 'expired_evidence' : null, + }; +} + +function candidateById(db: Database, id: string): CandidateRow | null { + return db.query<CandidateRow, [string]>('SELECT * FROM knowledge_promotion_candidates WHERE id = ?').get(id) ?? null; +} + +function assessCandidate(db: Database, row: CandidateRow, now: string): KnowledgePromotionCandidate { + const evidence = parseJson<KnowledgePromotionEvidenceRef[]>(row.evidence_refs_json, []); + const sourceRefs = parseJson<string[]>(row.source_refs_json, []); + const metadata = parseJson<Record<string, unknown>>(row.metadata_json, {}); + const checks = emptyChecks(); + checks.invalid_source_refs = sourceRefs.filter((ref) => !validReference(ref)); + checks.citations.entries = evidence.map((entry) => inspectCitation(db, entry, now)); + checks.citations.provided = evidence.length; + checks.citations.valid = checks.citations.entries.filter((entry) => entry.valid).length; + checks.citations.invalid = checks.citations.entries.length - checks.citations.valid; + checks.stale_refs = checks.citations.entries.filter((entry) => entry.stale).map((entry) => entry.ref); + + checks.duplicate_record_ids = db.query<{ id: string }, [string, string]>( + `SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND content_hash = ? AND status IN ('active', 'conflicted') + ORDER BY created_at`, + ).all(row.record_kind, row.content_hash).map((entry) => entry.id); + checks.duplicate_candidate_ids = db.query<{ id: string }, [string, string, string]>( + `SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND content_hash = ? AND status NOT IN ('rejected') + ORDER BY created_at`, + ).all(row.id, row.record_kind, row.content_hash).map((entry) => entry.id); + checks.conflicting_record_ids = db.query<{ id: string }, [string, string, string]>( + `SELECT id FROM durable_knowledge_records + WHERE record_kind = ? AND canonical_key = ? AND content_hash <> ? AND status IN ('active', 'conflicted') + ORDER BY created_at`, + ).all(row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + checks.conflicting_candidate_ids = db.query<{ id: string }, [string, string, string, string]>( + `SELECT id FROM knowledge_promotion_candidates + WHERE id <> ? AND record_kind = ? AND canonical_key = ? AND content_hash <> ? + AND status IN ('ready', 'needs_approval', 'promoted') + ORDER BY created_at`, + ).all(row.id, row.record_kind, row.canonical_key, row.content_hash).map((entry) => entry.id); + + const duplicateOf = checks.duplicate_record_ids[0] ?? checks.duplicate_candidate_ids[0] ?? null; + const blocked = sourceRefs.length === 0 + || evidence.length === 0 + || checks.invalid_source_refs.length > 0 + || checks.citations.invalid > 0; + if (row.record_kind === 'decision' || row.record_kind === 'claim') checks.approval_reasons.push(`${row.record_kind}_requires_review`); + if (metadata.requested_approval === true) checks.approval_reasons.push('explicit_approval_request'); + if (checks.stale_refs.length > 0) checks.approval_reasons.push('stale_evidence'); + if (checks.conflicting_record_ids.length > 0 || checks.conflicting_candidate_ids.length > 0) { + checks.approval_reasons.push('conflicting_knowledge'); + } + const requiresApproval = checks.approval_reasons.length > 0; + const status: KnowledgePromotionStatus = duplicateOf + ? 'duplicate' + : blocked + ? 'blocked' + : requiresApproval + ? 'needs_approval' + : 'ready'; + + db.run( + `UPDATE knowledge_promotion_candidates + SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, + [status, requiresApproval ? 1 : 0, JSON.stringify(checks), duplicateOf, now, now, row.id], + ); + return asCandidate(candidateById(db, row.id)!); +} + +export function enqueueKnowledgePromotion(dbPath: string, input: EnqueueKnowledgePromotionInput): { + created: boolean; + candidate: KnowledgePromotionCandidate; +} { + const kinds: KnowledgePromotionKind[] = ['lesson', 'decision', 'claim']; + const sourceKinds: KnowledgePromotionSourceKind[] = ['memento', 'session', 'report']; + if (!kinds.includes(input.kind)) throw new Error('Promotion kind must be lesson, decision, or claim.'); + if (!sourceKinds.includes(input.sourceKind)) throw new Error('Promotion source kind must be memento, session, or report.'); + const titleResult = redactSecrets(normalizedText(input.title)); + const contentResult = redactSecrets(normalizedText(input.content)); + if (!titleResult.text) throw new Error('Promotion title is required.'); + if (!contentResult.text) throw new Error('Promotion content is required.'); + const sourceRefs = Array.from(new Set(input.sourceRefs.map(normalizedText).filter(Boolean))).sort(); + const evidenceRefs = input.evidenceRefs.map(normalizeEvidenceRef) + .filter((entry) => entry.ref.length > 0) + .sort((a, b) => a.ref.localeCompare(b.ref)); + const canonicalKey = normalizedKey(input.canonicalKey ?? titleResult.text); + if (!canonicalKey) throw new Error('Promotion canonical key is empty after normalization.'); + const contentHash = `sha256:${createHash('sha256').update(`${input.kind}\0${normalizedText(contentResult.text).toLowerCase()}`).digest('hex')}`; + const idempotencyKey = stableId('promote', [ + input.sourceKind, + input.kind, + canonicalKey, + contentHash, + ...sourceRefs, + ].join('\0')); + const id = stableId('promotion', idempotencyKey); + const now = (input.now ?? new Date()).toISOString(); + const metadata: Record<string, unknown> = { + ...(input.metadata ?? {}), + requested_approval: input.requiresApproval === true, + confidence: input.confidence ?? null, + valid_from: input.validFrom ?? now, + valid_to: input.validTo ?? null, + redactions: titleResult.findings.length + contentResult.findings.length, + }; + + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const existing = db.query<CandidateRow, [string]>( + 'SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?', + ).get(idempotencyKey); + if (existing) return { created: false, candidate: asCandidate(existing) }; + + db.run( + `INSERT INTO knowledge_promotion_candidates ( + id, record_kind, title, content, canonical_key, content_hash, source_kind, + source_refs_json, evidence_refs_json, status, requires_approval, checks_json, + idempotency_key, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`, + [ + id, + input.kind, + titleResult.text, + contentResult.text, + canonicalKey, + contentHash, + input.sourceKind, + JSON.stringify(sourceRefs), + JSON.stringify(evidenceRefs), + idempotencyKey, + JSON.stringify(metadata), + now, + now, + ], + ); + const findings = [...titleResult.findings, ...contentResult.findings]; + if (findings.length > 0) { + recordRedactionFindings(db, { + source_uri: sourceRefs[0] ?? `knowledge://promotion/${id}`, + findings, + metadata: { promotion_candidate_id: id }, + created_at: now, + }); + } + recordAuditEvent(db, { + event_type: 'knowledge_promotion', + action: 'enqueue_promotion', + target_uri: `knowledge://promotion/${id}`, + decision: 'info', + metadata: { record_kind: input.kind, source_kind: input.sourceKind, source_refs: sourceRefs }, + created_at: now, + }); + return { created: true, candidate: assessCandidate(db, candidateById(db, id)!, now) }; + } finally { + db.close(); + } +} + +export function getKnowledgePromotion(dbPath: string, id: string): KnowledgePromotionCandidate | null { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const row = candidateById(db, id); + return row ? asCandidate(row) : null; + } finally { + db.close(); + } +} + +export function listKnowledgePromotions(dbPath: string, options: { + status?: KnowledgePromotionStatus | 'inbox'; + kind?: KnowledgePromotionKind; + limit?: number; +} = {}): KnowledgePromotionCandidate[] { + migrateKnowledgeDb(dbPath); + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const conditions: string[] = []; + const params: Array<string | number> = []; + if (options.status === 'inbox' || !options.status) { + conditions.push("status IN ('ready', 'needs_approval', 'blocked')"); + } else { + conditions.push('status = ?'); + params.push(options.status); + } + if (options.kind) { + conditions.push('record_kind = ?'); + params.push(options.kind); + } + const db = openKnowledgeDb(dbPath); + try { + return db.query<CandidateRow, any[]>( + `SELECT * FROM knowledge_promotion_candidates + WHERE ${conditions.join(' AND ')} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`, + ).all(...params, limit).map(asCandidate); + } finally { + db.close(); + } +} + +export function reviewKnowledgePromotion(dbPath: string, id: string, now = new Date()): KnowledgePromotionCandidate { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + try { + const row = candidateById(db, id); + if (!row) throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === 'promoted' || row.status === 'rejected') return asCandidate(row); + return assessCandidate(db, row, now.toISOString()); + } finally { + db.close(); + } +} + +export function promoteKnowledgeCandidate(dbPath: string, id: string, options: PromoteKnowledgeCandidateOptions = {}): { + ok: boolean; + promoted: boolean; + requires_approval: boolean; + candidate: KnowledgePromotionCandidate; + record: DurableKnowledgeRecord | null; + approval_id: string | null; + reason: string | null; +} { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = (options.now ?? new Date()).toISOString(); + try { + const row = candidateById(db, id); + if (!row) throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === 'promoted' && row.promoted_record_id) { + const existingRecord = db.query<DurableRow, [string]>('SELECT * FROM durable_knowledge_records WHERE id = ?').get(row.promoted_record_id); + return { + ok: true, + promoted: false, + requires_approval: row.requires_approval === 1, + candidate: asCandidate(row), + record: existingRecord ? asDurableRecord(existingRecord) : null, + approval_id: null, + reason: 'already_promoted', + }; + } + if (row.status === 'rejected') throw new Error(`Promotion candidate ${id} was rejected.`); + const candidate = assessCandidate(db, row, now); + if (candidate.status === 'duplicate') { + return { ok: true, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: 'duplicate' }; + } + if (candidate.status === 'blocked') { + return { ok: false, promoted: false, requires_approval: false, candidate, record: null, approval_id: null, reason: 'citation_check_failed' }; + } + if (candidate.requires_approval && !options.approveWrite) { + return { ok: false, promoted: false, requires_approval: true, candidate, record: null, approval_id: null, reason: 'approval_required' }; + } + if (candidate.requires_approval && !options.approvedBy?.trim()) { + throw new Error('Promotion approval requires --approved-by <name>.'); + } + + const approvedBy = candidate.requires_approval ? options.approvedBy!.trim() : null; + let approvalId: string | null = null; + if (candidate.requires_approval) { + approvalId = createApprovalGate(db, { + action: 'promote_durable_knowledge', + target_uri: `knowledge://promotion/${candidate.id}`, + reason: candidate.checks.approval_reasons.join(', '), + approved_by: approvedBy, + metadata: { promotion_candidate_id: candidate.id, checks: candidate.checks }, + created_at: now, + }).id; + } + const recordId = stableId('durable', candidate.id); + const metadata = { + ...candidate.metadata, + promotion_candidate_id: candidate.id, + source_kind: candidate.source_kind, + checks: candidate.checks, + approval_id: approvalId, + provenance: generatedArtifactProvenance({ + generated_from: `knowledge://promotion/${candidate.id}`, + artifact_key: `durable/${candidate.record_kind}/${candidate.canonical_key}`, + source_refs: candidate.source_refs, + citation_required: true, + }), + }; + db.run( + `INSERT INTO durable_knowledge_records ( + id, record_kind, title, content, canonical_key, content_hash, status, + source_refs_json, evidence_refs_json, confidence, valid_from, valid_to, + promoted_from_candidate_id, approved_by, metadata_json, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + recordId, + candidate.record_kind, + candidate.title, + candidate.content, + candidate.canonical_key, + candidate.content_hash, + candidate.checks.conflicting_record_ids.length > 0 ? 'conflicted' : 'active', + JSON.stringify(candidate.source_refs), + JSON.stringify(candidate.evidence_refs), + typeof candidate.metadata.confidence === 'number' ? candidate.metadata.confidence : null, + typeof candidate.metadata.valid_from === 'string' ? candidate.metadata.valid_from : now, + typeof candidate.metadata.valid_to === 'string' ? candidate.metadata.valid_to : null, + candidate.id, + approvedBy, + JSON.stringify(metadata), + now, + now, + ], + ); + db.run( + `UPDATE knowledge_promotion_candidates + SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? + WHERE id = ?`, + [approvedBy, recordId, now, now, candidate.id], + ); + recordAuditEvent(db, { + event_type: 'knowledge_promotion', + action: 'promote_durable_knowledge', + target_uri: `knowledge://durable/${recordId}`, + decision: 'allow', + metadata: { promotion_candidate_id: candidate.id, approval_id: approvalId, source_refs: candidate.source_refs }, + created_at: now, + }); + const promotedCandidate = asCandidate(candidateById(db, candidate.id)!); + const record = db.query<DurableRow, [string]>('SELECT * FROM durable_knowledge_records WHERE id = ?').get(recordId)!; + return { + ok: true, + promoted: true, + requires_approval: candidate.requires_approval, + candidate: promotedCandidate, + record: asDurableRecord(record), + approval_id: approvalId, + reason: null, + }; + } finally { + db.close(); + } +} + +export function rejectKnowledgePromotion(dbPath: string, id: string, options: { rejectedBy?: string; now?: Date } = {}): KnowledgePromotionCandidate { + migrateKnowledgeDb(dbPath); + const db = openKnowledgeDb(dbPath); + const now = (options.now ?? new Date()).toISOString(); + try { + const row = candidateById(db, id); + if (!row) throw new Error(`Promotion candidate not found: ${id}`); + if (row.status === 'promoted') throw new Error(`Promotion candidate ${id} is already promoted.`); + db.run( + `UPDATE knowledge_promotion_candidates + SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? + WHERE id = ?`, + [options.rejectedBy?.trim() || null, now, now, id], + ); + recordAuditEvent(db, { + event_type: 'knowledge_promotion', + action: 'reject_promotion', + target_uri: `knowledge://promotion/${id}`, + decision: 'deny', + metadata: { rejected_by: options.rejectedBy ?? null }, + created_at: now, + }); + return asCandidate(candidateById(db, id)!); + } finally { + db.close(); + } +} + +export function listDurableKnowledgeRecords(dbPath: string, options: { + kind?: KnowledgePromotionKind; + status?: string; + limit?: number; +} = {}): DurableKnowledgeRecord[] { + migrateKnowledgeDb(dbPath); + const conditions: string[] = []; + const params: Array<string | number> = []; + if (options.kind) { conditions.push('record_kind = ?'); params.push(options.kind); } + if (options.status) { conditions.push('status = ?'); params.push(options.status); } + const limit = Math.max(1, Math.min(options.limit ?? 50, 200)); + const db = openKnowledgeDb(dbPath); + try { + return db.query<DurableRow, any[]>( + `SELECT * FROM durable_knowledge_records + ${conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''} + ORDER BY updated_at DESC, created_at DESC + LIMIT ?`, + ).all(...params, limit).map(asDurableRecord); + } finally { + db.close(); + } +} diff --git a/src/service.ts b/src/service.ts index ea85bb0..2e3f4d1 100644 --- a/src/service.ts +++ b/src/service.ts @@ -53,6 +53,21 @@ import { import { ingestSourceRef } from './source-ingest'; import { resolveOpenFilesSource } from './source-resolver'; import { providerStatus, listModelRegistry, type ProviderStatusResult, type ModelRegistryEntry } from './providers'; +import { + enqueueKnowledgePromotion, + getKnowledgePromotion, + listDurableKnowledgeRecords, + listKnowledgePromotions, + promoteKnowledgeCandidate, + rejectKnowledgePromotion, + reviewKnowledgePromotion, + type DurableKnowledgeRecord, + type EnqueueKnowledgePromotionInput, + type KnowledgePromotionCandidate, + type KnowledgePromotionKind, + type KnowledgePromotionStatus, + type PromoteKnowledgeCandidateOptions, +} from './promotion-inbox'; import { enqueueMissingEmbeddings, refreshEmbeddingIndex, reindexHealth, type ReindexRuntimeOptions } from './reindex'; import { retrieveKnowledgeContext, retrieveKnowledgeContextFromItems, retrieveKnowledgeContextFromSearch, type KnowledgeContextPack, type RetrievalOptions } from './retrieval'; import { @@ -206,6 +221,8 @@ export interface KnowledgeInventoryResult { sync_conflicts: Array<Record<string, unknown>>; approval_gates: Array<Record<string, unknown>>; audit_events: Array<Record<string, unknown>>; + promotion_candidates: Array<Record<string, unknown>>; + durable_records: Array<Record<string, unknown>>; message: string; } @@ -816,6 +833,46 @@ function rowsWithJsonFields( }); } +function parseInventoryJsonArray(value: unknown): unknown[] { + if (typeof value !== 'string') return []; + try { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } +} + +function parseInventoryJsonObject(value: unknown): Record<string, unknown> { + if (typeof value !== 'string') return {}; + return parseMetadataJson(value); +} + +function promotionCandidateInventoryRow(row: Record<string, unknown>): Record<string, unknown> { + const next: Record<string, unknown> = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.requires_approval = next.requires_approval === 1 || next.requires_approval === true; + next.checks = parseInventoryJsonObject(next.checks_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.checks_json; + delete next.metadata_json; + return next; +} + +function durableRecordInventoryRow(row: Record<string, unknown>): Record<string, unknown> { + const next: Record<string, unknown> = { ...row }; + next.source_refs = parseInventoryJsonArray(next.source_refs_json); + next.evidence_refs = parseInventoryJsonArray(next.evidence_refs_json); + next.metadata = parseInventoryJsonObject(next.metadata_json); + delete next.source_refs_json; + delete next.evidence_refs_json; + delete next.metadata_json; + return next; +} + function selectInventoryRows( db: ReturnType<typeof openKnowledgeDb>, sql: string, @@ -884,6 +941,8 @@ function emptyKnowledgeDbStats(): ReturnType<typeof getKnowledgeDbStats> { sync_conflicts: 0, sync_table_clocks: 0, sync_imports: 0, + promotion_candidates: 0, + durable_records: 0, }; } @@ -1814,6 +1873,38 @@ export class KnowledgeService { return getKnowledgeDbStats(workspace.knowledgeDbPath); } + enqueuePromotion(input: EnqueueKnowledgePromotionInput): { created: boolean; candidate: KnowledgePromotionCandidate } { + return enqueueKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, input); + } + + promotionInbox(options: { + status?: KnowledgePromotionStatus | 'inbox'; + kind?: KnowledgePromotionKind; + limit?: number; + } = {}): KnowledgePromotionCandidate[] { + return listKnowledgePromotions(this.ensureWorkspace().knowledgeDbPath, options); + } + + getPromotion(id: string): KnowledgePromotionCandidate | null { + return getKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id); + } + + reviewPromotion(id: string, now?: Date): KnowledgePromotionCandidate { + return reviewKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, now); + } + + promoteCandidate(id: string, options: PromoteKnowledgeCandidateOptions = {}) { + return promoteKnowledgeCandidate(this.ensureWorkspace().knowledgeDbPath, id, options); + } + + rejectPromotion(id: string, options: { rejectedBy?: string; now?: Date } = {}): KnowledgePromotionCandidate { + return rejectKnowledgePromotion(this.ensureWorkspace().knowledgeDbPath, id, options); + } + + durableRecords(options: { kind?: KnowledgePromotionKind; status?: string; limit?: number } = {}): DurableKnowledgeRecord[] { + return listDurableKnowledgeRecords(this.ensureWorkspace().knowledgeDbPath, options); + } + /** * Build a knowledge inventory from a bare item list (no local sqlite catalog). * Shared by the local no-db path and the cloud path so both produce the exact @@ -1858,6 +1949,8 @@ export class KnowledgeService { sync_conflicts: stats.sync_conflicts, sync_table_clocks: stats.sync_table_clocks, sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records, }; return { ok: true, @@ -1907,6 +2000,8 @@ export class KnowledgeService { sync_conflicts: [], approval_gates: [], audit_events: [], + promotion_candidates: [], + durable_records: [], message: `${items.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`, }; } @@ -2119,6 +2214,57 @@ export class KnowledgeService { LIMIT ? `, [limit])); + const promotionCandidates = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + source_kind, + source_refs_json, + evidence_refs_json, + status, + requires_approval, + checks_json, + duplicate_of, + approved_by, + promoted_record_id, + metadata_json, + created_at, + updated_at, + reviewed_at, + promoted_at + FROM knowledge_promotion_candidates + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(promotionCandidateInventoryRow); + + const durableRecords = selectInventoryRows(db, ` + SELECT + id, + record_kind, + title, + substr(content, 1, 220) AS content_preview, + canonical_key, + content_hash, + status, + source_refs_json, + evidence_refs_json, + confidence, + valid_from, + valid_to, + promoted_from_candidate_id, + approved_by, + metadata_json, + created_at, + updated_at + FROM durable_knowledge_records + ORDER BY updated_at DESC, created_at DESC + LIMIT ? + `, [limit]).map(durableRecordInventoryRow); + const summary = { legacy_items: legacyStore.items.length, active_items: activeItems.length, @@ -2145,6 +2291,8 @@ export class KnowledgeService { sync_conflicts: stats.sync_conflicts, sync_table_clocks: stats.sync_table_clocks, sync_imports: stats.sync_imports, + promotion_candidates: stats.promotion_candidates, + durable_records: stats.durable_records, }; return { @@ -2186,6 +2334,8 @@ export class KnowledgeService { sync_conflicts: syncConflicts, approval_gates: approvalGates, audit_events: auditEvents, + promotion_candidates: promotionCandidates, + durable_records: durableRecords, message: `${legacyStore.items.length} item(s), ${stats.sources} source(s), ${stats.chunks} chunk(s), ${stats.wiki_pages} wiki page(s), ${stats.storage_objects} artifact(s)`, }; } finally { diff --git a/tests/app-wiki.test.ts b/tests/app-wiki.test.ts index f83f281..9e5aef5 100644 --- a/tests/app-wiki.test.ts +++ b/tests/app-wiki.test.ts @@ -8,14 +8,19 @@ import { createAppWikiScope, openProjectWiki, } from '../src/index'; +import { KNOWLEDGE_API_KEY_ENV_KEYS, KNOWLEDGE_API_URL_ENV_KEYS, KNOWLEDGE_MODE_ENV_KEYS } from '../src/knowledge-mode'; const __dirname = dirname(fileURLToPath(import.meta.url)); const CLI = join(__dirname, '..', 'src', 'cli.ts'); function runCli(args: string[], cwd: string, env: Record<string, string>) { + const inherited = { ...process.env } as Record<string, string>; + for (const key of [...KNOWLEDGE_API_URL_ENV_KEYS, ...KNOWLEDGE_API_KEY_ENV_KEYS, ...KNOWLEDGE_MODE_ENV_KEYS]) { + delete inherited[key]; + } return spawnSync('bun', [CLI, ...args], { cwd, - env: { ...process.env, ...env }, + env: { ...inherited, ...env }, maxBuffer: 64 * 1024 * 1024, }); } diff --git a/tests/cli.test.ts b/tests/cli.test.ts index 508c5bd..8fc091f 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -9,7 +9,7 @@ import { spawnSync } from 'node:child_process'; import { tmpdir } from 'node:os'; import { delimiter, join, dirname, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { migrateKnowledgeDb, openKnowledgeDb } from '../src/knowledge-db'; +import { CURRENT_SCHEMA_VERSION, migrateKnowledgeDb, openKnowledgeDb } from '../src/knowledge-db'; import { KNOWLEDGE_API_KEY_ENV_KEYS, KNOWLEDGE_API_URL_ENV_KEYS, KNOWLEDGE_MODE_ENV_KEYS } from '../src/knowledge-mode'; import { createKnowledgeService } from '../src/service'; import { parseSourceRef } from '../src/source-ref'; @@ -2381,13 +2381,13 @@ describe('knowledge cli', () => { const init = runCli(['db', 'init', '--scope', 'project', '--json'], dir); expect(init.exitCode).toBe(0); const initOut = JSON.parse(new TextDecoder().decode(init.stdout)); - expect(initOut.schema_version).toBe(9); + expect(initOut.schema_version).toBe(CURRENT_SCHEMA_VERSION); expect(existsSync(join(dir, '.hasna', 'knowledge', 'knowledge.db'))).toBe(true); const stats = runCli(['db', 'stats', '--scope', 'project', '--json'], dir); expect(stats.exitCode).toBe(0); const statsOut = JSON.parse(new TextDecoder().decode(stats.stdout)); - expect(statsOut.schema_version).toBe(9); + expect(statsOut.schema_version).toBe(CURRENT_SCHEMA_VERSION); expect(statsOut.sources).toBe(0); expect(statsOut.runs).toBe(0); @@ -2413,7 +2413,7 @@ describe('knowledge cli', () => { expect(init.exitCode).toBe(0); const initOut = JSON.parse(new TextDecoder().decode(init.stdout)); expect(initOut.ok).toBe(true); - expect(initOut.schema_version).toBe(9); + expect(initOut.schema_version).toBe(CURRENT_SCHEMA_VERSION); const stats = runCli(['db', 'stats', '--scope', 'global', '--json'], dir, { HOME: home, @@ -2421,7 +2421,7 @@ describe('knowledge cli', () => { }); expect(stats.exitCode).toBe(0); const statsOut = JSON.parse(new TextDecoder().decode(stats.stdout)); - expect(statsOut.schema_version).toBe(9); + expect(statsOut.schema_version).toBe(CURRENT_SCHEMA_VERSION); const db = openKnowledgeDb(dbPath); try { @@ -2459,7 +2459,7 @@ describe('knowledge cli', () => { const statusAfterSnapshot = runCli(['sync', 'status', '--scope', 'project', '--json'], dir); expect(statusAfterSnapshot.exitCode).toBe(0); const statusAfterSnapshotOut = JSON.parse(new TextDecoder().decode(statusAfterSnapshot.stdout)); - expect(statusAfterSnapshotOut.sqlite_schema_version).toBe(9); + expect(statusAfterSnapshotOut.sqlite_schema_version).toBe(CURRENT_SCHEMA_VERSION); const machines = runCli(['sync', 'machines', '--scope', 'project', '--json'], dir); expect(machines.exitCode).toBe(0); diff --git a/tests/knowledge-db.test.ts b/tests/knowledge-db.test.ts index b0080c9..ce9b202 100644 --- a/tests/knowledge-db.test.ts +++ b/tests/knowledge-db.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { getKnowledgeDbStats, migrateKnowledgeDb, openKnowledgeDb } from '../src/knowledge-db'; +import { CURRENT_SCHEMA_VERSION, getKnowledgeDbStats, migrateKnowledgeDb, openKnowledgeDb } from '../src/knowledge-db'; import { ingestOpenFilesManifest } from '../src/manifest-ingest'; import { ingestSourceRef } from '../src/source-ingest'; import { consumeOpenFilesOutbox } from '../src/outbox-consume'; @@ -48,7 +48,7 @@ describe('knowledge sqlite store', () => { const dbPath = join(dir, 'knowledge.db'); const migration = migrateKnowledgeDb(dbPath); - expect(migration.schema_version).toBe(9); + expect(migration.schema_version).toBe(CURRENT_SCHEMA_VERSION); const db = openKnowledgeDb(dbPath); try { @@ -75,6 +75,8 @@ describe('knowledge sqlite store', () => { expect(tables).toContain('knowledge_sync_conflicts'); expect(tables).toContain('knowledge_sync_table_clocks'); expect(tables).toContain('knowledge_sync_imports'); + expect(tables).toContain('knowledge_promotion_candidates'); + expect(tables).toContain('durable_knowledge_records'); const wikiColumns = db.query<{ name: string }, []>('PRAGMA table_info(wiki_pages)').all() .map((row) => row.name); expect(wikiColumns).toContain('valid_from'); @@ -88,7 +90,7 @@ describe('knowledge sqlite store', () => { } const stats = getKnowledgeDbStats(dbPath); - expect(stats.schema_version).toBe(9); + expect(stats.schema_version).toBe(CURRENT_SCHEMA_VERSION); expect(stats.sources).toBe(0); expect(stats.runs).toBe(0); expect(stats.redaction_findings).toBe(0); @@ -137,7 +139,7 @@ describe('knowledge sqlite store', () => { } const migration = migrateKnowledgeDb(dbPath); - expect(migration.schema_version).toBe(9); + expect(migration.schema_version).toBe(CURRENT_SCHEMA_VERSION); const migrated = openKnowledgeDb(dbPath); try { @@ -268,7 +270,7 @@ describe('knowledge sqlite store', () => { } const migration = migrateKnowledgeDb(dbPath); - expect(migration.schema_version).toBe(9); + expect(migration.schema_version).toBe(CURRENT_SCHEMA_VERSION); const recovered = openKnowledgeDb(dbPath); try { @@ -306,7 +308,7 @@ describe('knowledge sqlite store', () => { } const migration = migrateKnowledgeDb(dbPath); - expect(migration.schema_version).toBe(9); + expect(migration.schema_version).toBe(CURRENT_SCHEMA_VERSION); const stats = getKnowledgeDbStats(dbPath); expect(stats.sync_table_clocks).toBe(0); @@ -370,7 +372,7 @@ describe('knowledge sqlite store', () => { }); const stats = getKnowledgeDbStats(dbPath); - expect(stats.schema_version).toBe(9); + expect(stats.schema_version).toBe(CURRENT_SCHEMA_VERSION); expect(stats.sources).toBe(2); expect(stats.source_revisions).toBe(2); expect(stats.chunks).toBe(1); diff --git a/tests/mcp.test.ts b/tests/mcp.test.ts index a12b423..fe17523 100644 --- a/tests/mcp.test.ts +++ b/tests/mcp.test.ts @@ -5,6 +5,7 @@ import { delimiter, join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { CURRENT_SCHEMA_VERSION } from '../src/knowledge-db'; import { ingestOpenFilesManifest } from '../src/manifest-ingest'; import { createKnowledgeService } from '../src/service'; import { recordKnowledgeSyncConflict } from '../src/sync'; @@ -353,7 +354,7 @@ describe('knowledge MCP', () => { const syncResource = parseResourceJson(await client.readResource({ uri: 'knowledge://project/sync' })); expect(syncResource.ok).toBe(true); - expect(syncResource.sqlite_schema_version).toBe(9); + expect(syncResource.sqlite_schema_version).toBe(CURRENT_SCHEMA_VERSION); const sourceResource = parseResourceJson(await client.readResource({ uri: 'knowledge://project/sources' })); expect(sourceResource.sources[0].uri).toBe('open-files://file/file_mcp'); diff --git a/tests/reindex.test.ts b/tests/reindex.test.ts index eb96729..f317823 100644 --- a/tests/reindex.test.ts +++ b/tests/reindex.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { getKnowledgeDbStats } from '../src/knowledge-db'; +import { CURRENT_SCHEMA_VERSION, getKnowledgeDbStats } from '../src/knowledge-db'; import { enqueueMissingEmbeddings, refreshEmbeddingIndex, reindexHealth } from '../src/reindex'; import { ingestSourceRef } from '../src/source-ingest'; @@ -22,7 +22,7 @@ describe('knowledge reindex queue and refresh jobs', () => { expect(ingest.chunks_inserted).toBe(1); const initial = reindexHealth({ dbPath, fake: true, dimensions: 8 }); - expect(initial.schema_version).toBe(9); + expect(initial.schema_version).toBe(CURRENT_SCHEMA_VERSION); expect(initial.chunks).toBe(1); expect(initial.vector_entries).toBe(0); expect(initial.missing_embeddings).toBe(1); diff --git a/tests/rules-provenance.test.ts b/tests/rules-provenance.test.ts index eb76354..7b46870 100644 --- a/tests/rules-provenance.test.ts +++ b/tests/rules-provenance.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { getKnowledgeDbStats, openKnowledgeDb } from '../src/knowledge-db'; +import { KNOWLEDGE_API_KEY_ENV_KEYS, KNOWLEDGE_API_URL_ENV_KEYS, KNOWLEDGE_MODE_ENV_KEYS } from '../src/knowledge-mode'; import { importRulesProvenance } from '../src/rules-provenance'; import { redactSecrets } from '../src/safety'; import { createKnowledgeService } from '../src/service'; @@ -13,9 +14,13 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); const CLI = join(__dirname, '..', 'src', 'cli.ts'); function runCli(args: string[], cwd: string) { + const env = { ...process.env, HOME: cwd, USERPROFILE: cwd }; + for (const key of [...KNOWLEDGE_API_URL_ENV_KEYS, ...KNOWLEDGE_API_KEY_ENV_KEYS, ...KNOWLEDGE_MODE_ENV_KEYS]) { + delete env[key]; + } const result = spawnSync('bun', [CLI, ...args], { cwd, - env: { ...process.env, HOME: cwd, USERPROFILE: cwd }, + env, maxBuffer: 64 * 1024 * 1024, }); return { diff --git a/tests/sdk.test.ts b/tests/sdk.test.ts index cd5de8c..275a572 100644 --- a/tests/sdk.test.ts +++ b/tests/sdk.test.ts @@ -11,6 +11,7 @@ import { recordKnowledgeSyncConflict, type KnowledgeClient, } from '../src/index'; +import { CURRENT_SCHEMA_VERSION } from '../src/knowledge-db'; function writeWindowsCmdShim(bin: string, name: string): void { writeFileSync(join(bin, `${name}.cmd`), [ @@ -326,7 +327,7 @@ describe('public knowledge sdk', () => { expect(parsed.kind).toBe('file'); const migration = client.db.init(); - expect(migration.schema_version).toBe(9); + expect(migration.schema_version).toBe(CURRENT_SCHEMA_VERSION); const ingest = await client.ingest.source(`file://${source}`, 'knowledge_index'); expect(ingest.sources_upserted).toBe(1); diff --git a/tests/service.test.ts b/tests/service.test.ts index 1ee481a..178be6b 100644 --- a/tests/service.test.ts +++ b/tests/service.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { CURRENT_SCHEMA_VERSION } from '../src/knowledge-db'; import { createKnowledgeService } from '../src/service'; function normalizeDarwinPath(path: string): string { @@ -23,7 +24,7 @@ describe('knowledge service facade', () => { expect(service.validateStorage().ok).toBe(true); const migration = service.initDb(); - expect(migration.schema_version).toBe(9); + expect(migration.schema_version).toBe(CURRENT_SCHEMA_VERSION); const ingest = await service.ingestSource(sourceRef, 'knowledge_index'); expect(ingest.chunks_inserted).toBe(1); @@ -38,6 +39,40 @@ describe('knowledge service facade', () => { expect(stats.sources).toBe(1); expect(stats.chunks).toBe(1); + const candidate = service.enqueuePromotion({ + kind: 'lesson', + title: 'Service Inventory Durable Lesson', + content: 'Inventory should list promoted durable knowledge records without dumping full content.', + sourceKind: 'session', + sourceRefs: [sourceRef], + evidenceRefs: [sourceRef], + confidence: 0.9, + }); + const promoted = service.promoteCandidate(candidate.candidate.id); + expect(promoted.promoted).toBe(true); + + const inventory = service.inventory({ limit: 10 }); + expect(inventory.summary.promotion_candidates).toBe(1); + expect(inventory.summary.durable_records).toBe(1); + expect(inventory.promotion_candidates[0]).toMatchObject({ + id: candidate.candidate.id, + record_kind: 'lesson', + status: 'promoted', + source_refs: [sourceRef], + requires_approval: false, + }); + expect(inventory.promotion_candidates[0].content).toBeUndefined(); + expect(inventory.promotion_candidates[0].content_preview).toContain('Inventory should list promoted'); + expect(inventory.durable_records[0]).toMatchObject({ + record_kind: 'lesson', + status: 'active', + source_refs: [sourceRef], + confidence: 0.9, + promoted_from_candidate_id: candidate.candidate.id, + }); + expect(inventory.durable_records[0].content).toBeUndefined(); + expect(inventory.durable_records[0].content_preview).toContain('Inventory should list promoted'); + const wiki = await service.initWiki(); expect(wiki.artifacts).toHaveLength(4); const wikiStats = service.dbStats(); diff --git a/tests/sync.test.ts b/tests/sync.test.ts index 2ad1688..0401dc5 100644 --- a/tests/sync.test.ts +++ b/tests/sync.test.ts @@ -3,7 +3,7 @@ import { existsSync, mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { normalizeArtifactKey, type ArtifactStore, type ArtifactWrite } from '../src/artifact-store'; -import { openKnowledgeDb } from '../src/knowledge-db'; +import { CURRENT_SCHEMA_VERSION, openKnowledgeDb } from '../src/knowledge-db'; import { createKnowledgeService } from '../src/service'; import { recordStorageObjects } from '../src/storage-contract'; import { @@ -239,7 +239,7 @@ describe('knowledge machine sync ledger', () => { expect(syncArtifactsFromSnapshot(snapshot.snapshot)).toHaveLength(1); const status = service.syncStatus(); - expect(status.sqlite_schema_version).toBe(9); + expect(status.sqlite_schema_version).toBe(CURRENT_SCHEMA_VERSION); expect(status.machines.total).toBe(2); expect(status.snapshots.total).toBe(1); expect(status.clocks.total).toBeGreaterThan(0);