From e62fd1f1cd69b38967834c4cbc7c0e9d547c32cc Mon Sep 17 00:00:00 2001 From: Andrei Hasna Date: Mon, 10 Aug 2026 22:07:02 +0300 Subject: [PATCH 1/2] fix: close knowledge release blockers Make the serve export importable under Node, serialize project-link adoption and compensation, and bound PostgreSQL resource page materialization. Agent: Theophrastus --- bin/knowledge-mcp.js | 385 +++++++++++++- bin/knowledge-serve.js | 381 +++++++++++++- bin/knowledge.js | 511 +++++++++++-------- dist/index.js | 389 +++++++++++++- dist/project-links.d.ts | 6 + dist/serve.js | 389 +++++++++++++- dist/storage.js | 389 +++++++++++++- src/project-links.ts | 505 +++++++++++++++++- tests/package-release.test.ts | 26 + tests/project-links-release-blockers.test.ts | 498 ++++++++++++++++++ tests/project-links.test.ts | 17 + 11 files changed, 3276 insertions(+), 220 deletions(-) create mode 100644 tests/project-links-release-blockers.test.ts diff --git a/bin/knowledge-mcp.js b/bin/knowledge-mcp.js index 9688f17..a51e810 100755 --- a/bin/knowledge-mcp.js +++ b/bin/knowledge-mcp.js @@ -29233,11 +29233,11 @@ function migrateLegacyKnowledgeWorkspace(options) { // src/project-links.ts import { createHash as createHash19 } from "crypto"; -import { Database as Database2 } from "bun:sqlite"; var KNOWLEDGE_PROJECT_REGISTRATION_ROUTE = "knowledge.project-registration.v1"; var KNOWLEDGE_PROJECT_RESOURCES_ROUTE = "knowledge.project-resources.v1"; var KNOWLEDGE_PROJECT_REGISTRATION_SCHEMA_VERSION = 1; var KNOWLEDGE_PROJECT_MEMBERSHIP_RULE = "explicit_collection_binding"; +var KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD = 1; class KnowledgeProjectLinksError extends Error { code; @@ -29251,6 +29251,7 @@ class KnowledgeProjectLinksError extends Error { } class SqliteProjectLinksSql { db; + kind = "sqlite"; tail = Promise.resolve(); closed = false; constructor(db) { @@ -29273,6 +29274,7 @@ class SqliteProjectLinksSql { const result = this.db.query(sql).run(...params); return { changes: Number(result.changes) }; } + async lock(_key) {} transaction(fn) { const run = this.tail.then(async () => { this.db.exec("BEGIN IMMEDIATE"); @@ -29672,6 +29674,27 @@ class PackageOwnedKnowledgeProjectLinksAuthority { stableCollectionId(sourceProjectId, collectionSlug) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00collection\x00${sourceProjectId}\x00${collectionSlug}`); } + collectionFence(collectionId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "collection", + collectionId + ].join("\x1F"); + } + membershipFence(collectionId, itemId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "membership", + collectionId, + itemId + ].join("\x1F"); + } stableReceiptId(operationId, stepId, action, direction) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00receipt\x00${operationId}\x00${stepId}\x00${action}\x00${direction}`); } @@ -29765,6 +29788,7 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (request.request_digest !== expectedRequestDigest) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH", "request_digest does not bind the normalized collection-registration request.", { expected_request_digest: expectedRequestDigest }); } + const stableCollectionId = this.stableCollectionId(sourceProjectId, collectionSlug); return this.sql.transaction(async (tx) => { const duplicate = await this.getReceiptByAttempt(tx, { operation_id: request.operation_id, @@ -29776,12 +29800,13 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(stableCollectionId)); let aggregate = await this.getAggregateBySource(tx, sourceProjectId); const createdByOperation = aggregate === null; if (!aggregate) { const now = this.now(); const projectId = this.stableProjectId(sourceProjectId); - const collectionId = this.stableCollectionId(sourceProjectId, collectionSlug); + const collectionId = stableCollectionId; await tx.run(`INSERT INTO knowledge_projects ( authority_id, tenant_id, corpus_id, source_project_id, project_id, project_slug, project_name, created_at, updated_at @@ -29925,6 +29950,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "register_collection" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted collection-registration receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } const aggregate = accepted.collection_id ? await this.getAggregateByCollection(tx, accepted.collection_id) : null; let outcome = "accepted"; let reason = null; @@ -30064,6 +30092,8 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(collectionId)); + await tx.lock(this.membershipFence(collectionId, itemId)); const aggregate = await this.getAggregateByCollection(tx, collectionId); if (!aggregate) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge collection was not found by exact id."); @@ -30186,6 +30216,12 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "bind_item" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted item-binding receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } + if (accepted.collection_id && accepted.item_id) { + await tx.lock(this.membershipFence(accepted.collection_id, accepted.item_id)); + } let outcome = "accepted"; let reason = null; const membership = await tx.get(`SELECT * FROM knowledge_project_collection_memberships @@ -30301,6 +30337,341 @@ class PackageOwnedKnowledgeProjectLinksAuthority { digest: inverse.result_digest }; } + resourceBase(aggregate) { + return { + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + revision: `r${Number(aggregate.revision)}` + }; + } + projectResource(aggregate) { + const body = { + ...this.resourceBase(aggregate), + kind: "project", + id: aggregate.project_id, + title: aggregate.project_name, + locator: { kind: "canonical_uri", value: `knowledge:project:${aggregate.project_id}` }, + metadata: { + source_project_id: aggregate.source_project_id, + slug: aggregate.project_slug, + collection_count: 1 + } + }; + return { + ...body, + key: `project:${aggregate.project_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + collectionResource(aggregate, memberCount) { + const body = { + ...this.resourceBase(aggregate), + kind: "collection", + id: aggregate.collection_id, + title: aggregate.collection_name, + locator: { kind: "external_uuid", value: aggregate.collection_id }, + metadata: { + slug: aggregate.collection_slug, + membership_rule: KNOWLEDGE_PROJECT_MEMBERSHIP_RULE, + member_count: memberCount + } + }; + return { + ...body, + key: `collection:${aggregate.collection_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + itemResource(aggregate, item) { + const body = { + ...this.resourceBase(aggregate), + kind: "item", + id: item.id, + revision: `v${item.version ?? 1}`, + title: item.title, + locator: { kind: "canonical_uri", value: `knowledge:item:${encodeURIComponent(item.id)}` }, + metadata: { + tags: [...item.tags ?? []], + archived: item.archived === true, + updated_at: item.updated_at + } + }; + return { + ...body, + key: `item:${item.id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + taxonomyResource(aggregate, normalized, input) { + const taxonomyId = stableUuid(`${aggregate.collection_id}\x00taxonomy\x00${normalized}`); + const body = { + ...this.resourceBase(aggregate), + kind: "taxonomy", + id: taxonomyId, + title: input.label, + locator: { kind: "external_uuid", value: taxonomyId }, + metadata: { + tag: input.label, + normalized_tag: normalized, + item_count: input.itemCount, + member_digest: input.memberDigest + } + }; + return { + ...body, + key: `taxonomy:${taxonomyId}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + postgresItem(row) { + const parseJson4 = (value, fallback) => { + if (value == null) + return fallback; + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return fallback; + } + } + return value; + }; + return { + id: String(row.id), + short_id: row.short_id ?? null, + title: String(row.title ?? ""), + content: String(row.content ?? ""), + url: row.url ?? null, + tags: parseJson4(row.tags, []), + metadata: parseJson4(row.metadata, {}), + archived: Boolean(row.archived), + created_at: String(row.created_at), + updated_at: String(row.updated_at), + version: row.version == null ? 1 : Number(row.version) + }; + } + resourceCursorAfter(input) { + if (!input.cursor) + return ""; + let decoded; + try { + decoded = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")); + } catch { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT", "cursor is not a valid Knowledge project-resources cursor."); + } + if (decoded.version !== 1 || decoded.project_id !== input.aggregate.project_id || decoded.collection_id !== input.aggregate.collection_id || decoded.collection_revision !== input.revision || decoded.population_digest !== input.populationDigest || canonicalKnowledgeProjectLinksJson(decoded.kinds) !== canonicalKnowledgeProjectLinksJson(input.kinds) || typeof decoded.after !== "string") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE", "project resources changed or the cursor belongs to a different project/kind selection; restart from the first page."); + } + return decoded.after; + } + async listPostgresProjectResources(projectId, options, limit, kinds) { + const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); + if (!aggregate) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge project aggregate was not found by source or stable project id."); + } + const identityParams = [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]; + const population = await this.sql.get(`SELECT + COUNT(*)::text AS membership_count, + COUNT(i.id)::text AS visible_item_count, + encode(sha256(convert_to(COALESCE(string_agg( + m.item_id || E'\\x1f' + || COALESCE(i.title, '') || E'\\x1f' + || COALESCE(i.updated_at, '') || E'\\x1f' + || COALESCE(i.version::text, '1') || E'\\x1f' + || COALESCE(i.tags::text, '[]') || E'\\x1f' + || COALESCE(i.archived::text, 'false'), + E'\\x1e' ORDER BY m.item_id + ), ''), 'UTF8')), 'hex') AS item_snapshot_digest + FROM knowledge_project_collection_memberships m + LEFT JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ?`, [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]); + const membershipCount = Number(population?.membership_count ?? 0); + const visibleItemCount = Number(population?.visible_item_count ?? 0); + if (membershipCount !== visibleItemCount) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION", "collection membership points at a missing or inaccessible Knowledge item; refusing a partial resource population.", { + collection_id: aggregate.collection_id, + membership_count: membershipCount, + visible_item_count: visibleItemCount + }); + } + const taxonomyCountRow = await this.sql.get(`SELECT COUNT(*)::text AS taxonomy_count + FROM ( + SELECT LOWER(BTRIM(tag.value)) AS normalized_tag + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) AS tag(value) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + GROUP BY LOWER(BTRIM(tag.value)) + ) taxonomy`, identityParams); + const taxonomyCount = Number(taxonomyCountRow?.taxonomy_count ?? 0); + const revision = `r${Number(aggregate.revision)}`; + const populationDigest = digestKnowledgeProjectLinksValue({ + collection_revision: revision, + kinds, + item_snapshot_digest: kinds.includes("item") || kinds.includes("taxonomy") ? population?.item_snapshot_digest ?? "" : null, + taxonomy_count: kinds.includes("taxonomy") ? taxonomyCount : null + }); + const after = this.resourceCursorAfter({ + cursor: options.cursor, + aggregate, + revision, + populationDigest, + kinds + }); + const targetCount = limit + KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD; + const candidates = []; + const append = (resource) => { + if (candidates.length < targetCount && kinds.includes(resource.kind) && resource.key > after) { + candidates.push(resource); + } + }; + append(this.collectionResource(aggregate, membershipCount)); + if (kinds.includes("item") && candidates.length < targetCount && after < "project:") { + const itemAfter = after.startsWith("item:") ? after.slice("item:".length) : ""; + const rows = await this.sql.many(`SELECT i.* + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? AND m.item_id > ? + ORDER BY m.item_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, itemAfter]); + for (const row of rows) + append(this.itemResource(aggregate, this.postgresItem(row))); + } + append(this.projectResource(aggregate)); + if (kinds.includes("taxonomy") && candidates.length < targetCount) { + const taxonomyAfter = after.startsWith("taxonomy:") ? after : "taxonomy:"; + const rows = await this.sql.many(`WITH tagged AS ( + SELECT + m.item_id, + BTRIM(tag.value) AS label, + LOWER(BTRIM(tag.value)) AS normalized_tag, + tag.ordinality + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) + WITH ORDINALITY AS tag(value, ordinality) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + ), + grouped AS ( + SELECT + normalized_tag, + (array_agg(label ORDER BY item_id, ordinality))[1] AS label, + COUNT(*)::text AS item_count, + encode(sha256(convert_to( + jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + 'UTF8' + )), 'hex') AS member_digest, + encode(sha256( + convert_to(?, 'UTF8') + || decode('00', 'hex') + || convert_to('taxonomy', 'UTF8') + || decode('00', 'hex') + || convert_to(normalized_tag, 'UTF8') + ), 'hex') AS stable_hex + FROM tagged + GROUP BY normalized_tag + ), + mutated AS ( + SELECT + *, + overlay( + overlay(substr(stable_hex, 1, 32) placing '5' from 13 for 1) + placing substr( + '89ab', + ((strpos('0123456789abcdef', substr(stable_hex, 17, 1)) - 1) % 4) + 1, + 1 + ) + from 17 for 1 + ) AS stable_uuid_hex + FROM grouped + ), + keyed AS ( + SELECT + normalized_tag, + label, + item_count, + member_digest, + substr(stable_uuid_hex, 1, 8) + || '-' || substr(stable_uuid_hex, 9, 4) + || '-' || substr(stable_uuid_hex, 13, 4) + || '-' || substr(stable_uuid_hex, 17, 4) + || '-' || substr(stable_uuid_hex, 21, 12) AS taxonomy_id + FROM mutated + ) + SELECT normalized_tag, label, item_count, member_digest + FROM keyed + WHERE 'taxonomy:' || taxonomy_id > ? + ORDER BY taxonomy_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, aggregate.collection_id, taxonomyAfter]); + for (const row of rows) { + append(this.taxonomyResource(aggregate, row.normalized_tag, { + label: row.label, + itemCount: Number(row.item_count), + memberDigest: row.member_digest + })); + } + } + const total = (kinds.includes("collection") ? 1 : 0) + (kinds.includes("item") ? membershipCount : 0) + (kinds.includes("project") ? 1 : 0) + (kinds.includes("taxonomy") ? taxonomyCount : 0); + const pageResources = candidates.slice(0, limit); + const hasMore = candidates.length > pageResources.length; + const nextCursor = hasMore && pageResources.length > 0 ? Buffer.from(JSON.stringify({ + version: 1, + project_id: aggregate.project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + kinds, + after: pageResources.at(-1).key + })).toString("base64url") : null; + return { + schema: "knowledge.project-resources.page.v1", + authority: "knowledge", + route: KNOWLEDGE_PROJECT_RESOURCES_ROUTE, + ...this.identity, + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + resource_kinds: kinds, + resources: pageResources, + count: pageResources.length, + total, + limit, + cursor: options.cursor ?? null, + next_cursor: nextCursor, + has_more: hasMore, + complete: !hasMore, + truncated: false + }; + } async buildResources(projectId) { const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); if (!aggregate) { @@ -30421,6 +30792,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { async listProjectResources(projectId, options = {}) { const limit = boundedLimit(options.limit); const kinds = normalizeKinds(options.kinds); + if (this.sql.kind === "postgres") { + return this.listPostgresProjectResources(projectId, options, limit, kinds); + } const { aggregate, resources } = await this.buildResources(projectId); const revision = `r${Number(aggregate.revision)}`; const population = resources.filter((resource) => kinds.includes(resource.kind)); @@ -30521,7 +30895,12 @@ function createLocalKnowledgeProjectLinksAuthority(input) { if (input.databasePath !== ":memory:") { ensureParentDir(input.databasePath); } - const db = new Database2(input.databasePath, { create: true }); + const require2 = import.meta.require; + if (typeof require2 !== "function") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CONFLICT", "the local Knowledge project-links authority requires the Bun runtime."); + } + const { Database: BunDatabase } = require2("bun:sqlite"); + const db = new BunDatabase(input.databasePath, { create: true }); db.exec(sqliteKnowledgeProjectLinksSchemaSql()); return new PackageOwnedKnowledgeProjectLinksAuthority(new SqliteProjectLinksSql(db), (id) => input.itemStore.get(id), input.options); } diff --git a/bin/knowledge-serve.js b/bin/knowledge-serve.js index 8df3bcc..997cc21 100755 --- a/bin/knowledge-serve.js +++ b/bin/knowledge-serve.js @@ -1371,6 +1371,7 @@ var KNOWLEDGE_PROJECT_REGISTRATION_ROUTE = "knowledge.project-registration.v1"; var KNOWLEDGE_PROJECT_RESOURCES_ROUTE = "knowledge.project-resources.v1"; var KNOWLEDGE_PROJECT_REGISTRATION_SCHEMA_VERSION = 1; var KNOWLEDGE_PROJECT_MEMBERSHIP_RULE = "explicit_collection_binding"; +var KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD = 1; class KnowledgeProjectLinksError extends Error { code; @@ -1390,6 +1391,7 @@ function postgresSql(sql) { class PostgresProjectLinksSql { client; transactionClient; + kind = "postgres"; constructor(client, transactionClient) { this.client = client; this.transactionClient = transactionClient; @@ -1405,6 +1407,9 @@ class PostgresProjectLinksSql { const result = await this.client.query(postgresSql(sql), params); return { changes: result.rowCount }; } + async lock(key) { + await this.client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [key]); + } async transaction(fn) { if (!this.transactionClient) return fn(this); @@ -1414,6 +1419,7 @@ class PostgresProjectLinksSql { class SqliteProjectLinksSql { db; + kind = "sqlite"; tail = Promise.resolve(); closed = false; constructor(db) { @@ -1436,6 +1442,7 @@ class SqliteProjectLinksSql { const result = this.db.query(sql).run(...params); return { changes: Number(result.changes) }; } + async lock(_key) {} transaction(fn) { const run = this.tail.then(async () => { this.db.exec("BEGIN IMMEDIATE"); @@ -1645,6 +1652,27 @@ class PackageOwnedKnowledgeProjectLinksAuthority { stableCollectionId(sourceProjectId, collectionSlug) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00collection\x00${sourceProjectId}\x00${collectionSlug}`); } + collectionFence(collectionId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "collection", + collectionId + ].join("\x1F"); + } + membershipFence(collectionId, itemId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "membership", + collectionId, + itemId + ].join("\x1F"); + } stableReceiptId(operationId, stepId, action, direction) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00receipt\x00${operationId}\x00${stepId}\x00${action}\x00${direction}`); } @@ -1738,6 +1766,7 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (request.request_digest !== expectedRequestDigest) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH", "request_digest does not bind the normalized collection-registration request.", { expected_request_digest: expectedRequestDigest }); } + const stableCollectionId = this.stableCollectionId(sourceProjectId, collectionSlug); return this.sql.transaction(async (tx) => { const duplicate = await this.getReceiptByAttempt(tx, { operation_id: request.operation_id, @@ -1749,12 +1778,13 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(stableCollectionId)); let aggregate = await this.getAggregateBySource(tx, sourceProjectId); const createdByOperation = aggregate === null; if (!aggregate) { const now = this.now(); const projectId = this.stableProjectId(sourceProjectId); - const collectionId = this.stableCollectionId(sourceProjectId, collectionSlug); + const collectionId = stableCollectionId; await tx.run(`INSERT INTO knowledge_projects ( authority_id, tenant_id, corpus_id, source_project_id, project_id, project_slug, project_name, created_at, updated_at @@ -1898,6 +1928,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "register_collection" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted collection-registration receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } const aggregate = accepted.collection_id ? await this.getAggregateByCollection(tx, accepted.collection_id) : null; let outcome = "accepted"; let reason = null; @@ -2037,6 +2070,8 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(collectionId)); + await tx.lock(this.membershipFence(collectionId, itemId)); const aggregate = await this.getAggregateByCollection(tx, collectionId); if (!aggregate) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge collection was not found by exact id."); @@ -2159,6 +2194,12 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "bind_item" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted item-binding receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } + if (accepted.collection_id && accepted.item_id) { + await tx.lock(this.membershipFence(accepted.collection_id, accepted.item_id)); + } let outcome = "accepted"; let reason = null; const membership = await tx.get(`SELECT * FROM knowledge_project_collection_memberships @@ -2274,6 +2315,341 @@ class PackageOwnedKnowledgeProjectLinksAuthority { digest: inverse.result_digest }; } + resourceBase(aggregate) { + return { + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + revision: `r${Number(aggregate.revision)}` + }; + } + projectResource(aggregate) { + const body = { + ...this.resourceBase(aggregate), + kind: "project", + id: aggregate.project_id, + title: aggregate.project_name, + locator: { kind: "canonical_uri", value: `knowledge:project:${aggregate.project_id}` }, + metadata: { + source_project_id: aggregate.source_project_id, + slug: aggregate.project_slug, + collection_count: 1 + } + }; + return { + ...body, + key: `project:${aggregate.project_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + collectionResource(aggregate, memberCount) { + const body = { + ...this.resourceBase(aggregate), + kind: "collection", + id: aggregate.collection_id, + title: aggregate.collection_name, + locator: { kind: "external_uuid", value: aggregate.collection_id }, + metadata: { + slug: aggregate.collection_slug, + membership_rule: KNOWLEDGE_PROJECT_MEMBERSHIP_RULE, + member_count: memberCount + } + }; + return { + ...body, + key: `collection:${aggregate.collection_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + itemResource(aggregate, item) { + const body = { + ...this.resourceBase(aggregate), + kind: "item", + id: item.id, + revision: `v${item.version ?? 1}`, + title: item.title, + locator: { kind: "canonical_uri", value: `knowledge:item:${encodeURIComponent(item.id)}` }, + metadata: { + tags: [...item.tags ?? []], + archived: item.archived === true, + updated_at: item.updated_at + } + }; + return { + ...body, + key: `item:${item.id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + taxonomyResource(aggregate, normalized, input) { + const taxonomyId = stableUuid(`${aggregate.collection_id}\x00taxonomy\x00${normalized}`); + const body = { + ...this.resourceBase(aggregate), + kind: "taxonomy", + id: taxonomyId, + title: input.label, + locator: { kind: "external_uuid", value: taxonomyId }, + metadata: { + tag: input.label, + normalized_tag: normalized, + item_count: input.itemCount, + member_digest: input.memberDigest + } + }; + return { + ...body, + key: `taxonomy:${taxonomyId}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + postgresItem(row) { + const parseJson = (value, fallback) => { + if (value == null) + return fallback; + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return fallback; + } + } + return value; + }; + return { + id: String(row.id), + short_id: row.short_id ?? null, + title: String(row.title ?? ""), + content: String(row.content ?? ""), + url: row.url ?? null, + tags: parseJson(row.tags, []), + metadata: parseJson(row.metadata, {}), + archived: Boolean(row.archived), + created_at: String(row.created_at), + updated_at: String(row.updated_at), + version: row.version == null ? 1 : Number(row.version) + }; + } + resourceCursorAfter(input) { + if (!input.cursor) + return ""; + let decoded; + try { + decoded = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")); + } catch { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT", "cursor is not a valid Knowledge project-resources cursor."); + } + if (decoded.version !== 1 || decoded.project_id !== input.aggregate.project_id || decoded.collection_id !== input.aggregate.collection_id || decoded.collection_revision !== input.revision || decoded.population_digest !== input.populationDigest || canonicalKnowledgeProjectLinksJson(decoded.kinds) !== canonicalKnowledgeProjectLinksJson(input.kinds) || typeof decoded.after !== "string") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE", "project resources changed or the cursor belongs to a different project/kind selection; restart from the first page."); + } + return decoded.after; + } + async listPostgresProjectResources(projectId, options, limit, kinds) { + const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); + if (!aggregate) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge project aggregate was not found by source or stable project id."); + } + const identityParams = [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]; + const population = await this.sql.get(`SELECT + COUNT(*)::text AS membership_count, + COUNT(i.id)::text AS visible_item_count, + encode(sha256(convert_to(COALESCE(string_agg( + m.item_id || E'\\x1f' + || COALESCE(i.title, '') || E'\\x1f' + || COALESCE(i.updated_at, '') || E'\\x1f' + || COALESCE(i.version::text, '1') || E'\\x1f' + || COALESCE(i.tags::text, '[]') || E'\\x1f' + || COALESCE(i.archived::text, 'false'), + E'\\x1e' ORDER BY m.item_id + ), ''), 'UTF8')), 'hex') AS item_snapshot_digest + FROM knowledge_project_collection_memberships m + LEFT JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ?`, [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]); + const membershipCount = Number(population?.membership_count ?? 0); + const visibleItemCount = Number(population?.visible_item_count ?? 0); + if (membershipCount !== visibleItemCount) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION", "collection membership points at a missing or inaccessible Knowledge item; refusing a partial resource population.", { + collection_id: aggregate.collection_id, + membership_count: membershipCount, + visible_item_count: visibleItemCount + }); + } + const taxonomyCountRow = await this.sql.get(`SELECT COUNT(*)::text AS taxonomy_count + FROM ( + SELECT LOWER(BTRIM(tag.value)) AS normalized_tag + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) AS tag(value) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + GROUP BY LOWER(BTRIM(tag.value)) + ) taxonomy`, identityParams); + const taxonomyCount = Number(taxonomyCountRow?.taxonomy_count ?? 0); + const revision = `r${Number(aggregate.revision)}`; + const populationDigest = digestKnowledgeProjectLinksValue({ + collection_revision: revision, + kinds, + item_snapshot_digest: kinds.includes("item") || kinds.includes("taxonomy") ? population?.item_snapshot_digest ?? "" : null, + taxonomy_count: kinds.includes("taxonomy") ? taxonomyCount : null + }); + const after = this.resourceCursorAfter({ + cursor: options.cursor, + aggregate, + revision, + populationDigest, + kinds + }); + const targetCount = limit + KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD; + const candidates = []; + const append = (resource) => { + if (candidates.length < targetCount && kinds.includes(resource.kind) && resource.key > after) { + candidates.push(resource); + } + }; + append(this.collectionResource(aggregate, membershipCount)); + if (kinds.includes("item") && candidates.length < targetCount && after < "project:") { + const itemAfter = after.startsWith("item:") ? after.slice("item:".length) : ""; + const rows = await this.sql.many(`SELECT i.* + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? AND m.item_id > ? + ORDER BY m.item_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, itemAfter]); + for (const row of rows) + append(this.itemResource(aggregate, this.postgresItem(row))); + } + append(this.projectResource(aggregate)); + if (kinds.includes("taxonomy") && candidates.length < targetCount) { + const taxonomyAfter = after.startsWith("taxonomy:") ? after : "taxonomy:"; + const rows = await this.sql.many(`WITH tagged AS ( + SELECT + m.item_id, + BTRIM(tag.value) AS label, + LOWER(BTRIM(tag.value)) AS normalized_tag, + tag.ordinality + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) + WITH ORDINALITY AS tag(value, ordinality) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + ), + grouped AS ( + SELECT + normalized_tag, + (array_agg(label ORDER BY item_id, ordinality))[1] AS label, + COUNT(*)::text AS item_count, + encode(sha256(convert_to( + jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + 'UTF8' + )), 'hex') AS member_digest, + encode(sha256( + convert_to(?, 'UTF8') + || decode('00', 'hex') + || convert_to('taxonomy', 'UTF8') + || decode('00', 'hex') + || convert_to(normalized_tag, 'UTF8') + ), 'hex') AS stable_hex + FROM tagged + GROUP BY normalized_tag + ), + mutated AS ( + SELECT + *, + overlay( + overlay(substr(stable_hex, 1, 32) placing '5' from 13 for 1) + placing substr( + '89ab', + ((strpos('0123456789abcdef', substr(stable_hex, 17, 1)) - 1) % 4) + 1, + 1 + ) + from 17 for 1 + ) AS stable_uuid_hex + FROM grouped + ), + keyed AS ( + SELECT + normalized_tag, + label, + item_count, + member_digest, + substr(stable_uuid_hex, 1, 8) + || '-' || substr(stable_uuid_hex, 9, 4) + || '-' || substr(stable_uuid_hex, 13, 4) + || '-' || substr(stable_uuid_hex, 17, 4) + || '-' || substr(stable_uuid_hex, 21, 12) AS taxonomy_id + FROM mutated + ) + SELECT normalized_tag, label, item_count, member_digest + FROM keyed + WHERE 'taxonomy:' || taxonomy_id > ? + ORDER BY taxonomy_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, aggregate.collection_id, taxonomyAfter]); + for (const row of rows) { + append(this.taxonomyResource(aggregate, row.normalized_tag, { + label: row.label, + itemCount: Number(row.item_count), + memberDigest: row.member_digest + })); + } + } + const total = (kinds.includes("collection") ? 1 : 0) + (kinds.includes("item") ? membershipCount : 0) + (kinds.includes("project") ? 1 : 0) + (kinds.includes("taxonomy") ? taxonomyCount : 0); + const pageResources = candidates.slice(0, limit); + const hasMore = candidates.length > pageResources.length; + const nextCursor = hasMore && pageResources.length > 0 ? Buffer.from(JSON.stringify({ + version: 1, + project_id: aggregate.project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + kinds, + after: pageResources.at(-1).key + })).toString("base64url") : null; + return { + schema: "knowledge.project-resources.page.v1", + authority: "knowledge", + route: KNOWLEDGE_PROJECT_RESOURCES_ROUTE, + ...this.identity, + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + resource_kinds: kinds, + resources: pageResources, + count: pageResources.length, + total, + limit, + cursor: options.cursor ?? null, + next_cursor: nextCursor, + has_more: hasMore, + complete: !hasMore, + truncated: false + }; + } async buildResources(projectId) { const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); if (!aggregate) { @@ -2394,6 +2770,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { async listProjectResources(projectId, options = {}) { const limit = boundedLimit(options.limit); const kinds = normalizeKinds(options.kinds); + if (this.sql.kind === "postgres") { + return this.listPostgresProjectResources(projectId, options, limit, kinds); + } const { aggregate, resources } = await this.buildResources(projectId); const revision = `r${Number(aggregate.revision)}`; const population = resources.filter((resource) => kinds.includes(resource.kind)); diff --git a/bin/knowledge.js b/bin/knowledge.js index 1200ffb..2dde0bc 100755 --- a/bin/knowledge.js +++ b/bin/knowledge.js @@ -1,9 +1,9 @@ #!/usr/bin/env bun // @bun -var TY=Object.create;var{getPrototypeOf:FY,defineProperty:wN,getOwnPropertyNames:VY}=Object;var BY=Object.prototype.hasOwnProperty;function MY(_){return this[_]}var bY,ZY,HY=(_,$,D)=>{var I=_!=null&&typeof _==="object";if(I){var U=$?bY??=new WeakMap:ZY??=new WeakMap,E=U.get(_);if(E)return E}D=_!=null?TY(FY(_)):{};let j=$||!_||!_.__esModule?wN(D,"default",{value:_,enumerable:!0}):D;for(let N of VY(_))if(!BY.call(j,N))wN(j,N,{get:MY.bind(_,N),enumerable:!0});if(I)U.set(_,j);return j};var D4=(_,$)=>()=>($||_(($={exports:{}}).exports,$),$.exports);var kY=(_)=>_;function qY(_,$){this[_]=kY.bind(null,$)}var x$=(_,$)=>{for(var D in $)wN(_,D,{get:$[D],enumerable:!0,configurable:!0,set:qY.bind($,D)})};var r=(_,$)=>()=>(_&&($=_(_=0)),$);var S_=import.meta.require;function K(_,$,D){function I(N,A){if(!N._zod)Object.defineProperty(N,"_zod",{value:{def:A,constr:j,traits:new Set},enumerable:!1});if(N._zod.traits.has(_))return;N._zod.traits.add(_),$(N,A);let O=j.prototype,S=Object.keys(O);for(let L=0;L{if(D?.Parent&&N instanceof D.Parent)return!0;return N?._zod?.traits?.has(_)}}),Object.defineProperty(j,"name",{value:_}),j}function Z_(_){if(_)Object.assign(P4,_);return P4}var yX,FI,VI,m$,z4,P4;var X4=r(()=>{FI=Object.freeze({status:"aborted"});VI=Symbol("zod_brand");m$=class m$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};z4=class z4 extends Error{constructor(_){super(`Encountered unidirectional transform during encode: ${_}`);this.name="ZodEncodeError"}};(yX=globalThis).__zod_globalConfig??(yX.__zod_globalConfig={});P4=globalThis.__zod_globalConfig});var H={};x$(H,{unwrapMessage:()=>DU,uint8ArrayToHex:()=>pV,uint8ArrayToBase64url:()=>tV,uint8ArrayToBase64:()=>nX,stringifyPrimitive:()=>B,slugify:()=>I2,shallowClone:()=>j2,safeExtend:()=>cV,required:()=>mV,randomString:()=>wV,propertyKeyTypes:()=>EU,promiseAllObject:()=>vV,primitiveTypes:()=>N2,prefixIssues:()=>$$,pick:()=>uV,partial:()=>dV,parsedType:()=>M,optionalKeys:()=>g2,omit:()=>yV,objectClone:()=>kV,numKeys:()=>rV,nullish:()=>C6,normalizeParams:()=>v,mergeDefs:()=>S6,merge:()=>nV,jsonStringifyReplacer:()=>H0,joinValues:()=>V,issue:()=>q0,isPlainObject:()=>w6,isObject:()=>G4,hexToUint8Array:()=>oV,getSizableOrigin:()=>jU,getParsedType:()=>fV,getLengthableOrigin:()=>NU,getEnumValues:()=>UU,getElementAtPath:()=>CV,floatSafeRemainder:()=>U2,finalizeIssue:()=>t_,extend:()=>hV,explicitlyAborted:()=>S2,escapeRegex:()=>z$,esc:()=>BI,defineLazy:()=>D_,createTransparentProxy:()=>xV,cloneDef:()=>qV,clone:()=>h_,cleanRegex:()=>IU,cleanEnum:()=>lV,captureStackTrace:()=>MI,cached:()=>k0,base64urlToUint8Array:()=>iV,base64ToUint8Array:()=>cX,assignProp:()=>v6,assertNotEqual:()=>MV,assertNever:()=>ZV,assertIs:()=>bV,assertEqual:()=>BV,assert:()=>HV,allowsEval:()=>E2,aborted:()=>r6,NUMBER_FORMAT_RANGES:()=>A2,Class:()=>dX,BIGINT_FORMAT_RANGES:()=>O2});function BV(_){return _}function MV(_){return _}function bV(_){}function ZV(_){throw Error("Unexpected value in exhaustive check")}function HV(_){}function UU(_){let $=Object.values(_).filter((I)=>typeof I==="number");return Object.entries(_).filter(([I,U])=>$.indexOf(+I)===-1).map(([I,U])=>U)}function V(_,$="|"){return _.map((D)=>B(D)).join($)}function H0(_,$){if(typeof $==="bigint")return $.toString();return $}function k0(_){return{get value(){{let D=_();return Object.defineProperty(this,"value",{value:D}),D}throw Error("cached value already set")}}}function C6(_){return _===null||_===void 0}function IU(_){let $=_.startsWith("^")?1:0,D=_.endsWith("$")?_.length-1:_.length;return _.slice($,D)}function U2(_,$){let D=_/$,I=Math.round(D),U=Number.EPSILON*Math.max(Math.abs(D),1);if(Math.abs(D-I)D?.[I],_)}function vV(_){let $=Object.keys(_),D=$.map((I)=>_[I]);return Promise.all(D).then((I)=>{let U={};for(let E=0;E<$.length;E++)U[$[E]]=I[E];return U})}function wV(_=10){let D="";for(let I=0;I<_;I++)D+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return D}function BI(_){return JSON.stringify(_)}function I2(_){return _.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function G4(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function w6(_){if(G4(_)===!1)return!1;let $=_.constructor;if($===void 0)return!0;if(typeof $!=="function")return!0;let D=$.prototype;if(G4(D)===!1)return!1;if(Object.prototype.hasOwnProperty.call(D,"isPrototypeOf")===!1)return!1;return!0}function j2(_){if(w6(_))return{..._};if(Array.isArray(_))return[..._];if(_ instanceof Map)return new Map(_);if(_ instanceof Set)return new Set(_);return _}function rV(_){let $=0;for(let D in _)if(Object.prototype.hasOwnProperty.call(_,D))$++;return $}function z$(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function h_(_,$,D){let I=new _._zod.constr($??_._zod.def);if(!$||D?.parent)I._zod.parent=_;return I}function v(_){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 xV(_){let $;return new Proxy({},{get(D,I,U){return $??($=_()),Reflect.get($,I,U)},set(D,I,U,E){return $??($=_()),Reflect.set($,I,U,E)},has(D,I){return $??($=_()),Reflect.has($,I)},deleteProperty(D,I){return $??($=_()),Reflect.deleteProperty($,I)},ownKeys(D){return $??($=_()),Reflect.ownKeys($)},getOwnPropertyDescriptor(D,I){return $??($=_()),Reflect.getOwnPropertyDescriptor($,I)},defineProperty(D,I,U){return $??($=_()),Reflect.defineProperty($,I,U)}})}function B(_){if(typeof _==="bigint")return _.toString()+"n";if(typeof _==="string")return`"${_}"`;return`${_}`}function g2(_){return Object.keys(_).filter(($)=>{return _[$]._zod.optin==="optional"&&_[$]._zod.optout==="optional"})}function uV(_,$){let D=_._zod.def,I=D.checks;if(I&&I.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let E=S6(_._zod.def,{get shape(){let j={};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;j[N]=D.shape[N]}return v6(this,"shape",j),j},checks:[]});return h_(_,E)}function yV(_,$){let D=_._zod.def,I=D.checks;if(I&&I.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let E=S6(_._zod.def,{get shape(){let j={..._._zod.def.shape};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;delete j[N]}return v6(this,"shape",j),j},checks:[]});return h_(_,E)}function hV(_,$){if(!w6($))throw Error("Invalid input to extend: expected a plain object");let D=_._zod.def.checks;if(D&&D.length>0){let E=_._zod.def.shape;for(let j in $)if(Object.getOwnPropertyDescriptor(E,j)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let U=S6(_._zod.def,{get shape(){let E={..._._zod.def.shape,...$};return v6(this,"shape",E),E}});return h_(_,U)}function cV(_,$){if(!w6($))throw Error("Invalid input to safeExtend: expected a plain object");let D=S6(_._zod.def,{get shape(){let I={..._._zod.def.shape,...$};return v6(this,"shape",I),I}});return h_(_,D)}function nV(_,$){if(_._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let D=S6(_._zod.def,{get shape(){let I={..._._zod.def.shape,...$._zod.def.shape};return v6(this,"shape",I),I},get catchall(){return $._zod.def.catchall},checks:$._zod.def.checks??[]});return h_(_,D)}function dV(_,$,D){let U=$._zod.def.checks;if(U&&U.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let j=S6($._zod.def,{get shape(){let N=$._zod.def.shape,A={...N};if(D)for(let O in D){if(!(O in N))throw Error(`Unrecognized key: "${O}"`);if(!D[O])continue;A[O]=_?new _({type:"optional",innerType:N[O]}):N[O]}else for(let O in N)A[O]=_?new _({type:"optional",innerType:N[O]}):N[O];return v6(this,"shape",A),A},checks:[]});return h_($,j)}function mV(_,$,D){let I=S6($._zod.def,{get shape(){let U=$._zod.def.shape,E={...U};if(D)for(let j in D){if(!(j in E))throw Error(`Unrecognized key: "${j}"`);if(!D[j])continue;E[j]=new _({type:"nonoptional",innerType:U[j]})}else for(let j in U)E[j]=new _({type:"nonoptional",innerType:U[j]});return v6(this,"shape",E),E}});return h_($,I)}function r6(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue!==!0)return!0;return!1}function S2(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue===!1)return!0;return!1}function $$(_,$){return $.map((D)=>{var I;return(I=D).path??(I.path=[]),D.path.unshift(_),D})}function DU(_){return typeof _==="string"?_:_?.message}function t_(_,$,D){let I=_.message?_.message:DU(_.inst?._zod.def?.error?.(_))??DU($?.error?.(_))??DU(D.customError?.(_))??DU(D.localeError?.(_))??"Invalid input",{inst:U,continue:E,input:j,...N}=_;if(N.path??(N.path=[]),N.message=I,$?.reportInput)N.input=j;return N}function jU(_){if(_ instanceof Set)return"set";if(_ instanceof Map)return"map";if(_ instanceof File)return"file";return"unknown"}function NU(_){if(Array.isArray(_))return"array";if(typeof _==="string")return"string";return"unknown"}function M(_){let $=typeof _;switch($){case"number":return Number.isNaN(_)?"nan":"number";case"object":{if(_===null)return"null";if(Array.isArray(_))return"array";let D=_;if(D&&Object.getPrototypeOf(D)!==Object.prototype&&"constructor"in D&&D.constructor)return D.constructor.name}}return $}function q0(..._){let[$,D,I]=_;if(typeof $==="string")return{message:$,code:"custom",input:D,inst:I};return{...$}}function lV(_){return Object.entries(_).filter(([$,D])=>{return Number.isNaN(Number.parseInt($,10))}).map(($)=>$[1])}function cX(_){let $=atob(_),D=new Uint8Array($.length);for(let I=0;I<$.length;I++)D[I]=$.charCodeAt(I);return D}function nX(_){let $="";for(let D=0;D<_.length;D++)$+=String.fromCharCode(_[D]);return btoa($)}function iV(_){let $=_.replace(/-/g,"+").replace(/_/g,"/"),D="=".repeat((4-$.length%4)%4);return cX($+D)}function tV(_){return nX(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function oV(_){let $=_.replace(/^0x/,"");if($.length%2!==0)throw Error("Invalid hex string length");let D=new Uint8Array($.length/2);for(let I=0;I<$.length;I+=2)D[I/2]=Number.parseInt($.slice(I,I+2),16);return D}function pV(_){return Array.from(_).map(($)=>$.toString(16).padStart(2,"0")).join("")}class dX{constructor(..._){}}var hX,MI,E2,fV=(_)=>{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: ${$}`)}},EU,N2,A2,O2;var n=r(()=>{X4();hX=Symbol("evaluating");MI="captureStackTrace"in Error?Error.captureStackTrace:(..._)=>{};E2=k0(()=>{if(P4.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});EU=new Set(["string","number","symbol"]),N2=new Set(["string","number","bigint","boolean","symbol","undefined"]);A2={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]},O2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function C0(_,$=(D)=>D.message){let D={},I=[];for(let U of _.issues)if(U.path.length>0)D[U.path[0]]=D[U.path[0]]||[],D[U.path[0]].push($(U));else I.push($(U));return{formErrors:I,fieldErrors:D}}function v0(_,$=(D)=>D.message){let D={_errors:[]},I=(U,E=[])=>{for(let j of U.issues)if(j.code==="invalid_union"&&j.errors.length)j.errors.map((N)=>I({issues:N},[...E,...j.path]));else if(j.code==="invalid_key")I({issues:j.issues},[...E,...j.path]);else if(j.code==="invalid_element")I({issues:j.issues},[...E,...j.path]);else{let N=[...E,...j.path];if(N.length===0)D._errors.push($(j));else{let A=D,O=0;while(OD.message){let D={errors:[]},I=(U,E=[])=>{var j,N;for(let A of U.issues)if(A.code==="invalid_union"&&A.errors.length)A.errors.map((O)=>I({issues:O},[...E,...A.path]));else if(A.code==="invalid_key")I({issues:A.issues},[...E,...A.path]);else if(A.code==="invalid_element")I({issues:A.issues},[...E,...A.path]);else{let O=[...E,...A.path];if(O.length===0){D.errors.push($(A));continue}let S=D,L=0;while(Ltypeof I==="object"?I.key:I);for(let I of D)if(typeof I==="number")$.push(`[${I}]`);else if(typeof I==="symbol")$.push(`[${JSON.stringify(String(I))}]`);else if(/[^\w$]/.test(I))$.push(`[${JSON.stringify(I)}]`);else{if($.length)$.push(".");$.push(I)}return $.join("")}function ZI(_){let $=[],D=[..._.issues].sort((I,U)=>(I.path??[]).length-(U.path??[]).length);for(let I of D)if($.push(`\u2716 ${I.message}`),I.path?.length)$.push(` \u2192 at ${lX(I.path)}`);return $.join(` -`)}var mX=(_,$)=>{_.name="$ZodError",Object.defineProperty(_,"_zod",{value:_._zod,enumerable:!1}),Object.defineProperty(_,"issues",{value:$,enumerable:!1}),_.message=JSON.stringify($,H0,2),Object.defineProperty(_,"toString",{value:()=>_.message,enumerable:!1})},gU,D$;var L2=r(()=>{X4();n();gU=K("$ZodError",mX),D$=K("$ZodError",mX,{Parent:Error})});var w0=(_)=>($,D,I,U)=>{let E=I?{...I,async:!1}:{async:!1},j=$._zod.run({value:D,issues:[]},E);if(j instanceof Promise)throw new m$;if(j.issues.length){let N=new(U?.Err??_)(j.issues.map((A)=>t_(A,E,Z_())));throw MI(N,U?.callee),N}return j.value},HI,r0=(_)=>async($,D,I,U)=>{let E=I?{...I,async:!0}:{async:!0},j=$._zod.run({value:D,issues:[]},E);if(j instanceof Promise)j=await j;if(j.issues.length){let N=new(U?.Err??_)(j.issues.map((A)=>t_(A,E,Z_())));throw MI(N,U?.callee),N}return j.value},kI,f0=(_)=>($,D,I)=>{let U=I?{...I,async:!1}:{async:!1},E=$._zod.run({value:D,issues:[]},U);if(E instanceof Promise)throw new m$;return E.issues.length?{success:!1,error:new(_??gU)(E.issues.map((j)=>t_(j,U,Z_())))}:{success:!0,data:E.value}},J2,x0=(_)=>async($,D,I)=>{let U=I?{...I,async:!0}:{async:!0},E=$._zod.run({value:D,issues:[]},U);if(E instanceof Promise)E=await E;return E.issues.length?{success:!1,error:new _(E.issues.map((j)=>t_(j,U,Z_())))}:{success:!0,data:E.value}},W2,qI=(_)=>($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return w0(_)($,D,U)},aV,CI=(_)=>($,D,I)=>{return w0(_)($,D,I)},sV,vI=(_)=>async($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return r0(_)($,D,U)},_B,wI=(_)=>async($,D,I)=>{return r0(_)($,D,I)},$B,rI=(_)=>($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return f0(_)($,D,U)},DB,fI=(_)=>($,D,I)=>{return f0(_)($,D,I)},UB,xI=(_)=>async($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return x0(_)($,D,U)},IB,uI=(_)=>async($,D,I)=>{return x0(_)($,D,I)},EB;var P2=r(()=>{X4();L2();n();HI=w0(D$),kI=r0(D$),J2=f0(D$),W2=x0(D$),aV=qI(D$),sV=CI(D$),_B=vI(D$),$B=wI(D$),DB=rI(D$),UB=fI(D$),IB=xI(D$),EB=uI(D$)});var U$={};x$(U$,{xid:()=>R2,uuid7:()=>AB,uuid6:()=>gB,uuid4:()=>NB,uuid:()=>R4,uppercase:()=>d2,unicodeEmail:()=>iX,undefined:()=>c2,ulid:()=>G2,time:()=>w2,string:()=>f2,sha512_hex:()=>HB,sha512_base64url:()=>qB,sha512_base64:()=>kB,sha384_hex:()=>MB,sha384_base64url:()=>ZB,sha384_base64:()=>bB,sha256_hex:()=>FB,sha256_base64url:()=>BB,sha256_base64:()=>VB,sha1_hex:()=>QB,sha1_base64url:()=>TB,sha1_base64:()=>KB,rfc5322Email:()=>SB,number:()=>AU,null:()=>h2,nanoid:()=>Q2,md5_hex:()=>GB,md5_base64url:()=>YB,md5_base64:()=>RB,mac:()=>b2,lowercase:()=>n2,ksuid:()=>Y2,ipv6:()=>M2,ipv4:()=>B2,integer:()=>u2,idnEmail:()=>LB,httpProtocol:()=>q2,html5Email:()=>OB,hostname:()=>PB,hex:()=>XB,guid:()=>T2,extendedDuration:()=>jB,emoji:()=>V2,email:()=>F2,e164:()=>C2,duration:()=>K2,domain:()=>zB,datetime:()=>r2,date:()=>v2,cuid2:()=>X2,cuid:()=>z2,cidrv6:()=>H2,cidrv4:()=>Z2,browserEmail:()=>JB,boolean:()=>y2,bigint:()=>x2,base64url:()=>yI,base64:()=>k2});function V2(){return new RegExp(WB,"u")}function oX(_){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 w2(_){return new RegExp(`^${oX(_)}$`)}function r2(_){let $=oX({precision:_.precision}),D=["Z"];if(_.local)D.push("");if(_.offset)D.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let I=`${$}(?:${D.join("|")})`;return new RegExp(`^${tX}T(?:${I})$`)}function OU(_,$){return new RegExp(`^[A-Za-z0-9+/]{${_}}${$}$`)}function SU(_){return new RegExp(`^[A-Za-z0-9_-]{${_}}$`)}var z2,X2,G2,R2,Y2,Q2,K2,jB,T2,R4=(_)=>{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})$`)},NB,gB,AB,F2,OB,SB,iX,LB,JB,WB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",B2,M2,b2=(_)=>{let $=z$(_??":");return new RegExp(`^(?:[0-9A-F]{2}${$}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${$}){5}[0-9a-f]{2}$`)},Z2,H2,k2,yI,PB,zB,q2,C2,tX="(?:(?:\\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])))",v2,f2=(_)=>{let $=_?`[\\s\\S]{${_?.minimum??0},${_?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${$}$`)},x2,u2,AU,y2,h2,c2,n2,d2,XB,GB,RB,YB,QB,KB,TB,FB,VB,BB,MB,bB,ZB,HB,kB,qB;var hI=r(()=>{n();z2=/^[cC][0-9a-z]{6,}$/,X2=/^[0-9a-z]+$/,G2=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,R2=/^[0-9a-vA-V]{20}$/,Y2=/^[A-Za-z0-9]{27}$/,Q2=/^[a-zA-Z0-9_-]{21}$/,K2=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jB=/^[-+]?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)?)??$/,T2=/^([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})$/,NB=R4(4),gB=R4(6),AB=R4(7),F2=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,OB=/^[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])?)*$/,SB=/^(([^<>()\[\]\\.,;:\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,}))$/,iX=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,LB=iX,JB=/^[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])?)*$/;B2=/^(?:(?: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])$/,M2=/^(([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}|:))$/,Z2=/^((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])$/,H2=/^(([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])$/,k2=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yI=/^[A-Za-z0-9_-]*$/,PB=/^(?=.{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])?)*\.?$/,zB=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,q2=/^https?$/,C2=/^\+[1-9]\d{6,14}$/,v2=new RegExp(`^${tX}$`);x2=/^-?\d+n?$/,u2=/^-?\d+$/,AU=/^-?\d+(?:\.\d+)?$/,y2=/^(?:true|false)$/i,h2=/^null$/i,c2=/^undefined$/i,n2=/^[^A-Z]*$/,d2=/^[^a-z]*$/,XB=/^[0-9a-fA-F]*$/;GB=/^[0-9a-fA-F]{32}$/,RB=OU(22,"=="),YB=SU(22),QB=/^[0-9a-fA-F]{40}$/,KB=OU(27,"="),TB=SU(27),FB=/^[0-9a-fA-F]{64}$/,VB=OU(43,"="),BB=SU(43),MB=/^[0-9a-fA-F]{96}$/,bB=OU(64,""),ZB=SU(64),HB=/^[0-9a-fA-F]{128}$/,kB=OU(86,"=="),qB=SU(86)});function pX(_,$,D){if(_.issues.length)$.issues.push(...$$(D,_.issues))}var Q_,eX,cI,nI,m2,l2,i2,t2,o2,p2,e2,a2,s2,u0,_A,$A,DA,UA,IA,EA,jA,NA,gA;var dI=r(()=>{X4();hI();n();Q_=K("$ZodCheck",(_,$)=>{var D;_._zod??(_._zod={}),_._zod.def=$,(D=_._zod).onattach??(D.onattach=[])}),eX={number:"number",bigint:"bigint",object:"date"},cI=K("$ZodCheckLessThan",(_,$)=>{Q_.init(_,$);let D=eX[typeof $.value];_._zod.onattach.push((I)=>{let U=I._zod.bag,E=($.inclusive?U.maximum:U.exclusiveMaximum)??Number.POSITIVE_INFINITY;if($.value{if($.inclusive?I.value<=$.value:I.value<$.value)return;I.issues.push({origin:D,code:"too_big",maximum:typeof $.value==="object"?$.value.getTime():$.value,input:I.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),nI=K("$ZodCheckGreaterThan",(_,$)=>{Q_.init(_,$);let D=eX[typeof $.value];_._zod.onattach.push((I)=>{let U=I._zod.bag,E=($.inclusive?U.minimum:U.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if($.value>E)if($.inclusive)U.minimum=$.value;else U.exclusiveMinimum=$.value}),_._zod.check=(I)=>{if($.inclusive?I.value>=$.value:I.value>$.value)return;I.issues.push({origin:D,code:"too_small",minimum:typeof $.value==="object"?$.value.getTime():$.value,input:I.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),m2=K("$ZodCheckMultipleOf",(_,$)=>{Q_.init(_,$),_._zod.onattach.push((D)=>{var I;(I=D._zod.bag).multipleOf??(I.multipleOf=$.value)}),_._zod.check=(D)=>{if(typeof D.value!==typeof $.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof D.value==="bigint"?D.value%$.value===BigInt(0):U2(D.value,$.value)===0)return;D.issues.push({origin:typeof D.value,code:"not_multiple_of",divisor:$.value,input:D.value,inst:_,continue:!$.abort})}}),l2=K("$ZodCheckNumberFormat",(_,$)=>{Q_.init(_,$),$.format=$.format||"float64";let D=$.format?.includes("int"),I=D?"int":"number",[U,E]=A2[$.format];_._zod.onattach.push((j)=>{let N=j._zod.bag;if(N.format=$.format,N.minimum=U,N.maximum=E,D)N.pattern=u2}),_._zod.check=(j)=>{let N=j.value;if(D){if(!Number.isInteger(N)){j.issues.push({expected:I,format:$.format,code:"invalid_type",continue:!1,input:N,inst:_});return}if(!Number.isSafeInteger(N)){if(N>0)j.issues.push({input:N,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:I,inclusive:!0,continue:!$.abort});else j.issues.push({input:N,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:I,inclusive:!0,continue:!$.abort});return}}if(NE)j.issues.push({origin:"number",input:N,code:"too_big",maximum:E,inclusive:!0,inst:_,continue:!$.abort})}}),i2=K("$ZodCheckBigIntFormat",(_,$)=>{Q_.init(_,$);let[D,I]=O2[$.format];_._zod.onattach.push((U)=>{let E=U._zod.bag;E.format=$.format,E.minimum=D,E.maximum=I}),_._zod.check=(U)=>{let E=U.value;if(EI)U.issues.push({origin:"bigint",input:E,code:"too_big",maximum:I,inclusive:!0,inst:_,continue:!$.abort})}}),t2=K("$ZodCheckMaxSize",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.size!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let U=I.value;if(U.size<=$.maximum)return;I.issues.push({origin:jU(U),code:"too_big",maximum:$.maximum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),o2=K("$ZodCheckMinSize",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.size!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>U)I._zod.bag.minimum=$.minimum}),_._zod.check=(I)=>{let U=I.value;if(U.size>=$.minimum)return;I.issues.push({origin:jU(U),code:"too_small",minimum:$.minimum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),p2=K("$ZodCheckSizeEquals",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.size!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.minimum=$.size,U.maximum=$.size,U.size=$.size}),_._zod.check=(I)=>{let U=I.value,E=U.size;if(E===$.size)return;let j=E>$.size;I.issues.push({origin:jU(U),...j?{code:"too_big",maximum:$.size}:{code:"too_small",minimum:$.size},inclusive:!0,exact:!0,input:I.value,inst:_,continue:!$.abort})}}),e2=K("$ZodCheckMaxLength",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.length!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let U=I.value;if(U.length<=$.maximum)return;let j=NU(U);I.issues.push({origin:j,code:"too_big",maximum:$.maximum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),a2=K("$ZodCheckMinLength",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.length!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>U)I._zod.bag.minimum=$.minimum}),_._zod.check=(I)=>{let U=I.value;if(U.length>=$.minimum)return;let j=NU(U);I.issues.push({origin:j,code:"too_small",minimum:$.minimum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),s2=K("$ZodCheckLengthEquals",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.length!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.minimum=$.length,U.maximum=$.length,U.length=$.length}),_._zod.check=(I)=>{let U=I.value,E=U.length;if(E===$.length)return;let j=NU(U),N=E>$.length;I.issues.push({origin:j,...N?{code:"too_big",maximum:$.length}:{code:"too_small",minimum:$.length},inclusive:!0,exact:!0,input:I.value,inst:_,continue:!$.abort})}}),u0=K("$ZodCheckStringFormat",(_,$)=>{var D,I;if(Q_.init(_,$),_._zod.onattach.push((U)=>{let E=U._zod.bag;if(E.format=$.format,$.pattern)E.patterns??(E.patterns=new Set),E.patterns.add($.pattern)}),$.pattern)(D=_._zod).check??(D.check=(U)=>{if($.pattern.lastIndex=0,$.pattern.test(U.value))return;U.issues.push({origin:"string",code:"invalid_format",format:$.format,input:U.value,...$.pattern?{pattern:$.pattern.toString()}:{},inst:_,continue:!$.abort})});else(I=_._zod).check??(I.check=()=>{})}),_A=K("$ZodCheckRegex",(_,$)=>{u0.init(_,$),_._zod.check=(D)=>{if($.pattern.lastIndex=0,$.pattern.test(D.value))return;D.issues.push({origin:"string",code:"invalid_format",format:"regex",input:D.value,pattern:$.pattern.toString(),inst:_,continue:!$.abort})}}),$A=K("$ZodCheckLowerCase",(_,$)=>{$.pattern??($.pattern=n2),u0.init(_,$)}),DA=K("$ZodCheckUpperCase",(_,$)=>{$.pattern??($.pattern=d2),u0.init(_,$)}),UA=K("$ZodCheckIncludes",(_,$)=>{Q_.init(_,$);let D=z$($.includes),I=new RegExp(typeof $.position==="number"?`^.{${$.position}}${D}`:D);$.pattern=I,_._zod.onattach.push((U)=>{let E=U._zod.bag;E.patterns??(E.patterns=new Set),E.patterns.add(I)}),_._zod.check=(U)=>{if(U.value.includes($.includes,$.position))return;U.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:$.includes,input:U.value,inst:_,continue:!$.abort})}}),IA=K("$ZodCheckStartsWith",(_,$)=>{Q_.init(_,$);let D=new RegExp(`^${z$($.prefix)}.*`);$.pattern??($.pattern=D),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.patterns??(U.patterns=new Set),U.patterns.add(D)}),_._zod.check=(I)=>{if(I.value.startsWith($.prefix))return;I.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:$.prefix,input:I.value,inst:_,continue:!$.abort})}}),EA=K("$ZodCheckEndsWith",(_,$)=>{Q_.init(_,$);let D=new RegExp(`.*${z$($.suffix)}$`);$.pattern??($.pattern=D),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.patterns??(U.patterns=new Set),U.patterns.add(D)}),_._zod.check=(I)=>{if(I.value.endsWith($.suffix))return;I.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:$.suffix,input:I.value,inst:_,continue:!$.abort})}});jA=K("$ZodCheckProperty",(_,$)=>{Q_.init(_,$),_._zod.check=(D)=>{let I=$.schema._zod.run({value:D.value[$.property],issues:[]},{});if(I instanceof Promise)return I.then((U)=>pX(U,D,$.property));pX(I,D,$.property);return}}),NA=K("$ZodCheckMimeType",(_,$)=>{Q_.init(_,$);let D=new Set($.mime);_._zod.onattach.push((I)=>{I._zod.bag.mime=$.mime}),_._zod.check=(I)=>{if(D.has(I.value.type))return;I.issues.push({code:"invalid_value",values:$.mime,input:I.value.type,inst:_,continue:!$.abort})}}),gA=K("$ZodCheckOverwrite",(_,$)=>{Q_.init(_,$),_._zod.check=(D)=>{D.value=$.tx(D.value)}})});class mI{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 D=_.split(` +var TY=Object.create;var{getPrototypeOf:FY,defineProperty:wN,getOwnPropertyNames:VY}=Object;var BY=Object.prototype.hasOwnProperty;function MY(_){return this[_]}var ZY,HY,bY=(_,$,D)=>{var I=_!=null&&typeof _==="object";if(I){var U=$?ZY??=new WeakMap:HY??=new WeakMap,E=U.get(_);if(E)return E}D=_!=null?TY(FY(_)):{};let j=$||!_||!_.__esModule?wN(D,"default",{value:_,enumerable:!0}):D;for(let N of VY(_))if(!BY.call(j,N))wN(j,N,{get:MY.bind(_,N),enumerable:!0});if(I)U.set(_,j);return j};var U4=(_,$)=>()=>($||_(($={exports:{}}).exports,$),$.exports);var qY=(_)=>_;function kY(_,$){this[_]=qY.bind(null,$)}var x$=(_,$)=>{for(var D in $)wN(_,D,{get:$[D],enumerable:!0,configurable:!0,set:kY.bind($,D)})};var r=(_,$)=>()=>(_&&($=_(_=0)),$);var L_=import.meta.require;function K(_,$,D){function I(N,O){if(!N._zod)Object.defineProperty(N,"_zod",{value:{def:O,constr:j,traits:new Set},enumerable:!1});if(N._zod.traits.has(_))return;N._zod.traits.add(_),$(N,O);let S=j.prototype,L=Object.keys(S);for(let W=0;W{if(D?.Parent&&N instanceof D.Parent)return!0;return N?._zod?.traits?.has(_)}}),Object.defineProperty(j,"name",{value:_}),j}function b_(_){if(_)Object.assign(g4,_);return g4}var hX,VI,BI,m$,X4,g4;var G4=r(()=>{VI=Object.freeze({status:"aborted"});BI=Symbol("zod_brand");m$=class m$ extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};X4=class X4 extends Error{constructor(_){super(`Encountered unidirectional transform during encode: ${_}`);this.name="ZodEncodeError"}};(hX=globalThis).__zod_globalConfig??(hX.__zod_globalConfig={});g4=globalThis.__zod_globalConfig});var q={};x$(q,{unwrapMessage:()=>DU,uint8ArrayToHex:()=>pV,uint8ArrayToBase64url:()=>tV,uint8ArrayToBase64:()=>dX,stringifyPrimitive:()=>M,slugify:()=>IA,shallowClone:()=>jA,safeExtend:()=>cV,required:()=>mV,randomString:()=>wV,propertyKeyTypes:()=>EU,promiseAllObject:()=>vV,primitiveTypes:()=>NA,prefixIssues:()=>$$,pick:()=>uV,partial:()=>dV,parsedType:()=>Z,optionalKeys:()=>AA,omit:()=>yV,objectClone:()=>qV,numKeys:()=>rV,nullish:()=>C6,normalizeParams:()=>v,mergeDefs:()=>L6,merge:()=>nV,jsonStringifyReplacer:()=>k0,joinValues:()=>V,issue:()=>v0,isPlainObject:()=>w6,isObject:()=>R4,hexToUint8Array:()=>oV,getSizableOrigin:()=>jU,getParsedType:()=>fV,getLengthableOrigin:()=>NU,getEnumValues:()=>UU,getElementAtPath:()=>CV,floatSafeRemainder:()=>UA,finalizeIssue:()=>t_,extend:()=>hV,explicitlyAborted:()=>LA,escapeRegex:()=>g$,esc:()=>MI,defineLazy:()=>D_,createTransparentProxy:()=>xV,cloneDef:()=>kV,clone:()=>h_,cleanRegex:()=>IU,cleanEnum:()=>lV,captureStackTrace:()=>ZI,cached:()=>C0,base64urlToUint8Array:()=>iV,base64ToUint8Array:()=>nX,assignProp:()=>v6,assertNotEqual:()=>MV,assertNever:()=>HV,assertIs:()=>ZV,assertEqual:()=>BV,assert:()=>bV,allowsEval:()=>EA,aborted:()=>r6,NUMBER_FORMAT_RANGES:()=>OA,Class:()=>mX,BIGINT_FORMAT_RANGES:()=>SA});function BV(_){return _}function MV(_){return _}function ZV(_){}function HV(_){throw Error("Unexpected value in exhaustive check")}function bV(_){}function UU(_){let $=Object.values(_).filter((I)=>typeof I==="number");return Object.entries(_).filter(([I,U])=>$.indexOf(+I)===-1).map(([I,U])=>U)}function V(_,$="|"){return _.map((D)=>M(D)).join($)}function k0(_,$){if(typeof $==="bigint")return $.toString();return $}function C0(_){return{get value(){{let D=_();return Object.defineProperty(this,"value",{value:D}),D}throw Error("cached value already set")}}}function C6(_){return _===null||_===void 0}function IU(_){let $=_.startsWith("^")?1:0,D=_.endsWith("$")?_.length-1:_.length;return _.slice($,D)}function UA(_,$){let D=_/$,I=Math.round(D),U=Number.EPSILON*Math.max(Math.abs(D),1);if(Math.abs(D-I)D?.[I],_)}function vV(_){let $=Object.keys(_),D=$.map((I)=>_[I]);return Promise.all(D).then((I)=>{let U={};for(let E=0;E<$.length;E++)U[$[E]]=I[E];return U})}function wV(_=10){let D="";for(let I=0;I<_;I++)D+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return D}function MI(_){return JSON.stringify(_)}function IA(_){return _.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function R4(_){return typeof _==="object"&&_!==null&&!Array.isArray(_)}function w6(_){if(R4(_)===!1)return!1;let $=_.constructor;if($===void 0)return!0;if(typeof $!=="function")return!0;let D=$.prototype;if(R4(D)===!1)return!1;if(Object.prototype.hasOwnProperty.call(D,"isPrototypeOf")===!1)return!1;return!0}function jA(_){if(w6(_))return{..._};if(Array.isArray(_))return[..._];if(_ instanceof Map)return new Map(_);if(_ instanceof Set)return new Set(_);return _}function rV(_){let $=0;for(let D in _)if(Object.prototype.hasOwnProperty.call(_,D))$++;return $}function g$(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function h_(_,$,D){let I=new _._zod.constr($??_._zod.def);if(!$||D?.parent)I._zod.parent=_;return I}function v(_){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 xV(_){let $;return new Proxy({},{get(D,I,U){return $??($=_()),Reflect.get($,I,U)},set(D,I,U,E){return $??($=_()),Reflect.set($,I,U,E)},has(D,I){return $??($=_()),Reflect.has($,I)},deleteProperty(D,I){return $??($=_()),Reflect.deleteProperty($,I)},ownKeys(D){return $??($=_()),Reflect.ownKeys($)},getOwnPropertyDescriptor(D,I){return $??($=_()),Reflect.getOwnPropertyDescriptor($,I)},defineProperty(D,I,U){return $??($=_()),Reflect.defineProperty($,I,U)}})}function M(_){if(typeof _==="bigint")return _.toString()+"n";if(typeof _==="string")return`"${_}"`;return`${_}`}function AA(_){return Object.keys(_).filter(($)=>{return _[$]._zod.optin==="optional"&&_[$]._zod.optout==="optional"})}function uV(_,$){let D=_._zod.def,I=D.checks;if(I&&I.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let E=L6(_._zod.def,{get shape(){let j={};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;j[N]=D.shape[N]}return v6(this,"shape",j),j},checks:[]});return h_(_,E)}function yV(_,$){let D=_._zod.def,I=D.checks;if(I&&I.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let E=L6(_._zod.def,{get shape(){let j={..._._zod.def.shape};for(let N in $){if(!(N in D.shape))throw Error(`Unrecognized key: "${N}"`);if(!$[N])continue;delete j[N]}return v6(this,"shape",j),j},checks:[]});return h_(_,E)}function hV(_,$){if(!w6($))throw Error("Invalid input to extend: expected a plain object");let D=_._zod.def.checks;if(D&&D.length>0){let E=_._zod.def.shape;for(let j in $)if(Object.getOwnPropertyDescriptor(E,j)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let U=L6(_._zod.def,{get shape(){let E={..._._zod.def.shape,...$};return v6(this,"shape",E),E}});return h_(_,U)}function cV(_,$){if(!w6($))throw Error("Invalid input to safeExtend: expected a plain object");let D=L6(_._zod.def,{get shape(){let I={..._._zod.def.shape,...$};return v6(this,"shape",I),I}});return h_(_,D)}function nV(_,$){if(_._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let D=L6(_._zod.def,{get shape(){let I={..._._zod.def.shape,...$._zod.def.shape};return v6(this,"shape",I),I},get catchall(){return $._zod.def.catchall},checks:$._zod.def.checks??[]});return h_(_,D)}function dV(_,$,D){let U=$._zod.def.checks;if(U&&U.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let j=L6($._zod.def,{get shape(){let N=$._zod.def.shape,O={...N};if(D)for(let S in D){if(!(S in N))throw Error(`Unrecognized key: "${S}"`);if(!D[S])continue;O[S]=_?new _({type:"optional",innerType:N[S]}):N[S]}else for(let S in N)O[S]=_?new _({type:"optional",innerType:N[S]}):N[S];return v6(this,"shape",O),O},checks:[]});return h_($,j)}function mV(_,$,D){let I=L6($._zod.def,{get shape(){let U=$._zod.def.shape,E={...U};if(D)for(let j in D){if(!(j in E))throw Error(`Unrecognized key: "${j}"`);if(!D[j])continue;E[j]=new _({type:"nonoptional",innerType:U[j]})}else for(let j in U)E[j]=new _({type:"nonoptional",innerType:U[j]});return v6(this,"shape",E),E}});return h_($,I)}function r6(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue!==!0)return!0;return!1}function LA(_,$=0){if(_.aborted===!0)return!0;for(let D=$;D<_.issues.length;D++)if(_.issues[D]?.continue===!1)return!0;return!1}function $$(_,$){return $.map((D)=>{var I;return(I=D).path??(I.path=[]),D.path.unshift(_),D})}function DU(_){return typeof _==="string"?_:_?.message}function t_(_,$,D){let I=_.message?_.message:DU(_.inst?._zod.def?.error?.(_))??DU($?.error?.(_))??DU(D.customError?.(_))??DU(D.localeError?.(_))??"Invalid input",{inst:U,continue:E,input:j,...N}=_;if(N.path??(N.path=[]),N.message=I,$?.reportInput)N.input=j;return N}function jU(_){if(_ instanceof Set)return"set";if(_ instanceof Map)return"map";if(_ instanceof File)return"file";return"unknown"}function NU(_){if(Array.isArray(_))return"array";if(typeof _==="string")return"string";return"unknown"}function Z(_){let $=typeof _;switch($){case"number":return Number.isNaN(_)?"nan":"number";case"object":{if(_===null)return"null";if(Array.isArray(_))return"array";let D=_;if(D&&Object.getPrototypeOf(D)!==Object.prototype&&"constructor"in D&&D.constructor)return D.constructor.name}}return $}function v0(..._){let[$,D,I]=_;if(typeof $==="string")return{message:$,code:"custom",input:D,inst:I};return{...$}}function lV(_){return Object.entries(_).filter(([$,D])=>{return Number.isNaN(Number.parseInt($,10))}).map(($)=>$[1])}function nX(_){let $=atob(_),D=new Uint8Array($.length);for(let I=0;I<$.length;I++)D[I]=$.charCodeAt(I);return D}function dX(_){let $="";for(let D=0;D<_.length;D++)$+=String.fromCharCode(_[D]);return btoa($)}function iV(_){let $=_.replace(/-/g,"+").replace(/_/g,"/"),D="=".repeat((4-$.length%4)%4);return nX($+D)}function tV(_){return dX(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function oV(_){let $=_.replace(/^0x/,"");if($.length%2!==0)throw Error("Invalid hex string length");let D=new Uint8Array($.length/2);for(let I=0;I<$.length;I+=2)D[I/2]=Number.parseInt($.slice(I,I+2),16);return D}function pV(_){return Array.from(_).map(($)=>$.toString(16).padStart(2,"0")).join("")}class mX{constructor(..._){}}var cX,ZI,EA,fV=(_)=>{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: ${$}`)}},EU,NA,OA,SA;var n=r(()=>{G4();cX=Symbol("evaluating");ZI="captureStackTrace"in Error?Error.captureStackTrace:(..._)=>{};EA=C0(()=>{if(g4.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});EU=new Set(["string","number","symbol"]),NA=new Set(["string","number","bigint","boolean","symbol","undefined"]);OA={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]},SA={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function w0(_,$=(D)=>D.message){let D={},I=[];for(let U of _.issues)if(U.path.length>0)D[U.path[0]]=D[U.path[0]]||[],D[U.path[0]].push($(U));else I.push($(U));return{formErrors:I,fieldErrors:D}}function r0(_,$=(D)=>D.message){let D={_errors:[]},I=(U,E=[])=>{for(let j of U.issues)if(j.code==="invalid_union"&&j.errors.length)j.errors.map((N)=>I({issues:N},[...E,...j.path]));else if(j.code==="invalid_key")I({issues:j.issues},[...E,...j.path]);else if(j.code==="invalid_element")I({issues:j.issues},[...E,...j.path]);else{let N=[...E,...j.path];if(N.length===0)D._errors.push($(j));else{let O=D,S=0;while(SD.message){let D={errors:[]},I=(U,E=[])=>{var j,N;for(let O of U.issues)if(O.code==="invalid_union"&&O.errors.length)O.errors.map((S)=>I({issues:S},[...E,...O.path]));else if(O.code==="invalid_key")I({issues:O.issues},[...E,...O.path]);else if(O.code==="invalid_element")I({issues:O.issues},[...E,...O.path]);else{let S=[...E,...O.path];if(S.length===0){D.errors.push($(O));continue}let L=D,W=0;while(Wtypeof I==="object"?I.key:I);for(let I of D)if(typeof I==="number")$.push(`[${I}]`);else if(typeof I==="symbol")$.push(`[${JSON.stringify(String(I))}]`);else if(/[^\w$]/.test(I))$.push(`[${JSON.stringify(I)}]`);else{if($.length)$.push(".");$.push(I)}return $.join("")}function bI(_){let $=[],D=[..._.issues].sort((I,U)=>(I.path??[]).length-(U.path??[]).length);for(let I of D)if($.push(`\u2716 ${I.message}`),I.path?.length)$.push(` \u2192 at ${iX(I.path)}`);return $.join(` +`)}var lX=(_,$)=>{_.name="$ZodError",Object.defineProperty(_,"_zod",{value:_._zod,enumerable:!1}),Object.defineProperty(_,"issues",{value:$,enumerable:!1}),_.message=JSON.stringify($,k0,2),Object.defineProperty(_,"toString",{value:()=>_.message,enumerable:!1})},AU,D$;var WA=r(()=>{G4();n();AU=K("$ZodError",lX),D$=K("$ZodError",lX,{Parent:Error})});var f0=(_)=>($,D,I,U)=>{let E=I?{...I,async:!1}:{async:!1},j=$._zod.run({value:D,issues:[]},E);if(j instanceof Promise)throw new m$;if(j.issues.length){let N=new(U?.Err??_)(j.issues.map((O)=>t_(O,E,b_())));throw ZI(N,U?.callee),N}return j.value},qI,x0=(_)=>async($,D,I,U)=>{let E=I?{...I,async:!0}:{async:!0},j=$._zod.run({value:D,issues:[]},E);if(j instanceof Promise)j=await j;if(j.issues.length){let N=new(U?.Err??_)(j.issues.map((O)=>t_(O,E,b_())));throw ZI(N,U?.callee),N}return j.value},kI,u0=(_)=>($,D,I)=>{let U=I?{...I,async:!1}:{async:!1},E=$._zod.run({value:D,issues:[]},U);if(E instanceof Promise)throw new m$;return E.issues.length?{success:!1,error:new(_??AU)(E.issues.map((j)=>t_(j,U,b_())))}:{success:!0,data:E.value}},JA,y0=(_)=>async($,D,I)=>{let U=I?{...I,async:!0}:{async:!0},E=$._zod.run({value:D,issues:[]},U);if(E instanceof Promise)E=await E;return E.issues.length?{success:!1,error:new _(E.issues.map((j)=>t_(j,U,b_())))}:{success:!0,data:E.value}},PA,CI=(_)=>($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return f0(_)($,D,U)},aV,vI=(_)=>($,D,I)=>{return f0(_)($,D,I)},sV,wI=(_)=>async($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return x0(_)($,D,U)},_B,rI=(_)=>async($,D,I)=>{return x0(_)($,D,I)},$B,fI=(_)=>($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return u0(_)($,D,U)},DB,xI=(_)=>($,D,I)=>{return u0(_)($,D,I)},UB,uI=(_)=>async($,D,I)=>{let U=I?{...I,direction:"backward"}:{direction:"backward"};return y0(_)($,D,U)},IB,yI=(_)=>async($,D,I)=>{return y0(_)($,D,I)},EB;var zA=r(()=>{G4();WA();n();qI=f0(D$),kI=x0(D$),JA=u0(D$),PA=y0(D$),aV=CI(D$),sV=vI(D$),_B=wI(D$),$B=rI(D$),DB=fI(D$),UB=xI(D$),IB=uI(D$),EB=yI(D$)});var U$={};x$(U$,{xid:()=>RA,uuid7:()=>OB,uuid6:()=>AB,uuid4:()=>NB,uuid:()=>Y4,uppercase:()=>dA,unicodeEmail:()=>tX,undefined:()=>cA,ulid:()=>GA,time:()=>wA,string:()=>fA,sha512_hex:()=>bB,sha512_base64url:()=>kB,sha512_base64:()=>qB,sha384_hex:()=>MB,sha384_base64url:()=>HB,sha384_base64:()=>ZB,sha256_hex:()=>FB,sha256_base64url:()=>BB,sha256_base64:()=>VB,sha1_hex:()=>QB,sha1_base64url:()=>TB,sha1_base64:()=>KB,rfc5322Email:()=>LB,number:()=>OU,null:()=>hA,nanoid:()=>QA,md5_hex:()=>GB,md5_base64url:()=>YB,md5_base64:()=>RB,mac:()=>ZA,lowercase:()=>nA,ksuid:()=>YA,ipv6:()=>MA,ipv4:()=>BA,integer:()=>uA,idnEmail:()=>WB,httpProtocol:()=>kA,html5Email:()=>SB,hostname:()=>zB,hex:()=>XB,guid:()=>TA,extendedDuration:()=>jB,emoji:()=>VA,email:()=>FA,e164:()=>CA,duration:()=>KA,domain:()=>gB,datetime:()=>rA,date:()=>vA,cuid2:()=>XA,cuid:()=>gA,cidrv6:()=>bA,cidrv4:()=>HA,browserEmail:()=>JB,boolean:()=>yA,bigint:()=>xA,base64url:()=>hI,base64:()=>qA});function VA(){return new RegExp(PB,"u")}function pX(_){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 wA(_){return new RegExp(`^${pX(_)}$`)}function rA(_){let $=pX({precision:_.precision}),D=["Z"];if(_.local)D.push("");if(_.offset)D.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let I=`${$}(?:${D.join("|")})`;return new RegExp(`^${oX}T(?:${I})$`)}function SU(_,$){return new RegExp(`^[A-Za-z0-9+/]{${_}}${$}$`)}function LU(_){return new RegExp(`^[A-Za-z0-9_-]{${_}}$`)}var gA,XA,GA,RA,YA,QA,KA,jB,TA,Y4=(_)=>{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})$`)},NB,AB,OB,FA,SB,LB,tX,WB,JB,PB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",BA,MA,ZA=(_)=>{let $=g$(_??":");return new RegExp(`^(?:[0-9A-F]{2}${$}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${$}){5}[0-9a-f]{2}$`)},HA,bA,qA,hI,zB,gB,kA,CA,oX="(?:(?:\\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])))",vA,fA=(_)=>{let $=_?`[\\s\\S]{${_?.minimum??0},${_?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${$}$`)},xA,uA,OU,yA,hA,cA,nA,dA,XB,GB,RB,YB,QB,KB,TB,FB,VB,BB,MB,ZB,HB,bB,qB,kB;var cI=r(()=>{n();gA=/^[cC][0-9a-z]{6,}$/,XA=/^[0-9a-z]+$/,GA=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,RA=/^[0-9a-vA-V]{20}$/,YA=/^[A-Za-z0-9]{27}$/,QA=/^[a-zA-Z0-9_-]{21}$/,KA=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jB=/^[-+]?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)?)??$/,TA=/^([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})$/,NB=Y4(4),AB=Y4(6),OB=Y4(7),FA=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,SB=/^[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])?)*$/,LB=/^(([^<>()\[\]\\.,;:\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,}))$/,tX=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,WB=tX,JB=/^[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])?)*$/;BA=/^(?:(?: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])$/,MA=/^(([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}|:))$/,HA=/^((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])$/,bA=/^(([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])$/,qA=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hI=/^[A-Za-z0-9_-]*$/,zB=/^(?=.{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])?)*\.?$/,gB=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,kA=/^https?$/,CA=/^\+[1-9]\d{6,14}$/,vA=new RegExp(`^${oX}$`);xA=/^-?\d+n?$/,uA=/^-?\d+$/,OU=/^-?\d+(?:\.\d+)?$/,yA=/^(?:true|false)$/i,hA=/^null$/i,cA=/^undefined$/i,nA=/^[^A-Z]*$/,dA=/^[^a-z]*$/,XB=/^[0-9a-fA-F]*$/;GB=/^[0-9a-fA-F]{32}$/,RB=SU(22,"=="),YB=LU(22),QB=/^[0-9a-fA-F]{40}$/,KB=SU(27,"="),TB=LU(27),FB=/^[0-9a-fA-F]{64}$/,VB=SU(43,"="),BB=LU(43),MB=/^[0-9a-fA-F]{96}$/,ZB=SU(64,""),HB=LU(64),bB=/^[0-9a-fA-F]{128}$/,qB=SU(86,"=="),kB=LU(86)});function eX(_,$,D){if(_.issues.length)$.issues.push(...$$(D,_.issues))}var Q_,aX,nI,dI,mA,lA,iA,tA,oA,pA,eA,aA,sA,h0,_O,$O,DO,UO,IO,EO,jO,NO,AO;var mI=r(()=>{G4();cI();n();Q_=K("$ZodCheck",(_,$)=>{var D;_._zod??(_._zod={}),_._zod.def=$,(D=_._zod).onattach??(D.onattach=[])}),aX={number:"number",bigint:"bigint",object:"date"},nI=K("$ZodCheckLessThan",(_,$)=>{Q_.init(_,$);let D=aX[typeof $.value];_._zod.onattach.push((I)=>{let U=I._zod.bag,E=($.inclusive?U.maximum:U.exclusiveMaximum)??Number.POSITIVE_INFINITY;if($.value{if($.inclusive?I.value<=$.value:I.value<$.value)return;I.issues.push({origin:D,code:"too_big",maximum:typeof $.value==="object"?$.value.getTime():$.value,input:I.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),dI=K("$ZodCheckGreaterThan",(_,$)=>{Q_.init(_,$);let D=aX[typeof $.value];_._zod.onattach.push((I)=>{let U=I._zod.bag,E=($.inclusive?U.minimum:U.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if($.value>E)if($.inclusive)U.minimum=$.value;else U.exclusiveMinimum=$.value}),_._zod.check=(I)=>{if($.inclusive?I.value>=$.value:I.value>$.value)return;I.issues.push({origin:D,code:"too_small",minimum:typeof $.value==="object"?$.value.getTime():$.value,input:I.value,inclusive:$.inclusive,inst:_,continue:!$.abort})}}),mA=K("$ZodCheckMultipleOf",(_,$)=>{Q_.init(_,$),_._zod.onattach.push((D)=>{var I;(I=D._zod.bag).multipleOf??(I.multipleOf=$.value)}),_._zod.check=(D)=>{if(typeof D.value!==typeof $.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof D.value==="bigint"?D.value%$.value===BigInt(0):UA(D.value,$.value)===0)return;D.issues.push({origin:typeof D.value,code:"not_multiple_of",divisor:$.value,input:D.value,inst:_,continue:!$.abort})}}),lA=K("$ZodCheckNumberFormat",(_,$)=>{Q_.init(_,$),$.format=$.format||"float64";let D=$.format?.includes("int"),I=D?"int":"number",[U,E]=OA[$.format];_._zod.onattach.push((j)=>{let N=j._zod.bag;if(N.format=$.format,N.minimum=U,N.maximum=E,D)N.pattern=uA}),_._zod.check=(j)=>{let N=j.value;if(D){if(!Number.isInteger(N)){j.issues.push({expected:I,format:$.format,code:"invalid_type",continue:!1,input:N,inst:_});return}if(!Number.isSafeInteger(N)){if(N>0)j.issues.push({input:N,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:I,inclusive:!0,continue:!$.abort});else j.issues.push({input:N,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:_,origin:I,inclusive:!0,continue:!$.abort});return}}if(NE)j.issues.push({origin:"number",input:N,code:"too_big",maximum:E,inclusive:!0,inst:_,continue:!$.abort})}}),iA=K("$ZodCheckBigIntFormat",(_,$)=>{Q_.init(_,$);let[D,I]=SA[$.format];_._zod.onattach.push((U)=>{let E=U._zod.bag;E.format=$.format,E.minimum=D,E.maximum=I}),_._zod.check=(U)=>{let E=U.value;if(EI)U.issues.push({origin:"bigint",input:E,code:"too_big",maximum:I,inclusive:!0,inst:_,continue:!$.abort})}}),tA=K("$ZodCheckMaxSize",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.size!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let U=I.value;if(U.size<=$.maximum)return;I.issues.push({origin:jU(U),code:"too_big",maximum:$.maximum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),oA=K("$ZodCheckMinSize",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.size!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>U)I._zod.bag.minimum=$.minimum}),_._zod.check=(I)=>{let U=I.value;if(U.size>=$.minimum)return;I.issues.push({origin:jU(U),code:"too_small",minimum:$.minimum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),pA=K("$ZodCheckSizeEquals",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.size!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.minimum=$.size,U.maximum=$.size,U.size=$.size}),_._zod.check=(I)=>{let U=I.value,E=U.size;if(E===$.size)return;let j=E>$.size;I.issues.push({origin:jU(U),...j?{code:"too_big",maximum:$.size}:{code:"too_small",minimum:$.size},inclusive:!0,exact:!0,input:I.value,inst:_,continue:!$.abort})}}),eA=K("$ZodCheckMaxLength",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.length!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.maximum??Number.POSITIVE_INFINITY;if($.maximum{let U=I.value;if(U.length<=$.maximum)return;let j=NU(U);I.issues.push({origin:j,code:"too_big",maximum:$.maximum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),aA=K("$ZodCheckMinLength",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.length!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag.minimum??Number.NEGATIVE_INFINITY;if($.minimum>U)I._zod.bag.minimum=$.minimum}),_._zod.check=(I)=>{let U=I.value;if(U.length>=$.minimum)return;let j=NU(U);I.issues.push({origin:j,code:"too_small",minimum:$.minimum,inclusive:!0,input:U,inst:_,continue:!$.abort})}}),sA=K("$ZodCheckLengthEquals",(_,$)=>{var D;Q_.init(_,$),(D=_._zod.def).when??(D.when=(I)=>{let U=I.value;return!C6(U)&&U.length!==void 0}),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.minimum=$.length,U.maximum=$.length,U.length=$.length}),_._zod.check=(I)=>{let U=I.value,E=U.length;if(E===$.length)return;let j=NU(U),N=E>$.length;I.issues.push({origin:j,...N?{code:"too_big",maximum:$.length}:{code:"too_small",minimum:$.length},inclusive:!0,exact:!0,input:I.value,inst:_,continue:!$.abort})}}),h0=K("$ZodCheckStringFormat",(_,$)=>{var D,I;if(Q_.init(_,$),_._zod.onattach.push((U)=>{let E=U._zod.bag;if(E.format=$.format,$.pattern)E.patterns??(E.patterns=new Set),E.patterns.add($.pattern)}),$.pattern)(D=_._zod).check??(D.check=(U)=>{if($.pattern.lastIndex=0,$.pattern.test(U.value))return;U.issues.push({origin:"string",code:"invalid_format",format:$.format,input:U.value,...$.pattern?{pattern:$.pattern.toString()}:{},inst:_,continue:!$.abort})});else(I=_._zod).check??(I.check=()=>{})}),_O=K("$ZodCheckRegex",(_,$)=>{h0.init(_,$),_._zod.check=(D)=>{if($.pattern.lastIndex=0,$.pattern.test(D.value))return;D.issues.push({origin:"string",code:"invalid_format",format:"regex",input:D.value,pattern:$.pattern.toString(),inst:_,continue:!$.abort})}}),$O=K("$ZodCheckLowerCase",(_,$)=>{$.pattern??($.pattern=nA),h0.init(_,$)}),DO=K("$ZodCheckUpperCase",(_,$)=>{$.pattern??($.pattern=dA),h0.init(_,$)}),UO=K("$ZodCheckIncludes",(_,$)=>{Q_.init(_,$);let D=g$($.includes),I=new RegExp(typeof $.position==="number"?`^.{${$.position}}${D}`:D);$.pattern=I,_._zod.onattach.push((U)=>{let E=U._zod.bag;E.patterns??(E.patterns=new Set),E.patterns.add(I)}),_._zod.check=(U)=>{if(U.value.includes($.includes,$.position))return;U.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:$.includes,input:U.value,inst:_,continue:!$.abort})}}),IO=K("$ZodCheckStartsWith",(_,$)=>{Q_.init(_,$);let D=new RegExp(`^${g$($.prefix)}.*`);$.pattern??($.pattern=D),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.patterns??(U.patterns=new Set),U.patterns.add(D)}),_._zod.check=(I)=>{if(I.value.startsWith($.prefix))return;I.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:$.prefix,input:I.value,inst:_,continue:!$.abort})}}),EO=K("$ZodCheckEndsWith",(_,$)=>{Q_.init(_,$);let D=new RegExp(`.*${g$($.suffix)}$`);$.pattern??($.pattern=D),_._zod.onattach.push((I)=>{let U=I._zod.bag;U.patterns??(U.patterns=new Set),U.patterns.add(D)}),_._zod.check=(I)=>{if(I.value.endsWith($.suffix))return;I.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:$.suffix,input:I.value,inst:_,continue:!$.abort})}});jO=K("$ZodCheckProperty",(_,$)=>{Q_.init(_,$),_._zod.check=(D)=>{let I=$.schema._zod.run({value:D.value[$.property],issues:[]},{});if(I instanceof Promise)return I.then((U)=>eX(U,D,$.property));eX(I,D,$.property);return}}),NO=K("$ZodCheckMimeType",(_,$)=>{Q_.init(_,$);let D=new Set($.mime);_._zod.onattach.push((I)=>{I._zod.bag.mime=$.mime}),_._zod.check=(I)=>{if(D.has(I.value.type))return;I.issues.push({code:"invalid_value",values:$.mime,input:I.value.type,inst:_,continue:!$.abort})}}),AO=K("$ZodCheckOverwrite",(_,$)=>{Q_.init(_,$),_._zod.check=(D)=>{D.value=$.tx(D.value)}})});class lI{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 D=_.split(` `).filter((E)=>E),I=Math.min(...D.map((E)=>E.length-E.trimStart().length)),U=D.map((E)=>E.slice(I)).map((E)=>" ".repeat(this.indent*2)+E);for(let E of U)this.content.push(E)}compile(){let _=Function,$=this?.args,I=[...(this?.content??[""]).map((U)=>` ${U}`)];return new _(...$,I.join(` -`))}}var AA;var OA=r(()=>{AA={major:4,minor:4,patch:3}});function qA(_){if(_==="")return!0;if(/\s/.test(_))return!1;if(_.length%4!==0)return!1;try{return atob(_),!0}catch{return!1}}function J5(_){if(!yI.test(_))return!1;let $=_.replace(/[-_]/g,(I)=>I==="-"?"+":"/"),D=$.padEnd(Math.ceil($.length/4)*4,"=");return qA(D)}function W5(_,$=null){try{let D=_.split(".");if(D.length!==3)return!1;let[I]=D;if(!I)return!1;let U=JSON.parse(atob(I));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if($&&(!("alg"in U)||U.alg!==$))return!1;return!0}catch{return!1}}function sX(_,$,D){if(_.issues.length)$.issues.push(...$$(D,_.issues));$.value[D]=_.value}function oI(_,$,D,I,U,E){let j=D in I;if(_.issues.length){if(U&&E&&!j)return;$.issues.push(...$$(D,_.issues))}if(!j&&!U){if(!_.issues.length)$.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[D]});return}if(_.value===void 0){if(j)$.value[D]=void 0}else $.value[D]=_.value}function P5(_){let $=Object.keys(_.shape);for(let I of $)if(!_.shape?.[I]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${I}": expected a Zod schema`);let D=g2(_.shape);return{..._,keys:$,keySet:new Set($),numKeys:$.length,optionalKeys:new Set(D)}}function z5(_,$,D,I,U,E){let j=[],N=U.keySet,A=U.catchall._zod,O=A.def.type,S=A.optin==="optional",L=A.optout==="optional";for(let P in $){if(P==="__proto__")continue;if(N.has(P))continue;if(O==="never"){j.push(P);continue}let z=A.run({value:$[P],issues:[]},I);if(z instanceof Promise)_.push(z.then((G)=>oI(G,D,P,$,S,L)));else oI(z,D,P,$,S,L)}if(j.length)D.issues.push({code:"unrecognized_keys",keys:j,input:$,inst:E});if(!_.length)return D;return Promise.all(_).then(()=>{return D})}function _5(_,$,D,I){for(let E of _)if(E.issues.length===0)return $.value=E.value,$;let U=_.filter((E)=>!r6(E));if(U.length===1)return $.value=U[0].value,U[0];return $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((E)=>E.issues.map((j)=>t_(j,I,Z_())))}),$}function $5(_,$,D,I){let U=_.filter((E)=>E.issues.length===0);if(U.length===1)return $.value=U[0].value,$;if(U.length===0)$.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((E)=>E.issues.map((j)=>t_(j,I,Z_())))});else $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:[],inclusive:!1});return $}function SA(_,$){if(_===$)return{valid:!0,data:_};if(_ instanceof Date&&$ instanceof Date&&+_===+$)return{valid:!0,data:_};if(w6(_)&&w6($)){let D=Object.keys($),I=Object.keys(_).filter((E)=>D.indexOf(E)!==-1),U={..._,...$};for(let E of I){let j=SA(_[E],$[E]);if(!j.valid)return{valid:!1,mergeErrorPath:[E,...j.mergeErrorPath]};U[E]=j.data}return{valid:!0,data:U}}if(Array.isArray(_)&&Array.isArray($)){if(_.length!==$.length)return{valid:!1,mergeErrorPath:[]};let D=[];for(let I=0;I<_.length;I++){let U=_[I],E=$[I],j=SA(U,E);if(!j.valid)return{valid:!1,mergeErrorPath:[I,...j.mergeErrorPath]};D.push(j.data)}return{valid:!0,data:D}}return{valid:!1,mergeErrorPath:[]}}function D5(_,$,D){let I=new Map,U;for(let N of $.issues)if(N.code==="unrecognized_keys"){U??(U=N);for(let A of N.keys){if(!I.has(A))I.set(A,{});I.get(A).l=!0}}else _.issues.push(N);for(let N of D.issues)if(N.code==="unrecognized_keys")for(let A of N.keys){if(!I.has(A))I.set(A,{});I.get(A).r=!0}else _.issues.push(N);let E=[...I].filter(([,N])=>N.l&&N.r).map(([N])=>N);if(E.length&&U)_.issues.push({...U,keys:E});if(r6(_))return _;let j=SA($.value,D.value);if(!j.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(j.mergeErrorPath)}`);return _.value=j.data,_}function U5(_,$){for(let D=_.length-1;D>=0;D--)if(_[D]._zod[$]!=="optional")return D+1;return 0}function I5(_,$,D){if(_.issues.length)$.issues.push(...$$(D,_.issues));$.value[D]=_.value}function E5(_,$,D,I,U){for(let E=0;E=U){$.value.length=E;break}$.issues.push(...$$(E,j.issues))}$.value[E]=j.value}for(let E=$.value.length-1;E>=I.length;E--)if(D[E]._zod.optout==="optional"&&$.value[E]===void 0)$.value.length=E;else break;return $}function j5(_,$,D,I,U,E,j){if(_.issues.length)if(EU.has(typeof I))D.issues.push(...$$(I,_.issues));else D.issues.push({code:"invalid_key",origin:"map",input:U,inst:E,issues:_.issues.map((N)=>t_(N,j,Z_()))});if($.issues.length)if(EU.has(typeof I))D.issues.push(...$$(I,$.issues));else D.issues.push({origin:"map",code:"invalid_element",input:U,inst:E,key:I,issues:$.issues.map((N)=>t_(N,j,Z_()))});D.value.set(_.value,$.value)}function N5(_,$){if(_.issues.length)$.issues.push(..._.issues);$.value.add(_.value)}function g5(_,$){if($===void 0&&(_.issues.length||_.fallback))return{issues:[],value:void 0};return _}function A5(_,$){if(_.value===void 0)_.value=$.defaultValue;return _}function O5(_,$){if(!_.issues.length&&_.value===void 0)_.issues.push({code:"invalid_type",expected:"nonoptional",input:_.value,inst:$});return _}function lI(_,$,D){if(_.issues.length)return _.aborted=!0,_;return $._zod.run({value:_.value,issues:_.issues,fallback:_.fallback},D)}function iI(_,$,D){if(_.issues.length)return _.aborted=!0,_;if((D.direction||"forward")==="forward"){let U=$.transform(_.value,_);if(U instanceof Promise)return U.then((E)=>tI(_,E,$.out,D));return tI(_,U,$.out,D)}else{let U=$.reverseTransform(_.value,_);if(U instanceof Promise)return U.then((E)=>tI(_,E,$.in,D));return tI(_,U,$.in,D)}}function tI(_,$,D,I){if(_.issues.length)return _.aborted=!0,_;return D._zod.run({value:$,issues:_.issues},I)}function S5(_){return _.value=Object.freeze(_.value),_}function L5(_,$,D,I){if(!_){let U={code:"custom",input:D,inst:I,path:[...I._zod.def.path??[]],continue:!I._zod.def.abort};if(I._zod.def.params)U.params=I._zod.def.params;$.issues.push(q0(U))}}var o,Y4,Y_,LA,JA,WA,PA,zA,XA,GA,RA,YA,QA,KA,TA,FA,VA,BA,MA,bA,ZA,HA,kA,CA,vA,wA,rA,fA,pI,xA,LU,eI,uA,yA,hA,cA,nA,dA,mA,lA,iA,tA,X5,oA,JU,pA,eA,aA,aI,sA,_O,$O,DO,UO,IO,EO,sI,jO,NO,gO,AO,OO,SO,LO,JO,_E,WU,WO,PO,zO,XO,GO,RO,YO;var QO=r(()=>{dI();X4();P2();hI();n();OA();n();o=K("$ZodType",(_,$)=>{var D;_??(_={}),_._zod.def=$,_._zod.bag=_._zod.bag||{},_._zod.version=AA;let I=[..._._zod.def.checks??[]];if(_._zod.traits.has("$ZodCheck"))I.unshift(_);for(let U of I)for(let E of U._zod.onattach)E(_);if(I.length===0)(D=_._zod).deferred??(D.deferred=[]),_._zod.deferred?.push(()=>{_._zod.run=_._zod.parse});else{let U=(j,N,A)=>{let O=r6(j),S;for(let L of N){if(L._zod.def.when){if(S2(j))continue;if(!L._zod.def.when(j))continue}else if(O)continue;let P=j.issues.length,z=L._zod.check(j);if(z instanceof Promise&&A?.async===!1)throw new m$;if(S||z instanceof Promise)S=(S??Promise.resolve()).then(async()=>{if(await z,j.issues.length===P)return;if(!O)O=r6(j,P)});else{if(j.issues.length===P)continue;if(!O)O=r6(j,P)}}if(S)return S.then(()=>{return j});return j},E=(j,N,A)=>{if(r6(j))return j.aborted=!0,j;let O=U(N,I,A);if(O instanceof Promise){if(A.async===!1)throw new m$;return O.then((S)=>_._zod.parse(S,A))}return _._zod.parse(O,A)};_._zod.run=(j,N)=>{if(N.skipChecks)return _._zod.parse(j,N);if(N.direction==="backward"){let O=_._zod.parse({value:j.value,issues:[]},{...N,skipChecks:!0});if(O instanceof Promise)return O.then((S)=>{return E(S,j,N)});return E(O,j,N)}let A=_._zod.parse(j,N);if(A instanceof Promise){if(N.async===!1)throw new m$;return A.then((O)=>U(O,I,N))}return U(A,I,N)}}D_(_,"~standard",()=>({validate:(U)=>{try{let E=J2(_,U);return E.success?{value:E.data}:{issues:E.error?.issues}}catch(E){return W2(_,U).then((j)=>j.success?{value:j.data}:{issues:j.error?.issues})}},vendor:"zod",version:1}))}),Y4=K("$ZodString",(_,$)=>{o.init(_,$),_._zod.pattern=[..._?._zod.bag?.patterns??[]].pop()??f2(_._zod.bag),_._zod.parse=(D,I)=>{if($.coerce)try{D.value=String(D.value)}catch(U){}if(typeof D.value==="string")return D;return D.issues.push({expected:"string",code:"invalid_type",input:D.value,inst:_}),D}}),Y_=K("$ZodStringFormat",(_,$)=>{u0.init(_,$),Y4.init(_,$)}),LA=K("$ZodGUID",(_,$)=>{$.pattern??($.pattern=T2),Y_.init(_,$)}),JA=K("$ZodUUID",(_,$)=>{if($.version){let I={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[$.version];if(I===void 0)throw Error(`Invalid UUID version: "${$.version}"`);$.pattern??($.pattern=R4(I))}else $.pattern??($.pattern=R4());Y_.init(_,$)}),WA=K("$ZodEmail",(_,$)=>{$.pattern??($.pattern=F2),Y_.init(_,$)}),PA=K("$ZodURL",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{try{let I=D.value.trim();if(!$.normalize&&$.protocol?.source===q2.source){if(!/^https?:\/\//i.test(I)){D.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:D.value,inst:_,continue:!$.abort});return}}let U=new URL(I);if($.hostname){if($.hostname.lastIndex=0,!$.hostname.test(U.hostname))D.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$.hostname.source,input:D.value,inst:_,continue:!$.abort})}if($.protocol){if($.protocol.lastIndex=0,!$.protocol.test(U.protocol.endsWith(":")?U.protocol.slice(0,-1):U.protocol))D.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:$.protocol.source,input:D.value,inst:_,continue:!$.abort})}if($.normalize)D.value=U.href;else D.value=I;return}catch(I){D.issues.push({code:"invalid_format",format:"url",input:D.value,inst:_,continue:!$.abort})}}}),zA=K("$ZodEmoji",(_,$)=>{$.pattern??($.pattern=V2()),Y_.init(_,$)}),XA=K("$ZodNanoID",(_,$)=>{$.pattern??($.pattern=Q2),Y_.init(_,$)}),GA=K("$ZodCUID",(_,$)=>{$.pattern??($.pattern=z2),Y_.init(_,$)}),RA=K("$ZodCUID2",(_,$)=>{$.pattern??($.pattern=X2),Y_.init(_,$)}),YA=K("$ZodULID",(_,$)=>{$.pattern??($.pattern=G2),Y_.init(_,$)}),QA=K("$ZodXID",(_,$)=>{$.pattern??($.pattern=R2),Y_.init(_,$)}),KA=K("$ZodKSUID",(_,$)=>{$.pattern??($.pattern=Y2),Y_.init(_,$)}),TA=K("$ZodISODateTime",(_,$)=>{$.pattern??($.pattern=r2($)),Y_.init(_,$)}),FA=K("$ZodISODate",(_,$)=>{$.pattern??($.pattern=v2),Y_.init(_,$)}),VA=K("$ZodISOTime",(_,$)=>{$.pattern??($.pattern=w2($)),Y_.init(_,$)}),BA=K("$ZodISODuration",(_,$)=>{$.pattern??($.pattern=K2),Y_.init(_,$)}),MA=K("$ZodIPv4",(_,$)=>{$.pattern??($.pattern=B2),Y_.init(_,$),_._zod.bag.format="ipv4"}),bA=K("$ZodIPv6",(_,$)=>{$.pattern??($.pattern=M2),Y_.init(_,$),_._zod.bag.format="ipv6",_._zod.check=(D)=>{try{new URL(`http://[${D.value}]`)}catch{D.issues.push({code:"invalid_format",format:"ipv6",input:D.value,inst:_,continue:!$.abort})}}}),ZA=K("$ZodMAC",(_,$)=>{$.pattern??($.pattern=b2($.delimiter)),Y_.init(_,$),_._zod.bag.format="mac"}),HA=K("$ZodCIDRv4",(_,$)=>{$.pattern??($.pattern=Z2),Y_.init(_,$)}),kA=K("$ZodCIDRv6",(_,$)=>{$.pattern??($.pattern=H2),Y_.init(_,$),_._zod.check=(D)=>{let I=D.value.split("/");try{if(I.length!==2)throw Error();let[U,E]=I;if(!E)throw Error();let j=Number(E);if(`${j}`!==E)throw Error();if(j<0||j>128)throw Error();new URL(`http://[${U}]`)}catch{D.issues.push({code:"invalid_format",format:"cidrv6",input:D.value,inst:_,continue:!$.abort})}}});CA=K("$ZodBase64",(_,$)=>{$.pattern??($.pattern=k2),Y_.init(_,$),_._zod.bag.contentEncoding="base64",_._zod.check=(D)=>{if(qA(D.value))return;D.issues.push({code:"invalid_format",format:"base64",input:D.value,inst:_,continue:!$.abort})}});vA=K("$ZodBase64URL",(_,$)=>{$.pattern??($.pattern=yI),Y_.init(_,$),_._zod.bag.contentEncoding="base64url",_._zod.check=(D)=>{if(J5(D.value))return;D.issues.push({code:"invalid_format",format:"base64url",input:D.value,inst:_,continue:!$.abort})}}),wA=K("$ZodE164",(_,$)=>{$.pattern??($.pattern=C2),Y_.init(_,$)});rA=K("$ZodJWT",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{if(W5(D.value,$.alg))return;D.issues.push({code:"invalid_format",format:"jwt",input:D.value,inst:_,continue:!$.abort})}}),fA=K("$ZodCustomStringFormat",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{if($.fn(D.value))return;D.issues.push({code:"invalid_format",format:$.format,input:D.value,inst:_,continue:!$.abort})}}),pI=K("$ZodNumber",(_,$)=>{o.init(_,$),_._zod.pattern=_._zod.bag.pattern??AU,_._zod.parse=(D,I)=>{if($.coerce)try{D.value=Number(D.value)}catch(j){}let U=D.value;if(typeof U==="number"&&!Number.isNaN(U)&&Number.isFinite(U))return D;let E=typeof U==="number"?Number.isNaN(U)?"NaN":!Number.isFinite(U)?"Infinity":void 0:void 0;return D.issues.push({expected:"number",code:"invalid_type",input:U,inst:_,...E?{received:E}:{}}),D}}),xA=K("$ZodNumberFormat",(_,$)=>{l2.init(_,$),pI.init(_,$)}),LU=K("$ZodBoolean",(_,$)=>{o.init(_,$),_._zod.pattern=y2,_._zod.parse=(D,I)=>{if($.coerce)try{D.value=Boolean(D.value)}catch(E){}let U=D.value;if(typeof U==="boolean")return D;return D.issues.push({expected:"boolean",code:"invalid_type",input:U,inst:_}),D}}),eI=K("$ZodBigInt",(_,$)=>{o.init(_,$),_._zod.pattern=x2,_._zod.parse=(D,I)=>{if($.coerce)try{D.value=BigInt(D.value)}catch(U){}if(typeof D.value==="bigint")return D;return D.issues.push({expected:"bigint",code:"invalid_type",input:D.value,inst:_}),D}}),uA=K("$ZodBigIntFormat",(_,$)=>{i2.init(_,$),eI.init(_,$)}),yA=K("$ZodSymbol",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(typeof U==="symbol")return D;return D.issues.push({expected:"symbol",code:"invalid_type",input:U,inst:_}),D}}),hA=K("$ZodUndefined",(_,$)=>{o.init(_,$),_._zod.pattern=c2,_._zod.values=new Set([void 0]),_._zod.parse=(D,I)=>{let U=D.value;if(typeof U>"u")return D;return D.issues.push({expected:"undefined",code:"invalid_type",input:U,inst:_}),D}}),cA=K("$ZodNull",(_,$)=>{o.init(_,$),_._zod.pattern=h2,_._zod.values=new Set([null]),_._zod.parse=(D,I)=>{let U=D.value;if(U===null)return D;return D.issues.push({expected:"null",code:"invalid_type",input:U,inst:_}),D}}),nA=K("$ZodAny",(_,$)=>{o.init(_,$),_._zod.parse=(D)=>D}),dA=K("$ZodUnknown",(_,$)=>{o.init(_,$),_._zod.parse=(D)=>D}),mA=K("$ZodNever",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{return D.issues.push({expected:"never",code:"invalid_type",input:D.value,inst:_}),D}}),lA=K("$ZodVoid",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(typeof U>"u")return D;return D.issues.push({expected:"void",code:"invalid_type",input:U,inst:_}),D}}),iA=K("$ZodDate",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{if($.coerce)try{D.value=new Date(D.value)}catch(N){}let U=D.value,E=U instanceof Date;if(E&&!Number.isNaN(U.getTime()))return D;return D.issues.push({expected:"date",code:"invalid_type",input:U,...E?{received:"Invalid Date"}:{},inst:_}),D}});tA=K("$ZodArray",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!Array.isArray(U))return D.issues.push({expected:"array",code:"invalid_type",input:U,inst:_}),D;D.value=Array(U.length);let E=[];for(let j=0;jsX(O,D,j)));else sX(A,D,j)}if(E.length)return Promise.all(E).then(()=>D);return D}});X5=K("$ZodObject",(_,$)=>{if(o.init(_,$),!Object.getOwnPropertyDescriptor($,"shape")?.get){let N=$.shape;Object.defineProperty($,"shape",{get:()=>{let A={...N};return Object.defineProperty($,"shape",{value:A}),A}})}let I=k0(()=>P5($));D_(_._zod,"propValues",()=>{let N=$.shape,A={};for(let O in N){let S=N[O]._zod;if(S.values){A[O]??(A[O]=new Set);for(let L of S.values)A[O].add(L)}}return A});let U=G4,E=$.catchall,j;_._zod.parse=(N,A)=>{j??(j=I.value);let O=N.value;if(!U(O))return N.issues.push({expected:"object",code:"invalid_type",input:O,inst:_}),N;N.value={};let S=[],L=j.shape;for(let P of j.keys){let z=L[P],G=z._zod.optin==="optional",J=z._zod.optout==="optional",W=z._zod.run({value:O[P],issues:[]},A);if(W instanceof Promise)S.push(W.then((X)=>oI(X,N,P,O,G,J)));else oI(W,N,P,O,G,J)}if(!E)return S.length?Promise.all(S).then(()=>N):N;return z5(S,O,N,A,I.value,_)}}),oA=K("$ZodObjectJIT",(_,$)=>{X5.init(_,$);let D=_._zod.parse,I=k0(()=>P5($)),U=(P)=>{let z=new mI(["shape","payload","ctx"]),G=I.value,J=(T)=>{let Y=BI(T);return`shape[${Y}]._zod.run({ value: input[${Y}], issues: [] }, ctx)`};z.write("const input = payload.value;");let W=Object.create(null),X=0;for(let T of G.keys)W[T]=`key_${X++}`;z.write("const newResult = {};");for(let T of G.keys){let Y=W[T],Q=BI(T),F=P[T],q=F?._zod?.optin==="optional",Z=F?._zod?.optout==="optional";if(z.write(`const ${Y} = ${J(T)};`),q&&Z)z.write(` +`))}}var OO;var SO=r(()=>{OO={major:4,minor:4,patch:3}});function kO(_){if(_==="")return!0;if(/\s/.test(_))return!1;if(_.length%4!==0)return!1;try{return atob(_),!0}catch{return!1}}function P5(_){if(!hI.test(_))return!1;let $=_.replace(/[-_]/g,(I)=>I==="-"?"+":"/"),D=$.padEnd(Math.ceil($.length/4)*4,"=");return kO(D)}function z5(_,$=null){try{let D=_.split(".");if(D.length!==3)return!1;let[I]=D;if(!I)return!1;let U=JSON.parse(atob(I));if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if($&&(!("alg"in U)||U.alg!==$))return!1;return!0}catch{return!1}}function _5(_,$,D){if(_.issues.length)$.issues.push(...$$(D,_.issues));$.value[D]=_.value}function pI(_,$,D,I,U,E){let j=D in I;if(_.issues.length){if(U&&E&&!j)return;$.issues.push(...$$(D,_.issues))}if(!j&&!U){if(!_.issues.length)$.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[D]});return}if(_.value===void 0){if(j)$.value[D]=void 0}else $.value[D]=_.value}function g5(_){let $=Object.keys(_.shape);for(let I of $)if(!_.shape?.[I]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${I}": expected a Zod schema`);let D=AA(_.shape);return{..._,keys:$,keySet:new Set($),numKeys:$.length,optionalKeys:new Set(D)}}function X5(_,$,D,I,U,E){let j=[],N=U.keySet,O=U.catchall._zod,S=O.def.type,L=O.optin==="optional",W=O.optout==="optional";for(let g in $){if(g==="__proto__")continue;if(N.has(g))continue;if(S==="never"){j.push(g);continue}let z=O.run({value:$[g],issues:[]},I);if(z instanceof Promise)_.push(z.then((G)=>pI(G,D,g,$,L,W)));else pI(z,D,g,$,L,W)}if(j.length)D.issues.push({code:"unrecognized_keys",keys:j,input:$,inst:E});if(!_.length)return D;return Promise.all(_).then(()=>{return D})}function $5(_,$,D,I){for(let E of _)if(E.issues.length===0)return $.value=E.value,$;let U=_.filter((E)=>!r6(E));if(U.length===1)return $.value=U[0].value,U[0];return $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((E)=>E.issues.map((j)=>t_(j,I,b_())))}),$}function D5(_,$,D,I){let U=_.filter((E)=>E.issues.length===0);if(U.length===1)return $.value=U[0].value,$;if(U.length===0)$.issues.push({code:"invalid_union",input:$.value,inst:D,errors:_.map((E)=>E.issues.map((j)=>t_(j,I,b_())))});else $.issues.push({code:"invalid_union",input:$.value,inst:D,errors:[],inclusive:!1});return $}function LO(_,$){if(_===$)return{valid:!0,data:_};if(_ instanceof Date&&$ instanceof Date&&+_===+$)return{valid:!0,data:_};if(w6(_)&&w6($)){let D=Object.keys($),I=Object.keys(_).filter((E)=>D.indexOf(E)!==-1),U={..._,...$};for(let E of I){let j=LO(_[E],$[E]);if(!j.valid)return{valid:!1,mergeErrorPath:[E,...j.mergeErrorPath]};U[E]=j.data}return{valid:!0,data:U}}if(Array.isArray(_)&&Array.isArray($)){if(_.length!==$.length)return{valid:!1,mergeErrorPath:[]};let D=[];for(let I=0;I<_.length;I++){let U=_[I],E=$[I],j=LO(U,E);if(!j.valid)return{valid:!1,mergeErrorPath:[I,...j.mergeErrorPath]};D.push(j.data)}return{valid:!0,data:D}}return{valid:!1,mergeErrorPath:[]}}function U5(_,$,D){let I=new Map,U;for(let N of $.issues)if(N.code==="unrecognized_keys"){U??(U=N);for(let O of N.keys){if(!I.has(O))I.set(O,{});I.get(O).l=!0}}else _.issues.push(N);for(let N of D.issues)if(N.code==="unrecognized_keys")for(let O of N.keys){if(!I.has(O))I.set(O,{});I.get(O).r=!0}else _.issues.push(N);let E=[...I].filter(([,N])=>N.l&&N.r).map(([N])=>N);if(E.length&&U)_.issues.push({...U,keys:E});if(r6(_))return _;let j=LO($.value,D.value);if(!j.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(j.mergeErrorPath)}`);return _.value=j.data,_}function I5(_,$){for(let D=_.length-1;D>=0;D--)if(_[D]._zod[$]!=="optional")return D+1;return 0}function E5(_,$,D){if(_.issues.length)$.issues.push(...$$(D,_.issues));$.value[D]=_.value}function j5(_,$,D,I,U){for(let E=0;E=U){$.value.length=E;break}$.issues.push(...$$(E,j.issues))}$.value[E]=j.value}for(let E=$.value.length-1;E>=I.length;E--)if(D[E]._zod.optout==="optional"&&$.value[E]===void 0)$.value.length=E;else break;return $}function N5(_,$,D,I,U,E,j){if(_.issues.length)if(EU.has(typeof I))D.issues.push(...$$(I,_.issues));else D.issues.push({code:"invalid_key",origin:"map",input:U,inst:E,issues:_.issues.map((N)=>t_(N,j,b_()))});if($.issues.length)if(EU.has(typeof I))D.issues.push(...$$(I,$.issues));else D.issues.push({origin:"map",code:"invalid_element",input:U,inst:E,key:I,issues:$.issues.map((N)=>t_(N,j,b_()))});D.value.set(_.value,$.value)}function A5(_,$){if(_.issues.length)$.issues.push(..._.issues);$.value.add(_.value)}function O5(_,$){if($===void 0&&(_.issues.length||_.fallback))return{issues:[],value:void 0};return _}function S5(_,$){if(_.value===void 0)_.value=$.defaultValue;return _}function L5(_,$){if(!_.issues.length&&_.value===void 0)_.issues.push({code:"invalid_type",expected:"nonoptional",input:_.value,inst:$});return _}function iI(_,$,D){if(_.issues.length)return _.aborted=!0,_;return $._zod.run({value:_.value,issues:_.issues,fallback:_.fallback},D)}function tI(_,$,D){if(_.issues.length)return _.aborted=!0,_;if((D.direction||"forward")==="forward"){let U=$.transform(_.value,_);if(U instanceof Promise)return U.then((E)=>oI(_,E,$.out,D));return oI(_,U,$.out,D)}else{let U=$.reverseTransform(_.value,_);if(U instanceof Promise)return U.then((E)=>oI(_,E,$.in,D));return oI(_,U,$.in,D)}}function oI(_,$,D,I){if(_.issues.length)return _.aborted=!0,_;return D._zod.run({value:$,issues:_.issues},I)}function W5(_){return _.value=Object.freeze(_.value),_}function J5(_,$,D,I){if(!_){let U={code:"custom",input:D,inst:I,path:[...I._zod.def.path??[]],continue:!I._zod.def.abort};if(I._zod.def.params)U.params=I._zod.def.params;$.issues.push(v0(U))}}var p,Q4,Y_,WO,JO,PO,zO,gO,XO,GO,RO,YO,QO,KO,TO,FO,VO,BO,MO,ZO,HO,bO,qO,CO,vO,wO,rO,fO,eI,xO,WU,aI,uO,yO,hO,cO,nO,dO,mO,lO,iO,tO,G5,oO,JU,pO,eO,aO,sI,sO,_S,$S,DS,US,IS,ES,_E,jS,NS,AS,OS,SS,LS,WS,JS,$E,PU,PS,zS,gS,XS,GS,RS,YS;var QS=r(()=>{mI();G4();zA();cI();n();SO();n();p=K("$ZodType",(_,$)=>{var D;_??(_={}),_._zod.def=$,_._zod.bag=_._zod.bag||{},_._zod.version=OO;let I=[..._._zod.def.checks??[]];if(_._zod.traits.has("$ZodCheck"))I.unshift(_);for(let U of I)for(let E of U._zod.onattach)E(_);if(I.length===0)(D=_._zod).deferred??(D.deferred=[]),_._zod.deferred?.push(()=>{_._zod.run=_._zod.parse});else{let U=(j,N,O)=>{let S=r6(j),L;for(let W of N){if(W._zod.def.when){if(LA(j))continue;if(!W._zod.def.when(j))continue}else if(S)continue;let g=j.issues.length,z=W._zod.check(j);if(z instanceof Promise&&O?.async===!1)throw new m$;if(L||z instanceof Promise)L=(L??Promise.resolve()).then(async()=>{if(await z,j.issues.length===g)return;if(!S)S=r6(j,g)});else{if(j.issues.length===g)continue;if(!S)S=r6(j,g)}}if(L)return L.then(()=>{return j});return j},E=(j,N,O)=>{if(r6(j))return j.aborted=!0,j;let S=U(N,I,O);if(S instanceof Promise){if(O.async===!1)throw new m$;return S.then((L)=>_._zod.parse(L,O))}return _._zod.parse(S,O)};_._zod.run=(j,N)=>{if(N.skipChecks)return _._zod.parse(j,N);if(N.direction==="backward"){let S=_._zod.parse({value:j.value,issues:[]},{...N,skipChecks:!0});if(S instanceof Promise)return S.then((L)=>{return E(L,j,N)});return E(S,j,N)}let O=_._zod.parse(j,N);if(O instanceof Promise){if(N.async===!1)throw new m$;return O.then((S)=>U(S,I,N))}return U(O,I,N)}}D_(_,"~standard",()=>({validate:(U)=>{try{let E=JA(_,U);return E.success?{value:E.data}:{issues:E.error?.issues}}catch(E){return PA(_,U).then((j)=>j.success?{value:j.data}:{issues:j.error?.issues})}},vendor:"zod",version:1}))}),Q4=K("$ZodString",(_,$)=>{p.init(_,$),_._zod.pattern=[..._?._zod.bag?.patterns??[]].pop()??fA(_._zod.bag),_._zod.parse=(D,I)=>{if($.coerce)try{D.value=String(D.value)}catch(U){}if(typeof D.value==="string")return D;return D.issues.push({expected:"string",code:"invalid_type",input:D.value,inst:_}),D}}),Y_=K("$ZodStringFormat",(_,$)=>{h0.init(_,$),Q4.init(_,$)}),WO=K("$ZodGUID",(_,$)=>{$.pattern??($.pattern=TA),Y_.init(_,$)}),JO=K("$ZodUUID",(_,$)=>{if($.version){let I={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[$.version];if(I===void 0)throw Error(`Invalid UUID version: "${$.version}"`);$.pattern??($.pattern=Y4(I))}else $.pattern??($.pattern=Y4());Y_.init(_,$)}),PO=K("$ZodEmail",(_,$)=>{$.pattern??($.pattern=FA),Y_.init(_,$)}),zO=K("$ZodURL",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{try{let I=D.value.trim();if(!$.normalize&&$.protocol?.source===kA.source){if(!/^https?:\/\//i.test(I)){D.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:D.value,inst:_,continue:!$.abort});return}}let U=new URL(I);if($.hostname){if($.hostname.lastIndex=0,!$.hostname.test(U.hostname))D.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:$.hostname.source,input:D.value,inst:_,continue:!$.abort})}if($.protocol){if($.protocol.lastIndex=0,!$.protocol.test(U.protocol.endsWith(":")?U.protocol.slice(0,-1):U.protocol))D.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:$.protocol.source,input:D.value,inst:_,continue:!$.abort})}if($.normalize)D.value=U.href;else D.value=I;return}catch(I){D.issues.push({code:"invalid_format",format:"url",input:D.value,inst:_,continue:!$.abort})}}}),gO=K("$ZodEmoji",(_,$)=>{$.pattern??($.pattern=VA()),Y_.init(_,$)}),XO=K("$ZodNanoID",(_,$)=>{$.pattern??($.pattern=QA),Y_.init(_,$)}),GO=K("$ZodCUID",(_,$)=>{$.pattern??($.pattern=gA),Y_.init(_,$)}),RO=K("$ZodCUID2",(_,$)=>{$.pattern??($.pattern=XA),Y_.init(_,$)}),YO=K("$ZodULID",(_,$)=>{$.pattern??($.pattern=GA),Y_.init(_,$)}),QO=K("$ZodXID",(_,$)=>{$.pattern??($.pattern=RA),Y_.init(_,$)}),KO=K("$ZodKSUID",(_,$)=>{$.pattern??($.pattern=YA),Y_.init(_,$)}),TO=K("$ZodISODateTime",(_,$)=>{$.pattern??($.pattern=rA($)),Y_.init(_,$)}),FO=K("$ZodISODate",(_,$)=>{$.pattern??($.pattern=vA),Y_.init(_,$)}),VO=K("$ZodISOTime",(_,$)=>{$.pattern??($.pattern=wA($)),Y_.init(_,$)}),BO=K("$ZodISODuration",(_,$)=>{$.pattern??($.pattern=KA),Y_.init(_,$)}),MO=K("$ZodIPv4",(_,$)=>{$.pattern??($.pattern=BA),Y_.init(_,$),_._zod.bag.format="ipv4"}),ZO=K("$ZodIPv6",(_,$)=>{$.pattern??($.pattern=MA),Y_.init(_,$),_._zod.bag.format="ipv6",_._zod.check=(D)=>{try{new URL(`http://[${D.value}]`)}catch{D.issues.push({code:"invalid_format",format:"ipv6",input:D.value,inst:_,continue:!$.abort})}}}),HO=K("$ZodMAC",(_,$)=>{$.pattern??($.pattern=ZA($.delimiter)),Y_.init(_,$),_._zod.bag.format="mac"}),bO=K("$ZodCIDRv4",(_,$)=>{$.pattern??($.pattern=HA),Y_.init(_,$)}),qO=K("$ZodCIDRv6",(_,$)=>{$.pattern??($.pattern=bA),Y_.init(_,$),_._zod.check=(D)=>{let I=D.value.split("/");try{if(I.length!==2)throw Error();let[U,E]=I;if(!E)throw Error();let j=Number(E);if(`${j}`!==E)throw Error();if(j<0||j>128)throw Error();new URL(`http://[${U}]`)}catch{D.issues.push({code:"invalid_format",format:"cidrv6",input:D.value,inst:_,continue:!$.abort})}}});CO=K("$ZodBase64",(_,$)=>{$.pattern??($.pattern=qA),Y_.init(_,$),_._zod.bag.contentEncoding="base64",_._zod.check=(D)=>{if(kO(D.value))return;D.issues.push({code:"invalid_format",format:"base64",input:D.value,inst:_,continue:!$.abort})}});vO=K("$ZodBase64URL",(_,$)=>{$.pattern??($.pattern=hI),Y_.init(_,$),_._zod.bag.contentEncoding="base64url",_._zod.check=(D)=>{if(P5(D.value))return;D.issues.push({code:"invalid_format",format:"base64url",input:D.value,inst:_,continue:!$.abort})}}),wO=K("$ZodE164",(_,$)=>{$.pattern??($.pattern=CA),Y_.init(_,$)});rO=K("$ZodJWT",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{if(z5(D.value,$.alg))return;D.issues.push({code:"invalid_format",format:"jwt",input:D.value,inst:_,continue:!$.abort})}}),fO=K("$ZodCustomStringFormat",(_,$)=>{Y_.init(_,$),_._zod.check=(D)=>{if($.fn(D.value))return;D.issues.push({code:"invalid_format",format:$.format,input:D.value,inst:_,continue:!$.abort})}}),eI=K("$ZodNumber",(_,$)=>{p.init(_,$),_._zod.pattern=_._zod.bag.pattern??OU,_._zod.parse=(D,I)=>{if($.coerce)try{D.value=Number(D.value)}catch(j){}let U=D.value;if(typeof U==="number"&&!Number.isNaN(U)&&Number.isFinite(U))return D;let E=typeof U==="number"?Number.isNaN(U)?"NaN":!Number.isFinite(U)?"Infinity":void 0:void 0;return D.issues.push({expected:"number",code:"invalid_type",input:U,inst:_,...E?{received:E}:{}}),D}}),xO=K("$ZodNumberFormat",(_,$)=>{lA.init(_,$),eI.init(_,$)}),WU=K("$ZodBoolean",(_,$)=>{p.init(_,$),_._zod.pattern=yA,_._zod.parse=(D,I)=>{if($.coerce)try{D.value=Boolean(D.value)}catch(E){}let U=D.value;if(typeof U==="boolean")return D;return D.issues.push({expected:"boolean",code:"invalid_type",input:U,inst:_}),D}}),aI=K("$ZodBigInt",(_,$)=>{p.init(_,$),_._zod.pattern=xA,_._zod.parse=(D,I)=>{if($.coerce)try{D.value=BigInt(D.value)}catch(U){}if(typeof D.value==="bigint")return D;return D.issues.push({expected:"bigint",code:"invalid_type",input:D.value,inst:_}),D}}),uO=K("$ZodBigIntFormat",(_,$)=>{iA.init(_,$),aI.init(_,$)}),yO=K("$ZodSymbol",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(typeof U==="symbol")return D;return D.issues.push({expected:"symbol",code:"invalid_type",input:U,inst:_}),D}}),hO=K("$ZodUndefined",(_,$)=>{p.init(_,$),_._zod.pattern=cA,_._zod.values=new Set([void 0]),_._zod.parse=(D,I)=>{let U=D.value;if(typeof U>"u")return D;return D.issues.push({expected:"undefined",code:"invalid_type",input:U,inst:_}),D}}),cO=K("$ZodNull",(_,$)=>{p.init(_,$),_._zod.pattern=hA,_._zod.values=new Set([null]),_._zod.parse=(D,I)=>{let U=D.value;if(U===null)return D;return D.issues.push({expected:"null",code:"invalid_type",input:U,inst:_}),D}}),nO=K("$ZodAny",(_,$)=>{p.init(_,$),_._zod.parse=(D)=>D}),dO=K("$ZodUnknown",(_,$)=>{p.init(_,$),_._zod.parse=(D)=>D}),mO=K("$ZodNever",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{return D.issues.push({expected:"never",code:"invalid_type",input:D.value,inst:_}),D}}),lO=K("$ZodVoid",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(typeof U>"u")return D;return D.issues.push({expected:"void",code:"invalid_type",input:U,inst:_}),D}}),iO=K("$ZodDate",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{if($.coerce)try{D.value=new Date(D.value)}catch(N){}let U=D.value,E=U instanceof Date;if(E&&!Number.isNaN(U.getTime()))return D;return D.issues.push({expected:"date",code:"invalid_type",input:U,...E?{received:"Invalid Date"}:{},inst:_}),D}});tO=K("$ZodArray",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!Array.isArray(U))return D.issues.push({expected:"array",code:"invalid_type",input:U,inst:_}),D;D.value=Array(U.length);let E=[];for(let j=0;j_5(S,D,j)));else _5(O,D,j)}if(E.length)return Promise.all(E).then(()=>D);return D}});G5=K("$ZodObject",(_,$)=>{if(p.init(_,$),!Object.getOwnPropertyDescriptor($,"shape")?.get){let N=$.shape;Object.defineProperty($,"shape",{get:()=>{let O={...N};return Object.defineProperty($,"shape",{value:O}),O}})}let I=C0(()=>g5($));D_(_._zod,"propValues",()=>{let N=$.shape,O={};for(let S in N){let L=N[S]._zod;if(L.values){O[S]??(O[S]=new Set);for(let W of L.values)O[S].add(W)}}return O});let U=R4,E=$.catchall,j;_._zod.parse=(N,O)=>{j??(j=I.value);let S=N.value;if(!U(S))return N.issues.push({expected:"object",code:"invalid_type",input:S,inst:_}),N;N.value={};let L=[],W=j.shape;for(let g of j.keys){let z=W[g],G=z._zod.optin==="optional",J=z._zod.optout==="optional",P=z._zod.run({value:S[g],issues:[]},O);if(P instanceof Promise)L.push(P.then((X)=>pI(X,N,g,S,G,J)));else pI(P,N,g,S,G,J)}if(!E)return L.length?Promise.all(L).then(()=>N):N;return X5(L,S,N,O,I.value,_)}}),oO=K("$ZodObjectJIT",(_,$)=>{G5.init(_,$);let D=_._zod.parse,I=C0(()=>g5($)),U=(g)=>{let z=new lI(["shape","payload","ctx"]),G=I.value,J=(T)=>{let Y=MI(T);return`shape[${Y}]._zod.run({ value: input[${Y}], issues: [] }, ctx)`};z.write("const input = payload.value;");let P=Object.create(null),X=0;for(let T of G.keys)P[T]=`key_${X++}`;z.write("const newResult = {};");for(let T of G.keys){let Y=P[T],Q=MI(T),F=g[T],B=F?._zod?.optin==="optional",b=F?._zod?.optout==="optional";if(z.write(`const ${Y} = ${J(T)};`),B&&b)z.write(` if (${Y}.issues.length) { if (${Q} in input) { payload.issues = payload.issues.concat(${Y}.issues.map(iss => ({ @@ -21,7 +21,7 @@ var TY=Object.create;var{getPrototypeOf:FY,defineProperty:wN,getOwnPropertyNames newResult[${Q}] = ${Y}.value; } - `);else if(!q)z.write(` + `);else if(!B)z.write(` const ${Y}_present = ${Q} in input; if (${Y}.issues.length) { payload.issues = payload.issues.concat(${Y}.issues.map(iss => ({ @@ -62,44 +62,44 @@ var TY=Object.create;var{getPrototypeOf:FY,defineProperty:wN,getOwnPropertyNames newResult[${Q}] = ${Y}.value; } - `)}z.write("payload.value = newResult;"),z.write("return payload;");let R=z.compile();return(T,Y)=>R(P,T,Y)},E,j=G4,N=!P4.jitless,O=N&&E2.value,S=$.catchall,L;_._zod.parse=(P,z)=>{L??(L=I.value);let G=P.value;if(!j(G))return P.issues.push({expected:"object",code:"invalid_type",input:G,inst:_}),P;if(N&&O&&z?.async===!1&&z.jitless!==!0){if(!E)E=U($.shape);if(P=E(P,z),!S)return P;return z5([],G,P,z,L,_)}return D(P,z)}});JU=K("$ZodUnion",(_,$)=>{o.init(_,$),D_(_._zod,"optin",()=>$.options.some((I)=>I._zod.optin==="optional")?"optional":void 0),D_(_._zod,"optout",()=>$.options.some((I)=>I._zod.optout==="optional")?"optional":void 0),D_(_._zod,"values",()=>{if($.options.every((I)=>I._zod.values))return new Set($.options.flatMap((I)=>Array.from(I._zod.values)));return}),D_(_._zod,"pattern",()=>{if($.options.every((I)=>I._zod.pattern)){let I=$.options.map((U)=>U._zod.pattern);return new RegExp(`^(${I.map((U)=>IU(U.source)).join("|")})$`)}return});let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(I,U)=>{if(D)return D(I,U);let E=!1,j=[];for(let N of $.options){let A=N._zod.run({value:I.value,issues:[]},U);if(A instanceof Promise)j.push(A),E=!0;else{if(A.issues.length===0)return A;j.push(A)}}if(!E)return _5(j,I,_,U);return Promise.all(j).then((N)=>{return _5(N,I,_,U)})}});pA=K("$ZodXor",(_,$)=>{JU.init(_,$),$.inclusive=!1;let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(I,U)=>{if(D)return D(I,U);let E=!1,j=[];for(let N of $.options){let A=N._zod.run({value:I.value,issues:[]},U);if(A instanceof Promise)j.push(A),E=!0;else j.push(A)}if(!E)return $5(j,I,_,U);return Promise.all(j).then((N)=>{return $5(N,I,_,U)})}}),eA=K("$ZodDiscriminatedUnion",(_,$)=>{$.inclusive=!1,JU.init(_,$);let D=_._zod.parse;D_(_._zod,"propValues",()=>{let U={};for(let E of $.options){let j=E._zod.propValues;if(!j||Object.keys(j).length===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(E)}"`);for(let[N,A]of Object.entries(j)){if(!U[N])U[N]=new Set;for(let O of A)U[N].add(O)}}return U});let I=k0(()=>{let U=$.options,E=new Map;for(let j of U){let N=j._zod.propValues?.[$.discriminator];if(!N||N.size===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(j)}"`);for(let A of N){if(E.has(A))throw Error(`Duplicate discriminator value "${String(A)}"`);E.set(A,j)}}return E});_._zod.parse=(U,E)=>{let j=U.value;if(!G4(j))return U.issues.push({code:"invalid_type",expected:"object",input:j,inst:_}),U;let N=I.value.get(j?.[$.discriminator]);if(N)return N._zod.run(U,E);if($.unionFallback||E.direction==="backward")return D(U,E);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:$.discriminator,options:Array.from(I.value.keys()),input:j,path:[$.discriminator],inst:_}),U}}),aA=K("$ZodIntersection",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value,E=$.left._zod.run({value:U,issues:[]},I),j=$.right._zod.run({value:U,issues:[]},I);if(E instanceof Promise||j instanceof Promise)return Promise.all([E,j]).then(([A,O])=>{return D5(D,A,O)});return D5(D,E,j)}});aI=K("$ZodTuple",(_,$)=>{o.init(_,$);let D=$.items;_._zod.parse=(I,U)=>{let E=I.value;if(!Array.isArray(E))return I.issues.push({input:E,inst:_,expected:"tuple",code:"invalid_type"}),I;I.value=[];let j=[],N=U5(D,"optin"),A=U5(D,"optout");if(!$.rest){if(E.lengthD.length)I.issues.push({code:"too_big",maximum:D.length,inclusive:!0,input:E,inst:_,origin:"array"})}let O=Array(D.length);for(let S=0;S{O[S]=P}));else O[S]=L}if($.rest){let S=D.length-1,L=E.slice(D.length);for(let P of L){S++;let z=$.rest._zod.run({value:P,issues:[]},U);if(z instanceof Promise)j.push(z.then((G)=>I5(G,I,S)));else I5(z,I,S)}}if(j.length)return Promise.all(j).then(()=>E5(O,I,D,E,A));return E5(O,I,D,E,A)}});sA=K("$ZodRecord",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!w6(U))return D.issues.push({expected:"record",code:"invalid_type",input:U,inst:_}),D;let E=[],j=$.keyType._zod.values;if(j){D.value={};let N=new Set;for(let O of j)if(typeof O==="string"||typeof O==="number"||typeof O==="symbol"){N.add(typeof O==="number"?O.toString():O);let S=$.keyType._zod.run({value:O,issues:[]},I);if(S instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(S.issues.length){D.issues.push({code:"invalid_key",origin:"record",issues:S.issues.map((z)=>t_(z,I,Z_())),input:O,path:[O],inst:_});continue}let L=S.value,P=$.valueType._zod.run({value:U[O],issues:[]},I);if(P instanceof Promise)E.push(P.then((z)=>{if(z.issues.length)D.issues.push(...$$(O,z.issues));D.value[L]=z.value}));else{if(P.issues.length)D.issues.push(...$$(O,P.issues));D.value[L]=P.value}}let A;for(let O in U)if(!N.has(O))A=A??[],A.push(O);if(A&&A.length>0)D.issues.push({code:"unrecognized_keys",input:U,inst:_,keys:A})}else{D.value={};for(let N of Reflect.ownKeys(U)){if(N==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(U,N))continue;let A=$.keyType._zod.run({value:N,issues:[]},I);if(A instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof N==="string"&&AU.test(N)&&A.issues.length){let L=$.keyType._zod.run({value:Number(N),issues:[]},I);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length===0)A=L}if(A.issues.length){if($.mode==="loose")D.value[N]=U[N];else D.issues.push({code:"invalid_key",origin:"record",issues:A.issues.map((L)=>t_(L,I,Z_())),input:N,path:[N],inst:_});continue}let S=$.valueType._zod.run({value:U[N],issues:[]},I);if(S instanceof Promise)E.push(S.then((L)=>{if(L.issues.length)D.issues.push(...$$(N,L.issues));D.value[A.value]=L.value}));else{if(S.issues.length)D.issues.push(...$$(N,S.issues));D.value[A.value]=S.value}}}if(E.length)return Promise.all(E).then(()=>D);return D}}),_O=K("$ZodMap",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!(U instanceof Map))return D.issues.push({expected:"map",code:"invalid_type",input:U,inst:_}),D;let E=[];D.value=new Map;for(let[j,N]of U){let A=$.keyType._zod.run({value:j,issues:[]},I),O=$.valueType._zod.run({value:N,issues:[]},I);if(A instanceof Promise||O instanceof Promise)E.push(Promise.all([A,O]).then(([S,L])=>{j5(S,L,D,j,U,_,I)}));else j5(A,O,D,j,U,_,I)}if(E.length)return Promise.all(E).then(()=>D);return D}});$O=K("$ZodSet",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!(U instanceof Set))return D.issues.push({input:U,inst:_,expected:"set",code:"invalid_type"}),D;let E=[];D.value=new Set;for(let j of U){let N=$.valueType._zod.run({value:j,issues:[]},I);if(N instanceof Promise)E.push(N.then((A)=>N5(A,D)));else N5(N,D)}if(E.length)return Promise.all(E).then(()=>D);return D}});DO=K("$ZodEnum",(_,$)=>{o.init(_,$);let D=UU($.entries),I=new Set(D);_._zod.values=I,_._zod.pattern=new RegExp(`^(${D.filter((U)=>EU.has(typeof U)).map((U)=>typeof U==="string"?z$(U):U.toString()).join("|")})$`),_._zod.parse=(U,E)=>{let j=U.value;if(I.has(j))return U;return U.issues.push({code:"invalid_value",values:D,input:j,inst:_}),U}}),UO=K("$ZodLiteral",(_,$)=>{if(o.init(_,$),$.values.length===0)throw Error("Cannot create literal schema with no valid values");let D=new Set($.values);_._zod.values=D,_._zod.pattern=new RegExp(`^(${$.values.map((I)=>typeof I==="string"?z$(I):I?z$(I.toString()):String(I)).join("|")})$`),_._zod.parse=(I,U)=>{let E=I.value;if(D.has(E))return I;return I.issues.push({code:"invalid_value",values:$.values,input:E,inst:_}),I}}),IO=K("$ZodFile",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(U instanceof File)return D;return D.issues.push({expected:"file",code:"invalid_type",input:U,inst:_}),D}}),EO=K("$ZodTransform",(_,$)=>{o.init(_,$),_._zod.optin="optional",_._zod.parse=(D,I)=>{if(I.direction==="backward")throw new z4(_.constructor.name);let U=$.transform(D.value,D);if(I.async)return(U instanceof Promise?U:Promise.resolve(U)).then((j)=>{return D.value=j,D.fallback=!0,D});if(U instanceof Promise)throw new m$;return D.value=U,D.fallback=!0,D}});sI=K("$ZodOptional",(_,$)=>{o.init(_,$),_._zod.optin="optional",_._zod.optout="optional",D_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,void 0]):void 0}),D_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${IU(D.source)})?$`):void 0}),_._zod.parse=(D,I)=>{if($.innerType._zod.optin==="optional"){let U=D.value,E=$.innerType._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>g5(j,U));return g5(E,U)}if(D.value===void 0)return D;return $.innerType._zod.run(D,I)}}),jO=K("$ZodExactOptional",(_,$)=>{sI.init(_,$),D_(_._zod,"values",()=>$.innerType._zod.values),D_(_._zod,"pattern",()=>$.innerType._zod.pattern),_._zod.parse=(D,I)=>{return $.innerType._zod.run(D,I)}}),NO=K("$ZodNullable",(_,$)=>{o.init(_,$),D_(_._zod,"optin",()=>$.innerType._zod.optin),D_(_._zod,"optout",()=>$.innerType._zod.optout),D_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${IU(D.source)}|null)$`):void 0}),D_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,null]):void 0}),_._zod.parse=(D,I)=>{if(D.value===null)return D;return $.innerType._zod.run(D,I)}}),gO=K("$ZodDefault",(_,$)=>{o.init(_,$),_._zod.optin="optional",D_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);if(D.value===void 0)return D.value=$.defaultValue,D;let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>A5(E,$));return A5(U,$)}});AO=K("$ZodPrefault",(_,$)=>{o.init(_,$),_._zod.optin="optional",D_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);if(D.value===void 0)D.value=$.defaultValue;return $.innerType._zod.run(D,I)}}),OO=K("$ZodNonOptional",(_,$)=>{o.init(_,$),D_(_._zod,"values",()=>{let D=$.innerType._zod.values;return D?new Set([...D].filter((I)=>I!==void 0)):void 0}),_._zod.parse=(D,I)=>{let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>O5(E,_));return O5(U,_)}});SO=K("$ZodSuccess",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{if(I.direction==="backward")throw new z4("ZodSuccess");let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>{return D.value=E.issues.length===0,D});return D.value=U.issues.length===0,D}}),LO=K("$ZodCatch",(_,$)=>{o.init(_,$),_._zod.optin="optional",D_(_._zod,"optout",()=>$.innerType._zod.optout),D_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>{if(D.value=E.value,E.issues.length)D.value=$.catchValue({...D,error:{issues:E.issues.map((j)=>t_(j,I,Z_()))},input:D.value}),D.issues=[],D.fallback=!0;return D});if(D.value=U.value,U.issues.length)D.value=$.catchValue({...D,error:{issues:U.issues.map((E)=>t_(E,I,Z_()))},input:D.value}),D.issues=[],D.fallback=!0;return D}}),JO=K("$ZodNaN",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{if(typeof D.value!=="number"||!Number.isNaN(D.value))return D.issues.push({input:D.value,inst:_,expected:"nan",code:"invalid_type"}),D;return D}}),_E=K("$ZodPipe",(_,$)=>{o.init(_,$),D_(_._zod,"values",()=>$.in._zod.values),D_(_._zod,"optin",()=>$.in._zod.optin),D_(_._zod,"optout",()=>$.out._zod.optout),D_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,I)=>{if(I.direction==="backward"){let E=$.out._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>lI(j,$.in,I));return lI(E,$.in,I)}let U=$.in._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>lI(E,$.out,I));return lI(U,$.out,I)}});WU=K("$ZodCodec",(_,$)=>{o.init(_,$),D_(_._zod,"values",()=>$.in._zod.values),D_(_._zod,"optin",()=>$.in._zod.optin),D_(_._zod,"optout",()=>$.out._zod.optout),D_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,I)=>{if((I.direction||"forward")==="forward"){let E=$.in._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>iI(j,$,I));return iI(E,$,I)}else{let E=$.out._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>iI(j,$,I));return iI(E,$,I)}}});WO=K("$ZodPreprocess",(_,$)=>{_E.init(_,$)}),PO=K("$ZodReadonly",(_,$)=>{o.init(_,$),D_(_._zod,"propValues",()=>$.innerType._zod.propValues),D_(_._zod,"values",()=>$.innerType._zod.values),D_(_._zod,"optin",()=>$.innerType?._zod?.optin),D_(_._zod,"optout",()=>$.innerType?._zod?.optout),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then(S5);return S5(U)}});zO=K("$ZodTemplateLiteral",(_,$)=>{o.init(_,$);let D=[];for(let I of $.parts)if(typeof I==="object"&&I!==null){if(!I._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...I._zod.traits].shift()}`);let U=I._zod.pattern instanceof RegExp?I._zod.pattern.source:I._zod.pattern;if(!U)throw Error(`Invalid template literal part: ${I._zod.traits}`);let E=U.startsWith("^")?1:0,j=U.endsWith("$")?U.length-1:U.length;D.push(U.slice(E,j))}else if(I===null||N2.has(typeof I))D.push(z$(`${I}`));else throw Error(`Invalid template literal part: ${I}`);_._zod.pattern=new RegExp(`^${D.join("")}$`),_._zod.parse=(I,U)=>{if(typeof I.value!=="string")return I.issues.push({input:I.value,inst:_,expected:"string",code:"invalid_type"}),I;if(_._zod.pattern.lastIndex=0,!_._zod.pattern.test(I.value))return I.issues.push({input:I.value,inst:_,code:"invalid_format",format:$.format??"template_literal",pattern:_._zod.pattern.source}),I;return I}}),XO=K("$ZodFunction",(_,$)=>{return o.init(_,$),_._def=$,_._zod.def=$,_.implement=(D)=>{if(typeof D!=="function")throw Error("implement() must be called with a function");return function(...I){let U=_._def.input?HI(_._def.input,I):I,E=Reflect.apply(D,this,U);if(_._def.output)return HI(_._def.output,E);return E}},_.implementAsync=(D)=>{if(typeof D!=="function")throw Error("implementAsync() must be called with a function");return async function(...I){let U=_._def.input?await kI(_._def.input,I):I,E=await Reflect.apply(D,this,U);if(_._def.output)return await kI(_._def.output,E);return E}},_._zod.parse=(D,I)=>{if(typeof D.value!=="function")return D.issues.push({code:"invalid_type",expected:"function",input:D.value,inst:_}),D;if(_._def.output&&_._def.output._zod.def.type==="promise")D.value=_.implementAsync(D.value);else D.value=_.implement(D.value);return D},_.input=(...D)=>{let I=_.constructor;if(Array.isArray(D[0]))return new I({type:"function",input:new aI({type:"tuple",items:D[0],rest:D[1]}),output:_._def.output});return new I({type:"function",input:D[0],output:_._def.output})},_.output=(D)=>{return new _.constructor({type:"function",input:_._def.input,output:D})},_}),GO=K("$ZodPromise",(_,$)=>{o.init(_,$),_._zod.parse=(D,I)=>{return Promise.resolve(D.value).then((U)=>$.innerType._zod.run({value:U,issues:[]},I))}}),RO=K("$ZodLazy",(_,$)=>{o.init(_,$),D_(_._zod,"innerType",()=>{let D=$;if(!D._cachedInner)D._cachedInner=$.getter();return D._cachedInner}),D_(_._zod,"pattern",()=>_._zod.innerType?._zod?.pattern),D_(_._zod,"propValues",()=>_._zod.innerType?._zod?.propValues),D_(_._zod,"optin",()=>_._zod.innerType?._zod?.optin??void 0),D_(_._zod,"optout",()=>_._zod.innerType?._zod?.optout??void 0),_._zod.parse=(D,I)=>{return _._zod.innerType._zod.run(D,I)}}),YO=K("$ZodCustom",(_,$)=>{Q_.init(_,$),o.init(_,$),_._zod.parse=(D,I)=>{return D},_._zod.check=(D)=>{let I=D.value,U=$.fn(I);if(U instanceof Promise)return U.then((E)=>L5(E,D,I,_));L5(U,D,I,_);return}})});function KO(){return{localeError:wB()}}var wB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`;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 ${E}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`}case"invalid_value":if(U.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 ${B(U.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: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${U.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${E} ${U.maximum.toString()} ${j.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 ${U.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${U.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${E} ${U.minimum.toString()} ${j.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${U.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${U.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${U.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${U.keys.length>1?"\u0629":""}: ${V(U.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${U.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 ${U.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var G5=r(()=>{n()});function TO(){return{localeError:rB()}}var rB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${U.expected}, daxil olan ${N}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${E}, daxil olan ${N}`}case"invalid_value":if(U.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${B(U.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${U.origin??"d\u0259y\u0259r"} ${E}${U.maximum.toString()} ${j.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${U.origin??"d\u0259y\u0259r"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${U.origin} ${E}${U.minimum.toString()} ${j.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${E.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(E.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${E.suffix}" il\u0259 bitm\u0259lidir`;if(E.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${E.includes}" daxil olmal\u0131d\u0131r`;if(E.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${E.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${D[E.format]??U.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${U.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${U.keys.length>1?"lar":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${U.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var R5=r(()=>{n()});function Y5(_,$,D,I){let U=Math.abs(_),E=U%10,j=U%100;if(j>=11&&j<=19)return I;if(E===1)return $;if(E>=2&&E<=4)return D;return I}function FO(){return{localeError:fB()}}var fB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${E}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j){let N=Number(U.maximum),A=Y5(N,j.unit.one,j.unit.few,j.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 ${U.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${E}${U.maximum.toString()} ${A}`}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 ${U.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j){let N=Number(U.minimum),A=Y5(N,j.unit.one,j.unit.few,j.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 ${U.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${E}${U.minimum.toString()} ${A}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${U.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${U.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${U.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 ${U.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var Q5=r(()=>{n()});function VO(){return{localeError:xB()}}var xB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${U.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${E}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`}case"invalid_value":if(U.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${U.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${U.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${E}${U.minimum.toString()} ${j.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${U.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;let j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(E.format==="emoji")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(E.format==="datetime")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(E.format==="date")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(E.format==="time")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(E.format==="duration")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${j} ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${U.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${U.keys.length>1?"\u043E\u0432\u0435":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${U.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 ${U.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var K5=r(()=>{n()});function BO(){return{localeError:uB()}}var uB=()=>{let _={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${U.expected}, s'ha rebut ${N}`;return`Tipus inv\xE0lid: s'esperava ${E}, s'ha rebut ${N}`}case"invalid_value":if(U.values.length===1)return`Valor inv\xE0lid: s'esperava ${B(U.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${V(U.values," o ")}`;case"too_big":{let E=U.inclusive?"com a m\xE0xim":"menys de",j=$(U.origin);if(j)return`Massa gran: s'esperava que ${U.origin??"el valor"} contingu\xE9s ${E} ${U.maximum.toString()} ${j.unit??"elements"}`;return`Massa gran: s'esperava que ${U.origin??"el valor"} fos ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?"com a m\xEDnim":"m\xE9s de",j=$(U.origin);if(j)return`Massa petit: s'esperava que ${U.origin} contingu\xE9s ${E} ${U.minimum.toString()} ${j.unit}`;return`Massa petit: s'esperava que ${U.origin} fos ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${E.prefix}"`;if(E.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${E.suffix}"`;if(E.format==="includes")return`Format inv\xE0lid: ha d'incloure "${E.includes}"`;if(E.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${E.pattern}`;return`Format inv\xE0lid per a ${D[E.format]??U.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${U.divisor}`;case"unrecognized_keys":return`Clau${U.keys.length>1?"s":""} no reconeguda${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${U.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${U.origin}`;default:return"Entrada inv\xE0lida"}}};var T5=r(()=>{n()});function MO(){return{localeError:yB()}}var yB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${U.expected}, obdr\u017Eeno ${N}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${E}, obdr\u017Eeno ${N}`}case"invalid_value":if(U.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${B(U.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${U.origin??"hodnota"} mus\xED m\xEDt ${E}${U.maximum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${U.origin??"hodnota"} mus\xED b\xFDt ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${U.origin??"hodnota"} mus\xED m\xEDt ${E}${U.minimum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${U.origin??"hodnota"} mus\xED b\xFDt ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${E.prefix}"`;if(E.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${E.suffix}"`;if(E.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${E.includes}"`;if(E.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${E.pattern}`;return`Neplatn\xFD form\xE1t ${D[E.format]??U.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${U.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${V(U.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${U.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${U.origin}`;default:return"Neplatn\xFD vstup"}}};var F5=r(()=>{n()});function bO(){return{localeError:hB()}}var hB=()=>{let _={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ugyldigt input: forventede instanceof ${U.expected}, fik ${N}`;return`Ugyldigt input: forventede ${E}, fik ${N}`}case"invalid_value":if(U.values.length===1)return`Ugyldig v\xE6rdi: forventede ${B(U.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`For stor: forventede ${N??"value"} ${j.verb} ${E} ${U.maximum.toString()} ${j.unit??"elementer"}`;return`For stor: forventede ${N??"value"} havde ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`For lille: forventede ${N} ${j.verb} ${E} ${U.minimum.toString()} ${j.unit}`;return`For lille: forventede ${N} havde ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ugyldig streng: skal starte med "${E.prefix}"`;if(E.format==="ends_with")return`Ugyldig streng: skal ende med "${E.suffix}"`;if(E.format==="includes")return`Ugyldig streng: skal indeholde "${E.includes}"`;if(E.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${E.pattern}`;return`Ugyldig ${D[E.format]??U.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${U.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${U.origin}`;default:return"Ugyldigt input"}}};var V5=r(()=>{n()});function ZO(){return{localeError:cB()}}var cB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"Zahl",array:"Array"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${U.expected}, erhalten ${N}`;return`Ung\xFCltige Eingabe: erwartet ${E}, erhalten ${N}`}case"invalid_value":if(U.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${B(U.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Zu gro\xDF: erwartet, dass ${U.origin??"Wert"} ${E}${U.maximum.toString()} ${j.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${U.origin??"Wert"} ${E}${U.maximum.toString()} ist`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Zu klein: erwartet, dass ${U.origin} ${E}${U.minimum.toString()} ${j.unit} hat`;return`Zu klein: erwartet, dass ${U.origin} ${E}${U.minimum.toString()} ist`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ung\xFCltiger String: muss mit "${E.prefix}" beginnen`;if(E.format==="ends_with")return`Ung\xFCltiger String: muss mit "${E.suffix}" enden`;if(E.format==="includes")return`Ung\xFCltiger String: muss "${E.includes}" enthalten`;if(E.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${E.pattern} entsprechen`;return`Ung\xFCltig: ${D[E.format]??U.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${U.divisor} sein`;case"unrecognized_keys":return`${U.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${U.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${U.origin}`;default:return"Ung\xFCltige Eingabe"}}};var B5=r(()=>{n()});function HO(){return{localeError:nB()}}var nB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(typeof U.expected==="string"&&/^[A-Z]/.test(U.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 ${U.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`;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 ${E}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${U.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${U.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${E}${U.minimum.toString()} ${j.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${U.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${U.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${U.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${U.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 ${U.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var M5=r(()=>{n()});function PU(){return{localeError:dB()}}var dB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;return`Invalid input: expected ${E}, received ${N}`}case"invalid_value":if(U.values.length===1)return`Invalid input: expected ${B(U.values[0])}`;return`Invalid option: expected one of ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Too big: expected ${U.origin??"value"} to have ${E}${U.maximum.toString()} ${j.unit??"elements"}`;return`Too big: expected ${U.origin??"value"} to be ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Too small: expected ${U.origin} to have ${E}${U.minimum.toString()} ${j.unit}`;return`Too small: expected ${U.origin} to be ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Invalid string: must start with "${E.prefix}"`;if(E.format==="ends_with")return`Invalid string: must end with "${E.suffix}"`;if(E.format==="includes")return`Invalid string: must include "${E.includes}"`;if(E.format==="regex")return`Invalid string: must match pattern ${E.pattern}`;return`Invalid ${D[E.format]??U.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${U.divisor}`;case"unrecognized_keys":return`Unrecognized key${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Invalid key in ${U.origin}`;case"invalid_union":if(U.options&&Array.isArray(U.options)&&U.options.length>0)return`Invalid discriminator value. Expected ${U.options.map((j)=>`'${j}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${U.origin}`;default:return"Invalid input"}}};var kO=r(()=>{n()});function qO(){return{localeError:mB()}}var mB=()=>{let _={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${U.expected}, ricevi\u011Dis ${N}`;return`Nevalida enigo: atendi\u011Dis ${E}, ricevi\u011Dis ${N}`}case"invalid_value":if(U.values.length===1)return`Nevalida enigo: atendi\u011Dis ${B(U.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Tro granda: atendi\u011Dis ke ${U.origin??"valoro"} havu ${E}${U.maximum.toString()} ${j.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${U.origin??"valoro"} havu ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Tro malgranda: atendi\u011Dis ke ${U.origin} havu ${E}${U.minimum.toString()} ${j.unit}`;return`Tro malgranda: atendi\u011Dis ke ${U.origin} estu ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${E.prefix}"`;if(E.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${E.suffix}"`;if(E.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${E.includes}"`;if(E.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${E.pattern}`;return`Nevalida ${D[E.format]??U.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${U.divisor}`;case"unrecognized_keys":return`Nekonata${U.keys.length>1?"j":""} \u015Dlosilo${U.keys.length>1?"j":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${U.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${U.origin}`;default:return"Nevalida enigo"}}};var b5=r(()=>{n()});function CO(){return{localeError:lB()}}var lB=()=>{let _={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${U.expected}, recibido ${N}`;return`Entrada inv\xE1lida: se esperaba ${E}, recibido ${N}`}case"invalid_value":if(U.values.length===1)return`Entrada inv\xE1lida: se esperaba ${B(U.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Demasiado grande: se esperaba que ${N??"valor"} tuviera ${E}${U.maximum.toString()} ${j.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${N??"valor"} fuera ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Demasiado peque\xF1o: se esperaba que ${N} tuviera ${E}${U.minimum.toString()} ${j.unit}`;return`Demasiado peque\xF1o: se esperaba que ${N} fuera ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${E.prefix}"`;if(E.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${E.suffix}"`;if(E.format==="includes")return`Cadena inv\xE1lida: debe incluir "${E.includes}"`;if(E.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${E.pattern}`;return`Inv\xE1lido ${D[E.format]??U.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${U.divisor}`;case"unrecognized_keys":return`Llave${U.keys.length>1?"s":""} desconocida${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${I[U.origin]??U.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${I[U.origin]??U.origin}`;default:return"Entrada inv\xE1lida"}}};var Z5=r(()=>{n()});function vO(){return{localeError:iB()}}var iB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${U.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \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 ${E} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(U.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${B(U.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 ${V(U.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${U.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${U.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} ${j.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${E.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(E.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${E.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(E.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${E.includes}" \u0628\u0627\u0634\u062F`;if(E.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 ${E.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${D[E.format]??U.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 ${U.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${U.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${V(U.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${U.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 ${U.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var H5=r(()=>{n()});function wO(){return{localeError:tB()}}var tB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Virheellinen tyyppi: odotettiin instanceof ${U.expected}, oli ${N}`;return`Virheellinen tyyppi: odotettiin ${E}, oli ${N}`}case"invalid_value":if(U.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${B(U.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Liian suuri: ${j.subject} t\xE4ytyy olla ${E}${U.maximum.toString()} ${j.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Liian pieni: ${j.subject} t\xE4ytyy olla ${E}${U.minimum.toString()} ${j.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${E.prefix}"`;if(E.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${E.suffix}"`;if(E.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${E.includes}"`;if(E.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${E.pattern}`;return`Virheellinen ${D[E.format]??U.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${U.divisor} monikerta`;case"unrecognized_keys":return`${U.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${V(U.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 k5=r(()=>{n()});function rO(){return{localeError:oB()}}var oB=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Entr\xE9e invalide : instanceof ${U.expected} attendu, ${N} re\xE7u`;return`Entr\xE9e invalide : ${E} attendu, ${N} re\xE7u`}case"invalid_value":if(U.values.length===1)return`Entr\xE9e invalide : ${B(U.values[0])} attendu`;return`Option invalide : une valeur parmi ${V(U.values,"|")} attendue`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Trop grand : ${I[U.origin]??"valeur"} doit ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${I[U.origin]??"valeur"} doit \xEAtre ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Trop petit : ${I[U.origin]??"valeur"} doit ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Trop petit : ${I[U.origin]??"valeur"} doit \xEAtre ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${E.prefix}"`;if(E.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${E.suffix}"`;if(E.format==="includes")return`Cha\xEEne invalide : doit inclure "${E.includes}"`;if(E.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${E.pattern}`;return`${D[E.format]??U.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${U.divisor}`;case"unrecognized_keys":return`Cl\xE9${U.keys.length>1?"s":""} non reconnue${U.keys.length>1?"s":""} : ${V(U.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${U.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${U.origin}`;default:return"Entr\xE9e invalide"}}};var q5=r(()=>{n()});function fO(){return{localeError:pB()}}var pB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Entr\xE9e invalide : attendu instanceof ${U.expected}, re\xE7u ${N}`;return`Entr\xE9e invalide : attendu ${E}, re\xE7u ${N}`}case"invalid_value":if(U.values.length===1)return`Entr\xE9e invalide : attendu ${B(U.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"\u2264":"<",j=$(U.origin);if(j)return`Trop grand : attendu que ${U.origin??"la valeur"} ait ${E}${U.maximum.toString()} ${j.unit}`;return`Trop grand : attendu que ${U.origin??"la valeur"} soit ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?"\u2265":">",j=$(U.origin);if(j)return`Trop petit : attendu que ${U.origin} ait ${E}${U.minimum.toString()} ${j.unit}`;return`Trop petit : attendu que ${U.origin} soit ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${E.prefix}"`;if(E.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${E.suffix}"`;if(E.format==="includes")return`Cha\xEEne invalide : doit inclure "${E.includes}"`;if(E.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${E.pattern}`;return`${D[E.format]??U.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${U.divisor}`;case"unrecognized_keys":return`Cl\xE9${U.keys.length>1?"s":""} non reconnue${U.keys.length>1?"s":""} : ${V(U.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${U.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${U.origin}`;default:return"Entr\xE9e invalide"}}};var C5=r(()=>{n()});function xO(){return{localeError:eB()}}var eB=()=>{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"}},D=(O)=>O?_[O]:void 0,I=(O)=>{let S=D(O);if(S)return S.label;return O??_.unknown.label},U=(O)=>`\u05D4${I(O)}`,E=(O)=>{return(D(O)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},j=(O)=>{if(!O)return null;return $[O]??null},N={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"}},A={nan:"NaN"};return(O)=>{switch(O.code){case"invalid_type":{let S=O.expected,L=A[S??""]??I(S),P=M(O.input),z=A[P]??_[P]?.label??P;if(/^[A-Z]/.test(O.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${O.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${z}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${L}, \u05D4\u05EA\u05E7\u05D1\u05DC ${z}`}case"invalid_value":{if(O.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 ${B(O.values[0])}`;let S=O.values.map((z)=>B(z));if(O.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 ${S[0]} \u05D0\u05D5 ${S[1]}`;let L=S[S.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 ${S.slice(0,-1).join(", ")} \u05D0\u05D5 ${L}`}case"too_big":{let S=j(O.origin),L=U(O.origin??"value");if(O.origin==="string")return`${S?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${L} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${O.maximum.toString()} ${S?.unit??""} ${O.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(O.origin==="number"){let G=O.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${O.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${O.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${L} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${G}`}if(O.origin==="array"||O.origin==="set"){let G=O.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",J=O.inclusive?`${O.maximum} ${S?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${O.maximum} ${S?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${L} ${G} \u05DC\u05D4\u05DB\u05D9\u05DC ${J}`.trim()}let P=O.inclusive?"<=":"<",z=E(O.origin??"value");if(S?.unit)return`${S.longLabel} \u05DE\u05D3\u05D9: ${L} ${z} ${P}${O.maximum.toString()} ${S.unit}`;return`${S?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${L} ${z} ${P}${O.maximum.toString()}`}case"too_small":{let S=j(O.origin),L=U(O.origin??"value");if(O.origin==="string")return`${S?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${L} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${O.minimum.toString()} ${S?.unit??""} ${O.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(O.origin==="number"){let G=O.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${O.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${O.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${L} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${G}`}if(O.origin==="array"||O.origin==="set"){let G=O.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(O.minimum===1&&O.inclusive){let W=O.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: ${L} ${G} \u05DC\u05D4\u05DB\u05D9\u05DC ${W}`}let J=O.inclusive?`${O.minimum} ${S?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${O.minimum} ${S?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${L} ${G} \u05DC\u05D4\u05DB\u05D9\u05DC ${J}`.trim()}let P=O.inclusive?">=":">",z=E(O.origin??"value");if(S?.unit)return`${S.shortLabel} \u05DE\u05D3\u05D9: ${L} ${z} ${P}${O.minimum.toString()} ${S.unit}`;return`${S?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${L} ${z} ${P}${O.minimum.toString()}`}case"invalid_format":{let S=O;if(S.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${S.prefix}"`;if(S.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${S.suffix}"`;if(S.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${S.includes}"`;if(S.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 ${S.pattern}`;let L=N[S.format],P=L?.label??S.format,G=(L?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${P} \u05DC\u05D0 ${G}`}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 ${O.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${O.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${O.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${V(O.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${U(O.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var v5=r(()=>{n()});function uO(){return{localeError:aB()}}var aB=()=>{let _={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${U.expected}, a primljeno je ${N}`;return`Neispravan unos: o\u010Dekuje se ${E}, a primljeno je ${N}`}case"invalid_value":if(U.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${B(U.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} ima ${E}${U.maximum.toString()} ${j.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} bude ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Premalo: o\u010Dekivano da ${N} ima ${E}${U.minimum.toString()} ${j.unit}`;return`Premalo: o\u010Dekivano da ${N} bude ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${E.prefix}"`;if(E.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${E.suffix}"`;if(E.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${E.includes}"`;if(E.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${E.pattern}`;return`Neispravna ${D[E.format]??U.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${U.divisor}`;case"unrecognized_keys":return`Neprepoznat${U.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${V(U.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${I[U.origin]??U.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${I[U.origin]??U.origin}`;default:return"Neispravan unos"}}};var w5=r(()=>{n()});function yO(){return{localeError:sB()}}var sB=()=>{let _={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${U.expected}, a kapott \xE9rt\xE9k ${N}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${E}, a kapott \xE9rt\xE9k ${N}`}case"invalid_value":if(U.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${B(U.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`T\xFAl nagy: ${U.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${E}${U.maximum.toString()} ${j.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${U.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${U.origin} m\xE9rete t\xFAl kicsi ${E}${U.minimum.toString()} ${j.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${U.origin} t\xFAl kicsi ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\xC9rv\xE9nytelen string: "${E.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(E.format==="ends_with")return`\xC9rv\xE9nytelen string: "${E.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(E.format==="includes")return`\xC9rv\xE9nytelen string: "${E.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(E.format==="regex")return`\xC9rv\xE9nytelen string: ${E.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${D[E.format]??U.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${U.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${U.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${U.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var r5=r(()=>{n()});function f5(_,$,D){return Math.abs(_)===1?$:D}function y0(_){if(!_)return"";let $=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],D=_[_.length-1];return _+($.includes(D)?"\u0576":"\u0568")}function hO(){return{localeError:_M()}}var _M=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`;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 ${E}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j){let N=Number(U.maximum),A=f5(N,j.unit.one,j.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 ${y0(U.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${E}${U.maximum.toString()} ${A}`}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 ${y0(U.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j){let N=Number(U.minimum),A=f5(N,j.unit.one,j.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 ${y0(U.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${E}${U.minimum.toString()} ${A}`}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 ${y0(U.origin)} \u056C\u056B\u0576\u056B ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${E.prefix}"-\u0578\u057E`;if(E.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${E.suffix}"-\u0578\u057E`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${D[E.format]??U.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 ${U.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${U.keys.length>1?"\u0576\u0565\u0580":""}. ${V(U.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${y0(U.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 ${y0(U.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var x5=r(()=>{n()});function cO(){return{localeError:$M()}}var $M=()=>{let _={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Input tidak valid: diharapkan instanceof ${U.expected}, diterima ${N}`;return`Input tidak valid: diharapkan ${E}, diterima ${N}`}case"invalid_value":if(U.values.length===1)return`Input tidak valid: diharapkan ${B(U.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Terlalu besar: diharapkan ${U.origin??"value"} memiliki ${E}${U.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: diharapkan ${U.origin??"value"} menjadi ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Terlalu kecil: diharapkan ${U.origin} memiliki ${E}${U.minimum.toString()} ${j.unit}`;return`Terlalu kecil: diharapkan ${U.origin} menjadi ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`String tidak valid: harus dimulai dengan "${E.prefix}"`;if(E.format==="ends_with")return`String tidak valid: harus berakhir dengan "${E.suffix}"`;if(E.format==="includes")return`String tidak valid: harus menyertakan "${E.includes}"`;if(E.format==="regex")return`String tidak valid: harus sesuai pola ${E.pattern}`;return`${D[E.format]??U.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${U.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${U.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${U.origin}`;default:return"Input tidak valid"}}};var u5=r(()=>{n()});function nO(){return{localeError:DM()}}var DM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera instanceof ${U.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera ${E}`}case"invalid_value":if(U.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${B(U.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin??"gildi"} hafi ${E}${U.maximum.toString()} ${j.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin??"gildi"} s\xE9 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin} hafi ${E}${U.minimum.toString()} ${j.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin} s\xE9 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${E.prefix}"`;if(E.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${E.suffix}"`;if(E.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${E.includes}"`;if(E.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${E.pattern}`;return`Rangt ${D[E.format]??U.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${U.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${U.keys.length>1?"ir lyklar":"ur lykill"}: ${V(U.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${U.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${U.origin}`;default:return"Rangt gildi"}}};var y5=r(()=>{n()});function dO(){return{localeError:UM()}}var UM=()=>{let _={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"numero",array:"vettore"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Input non valido: atteso instanceof ${U.expected}, ricevuto ${N}`;return`Input non valido: atteso ${E}, ricevuto ${N}`}case"invalid_value":if(U.values.length===1)return`Input non valido: atteso ${B(U.values[0])}`;return`Opzione non valida: atteso uno tra ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Troppo grande: ${U.origin??"valore"} deve avere ${E}${U.maximum.toString()} ${j.unit??"elementi"}`;return`Troppo grande: ${U.origin??"valore"} deve essere ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Troppo piccolo: ${U.origin} deve avere ${E}${U.minimum.toString()} ${j.unit}`;return`Troppo piccolo: ${U.origin} deve essere ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Stringa non valida: deve iniziare con "${E.prefix}"`;if(E.format==="ends_with")return`Stringa non valida: deve terminare con "${E.suffix}"`;if(E.format==="includes")return`Stringa non valida: deve includere "${E.includes}"`;if(E.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${E.pattern}`;return`Input non valido: ${D[E.format]??U.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${U.divisor}`;case"unrecognized_keys":return`Chiav${U.keys.length>1?"i":"e"} non riconosciut${U.keys.length>1?"e":"a"}: ${V(U.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${U.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${U.origin}`;default:return"Input non valido"}}};var h5=r(()=>{n()});function mO(){return{localeError:IM()}}var IM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${U.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${E}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(U.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${B(U.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${V(U.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let E=U.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",j=$(U.origin);if(j)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${U.origin??"\u5024"}\u306F${U.maximum.toString()}${j.unit??"\u8981\u7D20"}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${U.origin??"\u5024"}\u306F${U.maximum.toString()}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let E=U.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",j=$(U.origin);if(j)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${U.origin}\u306F${U.minimum.toString()}${j.unit}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${U.origin}\u306F${U.minimum.toString()}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${E.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(E.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${E.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(E.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${E.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(E.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${E.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${D[E.format]??U.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${U.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${U.keys.length>1?"\u7FA4":""}: ${V(U.keys,"\u3001")}`;case"invalid_key":return`${U.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${U.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var c5=r(()=>{n()});function lO(){return{localeError:EM()}}var EM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`;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 ${E}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${U.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${j.verb} ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)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 ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.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 ${U.origin} \u10D8\u10E7\u10DD\u10E1 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"-\u10D8\u10D7`;if(E.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 "${E.suffix}"-\u10D8\u10D7`;if(E.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 "${E.includes}"-\u10E1`;if(E.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 ${E.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${D[E.format]??U.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 ${U.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${U.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${U.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 ${U.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var n5=r(()=>{n()});function zU(){return{localeError:jM()}}var jM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`;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 ${E} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${E} ${U.maximum.toString()} ${j.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin} ${E} ${U.minimum.toString()} ${j.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin} ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${V(U.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 ${U.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 ${U.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 iO=r(()=>{n()});function tO(){return zU()}var d5=r(()=>{iO()});function oO(){return{localeError:NM()}}var NM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${U.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${E}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`}case"invalid_value":if(U.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${B(U.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${V(U.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let E=U.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",j=E==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(U.origin),A=N?.unit??"\uC694\uC18C";if(N)return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${U.maximum.toString()}${A} ${E}${j}`;return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${U.maximum.toString()} ${E}${j}`}case"too_small":{let E=U.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",j=E==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(U.origin),A=N?.unit??"\uC694\uC18C";if(N)return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${U.minimum.toString()}${A} ${E}${j}`;return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${U.minimum.toString()} ${E}${j}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${E.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(E.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${E.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(E.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${E.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(E.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${E.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${D[E.format]??U.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${U.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${V(U.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${U.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${U.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var m5=r(()=>{n()});function l5(_){let $=Math.abs(_),D=$%10,I=$%100;if(I>=11&&I<=19||D===0)return"many";if(D===1)return"one";return"few"}function pO(){return{localeError:gM()}}var XU=(_)=>{return _.charAt(0).toUpperCase()+_.slice(1)},gM=()=>{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 $(U,E,j,N){let A=_[U]??null;if(A===null)return A;return{unit:A.unit[E],verb:A.verb[N][j?"inclusive":"notInclusive"]}}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Gautas tipas ${N}, o tik\u0117tasi - instanceof ${U.expected}`;return`Gautas tipas ${N}, o tik\u0117tasi - ${E}`}case"invalid_value":if(U.values.length===1)return`Privalo b\u016Bti ${B(U.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${V(U.values,"|")} pasirinkim\u0173`;case"too_big":{let E=I[U.origin]??U.origin,j=$(U.origin,l5(Number(U.maximum)),U.inclusive??!1,"smaller");if(j?.verb)return`${XU(E??U.origin??"reik\u0161m\u0117")} ${j.verb} ${U.maximum.toString()} ${j.unit??"element\u0173"}`;let N=U.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${XU(E??U.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${U.maximum.toString()} ${j?.unit}`}case"too_small":{let E=I[U.origin]??U.origin,j=$(U.origin,l5(Number(U.minimum)),U.inclusive??!1,"bigger");if(j?.verb)return`${XU(E??U.origin??"reik\u0161m\u0117")} ${j.verb} ${U.minimum.toString()} ${j.unit??"element\u0173"}`;let N=U.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${XU(E??U.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${U.minimum.toString()} ${j?.unit}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${E.prefix}"`;if(E.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${E.suffix}"`;if(E.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${E.includes}"`;if(E.format==="regex")return`Eilut\u0117 privalo atitikti ${E.pattern}`;return`Neteisingas ${D[E.format]??U.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${U.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${U.keys.length>1?"i":"as"} rakt${U.keys.length>1?"ai":"as"}: ${V(U.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let E=I[U.origin]??U.origin;return`${XU(E??U.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var i5=r(()=>{n()});function eO(){return{localeError:AM()}}var AM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${U.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${E}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`}case"invalid_value":if(U.values.length===1)return`Invalid input: expected ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${U.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${U.origin} \u0434\u0430 \u0438\u043C\u0430 ${E}${U.minimum.toString()} ${j.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${U.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`Invalid ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`${U.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"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${U.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 ${U.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var t5=r(()=>{n()});function aO(){return{localeError:OM()}}var OM=()=>{let _={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"nombor"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Input tidak sah: dijangka instanceof ${U.expected}, diterima ${N}`;return`Input tidak sah: dijangka ${E}, diterima ${N}`}case"invalid_value":if(U.values.length===1)return`Input tidak sah: dijangka ${B(U.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Terlalu besar: dijangka ${U.origin??"nilai"} ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: dijangka ${U.origin??"nilai"} adalah ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Terlalu kecil: dijangka ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Terlalu kecil: dijangka ${U.origin} adalah ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`String tidak sah: mesti bermula dengan "${E.prefix}"`;if(E.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${E.suffix}"`;if(E.format==="includes")return`String tidak sah: mesti mengandungi "${E.includes}"`;if(E.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${E.pattern}`;return`${D[E.format]??U.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${U.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${V(U.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${U.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${U.origin}`;default:return"Input tidak sah"}}};var o5=r(()=>{n()});function sO(){return{localeError:SM()}}var SM=()=>{let _={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"getal"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ongeldige invoer: verwacht instanceof ${U.expected}, ontving ${N}`;return`Ongeldige invoer: verwacht ${E}, ontving ${N}`}case"invalid_value":if(U.values.length===1)return`Ongeldige invoer: verwacht ${B(U.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=U.origin==="date"?"laat":U.origin==="string"?"lang":"groot";if(j)return`Te ${N}: verwacht dat ${U.origin??"waarde"} ${E}${U.maximum.toString()} ${j.unit??"elementen"} ${j.verb}`;return`Te ${N}: verwacht dat ${U.origin??"waarde"} ${E}${U.maximum.toString()} is`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=U.origin==="date"?"vroeg":U.origin==="string"?"kort":"klein";if(j)return`Te ${N}: verwacht dat ${U.origin} ${E}${U.minimum.toString()} ${j.unit} ${j.verb}`;return`Te ${N}: verwacht dat ${U.origin} ${E}${U.minimum.toString()} is`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ongeldige tekst: moet met "${E.prefix}" beginnen`;if(E.format==="ends_with")return`Ongeldige tekst: moet op "${E.suffix}" eindigen`;if(E.format==="includes")return`Ongeldige tekst: moet "${E.includes}" bevatten`;if(E.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${E.pattern}`;return`Ongeldig: ${D[E.format]??U.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${U.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${U.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${U.origin}`;default:return"Ongeldige invoer"}}};var p5=r(()=>{n()});function _S(){return{localeError:LM()}}var LM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"tall",array:"liste"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ugyldig input: forventet instanceof ${U.expected}, fikk ${N}`;return`Ugyldig input: forventet ${E}, fikk ${N}`}case"invalid_value":if(U.values.length===1)return`Ugyldig verdi: forventet ${B(U.values[0])}`;return`Ugyldig valg: forventet en av ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`For stor(t): forventet ${U.origin??"value"} til \xE5 ha ${E}${U.maximum.toString()} ${j.unit??"elementer"}`;return`For stor(t): forventet ${U.origin??"value"} til \xE5 ha ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`For lite(n): forventet ${U.origin} til \xE5 ha ${E}${U.minimum.toString()} ${j.unit}`;return`For lite(n): forventet ${U.origin} til \xE5 ha ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${E.prefix}"`;if(E.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${E.suffix}"`;if(E.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${E.includes}"`;if(E.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${E.pattern}`;return`Ugyldig ${D[E.format]??U.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${U.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${U.origin}`;default:return"Ugyldig input"}}};var e5=r(()=>{n()});function $S(){return{localeError:JM()}}var JM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`F\xE2sit giren: umulan instanceof ${U.expected}, al\u0131nan ${N}`;return`F\xE2sit giren: umulan ${E}, al\u0131nan ${N}`}case"invalid_value":if(U.values.length===1)return`F\xE2sit giren: umulan ${B(U.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Fazla b\xFCy\xFCk: ${U.origin??"value"}, ${E}${U.maximum.toString()} ${j.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${U.origin??"value"}, ${E}${U.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Fazla k\xFC\xE7\xFCk: ${U.origin}, ${E}${U.minimum.toString()} ${j.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${U.origin}, ${E}${U.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`F\xE2sit metin: "${E.prefix}" ile ba\u015Flamal\u0131.`;if(E.format==="ends_with")return`F\xE2sit metin: "${E.suffix}" ile bitmeli.`;if(E.format==="includes")return`F\xE2sit metin: "${E.includes}" ihtiv\xE2 etmeli.`;if(E.format==="regex")return`F\xE2sit metin: ${E.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${D[E.format]??U.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${U.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${U.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var a5=r(()=>{n()});function DS(){return{localeError:WM()}}var WM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${U.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${E} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(U.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${B(U.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${V(U.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${U.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${U.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} \u0648\u064A`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} ${j.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} \u0648\u064A`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${E.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(E.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${E.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(E.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${E.includes}" \u0648\u0644\u0631\u064A`;if(E.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${E.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${D[E.format]??U.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${U.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${U.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${U.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 ${U.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var s5=r(()=>{n()});function US(){return{localeError:PM()}}var PM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"liczba",array:"tablica"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${U.expected}, otrzymano ${N}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${E}, otrzymano ${N}`}case"invalid_value":if(U.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${B(U.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${E}${U.maximum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${E}${U.minimum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${E.prefix}"`;if(E.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${E.suffix}"`;if(E.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${E.includes}"`;if(E.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${E.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${D[E.format]??U.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${U.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${U.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${U.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var _G=r(()=>{n()});function IS(){return{localeError:zM()}}var zM=()=>{let _={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Tipo inv\xE1lido: esperado instanceof ${U.expected}, recebido ${N}`;return`Tipo inv\xE1lido: esperado ${E}, recebido ${N}`}case"invalid_value":if(U.values.length===1)return`Entrada inv\xE1lida: esperado ${B(U.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Muito grande: esperado que ${U.origin??"valor"} tivesse ${E}${U.maximum.toString()} ${j.unit??"elementos"}`;return`Muito grande: esperado que ${U.origin??"valor"} fosse ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Muito pequeno: esperado que ${U.origin} tivesse ${E}${U.minimum.toString()} ${j.unit}`;return`Muito pequeno: esperado que ${U.origin} fosse ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${E.prefix}"`;if(E.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${E.suffix}"`;if(E.format==="includes")return`Texto inv\xE1lido: deve incluir "${E.includes}"`;if(E.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${E.pattern}`;return`${D[E.format]??U.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${U.divisor}`;case"unrecognized_keys":return`Chave${U.keys.length>1?"s":""} desconhecida${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${U.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${U.origin}`;default:return"Campo inv\xE1lido"}}};var $G=r(()=>{n()});function ES(){return{localeError:XM()}}var XM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;return`Intrare invalid\u0103: a\u0219teptat ${E}, primit ${N}`}case"invalid_value":if(U.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${B(U.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Prea mare: a\u0219teptat ca ${U.origin??"valoarea"} ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${U.origin??"valoarea"} s\u0103 fie ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Prea mic: a\u0219teptat ca ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Prea mic: a\u0219teptat ca ${U.origin} s\u0103 fie ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${E.prefix}"`;if(E.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${E.suffix}"`;if(E.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${E.includes}"`;if(E.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${E.pattern}`;return`Format invalid: ${D[E.format]??U.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${U.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${V(U.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${U.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${U.origin}`;default:return"Intrare invalid\u0103"}}};var DG=r(()=>{n()});function UG(_,$,D,I){let U=Math.abs(_),E=U%10,j=U%100;if(j>=11&&j<=19)return I;if(E===1)return $;if(E>=2&&E<=4)return D;return I}function jS(){return{localeError:GM()}}var GM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${U.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${E}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j){let N=Number(U.maximum),A=UG(N,j.unit.one,j.unit.few,j.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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${E}${U.maximum.toString()} ${A}`}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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j){let N=Number(U.minimum),A=UG(N,j.unit.one,j.unit.few,j.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 ${U.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${E}${U.minimum.toString()} ${A}`}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 ${U.origin} \u0431\u0443\u0434\u0435\u0442 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${U.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${U.keys.length>1?"\u0438":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${U.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 ${U.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 IG=r(()=>{n()});function NS(){return{localeError:RM()}}var RM=()=>{let _={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${U.expected}, prejeto ${N}`;return`Neveljaven vnos: pri\u010Dakovano ${E}, prejeto ${N}`}case"invalid_value":if(U.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${B(U.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Preveliko: pri\u010Dakovano, da bo ${U.origin??"vrednost"} imelo ${E}${U.maximum.toString()} ${j.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${U.origin??"vrednost"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Premajhno: pri\u010Dakovano, da bo ${U.origin} imelo ${E}${U.minimum.toString()} ${j.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${E.prefix}"`;if(E.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${E.suffix}"`;if(E.format==="includes")return`Neveljaven niz: mora vsebovati "${E.includes}"`;if(E.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${E.pattern}`;return`Neveljaven ${D[E.format]??U.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${U.divisor}`;case"unrecognized_keys":return`Neprepoznan${U.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${V(U.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${U.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${U.origin}`;default:return"Neveljaven vnos"}}};var EG=r(()=>{n()});function gS(){return{localeError:YM()}}var YM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"antal",array:"lista"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${U.expected}, fick ${N}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${E}, fick ${N}`}case"invalid_value":if(U.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${B(U.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${U.origin??"v\xE4rdet"} att ha ${E}${U.maximum.toString()} ${j.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${U.origin??"v\xE4rdet"} att ha ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${U.origin??"v\xE4rdet"} att ha ${E}${U.minimum.toString()} ${j.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${U.origin??"v\xE4rdet"} att ha ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${E.prefix}"`;if(E.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${E.suffix}"`;if(E.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${E.includes}"`;if(E.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${E.pattern}"`;return`Ogiltig(t) ${D[E.format]??U.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${U.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${U.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var jG=r(()=>{n()});function AS(){return{localeError:QM()}}var QM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`;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 ${E}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)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 ${U.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${E}${U.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)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 ${U.origin} ${E}${U.minimum.toString()} ${j.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 ${U.origin} ${E}${U.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${E.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(E.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${E.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(E.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${E.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(E.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${E.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 ${D[E.format]??U.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${U.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${U.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.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`${U.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 NG=r(()=>{n()});function OS(){return{localeError:KM()}}var KM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`;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 ${E} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`}case"invalid_value":if(U.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",j=$(U.origin);if(j)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.maximum.toString()} ${j.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",j=$(U.origin);if(j)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.minimum.toString()} ${j.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(E.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 ${E.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${D[E.format]??U.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 ${U.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: ${V(U.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${U.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 ${U.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var gG=r(()=>{n()});function SS(){return{localeError:TM()}}var TM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${U.expected}, al\u0131nan ${N}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${E}, al\u0131nan ${N}`}case"invalid_value":if(U.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${B(U.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\xC7ok b\xFCy\xFCk: beklenen ${U.origin??"de\u011Fer"} ${E}${U.maximum.toString()} ${j.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${U.origin??"de\u011Fer"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${U.origin} ${E}${U.minimum.toString()} ${j.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ge\xE7ersiz metin: "${E.prefix}" ile ba\u015Flamal\u0131`;if(E.format==="ends_with")return`Ge\xE7ersiz metin: "${E.suffix}" ile bitmeli`;if(E.format==="includes")return`Ge\xE7ersiz metin: "${E.includes}" i\xE7ermeli`;if(E.format==="regex")return`Ge\xE7ersiz metin: ${E.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${D[E.format]??U.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${U.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${U.keys.length>1?"lar":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${U.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var AG=r(()=>{n()});function GU(){return{localeError:FM()}}var FM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`;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 ${E}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`}case"invalid_value":if(U.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 ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${j.verb} ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.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 ${U.origin} \u0431\u0443\u0434\u0435 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${U.keys.length>1?"\u0456":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${U.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 ${U.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 LS=r(()=>{n()});function JS(){return GU()}var OG=r(()=>{LS()});function WS(){return{localeError:VM()}}var VM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${U.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${E} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(U.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${B(U.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${V(U.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${U.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${E}${U.maximum.toString()} ${j.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: ${U.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${E}${U.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${U.origin} \u06A9\u06D2 ${E}${U.minimum.toString()} ${j.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${U.origin} \u06A9\u0627 ${E}${U.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${E.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(E.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${E.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(E.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${E.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(E.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${E.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${D[E.format]??U.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${U.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${U.keys.length>1?"\u0632":""}: ${V(U.keys,"\u060C ")}`;case"invalid_key":return`${U.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${U.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var SG=r(()=>{n()});function PS(){return{localeError:BM()}}var BM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"raqam",array:"massiv"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${U.expected}, qabul qilingan ${N}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${E}, qabul qilingan ${N}`}case"invalid_value":if(U.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${B(U.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Juda katta: kutilgan ${U.origin??"qiymat"} ${E}${U.maximum.toString()} ${j.unit} ${j.verb}`;return`Juda katta: kutilgan ${U.origin??"qiymat"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Juda kichik: kutilgan ${U.origin} ${E}${U.minimum.toString()} ${j.unit} ${j.verb}`;return`Juda kichik: kutilgan ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${E.prefix}" bilan boshlanishi kerak`;if(E.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${E.suffix}" bilan tugashi kerak`;if(E.format==="includes")return`Noto\u2018g\u2018ri satr: "${E.includes}" ni o\u2018z ichiga olishi kerak`;if(E.format==="regex")return`Noto\u2018g\u2018ri satr: ${E.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${D[E.format]??U.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${U.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${U.keys.length>1?"lar":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${U.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var LG=r(()=>{n()});function zS(){return{localeError:MM()}}var MM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${U.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${E}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`}case"invalid_value":if(U.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${B(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${U.origin??"gi\xE1 tr\u1ECB"} ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${U.origin??"gi\xE1 tr\u1ECB"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${E.prefix}"`;if(E.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${E.suffix}"`;if(E.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${E.includes}"`;if(E.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${E.pattern}`;return`${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${V(U.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${U.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 ${U.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var JG=r(()=>{n()});function XS(){return{localeError:bM()}}var bM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${U.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${E}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`}case"invalid_value":if(U.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${B(U.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${U.origin??"\u503C"} ${E}${U.maximum.toString()} ${j.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${U.origin??"\u503C"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${U.origin} ${E}${U.minimum.toString()} ${j.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${E.prefix}" \u5F00\u5934`;if(E.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${E.suffix}" \u7ED3\u5C3E`;if(E.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${E.includes}"`;if(E.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${E.pattern}`;return`\u65E0\u6548${D[E.format]??U.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${U.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${U.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var WG=r(()=>{n()});function GS(){return{localeError:ZM()}}var ZM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${U.expected}\uFF0C\u4F46\u6536\u5230 ${N}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${E}\uFF0C\u4F46\u6536\u5230 ${N}`}case"invalid_value":if(U.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${B(U.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${U.origin??"\u503C"} \u61C9\u70BA ${E}${U.maximum.toString()} ${j.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${U.origin??"\u503C"} \u61C9\u70BA ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${U.origin} \u61C9\u70BA ${E}${U.minimum.toString()} ${j.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${U.origin} \u61C9\u70BA ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${E.prefix}" \u958B\u982D`;if(E.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${E.suffix}" \u7D50\u5C3E`;if(E.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${E.includes}"`;if(E.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${E.pattern}`;return`\u7121\u6548\u7684 ${D[E.format]??U.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${U.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${U.keys.length>1?"\u5011":""}\uFF1A${V(U.keys,"\u3001")}`;case"invalid_key":return`${U.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${U.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var PG=r(()=>{n()});function RS(){return{localeError:HM()}}var HM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=M(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${U.expected}, \xE0m\u1ECD\u0300 a r\xED ${N}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${E}, \xE0m\u1ECD\u0300 a r\xED ${N}`}case"invalid_value":if(U.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${B(U.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${U.origin??"iye"} ${j.verb} ${E}${U.maximum} ${j.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${E}${U.maximum}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${U.origin} ${j.verb} ${E}${U.minimum} ${j.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${E}${U.minimum}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${E.suffix}"`;if(E.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${E.includes}"`;if(E.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${E.pattern}`;return`A\u1E63\xEC\u1E63e: ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${V(U.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${U.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 ${U.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var zG=r(()=>{n()});var h0={};x$(h0,{zhTW:()=>GS,zhCN:()=>XS,yo:()=>RS,vi:()=>zS,uz:()=>PS,ur:()=>WS,uk:()=>GU,ua:()=>JS,tr:()=>SS,th:()=>OS,ta:()=>AS,sv:()=>gS,sl:()=>NS,ru:()=>jS,ro:()=>ES,pt:()=>IS,ps:()=>DS,pl:()=>US,ota:()=>$S,no:()=>_S,nl:()=>sO,ms:()=>aO,mk:()=>eO,lt:()=>pO,ko:()=>oO,km:()=>zU,kh:()=>tO,ka:()=>lO,ja:()=>mO,it:()=>dO,is:()=>nO,id:()=>cO,hy:()=>hO,hu:()=>yO,hr:()=>uO,he:()=>xO,frCA:()=>fO,fr:()=>rO,fi:()=>wO,fa:()=>vO,es:()=>CO,eo:()=>qO,en:()=>PU,el:()=>HO,de:()=>ZO,da:()=>bO,cs:()=>MO,ca:()=>BO,bg:()=>VO,be:()=>FO,az:()=>TO,ar:()=>KO});var YS=r(()=>{G5();R5();Q5();K5();T5();F5();V5();B5();M5();kO();b5();Z5();H5();k5();q5();C5();v5();w5();r5();x5();u5();y5();h5();c5();n5();d5();iO();m5();i5();t5();o5();p5();e5();a5();s5();_G();$G();DG();IG();EG();jG();NG();gG();AG();OG();LS();SG();LG();JG();WG();PG();zG()});class QS{constructor(){this._map=new WeakMap,this._idmap=new Map}add(_,...$){let D=$[0];if(this._map.set(_,D),D&&typeof D==="object"&&"id"in D)this._idmap.set(D.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 D={...this.get($)??{}};delete D.id;let I={...D,...this._map.get(_)};return Object.keys(I).length?I:void 0}return this._map.get(_)}has(_){return this._map.has(_)}}function RU(){return new QS}var XG,$E,DE,x_;var YU=r(()=>{$E=Symbol("ZodOutput"),DE=Symbol("ZodInput");(XG=globalThis).__zod_globalRegistry??(XG.__zod_globalRegistry=RU());x_=globalThis.__zod_globalRegistry});function KS(_,$){return new _({type:"string",...v($)})}function TS(_,$){return new _({type:"string",coerce:!0,...v($)})}function UE(_,$){return new _({type:"string",format:"email",check:"string_format",abort:!1,...v($)})}function QU(_,$){return new _({type:"string",format:"guid",check:"string_format",abort:!1,...v($)})}function IE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,...v($)})}function EE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v($)})}function jE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v($)})}function NE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v($)})}function KU(_,$){return new _({type:"string",format:"url",check:"string_format",abort:!1,...v($)})}function gE(_,$){return new _({type:"string",format:"emoji",check:"string_format",abort:!1,...v($)})}function AE(_,$){return new _({type:"string",format:"nanoid",check:"string_format",abort:!1,...v($)})}function OE(_,$){return new _({type:"string",format:"cuid",check:"string_format",abort:!1,...v($)})}function SE(_,$){return new _({type:"string",format:"cuid2",check:"string_format",abort:!1,...v($)})}function LE(_,$){return new _({type:"string",format:"ulid",check:"string_format",abort:!1,...v($)})}function JE(_,$){return new _({type:"string",format:"xid",check:"string_format",abort:!1,...v($)})}function WE(_,$){return new _({type:"string",format:"ksuid",check:"string_format",abort:!1,...v($)})}function PE(_,$){return new _({type:"string",format:"ipv4",check:"string_format",abort:!1,...v($)})}function zE(_,$){return new _({type:"string",format:"ipv6",check:"string_format",abort:!1,...v($)})}function FS(_,$){return new _({type:"string",format:"mac",check:"string_format",abort:!1,...v($)})}function XE(_,$){return new _({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v($)})}function GE(_,$){return new _({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v($)})}function RE(_,$){return new _({type:"string",format:"base64",check:"string_format",abort:!1,...v($)})}function YE(_,$){return new _({type:"string",format:"base64url",check:"string_format",abort:!1,...v($)})}function QE(_,$){return new _({type:"string",format:"e164",check:"string_format",abort:!1,...v($)})}function KE(_,$){return new _({type:"string",format:"jwt",check:"string_format",abort:!1,...v($)})}function VS(_,$){return new _({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v($)})}function BS(_,$){return new _({type:"string",format:"date",check:"string_format",...v($)})}function MS(_,$){return new _({type:"string",format:"time",check:"string_format",precision:null,...v($)})}function bS(_,$){return new _({type:"string",format:"duration",check:"string_format",...v($)})}function ZS(_,$){return new _({type:"number",checks:[],...v($)})}function HS(_,$){return new _({type:"number",coerce:!0,checks:[],...v($)})}function kS(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"safeint",...v($)})}function qS(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float32",...v($)})}function CS(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float64",...v($)})}function vS(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"int32",...v($)})}function wS(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"uint32",...v($)})}function rS(_,$){return new _({type:"boolean",...v($)})}function fS(_,$){return new _({type:"boolean",coerce:!0,...v($)})}function xS(_,$){return new _({type:"bigint",...v($)})}function uS(_,$){return new _({type:"bigint",coerce:!0,...v($)})}function yS(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...v($)})}function hS(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...v($)})}function cS(_,$){return new _({type:"symbol",...v($)})}function nS(_,$){return new _({type:"undefined",...v($)})}function dS(_,$){return new _({type:"null",...v($)})}function mS(_){return new _({type:"any"})}function lS(_){return new _({type:"unknown"})}function iS(_,$){return new _({type:"never",...v($)})}function tS(_,$){return new _({type:"void",...v($)})}function oS(_,$){return new _({type:"date",...v($)})}function pS(_,$){return new _({type:"date",coerce:!0,...v($)})}function eS(_,$){return new _({type:"nan",...v($)})}function V$(_,$){return new cI({check:"less_than",...v($),value:_,inclusive:!1})}function I$(_,$){return new cI({check:"less_than",...v($),value:_,inclusive:!0})}function B$(_,$){return new nI({check:"greater_than",...v($),value:_,inclusive:!1})}function c_(_,$){return new nI({check:"greater_than",...v($),value:_,inclusive:!0})}function TU(_){return B$(0,_)}function FU(_){return V$(0,_)}function VU(_){return I$(0,_)}function BU(_){return c_(0,_)}function L6(_,$){return new m2({check:"multiple_of",...v($),value:_})}function J6(_,$){return new t2({check:"max_size",...v($),maximum:_})}function M$(_,$){return new o2({check:"min_size",...v($),minimum:_})}function f6(_,$){return new p2({check:"size_equals",...v($),size:_})}function x6(_,$){return new e2({check:"max_length",...v($),maximum:_})}function l$(_,$){return new a2({check:"min_length",...v($),minimum:_})}function u6(_,$){return new s2({check:"length_equals",...v($),length:_})}function Q4(_,$){return new _A({check:"string_format",format:"regex",...v($),pattern:_})}function K4(_){return new $A({check:"string_format",format:"lowercase",...v(_)})}function T4(_){return new DA({check:"string_format",format:"uppercase",...v(_)})}function F4(_,$){return new UA({check:"string_format",format:"includes",...v($),includes:_})}function V4(_,$){return new IA({check:"string_format",format:"starts_with",...v($),prefix:_})}function B4(_,$){return new EA({check:"string_format",format:"ends_with",...v($),suffix:_})}function MU(_,$,D){return new jA({check:"property",property:_,schema:$,...v(D)})}function M4(_,$){return new NA({check:"mime_type",mime:_,...v($)})}function X$(_){return new gA({check:"overwrite",tx:_})}function b4(_){return X$(($)=>$.normalize(_))}function Z4(){return X$((_)=>_.trim())}function H4(){return X$((_)=>_.toLowerCase())}function k4(){return X$((_)=>_.toUpperCase())}function q4(){return X$((_)=>I2(_))}function aS(_,$,D){return new _({type:"array",element:$,...v(D)})}function qM(_,$,D){return new _({type:"union",options:$,...v(D)})}function CM(_,$,D){return new _({type:"union",options:$,inclusive:!1,...v(D)})}function vM(_,$,D,I){return new _({type:"union",options:D,discriminator:$,...v(I)})}function wM(_,$,D){return new _({type:"intersection",left:$,right:D})}function rM(_,$,D,I){let U=D instanceof o;return new _({type:"tuple",items:$,rest:U?D:null,...v(U?I:D)})}function fM(_,$,D,I){return new _({type:"record",keyType:$,valueType:D,...v(I)})}function xM(_,$,D,I){return new _({type:"map",keyType:$,valueType:D,...v(I)})}function uM(_,$,D){return new _({type:"set",valueType:$,...v(D)})}function yM(_,$,D){let I=Array.isArray($)?Object.fromEntries($.map((U)=>[U,U])):$;return new _({type:"enum",entries:I,...v(D)})}function hM(_,$,D){return new _({type:"enum",entries:$,...v(D)})}function cM(_,$,D){return new _({type:"literal",values:Array.isArray($)?$:[$],...v(D)})}function sS(_,$){return new _({type:"file",...v($)})}function nM(_,$){return new _({type:"transform",transform:$})}function dM(_,$){return new _({type:"optional",innerType:$})}function mM(_,$){return new _({type:"nullable",innerType:$})}function lM(_,$,D){return new _({type:"default",innerType:$,get defaultValue(){return typeof D==="function"?D():j2(D)}})}function iM(_,$,D){return new _({type:"nonoptional",innerType:$,...v(D)})}function tM(_,$){return new _({type:"success",innerType:$})}function oM(_,$,D){return new _({type:"catch",innerType:$,catchValue:typeof D==="function"?D:()=>D})}function pM(_,$,D){return new _({type:"pipe",in:$,out:D})}function eM(_,$){return new _({type:"readonly",innerType:$})}function aM(_,$,D){return new _({type:"template_literal",parts:$,...v(D)})}function sM(_,$){return new _({type:"lazy",getter:$})}function _b(_,$){return new _({type:"promise",innerType:$})}function _L(_,$,D){let I=v(D);return I.abort??(I.abort=!0),new _({type:"custom",check:"custom",fn:$,...I})}function $L(_,$,D){return new _({type:"custom",check:"custom",fn:$,...v(D)})}function DL(_,$){let D=GG((I)=>{return I.addIssue=(U)=>{if(typeof U==="string")I.issues.push(q0(U,I.value,D._zod.def));else{let E=U;if(E.fatal)E.continue=!1;E.code??(E.code="custom"),E.input??(E.input=I.value),E.inst??(E.inst=D),E.continue??(E.continue=!D._zod.def.abort),I.issues.push(q0(E))}},_(I.value,I)},$);return D}function GG(_,$){let D=new Q_({check:"custom",...v($)});return D._zod.check=_,D}function UL(_){let $=new Q_({check:"describe"});return $._zod.onattach=[(D)=>{let I=x_.get(D)??{};x_.add(D,{...I,description:_})}],$._zod.check=()=>{},$}function IL(_){let $=new Q_({check:"meta"});return $._zod.onattach=[(D)=>{let I=x_.get(D)??{};x_.add(D,{...I,..._})}],$._zod.check=()=>{},$}function EL(_,$){let D=v($),I=D.truthy??["true","1","yes","on","y","enabled"],U=D.falsy??["false","0","no","off","n","disabled"];if(D.case!=="sensitive")I=I.map((z)=>typeof z==="string"?z.toLowerCase():z),U=U.map((z)=>typeof z==="string"?z.toLowerCase():z);let E=new Set(I),j=new Set(U),N=_.Codec??WU,A=_.Boolean??LU,S=new(_.String??Y4)({type:"string",error:D.error}),L=new A({type:"boolean",error:D.error}),P=new N({type:"pipe",in:S,out:L,transform:(z,G)=>{let J=z;if(D.case!=="sensitive")J=J.toLowerCase();if(E.has(J))return!0;else if(j.has(J))return!1;else return G.issues.push({code:"invalid_value",expected:"stringbool",values:[...E,...j],input:G.value,inst:P,continue:!1}),{}},reverseTransform:(z,G)=>{if(z===!0)return I[0]||"true";else return U[0]||"false"},error:D.error});return P}function c0(_,$,D,I={}){let U=v(I),E={...v(I),check:"string_format",type:"string",format:$,fn:typeof D==="function"?D:(N)=>D.test(N),...U};if(D instanceof RegExp)E.pattern=D;return new _(E)}var TE;var RG=r(()=>{dI();YU();QO();n();TE={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function y6(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";return{processors:_.processors??{},metadataRegistry:_?.metadata??x_,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_(_,$,D={path:[],schemaPath:[]}){var I;let U=_._zod.def,E=$.seen.get(_);if(E){if(E.count++,D.schemaPath.includes(_))E.cycle=D.path;return E.schema}let j={schema:{},count:1,cycle:void 0,path:D.path};$.seen.set(_,j);let N=_._zod.toJSONSchema?.();if(N)j.schema=N;else{let S={...D,schemaPath:[...D.schemaPath,_],path:D.path};if(_._zod.processJSONSchema)_._zod.processJSONSchema($,j.schema,S);else{let P=j.schema,z=$.processors[U.type];if(!z)throw Error(`[toJSONSchema]: Non-representable type encountered: ${U.type}`);z(_,$,P,S)}let L=_._zod.parent;if(L){if(!j.ref)j.ref=L;L_(L,$,S),$.seen.get(L).isParent=!0}}let A=$.metadataRegistry.get(_);if(A)Object.assign(j.schema,A);if($.io==="input"&&o_(_))delete j.schema.examples,delete j.schema.default;if($.io==="input"&&"_prefault"in j.schema)(I=j.schema).default??(I.default=j.schema._prefault);return delete j.schema._prefault,$.seen.get(_).schema}function h6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let I=new Map;for(let j of _.seen.entries()){let N=_.metadataRegistry.get(j[0])?.id;if(N){let A=I.get(N);if(A&&A!==j[0])throw Error(`Duplicate schema id "${N}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);I.set(N,j[0])}}let U=(j)=>{let N=_.target==="draft-2020-12"?"$defs":"definitions";if(_.external){let L=_.external.registry.get(j[0])?.id,P=_.external.uri??((G)=>G);if(L)return{ref:P(L)};let z=j[1].defId??j[1].schema.id??`schema${_.counter++}`;return j[1].defId=z,{defId:z,ref:`${P("__shared")}#/${N}/${z}`}}if(j[1]===D)return{ref:"#"};let O=`${"#"}/${N}/`,S=j[1].schema.id??`__schema${_.counter++}`;return{defId:S,ref:O+S}},E=(j)=>{if(j[1].schema.$ref)return;let N=j[1],{ref:A,defId:O}=U(j);if(N.def={...N.schema},O)N.defId=O;let S=N.schema;for(let L in S)delete S[L];S.$ref=A};if(_.cycles==="throw")for(let j of _.seen.entries()){let N=j[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/ + `)}z.write("payload.value = newResult;"),z.write("return payload;");let R=z.compile();return(T,Y)=>R(g,T,Y)},E,j=R4,N=!g4.jitless,S=N&&EA.value,L=$.catchall,W;_._zod.parse=(g,z)=>{W??(W=I.value);let G=g.value;if(!j(G))return g.issues.push({expected:"object",code:"invalid_type",input:G,inst:_}),g;if(N&&S&&z?.async===!1&&z.jitless!==!0){if(!E)E=U($.shape);if(g=E(g,z),!L)return g;return X5([],G,g,z,W,_)}return D(g,z)}});JU=K("$ZodUnion",(_,$)=>{p.init(_,$),D_(_._zod,"optin",()=>$.options.some((I)=>I._zod.optin==="optional")?"optional":void 0),D_(_._zod,"optout",()=>$.options.some((I)=>I._zod.optout==="optional")?"optional":void 0),D_(_._zod,"values",()=>{if($.options.every((I)=>I._zod.values))return new Set($.options.flatMap((I)=>Array.from(I._zod.values)));return}),D_(_._zod,"pattern",()=>{if($.options.every((I)=>I._zod.pattern)){let I=$.options.map((U)=>U._zod.pattern);return new RegExp(`^(${I.map((U)=>IU(U.source)).join("|")})$`)}return});let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(I,U)=>{if(D)return D(I,U);let E=!1,j=[];for(let N of $.options){let O=N._zod.run({value:I.value,issues:[]},U);if(O instanceof Promise)j.push(O),E=!0;else{if(O.issues.length===0)return O;j.push(O)}}if(!E)return $5(j,I,_,U);return Promise.all(j).then((N)=>{return $5(N,I,_,U)})}});pO=K("$ZodXor",(_,$)=>{JU.init(_,$),$.inclusive=!1;let D=$.options.length===1?$.options[0]._zod.run:null;_._zod.parse=(I,U)=>{if(D)return D(I,U);let E=!1,j=[];for(let N of $.options){let O=N._zod.run({value:I.value,issues:[]},U);if(O instanceof Promise)j.push(O),E=!0;else j.push(O)}if(!E)return D5(j,I,_,U);return Promise.all(j).then((N)=>{return D5(N,I,_,U)})}}),eO=K("$ZodDiscriminatedUnion",(_,$)=>{$.inclusive=!1,JU.init(_,$);let D=_._zod.parse;D_(_._zod,"propValues",()=>{let U={};for(let E of $.options){let j=E._zod.propValues;if(!j||Object.keys(j).length===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(E)}"`);for(let[N,O]of Object.entries(j)){if(!U[N])U[N]=new Set;for(let S of O)U[N].add(S)}}return U});let I=C0(()=>{let U=$.options,E=new Map;for(let j of U){let N=j._zod.propValues?.[$.discriminator];if(!N||N.size===0)throw Error(`Invalid discriminated union option at index "${$.options.indexOf(j)}"`);for(let O of N){if(E.has(O))throw Error(`Duplicate discriminator value "${String(O)}"`);E.set(O,j)}}return E});_._zod.parse=(U,E)=>{let j=U.value;if(!R4(j))return U.issues.push({code:"invalid_type",expected:"object",input:j,inst:_}),U;let N=I.value.get(j?.[$.discriminator]);if(N)return N._zod.run(U,E);if($.unionFallback||E.direction==="backward")return D(U,E);return U.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:$.discriminator,options:Array.from(I.value.keys()),input:j,path:[$.discriminator],inst:_}),U}}),aO=K("$ZodIntersection",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value,E=$.left._zod.run({value:U,issues:[]},I),j=$.right._zod.run({value:U,issues:[]},I);if(E instanceof Promise||j instanceof Promise)return Promise.all([E,j]).then(([O,S])=>{return U5(D,O,S)});return U5(D,E,j)}});sI=K("$ZodTuple",(_,$)=>{p.init(_,$);let D=$.items;_._zod.parse=(I,U)=>{let E=I.value;if(!Array.isArray(E))return I.issues.push({input:E,inst:_,expected:"tuple",code:"invalid_type"}),I;I.value=[];let j=[],N=I5(D,"optin"),O=I5(D,"optout");if(!$.rest){if(E.lengthD.length)I.issues.push({code:"too_big",maximum:D.length,inclusive:!0,input:E,inst:_,origin:"array"})}let S=Array(D.length);for(let L=0;L{S[L]=g}));else S[L]=W}if($.rest){let L=D.length-1,W=E.slice(D.length);for(let g of W){L++;let z=$.rest._zod.run({value:g,issues:[]},U);if(z instanceof Promise)j.push(z.then((G)=>E5(G,I,L)));else E5(z,I,L)}}if(j.length)return Promise.all(j).then(()=>j5(S,I,D,E,O));return j5(S,I,D,E,O)}});sO=K("$ZodRecord",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!w6(U))return D.issues.push({expected:"record",code:"invalid_type",input:U,inst:_}),D;let E=[],j=$.keyType._zod.values;if(j){D.value={};let N=new Set;for(let S of j)if(typeof S==="string"||typeof S==="number"||typeof S==="symbol"){N.add(typeof S==="number"?S.toString():S);let L=$.keyType._zod.run({value:S,issues:[]},I);if(L instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(L.issues.length){D.issues.push({code:"invalid_key",origin:"record",issues:L.issues.map((z)=>t_(z,I,b_())),input:S,path:[S],inst:_});continue}let W=L.value,g=$.valueType._zod.run({value:U[S],issues:[]},I);if(g instanceof Promise)E.push(g.then((z)=>{if(z.issues.length)D.issues.push(...$$(S,z.issues));D.value[W]=z.value}));else{if(g.issues.length)D.issues.push(...$$(S,g.issues));D.value[W]=g.value}}let O;for(let S in U)if(!N.has(S))O=O??[],O.push(S);if(O&&O.length>0)D.issues.push({code:"unrecognized_keys",input:U,inst:_,keys:O})}else{D.value={};for(let N of Reflect.ownKeys(U)){if(N==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(U,N))continue;let O=$.keyType._zod.run({value:N,issues:[]},I);if(O instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof N==="string"&&OU.test(N)&&O.issues.length){let W=$.keyType._zod.run({value:Number(N),issues:[]},I);if(W instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(W.issues.length===0)O=W}if(O.issues.length){if($.mode==="loose")D.value[N]=U[N];else D.issues.push({code:"invalid_key",origin:"record",issues:O.issues.map((W)=>t_(W,I,b_())),input:N,path:[N],inst:_});continue}let L=$.valueType._zod.run({value:U[N],issues:[]},I);if(L instanceof Promise)E.push(L.then((W)=>{if(W.issues.length)D.issues.push(...$$(N,W.issues));D.value[O.value]=W.value}));else{if(L.issues.length)D.issues.push(...$$(N,L.issues));D.value[O.value]=L.value}}}if(E.length)return Promise.all(E).then(()=>D);return D}}),_S=K("$ZodMap",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!(U instanceof Map))return D.issues.push({expected:"map",code:"invalid_type",input:U,inst:_}),D;let E=[];D.value=new Map;for(let[j,N]of U){let O=$.keyType._zod.run({value:j,issues:[]},I),S=$.valueType._zod.run({value:N,issues:[]},I);if(O instanceof Promise||S instanceof Promise)E.push(Promise.all([O,S]).then(([L,W])=>{N5(L,W,D,j,U,_,I)}));else N5(O,S,D,j,U,_,I)}if(E.length)return Promise.all(E).then(()=>D);return D}});$S=K("$ZodSet",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(!(U instanceof Set))return D.issues.push({input:U,inst:_,expected:"set",code:"invalid_type"}),D;let E=[];D.value=new Set;for(let j of U){let N=$.valueType._zod.run({value:j,issues:[]},I);if(N instanceof Promise)E.push(N.then((O)=>A5(O,D)));else A5(N,D)}if(E.length)return Promise.all(E).then(()=>D);return D}});DS=K("$ZodEnum",(_,$)=>{p.init(_,$);let D=UU($.entries),I=new Set(D);_._zod.values=I,_._zod.pattern=new RegExp(`^(${D.filter((U)=>EU.has(typeof U)).map((U)=>typeof U==="string"?g$(U):U.toString()).join("|")})$`),_._zod.parse=(U,E)=>{let j=U.value;if(I.has(j))return U;return U.issues.push({code:"invalid_value",values:D,input:j,inst:_}),U}}),US=K("$ZodLiteral",(_,$)=>{if(p.init(_,$),$.values.length===0)throw Error("Cannot create literal schema with no valid values");let D=new Set($.values);_._zod.values=D,_._zod.pattern=new RegExp(`^(${$.values.map((I)=>typeof I==="string"?g$(I):I?g$(I.toString()):String(I)).join("|")})$`),_._zod.parse=(I,U)=>{let E=I.value;if(D.has(E))return I;return I.issues.push({code:"invalid_value",values:$.values,input:E,inst:_}),I}}),IS=K("$ZodFile",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{let U=D.value;if(U instanceof File)return D;return D.issues.push({expected:"file",code:"invalid_type",input:U,inst:_}),D}}),ES=K("$ZodTransform",(_,$)=>{p.init(_,$),_._zod.optin="optional",_._zod.parse=(D,I)=>{if(I.direction==="backward")throw new X4(_.constructor.name);let U=$.transform(D.value,D);if(I.async)return(U instanceof Promise?U:Promise.resolve(U)).then((j)=>{return D.value=j,D.fallback=!0,D});if(U instanceof Promise)throw new m$;return D.value=U,D.fallback=!0,D}});_E=K("$ZodOptional",(_,$)=>{p.init(_,$),_._zod.optin="optional",_._zod.optout="optional",D_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,void 0]):void 0}),D_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${IU(D.source)})?$`):void 0}),_._zod.parse=(D,I)=>{if($.innerType._zod.optin==="optional"){let U=D.value,E=$.innerType._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>O5(j,U));return O5(E,U)}if(D.value===void 0)return D;return $.innerType._zod.run(D,I)}}),jS=K("$ZodExactOptional",(_,$)=>{_E.init(_,$),D_(_._zod,"values",()=>$.innerType._zod.values),D_(_._zod,"pattern",()=>$.innerType._zod.pattern),_._zod.parse=(D,I)=>{return $.innerType._zod.run(D,I)}}),NS=K("$ZodNullable",(_,$)=>{p.init(_,$),D_(_._zod,"optin",()=>$.innerType._zod.optin),D_(_._zod,"optout",()=>$.innerType._zod.optout),D_(_._zod,"pattern",()=>{let D=$.innerType._zod.pattern;return D?new RegExp(`^(${IU(D.source)}|null)$`):void 0}),D_(_._zod,"values",()=>{return $.innerType._zod.values?new Set([...$.innerType._zod.values,null]):void 0}),_._zod.parse=(D,I)=>{if(D.value===null)return D;return $.innerType._zod.run(D,I)}}),AS=K("$ZodDefault",(_,$)=>{p.init(_,$),_._zod.optin="optional",D_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);if(D.value===void 0)return D.value=$.defaultValue,D;let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>S5(E,$));return S5(U,$)}});OS=K("$ZodPrefault",(_,$)=>{p.init(_,$),_._zod.optin="optional",D_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);if(D.value===void 0)D.value=$.defaultValue;return $.innerType._zod.run(D,I)}}),SS=K("$ZodNonOptional",(_,$)=>{p.init(_,$),D_(_._zod,"values",()=>{let D=$.innerType._zod.values;return D?new Set([...D].filter((I)=>I!==void 0)):void 0}),_._zod.parse=(D,I)=>{let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>L5(E,_));return L5(U,_)}});LS=K("$ZodSuccess",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{if(I.direction==="backward")throw new X4("ZodSuccess");let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>{return D.value=E.issues.length===0,D});return D.value=U.issues.length===0,D}}),WS=K("$ZodCatch",(_,$)=>{p.init(_,$),_._zod.optin="optional",D_(_._zod,"optout",()=>$.innerType._zod.optout),D_(_._zod,"values",()=>$.innerType._zod.values),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>{if(D.value=E.value,E.issues.length)D.value=$.catchValue({...D,error:{issues:E.issues.map((j)=>t_(j,I,b_()))},input:D.value}),D.issues=[],D.fallback=!0;return D});if(D.value=U.value,U.issues.length)D.value=$.catchValue({...D,error:{issues:U.issues.map((E)=>t_(E,I,b_()))},input:D.value}),D.issues=[],D.fallback=!0;return D}}),JS=K("$ZodNaN",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{if(typeof D.value!=="number"||!Number.isNaN(D.value))return D.issues.push({input:D.value,inst:_,expected:"nan",code:"invalid_type"}),D;return D}}),$E=K("$ZodPipe",(_,$)=>{p.init(_,$),D_(_._zod,"values",()=>$.in._zod.values),D_(_._zod,"optin",()=>$.in._zod.optin),D_(_._zod,"optout",()=>$.out._zod.optout),D_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,I)=>{if(I.direction==="backward"){let E=$.out._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>iI(j,$.in,I));return iI(E,$.in,I)}let U=$.in._zod.run(D,I);if(U instanceof Promise)return U.then((E)=>iI(E,$.out,I));return iI(U,$.out,I)}});PU=K("$ZodCodec",(_,$)=>{p.init(_,$),D_(_._zod,"values",()=>$.in._zod.values),D_(_._zod,"optin",()=>$.in._zod.optin),D_(_._zod,"optout",()=>$.out._zod.optout),D_(_._zod,"propValues",()=>$.in._zod.propValues),_._zod.parse=(D,I)=>{if((I.direction||"forward")==="forward"){let E=$.in._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>tI(j,$,I));return tI(E,$,I)}else{let E=$.out._zod.run(D,I);if(E instanceof Promise)return E.then((j)=>tI(j,$,I));return tI(E,$,I)}}});PS=K("$ZodPreprocess",(_,$)=>{$E.init(_,$)}),zS=K("$ZodReadonly",(_,$)=>{p.init(_,$),D_(_._zod,"propValues",()=>$.innerType._zod.propValues),D_(_._zod,"values",()=>$.innerType._zod.values),D_(_._zod,"optin",()=>$.innerType?._zod?.optin),D_(_._zod,"optout",()=>$.innerType?._zod?.optout),_._zod.parse=(D,I)=>{if(I.direction==="backward")return $.innerType._zod.run(D,I);let U=$.innerType._zod.run(D,I);if(U instanceof Promise)return U.then(W5);return W5(U)}});gS=K("$ZodTemplateLiteral",(_,$)=>{p.init(_,$);let D=[];for(let I of $.parts)if(typeof I==="object"&&I!==null){if(!I._zod.pattern)throw Error(`Invalid template literal part, no pattern found: ${[...I._zod.traits].shift()}`);let U=I._zod.pattern instanceof RegExp?I._zod.pattern.source:I._zod.pattern;if(!U)throw Error(`Invalid template literal part: ${I._zod.traits}`);let E=U.startsWith("^")?1:0,j=U.endsWith("$")?U.length-1:U.length;D.push(U.slice(E,j))}else if(I===null||NA.has(typeof I))D.push(g$(`${I}`));else throw Error(`Invalid template literal part: ${I}`);_._zod.pattern=new RegExp(`^${D.join("")}$`),_._zod.parse=(I,U)=>{if(typeof I.value!=="string")return I.issues.push({input:I.value,inst:_,expected:"string",code:"invalid_type"}),I;if(_._zod.pattern.lastIndex=0,!_._zod.pattern.test(I.value))return I.issues.push({input:I.value,inst:_,code:"invalid_format",format:$.format??"template_literal",pattern:_._zod.pattern.source}),I;return I}}),XS=K("$ZodFunction",(_,$)=>{return p.init(_,$),_._def=$,_._zod.def=$,_.implement=(D)=>{if(typeof D!=="function")throw Error("implement() must be called with a function");return function(...I){let U=_._def.input?qI(_._def.input,I):I,E=Reflect.apply(D,this,U);if(_._def.output)return qI(_._def.output,E);return E}},_.implementAsync=(D)=>{if(typeof D!=="function")throw Error("implementAsync() must be called with a function");return async function(...I){let U=_._def.input?await kI(_._def.input,I):I,E=await Reflect.apply(D,this,U);if(_._def.output)return await kI(_._def.output,E);return E}},_._zod.parse=(D,I)=>{if(typeof D.value!=="function")return D.issues.push({code:"invalid_type",expected:"function",input:D.value,inst:_}),D;if(_._def.output&&_._def.output._zod.def.type==="promise")D.value=_.implementAsync(D.value);else D.value=_.implement(D.value);return D},_.input=(...D)=>{let I=_.constructor;if(Array.isArray(D[0]))return new I({type:"function",input:new sI({type:"tuple",items:D[0],rest:D[1]}),output:_._def.output});return new I({type:"function",input:D[0],output:_._def.output})},_.output=(D)=>{return new _.constructor({type:"function",input:_._def.input,output:D})},_}),GS=K("$ZodPromise",(_,$)=>{p.init(_,$),_._zod.parse=(D,I)=>{return Promise.resolve(D.value).then((U)=>$.innerType._zod.run({value:U,issues:[]},I))}}),RS=K("$ZodLazy",(_,$)=>{p.init(_,$),D_(_._zod,"innerType",()=>{let D=$;if(!D._cachedInner)D._cachedInner=$.getter();return D._cachedInner}),D_(_._zod,"pattern",()=>_._zod.innerType?._zod?.pattern),D_(_._zod,"propValues",()=>_._zod.innerType?._zod?.propValues),D_(_._zod,"optin",()=>_._zod.innerType?._zod?.optin??void 0),D_(_._zod,"optout",()=>_._zod.innerType?._zod?.optout??void 0),_._zod.parse=(D,I)=>{return _._zod.innerType._zod.run(D,I)}}),YS=K("$ZodCustom",(_,$)=>{Q_.init(_,$),p.init(_,$),_._zod.parse=(D,I)=>{return D},_._zod.check=(D)=>{let I=D.value,U=$.fn(I);if(U instanceof Promise)return U.then((E)=>J5(E,D,I,_));J5(U,D,I,_);return}})});function KS(){return{localeError:wB()}}var wB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`;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 ${E}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${N}`}case"invalid_value":if(U.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 ${M(U.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: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${U.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${E} ${U.maximum.toString()} ${j.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 ${U.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${U.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${E} ${U.minimum.toString()} ${j.unit}`;return`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${U.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${U.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${U.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${U.keys.length>1?"\u0629":""}: ${V(U.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${U.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 ${U.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}};var R5=r(()=>{n()});function TS(){return{localeError:rB()}}var rB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${U.expected}, daxil olan ${N}`;return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${E}, daxil olan ${N}`}case"invalid_value":if(U.values.length===1)return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${M(U.values[0])}`;return`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${U.origin??"d\u0259y\u0259r"} ${E}${U.maximum.toString()} ${j.unit??"element"}`;return`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${U.origin??"d\u0259y\u0259r"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${U.origin} ${E}${U.minimum.toString()} ${j.unit}`;return`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Yanl\u0131\u015F m\u0259tn: "${E.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;if(E.format==="ends_with")return`Yanl\u0131\u015F m\u0259tn: "${E.suffix}" il\u0259 bitm\u0259lidir`;if(E.format==="includes")return`Yanl\u0131\u015F m\u0259tn: "${E.includes}" daxil olmal\u0131d\u0131r`;if(E.format==="regex")return`Yanl\u0131\u015F m\u0259tn: ${E.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;return`Yanl\u0131\u015F ${D[E.format]??U.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${U.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${U.keys.length>1?"lar":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${U.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}};var Y5=r(()=>{n()});function Q5(_,$,D,I){let U=Math.abs(_),E=U%10,j=U%100;if(j>=11&&j<=19)return I;if(E===1)return $;if(E>=2&&E<=4)return D;return I}function FS(){return{localeError:fB()}}var fB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${E}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j){let N=Number(U.maximum),O=Q5(N,j.unit.one,j.unit.few,j.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 ${U.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${E}${U.maximum.toString()} ${O}`}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 ${U.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j){let N=Number(U.minimum),O=Q5(N,j.unit.one,j.unit.few,j.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 ${U.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${j.verb} ${E}${U.minimum.toString()} ${O}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${U.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${U.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${U.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 ${U.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}};var K5=r(()=>{n()});function VS(){return{localeError:xB()}}var xB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${U.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`;return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${E}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${N}`}case"invalid_value":if(U.values.length===1)return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${U.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${U.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${E}${U.minimum.toString()} ${j.unit}`;return`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${U.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;let j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";if(E.format==="emoji")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(E.format==="datetime")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(E.format==="date")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";if(E.format==="time")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";if(E.format==="duration")j="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";return`${j} ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${U.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${U.keys.length>1?"\u043E\u0432\u0435":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${U.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 ${U.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}};var T5=r(()=>{n()});function BS(){return{localeError:uB()}}var uB=()=>{let _={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Tipus inv\xE0lid: s'esperava instanceof ${U.expected}, s'ha rebut ${N}`;return`Tipus inv\xE0lid: s'esperava ${E}, s'ha rebut ${N}`}case"invalid_value":if(U.values.length===1)return`Valor inv\xE0lid: s'esperava ${M(U.values[0])}`;return`Opci\xF3 inv\xE0lida: s'esperava una de ${V(U.values," o ")}`;case"too_big":{let E=U.inclusive?"com a m\xE0xim":"menys de",j=$(U.origin);if(j)return`Massa gran: s'esperava que ${U.origin??"el valor"} contingu\xE9s ${E} ${U.maximum.toString()} ${j.unit??"elements"}`;return`Massa gran: s'esperava que ${U.origin??"el valor"} fos ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?"com a m\xEDnim":"m\xE9s de",j=$(U.origin);if(j)return`Massa petit: s'esperava que ${U.origin} contingu\xE9s ${E} ${U.minimum.toString()} ${j.unit}`;return`Massa petit: s'esperava que ${U.origin} fos ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Format inv\xE0lid: ha de comen\xE7ar amb "${E.prefix}"`;if(E.format==="ends_with")return`Format inv\xE0lid: ha d'acabar amb "${E.suffix}"`;if(E.format==="includes")return`Format inv\xE0lid: ha d'incloure "${E.includes}"`;if(E.format==="regex")return`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${E.pattern}`;return`Format inv\xE0lid per a ${D[E.format]??U.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${U.divisor}`;case"unrecognized_keys":return`Clau${U.keys.length>1?"s":""} no reconeguda${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${U.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${U.origin}`;default:return"Entrada inv\xE0lida"}}};var F5=r(()=>{n()});function MS(){return{localeError:yB()}}var yB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${U.expected}, obdr\u017Eeno ${N}`;return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${E}, obdr\u017Eeno ${N}`}case"invalid_value":if(U.values.length===1)return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${M(U.values[0])}`;return`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${U.origin??"hodnota"} mus\xED m\xEDt ${E}${U.maximum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${U.origin??"hodnota"} mus\xED b\xFDt ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${U.origin??"hodnota"} mus\xED m\xEDt ${E}${U.minimum.toString()} ${j.unit??"prvk\u016F"}`;return`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${U.origin??"hodnota"} mus\xED b\xFDt ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${E.prefix}"`;if(E.format==="ends_with")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${E.suffix}"`;if(E.format==="includes")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${E.includes}"`;if(E.format==="regex")return`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${E.pattern}`;return`Neplatn\xFD form\xE1t ${D[E.format]??U.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${U.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${V(U.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${U.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${U.origin}`;default:return"Neplatn\xFD vstup"}}};var V5=r(()=>{n()});function ZS(){return{localeError:hB()}}var hB=()=>{let _={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ugyldigt input: forventede instanceof ${U.expected}, fik ${N}`;return`Ugyldigt input: forventede ${E}, fik ${N}`}case"invalid_value":if(U.values.length===1)return`Ugyldig v\xE6rdi: forventede ${M(U.values[0])}`;return`Ugyldigt valg: forventede en af f\xF8lgende ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`For stor: forventede ${N??"value"} ${j.verb} ${E} ${U.maximum.toString()} ${j.unit??"elementer"}`;return`For stor: forventede ${N??"value"} havde ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`For lille: forventede ${N} ${j.verb} ${E} ${U.minimum.toString()} ${j.unit}`;return`For lille: forventede ${N} havde ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ugyldig streng: skal starte med "${E.prefix}"`;if(E.format==="ends_with")return`Ugyldig streng: skal ende med "${E.suffix}"`;if(E.format==="includes")return`Ugyldig streng: skal indeholde "${E.includes}"`;if(E.format==="regex")return`Ugyldig streng: skal matche m\xF8nsteret ${E.pattern}`;return`Ugyldig ${D[E.format]??U.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${U.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${U.origin}`;default:return"Ugyldigt input"}}};var B5=r(()=>{n()});function HS(){return{localeError:cB()}}var cB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"Zahl",array:"Array"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ung\xFCltige Eingabe: erwartet instanceof ${U.expected}, erhalten ${N}`;return`Ung\xFCltige Eingabe: erwartet ${E}, erhalten ${N}`}case"invalid_value":if(U.values.length===1)return`Ung\xFCltige Eingabe: erwartet ${M(U.values[0])}`;return`Ung\xFCltige Option: erwartet eine von ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Zu gro\xDF: erwartet, dass ${U.origin??"Wert"} ${E}${U.maximum.toString()} ${j.unit??"Elemente"} hat`;return`Zu gro\xDF: erwartet, dass ${U.origin??"Wert"} ${E}${U.maximum.toString()} ist`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Zu klein: erwartet, dass ${U.origin} ${E}${U.minimum.toString()} ${j.unit} hat`;return`Zu klein: erwartet, dass ${U.origin} ${E}${U.minimum.toString()} ist`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ung\xFCltiger String: muss mit "${E.prefix}" beginnen`;if(E.format==="ends_with")return`Ung\xFCltiger String: muss mit "${E.suffix}" enden`;if(E.format==="includes")return`Ung\xFCltiger String: muss "${E.includes}" enthalten`;if(E.format==="regex")return`Ung\xFCltiger String: muss dem Muster ${E.pattern} entsprechen`;return`Ung\xFCltig: ${D[E.format]??U.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${U.divisor} sein`;case"unrecognized_keys":return`${U.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${U.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${U.origin}`;default:return"Ung\xFCltige Eingabe"}}};var M5=r(()=>{n()});function bS(){return{localeError:nB()}}var nB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(typeof U.expected==="string"&&/^[A-Z]/.test(U.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 ${U.expected}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`;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 ${E}, \u03BB\u03AE\u03C6\u03B8\u03B7\u03BA\u03B5 ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B5\u03B3\u03AC\u03BB\u03BF: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${U.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u03C4\u03B9\u03BC\u03AE"} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${U.origin} \u03BD\u03B1 \u03AD\u03C7\u03B5\u03B9 ${E}${U.minimum.toString()} ${j.unit}`;return`\u03A0\u03BF\u03BB\u03CD \u03BC\u03B9\u03BA\u03C1\u03CC: \u03B1\u03BD\u03B1\u03BC\u03B5\u03BD\u03CC\u03C4\u03B1\u03BD ${U.origin} \u03BD\u03B1 \u03B5\u03AF\u03BD\u03B1\u03B9 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF: ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u0386\u03B3\u03BD\u03C9\u03C3\u03C4${U.keys.length>1?"\u03B1":"\u03BF"} \u03BA\u03BB\u03B5\u03B9\u03B4${U.keys.length>1?"\u03B9\u03AC":"\u03AF"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03BF \u03BA\u03BB\u03B5\u03B9\u03B4\u03AF \u03C3\u03C4\u03BF ${U.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 ${U.origin}`;default:return"\u039C\u03B7 \u03AD\u03B3\u03BA\u03C5\u03C1\u03B7 \u03B5\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"}}};var Z5=r(()=>{n()});function zU(){return{localeError:dB()}}var dB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;return`Invalid input: expected ${E}, received ${N}`}case"invalid_value":if(U.values.length===1)return`Invalid input: expected ${M(U.values[0])}`;return`Invalid option: expected one of ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Too big: expected ${U.origin??"value"} to have ${E}${U.maximum.toString()} ${j.unit??"elements"}`;return`Too big: expected ${U.origin??"value"} to be ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Too small: expected ${U.origin} to have ${E}${U.minimum.toString()} ${j.unit}`;return`Too small: expected ${U.origin} to be ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Invalid string: must start with "${E.prefix}"`;if(E.format==="ends_with")return`Invalid string: must end with "${E.suffix}"`;if(E.format==="includes")return`Invalid string: must include "${E.includes}"`;if(E.format==="regex")return`Invalid string: must match pattern ${E.pattern}`;return`Invalid ${D[E.format]??U.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${U.divisor}`;case"unrecognized_keys":return`Unrecognized key${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Invalid key in ${U.origin}`;case"invalid_union":if(U.options&&Array.isArray(U.options)&&U.options.length>0)return`Invalid discriminator value. Expected ${U.options.map((j)=>`'${j}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${U.origin}`;default:return"Invalid input"}}};var qS=r(()=>{n()});function kS(){return{localeError:mB()}}var mB=()=>{let _={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Nevalida enigo: atendi\u011Dis instanceof ${U.expected}, ricevi\u011Dis ${N}`;return`Nevalida enigo: atendi\u011Dis ${E}, ricevi\u011Dis ${N}`}case"invalid_value":if(U.values.length===1)return`Nevalida enigo: atendi\u011Dis ${M(U.values[0])}`;return`Nevalida opcio: atendi\u011Dis unu el ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Tro granda: atendi\u011Dis ke ${U.origin??"valoro"} havu ${E}${U.maximum.toString()} ${j.unit??"elementojn"}`;return`Tro granda: atendi\u011Dis ke ${U.origin??"valoro"} havu ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Tro malgranda: atendi\u011Dis ke ${U.origin} havu ${E}${U.minimum.toString()} ${j.unit}`;return`Tro malgranda: atendi\u011Dis ke ${U.origin} estu ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Nevalida karaktraro: devas komenci\u011Di per "${E.prefix}"`;if(E.format==="ends_with")return`Nevalida karaktraro: devas fini\u011Di per "${E.suffix}"`;if(E.format==="includes")return`Nevalida karaktraro: devas inkluzivi "${E.includes}"`;if(E.format==="regex")return`Nevalida karaktraro: devas kongrui kun la modelo ${E.pattern}`;return`Nevalida ${D[E.format]??U.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${U.divisor}`;case"unrecognized_keys":return`Nekonata${U.keys.length>1?"j":""} \u015Dlosilo${U.keys.length>1?"j":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${U.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${U.origin}`;default:return"Nevalida enigo"}}};var H5=r(()=>{n()});function CS(){return{localeError:lB()}}var lB=()=>{let _={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Entrada inv\xE1lida: se esperaba instanceof ${U.expected}, recibido ${N}`;return`Entrada inv\xE1lida: se esperaba ${E}, recibido ${N}`}case"invalid_value":if(U.values.length===1)return`Entrada inv\xE1lida: se esperaba ${M(U.values[0])}`;return`Opci\xF3n inv\xE1lida: se esperaba una de ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Demasiado grande: se esperaba que ${N??"valor"} tuviera ${E}${U.maximum.toString()} ${j.unit??"elementos"}`;return`Demasiado grande: se esperaba que ${N??"valor"} fuera ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Demasiado peque\xF1o: se esperaba que ${N} tuviera ${E}${U.minimum.toString()} ${j.unit}`;return`Demasiado peque\xF1o: se esperaba que ${N} fuera ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Cadena inv\xE1lida: debe comenzar con "${E.prefix}"`;if(E.format==="ends_with")return`Cadena inv\xE1lida: debe terminar en "${E.suffix}"`;if(E.format==="includes")return`Cadena inv\xE1lida: debe incluir "${E.includes}"`;if(E.format==="regex")return`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${E.pattern}`;return`Inv\xE1lido ${D[E.format]??U.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${U.divisor}`;case"unrecognized_keys":return`Llave${U.keys.length>1?"s":""} desconocida${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${I[U.origin]??U.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${I[U.origin]??U.origin}`;default:return"Entrada inv\xE1lida"}}};var b5=r(()=>{n()});function vS(){return{localeError:iB()}}var iB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${U.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \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 ${E} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${N} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":if(U.values.length===1)return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${M(U.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 ${V(U.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${U.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${U.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} ${j.unit} \u0628\u0627\u0634\u062F`;return`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${E.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;if(E.format==="ends_with")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${E.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;if(E.format==="includes")return`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${E.includes}" \u0628\u0627\u0634\u062F`;if(E.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 ${E.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;return`${D[E.format]??U.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 ${U.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${U.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${V(U.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${U.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 ${U.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}};var q5=r(()=>{n()});function wS(){return{localeError:tB()}}var tB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Virheellinen tyyppi: odotettiin instanceof ${U.expected}, oli ${N}`;return`Virheellinen tyyppi: odotettiin ${E}, oli ${N}`}case"invalid_value":if(U.values.length===1)return`Virheellinen sy\xF6te: t\xE4ytyy olla ${M(U.values[0])}`;return`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Liian suuri: ${j.subject} t\xE4ytyy olla ${E}${U.maximum.toString()} ${j.unit}`.trim();return`Liian suuri: arvon t\xE4ytyy olla ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Liian pieni: ${j.subject} t\xE4ytyy olla ${E}${U.minimum.toString()} ${j.unit}`.trim();return`Liian pieni: arvon t\xE4ytyy olla ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${E.prefix}"`;if(E.format==="ends_with")return`Virheellinen sy\xF6te: t\xE4ytyy loppua "${E.suffix}"`;if(E.format==="includes")return`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${E.includes}"`;if(E.format==="regex")return`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${E.pattern}`;return`Virheellinen ${D[E.format]??U.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${U.divisor} monikerta`;case"unrecognized_keys":return`${U.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${V(U.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 k5=r(()=>{n()});function rS(){return{localeError:oB()}}var oB=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Entr\xE9e invalide : instanceof ${U.expected} attendu, ${N} re\xE7u`;return`Entr\xE9e invalide : ${E} attendu, ${N} re\xE7u`}case"invalid_value":if(U.values.length===1)return`Entr\xE9e invalide : ${M(U.values[0])} attendu`;return`Option invalide : une valeur parmi ${V(U.values,"|")} attendue`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Trop grand : ${I[U.origin]??"valeur"} doit ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"\xE9l\xE9ment(s)"}`;return`Trop grand : ${I[U.origin]??"valeur"} doit \xEAtre ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Trop petit : ${I[U.origin]??"valeur"} doit ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Trop petit : ${I[U.origin]??"valeur"} doit \xEAtre ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${E.prefix}"`;if(E.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${E.suffix}"`;if(E.format==="includes")return`Cha\xEEne invalide : doit inclure "${E.includes}"`;if(E.format==="regex")return`Cha\xEEne invalide : doit correspondre au mod\xE8le ${E.pattern}`;return`${D[E.format]??U.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${U.divisor}`;case"unrecognized_keys":return`Cl\xE9${U.keys.length>1?"s":""} non reconnue${U.keys.length>1?"s":""} : ${V(U.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${U.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${U.origin}`;default:return"Entr\xE9e invalide"}}};var C5=r(()=>{n()});function fS(){return{localeError:pB()}}var pB=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Entr\xE9e invalide : attendu instanceof ${U.expected}, re\xE7u ${N}`;return`Entr\xE9e invalide : attendu ${E}, re\xE7u ${N}`}case"invalid_value":if(U.values.length===1)return`Entr\xE9e invalide : attendu ${M(U.values[0])}`;return`Option invalide : attendu l'une des valeurs suivantes ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"\u2264":"<",j=$(U.origin);if(j)return`Trop grand : attendu que ${U.origin??"la valeur"} ait ${E}${U.maximum.toString()} ${j.unit}`;return`Trop grand : attendu que ${U.origin??"la valeur"} soit ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?"\u2265":">",j=$(U.origin);if(j)return`Trop petit : attendu que ${U.origin} ait ${E}${U.minimum.toString()} ${j.unit}`;return`Trop petit : attendu que ${U.origin} soit ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Cha\xEEne invalide : doit commencer par "${E.prefix}"`;if(E.format==="ends_with")return`Cha\xEEne invalide : doit se terminer par "${E.suffix}"`;if(E.format==="includes")return`Cha\xEEne invalide : doit inclure "${E.includes}"`;if(E.format==="regex")return`Cha\xEEne invalide : doit correspondre au motif ${E.pattern}`;return`${D[E.format]??U.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${U.divisor}`;case"unrecognized_keys":return`Cl\xE9${U.keys.length>1?"s":""} non reconnue${U.keys.length>1?"s":""} : ${V(U.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${U.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${U.origin}`;default:return"Entr\xE9e invalide"}}};var v5=r(()=>{n()});function xS(){return{localeError:eB()}}var eB=()=>{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"}},D=(S)=>S?_[S]:void 0,I=(S)=>{let L=D(S);if(L)return L.label;return S??_.unknown.label},U=(S)=>`\u05D4${I(S)}`,E=(S)=>{return(D(S)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA"},j=(S)=>{if(!S)return null;return $[S]??null},N={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"}},O={nan:"NaN"};return(S)=>{switch(S.code){case"invalid_type":{let L=S.expected,W=O[L??""]??I(L),g=Z(S.input),z=O[g]??_[g]?.label??g;if(/^[A-Z]/.test(S.expected))return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${S.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${z}`;return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${W}, \u05D4\u05EA\u05E7\u05D1\u05DC ${z}`}case"invalid_value":{if(S.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 ${M(S.values[0])}`;let L=S.values.map((z)=>M(z));if(S.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 W=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 ${W}`}case"too_big":{let L=j(S.origin),W=U(S.origin??"value");if(S.origin==="string")return`${L?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${W} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${S.maximum.toString()} ${L?.unit??""} ${S.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(S.origin==="number"){let G=S.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${S.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${S.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${W} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${G}`}if(S.origin==="array"||S.origin==="set"){let G=S.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",J=S.inclusive?`${S.maximum} ${L?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${S.maximum} ${L?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${W} ${G} \u05DC\u05D4\u05DB\u05D9\u05DC ${J}`.trim()}let g=S.inclusive?"<=":"<",z=E(S.origin??"value");if(L?.unit)return`${L.longLabel} \u05DE\u05D3\u05D9: ${W} ${z} ${g}${S.maximum.toString()} ${L.unit}`;return`${L?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${W} ${z} ${g}${S.maximum.toString()}`}case"too_small":{let L=j(S.origin),W=U(S.origin??"value");if(S.origin==="string")return`${L?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${W} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${S.minimum.toString()} ${L?.unit??""} ${S.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(S.origin==="number"){let G=S.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${S.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${S.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${W} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${G}`}if(S.origin==="array"||S.origin==="set"){let G=S.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(S.minimum===1&&S.inclusive){let P=S.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: ${W} ${G} \u05DC\u05D4\u05DB\u05D9\u05DC ${P}`}let J=S.inclusive?`${S.minimum} ${L?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${S.minimum} ${L?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${W} ${G} \u05DC\u05D4\u05DB\u05D9\u05DC ${J}`.trim()}let g=S.inclusive?">=":">",z=E(S.origin??"value");if(L?.unit)return`${L.shortLabel} \u05DE\u05D3\u05D9: ${W} ${z} ${g}${S.minimum.toString()} ${L.unit}`;return`${L?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${W} ${z} ${g}${S.minimum.toString()}`}case"invalid_format":{let L=S;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 W=N[L.format],g=W?.label??L.format,G=(W?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${g} \u05DC\u05D0 ${G}`}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 ${S.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${S.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${S.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${V(S.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${U(S.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}};var w5=r(()=>{n()});function uS(){return{localeError:aB()}}var aB=()=>{let _={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Neispravan unos: o\u010Dekuje se instanceof ${U.expected}, a primljeno je ${N}`;return`Neispravan unos: o\u010Dekuje se ${E}, a primljeno je ${N}`}case"invalid_value":if(U.values.length===1)return`Neispravna vrijednost: o\u010Dekivano ${M(U.values[0])}`;return`Neispravna opcija: o\u010Dekivano jedno od ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} ima ${E}${U.maximum.toString()} ${j.unit??"elemenata"}`;return`Preveliko: o\u010Dekivano da ${N??"vrijednost"} bude ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=I[U.origin]??U.origin;if(j)return`Premalo: o\u010Dekivano da ${N} ima ${E}${U.minimum.toString()} ${j.unit}`;return`Premalo: o\u010Dekivano da ${N} bude ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Neispravan tekst: mora zapo\u010Dinjati s "${E.prefix}"`;if(E.format==="ends_with")return`Neispravan tekst: mora zavr\u0161avati s "${E.suffix}"`;if(E.format==="includes")return`Neispravan tekst: mora sadr\u017Eavati "${E.includes}"`;if(E.format==="regex")return`Neispravan tekst: mora odgovarati uzorku ${E.pattern}`;return`Neispravna ${D[E.format]??U.format}`}case"not_multiple_of":return`Neispravan broj: mora biti vi\u0161ekratnik od ${U.divisor}`;case"unrecognized_keys":return`Neprepoznat${U.keys.length>1?"i klju\u010Devi":" klju\u010D"}: ${V(U.keys,", ")}`;case"invalid_key":return`Neispravan klju\u010D u ${I[U.origin]??U.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${I[U.origin]??U.origin}`;default:return"Neispravan unos"}}};var r5=r(()=>{n()});function yS(){return{localeError:sB()}}var sB=()=>{let _={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${U.expected}, a kapott \xE9rt\xE9k ${N}`;return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${E}, a kapott \xE9rt\xE9k ${N}`}case"invalid_value":if(U.values.length===1)return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${M(U.values[0])}`;return`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`T\xFAl nagy: ${U.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${E}${U.maximum.toString()} ${j.unit??"elem"}`;return`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${U.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${U.origin} m\xE9rete t\xFAl kicsi ${E}${U.minimum.toString()} ${j.unit}`;return`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${U.origin} t\xFAl kicsi ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\xC9rv\xE9nytelen string: "${E.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;if(E.format==="ends_with")return`\xC9rv\xE9nytelen string: "${E.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;if(E.format==="includes")return`\xC9rv\xE9nytelen string: "${E.includes}" \xE9rt\xE9ket kell tartalmaznia`;if(E.format==="regex")return`\xC9rv\xE9nytelen string: ${E.pattern} mint\xE1nak kell megfelelnie`;return`\xC9rv\xE9nytelen ${D[E.format]??U.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${U.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${U.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${U.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}};var f5=r(()=>{n()});function x5(_,$,D){return Math.abs(_)===1?$:D}function c0(_){if(!_)return"";let $=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],D=_[_.length-1];return _+($.includes(D)?"\u0576":"\u0568")}function hS(){return{localeError:_M()}}var _M=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`;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 ${E}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j){let N=Number(U.maximum),O=x5(N,j.unit.one,j.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 ${c0(U.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${E}${U.maximum.toString()} ${O}`}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 ${c0(U.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j){let N=Number(U.minimum),O=x5(N,j.unit.one,j.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 ${c0(U.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${E}${U.minimum.toString()} ${O}`}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 ${c0(U.origin)} \u056C\u056B\u0576\u056B ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${E.prefix}"-\u0578\u057E`;if(E.format==="ends_with")return`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${E.suffix}"-\u0578\u057E`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;return`\u054D\u056D\u0561\u056C ${D[E.format]??U.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 ${U.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${U.keys.length>1?"\u0576\u0565\u0580":""}. ${V(U.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${c0(U.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 ${c0(U.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}};var u5=r(()=>{n()});function cS(){return{localeError:$M()}}var $M=()=>{let _={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Input tidak valid: diharapkan instanceof ${U.expected}, diterima ${N}`;return`Input tidak valid: diharapkan ${E}, diterima ${N}`}case"invalid_value":if(U.values.length===1)return`Input tidak valid: diharapkan ${M(U.values[0])}`;return`Pilihan tidak valid: diharapkan salah satu dari ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Terlalu besar: diharapkan ${U.origin??"value"} memiliki ${E}${U.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: diharapkan ${U.origin??"value"} menjadi ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Terlalu kecil: diharapkan ${U.origin} memiliki ${E}${U.minimum.toString()} ${j.unit}`;return`Terlalu kecil: diharapkan ${U.origin} menjadi ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`String tidak valid: harus dimulai dengan "${E.prefix}"`;if(E.format==="ends_with")return`String tidak valid: harus berakhir dengan "${E.suffix}"`;if(E.format==="includes")return`String tidak valid: harus menyertakan "${E.includes}"`;if(E.format==="regex")return`String tidak valid: harus sesuai pola ${E.pattern}`;return`${D[E.format]??U.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${U.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${U.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${U.origin}`;default:return"Input tidak valid"}}};var y5=r(()=>{n()});function nS(){return{localeError:DM()}}var DM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"n\xFAmer",array:"fylki"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera instanceof ${U.expected}`;return`Rangt gildi: \xDE\xFA sl\xF3st inn ${N} \xFEar sem \xE1 a\xF0 vera ${E}`}case"invalid_value":if(U.values.length===1)return`Rangt gildi: gert r\xE1\xF0 fyrir ${M(U.values[0])}`;return`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin??"gildi"} hafi ${E}${U.maximum.toString()} ${j.unit??"hluti"}`;return`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin??"gildi"} s\xE9 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin} hafi ${E}${U.minimum.toString()} ${j.unit}`;return`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${U.origin} s\xE9 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${E.prefix}"`;if(E.format==="ends_with")return`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${E.suffix}"`;if(E.format==="includes")return`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${E.includes}"`;if(E.format==="regex")return`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${E.pattern}`;return`Rangt ${D[E.format]??U.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${U.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${U.keys.length>1?"ir lyklar":"ur lykill"}: ${V(U.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${U.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${U.origin}`;default:return"Rangt gildi"}}};var h5=r(()=>{n()});function dS(){return{localeError:UM()}}var UM=()=>{let _={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"numero",array:"vettore"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Input non valido: atteso instanceof ${U.expected}, ricevuto ${N}`;return`Input non valido: atteso ${E}, ricevuto ${N}`}case"invalid_value":if(U.values.length===1)return`Input non valido: atteso ${M(U.values[0])}`;return`Opzione non valida: atteso uno tra ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Troppo grande: ${U.origin??"valore"} deve avere ${E}${U.maximum.toString()} ${j.unit??"elementi"}`;return`Troppo grande: ${U.origin??"valore"} deve essere ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Troppo piccolo: ${U.origin} deve avere ${E}${U.minimum.toString()} ${j.unit}`;return`Troppo piccolo: ${U.origin} deve essere ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Stringa non valida: deve iniziare con "${E.prefix}"`;if(E.format==="ends_with")return`Stringa non valida: deve terminare con "${E.suffix}"`;if(E.format==="includes")return`Stringa non valida: deve includere "${E.includes}"`;if(E.format==="regex")return`Stringa non valida: deve corrispondere al pattern ${E.pattern}`;return`Input non valido: ${D[E.format]??U.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${U.divisor}`;case"unrecognized_keys":return`Chiav${U.keys.length>1?"i":"e"} non riconosciut${U.keys.length>1?"e":"a"}: ${V(U.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${U.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${U.origin}`;default:return"Input non valido"}}};var c5=r(()=>{n()});function mS(){return{localeError:IM()}}var IM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u7121\u52B9\u306A\u5165\u529B: instanceof ${U.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u5165\u529B: ${E}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${N}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":if(U.values.length===1)return`\u7121\u52B9\u306A\u5165\u529B: ${M(U.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;return`\u7121\u52B9\u306A\u9078\u629E: ${V(U.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let E=U.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",j=$(U.origin);if(j)return`\u5927\u304D\u3059\u304E\u308B\u5024: ${U.origin??"\u5024"}\u306F${U.maximum.toString()}${j.unit??"\u8981\u7D20"}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5927\u304D\u3059\u304E\u308B\u5024: ${U.origin??"\u5024"}\u306F${U.maximum.toString()}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let E=U.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",j=$(U.origin);if(j)return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${U.origin}\u306F${U.minimum.toString()}${j.unit}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${U.origin}\u306F${U.minimum.toString()}${E}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${E.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(E.format==="ends_with")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${E.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(E.format==="includes")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${E.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;if(E.format==="regex")return`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${E.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;return`\u7121\u52B9\u306A${D[E.format]??U.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${U.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${U.keys.length>1?"\u7FA4":""}: ${V(U.keys,"\u3001")}`;case"invalid_key":return`${U.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${U.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}};var n5=r(()=>{n()});function lS(){return{localeError:EM()}}var EM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`;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 ${E}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${U.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${j.verb} ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)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 ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.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 ${U.origin} \u10D8\u10E7\u10DD\u10E1 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"-\u10D8\u10D7`;if(E.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 "${E.suffix}"-\u10D8\u10D7`;if(E.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 "${E.includes}"-\u10E1`;if(E.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 ${E.pattern}`;return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${D[E.format]??U.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 ${U.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${U.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${U.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 ${U.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}};var d5=r(()=>{n()});function gU(){return{localeError:jM()}}var jM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`;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 ${E} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${E} ${U.maximum.toString()} ${j.unit??"\u1792\u17B6\u178F\u17BB"}`;return`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin} ${E} ${U.minimum.toString()} ${j.unit}`;return`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${U.origin} ${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${V(U.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 ${U.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 ${U.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 iS=r(()=>{n()});function tS(){return gU()}var m5=r(()=>{iS()});function oS(){return{localeError:NM()}}var NM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${U.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${E}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${N}\uC785\uB2C8\uB2E4`}case"invalid_value":if(U.values.length===1)return`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${M(U.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C \uC635\uC158: ${V(U.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let E=U.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",j=E==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(U.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${U.maximum.toString()}${O} ${E}${j}`;return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${U.maximum.toString()} ${E}${j}`}case"too_small":{let E=U.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",j=E==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",N=$(U.origin),O=N?.unit??"\uC694\uC18C";if(N)return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${U.minimum.toString()}${O} ${E}${j}`;return`${U.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${U.minimum.toString()} ${E}${j}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${E.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;if(E.format==="ends_with")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${E.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;if(E.format==="includes")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${E.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;if(E.format==="regex")return`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${E.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;return`\uC798\uBABB\uB41C ${D[E.format]??U.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${U.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${V(U.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${U.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${U.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}};var l5=r(()=>{n()});function i5(_){let $=Math.abs(_),D=$%10,I=$%100;if(I>=11&&I<=19||D===0)return"many";if(D===1)return"one";return"few"}function pS(){return{localeError:AM()}}var XU=(_)=>{return _.charAt(0).toUpperCase()+_.slice(1)},AM=()=>{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 $(U,E,j,N){let O=_[U]??null;if(O===null)return O;return{unit:O.unit[E],verb:O.verb[N][j?"inclusive":"notInclusive"]}}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Gautas tipas ${N}, o tik\u0117tasi - instanceof ${U.expected}`;return`Gautas tipas ${N}, o tik\u0117tasi - ${E}`}case"invalid_value":if(U.values.length===1)return`Privalo b\u016Bti ${M(U.values[0])}`;return`Privalo b\u016Bti vienas i\u0161 ${V(U.values,"|")} pasirinkim\u0173`;case"too_big":{let E=I[U.origin]??U.origin,j=$(U.origin,i5(Number(U.maximum)),U.inclusive??!1,"smaller");if(j?.verb)return`${XU(E??U.origin??"reik\u0161m\u0117")} ${j.verb} ${U.maximum.toString()} ${j.unit??"element\u0173"}`;let N=U.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${XU(E??U.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${U.maximum.toString()} ${j?.unit}`}case"too_small":{let E=I[U.origin]??U.origin,j=$(U.origin,i5(Number(U.minimum)),U.inclusive??!1,"bigger");if(j?.verb)return`${XU(E??U.origin??"reik\u0161m\u0117")} ${j.verb} ${U.minimum.toString()} ${j.unit??"element\u0173"}`;let N=U.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${XU(E??U.origin??"reik\u0161m\u0117")} turi b\u016Bti ${N} ${U.minimum.toString()} ${j?.unit}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Eilut\u0117 privalo prasid\u0117ti "${E.prefix}"`;if(E.format==="ends_with")return`Eilut\u0117 privalo pasibaigti "${E.suffix}"`;if(E.format==="includes")return`Eilut\u0117 privalo \u012Ftraukti "${E.includes}"`;if(E.format==="regex")return`Eilut\u0117 privalo atitikti ${E.pattern}`;return`Neteisingas ${D[E.format]??U.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${U.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${U.keys.length>1?"i":"as"} rakt${U.keys.length>1?"ai":"as"}: ${V(U.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let E=I[U.origin]??U.origin;return`${XU(E??U.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}};var t5=r(()=>{n()});function eS(){return{localeError:OM()}}var OM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${U.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`;return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${E}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${N}`}case"invalid_value":if(U.values.length===1)return`Invalid input: expected ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${U.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${U.origin} \u0434\u0430 \u0438\u043C\u0430 ${E}${U.minimum.toString()} ${j.unit}`;return`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${U.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`Invalid ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`${U.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"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${U.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 ${U.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}};var o5=r(()=>{n()});function aS(){return{localeError:SM()}}var SM=()=>{let _={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"nombor"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Input tidak sah: dijangka instanceof ${U.expected}, diterima ${N}`;return`Input tidak sah: dijangka ${E}, diterima ${N}`}case"invalid_value":if(U.values.length===1)return`Input tidak sah: dijangka ${M(U.values[0])}`;return`Pilihan tidak sah: dijangka salah satu daripada ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Terlalu besar: dijangka ${U.origin??"nilai"} ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"elemen"}`;return`Terlalu besar: dijangka ${U.origin??"nilai"} adalah ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Terlalu kecil: dijangka ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Terlalu kecil: dijangka ${U.origin} adalah ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`String tidak sah: mesti bermula dengan "${E.prefix}"`;if(E.format==="ends_with")return`String tidak sah: mesti berakhir dengan "${E.suffix}"`;if(E.format==="includes")return`String tidak sah: mesti mengandungi "${E.includes}"`;if(E.format==="regex")return`String tidak sah: mesti sepadan dengan corak ${E.pattern}`;return`${D[E.format]??U.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${U.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${V(U.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${U.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${U.origin}`;default:return"Input tidak sah"}}};var p5=r(()=>{n()});function sS(){return{localeError:LM()}}var LM=()=>{let _={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"getal"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ongeldige invoer: verwacht instanceof ${U.expected}, ontving ${N}`;return`Ongeldige invoer: verwacht ${E}, ontving ${N}`}case"invalid_value":if(U.values.length===1)return`Ongeldige invoer: verwacht ${M(U.values[0])}`;return`Ongeldige optie: verwacht \xE9\xE9n van ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin),N=U.origin==="date"?"laat":U.origin==="string"?"lang":"groot";if(j)return`Te ${N}: verwacht dat ${U.origin??"waarde"} ${E}${U.maximum.toString()} ${j.unit??"elementen"} ${j.verb}`;return`Te ${N}: verwacht dat ${U.origin??"waarde"} ${E}${U.maximum.toString()} is`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin),N=U.origin==="date"?"vroeg":U.origin==="string"?"kort":"klein";if(j)return`Te ${N}: verwacht dat ${U.origin} ${E}${U.minimum.toString()} ${j.unit} ${j.verb}`;return`Te ${N}: verwacht dat ${U.origin} ${E}${U.minimum.toString()} is`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ongeldige tekst: moet met "${E.prefix}" beginnen`;if(E.format==="ends_with")return`Ongeldige tekst: moet op "${E.suffix}" eindigen`;if(E.format==="includes")return`Ongeldige tekst: moet "${E.includes}" bevatten`;if(E.format==="regex")return`Ongeldige tekst: moet overeenkomen met patroon ${E.pattern}`;return`Ongeldig: ${D[E.format]??U.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${U.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${U.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${U.origin}`;default:return"Ongeldige invoer"}}};var e5=r(()=>{n()});function _L(){return{localeError:WM()}}var WM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"tall",array:"liste"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ugyldig input: forventet instanceof ${U.expected}, fikk ${N}`;return`Ugyldig input: forventet ${E}, fikk ${N}`}case"invalid_value":if(U.values.length===1)return`Ugyldig verdi: forventet ${M(U.values[0])}`;return`Ugyldig valg: forventet en av ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`For stor(t): forventet ${U.origin??"value"} til \xE5 ha ${E}${U.maximum.toString()} ${j.unit??"elementer"}`;return`For stor(t): forventet ${U.origin??"value"} til \xE5 ha ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`For lite(n): forventet ${U.origin} til \xE5 ha ${E}${U.minimum.toString()} ${j.unit}`;return`For lite(n): forventet ${U.origin} til \xE5 ha ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ugyldig streng: m\xE5 starte med "${E.prefix}"`;if(E.format==="ends_with")return`Ugyldig streng: m\xE5 ende med "${E.suffix}"`;if(E.format==="includes")return`Ugyldig streng: m\xE5 inneholde "${E.includes}"`;if(E.format==="regex")return`Ugyldig streng: m\xE5 matche m\xF8nsteret ${E.pattern}`;return`Ugyldig ${D[E.format]??U.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${U.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${U.origin}`;default:return"Ugyldig input"}}};var a5=r(()=>{n()});function $L(){return{localeError:JM()}}var JM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`F\xE2sit giren: umulan instanceof ${U.expected}, al\u0131nan ${N}`;return`F\xE2sit giren: umulan ${E}, al\u0131nan ${N}`}case"invalid_value":if(U.values.length===1)return`F\xE2sit giren: umulan ${M(U.values[0])}`;return`F\xE2sit tercih: m\xFBteberler ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Fazla b\xFCy\xFCk: ${U.origin??"value"}, ${E}${U.maximum.toString()} ${j.unit??"elements"} sahip olmal\u0131yd\u0131.`;return`Fazla b\xFCy\xFCk: ${U.origin??"value"}, ${E}${U.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Fazla k\xFC\xE7\xFCk: ${U.origin}, ${E}${U.minimum.toString()} ${j.unit} sahip olmal\u0131yd\u0131.`;return`Fazla k\xFC\xE7\xFCk: ${U.origin}, ${E}${U.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`F\xE2sit metin: "${E.prefix}" ile ba\u015Flamal\u0131.`;if(E.format==="ends_with")return`F\xE2sit metin: "${E.suffix}" ile bitmeli.`;if(E.format==="includes")return`F\xE2sit metin: "${E.includes}" ihtiv\xE2 etmeli.`;if(E.format==="regex")return`F\xE2sit metin: ${E.pattern} nak\u015F\u0131na uymal\u0131.`;return`F\xE2sit ${D[E.format]??U.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${U.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${U.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}};var s5=r(()=>{n()});function DL(){return{localeError:PM()}}var PM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${U.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${E} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${N} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":if(U.values.length===1)return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${M(U.values[0])} \u0648\u0627\u06CC`;return`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${V(U.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${U.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} ${j.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${U.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${E}${U.maximum.toString()} \u0648\u064A`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} ${j.unit} \u0648\u0644\u0631\u064A`;return`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${U.origin} \u0628\u0627\u06CC\u062F ${E}${U.minimum.toString()} \u0648\u064A`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${E.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;if(E.format==="ends_with")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${E.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;if(E.format==="includes")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${E.includes}" \u0648\u0644\u0631\u064A`;if(E.format==="regex")return`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${E.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;return`${D[E.format]??U.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${U.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${U.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${V(U.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${U.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 ${U.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}};var _G=r(()=>{n()});function UL(){return{localeError:zM()}}var zM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"liczba",array:"tablica"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${U.expected}, otrzymano ${N}`;return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${E}, otrzymano ${N}`}case"invalid_value":if(U.values.length===1)return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${M(U.values[0])}`;return`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${E}${U.maximum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${E}${U.minimum.toString()} ${j.unit??"element\xF3w"}`;return`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${U.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${E.prefix}"`;if(E.format==="ends_with")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${E.suffix}"`;if(E.format==="includes")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${E.includes}"`;if(E.format==="regex")return`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${E.pattern}`;return`Nieprawid\u0142ow(y/a/e) ${D[E.format]??U.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${U.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${U.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${U.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}};var $G=r(()=>{n()});function IL(){return{localeError:gM()}}var gM=()=>{let _={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"n\xFAmero",null:"nulo"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Tipo inv\xE1lido: esperado instanceof ${U.expected}, recebido ${N}`;return`Tipo inv\xE1lido: esperado ${E}, recebido ${N}`}case"invalid_value":if(U.values.length===1)return`Entrada inv\xE1lida: esperado ${M(U.values[0])}`;return`Op\xE7\xE3o inv\xE1lida: esperada uma das ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Muito grande: esperado que ${U.origin??"valor"} tivesse ${E}${U.maximum.toString()} ${j.unit??"elementos"}`;return`Muito grande: esperado que ${U.origin??"valor"} fosse ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Muito pequeno: esperado que ${U.origin} tivesse ${E}${U.minimum.toString()} ${j.unit}`;return`Muito pequeno: esperado que ${U.origin} fosse ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Texto inv\xE1lido: deve come\xE7ar com "${E.prefix}"`;if(E.format==="ends_with")return`Texto inv\xE1lido: deve terminar com "${E.suffix}"`;if(E.format==="includes")return`Texto inv\xE1lido: deve incluir "${E.includes}"`;if(E.format==="regex")return`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${E.pattern}`;return`${D[E.format]??U.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${U.divisor}`;case"unrecognized_keys":return`Chave${U.keys.length>1?"s":""} desconhecida${U.keys.length>1?"s":""}: ${V(U.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${U.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${U.origin}`;default:return"Campo inv\xE1lido"}}};var DG=r(()=>{n()});function EL(){return{localeError:XM()}}var XM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;return`Intrare invalid\u0103: a\u0219teptat ${E}, primit ${N}`}case"invalid_value":if(U.values.length===1)return`Intrare invalid\u0103: a\u0219teptat ${M(U.values[0])}`;return`Op\u021Biune invalid\u0103: a\u0219teptat una dintre ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Prea mare: a\u0219teptat ca ${U.origin??"valoarea"} ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"elemente"}`;return`Prea mare: a\u0219teptat ca ${U.origin??"valoarea"} s\u0103 fie ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Prea mic: a\u0219teptat ca ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Prea mic: a\u0219teptat ca ${U.origin} s\u0103 fie ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0218ir invalid: trebuie s\u0103 \xEEnceap\u0103 cu "${E.prefix}"`;if(E.format==="ends_with")return`\u0218ir invalid: trebuie s\u0103 se termine cu "${E.suffix}"`;if(E.format==="includes")return`\u0218ir invalid: trebuie s\u0103 includ\u0103 "${E.includes}"`;if(E.format==="regex")return`\u0218ir invalid: trebuie s\u0103 se potriveasc\u0103 cu modelul ${E.pattern}`;return`Format invalid: ${D[E.format]??U.format}`}case"not_multiple_of":return`Num\u0103r invalid: trebuie s\u0103 fie multiplu de ${U.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${V(U.keys,", ")}`;case"invalid_key":return`Cheie invalid\u0103 \xEEn ${U.origin}`;case"invalid_union":return"Intrare invalid\u0103";case"invalid_element":return`Valoare invalid\u0103 \xEEn ${U.origin}`;default:return"Intrare invalid\u0103"}}};var UG=r(()=>{n()});function IG(_,$,D,I){let U=Math.abs(_),E=U%10,j=U%100;if(j>=11&&j<=19)return I;if(E===1)return $;if(E>=2&&E<=4)return D;return I}function jL(){return{localeError:GM()}}var GM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${U.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${E}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j){let N=Number(U.maximum),O=IG(N,j.unit.one,j.unit.few,j.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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${E}${U.maximum.toString()} ${O}`}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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j){let N=Number(U.minimum),O=IG(N,j.unit.one,j.unit.few,j.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 ${U.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${E}${U.minimum.toString()} ${O}`}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 ${U.origin} \u0431\u0443\u0434\u0435\u0442 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${U.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${U.keys.length>1?"\u0438":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${U.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 ${U.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 EG=r(()=>{n()});function NL(){return{localeError:RM()}}var RM=()=>{let _={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Neveljaven vnos: pri\u010Dakovano instanceof ${U.expected}, prejeto ${N}`;return`Neveljaven vnos: pri\u010Dakovano ${E}, prejeto ${N}`}case"invalid_value":if(U.values.length===1)return`Neveljaven vnos: pri\u010Dakovano ${M(U.values[0])}`;return`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Preveliko: pri\u010Dakovano, da bo ${U.origin??"vrednost"} imelo ${E}${U.maximum.toString()} ${j.unit??"elementov"}`;return`Preveliko: pri\u010Dakovano, da bo ${U.origin??"vrednost"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Premajhno: pri\u010Dakovano, da bo ${U.origin} imelo ${E}${U.minimum.toString()} ${j.unit}`;return`Premajhno: pri\u010Dakovano, da bo ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Neveljaven niz: mora se za\u010Deti z "${E.prefix}"`;if(E.format==="ends_with")return`Neveljaven niz: mora se kon\u010Dati z "${E.suffix}"`;if(E.format==="includes")return`Neveljaven niz: mora vsebovati "${E.includes}"`;if(E.format==="regex")return`Neveljaven niz: mora ustrezati vzorcu ${E.pattern}`;return`Neveljaven ${D[E.format]??U.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${U.divisor}`;case"unrecognized_keys":return`Neprepoznan${U.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${V(U.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${U.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${U.origin}`;default:return"Neveljaven vnos"}}};var jG=r(()=>{n()});function AL(){return{localeError:YM()}}var YM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"antal",array:"lista"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${U.expected}, fick ${N}`;return`Ogiltig inmatning: f\xF6rv\xE4ntat ${E}, fick ${N}`}case"invalid_value":if(U.values.length===1)return`Ogiltig inmatning: f\xF6rv\xE4ntat ${M(U.values[0])}`;return`Ogiltigt val: f\xF6rv\xE4ntade en av ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`F\xF6r stor(t): f\xF6rv\xE4ntade ${U.origin??"v\xE4rdet"} att ha ${E}${U.maximum.toString()} ${j.unit??"element"}`;return`F\xF6r stor(t): f\xF6rv\xE4ntat ${U.origin??"v\xE4rdet"} att ha ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`F\xF6r lite(t): f\xF6rv\xE4ntade ${U.origin??"v\xE4rdet"} att ha ${E}${U.minimum.toString()} ${j.unit}`;return`F\xF6r lite(t): f\xF6rv\xE4ntade ${U.origin??"v\xE4rdet"} att ha ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${E.prefix}"`;if(E.format==="ends_with")return`Ogiltig str\xE4ng: m\xE5ste sluta med "${E.suffix}"`;if(E.format==="includes")return`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${E.includes}"`;if(E.format==="regex")return`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${E.pattern}"`;return`Ogiltig(t) ${D[E.format]??U.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${U.divisor}`;case"unrecognized_keys":return`${U.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${V(U.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${U.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${U.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}};var NG=r(()=>{n()});function OL(){return{localeError:QM()}}var QM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`;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 ${E}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)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 ${U.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${E}${U.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)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 ${U.origin} ${E}${U.minimum.toString()} ${j.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 ${U.origin} ${E}${U.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${E.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(E.format==="ends_with")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${E.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(E.format==="includes")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${E.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;if(E.format==="regex")return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${E.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 ${D[E.format]??U.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${U.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${U.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.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`${U.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 AG=r(()=>{n()});function SL(){return{localeError:KM()}}var KM=()=>{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 $(U){return _[U]??null}let D={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"},I={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(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`;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 ${E} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${N}`}case"invalid_value":if(U.values.length===1)return`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",j=$(U.origin);if(j)return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.maximum.toString()} ${j.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;return`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",j=$(U.origin);if(j)return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.minimum.toString()} ${j.unit}`;return`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${U.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${E} ${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;if(E.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 ${E.pattern}`;return`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${D[E.format]??U.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 ${U.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: ${V(U.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${U.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 ${U.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}};var OG=r(()=>{n()});function LL(){return{localeError:TM()}}var TM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${U.expected}, al\u0131nan ${N}`;return`Ge\xE7ersiz de\u011Fer: beklenen ${E}, al\u0131nan ${N}`}case"invalid_value":if(U.values.length===1)return`Ge\xE7ersiz de\u011Fer: beklenen ${M(U.values[0])}`;return`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\xC7ok b\xFCy\xFCk: beklenen ${U.origin??"de\u011Fer"} ${E}${U.maximum.toString()} ${j.unit??"\xF6\u011Fe"}`;return`\xC7ok b\xFCy\xFCk: beklenen ${U.origin??"de\u011Fer"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\xC7ok k\xFC\xE7\xFCk: beklenen ${U.origin} ${E}${U.minimum.toString()} ${j.unit}`;return`\xC7ok k\xFC\xE7\xFCk: beklenen ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Ge\xE7ersiz metin: "${E.prefix}" ile ba\u015Flamal\u0131`;if(E.format==="ends_with")return`Ge\xE7ersiz metin: "${E.suffix}" ile bitmeli`;if(E.format==="includes")return`Ge\xE7ersiz metin: "${E.includes}" i\xE7ermeli`;if(E.format==="regex")return`Ge\xE7ersiz metin: ${E.pattern} desenine uymal\u0131`;return`Ge\xE7ersiz ${D[E.format]??U.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${U.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${U.keys.length>1?"lar":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${U.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}};var SG=r(()=>{n()});function GU(){return{localeError:FM()}}var FM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.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 ${U.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`;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 ${E}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${N}`}case"invalid_value":if(U.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 ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${j.verb} ${E}${U.maximum.toString()} ${j.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 ${U.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.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 ${U.origin} \u0431\u0443\u0434\u0435 ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.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 "${E.suffix}"`;if(E.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 "${E.includes}"`;if(E.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 ${E.pattern}`;return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${U.keys.length>1?"\u0456":""}: ${V(U.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${U.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 ${U.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 WL=r(()=>{n()});function JL(){return GU()}var LG=r(()=>{WL()});function PL(){return{localeError:VM()}}var VM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${U.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${E} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${N} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":if(U.values.length===1)return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${M(U.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;return`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${V(U.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u0628\u06C1\u062A \u0628\u0691\u0627: ${U.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${E}${U.maximum.toString()} ${j.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: ${U.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${E}${U.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${U.origin} \u06A9\u06D2 ${E}${U.minimum.toString()} ${j.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;return`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${U.origin} \u06A9\u0627 ${E}${U.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${E.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(E.format==="ends_with")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${E.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(E.format==="includes")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${E.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;if(E.format==="regex")return`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${E.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;return`\u063A\u0644\u0637 ${D[E.format]??U.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${U.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${U.keys.length>1?"\u0632":""}: ${V(U.keys,"\u060C ")}`;case"invalid_key":return`${U.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${U.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}};var WG=r(()=>{n()});function zL(){return{localeError:BM()}}var BM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"raqam",array:"massiv"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${U.expected}, qabul qilingan ${N}`;return`Noto\u2018g\u2018ri kirish: kutilgan ${E}, qabul qilingan ${N}`}case"invalid_value":if(U.values.length===1)return`Noto\u2018g\u2018ri kirish: kutilgan ${M(U.values[0])}`;return`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Juda katta: kutilgan ${U.origin??"qiymat"} ${E}${U.maximum.toString()} ${j.unit} ${j.verb}`;return`Juda katta: kutilgan ${U.origin??"qiymat"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Juda kichik: kutilgan ${U.origin} ${E}${U.minimum.toString()} ${j.unit} ${j.verb}`;return`Juda kichik: kutilgan ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Noto\u2018g\u2018ri satr: "${E.prefix}" bilan boshlanishi kerak`;if(E.format==="ends_with")return`Noto\u2018g\u2018ri satr: "${E.suffix}" bilan tugashi kerak`;if(E.format==="includes")return`Noto\u2018g\u2018ri satr: "${E.includes}" ni o\u2018z ichiga olishi kerak`;if(E.format==="regex")return`Noto\u2018g\u2018ri satr: ${E.pattern} shabloniga mos kelishi kerak`;return`Noto\u2018g\u2018ri ${D[E.format]??U.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${U.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${U.keys.length>1?"lar":""}: ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${U.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}};var JG=r(()=>{n()});function gL(){return{localeError:MM()}}var MM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${U.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`;return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${E}, nh\u1EADn \u0111\u01B0\u1EE3c ${N}`}case"invalid_value":if(U.values.length===1)return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${M(U.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 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${U.origin??"gi\xE1 tr\u1ECB"} ${j.verb} ${E}${U.maximum.toString()} ${j.unit??"ph\u1EA7n t\u1EED"}`;return`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${U.origin??"gi\xE1 tr\u1ECB"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${U.origin} ${j.verb} ${E}${U.minimum.toString()} ${j.unit}`;return`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${E.prefix}"`;if(E.format==="ends_with")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${E.suffix}"`;if(E.format==="includes")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${E.includes}"`;if(E.format==="regex")return`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${E.pattern}`;return`${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${V(U.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${U.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 ${U.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}};var PG=r(()=>{n()});function XL(){return{localeError:ZM()}}var ZM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${U.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`;return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${E}\uFF0C\u5B9E\u9645\u63A5\u6536 ${N}`}case"invalid_value":if(U.values.length===1)return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${M(U.values[0])}`;return`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${U.origin??"\u503C"} ${E}${U.maximum.toString()} ${j.unit??"\u4E2A\u5143\u7D20"}`;return`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${U.origin??"\u503C"} ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${U.origin} ${E}${U.minimum.toString()} ${j.unit}`;return`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${U.origin} ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${E.prefix}" \u5F00\u5934`;if(E.format==="ends_with")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${E.suffix}" \u7ED3\u5C3E`;if(E.format==="includes")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${E.includes}"`;if(E.format==="regex")return`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${E.pattern}`;return`\u65E0\u6548${D[E.format]??U.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${U.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${V(U.keys,", ")}`;case"invalid_key":return`${U.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${U.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}};var zG=r(()=>{n()});function GL(){return{localeError:HM()}}var HM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${U.expected}\uFF0C\u4F46\u6536\u5230 ${N}`;return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${E}\uFF0C\u4F46\u6536\u5230 ${N}`}case"invalid_value":if(U.values.length===1)return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${M(U.values[0])}`;return`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${U.origin??"\u503C"} \u61C9\u70BA ${E}${U.maximum.toString()} ${j.unit??"\u500B\u5143\u7D20"}`;return`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${U.origin??"\u503C"} \u61C9\u70BA ${E}${U.maximum.toString()}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${U.origin} \u61C9\u70BA ${E}${U.minimum.toString()} ${j.unit}`;return`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${U.origin} \u61C9\u70BA ${E}${U.minimum.toString()}`}case"invalid_format":{let E=U;if(E.format==="starts_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${E.prefix}" \u958B\u982D`;if(E.format==="ends_with")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${E.suffix}" \u7D50\u5C3E`;if(E.format==="includes")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${E.includes}"`;if(E.format==="regex")return`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${E.pattern}`;return`\u7121\u6548\u7684 ${D[E.format]??U.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${U.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${U.keys.length>1?"\u5011":""}\uFF1A${V(U.keys,"\u3001")}`;case"invalid_key":return`${U.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${U.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}};var gG=r(()=>{n()});function RL(){return{localeError:bM()}}var bM=()=>{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 $(U){return _[U]??null}let D={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"},I={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return(U)=>{switch(U.code){case"invalid_type":{let E=I[U.expected]??U.expected,j=Z(U.input),N=I[j]??j;if(/^[A-Z]/.test(U.expected))return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${U.expected}, \xE0m\u1ECD\u0300 a r\xED ${N}`;return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${E}, \xE0m\u1ECD\u0300 a r\xED ${N}`}case"invalid_value":if(U.values.length===1)return`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${M(U.values[0])}`;return`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${V(U.values,"|")}`;case"too_big":{let E=U.inclusive?"<=":"<",j=$(U.origin);if(j)return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${U.origin??"iye"} ${j.verb} ${E}${U.maximum} ${j.unit}`;return`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${E}${U.maximum}`}case"too_small":{let E=U.inclusive?">=":">",j=$(U.origin);if(j)return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${U.origin} ${j.verb} ${E}${U.minimum} ${j.unit}`;return`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${E}${U.minimum}`}case"invalid_format":{let E=U;if(E.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 "${E.prefix}"`;if(E.format==="ends_with")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${E.suffix}"`;if(E.format==="includes")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${E.includes}"`;if(E.format==="regex")return`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${E.pattern}`;return`A\u1E63\xEC\u1E63e: ${D[E.format]??U.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 ${U.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${V(U.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${U.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 ${U.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}};var XG=r(()=>{n()});var n0={};x$(n0,{zhTW:()=>GL,zhCN:()=>XL,yo:()=>RL,vi:()=>gL,uz:()=>zL,ur:()=>PL,uk:()=>GU,ua:()=>JL,tr:()=>LL,th:()=>SL,ta:()=>OL,sv:()=>AL,sl:()=>NL,ru:()=>jL,ro:()=>EL,pt:()=>IL,ps:()=>DL,pl:()=>UL,ota:()=>$L,no:()=>_L,nl:()=>sS,ms:()=>aS,mk:()=>eS,lt:()=>pS,ko:()=>oS,km:()=>gU,kh:()=>tS,ka:()=>lS,ja:()=>mS,it:()=>dS,is:()=>nS,id:()=>cS,hy:()=>hS,hu:()=>yS,hr:()=>uS,he:()=>xS,frCA:()=>fS,fr:()=>rS,fi:()=>wS,fa:()=>vS,es:()=>CS,eo:()=>kS,en:()=>zU,el:()=>bS,de:()=>HS,da:()=>ZS,cs:()=>MS,ca:()=>BS,bg:()=>VS,be:()=>FS,az:()=>TS,ar:()=>KS});var YL=r(()=>{R5();Y5();K5();T5();F5();V5();B5();M5();Z5();qS();H5();b5();q5();k5();C5();v5();w5();r5();f5();u5();y5();h5();c5();n5();d5();m5();iS();l5();t5();o5();p5();e5();a5();s5();_G();$G();DG();UG();EG();jG();NG();AG();OG();SG();LG();WL();WG();JG();PG();zG();gG();XG()});class QL{constructor(){this._map=new WeakMap,this._idmap=new Map}add(_,...$){let D=$[0];if(this._map.set(_,D),D&&typeof D==="object"&&"id"in D)this._idmap.set(D.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 D={...this.get($)??{}};delete D.id;let I={...D,...this._map.get(_)};return Object.keys(I).length?I:void 0}return this._map.get(_)}has(_){return this._map.has(_)}}function RU(){return new QL}var GG,DE,UE,x_;var YU=r(()=>{DE=Symbol("ZodOutput"),UE=Symbol("ZodInput");(GG=globalThis).__zod_globalRegistry??(GG.__zod_globalRegistry=RU());x_=globalThis.__zod_globalRegistry});function KL(_,$){return new _({type:"string",...v($)})}function TL(_,$){return new _({type:"string",coerce:!0,...v($)})}function IE(_,$){return new _({type:"string",format:"email",check:"string_format",abort:!1,...v($)})}function QU(_,$){return new _({type:"string",format:"guid",check:"string_format",abort:!1,...v($)})}function EE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,...v($)})}function jE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v($)})}function NE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v($)})}function AE(_,$){return new _({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v($)})}function KU(_,$){return new _({type:"string",format:"url",check:"string_format",abort:!1,...v($)})}function OE(_,$){return new _({type:"string",format:"emoji",check:"string_format",abort:!1,...v($)})}function SE(_,$){return new _({type:"string",format:"nanoid",check:"string_format",abort:!1,...v($)})}function LE(_,$){return new _({type:"string",format:"cuid",check:"string_format",abort:!1,...v($)})}function WE(_,$){return new _({type:"string",format:"cuid2",check:"string_format",abort:!1,...v($)})}function JE(_,$){return new _({type:"string",format:"ulid",check:"string_format",abort:!1,...v($)})}function PE(_,$){return new _({type:"string",format:"xid",check:"string_format",abort:!1,...v($)})}function zE(_,$){return new _({type:"string",format:"ksuid",check:"string_format",abort:!1,...v($)})}function gE(_,$){return new _({type:"string",format:"ipv4",check:"string_format",abort:!1,...v($)})}function XE(_,$){return new _({type:"string",format:"ipv6",check:"string_format",abort:!1,...v($)})}function FL(_,$){return new _({type:"string",format:"mac",check:"string_format",abort:!1,...v($)})}function GE(_,$){return new _({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v($)})}function RE(_,$){return new _({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v($)})}function YE(_,$){return new _({type:"string",format:"base64",check:"string_format",abort:!1,...v($)})}function QE(_,$){return new _({type:"string",format:"base64url",check:"string_format",abort:!1,...v($)})}function KE(_,$){return new _({type:"string",format:"e164",check:"string_format",abort:!1,...v($)})}function TE(_,$){return new _({type:"string",format:"jwt",check:"string_format",abort:!1,...v($)})}function VL(_,$){return new _({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v($)})}function BL(_,$){return new _({type:"string",format:"date",check:"string_format",...v($)})}function ML(_,$){return new _({type:"string",format:"time",check:"string_format",precision:null,...v($)})}function ZL(_,$){return new _({type:"string",format:"duration",check:"string_format",...v($)})}function HL(_,$){return new _({type:"number",checks:[],...v($)})}function bL(_,$){return new _({type:"number",coerce:!0,checks:[],...v($)})}function qL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"safeint",...v($)})}function kL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float32",...v($)})}function CL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"float64",...v($)})}function vL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"int32",...v($)})}function wL(_,$){return new _({type:"number",check:"number_format",abort:!1,format:"uint32",...v($)})}function rL(_,$){return new _({type:"boolean",...v($)})}function fL(_,$){return new _({type:"boolean",coerce:!0,...v($)})}function xL(_,$){return new _({type:"bigint",...v($)})}function uL(_,$){return new _({type:"bigint",coerce:!0,...v($)})}function yL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...v($)})}function hL(_,$){return new _({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...v($)})}function cL(_,$){return new _({type:"symbol",...v($)})}function nL(_,$){return new _({type:"undefined",...v($)})}function dL(_,$){return new _({type:"null",...v($)})}function mL(_){return new _({type:"any"})}function lL(_){return new _({type:"unknown"})}function iL(_,$){return new _({type:"never",...v($)})}function tL(_,$){return new _({type:"void",...v($)})}function oL(_,$){return new _({type:"date",...v($)})}function pL(_,$){return new _({type:"date",coerce:!0,...v($)})}function eL(_,$){return new _({type:"nan",...v($)})}function V$(_,$){return new nI({check:"less_than",...v($),value:_,inclusive:!1})}function I$(_,$){return new nI({check:"less_than",...v($),value:_,inclusive:!0})}function B$(_,$){return new dI({check:"greater_than",...v($),value:_,inclusive:!1})}function c_(_,$){return new dI({check:"greater_than",...v($),value:_,inclusive:!0})}function TU(_){return B$(0,_)}function FU(_){return V$(0,_)}function VU(_){return I$(0,_)}function BU(_){return c_(0,_)}function W6(_,$){return new mA({check:"multiple_of",...v($),value:_})}function J6(_,$){return new tA({check:"max_size",...v($),maximum:_})}function M$(_,$){return new oA({check:"min_size",...v($),minimum:_})}function f6(_,$){return new pA({check:"size_equals",...v($),size:_})}function x6(_,$){return new eA({check:"max_length",...v($),maximum:_})}function l$(_,$){return new aA({check:"min_length",...v($),minimum:_})}function u6(_,$){return new sA({check:"length_equals",...v($),length:_})}function K4(_,$){return new _O({check:"string_format",format:"regex",...v($),pattern:_})}function T4(_){return new $O({check:"string_format",format:"lowercase",...v(_)})}function F4(_){return new DO({check:"string_format",format:"uppercase",...v(_)})}function V4(_,$){return new UO({check:"string_format",format:"includes",...v($),includes:_})}function B4(_,$){return new IO({check:"string_format",format:"starts_with",...v($),prefix:_})}function M4(_,$){return new EO({check:"string_format",format:"ends_with",...v($),suffix:_})}function MU(_,$,D){return new jO({check:"property",property:_,schema:$,...v(D)})}function Z4(_,$){return new NO({check:"mime_type",mime:_,...v($)})}function X$(_){return new AO({check:"overwrite",tx:_})}function H4(_){return X$(($)=>$.normalize(_))}function b4(){return X$((_)=>_.trim())}function q4(){return X$((_)=>_.toLowerCase())}function k4(){return X$((_)=>_.toUpperCase())}function C4(){return X$((_)=>IA(_))}function aL(_,$,D){return new _({type:"array",element:$,...v(D)})}function kM(_,$,D){return new _({type:"union",options:$,...v(D)})}function CM(_,$,D){return new _({type:"union",options:$,inclusive:!1,...v(D)})}function vM(_,$,D,I){return new _({type:"union",options:D,discriminator:$,...v(I)})}function wM(_,$,D){return new _({type:"intersection",left:$,right:D})}function rM(_,$,D,I){let U=D instanceof p;return new _({type:"tuple",items:$,rest:U?D:null,...v(U?I:D)})}function fM(_,$,D,I){return new _({type:"record",keyType:$,valueType:D,...v(I)})}function xM(_,$,D,I){return new _({type:"map",keyType:$,valueType:D,...v(I)})}function uM(_,$,D){return new _({type:"set",valueType:$,...v(D)})}function yM(_,$,D){let I=Array.isArray($)?Object.fromEntries($.map((U)=>[U,U])):$;return new _({type:"enum",entries:I,...v(D)})}function hM(_,$,D){return new _({type:"enum",entries:$,...v(D)})}function cM(_,$,D){return new _({type:"literal",values:Array.isArray($)?$:[$],...v(D)})}function sL(_,$){return new _({type:"file",...v($)})}function nM(_,$){return new _({type:"transform",transform:$})}function dM(_,$){return new _({type:"optional",innerType:$})}function mM(_,$){return new _({type:"nullable",innerType:$})}function lM(_,$,D){return new _({type:"default",innerType:$,get defaultValue(){return typeof D==="function"?D():jA(D)}})}function iM(_,$,D){return new _({type:"nonoptional",innerType:$,...v(D)})}function tM(_,$){return new _({type:"success",innerType:$})}function oM(_,$,D){return new _({type:"catch",innerType:$,catchValue:typeof D==="function"?D:()=>D})}function pM(_,$,D){return new _({type:"pipe",in:$,out:D})}function eM(_,$){return new _({type:"readonly",innerType:$})}function aM(_,$,D){return new _({type:"template_literal",parts:$,...v(D)})}function sM(_,$){return new _({type:"lazy",getter:$})}function _Z(_,$){return new _({type:"promise",innerType:$})}function _W(_,$,D){let I=v(D);return I.abort??(I.abort=!0),new _({type:"custom",check:"custom",fn:$,...I})}function $W(_,$,D){return new _({type:"custom",check:"custom",fn:$,...v(D)})}function DW(_,$){let D=RG((I)=>{return I.addIssue=(U)=>{if(typeof U==="string")I.issues.push(v0(U,I.value,D._zod.def));else{let E=U;if(E.fatal)E.continue=!1;E.code??(E.code="custom"),E.input??(E.input=I.value),E.inst??(E.inst=D),E.continue??(E.continue=!D._zod.def.abort),I.issues.push(v0(E))}},_(I.value,I)},$);return D}function RG(_,$){let D=new Q_({check:"custom",...v($)});return D._zod.check=_,D}function UW(_){let $=new Q_({check:"describe"});return $._zod.onattach=[(D)=>{let I=x_.get(D)??{};x_.add(D,{...I,description:_})}],$._zod.check=()=>{},$}function IW(_){let $=new Q_({check:"meta"});return $._zod.onattach=[(D)=>{let I=x_.get(D)??{};x_.add(D,{...I,..._})}],$._zod.check=()=>{},$}function EW(_,$){let D=v($),I=D.truthy??["true","1","yes","on","y","enabled"],U=D.falsy??["false","0","no","off","n","disabled"];if(D.case!=="sensitive")I=I.map((z)=>typeof z==="string"?z.toLowerCase():z),U=U.map((z)=>typeof z==="string"?z.toLowerCase():z);let E=new Set(I),j=new Set(U),N=_.Codec??PU,O=_.Boolean??WU,L=new(_.String??Q4)({type:"string",error:D.error}),W=new O({type:"boolean",error:D.error}),g=new N({type:"pipe",in:L,out:W,transform:(z,G)=>{let J=z;if(D.case!=="sensitive")J=J.toLowerCase();if(E.has(J))return!0;else if(j.has(J))return!1;else return G.issues.push({code:"invalid_value",expected:"stringbool",values:[...E,...j],input:G.value,inst:g,continue:!1}),{}},reverseTransform:(z,G)=>{if(z===!0)return I[0]||"true";else return U[0]||"false"},error:D.error});return g}function d0(_,$,D,I={}){let U=v(I),E={...v(I),check:"string_format",type:"string",format:$,fn:typeof D==="function"?D:(N)=>D.test(N),...U};if(D instanceof RegExp)E.pattern=D;return new _(E)}var FE;var YG=r(()=>{mI();YU();QS();n();FE={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function y6(_){let $=_?.target??"draft-2020-12";if($==="draft-4")$="draft-04";if($==="draft-7")$="draft-07";return{processors:_.processors??{},metadataRegistry:_?.metadata??x_,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 W_(_,$,D={path:[],schemaPath:[]}){var I;let U=_._zod.def,E=$.seen.get(_);if(E){if(E.count++,D.schemaPath.includes(_))E.cycle=D.path;return E.schema}let j={schema:{},count:1,cycle:void 0,path:D.path};$.seen.set(_,j);let N=_._zod.toJSONSchema?.();if(N)j.schema=N;else{let L={...D,schemaPath:[...D.schemaPath,_],path:D.path};if(_._zod.processJSONSchema)_._zod.processJSONSchema($,j.schema,L);else{let g=j.schema,z=$.processors[U.type];if(!z)throw Error(`[toJSONSchema]: Non-representable type encountered: ${U.type}`);z(_,$,g,L)}let W=_._zod.parent;if(W){if(!j.ref)j.ref=W;W_(W,$,L),$.seen.get(W).isParent=!0}}let O=$.metadataRegistry.get(_);if(O)Object.assign(j.schema,O);if($.io==="input"&&o_(_))delete j.schema.examples,delete j.schema.default;if($.io==="input"&&"_prefault"in j.schema)(I=j.schema).default??(I.default=j.schema._prefault);return delete j.schema._prefault,$.seen.get(_).schema}function h6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let I=new Map;for(let j of _.seen.entries()){let N=_.metadataRegistry.get(j[0])?.id;if(N){let O=I.get(N);if(O&&O!==j[0])throw Error(`Duplicate schema id "${N}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);I.set(N,j[0])}}let U=(j)=>{let N=_.target==="draft-2020-12"?"$defs":"definitions";if(_.external){let W=_.external.registry.get(j[0])?.id,g=_.external.uri??((G)=>G);if(W)return{ref:g(W)};let z=j[1].defId??j[1].schema.id??`schema${_.counter++}`;return j[1].defId=z,{defId:z,ref:`${g("__shared")}#/${N}/${z}`}}if(j[1]===D)return{ref:"#"};let S=`${"#"}/${N}/`,L=j[1].schema.id??`__schema${_.counter++}`;return{defId:L,ref:S+L}},E=(j)=>{if(j[1].schema.$ref)return;let N=j[1],{ref:O,defId:S}=U(j);if(N.def={...N.schema},S)N.defId=S;let L=N.schema;for(let W in L)delete L[W];L.$ref=O};if(_.cycles==="throw")for(let j of _.seen.entries()){let N=j[1];if(N.cycle)throw Error(`Cycle detected: #/${N.cycle?.join("/")}/ -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let j of _.seen.entries()){let N=j[1];if($===j[0]){E(j);continue}if(_.external){let O=_.external.registry.get(j[0])?.id;if($!==j[0]&&O){E(j);continue}}if(_.metadataRegistry.get(j[0])?.id){E(j);continue}if(N.cycle){E(j);continue}if(N.count>1){if(_.reused==="ref"){E(j);continue}}}}function c6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let I=(N)=>{let A=_.seen.get(N);if(A.ref===null)return;let O=A.def??A.schema,S={...O},L=A.ref;if(A.ref=null,L){I(L);let z=_.seen.get(L),G=z.schema;if(G.$ref&&(_.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"))O.allOf=O.allOf??[],O.allOf.push(G);else Object.assign(O,G);if(Object.assign(O,S),N._zod.parent===L)for(let W in O){if(W==="$ref"||W==="allOf")continue;if(!(W in S))delete O[W]}if(G.$ref&&z.def)for(let W in O){if(W==="$ref"||W==="allOf")continue;if(W in z.def&&JSON.stringify(O[W])===JSON.stringify(z.def[W]))delete O[W]}}let P=N._zod.parent;if(P&&P!==L){I(P);let z=_.seen.get(P);if(z?.schema.$ref){if(O.$ref=z.schema.$ref,z.def)for(let G in O){if(G==="$ref"||G==="allOf")continue;if(G in z.def&&JSON.stringify(O[G])===JSON.stringify(z.def[G]))delete O[G]}}}_.override({zodSchema:N,jsonSchema:O,path:A.path??[]})};for(let N of[..._.seen.entries()].reverse())I(N[0]);let U={};if(_.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if(_.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";else if(_.target==="draft-04")U.$schema="http://json-schema.org/draft-04/schema#";else if(_.target==="openapi-3.0");if(_.external?.uri){let N=_.external.registry.get($)?.id;if(!N)throw Error("Schema is missing an `id` property");U.$id=_.external.uri(N)}Object.assign(U,D.def??D.schema);let E=_.metadataRegistry.get($)?.id;if(E!==void 0&&U.id===E)delete U.id;let j=_.external?.defs??{};for(let N of _.seen.entries()){let A=N[1];if(A.def&&A.defId){if(A.def.id===A.defId)delete A.def.id;j[A.defId]=A.def}}if(_.external);else if(Object.keys(j).length>0)if(_.target==="draft-2020-12")U.$defs=j;else U.definitions=j;try{let N=JSON.parse(JSON.stringify(U));return Object.defineProperty(N,"~standard",{value:{...$["~standard"],jsonSchema:{input:n0($,"input",_.processors),output:n0($,"output",_.processors)}},enumerable:!1,writable:!1}),N}catch(N){throw Error("Error converting schema to JSON.")}}function o_(_,$){let D=$??{seen:new Set};if(D.seen.has(_))return!1;D.seen.add(_);let I=_._zod.def;if(I.type==="transform")return!0;if(I.type==="array")return o_(I.element,D);if(I.type==="set")return o_(I.valueType,D);if(I.type==="lazy")return o_(I.getter(),D);if(I.type==="promise"||I.type==="optional"||I.type==="nonoptional"||I.type==="nullable"||I.type==="readonly"||I.type==="default"||I.type==="prefault")return o_(I.innerType,D);if(I.type==="intersection")return o_(I.left,D)||o_(I.right,D);if(I.type==="record"||I.type==="map")return o_(I.keyType,D)||o_(I.valueType,D);if(I.type==="pipe"){if(_._zod.traits.has("$ZodCodec"))return!0;return o_(I.in,D)||o_(I.out,D)}if(I.type==="object"){for(let U in I.shape)if(o_(I.shape[U],D))return!0;return!1}if(I.type==="union"){for(let U of I.options)if(o_(U,D))return!0;return!1}if(I.type==="tuple"){for(let U of I.items)if(o_(U,D))return!0;if(I.rest&&o_(I.rest,D))return!0;return!1}return!1}var jL=(_,$={})=>(D)=>{let I=y6({...D,processors:$});return L_(_,I),h6(I,_),c6(I,_)},n0=(_,$,D={})=>(I)=>{let{libraryOptions:U,target:E}=I??{},j=y6({...U??{},target:E,io:$,processors:D});return L_(_,j),h6(j,_),c6(j,_)};var bU=r(()=>{YU()});function ZU(_,$){if("_idmap"in _){let I=_,U=y6({...$,processors:FE}),E={};for(let A of I._idmap.entries()){let[O,S]=A;L_(S,U)}let j={},N={registry:I,uri:$?.uri,defs:E};U.external=N;for(let A of I._idmap.entries()){let[O,S]=A;h6(U,S),j[O]=c6(U,S)}if(Object.keys(E).length>0){let A=U.target==="draft-2020-12"?"$defs":"definitions";j.__shared={[A]:E}}return{schemas:j}}let D=y6({...$,processors:FE});return L_(_,D),h6(D,_),c6(D,_)}var $b,NL=(_,$,D,I)=>{let U=D;U.type="string";let{minimum:E,maximum:j,format:N,patterns:A,contentEncoding:O}=_._zod.bag;if(typeof E==="number")U.minLength=E;if(typeof j==="number")U.maxLength=j;if(N){if(U.format=$b[N]??N,U.format==="")delete U.format;if(N==="time")delete U.format}if(O)U.contentEncoding=O;if(A&&A.size>0){let S=[...A];if(S.length===1)U.pattern=S[0].source;else if(S.length>1)U.allOf=[...S.map((L)=>({...$.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"?{type:"string"}:{},pattern:L.source}))]}},gL=(_,$,D,I)=>{let U=D,{minimum:E,maximum:j,format:N,multipleOf:A,exclusiveMaximum:O,exclusiveMinimum:S}=_._zod.bag;if(typeof N==="string"&&N.includes("int"))U.type="integer";else U.type="number";let L=typeof S==="number"&&S>=(E??Number.NEGATIVE_INFINITY),P=typeof O==="number"&&O<=(j??Number.POSITIVE_INFINITY),z=$.target==="draft-04"||$.target==="openapi-3.0";if(L)if(z)U.minimum=S,U.exclusiveMinimum=!0;else U.exclusiveMinimum=S;else if(typeof E==="number")U.minimum=E;if(P)if(z)U.maximum=O,U.exclusiveMaximum=!0;else U.exclusiveMaximum=O;else if(typeof j==="number")U.maximum=j;if(typeof A==="number")U.multipleOf=A},AL=(_,$,D,I)=>{D.type="boolean"},OL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},SL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},LL=(_,$,D,I)=>{if($.target==="openapi-3.0")D.type="string",D.nullable=!0,D.enum=[null];else D.type="null"},JL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},WL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},PL=(_,$,D,I)=>{D.not={}},zL=(_,$,D,I)=>{},XL=(_,$,D,I)=>{},GL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},RL=(_,$,D,I)=>{let U=_._zod.def,E=UU(U.entries);if(E.every((j)=>typeof j==="number"))D.type="number";if(E.every((j)=>typeof j==="string"))D.type="string";D.enum=E},YL=(_,$,D,I)=>{let U=_._zod.def,E=[];for(let j of U.values)if(j===void 0){if($.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if($.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else E.push(Number(j));else E.push(j);if(E.length===0);else if(E.length===1){let j=E[0];if(D.type=j===null?"null":typeof j,$.target==="draft-04"||$.target==="openapi-3.0")D.enum=[j];else D.const=j}else{if(E.every((j)=>typeof j==="number"))D.type="number";if(E.every((j)=>typeof j==="string"))D.type="string";if(E.every((j)=>typeof j==="boolean"))D.type="boolean";if(E.every((j)=>j===null))D.type="null";D.enum=E}},QL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},KL=(_,$,D,I)=>{let U=D,E=_._zod.pattern;if(!E)throw Error("Pattern not found in template literal");U.type="string",U.pattern=E.source},TL=(_,$,D,I)=>{let U=D,E={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:N,mime:A}=_._zod.bag;if(j!==void 0)E.minLength=j;if(N!==void 0)E.maxLength=N;if(A)if(A.length===1)E.contentMediaType=A[0],Object.assign(U,E);else Object.assign(U,E),U.anyOf=A.map((O)=>({contentMediaType:O}));else Object.assign(U,E)},FL=(_,$,D,I)=>{D.type="boolean"},VL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},BL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},ML=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},bL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},ZL=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},HL=(_,$,D,I)=>{let U=D,E=_._zod.def,{minimum:j,maximum:N}=_._zod.bag;if(typeof j==="number")U.minItems=j;if(typeof N==="number")U.maxItems=N;U.type="array",U.items=L_(E.element,$,{...I,path:[...I.path,"items"]})},kL=(_,$,D,I)=>{let U=D,E=_._zod.def;U.type="object",U.properties={};let j=E.shape;for(let O in j)U.properties[O]=L_(j[O],$,{...I,path:[...I.path,"properties",O]});let N=new Set(Object.keys(j)),A=new Set([...N].filter((O)=>{let S=E.shape[O]._zod;if($.io==="input")return S.optin===void 0;else return S.optout===void 0}));if(A.size>0)U.required=Array.from(A);if(E.catchall?._zod.def.type==="never")U.additionalProperties=!1;else if(!E.catchall){if($.io==="output")U.additionalProperties=!1}else if(E.catchall)U.additionalProperties=L_(E.catchall,$,{...I,path:[...I.path,"additionalProperties"]})},VE=(_,$,D,I)=>{let U=_._zod.def,E=U.inclusive===!1,j=U.options.map((N,A)=>L_(N,$,{...I,path:[...I.path,E?"oneOf":"anyOf",A]}));if(E)D.oneOf=j;else D.anyOf=j},qL=(_,$,D,I)=>{let U=_._zod.def,E=L_(U.left,$,{...I,path:[...I.path,"allOf",0]}),j=L_(U.right,$,{...I,path:[...I.path,"allOf",1]}),N=(O)=>("allOf"in O)&&Object.keys(O).length===1,A=[...N(E)?E.allOf:[E],...N(j)?j.allOf:[j]];D.allOf=A},CL=(_,$,D,I)=>{let U=D,E=_._zod.def;U.type="array";let j=$.target==="draft-2020-12"?"prefixItems":"items",N=$.target==="draft-2020-12"?"items":$.target==="openapi-3.0"?"items":"additionalItems",A=E.items.map((P,z)=>L_(P,$,{...I,path:[...I.path,j,z]})),O=E.rest?L_(E.rest,$,{...I,path:[...I.path,N,...$.target==="openapi-3.0"?[E.items.length]:[]]}):null;if($.target==="draft-2020-12"){if(U.prefixItems=A,O)U.items=O}else if($.target==="openapi-3.0"){if(U.items={anyOf:A},O)U.items.anyOf.push(O);if(U.minItems=A.length,!O)U.maxItems=A.length}else if(U.items=A,O)U.additionalItems=O;let{minimum:S,maximum:L}=_._zod.bag;if(typeof S==="number")U.minItems=S;if(typeof L==="number")U.maxItems=L},vL=(_,$,D,I)=>{let U=D,E=_._zod.def;U.type="object";let j=E.keyType,A=j._zod.bag?.patterns;if(E.mode==="loose"&&A&&A.size>0){let S=L_(E.valueType,$,{...I,path:[...I.path,"patternProperties","*"]});U.patternProperties={};for(let L of A)U.patternProperties[L.source]=S}else{if($.target==="draft-07"||$.target==="draft-2020-12")U.propertyNames=L_(E.keyType,$,{...I,path:[...I.path,"propertyNames"]});U.additionalProperties=L_(E.valueType,$,{...I,path:[...I.path,"additionalProperties"]})}let O=j._zod.values;if(O){let S=[...O].filter((L)=>typeof L==="string"||typeof L==="number");if(S.length>0)U.required=S}},wL=(_,$,D,I)=>{let U=_._zod.def,E=L_(U.innerType,$,I),j=$.seen.get(_);if($.target==="openapi-3.0")j.ref=U.innerType,D.nullable=!0;else D.anyOf=[E,{type:"null"}]},rL=(_,$,D,I)=>{let U=_._zod.def;L_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType},fL=(_,$,D,I)=>{let U=_._zod.def;L_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType,D.default=JSON.parse(JSON.stringify(U.defaultValue))},xL=(_,$,D,I)=>{let U=_._zod.def;L_(U.innerType,$,I);let E=$.seen.get(_);if(E.ref=U.innerType,$.io==="input")D._prefault=JSON.parse(JSON.stringify(U.defaultValue))},uL=(_,$,D,I)=>{let U=_._zod.def;L_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType;let j;try{j=U.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}D.default=j},yL=(_,$,D,I)=>{let U=_._zod.def,E=U.in._zod.traits.has("$ZodTransform"),j=$.io==="input"?E?U.out:U.in:U.out;L_(j,$,I);let N=$.seen.get(_);N.ref=j},hL=(_,$,D,I)=>{let U=_._zod.def;L_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType,D.readOnly=!0},cL=(_,$,D,I)=>{let U=_._zod.def;L_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType},BE=(_,$,D,I)=>{let U=_._zod.def;L_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType},nL=(_,$,D,I)=>{let U=_._zod.innerType;L_(U,$,I);let E=$.seen.get(_);E.ref=U},FE;var HU=r(()=>{bU();n();$b={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},FE={string:NL,number:gL,boolean:AL,bigint:OL,symbol:SL,null:LL,undefined:JL,void:WL,never:PL,any:zL,unknown:XL,date:GL,enum:RL,literal:YL,nan:QL,template_literal:KL,file:TL,success:FL,custom:VL,function:BL,transform:ML,map:bL,set:ZL,array:HL,object:kL,union:VE,intersection:qL,tuple:CL,record:vL,nullable:wL,nonoptional:rL,default:fL,prefault:xL,catch:uL,pipe:yL,readonly:hL,promise:cL,optional:BE,lazy:nL}});class dL{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=y6({processors:FE,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}h6(this.ctx,_);let D=c6(this.ctx,_),{"~standard":I,...U}=D;return U}}var YG=r(()=>{HU();bU()});var QG={};var KG=()=>{};var i$={};x$(i$,{version:()=>AA,util:()=>H,treeifyError:()=>bI,toJSONSchema:()=>ZU,toDotPath:()=>lX,safeParseAsync:()=>W2,safeParse:()=>J2,safeEncodeAsync:()=>IB,safeEncode:()=>DB,safeDecodeAsync:()=>EB,safeDecode:()=>UB,registry:()=>RU,regexes:()=>U$,process:()=>L_,prettifyError:()=>ZI,parseAsync:()=>kI,parse:()=>HI,meta:()=>IL,locales:()=>h0,isValidJWT:()=>W5,isValidBase64URL:()=>J5,isValidBase64:()=>qA,initializeContext:()=>y6,globalRegistry:()=>x_,globalConfig:()=>P4,formatError:()=>v0,flattenError:()=>C0,finalize:()=>c6,extractDefs:()=>h6,encodeAsync:()=>_B,encode:()=>aV,describe:()=>UL,decodeAsync:()=>$B,decode:()=>sV,createToJSONSchemaMethod:()=>jL,createStandardJSONSchemaMethod:()=>n0,config:()=>Z_,clone:()=>h_,_xor:()=>CM,_xid:()=>JE,_void:()=>tS,_uuidv7:()=>NE,_uuidv6:()=>jE,_uuidv4:()=>EE,_uuid:()=>IE,_url:()=>KU,_uppercase:()=>T4,_unknown:()=>lS,_union:()=>qM,_undefined:()=>nS,_ulid:()=>LE,_uint64:()=>hS,_uint32:()=>wS,_tuple:()=>rM,_trim:()=>Z4,_transform:()=>nM,_toUpperCase:()=>k4,_toLowerCase:()=>H4,_templateLiteral:()=>aM,_symbol:()=>cS,_superRefine:()=>DL,_success:()=>tM,_stringbool:()=>EL,_stringFormat:()=>c0,_string:()=>KS,_startsWith:()=>V4,_slugify:()=>q4,_size:()=>f6,_set:()=>uM,_safeParseAsync:()=>x0,_safeParse:()=>f0,_safeEncodeAsync:()=>xI,_safeEncode:()=>rI,_safeDecodeAsync:()=>uI,_safeDecode:()=>fI,_regex:()=>Q4,_refine:()=>$L,_record:()=>fM,_readonly:()=>eM,_property:()=>MU,_promise:()=>_b,_positive:()=>TU,_pipe:()=>pM,_parseAsync:()=>r0,_parse:()=>w0,_overwrite:()=>X$,_optional:()=>dM,_number:()=>ZS,_nullable:()=>mM,_null:()=>dS,_normalize:()=>b4,_nonpositive:()=>VU,_nonoptional:()=>iM,_nonnegative:()=>BU,_never:()=>iS,_negative:()=>FU,_nativeEnum:()=>hM,_nanoid:()=>AE,_nan:()=>eS,_multipleOf:()=>L6,_minSize:()=>M$,_minLength:()=>l$,_min:()=>c_,_mime:()=>M4,_maxSize:()=>J6,_maxLength:()=>x6,_max:()=>I$,_map:()=>xM,_mac:()=>FS,_lte:()=>I$,_lt:()=>V$,_lowercase:()=>K4,_literal:()=>cM,_length:()=>u6,_lazy:()=>sM,_ksuid:()=>WE,_jwt:()=>KE,_isoTime:()=>MS,_isoDuration:()=>bS,_isoDateTime:()=>VS,_isoDate:()=>BS,_ipv6:()=>zE,_ipv4:()=>PE,_intersection:()=>wM,_int64:()=>yS,_int32:()=>vS,_int:()=>kS,_includes:()=>F4,_guid:()=>QU,_gte:()=>c_,_gt:()=>B$,_float64:()=>CS,_float32:()=>qS,_file:()=>sS,_enum:()=>yM,_endsWith:()=>B4,_encodeAsync:()=>vI,_encode:()=>qI,_emoji:()=>gE,_email:()=>UE,_e164:()=>QE,_discriminatedUnion:()=>vM,_default:()=>lM,_decodeAsync:()=>wI,_decode:()=>CI,_date:()=>oS,_custom:()=>_L,_cuid2:()=>SE,_cuid:()=>OE,_coercedString:()=>TS,_coercedNumber:()=>HS,_coercedDate:()=>pS,_coercedBoolean:()=>fS,_coercedBigint:()=>uS,_cidrv6:()=>GE,_cidrv4:()=>XE,_check:()=>GG,_catch:()=>oM,_boolean:()=>rS,_bigint:()=>xS,_base64url:()=>YE,_base64:()=>RE,_array:()=>aS,_any:()=>mS,TimePrecision:()=>TE,NEVER:()=>FI,JSONSchemaGenerator:()=>dL,JSONSchema:()=>QG,Doc:()=>mI,$output:()=>$E,$input:()=>DE,$constructor:()=>K,$brand:()=>VI,$ZodXor:()=>pA,$ZodXID:()=>QA,$ZodVoid:()=>lA,$ZodUnknown:()=>dA,$ZodUnion:()=>JU,$ZodUndefined:()=>hA,$ZodUUID:()=>JA,$ZodURL:()=>PA,$ZodULID:()=>YA,$ZodType:()=>o,$ZodTuple:()=>aI,$ZodTransform:()=>EO,$ZodTemplateLiteral:()=>zO,$ZodSymbol:()=>yA,$ZodSuccess:()=>SO,$ZodStringFormat:()=>Y_,$ZodString:()=>Y4,$ZodSet:()=>$O,$ZodRegistry:()=>QS,$ZodRecord:()=>sA,$ZodRealError:()=>D$,$ZodReadonly:()=>PO,$ZodPromise:()=>GO,$ZodPreprocess:()=>WO,$ZodPrefault:()=>AO,$ZodPipe:()=>_E,$ZodOptional:()=>sI,$ZodObjectJIT:()=>oA,$ZodObject:()=>X5,$ZodNumberFormat:()=>xA,$ZodNumber:()=>pI,$ZodNullable:()=>NO,$ZodNull:()=>cA,$ZodNonOptional:()=>OO,$ZodNever:()=>mA,$ZodNanoID:()=>XA,$ZodNaN:()=>JO,$ZodMap:()=>_O,$ZodMAC:()=>ZA,$ZodLiteral:()=>UO,$ZodLazy:()=>RO,$ZodKSUID:()=>KA,$ZodJWT:()=>rA,$ZodIntersection:()=>aA,$ZodISOTime:()=>VA,$ZodISODuration:()=>BA,$ZodISODateTime:()=>TA,$ZodISODate:()=>FA,$ZodIPv6:()=>bA,$ZodIPv4:()=>MA,$ZodGUID:()=>LA,$ZodFunction:()=>XO,$ZodFile:()=>IO,$ZodExactOptional:()=>jO,$ZodError:()=>gU,$ZodEnum:()=>DO,$ZodEncodeError:()=>z4,$ZodEmoji:()=>zA,$ZodEmail:()=>WA,$ZodE164:()=>wA,$ZodDiscriminatedUnion:()=>eA,$ZodDefault:()=>gO,$ZodDate:()=>iA,$ZodCustomStringFormat:()=>fA,$ZodCustom:()=>YO,$ZodCodec:()=>WU,$ZodCheckUpperCase:()=>DA,$ZodCheckStringFormat:()=>u0,$ZodCheckStartsWith:()=>IA,$ZodCheckSizeEquals:()=>p2,$ZodCheckRegex:()=>_A,$ZodCheckProperty:()=>jA,$ZodCheckOverwrite:()=>gA,$ZodCheckNumberFormat:()=>l2,$ZodCheckMultipleOf:()=>m2,$ZodCheckMinSize:()=>o2,$ZodCheckMinLength:()=>a2,$ZodCheckMimeType:()=>NA,$ZodCheckMaxSize:()=>t2,$ZodCheckMaxLength:()=>e2,$ZodCheckLowerCase:()=>$A,$ZodCheckLessThan:()=>cI,$ZodCheckLengthEquals:()=>s2,$ZodCheckIncludes:()=>UA,$ZodCheckGreaterThan:()=>nI,$ZodCheckEndsWith:()=>EA,$ZodCheckBigIntFormat:()=>i2,$ZodCheck:()=>Q_,$ZodCatch:()=>LO,$ZodCUID2:()=>RA,$ZodCUID:()=>GA,$ZodCIDRv6:()=>kA,$ZodCIDRv4:()=>HA,$ZodBoolean:()=>LU,$ZodBigIntFormat:()=>uA,$ZodBigInt:()=>eI,$ZodBase64URL:()=>vA,$ZodBase64:()=>CA,$ZodAsyncError:()=>m$,$ZodArray:()=>tA,$ZodAny:()=>nA});var O$=r(()=>{n();hI();YS();HU();YG();KG();X4();P2();L2();QO();dI();OA();YU();RG();bU()});var ME={};x$(ME,{uppercase:()=>T4,trim:()=>Z4,toUpperCase:()=>k4,toLowerCase:()=>H4,startsWith:()=>V4,slugify:()=>q4,size:()=>f6,regex:()=>Q4,property:()=>MU,positive:()=>TU,overwrite:()=>X$,normalize:()=>b4,nonpositive:()=>VU,nonnegative:()=>BU,negative:()=>FU,multipleOf:()=>L6,minSize:()=>M$,minLength:()=>l$,mime:()=>M4,maxSize:()=>J6,maxLength:()=>x6,lte:()=>I$,lt:()=>V$,lowercase:()=>K4,length:()=>u6,includes:()=>F4,gte:()=>c_,gt:()=>B$,endsWith:()=>B4});var bE=r(()=>{O$()});var C4={};x$(C4,{time:()=>iL,duration:()=>tL,datetime:()=>mL,date:()=>lL,ZodISOTime:()=>CU,ZodISODuration:()=>vU,ZodISODateTime:()=>kU,ZodISODate:()=>qU});function mL(_){return VS(kU,_)}function lL(_){return BS(qU,_)}function iL(_){return MS(CU,_)}function tL(_){return bS(vU,_)}var kU,qU,CU,vU;var wU=r(()=>{O$();fU();kU=K("ZodISODateTime",(_,$)=>{TA.init(_,$),P_.init(_,$)});qU=K("ZodISODate",(_,$)=>{FA.init(_,$),P_.init(_,$)});CU=K("ZodISOTime",(_,$)=>{VA.init(_,$),P_.init(_,$)});vU=K("ZodISODuration",(_,$)=>{BA.init(_,$),P_.init(_,$)})});var TG=(_,$)=>{gU.init(_,$),_.name="ZodError",Object.defineProperties(_,{format:{value:(D)=>v0(_,D)},flatten:{value:(D)=>C0(_,D)},addIssue:{value:(D)=>{_.issues.push(D),_.message=JSON.stringify(_.issues,H0,2)}},addIssues:{value:(D)=>{_.issues.push(...D),_.message=JSON.stringify(_.issues,H0,2)}},isEmpty:{get(){return _.issues.length===0}}})},FG,p_;var oL=r(()=>{O$();O$();n();FG=K("ZodError",TG),p_=K("ZodError",TG,{Parent:Error})});var ZE,HE,kE,qE,CE,vE,wE,rE,fE,xE,uE,yE;var pL=r(()=>{O$();oL();ZE=w0(p_),HE=r0(p_),kE=f0(p_),qE=x0(p_),CE=qI(p_),vE=CI(p_),wE=vI(p_),rE=wI(p_),fE=rI(p_),xE=fI(p_),uE=xI(p_),yE=uI(p_)});var rU={};x$(rU,{xor:()=>hJ,xid:()=>OJ,void:()=>wJ,uuidv7:()=>DJ,uuidv6:()=>$J,uuidv4:()=>_J,uuid:()=>sL,url:()=>UJ,unknown:()=>n6,union:()=>j1,undefined:()=>CJ,ulid:()=>AJ,uint64:()=>kJ,uint32:()=>bJ,tuple:()=>Ij,transform:()=>g1,templateLiteral:()=>$W,symbol:()=>qJ,superRefine:()=>qj,success:()=>eJ,stringbool:()=>AW,stringFormat:()=>QJ,string:()=>d0,strictObject:()=>uJ,set:()=>lJ,refine:()=>kj,record:()=>Ej,readonly:()=>Vj,promise:()=>DW,preprocess:()=>SW,prefault:()=>Xj,pipe:()=>uU,partialRecord:()=>nJ,optional:()=>l0,object:()=>xJ,number:()=>cE,nullish:()=>pJ,nullable:()=>i0,null:()=>iE,nonoptional:()=>Gj,never:()=>E1,nativeEnum:()=>iJ,nanoid:()=>jJ,nan:()=>aJ,meta:()=>NW,map:()=>mJ,mac:()=>JJ,looseRecord:()=>dJ,looseObject:()=>yJ,literal:()=>tJ,lazy:()=>bj,ksuid:()=>SJ,keyof:()=>fJ,jwt:()=>YJ,json:()=>OW,ipv6:()=>WJ,ipv4:()=>LJ,invertCodec:()=>_W,intersection:()=>Dj,int64:()=>HJ,int32:()=>MJ,int:()=>xU,instanceof:()=>gW,httpUrl:()=>IJ,hostname:()=>KJ,hex:()=>TJ,hash:()=>FJ,guid:()=>aL,function:()=>UW,float64:()=>BJ,float32:()=>VJ,file:()=>oJ,exactOptional:()=>Lj,enum:()=>N1,emoji:()=>EJ,email:()=>eL,e164:()=>RJ,discriminatedUnion:()=>cJ,describe:()=>jW,date:()=>rJ,custom:()=>EW,cuid2:()=>gJ,cuid:()=>NJ,codec:()=>sJ,cidrv6:()=>zJ,cidrv4:()=>PJ,check:()=>IW,catch:()=>Qj,boolean:()=>nE,bigint:()=>ZJ,base64url:()=>GJ,base64:()=>XJ,array:()=>p0,any:()=>vJ,_function:()=>UW,_default:()=>Pj,_ZodString:()=>hU,ZodXor:()=>sE,ZodXID:()=>tU,ZodVoid:()=>eE,ZodUnknown:()=>oE,ZodUnion:()=>a0,ZodUndefined:()=>mE,ZodUUID:()=>b$,ZodURL:()=>t0,ZodULID:()=>iU,ZodType:()=>e,ZodTuple:()=>Uj,ZodTransform:()=>Oj,ZodTemplateLiteral:()=>Bj,ZodSymbol:()=>dE,ZodSuccess:()=>Rj,ZodStringFormat:()=>P_,ZodString:()=>r4,ZodSet:()=>Nj,ZodRecord:()=>v4,ZodReadonly:()=>Fj,ZodPromise:()=>Zj,ZodPreprocess:()=>Tj,ZodPrefault:()=>zj,ZodPipe:()=>s0,ZodOptional:()=>A1,ZodObject:()=>e0,ZodNumberFormat:()=>d6,ZodNumber:()=>x4,ZodNullable:()=>Jj,ZodNull:()=>lE,ZodNonOptional:()=>O1,ZodNever:()=>pE,ZodNanoID:()=>dU,ZodNaN:()=>Kj,ZodMap:()=>jj,ZodMAC:()=>hE,ZodLiteral:()=>gj,ZodLazy:()=>Mj,ZodKSUID:()=>oU,ZodJWT:()=>U1,ZodIntersection:()=>$j,ZodIPv6:()=>eU,ZodIPv4:()=>pU,ZodGUID:()=>m0,ZodFunction:()=>Hj,ZodFile:()=>Aj,ZodExactOptional:()=>Sj,ZodEnum:()=>w4,ZodEmoji:()=>nU,ZodEmail:()=>cU,ZodE164:()=>D1,ZodDiscriminatedUnion:()=>_j,ZodDefault:()=>Wj,ZodDate:()=>o0,ZodCustomStringFormat:()=>f4,ZodCustom:()=>$D,ZodCodec:()=>_D,ZodCatch:()=>Yj,ZodCUID2:()=>lU,ZodCUID:()=>mU,ZodCIDRv6:()=>sU,ZodCIDRv4:()=>aU,ZodBoolean:()=>u4,ZodBigIntFormat:()=>I1,ZodBigInt:()=>y4,ZodBase64URL:()=>$1,ZodBase64:()=>_1,ZodArray:()=>aE,ZodAny:()=>tE});function yU(_,$,D){let I=Object.getPrototypeOf(_),U=VG.get(I);if(!U)U=new Set,VG.set(I,U);if(U.has($))return;U.add($);for(let E in D){let j=D[E];Object.defineProperty(I,E,{configurable:!0,enumerable:!1,get(){let N=j.bind(this);return Object.defineProperty(this,E,{configurable:!0,writable:!0,enumerable:!0,value:N}),N},set(N){Object.defineProperty(this,E,{configurable:!0,writable:!0,enumerable:!0,value:N})}})}}function d0(_){return KS(r4,_)}function eL(_){return UE(cU,_)}function aL(_){return QU(m0,_)}function sL(_){return IE(b$,_)}function _J(_){return EE(b$,_)}function $J(_){return jE(b$,_)}function DJ(_){return NE(b$,_)}function UJ(_){return KU(t0,_)}function IJ(_){return KU(t0,{protocol:U$.httpProtocol,hostname:U$.domain,...H.normalizeParams(_)})}function EJ(_){return gE(nU,_)}function jJ(_){return AE(dU,_)}function NJ(_){return OE(mU,_)}function gJ(_){return SE(lU,_)}function AJ(_){return LE(iU,_)}function OJ(_){return JE(tU,_)}function SJ(_){return WE(oU,_)}function LJ(_){return PE(pU,_)}function JJ(_){return FS(hE,_)}function WJ(_){return zE(eU,_)}function PJ(_){return XE(aU,_)}function zJ(_){return GE(sU,_)}function XJ(_){return RE(_1,_)}function GJ(_){return YE($1,_)}function RJ(_){return QE(D1,_)}function YJ(_){return KE(U1,_)}function QJ(_,$,D={}){return c0(f4,_,$,D)}function KJ(_){return c0(f4,"hostname",U$.hostname,_)}function TJ(_){return c0(f4,"hex",U$.hex,_)}function FJ(_,$){let D=$?.enc??"hex",I=`${_}_${D}`,U=U$[I];if(!U)throw Error(`Unrecognized hash format: ${I}`);return c0(f4,I,U,$)}function cE(_){return ZS(x4,_)}function xU(_){return kS(d6,_)}function VJ(_){return qS(d6,_)}function BJ(_){return CS(d6,_)}function MJ(_){return vS(d6,_)}function bJ(_){return wS(d6,_)}function nE(_){return rS(u4,_)}function ZJ(_){return xS(y4,_)}function HJ(_){return yS(I1,_)}function kJ(_){return hS(I1,_)}function qJ(_){return cS(dE,_)}function CJ(_){return nS(mE,_)}function iE(_){return dS(lE,_)}function vJ(){return mS(tE)}function n6(){return lS(oE)}function E1(_){return iS(pE,_)}function wJ(_){return tS(eE,_)}function rJ(_){return oS(o0,_)}function p0(_,$){return aS(aE,_,$)}function fJ(_){let $=_._zod.def.shape;return N1(Object.keys($))}function xJ(_,$){let D={type:"object",shape:_??{},...H.normalizeParams($)};return new e0(D)}function uJ(_,$){return new e0({type:"object",shape:_,catchall:E1(),...H.normalizeParams($)})}function yJ(_,$){return new e0({type:"object",shape:_,catchall:n6(),...H.normalizeParams($)})}function j1(_,$){return new a0({type:"union",options:_,...H.normalizeParams($)})}function hJ(_,$){return new sE({type:"union",options:_,inclusive:!1,...H.normalizeParams($)})}function cJ(_,$,D){return new _j({type:"union",options:$,discriminator:_,...H.normalizeParams(D)})}function Dj(_,$){return new $j({type:"intersection",left:_,right:$})}function Ij(_,$,D){let I=$ instanceof o,U=I?D:$;return new Uj({type:"tuple",items:_,rest:I?$:null,...H.normalizeParams(U)})}function Ej(_,$,D){if(!$||!$._zod)return new v4({type:"record",keyType:d0(),valueType:_,...H.normalizeParams($)});return new v4({type:"record",keyType:_,valueType:$,...H.normalizeParams(D)})}function nJ(_,$,D){let I=h_(_);return I._zod.values=void 0,new v4({type:"record",keyType:I,valueType:$,...H.normalizeParams(D)})}function dJ(_,$,D){return new v4({type:"record",keyType:_,valueType:$,mode:"loose",...H.normalizeParams(D)})}function mJ(_,$,D){return new jj({type:"map",keyType:_,valueType:$,...H.normalizeParams(D)})}function lJ(_,$){return new Nj({type:"set",valueType:_,...H.normalizeParams($)})}function N1(_,$){let D=Array.isArray(_)?Object.fromEntries(_.map((I)=>[I,I])):_;return new w4({type:"enum",entries:D,...H.normalizeParams($)})}function iJ(_,$){return new w4({type:"enum",entries:_,...H.normalizeParams($)})}function tJ(_,$){return new gj({type:"literal",values:Array.isArray(_)?_:[_],...H.normalizeParams($)})}function oJ(_){return sS(Aj,_)}function g1(_){return new Oj({type:"transform",transform:_})}function l0(_){return new A1({type:"optional",innerType:_})}function Lj(_){return new Sj({type:"optional",innerType:_})}function i0(_){return new Jj({type:"nullable",innerType:_})}function pJ(_){return l0(i0(_))}function Pj(_,$){return new Wj({type:"default",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Xj(_,$){return new zj({type:"prefault",innerType:_,get defaultValue(){return typeof $==="function"?$():H.shallowClone($)}})}function Gj(_,$){return new O1({type:"nonoptional",innerType:_,...H.normalizeParams($)})}function eJ(_){return new Rj({type:"success",innerType:_})}function Qj(_,$){return new Yj({type:"catch",innerType:_,catchValue:typeof $==="function"?$:()=>$})}function aJ(_){return eS(Kj,_)}function uU(_,$){return new s0({type:"pipe",in:_,out:$})}function sJ(_,$,D){return new _D({type:"pipe",in:_,out:$,transform:D.decode,reverseTransform:D.encode})}function _W(_){let $=_._zod.def;return new _D({type:"pipe",in:$.out,out:$.in,transform:$.reverseTransform,reverseTransform:$.transform})}function Vj(_){return new Fj({type:"readonly",innerType:_})}function $W(_,$){return new Bj({type:"template_literal",parts:_,...H.normalizeParams($)})}function bj(_){return new Mj({type:"lazy",getter:_})}function DW(_){return new Zj({type:"promise",innerType:_})}function UW(_){return new Hj({type:"function",input:Array.isArray(_?.input)?Ij(_?.input):_?.input??p0(n6()),output:_?.output??n6()})}function IW(_){let $=new Q_({check:"custom"});return $._zod.check=_,$}function EW(_,$){return _L($D,_??(()=>!0),$)}function kj(_,$={}){return $L($D,_,$)}function qj(_,$){return DL(_,$)}function gW(_,$={}){let D=new $D({type:"custom",check:"custom",fn:(I)=>I instanceof _,abort:!0,...H.normalizeParams($)});return D._zod.bag.Class=_,D._zod.check=(I)=>{if(!(I.value instanceof _))I.issues.push({code:"invalid_type",expected:_.name,input:I.value,inst:D,path:[...D._zod.def.path??[]]})},D}function OW(_){let $=bj(()=>{return j1([d0(_),cE(),nE(),iE(),p0($),Ej(d0(),$)])});return $}function SW(_,$){return new Tj({type:"pipe",in:g1(_),out:$})}var VG,e,hU,r4,P_,cU,m0,b$,t0,nU,dU,mU,lU,iU,tU,oU,pU,hE,eU,aU,sU,_1,$1,D1,U1,f4,x4,d6,u4,y4,I1,dE,mE,lE,tE,oE,pE,eE,o0,aE,e0,a0,sE,_j,$j,Uj,v4,jj,Nj,w4,gj,Aj,Oj,A1,Sj,Jj,Wj,zj,O1,Rj,Yj,Kj,s0,_D,Tj,Fj,Bj,Mj,Zj,Hj,$D,jW,NW,AW=(..._)=>EL({Codec:_D,Boolean:u4,String:r4},..._);var fU=r(()=>{O$();O$();HU();bU();bE();wU();pL();VG=new WeakMap;e=K("ZodType",(_,$)=>{return o.init(_,$),Object.assign(_["~standard"],{jsonSchema:{input:n0(_,"input"),output:n0(_,"output")}}),_.toJSONSchema=jL(_,{}),_.def=$,_.type=$.type,Object.defineProperty(_,"_def",{value:$}),_.parse=(D,I)=>ZE(_,D,I,{callee:_.parse}),_.safeParse=(D,I)=>kE(_,D,I),_.parseAsync=async(D,I)=>HE(_,D,I,{callee:_.parseAsync}),_.safeParseAsync=async(D,I)=>qE(_,D,I),_.spa=_.safeParseAsync,_.encode=(D,I)=>CE(_,D,I),_.decode=(D,I)=>vE(_,D,I),_.encodeAsync=async(D,I)=>wE(_,D,I),_.decodeAsync=async(D,I)=>rE(_,D,I),_.safeEncode=(D,I)=>fE(_,D,I),_.safeDecode=(D,I)=>xE(_,D,I),_.safeEncodeAsync=async(D,I)=>uE(_,D,I),_.safeDecodeAsync=async(D,I)=>yE(_,D,I),yU(_,"ZodType",{check(...D){let I=this.def;return this.clone(H.mergeDefs(I,{checks:[...I.checks??[],...D.map((U)=>typeof U==="function"?{_zod:{check:U,def:{check:"custom"},onattach:[]}}:U)]}),{parent:!0})},with(...D){return this.check(...D)},clone(D,I){return h_(this,D,I)},brand(){return this},register(D,I){return D.add(this,I),this},refine(D,I){return this.check(kj(D,I))},superRefine(D,I){return this.check(qj(D,I))},overwrite(D){return this.check(X$(D))},optional(){return l0(this)},exactOptional(){return Lj(this)},nullable(){return i0(this)},nullish(){return l0(i0(this))},nonoptional(D){return Gj(this,D)},array(){return p0(this)},or(D){return j1([this,D])},and(D){return Dj(this,D)},transform(D){return uU(this,g1(D))},default(D){return Pj(this,D)},prefault(D){return Xj(this,D)},catch(D){return Qj(this,D)},pipe(D){return uU(this,D)},readonly(){return Vj(this)},describe(D){let I=this.clone();return x_.add(I,{description:D}),I},meta(...D){if(D.length===0)return x_.get(this);let I=this.clone();return x_.add(I,D[0]),I},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(D){return D(this)}}),Object.defineProperty(_,"description",{get(){return x_.get(_)?.description},configurable:!0}),_}),hU=K("_ZodString",(_,$)=>{Y4.init(_,$),e.init(_,$),_._zod.processJSONSchema=(I,U,E)=>NL(_,I,U,E);let D=_._zod.bag;_.format=D.format??null,_.minLength=D.minimum??null,_.maxLength=D.maximum??null,yU(_,"_ZodString",{regex(...I){return this.check(Q4(...I))},includes(...I){return this.check(F4(...I))},startsWith(...I){return this.check(V4(...I))},endsWith(...I){return this.check(B4(...I))},min(...I){return this.check(l$(...I))},max(...I){return this.check(x6(...I))},length(...I){return this.check(u6(...I))},nonempty(...I){return this.check(l$(1,...I))},lowercase(I){return this.check(K4(I))},uppercase(I){return this.check(T4(I))},trim(){return this.check(Z4())},normalize(...I){return this.check(b4(...I))},toLowerCase(){return this.check(H4())},toUpperCase(){return this.check(k4())},slugify(){return this.check(q4())}})}),r4=K("ZodString",(_,$)=>{Y4.init(_,$),hU.init(_,$),_.email=(D)=>_.check(UE(cU,D)),_.url=(D)=>_.check(KU(t0,D)),_.jwt=(D)=>_.check(KE(U1,D)),_.emoji=(D)=>_.check(gE(nU,D)),_.guid=(D)=>_.check(QU(m0,D)),_.uuid=(D)=>_.check(IE(b$,D)),_.uuidv4=(D)=>_.check(EE(b$,D)),_.uuidv6=(D)=>_.check(jE(b$,D)),_.uuidv7=(D)=>_.check(NE(b$,D)),_.nanoid=(D)=>_.check(AE(dU,D)),_.guid=(D)=>_.check(QU(m0,D)),_.cuid=(D)=>_.check(OE(mU,D)),_.cuid2=(D)=>_.check(SE(lU,D)),_.ulid=(D)=>_.check(LE(iU,D)),_.base64=(D)=>_.check(RE(_1,D)),_.base64url=(D)=>_.check(YE($1,D)),_.xid=(D)=>_.check(JE(tU,D)),_.ksuid=(D)=>_.check(WE(oU,D)),_.ipv4=(D)=>_.check(PE(pU,D)),_.ipv6=(D)=>_.check(zE(eU,D)),_.cidrv4=(D)=>_.check(XE(aU,D)),_.cidrv6=(D)=>_.check(GE(sU,D)),_.e164=(D)=>_.check(QE(D1,D)),_.datetime=(D)=>_.check(mL(D)),_.date=(D)=>_.check(lL(D)),_.time=(D)=>_.check(iL(D)),_.duration=(D)=>_.check(tL(D))});P_=K("ZodStringFormat",(_,$)=>{Y_.init(_,$),hU.init(_,$)}),cU=K("ZodEmail",(_,$)=>{WA.init(_,$),P_.init(_,$)});m0=K("ZodGUID",(_,$)=>{LA.init(_,$),P_.init(_,$)});b$=K("ZodUUID",(_,$)=>{JA.init(_,$),P_.init(_,$)});t0=K("ZodURL",(_,$)=>{PA.init(_,$),P_.init(_,$)});nU=K("ZodEmoji",(_,$)=>{zA.init(_,$),P_.init(_,$)});dU=K("ZodNanoID",(_,$)=>{XA.init(_,$),P_.init(_,$)});mU=K("ZodCUID",(_,$)=>{GA.init(_,$),P_.init(_,$)});lU=K("ZodCUID2",(_,$)=>{RA.init(_,$),P_.init(_,$)});iU=K("ZodULID",(_,$)=>{YA.init(_,$),P_.init(_,$)});tU=K("ZodXID",(_,$)=>{QA.init(_,$),P_.init(_,$)});oU=K("ZodKSUID",(_,$)=>{KA.init(_,$),P_.init(_,$)});pU=K("ZodIPv4",(_,$)=>{MA.init(_,$),P_.init(_,$)});hE=K("ZodMAC",(_,$)=>{ZA.init(_,$),P_.init(_,$)});eU=K("ZodIPv6",(_,$)=>{bA.init(_,$),P_.init(_,$)});aU=K("ZodCIDRv4",(_,$)=>{HA.init(_,$),P_.init(_,$)});sU=K("ZodCIDRv6",(_,$)=>{kA.init(_,$),P_.init(_,$)});_1=K("ZodBase64",(_,$)=>{CA.init(_,$),P_.init(_,$)});$1=K("ZodBase64URL",(_,$)=>{vA.init(_,$),P_.init(_,$)});D1=K("ZodE164",(_,$)=>{wA.init(_,$),P_.init(_,$)});U1=K("ZodJWT",(_,$)=>{rA.init(_,$),P_.init(_,$)});f4=K("ZodCustomStringFormat",(_,$)=>{fA.init(_,$),P_.init(_,$)});x4=K("ZodNumber",(_,$)=>{pI.init(_,$),e.init(_,$),_._zod.processJSONSchema=(I,U,E)=>gL(_,I,U,E),yU(_,"ZodNumber",{gt(I,U){return this.check(B$(I,U))},gte(I,U){return this.check(c_(I,U))},min(I,U){return this.check(c_(I,U))},lt(I,U){return this.check(V$(I,U))},lte(I,U){return this.check(I$(I,U))},max(I,U){return this.check(I$(I,U))},int(I){return this.check(xU(I))},safe(I){return this.check(xU(I))},positive(I){return this.check(B$(0,I))},nonnegative(I){return this.check(c_(0,I))},negative(I){return this.check(V$(0,I))},nonpositive(I){return this.check(I$(0,I))},multipleOf(I,U){return this.check(L6(I,U))},step(I,U){return this.check(L6(I,U))},finite(){return this}});let D=_._zod.bag;_.minValue=Math.max(D.minimum??Number.NEGATIVE_INFINITY,D.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,_.maxValue=Math.min(D.maximum??Number.POSITIVE_INFINITY,D.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,_.isInt=(D.format??"").includes("int")||Number.isSafeInteger(D.multipleOf??0.5),_.isFinite=!0,_.format=D.format??null});d6=K("ZodNumberFormat",(_,$)=>{xA.init(_,$),x4.init(_,$)});u4=K("ZodBoolean",(_,$)=>{LU.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>AL(_,D,I,U)});y4=K("ZodBigInt",(_,$)=>{eI.init(_,$),e.init(_,$),_._zod.processJSONSchema=(I,U,E)=>OL(_,I,U,E),_.gte=(I,U)=>_.check(c_(I,U)),_.min=(I,U)=>_.check(c_(I,U)),_.gt=(I,U)=>_.check(B$(I,U)),_.gte=(I,U)=>_.check(c_(I,U)),_.min=(I,U)=>_.check(c_(I,U)),_.lt=(I,U)=>_.check(V$(I,U)),_.lte=(I,U)=>_.check(I$(I,U)),_.max=(I,U)=>_.check(I$(I,U)),_.positive=(I)=>_.check(B$(BigInt(0),I)),_.negative=(I)=>_.check(V$(BigInt(0),I)),_.nonpositive=(I)=>_.check(I$(BigInt(0),I)),_.nonnegative=(I)=>_.check(c_(BigInt(0),I)),_.multipleOf=(I,U)=>_.check(L6(I,U));let D=_._zod.bag;_.minValue=D.minimum??null,_.maxValue=D.maximum??null,_.format=D.format??null});I1=K("ZodBigIntFormat",(_,$)=>{uA.init(_,$),y4.init(_,$)});dE=K("ZodSymbol",(_,$)=>{yA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>SL(_,D,I,U)});mE=K("ZodUndefined",(_,$)=>{hA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>JL(_,D,I,U)});lE=K("ZodNull",(_,$)=>{cA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>LL(_,D,I,U)});tE=K("ZodAny",(_,$)=>{nA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>zL(_,D,I,U)});oE=K("ZodUnknown",(_,$)=>{dA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>XL(_,D,I,U)});pE=K("ZodNever",(_,$)=>{mA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>PL(_,D,I,U)});eE=K("ZodVoid",(_,$)=>{lA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>WL(_,D,I,U)});o0=K("ZodDate",(_,$)=>{iA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(I,U,E)=>GL(_,I,U,E),_.min=(I,U)=>_.check(c_(I,U)),_.max=(I,U)=>_.check(I$(I,U));let D=_._zod.bag;_.minDate=D.minimum?new Date(D.minimum):null,_.maxDate=D.maximum?new Date(D.maximum):null});aE=K("ZodArray",(_,$)=>{tA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>HL(_,D,I,U),_.element=$.element,yU(_,"ZodArray",{min(D,I){return this.check(l$(D,I))},nonempty(D){return this.check(l$(1,D))},max(D,I){return this.check(x6(D,I))},length(D,I){return this.check(u6(D,I))},unwrap(){return this.element}})});e0=K("ZodObject",(_,$)=>{oA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>kL(_,D,I,U),H.defineLazy(_,"shape",()=>{return $.shape}),yU(_,"ZodObject",{keyof(){return N1(Object.keys(this._zod.def.shape))},catchall(D){return this.clone({...this._zod.def,catchall:D})},passthrough(){return this.clone({...this._zod.def,catchall:n6()})},loose(){return this.clone({...this._zod.def,catchall:n6()})},strict(){return this.clone({...this._zod.def,catchall:E1()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(D){return H.extend(this,D)},safeExtend(D){return H.safeExtend(this,D)},merge(D){return H.merge(this,D)},pick(D){return H.pick(this,D)},omit(D){return H.omit(this,D)},partial(...D){return H.partial(A1,this,D[0])},required(...D){return H.required(O1,this,D[0])}})});a0=K("ZodUnion",(_,$)=>{JU.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>VE(_,D,I,U),_.options=$.options});sE=K("ZodXor",(_,$)=>{a0.init(_,$),pA.init(_,$),_._zod.processJSONSchema=(D,I,U)=>VE(_,D,I,U),_.options=$.options});_j=K("ZodDiscriminatedUnion",(_,$)=>{a0.init(_,$),eA.init(_,$)});$j=K("ZodIntersection",(_,$)=>{aA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>qL(_,D,I,U)});Uj=K("ZodTuple",(_,$)=>{aI.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>CL(_,D,I,U),_.rest=(D)=>_.clone({..._._zod.def,rest:D})});v4=K("ZodRecord",(_,$)=>{sA.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>vL(_,D,I,U),_.keyType=$.keyType,_.valueType=$.valueType});jj=K("ZodMap",(_,$)=>{_O.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>bL(_,D,I,U),_.keyType=$.keyType,_.valueType=$.valueType,_.min=(...D)=>_.check(M$(...D)),_.nonempty=(D)=>_.check(M$(1,D)),_.max=(...D)=>_.check(J6(...D)),_.size=(...D)=>_.check(f6(...D))});Nj=K("ZodSet",(_,$)=>{$O.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>ZL(_,D,I,U),_.min=(...D)=>_.check(M$(...D)),_.nonempty=(D)=>_.check(M$(1,D)),_.max=(...D)=>_.check(J6(...D)),_.size=(...D)=>_.check(f6(...D))});w4=K("ZodEnum",(_,$)=>{DO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(I,U,E)=>RL(_,I,U,E),_.enum=$.entries,_.options=Object.values($.entries);let D=new Set(Object.keys($.entries));_.extract=(I,U)=>{let E={};for(let j of I)if(D.has(j))E[j]=$.entries[j];else throw Error(`Key ${j} not found in enum`);return new w4({...$,checks:[],...H.normalizeParams(U),entries:E})},_.exclude=(I,U)=>{let E={...$.entries};for(let j of I)if(D.has(j))delete E[j];else throw Error(`Key ${j} not found in enum`);return new w4({...$,checks:[],...H.normalizeParams(U),entries:E})}});gj=K("ZodLiteral",(_,$)=>{UO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>YL(_,D,I,U),_.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]}})});Aj=K("ZodFile",(_,$)=>{IO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>TL(_,D,I,U),_.min=(D,I)=>_.check(M$(D,I)),_.max=(D,I)=>_.check(J6(D,I)),_.mime=(D,I)=>_.check(M4(Array.isArray(D)?D:[D],I))});Oj=K("ZodTransform",(_,$)=>{EO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>ML(_,D,I,U),_._zod.parse=(D,I)=>{if(I.direction==="backward")throw new z4(_.constructor.name);D.addIssue=(E)=>{if(typeof E==="string")D.issues.push(H.issue(E,D.value,$));else{let j=E;if(j.fatal)j.continue=!1;j.code??(j.code="custom"),j.input??(j.input=D.value),j.inst??(j.inst=_),D.issues.push(H.issue(j))}};let U=$.transform(D.value,D);if(U instanceof Promise)return U.then((E)=>{return D.value=E,D.fallback=!0,D});return D.value=U,D.fallback=!0,D}});A1=K("ZodOptional",(_,$)=>{sI.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>BE(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Sj=K("ZodExactOptional",(_,$)=>{jO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>BE(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Jj=K("ZodNullable",(_,$)=>{NO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>wL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Wj=K("ZodDefault",(_,$)=>{gO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>fL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType,_.removeDefault=_.unwrap});zj=K("ZodPrefault",(_,$)=>{AO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>xL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});O1=K("ZodNonOptional",(_,$)=>{OO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>rL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Rj=K("ZodSuccess",(_,$)=>{SO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>FL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Yj=K("ZodCatch",(_,$)=>{LO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>uL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType,_.removeCatch=_.unwrap});Kj=K("ZodNaN",(_,$)=>{JO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>QL(_,D,I,U)});s0=K("ZodPipe",(_,$)=>{_E.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>yL(_,D,I,U),_.in=$.in,_.out=$.out});_D=K("ZodCodec",(_,$)=>{s0.init(_,$),WU.init(_,$)});Tj=K("ZodPreprocess",(_,$)=>{s0.init(_,$),WO.init(_,$)}),Fj=K("ZodReadonly",(_,$)=>{PO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>hL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Bj=K("ZodTemplateLiteral",(_,$)=>{zO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>KL(_,D,I,U)});Mj=K("ZodLazy",(_,$)=>{RO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>nL(_,D,I,U),_.unwrap=()=>_._zod.def.getter()});Zj=K("ZodPromise",(_,$)=>{GO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>cL(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Hj=K("ZodFunction",(_,$)=>{XO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>BL(_,D,I,U)});$D=K("ZodCustom",(_,$)=>{YO.init(_,$),e.init(_,$),_._zod.processJSONSchema=(D,I,U)=>VL(_,D,I,U)});jW=UL,NW=IL});function MG(_){Z_({customError:_})}function bG(){return Z_().customError}var BG,Cj;var ZG=r(()=>{O$();BG={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(_){})(Cj||(Cj={}))});function Eb(_,$){let D=_.$schema;if(D==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(D==="http://json-schema.org/draft-07/schema#")return"draft-7";if(D==="http://json-schema.org/draft-04/schema#")return"draft-4";return $??"draft-2020-12"}function jb(_,$){if(!_.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let D=_.slice(1).split("/").filter(Boolean);if(D.length===0)return $.rootSchema;let I=$.version==="draft-2020-12"?"$defs":"definitions";if(D[0]===I){let U=D[1];if(!U||!$.defs[U])throw Error(`Reference not found: ${_}`);return $.defs[U]}throw Error(`Reference not found: ${_}`)}function HG(_,$){if(_.not!==void 0){if(typeof _.not==="object"&&Object.keys(_.not).length===0)return x.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 U=_.$ref;if($.refs.has(U))return $.refs.get(U);if($.processing.has(U))return x.lazy(()=>{if(!$.refs.has(U))throw Error(`Circular reference not resolved: ${U}`);return $.refs.get(U)});$.processing.add(U);let E=jb(U,$),j=n_(E,$);return $.refs.set(U,j),$.processing.delete(U),j}if(_.enum!==void 0){let U=_.enum;if($.version==="openapi-3.0"&&_.nullable===!0&&U.length===1&&U[0]===null)return x.null();if(U.length===0)return x.never();if(U.length===1)return x.literal(U[0]);if(U.every((j)=>typeof j==="string"))return x.enum(U);let E=U.map((j)=>x.literal(j));if(E.length<2)return E[0];return x.union([E[0],E[1],...E.slice(2)])}if(_.const!==void 0)return x.literal(_.const);let D=_.type;if(Array.isArray(D)){let U=D.map((E)=>{let j={..._,type:E};return HG(j,$)});if(U.length===0)return x.never();if(U.length===1)return U[0];return x.union(U)}if(!D)return x.any();let I;switch(D){case"string":{let U=x.string();if(_.format){let E=_.format;if(E==="email")U=U.check(x.email());else if(E==="uri"||E==="uri-reference")U=U.check(x.url());else if(E==="uuid"||E==="guid")U=U.check(x.uuid());else if(E==="date-time")U=U.check(x.iso.datetime());else if(E==="date")U=U.check(x.iso.date());else if(E==="time")U=U.check(x.iso.time());else if(E==="duration")U=U.check(x.iso.duration());else if(E==="ipv4")U=U.check(x.ipv4());else if(E==="ipv6")U=U.check(x.ipv6());else if(E==="mac")U=U.check(x.mac());else if(E==="cidr")U=U.check(x.cidrv4());else if(E==="cidr-v6")U=U.check(x.cidrv6());else if(E==="base64")U=U.check(x.base64());else if(E==="base64url")U=U.check(x.base64url());else if(E==="e164")U=U.check(x.e164());else if(E==="jwt")U=U.check(x.jwt());else if(E==="emoji")U=U.check(x.emoji());else if(E==="nanoid")U=U.check(x.nanoid());else if(E==="cuid")U=U.check(x.cuid());else if(E==="cuid2")U=U.check(x.cuid2());else if(E==="ulid")U=U.check(x.ulid());else if(E==="xid")U=U.check(x.xid());else if(E==="ksuid")U=U.check(x.ksuid())}if(typeof _.minLength==="number")U=U.min(_.minLength);if(typeof _.maxLength==="number")U=U.max(_.maxLength);if(_.pattern)U=U.regex(new RegExp(_.pattern));I=U;break}case"number":case"integer":{let U=D==="integer"?x.number().int():x.number();if(typeof _.minimum==="number")U=U.min(_.minimum);if(typeof _.maximum==="number")U=U.max(_.maximum);if(typeof _.exclusiveMinimum==="number")U=U.gt(_.exclusiveMinimum);else if(_.exclusiveMinimum===!0&&typeof _.minimum==="number")U=U.gt(_.minimum);if(typeof _.exclusiveMaximum==="number")U=U.lt(_.exclusiveMaximum);else if(_.exclusiveMaximum===!0&&typeof _.maximum==="number")U=U.lt(_.maximum);if(typeof _.multipleOf==="number")U=U.multipleOf(_.multipleOf);I=U;break}case"boolean":{I=x.boolean();break}case"null":{I=x.null();break}case"object":{let U={},E=_.properties||{},j=new Set(_.required||[]);for(let[A,O]of Object.entries(E)){let S=n_(O,$);U[A]=j.has(A)?S:S.optional()}if(_.propertyNames){let A=n_(_.propertyNames,$),O=_.additionalProperties&&typeof _.additionalProperties==="object"?n_(_.additionalProperties,$):x.any();if(Object.keys(U).length===0){I=x.record(A,O);break}let S=x.object(U).passthrough(),L=x.looseRecord(A,O);I=x.intersection(S,L);break}if(_.patternProperties){let A=_.patternProperties,O=Object.keys(A),S=[];for(let P of O){let z=n_(A[P],$),G=x.string().regex(new RegExp(P));S.push(x.looseRecord(G,z))}let L=[];if(Object.keys(U).length>0)L.push(x.object(U).passthrough());if(L.push(...S),L.length===0)I=x.object({}).passthrough();else if(L.length===1)I=L[0];else{let P=x.intersection(L[0],L[1]);for(let z=2;zn_(A,$)),N=E&&typeof E==="object"&&!Array.isArray(E)?n_(E,$):void 0;if(N)I=x.tuple(j).rest(N);else I=x.tuple(j);if(typeof _.minItems==="number")I=I.check(x.minLength(_.minItems));if(typeof _.maxItems==="number")I=I.check(x.maxLength(_.maxItems))}else if(Array.isArray(E)){let j=E.map((A)=>n_(A,$)),N=_.additionalItems&&typeof _.additionalItems==="object"?n_(_.additionalItems,$):void 0;if(N)I=x.tuple(j).rest(N);else I=x.tuple(j);if(typeof _.minItems==="number")I=I.check(x.minLength(_.minItems));if(typeof _.maxItems==="number")I=I.check(x.maxLength(_.maxItems))}else if(E!==void 0){let j=n_(E,$),N=x.array(j);if(typeof _.minItems==="number")N=N.min(_.minItems);if(typeof _.maxItems==="number")N=N.max(_.maxItems);I=N}else I=x.array(x.any());break}default:throw Error(`Unsupported type: ${D}`)}return I}function n_(_,$){if(typeof _==="boolean")return _?x.any():x.never();let D=HG(_,$),I=_.type||_.enum!==void 0||_.const!==void 0;if(_.anyOf&&Array.isArray(_.anyOf)){let N=_.anyOf.map((O)=>n_(O,$)),A=x.union(N);D=I?x.intersection(D,A):A}if(_.oneOf&&Array.isArray(_.oneOf)){let N=_.oneOf.map((O)=>n_(O,$)),A=x.xor(N);D=I?x.intersection(D,A):A}if(_.allOf&&Array.isArray(_.allOf))if(_.allOf.length===0)D=I?D:x.any();else{let N=I?D:n_(_.allOf[0],$),A=I?0:1;for(let O=A;O<_.allOf.length;O++)N=x.intersection(N,n_(_.allOf[O],$));D=N}if(_.nullable===!0&&$.version==="openapi-3.0")D=x.nullable(D);if(_.readOnly===!0)D=x.readonly(D);if(_.default!==void 0)D=D.default(_.default);let U={},E=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let N of E)if(N in _)U[N]=_[N];let j=["contentEncoding","contentMediaType","contentSchema"];for(let N of j)if(N in _)U[N]=_[N];for(let N of Object.keys(_))if(!Ib.has(N))U[N]=_[N];if(Object.keys(U).length>0)$.registry.add(D,U);if(_.description)D=D.describe(_.description);return D}function LW(_,$){if(typeof _==="boolean")return _?x.any():x.never();let D;try{D=JSON.parse(JSON.stringify(_))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let I=Eb(D,$?.defaultTarget),U=D.$defs||D.definitions||{},E={version:I,defs:U,refs:new Map,processing:new Set,rootSchema:D,registry:$?.registry??x_};return n_(D,E)}var x,Ib;var kG=r(()=>{YU();bE();wU();fU();x={...rU,...ME,iso:C4},Ib=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 vj={};x$(vj,{string:()=>Nb,number:()=>gb,date:()=>Sb,boolean:()=>Ab,bigint:()=>Ob});function Nb(_){return TS(r4,_)}function gb(_){return HS(x4,_)}function Ab(_){return fS(u4,_)}function Ob(_){return uS(y4,_)}function Sb(_){return pS(o0,_)}var qG=r(()=>{O$();fU()});var wj={};x$(wj,{xor:()=>hJ,xid:()=>OJ,void:()=>wJ,uuidv7:()=>DJ,uuidv6:()=>$J,uuidv4:()=>_J,uuid:()=>sL,util:()=>H,url:()=>UJ,uppercase:()=>T4,unknown:()=>n6,union:()=>j1,undefined:()=>CJ,ulid:()=>AJ,uint64:()=>kJ,uint32:()=>bJ,tuple:()=>Ij,trim:()=>Z4,treeifyError:()=>bI,transform:()=>g1,toUpperCase:()=>k4,toLowerCase:()=>H4,toJSONSchema:()=>ZU,templateLiteral:()=>$W,symbol:()=>qJ,superRefine:()=>qj,success:()=>eJ,stringbool:()=>AW,stringFormat:()=>QJ,string:()=>d0,strictObject:()=>uJ,startsWith:()=>V4,slugify:()=>q4,size:()=>f6,setErrorMap:()=>MG,set:()=>lJ,safeParseAsync:()=>qE,safeParse:()=>kE,safeEncodeAsync:()=>uE,safeEncode:()=>fE,safeDecodeAsync:()=>yE,safeDecode:()=>xE,registry:()=>RU,regexes:()=>U$,regex:()=>Q4,refine:()=>kj,record:()=>Ej,readonly:()=>Vj,property:()=>MU,promise:()=>DW,prettifyError:()=>ZI,preprocess:()=>SW,prefault:()=>Xj,positive:()=>TU,pipe:()=>uU,partialRecord:()=>nJ,parseAsync:()=>HE,parse:()=>ZE,overwrite:()=>X$,optional:()=>l0,object:()=>xJ,number:()=>cE,nullish:()=>pJ,nullable:()=>i0,null:()=>iE,normalize:()=>b4,nonpositive:()=>VU,nonoptional:()=>Gj,nonnegative:()=>BU,never:()=>E1,negative:()=>FU,nativeEnum:()=>iJ,nanoid:()=>jJ,nan:()=>aJ,multipleOf:()=>L6,minSize:()=>M$,minLength:()=>l$,mime:()=>M4,meta:()=>NW,maxSize:()=>J6,maxLength:()=>x6,map:()=>mJ,mac:()=>JJ,lte:()=>I$,lt:()=>V$,lowercase:()=>K4,looseRecord:()=>dJ,looseObject:()=>yJ,locales:()=>h0,literal:()=>tJ,length:()=>u6,lazy:()=>bj,ksuid:()=>SJ,keyof:()=>fJ,jwt:()=>YJ,json:()=>OW,iso:()=>C4,ipv6:()=>WJ,ipv4:()=>LJ,invertCodec:()=>_W,intersection:()=>Dj,int64:()=>HJ,int32:()=>MJ,int:()=>xU,instanceof:()=>gW,includes:()=>F4,httpUrl:()=>IJ,hostname:()=>KJ,hex:()=>TJ,hash:()=>FJ,guid:()=>aL,gte:()=>c_,gt:()=>B$,globalRegistry:()=>x_,getErrorMap:()=>bG,function:()=>UW,fromJSONSchema:()=>LW,formatError:()=>v0,float64:()=>BJ,float32:()=>VJ,flattenError:()=>C0,file:()=>oJ,exactOptional:()=>Lj,enum:()=>N1,endsWith:()=>B4,encodeAsync:()=>wE,encode:()=>CE,emoji:()=>EJ,email:()=>eL,e164:()=>RJ,discriminatedUnion:()=>cJ,describe:()=>jW,decodeAsync:()=>rE,decode:()=>vE,date:()=>rJ,custom:()=>EW,cuid2:()=>gJ,cuid:()=>NJ,core:()=>i$,config:()=>Z_,coerce:()=>vj,codec:()=>sJ,clone:()=>h_,cidrv6:()=>zJ,cidrv4:()=>PJ,check:()=>IW,catch:()=>Qj,boolean:()=>nE,bigint:()=>ZJ,base64url:()=>GJ,base64:()=>XJ,array:()=>p0,any:()=>vJ,_function:()=>UW,_default:()=>Pj,_ZodString:()=>hU,ZodXor:()=>sE,ZodXID:()=>tU,ZodVoid:()=>eE,ZodUnknown:()=>oE,ZodUnion:()=>a0,ZodUndefined:()=>mE,ZodUUID:()=>b$,ZodURL:()=>t0,ZodULID:()=>iU,ZodType:()=>e,ZodTuple:()=>Uj,ZodTransform:()=>Oj,ZodTemplateLiteral:()=>Bj,ZodSymbol:()=>dE,ZodSuccess:()=>Rj,ZodStringFormat:()=>P_,ZodString:()=>r4,ZodSet:()=>Nj,ZodRecord:()=>v4,ZodRealError:()=>p_,ZodReadonly:()=>Fj,ZodPromise:()=>Zj,ZodPreprocess:()=>Tj,ZodPrefault:()=>zj,ZodPipe:()=>s0,ZodOptional:()=>A1,ZodObject:()=>e0,ZodNumberFormat:()=>d6,ZodNumber:()=>x4,ZodNullable:()=>Jj,ZodNull:()=>lE,ZodNonOptional:()=>O1,ZodNever:()=>pE,ZodNanoID:()=>dU,ZodNaN:()=>Kj,ZodMap:()=>jj,ZodMAC:()=>hE,ZodLiteral:()=>gj,ZodLazy:()=>Mj,ZodKSUID:()=>oU,ZodJWT:()=>U1,ZodIssueCode:()=>BG,ZodIntersection:()=>$j,ZodISOTime:()=>CU,ZodISODuration:()=>vU,ZodISODateTime:()=>kU,ZodISODate:()=>qU,ZodIPv6:()=>eU,ZodIPv4:()=>pU,ZodGUID:()=>m0,ZodFunction:()=>Hj,ZodFirstPartyTypeKind:()=>Cj,ZodFile:()=>Aj,ZodExactOptional:()=>Sj,ZodError:()=>FG,ZodEnum:()=>w4,ZodEmoji:()=>nU,ZodEmail:()=>cU,ZodE164:()=>D1,ZodDiscriminatedUnion:()=>_j,ZodDefault:()=>Wj,ZodDate:()=>o0,ZodCustomStringFormat:()=>f4,ZodCustom:()=>$D,ZodCodec:()=>_D,ZodCatch:()=>Yj,ZodCUID2:()=>lU,ZodCUID:()=>mU,ZodCIDRv6:()=>sU,ZodCIDRv4:()=>aU,ZodBoolean:()=>u4,ZodBigIntFormat:()=>I1,ZodBigInt:()=>y4,ZodBase64URL:()=>$1,ZodBase64:()=>_1,ZodArray:()=>aE,ZodAny:()=>tE,TimePrecision:()=>TE,NEVER:()=>FI,$output:()=>$E,$input:()=>DE,$brand:()=>VI});var JW=r(()=>{O$();O$();kO();O$();HU();kG();YS();wU();wU();qG();fU();bE();oL();pL();ZG();Z_(PU())});var CG={};x$(CG,{z:()=>wj,xor:()=>hJ,xid:()=>OJ,void:()=>wJ,uuidv7:()=>DJ,uuidv6:()=>$J,uuidv4:()=>_J,uuid:()=>sL,util:()=>H,url:()=>UJ,uppercase:()=>T4,unknown:()=>n6,union:()=>j1,undefined:()=>CJ,ulid:()=>AJ,uint64:()=>kJ,uint32:()=>bJ,tuple:()=>Ij,trim:()=>Z4,treeifyError:()=>bI,transform:()=>g1,toUpperCase:()=>k4,toLowerCase:()=>H4,toJSONSchema:()=>ZU,templateLiteral:()=>$W,symbol:()=>qJ,superRefine:()=>qj,success:()=>eJ,stringbool:()=>AW,stringFormat:()=>QJ,string:()=>d0,strictObject:()=>uJ,startsWith:()=>V4,slugify:()=>q4,size:()=>f6,setErrorMap:()=>MG,set:()=>lJ,safeParseAsync:()=>qE,safeParse:()=>kE,safeEncodeAsync:()=>uE,safeEncode:()=>fE,safeDecodeAsync:()=>yE,safeDecode:()=>xE,registry:()=>RU,regexes:()=>U$,regex:()=>Q4,refine:()=>kj,record:()=>Ej,readonly:()=>Vj,property:()=>MU,promise:()=>DW,prettifyError:()=>ZI,preprocess:()=>SW,prefault:()=>Xj,positive:()=>TU,pipe:()=>uU,partialRecord:()=>nJ,parseAsync:()=>HE,parse:()=>ZE,overwrite:()=>X$,optional:()=>l0,object:()=>xJ,number:()=>cE,nullish:()=>pJ,nullable:()=>i0,null:()=>iE,normalize:()=>b4,nonpositive:()=>VU,nonoptional:()=>Gj,nonnegative:()=>BU,never:()=>E1,negative:()=>FU,nativeEnum:()=>iJ,nanoid:()=>jJ,nan:()=>aJ,multipleOf:()=>L6,minSize:()=>M$,minLength:()=>l$,mime:()=>M4,meta:()=>NW,maxSize:()=>J6,maxLength:()=>x6,map:()=>mJ,mac:()=>JJ,lte:()=>I$,lt:()=>V$,lowercase:()=>K4,looseRecord:()=>dJ,looseObject:()=>yJ,locales:()=>h0,literal:()=>tJ,length:()=>u6,lazy:()=>bj,ksuid:()=>SJ,keyof:()=>fJ,jwt:()=>YJ,json:()=>OW,iso:()=>C4,ipv6:()=>WJ,ipv4:()=>LJ,invertCodec:()=>_W,intersection:()=>Dj,int64:()=>HJ,int32:()=>MJ,int:()=>xU,instanceof:()=>gW,includes:()=>F4,httpUrl:()=>IJ,hostname:()=>KJ,hex:()=>TJ,hash:()=>FJ,guid:()=>aL,gte:()=>c_,gt:()=>B$,globalRegistry:()=>x_,getErrorMap:()=>bG,function:()=>UW,fromJSONSchema:()=>LW,formatError:()=>v0,float64:()=>BJ,float32:()=>VJ,flattenError:()=>C0,file:()=>oJ,exactOptional:()=>Lj,enum:()=>N1,endsWith:()=>B4,encodeAsync:()=>wE,encode:()=>CE,emoji:()=>EJ,email:()=>eL,e164:()=>RJ,discriminatedUnion:()=>cJ,describe:()=>jW,default:()=>Lb,decodeAsync:()=>rE,decode:()=>vE,date:()=>rJ,custom:()=>EW,cuid2:()=>gJ,cuid:()=>NJ,core:()=>i$,config:()=>Z_,coerce:()=>vj,codec:()=>sJ,clone:()=>h_,cidrv6:()=>zJ,cidrv4:()=>PJ,check:()=>IW,catch:()=>Qj,boolean:()=>nE,bigint:()=>ZJ,base64url:()=>GJ,base64:()=>XJ,array:()=>p0,any:()=>vJ,_function:()=>UW,_default:()=>Pj,_ZodString:()=>hU,ZodXor:()=>sE,ZodXID:()=>tU,ZodVoid:()=>eE,ZodUnknown:()=>oE,ZodUnion:()=>a0,ZodUndefined:()=>mE,ZodUUID:()=>b$,ZodURL:()=>t0,ZodULID:()=>iU,ZodType:()=>e,ZodTuple:()=>Uj,ZodTransform:()=>Oj,ZodTemplateLiteral:()=>Bj,ZodSymbol:()=>dE,ZodSuccess:()=>Rj,ZodStringFormat:()=>P_,ZodString:()=>r4,ZodSet:()=>Nj,ZodRecord:()=>v4,ZodRealError:()=>p_,ZodReadonly:()=>Fj,ZodPromise:()=>Zj,ZodPreprocess:()=>Tj,ZodPrefault:()=>zj,ZodPipe:()=>s0,ZodOptional:()=>A1,ZodObject:()=>e0,ZodNumberFormat:()=>d6,ZodNumber:()=>x4,ZodNullable:()=>Jj,ZodNull:()=>lE,ZodNonOptional:()=>O1,ZodNever:()=>pE,ZodNanoID:()=>dU,ZodNaN:()=>Kj,ZodMap:()=>jj,ZodMAC:()=>hE,ZodLiteral:()=>gj,ZodLazy:()=>Mj,ZodKSUID:()=>oU,ZodJWT:()=>U1,ZodIssueCode:()=>BG,ZodIntersection:()=>$j,ZodISOTime:()=>CU,ZodISODuration:()=>vU,ZodISODateTime:()=>kU,ZodISODate:()=>qU,ZodIPv6:()=>eU,ZodIPv4:()=>pU,ZodGUID:()=>m0,ZodFunction:()=>Hj,ZodFirstPartyTypeKind:()=>Cj,ZodFile:()=>Aj,ZodExactOptional:()=>Sj,ZodError:()=>FG,ZodEnum:()=>w4,ZodEmoji:()=>nU,ZodEmail:()=>cU,ZodE164:()=>D1,ZodDiscriminatedUnion:()=>_j,ZodDefault:()=>Wj,ZodDate:()=>o0,ZodCustomStringFormat:()=>f4,ZodCustom:()=>$D,ZodCodec:()=>_D,ZodCatch:()=>Yj,ZodCUID2:()=>lU,ZodCUID:()=>mU,ZodCIDRv6:()=>sU,ZodCIDRv4:()=>aU,ZodBoolean:()=>u4,ZodBigIntFormat:()=>I1,ZodBigInt:()=>y4,ZodBase64URL:()=>$1,ZodBase64:()=>_1,ZodArray:()=>aE,ZodAny:()=>tE,TimePrecision:()=>TE,NEVER:()=>FI,$output:()=>$E,$input:()=>DE,$brand:()=>VI});var Lb;var vG=r(()=>{JW();JW();Lb=wj});var k1=D4((Sw)=>{class WP extends Error{constructor(_,$,D){super(D);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=_,this.nestedError=void 0}}class H8 extends WP{constructor(_){super(1,"commander.invalidArgument",_);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Sw.CommanderError=WP;Sw.InvalidArgumentError=H8});var BN=D4((zw)=>{var{InvalidArgumentError:Ww}=k1();class k8{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=($,D)=>{if(!this.argChoices.includes($))throw new Ww(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function Pw(_){let $=_.name()+(_.variadic===!0?"...":"");return _.required?"<"+$+">":"["+$+"]"}zw.Argument=k8;zw.humanReadableArgName=Pw});var PP=D4((Yw)=>{var{humanReadableArgName:Rw}=BN();class q8{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((I)=>!I._hidden),D=_._getHelpCommand();if(D&&!D._hidden)$.push(D);if(this.sortSubcommands)$.sort((I,U)=>{return I.name().localeCompare(U.name())});return $}compareOptions(_,$){let D=(I)=>{return I.short?I.short.replace(/^-/,""):I.long.replace(/^--/,"")};return D(_).localeCompare(D($))}visibleOptions(_){let $=_.options.filter((I)=>!I.hidden),D=_._getHelpOption();if(D&&!D.hidden){let I=D.short&&_._findOption(D.short),U=D.long&&_._findOption(D.long);if(!I&&!U)$.push(D);else if(D.long&&!U)$.push(_.createOption(D.long,D.description));else if(D.short&&!I)$.push(_.createOption(D.short,D.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(_){if(!this.showGlobalOptions)return[];let $=[];for(let D=_.parent;D;D=D.parent){let I=D.options.filter((U)=>!U.hidden);$.push(...I)}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((D)=>Rw(D)).join(" ");return _._name+(_._aliases[0]?"|"+_._aliases[0]:"")+(_.options.length?" [options]":"")+($?" "+$:"")}optionTerm(_){return _.flags}argumentTerm(_){return _.name()}longestSubcommandTermLength(_,$){return $.visibleCommands(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(I))))},0)}longestOptionTermLength(_,$){return $.visibleOptions(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(I))))},0)}longestGlobalOptionTermLength(_,$){return $.visibleGlobalOptions(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(I))))},0)}longestArgumentTermLength(_,$){return $.visibleArguments(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleArgumentTerm($.argumentTerm(I))))},0)}commandUsage(_){let $=_._name;if(_._aliases[0])$=$+"|"+_._aliases[0];let D="";for(let I=_.parent;I;I=I.parent)D=I.name()+" "+D;return D+$+" "+_.usage()}commandDescription(_){return _.description()}subcommandDescription(_){return _.summary()||_.description()}optionDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((D)=>JSON.stringify(D)).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((D)=>JSON.stringify(D)).join(", ")}`);if(_.defaultValue!==void 0)$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`);if($.length>0){let D=`(${$.join(", ")})`;if(_.description)return`${_.description} ${D}`;return D}return _.description}formatHelp(_,$){let D=$.padWidth(_,$),I=$.helpWidth??80;function U(S,L){return $.formatItem(S,D,L,$)}let E=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(_))}`,""],j=$.commandDescription(_);if(j.length>0)E=E.concat([$.boxWrap($.styleCommandDescription(j),I),""]);let N=$.visibleArguments(_).map((S)=>{return U($.styleArgumentTerm($.argumentTerm(S)),$.styleArgumentDescription($.argumentDescription(S)))});if(N.length>0)E=E.concat([$.styleTitle("Arguments:"),...N,""]);let A=$.visibleOptions(_).map((S)=>{return U($.styleOptionTerm($.optionTerm(S)),$.styleOptionDescription($.optionDescription(S)))});if(A.length>0)E=E.concat([$.styleTitle("Options:"),...A,""]);if($.showGlobalOptions){let S=$.visibleGlobalOptions(_).map((L)=>{return U($.styleOptionTerm($.optionTerm(L)),$.styleOptionDescription($.optionDescription(L)))});if(S.length>0)E=E.concat([$.styleTitle("Global Options:"),...S,""])}let O=$.visibleCommands(_).map((S)=>{return U($.styleSubcommandTerm($.subcommandTerm(S)),$.styleSubcommandDescription($.subcommandDescription(S)))});if(O.length>0)E=E.concat([$.styleTitle("Commands:"),...O,""]);return E.join(` -`)}displayWidth(_){return C8(_).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(_,$,D,I){let E=" ".repeat(2);if(!D)return E+_;let j=_.padEnd($+_.length-I.displayWidth(_)),N=2,O=(this.helpWidth??80)-$-N-2,S;if(O{let j=E.match(I);if(j===null){U.push("");return}let N=[j.shift()],A=this.displayWidth(N[0]);j.forEach((O)=>{let S=this.displayWidth(O);if(A+S<=$){N.push(O),A+=S;return}U.push(N.join(""));let L=O.trimStart();N=[L],A=this.displayWidth(L)}),U.push(N.join(""))}),U.join(` -`)}}function C8(_){let $=/\x1b\[\d*(;\d*)*m/g;return _.replace($,"")}Yw.Help=q8;Yw.stripColor=C8});var zP=D4((Vw)=>{var{InvalidArgumentError:Tw}=k1();class w8{constructor(_,$){this.flags=_,this.description=$||"",this.required=_.includes("<"),this.optional=_.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(_),this.mandatory=!1;let D=Fw(_);if(this.short=D.shortFlag,this.long=D.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=($,D)=>{if(!this.argChoices.includes($))throw new Tw(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return v8(this.name().replace(/^no-/,""));return v8(this.name())}is(_){return this.short===_||this.long===_}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class r8{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(($,D)=>{if(this.positiveOptions.has(D))this.dualOptions.add(D)})}valueFromOption(_,$){let D=$.attributeName();if(!this.dualOptions.has(D))return!0;let I=this.negativeOptions.get(D).presetArg,U=I!==void 0?I:!1;return $.negate===(U===_)}}function v8(_){return _.split("-").reduce(($,D)=>{return $+D[0].toUpperCase()+D.slice(1)})}function Fw(_){let $,D,I=/^-[^-]$/,U=/^--[^-]/,E=_.split(/[ |,]+/).concat("guard");if(I.test(E[0]))$=E.shift();if(U.test(E[0]))D=E.shift();if(!$&&I.test(E[0]))$=E.shift();if(!$&&U.test(E[0]))$=D,D=E.shift();if(E[0].startsWith("-")){let j=E[0],N=`option creation failed due to '${j}' in option flags '${_}'`;if(/^-[^-][^-]/.test(j))throw Error(`${N} +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let j of _.seen.entries()){let N=j[1];if($===j[0]){E(j);continue}if(_.external){let S=_.external.registry.get(j[0])?.id;if($!==j[0]&&S){E(j);continue}}if(_.metadataRegistry.get(j[0])?.id){E(j);continue}if(N.cycle){E(j);continue}if(N.count>1){if(_.reused==="ref"){E(j);continue}}}}function c6(_,$){let D=_.seen.get($);if(!D)throw Error("Unprocessed schema. This is a bug in Zod.");let I=(N)=>{let O=_.seen.get(N);if(O.ref===null)return;let S=O.def??O.schema,L={...S},W=O.ref;if(O.ref=null,W){I(W);let z=_.seen.get(W),G=z.schema;if(G.$ref&&(_.target==="draft-07"||_.target==="draft-04"||_.target==="openapi-3.0"))S.allOf=S.allOf??[],S.allOf.push(G);else Object.assign(S,G);if(Object.assign(S,L),N._zod.parent===W)for(let P in S){if(P==="$ref"||P==="allOf")continue;if(!(P in L))delete S[P]}if(G.$ref&&z.def)for(let P in S){if(P==="$ref"||P==="allOf")continue;if(P in z.def&&JSON.stringify(S[P])===JSON.stringify(z.def[P]))delete S[P]}}let g=N._zod.parent;if(g&&g!==W){I(g);let z=_.seen.get(g);if(z?.schema.$ref){if(S.$ref=z.schema.$ref,z.def)for(let G in S){if(G==="$ref"||G==="allOf")continue;if(G in z.def&&JSON.stringify(S[G])===JSON.stringify(z.def[G]))delete S[G]}}}_.override({zodSchema:N,jsonSchema:S,path:O.path??[]})};for(let N of[..._.seen.entries()].reverse())I(N[0]);let U={};if(_.target==="draft-2020-12")U.$schema="https://json-schema.org/draft/2020-12/schema";else if(_.target==="draft-07")U.$schema="http://json-schema.org/draft-07/schema#";else if(_.target==="draft-04")U.$schema="http://json-schema.org/draft-04/schema#";else if(_.target==="openapi-3.0");if(_.external?.uri){let N=_.external.registry.get($)?.id;if(!N)throw Error("Schema is missing an `id` property");U.$id=_.external.uri(N)}Object.assign(U,D.def??D.schema);let E=_.metadataRegistry.get($)?.id;if(E!==void 0&&U.id===E)delete U.id;let j=_.external?.defs??{};for(let N of _.seen.entries()){let O=N[1];if(O.def&&O.defId){if(O.def.id===O.defId)delete O.def.id;j[O.defId]=O.def}}if(_.external);else if(Object.keys(j).length>0)if(_.target==="draft-2020-12")U.$defs=j;else U.definitions=j;try{let N=JSON.parse(JSON.stringify(U));return Object.defineProperty(N,"~standard",{value:{...$["~standard"],jsonSchema:{input:m0($,"input",_.processors),output:m0($,"output",_.processors)}},enumerable:!1,writable:!1}),N}catch(N){throw Error("Error converting schema to JSON.")}}function o_(_,$){let D=$??{seen:new Set};if(D.seen.has(_))return!1;D.seen.add(_);let I=_._zod.def;if(I.type==="transform")return!0;if(I.type==="array")return o_(I.element,D);if(I.type==="set")return o_(I.valueType,D);if(I.type==="lazy")return o_(I.getter(),D);if(I.type==="promise"||I.type==="optional"||I.type==="nonoptional"||I.type==="nullable"||I.type==="readonly"||I.type==="default"||I.type==="prefault")return o_(I.innerType,D);if(I.type==="intersection")return o_(I.left,D)||o_(I.right,D);if(I.type==="record"||I.type==="map")return o_(I.keyType,D)||o_(I.valueType,D);if(I.type==="pipe"){if(_._zod.traits.has("$ZodCodec"))return!0;return o_(I.in,D)||o_(I.out,D)}if(I.type==="object"){for(let U in I.shape)if(o_(I.shape[U],D))return!0;return!1}if(I.type==="union"){for(let U of I.options)if(o_(U,D))return!0;return!1}if(I.type==="tuple"){for(let U of I.items)if(o_(U,D))return!0;if(I.rest&&o_(I.rest,D))return!0;return!1}return!1}var jW=(_,$={})=>(D)=>{let I=y6({...D,processors:$});return W_(_,I),h6(I,_),c6(I,_)},m0=(_,$,D={})=>(I)=>{let{libraryOptions:U,target:E}=I??{},j=y6({...U??{},target:E,io:$,processors:D});return W_(_,j),h6(j,_),c6(j,_)};var ZU=r(()=>{YU()});function HU(_,$){if("_idmap"in _){let I=_,U=y6({...$,processors:VE}),E={};for(let O of I._idmap.entries()){let[S,L]=O;W_(L,U)}let j={},N={registry:I,uri:$?.uri,defs:E};U.external=N;for(let O of I._idmap.entries()){let[S,L]=O;h6(U,L),j[S]=c6(U,L)}if(Object.keys(E).length>0){let O=U.target==="draft-2020-12"?"$defs":"definitions";j.__shared={[O]:E}}return{schemas:j}}let D=y6({...$,processors:VE});return W_(_,D),h6(D,_),c6(D,_)}var $Z,NW=(_,$,D,I)=>{let U=D;U.type="string";let{minimum:E,maximum:j,format:N,patterns:O,contentEncoding:S}=_._zod.bag;if(typeof E==="number")U.minLength=E;if(typeof j==="number")U.maxLength=j;if(N){if(U.format=$Z[N]??N,U.format==="")delete U.format;if(N==="time")delete U.format}if(S)U.contentEncoding=S;if(O&&O.size>0){let L=[...O];if(L.length===1)U.pattern=L[0].source;else if(L.length>1)U.allOf=[...L.map((W)=>({...$.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"?{type:"string"}:{},pattern:W.source}))]}},AW=(_,$,D,I)=>{let U=D,{minimum:E,maximum:j,format:N,multipleOf:O,exclusiveMaximum:S,exclusiveMinimum:L}=_._zod.bag;if(typeof N==="string"&&N.includes("int"))U.type="integer";else U.type="number";let W=typeof L==="number"&&L>=(E??Number.NEGATIVE_INFINITY),g=typeof S==="number"&&S<=(j??Number.POSITIVE_INFINITY),z=$.target==="draft-04"||$.target==="openapi-3.0";if(W)if(z)U.minimum=L,U.exclusiveMinimum=!0;else U.exclusiveMinimum=L;else if(typeof E==="number")U.minimum=E;if(g)if(z)U.maximum=S,U.exclusiveMaximum=!0;else U.exclusiveMaximum=S;else if(typeof j==="number")U.maximum=j;if(typeof O==="number")U.multipleOf=O},OW=(_,$,D,I)=>{D.type="boolean"},SW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},LW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},WW=(_,$,D,I)=>{if($.target==="openapi-3.0")D.type="string",D.nullable=!0,D.enum=[null];else D.type="null"},JW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},PW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},zW=(_,$,D,I)=>{D.not={}},gW=(_,$,D,I)=>{},XW=(_,$,D,I)=>{},GW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},RW=(_,$,D,I)=>{let U=_._zod.def,E=UU(U.entries);if(E.every((j)=>typeof j==="number"))D.type="number";if(E.every((j)=>typeof j==="string"))D.type="string";D.enum=E},YW=(_,$,D,I)=>{let U=_._zod.def,E=[];for(let j of U.values)if(j===void 0){if($.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof j==="bigint")if($.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else E.push(Number(j));else E.push(j);if(E.length===0);else if(E.length===1){let j=E[0];if(D.type=j===null?"null":typeof j,$.target==="draft-04"||$.target==="openapi-3.0")D.enum=[j];else D.const=j}else{if(E.every((j)=>typeof j==="number"))D.type="number";if(E.every((j)=>typeof j==="string"))D.type="string";if(E.every((j)=>typeof j==="boolean"))D.type="boolean";if(E.every((j)=>j===null))D.type="null";D.enum=E}},QW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},KW=(_,$,D,I)=>{let U=D,E=_._zod.pattern;if(!E)throw Error("Pattern not found in template literal");U.type="string",U.pattern=E.source},TW=(_,$,D,I)=>{let U=D,E={type:"string",format:"binary",contentEncoding:"binary"},{minimum:j,maximum:N,mime:O}=_._zod.bag;if(j!==void 0)E.minLength=j;if(N!==void 0)E.maxLength=N;if(O)if(O.length===1)E.contentMediaType=O[0],Object.assign(U,E);else Object.assign(U,E),U.anyOf=O.map((S)=>({contentMediaType:S}));else Object.assign(U,E)},FW=(_,$,D,I)=>{D.type="boolean"},VW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},BW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},MW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},ZW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},HW=(_,$,D,I)=>{if($.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},bW=(_,$,D,I)=>{let U=D,E=_._zod.def,{minimum:j,maximum:N}=_._zod.bag;if(typeof j==="number")U.minItems=j;if(typeof N==="number")U.maxItems=N;U.type="array",U.items=W_(E.element,$,{...I,path:[...I.path,"items"]})},qW=(_,$,D,I)=>{let U=D,E=_._zod.def;U.type="object",U.properties={};let j=E.shape;for(let S in j)U.properties[S]=W_(j[S],$,{...I,path:[...I.path,"properties",S]});let N=new Set(Object.keys(j)),O=new Set([...N].filter((S)=>{let L=E.shape[S]._zod;if($.io==="input")return L.optin===void 0;else return L.optout===void 0}));if(O.size>0)U.required=Array.from(O);if(E.catchall?._zod.def.type==="never")U.additionalProperties=!1;else if(!E.catchall){if($.io==="output")U.additionalProperties=!1}else if(E.catchall)U.additionalProperties=W_(E.catchall,$,{...I,path:[...I.path,"additionalProperties"]})},BE=(_,$,D,I)=>{let U=_._zod.def,E=U.inclusive===!1,j=U.options.map((N,O)=>W_(N,$,{...I,path:[...I.path,E?"oneOf":"anyOf",O]}));if(E)D.oneOf=j;else D.anyOf=j},kW=(_,$,D,I)=>{let U=_._zod.def,E=W_(U.left,$,{...I,path:[...I.path,"allOf",0]}),j=W_(U.right,$,{...I,path:[...I.path,"allOf",1]}),N=(S)=>("allOf"in S)&&Object.keys(S).length===1,O=[...N(E)?E.allOf:[E],...N(j)?j.allOf:[j]];D.allOf=O},CW=(_,$,D,I)=>{let U=D,E=_._zod.def;U.type="array";let j=$.target==="draft-2020-12"?"prefixItems":"items",N=$.target==="draft-2020-12"?"items":$.target==="openapi-3.0"?"items":"additionalItems",O=E.items.map((g,z)=>W_(g,$,{...I,path:[...I.path,j,z]})),S=E.rest?W_(E.rest,$,{...I,path:[...I.path,N,...$.target==="openapi-3.0"?[E.items.length]:[]]}):null;if($.target==="draft-2020-12"){if(U.prefixItems=O,S)U.items=S}else if($.target==="openapi-3.0"){if(U.items={anyOf:O},S)U.items.anyOf.push(S);if(U.minItems=O.length,!S)U.maxItems=O.length}else if(U.items=O,S)U.additionalItems=S;let{minimum:L,maximum:W}=_._zod.bag;if(typeof L==="number")U.minItems=L;if(typeof W==="number")U.maxItems=W},vW=(_,$,D,I)=>{let U=D,E=_._zod.def;U.type="object";let j=E.keyType,O=j._zod.bag?.patterns;if(E.mode==="loose"&&O&&O.size>0){let L=W_(E.valueType,$,{...I,path:[...I.path,"patternProperties","*"]});U.patternProperties={};for(let W of O)U.patternProperties[W.source]=L}else{if($.target==="draft-07"||$.target==="draft-2020-12")U.propertyNames=W_(E.keyType,$,{...I,path:[...I.path,"propertyNames"]});U.additionalProperties=W_(E.valueType,$,{...I,path:[...I.path,"additionalProperties"]})}let S=j._zod.values;if(S){let L=[...S].filter((W)=>typeof W==="string"||typeof W==="number");if(L.length>0)U.required=L}},wW=(_,$,D,I)=>{let U=_._zod.def,E=W_(U.innerType,$,I),j=$.seen.get(_);if($.target==="openapi-3.0")j.ref=U.innerType,D.nullable=!0;else D.anyOf=[E,{type:"null"}]},rW=(_,$,D,I)=>{let U=_._zod.def;W_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType},fW=(_,$,D,I)=>{let U=_._zod.def;W_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType,D.default=JSON.parse(JSON.stringify(U.defaultValue))},xW=(_,$,D,I)=>{let U=_._zod.def;W_(U.innerType,$,I);let E=$.seen.get(_);if(E.ref=U.innerType,$.io==="input")D._prefault=JSON.parse(JSON.stringify(U.defaultValue))},uW=(_,$,D,I)=>{let U=_._zod.def;W_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType;let j;try{j=U.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}D.default=j},yW=(_,$,D,I)=>{let U=_._zod.def,E=U.in._zod.traits.has("$ZodTransform"),j=$.io==="input"?E?U.out:U.in:U.out;W_(j,$,I);let N=$.seen.get(_);N.ref=j},hW=(_,$,D,I)=>{let U=_._zod.def;W_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType,D.readOnly=!0},cW=(_,$,D,I)=>{let U=_._zod.def;W_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType},ME=(_,$,D,I)=>{let U=_._zod.def;W_(U.innerType,$,I);let E=$.seen.get(_);E.ref=U.innerType},nW=(_,$,D,I)=>{let U=_._zod.innerType;W_(U,$,I);let E=$.seen.get(_);E.ref=U},VE;var bU=r(()=>{ZU();n();$Z={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},VE={string:NW,number:AW,boolean:OW,bigint:SW,symbol:LW,null:WW,undefined:JW,void:PW,never:zW,any:gW,unknown:XW,date:GW,enum:RW,literal:YW,nan:QW,template_literal:KW,file:TW,success:FW,custom:VW,function:BW,transform:MW,map:ZW,set:HW,array:bW,object:qW,union:BE,intersection:kW,tuple:CW,record:vW,nullable:wW,nonoptional:rW,default:fW,prefault:xW,catch:uW,pipe:yW,readonly:hW,promise:cW,optional:ME,lazy:nW}});class dW{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=y6({processors:VE,target:$,..._?.metadata&&{metadata:_.metadata},..._?.unrepresentable&&{unrepresentable:_.unrepresentable},..._?.override&&{override:_.override},..._?.io&&{io:_.io}})}process(_,$={path:[],schemaPath:[]}){return W_(_,this.ctx,$)}emit(_,$){if($){if($.cycles)this.ctx.cycles=$.cycles;if($.reused)this.ctx.reused=$.reused;if($.external)this.ctx.external=$.external}h6(this.ctx,_);let D=c6(this.ctx,_),{"~standard":I,...U}=D;return U}}var QG=r(()=>{bU();ZU()});var KG={};var TG=()=>{};var i$={};x$(i$,{version:()=>OO,util:()=>q,treeifyError:()=>HI,toJSONSchema:()=>HU,toDotPath:()=>iX,safeParseAsync:()=>PA,safeParse:()=>JA,safeEncodeAsync:()=>IB,safeEncode:()=>DB,safeDecodeAsync:()=>EB,safeDecode:()=>UB,registry:()=>RU,regexes:()=>U$,process:()=>W_,prettifyError:()=>bI,parseAsync:()=>kI,parse:()=>qI,meta:()=>IW,locales:()=>n0,isValidJWT:()=>z5,isValidBase64URL:()=>P5,isValidBase64:()=>kO,initializeContext:()=>y6,globalRegistry:()=>x_,globalConfig:()=>g4,formatError:()=>r0,flattenError:()=>w0,finalize:()=>c6,extractDefs:()=>h6,encodeAsync:()=>_B,encode:()=>aV,describe:()=>UW,decodeAsync:()=>$B,decode:()=>sV,createToJSONSchemaMethod:()=>jW,createStandardJSONSchemaMethod:()=>m0,config:()=>b_,clone:()=>h_,_xor:()=>CM,_xid:()=>PE,_void:()=>tL,_uuidv7:()=>AE,_uuidv6:()=>NE,_uuidv4:()=>jE,_uuid:()=>EE,_url:()=>KU,_uppercase:()=>F4,_unknown:()=>lL,_union:()=>kM,_undefined:()=>nL,_ulid:()=>JE,_uint64:()=>hL,_uint32:()=>wL,_tuple:()=>rM,_trim:()=>b4,_transform:()=>nM,_toUpperCase:()=>k4,_toLowerCase:()=>q4,_templateLiteral:()=>aM,_symbol:()=>cL,_superRefine:()=>DW,_success:()=>tM,_stringbool:()=>EW,_stringFormat:()=>d0,_string:()=>KL,_startsWith:()=>B4,_slugify:()=>C4,_size:()=>f6,_set:()=>uM,_safeParseAsync:()=>y0,_safeParse:()=>u0,_safeEncodeAsync:()=>uI,_safeEncode:()=>fI,_safeDecodeAsync:()=>yI,_safeDecode:()=>xI,_regex:()=>K4,_refine:()=>$W,_record:()=>fM,_readonly:()=>eM,_property:()=>MU,_promise:()=>_Z,_positive:()=>TU,_pipe:()=>pM,_parseAsync:()=>x0,_parse:()=>f0,_overwrite:()=>X$,_optional:()=>dM,_number:()=>HL,_nullable:()=>mM,_null:()=>dL,_normalize:()=>H4,_nonpositive:()=>VU,_nonoptional:()=>iM,_nonnegative:()=>BU,_never:()=>iL,_negative:()=>FU,_nativeEnum:()=>hM,_nanoid:()=>SE,_nan:()=>eL,_multipleOf:()=>W6,_minSize:()=>M$,_minLength:()=>l$,_min:()=>c_,_mime:()=>Z4,_maxSize:()=>J6,_maxLength:()=>x6,_max:()=>I$,_map:()=>xM,_mac:()=>FL,_lte:()=>I$,_lt:()=>V$,_lowercase:()=>T4,_literal:()=>cM,_length:()=>u6,_lazy:()=>sM,_ksuid:()=>zE,_jwt:()=>TE,_isoTime:()=>ML,_isoDuration:()=>ZL,_isoDateTime:()=>VL,_isoDate:()=>BL,_ipv6:()=>XE,_ipv4:()=>gE,_intersection:()=>wM,_int64:()=>yL,_int32:()=>vL,_int:()=>qL,_includes:()=>V4,_guid:()=>QU,_gte:()=>c_,_gt:()=>B$,_float64:()=>CL,_float32:()=>kL,_file:()=>sL,_enum:()=>yM,_endsWith:()=>M4,_encodeAsync:()=>wI,_encode:()=>CI,_emoji:()=>OE,_email:()=>IE,_e164:()=>KE,_discriminatedUnion:()=>vM,_default:()=>lM,_decodeAsync:()=>rI,_decode:()=>vI,_date:()=>oL,_custom:()=>_W,_cuid2:()=>WE,_cuid:()=>LE,_coercedString:()=>TL,_coercedNumber:()=>bL,_coercedDate:()=>pL,_coercedBoolean:()=>fL,_coercedBigint:()=>uL,_cidrv6:()=>RE,_cidrv4:()=>GE,_check:()=>RG,_catch:()=>oM,_boolean:()=>rL,_bigint:()=>xL,_base64url:()=>QE,_base64:()=>YE,_array:()=>aL,_any:()=>mL,TimePrecision:()=>FE,NEVER:()=>VI,JSONSchemaGenerator:()=>dW,JSONSchema:()=>KG,Doc:()=>lI,$output:()=>DE,$input:()=>UE,$constructor:()=>K,$brand:()=>BI,$ZodXor:()=>pO,$ZodXID:()=>QO,$ZodVoid:()=>lO,$ZodUnknown:()=>dO,$ZodUnion:()=>JU,$ZodUndefined:()=>hO,$ZodUUID:()=>JO,$ZodURL:()=>zO,$ZodULID:()=>YO,$ZodType:()=>p,$ZodTuple:()=>sI,$ZodTransform:()=>ES,$ZodTemplateLiteral:()=>gS,$ZodSymbol:()=>yO,$ZodSuccess:()=>LS,$ZodStringFormat:()=>Y_,$ZodString:()=>Q4,$ZodSet:()=>$S,$ZodRegistry:()=>QL,$ZodRecord:()=>sO,$ZodRealError:()=>D$,$ZodReadonly:()=>zS,$ZodPromise:()=>GS,$ZodPreprocess:()=>PS,$ZodPrefault:()=>OS,$ZodPipe:()=>$E,$ZodOptional:()=>_E,$ZodObjectJIT:()=>oO,$ZodObject:()=>G5,$ZodNumberFormat:()=>xO,$ZodNumber:()=>eI,$ZodNullable:()=>NS,$ZodNull:()=>cO,$ZodNonOptional:()=>SS,$ZodNever:()=>mO,$ZodNanoID:()=>XO,$ZodNaN:()=>JS,$ZodMap:()=>_S,$ZodMAC:()=>HO,$ZodLiteral:()=>US,$ZodLazy:()=>RS,$ZodKSUID:()=>KO,$ZodJWT:()=>rO,$ZodIntersection:()=>aO,$ZodISOTime:()=>VO,$ZodISODuration:()=>BO,$ZodISODateTime:()=>TO,$ZodISODate:()=>FO,$ZodIPv6:()=>ZO,$ZodIPv4:()=>MO,$ZodGUID:()=>WO,$ZodFunction:()=>XS,$ZodFile:()=>IS,$ZodExactOptional:()=>jS,$ZodError:()=>AU,$ZodEnum:()=>DS,$ZodEncodeError:()=>X4,$ZodEmoji:()=>gO,$ZodEmail:()=>PO,$ZodE164:()=>wO,$ZodDiscriminatedUnion:()=>eO,$ZodDefault:()=>AS,$ZodDate:()=>iO,$ZodCustomStringFormat:()=>fO,$ZodCustom:()=>YS,$ZodCodec:()=>PU,$ZodCheckUpperCase:()=>DO,$ZodCheckStringFormat:()=>h0,$ZodCheckStartsWith:()=>IO,$ZodCheckSizeEquals:()=>pA,$ZodCheckRegex:()=>_O,$ZodCheckProperty:()=>jO,$ZodCheckOverwrite:()=>AO,$ZodCheckNumberFormat:()=>lA,$ZodCheckMultipleOf:()=>mA,$ZodCheckMinSize:()=>oA,$ZodCheckMinLength:()=>aA,$ZodCheckMimeType:()=>NO,$ZodCheckMaxSize:()=>tA,$ZodCheckMaxLength:()=>eA,$ZodCheckLowerCase:()=>$O,$ZodCheckLessThan:()=>nI,$ZodCheckLengthEquals:()=>sA,$ZodCheckIncludes:()=>UO,$ZodCheckGreaterThan:()=>dI,$ZodCheckEndsWith:()=>EO,$ZodCheckBigIntFormat:()=>iA,$ZodCheck:()=>Q_,$ZodCatch:()=>WS,$ZodCUID2:()=>RO,$ZodCUID:()=>GO,$ZodCIDRv6:()=>qO,$ZodCIDRv4:()=>bO,$ZodBoolean:()=>WU,$ZodBigIntFormat:()=>uO,$ZodBigInt:()=>aI,$ZodBase64URL:()=>vO,$ZodBase64:()=>CO,$ZodAsyncError:()=>m$,$ZodArray:()=>tO,$ZodAny:()=>nO});var S$=r(()=>{n();cI();YL();bU();QG();TG();G4();zA();WA();QS();mI();SO();YU();YG();ZU()});var ZE={};x$(ZE,{uppercase:()=>F4,trim:()=>b4,toUpperCase:()=>k4,toLowerCase:()=>q4,startsWith:()=>B4,slugify:()=>C4,size:()=>f6,regex:()=>K4,property:()=>MU,positive:()=>TU,overwrite:()=>X$,normalize:()=>H4,nonpositive:()=>VU,nonnegative:()=>BU,negative:()=>FU,multipleOf:()=>W6,minSize:()=>M$,minLength:()=>l$,mime:()=>Z4,maxSize:()=>J6,maxLength:()=>x6,lte:()=>I$,lt:()=>V$,lowercase:()=>T4,length:()=>u6,includes:()=>V4,gte:()=>c_,gt:()=>B$,endsWith:()=>M4});var HE=r(()=>{S$()});var v4={};x$(v4,{time:()=>iW,duration:()=>tW,datetime:()=>mW,date:()=>lW,ZodISOTime:()=>CU,ZodISODuration:()=>vU,ZodISODateTime:()=>qU,ZodISODate:()=>kU});function mW(_){return VL(qU,_)}function lW(_){return BL(kU,_)}function iW(_){return ML(CU,_)}function tW(_){return ZL(vU,_)}var qU,kU,CU,vU;var wU=r(()=>{S$();fU();qU=K("ZodISODateTime",(_,$)=>{TO.init(_,$),z_.init(_,$)});kU=K("ZodISODate",(_,$)=>{FO.init(_,$),z_.init(_,$)});CU=K("ZodISOTime",(_,$)=>{VO.init(_,$),z_.init(_,$)});vU=K("ZodISODuration",(_,$)=>{BO.init(_,$),z_.init(_,$)})});var FG=(_,$)=>{AU.init(_,$),_.name="ZodError",Object.defineProperties(_,{format:{value:(D)=>r0(_,D)},flatten:{value:(D)=>w0(_,D)},addIssue:{value:(D)=>{_.issues.push(D),_.message=JSON.stringify(_.issues,k0,2)}},addIssues:{value:(D)=>{_.issues.push(...D),_.message=JSON.stringify(_.issues,k0,2)}},isEmpty:{get(){return _.issues.length===0}}})},VG,p_;var oW=r(()=>{S$();S$();n();VG=K("ZodError",FG),p_=K("ZodError",FG,{Parent:Error})});var bE,qE,kE,CE,vE,wE,rE,fE,xE,uE,yE,hE;var pW=r(()=>{S$();oW();bE=f0(p_),qE=x0(p_),kE=u0(p_),CE=y0(p_),vE=CI(p_),wE=vI(p_),rE=wI(p_),fE=rI(p_),xE=fI(p_),uE=xI(p_),yE=uI(p_),hE=yI(p_)});var rU={};x$(rU,{xor:()=>hJ,xid:()=>SJ,void:()=>wJ,uuidv7:()=>DJ,uuidv6:()=>$J,uuidv4:()=>_J,uuid:()=>sW,url:()=>UJ,unknown:()=>n6,union:()=>j1,undefined:()=>CJ,ulid:()=>OJ,uint64:()=>qJ,uint32:()=>ZJ,tuple:()=>Ej,transform:()=>A1,templateLiteral:()=>$P,symbol:()=>kJ,superRefine:()=>Cj,success:()=>eJ,stringbool:()=>OP,stringFormat:()=>QJ,string:()=>l0,strictObject:()=>uJ,set:()=>lJ,refine:()=>kj,record:()=>jj,readonly:()=>Bj,promise:()=>DP,preprocess:()=>LP,prefault:()=>Gj,pipe:()=>uU,partialRecord:()=>nJ,optional:()=>t0,object:()=>xJ,number:()=>nE,nullish:()=>pJ,nullable:()=>o0,null:()=>tE,nonoptional:()=>Rj,never:()=>E1,nativeEnum:()=>iJ,nanoid:()=>jJ,nan:()=>aJ,meta:()=>NP,map:()=>mJ,mac:()=>JJ,looseRecord:()=>dJ,looseObject:()=>yJ,literal:()=>tJ,lazy:()=>Hj,ksuid:()=>LJ,keyof:()=>fJ,jwt:()=>YJ,json:()=>SP,ipv6:()=>PJ,ipv4:()=>WJ,invertCodec:()=>_P,intersection:()=>Uj,int64:()=>bJ,int32:()=>MJ,int:()=>xU,instanceof:()=>AP,httpUrl:()=>IJ,hostname:()=>KJ,hex:()=>TJ,hash:()=>FJ,guid:()=>aW,function:()=>UP,float64:()=>BJ,float32:()=>VJ,file:()=>oJ,exactOptional:()=>Jj,enum:()=>N1,emoji:()=>EJ,email:()=>eW,e164:()=>RJ,discriminatedUnion:()=>cJ,describe:()=>jP,date:()=>rJ,custom:()=>EP,cuid2:()=>AJ,cuid:()=>NJ,codec:()=>sJ,cidrv6:()=>gJ,cidrv4:()=>zJ,check:()=>IP,catch:()=>Kj,boolean:()=>dE,bigint:()=>HJ,base64url:()=>GJ,base64:()=>XJ,array:()=>a0,any:()=>vJ,_function:()=>UP,_default:()=>gj,_ZodString:()=>hU,ZodXor:()=>_j,ZodXID:()=>tU,ZodVoid:()=>aE,ZodUnknown:()=>pE,ZodUnion:()=>_D,ZodUndefined:()=>lE,ZodUUID:()=>Z$,ZodURL:()=>p0,ZodULID:()=>iU,ZodType:()=>a,ZodTuple:()=>Ij,ZodTransform:()=>Lj,ZodTemplateLiteral:()=>Mj,ZodSymbol:()=>mE,ZodSuccess:()=>Yj,ZodStringFormat:()=>z_,ZodString:()=>f4,ZodSet:()=>Aj,ZodRecord:()=>w4,ZodReadonly:()=>Vj,ZodPromise:()=>bj,ZodPreprocess:()=>Fj,ZodPrefault:()=>Xj,ZodPipe:()=>$D,ZodOptional:()=>O1,ZodObject:()=>s0,ZodNumberFormat:()=>d6,ZodNumber:()=>u4,ZodNullable:()=>Pj,ZodNull:()=>iE,ZodNonOptional:()=>S1,ZodNever:()=>eE,ZodNanoID:()=>dU,ZodNaN:()=>Tj,ZodMap:()=>Nj,ZodMAC:()=>cE,ZodLiteral:()=>Oj,ZodLazy:()=>Zj,ZodKSUID:()=>oU,ZodJWT:()=>U1,ZodIntersection:()=>Dj,ZodIPv6:()=>eU,ZodIPv4:()=>pU,ZodGUID:()=>i0,ZodFunction:()=>qj,ZodFile:()=>Sj,ZodExactOptional:()=>Wj,ZodEnum:()=>r4,ZodEmoji:()=>nU,ZodEmail:()=>cU,ZodE164:()=>D1,ZodDiscriminatedUnion:()=>$j,ZodDefault:()=>zj,ZodDate:()=>e0,ZodCustomStringFormat:()=>x4,ZodCustom:()=>UD,ZodCodec:()=>DD,ZodCatch:()=>Qj,ZodCUID2:()=>lU,ZodCUID:()=>mU,ZodCIDRv6:()=>sU,ZodCIDRv4:()=>aU,ZodBoolean:()=>y4,ZodBigIntFormat:()=>I1,ZodBigInt:()=>h4,ZodBase64URL:()=>$1,ZodBase64:()=>_1,ZodArray:()=>sE,ZodAny:()=>oE});function yU(_,$,D){let I=Object.getPrototypeOf(_),U=BG.get(I);if(!U)U=new Set,BG.set(I,U);if(U.has($))return;U.add($);for(let E in D){let j=D[E];Object.defineProperty(I,E,{configurable:!0,enumerable:!1,get(){let N=j.bind(this);return Object.defineProperty(this,E,{configurable:!0,writable:!0,enumerable:!0,value:N}),N},set(N){Object.defineProperty(this,E,{configurable:!0,writable:!0,enumerable:!0,value:N})}})}}function l0(_){return KL(f4,_)}function eW(_){return IE(cU,_)}function aW(_){return QU(i0,_)}function sW(_){return EE(Z$,_)}function _J(_){return jE(Z$,_)}function $J(_){return NE(Z$,_)}function DJ(_){return AE(Z$,_)}function UJ(_){return KU(p0,_)}function IJ(_){return KU(p0,{protocol:U$.httpProtocol,hostname:U$.domain,...q.normalizeParams(_)})}function EJ(_){return OE(nU,_)}function jJ(_){return SE(dU,_)}function NJ(_){return LE(mU,_)}function AJ(_){return WE(lU,_)}function OJ(_){return JE(iU,_)}function SJ(_){return PE(tU,_)}function LJ(_){return zE(oU,_)}function WJ(_){return gE(pU,_)}function JJ(_){return FL(cE,_)}function PJ(_){return XE(eU,_)}function zJ(_){return GE(aU,_)}function gJ(_){return RE(sU,_)}function XJ(_){return YE(_1,_)}function GJ(_){return QE($1,_)}function RJ(_){return KE(D1,_)}function YJ(_){return TE(U1,_)}function QJ(_,$,D={}){return d0(x4,_,$,D)}function KJ(_){return d0(x4,"hostname",U$.hostname,_)}function TJ(_){return d0(x4,"hex",U$.hex,_)}function FJ(_,$){let D=$?.enc??"hex",I=`${_}_${D}`,U=U$[I];if(!U)throw Error(`Unrecognized hash format: ${I}`);return d0(x4,I,U,$)}function nE(_){return HL(u4,_)}function xU(_){return qL(d6,_)}function VJ(_){return kL(d6,_)}function BJ(_){return CL(d6,_)}function MJ(_){return vL(d6,_)}function ZJ(_){return wL(d6,_)}function dE(_){return rL(y4,_)}function HJ(_){return xL(h4,_)}function bJ(_){return yL(I1,_)}function qJ(_){return hL(I1,_)}function kJ(_){return cL(mE,_)}function CJ(_){return nL(lE,_)}function tE(_){return dL(iE,_)}function vJ(){return mL(oE)}function n6(){return lL(pE)}function E1(_){return iL(eE,_)}function wJ(_){return tL(aE,_)}function rJ(_){return oL(e0,_)}function a0(_,$){return aL(sE,_,$)}function fJ(_){let $=_._zod.def.shape;return N1(Object.keys($))}function xJ(_,$){let D={type:"object",shape:_??{},...q.normalizeParams($)};return new s0(D)}function uJ(_,$){return new s0({type:"object",shape:_,catchall:E1(),...q.normalizeParams($)})}function yJ(_,$){return new s0({type:"object",shape:_,catchall:n6(),...q.normalizeParams($)})}function j1(_,$){return new _D({type:"union",options:_,...q.normalizeParams($)})}function hJ(_,$){return new _j({type:"union",options:_,inclusive:!1,...q.normalizeParams($)})}function cJ(_,$,D){return new $j({type:"union",options:$,discriminator:_,...q.normalizeParams(D)})}function Uj(_,$){return new Dj({type:"intersection",left:_,right:$})}function Ej(_,$,D){let I=$ instanceof p,U=I?D:$;return new Ij({type:"tuple",items:_,rest:I?$:null,...q.normalizeParams(U)})}function jj(_,$,D){if(!$||!$._zod)return new w4({type:"record",keyType:l0(),valueType:_,...q.normalizeParams($)});return new w4({type:"record",keyType:_,valueType:$,...q.normalizeParams(D)})}function nJ(_,$,D){let I=h_(_);return I._zod.values=void 0,new w4({type:"record",keyType:I,valueType:$,...q.normalizeParams(D)})}function dJ(_,$,D){return new w4({type:"record",keyType:_,valueType:$,mode:"loose",...q.normalizeParams(D)})}function mJ(_,$,D){return new Nj({type:"map",keyType:_,valueType:$,...q.normalizeParams(D)})}function lJ(_,$){return new Aj({type:"set",valueType:_,...q.normalizeParams($)})}function N1(_,$){let D=Array.isArray(_)?Object.fromEntries(_.map((I)=>[I,I])):_;return new r4({type:"enum",entries:D,...q.normalizeParams($)})}function iJ(_,$){return new r4({type:"enum",entries:_,...q.normalizeParams($)})}function tJ(_,$){return new Oj({type:"literal",values:Array.isArray(_)?_:[_],...q.normalizeParams($)})}function oJ(_){return sL(Sj,_)}function A1(_){return new Lj({type:"transform",transform:_})}function t0(_){return new O1({type:"optional",innerType:_})}function Jj(_){return new Wj({type:"optional",innerType:_})}function o0(_){return new Pj({type:"nullable",innerType:_})}function pJ(_){return t0(o0(_))}function gj(_,$){return new zj({type:"default",innerType:_,get defaultValue(){return typeof $==="function"?$():q.shallowClone($)}})}function Gj(_,$){return new Xj({type:"prefault",innerType:_,get defaultValue(){return typeof $==="function"?$():q.shallowClone($)}})}function Rj(_,$){return new S1({type:"nonoptional",innerType:_,...q.normalizeParams($)})}function eJ(_){return new Yj({type:"success",innerType:_})}function Kj(_,$){return new Qj({type:"catch",innerType:_,catchValue:typeof $==="function"?$:()=>$})}function aJ(_){return eL(Tj,_)}function uU(_,$){return new $D({type:"pipe",in:_,out:$})}function sJ(_,$,D){return new DD({type:"pipe",in:_,out:$,transform:D.decode,reverseTransform:D.encode})}function _P(_){let $=_._zod.def;return new DD({type:"pipe",in:$.out,out:$.in,transform:$.reverseTransform,reverseTransform:$.transform})}function Bj(_){return new Vj({type:"readonly",innerType:_})}function $P(_,$){return new Mj({type:"template_literal",parts:_,...q.normalizeParams($)})}function Hj(_){return new Zj({type:"lazy",getter:_})}function DP(_){return new bj({type:"promise",innerType:_})}function UP(_){return new qj({type:"function",input:Array.isArray(_?.input)?Ej(_?.input):_?.input??a0(n6()),output:_?.output??n6()})}function IP(_){let $=new Q_({check:"custom"});return $._zod.check=_,$}function EP(_,$){return _W(UD,_??(()=>!0),$)}function kj(_,$={}){return $W(UD,_,$)}function Cj(_,$){return DW(_,$)}function AP(_,$={}){let D=new UD({type:"custom",check:"custom",fn:(I)=>I instanceof _,abort:!0,...q.normalizeParams($)});return D._zod.bag.Class=_,D._zod.check=(I)=>{if(!(I.value instanceof _))I.issues.push({code:"invalid_type",expected:_.name,input:I.value,inst:D,path:[...D._zod.def.path??[]]})},D}function SP(_){let $=Hj(()=>{return j1([l0(_),nE(),dE(),tE(),a0($),jj(l0(),$)])});return $}function LP(_,$){return new Fj({type:"pipe",in:A1(_),out:$})}var BG,a,hU,f4,z_,cU,i0,Z$,p0,nU,dU,mU,lU,iU,tU,oU,pU,cE,eU,aU,sU,_1,$1,D1,U1,x4,u4,d6,y4,h4,I1,mE,lE,iE,oE,pE,eE,aE,e0,sE,s0,_D,_j,$j,Dj,Ij,w4,Nj,Aj,r4,Oj,Sj,Lj,O1,Wj,Pj,zj,Xj,S1,Yj,Qj,Tj,$D,DD,Fj,Vj,Mj,Zj,bj,qj,UD,jP,NP,OP=(..._)=>EW({Codec:DD,Boolean:y4,String:f4},..._);var fU=r(()=>{S$();S$();bU();ZU();HE();wU();pW();BG=new WeakMap;a=K("ZodType",(_,$)=>{return p.init(_,$),Object.assign(_["~standard"],{jsonSchema:{input:m0(_,"input"),output:m0(_,"output")}}),_.toJSONSchema=jW(_,{}),_.def=$,_.type=$.type,Object.defineProperty(_,"_def",{value:$}),_.parse=(D,I)=>bE(_,D,I,{callee:_.parse}),_.safeParse=(D,I)=>kE(_,D,I),_.parseAsync=async(D,I)=>qE(_,D,I,{callee:_.parseAsync}),_.safeParseAsync=async(D,I)=>CE(_,D,I),_.spa=_.safeParseAsync,_.encode=(D,I)=>vE(_,D,I),_.decode=(D,I)=>wE(_,D,I),_.encodeAsync=async(D,I)=>rE(_,D,I),_.decodeAsync=async(D,I)=>fE(_,D,I),_.safeEncode=(D,I)=>xE(_,D,I),_.safeDecode=(D,I)=>uE(_,D,I),_.safeEncodeAsync=async(D,I)=>yE(_,D,I),_.safeDecodeAsync=async(D,I)=>hE(_,D,I),yU(_,"ZodType",{check(...D){let I=this.def;return this.clone(q.mergeDefs(I,{checks:[...I.checks??[],...D.map((U)=>typeof U==="function"?{_zod:{check:U,def:{check:"custom"},onattach:[]}}:U)]}),{parent:!0})},with(...D){return this.check(...D)},clone(D,I){return h_(this,D,I)},brand(){return this},register(D,I){return D.add(this,I),this},refine(D,I){return this.check(kj(D,I))},superRefine(D,I){return this.check(Cj(D,I))},overwrite(D){return this.check(X$(D))},optional(){return t0(this)},exactOptional(){return Jj(this)},nullable(){return o0(this)},nullish(){return t0(o0(this))},nonoptional(D){return Rj(this,D)},array(){return a0(this)},or(D){return j1([this,D])},and(D){return Uj(this,D)},transform(D){return uU(this,A1(D))},default(D){return gj(this,D)},prefault(D){return Gj(this,D)},catch(D){return Kj(this,D)},pipe(D){return uU(this,D)},readonly(){return Bj(this)},describe(D){let I=this.clone();return x_.add(I,{description:D}),I},meta(...D){if(D.length===0)return x_.get(this);let I=this.clone();return x_.add(I,D[0]),I},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(D){return D(this)}}),Object.defineProperty(_,"description",{get(){return x_.get(_)?.description},configurable:!0}),_}),hU=K("_ZodString",(_,$)=>{Q4.init(_,$),a.init(_,$),_._zod.processJSONSchema=(I,U,E)=>NW(_,I,U,E);let D=_._zod.bag;_.format=D.format??null,_.minLength=D.minimum??null,_.maxLength=D.maximum??null,yU(_,"_ZodString",{regex(...I){return this.check(K4(...I))},includes(...I){return this.check(V4(...I))},startsWith(...I){return this.check(B4(...I))},endsWith(...I){return this.check(M4(...I))},min(...I){return this.check(l$(...I))},max(...I){return this.check(x6(...I))},length(...I){return this.check(u6(...I))},nonempty(...I){return this.check(l$(1,...I))},lowercase(I){return this.check(T4(I))},uppercase(I){return this.check(F4(I))},trim(){return this.check(b4())},normalize(...I){return this.check(H4(...I))},toLowerCase(){return this.check(q4())},toUpperCase(){return this.check(k4())},slugify(){return this.check(C4())}})}),f4=K("ZodString",(_,$)=>{Q4.init(_,$),hU.init(_,$),_.email=(D)=>_.check(IE(cU,D)),_.url=(D)=>_.check(KU(p0,D)),_.jwt=(D)=>_.check(TE(U1,D)),_.emoji=(D)=>_.check(OE(nU,D)),_.guid=(D)=>_.check(QU(i0,D)),_.uuid=(D)=>_.check(EE(Z$,D)),_.uuidv4=(D)=>_.check(jE(Z$,D)),_.uuidv6=(D)=>_.check(NE(Z$,D)),_.uuidv7=(D)=>_.check(AE(Z$,D)),_.nanoid=(D)=>_.check(SE(dU,D)),_.guid=(D)=>_.check(QU(i0,D)),_.cuid=(D)=>_.check(LE(mU,D)),_.cuid2=(D)=>_.check(WE(lU,D)),_.ulid=(D)=>_.check(JE(iU,D)),_.base64=(D)=>_.check(YE(_1,D)),_.base64url=(D)=>_.check(QE($1,D)),_.xid=(D)=>_.check(PE(tU,D)),_.ksuid=(D)=>_.check(zE(oU,D)),_.ipv4=(D)=>_.check(gE(pU,D)),_.ipv6=(D)=>_.check(XE(eU,D)),_.cidrv4=(D)=>_.check(GE(aU,D)),_.cidrv6=(D)=>_.check(RE(sU,D)),_.e164=(D)=>_.check(KE(D1,D)),_.datetime=(D)=>_.check(mW(D)),_.date=(D)=>_.check(lW(D)),_.time=(D)=>_.check(iW(D)),_.duration=(D)=>_.check(tW(D))});z_=K("ZodStringFormat",(_,$)=>{Y_.init(_,$),hU.init(_,$)}),cU=K("ZodEmail",(_,$)=>{PO.init(_,$),z_.init(_,$)});i0=K("ZodGUID",(_,$)=>{WO.init(_,$),z_.init(_,$)});Z$=K("ZodUUID",(_,$)=>{JO.init(_,$),z_.init(_,$)});p0=K("ZodURL",(_,$)=>{zO.init(_,$),z_.init(_,$)});nU=K("ZodEmoji",(_,$)=>{gO.init(_,$),z_.init(_,$)});dU=K("ZodNanoID",(_,$)=>{XO.init(_,$),z_.init(_,$)});mU=K("ZodCUID",(_,$)=>{GO.init(_,$),z_.init(_,$)});lU=K("ZodCUID2",(_,$)=>{RO.init(_,$),z_.init(_,$)});iU=K("ZodULID",(_,$)=>{YO.init(_,$),z_.init(_,$)});tU=K("ZodXID",(_,$)=>{QO.init(_,$),z_.init(_,$)});oU=K("ZodKSUID",(_,$)=>{KO.init(_,$),z_.init(_,$)});pU=K("ZodIPv4",(_,$)=>{MO.init(_,$),z_.init(_,$)});cE=K("ZodMAC",(_,$)=>{HO.init(_,$),z_.init(_,$)});eU=K("ZodIPv6",(_,$)=>{ZO.init(_,$),z_.init(_,$)});aU=K("ZodCIDRv4",(_,$)=>{bO.init(_,$),z_.init(_,$)});sU=K("ZodCIDRv6",(_,$)=>{qO.init(_,$),z_.init(_,$)});_1=K("ZodBase64",(_,$)=>{CO.init(_,$),z_.init(_,$)});$1=K("ZodBase64URL",(_,$)=>{vO.init(_,$),z_.init(_,$)});D1=K("ZodE164",(_,$)=>{wO.init(_,$),z_.init(_,$)});U1=K("ZodJWT",(_,$)=>{rO.init(_,$),z_.init(_,$)});x4=K("ZodCustomStringFormat",(_,$)=>{fO.init(_,$),z_.init(_,$)});u4=K("ZodNumber",(_,$)=>{eI.init(_,$),a.init(_,$),_._zod.processJSONSchema=(I,U,E)=>AW(_,I,U,E),yU(_,"ZodNumber",{gt(I,U){return this.check(B$(I,U))},gte(I,U){return this.check(c_(I,U))},min(I,U){return this.check(c_(I,U))},lt(I,U){return this.check(V$(I,U))},lte(I,U){return this.check(I$(I,U))},max(I,U){return this.check(I$(I,U))},int(I){return this.check(xU(I))},safe(I){return this.check(xU(I))},positive(I){return this.check(B$(0,I))},nonnegative(I){return this.check(c_(0,I))},negative(I){return this.check(V$(0,I))},nonpositive(I){return this.check(I$(0,I))},multipleOf(I,U){return this.check(W6(I,U))},step(I,U){return this.check(W6(I,U))},finite(){return this}});let D=_._zod.bag;_.minValue=Math.max(D.minimum??Number.NEGATIVE_INFINITY,D.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,_.maxValue=Math.min(D.maximum??Number.POSITIVE_INFINITY,D.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,_.isInt=(D.format??"").includes("int")||Number.isSafeInteger(D.multipleOf??0.5),_.isFinite=!0,_.format=D.format??null});d6=K("ZodNumberFormat",(_,$)=>{xO.init(_,$),u4.init(_,$)});y4=K("ZodBoolean",(_,$)=>{WU.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>OW(_,D,I,U)});h4=K("ZodBigInt",(_,$)=>{aI.init(_,$),a.init(_,$),_._zod.processJSONSchema=(I,U,E)=>SW(_,I,U,E),_.gte=(I,U)=>_.check(c_(I,U)),_.min=(I,U)=>_.check(c_(I,U)),_.gt=(I,U)=>_.check(B$(I,U)),_.gte=(I,U)=>_.check(c_(I,U)),_.min=(I,U)=>_.check(c_(I,U)),_.lt=(I,U)=>_.check(V$(I,U)),_.lte=(I,U)=>_.check(I$(I,U)),_.max=(I,U)=>_.check(I$(I,U)),_.positive=(I)=>_.check(B$(BigInt(0),I)),_.negative=(I)=>_.check(V$(BigInt(0),I)),_.nonpositive=(I)=>_.check(I$(BigInt(0),I)),_.nonnegative=(I)=>_.check(c_(BigInt(0),I)),_.multipleOf=(I,U)=>_.check(W6(I,U));let D=_._zod.bag;_.minValue=D.minimum??null,_.maxValue=D.maximum??null,_.format=D.format??null});I1=K("ZodBigIntFormat",(_,$)=>{uO.init(_,$),h4.init(_,$)});mE=K("ZodSymbol",(_,$)=>{yO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>LW(_,D,I,U)});lE=K("ZodUndefined",(_,$)=>{hO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>JW(_,D,I,U)});iE=K("ZodNull",(_,$)=>{cO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>WW(_,D,I,U)});oE=K("ZodAny",(_,$)=>{nO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>gW(_,D,I,U)});pE=K("ZodUnknown",(_,$)=>{dO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>XW(_,D,I,U)});eE=K("ZodNever",(_,$)=>{mO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>zW(_,D,I,U)});aE=K("ZodVoid",(_,$)=>{lO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>PW(_,D,I,U)});e0=K("ZodDate",(_,$)=>{iO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(I,U,E)=>GW(_,I,U,E),_.min=(I,U)=>_.check(c_(I,U)),_.max=(I,U)=>_.check(I$(I,U));let D=_._zod.bag;_.minDate=D.minimum?new Date(D.minimum):null,_.maxDate=D.maximum?new Date(D.maximum):null});sE=K("ZodArray",(_,$)=>{tO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>bW(_,D,I,U),_.element=$.element,yU(_,"ZodArray",{min(D,I){return this.check(l$(D,I))},nonempty(D){return this.check(l$(1,D))},max(D,I){return this.check(x6(D,I))},length(D,I){return this.check(u6(D,I))},unwrap(){return this.element}})});s0=K("ZodObject",(_,$)=>{oO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>qW(_,D,I,U),q.defineLazy(_,"shape",()=>{return $.shape}),yU(_,"ZodObject",{keyof(){return N1(Object.keys(this._zod.def.shape))},catchall(D){return this.clone({...this._zod.def,catchall:D})},passthrough(){return this.clone({...this._zod.def,catchall:n6()})},loose(){return this.clone({...this._zod.def,catchall:n6()})},strict(){return this.clone({...this._zod.def,catchall:E1()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(D){return q.extend(this,D)},safeExtend(D){return q.safeExtend(this,D)},merge(D){return q.merge(this,D)},pick(D){return q.pick(this,D)},omit(D){return q.omit(this,D)},partial(...D){return q.partial(O1,this,D[0])},required(...D){return q.required(S1,this,D[0])}})});_D=K("ZodUnion",(_,$)=>{JU.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>BE(_,D,I,U),_.options=$.options});_j=K("ZodXor",(_,$)=>{_D.init(_,$),pO.init(_,$),_._zod.processJSONSchema=(D,I,U)=>BE(_,D,I,U),_.options=$.options});$j=K("ZodDiscriminatedUnion",(_,$)=>{_D.init(_,$),eO.init(_,$)});Dj=K("ZodIntersection",(_,$)=>{aO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>kW(_,D,I,U)});Ij=K("ZodTuple",(_,$)=>{sI.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>CW(_,D,I,U),_.rest=(D)=>_.clone({..._._zod.def,rest:D})});w4=K("ZodRecord",(_,$)=>{sO.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>vW(_,D,I,U),_.keyType=$.keyType,_.valueType=$.valueType});Nj=K("ZodMap",(_,$)=>{_S.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>ZW(_,D,I,U),_.keyType=$.keyType,_.valueType=$.valueType,_.min=(...D)=>_.check(M$(...D)),_.nonempty=(D)=>_.check(M$(1,D)),_.max=(...D)=>_.check(J6(...D)),_.size=(...D)=>_.check(f6(...D))});Aj=K("ZodSet",(_,$)=>{$S.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>HW(_,D,I,U),_.min=(...D)=>_.check(M$(...D)),_.nonempty=(D)=>_.check(M$(1,D)),_.max=(...D)=>_.check(J6(...D)),_.size=(...D)=>_.check(f6(...D))});r4=K("ZodEnum",(_,$)=>{DS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(I,U,E)=>RW(_,I,U,E),_.enum=$.entries,_.options=Object.values($.entries);let D=new Set(Object.keys($.entries));_.extract=(I,U)=>{let E={};for(let j of I)if(D.has(j))E[j]=$.entries[j];else throw Error(`Key ${j} not found in enum`);return new r4({...$,checks:[],...q.normalizeParams(U),entries:E})},_.exclude=(I,U)=>{let E={...$.entries};for(let j of I)if(D.has(j))delete E[j];else throw Error(`Key ${j} not found in enum`);return new r4({...$,checks:[],...q.normalizeParams(U),entries:E})}});Oj=K("ZodLiteral",(_,$)=>{US.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>YW(_,D,I,U),_.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]}})});Sj=K("ZodFile",(_,$)=>{IS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>TW(_,D,I,U),_.min=(D,I)=>_.check(M$(D,I)),_.max=(D,I)=>_.check(J6(D,I)),_.mime=(D,I)=>_.check(Z4(Array.isArray(D)?D:[D],I))});Lj=K("ZodTransform",(_,$)=>{ES.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>MW(_,D,I,U),_._zod.parse=(D,I)=>{if(I.direction==="backward")throw new X4(_.constructor.name);D.addIssue=(E)=>{if(typeof E==="string")D.issues.push(q.issue(E,D.value,$));else{let j=E;if(j.fatal)j.continue=!1;j.code??(j.code="custom"),j.input??(j.input=D.value),j.inst??(j.inst=_),D.issues.push(q.issue(j))}};let U=$.transform(D.value,D);if(U instanceof Promise)return U.then((E)=>{return D.value=E,D.fallback=!0,D});return D.value=U,D.fallback=!0,D}});O1=K("ZodOptional",(_,$)=>{_E.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>ME(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Wj=K("ZodExactOptional",(_,$)=>{jS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>ME(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Pj=K("ZodNullable",(_,$)=>{NS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>wW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});zj=K("ZodDefault",(_,$)=>{AS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>fW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType,_.removeDefault=_.unwrap});Xj=K("ZodPrefault",(_,$)=>{OS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>xW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});S1=K("ZodNonOptional",(_,$)=>{SS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>rW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Yj=K("ZodSuccess",(_,$)=>{LS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>FW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Qj=K("ZodCatch",(_,$)=>{WS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>uW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType,_.removeCatch=_.unwrap});Tj=K("ZodNaN",(_,$)=>{JS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>QW(_,D,I,U)});$D=K("ZodPipe",(_,$)=>{$E.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>yW(_,D,I,U),_.in=$.in,_.out=$.out});DD=K("ZodCodec",(_,$)=>{$D.init(_,$),PU.init(_,$)});Fj=K("ZodPreprocess",(_,$)=>{$D.init(_,$),PS.init(_,$)}),Vj=K("ZodReadonly",(_,$)=>{zS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>hW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});Mj=K("ZodTemplateLiteral",(_,$)=>{gS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>KW(_,D,I,U)});Zj=K("ZodLazy",(_,$)=>{RS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>nW(_,D,I,U),_.unwrap=()=>_._zod.def.getter()});bj=K("ZodPromise",(_,$)=>{GS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>cW(_,D,I,U),_.unwrap=()=>_._zod.def.innerType});qj=K("ZodFunction",(_,$)=>{XS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>BW(_,D,I,U)});UD=K("ZodCustom",(_,$)=>{YS.init(_,$),a.init(_,$),_._zod.processJSONSchema=(D,I,U)=>VW(_,D,I,U)});jP=UW,NP=IW});function ZG(_){b_({customError:_})}function HG(){return b_().customError}var MG,vj;var bG=r(()=>{S$();MG={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(_){})(vj||(vj={}))});function EZ(_,$){let D=_.$schema;if(D==="https://json-schema.org/draft/2020-12/schema")return"draft-2020-12";if(D==="http://json-schema.org/draft-07/schema#")return"draft-7";if(D==="http://json-schema.org/draft-04/schema#")return"draft-4";return $??"draft-2020-12"}function jZ(_,$){if(!_.startsWith("#"))throw Error("External $ref is not supported, only local refs (#/...) are allowed");let D=_.slice(1).split("/").filter(Boolean);if(D.length===0)return $.rootSchema;let I=$.version==="draft-2020-12"?"$defs":"definitions";if(D[0]===I){let U=D[1];if(!U||!$.defs[U])throw Error(`Reference not found: ${_}`);return $.defs[U]}throw Error(`Reference not found: ${_}`)}function qG(_,$){if(_.not!==void 0){if(typeof _.not==="object"&&Object.keys(_.not).length===0)return x.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 U=_.$ref;if($.refs.has(U))return $.refs.get(U);if($.processing.has(U))return x.lazy(()=>{if(!$.refs.has(U))throw Error(`Circular reference not resolved: ${U}`);return $.refs.get(U)});$.processing.add(U);let E=jZ(U,$),j=n_(E,$);return $.refs.set(U,j),$.processing.delete(U),j}if(_.enum!==void 0){let U=_.enum;if($.version==="openapi-3.0"&&_.nullable===!0&&U.length===1&&U[0]===null)return x.null();if(U.length===0)return x.never();if(U.length===1)return x.literal(U[0]);if(U.every((j)=>typeof j==="string"))return x.enum(U);let E=U.map((j)=>x.literal(j));if(E.length<2)return E[0];return x.union([E[0],E[1],...E.slice(2)])}if(_.const!==void 0)return x.literal(_.const);let D=_.type;if(Array.isArray(D)){let U=D.map((E)=>{let j={..._,type:E};return qG(j,$)});if(U.length===0)return x.never();if(U.length===1)return U[0];return x.union(U)}if(!D)return x.any();let I;switch(D){case"string":{let U=x.string();if(_.format){let E=_.format;if(E==="email")U=U.check(x.email());else if(E==="uri"||E==="uri-reference")U=U.check(x.url());else if(E==="uuid"||E==="guid")U=U.check(x.uuid());else if(E==="date-time")U=U.check(x.iso.datetime());else if(E==="date")U=U.check(x.iso.date());else if(E==="time")U=U.check(x.iso.time());else if(E==="duration")U=U.check(x.iso.duration());else if(E==="ipv4")U=U.check(x.ipv4());else if(E==="ipv6")U=U.check(x.ipv6());else if(E==="mac")U=U.check(x.mac());else if(E==="cidr")U=U.check(x.cidrv4());else if(E==="cidr-v6")U=U.check(x.cidrv6());else if(E==="base64")U=U.check(x.base64());else if(E==="base64url")U=U.check(x.base64url());else if(E==="e164")U=U.check(x.e164());else if(E==="jwt")U=U.check(x.jwt());else if(E==="emoji")U=U.check(x.emoji());else if(E==="nanoid")U=U.check(x.nanoid());else if(E==="cuid")U=U.check(x.cuid());else if(E==="cuid2")U=U.check(x.cuid2());else if(E==="ulid")U=U.check(x.ulid());else if(E==="xid")U=U.check(x.xid());else if(E==="ksuid")U=U.check(x.ksuid())}if(typeof _.minLength==="number")U=U.min(_.minLength);if(typeof _.maxLength==="number")U=U.max(_.maxLength);if(_.pattern)U=U.regex(new RegExp(_.pattern));I=U;break}case"number":case"integer":{let U=D==="integer"?x.number().int():x.number();if(typeof _.minimum==="number")U=U.min(_.minimum);if(typeof _.maximum==="number")U=U.max(_.maximum);if(typeof _.exclusiveMinimum==="number")U=U.gt(_.exclusiveMinimum);else if(_.exclusiveMinimum===!0&&typeof _.minimum==="number")U=U.gt(_.minimum);if(typeof _.exclusiveMaximum==="number")U=U.lt(_.exclusiveMaximum);else if(_.exclusiveMaximum===!0&&typeof _.maximum==="number")U=U.lt(_.maximum);if(typeof _.multipleOf==="number")U=U.multipleOf(_.multipleOf);I=U;break}case"boolean":{I=x.boolean();break}case"null":{I=x.null();break}case"object":{let U={},E=_.properties||{},j=new Set(_.required||[]);for(let[O,S]of Object.entries(E)){let L=n_(S,$);U[O]=j.has(O)?L:L.optional()}if(_.propertyNames){let O=n_(_.propertyNames,$),S=_.additionalProperties&&typeof _.additionalProperties==="object"?n_(_.additionalProperties,$):x.any();if(Object.keys(U).length===0){I=x.record(O,S);break}let L=x.object(U).passthrough(),W=x.looseRecord(O,S);I=x.intersection(L,W);break}if(_.patternProperties){let O=_.patternProperties,S=Object.keys(O),L=[];for(let g of S){let z=n_(O[g],$),G=x.string().regex(new RegExp(g));L.push(x.looseRecord(G,z))}let W=[];if(Object.keys(U).length>0)W.push(x.object(U).passthrough());if(W.push(...L),W.length===0)I=x.object({}).passthrough();else if(W.length===1)I=W[0];else{let g=x.intersection(W[0],W[1]);for(let z=2;zn_(O,$)),N=E&&typeof E==="object"&&!Array.isArray(E)?n_(E,$):void 0;if(N)I=x.tuple(j).rest(N);else I=x.tuple(j);if(typeof _.minItems==="number")I=I.check(x.minLength(_.minItems));if(typeof _.maxItems==="number")I=I.check(x.maxLength(_.maxItems))}else if(Array.isArray(E)){let j=E.map((O)=>n_(O,$)),N=_.additionalItems&&typeof _.additionalItems==="object"?n_(_.additionalItems,$):void 0;if(N)I=x.tuple(j).rest(N);else I=x.tuple(j);if(typeof _.minItems==="number")I=I.check(x.minLength(_.minItems));if(typeof _.maxItems==="number")I=I.check(x.maxLength(_.maxItems))}else if(E!==void 0){let j=n_(E,$),N=x.array(j);if(typeof _.minItems==="number")N=N.min(_.minItems);if(typeof _.maxItems==="number")N=N.max(_.maxItems);I=N}else I=x.array(x.any());break}default:throw Error(`Unsupported type: ${D}`)}return I}function n_(_,$){if(typeof _==="boolean")return _?x.any():x.never();let D=qG(_,$),I=_.type||_.enum!==void 0||_.const!==void 0;if(_.anyOf&&Array.isArray(_.anyOf)){let N=_.anyOf.map((S)=>n_(S,$)),O=x.union(N);D=I?x.intersection(D,O):O}if(_.oneOf&&Array.isArray(_.oneOf)){let N=_.oneOf.map((S)=>n_(S,$)),O=x.xor(N);D=I?x.intersection(D,O):O}if(_.allOf&&Array.isArray(_.allOf))if(_.allOf.length===0)D=I?D:x.any();else{let N=I?D:n_(_.allOf[0],$),O=I?0:1;for(let S=O;S<_.allOf.length;S++)N=x.intersection(N,n_(_.allOf[S],$));D=N}if(_.nullable===!0&&$.version==="openapi-3.0")D=x.nullable(D);if(_.readOnly===!0)D=x.readonly(D);if(_.default!==void 0)D=D.default(_.default);let U={},E=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let N of E)if(N in _)U[N]=_[N];let j=["contentEncoding","contentMediaType","contentSchema"];for(let N of j)if(N in _)U[N]=_[N];for(let N of Object.keys(_))if(!IZ.has(N))U[N]=_[N];if(Object.keys(U).length>0)$.registry.add(D,U);if(_.description)D=D.describe(_.description);return D}function WP(_,$){if(typeof _==="boolean")return _?x.any():x.never();let D;try{D=JSON.parse(JSON.stringify(_))}catch{throw Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let I=EZ(D,$?.defaultTarget),U=D.$defs||D.definitions||{},E={version:I,defs:U,refs:new Map,processing:new Set,rootSchema:D,registry:$?.registry??x_};return n_(D,E)}var x,IZ;var kG=r(()=>{YU();HE();wU();fU();x={...rU,...ZE,iso:v4},IZ=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 wj={};x$(wj,{string:()=>NZ,number:()=>AZ,date:()=>LZ,boolean:()=>OZ,bigint:()=>SZ});function NZ(_){return TL(f4,_)}function AZ(_){return bL(u4,_)}function OZ(_){return fL(y4,_)}function SZ(_){return uL(h4,_)}function LZ(_){return pL(e0,_)}var CG=r(()=>{S$();fU()});var rj={};x$(rj,{xor:()=>hJ,xid:()=>SJ,void:()=>wJ,uuidv7:()=>DJ,uuidv6:()=>$J,uuidv4:()=>_J,uuid:()=>sW,util:()=>q,url:()=>UJ,uppercase:()=>F4,unknown:()=>n6,union:()=>j1,undefined:()=>CJ,ulid:()=>OJ,uint64:()=>qJ,uint32:()=>ZJ,tuple:()=>Ej,trim:()=>b4,treeifyError:()=>HI,transform:()=>A1,toUpperCase:()=>k4,toLowerCase:()=>q4,toJSONSchema:()=>HU,templateLiteral:()=>$P,symbol:()=>kJ,superRefine:()=>Cj,success:()=>eJ,stringbool:()=>OP,stringFormat:()=>QJ,string:()=>l0,strictObject:()=>uJ,startsWith:()=>B4,slugify:()=>C4,size:()=>f6,setErrorMap:()=>ZG,set:()=>lJ,safeParseAsync:()=>CE,safeParse:()=>kE,safeEncodeAsync:()=>yE,safeEncode:()=>xE,safeDecodeAsync:()=>hE,safeDecode:()=>uE,registry:()=>RU,regexes:()=>U$,regex:()=>K4,refine:()=>kj,record:()=>jj,readonly:()=>Bj,property:()=>MU,promise:()=>DP,prettifyError:()=>bI,preprocess:()=>LP,prefault:()=>Gj,positive:()=>TU,pipe:()=>uU,partialRecord:()=>nJ,parseAsync:()=>qE,parse:()=>bE,overwrite:()=>X$,optional:()=>t0,object:()=>xJ,number:()=>nE,nullish:()=>pJ,nullable:()=>o0,null:()=>tE,normalize:()=>H4,nonpositive:()=>VU,nonoptional:()=>Rj,nonnegative:()=>BU,never:()=>E1,negative:()=>FU,nativeEnum:()=>iJ,nanoid:()=>jJ,nan:()=>aJ,multipleOf:()=>W6,minSize:()=>M$,minLength:()=>l$,mime:()=>Z4,meta:()=>NP,maxSize:()=>J6,maxLength:()=>x6,map:()=>mJ,mac:()=>JJ,lte:()=>I$,lt:()=>V$,lowercase:()=>T4,looseRecord:()=>dJ,looseObject:()=>yJ,locales:()=>n0,literal:()=>tJ,length:()=>u6,lazy:()=>Hj,ksuid:()=>LJ,keyof:()=>fJ,jwt:()=>YJ,json:()=>SP,iso:()=>v4,ipv6:()=>PJ,ipv4:()=>WJ,invertCodec:()=>_P,intersection:()=>Uj,int64:()=>bJ,int32:()=>MJ,int:()=>xU,instanceof:()=>AP,includes:()=>V4,httpUrl:()=>IJ,hostname:()=>KJ,hex:()=>TJ,hash:()=>FJ,guid:()=>aW,gte:()=>c_,gt:()=>B$,globalRegistry:()=>x_,getErrorMap:()=>HG,function:()=>UP,fromJSONSchema:()=>WP,formatError:()=>r0,float64:()=>BJ,float32:()=>VJ,flattenError:()=>w0,file:()=>oJ,exactOptional:()=>Jj,enum:()=>N1,endsWith:()=>M4,encodeAsync:()=>rE,encode:()=>vE,emoji:()=>EJ,email:()=>eW,e164:()=>RJ,discriminatedUnion:()=>cJ,describe:()=>jP,decodeAsync:()=>fE,decode:()=>wE,date:()=>rJ,custom:()=>EP,cuid2:()=>AJ,cuid:()=>NJ,core:()=>i$,config:()=>b_,coerce:()=>wj,codec:()=>sJ,clone:()=>h_,cidrv6:()=>gJ,cidrv4:()=>zJ,check:()=>IP,catch:()=>Kj,boolean:()=>dE,bigint:()=>HJ,base64url:()=>GJ,base64:()=>XJ,array:()=>a0,any:()=>vJ,_function:()=>UP,_default:()=>gj,_ZodString:()=>hU,ZodXor:()=>_j,ZodXID:()=>tU,ZodVoid:()=>aE,ZodUnknown:()=>pE,ZodUnion:()=>_D,ZodUndefined:()=>lE,ZodUUID:()=>Z$,ZodURL:()=>p0,ZodULID:()=>iU,ZodType:()=>a,ZodTuple:()=>Ij,ZodTransform:()=>Lj,ZodTemplateLiteral:()=>Mj,ZodSymbol:()=>mE,ZodSuccess:()=>Yj,ZodStringFormat:()=>z_,ZodString:()=>f4,ZodSet:()=>Aj,ZodRecord:()=>w4,ZodRealError:()=>p_,ZodReadonly:()=>Vj,ZodPromise:()=>bj,ZodPreprocess:()=>Fj,ZodPrefault:()=>Xj,ZodPipe:()=>$D,ZodOptional:()=>O1,ZodObject:()=>s0,ZodNumberFormat:()=>d6,ZodNumber:()=>u4,ZodNullable:()=>Pj,ZodNull:()=>iE,ZodNonOptional:()=>S1,ZodNever:()=>eE,ZodNanoID:()=>dU,ZodNaN:()=>Tj,ZodMap:()=>Nj,ZodMAC:()=>cE,ZodLiteral:()=>Oj,ZodLazy:()=>Zj,ZodKSUID:()=>oU,ZodJWT:()=>U1,ZodIssueCode:()=>MG,ZodIntersection:()=>Dj,ZodISOTime:()=>CU,ZodISODuration:()=>vU,ZodISODateTime:()=>qU,ZodISODate:()=>kU,ZodIPv6:()=>eU,ZodIPv4:()=>pU,ZodGUID:()=>i0,ZodFunction:()=>qj,ZodFirstPartyTypeKind:()=>vj,ZodFile:()=>Sj,ZodExactOptional:()=>Wj,ZodError:()=>VG,ZodEnum:()=>r4,ZodEmoji:()=>nU,ZodEmail:()=>cU,ZodE164:()=>D1,ZodDiscriminatedUnion:()=>$j,ZodDefault:()=>zj,ZodDate:()=>e0,ZodCustomStringFormat:()=>x4,ZodCustom:()=>UD,ZodCodec:()=>DD,ZodCatch:()=>Qj,ZodCUID2:()=>lU,ZodCUID:()=>mU,ZodCIDRv6:()=>sU,ZodCIDRv4:()=>aU,ZodBoolean:()=>y4,ZodBigIntFormat:()=>I1,ZodBigInt:()=>h4,ZodBase64URL:()=>$1,ZodBase64:()=>_1,ZodArray:()=>sE,ZodAny:()=>oE,TimePrecision:()=>FE,NEVER:()=>VI,$output:()=>DE,$input:()=>UE,$brand:()=>BI});var JP=r(()=>{S$();S$();qS();S$();bU();kG();YL();wU();wU();CG();fU();HE();oW();pW();bG();b_(zU())});var vG={};x$(vG,{z:()=>rj,xor:()=>hJ,xid:()=>SJ,void:()=>wJ,uuidv7:()=>DJ,uuidv6:()=>$J,uuidv4:()=>_J,uuid:()=>sW,util:()=>q,url:()=>UJ,uppercase:()=>F4,unknown:()=>n6,union:()=>j1,undefined:()=>CJ,ulid:()=>OJ,uint64:()=>qJ,uint32:()=>ZJ,tuple:()=>Ej,trim:()=>b4,treeifyError:()=>HI,transform:()=>A1,toUpperCase:()=>k4,toLowerCase:()=>q4,toJSONSchema:()=>HU,templateLiteral:()=>$P,symbol:()=>kJ,superRefine:()=>Cj,success:()=>eJ,stringbool:()=>OP,stringFormat:()=>QJ,string:()=>l0,strictObject:()=>uJ,startsWith:()=>B4,slugify:()=>C4,size:()=>f6,setErrorMap:()=>ZG,set:()=>lJ,safeParseAsync:()=>CE,safeParse:()=>kE,safeEncodeAsync:()=>yE,safeEncode:()=>xE,safeDecodeAsync:()=>hE,safeDecode:()=>uE,registry:()=>RU,regexes:()=>U$,regex:()=>K4,refine:()=>kj,record:()=>jj,readonly:()=>Bj,property:()=>MU,promise:()=>DP,prettifyError:()=>bI,preprocess:()=>LP,prefault:()=>Gj,positive:()=>TU,pipe:()=>uU,partialRecord:()=>nJ,parseAsync:()=>qE,parse:()=>bE,overwrite:()=>X$,optional:()=>t0,object:()=>xJ,number:()=>nE,nullish:()=>pJ,nullable:()=>o0,null:()=>tE,normalize:()=>H4,nonpositive:()=>VU,nonoptional:()=>Rj,nonnegative:()=>BU,never:()=>E1,negative:()=>FU,nativeEnum:()=>iJ,nanoid:()=>jJ,nan:()=>aJ,multipleOf:()=>W6,minSize:()=>M$,minLength:()=>l$,mime:()=>Z4,meta:()=>NP,maxSize:()=>J6,maxLength:()=>x6,map:()=>mJ,mac:()=>JJ,lte:()=>I$,lt:()=>V$,lowercase:()=>T4,looseRecord:()=>dJ,looseObject:()=>yJ,locales:()=>n0,literal:()=>tJ,length:()=>u6,lazy:()=>Hj,ksuid:()=>LJ,keyof:()=>fJ,jwt:()=>YJ,json:()=>SP,iso:()=>v4,ipv6:()=>PJ,ipv4:()=>WJ,invertCodec:()=>_P,intersection:()=>Uj,int64:()=>bJ,int32:()=>MJ,int:()=>xU,instanceof:()=>AP,includes:()=>V4,httpUrl:()=>IJ,hostname:()=>KJ,hex:()=>TJ,hash:()=>FJ,guid:()=>aW,gte:()=>c_,gt:()=>B$,globalRegistry:()=>x_,getErrorMap:()=>HG,function:()=>UP,fromJSONSchema:()=>WP,formatError:()=>r0,float64:()=>BJ,float32:()=>VJ,flattenError:()=>w0,file:()=>oJ,exactOptional:()=>Jj,enum:()=>N1,endsWith:()=>M4,encodeAsync:()=>rE,encode:()=>vE,emoji:()=>EJ,email:()=>eW,e164:()=>RJ,discriminatedUnion:()=>cJ,describe:()=>jP,default:()=>WZ,decodeAsync:()=>fE,decode:()=>wE,date:()=>rJ,custom:()=>EP,cuid2:()=>AJ,cuid:()=>NJ,core:()=>i$,config:()=>b_,coerce:()=>wj,codec:()=>sJ,clone:()=>h_,cidrv6:()=>gJ,cidrv4:()=>zJ,check:()=>IP,catch:()=>Kj,boolean:()=>dE,bigint:()=>HJ,base64url:()=>GJ,base64:()=>XJ,array:()=>a0,any:()=>vJ,_function:()=>UP,_default:()=>gj,_ZodString:()=>hU,ZodXor:()=>_j,ZodXID:()=>tU,ZodVoid:()=>aE,ZodUnknown:()=>pE,ZodUnion:()=>_D,ZodUndefined:()=>lE,ZodUUID:()=>Z$,ZodURL:()=>p0,ZodULID:()=>iU,ZodType:()=>a,ZodTuple:()=>Ij,ZodTransform:()=>Lj,ZodTemplateLiteral:()=>Mj,ZodSymbol:()=>mE,ZodSuccess:()=>Yj,ZodStringFormat:()=>z_,ZodString:()=>f4,ZodSet:()=>Aj,ZodRecord:()=>w4,ZodRealError:()=>p_,ZodReadonly:()=>Vj,ZodPromise:()=>bj,ZodPreprocess:()=>Fj,ZodPrefault:()=>Xj,ZodPipe:()=>$D,ZodOptional:()=>O1,ZodObject:()=>s0,ZodNumberFormat:()=>d6,ZodNumber:()=>u4,ZodNullable:()=>Pj,ZodNull:()=>iE,ZodNonOptional:()=>S1,ZodNever:()=>eE,ZodNanoID:()=>dU,ZodNaN:()=>Tj,ZodMap:()=>Nj,ZodMAC:()=>cE,ZodLiteral:()=>Oj,ZodLazy:()=>Zj,ZodKSUID:()=>oU,ZodJWT:()=>U1,ZodIssueCode:()=>MG,ZodIntersection:()=>Dj,ZodISOTime:()=>CU,ZodISODuration:()=>vU,ZodISODateTime:()=>qU,ZodISODate:()=>kU,ZodIPv6:()=>eU,ZodIPv4:()=>pU,ZodGUID:()=>i0,ZodFunction:()=>qj,ZodFirstPartyTypeKind:()=>vj,ZodFile:()=>Sj,ZodExactOptional:()=>Wj,ZodError:()=>VG,ZodEnum:()=>r4,ZodEmoji:()=>nU,ZodEmail:()=>cU,ZodE164:()=>D1,ZodDiscriminatedUnion:()=>$j,ZodDefault:()=>zj,ZodDate:()=>e0,ZodCustomStringFormat:()=>x4,ZodCustom:()=>UD,ZodCodec:()=>DD,ZodCatch:()=>Qj,ZodCUID2:()=>lU,ZodCUID:()=>mU,ZodCIDRv6:()=>sU,ZodCIDRv4:()=>aU,ZodBoolean:()=>y4,ZodBigIntFormat:()=>I1,ZodBigInt:()=>h4,ZodBase64URL:()=>$1,ZodBase64:()=>_1,ZodArray:()=>sE,ZodAny:()=>oE,TimePrecision:()=>FE,NEVER:()=>VI,$output:()=>DE,$input:()=>UE,$brand:()=>BI});var WZ;var wG=r(()=>{JP();JP();WZ=rj});var k1=U4((Lw)=>{class zz extends Error{constructor(_,$,D){super(D);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=$,this.exitCode=_,this.nestedError=void 0}}class b8 extends zz{constructor(_){super(1,"commander.invalidArgument",_);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}Lw.CommanderError=zz;Lw.InvalidArgumentError=b8});var BN=U4((gw)=>{var{InvalidArgumentError:Pw}=k1();class q8{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=($,D)=>{if(!this.argChoices.includes($))throw new Pw(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function zw(_){let $=_.name()+(_.variadic===!0?"...":"");return _.required?"<"+$+">":"["+$+"]"}gw.Argument=q8;gw.humanReadableArgName=zw});var gz=U4((Yw)=>{var{humanReadableArgName:Rw}=BN();class k8{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((I)=>!I._hidden),D=_._getHelpCommand();if(D&&!D._hidden)$.push(D);if(this.sortSubcommands)$.sort((I,U)=>{return I.name().localeCompare(U.name())});return $}compareOptions(_,$){let D=(I)=>{return I.short?I.short.replace(/^-/,""):I.long.replace(/^--/,"")};return D(_).localeCompare(D($))}visibleOptions(_){let $=_.options.filter((I)=>!I.hidden),D=_._getHelpOption();if(D&&!D.hidden){let I=D.short&&_._findOption(D.short),U=D.long&&_._findOption(D.long);if(!I&&!U)$.push(D);else if(D.long&&!U)$.push(_.createOption(D.long,D.description));else if(D.short&&!I)$.push(_.createOption(D.short,D.description))}if(this.sortOptions)$.sort(this.compareOptions);return $}visibleGlobalOptions(_){if(!this.showGlobalOptions)return[];let $=[];for(let D=_.parent;D;D=D.parent){let I=D.options.filter((U)=>!U.hidden);$.push(...I)}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((D)=>Rw(D)).join(" ");return _._name+(_._aliases[0]?"|"+_._aliases[0]:"")+(_.options.length?" [options]":"")+($?" "+$:"")}optionTerm(_){return _.flags}argumentTerm(_){return _.name()}longestSubcommandTermLength(_,$){return $.visibleCommands(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleSubcommandTerm($.subcommandTerm(I))))},0)}longestOptionTermLength(_,$){return $.visibleOptions(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(I))))},0)}longestGlobalOptionTermLength(_,$){return $.visibleGlobalOptions(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleOptionTerm($.optionTerm(I))))},0)}longestArgumentTermLength(_,$){return $.visibleArguments(_).reduce((D,I)=>{return Math.max(D,this.displayWidth($.styleArgumentTerm($.argumentTerm(I))))},0)}commandUsage(_){let $=_._name;if(_._aliases[0])$=$+"|"+_._aliases[0];let D="";for(let I=_.parent;I;I=I.parent)D=I.name()+" "+D;return D+$+" "+_.usage()}commandDescription(_){return _.description()}subcommandDescription(_){return _.summary()||_.description()}optionDescription(_){let $=[];if(_.argChoices)$.push(`choices: ${_.argChoices.map((D)=>JSON.stringify(D)).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((D)=>JSON.stringify(D)).join(", ")}`);if(_.defaultValue!==void 0)$.push(`default: ${_.defaultValueDescription||JSON.stringify(_.defaultValue)}`);if($.length>0){let D=`(${$.join(", ")})`;if(_.description)return`${_.description} ${D}`;return D}return _.description}formatHelp(_,$){let D=$.padWidth(_,$),I=$.helpWidth??80;function U(L,W){return $.formatItem(L,D,W,$)}let E=[`${$.styleTitle("Usage:")} ${$.styleUsage($.commandUsage(_))}`,""],j=$.commandDescription(_);if(j.length>0)E=E.concat([$.boxWrap($.styleCommandDescription(j),I),""]);let N=$.visibleArguments(_).map((L)=>{return U($.styleArgumentTerm($.argumentTerm(L)),$.styleArgumentDescription($.argumentDescription(L)))});if(N.length>0)E=E.concat([$.styleTitle("Arguments:"),...N,""]);let O=$.visibleOptions(_).map((L)=>{return U($.styleOptionTerm($.optionTerm(L)),$.styleOptionDescription($.optionDescription(L)))});if(O.length>0)E=E.concat([$.styleTitle("Options:"),...O,""]);if($.showGlobalOptions){let L=$.visibleGlobalOptions(_).map((W)=>{return U($.styleOptionTerm($.optionTerm(W)),$.styleOptionDescription($.optionDescription(W)))});if(L.length>0)E=E.concat([$.styleTitle("Global Options:"),...L,""])}let S=$.visibleCommands(_).map((L)=>{return U($.styleSubcommandTerm($.subcommandTerm(L)),$.styleSubcommandDescription($.subcommandDescription(L)))});if(S.length>0)E=E.concat([$.styleTitle("Commands:"),...S,""]);return E.join(` +`)}displayWidth(_){return C8(_).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(_,$,D,I){let E=" ".repeat(2);if(!D)return E+_;let j=_.padEnd($+_.length-I.displayWidth(_)),N=2,S=(this.helpWidth??80)-$-N-2,L;if(S{let j=E.match(I);if(j===null){U.push("");return}let N=[j.shift()],O=this.displayWidth(N[0]);j.forEach((S)=>{let L=this.displayWidth(S);if(O+L<=$){N.push(S),O+=L;return}U.push(N.join(""));let W=S.trimStart();N=[W],O=this.displayWidth(W)}),U.push(N.join(""))}),U.join(` +`)}}function C8(_){let $=/\x1b\[\d*(;\d*)*m/g;return _.replace($,"")}Yw.Help=k8;Yw.stripColor=C8});var Xz=U4((Vw)=>{var{InvalidArgumentError:Tw}=k1();class w8{constructor(_,$){this.flags=_,this.description=$||"",this.required=_.includes("<"),this.optional=_.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(_),this.mandatory=!1;let D=Fw(_);if(this.short=D.shortFlag,this.long=D.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=($,D)=>{if(!this.argChoices.includes($))throw new Tw(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue($,D);return $},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return v8(this.name().replace(/^no-/,""));return v8(this.name())}is(_){return this.short===_||this.long===_}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class r8{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(($,D)=>{if(this.positiveOptions.has(D))this.dualOptions.add(D)})}valueFromOption(_,$){let D=$.attributeName();if(!this.dualOptions.has(D))return!0;let I=this.negativeOptions.get(D).presetArg,U=I!==void 0?I:!1;return $.negate===(U===_)}}function v8(_){return _.split("-").reduce(($,D)=>{return $+D[0].toUpperCase()+D.slice(1)})}function Fw(_){let $,D,I=/^-[^-]$/,U=/^--[^-]/,E=_.split(/[ |,]+/).concat("guard");if(I.test(E[0]))$=E.shift();if(U.test(E[0]))D=E.shift();if(!$&&I.test(E[0]))$=E.shift();if(!$&&U.test(E[0]))$=D,D=E.shift();if(E[0].startsWith("-")){let j=E[0],N=`option creation failed due to '${j}' in option flags '${_}'`;if(/^-[^-][^-]/.test(j))throw Error(`${N} - 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(I.test(j))throw Error(`${N} - too many short flags`);if(U.test(j))throw Error(`${N} - too many long flags`);throw Error(`${N} -- unrecognised flag format`)}if($===void 0&&D===void 0)throw Error(`option creation failed due to no flags found in '${_}'.`);return{shortFlag:$,longFlag:D}}Vw.Option=w8;Vw.DualOptions=r8});var f8=D4((Hw)=>{function bw(_,$){if(Math.abs(_.length-$.length)>3)return Math.max(_.length,$.length);let D=[];for(let I=0;I<=_.length;I++)D[I]=[I];for(let I=0;I<=$.length;I++)D[0][I]=I;for(let I=1;I<=$.length;I++)for(let U=1;U<=_.length;U++){let E=1;if(_[U-1]===$[I-1])E=0;else E=1;if(D[U][I]=Math.min(D[U-1][I]+1,D[U][I-1]+1,D[U-1][I-1]+E),U>1&&I>1&&_[U-1]===$[I-2]&&_[U-2]===$[I-1])D[U][I]=Math.min(D[U][I],D[U-2][I-2]+1)}return D[_.length][$.length]}function Zw(_,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let D=_.startsWith("--");if(D)_=_.slice(2),$=$.map((j)=>j.slice(2));let I=[],U=3,E=0.4;if($.forEach((j)=>{if(j.length<=1)return;let N=bw(_,j),A=Math.max(_.length,j.length);if((A-N)/A>E){if(Nj.localeCompare(N)),D)I=I.map((j)=>`--${j}`);if(I.length>1)return` +- unrecognised flag format`)}if($===void 0&&D===void 0)throw Error(`option creation failed due to no flags found in '${_}'.`);return{shortFlag:$,longFlag:D}}Vw.Option=w8;Vw.DualOptions=r8});var f8=U4((bw)=>{function Zw(_,$){if(Math.abs(_.length-$.length)>3)return Math.max(_.length,$.length);let D=[];for(let I=0;I<=_.length;I++)D[I]=[I];for(let I=0;I<=$.length;I++)D[0][I]=I;for(let I=1;I<=$.length;I++)for(let U=1;U<=_.length;U++){let E=1;if(_[U-1]===$[I-1])E=0;else E=1;if(D[U][I]=Math.min(D[U-1][I]+1,D[U][I-1]+1,D[U-1][I-1]+E),U>1&&I>1&&_[U-1]===$[I-2]&&_[U-2]===$[I-1])D[U][I]=Math.min(D[U][I],D[U-2][I-2]+1)}return D[_.length][$.length]}function Hw(_,$){if(!$||$.length===0)return"";$=Array.from(new Set($));let D=_.startsWith("--");if(D)_=_.slice(2),$=$.map((j)=>j.slice(2));let I=[],U=3,E=0.4;if($.forEach((j)=>{if(j.length<=1)return;let N=Zw(_,j),O=Math.max(_.length,j.length);if((O-N)/O>E){if(Nj.localeCompare(N)),D)I=I.map((j)=>`--${j}`);if(I.length>1)return` (Did you mean one of ${I.join(", ")}?)`;if(I.length===1)return` -(Did you mean ${I[0]}?)`;return""}Hw.suggestSimilar=Zw});var h8=D4((xw)=>{var qw=S_("events").EventEmitter,XP=S_("child_process"),T6=S_("path"),MN=S_("fs"),O_=S_("process"),{Argument:Cw,humanReadableArgName:vw}=BN(),{CommanderError:GP}=k1(),{Help:ww,stripColor:rw}=PP(),{Option:x8,DualOptions:fw}=zP(),{suggestSimilar:u8}=f8();class YP extends qw{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:($)=>O_.stdout.write($),writeErr:($)=>O_.stderr.write($),outputError:($,D)=>D($),getOutHelpWidth:()=>O_.stdout.isTTY?O_.stdout.columns:void 0,getErrHelpWidth:()=>O_.stderr.isTTY?O_.stderr.columns:void 0,getOutHasColors:()=>RP()??(O_.stdout.isTTY&&O_.stdout.hasColors?.()),getErrHasColors:()=>RP()??(O_.stderr.isTTY&&O_.stderr.hasColors?.()),stripColor:($)=>rw($)},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(_,$,D){let I=$,U=D;if(typeof I==="object"&&I!==null)U=I,I=null;U=U||{};let[,E,j]=_.match(/([^ ]+) *(.*)/),N=this.createCommand(E);if(I)N.description(I),N._executableHandler=!0;if(U.isDefault)this._defaultCommandName=N._name;if(N._hidden=!!(U.noHelp||U.hidden),N._executableFile=U.executableFile||null,j)N.arguments(j);if(this._registerCommand(N),N.parent=this,N.copyInheritedSettings(this),I)return this;return N}createCommand(_){return new YP(_)}createHelp(){return Object.assign(new ww,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 +(Did you mean ${I[0]}?)`;return""}bw.suggestSimilar=Hw});var h8=U4((xw)=>{var kw=L_("events").EventEmitter,Gz=L_("child_process"),T6=L_("path"),MN=L_("fs"),S_=L_("process"),{Argument:Cw,humanReadableArgName:vw}=BN(),{CommanderError:Rz}=k1(),{Help:ww,stripColor:rw}=gz(),{Option:x8,DualOptions:fw}=Xz(),{suggestSimilar:u8}=f8();class Qz extends kw{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:($)=>S_.stdout.write($),writeErr:($)=>S_.stderr.write($),outputError:($,D)=>D($),getOutHelpWidth:()=>S_.stdout.isTTY?S_.stdout.columns:void 0,getErrHelpWidth:()=>S_.stderr.isTTY?S_.stderr.columns:void 0,getOutHasColors:()=>Yz()??(S_.stdout.isTTY&&S_.stdout.hasColors?.()),getErrHasColors:()=>Yz()??(S_.stderr.isTTY&&S_.stderr.hasColors?.()),stripColor:($)=>rw($)},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(_,$,D){let I=$,U=D;if(typeof I==="object"&&I!==null)U=I,I=null;U=U||{};let[,E,j]=_.match(/([^ ]+) *(.*)/),N=this.createCommand(E);if(I)N.description(I),N._executableHandler=!0;if(U.isDefault)this._defaultCommandName=N._name;if(N._hidden=!!(U.noHelp||U.hidden),N._executableFile=U.executableFile||null,j)N.arguments(j);if(this._registerCommand(N),N.parent=this,N.copyInheritedSettings(this),I)return this;return N}createCommand(_){return new Qz(_)}createHelp(){return Object.assign(new ww,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 Cw(_,$)}argument(_,$,D,I){let U=this.createArgument(_,$);if(typeof D==="function")U.default(I).argParser(D);else U.default(D);return this.addArgument(U),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[,D,I]=_.match(/([^ ]+) *(.*)/),U=$??"display help for command",E=this.createCommand(D);if(E.helpOption(!1),I)E.arguments(I);if(U)E.description(U);return this._addImplicitHelpCommand=!0,this._helpCommand=E,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 D=["preSubcommand","preAction","postAction"];if(!D.includes(_))throw Error(`Unexpected value for event passed to hook : '${_}'. -Expecting one of '${D.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(_,$,D){if(this._exitCallback)this._exitCallback(new GP(_,$,D));O_.exit(_)}action(_){let $=(D)=>{let I=this.registeredArguments.length,U=D.slice(0,I);if(this._storeOptionsAsProperties)U[I]=this;else U[I]=this.opts();return U.push(this),_.apply(this,U)};return this._actionHandler=$,this}createOption(_,$){return new x8(_,$)}_callParseArg(_,$,D,I){try{return _.parseArg($,D)}catch(U){if(U.code==="commander.invalidArgument"){let E=`${I} ${U.message}`;this.error(E,{exitCode:U.exitCode,code:U.code})}throw U}}_registerOption(_){let $=_.short&&this._findOption(_.short)||_.long&&this._findOption(_.long);if($){let D=_.long&&this._findOption(_.long)?_.long:_.short;throw Error(`Cannot add option '${_.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${D}' -- already used by option '${$.flags}'`)}this.options.push(_)}_registerCommand(_){let $=(I)=>{return[I.name()].concat(I.aliases())},D=$(_).find((I)=>this._findCommand(I));if(D){let I=$(this._findCommand(D)).join("|"),U=$(_).join("|");throw Error(`cannot add command '${U}' as already have command '${I}'`)}this.commands.push(_)}addOption(_){this._registerOption(_);let $=_.name(),D=_.attributeName();if(_.negate){let U=_.long.replace(/^--no-/,"--");if(!this._findOption(U))this.setOptionValueWithSource(D,_.defaultValue===void 0?!0:_.defaultValue,"default")}else if(_.defaultValue!==void 0)this.setOptionValueWithSource(D,_.defaultValue,"default");let I=(U,E,j)=>{if(U==null&&_.presetArg!==void 0)U=_.presetArg;let N=this.getOptionValue(D);if(U!==null&&_.parseArg)U=this._callParseArg(_,U,N,E);else if(U!==null&&_.variadic)U=_._concatValue(U,N);if(U==null)if(_.negate)U=!1;else if(_.isBoolean()||_.optional)U=!0;else U="";this.setOptionValueWithSource(D,U,j)};if(this.on("option:"+$,(U)=>{let E=`error: option '${_.flags}' argument '${U}' is invalid.`;I(U,E,"cli")}),_.envVar)this.on("optionEnv:"+$,(U)=>{let E=`error: option '${_.flags}' value '${U}' from env '${_.envVar}' is invalid.`;I(U,E,"env")});return this}_optionEx(_,$,D,I,U){if(typeof $==="object"&&$ instanceof x8)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let E=this.createOption($,D);if(E.makeOptionMandatory(!!_.mandatory),typeof I==="function")E.default(U).argParser(I);else if(I instanceof RegExp){let j=I;I=(N,A)=>{let O=j.exec(N);return O?O[0]:A},E.default(U).argParser(I)}else E.default(I);return this.addOption(E)}option(_,$,D,I){return this._optionEx({},_,$,D,I)}requiredOption(_,$,D,I){return this._optionEx({mandatory:!0},_,$,D,I)}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(_,$,D){if(this._storeOptionsAsProperties)this[_]=$;else this._optionValues[_]=$;return this._optionValueSources[_]=D,this}getOptionValueSource(_){return this._optionValueSources[_]}getOptionValueSourceWithGlobals(_){let $;return this._getCommandAndAncestors().forEach((D)=>{if(D.getOptionValueSource(_)!==void 0)$=D.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(O_.versions?.electron)$.from="electron";let I=O_.execArgv??[];if(I.includes("-e")||I.includes("--eval")||I.includes("-p")||I.includes("--print"))$.from="eval"}if(_===void 0)_=O_.argv;this.rawArgs=_.slice();let D;switch($.from){case void 0:case"node":this._scriptPath=_[1],D=_.slice(2);break;case"electron":if(O_.defaultApp)this._scriptPath=_[1],D=_.slice(2);else D=_.slice(1);break;case"user":D=_.slice(0);break;case"eval":D=_.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",D}parse(_,$){this._prepareForParse();let D=this._prepareUserArgs(_,$);return this._parseCommand([],D),this}async parseAsync(_,$){this._prepareForParse();let D=this._prepareUserArgs(_,$);return await this._parseCommand([],D),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. +Expecting one of '${D.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(_,$,D){if(this._exitCallback)this._exitCallback(new Rz(_,$,D));S_.exit(_)}action(_){let $=(D)=>{let I=this.registeredArguments.length,U=D.slice(0,I);if(this._storeOptionsAsProperties)U[I]=this;else U[I]=this.opts();return U.push(this),_.apply(this,U)};return this._actionHandler=$,this}createOption(_,$){return new x8(_,$)}_callParseArg(_,$,D,I){try{return _.parseArg($,D)}catch(U){if(U.code==="commander.invalidArgument"){let E=`${I} ${U.message}`;this.error(E,{exitCode:U.exitCode,code:U.code})}throw U}}_registerOption(_){let $=_.short&&this._findOption(_.short)||_.long&&this._findOption(_.long);if($){let D=_.long&&this._findOption(_.long)?_.long:_.short;throw Error(`Cannot add option '${_.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${D}' +- already used by option '${$.flags}'`)}this.options.push(_)}_registerCommand(_){let $=(I)=>{return[I.name()].concat(I.aliases())},D=$(_).find((I)=>this._findCommand(I));if(D){let I=$(this._findCommand(D)).join("|"),U=$(_).join("|");throw Error(`cannot add command '${U}' as already have command '${I}'`)}this.commands.push(_)}addOption(_){this._registerOption(_);let $=_.name(),D=_.attributeName();if(_.negate){let U=_.long.replace(/^--no-/,"--");if(!this._findOption(U))this.setOptionValueWithSource(D,_.defaultValue===void 0?!0:_.defaultValue,"default")}else if(_.defaultValue!==void 0)this.setOptionValueWithSource(D,_.defaultValue,"default");let I=(U,E,j)=>{if(U==null&&_.presetArg!==void 0)U=_.presetArg;let N=this.getOptionValue(D);if(U!==null&&_.parseArg)U=this._callParseArg(_,U,N,E);else if(U!==null&&_.variadic)U=_._concatValue(U,N);if(U==null)if(_.negate)U=!1;else if(_.isBoolean()||_.optional)U=!0;else U="";this.setOptionValueWithSource(D,U,j)};if(this.on("option:"+$,(U)=>{let E=`error: option '${_.flags}' argument '${U}' is invalid.`;I(U,E,"cli")}),_.envVar)this.on("optionEnv:"+$,(U)=>{let E=`error: option '${_.flags}' value '${U}' from env '${_.envVar}' is invalid.`;I(U,E,"env")});return this}_optionEx(_,$,D,I,U){if(typeof $==="object"&&$ instanceof x8)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let E=this.createOption($,D);if(E.makeOptionMandatory(!!_.mandatory),typeof I==="function")E.default(U).argParser(I);else if(I instanceof RegExp){let j=I;I=(N,O)=>{let S=j.exec(N);return S?S[0]:O},E.default(U).argParser(I)}else E.default(I);return this.addOption(E)}option(_,$,D,I){return this._optionEx({},_,$,D,I)}requiredOption(_,$,D,I){return this._optionEx({mandatory:!0},_,$,D,I)}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(_,$,D){if(this._storeOptionsAsProperties)this[_]=$;else this._optionValues[_]=$;return this._optionValueSources[_]=D,this}getOptionValueSource(_){return this._optionValueSources[_]}getOptionValueSourceWithGlobals(_){let $;return this._getCommandAndAncestors().forEach((D)=>{if(D.getOptionValueSource(_)!==void 0)$=D.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(S_.versions?.electron)$.from="electron";let I=S_.execArgv??[];if(I.includes("-e")||I.includes("--eval")||I.includes("-p")||I.includes("--print"))$.from="eval"}if(_===void 0)_=S_.argv;this.rawArgs=_.slice();let D;switch($.from){case void 0:case"node":this._scriptPath=_[1],D=_.slice(2);break;case"electron":if(S_.defaultApp)this._scriptPath=_[1],D=_.slice(2);else D=_.slice(1);break;case"user":D=_.slice(0);break;case"eval":D=_.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",D}parse(_,$){this._prepareForParse();let D=this._prepareUserArgs(_,$);return this._parseCommand([],D),this}async parseAsync(_,$){this._prepareForParse();let D=this._prepareUserArgs(_,$);return await this._parseCommand([],D),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(_,$,D){if(MN.existsSync(_))return;let I=$?`searched for local subcommand relative to directory '${$}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",U=`'${_}' does not exist - if '${D}' 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 - - ${I}`;throw Error(U)}_executeSubCommand(_,$){$=$.slice();let D=!1,I=[".js",".ts",".tsx",".mjs",".cjs"];function U(O,S){let L=T6.resolve(O,S);if(MN.existsSync(L))return L;if(I.includes(T6.extname(S)))return;let P=I.find((z)=>MN.existsSync(`${L}${z}`));if(P)return`${L}${P}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let E=_._executableFile||`${this._name}-${_._name}`,j=this._executableDir||"";if(this._scriptPath){let O;try{O=MN.realpathSync(this._scriptPath)}catch{O=this._scriptPath}j=T6.resolve(T6.dirname(O),j)}if(j){let O=U(j,E);if(!O&&!_._executableFile&&this._scriptPath){let S=T6.basename(this._scriptPath,T6.extname(this._scriptPath));if(S!==this._name)O=U(j,`${S}-${_._name}`)}E=O||E}D=I.includes(T6.extname(E));let N;if(O_.platform!=="win32")if(D)$.unshift(E),$=y8(O_.execArgv).concat($),N=XP.spawn(O_.argv[0],$,{stdio:"inherit"});else N=XP.spawn(E,$,{stdio:"inherit"});else this._checkForMissingExecutable(E,j,_._name),$.unshift(E),$=y8(O_.execArgv).concat($),N=XP.spawn(O_.execPath,$,{stdio:"inherit"});if(!N.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((S)=>{O_.on(S,()=>{if(N.killed===!1&&N.exitCode===null)N.kill(S)})});let A=this._exitCallback;N.on("close",(O)=>{if(O=O??1,!A)O_.exit(O);else A(new GP(O,"commander.executeSubCommandAsync","(close)"))}),N.on("error",(O)=>{if(O.code==="ENOENT")this._checkForMissingExecutable(E,j,_._name);else if(O.code==="EACCES")throw Error(`'${E}' not executable`);if(!A)O_.exit(1);else{let S=new GP(1,"commander.executeSubCommandAsync","(error)");S.nestedError=O,A(S)}}),this.runningCommand=N}_dispatchSubcommand(_,$,D){let I=this._findCommand(_);if(!I)this.help({error:!0});I._prepareForParse();let U;return U=this._chainOrCallSubCommandHook(U,I,"preSubcommand"),U=this._chainOrCall(U,()=>{if(I._executableHandler)this._executeSubCommand(I,$.concat(D));else return I._parseCommand($,D)}),U}_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 _=(D,I,U)=>{let E=I;if(I!==null&&D.parseArg){let j=`error: command-argument value '${I}' is invalid for argument '${D.name()}'.`;E=this._callParseArg(D,I,U,j)}return E};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((D,I)=>{let U=D.defaultValue;if(D.variadic){if(I{return _(D,j,E)},D.defaultValue)}else if(U===void 0)U=[]}else if(I$());return $()}_chainOrCallHooks(_,$){let D=_,I=[];if(this._getCommandAndAncestors().reverse().filter((U)=>U._lifeCycleHooks[$]!==void 0).forEach((U)=>{U._lifeCycleHooks[$].forEach((E)=>{I.push({hookedCommand:U,callback:E})})}),$==="postAction")I.reverse();return I.forEach((U)=>{D=this._chainOrCall(D,()=>{return U.callback(U.hookedCommand,this)})}),D}_chainOrCallSubCommandHook(_,$,D){let I=_;if(this._lifeCycleHooks[D]!==void 0)this._lifeCycleHooks[D].forEach((U)=>{I=this._chainOrCall(I,()=>{return U(this,$)})});return I}_parseCommand(_,$){let D=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),_=_.concat(D.operands),$=D.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(D.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let I=()=>{if(D.unknown.length>0)this.unknownOption(D.unknown[0])},U=`command:${this.name()}`;if(this._actionHandler){I(),this._processArguments();let E;if(E=this._chainOrCallHooks(E,"preAction"),E=this._chainOrCall(E,()=>this._actionHandler(this.processedArgs)),this.parent)E=this._chainOrCall(E,()=>{this.parent.emit(U,_,$)});return E=this._chainOrCallHooks(E,"postAction"),E}if(this.parent&&this.parent.listenerCount(U))I(),this._processArguments(),this.parent.emit(U,_,$);else if(_.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",_,$);if(this.listenerCount("command:*"))this.emit("command:*",_,$);else if(this.commands.length)this.unknownCommand();else I(),this._processArguments()}else if(this.commands.length)I(),this.help({error:!0});else I(),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((D)=>{let I=D.attributeName();if(this.getOptionValue(I)===void 0)return!1;return this.getOptionValueSource(I)!=="default"});_.filter((D)=>D.conflictsWith.length>0).forEach((D)=>{let I=_.find((U)=>D.conflictsWith.includes(U.attributeName()));if(I)this._conflictingOption(D,I)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((_)=>{_._checkForConflictingLocalOptions()})}parseOptions(_){let $=[],D=[],I=$,U=_.slice();function E(N){return N.length>1&&N[0]==="-"}let j=null;while(U.length){let N=U.shift();if(N==="--"){if(I===D)I.push(N);I.push(...U);break}if(j&&!E(N)){this.emit(`option:${j.name()}`,N);continue}if(j=null,E(N)){let A=this._findOption(N);if(A){if(A.required){let O=U.shift();if(O===void 0)this.optionMissingArgument(A);this.emit(`option:${A.name()}`,O)}else if(A.optional){let O=null;if(U.length>0&&!E(U[0]))O=U.shift();this.emit(`option:${A.name()}`,O)}else this.emit(`option:${A.name()}`);j=A.variadic?A:null;continue}}if(N.length>2&&N[0]==="-"&&N[1]!=="-"){let A=this._findOption(`-${N[1]}`);if(A){if(A.required||A.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${A.name()}`,N.slice(2));else this.emit(`option:${A.name()}`),U.unshift(`-${N.slice(2)}`);continue}}if(/^--[^=]+=/.test(N)){let A=N.indexOf("="),O=this._findOption(N.slice(0,A));if(O&&(O.required||O.optional)){this.emit(`option:${O.name()}`,N.slice(A+1));continue}}if(E(N))I=D;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&D.length===0){if(this._findCommand(N)){if($.push(N),U.length>0)D.push(...U);break}else if(this._getHelpCommand()&&N===this._getHelpCommand().name()){if($.push(N),U.length>0)$.push(...U);break}else if(this._defaultCommandName){if(D.push(N),U.length>0)D.push(...U);break}}if(this._passThroughOptions){if(I.push(N),U.length>0)I.push(...U);break}I.push(N)}return{operands:$,unknown:D}}opts(){if(this._storeOptionsAsProperties){let _={},$=this.options.length;for(let D=0;D<$;D++){let I=this.options[D].attributeName();_[I]=I===this._versionOptionName?this._version:this[I]}return _}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((_,$)=>Object.assign(_,$.opts()),{})}error(_,$){if(this._outputConfiguration.outputError(`${_} + - ${I}`;throw Error(U)}_executeSubCommand(_,$){$=$.slice();let D=!1,I=[".js",".ts",".tsx",".mjs",".cjs"];function U(S,L){let W=T6.resolve(S,L);if(MN.existsSync(W))return W;if(I.includes(T6.extname(L)))return;let g=I.find((z)=>MN.existsSync(`${W}${z}`));if(g)return`${W}${g}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let E=_._executableFile||`${this._name}-${_._name}`,j=this._executableDir||"";if(this._scriptPath){let S;try{S=MN.realpathSync(this._scriptPath)}catch{S=this._scriptPath}j=T6.resolve(T6.dirname(S),j)}if(j){let S=U(j,E);if(!S&&!_._executableFile&&this._scriptPath){let L=T6.basename(this._scriptPath,T6.extname(this._scriptPath));if(L!==this._name)S=U(j,`${L}-${_._name}`)}E=S||E}D=I.includes(T6.extname(E));let N;if(S_.platform!=="win32")if(D)$.unshift(E),$=y8(S_.execArgv).concat($),N=Gz.spawn(S_.argv[0],$,{stdio:"inherit"});else N=Gz.spawn(E,$,{stdio:"inherit"});else this._checkForMissingExecutable(E,j,_._name),$.unshift(E),$=y8(S_.execArgv).concat($),N=Gz.spawn(S_.execPath,$,{stdio:"inherit"});if(!N.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((L)=>{S_.on(L,()=>{if(N.killed===!1&&N.exitCode===null)N.kill(L)})});let O=this._exitCallback;N.on("close",(S)=>{if(S=S??1,!O)S_.exit(S);else O(new Rz(S,"commander.executeSubCommandAsync","(close)"))}),N.on("error",(S)=>{if(S.code==="ENOENT")this._checkForMissingExecutable(E,j,_._name);else if(S.code==="EACCES")throw Error(`'${E}' not executable`);if(!O)S_.exit(1);else{let L=new Rz(1,"commander.executeSubCommandAsync","(error)");L.nestedError=S,O(L)}}),this.runningCommand=N}_dispatchSubcommand(_,$,D){let I=this._findCommand(_);if(!I)this.help({error:!0});I._prepareForParse();let U;return U=this._chainOrCallSubCommandHook(U,I,"preSubcommand"),U=this._chainOrCall(U,()=>{if(I._executableHandler)this._executeSubCommand(I,$.concat(D));else return I._parseCommand($,D)}),U}_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 _=(D,I,U)=>{let E=I;if(I!==null&&D.parseArg){let j=`error: command-argument value '${I}' is invalid for argument '${D.name()}'.`;E=this._callParseArg(D,I,U,j)}return E};this._checkNumberOfArguments();let $=[];this.registeredArguments.forEach((D,I)=>{let U=D.defaultValue;if(D.variadic){if(I{return _(D,j,E)},D.defaultValue)}else if(U===void 0)U=[]}else if(I$());return $()}_chainOrCallHooks(_,$){let D=_,I=[];if(this._getCommandAndAncestors().reverse().filter((U)=>U._lifeCycleHooks[$]!==void 0).forEach((U)=>{U._lifeCycleHooks[$].forEach((E)=>{I.push({hookedCommand:U,callback:E})})}),$==="postAction")I.reverse();return I.forEach((U)=>{D=this._chainOrCall(D,()=>{return U.callback(U.hookedCommand,this)})}),D}_chainOrCallSubCommandHook(_,$,D){let I=_;if(this._lifeCycleHooks[D]!==void 0)this._lifeCycleHooks[D].forEach((U)=>{I=this._chainOrCall(I,()=>{return U(this,$)})});return I}_parseCommand(_,$){let D=this.parseOptions($);if(this._parseOptionsEnv(),this._parseOptionsImplied(),_=_.concat(D.operands),$=D.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(D.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let I=()=>{if(D.unknown.length>0)this.unknownOption(D.unknown[0])},U=`command:${this.name()}`;if(this._actionHandler){I(),this._processArguments();let E;if(E=this._chainOrCallHooks(E,"preAction"),E=this._chainOrCall(E,()=>this._actionHandler(this.processedArgs)),this.parent)E=this._chainOrCall(E,()=>{this.parent.emit(U,_,$)});return E=this._chainOrCallHooks(E,"postAction"),E}if(this.parent&&this.parent.listenerCount(U))I(),this._processArguments(),this.parent.emit(U,_,$);else if(_.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",_,$);if(this.listenerCount("command:*"))this.emit("command:*",_,$);else if(this.commands.length)this.unknownCommand();else I(),this._processArguments()}else if(this.commands.length)I(),this.help({error:!0});else I(),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((D)=>{let I=D.attributeName();if(this.getOptionValue(I)===void 0)return!1;return this.getOptionValueSource(I)!=="default"});_.filter((D)=>D.conflictsWith.length>0).forEach((D)=>{let I=_.find((U)=>D.conflictsWith.includes(U.attributeName()));if(I)this._conflictingOption(D,I)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((_)=>{_._checkForConflictingLocalOptions()})}parseOptions(_){let $=[],D=[],I=$,U=_.slice();function E(N){return N.length>1&&N[0]==="-"}let j=null;while(U.length){let N=U.shift();if(N==="--"){if(I===D)I.push(N);I.push(...U);break}if(j&&!E(N)){this.emit(`option:${j.name()}`,N);continue}if(j=null,E(N)){let O=this._findOption(N);if(O){if(O.required){let S=U.shift();if(S===void 0)this.optionMissingArgument(O);this.emit(`option:${O.name()}`,S)}else if(O.optional){let S=null;if(U.length>0&&!E(U[0]))S=U.shift();this.emit(`option:${O.name()}`,S)}else this.emit(`option:${O.name()}`);j=O.variadic?O:null;continue}}if(N.length>2&&N[0]==="-"&&N[1]!=="-"){let O=this._findOption(`-${N[1]}`);if(O){if(O.required||O.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${O.name()}`,N.slice(2));else this.emit(`option:${O.name()}`),U.unshift(`-${N.slice(2)}`);continue}}if(/^--[^=]+=/.test(N)){let O=N.indexOf("="),S=this._findOption(N.slice(0,O));if(S&&(S.required||S.optional)){this.emit(`option:${S.name()}`,N.slice(O+1));continue}}if(E(N))I=D;if((this._enablePositionalOptions||this._passThroughOptions)&&$.length===0&&D.length===0){if(this._findCommand(N)){if($.push(N),U.length>0)D.push(...U);break}else if(this._getHelpCommand()&&N===this._getHelpCommand().name()){if($.push(N),U.length>0)$.push(...U);break}else if(this._defaultCommandName){if(D.push(N),U.length>0)D.push(...U);break}}if(this._passThroughOptions){if(I.push(N),U.length>0)I.push(...U);break}I.push(N)}return{operands:$,unknown:D}}opts(){if(this._storeOptionsAsProperties){let _={},$=this.options.length;for(let D=0;D<$;D++){let I=this.options[D].attributeName();_[I]=I===this._versionOptionName?this._version:this[I]}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 D=$||{},I=D.exitCode||1,U=D.code||"commander.error";this._exit(I,U,_)}_parseOptionsEnv(){this.options.forEach((_)=>{if(_.envVar&&_.envVar in O_.env){let $=_.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(_.required||_.optional)this.emit(`optionEnv:${_.name()}`,O_.env[_.envVar]);else this.emit(`optionEnv:${_.name()}`)}})}_parseOptionsImplied(){let _=new fw(this.options),$=(D)=>{return this.getOptionValue(D)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(D))};this.options.filter((D)=>D.implied!==void 0&&$(D.attributeName())&&_.valueFromOption(this.getOptionValue(D.attributeName()),D)).forEach((D)=>{Object.keys(D.implied).filter((I)=>!$(I)).forEach((I)=>{this.setOptionValueWithSource(I,D.implied[I],"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 D=(E)=>{let j=E.attributeName(),N=this.getOptionValue(j),A=this.options.find((S)=>S.negate&&j===S.attributeName()),O=this.options.find((S)=>!S.negate&&j===S.attributeName());if(A&&(A.presetArg===void 0&&N===!1||A.presetArg!==void 0&&N===A.presetArg))return A;return O||E},I=(E)=>{let j=D(E),N=j.attributeName();if(this.getOptionValueSource(N)==="env")return`environment variable '${j.envVar}'`;return`option '${j.flags}'`},U=`error: ${I(_)} cannot be used with ${I($)}`;this.error(U,{code:"commander.conflictingOption"})}unknownOption(_){if(this._allowUnknownOption)return;let $="";if(_.startsWith("--")&&this._showSuggestionAfterError){let I=[],U=this;do{let E=U.createHelp().visibleOptions(U).filter((j)=>j.long).map((j)=>j.long);I=I.concat(E),U=U.parent}while(U&&!U._enablePositionalOptions);$=u8(_,I)}let D=`error: unknown option '${_}'${$}`;this.error(D,{code:"commander.unknownOption"})}_excessArguments(_){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,D=$===1?"":"s",U=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${D} but got ${_.length}.`;this.error(U,{code:"commander.excessArguments"})}unknownCommand(){let _=this.args[0],$="";if(this._showSuggestionAfterError){let I=[];this.createHelp().visibleCommands(this).forEach((U)=>{if(I.push(U.name()),U.alias())I.push(U.alias())}),$=u8(_,I)}let D=`error: unknown command '${_}'${$}`;this.error(D,{code:"commander.unknownCommand"})}version(_,$,D){if(_===void 0)return this._version;this._version=_,$=$||"-V, --version",D=D||"output the version number";let I=this.createOption($,D);return this._versionOptionName=I.attributeName(),this._registerOption(I),this.on("option:"+I.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 D=this.parent?._findCommand(_);if(D){let I=[D.name()].concat(D.aliases()).join("|");throw Error(`cannot add alias '${_}' to command '${this.name()}' as already have command '${I}'`)}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((D)=>{return vw(D)});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=T6.basename(_,T6.extname(_)),this}executableDir(_){if(_===void 0)return this._executableDir;return this._executableDir=_,this}helpInformation(_){let $=this.createHelp(),D=this._getOutputContext(_);$.prepareContext({error:D.error,helpWidth:D.helpWidth,outputHasColors:D.hasColors});let I=$.formatHelp(this,$);if(D.hasColors)return I;return this._outputConfiguration.stripColor(I)}_getOutputContext(_){_=_||{};let $=!!_.error,D,I,U;if($)D=(j)=>this._outputConfiguration.writeErr(j),I=this._outputConfiguration.getErrHasColors(),U=this._outputConfiguration.getErrHelpWidth();else D=(j)=>this._outputConfiguration.writeOut(j),I=this._outputConfiguration.getOutHasColors(),U=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(j)=>{if(!I)j=this._outputConfiguration.stripColor(j);return D(j)},hasColors:I,helpWidth:U}}outputHelp(_){let $;if(typeof _==="function")$=_,_=void 0;let D=this._getOutputContext(_),I={error:D.error,write:D.write,command:this};this._getCommandAndAncestors().reverse().forEach((E)=>E.emit("beforeAllHelp",I)),this.emit("beforeHelp",I);let U=this.helpInformation({error:D.error});if($){if(U=$(U),typeof U!=="string"&&!Buffer.isBuffer(U))throw Error("outputHelp callback must return a string or a Buffer")}if(D.write(U),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",I),this._getCommandAndAncestors().forEach((E)=>E.emit("afterAllHelp",I))}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(O_.exitCode??0);if($===0&&_&&typeof _!=="function"&&_.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(_,$){let D=["beforeAll","before","after","afterAll"];if(!D.includes(_))throw Error(`Unexpected value for position to addHelpText. +`),this.outputHelp({error:!0});let D=$||{},I=D.exitCode||1,U=D.code||"commander.error";this._exit(I,U,_)}_parseOptionsEnv(){this.options.forEach((_)=>{if(_.envVar&&_.envVar in S_.env){let $=_.attributeName();if(this.getOptionValue($)===void 0||["default","config","env"].includes(this.getOptionValueSource($)))if(_.required||_.optional)this.emit(`optionEnv:${_.name()}`,S_.env[_.envVar]);else this.emit(`optionEnv:${_.name()}`)}})}_parseOptionsImplied(){let _=new fw(this.options),$=(D)=>{return this.getOptionValue(D)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(D))};this.options.filter((D)=>D.implied!==void 0&&$(D.attributeName())&&_.valueFromOption(this.getOptionValue(D.attributeName()),D)).forEach((D)=>{Object.keys(D.implied).filter((I)=>!$(I)).forEach((I)=>{this.setOptionValueWithSource(I,D.implied[I],"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 D=(E)=>{let j=E.attributeName(),N=this.getOptionValue(j),O=this.options.find((L)=>L.negate&&j===L.attributeName()),S=this.options.find((L)=>!L.negate&&j===L.attributeName());if(O&&(O.presetArg===void 0&&N===!1||O.presetArg!==void 0&&N===O.presetArg))return O;return S||E},I=(E)=>{let j=D(E),N=j.attributeName();if(this.getOptionValueSource(N)==="env")return`environment variable '${j.envVar}'`;return`option '${j.flags}'`},U=`error: ${I(_)} cannot be used with ${I($)}`;this.error(U,{code:"commander.conflictingOption"})}unknownOption(_){if(this._allowUnknownOption)return;let $="";if(_.startsWith("--")&&this._showSuggestionAfterError){let I=[],U=this;do{let E=U.createHelp().visibleOptions(U).filter((j)=>j.long).map((j)=>j.long);I=I.concat(E),U=U.parent}while(U&&!U._enablePositionalOptions);$=u8(_,I)}let D=`error: unknown option '${_}'${$}`;this.error(D,{code:"commander.unknownOption"})}_excessArguments(_){if(this._allowExcessArguments)return;let $=this.registeredArguments.length,D=$===1?"":"s",U=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${$} argument${D} but got ${_.length}.`;this.error(U,{code:"commander.excessArguments"})}unknownCommand(){let _=this.args[0],$="";if(this._showSuggestionAfterError){let I=[];this.createHelp().visibleCommands(this).forEach((U)=>{if(I.push(U.name()),U.alias())I.push(U.alias())}),$=u8(_,I)}let D=`error: unknown command '${_}'${$}`;this.error(D,{code:"commander.unknownCommand"})}version(_,$,D){if(_===void 0)return this._version;this._version=_,$=$||"-V, --version",D=D||"output the version number";let I=this.createOption($,D);return this._versionOptionName=I.attributeName(),this._registerOption(I),this.on("option:"+I.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 D=this.parent?._findCommand(_);if(D){let I=[D.name()].concat(D.aliases()).join("|");throw Error(`cannot add alias '${_}' to command '${this.name()}' as already have command '${I}'`)}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((D)=>{return vw(D)});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=T6.basename(_,T6.extname(_)),this}executableDir(_){if(_===void 0)return this._executableDir;return this._executableDir=_,this}helpInformation(_){let $=this.createHelp(),D=this._getOutputContext(_);$.prepareContext({error:D.error,helpWidth:D.helpWidth,outputHasColors:D.hasColors});let I=$.formatHelp(this,$);if(D.hasColors)return I;return this._outputConfiguration.stripColor(I)}_getOutputContext(_){_=_||{};let $=!!_.error,D,I,U;if($)D=(j)=>this._outputConfiguration.writeErr(j),I=this._outputConfiguration.getErrHasColors(),U=this._outputConfiguration.getErrHelpWidth();else D=(j)=>this._outputConfiguration.writeOut(j),I=this._outputConfiguration.getOutHasColors(),U=this._outputConfiguration.getOutHelpWidth();return{error:$,write:(j)=>{if(!I)j=this._outputConfiguration.stripColor(j);return D(j)},hasColors:I,helpWidth:U}}outputHelp(_){let $;if(typeof _==="function")$=_,_=void 0;let D=this._getOutputContext(_),I={error:D.error,write:D.write,command:this};this._getCommandAndAncestors().reverse().forEach((E)=>E.emit("beforeAllHelp",I)),this.emit("beforeHelp",I);let U=this.helpInformation({error:D.error});if($){if(U=$(U),typeof U!=="string"&&!Buffer.isBuffer(U))throw Error("outputHelp callback must return a string or a Buffer")}if(D.write(U),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",I),this._getCommandAndAncestors().forEach((E)=>E.emit("afterAllHelp",I))}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(S_.exitCode??0);if($===0&&_&&typeof _!=="function"&&_.error)$=1;this._exit($,"commander.help","(outputHelp)")}addHelpText(_,$){let D=["beforeAll","before","after","afterAll"];if(!D.includes(_))throw Error(`Unexpected value for position to addHelpText. Expecting one of '${D.join("', '")}'`);let I=`${_}Help`;return this.on(I,(U)=>{let E;if(typeof $==="function")E=$({error:U.error,command:U.command});else E=$;if(E)U.write(`${E} -`)}),this}_outputHelpIfRequested(_){let $=this._getHelpOption();if($&&_.find((I)=>$.is(I)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function y8(_){return _.map(($)=>{if(!$.startsWith("--inspect"))return $;let D,I="127.0.0.1",U="9229",E;if((E=$.match(/^(--inspect(-brk)?)$/))!==null)D=E[1];else if((E=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(D=E[1],/^\d+$/.test(E[3]))U=E[3];else I=E[3];else if((E=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)D=E[1],I=E[3],U=E[4];if(D&&U!=="0")return`${D}=${I}:${parseInt(U)+1}`;return $})}function RP(){if(O_.env.NO_COLOR||O_.env.FORCE_COLOR==="0"||O_.env.FORCE_COLOR==="false")return!1;if(O_.env.FORCE_COLOR||O_.env.CLICOLOR_FORCE!==void 0)return!0;return}xw.Command=YP;xw.useColor=RP});var m8=D4((nw)=>{var{Argument:c8}=BN(),{Command:QP}=h8(),{CommanderError:hw,InvalidArgumentError:n8}=k1(),{Help:cw}=PP(),{Option:d8}=zP();nw.program=new QP;nw.createCommand=(_)=>new QP(_);nw.createOption=(_,$)=>new d8(_,$);nw.createArgument=(_,$)=>new c8(_,$);nw.Command=QP;nw.Option=d8;nw.Argument=c8;nw.Help=cw;nw.CommanderError=hw;nw.InvalidArgumentError=n8;nw.InvalidOptionArgumentError=n8});import{chmodSync as yP,closeSync as wD,existsSync as A0,fsyncSync as dN,lstatSync as xY,openSync as mN,readFileSync as rD,renameSync as hP,unlinkSync as lN,writeFileSync as iN}from"fs";import{randomUUID as fD}from"crypto";import{basename as uY,dirname as cP,join as nN}from"path";import{chmodSync as kP,existsSync as CY,mkdirSync as rN,readFileSync as vY,writeFileSync as qP}from"fs";import{homedir as fN}from"os";import{dirname as wY,join as y_,resolve as CP}from"path";var s$=y_(".hasna","knowledge"),vP=y_(".hasna","apps","knowledge"),W_={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:s$,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 wP(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:W_.s3.bucket,prefix:W_.s3.prefix,region:W_.s3.region,profile:W_.s3.profile,server_side_encryption:W_.s3.server_side_encryption}}}function CD(){return y_(fN(),".open-knowledge","db.json")}function r1(){return y_(fN(),".hasna","knowledge")}function xN(_=process.cwd()){return CP(_,s$)}function rY(){return y_(fN(),vP)}function fY(_=process.cwd()){return CP(_,vP)}function uN(_,$=process.cwd()){if(_==="project"||_==="local")return j$(fY($));return j$(rY())}function j$(_){return{home:_,configPath:y_(_,"config.json"),jsonStorePath:y_(_,"db.json"),knowledgeDbPath:y_(_,"knowledge.db"),artifactsDir:y_(_,"artifacts"),cacheDir:y_(_,"cache"),exportsDir:y_(_,"exports"),indexesDir:y_(_,"indexes"),logsDir:y_(_,"logs"),runsDir:y_(_,"runs"),schemasDir:y_(_,"schemas"),wikiDir:y_(_,"wiki")}}function vD(){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 g0(_){let $=j$(_);rN($.home,{recursive:!0,mode:448});for(let D of[$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir])rN(D,{recursive:!0,mode:448});if(!CY($.configPath))qP($.configPath,`${JSON.stringify(vD(),null,2)} -`,{mode:384}),kP($.configPath,384);return $}function f1(_,$=process.cwd()){if(_==="project"||_==="local")return j$(xN($));return j$(r1())}function u$(_){rN(wY(_),{recursive:!0})}function yN(_){let $=vY(_,"utf8");return JSON.parse($)}function rP(_,$){u$(_),qP(_,`${JSON.stringify($,null,2)} -`,{mode:384}),kP(_,384)}function u1(){return j$(r1()).jsonStorePath}function xD(_){if(_===u1()&&A0(CD()))oN();if(!A0(_))u$(_),mP(_,`${JSON.stringify({items:[]},null,2)} +`)}),this}_outputHelpIfRequested(_){let $=this._getHelpOption();if($&&_.find((I)=>$.is(I)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function y8(_){return _.map(($)=>{if(!$.startsWith("--inspect"))return $;let D,I="127.0.0.1",U="9229",E;if((E=$.match(/^(--inspect(-brk)?)$/))!==null)D=E[1];else if((E=$.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(D=E[1],/^\d+$/.test(E[3]))U=E[3];else I=E[3];else if((E=$.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)D=E[1],I=E[3],U=E[4];if(D&&U!=="0")return`${D}=${I}:${parseInt(U)+1}`;return $})}function Yz(){if(S_.env.NO_COLOR||S_.env.FORCE_COLOR==="0"||S_.env.FORCE_COLOR==="false")return!1;if(S_.env.FORCE_COLOR||S_.env.CLICOLOR_FORCE!==void 0)return!0;return}xw.Command=Qz;xw.useColor=Yz});var m8=U4((nw)=>{var{Argument:c8}=BN(),{Command:Kz}=h8(),{CommanderError:hw,InvalidArgumentError:n8}=k1(),{Help:cw}=gz(),{Option:d8}=Xz();nw.program=new Kz;nw.createCommand=(_)=>new Kz(_);nw.createOption=(_,$)=>new d8(_,$);nw.createArgument=(_,$)=>new c8(_,$);nw.Command=Kz;nw.Option=d8;nw.Argument=c8;nw.Help=cw;nw.CommanderError=hw;nw.InvalidArgumentError=n8;nw.InvalidOptionArgumentError=n8});import{chmodSync as hz,closeSync as wD,existsSync as L0,fsyncSync as dN,lstatSync as xY,openSync as mN,readFileSync as rD,renameSync as cz,unlinkSync as lN,writeFileSync as iN}from"fs";import{randomUUID as fD}from"crypto";import{basename as uY,dirname as nz,join as nN}from"path";import{chmodSync as kz,existsSync as CY,mkdirSync as rN,readFileSync as vY,writeFileSync as Cz}from"fs";import{homedir as fN}from"os";import{dirname as wY,join as y_,resolve as vz}from"path";var s$=y_(".hasna","knowledge"),wz=y_(".hasna","apps","knowledge"),P_={division:"xyz",app_type:"opensource",app:"knowledge",env:"prod",local_path:s$,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 rz(){return{type:"s3",artifacts_root:"artifacts",s3:{bucket:P_.s3.bucket,prefix:P_.s3.prefix,region:P_.s3.region,profile:P_.s3.profile,server_side_encryption:P_.s3.server_side_encryption}}}function CD(){return y_(fN(),".open-knowledge","db.json")}function f1(){return y_(fN(),".hasna","knowledge")}function xN(_=process.cwd()){return vz(_,s$)}function rY(){return y_(fN(),wz)}function fY(_=process.cwd()){return vz(_,wz)}function uN(_,$=process.cwd()){if(_==="project"||_==="local")return j$(fY($));return j$(rY())}function j$(_){return{home:_,configPath:y_(_,"config.json"),jsonStorePath:y_(_,"db.json"),knowledgeDbPath:y_(_,"knowledge.db"),artifactsDir:y_(_,"artifacts"),cacheDir:y_(_,"cache"),exportsDir:y_(_,"exports"),indexesDir:y_(_,"indexes"),logsDir:y_(_,"logs"),runsDir:y_(_,"runs"),schemasDir:y_(_,"schemas"),wikiDir:y_(_,"wiki")}}function vD(){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 S0(_){let $=j$(_);rN($.home,{recursive:!0,mode:448});for(let D of[$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir])rN(D,{recursive:!0,mode:448});if(!CY($.configPath))Cz($.configPath,`${JSON.stringify(vD(),null,2)} +`,{mode:384}),kz($.configPath,384);return $}function x1(_,$=process.cwd()){if(_==="project"||_==="local")return j$(xN($));return j$(f1())}function u$(_){rN(wY(_),{recursive:!0})}function yN(_){let $=vY(_,"utf8");return JSON.parse($)}function fz(_,$){u$(_),Cz(_,`${JSON.stringify($,null,2)} +`,{mode:384}),kz(_,384)}function y1(){return j$(f1()).jsonStorePath}function xD(_){if(_===y1()&&L0(CD()))oN();if(!L0(_))u$(_),lz(_,`${JSON.stringify({items:[]},null,2)} `)}function yY(_){return _.toISOString().replace(/[:.]/g,"-")}function tN(_){let $=[`id:${_.id}`];if(typeof _.short_id==="string"&&_.short_id.length>0)$.push(`short_id:${_.short_id}`);return $}function hY(_){let $=new Set;for(let D of _)for(let I of tN(D))$.add(I);return $}function cY(_,$){return tN($).some((D)=>_.has(D))}function hN(_,$){u$(_),iN(_,`${JSON.stringify($,null,2)} -`,{mode:384}),yP(_,384)}function fP(_){let $=JSON.parse(rD(_,"utf8"));if(!$||typeof $!=="object"||!Array.isArray($.items))return{store:{items:[]},skippedInvalid:0};let D={items:[]},I=0;for(let U of $.items)if(U&&typeof U==="object"&&typeof U.id==="string"&&U.id.length>0)D.items.push(U);else I+=1;return{store:D,skippedInvalid:I}}function oN(_={}){if(_.dryRun===!0)return xP(_);return y$(u1(),()=>xP(_),{createParent:!0})}function xP(_={}){let $=_.dryRun===!0,D=_.now??new Date,I=j$(r1()),U=CD(),E=I.jsonStorePath,j=A0(U),N=A0(E),A={ok:!0,dry_run:$,legacy_path:U,canonical_path:E,legacy_exists:j,canonical_existed:N,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:j?"Legacy global store already imported":"No legacy global store found"};if(!j)return A;let O;try{let G=fP(U);O=G.store,A.skipped_invalid=G.skippedInvalid}catch(G){return A.ok=!1,A.errors.push(`Could not read legacy store: ${G instanceof Error?G.message:String(G)}`),A.message="Legacy global store import failed",A}let S={items:[]};if(N)try{S=fP(E).store}catch(G){return A.ok=!1,A.errors.push(`Could not read canonical store: ${G instanceof Error?G.message:String(G)}`),A.message="Legacy global store import failed",A}let L=hY(S.items),P={items:[...S.items]};for(let G of O.items){if(!G?.id){A.skipped_invalid+=1;continue}if(cY(L,G)){A.skipped_existing+=1;continue}P.items.push(G);for(let J of tN(G))L.add(J);A.imported+=1}if(A.would_create_canonical=!N&&A.imported>0,A.canonical_created=!$&&A.would_create_canonical,A.message=A.imported>0?`Imported ${A.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",$||A.imported===0)return A;let z=`${yY(D)}-${fD().slice(0,8)}`;if(N)A.backup_path=nN(I.exportsDir,`legacy-open-knowledge-db-before-import-${z}.json`),hN(A.backup_path,S);return hN(E,P),A.report_path=nN(I.runsDir,`legacy-open-knowledge-import-${z}.json`),hN(A.report_path,A),A}function U4(_){if(!A0(_))return{exists:!1,items:[]};let $=rD(_,"utf8"),D=JSON.parse($);if(!D||!Array.isArray(D.items))return{exists:!0,items:[]};return{exists:!0,items:D.items}}function nY(_){return`${_}.lock`}var x1=1e4,nP=25,uP=120000,dY=new Int32Array(new SharedArrayBuffer(4));function pN(_){return typeof _==="object"&&_!==null&&"code"in _?String(_.code):void 0}function dP(_){let $=null;try{$=mN(cP(_),"r"),dN($)}catch{}finally{if($!==null)try{wD($)}catch{}}}var cN=new Set;function mP(_,$){u$(_);let D=nN(cP(_),`.${uY(_)}.tmp.${fD()}`),I=null;try{I=mN(D,"wx",384),iN(I,$),dN(I),wD(I),I=null,hP(D,_);try{yP(_,384)}catch{}dP(_)}catch(U){if(I!==null)try{wD(I)}catch{}try{lN(D)}catch{}throw U}}function lP(_){Atomics.wait(dY,0,0,_)}function mY(_){if(typeof _!=="number"||!Number.isInteger(_)||_<=0)return!1;try{return process.kill(_,0),!0}catch($){return pN($)!=="ESRCH"}}function iP(_,$){try{let D=rD(_,"utf8"),I=JSON.parse(D);if(typeof I.ts==="number")return $-I.ts>uP&&!mY(I.pid)}catch{}try{return $-xY(_).mtimeMs>uP}catch{return!1}}function lY(_){let $=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),D=`${_}.stale.${$}.${fD()}`;try{hP(_,D)}catch(I){if(pN(I)!=="ENOENT")throw I;return}}function iY(_){let $=fD(),D=`${_}.breaker`,I=Date.now();while(Date.now()-I{I=E};while(Date.now()-DEQ)return null;D=sY(_,"utf8")}catch{return null}let I=OQ(D);for(let U of $){let E=I.get(U)?.trim();if(E)return E}return null}function O0(_,$,D){if(!gQ.test(D))return;throw new yD(_,`The credential from ${$} contains characters that cannot be sent in an HTTP header (a control character or non-ASCII byte). A file written with CR-only line endings is the usual cause. Rewrite that credential file with one LF-terminated KEY=value line. The value is not shown here, and is deliberately never logged.`,[$])}var SQ=Symbol.for("nodejs.util.inspect.custom");function S0(_){let{apiKey:$,...D}=_,I={...D};return Object.defineProperty(I,"apiKey",{value:$,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(I,SQ,{value:()=>({...D,apiKey:"[redacted]"}),enumerable:!1,writable:!1,configurable:!1}),I}function LQ(_,$){return O0(_,"explicit apiKey option",$),S0({apiKey:$,tier:"argument",source:"explicit apiKey option",deliberate:!0,deprecated:!1,diskCandidates:[],warning:null})}function $z(_,$){for(let D of $){let I=_[D]?.trim();if(I)return{key:D,value:I}}return null}var Dz=Symbol.for("hasna:contracts:credentialDeprecationNotices");function JQ(){let _=globalThis,$=_[Dz];if($ instanceof Set)return $;let D=new Set;return _[Dz]=D,D}function WQ(_){if(typeof process<"u"&&process.stderr)process.stderr.write(`${_} -`)}function _g(_,$,D={}){let{apiKeyKeys:I}=jz(_),U=Nz(_,$),E=D.apiKey?.trim();if(E)return O0(_,"the explicit apiKey argument",E),S0({apiKey:E,tier:"argument",source:"explicit apiKey argument",deliberate:!0,deprecated:!1,diskCandidates:U,warning:null});let j=aY(_),N=$[j];if(N!==void 0){let L=N.trim();if(!L)throw new yD(_,`${j} is set but empty. It is a deliberate override, so it is not resolved around: either give it a real key or unset it to fall back to the credential on disk.`,[j]);return O0(_,j,L),S0({apiKey:L,tier:"override",source:j,deliberate:!0,deprecated:!1,diskCandidates:U,warning:null})}let A=D.profile?.trim()||$[eN]?.trim();if(A){let L=D.profile?.trim()?"explicit profile argument":eN;if(!NQ.test(A))throw new yD(_,`Profile name from ${L} is not usable in a path. Use letters, digits, dot, dash, or underscore.`,[L]);let P=gz(_,$,A);for(let z of P){let G=_z(z,I);if(G)return O0(_,z,G),S0({apiKey:G,tier:"profile",source:z,deliberate:!0,deprecated:!1,diskCandidates:P,warning:null})}throw new yD(_,`Profile '${A}' (from ${L}) has no ${I[0]} for '${_}'. Looked in: ${P.join(", ")||""}. `+"A profile names WHICH identity to use, so it is never resolved around \u2014 "+`create the profile's credential file or unset ${eN}.`,P)}let O=U.map((L)=>({path:L,value:_z(L,I)})).filter((L)=>L.value!==null);if(O.length>0){let L=O[0];O0(_,L.path,L.value);let P=[...O.slice(1).filter((G)=>G.value!==L.value).map((G)=>G.path),...(()=>{let G=$z($,I);return G&&G.value!==L.value?[G.key]:[]})()],z=P.length>0?`Credential sources disagree for '${_}': ${L.path} and ${P.join(", ")} hold different keys. ${L.path} wins, because a file on `+"disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 "+"a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.":null;return S0({apiKey:L.value,tier:"disk",source:L.path,deliberate:!1,deprecated:!1,diskCandidates:U,warning:z})}let S=$z($,I);if(S){O0(_,S.key,S.value);let L=U.length>0?`Put the current key in ${U[0]} \u2014 it is re-read on every call, so rotations take effect immediately.`:"This environment has no HOME, so no credential file could be consulted at all; the disk tier is unavailable here and this process will keep using the environment snapshot.",P=`[${_}] DEPRECATED: the API key came from ${S.key} in this process's environment. Environment variables are a snapshot taken when this process started, so a shell that started before a key rotation keeps using the old key until it exits. ${L}`,z=D.onDeprecation??WQ,G=JQ();if(!G.has(_))G.add(_),z(P);return S0({apiKey:S.value,tier:"legacy-env",source:S.key,deliberate:!1,deprecated:!0,diskCandidates:U,warning:P})}return null}var V6="HASNA_FLEET_API_DOMAIN",L0="your-deployment.example",Dg=/[\u0000-\u001f\u007f]/,Az=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function y1(_){if(_.length===0||_.length>253||Dg.test(_)||/[^\x00-\x7f]/.test(_))return!1;return _.split(".").every(($)=>$.length<=63&&!$.startsWith("xn--")&&Az.test($))}function PQ(_){let $=_[V6];if($===void 0)return{domain:L0,source:"default",misconfigured:!0,warning:`${V6} is not set; using the non-resolving ${L0} fallback.`};let D=$.trim().toLowerCase();if(Dg.test($)||!y1(D))return{domain:L0,source:V6,misconfigured:!0,warning:`${V6} is blank or invalid; using the non-resolving ${L0} fallback.`};return{domain:D,source:V6,misconfigured:!1,warning:null}}function Oz(_){if(_.length>63||!Az.test(_))throw Error("App name must be one lowercase DNS label.");return _}function zQ(_,$){let D=`${Oz(_)}.${$}`;if(!y1(D))throw Error("Composed cloud hostname must be a valid DNS domain");return D}function XQ(_,$){let D=Oz(_),I=PQ($),U=`${D}.${I.domain}`;if(y1(U))return{baseUrl:`https://${U}`,source:I.source,misconfigured:I.misconfigured,warning:I.warning};return{baseUrl:`https://${zQ(D,L0)}`,source:I.source,misconfigured:!0,warning:`${V6} cannot form a valid composed cloud hostname for app '${D}'; using the non-resolving ${L0} fallback.`}}function aN(_,$,D={}){for(let I of $){let U=_[I],E=U?.trim();if(E)return{key:I,value:D.preserveRaw?U:E}}return null}function GQ(_){let $=/^[a-z][a-z0-9+.-]*:\/\//i.exec(_);if(!$)throw Error("API URL must be absolute.");let D=_.slice($[0].length),I=D.search(/[/?#]/),U=I===-1?D:D.slice(0,I);if(!U)throw Error("API URL must include a hostname.");return U}function Uz(_){if(!/^[0-9]+$/.test(_)||_.length>1&&_.startsWith("0"))throw Error("API URL authority must contain a canonical port between 1 and 65535.");let $=Number(_);if(!Number.isSafeInteger($)||$<1||$>65535)throw Error("API URL authority must contain a canonical port between 1 and 65535.")}function RQ(_){let $;if(_.startsWith("[")){let D=_.indexOf("]");if(D===-1)throw Error("API URL authority must contain a canonical hostname.");$=_.slice(0,D+1);let I=_.slice(D+1);if(I){if(!I.startsWith(":"))throw Error("API URL authority must contain a canonical hostname and port.");Uz(I.slice(1))}if(aP($.slice(1,-1))!==6)throw Error("API URL authority must contain a canonical IPv6 literal.")}else{let D=_.indexOf(":"),I=_.lastIndexOf(":");if(D!==I)throw Error("IPv6 API URL authorities must use brackets.");if(I!==-1){let N=_.slice(I+1);Uz(N),$=_.slice(0,I)}else $=_;let U=aP($),j=$.split(".").every((N)=>/^(?:0x[0-9a-f]+|[0-9]+)$/i.test(N));if(U!==4&&j||U!==4&&!y1($.toLowerCase()))throw Error("API URL authority must contain a canonical ASCII hostname.")}return $.toLowerCase()}function YQ(_){return/^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(_)}function Sz(_){if(Dg.test(_))throw Error("API URL must not contain ASCII control characters.");let $=_.trim(),D=GQ($);if(D.includes("@")||D.includes("\\")||D.includes("%")||/[^\x00-\x7f]/.test(D))throw Error("API URL authority must be canonical ASCII without credentials.");let I=RQ(D),U=new URL($);if(U.protocol!=="http:"&&U.protocol!=="https:")throw Error("API URL must use http or https.");if(U.username||U.password)throw Error("API URL must not include credentials.");if(!U.hostname||U.hostname.endsWith("."))throw Error("API URL must include a canonical hostname.");if(U.hostname.toLowerCase()!==I)throw Error("API URL authority must not rely on parser hostname normalization.");if(U.hostname.split(".").some((j)=>j.toLowerCase().startsWith("xn--")))throw Error("API URL must not use IDN or punycode hostnames.");if(U.protocol==="http:"&&!YQ(D))throw Error("API URL may use http only for an exact loopback authority.");if(U.search||U.hash)throw Error("API URL must not include a query string or fragment.");let E=U.pathname.replace(/\/+$/,"");if(E.endsWith("/v1"))E=E.slice(0,-3);return U.pathname=`${E}/v1`,U.toString().replace(/\/+$/,"")}function QQ(_,$=process.env,D={}){let I=jz(_),U=aN($,I.modeKeys),E=aN($,I.apiUrlKeys,{preserveRaw:!0}),j=aN($,I.apiKeyKeys),N="sqlite",A="default",O=[],S;if(U)N=eY(U.value).mode,A=U.key;else if(E){if(S=_g(_,$,D.credentials),S)N="postgres",A=`${E.key}+${S.source}`}if(N==="sqlite")return{transport:"sqlite",mode:N,modeSource:A,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(j),apiKeySource:j?j.key:null,apiKeyTier:null,misconfigured:!1,warning:O.length>0?O.join(" "):null};if(S===void 0)S=_g(_,$,D.credentials);if(!S){let G=Lz(_,$);return O.push(`${A}=postgres but no API key could be resolved for '${_}'. A client reaches server data over HTTP only; refusing to route. Using the local sqlite store. Looked for a credential file at ${G}, then for ${I.apiKeyKeys[0]} in the environment.`),{transport:"sqlite",mode:N,modeSource:A,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,apiKeyTier:null,misconfigured:!0,warning:O.join(" ")}}if(S.warning)O.push(S.warning);let L=null,P=E?.key??($[V6]===void 0?"default":V6),z;try{if(!E)L=XQ(_,$),P=L.source;let G=E?.value??L.baseUrl;z=Sz(G)}catch(G){let J=G instanceof Error?G.message:String(G);return O.push(`Invalid API URL from ${P}: ${J}. Using local store.`),{transport:"sqlite",mode:N,modeSource:A,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:S.source,apiKeyTier:S.tier,misconfigured:!0,warning:O.join(" ")}}if(L?.warning)O.push(L.warning);return{transport:"http",mode:N,modeSource:A,baseUrl:z,apiUrlSource:P,apiKeyPresent:!0,apiKeySource:S.source,apiKeyTier:S.tier,misconfigured:L?.misconfigured??!1,warning:O.length>0?O.join(" "):null}}function Lz(_,$){let D=Nz(_,$);return D.length>0?D.join(" or "):""}class J0 extends Error{status;method;path;body;credentialSource;credentialTier;constructor(_,$,D,I,U){let E=U?`. ${U.guidance}`:"";super(`Hasna cloud request failed: ${_} ${$} -> ${D}${E}`);this.name="HasnaHttpError",this.status=D,this.method=_,this.path=$,this.body=I,this.credentialSource=U?.source??null,this.credentialTier=U?.tier??null}}function KQ(_,$){if(typeof $==="function")return $();return LQ(_,$)}function TQ(_){let $=`The API key for this request came from ${_.source}`;if(_.deliberate)return`${$} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: `+"falling back here would authenticate as a different principal than the one you named, which is exactly the failure an override exists to prevent. Rotate that key, or unset the override to use the credential on disk.";if(_.deprecated){let D=_.diskCandidates[0],I=D?`Write the CURRENT key to ${D} \u2014 that file is re-read on every call, so rotations take `+`effect immediately and in every shell. Do not simply unset ${_.source}: nothing was found on disk, so that would leave this client with no credential at all.`:"This environment has no HOME, so no credential file could be consulted; the disk tier is unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.";return`${$}, a variable in this process's environment \u2014 which is a snapshot taken when the process `+`started. A STALE SHELL is the most common cause of this error: this shell exported the key before it was rotated, and will keep sending the old one until it exits. ${I}`}return`${$}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. `+"The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution so this machine gets the current key."}var FQ=[408,425,429,500,502,503,504],VQ=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),BQ=new Set(["host",":authority","forwarded","x-forwarded-host","x-original-host"]);function Iz(_,$){if(!_)return;let D=Object.keys(_).find((I)=>BQ.has(I.trim().toLowerCase()));if(D)throw Error(`Authenticated ${$} headers must not set authority header '${D}'.`)}function MQ(_,$){if(!$)return _;let D=$ instanceof URLSearchParams?$:new URLSearchParams;if(!($ instanceof URLSearchParams))for(let[U,E]of Object.entries($)){if(E===null||E===void 0)continue;if(Array.isArray(E))for(let j of E)D.append(U,String(j));else D.append(U,String(E))}let I=D.toString();if(!I)return _;return`${_}${_.includes("?")?"&":"?"}${I}`}var bQ=(_)=>new Promise(($)=>setTimeout($,_));function ZQ(_){let $=_.fetchImpl??((O,S)=>fetch(O,S)),D=Sz(_.baseUrl),I=_.timeoutMs??30000,U=_.sleepImpl??bQ,E=_.retry;function j(O){let S=O!==void 0?O:E;if(S===!1)return null;let L=S??{};return{retries:L.retries??2,baseDelayMs:L.baseDelayMs??200,maxDelayMs:L.maxDelayMs??2000,retryStatuses:L.retryStatuses??[...FQ]}}async function N(O,S,L,P,z,G){Iz(_.headers,"transport"),Iz(z.headers,"request");let J={"x-api-key":G.apiKey,Authorization:`Bearer ${G.apiKey}`,Accept:"application/json",..._.headers??{},...z.headers??{}};if(z.idempotencyKey)J["Idempotency-Key"]=z.idempotencyKey;let W={method:O,headers:J,redirect:"manual"};if(P!==void 0)J["Content-Type"]="application/json",W.body=JSON.stringify(P);let X=new AbortController,R=()=>X.abort();if(z.signal)if(z.signal.aborted)X.abort();else z.signal.addEventListener("abort",R,{once:!0});let T=setTimeout(()=>X.abort(),z.timeoutMs??I);W.signal=X.signal;let Y;try{Y=await $(L,W)}catch(q){let Z=q instanceof Error?q:Error(String(q));if(z.signal?.aborted)return{ok:!1,retryable:!1,error:Z};return{ok:!1,retryable:!0,error:Z}}finally{if(clearTimeout(T),z.signal)z.signal.removeEventListener("abort",R)}let Q=await Y.text(),F=void 0;if(Q.length>0)try{F=JSON.parse(Q)}catch{F=Q}if(!Y.ok){if(Y.status>=300&&Y.status<400)return{ok:!1,retryable:!1,error:new J0(O,S,Y.status,F)};if(Y.status===401||Y.status===403)return{ok:!1,retryable:!1,error:new J0(O,S,Y.status,F,{source:G.source,tier:G.tier,guidance:TQ(G)})};let q=j(z.retry);return{ok:!1,retryable:q?q.retryStatuses.includes(Y.status):!1,error:new J0(O,S,Y.status,F)}}return{ok:!0,value:F}}async function A(O,S,L,P={}){let z=O.toUpperCase(),G=MQ(S.startsWith("/")?S:`/${S}`,P.query),J=`${D}${G}`,W=j(P.retry),X=VQ.has(z)||Boolean(P.idempotencyKey),R=W&&X?W.retries+1:1,T=KQ(_.name,_.apiKey),Y=null;for(let Q=1;Q<=R;Q++){let F=await N(z,G,J,L,P,T);if(F.ok)return F.value;if(Y=F,!(W!==null&&X&&F.retryable&&QA("GET",O,void 0,S),post:(O,S,L)=>A("POST",O,S,L),put:(O,S,L)=>A("PUT",O,S,L),patch:(O,S,L)=>A("PATCH",O,S,L),del:(O,S,L)=>A("DELETE",O,S,L)}}function HQ(_,$=process.env,D){let I=D?.credentials,U=QQ(_,$,{...I?{credentials:I}:{}});if(U.misconfigured)throw Error(U.warning??`Client for '${_}' is misconfigured for the API client.`);if(U.transport==="sqlite"||!U.baseUrl)return{transport:"sqlite",client:null,resolution:U};let E=()=>{let j=_g(_,$,I);if(!j)throw Error(`Client for '${_}' resolved to the http transport but no API key is available any more. Looked at ${Lz(_,$)}, then the environment. A credential file that was removed after this client was built is the usual cause.`);return j};return{transport:"http",client:ZQ({name:_,baseUrl:U.baseUrl,apiKey:E,...D?.fetchImpl?{fetchImpl:D.fetchImpl}:{},...D?.headers?{headers:D.headers}:{},...D?.timeoutMs?{timeoutMs:D.timeoutMs}:{},...D?.retry!==void 0?{retry:D.retry}:{},...D?.sleepImpl?{sleepImpl:D.sleepImpl}:{}}),resolution:U}}function $g(_){let $=_.replace(/^\/+|\/+$/g,"");if(!$)throw Error("resource must be a non-empty path segment");return`/${$}`}function sN(_,$){if($===void 0||$===null||`${$}`.length===0)throw Error("id must be a non-empty string");return`${$g(_)}/${encodeURIComponent(String($))}`}function kQ(){let _=globalThis;if(_.crypto?.randomUUID)return _.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function qQ(_){if(Array.isArray(_))return _;if(_&&typeof _==="object"){let $=_;for(let D of["items","data","results","rows","records"])if(Array.isArray($[D]))return $[D]}return[]}function CQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["total","count","totalCount","total_count"])if(typeof $[D]==="number")return $[D]}return null}function vQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["cursor","nextCursor","next_cursor","next"])if(typeof $[D]==="string")return $[D]}return null}function wQ(_,$){return{name:_,baseUrl:$.baseUrl,transport:$,async list(D,I={}){let U=await $.get($g(D),I);return{items:qQ(U),total:CQ(U),cursor:vQ(U),raw:U}},async get(D,I,U={}){try{return await $.get(sN(D,I),U)}catch(E){if(E instanceof J0&&E.status===404)return null;throw E}},async create(D,I,U={}){let{idempotencyKey:E,...j}=U;return $.post($g(D),I,{...j,idempotencyKey:E??kQ()})},async update(D,I,U,E={}){let{method:j="PATCH",idempotencyKey:N,...A}=E;return(j==="PUT"?$.put:$.patch)(sN(D,I),U,{...A,...N?{idempotencyKey:N}:{}})},async delete(D,I,U={}){try{await $.del(sN(D,I),void 0,U)}catch(E){if(E instanceof J0&&E.status===404)return;throw E}}}}function Ug(_,$=process.env,D){let I=HQ(_,$,D);if(I.transport==="http")return{transport:"http",client:wQ(_,I.client)};return{transport:"sqlite",client:null}}function Jz(_){return _.toUpperCase().replace(/-/g,"_")}function Wz(_){let $=Jz(_);return{modeKeys:[`HASNA_${$}_STORAGE_MODE`,`HASNA_${$}_MODE`,`${$}_STORAGE_MODE`,`${$}_MODE`],apiUrlKeys:[`HASNA_${$}_API_URL`,`${$}_API_URL`],apiKeyKeys:[`HASNA_${$}_API_KEY`,`${$}_API_KEY`]}}function Pz(_){return`HASNA_${Jz(_)}_API_KEY_OVERRIDE`}var zz="HASNA_PROFILE";function hD(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}function h1(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}import tf from"pg";class c1 extends Error{scheme;port;constructor(_,$){super(_);this.name="KnowledgeNetworkGuardError",this.scheme=$.scheme,this.port=$.port}}function W0(_=process.env){return(_.NODE_ENV??"").trim().toLowerCase()==="test"}function Xz(_){let $=_.split(".");if($.length!==4)return!1;if(!$.every((D)=>/^\d{1,3}$/.test(D)&&Number(D)<=255))return!1;return $[0]==="127"}function yQ(_){let $=_.trim().toLowerCase();if($.length===0)return!1;if($==="localhost"||$.endsWith(".localhost"))return!0;if(Xz($))return!0;if(!$.startsWith("[")||!$.endsWith("]"))return!1;let D=$.slice(1,-1);if(D==="::1"||/^(0:){7}1$/.test(D))return!0;let I=D.split(":").pop()??"";if(/^(::ffff:|::)/.test(D)&&Xz(I))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(D)}function Yz(_){if(typeof _==="string")return _;if(_ instanceof URL)return _.href;return _.url}function Gz(_,$=process.env){if(!W0($))return;let D=Yz(_),I;try{I=new URL(D)}catch{throw new c1("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(yQ(I.hostname))return;throw new c1(`knowledge: refused a non-loopback ${I.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=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:I.protocol.replace(":",""),port:I.port})}var hQ=new Set([301,302,303,307,308]),Rz=5;function cQ(_,$){if($?.method)return $.method.toUpperCase();if(typeof _!=="string"&&!(_ instanceof URL))return _.method.toUpperCase();return"GET"}async function P0(_,$){if(Gz(_),!W0()||$?.redirect!==void 0)return fetch(_,$);let D=Yz(_),I=cQ(_,$),U=$?.body,E=await fetch(_,{...$??{},redirect:"manual"});for(let j=0;hQ.has(E.status);j++){let N=E.headers.get("location");if(!N)return E;let A=new URL(N,D).href;if(Gz(A),j>=Rz){let S=new URL(A);throw new c1(`knowledge: refused to follow more than ${Rz} 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:S.protocol.replace(":",""),port:S.port})}if(E.status===303||(E.status===301||E.status===302)&&I!=="GET"&&I!=="HEAD")I="GET",U=void 0;let O={...$??{},method:I,redirect:"manual"};if(U===void 0)delete O.body;else O.body=U;E=await fetch(A,O),D=A}return E}var cD="knowledge",Ig=Wz(cD),$6=Ig.modeKeys,d1=Ig.apiUrlKeys,m1=Ig.apiKeyKeys;function n1(_,$){return $.filter((D)=>(_[D]??"").trim().length>0)}function nD(_=process.env){let $=[...n1(_,d1),...n1(_,m1)],D=$6[0];for(let I of $6){let U=_[I]?.trim();if(!U)continue;let E;try{E=h1(U)}catch(N){let A=N instanceof Error?N.message:String(N);throw Error(`knowledge: ${I}=${U} is not a valid mode. ${A} Unset ${I} to use the default sqlite backend, or set ${I}=sqlite or ${I}=postgres.`)}let j=[];if(I!==D)j.push(`Using alias env ${I}; the canonical key is ${D}.`);if(E.mode==="sqlite"&&$.length>0)j.push(`${I}=sqlite pins the on-box store; ${$.join(", ")} are set but ignored.`);return{mode:E.mode,source:{kind:"env",name:I,value:U},pointer_env_present:$,pointer_ignored:E.mode==="sqlite"&&$.length>0,warning:j.length>0?j.join(" "):null}}return{mode:"sqlite",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 sqlite by default. Set ${D}=postgres to route reads and writes to the API, or unset those vars to silence this note.`:null}}var nQ=["postgres"],dQ=["sqlite"],Qz=new Map;function Kz(_,$,D){let I=$===hD;if(I){let U=Qz.get(_);if(U!==void 0)return U}for(let U of _)try{if($(U),I)Qz.set(_,U);return U}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 ${D} in src/knowledge-mode.ts.`)}function mQ(_=hD){return Kz(nQ,_,"SERVER_MODE_CANDIDATES")}function lQ(_=hD){return Kz(dQ,_,"LOCAL_MODE_CANDIDATES")}function iQ(_,$=hD){return _==="postgres"?mQ($):lQ($)}function Eg(_,$){return{..._,[$6[0]]:iQ($)}}class Tz extends Error{code="knowledge_mode_unset_with_api_url";constructor(_){let $=$6[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 ${$}=postgres to use the API, or ${$}=sqlite to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function Fz(_=process.env,$={}){let D=nD(_);if($.storePathOverridden)return D;if(D.source.kind!=="default")return D;let I=n1(_,d1);if(I.length===0)return D;throw new Tz(I)}function Vz(_=process.env){let $=nD(_);return{...$,store_transport:$.mode==="postgres"?"api":"local",api_key_present:n1(_,m1).length>0,network_guard_active:W0(_)}}function jg(_){return Boolean(_&&typeof _==="object"&&_.query_capability==="hasna.knowledge.bounded-query.v1")}function Bz(_){return{fetchImpl:P0,...W0(_)?{retry:!1}:{}}}var D6="notes";class z0 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"}}class gg extends Error{operation;fields;code="bounded_query_capability_required";constructor(_,$){super(`bounded_query_capability_required: the Knowledge server did not prove support for ${_} field(s): ${$.join(", ")}. Refusing to accept a possibly unfiltered response; update the server and retry.`);this.operation=_;this.fields=$;this.name="KnowledgeBoundedQueryCapabilityError"}}function tQ(_){let $={};if(_.search)$.filter=_.search,$.search=_.search;if(_.tags?.length)$.tags=_.tags;if(_.archive){if($.archive=_.archive,_.archive==="all")$.includeArchived=!0}if(_.sort)$.sort=_.sort;if(_.direction)$.direction=_.direction;if(_.limit!==void 0)$.limit=_.limit;if(_.offset!==void 0)$.offset=_.offset;return $}function oQ(_){let $=[];if(_.tags?.length)$.push("tags");if(_.sort!==void 0)$.push("sort");if(_.direction!==void 0)$.push("direction");if(_.archive==="archived")$.push("archive=archived");return $}function l1(_,$,D,I,U){let E=_??$;if(!Number.isFinite(E)||!Number.isInteger(E)||EU)throw Error(`${D} must be an integer between ${I} and ${U}.`);return E}function pQ(_){return{baseUrl:_.baseUrl,async list($={}){let D=l1($.limit,200,"limit",1,200),I=l1($.offset,0,"offset",0,1e4),U=tQ({...$,limit:D,offset:I}),E=await _.list(D6,{query:U});if(!Number.isInteger(E.total)||Number(E.total)<0)throw Error("knowledge cloud list response is missing a valid producer total.");let j=oQ($);if(j.length>0&&!jg(E.raw))throw new gg("list",j);return{items:E.items,total:Number(E.total)}},async search($){let D=l1($.limit,20,"limit",1,200),I=l1($.offset,0,"offset",0,1e4),U=await _.transport.get(`/${D6}/search`,{query:{q:$.query,archive:$.archive??"active",limit:D,offset:I}});if(!Number.isInteger(U.total)||U.total<0||!Array.isArray(U.items)||U.items.some((E)=>!E||typeof E!=="object"||!E.item||typeof E.rank!=="number"||!Number.isFinite(E.rank)))throw Error("knowledge cloud search response is missing producer rank or total evidence.");if(!jg(U))throw new gg("search",["q","rank","total"]);return{items:U.items,total:U.total}},async get($){return _.get(D6,$)},async create($){return _.create(D6,{...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})},async update($,D,I={}){try{return await _.update(D6,$,D,{...I.expectedVersion!==void 0?{headers:{"if-match":String(I.expectedVersion)}}:{}})}catch(U){if(Ng(U))return null;let E=eQ(U);if(E)throw E;throw U}},async delete($){let D=await _.get(D6,$);if(!D)return!1;return await _.delete(D6,D.id),!0},async listVersions($,D={}){try{return await _.transport.get(`/${D6}/${encodeURIComponent($)}/versions`,{query:{limit:D.limit,offset:D.offset}})}catch(I){if(Ng(I))return null;throw I}},async getVersion($,D){try{return await _.transport.get(`/${D6}/${encodeURIComponent($)}/versions/${D}`)}catch(I){if(Ng(I))return null;throw I}}}}function eQ(_){if(!_||typeof _!=="object")return null;if(_.status!==409)return null;let $=_.body,I=(typeof $==="string"?aQ($):$)??{};if(I.error!=="version_conflict")return null;return new z0(Number(I.expected??0),Number(I.current??0))}function aQ(_){try{return JSON.parse(_)}catch{return null}}function Ng(_){return Boolean(_&&typeof _==="object"&&_.status===404)}function dD(_=process.env){let $=_7(_);return $?pQ($):null}function sQ(_){let $={..._};return delete $.HOME,delete $.USERPROFILE,delete $[zz],delete $[Pz(cD)],$}function _7(_,$={}){if(nD(_).mode!=="postgres")return null;let D=$.guarded?sQ(_):_,I=Ug(cD,Eg(D,"postgres"),Bz(D));if(I.transport!=="http")return null;return I.client}function h$(_=process.env){if(nD(_).mode!=="postgres")return!1;return Ug(cD,Eg(_,"postgres"),Bz(_)).transport==="http"}async function i1(_){let D=[];for(let I=0;;I+=200){let{items:U}=await _.list({archive:"all",limit:200,offset:I});if(D.push(...U),U.length<200)break;if(I>1e5)break}return D}class Og 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=postgres plus the API url/key) and re-run.`);this.location=_;this.name="VersionHistoryUnsupportedError"}}function Ag(_,$){return _.id===$||_.short_id===$}function D7(_,$){let D=$.trim().toLowerCase();if(!D)return!0;return _.id.toLowerCase().includes(D)||_.title.toLowerCase().includes(D)||_.content.toLowerCase().includes(D)}function U7(_,$){if($.length===0)return!0;let D=new Set((_.tags??[]).map((I)=>I.toLowerCase()));return $.every((I)=>{let U=I.trim().toLowerCase(),E=I.split(",").map((j)=>j.trim().toLowerCase()).filter(Boolean);return U.length>0&&D.has(U)||E.length>0&&E.every((j)=>D.has(j))})}function I7(_,$,D,I){let U=D==="title"?_.title.localeCompare($.title):_.created_at.localeCompare($.created_at),E=U===0?_.id.localeCompare($.id):U;return I==="desc"?-E:E}function Mz(_,$,D,I,U){let E=_??$;if(!Number.isFinite(E)||!Number.isInteger(E)||EU)throw Error(`${D} must be an integer between ${I} and ${U}.`);return E}function E7(_,$){let D=$.archive??"active",I=$.sort??"created",U=$.direction??"asc",E=Mz($.limit,50,"limit",1,200),j=Mz($.offset,0,"offset",0,1e4),N=_.filter((A)=>D==="all"||(D==="archived"?A.archived===!0:A.archived!==!0));if($.search)N=N.filter((A)=>D7(A,$.search));if($.tags?.length)N=N.filter((A)=>U7(A,$.tags));return N.sort((A,O)=>I7(A,O,I,U)),{total:N.length,items:N.slice(j,j+E)}}class bz{storePath;kind="local";supportsVersions=!1;constructor(_){this.storePath=_}async listVersions(){throw new Og(this.storePath)}async getVersion(){throw new Og(this.storePath)}get location(){return this.storePath}get exists(){return $7(this.storePath)}async list(_={}){let $=U4(this.storePath);return{...E7($.items,_),exists:$.exists}}async listAll(){let _=U4(this.storePath);return{items:_.items,total:_.items.length,exists:_.exists}}async get(_){return U4(this.storePath).items.find((D)=>Ag(D,_))??null}async create(_){return y$(this.storePath,()=>{let $=uD(this.storePath),D=new Date().toISOString(),I=_.id??pP(),U={id:I,short_id:eP(I),title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:!1,created_at:D,updated_at:D,version:1};return $.items.push(U),_6(this.storePath,$),U},{createParent:!0})}async update(_,$,D={}){return y$(this.storePath,()=>{let I=uD(this.storePath),U=I.items.findIndex((N)=>Ag(N,_));if(U===-1)return null;let E=I.items[U],j=E.version??1;if(D.expectedVersion!==void 0&&D.expectedVersion!==j)throw new z0(D.expectedVersion,j);if($.title!==void 0)E.title=$.title;if($.content!==void 0)E.content=$.content;if($.url!==void 0)E.url=$.url;if($.tags!==void 0)E.tags=$.tags;if($.metadata!==void 0)E.metadata=$.metadata;if($.archived!==void 0)E.archived=$.archived;return E.updated_at=new Date().toISOString(),E.version=j+1,I.items[U]=E,_6(this.storePath,I),E},{createParent:!0})}async delete(_){return y$(this.storePath,()=>{let $=uD(this.storePath),D=$.items.length;$.items=$.items.filter((U)=>!Ag(U,_));let I=D!==$.items.length;if(I)_6(this.storePath,$);return I},{createParent:!0})}async deleteMany(_){if(_.length===0)return 0;let $=new Set(_);return y$(this.storePath,()=>{let D=uD(this.storePath),I=D.items.length;D.items=D.items.filter((E)=>!$.has(E.id)&&!(E.short_id!=null&&$.has(E.short_id)));let U=I-D.items.length;if(U>0)_6(this.storePath,D);return U},{createParent:!0})}}class Zz{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 list(_={}){let $=await this.cloud.list({search:_.search,tags:_.tags,archive:_.archive,sort:_.sort,direction:_.direction,limit:_.limit,offset:_.offset});return{items:$.items,total:$.total,exists:!0}}async listAll(){let _=await i1(this.cloud);return{items:_,total:_.length,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(_,$,D={}){return this.cloud.update(_,$,{expectedVersion:D.expectedVersion})}async delete(_){return this.cloud.delete(_)}async deleteMany(_){let $=0;for(let D of _)if(await this.cloud.delete(D))$+=1;return $}}function t1(_){let $=_.storePathOverridden?null:dD(_.env??process.env);if($)return new Zz($);return new bz(_.storePath)}function Hz(_){let $=_??"";if($==="")return[];return $.replace(/\n$/,"").split(` -`)}var Sg=5000;function j7(_,$){let D=Hz(_),I=Hz($);if(D.length>Sg||I.length>Sg)throw Error(`Refusing to line-diff ${Math.max(D.length,I.length)} lines (limit ${Sg}). Fetch the two versions and diff them with a dedicated tool.`);let U=Array.from({length:D.length+1},()=>Array(I.length+1).fill(0));for(let A=D.length-1;A>=0;A-=1)for(let O=I.length-1;O>=0;O-=1)U[A][O]=D[A]===I[O]?U[A+1][O+1]+1:Math.max(U[A+1][O],U[A][O+1]);let E=[],j=0,N=0;while(j=U[j][N+1])E.push({op:"remove",from_line:j+1,to_line:null,text:D[j]}),j+=1;else E.push({op:"add",from_line:null,to_line:N+1,text:I[N]}),N+=1;while(j{if(!N7(_[N],$[N]))D.push({field:N,from:_[N]??null,to:$[N]??null})};I("title"),I("url"),I("tags"),I("metadata"),I("archived");let U=j7(_.content,$.content),E=U.filter((N)=>N.op==="add").length,j=U.filter((N)=>N.op==="remove").length;return{identical:D.length===0&&E===0&&j===0,fields:D,content:U,added:E,removed:j}}function qz(_,$,D){let I=[`--- ${$}`,`+++ ${D}`];if(_.identical)return I.push("(no changes)"),I.join(` +`,{mode:384}),hz(_,384)}function xz(_){let $=JSON.parse(rD(_,"utf8"));if(!$||typeof $!=="object"||!Array.isArray($.items))return{store:{items:[]},skippedInvalid:0};let D={items:[]},I=0;for(let U of $.items)if(U&&typeof U==="object"&&typeof U.id==="string"&&U.id.length>0)D.items.push(U);else I+=1;return{store:D,skippedInvalid:I}}function oN(_={}){if(_.dryRun===!0)return uz(_);return y$(y1(),()=>uz(_),{createParent:!0})}function uz(_={}){let $=_.dryRun===!0,D=_.now??new Date,I=j$(f1()),U=CD(),E=I.jsonStorePath,j=L0(U),N=L0(E),O={ok:!0,dry_run:$,legacy_path:U,canonical_path:E,legacy_exists:j,canonical_existed:N,canonical_created:!1,would_create_canonical:!1,imported:0,skipped_existing:0,skipped_invalid:0,backup_path:null,report_path:null,errors:[],message:j?"Legacy global store already imported":"No legacy global store found"};if(!j)return O;let S;try{let G=xz(U);S=G.store,O.skipped_invalid=G.skippedInvalid}catch(G){return O.ok=!1,O.errors.push(`Could not read legacy store: ${G instanceof Error?G.message:String(G)}`),O.message="Legacy global store import failed",O}let L={items:[]};if(N)try{L=xz(E).store}catch(G){return O.ok=!1,O.errors.push(`Could not read canonical store: ${G instanceof Error?G.message:String(G)}`),O.message="Legacy global store import failed",O}let W=hY(L.items),g={items:[...L.items]};for(let G of S.items){if(!G?.id){O.skipped_invalid+=1;continue}if(cY(W,G)){O.skipped_existing+=1;continue}g.items.push(G);for(let J of tN(G))W.add(J);O.imported+=1}if(O.would_create_canonical=!N&&O.imported>0,O.canonical_created=!$&&O.would_create_canonical,O.message=O.imported>0?`Imported ${O.imported} legacy item(s) into canonical knowledge store`:"Legacy global store already imported",$||O.imported===0)return O;let z=`${yY(D)}-${fD().slice(0,8)}`;if(N)O.backup_path=nN(I.exportsDir,`legacy-open-knowledge-db-before-import-${z}.json`),hN(O.backup_path,L);return hN(E,g),O.report_path=nN(I.runsDir,`legacy-open-knowledge-import-${z}.json`),hN(O.report_path,O),O}function I4(_){if(!L0(_))return{exists:!1,items:[]};let $=rD(_,"utf8"),D=JSON.parse($);if(!D||!Array.isArray(D.items))return{exists:!0,items:[]};return{exists:!0,items:D.items}}function nY(_){return`${_}.lock`}var u1=1e4,dz=25,yz=120000,dY=new Int32Array(new SharedArrayBuffer(4));function pN(_){return typeof _==="object"&&_!==null&&"code"in _?String(_.code):void 0}function mz(_){let $=null;try{$=mN(nz(_),"r"),dN($)}catch{}finally{if($!==null)try{wD($)}catch{}}}var cN=new Set;function lz(_,$){u$(_);let D=nN(nz(_),`.${uY(_)}.tmp.${fD()}`),I=null;try{I=mN(D,"wx",384),iN(I,$),dN(I),wD(I),I=null,cz(D,_);try{hz(_,384)}catch{}mz(_)}catch(U){if(I!==null)try{wD(I)}catch{}try{lN(D)}catch{}throw U}}function iz(_){Atomics.wait(dY,0,0,_)}function mY(_){if(typeof _!=="number"||!Number.isInteger(_)||_<=0)return!1;try{return process.kill(_,0),!0}catch($){return pN($)!=="ESRCH"}}function tz(_,$){try{let D=rD(_,"utf8"),I=JSON.parse(D);if(typeof I.ts==="number")return $-I.ts>yz&&!mY(I.pid)}catch{}try{return $-xY(_).mtimeMs>yz}catch{return!1}}function lY(_){let $=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z"),D=`${_}.stale.${$}.${fD()}`;try{cz(_,D)}catch(I){if(pN(I)!=="ENOENT")throw I;return}}function iY(_){let $=fD(),D=`${_}.breaker`,I=Date.now();while(Date.now()-I{I=E};while(Date.now()-DEQ)return null;D=sY(_,"utf8")}catch{return null}let I=SQ(D);for(let U of $){let E=I.get(U)?.trim();if(E)return E}return null}function W0(_,$,D){if(!AQ.test(D))return;throw new yD(_,`The credential from ${$} contains characters that cannot be sent in an HTTP header (a control character or non-ASCII byte). A file written with CR-only line endings is the usual cause. Rewrite that credential file with one LF-terminated KEY=value line. The value is not shown here, and is deliberately never logged.`,[$])}var LQ=Symbol.for("nodejs.util.inspect.custom");function J0(_){let{apiKey:$,...D}=_,I={...D};return Object.defineProperty(I,"apiKey",{value:$,enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(I,LQ,{value:()=>({...D,apiKey:"[redacted]"}),enumerable:!1,writable:!1,configurable:!1}),I}function WQ(_,$){return W0(_,"explicit apiKey option",$),J0({apiKey:$,tier:"argument",source:"explicit apiKey option",deliberate:!0,deprecated:!1,diskCandidates:[],warning:null})}function D3(_,$){for(let D of $){let I=_[D]?.trim();if(I)return{key:D,value:I}}return null}var U3=Symbol.for("hasna:contracts:credentialDeprecationNotices");function JQ(){let _=globalThis,$=_[U3];if($ instanceof Set)return $;let D=new Set;return _[U3]=D,D}function PQ(_){if(typeof process<"u"&&process.stderr)process.stderr.write(`${_} +`)}function _2(_,$,D={}){let{apiKeyKeys:I}=N3(_),U=A3(_,$),E=D.apiKey?.trim();if(E)return W0(_,"the explicit apiKey argument",E),J0({apiKey:E,tier:"argument",source:"explicit apiKey argument",deliberate:!0,deprecated:!1,diskCandidates:U,warning:null});let j=aY(_),N=$[j];if(N!==void 0){let W=N.trim();if(!W)throw new yD(_,`${j} is set but empty. It is a deliberate override, so it is not resolved around: either give it a real key or unset it to fall back to the credential on disk.`,[j]);return W0(_,j,W),J0({apiKey:W,tier:"override",source:j,deliberate:!0,deprecated:!1,diskCandidates:U,warning:null})}let O=D.profile?.trim()||$[eN]?.trim();if(O){let W=D.profile?.trim()?"explicit profile argument":eN;if(!NQ.test(O))throw new yD(_,`Profile name from ${W} is not usable in a path. Use letters, digits, dot, dash, or underscore.`,[W]);let g=O3(_,$,O);for(let z of g){let G=$3(z,I);if(G)return W0(_,z,G),J0({apiKey:G,tier:"profile",source:z,deliberate:!0,deprecated:!1,diskCandidates:g,warning:null})}throw new yD(_,`Profile '${O}' (from ${W}) has no ${I[0]} for '${_}'. Looked in: ${g.join(", ")||""}. `+"A profile names WHICH identity to use, so it is never resolved around \u2014 "+`create the profile's credential file or unset ${eN}.`,g)}let S=U.map((W)=>({path:W,value:$3(W,I)})).filter((W)=>W.value!==null);if(S.length>0){let W=S[0];W0(_,W.path,W.value);let g=[...S.slice(1).filter((G)=>G.value!==W.value).map((G)=>G.path),...(()=>{let G=D3($,I);return G&&G.value!==W.value?[G.key]:[]})()],z=g.length>0?`Credential sources disagree for '${_}': ${W.path} and ${g.join(", ")} hold different keys. ${W.path} wins, because a file on `+"disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 "+"a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.":null;return J0({apiKey:W.value,tier:"disk",source:W.path,deliberate:!1,deprecated:!1,diskCandidates:U,warning:z})}let L=D3($,I);if(L){W0(_,L.key,L.value);let W=U.length>0?`Put the current key in ${U[0]} \u2014 it is re-read on every call, so rotations take effect immediately.`:"This environment has no HOME, so no credential file could be consulted at all; the disk tier is unavailable here and this process will keep using the environment snapshot.",g=`[${_}] DEPRECATED: the API key came from ${L.key} in this process's environment. Environment variables are a snapshot taken when this process started, so a shell that started before a key rotation keeps using the old key until it exits. ${W}`,z=D.onDeprecation??PQ,G=JQ();if(!G.has(_))G.add(_),z(g);return J0({apiKey:L.value,tier:"legacy-env",source:L.key,deliberate:!1,deprecated:!0,diskCandidates:U,warning:g})}return null}var V6="HASNA_FLEET_API_DOMAIN",P0="your-deployment.example",D2=/[\u0000-\u001f\u007f]/,S3=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function h1(_){if(_.length===0||_.length>253||D2.test(_)||/[^\x00-\x7f]/.test(_))return!1;return _.split(".").every(($)=>$.length<=63&&!$.startsWith("xn--")&&S3.test($))}function zQ(_){let $=_[V6];if($===void 0)return{domain:P0,source:"default",misconfigured:!0,warning:`${V6} is not set; using the non-resolving ${P0} fallback.`};let D=$.trim().toLowerCase();if(D2.test($)||!h1(D))return{domain:P0,source:V6,misconfigured:!0,warning:`${V6} is blank or invalid; using the non-resolving ${P0} fallback.`};return{domain:D,source:V6,misconfigured:!1,warning:null}}function L3(_){if(_.length>63||!S3.test(_))throw Error("App name must be one lowercase DNS label.");return _}function gQ(_,$){let D=`${L3(_)}.${$}`;if(!h1(D))throw Error("Composed cloud hostname must be a valid DNS domain");return D}function XQ(_,$){let D=L3(_),I=zQ($),U=`${D}.${I.domain}`;if(h1(U))return{baseUrl:`https://${U}`,source:I.source,misconfigured:I.misconfigured,warning:I.warning};return{baseUrl:`https://${gQ(D,P0)}`,source:I.source,misconfigured:!0,warning:`${V6} cannot form a valid composed cloud hostname for app '${D}'; using the non-resolving ${P0} fallback.`}}function aN(_,$,D={}){for(let I of $){let U=_[I],E=U?.trim();if(E)return{key:I,value:D.preserveRaw?U:E}}return null}function GQ(_){let $=/^[a-z][a-z0-9+.-]*:\/\//i.exec(_);if(!$)throw Error("API URL must be absolute.");let D=_.slice($[0].length),I=D.search(/[/?#]/),U=I===-1?D:D.slice(0,I);if(!U)throw Error("API URL must include a hostname.");return U}function I3(_){if(!/^[0-9]+$/.test(_)||_.length>1&&_.startsWith("0"))throw Error("API URL authority must contain a canonical port between 1 and 65535.");let $=Number(_);if(!Number.isSafeInteger($)||$<1||$>65535)throw Error("API URL authority must contain a canonical port between 1 and 65535.")}function RQ(_){let $;if(_.startsWith("[")){let D=_.indexOf("]");if(D===-1)throw Error("API URL authority must contain a canonical hostname.");$=_.slice(0,D+1);let I=_.slice(D+1);if(I){if(!I.startsWith(":"))throw Error("API URL authority must contain a canonical hostname and port.");I3(I.slice(1))}if(sz($.slice(1,-1))!==6)throw Error("API URL authority must contain a canonical IPv6 literal.")}else{let D=_.indexOf(":"),I=_.lastIndexOf(":");if(D!==I)throw Error("IPv6 API URL authorities must use brackets.");if(I!==-1){let N=_.slice(I+1);I3(N),$=_.slice(0,I)}else $=_;let U=sz($),j=$.split(".").every((N)=>/^(?:0x[0-9a-f]+|[0-9]+)$/i.test(N));if(U!==4&&j||U!==4&&!h1($.toLowerCase()))throw Error("API URL authority must contain a canonical ASCII hostname.")}return $.toLowerCase()}function YQ(_){return/^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(_)}function W3(_){if(D2.test(_))throw Error("API URL must not contain ASCII control characters.");let $=_.trim(),D=GQ($);if(D.includes("@")||D.includes("\\")||D.includes("%")||/[^\x00-\x7f]/.test(D))throw Error("API URL authority must be canonical ASCII without credentials.");let I=RQ(D),U=new URL($);if(U.protocol!=="http:"&&U.protocol!=="https:")throw Error("API URL must use http or https.");if(U.username||U.password)throw Error("API URL must not include credentials.");if(!U.hostname||U.hostname.endsWith("."))throw Error("API URL must include a canonical hostname.");if(U.hostname.toLowerCase()!==I)throw Error("API URL authority must not rely on parser hostname normalization.");if(U.hostname.split(".").some((j)=>j.toLowerCase().startsWith("xn--")))throw Error("API URL must not use IDN or punycode hostnames.");if(U.protocol==="http:"&&!YQ(D))throw Error("API URL may use http only for an exact loopback authority.");if(U.search||U.hash)throw Error("API URL must not include a query string or fragment.");let E=U.pathname.replace(/\/+$/,"");if(E.endsWith("/v1"))E=E.slice(0,-3);return U.pathname=`${E}/v1`,U.toString().replace(/\/+$/,"")}function QQ(_,$=process.env,D={}){let I=N3(_),U=aN($,I.modeKeys),E=aN($,I.apiUrlKeys,{preserveRaw:!0}),j=aN($,I.apiKeyKeys),N="sqlite",O="default",S=[],L;if(U)N=eY(U.value).mode,O=U.key;else if(E){if(L=_2(_,$,D.credentials),L)N="postgres",O=`${E.key}+${L.source}`}if(N==="sqlite")return{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:Boolean(j),apiKeySource:j?j.key:null,apiKeyTier:null,misconfigured:!1,warning:S.length>0?S.join(" "):null};if(L===void 0)L=_2(_,$,D.credentials);if(!L){let G=J3(_,$);return S.push(`${O}=postgres but no API key could be resolved for '${_}'. A client reaches server data over HTTP only; refusing to route. Using the local sqlite store. Looked for a credential file at ${G}, then for ${I.apiKeyKeys[0]} in the environment.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!1,apiKeySource:null,apiKeyTier:null,misconfigured:!0,warning:S.join(" ")}}if(L.warning)S.push(L.warning);let W=null,g=E?.key??($[V6]===void 0?"default":V6),z;try{if(!E)W=XQ(_,$),g=W.source;let G=E?.value??W.baseUrl;z=W3(G)}catch(G){let J=G instanceof Error?G.message:String(G);return S.push(`Invalid API URL from ${g}: ${J}. Using local store.`),{transport:"sqlite",mode:N,modeSource:O,baseUrl:null,apiUrlSource:null,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:!0,warning:S.join(" ")}}if(W?.warning)S.push(W.warning);return{transport:"http",mode:N,modeSource:O,baseUrl:z,apiUrlSource:g,apiKeyPresent:!0,apiKeySource:L.source,apiKeyTier:L.tier,misconfigured:W?.misconfigured??!1,warning:S.length>0?S.join(" "):null}}function J3(_,$){let D=A3(_,$);return D.length>0?D.join(" or "):""}class z0 extends Error{status;method;path;body;credentialSource;credentialTier;constructor(_,$,D,I,U){let E=U?`. ${U.guidance}`:"";super(`Hasna cloud request failed: ${_} ${$} -> ${D}${E}`);this.name="HasnaHttpError",this.status=D,this.method=_,this.path=$,this.body=I,this.credentialSource=U?.source??null,this.credentialTier=U?.tier??null}}function KQ(_,$){if(typeof $==="function")return $();return WQ(_,$)}function TQ(_){let $=`The API key for this request came from ${_.source}`;if(_.deliberate)return`${$} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: `+"falling back here would authenticate as a different principal than the one you named, which is exactly the failure an override exists to prevent. Rotate that key, or unset the override to use the credential on disk.";if(_.deprecated){let D=_.diskCandidates[0],I=D?`Write the CURRENT key to ${D} \u2014 that file is re-read on every call, so rotations take `+`effect immediately and in every shell. Do not simply unset ${_.source}: nothing was found on disk, so that would leave this client with no credential at all.`:"This environment has no HOME, so no credential file could be consulted; the disk tier is unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.";return`${$}, a variable in this process's environment \u2014 which is a snapshot taken when the process `+`started. A STALE SHELL is the most common cause of this error: this shell exported the key before it was rotated, and will keep sending the old one until it exits. ${I}`}return`${$}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. `+"The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution so this machine gets the current key."}var FQ=[408,425,429,500,502,503,504],VQ=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),BQ=new Set(["host",":authority","forwarded","x-forwarded-host","x-original-host"]);function E3(_,$){if(!_)return;let D=Object.keys(_).find((I)=>BQ.has(I.trim().toLowerCase()));if(D)throw Error(`Authenticated ${$} headers must not set authority header '${D}'.`)}function MQ(_,$){if(!$)return _;let D=$ instanceof URLSearchParams?$:new URLSearchParams;if(!($ instanceof URLSearchParams))for(let[U,E]of Object.entries($)){if(E===null||E===void 0)continue;if(Array.isArray(E))for(let j of E)D.append(U,String(j));else D.append(U,String(E))}let I=D.toString();if(!I)return _;return`${_}${_.includes("?")?"&":"?"}${I}`}var ZQ=(_)=>new Promise(($)=>setTimeout($,_));function HQ(_){let $=_.fetchImpl??((S,L)=>fetch(S,L)),D=W3(_.baseUrl),I=_.timeoutMs??30000,U=_.sleepImpl??ZQ,E=_.retry;function j(S){let L=S!==void 0?S:E;if(L===!1)return null;let W=L??{};return{retries:W.retries??2,baseDelayMs:W.baseDelayMs??200,maxDelayMs:W.maxDelayMs??2000,retryStatuses:W.retryStatuses??[...FQ]}}async function N(S,L,W,g,z,G){E3(_.headers,"transport"),E3(z.headers,"request");let J={"x-api-key":G.apiKey,Authorization:`Bearer ${G.apiKey}`,Accept:"application/json",..._.headers??{},...z.headers??{}};if(z.idempotencyKey)J["Idempotency-Key"]=z.idempotencyKey;let P={method:S,headers:J,redirect:"manual"};if(g!==void 0)J["Content-Type"]="application/json",P.body=JSON.stringify(g);let X=new AbortController,R=()=>X.abort();if(z.signal)if(z.signal.aborted)X.abort();else z.signal.addEventListener("abort",R,{once:!0});let T=setTimeout(()=>X.abort(),z.timeoutMs??I);P.signal=X.signal;let Y;try{Y=await $(W,P)}catch(B){let b=B instanceof Error?B:Error(String(B));if(z.signal?.aborted)return{ok:!1,retryable:!1,error:b};return{ok:!1,retryable:!0,error:b}}finally{if(clearTimeout(T),z.signal)z.signal.removeEventListener("abort",R)}let Q=await Y.text(),F=void 0;if(Q.length>0)try{F=JSON.parse(Q)}catch{F=Q}if(!Y.ok){if(Y.status>=300&&Y.status<400)return{ok:!1,retryable:!1,error:new z0(S,L,Y.status,F)};if(Y.status===401||Y.status===403)return{ok:!1,retryable:!1,error:new z0(S,L,Y.status,F,{source:G.source,tier:G.tier,guidance:TQ(G)})};let B=j(z.retry);return{ok:!1,retryable:B?B.retryStatuses.includes(Y.status):!1,error:new z0(S,L,Y.status,F)}}return{ok:!0,value:F}}async function O(S,L,W,g={}){let z=S.toUpperCase(),G=MQ(L.startsWith("/")?L:`/${L}`,g.query),J=`${D}${G}`,P=j(g.retry),X=VQ.has(z)||Boolean(g.idempotencyKey),R=P&&X?P.retries+1:1,T=KQ(_.name,_.apiKey),Y=null;for(let Q=1;Q<=R;Q++){let F=await N(z,G,J,W,g,T);if(F.ok)return F.value;if(Y=F,!(P!==null&&X&&F.retryable&&QO("GET",S,void 0,L),post:(S,L,W)=>O("POST",S,L,W),put:(S,L,W)=>O("PUT",S,L,W),patch:(S,L,W)=>O("PATCH",S,L,W),del:(S,L,W)=>O("DELETE",S,L,W)}}function bQ(_,$=process.env,D){let I=D?.credentials,U=QQ(_,$,{...I?{credentials:I}:{}});if(U.misconfigured)throw Error(U.warning??`Client for '${_}' is misconfigured for the API client.`);if(U.transport==="sqlite"||!U.baseUrl)return{transport:"sqlite",client:null,resolution:U};let E=()=>{let j=_2(_,$,I);if(!j)throw Error(`Client for '${_}' resolved to the http transport but no API key is available any more. Looked at ${J3(_,$)}, then the environment. A credential file that was removed after this client was built is the usual cause.`);return j};return{transport:"http",client:HQ({name:_,baseUrl:U.baseUrl,apiKey:E,...D?.fetchImpl?{fetchImpl:D.fetchImpl}:{},...D?.headers?{headers:D.headers}:{},...D?.timeoutMs?{timeoutMs:D.timeoutMs}:{},...D?.retry!==void 0?{retry:D.retry}:{},...D?.sleepImpl?{sleepImpl:D.sleepImpl}:{}}),resolution:U}}function $2(_){let $=_.replace(/^\/+|\/+$/g,"");if(!$)throw Error("resource must be a non-empty path segment");return`/${$}`}function sN(_,$){if($===void 0||$===null||`${$}`.length===0)throw Error("id must be a non-empty string");return`${$2(_)}/${encodeURIComponent(String($))}`}function qQ(){let _=globalThis;if(_.crypto?.randomUUID)return _.crypto.randomUUID();return`idmp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,12)}`}function kQ(_){if(Array.isArray(_))return _;if(_&&typeof _==="object"){let $=_;for(let D of["items","data","results","rows","records"])if(Array.isArray($[D]))return $[D]}return[]}function CQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["total","count","totalCount","total_count"])if(typeof $[D]==="number")return $[D]}return null}function vQ(_){if(_&&typeof _==="object"){let $=_;for(let D of["cursor","nextCursor","next_cursor","next"])if(typeof $[D]==="string")return $[D]}return null}function wQ(_,$){return{name:_,baseUrl:$.baseUrl,transport:$,async list(D,I={}){let U=await $.get($2(D),I);return{items:kQ(U),total:CQ(U),cursor:vQ(U),raw:U}},async get(D,I,U={}){try{return await $.get(sN(D,I),U)}catch(E){if(E instanceof z0&&E.status===404)return null;throw E}},async create(D,I,U={}){let{idempotencyKey:E,...j}=U;return $.post($2(D),I,{...j,idempotencyKey:E??qQ()})},async update(D,I,U,E={}){let{method:j="PATCH",idempotencyKey:N,...O}=E;return(j==="PUT"?$.put:$.patch)(sN(D,I),U,{...O,...N?{idempotencyKey:N}:{}})},async delete(D,I,U={}){try{await $.del(sN(D,I),void 0,U)}catch(E){if(E instanceof z0&&E.status===404)return;throw E}}}}function U2(_,$=process.env,D){let I=bQ(_,$,D);if(I.transport==="http")return{transport:"http",client:wQ(_,I.client)};return{transport:"sqlite",client:null}}function P3(_){return _.toUpperCase().replace(/-/g,"_")}function z3(_){let $=P3(_);return{modeKeys:[`HASNA_${$}_STORAGE_MODE`,`HASNA_${$}_MODE`,`${$}_STORAGE_MODE`,`${$}_MODE`],apiUrlKeys:[`HASNA_${$}_API_URL`,`${$}_API_URL`],apiKeyKeys:[`HASNA_${$}_API_KEY`,`${$}_API_KEY`]}}function g3(_){return`HASNA_${P3(_)}_API_KEY_OVERRIDE`}var X3="HASNA_PROFILE";function hD(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}function c1(_){let $=_.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return{mode:"sqlite"};if($==="postgres"||$==="postgresql")return{mode:"postgres"};throw Error(`Unknown storage mode '${_}'. The runtime-placement axis was removed; set sqlite for the on-box SQLite file or postgres for a PostgreSQL server (DATABASE_URL).`)}import tf from"pg";class n1 extends Error{scheme;port;constructor(_,$){super(_);this.name="KnowledgeNetworkGuardError",this.scheme=$.scheme,this.port=$.port}}function g0(_=process.env){return(_.NODE_ENV??"").trim().toLowerCase()==="test"}function G3(_){let $=_.split(".");if($.length!==4)return!1;if(!$.every((D)=>/^\d{1,3}$/.test(D)&&Number(D)<=255))return!1;return $[0]==="127"}function yQ(_){let $=_.trim().toLowerCase();if($.length===0)return!1;if($==="localhost"||$.endsWith(".localhost"))return!0;if(G3($))return!0;if(!$.startsWith("[")||!$.endsWith("]"))return!1;let D=$.slice(1,-1);if(D==="::1"||/^(0:){7}1$/.test(D))return!0;let I=D.split(":").pop()??"";if(/^(::ffff:|::)/.test(D)&&G3(I))return!0;return/^::(ffff:)?7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(D)}function Q3(_){if(typeof _==="string")return _;if(_ instanceof URL)return _.href;return _.url}function R3(_,$=process.env){if(!g0($))return;let D=Q3(_),I;try{I=new URL(D)}catch{throw new n1("knowledge: refused an outbound request with an unparseable target while NODE_ENV=test. Under test, only loopback requests are permitted.",{scheme:"unknown",port:""})}if(yQ(I.hostname))return;throw new n1(`knowledge: refused a non-loopback ${I.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=sqlite) or point the API URL at 127.0.0.1 for a hermetic test.`,{scheme:I.protocol.replace(":",""),port:I.port})}var hQ=new Set([301,302,303,307,308]),Y3=5;function cQ(_,$){if($?.method)return $.method.toUpperCase();if(typeof _!=="string"&&!(_ instanceof URL))return _.method.toUpperCase();return"GET"}async function X0(_,$){if(R3(_),!g0()||$?.redirect!==void 0)return fetch(_,$);let D=Q3(_),I=cQ(_,$),U=$?.body,E=await fetch(_,{...$??{},redirect:"manual"});for(let j=0;hQ.has(E.status);j++){let N=E.headers.get("location");if(!N)return E;let O=new URL(N,D).href;if(R3(O),j>=Y3){let L=new URL(O);throw new n1(`knowledge: refused to follow more than ${Y3} 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(E.status===303||(E.status===301||E.status===302)&&I!=="GET"&&I!=="HEAD")I="GET",U=void 0;let S={...$??{},method:I,redirect:"manual"};if(U===void 0)delete S.body;else S.body=U;E=await fetch(O,S),D=O}return E}var cD="knowledge",I2=z3(cD),$6=I2.modeKeys,m1=I2.apiUrlKeys,l1=I2.apiKeyKeys;function d1(_,$){return $.filter((D)=>(_[D]??"").trim().length>0)}function nD(_=process.env){let $=[...d1(_,m1),...d1(_,l1)],D=$6[0];for(let I of $6){let U=_[I]?.trim();if(!U)continue;let E;try{E=c1(U)}catch(N){let O=N instanceof Error?N.message:String(N);throw Error(`knowledge: ${I}=${U} is not a valid mode. ${O} Unset ${I} to use the default sqlite backend, or set ${I}=sqlite or ${I}=postgres.`)}let j=[];if(I!==D)j.push(`Using alias env ${I}; the canonical key is ${D}.`);if(E.mode==="sqlite"&&$.length>0)j.push(`${I}=sqlite pins the on-box store; ${$.join(", ")} are set but ignored.`);return{mode:E.mode,source:{kind:"env",name:I,value:U},pointer_env_present:$,pointer_ignored:E.mode==="sqlite"&&$.length>0,warning:j.length>0?j.join(" "):null}}return{mode:"sqlite",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 sqlite by default. Set ${D}=postgres to route reads and writes to the API, or unset those vars to silence this note.`:null}}var nQ=["postgres"],dQ=["sqlite"],K3=new Map;function T3(_,$,D){let I=$===hD;if(I){let U=K3.get(_);if(U!==void 0)return U}for(let U of _)try{if($(U),I)K3.set(_,U);return U}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 ${D} in src/knowledge-mode.ts.`)}function mQ(_=hD){return T3(nQ,_,"SERVER_MODE_CANDIDATES")}function lQ(_=hD){return T3(dQ,_,"LOCAL_MODE_CANDIDATES")}function iQ(_,$=hD){return _==="postgres"?mQ($):lQ($)}function E2(_,$){return{..._,[$6[0]]:iQ($)}}class F3 extends Error{code="knowledge_mode_unset_with_api_url";constructor(_){let $=$6[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 ${$}=postgres to use the API, or ${$}=sqlite to confirm you want the on-box store. Run 'knowledge mode' to see the full resolution.`);this.name="HalfConfiguredKnowledgeClientError"}}function V3(_=process.env,$={}){let D=nD(_);if($.storePathOverridden)return D;if(D.source.kind!=="default")return D;let I=d1(_,m1);if(I.length===0)return D;throw new F3(I)}function B3(_=process.env){let $=nD(_);return{...$,store_transport:$.mode==="postgres"?"api":"local",api_key_present:d1(_,l1).length>0,network_guard_active:g0(_)}}function j2(_){return Boolean(_&&typeof _==="object"&&_.query_capability==="hasna.knowledge.bounded-query.v1")}function M3(_){return{fetchImpl:X0,...g0(_)?{retry:!1}:{}}}var D6="notes";class G0 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"}}class A2 extends Error{operation;fields;code="bounded_query_capability_required";constructor(_,$){super(`bounded_query_capability_required: the Knowledge server did not prove support for ${_} field(s): ${$.join(", ")}. Refusing to accept a possibly unfiltered response; update the server and retry.`);this.operation=_;this.fields=$;this.name="KnowledgeBoundedQueryCapabilityError"}}function tQ(_){let $={};if(_.search)$.filter=_.search,$.search=_.search;if(_.tags?.length)$.tags=_.tags;if(_.archive){if($.archive=_.archive,_.archive==="all")$.includeArchived=!0}if(_.sort)$.sort=_.sort;if(_.direction)$.direction=_.direction;if(_.limit!==void 0)$.limit=_.limit;if(_.offset!==void 0)$.offset=_.offset;return $}function oQ(_){let $=[];if(_.tags?.length)$.push("tags");if(_.sort!==void 0)$.push("sort");if(_.direction!==void 0)$.push("direction");if(_.archive==="archived")$.push("archive=archived");return $}function i1(_,$,D,I,U){let E=_??$;if(!Number.isFinite(E)||!Number.isInteger(E)||EU)throw Error(`${D} must be an integer between ${I} and ${U}.`);return E}function pQ(_){return{baseUrl:_.baseUrl,async list($={}){let D=i1($.limit,200,"limit",1,200),I=i1($.offset,0,"offset",0,1e4),U=tQ({...$,limit:D,offset:I}),E=await _.list(D6,{query:U});if(!Number.isInteger(E.total)||Number(E.total)<0)throw Error("knowledge cloud list response is missing a valid producer total.");let j=oQ($);if(j.length>0&&!j2(E.raw))throw new A2("list",j);return{items:E.items,total:Number(E.total)}},async search($){let D=i1($.limit,20,"limit",1,200),I=i1($.offset,0,"offset",0,1e4),U=await _.transport.get(`/${D6}/search`,{query:{q:$.query,archive:$.archive??"active",limit:D,offset:I}});if(!Number.isInteger(U.total)||U.total<0||!Array.isArray(U.items)||U.items.some((E)=>!E||typeof E!=="object"||!E.item||typeof E.rank!=="number"||!Number.isFinite(E.rank)))throw Error("knowledge cloud search response is missing producer rank or total evidence.");if(!j2(U))throw new A2("search",["q","rank","total"]);return{items:U.items,total:U.total}},async get($){return _.get(D6,$)},async create($){return _.create(D6,{...$.id?{id:$.id}:{},title:$.title,content:$.content,url:$.url??null,tags:$.tags??[],...$.metadata?{metadata:$.metadata}:{}})},async update($,D,I={}){try{return await _.update(D6,$,D,{...I.expectedVersion!==void 0?{headers:{"if-match":String(I.expectedVersion)}}:{}})}catch(U){if(N2(U))return null;let E=eQ(U);if(E)throw E;throw U}},async delete($){let D=await _.get(D6,$);if(!D)return!1;return await _.delete(D6,D.id),!0},async listVersions($,D={}){try{return await _.transport.get(`/${D6}/${encodeURIComponent($)}/versions`,{query:{limit:D.limit,offset:D.offset}})}catch(I){if(N2(I))return null;throw I}},async getVersion($,D){try{return await _.transport.get(`/${D6}/${encodeURIComponent($)}/versions/${D}`)}catch(I){if(N2(I))return null;throw I}}}}function eQ(_){if(!_||typeof _!=="object")return null;if(_.status!==409)return null;let $=_.body,I=(typeof $==="string"?aQ($):$)??{};if(I.error!=="version_conflict")return null;return new G0(Number(I.expected??0),Number(I.current??0))}function aQ(_){try{return JSON.parse(_)}catch{return null}}function N2(_){return Boolean(_&&typeof _==="object"&&_.status===404)}function dD(_=process.env){let $=_7(_);return $?pQ($):null}function sQ(_){let $={..._};return delete $.HOME,delete $.USERPROFILE,delete $[X3],delete $[g3(cD)],$}function _7(_,$={}){if(nD(_).mode!=="postgres")return null;let D=$.guarded?sQ(_):_,I=U2(cD,E2(D,"postgres"),M3(D));if(I.transport!=="http")return null;return I.client}function h$(_=process.env){if(nD(_).mode!=="postgres")return!1;return U2(cD,E2(_,"postgres"),M3(_)).transport==="http"}async function t1(_){let D=[];for(let I=0;;I+=200){let{items:U}=await _.list({archive:"all",limit:200,offset:I});if(D.push(...U),U.length<200)break;if(I>1e5)break}return D}class S2 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=postgres plus the API url/key) and re-run.`);this.location=_;this.name="VersionHistoryUnsupportedError"}}function O2(_,$){return _.id===$||_.short_id===$}function D7(_,$){let D=$.trim().toLowerCase();if(!D)return!0;return _.id.toLowerCase().includes(D)||_.title.toLowerCase().includes(D)||_.content.toLowerCase().includes(D)}function U7(_,$){if($.length===0)return!0;let D=new Set((_.tags??[]).map((I)=>I.toLowerCase()));return $.every((I)=>{let U=I.trim().toLowerCase(),E=I.split(",").map((j)=>j.trim().toLowerCase()).filter(Boolean);return U.length>0&&D.has(U)||E.length>0&&E.every((j)=>D.has(j))})}function I7(_,$,D,I){let U=D==="title"?_.title.localeCompare($.title):_.created_at.localeCompare($.created_at),E=U===0?_.id.localeCompare($.id):U;return I==="desc"?-E:E}function Z3(_,$,D,I,U){let E=_??$;if(!Number.isFinite(E)||!Number.isInteger(E)||EU)throw Error(`${D} must be an integer between ${I} and ${U}.`);return E}function E7(_,$){let D=$.archive??"active",I=$.sort??"created",U=$.direction??"asc",E=Z3($.limit,50,"limit",1,200),j=Z3($.offset,0,"offset",0,1e4),N=_.filter((O)=>D==="all"||(D==="archived"?O.archived===!0:O.archived!==!0));if($.search)N=N.filter((O)=>D7(O,$.search));if($.tags?.length)N=N.filter((O)=>U7(O,$.tags));return N.sort((O,S)=>I7(O,S,I,U)),{total:N.length,items:N.slice(j,j+E)}}class H3{storePath;kind="local";supportsVersions=!1;constructor(_){this.storePath=_}async listVersions(){throw new S2(this.storePath)}async getVersion(){throw new S2(this.storePath)}get location(){return this.storePath}get exists(){return $7(this.storePath)}async list(_={}){let $=I4(this.storePath);return{...E7($.items,_),exists:$.exists}}async listAll(){let _=I4(this.storePath);return{items:_.items,total:_.items.length,exists:_.exists}}async get(_){return I4(this.storePath).items.find((D)=>O2(D,_))??null}async create(_){return y$(this.storePath,()=>{let $=uD(this.storePath),D=new Date().toISOString(),I=_.id??ez(),U={id:I,short_id:az(I),title:_.title,content:_.content,url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:!1,created_at:D,updated_at:D,version:1};return $.items.push(U),_6(this.storePath,$),U},{createParent:!0})}async update(_,$,D={}){return y$(this.storePath,()=>{let I=uD(this.storePath),U=I.items.findIndex((N)=>O2(N,_));if(U===-1)return null;let E=I.items[U],j=E.version??1;if(D.expectedVersion!==void 0&&D.expectedVersion!==j)throw new G0(D.expectedVersion,j);if($.title!==void 0)E.title=$.title;if($.content!==void 0)E.content=$.content;if($.url!==void 0)E.url=$.url;if($.tags!==void 0)E.tags=$.tags;if($.metadata!==void 0)E.metadata=$.metadata;if($.archived!==void 0)E.archived=$.archived;return E.updated_at=new Date().toISOString(),E.version=j+1,I.items[U]=E,_6(this.storePath,I),E},{createParent:!0})}async delete(_){return y$(this.storePath,()=>{let $=uD(this.storePath),D=$.items.length;$.items=$.items.filter((U)=>!O2(U,_));let I=D!==$.items.length;if(I)_6(this.storePath,$);return I},{createParent:!0})}async deleteMany(_){if(_.length===0)return 0;let $=new Set(_);return y$(this.storePath,()=>{let D=uD(this.storePath),I=D.items.length;D.items=D.items.filter((E)=>!$.has(E.id)&&!(E.short_id!=null&&$.has(E.short_id)));let U=I-D.items.length;if(U>0)_6(this.storePath,D);return U},{createParent:!0})}}class b3{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 list(_={}){let $=await this.cloud.list({search:_.search,tags:_.tags,archive:_.archive,sort:_.sort,direction:_.direction,limit:_.limit,offset:_.offset});return{items:$.items,total:$.total,exists:!0}}async listAll(){let _=await t1(this.cloud);return{items:_,total:_.length,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(_,$,D={}){return this.cloud.update(_,$,{expectedVersion:D.expectedVersion})}async delete(_){return this.cloud.delete(_)}async deleteMany(_){let $=0;for(let D of _)if(await this.cloud.delete(D))$+=1;return $}}function o1(_){let $=_.storePathOverridden?null:dD(_.env??process.env);if($)return new b3($);return new H3(_.storePath)}function q3(_){let $=_??"";if($==="")return[];return $.replace(/\n$/,"").split(` +`)}var L2=5000;function j7(_,$){let D=q3(_),I=q3($);if(D.length>L2||I.length>L2)throw Error(`Refusing to line-diff ${Math.max(D.length,I.length)} lines (limit ${L2}). Fetch the two versions and diff them with a dedicated tool.`);let U=Array.from({length:D.length+1},()=>Array(I.length+1).fill(0));for(let O=D.length-1;O>=0;O-=1)for(let S=I.length-1;S>=0;S-=1)U[O][S]=D[O]===I[S]?U[O+1][S+1]+1:Math.max(U[O+1][S],U[O][S+1]);let E=[],j=0,N=0;while(j=U[j][N+1])E.push({op:"remove",from_line:j+1,to_line:null,text:D[j]}),j+=1;else E.push({op:"add",from_line:null,to_line:N+1,text:I[N]}),N+=1;while(j{if(!N7(_[N],$[N]))D.push({field:N,from:_[N]??null,to:$[N]??null})};I("title"),I("url"),I("tags"),I("metadata"),I("archived");let U=j7(_.content,$.content),E=U.filter((N)=>N.op==="add").length,j=U.filter((N)=>N.op==="remove").length;return{identical:D.length===0&&E===0&&j===0,fields:D,content:U,added:E,removed:j}}function C3(_,$,D){let I=[`--- ${$}`,`+++ ${D}`];if(_.identical)return I.push("(no changes)"),I.join(` `);for(let U of _.fields)I.push(`~ ${U.field}: ${JSON.stringify(U.from)} -> ${JSON.stringify(U.to)}`);if(_.added===0&&_.removed===0){if(_.fields.length>0)I.push("(content unchanged)")}else{I.push(`@@ content +${_.added} -${_.removed} @@`);for(let U of _.content){let E=U.op==="add"?"+":U.op==="remove"?"-":" ";I.push(`${E}${U.text}`)}}return I.join(` -`)}import{Database as Cz}from"bun:sqlite";function o1(_="catalog"){if(h$()){let $=$6[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 g7="porter unicode61 remove_diacritics 2",vz=` +`)}import{Database as v3}from"bun:sqlite";function p1(_="catalog"){if(h$()){let $=$6[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 A7="porter unicode61 remove_diacritics 2",w3=` PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; @@ -266,7 +266,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (1, datetime('now')); -`,A7=` +`,O7=` DROP TABLE IF EXISTS chunks_fts; CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( @@ -279,7 +279,7 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5( INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (2, datetime('now')); -`,O7=` +`,S7=` CREATE TABLE IF NOT EXISTS audit_events ( id TEXT PRIMARY KEY, event_type TEXT NOT NULL, @@ -310,7 +310,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')); -`,S7=` +`,L7=` CREATE TABLE IF NOT EXISTS vector_index_entries ( id TEXT PRIMARY KEY, chunk_id TEXT NOT NULL REFERENCES chunks(id) ON DELETE CASCADE, @@ -341,7 +341,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')); -`,L7=` +`,W7=` CREATE TABLE IF NOT EXISTS reindex_queue ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, @@ -362,7 +362,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')); -`,wz=` +`,r3=` CREATE TABLE IF NOT EXISTS knowledge_machines ( machine_id TEXT PRIMARY KEY, hostname TEXT, @@ -477,7 +477,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')); -`,W7=` +`,P7=` 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); @@ -485,7 +485,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')); -`,P7=` +`,z7=` BEGIN; CREATE TEMP TABLE _chunks_fts_backup AS @@ -498,7 +498,7 @@ CREATE VIRTUAL TABLE chunks_fts USING fts5( text, title, source_uri, - tokenize='${g7}' + tokenize='${A7}' ); INSERT INTO chunks_fts (chunk_id, text, title, source_uri) @@ -510,7 +510,7 @@ INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now')); COMMIT; -`,z7=` +`,g7=` CREATE TABLE IF NOT EXISTS knowledge_promotion_candidates ( id TEXT PRIMARY KEY, record_kind TEXT NOT NULL, @@ -571,14 +571,14 @@ CREATE INDEX IF NOT EXISTS idx_durable_records_validity INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (10, datetime('now')); -`;function w(_){o1("opening the local knowledge.db catalog"),u$(_);let $=new Cz(_);return $.exec("PRAGMA foreign_keys = ON;"),$.exec("PRAGMA busy_timeout = 5000;"),$}function rz(_){return o1("reading the local knowledge.db catalog"),new Cz(_,{readonly:!0})}function c(_){let $=w(_);try{if($.exec(vz),r_($)<2)$.exec(A7);if(r_($)<3)$.exec(O7);if(r_($)<4)$.exec(S7);if(r_($)<5)$.exec(L7);if(r_($)<6)$.exec(wz);if(X7($))G7($);if(R7($))Y7($);if(Q7($))K7($);if(T7($))F7($);return{path:_,schema_version:r_($)}}finally{$.close()}}function r_(_){return _.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function M_(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function Lg(_){return`"${_.replaceAll('"','""')}"`}function I6(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get($);return Boolean(D)}function U6(_,$,D){if(!I6(_,$))return!1;return _.query(`PRAGMA table_info(${Lg($)})`).all().some((U)=>U.name===D)}function B6(_,$,D,I){if(!U6(_,$,D))_.exec(`ALTER TABLE ${Lg($)} ADD COLUMN ${Lg(D)} ${I};`)}function X7(_){return r_(_)<7||!U6(_,"knowledge_sync_changes","logical_clock")||!U6(_,"knowledge_sync_changes","bundle_id")||!I6(_,"knowledge_sync_table_clocks")||!I6(_,"knowledge_sync_imports")}function G7(_){if(!I6(_,"knowledge_sync_changes"))_.exec(wz);B6(_,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),B6(_,"knowledge_sync_changes","bundle_id","TEXT"),_.exec(J7)}function R7(_){return r_(_)<8||!U6(_,"wiki_pages","valid_from")||!U6(_,"wiki_pages","valid_to")||!U6(_,"wiki_pages","supersedes")||!U6(_,"wiki_pages","superseded_by")||!U6(_,"wiki_pages","confidence")||!U6(_,"wiki_pages","last_verified_at")}function Y7(_){if(!I6(_,"wiki_pages"))_.exec(vz);B6(_,"wiki_pages","valid_from","TEXT"),B6(_,"wiki_pages","valid_to","TEXT"),B6(_,"wiki_pages","supersedes","TEXT"),B6(_,"wiki_pages","superseded_by","TEXT"),B6(_,"wiki_pages","confidence","REAL"),B6(_,"wiki_pages","last_verified_at","TEXT"),_.exec(` +`;function w(_){p1("opening the local knowledge.db catalog"),u$(_);let $=new v3(_);return $.exec("PRAGMA foreign_keys = ON;"),$.exec("PRAGMA busy_timeout = 5000;"),$}function f3(_){return p1("reading the local knowledge.db catalog"),new v3(_,{readonly:!0})}function c(_){let $=w(_);try{if($.exec(w3),r_($)<2)$.exec(O7);if(r_($)<3)$.exec(S7);if(r_($)<4)$.exec(L7);if(r_($)<5)$.exec(W7);if(r_($)<6)$.exec(r3);if(X7($))G7($);if(R7($))Y7($);if(Q7($))K7($);if(T7($))F7($);return{path:_,schema_version:r_($)}}finally{$.close()}}function r_(_){return _.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0}function Z_(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function W2(_){return`"${_.replaceAll('"','""')}"`}function I6(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type IN ('table', 'virtual') AND name = ?").get($);return Boolean(D)}function U6(_,$,D){if(!I6(_,$))return!1;return _.query(`PRAGMA table_info(${W2($)})`).all().some((U)=>U.name===D)}function B6(_,$,D,I){if(!U6(_,$,D))_.exec(`ALTER TABLE ${W2($)} ADD COLUMN ${W2(D)} ${I};`)}function X7(_){return r_(_)<7||!U6(_,"knowledge_sync_changes","logical_clock")||!U6(_,"knowledge_sync_changes","bundle_id")||!I6(_,"knowledge_sync_table_clocks")||!I6(_,"knowledge_sync_imports")}function G7(_){if(!I6(_,"knowledge_sync_changes"))_.exec(r3);B6(_,"knowledge_sync_changes","logical_clock","INTEGER NOT NULL DEFAULT 0"),B6(_,"knowledge_sync_changes","bundle_id","TEXT"),_.exec(J7)}function R7(_){return r_(_)<8||!U6(_,"wiki_pages","valid_from")||!U6(_,"wiki_pages","valid_to")||!U6(_,"wiki_pages","supersedes")||!U6(_,"wiki_pages","superseded_by")||!U6(_,"wiki_pages","confidence")||!U6(_,"wiki_pages","last_verified_at")}function Y7(_){if(!I6(_,"wiki_pages"))_.exec(w3);B6(_,"wiki_pages","valid_from","TEXT"),B6(_,"wiki_pages","valid_to","TEXT"),B6(_,"wiki_pages","supersedes","TEXT"),B6(_,"wiki_pages","superseded_by","TEXT"),B6(_,"wiki_pages","confidence","REAL"),B6(_,"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(W7)}function fz(_){let $=_.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean($?.sql&&$.sql.includes("remove_diacritics"))}function Q7(_){if(!I6(_,"chunks_fts"))return!1;return r_(_)<9||!fz(_)}function K7(_){if(!I6(_,"chunks_fts"))return;if(fz(_)){_.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}_.exec(P7)}function T7(_){return r_(_)<10||!I6(_,"knowledge_promotion_candidates")||!I6(_,"durable_knowledge_records")}function F7(_){_.exec(z7)}function Jg(_){let $=w(_);try{return{schema_version:r_($),sources:M_($,"sources"),source_revisions:M_($,"source_revisions"),chunks:M_($,"chunks"),wiki_pages:M_($,"wiki_pages"),citations:M_($,"citations"),indexes:M_($,"knowledge_indexes"),runs:M_($,"runs"),run_events:M_($,"run_events"),redaction_findings:M_($,"redaction_findings"),audit_events:M_($,"audit_events"),approval_gates:M_($,"approval_gates"),storage_objects:M_($,"storage_objects"),embeddings:M_($,"chunk_embeddings"),vector_entries:M_($,"vector_index_entries"),reindex_queue:M_($,"reindex_queue"),knowledge_machines:M_($,"knowledge_machines"),sync_snapshots:M_($,"knowledge_sync_snapshots"),sync_changes:M_($,"knowledge_sync_changes"),sync_conflicts:M_($,"knowledge_sync_conflicts"),sync_table_clocks:M_($,"knowledge_sync_table_clocks"),sync_imports:M_($,"knowledge_sync_imports"),promotion_candidates:M_($,"knowledge_promotion_candidates"),durable_records:M_($,"durable_knowledge_records")}}finally{$.close()}}import{chmodSync as V7,existsSync as B7,mkdirSync as xz,readFileSync as M7,statSync as b7,writeFileSync as Z7}from"fs";import{dirname as H7,join as Wg,relative as k7,sep as q7}from"path";import{pathToFileURL as C7}from"url";function c$(_){let $=_.replace(/\\/g,"/").trim();if(!$||$.startsWith("/"))throw Error(`Invalid artifact key: ${_}`);let D=$.split("/").filter(Boolean);if(D.length===0||D.some((I)=>I==="."||I===".."))throw Error(`Invalid artifact key: ${_}`);return D.join("/")}function Pg(_,$){let D=k7(_,$);if(D.startsWith("..")||D===".."||D.startsWith(`..${q7}`))throw Error(`Artifact path escapes root: ${$}`)}function v7(_){if(!_)return;let $={};for(let[D,I]of Object.entries(_))if(typeof I==="string")$[D]=I;else if(typeof I==="number"||typeof I==="boolean")$[D]=String(I);return Object.keys($).length>0?$:void 0}class uz{root;type="local";canRead=!0;canWrite=!0;constructor(_){this.root=_;xz(_,{recursive:!0,mode:448})}async put(_){let $=c$(_.key),D=Wg(this.root,$);return Pg(this.root,D),xz(H7(D),{recursive:!0,mode:448}),Z7(D,_.body,{mode:384}),V7(D,384),{key:$,uri:C7(D).href,modified_at:b7(D).mtime.toISOString()}}async getText(_){let $=c$(_),D=Wg(this.root,$);return Pg(this.root,D),M7(D,"utf8")}async exists(_){let $=c$(_),D=Wg(this.root,$);return Pg(this.root,D),B7(D)}}class yz{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 $=c$(_),D=this.options.prefix?c$(this.options.prefix):"";return D?`${D}/${$}`:$}async put(_){let[{PutObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),I=c$(_.key),U=this.objectKey(I);return await D.send(new $({Bucket:this.options.bucket,Key:U,Body:_.body,ContentType:_.content_type,Metadata:v7(_.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:I,uri:`s3://${this.options.bucket}/${U}`,modified_at:new Date().toISOString()}}async getText(_){let[{GetObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),I=this.objectKey(_),U=await D.send(new $({Bucket:this.options.bucket,Key:I}));if(!U.Body)return"";return await U.Body.transformToString()}async exists(_){let[{HeadObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),I=this.objectKey(_);try{return await D.send(new $({Bucket:this.options.bucket,Key:I})),!0}catch(U){let E=U instanceof Error?U.name:"";if(E==="NotFound"||E==="NoSuchKey"||E==="NotFoundError")return!1;throw U}}}function zg(_,$){if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new yz({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 uz($.artifactsDir)}import{createHash as G1}from"crypto";import{spawnSync as qH}from"child_process";import{existsSync as X_,readFileSync as CH}from"fs";import{hostname as vH}from"os";import{join as g9,resolve as K9}from"path";import{createHash as ET,randomUUID as jT}from"crypto";import{createHash as c7,randomUUID as n7}from"crypto";import{existsSync as Rg,readdirSync as d7}from"fs";import{join as iz}from"path";import{pathToFileURL as m7}from"url";import{existsSync as w7,mkdirSync as r7,readFileSync as f7,unlinkSync as x7,writeFileSync as u7}from"fs";import{homedir as y7}from"os";import{dirname as h7,join as hz}from"path";var Xg="https://knowledge.md";function E6(_){let $=new URL(_);if($.protocol!=="http:"&&$.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let D=$.pathname.replace(/\/+$/,"");if(D==="/api"||D==="/api/v1")$.pathname="/";else if(D.endsWith("/api/v1"))$.pathname=D.slice(0,-7)||"/";else if(D.endsWith("/api"))$.pathname=D.slice(0,-4)||"/";return $.toString().replace(/\/+$/,"")}function e1(_=process.env){if(_.HASNA_KNOWLEDGE_AUTH_PATH)return _.HASNA_KNOWLEDGE_AUTH_PATH;let $=_.HASNA_KNOWLEDGE_AUTH_DIR??hz(y7(),".hasna","knowledge");return hz($,"auth.json")}function p1(_,$=process.env){return E6($.KNOWLEDGE_API_URL??_?.hosted?.api_url??Xg)}function cz(_=process.env){try{let $=e1(_);if(!w7($))return null;let D=JSON.parse(f7($,"utf8"));return typeof D.api_key==="string"&&D.api_key.length>0?D:null}catch{return null}}function nz(_,$=process.env){let D=e1($),I={..._,api_url:_.api_url?E6(_.api_url):void 0,created_at:_.created_at??new Date().toISOString()};return r7(h7(D),{recursive:!0,mode:448}),u7(D,`${JSON.stringify(I,null,2)} -`,{mode:384}),I}function dz(_=process.env){try{return x7(e1(_)),!0}catch{return!1}}function Gg(_=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 $=cz(_);return $?.api_key?{apiKey:$.api_key,source:"file"}:{apiKey:null,source:"none"}}function mz(_,$=process.env){let D=cz($),I=Gg($),U=$.KNOWLEDGE_API_URL?p1(_,$):D?.api_url?E6(D.api_url):p1(_,$);return{authenticated:Boolean(I.apiKey),source:I.source,api_url:U,auth_path:e1($),email:I.source==="file"?D?.email??null:null,org_id:I.source==="file"?D?.org_id??null:null,org_slug:I.source==="file"?D?.org_slug??null:null,user_id:I.source==="file"?D?.user_id??null:null,api_key_present:Boolean(I.apiKey)}}var lz=2;var tz=[{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."}],l7=["cloud.env","knowledge.db.pre-cloud-*.bak","db.json.pre-cloud-*.bak","migration-exports"];function oz(_){let $=[];if(Rg(iz(_.home,"cloud.env")))$.push("cloud.env");if(Rg(iz(_.home,"migration-exports")))$.push("migration-exports");if(Rg(_.home)){for(let D of d7(_.home))if(/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(D))$.push(D)}return $}function X0(_){let $=typeof _==="string"?Buffer.from(_):Buffer.from(_);return{hash:`sha256:${c7("sha256").update($).digest("hex")}`,size_bytes:$.byteLength}}function pz(_){return tz.find((D)=>_.startsWith(D.prefix))?.kind??"artifact"}function a1(_,$,D="global"){let I=Yg(_,$),U=_.storage.s3??null,E=U?.prefix?.replace(/^\/+|\/+$/g,"")??"",j=U?`s3://${U.bucket}/${E?`${E}/`:""}`:"",N=W_.s3.prefix.replace(/^\/+|\/+$/g,""),A=`s3://${W_.s3.bucket}/${N}/`,O=_.storage.type==="s3"&&U?.bucket===W_.s3.bucket&&(U.region??null)===W_.s3.region;return{scope:D,mode:_.mode,storage_type:_.storage.type,workspace_home:$.home,local_layout:{app_path:s$,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"?j:m7(`${$.artifactsDir}/`).href,s3:U?{bucket:U.bucket,prefix:E,region:U.region??null,profile:U.profile??null,server_side_encryption:U.server_side_encryption??null,kms_key_configured:Boolean(U.kms_key_id)}:null},canonical_example:{division:W_.division,app_type:W_.app_type,app:W_.app,env:W_.env,active:O,local_path:W_.local_path,s3:{bucket:W_.s3.bucket,region:W_.s3.region,profile:W_.s3.profile,prefix:N,uri_prefix:A,server_side_encryption:W_.s3.server_side_encryption},secrets:{env:W_.secrets.env,aws:W_.secrets.aws,s3:W_.secrets.s3,rds:W_.secrets.rds,future_rds:W_.secrets.future_rds},evidence_doc:W_.evidence_doc},hosted:{enabled:_.mode==="hosted",api_url:E6(_.hosted?.api_url??Xg),api_url_env:"KNOWLEDGE_API_URL",api_key_env:"KNOWLEDGE_API_KEY",auth_storage:"~/.hasna/knowledge/auth.json",registry_contract_version:lz,requires_hosted_account_for_local_use:!1},secret_handling:{workspace_env_files_supported:!1,forbidden_workspace_files:l7,forbidden_workspace_files_present:oz($),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:W_.secrets.env,aws:W_.secrets.aws,s3:W_.secrets.s3,rds:W_.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((S)=>["open-files","s3","file"].includes(S)),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:tz,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:I.warnings}}function Yg(_,$){let D=[],I=[],U=oz($);for(let E of U)D.push(`Forbidden Knowledge workspace file present: ${E}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`);if(!$.home.endsWith(s$))I.push(`Workspace home does not end with ${s$}: ${$.home}`);if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)D.push("storage.s3.bucket is required when storage.type is s3.");if(!_.storage.s3?.prefix)I.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root.");if(_.mode==="local")I.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)I.push("storage.s3 is configured but ignored while storage.type is local.");if(_.sources.preferred_ref!=="open-files")I.push("sources.preferred_ref should stay open-files for durable company knowledge.");if(!_.sources.allowed_schemes.includes("open-files"))D.push("sources.allowed_schemes must include open-files.");if(_.mode==="hosted"&&_.hosted?.api_url)try{E6(_.hosted.api_url)}catch{D.push("hosted.api_url must be an http(s) URL when mode is hosted.")}return{ok:D.length===0,errors:D,warnings:I}}function j6(_,$,D=new Date){let I=D.toISOString(),U=_.prepare(` + `),_.exec(P7)}function x3(_){let $=_.query("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get("chunks_fts");return Boolean($?.sql&&$.sql.includes("remove_diacritics"))}function Q7(_){if(!I6(_,"chunks_fts"))return!1;return r_(_)<9||!x3(_)}function K7(_){if(!I6(_,"chunks_fts"))return;if(x3(_)){_.exec("INSERT OR IGNORE INTO schema_versions(version, applied_at) VALUES (9, datetime('now'));");return}_.exec(z7)}function T7(_){return r_(_)<10||!I6(_,"knowledge_promotion_candidates")||!I6(_,"durable_knowledge_records")}function F7(_){_.exec(g7)}function J2(_){let $=w(_);try{return{schema_version:r_($),sources:Z_($,"sources"),source_revisions:Z_($,"source_revisions"),chunks:Z_($,"chunks"),wiki_pages:Z_($,"wiki_pages"),citations:Z_($,"citations"),indexes:Z_($,"knowledge_indexes"),runs:Z_($,"runs"),run_events:Z_($,"run_events"),redaction_findings:Z_($,"redaction_findings"),audit_events:Z_($,"audit_events"),approval_gates:Z_($,"approval_gates"),storage_objects:Z_($,"storage_objects"),embeddings:Z_($,"chunk_embeddings"),vector_entries:Z_($,"vector_index_entries"),reindex_queue:Z_($,"reindex_queue"),knowledge_machines:Z_($,"knowledge_machines"),sync_snapshots:Z_($,"knowledge_sync_snapshots"),sync_changes:Z_($,"knowledge_sync_changes"),sync_conflicts:Z_($,"knowledge_sync_conflicts"),sync_table_clocks:Z_($,"knowledge_sync_table_clocks"),sync_imports:Z_($,"knowledge_sync_imports"),promotion_candidates:Z_($,"knowledge_promotion_candidates"),durable_records:Z_($,"durable_knowledge_records")}}finally{$.close()}}import{chmodSync as V7,existsSync as B7,mkdirSync as u3,readFileSync as M7,statSync as Z7,writeFileSync as H7}from"fs";import{dirname as b7,join as P2,relative as q7,sep as k7}from"path";import{pathToFileURL as C7}from"url";function c$(_){let $=_.replace(/\\/g,"/").trim();if(!$||$.startsWith("/"))throw Error(`Invalid artifact key: ${_}`);let D=$.split("/").filter(Boolean);if(D.length===0||D.some((I)=>I==="."||I===".."))throw Error(`Invalid artifact key: ${_}`);return D.join("/")}function z2(_,$){let D=q7(_,$);if(D.startsWith("..")||D===".."||D.startsWith(`..${k7}`))throw Error(`Artifact path escapes root: ${$}`)}function v7(_){if(!_)return;let $={};for(let[D,I]of Object.entries(_))if(typeof I==="string")$[D]=I;else if(typeof I==="number"||typeof I==="boolean")$[D]=String(I);return Object.keys($).length>0?$:void 0}class y3{root;type="local";canRead=!0;canWrite=!0;constructor(_){this.root=_;u3(_,{recursive:!0,mode:448})}async put(_){let $=c$(_.key),D=P2(this.root,$);return z2(this.root,D),u3(b7(D),{recursive:!0,mode:448}),H7(D,_.body,{mode:384}),V7(D,384),{key:$,uri:C7(D).href,modified_at:Z7(D).mtime.toISOString()}}async getText(_){let $=c$(_),D=P2(this.root,$);return z2(this.root,D),M7(D,"utf8")}async exists(_){let $=c$(_),D=P2(this.root,$);return z2(this.root,D),B7(D)}}class h3{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 $=c$(_),D=this.options.prefix?c$(this.options.prefix):"";return D?`${D}/${$}`:$}async put(_){let[{PutObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),I=c$(_.key),U=this.objectKey(I);return await D.send(new $({Bucket:this.options.bucket,Key:U,Body:_.body,ContentType:_.content_type,Metadata:v7(_.metadata),ServerSideEncryption:this.options.server_side_encryption,SSEKMSKeyId:this.options.kms_key_id})),{key:I,uri:`s3://${this.options.bucket}/${U}`,modified_at:new Date().toISOString()}}async getText(_){let[{GetObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),I=this.objectKey(_),U=await D.send(new $({Bucket:this.options.bucket,Key:I}));if(!U.Body)return"";return await U.Body.transformToString()}async exists(_){let[{HeadObjectCommand:$},D]=await Promise.all([import("@aws-sdk/client-s3"),this.getClient()]),I=this.objectKey(_);try{return await D.send(new $({Bucket:this.options.bucket,Key:I})),!0}catch(U){let E=U instanceof Error?U.name:"";if(E==="NotFound"||E==="NoSuchKey"||E==="NotFoundError")return!1;throw U}}}function g2(_,$){if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)throw Error("S3 artifact storage requires storage.s3.bucket");return new h3({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 y3($.artifactsDir)}import{createHash as R1}from"crypto";import{spawnSync as kb}from"child_process";import{existsSync as X_,readFileSync as Cb}from"fs";import{hostname as vb}from"os";import{join as A9,resolve as K9}from"path";import{createHash as ET,randomUUID as jT}from"crypto";import{createHash as c7,randomUUID as n7}from"crypto";import{existsSync as R2,readdirSync as d7}from"fs";import{join as t3}from"path";import{pathToFileURL as m7}from"url";import{existsSync as w7,mkdirSync as r7,readFileSync as f7,unlinkSync as x7,writeFileSync as u7}from"fs";import{homedir as y7}from"os";import{dirname as h7,join as c3}from"path";var X2="https://knowledge.md";function E6(_){let $=new URL(_);if($.protocol!=="http:"&&$.protocol!=="https:")throw Error("Knowledge API URL must use http or https.");let D=$.pathname.replace(/\/+$/,"");if(D==="/api"||D==="/api/v1")$.pathname="/";else if(D.endsWith("/api/v1"))$.pathname=D.slice(0,-7)||"/";else if(D.endsWith("/api"))$.pathname=D.slice(0,-4)||"/";return $.toString().replace(/\/+$/,"")}function a1(_=process.env){if(_.HASNA_KNOWLEDGE_AUTH_PATH)return _.HASNA_KNOWLEDGE_AUTH_PATH;let $=_.HASNA_KNOWLEDGE_AUTH_DIR??c3(y7(),".hasna","knowledge");return c3($,"auth.json")}function e1(_,$=process.env){return E6($.KNOWLEDGE_API_URL??_?.hosted?.api_url??X2)}function n3(_=process.env){try{let $=a1(_);if(!w7($))return null;let D=JSON.parse(f7($,"utf8"));return typeof D.api_key==="string"&&D.api_key.length>0?D:null}catch{return null}}function d3(_,$=process.env){let D=a1($),I={..._,api_url:_.api_url?E6(_.api_url):void 0,created_at:_.created_at??new Date().toISOString()};return r7(h7(D),{recursive:!0,mode:448}),u7(D,`${JSON.stringify(I,null,2)} +`,{mode:384}),I}function m3(_=process.env){try{return x7(a1(_)),!0}catch{return!1}}function G2(_=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 $=n3(_);return $?.api_key?{apiKey:$.api_key,source:"file"}:{apiKey:null,source:"none"}}function l3(_,$=process.env){let D=n3($),I=G2($),U=$.KNOWLEDGE_API_URL?e1(_,$):D?.api_url?E6(D.api_url):e1(_,$);return{authenticated:Boolean(I.apiKey),source:I.source,api_url:U,auth_path:a1($),email:I.source==="file"?D?.email??null:null,org_id:I.source==="file"?D?.org_id??null:null,org_slug:I.source==="file"?D?.org_slug??null:null,user_id:I.source==="file"?D?.user_id??null:null,api_key_present:Boolean(I.apiKey)}}var i3=2;var o3=[{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."}],l7=["cloud.env","knowledge.db.pre-cloud-*.bak","db.json.pre-cloud-*.bak","migration-exports"];function p3(_){let $=[];if(R2(t3(_.home,"cloud.env")))$.push("cloud.env");if(R2(t3(_.home,"migration-exports")))$.push("migration-exports");if(R2(_.home)){for(let D of d7(_.home))if(/^(?:knowledge\.db|db\.json)\.pre-cloud-.+\.bak$/i.test(D))$.push(D)}return $}function R0(_){let $=typeof _==="string"?Buffer.from(_):Buffer.from(_);return{hash:`sha256:${c7("sha256").update($).digest("hex")}`,size_bytes:$.byteLength}}function e3(_){return o3.find((D)=>_.startsWith(D.prefix))?.kind??"artifact"}function s1(_,$,D="global"){let I=Y2(_,$),U=_.storage.s3??null,E=U?.prefix?.replace(/^\/+|\/+$/g,"")??"",j=U?`s3://${U.bucket}/${E?`${E}/`:""}`:"",N=P_.s3.prefix.replace(/^\/+|\/+$/g,""),O=`s3://${P_.s3.bucket}/${N}/`,S=_.storage.type==="s3"&&U?.bucket===P_.s3.bucket&&(U.region??null)===P_.s3.region;return{scope:D,mode:_.mode,storage_type:_.storage.type,workspace_home:$.home,local_layout:{app_path:s$,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"?j:m7(`${$.artifactsDir}/`).href,s3:U?{bucket:U.bucket,prefix:E,region:U.region??null,profile:U.profile??null,server_side_encryption:U.server_side_encryption??null,kms_key_configured:Boolean(U.kms_key_id)}:null},canonical_example:{division:P_.division,app_type:P_.app_type,app:P_.app,env:P_.env,active:S,local_path:P_.local_path,s3:{bucket:P_.s3.bucket,region:P_.s3.region,profile:P_.s3.profile,prefix:N,uri_prefix:O,server_side_encryption:P_.s3.server_side_encryption},secrets:{env:P_.secrets.env,aws:P_.secrets.aws,s3:P_.secrets.s3,rds:P_.secrets.rds,future_rds:P_.secrets.future_rds},evidence_doc:P_.evidence_doc},hosted:{enabled:_.mode==="hosted",api_url:E6(_.hosted?.api_url??X2),api_url_env:"KNOWLEDGE_API_URL",api_key_env:"KNOWLEDGE_API_KEY",auth_storage:"~/.hasna/knowledge/auth.json",registry_contract_version:i3,requires_hosted_account_for_local_use:!1},secret_handling:{workspace_env_files_supported:!1,forbidden_workspace_files:l7,forbidden_workspace_files_present:p3($),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:P_.secrets.env,aws:P_.secrets.aws,s3:P_.secrets.s3,rds:P_.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:o3,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:I.warnings}}function Y2(_,$){let D=[],I=[],U=p3($);for(let E of U)D.push(`Forbidden Knowledge workspace file present: ${E}. Move secrets to open-secrets/runtime env and remove or replace legacy backups/exports with redacted owner-only artifacts.`);if(!$.home.endsWith(s$))I.push(`Workspace home does not end with ${s$}: ${$.home}`);if(_.storage.type==="s3"){if(!_.storage.s3?.bucket)D.push("storage.s3.bucket is required when storage.type is s3.");if(!_.storage.s3?.prefix)I.push("storage.s3.prefix is empty; generated knowledge artifacts will be written at the bucket root.");if(_.mode==="local")I.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)I.push("storage.s3 is configured but ignored while storage.type is local.");if(_.sources.preferred_ref!=="open-files")I.push("sources.preferred_ref should stay open-files for durable company knowledge.");if(!_.sources.allowed_schemes.includes("open-files"))D.push("sources.allowed_schemes must include open-files.");if(_.mode==="hosted"&&_.hosted?.api_url)try{E6(_.hosted.api_url)}catch{D.push("hosted.api_url must be an http(s) URL when mode is hosted.")}return{ok:D.length===0,errors:D,warnings:I}}function j6(_,$,D=new Date){let I=D.toISOString(),U=_.prepare(` INSERT INTO storage_objects ( id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json, created_at, updated_at ) @@ -590,28 +590,28 @@ VALUES (10, datetime('now')); size_bytes = excluded.size_bytes, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);_.transaction((j)=>{for(let N of j){let A={key:N.key,...N.modified_at?{artifact_modified_at:N.modified_at}:{},...N.metadata??{}};U.run(n7(),N.uri,N.kind,N.content_type??null,N.hash??null,N.size_bytes??null,JSON.stringify(A),I,I)}})($)}function Qg(_){return["deleted","stale","invalidated","reindex_required"].includes((_??"").toLowerCase())}function M6(_){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:Qg($)}}function N$(_){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 ez(_,$){return{..._,provenance:$}}import{createHash as pK}from"crypto";import{existsSync as eK,readFileSync as aK}from"fs";import{basename as DI}from"path";import{createHash as RK}from"crypto";import{existsSync as YK,readFileSync as QK}from"fs";import{basename as KK}from"path";import{fileURLToPath as i7}from"url";function az(_,$){if(!_)throw Error($);return _}function t7(_){let D=_.slice(13).split("/").filter(Boolean),I=D[0];if(I!=="file"&&I!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let U=az(D[1],"Invalid open-files ref. Missing id.");if(I==="file"){if(D.length===2)return{kind:"open-files",uri:_,entity:I,id:U};if(D[2]==="revision"&&D[3]&&D.length===4)return{kind:"open-files",uri:_,entity:I,id:U,revision_id:decodeURIComponent(D[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let E=D.indexOf("path"),j=E>=0?decodeURIComponent(D.slice(E+1).join("/")):void 0;return{kind:"open-files",uri:_,entity:I,id:U,path:j}}function o7(_){let $=new URL(_),D=az($.hostname,"Invalid s3 ref. Missing bucket."),I=decodeURIComponent($.pathname.replace(/^\/+/,""));if(!I)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:_,bucket:D,key:I}}function p7(_){return{kind:"file",uri:_,path:i7(_)}}function e7(_){let $=new URL(_);return{kind:"web",uri:_,url:$.toString()}}function J$(_){if(_.startsWith("open-files://"))return t7(_);if(_.startsWith("s3://"))return o7(_);if(_.startsWith("file://"))return p7(_);if(_.startsWith("https://")||_.startsWith("http://"))return e7(_);throw Error(`Unsupported source ref scheme: ${_}`)}function sz(_,$=J$(_)){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function _3(_){let $=J$(_);return $.kind==="open-files"&&$.entity==="file"?$.revision_id??null:null}import{createHash as a7,randomUUID as Tg}from"crypto";import{relative as s7,resolve as D3,sep as _K}from"path";function $3(_){let $=process.env[_];return $==="1"||$==="true"||$==="yes"}function U3(_,$){let D=_,I=new Set(D.safety?.network?.allowed_s3_buckets??[]);if(_.storage.type==="s3"&&_.storage.s3?.bucket)I.add(_.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let U of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((E)=>E.trim()).filter(Boolean))I.add(U);return{mode:_.mode,allowWriteRoots:[$.home,$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir].map((U)=>D3(U)),readOnlySourceAccess:!0,network:{webSearchEnabled:D.safety?.network?.web_search_enabled??$3("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:D.safety?.network?.s3_reads_enabled??$3("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...I].sort()},redaction:{enabled:D.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:D.safety?.approvals?.generated_writes_require_approval??!0}}}function $K(_,$){let D=s7(_,$);return D===""||!D.startsWith("..")&&D!==".."&&!D.startsWith(`..${_K}`)}function N6(_,$){let D=D3(_);if(!$.allowWriteRoots.some((I)=>$K(I,D)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${_}`)}function b6(_,$){let I=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(I))throw Error(`Safety policy denied S3 bucket "${I}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function G0(_){if(!_.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var I3=[{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 u_(_,$){if($&&!$.redaction.enabled)return{text:_,findings:[]};let D=_,I=[];for(let U of I3)D=D.replace(U.regex,(E,...j)=>{let N=typeof j.at(-2)==="number"?j.at(-2):D.indexOf(E);return I.push({type:U.type,severity:U.severity,start:Math.max(0,N),end:Math.max(0,N+E.length)}),U.replacement});return{text:D,findings:I}}function DK(_){return`audit_${a7("sha256").update(`${_.event_type}\x00${_.action}\x00${_.target_uri??""}\x00${_.created_at??""}\x00${JSON.stringify(_.metadata??{})}\x00${Tg()}`).digest("hex").slice(0,24)}`}function Kg(_,$=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 D=_.slice(0,25).map((I)=>Kg(I,$+1));if(_.length>25)D.push(`[Truncated:${_.length-25} items]`);return D}if(typeof _==="object"){let D={},I=Object.entries(_).slice(0,50);for(let[E,j]of I)D[E]=Kg(j,$+1);let U=Object.keys(_).length;if(U>I.length)D.__truncated_keys=U-I.length;return D}return String(_)}function R_(_,$){let D=$.created_at??new Date().toISOString(),I=Kg($.metadata??{}),U=DK({...$,metadata:I,created_at:D});return _.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`,[U,$.event_type,$.action,$.target_uri??null,$.decision,JSON.stringify(I),D]),U}function R0(_,$){let D=$.created_at??new Date().toISOString();for(let I of $.findings)_.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`,[`redact_${Tg()}`,$.source_uri??null,$.run_id??null,I.severity,I.type,JSON.stringify({...$.metadata??{},start:I.start,end:I.end}),D]);return $.findings.length}function s1(_,$){let D=$.created_at??new Date().toISOString(),I=`approval_${Tg()}`;return _.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,$.action,$.target_uri??null,"approved",$.reason??null,$.approved_by??"local-cli",JSON.stringify($.metadata??{}),D,D]),{id:I,status:"approved"}}var UK=[{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]"}];I3.push(...UK);function IK(_,$,D){let I=_.query(`SELECT id FROM approval_gates + `);_.transaction((j)=>{for(let N of j){let O={key:N.key,...N.modified_at?{artifact_modified_at:N.modified_at}:{},...N.metadata??{}};U.run(n7(),N.uri,N.kind,N.content_type??null,N.hash??null,N.size_bytes??null,JSON.stringify(O),I,I)}})($)}function Q2(_){return["deleted","stale","invalidated","reindex_required"].includes((_??"").toLowerCase())}function M6(_){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:Q2($)}}function N$(_){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 a3(_,$){return{..._,provenance:$}}import{createHash as pK}from"crypto";import{existsSync as eK,readFileSync as aK}from"fs";import{basename as UI}from"path";import{createHash as RK}from"crypto";import{existsSync as YK,readFileSync as QK}from"fs";import{basename as KK}from"path";import{fileURLToPath as i7}from"url";function s3(_,$){if(!_)throw Error($);return _}function t7(_){let D=_.slice(13).split("/").filter(Boolean),I=D[0];if(I!=="file"&&I!=="source")throw Error("Invalid open-files ref. Expected open-files://file/, open-files://file//revision/, or open-files://source//path/.");let U=s3(D[1],"Invalid open-files ref. Missing id.");if(I==="file"){if(D.length===2)return{kind:"open-files",uri:_,entity:I,id:U};if(D[2]==="revision"&&D[3]&&D.length===4)return{kind:"open-files",uri:_,entity:I,id:U,revision_id:decodeURIComponent(D[3])};throw Error("Invalid open-files file ref. Expected open-files://file//revision/.")}let E=D.indexOf("path"),j=E>=0?decodeURIComponent(D.slice(E+1).join("/")):void 0;return{kind:"open-files",uri:_,entity:I,id:U,path:j}}function o7(_){let $=new URL(_),D=s3($.hostname,"Invalid s3 ref. Missing bucket."),I=decodeURIComponent($.pathname.replace(/^\/+/,""));if(!I)throw Error("Invalid s3 ref. Missing object key.");return{kind:"s3",uri:_,bucket:D,key:I}}function p7(_){return{kind:"file",uri:_,path:i7(_)}}function e7(_){let $=new URL(_);return{kind:"web",uri:_,url:$.toString()}}function J$(_){if(_.startsWith("open-files://"))return t7(_);if(_.startsWith("s3://"))return o7(_);if(_.startsWith("file://"))return p7(_);if(_.startsWith("https://")||_.startsWith("http://"))return e7(_);throw Error(`Unsupported source ref scheme: ${_}`)}function _g(_,$=J$(_)){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function $g(_){let $=J$(_);return $.kind==="open-files"&&$.entity==="file"?$.revision_id??null:null}import{createHash as a7,randomUUID as T2}from"crypto";import{relative as s7,resolve as Ug,sep as _K}from"path";function Dg(_){let $=process.env[_];return $==="1"||$==="true"||$==="yes"}function Ig(_,$){let D=_,I=new Set(D.safety?.network?.allowed_s3_buckets??[]);if(_.storage.type==="s3"&&_.storage.s3?.bucket)I.add(_.storage.s3.bucket);if(process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS)for(let U of process.env.HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.split(",").map((E)=>E.trim()).filter(Boolean))I.add(U);return{mode:_.mode,allowWriteRoots:[$.home,$.artifactsDir,$.cacheDir,$.exportsDir,$.indexesDir,$.logsDir,$.runsDir,$.schemasDir,$.wikiDir].map((U)=>Ug(U)),readOnlySourceAccess:!0,network:{webSearchEnabled:D.safety?.network?.web_search_enabled??Dg("HASNA_KNOWLEDGE_WEB_SEARCH"),s3ReadsEnabled:D.safety?.network?.s3_reads_enabled??Dg("HASNA_KNOWLEDGE_ALLOW_S3_READS"),allowedS3Buckets:[...I].sort()},redaction:{enabled:D.safety?.redaction?.enabled??!0},approvals:{generatedWritesRequireApproval:D.safety?.approvals?.generated_writes_require_approval??!0}}}function $K(_,$){let D=s7(_,$);return D===""||!D.startsWith("..")&&D!==".."&&!D.startsWith(`..${_K}`)}function N6(_,$){let D=Ug(_);if(!$.allowWriteRoots.some((I)=>$K(I,D)))throw Error(`Safety policy denied write outside .hasna/knowledge: ${_}`)}function Z6(_,$){let I=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(I))throw Error(`Safety policy denied S3 bucket "${I}". Add it to safety.network.allowed_s3_buckets or HASNA_KNOWLEDGE_ALLOWED_S3_BUCKETS.`)}function Y0(_){if(!_.network.webSearchEnabled)throw Error("Safety policy denied web search. Set safety.network.web_search_enabled=true or HASNA_KNOWLEDGE_WEB_SEARCH=1.")}var Eg=[{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 u_(_,$){if($&&!$.redaction.enabled)return{text:_,findings:[]};let D=_,I=[];for(let U of Eg)D=D.replace(U.regex,(E,...j)=>{let N=typeof j.at(-2)==="number"?j.at(-2):D.indexOf(E);return I.push({type:U.type,severity:U.severity,start:Math.max(0,N),end:Math.max(0,N+E.length)}),U.replacement});return{text:D,findings:I}}function DK(_){return`audit_${a7("sha256").update(`${_.event_type}\x00${_.action}\x00${_.target_uri??""}\x00${_.created_at??""}\x00${JSON.stringify(_.metadata??{})}\x00${T2()}`).digest("hex").slice(0,24)}`}function K2(_,$=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 D=_.slice(0,25).map((I)=>K2(I,$+1));if(_.length>25)D.push(`[Truncated:${_.length-25} items]`);return D}if(typeof _==="object"){let D={},I=Object.entries(_).slice(0,50);for(let[E,j]of I)D[E]=K2(j,$+1);let U=Object.keys(_).length;if(U>I.length)D.__truncated_keys=U-I.length;return D}return String(_)}function R_(_,$){let D=$.created_at??new Date().toISOString(),I=K2($.metadata??{}),U=DK({...$,metadata:I,created_at:D});return _.run(`INSERT INTO audit_events (id, event_type, action, target_uri, decision, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`,[U,$.event_type,$.action,$.target_uri??null,$.decision,JSON.stringify(I),D]),U}function Q0(_,$){let D=$.created_at??new Date().toISOString();for(let I of $.findings)_.run(`INSERT INTO redaction_findings (id, source_uri, run_id, severity, finding_type, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`,[`redact_${T2()}`,$.source_uri??null,$.run_id??null,I.severity,I.type,JSON.stringify({...$.metadata??{},start:I.start,end:I.end}),D]);return $.findings.length}function _I(_,$){let D=$.created_at??new Date().toISOString(),I=`approval_${T2()}`;return _.run(`INSERT INTO approval_gates (id, action, target_uri, status, reason, approved_by, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,$.action,$.target_uri??null,"approved",$.reason??null,$.approved_by??"local-cli",JSON.stringify($.metadata??{}),D,D]),{id:I,status:"approved"}}var UK=[{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]"}];Eg.push(...UK);function IK(_,$,D){let I=_.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($,D??null,D??null);return Boolean(I)}function E3(_,$,D,I){let U=D==="generated_write"&&$.approvals.generatedWritesRequireApproval,E=!U||IK(_,D,I);return{action:D,target_uri:I??null,approval_required:U,approved:E,decision:E?"allow":"requires_approval"}}import{createHash as EK}from"crypto";import{realpathSync as jK}from"fs";import{homedir as NK,tmpdir as gK}from"os";var I4=String.raw`[^\s"'<>),\]}]`,Vg=String.raw`[^/\\\s"'<>]+`,g3=/file:\/\/[^\s"'<>),\]}]+/gi,AK=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,A3=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,O3=new RegExp(String.raw`/(?:home|Users)/${Vg}/(?:workspace|Workspace)/${I4}*`,"g"),OK=[new RegExp(String.raw`/(?:home|Users)/${Vg}(?:/${I4}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${I4}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${I4}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,L3=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,SK=new Set(["content_base64"]);function LK(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function JK(_){return _.length>=4&&_!=="/"&&!/^[A-Za-z]:[\\/]?$/.test(_)}var j3=null,Fg=[];function WK(){let _=new Set;for(let D of[NK(),gK()]){if(!D)continue;_.add(D);try{_.add(jK(D))}catch{}}let $=[..._].sort().join("\x00");if($===j3)return Fg;return j3=$,Fg=[..._].filter(JK).sort((D,I)=>I.length-D.length).map((D)=>new RegExp(`${LK(D)}(?:[/\\\\]${I4}*)?`,"g")),Fg}function W$(_){return EK("sha256").update(_).digest("hex").slice(0,12)}function PK(_){return _.length<=80?_:`${_.slice(0,77)}...`}function N3(_){return/(?:^|\/)\.hasna(?:\/|$)/i.test(_)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test(_)||/\bmigration-exports\//i.test(_)}function zK(_,$,D,I){for(let U of _.matchAll(g3)){let E=U[0];if(!D.allowFileSourceRefs||N3(E))I.push({type:N3(E)?"private_file_uri":"local_file_uri",severity:"high",path:$,preview:PK(E.replace(/^file:\/\/.*/,`[redacted:file-uri:${W$(E)}]`))})}for(let U of _.matchAll(A3))I.push({type:"private_hasna_path",severity:"high",path:$,preview:`[redacted:.hasna:${W$(U[0])}]`});for(let U of _.matchAll(S3))I.push({type:U[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:$,preview:`[redacted:${W$(U[0])}]`});for(let U of _.matchAll(L3))I.push({type:"database_url",severity:"high",path:$,preview:`[redacted:database-url:${W$(U[0])}]`});if(!D.allowPrivateWorkspaceRefs)for(let U of _.matchAll(O3))I.push({type:"private_workspace_path",severity:"medium",path:$,preview:`[redacted:workspace:${W$(U[0])}]`})}function XK(_,$={},D="$"){let I=[],U=(E,j)=>{if(typeof E==="string"){zK(E,j,$,I);return}if(!E||typeof E!=="object")return;if(Array.isArray(E)){E.forEach((N,A)=>U(N,`${j}[${A}]`));return}for(let[N,A]of Object.entries(E))U(A,`${j}.${N}`)};return U(_,D),I}function E4(_,$={}){let D=XK(_,$);if(D.length===0)return;let I=new Map;for(let E of D)I.set(E.type,(I.get(E.type)??0)+1);let U=[...I.entries()].map(([E,j])=>`${E}:${j}`).join(", ");throw Error(`Knowledge private-ref lint failed (${U}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function GK(_){let $=u_(_).text.replace(L3,(D)=>`[REDACTED:database-url:${W$(D)}]`).replace(g3,(D)=>`[REDACTED:local-file-uri:${W$(D)}]`).replace(AK,(D)=>`[REDACTED:local-hasna-path:${W$(D)}]`).replace(O3,(D)=>`[REDACTED:private-workspace:${W$(D)}]`);for(let D of[...WK(),...OK])$=$.replace(D,(I)=>`[REDACTED:local-path:${W$(I)}]`);return $.replace(A3,(D)=>`[REDACTED:hasna-path:${W$(D)}]`).replace(S3,(D)=>`[REDACTED:private-artifact:${W$(D)}]`)}function F_(_){if(typeof _==="string")return GK(_);if(!_||typeof _!=="object")return _;if(Array.isArray(_))return _.map((D)=>F_(D));let $={};for(let[D,I]of Object.entries(_))$[D]=SK.has(D)?I:F_(I);return $}var TK=20971520,J3=1e4,FK=10;function Mg(_,$){return`${_}_${RK("sha256").update($).digest("hex").slice(0,20)}`}function j4(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function A_(_){return typeof _==="string"&&_.length>0?_:void 0}function VK(_){return typeof _==="number"&&Number.isFinite(_)?_:void 0}function BK(_){let $=A_(_.source_ref)??A_(_.source_uri)??A_(_.uri);if($)return $;let D=A_(_.file_id);if(D){let E=A_(_.revision_id)??A_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return E?`${j}/revision/${encodeURIComponent(E)}`:j}let I=A_(_.source_id),U=A_(_.path);if(I&&U)return`open-files://source/${encodeURIComponent(I)}/path/${encodeURIComponent(U)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function MK(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function bK(_){let $=A_(_.extracted_text)??A_(_.text)??A_(_.content_text)??A_(_.markdown);if($!==void 0)return $;let D=_.content;return typeof D==="string"?D:null}function ZK(_){let $=A_(_.extracted_text_ref)??A_(_.extracted_text_uri)??A_(_.text_ref);if($)return $;let D=j4(_.content);return A_(D?.extracted_text_ref)??A_(D?.extracted_text_uri)??null}function HK(_){let $=A_(_.path);return A_(_.title)??A_(_.name)??($?KK($):null)}function kK(_){return A_(_.hash)??A_(_.checksum)??A_(_.sha256)??null}var W3=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 P3(_){return _.toLowerCase().replace(/[\s-]+/g,"_")}function Bg(_){if(Array.isArray(_))return _.map((I)=>Bg(I));let $=j4(_);if(!$)return _;let D={};for(let[I,U]of Object.entries($)){if(W3.has(P3(I)))continue;D[I]=Bg(U)}return D}function qK(_,$,D){return A_(_.revision_id)??A_(_.revision)??A_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??A_(_.updated_at)??"current"}function CK(_,$){let D={};for(let[I,U]of Object.entries(_)){if(W3.has(P3(I)))continue;D[I]=F_(Bg(U))}return D.source_ref=$.sourceRef,D.source_uri=$.sourceUri,D.status=$.status,D}function vK(_,$,D={}){let I=BK(_);E4(I,{allowFileSourceRefs:D.allowFileSourceRefs===!0});let U=J$(I),E=MK(I,U),j=kK(_),N=A_(_.status)??"active";return{raw:_,sourceRef:I,sourceUri:E,kind:U.kind,title:HK(_),revision:qK(_,U,j),hash:j,extractedTextUri:ZK(_),text:bK(_),metadata:CK(_,{sourceRef:I,sourceUri:E,status:N}),acl:_.permissions??_.acl??{},status:N,updatedAt:A_(_.updated_at)??$}}function wK(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Manifest array parse failed.");return D.map((I)=>{let U=j4(I);if(!U)throw Error("Manifest array entries must be objects.");return U})}if($.startsWith("{"))try{let D=JSON.parse($),I=j4(D);if(!I)throw Error("Manifest object parse failed.");if(Array.isArray(I.items))return I.items.map((U)=>{let E=j4(U);if(!E)throw Error("Manifest items entries must be objects.");return E});if("source_ref"in I||"source_uri"in I||"file_id"in I)return[I]}catch(D){let I=$.split(/\r?\n/).filter((U)=>U.trim().length>0);if(I.length<=1)throw D;return I.map((U)=>{let E=j4(JSON.parse(U));if(!E)throw Error("Manifest JSONL entries must be objects.");return E})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let I=j4(JSON.parse(D));if(!I)throw Error("Manifest JSONL entries must be objects.");return I})}async function rK(_,$,D){let I=new URL(_),U=I.hostname,E=decodeURIComponent(I.pathname.replace(/^\/+/,""));if(!U||!E)throw Error(`Invalid S3 manifest URI: ${_}`);if(D)b6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:A}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),O=$?.storage.type==="s3"&&$.storage.s3?.bucket===U?$.storage.s3:void 0,L=await new j({region:O?.region,credentials:O?.profile?A({profile:O.profile}):void 0,maxAttempts:O?.max_attempts}).send(new N({Bucket:U,Key:E}));if(!L.Body)return"";return await L.Body.transformToString()}async function fK(_,$,D,I=TK){let U=_.startsWith("s3://")?await rK(_,$,D):(()=>{if(!YK(_))throw Error(`Manifest not found: ${_}`);return QK(_,"utf8")})(),E=Buffer.byteLength(U);if(E>I)throw Error(`Manifest input is too large: ${E} bytes exceeds ${I} byte limit.`);return U}function xK(_,$,D){let I=_.replace(/\r\n/g,` -`);if(!I.trim())return[];let U=[],E=0;while(E),\]}]`,V2=String.raw`[^/\\\s"'<>]+`,Og=/file:\/\/[^\s"'<>),\]}]+/gi,OK=/\/[^\s"'<>),\]}]*\.hasna\/[^\s"'<>),\]}]*/g,Sg=/(?:~|\/(?:home|Users)\/[^/\s"'<>]+)?\/?\.hasna(?:\/[^\s"'<>),\]}]*)?/gi,Lg=new RegExp(String.raw`/(?:home|Users)/${V2}/(?:workspace|Workspace)/${E4}*`,"g"),SK=[new RegExp(String.raw`/(?:home|Users)/${V2}(?:/${E4}*)?`,"g"),new RegExp(String.raw`(?:/private)?/var/(?:folders|tmp)/${E4}+`,"g"),new RegExp(String.raw`(?:/private)?/tmp/${E4}+`,"g"),new RegExp(String.raw`(?),\]}]+)\b/gi,Jg=/\b(?:postgres(?:ql)?|mysql|mariadb):\/\/[^\s"'<>),\]}]+/gi,LK=new Set(["content_base64"]);function WK(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function JK(_){return _.length>=4&&_!=="/"&&!/^[A-Za-z]:[\\/]?$/.test(_)}var Ng=null,F2=[];function PK(){let _=new Set;for(let D of[NK(),AK()]){if(!D)continue;_.add(D);try{_.add(jK(D))}catch{}}let $=[..._].sort().join("\x00");if($===Ng)return F2;return Ng=$,F2=[..._].filter(JK).sort((D,I)=>I.length-D.length).map((D)=>new RegExp(`${WK(D)}(?:[/\\\\]${E4}*)?`,"g")),F2}function P$(_){return EK("sha256").update(_).digest("hex").slice(0,12)}function zK(_){return _.length<=80?_:`${_.slice(0,77)}...`}function Ag(_){return/(?:^|\/)\.hasna(?:\/|$)/i.test(_)||/\b(?:knowledge\.db|db\.json|cloud\.env)\b/i.test(_)||/\bmigration-exports\//i.test(_)}function gK(_,$,D,I){for(let U of _.matchAll(Og)){let E=U[0];if(!D.allowFileSourceRefs||Ag(E))I.push({type:Ag(E)?"private_file_uri":"local_file_uri",severity:"high",path:$,preview:zK(E.replace(/^file:\/\/.*/,`[redacted:file-uri:${P$(E)}]`))})}for(let U of _.matchAll(Sg))I.push({type:"private_hasna_path",severity:"high",path:$,preview:`[redacted:.hasna:${P$(U[0])}]`});for(let U of _.matchAll(Wg))I.push({type:U[0].toLowerCase()==="cloud.env"?"workspace_env_file":"raw_database_or_export_ref",severity:"high",path:$,preview:`[redacted:${P$(U[0])}]`});for(let U of _.matchAll(Jg))I.push({type:"database_url",severity:"high",path:$,preview:`[redacted:database-url:${P$(U[0])}]`});if(!D.allowPrivateWorkspaceRefs)for(let U of _.matchAll(Lg))I.push({type:"private_workspace_path",severity:"medium",path:$,preview:`[redacted:workspace:${P$(U[0])}]`})}function XK(_,$={},D="$"){let I=[],U=(E,j)=>{if(typeof E==="string"){gK(E,j,$,I);return}if(!E||typeof E!=="object")return;if(Array.isArray(E)){E.forEach((N,O)=>U(N,`${j}[${O}]`));return}for(let[N,O]of Object.entries(E))U(O,`${j}.${N}`)};return U(_,D),I}function j4(_,$={}){let D=XK(_,$);if(D.length===0)return;let I=new Map;for(let E of D)I.set(E.type,(I.get(E.type)??0)+1);let U=[...I.entries()].map(([E,j])=>`${E}:${j}`).join(", ");throw Error(`Knowledge private-ref lint failed (${U}). Store open-files/s3 refs or approved runtime secret refs instead of private .hasna, file://, raw DB/export, or cloud.env refs.`)}function GK(_){let $=u_(_).text.replace(Jg,(D)=>`[REDACTED:database-url:${P$(D)}]`).replace(Og,(D)=>`[REDACTED:local-file-uri:${P$(D)}]`).replace(OK,(D)=>`[REDACTED:local-hasna-path:${P$(D)}]`).replace(Lg,(D)=>`[REDACTED:private-workspace:${P$(D)}]`);for(let D of[...PK(),...SK])$=$.replace(D,(I)=>`[REDACTED:local-path:${P$(I)}]`);return $.replace(Sg,(D)=>`[REDACTED:hasna-path:${P$(D)}]`).replace(Wg,(D)=>`[REDACTED:private-artifact:${P$(D)}]`)}function F_(_){if(typeof _==="string")return GK(_);if(!_||typeof _!=="object")return _;if(Array.isArray(_))return _.map((D)=>F_(D));let $={};for(let[D,I]of Object.entries(_))$[D]=LK.has(D)?I:F_(I);return $}var TK=20971520,Pg=1e4,FK=10;function M2(_,$){return`${_}_${RK("sha256").update($).digest("hex").slice(0,20)}`}function N4(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function O_(_){return typeof _==="string"&&_.length>0?_:void 0}function VK(_){return typeof _==="number"&&Number.isFinite(_)?_:void 0}function BK(_){let $=O_(_.source_ref)??O_(_.source_uri)??O_(_.uri);if($)return $;let D=O_(_.file_id);if(D){let E=O_(_.revision_id)??O_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return E?`${j}/revision/${encodeURIComponent(E)}`:j}let I=O_(_.source_id),U=O_(_.path);if(I&&U)return`open-files://source/${encodeURIComponent(I)}/path/${encodeURIComponent(U)}`;throw Error("Manifest item is missing source_ref, file_id, or source_id/path.")}function MK(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function ZK(_){let $=O_(_.extracted_text)??O_(_.text)??O_(_.content_text)??O_(_.markdown);if($!==void 0)return $;let D=_.content;return typeof D==="string"?D:null}function HK(_){let $=O_(_.extracted_text_ref)??O_(_.extracted_text_uri)??O_(_.text_ref);if($)return $;let D=N4(_.content);return O_(D?.extracted_text_ref)??O_(D?.extracted_text_uri)??null}function bK(_){let $=O_(_.path);return O_(_.title)??O_(_.name)??($?KK($):null)}function qK(_){return O_(_.hash)??O_(_.checksum)??O_(_.sha256)??null}var zg=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 gg(_){return _.toLowerCase().replace(/[\s-]+/g,"_")}function B2(_){if(Array.isArray(_))return _.map((I)=>B2(I));let $=N4(_);if(!$)return _;let D={};for(let[I,U]of Object.entries($)){if(zg.has(gg(I)))continue;D[I]=B2(U)}return D}function kK(_,$,D){return O_(_.revision_id)??O_(_.revision)??O_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??O_(_.updated_at)??"current"}function CK(_,$){let D={};for(let[I,U]of Object.entries(_)){if(zg.has(gg(I)))continue;D[I]=F_(B2(U))}return D.source_ref=$.sourceRef,D.source_uri=$.sourceUri,D.status=$.status,D}function vK(_,$,D={}){let I=BK(_);j4(I,{allowFileSourceRefs:D.allowFileSourceRefs===!0});let U=J$(I),E=MK(I,U),j=qK(_),N=O_(_.status)??"active";return{raw:_,sourceRef:I,sourceUri:E,kind:U.kind,title:bK(_),revision:kK(_,U,j),hash:j,extractedTextUri:HK(_),text:ZK(_),metadata:CK(_,{sourceRef:I,sourceUri:E,status:N}),acl:_.permissions??_.acl??{},status:N,updatedAt:O_(_.updated_at)??$}}function wK(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Manifest array parse failed.");return D.map((I)=>{let U=N4(I);if(!U)throw Error("Manifest array entries must be objects.");return U})}if($.startsWith("{"))try{let D=JSON.parse($),I=N4(D);if(!I)throw Error("Manifest object parse failed.");if(Array.isArray(I.items))return I.items.map((U)=>{let E=N4(U);if(!E)throw Error("Manifest items entries must be objects.");return E});if("source_ref"in I||"source_uri"in I||"file_id"in I)return[I]}catch(D){let I=$.split(/\r?\n/).filter((U)=>U.trim().length>0);if(I.length<=1)throw D;return I.map((U)=>{let E=N4(JSON.parse(U));if(!E)throw Error("Manifest JSONL entries must be objects.");return E})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let I=N4(JSON.parse(D));if(!I)throw Error("Manifest JSONL entries must be objects.");return I})}async function rK(_,$,D){let I=new URL(_),U=I.hostname,E=decodeURIComponent(I.pathname.replace(/^\/+/,""));if(!U||!E)throw Error(`Invalid S3 manifest URI: ${_}`);if(D)Z6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),S=$?.storage.type==="s3"&&$.storage.s3?.bucket===U?$.storage.s3:void 0,W=await new j({region:S?.region,credentials:S?.profile?O({profile:S.profile}):void 0,maxAttempts:S?.max_attempts}).send(new N({Bucket:U,Key:E}));if(!W.Body)return"";return await W.Body.transformToString()}async function fK(_,$,D,I=TK){let U=_.startsWith("s3://")?await rK(_,$,D):(()=>{if(!YK(_))throw Error(`Manifest not found: ${_}`);return QK(_,"utf8")})(),E=Buffer.byteLength(U);if(E>I)throw Error(`Manifest input is too large: ${E} bytes exceeds ${I} byte limit.`);return U}function xK(_,$,D){let I=_.replace(/\r\n/g,` +`);if(!I.trim())return[];let U=[],E=0;while(EE+Math.floor($*0.5))N=L+(L===O?2:1)}let A=I.slice(E,N).trim();if(A)U.push({ordinal:U.length,text:A,startOffset:E,endOffset:N});if(N>=I.length)break;E=Math.max(0,N-D)}return U}function uK(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function yK(_,$){let D=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($);for(let I of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[I.id]);return _.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]),D.length}function hK(_,$,D){let I=Mg("src",$.sourceUri);_.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) +`,j),L=I.lastIndexOf(". ",j),W=Math.max(S,L);if(W>E+Math.floor($*0.5))N=W+(W===S?2:1)}let O=I.slice(E,N).trim();if(O)U.push({ordinal:U.length,text:O,startOffset:E,endOffset:N});if(N>=I.length)break;E=Math.max(0,N-D)}return U}function uK(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function yK(_,$){let D=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($);for(let I of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[I.id]);return _.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]),D.length}function hK(_,$,D){let I=M2("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`,[I,$.sourceUri,$.kind,$.title,JSON.stringify($.metadata),JSON.stringify($.acl??{}),D,$.updatedAt]);let U=_.query("SELECT id FROM sources WHERE uri = ?").get($.sourceUri);if(!U)throw Error(`Failed to upsert source: ${$.sourceUri}`);return U.id}function cK(_,$,D,I){let U=Mg("rev",`${$}\x00${D.revision}`);_.run(`INSERT INTO source_revisions (id, source_id, revision, hash, extracted_text_uri, metadata_json, created_at) + updated_at = excluded.updated_at`,[I,$.sourceUri,$.kind,$.title,JSON.stringify($.metadata),JSON.stringify($.acl??{}),D,$.updatedAt]);let U=_.query("SELECT id FROM sources WHERE uri = ?").get($.sourceUri);if(!U)throw Error(`Failed to upsert source: ${$.sourceUri}`);return U.id}function cK(_,$,D,I){let U=M2("rev",`${$}\x00${D.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`,[U,$,D.revision,D.hash,D.extractedTextUri,JSON.stringify(D.metadata),I]);let E=_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get($,D.revision);if(!E)throw Error(`Failed to upsert source revision: ${D.sourceRef}`);return E.id}function nK(_,$,D,I,U,E,j){if(!D.text||D.status.toLowerCase()==="deleted")return{chunksInserted:0,redactions:0};let N=u_(D.text,j);if(N.findings.length>0)R0(_,{source_uri:D.sourceUri,findings:N.findings,metadata:{source_ref:D.sourceRef,revision:D.revision},created_at:I}),R_(_,{event_type:"redaction",action:"source_text_redact",target_uri:D.sourceUri,decision:"redacted",metadata:{findings:N.findings.length,source_ref:D.sourceRef,revision:D.revision},created_at:I});let A=xK(N.text,U,E);for(let O of A){let S=Mg("chk",`${$}\x00${O.ordinal}\x00${O.text}`),L=M6({source_ref:D.sourceRef,source_uri:D.sourceUri,source_kind:D.kind,source_revision_id:$,revision:D.revision,hash:D.hash,chunk_id:S,start_offset:O.startOffset,end_offset:O.endOffset,status:D.status,resolver:"open-files-read-only"}),P=ez({source_ref:D.sourceRef,source_uri:D.sourceUri,source_kind:D.kind,source_revision_id:$,revision:D.revision,hash:D.hash,status:D.status,path:A_(D.raw.path)??null,mime:A_(D.raw.mime)??A_(D.raw.content_type)??null,size:VK(D.raw.size)??null},L);_.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[S,$,"source",O.ordinal,O.text,uK(O.text),O.startOffset,O.endOffset,JSON.stringify(P),I]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[S,O.text,D.title??"",D.sourceUri])}return{chunksInserted:A.length,redactions:N.findings.length}}async function z3(_){let $=_.now??new Date;if(_.safetyPolicy)N6(_.dbPath,_.safetyPolicy);c(_.dbPath);let D=await fK(_.input,_.config,_.safetyPolicy,_.maxInputBytes),I=wK(D),U=_.maxItems??J3;if(I.length>U)throw Error(`Manifest contains too many items: ${I.length} exceeds ${U} item limit.`);return N4({dbPath:_.dbPath,items:I,sourceLabel:_.input,allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")===!0,safetyPolicy:_.safetyPolicy,now:$,maxChunkChars:_.maxChunkChars,chunkOverlapChars:_.chunkOverlapChars,maxItems:_.maxItems})}async function N4(_){let $=(_.now??new Date).toISOString(),D=_.maxChunkChars??4000,I=_.chunkOverlapChars??200,U=_.maxItems??J3;if(D<500)throw Error("maxChunkChars must be at least 500.");if(I<0||I>=D)throw Error("chunkOverlapChars must be less than maxChunkChars.");if(_.items.length>U)throw Error(`Manifest contains too many items: ${_.items.length} exceeds ${U} item limit.`);if(_.safetyPolicy)N6(_.dbPath,_.safetyPolicy);c(_.dbPath);let E=w(_.dbPath);try{return E.transaction(()=>{let N=new Set,A=new Set,O=0,S=0,L=0,P=0,z=[];R_(E,{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 G of _.items){let J=vK(G,$,{allowFileSourceRefs:_.allowFileSourceRefs});if(z.length0)return I}return null}function X3(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return null}function dK(_,$){let D=_.mode;if(typeof D==="string"&&D!=="read_only")throw Error(`Source resolver denied ${$}. Permission mode is ${D}, expected read_only.`);let I=_.denied_purposes;if(Array.isArray(I)&&I.includes($))throw Error(`Source resolver denied ${$}. Purpose is explicitly denied.`);let U=_.allowed_purposes;if(Array.isArray(U)&&U.length>0&&!U.includes($))throw Error(`Source resolver denied ${$}. Allowed purposes: ${U.join(", ")}`)}function mK(_,$,D){if(!$)return D;try{let I=J$(_);if(I.kind==="open-files"&&I.entity==="file")return`${_}/revision/${encodeURIComponent($.revision)}`}catch{return D}return D}function lK(_,$,D){return _.query(`SELECT id, uri, kind, title, metadata_json, acl_json, updated_at + metadata_json = excluded.metadata_json`,[U,$,D.revision,D.hash,D.extractedTextUri,JSON.stringify(D.metadata),I]);let E=_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get($,D.revision);if(!E)throw Error(`Failed to upsert source revision: ${D.sourceRef}`);return E.id}function nK(_,$,D,I,U,E,j){if(!D.text||D.status.toLowerCase()==="deleted")return{chunksInserted:0,redactions:0};let N=u_(D.text,j);if(N.findings.length>0)Q0(_,{source_uri:D.sourceUri,findings:N.findings,metadata:{source_ref:D.sourceRef,revision:D.revision},created_at:I}),R_(_,{event_type:"redaction",action:"source_text_redact",target_uri:D.sourceUri,decision:"redacted",metadata:{findings:N.findings.length,source_ref:D.sourceRef,revision:D.revision},created_at:I});let O=xK(N.text,U,E);for(let S of O){let L=M2("chk",`${$}\x00${S.ordinal}\x00${S.text}`),W=M6({source_ref:D.sourceRef,source_uri:D.sourceUri,source_kind:D.kind,source_revision_id:$,revision:D.revision,hash:D.hash,chunk_id:L,start_offset:S.startOffset,end_offset:S.endOffset,status:D.status,resolver:"open-files-read-only"}),g=a3({source_ref:D.sourceRef,source_uri:D.sourceUri,source_kind:D.kind,source_revision_id:$,revision:D.revision,hash:D.hash,status:D.status,path:O_(D.raw.path)??null,mime:O_(D.raw.mime)??O_(D.raw.content_type)??null,size:VK(D.raw.size)??null},W);_.run(`INSERT INTO chunks (id, source_revision_id, kind, ordinal, text, token_count, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[L,$,"source",S.ordinal,S.text,uK(S.text),S.startOffset,S.endOffset,JSON.stringify(g),I]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[L,S.text,D.title??"",D.sourceUri])}return{chunksInserted:O.length,redactions:N.findings.length}}async function Xg(_){let $=_.now??new Date;if(_.safetyPolicy)N6(_.dbPath,_.safetyPolicy);c(_.dbPath);let D=await fK(_.input,_.config,_.safetyPolicy,_.maxInputBytes),I=wK(D),U=_.maxItems??Pg;if(I.length>U)throw Error(`Manifest contains too many items: ${I.length} exceeds ${U} item limit.`);return A4({dbPath:_.dbPath,items:I,sourceLabel:_.input,allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")===!0,safetyPolicy:_.safetyPolicy,now:$,maxChunkChars:_.maxChunkChars,chunkOverlapChars:_.chunkOverlapChars,maxItems:_.maxItems})}async function A4(_){let $=(_.now??new Date).toISOString(),D=_.maxChunkChars??4000,I=_.chunkOverlapChars??200,U=_.maxItems??Pg;if(D<500)throw Error("maxChunkChars must be at least 500.");if(I<0||I>=D)throw Error("chunkOverlapChars must be less than maxChunkChars.");if(_.items.length>U)throw Error(`Manifest contains too many items: ${_.items.length} exceeds ${U} item limit.`);if(_.safetyPolicy)N6(_.dbPath,_.safetyPolicy);c(_.dbPath);let E=w(_.dbPath);try{return E.transaction(()=>{let N=new Set,O=new Set,S=0,L=0,W=0,g=0,z=[];R_(E,{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 G of _.items){let J=vK(G,$,{allowFileSourceRefs:_.allowFileSourceRefs});if(z.length0)return I}return null}function Gg(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return null}function dK(_,$){let D=_.mode;if(typeof D==="string"&&D!=="read_only")throw Error(`Source resolver denied ${$}. Permission mode is ${D}, expected read_only.`);let I=_.denied_purposes;if(Array.isArray(I)&&I.includes($))throw Error(`Source resolver denied ${$}. Purpose is explicitly denied.`);let U=_.allowed_purposes;if(Array.isArray(U)&&U.length>0&&!U.includes($))throw Error(`Source resolver denied ${$}. Allowed purposes: ${U.join(", ")}`)}function mK(_,$,D){if(!$)return D;try{let I=J$(_);if(I.kind==="open-files"&&I.entity==="file")return`${_}/revision/${encodeURIComponent($.revision)}`}catch{return D}return D}function lK(_,$,D){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 @@ -626,13 +626,13 @@ VALUES (10, datetime('now')); FROM chunks WHERE source_revision_id = ? ORDER BY ordinal ASC - LIMIT ?`).all($,D)}async function $I(_){let $=_.purpose??"knowledge_answer",D=Math.max(0,Math.min(_.limit??10,100)),I=(_.now??new Date).toISOString(),U=J$(_.sourceRef),E=sz(_.sourceRef,U),j=_3(_.sourceRef);if(_.safetyPolicy){if(!_.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");N6(_.dbPath,_.safetyPolicy)}c(_.dbPath);let N=w(_.dbPath);try{return N.transaction(()=>{let A=lK(N,E,_.sourceRef);if(!A)return R_(N,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:E},created_at:I}),{source_ref:_.sourceRef,source_uri:E,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 O=_I(A.metadata_json),S=_I(A.acl_json);try{dK(S,$)}catch(Y){throw R_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"deny",metadata:{purpose:$,read_only:!0,source_uri:A.uri,error:Y instanceof Error?Y.message:String(Y)},created_at:I}),Y}let L=iK(N,A.id,j),P=_I(L?.metadata_json),z=tK(N,L?.id??null),G=oK(N,L?.id??null,D),J=mK(A.uri,L,_.sourceRef),W=G.map((Y)=>{let Q=_I(Y.metadata_json),F={resolver:"open-files-read-only",mode:"local_catalog",purpose:$,read_only:!0,source_ref:g4(Q,["source_ref"])??J,source_uri:A.uri,source_revision_id:L?.id??null,revision:L?.revision??null,hash:L?.hash??g4(Q,["hash"]),chunk_id:Y.id,start_offset:Y.start_offset,end_offset:Y.end_offset,resolved_at:I},q=M6({source_ref:F.source_ref,source_uri:F.source_uri,source_kind:A.kind,source_revision_id:F.source_revision_id,revision:F.revision,hash:F.hash,chunk_id:Y.id,start_offset:Y.start_offset,end_offset:Y.end_offset,status:g4(Q,["status"]),resolver:F.resolver});return{id:Y.id,kind:Y.kind,ordinal:Y.ordinal,text:Y.text,token_count:Y.token_count,start_offset:Y.start_offset,end_offset:Y.end_offset,metadata:Q,evidence:F,provenance:q}}),X=W.map((Y)=>({source_ref:Y.evidence.source_ref,source_uri:A.uri,chunk_id:Y.id,quote:Y.text.slice(0,500),start_offset:Y.start_offset,end_offset:Y.end_offset,evidence:Y.evidence,provenance:Y.provenance}));R_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:A.uri,revision:L?.revision??null,chunks_returned:W.length,chunks_total:z},created_at:I});let R=g4(O,["mime","content_type"])??g4(P,["mime","content_type"]),T=X3(O,["size","size_bytes"])??X3(P,["size","size_bytes"]);return{source_ref:J,source_uri:A.uri,purpose:$,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:A.id,uri:A.uri,kind:A.kind,title:A.title,metadata:O,permissions:S,updated_at:A.updated_at},revision:L?{id:L.id,revision:L.revision,hash:L.hash,extracted_text_uri:L.extracted_text_uri,metadata:P,created_at:L.created_at,reindex_required:P.reindex_required===!0}:null,content:{mime:R,size:T,hash:L?.hash??g4(O,["hash","checksum","sha256"]),text_available:z>0,chunks_total:z,chunks_returned:W.length,char_count_returned:W.reduce((Y,Q)=>Y+Q.text.length,0),extracted_text_ref:L?.extracted_text_uri??g4(P,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:W,citations:X}})()}finally{N.close()}}function Y0(_){return`sha256:${pK("sha256").update(_).digest("hex")}`}function sK(_){return _.replace(//gi," ").replace(//gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+\n/g,` + LIMIT ?`).all($,D)}async function DI(_){let $=_.purpose??"knowledge_answer",D=Math.max(0,Math.min(_.limit??10,100)),I=(_.now??new Date).toISOString(),U=J$(_.sourceRef),E=_g(_.sourceRef,U),j=$g(_.sourceRef);if(_.safetyPolicy){if(!_.safetyPolicy.readOnlySourceAccess)throw Error("Safety policy denied source resolution.");N6(_.dbPath,_.safetyPolicy)}c(_.dbPath);let N=w(_.dbPath);try{return N.transaction(()=>{let O=lK(N,E,_.sourceRef);if(!O)return R_(N,{event_type:"source_read",action:"open_files_resolve_missing",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:E},created_at:I}),{source_ref:_.sourceRef,source_uri:E,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 S=$I(O.metadata_json),L=$I(O.acl_json);try{dK(L,$)}catch(Y){throw R_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"deny",metadata:{purpose:$,read_only:!0,source_uri:O.uri,error:Y instanceof Error?Y.message:String(Y)},created_at:I}),Y}let W=iK(N,O.id,j),g=$I(W?.metadata_json),z=tK(N,W?.id??null),G=oK(N,W?.id??null,D),J=mK(O.uri,W,_.sourceRef),P=G.map((Y)=>{let Q=$I(Y.metadata_json),F={resolver:"open-files-read-only",mode:"local_catalog",purpose:$,read_only:!0,source_ref:O4(Q,["source_ref"])??J,source_uri:O.uri,source_revision_id:W?.id??null,revision:W?.revision??null,hash:W?.hash??O4(Q,["hash"]),chunk_id:Y.id,start_offset:Y.start_offset,end_offset:Y.end_offset,resolved_at:I},B=M6({source_ref:F.source_ref,source_uri:F.source_uri,source_kind:O.kind,source_revision_id:F.source_revision_id,revision:F.revision,hash:F.hash,chunk_id:Y.id,start_offset:Y.start_offset,end_offset:Y.end_offset,status:O4(Q,["status"]),resolver:F.resolver});return{id:Y.id,kind:Y.kind,ordinal:Y.ordinal,text:Y.text,token_count:Y.token_count,start_offset:Y.start_offset,end_offset:Y.end_offset,metadata:Q,evidence:F,provenance:B}}),X=P.map((Y)=>({source_ref:Y.evidence.source_ref,source_uri:O.uri,chunk_id:Y.id,quote:Y.text.slice(0,500),start_offset:Y.start_offset,end_offset:Y.end_offset,evidence:Y.evidence,provenance:Y.provenance}));R_(N,{event_type:"source_read",action:"open_files_resolve",target_uri:_.sourceRef,decision:"allow",metadata:{purpose:$,read_only:!0,source_uri:O.uri,revision:W?.revision??null,chunks_returned:P.length,chunks_total:z},created_at:I});let R=O4(S,["mime","content_type"])??O4(g,["mime","content_type"]),T=Gg(S,["size","size_bytes"])??Gg(g,["size","size_bytes"]);return{source_ref:J,source_uri:O.uri,purpose:$,read_only:!0,resolved:!0,resolver:{name:"open-files-read-only",mode:"local_catalog",contract:"open-files-knowledge-source-v1"},source:{id:O.id,uri:O.uri,kind:O.kind,title:O.title,metadata:S,permissions:L,updated_at:O.updated_at},revision:W?{id:W.id,revision:W.revision,hash:W.hash,extracted_text_uri:W.extracted_text_uri,metadata:g,created_at:W.created_at,reindex_required:g.reindex_required===!0}:null,content:{mime:R,size:T,hash:W?.hash??O4(S,["hash","checksum","sha256"]),text_available:z>0,chunks_total:z,chunks_returned:P.length,char_count_returned:P.reduce((Y,Q)=>Y+Q.text.length,0),extracted_text_ref:W?.extracted_text_uri??O4(g,["extracted_text_ref","extracted_text_uri"]),bytes_available:!1,bytes_exposed:!1},chunks:P,citations:X}})()}finally{N.close()}}function K0(_){return`sha256:${pK("sha256").update(_).digest("hex")}`}function sK(_){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 _T(_,$,D){let I=new URL(_),U=I.hostname,E=decodeURIComponent(I.pathname.replace(/^\/+/,""));if(!U||!E)throw Error(`Invalid S3 source URI: ${_}`);if(D)b6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:A}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),O=$?.storage.type==="s3"&&$.storage.s3?.bucket===U?$.storage.s3:void 0,L=await new j({region:O?.region,credentials:O?.profile?A({profile:O.profile}):void 0,maxAttempts:O?.max_attempts}).send(new N({Bucket:U,Key:E}));if(!L.Body)return"";return await L.Body.transformToString()}async function $T(_,$){if($)G0($);let D=await P0(_,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!D.ok)throw Error(`Web source read failed ${D.status}: ${_}`);let I=D.headers.get("content-type"),U=await D.text();return{text:I?.includes("html")?sK(U):U,mime:I}}function UI(_){if(_.kind==="file")return DI(_.path);if(_.kind==="s3")return DI(_.key);if(_.kind==="web")return DI(new URL(_.url).pathname)||_.url;return _.path?DI(_.path):_.id}async function G3(_,$,D){if(_.kind==="file"){if(!eK(_.path))throw Error(`Source file not found: ${_.path}`);let I=aK(_.path,"utf8");return{text:I,contentSource:"file",title:UI(_),mime:"text/plain",size:I.length,hash:Y0(I),revision:null,extractedTextRef:null,metadata:{path:_.path},permissions:{mode:"read_only"}}}if(_.kind==="s3"){let I=await _T(_.uri,$,D);return{text:I,contentSource:"s3",title:UI(_),mime:"text/plain",size:I.length,hash:Y0(I),revision:null,extractedTextRef:null,metadata:{bucket:_.bucket,key:_.key},permissions:{mode:"read_only"}}}if(_.kind==="web"){let I=await $T(_.url,D);return{text:I.text,contentSource:"web",title:UI(_),mime:I.mime,size:I.text.length,hash:Y0(I.text),revision:null,extractedTextRef:null,metadata:{url:_.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${_.uri}`)}async function DT(_,$,D){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 I=J$(_);return{text:(await G3(I,$,D)).text,contentSource:"extracted_text_ref"}}async function UT(_){let $=await $I({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 I=await DT($.revision.extracted_text_uri,_.config,_.safetyPolicy);return{text:I.text,contentSource:I.contentSource,title:$.source?.title??null,mime:$.content.mime,size:I.text.length,hash:$.revision.hash??Y0(I.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 D=$.chunks.map((I)=>I.text).join(` +`).replace(/[ \t]{2,}/g," ").trim()}async function _T(_,$,D){let I=new URL(_),U=I.hostname,E=decodeURIComponent(I.pathname.replace(/^\/+/,""));if(!U||!E)throw Error(`Invalid S3 source URI: ${_}`);if(D)Z6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),S=$?.storage.type==="s3"&&$.storage.s3?.bucket===U?$.storage.s3:void 0,W=await new j({region:S?.region,credentials:S?.profile?O({profile:S.profile}):void 0,maxAttempts:S?.max_attempts}).send(new N({Bucket:U,Key:E}));if(!W.Body)return"";return await W.Body.transformToString()}async function $T(_,$){if($)Y0($);let D=await X0(_,{headers:{accept:"text/markdown,text/plain,text/html,application/json;q=0.8,*/*;q=0.5","user-agent":"@hasna/knowledge source-ingest"}});if(!D.ok)throw Error(`Web source read failed ${D.status}: ${_}`);let I=D.headers.get("content-type"),U=await D.text();return{text:I?.includes("html")?sK(U):U,mime:I}}function II(_){if(_.kind==="file")return UI(_.path);if(_.kind==="s3")return UI(_.key);if(_.kind==="web")return UI(new URL(_.url).pathname)||_.url;return _.path?UI(_.path):_.id}async function Rg(_,$,D){if(_.kind==="file"){if(!eK(_.path))throw Error(`Source file not found: ${_.path}`);let I=aK(_.path,"utf8");return{text:I,contentSource:"file",title:II(_),mime:"text/plain",size:I.length,hash:K0(I),revision:null,extractedTextRef:null,metadata:{path:_.path},permissions:{mode:"read_only"}}}if(_.kind==="s3"){let I=await _T(_.uri,$,D);return{text:I,contentSource:"s3",title:II(_),mime:"text/plain",size:I.length,hash:K0(I),revision:null,extractedTextRef:null,metadata:{bucket:_.bucket,key:_.key},permissions:{mode:"read_only"}}}if(_.kind==="web"){let I=await $T(_.url,D);return{text:I.text,contentSource:"web",title:II(_),mime:I.mime,size:I.text.length,hash:K0(I.text),revision:null,extractedTextRef:null,metadata:{url:_.url},permissions:{mode:"read_only"}}}throw Error(`Direct source reading is not available for ${_.uri}`)}async function DT(_,$,D){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 I=J$(_);return{text:(await Rg(I,$,D)).text,contentSource:"extracted_text_ref"}}async function UT(_){let $=await DI({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 I=await DT($.revision.extracted_text_uri,_.config,_.safetyPolicy);return{text:I.text,contentSource:I.contentSource,title:$.source?.title??null,mime:$.content.mime,size:I.text.length,hash:$.revision.hash??K0(I.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 D=$.chunks.map((I)=>I.text).join(` -`);return{text:D,contentSource:"catalog_chunks",title:$.source?.title??null,mime:$.content.mime,size:D.length,hash:$.revision?.hash??Y0(D),revision:$.revision?.revision??null,extractedTextRef:$.revision?.extracted_text_uri??null,metadata:$.source?.metadata??{},permissions:$.source?.permissions??{mode:"read_only"}}}function IT(_,$,D,I){let U=D.hash??Y0(D.text),E={...F_(D.metadata),source_ref:_,content_source:D.contentSource,read_only:!0},j={source_ref:_,name:D.title??UI($),mime:D.mime??"text/plain",size:D.size??D.text.length,hash:U,revision:D.revision??U,status:"active",updated_at:new Date().toISOString(),permissions:{mode:"read_only",allowed_purposes:[I],...D.permissions},metadata:E,extracted_text_ref:D.extractedTextRef,extracted_text:D.text};if($.kind==="open-files"){if($.entity==="file")j.file_id=$.id;if($.entity==="source")j.source_id=$.id,j.path=$.path}if($.kind==="file")j.path=$.path;if($.kind==="s3")j.path=$.key;if($.kind==="web")j.url=$.url;return j}async function II(_){let $=_.purpose??"knowledge_index";E4(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1});let D=J$(_.sourceRef),I=D.kind==="open-files"?await UT(_):await G3(D,_.config,_.safetyPolicy),U=IT(_.sourceRef,D,I,$);return{...await N4({dbPath:_.dbPath,items:[U],sourceLabel:_.sourceRef,readAction:"source_ref_ingest_read",allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1,safetyPolicy:_.safetyPolicy,now:_.now}),source_ref:_.sourceRef,content_source:I.contentSource,read_only:!0,hash:String(U.hash)}}function EI(_,$){return`${_}_${ET("sha256").update($).digest("hex").slice(0,20)}`}function NT(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"note"}function bg(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function gT(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function R3(_){return Array.from(new Set((_??[]).map(($)=>$.trim()).filter(Boolean)))}function AT(_){let $=_.path?.trim()||`wiki/notes/${NT(_.title)}.md`,D=$.replace(/\\/g,"/");if(!D.startsWith("wiki/notes/")||!D.endsWith(".md"))throw Error("App wiki note paths must be relative wiki/notes/*.md artifact keys.");if(D.startsWith("/")||D.split("/").some((I)=>I===".."||I==="."))throw Error(`Invalid app wiki note path: ${$}`);return D}function OT(_){let $=[`# ${_.title}`,"",_.content.trim(),"",`Updated: ${_.now}`];if(_.tags.length>0)$.push("","Tags:",..._.tags.map((D)=>`- ${D}`));if(_.sourceRefs.length>0)$.push("","Source refs:",..._.sourceRefs.map((D)=>`- ${D}`));return $.push(""),$.join(` -`)}async function Y3(_,$){let D=await _.put($);return{key:D.key,uri:D.uri,kind:$.key.startsWith("logs/")?"log":"wiki_page",content_type:$.content_type,modified_at:D.modified_at,...X0($.body),metadata:{...$.metadata??{}}}}async function ST(_,$,D){let I=String(D.getUTCFullYear()),U=String(D.getUTCMonth()+1).padStart(2,"0"),E=String(D.getUTCDate()).padStart(2,"0"),j=`logs/${I}/${U}/${E}.jsonl`,N="";try{N=await _.getText(j)}catch{N=""}return Y3(_,{key:j,body:`${N}${JSON.stringify($)} -`,content_type:"application/x-ndjson",metadata:{provenance:N$({generated_from:String($.event??"app_wiki_log"),artifact_key:j})}})}function LT(_){return{...F_(_.metadata??{}),app_wiki:!0,note:!0,artifact_key:_.path,tags:_.tags,source_refs:_.sourceRefs,provenance:_.provenance}}function Zg(_){let $=bg(_.metadata_json);return{id:_.id,path:_.path,title:_.title,artifact_uri:_.artifact_uri,content_hash:_.content_hash,tags:Array.isArray($.tags)?$.tags.filter((D)=>typeof D==="string"):[],source_refs:Array.isArray($.source_refs)?$.source_refs.filter((D)=>typeof D==="string"):[],created_at:_.created_at,updated_at:_.updated_at}}function JT(_,$){return $.map((D)=>{let I=_.query(`SELECT +`);return{text:D,contentSource:"catalog_chunks",title:$.source?.title??null,mime:$.content.mime,size:D.length,hash:$.revision?.hash??K0(D),revision:$.revision?.revision??null,extractedTextRef:$.revision?.extracted_text_uri??null,metadata:$.source?.metadata??{},permissions:$.source?.permissions??{mode:"read_only"}}}function IT(_,$,D,I){let U=D.hash??K0(D.text),E={...F_(D.metadata),source_ref:_,content_source:D.contentSource,read_only:!0},j={source_ref:_,name:D.title??II($),mime:D.mime??"text/plain",size:D.size??D.text.length,hash:U,revision:D.revision??U,status:"active",updated_at:new Date().toISOString(),permissions:{mode:"read_only",allowed_purposes:[I],...D.permissions},metadata:E,extracted_text_ref:D.extractedTextRef,extracted_text:D.text};if($.kind==="open-files"){if($.entity==="file")j.file_id=$.id;if($.entity==="source")j.source_id=$.id,j.path=$.path}if($.kind==="file")j.path=$.path;if($.kind==="s3")j.path=$.key;if($.kind==="web")j.url=$.url;return j}async function EI(_){let $=_.purpose??"knowledge_index";j4(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1});let D=J$(_.sourceRef),I=D.kind==="open-files"?await UT(_):await Rg(D,_.config,_.safetyPolicy),U=IT(_.sourceRef,D,I,$);return{...await A4({dbPath:_.dbPath,items:[U],sourceLabel:_.sourceRef,readAction:"source_ref_ingest_read",allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1,safetyPolicy:_.safetyPolicy,now:_.now}),source_ref:_.sourceRef,content_source:I.contentSource,read_only:!0,hash:String(U.hash)}}function jI(_,$){return`${_}_${ET("sha256").update($).digest("hex").slice(0,20)}`}function NT(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"note"}function Z2(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function AT(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function Yg(_){return Array.from(new Set((_??[]).map(($)=>$.trim()).filter(Boolean)))}function OT(_){let $=_.path?.trim()||`wiki/notes/${NT(_.title)}.md`,D=$.replace(/\\/g,"/");if(!D.startsWith("wiki/notes/")||!D.endsWith(".md"))throw Error("App wiki note paths must be relative wiki/notes/*.md artifact keys.");if(D.startsWith("/")||D.split("/").some((I)=>I===".."||I==="."))throw Error(`Invalid app wiki note path: ${$}`);return D}function ST(_){let $=[`# ${_.title}`,"",_.content.trim(),"",`Updated: ${_.now}`];if(_.tags.length>0)$.push("","Tags:",..._.tags.map((D)=>`- ${D}`));if(_.sourceRefs.length>0)$.push("","Source refs:",..._.sourceRefs.map((D)=>`- ${D}`));return $.push(""),$.join(` +`)}async function Qg(_,$){let D=await _.put($);return{key:D.key,uri:D.uri,kind:$.key.startsWith("logs/")?"log":"wiki_page",content_type:$.content_type,modified_at:D.modified_at,...R0($.body),metadata:{...$.metadata??{}}}}async function LT(_,$,D){let I=String(D.getUTCFullYear()),U=String(D.getUTCMonth()+1).padStart(2,"0"),E=String(D.getUTCDate()).padStart(2,"0"),j=`logs/${I}/${U}/${E}.jsonl`,N="";try{N=await _.getText(j)}catch{N=""}return Qg(_,{key:j,body:`${N}${JSON.stringify($)} +`,content_type:"application/x-ndjson",metadata:{provenance:N$({generated_from:String($.event??"app_wiki_log"),artifact_key:j})}})}function WT(_){return{...F_(_.metadata??{}),app_wiki:!0,note:!0,artifact_key:_.path,tags:_.tags,source_refs:_.sourceRefs,provenance:_.provenance}}function H2(_){let $=Z2(_.metadata_json);return{id:_.id,path:_.path,title:_.title,artifact_uri:_.artifact_uri,content_hash:_.content_hash,tags:Array.isArray($.tags)?$.tags.filter((D)=>typeof D==="string"):[],source_refs:Array.isArray($.source_refs)?$.source_refs.filter((D)=>typeof D==="string"):[],created_at:_.created_at,updated_at:_.updated_at}}function JT(_,$){return $.map((D)=>{let I=_.query(`SELECT s.uri AS source_uri, c.id AS chunk_id, c.text, @@ -646,13 +646,13 @@ VALUES (10, datetime('now')); 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(D,`%${D}%`),U=bg(I?.metadata_json);return{source_ref:D,source_uri:I?.source_uri??D,chunk_id:I?.chunk_id??null,quote:I?.text?I.text.replace(/\s+/g," ").slice(0,240):null,start_offset:I?.start_offset??null,end_offset:I?.end_offset??null,metadata:{source_ref:D,revision:I?.revision??U.revision,hash:I?.hash??U.hash}}})}function WT(_,$,D,I){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);let U=JT(_,D);for(let E of U)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[EI("cit",`${$}\x00${E.source_uri}\x00${E.chunk_id??jT()}`),$,E.chunk_id,E.source_uri,E.quote,E.start_offset,E.end_offset,JSON.stringify(E.metadata),I]);return U.length}function PT(_,$){_.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) + LIMIT 1`).get(D,`%${D}%`),U=Z2(I?.metadata_json);return{source_ref:D,source_uri:I?.source_uri??D,chunk_id:I?.chunk_id??null,quote:I?.text?I.text.replace(/\s+/g," ").slice(0,240):null,start_offset:I?.start_offset??null,end_offset:I?.end_offset??null,metadata:{source_ref:D,revision:I?.revision??U.revision,hash:I?.hash??U.hash}}})}function PT(_,$,D,I){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);let U=JT(_,D);for(let E of U)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[jI("cit",`${$}\x00${E.source_uri}\x00${E.chunk_id??jT()}`),$,E.chunk_id,E.source_uri,E.quote,E.start_offset,E.end_offset,JSON.stringify(E.metadata),I]);return U.length}function zT(_,$){_.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`,[EI("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 zT(_,$){_.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) + updated_at = excluded.updated_at`,[jI("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 gT(_,$){_.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, @@ -660,22 +660,22 @@ VALUES (10, datetime('now')); 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 D=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($.pageId);for(let U of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$.pageId]);let I=EI("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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,$.pageId,"wiki",0,$.body,gT($.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 (?, ?, ?, ?)",[I,$.body,$.title,$.artifactUri])}function mD(_){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)N6(_.workspace.knowledgeDbPath,_.safetyPolicy)}async function Q3(_){mD(_);let $=c(_.workspace.knowledgeDbPath),D=w(_.workspace.knowledgeDbPath);try{R_(D,{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{D.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 K3(_){mD(_);let $=_.now??new Date,D=$.toISOString(),I=R3(_.tags),U=R3(_.sourceRefs);for(let L of U)E4(L,{allowFileSourceRefs:_.safetyPolicy?.readOnlySourceAccess===!0});let E=AT(_),j=OT({title:_.title,content:_.content,tags:I,sourceRefs:U,now:D}),N=N$({generated_from:"app_wiki_note",artifact_key:E,source_refs:U}),A=await Y3(_.store,{key:E,body:j,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:N,scope:_.scope,tags:I.join(","),source_refs:U.join(",")}}),O=await ST(_.store,{ts:D,event:"app_wiki_note_written",page_key:E,source_refs:U,tags:I},$);c(_.workspace.knowledgeDbPath);let S=w(_.workspace.knowledgeDbPath);try{let L=EI("wiki",E),P=LT({path:E,tags:I,sourceRefs:U,provenance:N,metadata:_.metadata});j6(S,[A,O],$),zT(S,{pageId:L,path:E,title:_.title,artifactUri:A.uri,contentHash:A.hash??"",body:j,metadata:P,now:D});let z=WT(S,L,U,D);PT(S,{title:_.title,path:E,artifactUri:A.uri,contentHash:A.hash??"",tags:I,sourceRefs:U,now:D}),R_(S,{event_type:"write",action:"app_wiki_note_write",target_uri:A.uri,decision:"allow",metadata:{scope:_.scope,path:E,source_refs:U,tags:I},created_at:D});let G=S.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(L);if(!G)throw Error(`Failed to write app wiki note: ${E}`);return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,note:Zg(G),artifact_uri:A.uri,content_hash:A.hash??"",citations_written:z,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${E}`}}finally{S.close()}}function T3(_){let $=Math.max(1,Math.min(_.limit??50,200));if(!_.dbPath)return[];c(_.dbPath);let D=w(_.dbPath);try{return D.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 D=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($.pageId);for(let U of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$.pageId]);let I=jI("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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,$.pageId,"wiki",0,$.body,AT($.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 (?, ?, ?, ?)",[I,$.body,$.title,$.artifactUri])}function mD(_){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)N6(_.workspace.knowledgeDbPath,_.safetyPolicy)}async function Kg(_){mD(_);let $=c(_.workspace.knowledgeDbPath),D=w(_.workspace.knowledgeDbPath);try{R_(D,{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{D.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 Tg(_){mD(_);let $=_.now??new Date,D=$.toISOString(),I=Yg(_.tags),U=Yg(_.sourceRefs);for(let W of U)j4(W,{allowFileSourceRefs:_.safetyPolicy?.readOnlySourceAccess===!0});let E=OT(_),j=ST({title:_.title,content:_.content,tags:I,sourceRefs:U,now:D}),N=N$({generated_from:"app_wiki_note",artifact_key:E,source_refs:U}),O=await Qg(_.store,{key:E,body:j,content_type:"text/markdown",metadata:{generated_from:"app_wiki_note",provenance:N,scope:_.scope,tags:I.join(","),source_refs:U.join(",")}}),S=await LT(_.store,{ts:D,event:"app_wiki_note_written",page_key:E,source_refs:U,tags:I},$);c(_.workspace.knowledgeDbPath);let L=w(_.workspace.knowledgeDbPath);try{let W=jI("wiki",E),g=WT({path:E,tags:I,sourceRefs:U,provenance:N,metadata:_.metadata});j6(L,[O,S],$),gT(L,{pageId:W,path:E,title:_.title,artifactUri:O.uri,contentHash:O.hash??"",body:j,metadata:g,now:D});let z=PT(L,W,U,D);zT(L,{title:_.title,path:E,artifactUri:O.uri,contentHash:O.hash??"",tags:I,sourceRefs:U,now:D}),R_(L,{event_type:"write",action:"app_wiki_note_write",target_uri:O.uri,decision:"allow",metadata:{scope:_.scope,path:E,source_refs:U,tags:I},created_at:D});let G=L.query("SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at FROM wiki_pages WHERE id = ?").get(W);if(!G)throw Error(`Failed to write app wiki note: ${E}`);return{ok:!0,scope:_.scope,workspace_home:_.workspace.home,note:H2(G),artifact_uri:O.uri,content_hash:O.hash??"",citations_written:z,chunks_written:1,storage_objects_written:2,message:`Wrote app wiki note ${E}`}}finally{L.close()}}function Fg(_){let $=Math.max(1,Math.min(_.limit??50,200));if(!_.dbPath)return[];c(_.dbPath);let D=w(_.dbPath);try{return D.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(Zg)}finally{D.close()}}async function F3(_){c(_.dbPath);let $=w(_.dbPath);try{let D=$.query(`SELECT id, path, title, artifact_uri, content_hash, metadata_json, created_at, updated_at + LIMIT ?`).all($).map(H2)}finally{D.close()}}async function Vg(_){c(_.dbPath);let $=w(_.dbPath);try{let D=$.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(!D)return null;let I=$.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(D.id).map((E)=>({...E,metadata:bg(E.metadata_json),metadata_json:void 0})),U=null;if(_.includeContent!==!1)try{U=await _.store.getText(D.path)}catch{U=null}return{ok:!0,note:Zg(D),citations:I,content:U}}finally{$.close()}}async function V3(_){return mD(_),E4(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1}),II({dbPath:_.workspace.knowledgeDbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",config:_.config,safetyPolicy:_.safetyPolicy})}import{randomUUID as hg}from"crypto";import{randomUUID as XT}from"crypto";var Hg={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"}},GT={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}},RT={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 M3(_){return _?.providers??{}}function g6(_,$){let D=M3(_)[$]??{};return{...Hg[$],...D}}function b3(_){let $=M3(_);return{...RT,...$.default_model?{default:$.default_model}:{},...$.aliases??{}}}function f_(_){let[$,...D]=_.split(":"),I=D.join(":");if($!=="openai"&&$!=="anthropic"&&$!=="deepseek")throw Error(`Unsupported AI provider: ${$}`);if(!I)throw Error(`Invalid model ref: ${_}. Expected provider:model.`);return{provider:$,model:I}}function T$(_,$){return b3($)[_]??_}function kg(_){let $=b3(_);return Object.entries($).map(([D,I])=>{let U=f_(I);return{alias:D,model_ref:I,provider:U.provider,model:U.model,default:D==="default",capabilities:GT[U.provider]}})}function Z3(_,$=process.env){return Object.keys(Hg).map((D)=>{let I=g6(_,D),U=Boolean($[I.api_key_env]);return{provider:D,api_key_env:I.api_key_env,configured:U,source:U?"env":"missing",base_url:I.base_url??null,default_model:I.default_model}})}function H3(_,$=process.env){return{default_model:T$("default",_),providers:Z3(_,$),models:kg(_)}}function A4(_,$,D=process.env){let I=Z3($,D).find((U)=>U.provider===_);if(!I)throw Error(`Unsupported AI provider: ${_}`);if(!I.configured)throw Error(`Missing ${I.api_key_env} for ${_}. Set the env var to use this provider.`);return I}async function YT(_){if(_==="openai"){let{createOpenAI:D}=await import("@ai-sdk/openai");return D}if(_==="anthropic"){let{createAnthropic:D}=await import("@ai-sdk/anthropic");return D}let{createDeepSeek:$}=await import("@ai-sdk/deepseek");return $}async function QT(_={}){let{createProviderRegistry:$}=await import("ai"),D=_.env??process.env,I={};for(let U of Object.keys(Hg)){let E=g6(_.config,U),j=D[E.api_key_env];if(!j)continue;let N=_.factories?.[U]??await YT(U);I[U]=N({apiKey:j,baseURL:E.base_url})}return $(I)}async function lD(_,$={}){let D=T$(_,$.config),I=f_(D);return A4(I.provider,$.config,$.env),(await QT($)).languageModel(D)}function B3(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return 0}function O4(_){let $=_.usage??{};return{provider:_.provider,model:_.model,input_tokens:B3($,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:B3($,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:_.costUsd??0,metadata:{usage:$,provider_metadata:_.providerMetadata??{}}}}function Q0(_,$){let D=`usage_${XT()}`;return _.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,$.run_id??null,$.provider,$.model,$.input_tokens,$.output_tokens,$.cost_usd,JSON.stringify($.metadata),$.created_at??new Date().toISOString()]),D}import{createHash as lT}from"crypto";import{existsSync as ZT,readFileSync as HT}from"fs";import{createHash as C3}from"crypto";var KT="openai:text-embedding-3-small",v3=1536;function jI(_){return _?.embeddings??{}}function k3(_,$){return`${_}_${C3("sha256").update($).digest("hex").slice(0,20)}`}function Cg(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function F$(_,$){for(let D of $){let I=_[D];if(typeof I==="string"&&I.length>0)return I}return null}function q3(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return null}function qg(_){return Math.sqrt(_.reduce(($,D)=>$+D*D,0))}function TT(_,$,D=qg($)){let I=qg(_);if(I===0||D===0)return 0;let U=Math.min(_.length,$.length),E=0;for(let j=0;j{let E=D[U%D.length]/255;return Number((E*2-1).toFixed(6))})}async function VT(_,$,D=process.env){A4("openai",$,D);let I=g6($,"openai"),{createOpenAI:U}=await import("@ai-sdk/openai"),E=U({apiKey:D[I.api_key_env],baseURL:I.base_url});if(E.embeddingModel)return E.embeddingModel(_);if(E.textEmbedding)return E.textEmbedding(_);if(E.textEmbeddingModel)return E.textEmbeddingModel(_);throw Error("OpenAI provider does not expose an embedding model factory.")}function S4(_,$){if(!_||_==="default"||_==="embedding")return jI($).default_model??KT;return _}async function w3(_,$={}){let D=S4($.modelRef,$.config),I=f_(D);if(I.provider!=="openai")throw Error(`Embedding provider ${I.provider} is not supported yet. Use openai:text-embedding-3-small.`);let U=$.dimensions??jI($.config).dimensions??v3;if($.fake)return{provider:I.provider,model:I.model,dimensions:U,vectors:_.map((O)=>FT(O,U)),usage:{input_tokens:_.reduce((O,S)=>O+Math.max(1,Math.ceil(S.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:E}=await import("ai"),j=await VT(I.model,$.config,$.env),N=await E({model:j,values:_,maxParallelCalls:$.maxParallelCalls??jI($.config).max_parallel_calls,providerOptions:{openai:{dimensions:U}}}),A=N.embeddings;return{provider:I.provider,model:I.model,dimensions:A[0]?.length??U,vectors:A,usage:{input_tokens:N.usage?.tokens??0}}}function BT(_,$){if($.sourceRevisionId)return _.query(`SELECT + ORDER BY created_at ASC`).all(D.id).map((E)=>({...E,metadata:Z2(E.metadata_json),metadata_json:void 0})),U=null;if(_.includeContent!==!1)try{U=await _.store.getText(D.path)}catch{U=null}return{ok:!0,note:H2(D),citations:I,content:U}}finally{$.close()}}async function Bg(_){return mD(_),j4(_.sourceRef,{allowFileSourceRefs:_.config?.sources.allowed_schemes.includes("file")!==!1}),EI({dbPath:_.workspace.knowledgeDbPath,sourceRef:_.sourceRef,purpose:_.purpose??"knowledge_index",config:_.config,safetyPolicy:_.safetyPolicy})}import{randomUUID as h2}from"crypto";import{randomUUID as XT}from"crypto";var b2={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"}},GT={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}},RT={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 Zg(_){return _?.providers??{}}function A6(_,$){let D=Zg(_)[$]??{};return{...b2[$],...D}}function Hg(_){let $=Zg(_);return{...RT,...$.default_model?{default:$.default_model}:{},...$.aliases??{}}}function f_(_){let[$,...D]=_.split(":"),I=D.join(":");if($!=="openai"&&$!=="anthropic"&&$!=="deepseek")throw Error(`Unsupported AI provider: ${$}`);if(!I)throw Error(`Invalid model ref: ${_}. Expected provider:model.`);return{provider:$,model:I}}function T$(_,$){return Hg($)[_]??_}function q2(_){let $=Hg(_);return Object.entries($).map(([D,I])=>{let U=f_(I);return{alias:D,model_ref:I,provider:U.provider,model:U.model,default:D==="default",capabilities:GT[U.provider]}})}function bg(_,$=process.env){return Object.keys(b2).map((D)=>{let I=A6(_,D),U=Boolean($[I.api_key_env]);return{provider:D,api_key_env:I.api_key_env,configured:U,source:U?"env":"missing",base_url:I.base_url??null,default_model:I.default_model}})}function qg(_,$=process.env){return{default_model:T$("default",_),providers:bg(_,$),models:q2(_)}}function S4(_,$,D=process.env){let I=bg($,D).find((U)=>U.provider===_);if(!I)throw Error(`Unsupported AI provider: ${_}`);if(!I.configured)throw Error(`Missing ${I.api_key_env} for ${_}. Set the env var to use this provider.`);return I}async function YT(_){if(_==="openai"){let{createOpenAI:D}=await import("@ai-sdk/openai");return D}if(_==="anthropic"){let{createAnthropic:D}=await import("@ai-sdk/anthropic");return D}let{createDeepSeek:$}=await import("@ai-sdk/deepseek");return $}async function QT(_={}){let{createProviderRegistry:$}=await import("ai"),D=_.env??process.env,I={};for(let U of Object.keys(b2)){let E=A6(_.config,U),j=D[E.api_key_env];if(!j)continue;let N=_.factories?.[U]??await YT(U);I[U]=N({apiKey:j,baseURL:E.base_url})}return $(I)}async function lD(_,$={}){let D=T$(_,$.config),I=f_(D);return S4(I.provider,$.config,$.env),(await QT($)).languageModel(D)}function Mg(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return 0}function L4(_){let $=_.usage??{};return{provider:_.provider,model:_.model,input_tokens:Mg($,["inputTokens","promptTokens","input_tokens","prompt_tokens"]),output_tokens:Mg($,["outputTokens","completionTokens","output_tokens","completion_tokens"]),cost_usd:_.costUsd??0,metadata:{usage:$,provider_metadata:_.providerMetadata??{}}}}function T0(_,$){let D=`usage_${XT()}`;return _.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,$.run_id??null,$.provider,$.model,$.input_tokens,$.output_tokens,$.cost_usd,JSON.stringify($.metadata),$.created_at??new Date().toISOString()]),D}import{createHash as lT}from"crypto";import{existsSync as HT,readFileSync as bT}from"fs";import{createHash as vg}from"crypto";var KT="openai:text-embedding-3-small",wg=1536;function NI(_){return _?.embeddings??{}}function kg(_,$){return`${_}_${vg("sha256").update($).digest("hex").slice(0,20)}`}function C2(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function F$(_,$){for(let D of $){let I=_[D];if(typeof I==="string"&&I.length>0)return I}return null}function Cg(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return null}function k2(_){return Math.sqrt(_.reduce(($,D)=>$+D*D,0))}function TT(_,$,D=k2($)){let I=k2(_);if(I===0||D===0)return 0;let U=Math.min(_.length,$.length),E=0;for(let j=0;j{let E=D[U%D.length]/255;return Number((E*2-1).toFixed(6))})}async function VT(_,$,D=process.env){S4("openai",$,D);let I=A6($,"openai"),{createOpenAI:U}=await import("@ai-sdk/openai"),E=U({apiKey:D[I.api_key_env],baseURL:I.base_url});if(E.embeddingModel)return E.embeddingModel(_);if(E.textEmbedding)return E.textEmbedding(_);if(E.textEmbeddingModel)return E.textEmbeddingModel(_);throw Error("OpenAI provider does not expose an embedding model factory.")}function W4(_,$){if(!_||_==="default"||_==="embedding")return NI($).default_model??KT;return _}async function rg(_,$={}){let D=W4($.modelRef,$.config),I=f_(D);if(I.provider!=="openai")throw Error(`Embedding provider ${I.provider} is not supported yet. Use openai:text-embedding-3-small.`);let U=$.dimensions??NI($.config).dimensions??wg;if($.fake)return{provider:I.provider,model:I.model,dimensions:U,vectors:_.map((S)=>FT(S,U)),usage:{input_tokens:_.reduce((S,L)=>S+Math.max(1,Math.ceil(L.split(/\s+/).filter(Boolean).length*1.25)),0)}};let{embedMany:E}=await import("ai"),j=await VT(I.model,$.config,$.env),N=await E({model:j,values:_,maxParallelCalls:$.maxParallelCalls??NI($.config).max_parallel_calls,providerOptions:{openai:{dimensions:U}}}),O=N.embeddings;return{provider:I.provider,model:I.model,dimensions:O[0]?.length??U,vectors:O,usage:{input_tokens:N.usage?.tokens??0}}}function BT(_,$){if($.sourceRevisionId)return _.query(`SELECT c.id, c.text, c.token_count, @@ -713,7 +713,7 @@ VALUES (10, datetime('now')); 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 MT(_){let $=Cg(_.metadata_json),D=$.provenance;if(D&&typeof D==="object"&&!Array.isArray(D))return D;return M6({source_ref:F$($,["source_ref"]),source_uri:_.source_uri??F$($,["source_uri"]),source_kind:_.source_kind??F$($,["source_kind"]),source_revision_id:_.source_revision_id,revision:_.revision??F$($,["revision"]),hash:_.hash??F$($,["hash"]),chunk_id:_.id,start_offset:_.start_offset??q3($,["start_offset"]),end_offset:_.end_offset??q3($,["end_offset"]),status:F$($,["status"]),resolver:"open-files-read-only"})}function bT(_,$,D,I){let U=_.prepare(` + LIMIT ?`).all($.provider,$.model,$.limit)}function MT(_){let $=C2(_.metadata_json),D=$.provenance;if(D&&typeof D==="object"&&!Array.isArray(D))return D;return M6({source_ref:F$($,["source_ref"]),source_uri:_.source_uri??F$($,["source_uri"]),source_kind:_.source_kind??F$($,["source_kind"]),source_revision_id:_.source_revision_id,revision:_.revision??F$($,["revision"]),hash:_.hash??F$($,["hash"]),chunk_id:_.id,start_offset:_.start_offset??Cg($,["start_offset"]),end_offset:_.end_offset??Cg($,["end_offset"]),status:F$($,["status"]),resolver:"open-files-read-only"})}function ZT(_,$,D,I){let U=_.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 @@ -742,10 +742,10 @@ VALUES (10, datetime('now')); status = excluded.status, metadata_json = excluded.metadata_json, updated_at = excluded.updated_at - `);return _.transaction(()=>{for(let N=0;N<$.length;N+=1){let A=$[N],O=D.vectors[N];if(!O)continue;let S=Cg(A.metadata_json),L=MT(A),P=L.source_ref??F$(S,["source_ref"]),z=L.source_uri??A.source_uri??F$(S,["source_uri"]),G=L.revision??A.revision??F$(S,["revision"]),J=L.hash??A.hash??F$(S,["hash"]),W=L.status??F$(S,["status"])??"active",X=JSON.stringify(O);U.run(k3("emb",`${A.id}\x00${D.provider}\x00${D.model}`),A.id,D.provider,D.model,D.dimensions,X,I),E.run(k3("vec",`${A.id}\x00${D.provider}\x00${D.model}`),A.id,A.source_revision_id,D.provider,D.model,D.dimensions,X,qg(O),z,P,G,J,L.start_offset,L.end_offset,A.token_count,W,JSON.stringify({...S,provenance:L,embedded_at:I}),I,I)}})(),$.length}async function NI(_){let $=S4(_.modelRef,_.config),D=f_($);if(D.provider!=="openai")throw Error(`Embedding provider ${D.provider} is not supported yet.`);let I=(_.now??new Date).toISOString(),U=Math.max(1,Math.min(_.limit??100,1000));c(_.dbPath);let E=w(_.dbPath),j;try{j=BT(E,{provider:D.provider,model:D.model,limit:U,sourceRevisionId:_.sourceRevisionId})}finally{E.close()}if(j.length===0)return{provider:D.provider,model:D.model,dimensions:_.dimensions??jI(_.config).dimensions??v3,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let N=await w3(j.map((O)=>O.text),_),A=w(_.dbPath);try{let O=bT(A,j,N,I);return{provider:N.provider,model:N.model,dimensions:N.dimensions,chunks_seen:j.length,chunks_embedded:j.length,embeddings_upserted:O,vector_entries_upserted:O,usage:N.usage}}finally{A.close()}}function r3(_){c(_);let $=w(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,I=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,U=$.query(`SELECT provider, model, dimensions, COUNT(*) AS entries, MAX(updated_at) AS updated_at + `);return _.transaction(()=>{for(let N=0;N<$.length;N+=1){let O=$[N],S=D.vectors[N];if(!S)continue;let L=C2(O.metadata_json),W=MT(O),g=W.source_ref??F$(L,["source_ref"]),z=W.source_uri??O.source_uri??F$(L,["source_uri"]),G=W.revision??O.revision??F$(L,["revision"]),J=W.hash??O.hash??F$(L,["hash"]),P=W.status??F$(L,["status"])??"active",X=JSON.stringify(S);U.run(kg("emb",`${O.id}\x00${D.provider}\x00${D.model}`),O.id,D.provider,D.model,D.dimensions,X,I),E.run(kg("vec",`${O.id}\x00${D.provider}\x00${D.model}`),O.id,O.source_revision_id,D.provider,D.model,D.dimensions,X,k2(S),z,g,G,J,W.start_offset,W.end_offset,O.token_count,P,JSON.stringify({...L,provenance:W,embedded_at:I}),I,I)}})(),$.length}async function AI(_){let $=W4(_.modelRef,_.config),D=f_($);if(D.provider!=="openai")throw Error(`Embedding provider ${D.provider} is not supported yet.`);let I=(_.now??new Date).toISOString(),U=Math.max(1,Math.min(_.limit??100,1000));c(_.dbPath);let E=w(_.dbPath),j;try{j=BT(E,{provider:D.provider,model:D.model,limit:U,sourceRevisionId:_.sourceRevisionId})}finally{E.close()}if(j.length===0)return{provider:D.provider,model:D.model,dimensions:_.dimensions??NI(_.config).dimensions??wg,chunks_seen:0,chunks_embedded:0,embeddings_upserted:0,vector_entries_upserted:0,usage:{input_tokens:0}};let N=await rg(j.map((S)=>S.text),_),O=w(_.dbPath);try{let S=ZT(O,j,N,I);return{provider:N.provider,model:N.model,dimensions:N.dimensions,chunks_seen:j.length,chunks_embedded:j.length,embeddings_upserted:S,vector_entries_upserted:S,usage:N.usage}}finally{O.close()}}function fg(_){c(_);let $=w(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,I=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,U=$.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:D,total_vector_entries:I,indexes:U}}finally{$.close()}}async function gI(_){let $=S4(_.modelRef,_.config),D=f_($),I=Math.max(1,Math.min(_.limit??10,100)),U=await w3([_.query],_),E=U.vectors[0]??[];c(_.dbPath);let j=w(_.dbPath);try{let A=j.query(`SELECT + ORDER BY provider, model`).all();return{total_embeddings:D,total_vector_entries:I,indexes:U}}finally{$.close()}}async function OI(_){let $=W4(_.modelRef,_.config),D=f_($),I=Math.max(1,Math.min(_.limit??10,100)),U=await rg([_.query],_),E=U.vectors[0]??[];c(_.dbPath);let j=w(_.dbPath);try{let O=j.query(`SELECT v.chunk_id, c.text, v.vector_json, @@ -757,7 +757,7 @@ VALUES (10, datetime('now')); 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(D.provider,D.model).map((O)=>{let S=JSON.parse(O.vector_json),L=Cg(O.metadata_json),P=L.provenance&&typeof L.provenance==="object"&&!Array.isArray(L.provenance)?L.provenance:null;return{chunk_id:O.chunk_id,score:TT(E,S,O.vector_norm),text:O.text,source_uri:O.source_uri,source_ref:O.source_ref,revision:O.revision,hash:O.hash,provenance:P}}).sort((O,S)=>S.score-O.score).slice(0,I);return{provider:D.provider,model:D.model,dimensions:U.dimensions,query:_.query,results:A}}finally{j.close()}}function AI(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function g$(_,$){for(let D of $){let I=_[D];if(typeof I==="string"&&I.length>0)return I}return null}function f3(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return null}function y3(_){return Array.from(new Set(_))}function h3(_){let $=_.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];return y3($.filter((D)=>D.length>0)).slice(0,16)}function x3(_){return _.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]}function kT(_){let $=[],D=/"([^"]*)"|(\S+)/g,I,U=!1;while((I=D.exec(_))!==null){if(I[1]!==void 0){let O=x3(I[1]);if(O.length>0)$.push({type:"phrase",value:O.join(" "),negate:U,prefix:!1});U=!1;continue}let E=I[2]??"";if(E==="OR"||E==="||"||E==="|"){$.push({type:"or",value:"",negate:!1,prefix:!1});continue}if(E==="AND"||E==="&&")continue;if(E==="NOT"){U=!0;continue}let j=U;if(U=!1,E.startsWith("-")&&E.length>1)j=!0,E=E.slice(1);let N=!1;if(E.endsWith("*"))N=!0,E=E.slice(0,-1);let A=x3(E);if(A.length===0)continue;$.push({type:A.length>1?"phrase":"term",value:A.join(" "),negate:j,prefix:N})}return $.slice(0,24)}function qT(_){if(_.type==="phrase")return`"${_.value}"`;return`"${_.value}"*`}function CT(_){let $=kT(_);if($.filter((j)=>j.type!=="or"&&!j.negate).length===0)return{and:null,or:null};let I=(j)=>{let N="",A=!1,O=[];for(let S of $){if(S.type==="or"){A=!0;continue}let L=qT(S);if(S.negate){O.push(L);continue}if(N.length===0)N=L;else N=A?`${N} OR ${L}`:`${N} ${j} ${L}`;A=!1}for(let S of O)N=`(${N}) NOT ${S}`;return N.length>0?N:null},U=I("AND"),E=I("OR");return{and:U,or:E!==U?E:null}}function vT(_){return _.replace(/[\\%_]/g,($)=>`\\${$}`)}function c3(_,$){return _.flatMap((D)=>Array.from({length:$},()=>`%${vT(D)}%`))}function wT(_,$){let D=Number.isFinite(_)?1/(1+Math.abs(_)):0,I=1/(1+$);return OI(Math.max(D,I))}function vg(_,$){if($.length===0)return 0;let D=$.filter((I)=>_.includes(I)).length;if(D===0)return 0;return OI(Math.min(0.85,0.35+D/$.length*0.5))}function rT(_){return OI(Math.max(0,Math.min(1,(_+1)/2)))}function OI(_){return Number(_.toFixed(6))}function T0(_,$){let D=_.keyword??0,I=_.semantic??0,U=_.catalog??0,E=$?.chunk_id?0.05:0;return OI(Math.min(1,D*0.55+I*0.4+U*0.35+E))}function wg(_){let $=_.provenance;return $&&typeof $==="object"&&!Array.isArray($)?$:null}function fT(_){let $=AI(_.chunk_metadata_json),D=wg($);if(D)return D;if(!_.source_revision_id&&!_.source_uri)return null;return M6({source_ref:g$($,["source_ref"]),source_uri:_.source_uri??g$($,["source_uri"]),source_kind:_.source_kind??g$($,["source_kind"]),source_revision_id:_.source_revision_id,revision:_.revision??g$($,["revision"]),hash:_.hash??g$($,["hash"]),chunk_id:_.chunk_id,start_offset:_.start_offset??f3($,["start_offset"]),end_offset:_.end_offset??f3($,["end_offset"]),status:g$($,["status"]),resolver:"open-files-read-only"})}function u3(_,$,D){if(!$)return[];try{return xT(_,$,D)}catch{return[]}}function xT(_,$,D){return _.query(`SELECT + WHERE v.provider = ? AND v.model = ? AND v.status = 'active'`).all(D.provider,D.model).map((S)=>{let L=JSON.parse(S.vector_json),W=C2(S.metadata_json),g=W.provenance&&typeof W.provenance==="object"&&!Array.isArray(W.provenance)?W.provenance:null;return{chunk_id:S.chunk_id,score:TT(E,L,S.vector_norm),text:S.text,source_uri:S.source_uri,source_ref:S.source_ref,revision:S.revision,hash:S.hash,provenance:g}}).sort((S,L)=>L.score-S.score).slice(0,I);return{provider:D.provider,model:D.model,dimensions:U.dimensions,query:_.query,results:O}}finally{j.close()}}function SI(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function A$(_,$){for(let D of $){let I=_[D];if(typeof I==="string"&&I.length>0)return I}return null}function xg(_,$){for(let D of $){let I=_[D];if(typeof I==="number"&&Number.isFinite(I))return I}return null}function hg(_){return Array.from(new Set(_))}function cg(_){let $=_.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[];return hg($.filter((D)=>D.length>0)).slice(0,16)}function ug(_){return _.normalize("NFKC").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[]}function qT(_){let $=[],D=/"([^"]*)"|(\S+)/g,I,U=!1;while((I=D.exec(_))!==null){if(I[1]!==void 0){let S=ug(I[1]);if(S.length>0)$.push({type:"phrase",value:S.join(" "),negate:U,prefix:!1});U=!1;continue}let E=I[2]??"";if(E==="OR"||E==="||"||E==="|"){$.push({type:"or",value:"",negate:!1,prefix:!1});continue}if(E==="AND"||E==="&&")continue;if(E==="NOT"){U=!0;continue}let j=U;if(U=!1,E.startsWith("-")&&E.length>1)j=!0,E=E.slice(1);let N=!1;if(E.endsWith("*"))N=!0,E=E.slice(0,-1);let O=ug(E);if(O.length===0)continue;$.push({type:O.length>1?"phrase":"term",value:O.join(" "),negate:j,prefix:N})}return $.slice(0,24)}function kT(_){if(_.type==="phrase")return`"${_.value}"`;return`"${_.value}"*`}function CT(_){let $=qT(_);if($.filter((j)=>j.type!=="or"&&!j.negate).length===0)return{and:null,or:null};let I=(j)=>{let N="",O=!1,S=[];for(let L of $){if(L.type==="or"){O=!0;continue}let W=kT(L);if(L.negate){S.push(W);continue}if(N.length===0)N=W;else N=O?`${N} OR ${W}`:`${N} ${j} ${W}`;O=!1}for(let L of S)N=`(${N}) NOT ${L}`;return N.length>0?N:null},U=I("AND"),E=I("OR");return{and:U,or:E!==U?E:null}}function vT(_){return _.replace(/[\\%_]/g,($)=>`\\${$}`)}function ng(_,$){return _.flatMap((D)=>Array.from({length:$},()=>`%${vT(D)}%`))}function wT(_,$){let D=Number.isFinite(_)?1/(1+Math.abs(_)):0,I=1/(1+$);return LI(Math.max(D,I))}function v2(_,$){if($.length===0)return 0;let D=$.filter((I)=>_.includes(I)).length;if(D===0)return 0;return LI(Math.min(0.85,0.35+D/$.length*0.5))}function rT(_){return LI(Math.max(0,Math.min(1,(_+1)/2)))}function LI(_){return Number(_.toFixed(6))}function V0(_,$){let D=_.keyword??0,I=_.semantic??0,U=_.catalog??0,E=$?.chunk_id?0.05:0;return LI(Math.min(1,D*0.55+I*0.4+U*0.35+E))}function w2(_){let $=_.provenance;return $&&typeof $==="object"&&!Array.isArray($)?$:null}function fT(_){let $=SI(_.chunk_metadata_json),D=w2($);if(D)return D;if(!_.source_revision_id&&!_.source_uri)return null;return M6({source_ref:A$($,["source_ref"]),source_uri:_.source_uri??A$($,["source_uri"]),source_kind:_.source_kind??A$($,["source_kind"]),source_revision_id:_.source_revision_id,revision:_.revision??A$($,["revision"]),hash:_.hash??A$($,["hash"]),chunk_id:_.chunk_id,start_offset:_.start_offset??xg($,["start_offset"]),end_offset:_.end_offset??xg($,["end_offset"]),status:A$($,["status"]),resolver:"open-files-read-only"})}function yg(_,$,D){if(!$)return[];try{return xT(_,$,D)}catch{return[]}}function xT(_,$,D){return _.query(`SELECT chunks_fts.chunk_id, c.kind AS chunk_kind, c.wiki_page_id, @@ -786,38 +786,38 @@ VALUES (10, datetime('now')); LEFT JOIN wiki_pages wp ON wp.id = c.wiki_page_id WHERE chunks_fts MATCH ? ORDER BY rank ASC - LIMIT ?`).all($,D)}function n3(_,$){if($.length===0)return"1 = 0";return $.map(()=>`(${_.map((I)=>`lower(COALESCE(${I}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`).join(" OR ")}function uT(_,$,D){let I=["path","title","artifact_uri","metadata_json"];return _.query(`SELECT id, path, title, artifact_uri, content_hash, status, metadata_json + LIMIT ?`).all($,D)}function dg(_,$){if($.length===0)return"1 = 0";return $.map(()=>`(${_.map((I)=>`lower(COALESCE(${I}, '')) LIKE ? ESCAPE '\\'`).join(" OR ")})`).join(" OR ")}function uT(_,$,D){let I=["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 (${n3(I,$)}) + WHERE status = 'active' AND (${dg(I,$)}) ORDER BY updated_at DESC - LIMIT ?`).all(...c3($,I.length),D)}function yT(_,$,D){let I=["kind","name","shard_key","artifact_uri","metadata_json"];return _.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json + LIMIT ?`).all(...ng($,I.length),D)}function yT(_,$,D){let I=["kind","name","shard_key","artifact_uri","metadata_json"];return _.query(`SELECT id, kind, name, artifact_uri, shard_key, metadata_json FROM knowledge_indexes - WHERE ${n3(I,$)} + WHERE ${dg(I,$)} ORDER BY updated_at DESC - LIMIT ?`).all(...c3($,I.length),D)}function d3(_){if(!_||!ZT(_))return[];try{let $=JSON.parse(HT(_,"utf8"));if(!$||!Array.isArray($.items))return[];return $.items.filter((D)=>{return Boolean(D&&typeof D==="object"&&typeof D.id==="string"&&typeof D.title==="string"&&typeof D.content==="string")})}catch{return[]}}function hT(_){return[_.id,_.short_id,_.title,_.content,_.url,..._.tags??[]].filter(($)=>typeof $==="string"&&$.length>0).join(" ").toLowerCase()}function m3(_,$,D){if($.length===0)return[];return _.filter((I)=>I.archived!==!0).map((I)=>({item:I,haystack:hT(I)})).filter(({haystack:I})=>$.some((U)=>I.includes(U))).map(({item:I,haystack:U})=>({item:I,score:vg(U,$)})).sort((I,U)=>U.score-I.score||I.item.id.localeCompare(U.item.id)).slice(0,D)}function cT(_,$,D){return m3(d3(_),$,D)}function nT(_,$){let D=AI(_.chunk_metadata_json),I=fT(_),U=g$(D,["source_ref"]),E=_.source_uri??g$(D,["source_uri"]),j=Boolean(_.wiki_page_id),N={kind:j?"wiki_chunk":"source_chunk",id:_.chunk_id,title:j?_.wiki_title:_.source_title,text:_.text,score:0,scores:{keyword:$},source:E||U?{uri:E,ref:U,kind:_.source_kind??g$(D,["source_kind"]),revision:_.revision??g$(D,["revision"]),hash:_.hash??g$(D,["hash"])}:null,citation:{chunk_id:_.chunk_id,start_offset:_.start_offset,end_offset:_.end_offset},artifact:j?{uri:_.wiki_artifact_uri,path:_.wiki_path,hash:_.wiki_content_hash,shard_key:_.wiki_path}:null,provenance:I,reasons:["keyword_match"]};return N.score=T0(N.scores,N.citation),N}function rg(_,$){let D=`knowledge://item/${encodeURIComponent(_.id)}`,I={kind:"legacy_item",id:_.id,title:_.title,text:_.content,score:0,scores:{keyword:$},source:{uri:D,ref:D,kind:"legacy_item",revision:null,hash:null},citation:null,artifact:null,provenance:null,reasons:["legacy_note_match","keyword_match"]};return I.score=T0(I.scores,I.citation),I}function dT(_,$){let D=AI(_.metadata_json),I=vg(`${_.path} ${_.title} ${_.artifact_uri??""} ${_.metadata_json}`.toLowerCase(),$),U={kind:"wiki_page",id:_.id,title:_.title,text:null,score:0,scores:{catalog:I},source:null,citation:null,artifact:{uri:_.artifact_uri,path:_.path,hash:_.content_hash,shard_key:_.path},provenance:wg(D),reasons:["wiki_catalog_match"]};return U.score=T0(U.scores,U.citation),U}function mT(_,$){let D=AI(_.metadata_json),I=vg(`${_.kind} ${_.name} ${_.shard_key??""} ${_.artifact_uri??""} ${_.metadata_json}`.toLowerCase(),$),U={kind:"knowledge_index",id:_.id,title:_.name,text:null,score:0,scores:{catalog:I},source:null,citation:null,artifact:{uri:_.artifact_uri,path:g$(D,["artifact_key"]),hash:g$(D,["content_hash"]),shard_key:_.shard_key},provenance:wg(D),reasons:["index_catalog_match"]};return U.score=T0(U.scores,U.citation),U}function K0(_,$){let D=`${$.kind}:${$.id}`,I=_.get(D);if(!I){_.set(D,$);return}I.scores={keyword:Math.max(I.scores.keyword??0,$.scores.keyword??0)||void 0,semantic:Math.max(I.scores.semantic??0,$.scores.semantic??0)||void 0,catalog:Math.max(I.scores.catalog??0,$.scores.catalog??0)||void 0},I.reasons=y3([...I.reasons,...$.reasons]),I.text=I.text??$.text,I.title=I.title??$.title,I.source=I.source??$.source,I.citation=I.citation??$.citation,I.artifact=I.artifact??$.artifact,I.provenance=I.provenance??$.provenance,I.score=T0(I.scores,I.citation)}function l3(_){let $={source_chunk:0,wiki_chunk:1,legacy_item:2,wiki_page:3,knowledge_index:4};return _.sort((D,I)=>{if(I.score!==D.score)return I.score-D.score;return $[D.kind]-$[I.kind]||D.id.localeCompare(I.id)})}async function SI(_){let $=_.query.trim();if(!$)throw Error("Search query is required.");let D=Math.max(1,Math.min(_.limit??10,100)),I=Math.max(0,Math.floor(_.offset??0)),U=I+D,E=h3($),j=CT($),N=_.semantic===!0||_.fake===!0||Boolean(_.modelRef),A=[],O=null,S=null,L=null,P=0,z=0,G=0,J=new Map;c(_.dbPath);let W=w(_.dbPath);try{let T=Math.max(U*3,20),Y=u3(W,j.and,T);if(Y.length===0&&j.or)Y=u3(W,j.or,T);P=Y.length,Y.forEach((Z,f)=>K0(J,nT(Z,wT(Z.rank,f))));let Q=uT(W,E,Math.max(U,10)),F=yT(W,E,Math.max(U,10)),q=cT(_.legacyStorePath,E,Math.max(U,10));z=Q.length+F.length,P+=q.length,q.forEach(({item:Z,score:f})=>K0(J,rg(Z,f))),Q.forEach((Z)=>K0(J,dT(Z,E))),F.forEach((Z)=>K0(J,mT(Z,E)))}finally{W.close()}if(N)try{let T=await gI({dbPath:_.dbPath,query:$,limit:Math.max(U*3,20),config:_.config,env:_.env,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake,batchSize:_.batchSize,maxParallelCalls:_.maxParallelCalls});O=T.provider,S=T.model,L=T.dimensions,G=T.results.length;for(let Y of T.results){let Q={kind:"source_chunk",id:Y.chunk_id,title:null,text:Y.text,score:0,scores:{semantic:rT(Y.score)},source:{uri:Y.source_uri,ref:Y.source_ref,kind:Y.provenance?.source_kind??null,revision:Y.revision,hash:Y.hash},citation:{chunk_id:Y.chunk_id,start_offset:Y.provenance?.start_offset??null,end_offset:Y.provenance?.end_offset??null},artifact:null,provenance:Y.provenance,reasons:["semantic_match"]};Q.score=T0(Q.scores,Q.citation),K0(J,Q)}}catch(T){A.push(`semantic_search_failed: ${T instanceof Error?T.message:String(T)}`)}let R=l3(Array.from(J.values())).slice(I,I+D);return{query:$,limit:D,offset:I,mode:{keyword:!0,catalog:!0,semantic:N},semantic_provider:O,semantic_model:S,semantic_dimensions:L,counts:{keyword_results:P,catalog_results:z,semantic_results:G,merged_results:R.length},warnings:A,results:R}}async function LI(_){return fg(d3(_.legacyStorePath),_,["knowledge_db_missing"])}async function fg(_,$,D=[]){let I=$.query.trim();if(!I)throw Error("Search query is required.");let U=Math.max(1,Math.min($.limit??10,100)),E=Math.max(0,Math.floor($.offset??0)),j=h3(I),N=$.semantic===!0||$.fake===!0||Boolean($.modelRef),A=new Map,O=m3(_,j,Math.max(E+U,10));O.forEach(({item:P,score:z})=>K0(A,rg(P,z)));let S=[...D];if(N)S.push("semantic_search_requires_local_catalog");let L=l3(Array.from(A.values())).slice(E,E+U);return{query:I,limit:U,offset:E,mode:{keyword:!0,catalog:!0,semantic:N},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:O.length,catalog_results:0,semantic_results:0,merged_results:L.length},warnings:S,results:L}}function xg(_,$,D=[],I=_.length){let U=$.query.trim();if(!U)throw Error("Search query is required.");let E=Math.max(1,Math.min($.limit??10,100)),j=Math.max(0,Math.floor($.offset??0)),N=_.map(({item:A,rank:O})=>rg(A,O));return{query:U,limit:E,offset:j,mode:{keyword:!0,catalog:!0,semantic:$.semantic===!0},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:I,catalog_results:0,semantic_results:0,merged_results:N.length},warnings:D,results:N}}function i3(_,$){return`${_}_${lT("sha256").update($).digest("hex").slice(0,20)}`}function t3(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function iT(_){return Array.from(new Set(t3(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,16)}function tT(_){return[_.title,_.text].filter(Boolean).join(" ").toLowerCase()}function oT(_,$){if($.length===0)return 0;let D=tT(_),I=$.filter((U)=>D.includes(U)).length;return Number((I/$.length).toFixed(6))}function pT(_){if(!_)return!0;if("read_only"in _)return _.read_only===!0;if("read_only_sources"in _)return _.read_only_sources===!0;return!0}function o3(_){if(!_)return!1;if("stale"in _&&_.stale)return!0;if("status"in _)return Qg(_.status);return!1}function eT(_){if(o3(_.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 aT(_){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 sT(_){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 _F(_,$){let D={base_score:_.score,exact_score:oT(_,$),citation_score:aT(_),freshness_score:eT(_),authority_score:sT(_)},I=Math.min(1,D.base_score*0.65+D.exact_score*0.1+D.citation_score*0.1+D.freshness_score*0.1+D.authority_score*0.05),U=new Set(_.reasons);if(D.exact_score>0.5)U.add("exact_term");if(D.citation_score>=0.75)U.add("cited_source");if(D.freshness_score>=0.85)U.add("fresh_source");return{..._,score:Number(I.toFixed(6)),reasons:Array.from(U),rerank:{...D,final_score:Number(I.toFixed(6))}}}function p3(_,$){let D=_.text??_.title;if(!D)return null;let I=D.replace(/\s+/g," ").trim();return I.length<=$?I:`${I.slice(0,Math.max(0,$-1)).trim()}...`}function $F(_){return{id:i3("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:p3(_,500),provenance:_.provenance}}function DF(_,$,D){let I=p3(_,D);if(!I)return null;return{id:i3("excerpt",`${_.kind}\x00${_.id}`),result_id:_.id,citation_id:$.id,kind:_.kind,text:I,score:_.score}}function JI(_){return _.map(()=>"?").join(", ")}function UF(_,$){let D=$.map((N)=>N.citation?.chunk_id).filter((N)=>Boolean(N)),I=$.filter((N)=>N.kind==="wiki_page").map((N)=>N.id),U=[],E=[];if(D.length===0&&I.length===0)return{citations:U,backlinks:E};let j=w(_);try{if(D.length>0)U.push(...j.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset + LIMIT ?`).all(...ng($,I.length),D)}function mg(_){if(!_||!HT(_))return[];try{let $=JSON.parse(bT(_,"utf8"));if(!$||!Array.isArray($.items))return[];return $.items.filter((D)=>{return Boolean(D&&typeof D==="object"&&typeof D.id==="string"&&typeof D.title==="string"&&typeof D.content==="string")})}catch{return[]}}function hT(_){return[_.id,_.short_id,_.title,_.content,_.url,..._.tags??[]].filter(($)=>typeof $==="string"&&$.length>0).join(" ").toLowerCase()}function lg(_,$,D){if($.length===0)return[];return _.filter((I)=>I.archived!==!0).map((I)=>({item:I,haystack:hT(I)})).filter(({haystack:I})=>$.some((U)=>I.includes(U))).map(({item:I,haystack:U})=>({item:I,score:v2(U,$)})).sort((I,U)=>U.score-I.score||I.item.id.localeCompare(U.item.id)).slice(0,D)}function cT(_,$,D){return lg(mg(_),$,D)}function nT(_,$){let D=SI(_.chunk_metadata_json),I=fT(_),U=A$(D,["source_ref"]),E=_.source_uri??A$(D,["source_uri"]),j=Boolean(_.wiki_page_id),N={kind:j?"wiki_chunk":"source_chunk",id:_.chunk_id,title:j?_.wiki_title:_.source_title,text:_.text,score:0,scores:{keyword:$},source:E||U?{uri:E,ref:U,kind:_.source_kind??A$(D,["source_kind"]),revision:_.revision??A$(D,["revision"]),hash:_.hash??A$(D,["hash"])}:null,citation:{chunk_id:_.chunk_id,start_offset:_.start_offset,end_offset:_.end_offset},artifact:j?{uri:_.wiki_artifact_uri,path:_.wiki_path,hash:_.wiki_content_hash,shard_key:_.wiki_path}:null,provenance:I,reasons:["keyword_match"]};return N.score=V0(N.scores,N.citation),N}function r2(_,$){let D=`knowledge://item/${encodeURIComponent(_.id)}`,I={kind:"legacy_item",id:_.id,title:_.title,text:_.content,score:0,scores:{keyword:$},source:{uri:D,ref:D,kind:"legacy_item",revision:null,hash:null},citation:null,artifact:null,provenance:null,reasons:["legacy_note_match","keyword_match"]};return I.score=V0(I.scores,I.citation),I}function dT(_,$){let D=SI(_.metadata_json),I=v2(`${_.path} ${_.title} ${_.artifact_uri??""} ${_.metadata_json}`.toLowerCase(),$),U={kind:"wiki_page",id:_.id,title:_.title,text:null,score:0,scores:{catalog:I},source:null,citation:null,artifact:{uri:_.artifact_uri,path:_.path,hash:_.content_hash,shard_key:_.path},provenance:w2(D),reasons:["wiki_catalog_match"]};return U.score=V0(U.scores,U.citation),U}function mT(_,$){let D=SI(_.metadata_json),I=v2(`${_.kind} ${_.name} ${_.shard_key??""} ${_.artifact_uri??""} ${_.metadata_json}`.toLowerCase(),$),U={kind:"knowledge_index",id:_.id,title:_.name,text:null,score:0,scores:{catalog:I},source:null,citation:null,artifact:{uri:_.artifact_uri,path:A$(D,["artifact_key"]),hash:A$(D,["content_hash"]),shard_key:_.shard_key},provenance:w2(D),reasons:["index_catalog_match"]};return U.score=V0(U.scores,U.citation),U}function F0(_,$){let D=`${$.kind}:${$.id}`,I=_.get(D);if(!I){_.set(D,$);return}I.scores={keyword:Math.max(I.scores.keyword??0,$.scores.keyword??0)||void 0,semantic:Math.max(I.scores.semantic??0,$.scores.semantic??0)||void 0,catalog:Math.max(I.scores.catalog??0,$.scores.catalog??0)||void 0},I.reasons=hg([...I.reasons,...$.reasons]),I.text=I.text??$.text,I.title=I.title??$.title,I.source=I.source??$.source,I.citation=I.citation??$.citation,I.artifact=I.artifact??$.artifact,I.provenance=I.provenance??$.provenance,I.score=V0(I.scores,I.citation)}function ig(_){let $={source_chunk:0,wiki_chunk:1,legacy_item:2,wiki_page:3,knowledge_index:4};return _.sort((D,I)=>{if(I.score!==D.score)return I.score-D.score;return $[D.kind]-$[I.kind]||D.id.localeCompare(I.id)})}async function WI(_){let $=_.query.trim();if(!$)throw Error("Search query is required.");let D=Math.max(1,Math.min(_.limit??10,100)),I=Math.max(0,Math.floor(_.offset??0)),U=I+D,E=cg($),j=CT($),N=_.semantic===!0||_.fake===!0||Boolean(_.modelRef),O=[],S=null,L=null,W=null,g=0,z=0,G=0,J=new Map;c(_.dbPath);let P=w(_.dbPath);try{let T=Math.max(U*3,20),Y=yg(P,j.and,T);if(Y.length===0&&j.or)Y=yg(P,j.or,T);g=Y.length,Y.forEach((b,f)=>F0(J,nT(b,wT(b.rank,f))));let Q=uT(P,E,Math.max(U,10)),F=yT(P,E,Math.max(U,10)),B=cT(_.legacyStorePath,E,Math.max(U,10));z=Q.length+F.length,g+=B.length,B.forEach(({item:b,score:f})=>F0(J,r2(b,f))),Q.forEach((b)=>F0(J,dT(b,E))),F.forEach((b)=>F0(J,mT(b,E)))}finally{P.close()}if(N)try{let T=await OI({dbPath:_.dbPath,query:$,limit:Math.max(U*3,20),config:_.config,env:_.env,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake,batchSize:_.batchSize,maxParallelCalls:_.maxParallelCalls});S=T.provider,L=T.model,W=T.dimensions,G=T.results.length;for(let Y of T.results){let Q={kind:"source_chunk",id:Y.chunk_id,title:null,text:Y.text,score:0,scores:{semantic:rT(Y.score)},source:{uri:Y.source_uri,ref:Y.source_ref,kind:Y.provenance?.source_kind??null,revision:Y.revision,hash:Y.hash},citation:{chunk_id:Y.chunk_id,start_offset:Y.provenance?.start_offset??null,end_offset:Y.provenance?.end_offset??null},artifact:null,provenance:Y.provenance,reasons:["semantic_match"]};Q.score=V0(Q.scores,Q.citation),F0(J,Q)}}catch(T){O.push(`semantic_search_failed: ${T instanceof Error?T.message:String(T)}`)}let R=ig(Array.from(J.values())).slice(I,I+D);return{query:$,limit:D,offset:I,mode:{keyword:!0,catalog:!0,semantic:N},semantic_provider:S,semantic_model:L,semantic_dimensions:W,counts:{keyword_results:g,catalog_results:z,semantic_results:G,merged_results:R.length},warnings:O,results:R}}async function JI(_){return f2(mg(_.legacyStorePath),_,["knowledge_db_missing"])}async function f2(_,$,D=[]){let I=$.query.trim();if(!I)throw Error("Search query is required.");let U=Math.max(1,Math.min($.limit??10,100)),E=Math.max(0,Math.floor($.offset??0)),j=cg(I),N=$.semantic===!0||$.fake===!0||Boolean($.modelRef),O=new Map,S=lg(_,j,Math.max(E+U,10));S.forEach(({item:g,score:z})=>F0(O,r2(g,z)));let L=[...D];if(N)L.push("semantic_search_requires_local_catalog");let W=ig(Array.from(O.values())).slice(E,E+U);return{query:I,limit:U,offset:E,mode:{keyword:!0,catalog:!0,semantic:N},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:S.length,catalog_results:0,semantic_results:0,merged_results:W.length},warnings:L,results:W}}function x2(_,$,D=[],I=_.length){let U=$.query.trim();if(!U)throw Error("Search query is required.");let E=Math.max(1,Math.min($.limit??10,100)),j=Math.max(0,Math.floor($.offset??0)),N=_.map(({item:O,rank:S})=>r2(O,S));return{query:U,limit:E,offset:j,mode:{keyword:!0,catalog:!0,semantic:$.semantic===!0},semantic_provider:null,semantic_model:null,semantic_dimensions:null,counts:{keyword_results:I,catalog_results:0,semantic_results:0,merged_results:N.length},warnings:D,results:N}}function tg(_,$){return`${_}_${lT("sha256").update($).digest("hex").slice(0,20)}`}function og(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function iT(_){return Array.from(new Set(og(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,16)}function tT(_){return[_.title,_.text].filter(Boolean).join(" ").toLowerCase()}function oT(_,$){if($.length===0)return 0;let D=tT(_),I=$.filter((U)=>D.includes(U)).length;return Number((I/$.length).toFixed(6))}function pT(_){if(!_)return!0;if("read_only"in _)return _.read_only===!0;if("read_only_sources"in _)return _.read_only_sources===!0;return!0}function pg(_){if(!_)return!1;if("stale"in _&&_.stale)return!0;if("status"in _)return Q2(_.status);return!1}function eT(_){if(pg(_.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 aT(_){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 sT(_){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 _F(_,$){let D={base_score:_.score,exact_score:oT(_,$),citation_score:aT(_),freshness_score:eT(_),authority_score:sT(_)},I=Math.min(1,D.base_score*0.65+D.exact_score*0.1+D.citation_score*0.1+D.freshness_score*0.1+D.authority_score*0.05),U=new Set(_.reasons);if(D.exact_score>0.5)U.add("exact_term");if(D.citation_score>=0.75)U.add("cited_source");if(D.freshness_score>=0.85)U.add("fresh_source");return{..._,score:Number(I.toFixed(6)),reasons:Array.from(U),rerank:{...D,final_score:Number(I.toFixed(6))}}}function eg(_,$){let D=_.text??_.title;if(!D)return null;let I=D.replace(/\s+/g," ").trim();return I.length<=$?I:`${I.slice(0,Math.max(0,$-1)).trim()}...`}function $F(_){return{id:tg("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:eg(_,500),provenance:_.provenance}}function DF(_,$,D){let I=eg(_,D);if(!I)return null;return{id:tg("excerpt",`${_.kind}\x00${_.id}`),result_id:_.id,citation_id:$.id,kind:_.kind,text:I,score:_.score}}function PI(_){return _.map(()=>"?").join(", ")}function UF(_,$){let D=$.map((N)=>N.citation?.chunk_id).filter((N)=>Boolean(N)),I=$.filter((N)=>N.kind==="wiki_page").map((N)=>N.id),U=[],E=[];if(D.length===0&&I.length===0)return{citations:U,backlinks:E};let j=w(_);try{if(D.length>0)U.push(...j.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset FROM citations - WHERE chunk_id IN (${JI(D)}) + WHERE chunk_id IN (${PI(D)}) ORDER BY created_at DESC LIMIT 50`).all(...D));if(I.length>0)U.push(...j.query(`SELECT id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset FROM citations - WHERE wiki_page_id IN (${JI(I)}) + WHERE wiki_page_id IN (${PI(I)}) ORDER BY created_at DESC LIMIT 50`).all(...I)),E.push(...j.query(`SELECT from_page_id, to_page_id, label FROM wiki_backlinks - WHERE from_page_id IN (${JI(I)}) OR to_page_id IN (${JI(I)}) - LIMIT 50`).all(...I,...I))}finally{j.close()}return{citations:U,backlinks:E}}function A6(_,$={}){let D=Math.max(200,Math.min($.contextChars??1200,4000)),I=iT(_.query),U=[..._.warnings],E=new Set,j=new Set,A=_.results.filter((L)=>{if(!pT(L.provenance))return U.push(`permission_filtered: ${L.kind}:${L.id}`),E.add("Dropped a result because provenance was not read-only."),!1;if(o3(L.provenance))return U.push(`stale_filtered: ${L.kind}:${L.id}`),j.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((L)=>_F(L,I)).sort((L,P)=>P.score-L.score||L.id.localeCompare(P.id)).slice(0,_.limit),O=A.map($F),S=A.map((L,P)=>DF(L,O[P],D)).filter((L)=>Boolean(L));for(let L of A){if(L.provenance&&"read_only"in L.provenance&&L.provenance.read_only)E.add("All source-backed excerpts are read-only and citation-required.");if(L.rerank.freshness_score>=0.85)j.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:_.query,normalized_query:t3(_.query),created_at:new Date().toISOString(),mode:_.mode,warnings:U,search_counts:_.counts,results:A,citations:O,excerpts:S,graph:$.dbPath?UF($.dbPath,A):{citations:[],backlinks:[]},notes:{permissions:Array.from(E),freshness:Array.from(j)}}}async function F0(_){let $=await SI(_);return A6($,{dbPath:_.dbPath,contextChars:_.contextChars})}async function e3(_,$){let D=await fg(_,$);return A6(D,{contextChars:$.contextChars})}function V0(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function yg(_){return`C${_+1}`}function s3(_,$){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((I,U)=>{let E=$.citations.find((N)=>N.id===I.citation_id),j=E?.source_ref??E?.source_uri??E?.artifact_path??E?.artifact_uri??"unknown source";return`[${yg(U)}] ${I.text} (${j})`})].join(` -`)}function _X(_,$){let D=$.citations.map((U,E)=>({id:yg(E),source_ref:U.source_ref,source_uri:U.source_uri,artifact_path:U.artifact_path,revision:U.revision,hash:U.hash,quote:U.quote})),I=$.excerpts.map((U,E)=>({id:yg(E),kind:U.kind,text:U.text,score:U.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 (${PI(I)}) OR to_page_id IN (${PI(I)}) + LIMIT 50`).all(...I,...I))}finally{j.close()}return{citations:U,backlinks:E}}function O6(_,$={}){let D=Math.max(200,Math.min($.contextChars??1200,4000)),I=iT(_.query),U=[..._.warnings],E=new Set,j=new Set,O=_.results.filter((W)=>{if(!pT(W.provenance))return U.push(`permission_filtered: ${W.kind}:${W.id}`),E.add("Dropped a result because provenance was not read-only."),!1;if(pg(W.provenance))return U.push(`stale_filtered: ${W.kind}:${W.id}`),j.add("Dropped a stale result whose source status requires reindexing."),!1;return!0}).map((W)=>_F(W,I)).sort((W,g)=>g.score-W.score||W.id.localeCompare(g.id)).slice(0,_.limit),S=O.map($F),L=O.map((W,g)=>DF(W,S[g],D)).filter((W)=>Boolean(W));for(let W of O){if(W.provenance&&"read_only"in W.provenance&&W.provenance.read_only)E.add("All source-backed excerpts are read-only and citation-required.");if(W.rerank.freshness_score>=0.85)j.add("Fresh source revision/hash or artifact hash is present for top context.")}return{query:_.query,normalized_query:og(_.query),created_at:new Date().toISOString(),mode:_.mode,warnings:U,search_counts:_.counts,results:O,citations:S,excerpts:L,graph:$.dbPath?UF($.dbPath,O):{citations:[],backlinks:[]},notes:{permissions:Array.from(E),freshness:Array.from(j)}}}async function B0(_){let $=await WI(_);return O6($,{dbPath:_.dbPath,contextChars:_.contextChars})}async function ag(_,$){let D=await f2(_,$);return O6(D,{contextChars:$.contextChars})}function M0(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function y2(_){return`C${_+1}`}function _X(_,$){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((I,U)=>{let E=$.citations.find((N)=>N.id===I.citation_id),j=E?.source_ref??E?.source_uri??E?.artifact_path??E?.artifact_uri??"unknown source";return`[${y2(U)}] ${I.text} (${j})`})].join(` +`)}function $X(_,$){let D=$.citations.map((U,E)=>({id:y2(E),source_ref:U.source_ref,source_uri:U.source_uri,artifact_path:U.artifact_path,revision:U.revision,hash:U.hash,quote:U.quote})),I=$.excerpts.map((U,E)=>({id:y2(E),kind:U.kind,text:U.text,score:U.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(I,null,2)}`,"",`Citations: ${JSON.stringify(D,null,2)}`].join(` -`)}function $X(_,$){if($.citations.length===0)return[];return[{kind:"answer_note",title:_.length>80?`${_.slice(0,77)}...`:_,citations:$.citations.map((D)=>D.id),requires_approval:!0}]}function IF(_,$){let D=w(_);try{D.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{D.close()}}function ug(_,$){let D=w(_);try{D.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${hg()}`,$.runId,$.level,$.event,JSON.stringify($.metadata),$.now])}finally{D.close()}}function a3(_,$){let D=w(_);try{D.run(`UPDATE runs +`)}function DX(_,$){if($.citations.length===0)return[];return[{kind:"answer_note",title:_.length>80?`${_.slice(0,77)}...`:_,citations:$.citations.map((D)=>D.id),requires_approval:!0}]}function IF(_,$){let D=w(_);try{D.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{D.close()}}function u2(_,$){let D=w(_);try{D.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${h2()}`,$.runId,$.level,$.event,JSON.stringify($.metadata),$.now])}finally{D.close()}}function sg(_,$){let D=w(_);try{D.run(`UPDATE runs SET status = ?, provider = ?, model = ?, metadata_json = ?, updated_at = ? - WHERE id = ?`,[$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.runId])}finally{D.close()}}function EF(_,$,D,I,U,E,j={}){let N=w(_);try{Q0(N,{run_id:$,provider:I,model:U,input_tokens:D.input_tokens,output_tokens:D.output_tokens,cost_usd:D.cost_usd,metadata:j,created_at:E})}finally{N.close()}}async function DX(_){let $=_.prompt.trim();if(!$)throw Error("Knowledge prompt is required.");let D=(_.now??new Date).toISOString(),I=`run_${hg()}`,U=T$(_.modelRef??"default",_.config),E=f_(U);c(_.dbPath),IF(_.dbPath,{runId:I,prompt:$,status:_.generate?"running":"dry_run",provider:_.generate?E.provider:"local",model:_.generate?E.model:"context-draft",metadata:{semantic:_.semantic===!0||_.fake===!0||Boolean(_.modelRef),approve_write:_.approveWrite===!0,generated:_.generate===!0},now:D});let{prompt:j,generate:N,approveWrite:A,now:O,...S}=_,L=await F0({...S,query:$});ug(_.dbPath,{runId:I,level:"info",event:"context_retrieved",metadata:{results:L.results.length,citations:L.citations.length,warnings:L.warnings},now:D});let P=s3($,L),z=!1,G="local",J="context-draft",W={input_tokens:V0($)+L.excerpts.reduce((Y,Q)=>Y+V0(Q.text),0),output_tokens:V0(P),cost_usd:0},X=[...L.warnings];if(_.generate)try{if(_.fake)z=!0,G=E.provider,J=E.model,P=`Fake generated answer for: ${$} + WHERE id = ?`,[$.status,$.provider,$.model,JSON.stringify($.metadata),$.now,$.runId])}finally{D.close()}}function EF(_,$,D,I,U,E,j={}){let N=w(_);try{T0(N,{run_id:$,provider:I,model:U,input_tokens:D.input_tokens,output_tokens:D.output_tokens,cost_usd:D.cost_usd,metadata:j,created_at:E})}finally{N.close()}}async function UX(_){let $=_.prompt.trim();if(!$)throw Error("Knowledge prompt is required.");let D=(_.now??new Date).toISOString(),I=`run_${h2()}`,U=T$(_.modelRef??"default",_.config),E=f_(U);c(_.dbPath),IF(_.dbPath,{runId:I,prompt:$,status:_.generate?"running":"dry_run",provider:_.generate?E.provider:"local",model:_.generate?E.model:"context-draft",metadata:{semantic:_.semantic===!0||_.fake===!0||Boolean(_.modelRef),approve_write:_.approveWrite===!0,generated:_.generate===!0},now:D});let{prompt:j,generate:N,approveWrite:O,now:S,...L}=_,W=await B0({...L,query:$});u2(_.dbPath,{runId:I,level:"info",event:"context_retrieved",metadata:{results:W.results.length,citations:W.citations.length,warnings:W.warnings},now:D});let g=_X($,W),z=!1,G="local",J="context-draft",P={input_tokens:M0($)+W.excerpts.reduce((Y,Q)=>Y+M0(Q.text),0),output_tokens:M0(g),cost_usd:0},X=[...W.warnings];if(_.generate)try{if(_.fake)z=!0,G=E.provider,J=E.model,g=`Fake generated answer for: ${$} -${P}`;else{let{generateText:Y}=await import("ai"),Q=await lD(U,{config:_.config,env:_.env}),F=await Y({model:Q,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:_X($,L)});z=!0,G=E.provider,J=E.model,P=F.text;let q=O4({provider:G,model:J,usage:F.usage,providerMetadata:F.providerMetadata});W={input_tokens:q.input_tokens,output_tokens:q.output_tokens,cost_usd:q.cost_usd}}}catch(Y){throw ug(_.dbPath,{runId:I,level:"error",event:"answer_generation_failed",metadata:{message:Y instanceof Error?Y.message:String(Y)},now:D}),a3(_.dbPath,{runId:I,status:"failed",provider:E.provider,model:E.model,metadata:{generated:!1,error:Y instanceof Error?Y.message:String(Y)},now:D}),Y}let R=$X($,L),T={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 ug(_.dbPath,{runId:I,level:"info",event:z?"answer_generated":"answer_drafted",metadata:{provider:G,model:J,proposed_updates:R.length,durable_writes_performed:!1},now:D}),EF(_.dbPath,I,W,G,J,D,{generated:z,citations:L.citations.length}),a3(_.dbPath,{runId:I,status:z?"completed":"dry_run",provider:G,model:J,metadata:{generated:z,citations:L.citations.length,proposed_updates:R.length,approve_write:_.approveWrite===!0},now:D}),{run_id:I,prompt:$,generated:z,provider:G,model:J,answer:P,context:L,citations:L.citations,proposed_wiki_updates:R,write_policy:T,usage:W,warnings:X}}async function UX(_,$,D){let I=$.prompt.trim();if(!I)throw Error("Knowledge prompt is required.");let U=`run_${hg()}`,E=T$($.modelRef??"default",$.config),j=f_(E),{prompt:N,generate:A,approveWrite:O,now:S,...L}=$,P=D?A6(D,{contextChars:$.contextChars}):await e3(_,{...L,query:I}),z=s3(I,P),G=!1,J="local",W="context-draft",X={input_tokens:V0(I)+P.excerpts.reduce((Q,F)=>Q+V0(F.text),0),output_tokens:V0(z),cost_usd:0},R=[...P.warnings];if($.generate)if($.fake)G=!0,J=j.provider,W=j.model,z=`Fake generated answer for: ${I} +${g}`;else{let{generateText:Y}=await import("ai"),Q=await lD(U,{config:_.config,env:_.env}),F=await Y({model:Q,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:$X($,W)});z=!0,G=E.provider,J=E.model,g=F.text;let B=L4({provider:G,model:J,usage:F.usage,providerMetadata:F.providerMetadata});P={input_tokens:B.input_tokens,output_tokens:B.output_tokens,cost_usd:B.cost_usd}}}catch(Y){throw u2(_.dbPath,{runId:I,level:"error",event:"answer_generation_failed",metadata:{message:Y instanceof Error?Y.message:String(Y)},now:D}),sg(_.dbPath,{runId:I,status:"failed",provider:E.provider,model:E.model,metadata:{generated:!1,error:Y instanceof Error?Y.message:String(Y)},now:D}),Y}let R=DX($,W),T={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 u2(_.dbPath,{runId:I,level:"info",event:z?"answer_generated":"answer_drafted",metadata:{provider:G,model:J,proposed_updates:R.length,durable_writes_performed:!1},now:D}),EF(_.dbPath,I,P,G,J,D,{generated:z,citations:W.citations.length}),sg(_.dbPath,{runId:I,status:z?"completed":"dry_run",provider:G,model:J,metadata:{generated:z,citations:W.citations.length,proposed_updates:R.length,approve_write:_.approveWrite===!0},now:D}),{run_id:I,prompt:$,generated:z,provider:G,model:J,answer:g,context:W,citations:W.citations,proposed_wiki_updates:R,write_policy:T,usage:P,warnings:X}}async function IX(_,$,D){let I=$.prompt.trim();if(!I)throw Error("Knowledge prompt is required.");let U=`run_${h2()}`,E=T$($.modelRef??"default",$.config),j=f_(E),{prompt:N,generate:O,approveWrite:S,now:L,...W}=$,g=D?O6(D,{contextChars:$.contextChars}):await ag(_,{...W,query:I}),z=_X(I,g),G=!1,J="local",P="context-draft",X={input_tokens:M0(I)+g.excerpts.reduce((Q,F)=>Q+M0(F.text),0),output_tokens:M0(z),cost_usd:0},R=[...g.warnings];if($.generate)if($.fake)G=!0,J=j.provider,P=j.model,z=`Fake generated answer for: ${I} -${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{config:$.config,env:$.env}),q=await Q({model:F,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:_X(I,P)});G=!0,J=j.provider,W=j.model,z=q.text;let Z=O4({provider:J,model:W,usage:q.usage,providerMetadata:q.providerMetadata});X={input_tokens:Z.input_tokens,output_tokens:Z.output_tokens,cost_usd:Z.cost_usd}}let T=$X(I,P),Y={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:I,generated:G,provider:J,model:W,answer:z,context:P,citations:P.citations,proposed_wiki_updates:T,write_policy:Y,usage:X,warnings:R}}import{createHash as jF}from"crypto";var NF=1200,gF=6,AF=12000,OF=50,IX=800;function M0(_,$,D=16){return`${_}_${jF("sha256").update($).digest("hex").slice(0,D)}`}function ng(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function dg(_){return ng(_).toLowerCase()}function SF(_){return Array.from(new Set(dg(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function O6(_,$){let D=ng(_);if(D.length<=$)return D;let I="...";if($<=I.length)return D.slice(0,Math.max(0,$));return`${D.slice(0,$-I.length).trim()}${I}`}function EX(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function mg(_){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test(_)}function cg(_){return Object.keys(_).filter(($)=>!mg($)).sort().slice(0,12)}function LF(_,$){for(let D of $){if(mg(D))continue;let I=_[D];if(typeof I==="string"&&I.trim())return I.trim()}return null}function iD(_,$){if(!_)return null;let D=u_(_,$).text;try{let I=new URL(D),U=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let E of U)I.searchParams.delete(E);for(let[E]of I.searchParams)if(mg(E))I.searchParams.delete(E);return I.toString()}catch{return D}}function n$(_,$,D){return iD(LF(_,$),D)}function WI(_){let $=[];for(let D of cg(_).slice(0,6)){let I=_[D];if(typeof I==="string"&&I.trim())$.push(`${D}=${O6(I,80)}`);else if(typeof I==="number"||typeof I==="boolean")$.push(`${D}=${String(I)}`);else if(I&&typeof I==="object")$.push(`${D}={...}`)}return $.join("; ")}function JF(_){if(!_.trim())return 0;return Math.max(1,Math.ceil(_.length/4))}function jX(_){return JF(JSON.stringify(_))}function WF(_){if(!Number.isFinite(_??NaN))return NF;let $=Math.floor(_);if($D.includes(U)).length;return Number((I/$.length).toFixed(6))}function zF(_){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 XF(_,$,D){let I=iD($.source_ref,D),U=iD($.source_uri,D),E=iD($.artifact_uri,D),j=iD($.artifact_path,D),N=I??U??j??E??$.id,A=$.quote?B0($.quote,D,_<3?220:140):null;return{citation:{id:M0("cite",`${$.id}\x00${N}`,12),kind:$.artifact_uri||$.artifact_path?"artifact":"source",ref:N,source_ref:I,source_uri:U,artifact_uri:E,artifact_path:j,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:A?.text??null},redactions:A?.redactions??0}}async function GF(_,$){let D=(_.query??_.topic??"").trim();if(!D)throw Error("Context pack query is required for search source.");let{config:I,dbPath:U,limit:E,semantic:j,modelRef:N,dimensions:A,fake:O,env:S,batchSize:L,maxParallelCalls:P,legacyStorePath:z}=_,G=await F0({dbPath:U,config:I,legacyStorePath:z,query:D,limit:Math.max($,E??$),semantic:j,modelRef:N,dimensions:A,fake:O,env:S,batchSize:L,maxParallelCalls:P,contextChars:Math.min(_.contextChars??700,1200)}),J=new Map,W=0;G.citations.forEach((Y,Q)=>{let F=XF(Q,Y,_.safetyPolicy);W+=F.redactions,J.set(Y.id,F.citation)});let X=G.excerpts.slice(0,Math.max($*2,$)).map((Y)=>{let Q=G.results.find((f)=>f.id===Y.result_id),F=Y.citation_id?J.get(Y.citation_id):null,q=B0(Y.text,_.safetyPolicy,520);W+=q.redactions;let Z=Q?.title??F?.ref??Y.kind;return{id:M0("ev",`${Y.kind}\x00${Y.result_id}\x00${Y.citation_id??""}`,14),kind:Y.kind,title:O6(Z,100),text_preview:q.text,score:Number(Y.score.toFixed(6)),citation_ids:F?[F.id]:[],provenance:{source:"search",record_ref:`${Y.kind}:${Y.result_id}`,created_at:G.created_at,updated_at:null,metadata_keys:[]}}}),R=new Set(X.flatMap((Y)=>Y.citation_ids));return{citations:Array.from(J.values()).filter((Y)=>R.has(Y.id)),evidence:X,duplicateCandidates:[],redactions:W,warnings:G.warnings,available:G.excerpts.length}}function RF(_,$,D){if($)return _.query(`SELECT id, type, prompt, status, provider, model, cost_tokens, cost_usd, metadata_json, created_at, updated_at +${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{config:$.config,env:$.env}),B=await Q({model:F,system:"You answer company knowledge-base prompts using only provided context and citation ids.",prompt:$X(I,g)});G=!0,J=j.provider,P=j.model,z=B.text;let b=L4({provider:J,model:P,usage:B.usage,providerMetadata:B.providerMetadata});X={input_tokens:b.input_tokens,output_tokens:b.output_tokens,cost_usd:b.cost_usd}}let T=DX(I,g),Y={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:I,generated:G,provider:J,model:P,answer:z,context:g,citations:g.citations,proposed_wiki_updates:T,write_policy:Y,usage:X,warnings:R}}import{createHash as jF}from"crypto";var NF=1200,AF=6,OF=12000,SF=50,EX=800;function H0(_,$,D=16){return`${_}_${jF("sha256").update($).digest("hex").slice(0,D)}`}function n2(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function d2(_){return n2(_).toLowerCase()}function LF(_){return Array.from(new Set(d2(_).match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,24)}function S6(_,$){let D=n2(_);if(D.length<=$)return D;let I="...";if($<=I.length)return D.slice(0,Math.max(0,$));return`${D.slice(0,$-I.length).trim()}${I}`}function jX(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function m2(_){return/(?:api[_-]?key|secret|token|password|private[_-]?key|credential)/i.test(_)}function c2(_){return Object.keys(_).filter(($)=>!m2($)).sort().slice(0,12)}function WF(_,$){for(let D of $){if(m2(D))continue;let I=_[D];if(typeof I==="string"&&I.trim())return I.trim()}return null}function iD(_,$){if(!_)return null;let D=u_(_,$).text;try{let I=new URL(D),U=["token","access_token","api_key","apikey","key","secret","password","signature","sig"];for(let E of U)I.searchParams.delete(E);for(let[E]of I.searchParams)if(m2(E))I.searchParams.delete(E);return I.toString()}catch{return D}}function n$(_,$,D){return iD(WF(_,$),D)}function zI(_){let $=[];for(let D of c2(_).slice(0,6)){let I=_[D];if(typeof I==="string"&&I.trim())$.push(`${D}=${S6(I,80)}`);else if(typeof I==="number"||typeof I==="boolean")$.push(`${D}=${String(I)}`);else if(I&&typeof I==="object")$.push(`${D}={...}`)}return $.join("; ")}function JF(_){if(!_.trim())return 0;return Math.max(1,Math.ceil(_.length/4))}function NX(_){return JF(JSON.stringify(_))}function PF(_){if(!Number.isFinite(_??NaN))return NF;let $=Math.floor(_);if($D.includes(U)).length;return Number((I/$.length).toFixed(6))}function gF(_){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 XF(_,$,D){let I=iD($.source_ref,D),U=iD($.source_uri,D),E=iD($.artifact_uri,D),j=iD($.artifact_path,D),N=I??U??j??E??$.id,O=$.quote?Z0($.quote,D,_<3?220:140):null;return{citation:{id:H0("cite",`${$.id}\x00${N}`,12),kind:$.artifact_uri||$.artifact_path?"artifact":"source",ref:N,source_ref:I,source_uri:U,artifact_uri:E,artifact_path:j,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:O?.text??null},redactions:O?.redactions??0}}async function GF(_,$){let D=(_.query??_.topic??"").trim();if(!D)throw Error("Context pack query is required for search source.");let{config:I,dbPath:U,limit:E,semantic:j,modelRef:N,dimensions:O,fake:S,env:L,batchSize:W,maxParallelCalls:g,legacyStorePath:z}=_,G=await B0({dbPath:U,config:I,legacyStorePath:z,query:D,limit:Math.max($,E??$),semantic:j,modelRef:N,dimensions:O,fake:S,env:L,batchSize:W,maxParallelCalls:g,contextChars:Math.min(_.contextChars??700,1200)}),J=new Map,P=0;G.citations.forEach((Y,Q)=>{let F=XF(Q,Y,_.safetyPolicy);P+=F.redactions,J.set(Y.id,F.citation)});let X=G.excerpts.slice(0,Math.max($*2,$)).map((Y)=>{let Q=G.results.find((f)=>f.id===Y.result_id),F=Y.citation_id?J.get(Y.citation_id):null,B=Z0(Y.text,_.safetyPolicy,520);P+=B.redactions;let b=Q?.title??F?.ref??Y.kind;return{id:H0("ev",`${Y.kind}\x00${Y.result_id}\x00${Y.citation_id??""}`,14),kind:Y.kind,title:S6(b,100),text_preview:B.text,score:Number(Y.score.toFixed(6)),citation_ids:F?[F.id]:[],provenance:{source:"search",record_ref:`${Y.kind}:${Y.result_id}`,created_at:G.created_at,updated_at:null,metadata_keys:[]}}}),R=new Set(X.flatMap((Y)=>Y.citation_ids));return{citations:Array.from(J.values()).filter((Y)=>R.has(Y.id)),evidence:X,duplicateCandidates:[],redactions:P,warnings:G.warnings,available:G.excerpts.length}}function RF(_,$,D){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 @@ -828,7 +828,7 @@ ${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{config:$.config, FROM run_events WHERE run_id IN (${I}) ORDER BY created_at DESC - LIMIT ?`).all(...$,D)}function QF(_,$){return`${_.type} ${_.metadata_json} ${$.map((I)=>`${I.event} ${I.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function KF(_,$,D){let I=n$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),U=n$($,["artifact_uri"],D),E=n$($,["artifact_path","artifact_key"],D),j=I??U??E??`knowledge://project/runs/${_.id}`,N=_.prompt?B0(_.prompt,D,180).text:null;return{id:M0("cite",`run\x00${_.id}\x00${j}`,12),kind:U||E?"artifact":"run",ref:j,source_ref:I?.startsWith("open-files://")?I:null,source_uri:I&&!I.startsWith("open-files://")?I:null,artifact_uri:U,artifact_path:E,run_id:_.id,run_event_id:null,revision:n$($,["revision"],D),hash:n$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function TF(_,$,D){let I=n$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),U=n$($,["artifact_uri"],D),E=n$($,["artifact_path","artifact_key"],D),j=I??U??E??`knowledge://project/runs/${_.run_id}`,N=B0(_.event,D,160).text;return{id:M0("cite",`event\x00${_.id}\x00${j}`,12),kind:U||E?"artifact":"run_event",ref:j,source_ref:I?.startsWith("open-files://")?I:null,source_uri:I&&!I.startsWith("open-files://")?I:null,artifact_uri:U,artifact_path:E,run_id:_.run_id,run_event_id:_.id,revision:n$($,["revision"],D),hash:n$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function OX(_){let $=new Map;for(let D of _){let I=dg(`${D.title} ${D.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(!I)continue;$.set(I,[...$.get(I)??[],D.id])}return Array.from($.entries()).filter(([,D])=>D.length>1).map(([D,I])=>({id:M0("dup",D,12),reason:"normalized_text_match",evidence_ids:I,confidence:I.length>2?"high":"medium"}))}async function FF(_,$,D){let I=_.source==="loops"?"loops":"runs",U=(_.topic??_.query??"").trim(),E=SF(U),j=AX(_.since,D),N=j.warning?[j.warning]:[];c(_.dbPath);let A=w(_.dbPath);try{let O=RF(A,j.cutoff,Math.max($*8,40)),S=YF(A,O.map((X)=>X.id),Math.max($*12,80)),L=new Map;for(let X of S)L.set(X.run_id,[...L.get(X.run_id)??[],X]);let z=(I==="loops"?O.filter((X)=>QF(X,L.get(X.id)??[])):O).map((X)=>{let R=EX(X.metadata_json),T=`${X.type} ${X.status} ${X.prompt??""} ${WI(R)} ${(L.get(X.id)??[]).map((Y)=>`${Y.event} ${Y.metadata_json}`).join(" ")}`;return{row:X,metadata:R,score:NX(T,E),text:T}}).filter((X)=>E.length===0||X.score>0).sort((X,R)=>R.score-X.score||R.row.updated_at.localeCompare(X.row.updated_at)||X.row.id.localeCompare(R.row.id)),G=[],J=[],W=0;for(let X of z.slice(0,Math.max($*2,$))){let R=KF(X.row,X.metadata,_.safetyPolicy);G.push(R);let T=WI(X.metadata),Y=[X.row.prompt,T].filter(Boolean).join(" | ")||`${X.row.type} ${X.row.status}`,Q=B0(Y,_.safetyPolicy,420);W+=Q.redactions,J.push({id:`run:${X.row.id}`,kind:X.row.type,title:O6(`${X.row.type}: ${X.row.status}`,100),text_preview:Q.text,score:X.score,citation_ids:[R.id],provenance:{source:I,record_ref:`knowledge://project/runs/${X.row.id}`,created_at:X.row.created_at,updated_at:X.row.updated_at,metadata_keys:cg(X.metadata)}});let F=(L.get(X.row.id)??[]).map((q)=>{let Z=EX(q.metadata_json),f=`${q.event} ${WI(Z)} ${q.metadata_json}`;return{event:q,metadata:Z,score:NX(f,E),text:f}}).filter((q)=>E.length===0||q.score>0).sort((q,Z)=>Z.score-q.score||Z.event.created_at.localeCompare(q.event.created_at)||q.event.id.localeCompare(Z.event.id)).slice(0,2);for(let q of F){let Z=TF(q.event,q.metadata,_.safetyPolicy);G.push(Z);let f=B0(`${q.event}: ${WI(q.metadata)}`,_.safetyPolicy,320);W+=f.redactions,J.push({id:`event:${q.event.id}`,kind:`run_event:${q.event.level}`,title:O6(q.event.event,100),text_preview:f.text,score:q.score,citation_ids:[Z.id],provenance:{source:I,record_ref:`knowledge://project/runs/${q.event.run_id}`,created_at:q.event.created_at,updated_at:null,metadata_keys:cg(q.metadata)}})}}return{citations:G,evidence:J,duplicateCandidates:_.dedupe?OX(J):[],redactions:W,warnings:N,available:z.length}}finally{A.close()}}function VF(_){let $=_.purpose==="proposal"?`Proposal context: ${O6(_.query||"loop evidence",80)}`:`Knowledge context: ${O6(_.query,80)}`,D=_.evidence.slice(0,8).map((E)=>E.id),I=_.duplicates.slice(0,5).map((E)=>E.id),U=_.evidence.slice(0,5).map((E)=>`${E.id}: ${E.title}`);if(_.evidence.length===0)U.push("No matching bounded evidence was found.");return{title:$,bullets:U,evidence_ids:D,duplicate_candidate_ids:I,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 SX(_){let $=new Set(_.evidence.flatMap((D)=>D.citation_ids));_.citations=_.citations.filter((D)=>$.has(D.id))}function gX(_){_.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 BF(_){let $=_.budgets.max_tokens,D=new Set(_.warnings);while(jX(_)>$){let I=_.evidence.map((E,j)=>({entry:E,index:j})).filter(({entry:E})=>E.text_preview.length>180).sort((E,j)=>j.entry.text_preview.length-E.entry.text_preview.length)[0];if(I){I.entry.text_preview=O6(I.entry.text_preview,180),D.add("text_preview_truncated_for_token_budget");continue}let U=_.citations.filter((E)=>(E.quote_preview?.length??0)>120).sort((E,j)=>(j.quote_preview?.length??0)-(E.quote_preview?.length??0))[0];if(U?.quote_preview){U.quote_preview=O6(U.quote_preview,120),D.add("citation_quote_truncated_for_token_budget");continue}if(_.evidence.length>0){_.evidence.pop(),_.budgets.items_truncated+=1,_.duplicate_candidates=_.duplicate_candidates.map((E)=>({...E,evidence_ids:E.evidence_ids.filter((j)=>_.evidence.some((N)=>N.id===j))})).filter((E)=>E.evidence_ids.length>1),gX(_),D.add("evidence_truncated_for_token_budget"),SX(_);continue}if(_.outline.next_actions.length>1){_.outline.next_actions.pop(),D.add("outline_truncated_for_token_budget");continue}D.add("token_budget_floor_exceeded");break}if(_.warnings=Array.from(D).sort(),_.budgets.items_included=_.evidence.length,gX(_),_.budgets.estimated_tokens=jX(_),_.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 LX(_){let $=_.now??new Date,D=_.source??"search",I=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),U=WF(_.maxTokens),E=PF(_.maxItems,_.limit),j=ng(_.query??_.topic??"");if(I==="proposal"&&D!=="search"&&!j)throw Error("Proposal context requires --topic or a positional topic.");if(D!=="search")c(_.dbPath);let N=AX(_.since,$).cutoff??_.since??"",A=D==="search"?await GF(_,E):await FF(_,E,$),O=A.evidence.sort((G,J)=>J.score-G.score||G.id.localeCompare(J.id)).slice(0,E),S=A.citations.filter((G,J,W)=>W.findIndex((X)=>X.id===G.id)===J).sort((G,J)=>G.id.localeCompare(J.id)),L=_.dedupe?OX(O):A.duplicateCandidates.filter((G)=>G.evidence_ids.every((J)=>O.some((W)=>W.id===J))),P=VF({source:D,purpose:I,query:j,evidence:O,duplicates:L}),z={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:I,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:M0("ctx",[D,I,j,N,_.dedupe===!0?"dedupe":"no-dedupe",_.semantic===!0?"semantic":"keyword",_.modelRef??"",_.limit??"",U,E,O.map((G)=>G.id).join(","),S.map((G)=>G.id).join(",")].join("\x00"),20),budgets:{max_tokens:U,estimated_tokens:0,max_items:E,items_included:O.length,items_available:A.available,items_truncated:Math.max(0,A.available-O.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:A.redactions,reminders:zF(D)},citations:S,evidence:O,duplicate_candidates:L,outline:P,warnings:A.warnings,message:`${O.length} bounded evidence item(s), estimated under ${U} token(s)`};return SX(z),BF(z)}import{randomUUID as rG}from"crypto";import{createHash as MF,randomUUID as bF}from"crypto";import{existsSync as ZF,readFileSync as HF}from"fs";import{hostname as GX}from"os";import{fileURLToPath as RX}from"url";import{extname as kF,relative as YX,resolve as JX,sep as qF}from"path";var XI=["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"],k6=2,q6=1,aD={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"]},sD=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function d$(_=new Date){return _.toISOString()}function eg(_){return`${_}_${Date.now().toString(36)}_${bF().slice(0,8)}`}function QX(_){let $=_?.trim();if($)return $;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??GX()}function Z0(_){if(Array.isArray(_))return`[${_.map(Z0).join(",")}]`;if(_&&typeof _==="object"){let $=_;return`{${Object.keys($).sort().map((D)=>`${JSON.stringify(D)}:${Z0($[D])}`).join(",")}}`}return JSON.stringify(_)}function oD(_){return`sha256:${MF("sha256").update(_).digest("hex")}`}function PI(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function RI(_,$){try{return JSON.parse(_)}catch{return $}}function A$(_){return`"${_.replace(/"/g,'""')}"`}function CF(_){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 KX(_,$){return $.filter((D)=>P$(_,D))}function P$(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get($);return Boolean(D)}function vF(_,$){let D=_.query(`PRAGMA table_info(${A$($)})`).all();return new Set(D.map((I)=>I.name))}function wF(_,$,D){let I=vF(_,$);return D.filter((U)=>I.has(U))}function TX(_){if(!_||_.length===0)return[...XI];let $=new Set(XI),D=_.map((U)=>U.trim()).filter(Boolean),I=D.filter((U)=>!$.has(U));if(I.length>0)throw Error(`Unknown knowledge sync table(s): ${I.join(", ")}`);return D}function J4(_,$){return aD[_].map((I)=>`${I}=${JSON.stringify($[I]??null)}`).join("&")}var rF=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function pD(_,$=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((I)=>pD(I,$+1));let D={};for(let[I,U]of Object.entries(_)){if(rF.has(I.toLowerCase()))continue;D[I]=pD(U,$+1)}return D}function tD(_){if(!_)return null;return pD(_)}function ag(_){return oD(Z0(_))}function fF(_,$){let D={};for(let[I,U]of Object.entries(_))if(I==="artifact_uri"&&typeof U==="string"&&$.has(U))D[I]=`artifact:${$.get(U)}`;else D[I]=U;return D}function L4(_,$=new Map){return ag(fF(_,$))}function FX(_,$){if(!P$(_,$))return[];return _.query(`SELECT * FROM ${A$($)} ORDER BY rowid ASC`).all()}function GI(_,$,D=new Map){return ag($.map((I)=>({key:J4(_,I),hash:L4(I,D)})).sort((I,U)=>I.key.localeCompare(U.key)))}function eD(_,$,D){return _.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get($,D)??null}function xF(_){if(!P$(_,"knowledge_sync_table_clocks"))return[];return _.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function YI(_,$){let D=$.now??d$(),U=eD(_,$.table,$.machineId)?.created_at??D;_.query(` + LIMIT ?`).all(...$,D)}function QF(_,$){return`${_.type} ${_.metadata_json} ${$.map((I)=>`${I.event} ${I.metadata_json}`).join(" ")}`.toLowerCase().includes("loop")}function KF(_,$,D){let I=n$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),U=n$($,["artifact_uri"],D),E=n$($,["artifact_path","artifact_key"],D),j=I??U??E??`knowledge://project/runs/${_.id}`,N=_.prompt?Z0(_.prompt,D,180).text:null;return{id:H0("cite",`run\x00${_.id}\x00${j}`,12),kind:U||E?"artifact":"run",ref:j,source_ref:I?.startsWith("open-files://")?I:null,source_uri:I&&!I.startsWith("open-files://")?I:null,artifact_uri:U,artifact_path:E,run_id:_.id,run_event_id:null,revision:n$($,["revision"],D),hash:n$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function TF(_,$,D){let I=n$($,["source_ref","source_uri","evidence_uri","receipt_uri"],D),U=n$($,["artifact_uri"],D),E=n$($,["artifact_path","artifact_key"],D),j=I??U??E??`knowledge://project/runs/${_.run_id}`,N=Z0(_.event,D,160).text;return{id:H0("cite",`event\x00${_.id}\x00${j}`,12),kind:U||E?"artifact":"run_event",ref:j,source_ref:I?.startsWith("open-files://")?I:null,source_uri:I&&!I.startsWith("open-files://")?I:null,artifact_uri:U,artifact_path:E,run_id:_.run_id,run_event_id:_.id,revision:n$($,["revision"],D),hash:n$($,["hash","content_hash"],D),chunk_id:null,offsets:{start:null,end:null},quote_preview:N}}function LX(_){let $=new Map;for(let D of _){let I=d2(`${D.title} ${D.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(!I)continue;$.set(I,[...$.get(I)??[],D.id])}return Array.from($.entries()).filter(([,D])=>D.length>1).map(([D,I])=>({id:H0("dup",D,12),reason:"normalized_text_match",evidence_ids:I,confidence:I.length>2?"high":"medium"}))}async function FF(_,$,D){let I=_.source==="loops"?"loops":"runs",U=(_.topic??_.query??"").trim(),E=LF(U),j=SX(_.since,D),N=j.warning?[j.warning]:[];c(_.dbPath);let O=w(_.dbPath);try{let S=RF(O,j.cutoff,Math.max($*8,40)),L=YF(O,S.map((X)=>X.id),Math.max($*12,80)),W=new Map;for(let X of L)W.set(X.run_id,[...W.get(X.run_id)??[],X]);let z=(I==="loops"?S.filter((X)=>QF(X,W.get(X.id)??[])):S).map((X)=>{let R=jX(X.metadata_json),T=`${X.type} ${X.status} ${X.prompt??""} ${zI(R)} ${(W.get(X.id)??[]).map((Y)=>`${Y.event} ${Y.metadata_json}`).join(" ")}`;return{row:X,metadata:R,score:AX(T,E),text:T}}).filter((X)=>E.length===0||X.score>0).sort((X,R)=>R.score-X.score||R.row.updated_at.localeCompare(X.row.updated_at)||X.row.id.localeCompare(R.row.id)),G=[],J=[],P=0;for(let X of z.slice(0,Math.max($*2,$))){let R=KF(X.row,X.metadata,_.safetyPolicy);G.push(R);let T=zI(X.metadata),Y=[X.row.prompt,T].filter(Boolean).join(" | ")||`${X.row.type} ${X.row.status}`,Q=Z0(Y,_.safetyPolicy,420);P+=Q.redactions,J.push({id:`run:${X.row.id}`,kind:X.row.type,title:S6(`${X.row.type}: ${X.row.status}`,100),text_preview:Q.text,score:X.score,citation_ids:[R.id],provenance:{source:I,record_ref:`knowledge://project/runs/${X.row.id}`,created_at:X.row.created_at,updated_at:X.row.updated_at,metadata_keys:c2(X.metadata)}});let F=(W.get(X.row.id)??[]).map((B)=>{let b=jX(B.metadata_json),f=`${B.event} ${zI(b)} ${B.metadata_json}`;return{event:B,metadata:b,score:AX(f,E),text:f}}).filter((B)=>E.length===0||B.score>0).sort((B,b)=>b.score-B.score||b.event.created_at.localeCompare(B.event.created_at)||B.event.id.localeCompare(b.event.id)).slice(0,2);for(let B of F){let b=TF(B.event,B.metadata,_.safetyPolicy);G.push(b);let f=Z0(`${B.event}: ${zI(B.metadata)}`,_.safetyPolicy,320);P+=f.redactions,J.push({id:`event:${B.event.id}`,kind:`run_event:${B.event.level}`,title:S6(B.event.event,100),text_preview:f.text,score:B.score,citation_ids:[b.id],provenance:{source:I,record_ref:`knowledge://project/runs/${B.event.run_id}`,created_at:B.event.created_at,updated_at:null,metadata_keys:c2(B.metadata)}})}}return{citations:G,evidence:J,duplicateCandidates:_.dedupe?LX(J):[],redactions:P,warnings:N,available:z.length}}finally{O.close()}}function VF(_){let $=_.purpose==="proposal"?`Proposal context: ${S6(_.query||"loop evidence",80)}`:`Knowledge context: ${S6(_.query,80)}`,D=_.evidence.slice(0,8).map((E)=>E.id),I=_.duplicates.slice(0,5).map((E)=>E.id),U=_.evidence.slice(0,5).map((E)=>`${E.id}: ${E.title}`);if(_.evidence.length===0)U.push("No matching bounded evidence was found.");return{title:$,bullets:U,evidence_ids:D,duplicate_candidate_ids:I,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 WX(_){let $=new Set(_.evidence.flatMap((D)=>D.citation_ids));_.citations=_.citations.filter((D)=>$.has(D.id))}function OX(_){_.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 BF(_){let $=_.budgets.max_tokens,D=new Set(_.warnings);while(NX(_)>$){let I=_.evidence.map((E,j)=>({entry:E,index:j})).filter(({entry:E})=>E.text_preview.length>180).sort((E,j)=>j.entry.text_preview.length-E.entry.text_preview.length)[0];if(I){I.entry.text_preview=S6(I.entry.text_preview,180),D.add("text_preview_truncated_for_token_budget");continue}let U=_.citations.filter((E)=>(E.quote_preview?.length??0)>120).sort((E,j)=>(j.quote_preview?.length??0)-(E.quote_preview?.length??0))[0];if(U?.quote_preview){U.quote_preview=S6(U.quote_preview,120),D.add("citation_quote_truncated_for_token_budget");continue}if(_.evidence.length>0){_.evidence.pop(),_.budgets.items_truncated+=1,_.duplicate_candidates=_.duplicate_candidates.map((E)=>({...E,evidence_ids:E.evidence_ids.filter((j)=>_.evidence.some((N)=>N.id===j))})).filter((E)=>E.evidence_ids.length>1),OX(_),D.add("evidence_truncated_for_token_budget"),WX(_);continue}if(_.outline.next_actions.length>1){_.outline.next_actions.pop(),D.add("outline_truncated_for_token_budget");continue}D.add("token_budget_floor_exceeded");break}if(_.warnings=Array.from(D).sort(),_.budgets.items_included=_.evidence.length,OX(_),_.budgets.estimated_tokens=NX(_),_.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 JX(_){let $=_.now??new Date,D=_.source??"search",I=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),U=PF(_.maxTokens),E=zF(_.maxItems,_.limit),j=n2(_.query??_.topic??"");if(I==="proposal"&&D!=="search"&&!j)throw Error("Proposal context requires --topic or a positional topic.");if(D!=="search")c(_.dbPath);let N=SX(_.since,$).cutoff??_.since??"",O=D==="search"?await GF(_,E):await FF(_,E,$),S=O.evidence.sort((G,J)=>J.score-G.score||G.id.localeCompare(J.id)).slice(0,E),L=O.citations.filter((G,J,P)=>P.findIndex((X)=>X.id===G.id)===J).sort((G,J)=>G.id.localeCompare(J.id)),W=_.dedupe?LX(S):O.duplicateCandidates.filter((G)=>G.evidence_ids.every((J)=>S.some((P)=>P.id===J))),g=VF({source:D,purpose:I,query:j,evidence:S,duplicates:W}),z={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:I,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:H0("ctx",[D,I,j,N,_.dedupe===!0?"dedupe":"no-dedupe",_.semantic===!0?"semantic":"keyword",_.modelRef??"",_.limit??"",U,E,S.map((G)=>G.id).join(","),L.map((G)=>G.id).join(",")].join("\x00"),20),budgets:{max_tokens:U,estimated_tokens:0,max_items:E,items_included:S.length,items_available:O.available,items_truncated:Math.max(0,O.available-S.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:O.redactions,reminders:gF(D)},citations:L,evidence:S,duplicate_candidates:W,outline:g,warnings:O.warnings,message:`${S.length} bounded evidence item(s), estimated under ${U} token(s)`};return WX(z),BF(z)}import{randomUUID as fG}from"crypto";import{createHash as MF,randomUUID as ZF}from"crypto";import{existsSync as HF,readFileSync as bF}from"fs";import{hostname as RX}from"os";import{fileURLToPath as YX}from"url";import{extname as qF,relative as QX,resolve as PX,sep as kF}from"path";var GI=["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"],q6=2,k6=1,aD={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"]},sD=new Set(["storage_objects","knowledge_sync_changes","knowledge_sync_table_clocks","knowledge_sync_imports"]);function d$(_=new Date){return _.toISOString()}function e2(_){return`${_}_${Date.now().toString(36)}_${ZF().slice(0,8)}`}function KX(_){let $=_?.trim();if($)return $;return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??RX()}function q0(_){if(Array.isArray(_))return`[${_.map(q0).join(",")}]`;if(_&&typeof _==="object"){let $=_;return`{${Object.keys($).sort().map((D)=>`${JSON.stringify(D)}:${q0($[D])}`).join(",")}}`}return JSON.stringify(_)}function oD(_){return`sha256:${MF("sha256").update(_).digest("hex")}`}function gI(_,$){return _.query(`SELECT COUNT(*) AS n FROM ${$}`).get()?.n??0}function YI(_,$){try{return JSON.parse(_)}catch{return $}}function O$(_){return`"${_.replace(/"/g,'""')}"`}function CF(_){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 TX(_,$){return $.filter((D)=>z$(_,D))}function z$(_,$){let D=_.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get($);return Boolean(D)}function vF(_,$){let D=_.query(`PRAGMA table_info(${O$($)})`).all();return new Set(D.map((I)=>I.name))}function wF(_,$,D){let I=vF(_,$);return D.filter((U)=>I.has(U))}function FX(_){if(!_||_.length===0)return[...GI];let $=new Set(GI),D=_.map((U)=>U.trim()).filter(Boolean),I=D.filter((U)=>!$.has(U));if(I.length>0)throw Error(`Unknown knowledge sync table(s): ${I.join(", ")}`);return D}function P4(_,$){return aD[_].map((I)=>`${I}=${JSON.stringify($[I]??null)}`).join("&")}var rF=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body_bytes"]);function pD(_,$=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((I)=>pD(I,$+1));let D={};for(let[I,U]of Object.entries(_)){if(rF.has(I.toLowerCase()))continue;D[I]=pD(U,$+1)}return D}function tD(_){if(!_)return null;return pD(_)}function a2(_){return oD(q0(_))}function fF(_,$){let D={};for(let[I,U]of Object.entries(_))if(I==="artifact_uri"&&typeof U==="string"&&$.has(U))D[I]=`artifact:${$.get(U)}`;else D[I]=U;return D}function J4(_,$=new Map){return a2(fF(_,$))}function VX(_,$){if(!z$(_,$))return[];return _.query(`SELECT * FROM ${O$($)} ORDER BY rowid ASC`).all()}function RI(_,$,D=new Map){return a2($.map((I)=>({key:P4(_,I),hash:J4(I,D)})).sort((I,U)=>I.key.localeCompare(U.key)))}function eD(_,$,D){return _.query("SELECT * FROM knowledge_sync_table_clocks WHERE table_name = ? AND machine_id = ?").get($,D)??null}function xF(_){if(!z$(_,"knowledge_sync_table_clocks"))return[];return _.query("SELECT * FROM knowledge_sync_table_clocks ORDER BY table_name ASC, machine_id ASC").all()}function QI(_,$){let D=$.now??d$(),U=eD(_,$.table,$.machineId)?.created_at??D;_.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, @@ -843,17 +843,17 @@ ${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{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??D,JSON.stringify($.metadata??{}),U,D);let E=eD(_,$.table,$.machineId);if(!E)throw Error(`Failed to record sync clock for ${$.table}:${$.machineId}`);return E}function uF(_,$){let D=eD(_,$.table,$.machineId),I=D?.high_water_hash===$.highWaterHash?D.logical_clock:(D?.logical_clock??0)+1,U=$.record?YI(_,{table:$.table,machineId:$.machineId,logicalClock:I,highWaterHash:$.highWaterHash,highWaterBundleId:null,originMachineId:D?.origin_machine_id??$.machineId,updatedByMachineId:$.machineId,lastAppliedAt:$.now,metadata:{source:"export",row_count:$.rowCount},now:$.now}):{table_name:$.table,machine_id:$.machineId,logical_clock:I,high_water_hash:$.highWaterHash,high_water_bundle_id:D?.high_water_bundle_id??null,origin_machine_id:D?.origin_machine_id??$.machineId,updated_by_machine_id:$.machineId,last_applied_at:$.now,metadata_json:"{}",created_at:D?.created_at??$.now,updated_at:$.now};return{table:$.table,machine_id:$.machineId,logical_clock:U.logical_clock,high_water_hash:$.highWaterHash,high_water_bundle_id:U.high_water_bundle_id,row_count:$.rowCount,updated_at:U.updated_at}}function yF(_,$,D,I,U){if($.high_water_bundle_id=D,!I)return;YI(_,{table:$.table,machineId:$.machine_id,logicalClock:$.logical_clock,highWaterHash:$.high_water_hash,highWaterBundleId:D,originMachineId:$.machine_id,updatedByMachineId:$.machine_id,lastAppliedAt:U,metadata:{source:"export",row_count:$.row_count},now:U})}function VX(_,$){return _.table_clocks?.find((D)=>D.table===$)??null}function hF(_,$){if(!_||!$)return!1;return $.logical_clock<_.logical_clock}function cF(_,$,D){if(D.length===0)return 0;let I=wF(_,$,Object.keys(D[0]));if(I.length===0)return 0;let U=aD[$],E=I.map(A$).join(", "),j=I.map(()=>"?").join(", "),N=U.map(A$).join(", "),A=I.filter((z)=>!U.includes(z)),O=U[0],S=A.length>0?A.map((z)=>`${A$(z)} = excluded.${A$(z)}`).join(", "):`${A$(O)} = excluded.${A$(O)}`,L=_.query(`INSERT INTO ${A$($)} (${E}) VALUES (${j}) - ON CONFLICT (${N}) DO UPDATE SET ${S}`);return _.transaction((z)=>{for(let G of z)L.run(...I.map((J)=>CF(G[J])))})(D),D.length}function BX(_,$){let D=aD[_],I=[],U=$;for(let E=0;E=0?A.slice(0,L):A;try{I.push(JSON.parse(P))}catch{return null}U=L>=0&&S?A.slice(L+1):""}return U.length===0?I:null}function MX(_){return aD[_].map(($)=>`${A$($)} = ?`).join(" AND ")}function nF(_,$,D){if(!P$(_,"knowledge_sync_changes"))return new Map;let I=_.query(`SELECT entity_id, next_hash + `).run($.table,$.machineId,$.logicalClock,$.highWaterHash,$.highWaterBundleId??null,$.originMachineId??$.machineId,$.updatedByMachineId??$.machineId,$.lastAppliedAt??D,JSON.stringify($.metadata??{}),U,D);let E=eD(_,$.table,$.machineId);if(!E)throw Error(`Failed to record sync clock for ${$.table}:${$.machineId}`);return E}function uF(_,$){let D=eD(_,$.table,$.machineId),I=D?.high_water_hash===$.highWaterHash?D.logical_clock:(D?.logical_clock??0)+1,U=$.record?QI(_,{table:$.table,machineId:$.machineId,logicalClock:I,highWaterHash:$.highWaterHash,highWaterBundleId:null,originMachineId:D?.origin_machine_id??$.machineId,updatedByMachineId:$.machineId,lastAppliedAt:$.now,metadata:{source:"export",row_count:$.rowCount},now:$.now}):{table_name:$.table,machine_id:$.machineId,logical_clock:I,high_water_hash:$.highWaterHash,high_water_bundle_id:D?.high_water_bundle_id??null,origin_machine_id:D?.origin_machine_id??$.machineId,updated_by_machine_id:$.machineId,last_applied_at:$.now,metadata_json:"{}",created_at:D?.created_at??$.now,updated_at:$.now};return{table:$.table,machine_id:$.machineId,logical_clock:U.logical_clock,high_water_hash:$.highWaterHash,high_water_bundle_id:U.high_water_bundle_id,row_count:$.rowCount,updated_at:U.updated_at}}function yF(_,$,D,I,U){if($.high_water_bundle_id=D,!I)return;QI(_,{table:$.table,machineId:$.machine_id,logicalClock:$.logical_clock,highWaterHash:$.high_water_hash,highWaterBundleId:D,originMachineId:$.machine_id,updatedByMachineId:$.machine_id,lastAppliedAt:U,metadata:{source:"export",row_count:$.row_count},now:U})}function BX(_,$){return _.table_clocks?.find((D)=>D.table===$)??null}function hF(_,$){if(!_||!$)return!1;return $.logical_clock<_.logical_clock}function cF(_,$,D){if(D.length===0)return 0;let I=wF(_,$,Object.keys(D[0]));if(I.length===0)return 0;let U=aD[$],E=I.map(O$).join(", "),j=I.map(()=>"?").join(", "),N=U.map(O$).join(", "),O=I.filter((z)=>!U.includes(z)),S=U[0],L=O.length>0?O.map((z)=>`${O$(z)} = excluded.${O$(z)}`).join(", "):`${O$(S)} = excluded.${O$(S)}`,W=_.query(`INSERT INTO ${O$($)} (${E}) VALUES (${j}) + ON CONFLICT (${N}) DO UPDATE SET ${L}`);return _.transaction((z)=>{for(let G of z)W.run(...I.map((J)=>CF(G[J])))})(D),D.length}function MX(_,$){let D=aD[_],I=[],U=$;for(let E=0;E=0?O.slice(0,W):O;try{I.push(JSON.parse(g))}catch{return null}U=W>=0&&L?O.slice(W+1):""}return U.length===0?I:null}function ZX(_){return aD[_].map(($)=>`${O$($)} = ?`).join(" AND ")}function nF(_,$,D){if(!z$(_,"knowledge_sync_changes"))return new Map;let I=_.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(D,$),U=new Map;for(let E of I)U.set(E.entity_id,E.next_hash);return U}function dF(_,$){if(P$(_,"chunks_fts"))_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run($);if(P$(_,"chunk_embeddings"))_.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run($);if(P$(_,"vector_index_entries"))_.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run($);if(P$(_,"citations"))_.query("DELETE FROM citations WHERE chunk_id = ?").run($)}function mF(_,$,D){let I=BX($,D);if(!I)return!1;let U=MX($),E=_.query(`SELECT * FROM ${A$($)} WHERE ${U} LIMIT 1`).get(...I);if(!E)return!1;if($==="chunks"&&typeof E.id==="string")dF(_,E.id);return _.query(`DELETE FROM ${A$($)} WHERE ${U}`).run(...I),!0}function lF(_,$){if(!P$(_,"chunks_fts"))return;for(let D of $){let I=typeof D.id==="string"?D.id:null,U=typeof D.text==="string"?D.text:null;if(!I||U===null)continue;let E="",j="",N=typeof D.source_revision_id==="string"?D.source_revision_id:null;if(N){let A=_.query(`SELECT s.title, s.uri + ORDER BY created_at ASC, id ASC`).all(D,$),U=new Map;for(let E of I)U.set(E.entity_id,E.next_hash);return U}function dF(_,$){if(z$(_,"chunks_fts"))_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run($);if(z$(_,"chunk_embeddings"))_.query("DELETE FROM chunk_embeddings WHERE chunk_id = ?").run($);if(z$(_,"vector_index_entries"))_.query("DELETE FROM vector_index_entries WHERE chunk_id = ?").run($);if(z$(_,"citations"))_.query("DELETE FROM citations WHERE chunk_id = ?").run($)}function mF(_,$,D){let I=MX($,D);if(!I)return!1;let U=ZX($),E=_.query(`SELECT * FROM ${O$($)} WHERE ${U} LIMIT 1`).get(...I);if(!E)return!1;if($==="chunks"&&typeof E.id==="string")dF(_,E.id);return _.query(`DELETE FROM ${O$($)} WHERE ${U}`).run(...I),!0}function lF(_,$){if(!z$(_,"chunks_fts"))return;for(let D of $){let I=typeof D.id==="string"?D.id:null,U=typeof D.text==="string"?D.text:null;if(!I||U===null)continue;let E="",j="",N=typeof D.source_revision_id==="string"?D.source_revision_id:null;if(N){let O=_.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(N);E=A?.title??"",j=A?.uri??""}if(!j&&typeof D.metadata_json==="string"){let A=RI(D.metadata_json,{});j=typeof A.source_uri==="string"?A.source_uri:""}_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(I),_.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(I,U,E,j)}}function iF(_,$,D){if($==="chunks")lF(_,D)}function tF(_,$){let D=YX(_,$);return D!==".."&&!D.startsWith("..")&&!D.startsWith(`..${qF}`)}function oF(_,$){let D=RI(_.metadata_json,{});if(typeof D.key==="string")return D.key;if(!_.artifact_uri.startsWith("file://"))return null;try{let I=RX(_.artifact_uri),U=JX($),E=JX(I);if(!tF(U,E))return null;let j=YX(U,E).replace(/\\/g,"/");return j?c$(j):null}catch{return null}}var pF=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function eF(_,$){let D=_?.toLowerCase()??"";if(D.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(D))return!0;return $?pF.has(kF($).toLowerCase()):!1}function W4(_){let $=new Map;for(let D of _)if(D.key)$.set(D.artifact_uri,D.key);return $}function Z6(_){return ag({key:_.key,kind:_.kind,hash:_.hash,size_bytes:_.size_bytes})}function QI(_){return _.key??_.artifact_uri}function aF(_,$){return _.artifact_uri.startsWith("s3://")&&$.artifact_store.type==="s3"&&_.artifact_uri.startsWith($.artifact_store.uri_prefix)}function bX(_){return Object.fromEntries(XI.map(($)=>[$,P$(_,$)?PI(_,$):0]))}function sF(_){return _.query(`SELECT artifact_uri, kind, hash, size_bytes + LIMIT 1`).get(N);E=O?.title??"",j=O?.uri??""}if(!j&&typeof D.metadata_json==="string"){let O=YI(D.metadata_json,{});j=typeof O.source_uri==="string"?O.source_uri:""}_.query("DELETE FROM chunks_fts WHERE chunk_id = ?").run(I),_.query("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)").run(I,U,E,j)}}function iF(_,$,D){if($==="chunks")lF(_,D)}function tF(_,$){let D=QX(_,$);return D!==".."&&!D.startsWith("..")&&!D.startsWith(`..${kF}`)}function oF(_,$){let D=YI(_.metadata_json,{});if(typeof D.key==="string")return D.key;if(!_.artifact_uri.startsWith("file://"))return null;try{let I=YX(_.artifact_uri),U=PX($),E=PX(I);if(!tF(U,E))return null;let j=QX(U,E).replace(/\\/g,"/");return j?c$(j):null}catch{return null}}var pF=new Set([".csv",".html",".json",".jsonl",".log",".md",".txt",".xml",".yaml",".yml"]);function eF(_,$){let D=_?.toLowerCase()??"";if(D.startsWith("text/"))return!0;if(/(json|markdown|xml|yaml|csv)/.test(D))return!0;return $?pF.has(qF($).toLowerCase()):!1}function z4(_){let $=new Map;for(let D of _)if(D.key)$.set(D.artifact_uri,D.key);return $}function H6(_){return a2({key:_.key,kind:_.kind,hash:_.hash,size_bytes:_.size_bytes})}function KI(_){return _.key??_.artifact_uri}function aF(_,$){return _.artifact_uri.startsWith("s3://")&&$.artifact_store.type==="s3"&&_.artifact_uri.startsWith($.artifact_store.uri_prefix)}function HX(_){return Object.fromEntries(GI.map(($)=>[$,z$(_,$)?gI(_,$):0]))}function sF(_){return _.query(`SELECT artifact_uri, kind, hash, size_bytes FROM storage_objects - ORDER BY artifact_uri ASC`).all()}function _V(_,$){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 lg(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function $V(_){if(!_)return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function H6(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function zI(_){return Object.fromEntries(Object.entries(_).filter(([,$])=>$!==void 0))}function b0(_){if(Array.isArray(_))return`[${_.map(b0).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).filter(([,$])=>$!==void 0).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>`${JSON.stringify($)}:${b0(D)}`).join(",")}}`;return JSON.stringify(_)}function WX(_){let{recorded_at:$,...D}=_;return D}function b_(_){return typeof _==="string"&&_.length>0?_:null}function DV(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function PX(_){return typeof _==="boolean"?_:null}function UV(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function ZX(_){let $=H6(_),D=b_($.observed_at),I=b_($.source_authority);if(!D||!I)return null;return{observed_at:D,verified_at:b_($.verified_at),expires_at:b_($.expires_at),ttl_ms:DV($.ttl_ms),source_authority:I,confidence:b_($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:UV($.reasons)}}function HX(_,$){if(!_||_.stale)return!1;if(!_.expires_at)return!0;let D=Date.parse(_.expires_at),I=Date.parse($);return Number.isNaN(D)||Number.isNaN(I)||D>I}function IV(_,$){return b_($.source)===_.source&&b_($.target)===_.target&&b_($.route)===_.route&&b_($.target_kind)===_.targetKind&&b_($.confidence)===_.confidence}function EV(_,$){return b_($.source)===_.source&&b_($.requested_machine_id)===_.requested_machine_id&&b_($.machine_id)===_.machine_id&&b_($.project_id)===_.project_id&&b_($.repo_name)===_.repo_name&&b_($.project_root)===_.project_root&&b_($.project_root_source)===_.project_root_source&&b_($.workspace_root)===_.workspace_root&&b_($.workspace_root_source)===_.workspace_root_source&&b_($.open_files_root)===_.open_files_root&&b_($.open_files_root_source)===_.open_files_root_source&&b_($.trust_status)===_.trust_status&&b_($.auth_status)===_.auth_status&&PX($.current)===_.current&&PX($.primary)===_.primary}function jV(_,$,D){if(!_)return null;let I=ZX($.cacheability);if(I&&HX(I,D)&&IV(_,$))return{..._,cacheability:I};return _}function NV(_,$,D){if(!_)return null;let I=ZX($.cacheability);if(I&&HX(I,D)&&EV(_,$))return{..._,cacheability:I};return _}function gV(_){return _.workspace?.machine_id??_.workspace?.requested_machine_id??_.machineId??_.route?.target??GX()}function AV(_,$){let D=new Set,I=Array.isArray($.sources)?$.sources:[];for(let U of I)if(typeof U==="string")D.add(U);if(typeof $.source==="string")D.add($.source);if(_.route?.source)D.add(_.route.source);if(_.workspace?.source)D.add(_.workspace.source);return D.add("knowledge"),[...D].sort()}function zX(_,$){if($?.target&&($.route==="tailscale"||$.targetKind==="tailscale"))return $.target;return _?.tailscale_dns??null}function OV(_,$,D){let I=H6($.resolver_evidence),U=_.route?zI({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}):H6(I.route),E=_.workspace?zI({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}):H6(I.workspace);return zI({...I,recorded_at:D,route:U,workspace:E})}function kX(_,$){c(_);let D=w(_);try{let I=gV($),U=D.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(I)??null,E=d$($.now),j=lg(U?.capabilities_json),N=lg(U?.metadata_json),A=H6(j.resolver),O=H6(N.resolver_evidence),S=H6(O.route),L=H6(O.workspace),P=jV($.route?.source==="registry"?null:$.route??null,S,E),z=NV($.workspace?.source==="registry"?null:$.workspace??null,L,E),G={...$,route:P,workspace:z},J={...j,resolver:zI({...A,route_source:P?.source??A.route_source,route_kind:P?.route??A.route_kind,route_target_kind:P?.targetKind??A.route_target_kind,route_confidence:P?.confidence??A.route_confidence,route_cacheable:P?.cacheability?.cacheable??A.route_cacheable,route_stale:P?.cacheability?.stale??A.route_stale,route_expires_at:P?.cacheability?.expires_at??A.route_expires_at,route_observed_at:P?.cacheability?.observed_at??A.route_observed_at,route_source_authority:P?.cacheability?.source_authority??A.route_source_authority,workspace_source:z?.source??A.workspace_source,project_root_source:z?.project_root_source??A.project_root_source,workspace_root_source:z?.workspace_root_source??A.workspace_root_source,open_files_root_source:z?.open_files_root_source??A.open_files_root_source,trust_status:z?.trust_status??A.trust_status,auth_status:z?.auth_status??A.auth_status,workspace_cacheable:z?.cacheability?.cacheable??A.workspace_cacheable,workspace_stale:z?.cacheability?.stale??A.workspace_stale,workspace_expires_at:z?.cacheability?.expires_at??A.workspace_expires_at,workspace_observed_at:z?.cacheability?.observed_at??A.workspace_observed_at,workspace_source_authority:z?.cacheability?.source_authority??A.workspace_source_authority}),route_fallback:Boolean(P?.target??U?.ssh_target),workspace_fallback:Boolean(z?.project_root??U?.workspace_home)},W=OV(G,N,E);if(U){let R=O;if(U.workspace_home===(z?.project_root??U.workspace_home??null)&&U.tailscale_dns===zX(U,P)&&U.ssh_target===(P?.target??U.ssh_target??null)&&b0(lg(U.capabilities_json))===b0(J)&&b0(WX(R))===b0(WX(W)))return U}let X={machine_id:I,hostname:U?.hostname??null,platform:U?.platform??null,user_label:U?.user_label??null,workspace_home:z?.project_root??U?.workspace_home??null,tailscale_dns:zX(U,P),tailscale_ips_json:JSON.stringify($V(U?.tailscale_ips_json)),ssh_target:P?.target??U?.ssh_target??null,last_seen_at:E,capabilities_json:JSON.stringify(J),metadata_json:JSON.stringify({...N,source:"knowledge",sources:AV(G,N),resolver_evidence:W}),created_at:U?.created_at??E,updated_at:E};return qX(D,X),X}finally{D.close()}}function qX(_,$){_.query(` + ORDER BY artifact_uri ASC`).all()}function _V(_,$){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 l2(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function $V(_){if(!_)return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function b6(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function XI(_){return Object.fromEntries(Object.entries(_).filter(([,$])=>$!==void 0))}function b0(_){if(Array.isArray(_))return`[${_.map(b0).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).filter(([,$])=>$!==void 0).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>`${JSON.stringify($)}:${b0(D)}`).join(",")}}`;return JSON.stringify(_)}function zX(_){let{recorded_at:$,...D}=_;return D}function H_(_){return typeof _==="string"&&_.length>0?_:null}function DV(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function gX(_){return typeof _==="boolean"?_:null}function UV(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function bX(_){let $=b6(_),D=H_($.observed_at),I=H_($.source_authority);if(!D||!I)return null;return{observed_at:D,verified_at:H_($.verified_at),expires_at:H_($.expires_at),ttl_ms:DV($.ttl_ms),source_authority:I,confidence:H_($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:UV($.reasons)}}function qX(_,$){if(!_||_.stale)return!1;if(!_.expires_at)return!0;let D=Date.parse(_.expires_at),I=Date.parse($);return Number.isNaN(D)||Number.isNaN(I)||D>I}function IV(_,$){return H_($.source)===_.source&&H_($.target)===_.target&&H_($.route)===_.route&&H_($.target_kind)===_.targetKind&&H_($.confidence)===_.confidence}function EV(_,$){return H_($.source)===_.source&&H_($.requested_machine_id)===_.requested_machine_id&&H_($.machine_id)===_.machine_id&&H_($.project_id)===_.project_id&&H_($.repo_name)===_.repo_name&&H_($.project_root)===_.project_root&&H_($.project_root_source)===_.project_root_source&&H_($.workspace_root)===_.workspace_root&&H_($.workspace_root_source)===_.workspace_root_source&&H_($.open_files_root)===_.open_files_root&&H_($.open_files_root_source)===_.open_files_root_source&&H_($.trust_status)===_.trust_status&&H_($.auth_status)===_.auth_status&&gX($.current)===_.current&&gX($.primary)===_.primary}function jV(_,$,D){if(!_)return null;let I=bX($.cacheability);if(I&&qX(I,D)&&IV(_,$))return{..._,cacheability:I};return _}function NV(_,$,D){if(!_)return null;let I=bX($.cacheability);if(I&&qX(I,D)&&EV(_,$))return{..._,cacheability:I};return _}function AV(_){return _.workspace?.machine_id??_.workspace?.requested_machine_id??_.machineId??_.route?.target??RX()}function OV(_,$){let D=new Set,I=Array.isArray($.sources)?$.sources:[];for(let U of I)if(typeof U==="string")D.add(U);if(typeof $.source==="string")D.add($.source);if(_.route?.source)D.add(_.route.source);if(_.workspace?.source)D.add(_.workspace.source);return D.add("knowledge"),[...D].sort()}function XX(_,$){if($?.target&&($.route==="tailscale"||$.targetKind==="tailscale"))return $.target;return _?.tailscale_dns??null}function SV(_,$,D){let I=b6($.resolver_evidence),U=_.route?XI({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}):b6(I.route),E=_.workspace?XI({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}):b6(I.workspace);return XI({...I,recorded_at:D,route:U,workspace:E})}function kX(_,$){c(_);let D=w(_);try{let I=AV($),U=D.query("SELECT * FROM knowledge_machines WHERE machine_id = ?").get(I)??null,E=d$($.now),j=l2(U?.capabilities_json),N=l2(U?.metadata_json),O=b6(j.resolver),S=b6(N.resolver_evidence),L=b6(S.route),W=b6(S.workspace),g=jV($.route?.source==="registry"?null:$.route??null,L,E),z=NV($.workspace?.source==="registry"?null:$.workspace??null,W,E),G={...$,route:g,workspace:z},J={...j,resolver:XI({...O,route_source:g?.source??O.route_source,route_kind:g?.route??O.route_kind,route_target_kind:g?.targetKind??O.route_target_kind,route_confidence:g?.confidence??O.route_confidence,route_cacheable:g?.cacheability?.cacheable??O.route_cacheable,route_stale:g?.cacheability?.stale??O.route_stale,route_expires_at:g?.cacheability?.expires_at??O.route_expires_at,route_observed_at:g?.cacheability?.observed_at??O.route_observed_at,route_source_authority:g?.cacheability?.source_authority??O.route_source_authority,workspace_source:z?.source??O.workspace_source,project_root_source:z?.project_root_source??O.project_root_source,workspace_root_source:z?.workspace_root_source??O.workspace_root_source,open_files_root_source:z?.open_files_root_source??O.open_files_root_source,trust_status:z?.trust_status??O.trust_status,auth_status:z?.auth_status??O.auth_status,workspace_cacheable:z?.cacheability?.cacheable??O.workspace_cacheable,workspace_stale:z?.cacheability?.stale??O.workspace_stale,workspace_expires_at:z?.cacheability?.expires_at??O.workspace_expires_at,workspace_observed_at:z?.cacheability?.observed_at??O.workspace_observed_at,workspace_source_authority:z?.cacheability?.source_authority??O.workspace_source_authority}),route_fallback:Boolean(g?.target??U?.ssh_target),workspace_fallback:Boolean(z?.project_root??U?.workspace_home)},P=SV(G,N,E);if(U){let R=S;if(U.workspace_home===(z?.project_root??U.workspace_home??null)&&U.tailscale_dns===XX(U,g)&&U.ssh_target===(g?.target??U.ssh_target??null)&&b0(l2(U.capabilities_json))===b0(J)&&b0(zX(R))===b0(zX(P)))return U}let X={machine_id:I,hostname:U?.hostname??null,platform:U?.platform??null,user_label:U?.user_label??null,workspace_home:z?.project_root??U?.workspace_home??null,tailscale_dns:XX(U,g),tailscale_ips_json:JSON.stringify($V(U?.tailscale_ips_json)),ssh_target:g?.target??U?.ssh_target??null,last_seen_at:E,capabilities_json:JSON.stringify(J),metadata_json:JSON.stringify({...N,source:"knowledge",sources:OV(G,N),resolver_evidence:P}),created_at:U?.created_at??E,updated_at:E};return CX(D,X),X}finally{D.close()}}function CX(_,$){_.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, @@ -871,15 +871,15 @@ ${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{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 SV(_,$,D=d$()){for(let I of $.machines)qX(_,_V(I,D));return $.machines.length}function sg(_){c(_);let $=w(_);try{return $.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{$.close()}}function _U(_){c(_.dbPath);let $=w(_.dbPath),D=[],I=d$(_.now),U=QX(_.machineId),E=_.recordClocks!==!1;try{let j=KX($,TX(_.tables)),A=$.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 LV(_,$,D=d$()){for(let I of $.machines)CX(_,_V(I,D));return $.machines.length}function s2(_){c(_);let $=w(_);try{return $.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all()}finally{$.close()}}function _U(_){c(_.dbPath);let $=w(_.dbPath),D=[],I=d$(_.now),U=KX(_.machineId),E=_.recordClocks!==!1;try{let j=TX($,FX(_.tables)),O=$.query(`SELECT id, artifact_uri, kind, content_type, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all().map((G)=>{let J=oF(G,_.storage.local_layout.directories.artifacts),W={...G,key:J};if(_.includeArtifactContent!==!1&&J&&G.artifact_uri.startsWith("file://"))try{let X=RX(G.artifact_uri);if(ZF(X))if(!eF(G.content_type,J))D.push(`artifact_content_not_embedded_binary:${G.id}`);else{let R=HF(X,"utf8"),T=F_(R);if(T!==R)D.push(`artifact_content_redacted:${G.id}`);W.content_base64=Buffer.from(T,"utf8").toString("base64"),W.hash=oD(T),W.size_bytes=Buffer.byteLength(T)}else D.push(`artifact_missing:${G.artifact_uri}`)}catch(X){D.push(`artifact_read_failed:${G.artifact_uri}:${X instanceof Error?X.message:String(X)}`)}else if(_.includeArtifactContent!==!1&&G.artifact_uri.startsWith("s3://"))D.push(`artifact_content_not_embedded:${G.artifact_uri}`);return W=F_(W),W}),O=W4(A),S=j.filter((G)=>!sD.has(G)).map((G)=>({table:G,primary_keys:aD[G],rows:FX($,G).map((J)=>F_(J))})),L=S.map((G)=>uF($,{table:G.table,machineId:U,highWaterHash:GI(G.table,G.rows,O),rowCount:G.rows.length,record:E,now:I})),P=oD(Z0({source:{scope:_.scope,workspace_home:F_(_.workspaceHome),sqlite_schema_version:r_($),machine_id:U,artifact_root_uri:F_(_.storage.artifact_store.uri_prefix)},tables:S.map((G)=>({table:G.table,primary_keys:G.primary_keys,rows:G.rows.map((J)=>({key:J4(G.table,J),hash:L4(J,O)})).sort((J,W)=>J.key.localeCompare(W.key))})),table_clocks:L.map((G)=>({table:G.table,machine_id:G.machine_id,logical_clock:G.logical_clock,high_water_hash:G.high_water_hash,row_count:G.row_count})),artifacts:A.map((G)=>({identity:QI(G),fingerprint:Z6(G)})).sort((G,J)=>G.identity.localeCompare(J.identity))})),z=`syncbundle_${P.replace("sha256:","").slice(0,32)}`;for(let G of L)yF($,G,z,E,I);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:k6,min_protocol_version:q6,bundle_id:z,content_hash:P,generated_at:I,source:{scope:_.scope,workspace_home:F_(_.workspaceHome),sqlite_schema_version:r_($),machine_id:U,artifact_root_uri:F_(_.storage.artifact_store.uri_prefix)},table_clocks:L,tables:S,artifacts:A,warnings:F_(D),message:`${S.reduce((G,J)=>G+J.rows.length,0)} row(s), ${A.length} artifact(s) exported`}}finally{$.close()}}function LV(_,$){let D=typeof _.protocol_version==="number"?_.protocol_version:null,I=typeof _.min_protocol_version==="number"?_.min_protocol_version:null;if(D===null||I===null||Dk6)throw Error(`Unsupported ${$} protocol. Expected knowledge sync protocol v${k6} with min v${q6}.`)}function JV(_){if(!_||_.format!=="knowledge-sync-bundle"||_.version!==1)throw Error("Invalid knowledge sync bundle.");LV(_,"knowledge sync bundle")}function _2(_,$){return _.tables.find((D)=>D.table===$)??null}function CX(_){if(typeof _.content_hash==="string"&&_.content_hash.length>0)return _.content_hash;return oD(Z0({source:_.source,tables:_.tables.map(($)=>({table:$.table,rows:$.rows.map((D)=>({key:J4($.table,D),hash:L4(D,W4(_.artifacts))})).sort((D,I)=>D.key.localeCompare(I.key))})),artifacts:_.artifacts.map(($)=>({identity:QI($),fingerprint:Z6($)})).sort(($,D)=>$.identity.localeCompare(D.identity))}))}function WV(_){if(typeof _.bundle_id==="string"&&_.bundle_id.length>0)return _.bundle_id;return`syncbundle_${CX(_).replace("sha256:","").slice(0,32)}`}function PV(_,$){return new Map($.map((D)=>[J4(_,D),D]))}function zV(_){return new Map(_.artifacts.map(($)=>[QI($),$]))}async function XV(_){let $=zV(_.targetBundle),D=new Map,I=[],U={source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let E of _.bundle.artifacts){let j=QI(E),N=$.get(j);if(N&&Z6(N)===Z6(E)){if(N.artifact_uri)D.set(E.artifact_uri,N.artifact_uri);U.skipped+=1;continue}if(N&&Z6(N)!==Z6(E)){let G={entityKind:"storage_object",entityId:j,localMachineId:_.localMachineId,remoteMachineId:_.bundle.source.machine_id??"unknown",localHash:Z6(N),remoteHash:Z6(E),metadata:{direction:_.direction,target_artifact_uri:N.artifact_uri,source_artifact_uri:E.artifact_uri,local_artifact:pD(N),remote_artifact:pD(E)}};if(og(_.db,G)){U.skipped+=1;continue}U.conflicts+=1,I.push(G);continue}let A=Boolean(E.key&&E.content_base64),O=aF(E,_.targetStorage);if(!A&&!O){U.missing_content+=1,_.warnings.push(`artifact_content_missing:${E.artifact_uri}`);continue}if(_.dryRun){U.copied+=1;continue}let S=E.artifact_uri;if(A&&E.key&&E.content_base64)S=(await _.targetStore.put({key:E.key,body:Buffer.from(E.content_base64,"base64"),content_type:E.content_type??void 0})).uri,D.set(E.artifact_uri,S);else if(O)D.set(E.artifact_uri,S);let L=RI(E.metadata_json,{}),P=typeof L.artifact_modified_at==="string"?L.artifact_modified_at:void 0,z={uri:S,key:E.key??L.key??E.artifact_uri,kind:E.kind,content_type:E.content_type??void 0,hash:E.hash??void 0,size_bytes:E.size_bytes??void 0,modified_at:P,metadata:{...L,synced_from_artifact_uri:E.artifact_uri,synced_from_machine_id:_.bundle.source.machine_id??void 0}};j6(_.db,[z]),U.copied+=1}return{result:U,uriMap:D,conflicts:I}}function ig(_,$){let D={..._};if(typeof D.artifact_uri==="string"&&$.has(D.artifact_uri))D.artifact_uri=$.get(D.artifact_uri);return D}function GV(_,$){let D=d$();_.query(` + ORDER BY artifact_uri ASC`).all().map((G)=>{let J=oF(G,_.storage.local_layout.directories.artifacts),P={...G,key:J};if(_.includeArtifactContent!==!1&&J&&G.artifact_uri.startsWith("file://"))try{let X=YX(G.artifact_uri);if(HF(X))if(!eF(G.content_type,J))D.push(`artifact_content_not_embedded_binary:${G.id}`);else{let R=bF(X,"utf8"),T=F_(R);if(T!==R)D.push(`artifact_content_redacted:${G.id}`);P.content_base64=Buffer.from(T,"utf8").toString("base64"),P.hash=oD(T),P.size_bytes=Buffer.byteLength(T)}else D.push(`artifact_missing:${G.artifact_uri}`)}catch(X){D.push(`artifact_read_failed:${G.artifact_uri}:${X instanceof Error?X.message:String(X)}`)}else if(_.includeArtifactContent!==!1&&G.artifact_uri.startsWith("s3://"))D.push(`artifact_content_not_embedded:${G.artifact_uri}`);return P=F_(P),P}),S=z4(O),L=j.filter((G)=>!sD.has(G)).map((G)=>({table:G,primary_keys:aD[G],rows:VX($,G).map((J)=>F_(J))})),W=L.map((G)=>uF($,{table:G.table,machineId:U,highWaterHash:RI(G.table,G.rows,S),rowCount:G.rows.length,record:E,now:I})),g=oD(q0({source:{scope:_.scope,workspace_home:F_(_.workspaceHome),sqlite_schema_version:r_($),machine_id:U,artifact_root_uri:F_(_.storage.artifact_store.uri_prefix)},tables:L.map((G)=>({table:G.table,primary_keys:G.primary_keys,rows:G.rows.map((J)=>({key:P4(G.table,J),hash:J4(J,S)})).sort((J,P)=>J.key.localeCompare(P.key))})),table_clocks:W.map((G)=>({table:G.table,machine_id:G.machine_id,logical_clock:G.logical_clock,high_water_hash:G.high_water_hash,row_count:G.row_count})),artifacts:O.map((G)=>({identity:KI(G),fingerprint:H6(G)})).sort((G,J)=>G.identity.localeCompare(J.identity))})),z=`syncbundle_${g.replace("sha256:","").slice(0,32)}`;for(let G of W)yF($,G,z,E,I);return{ok:!0,format:"knowledge-sync-bundle",version:1,protocol_version:q6,min_protocol_version:k6,bundle_id:z,content_hash:g,generated_at:I,source:{scope:_.scope,workspace_home:F_(_.workspaceHome),sqlite_schema_version:r_($),machine_id:U,artifact_root_uri:F_(_.storage.artifact_store.uri_prefix)},table_clocks:W,tables:L,artifacts:O,warnings:F_(D),message:`${L.reduce((G,J)=>G+J.rows.length,0)} row(s), ${O.length} artifact(s) exported`}}finally{$.close()}}function WV(_,$){let D=typeof _.protocol_version==="number"?_.protocol_version:null,I=typeof _.min_protocol_version==="number"?_.min_protocol_version:null;if(D===null||I===null||Dq6)throw Error(`Unsupported ${$} protocol. Expected knowledge sync protocol v${q6} with min v${k6}.`)}function JV(_){if(!_||_.format!=="knowledge-sync-bundle"||_.version!==1)throw Error("Invalid knowledge sync bundle.");WV(_,"knowledge sync bundle")}function _A(_,$){return _.tables.find((D)=>D.table===$)??null}function vX(_){if(typeof _.content_hash==="string"&&_.content_hash.length>0)return _.content_hash;return oD(q0({source:_.source,tables:_.tables.map(($)=>({table:$.table,rows:$.rows.map((D)=>({key:P4($.table,D),hash:J4(D,z4(_.artifacts))})).sort((D,I)=>D.key.localeCompare(I.key))})),artifacts:_.artifacts.map(($)=>({identity:KI($),fingerprint:H6($)})).sort(($,D)=>$.identity.localeCompare(D.identity))}))}function PV(_){if(typeof _.bundle_id==="string"&&_.bundle_id.length>0)return _.bundle_id;return`syncbundle_${vX(_).replace("sha256:","").slice(0,32)}`}function zV(_,$){return new Map($.map((D)=>[P4(_,D),D]))}function gV(_){return new Map(_.artifacts.map(($)=>[KI($),$]))}async function XV(_){let $=gV(_.targetBundle),D=new Map,I=[],U={source_artifacts:_.bundle.artifacts.length,target_artifacts:_.targetBundle.artifacts.length,copied:0,skipped:0,conflicts:0,missing_content:0};for(let E of _.bundle.artifacts){let j=KI(E),N=$.get(j);if(N&&H6(N)===H6(E)){if(N.artifact_uri)D.set(E.artifact_uri,N.artifact_uri);U.skipped+=1;continue}if(N&&H6(N)!==H6(E)){let G={entityKind:"storage_object",entityId:j,localMachineId:_.localMachineId,remoteMachineId:_.bundle.source.machine_id??"unknown",localHash:H6(N),remoteHash:H6(E),metadata:{direction:_.direction,target_artifact_uri:N.artifact_uri,source_artifact_uri:E.artifact_uri,local_artifact:pD(N),remote_artifact:pD(E)}};if(o2(_.db,G)){U.skipped+=1;continue}U.conflicts+=1,I.push(G);continue}let O=Boolean(E.key&&E.content_base64),S=aF(E,_.targetStorage);if(!O&&!S){U.missing_content+=1,_.warnings.push(`artifact_content_missing:${E.artifact_uri}`);continue}if(_.dryRun){U.copied+=1;continue}let L=E.artifact_uri;if(O&&E.key&&E.content_base64)L=(await _.targetStore.put({key:E.key,body:Buffer.from(E.content_base64,"base64"),content_type:E.content_type??void 0})).uri,D.set(E.artifact_uri,L);else if(S)D.set(E.artifact_uri,L);let W=YI(E.metadata_json,{}),g=typeof W.artifact_modified_at==="string"?W.artifact_modified_at:void 0,z={uri:L,key:E.key??W.key??E.artifact_uri,kind:E.kind,content_type:E.content_type??void 0,hash:E.hash??void 0,size_bytes:E.size_bytes??void 0,modified_at:g,metadata:{...W,synced_from_artifact_uri:E.artifact_uri,synced_from_machine_id:_.bundle.source.machine_id??void 0}};j6(_.db,[z]),U.copied+=1}return{result:U,uriMap:D,conflicts:I}}function i2(_,$){let D={..._};if(typeof D.artifact_uri==="string"&&$.has(D.artifact_uri))D.artifact_uri=$.get(D.artifact_uri);return D}function GV(_,$){let D=d$();_.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(eg("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}),D)}function og(_,$){let D=$.localHash??"",I=$.remoteHash??"";if(_.query(` + `).run(e2("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}),D)}function o2(_,$){let D=$.localHash??"",I=$.remoteHash??"";if(_.query(` SELECT id FROM knowledge_sync_conflicts WHERE entity_kind = ? AND entity_id = ? @@ -901,7 +901,7 @@ ${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{config:$.config, AND status IN ('resolved', 'ignored') AND resolved_at IS NOT NULL LIMIT 1 - `).get($.entityKind,$.entityId,$.remoteMachineId,$.localMachineId,I,D);return Boolean(E)}function tg(_,$){if(_.query(` + `).get($.entityKind,$.entityId,$.remoteMachineId,$.localMachineId,I,D);return Boolean(E)}function t2(_,$){if(_.query(` SELECT id FROM knowledge_sync_conflicts WHERE entity_kind = ? AND entity_id = ? @@ -918,7 +918,7 @@ ${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{config:$.config, local_hash, remote_hash, base_hash, status, resolution_strategy, proposed_patch_uri, approved_by, resolved_at, metadata_json, created_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(eg("syncconf"),$.entityKind,$.entityId,$.localMachineId,$.remoteMachineId,$.localHash??null,$.remoteHash??null,$.baseHash??null,$.status??"open",$.resolutionStrategy??null,$.proposedPatchUri??null,$.approvedBy??null,$.resolvedAt??null,JSON.stringify($.metadata??{}),I),!0}function RV(_,$){return _.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get($)??null}function YV(_,$){let D=$.now??d$();_.query(` + `).run(e2("syncconf"),$.entityKind,$.entityId,$.localMachineId,$.remoteMachineId,$.localHash??null,$.remoteHash??null,$.baseHash??null,$.status??"open",$.resolutionStrategy??null,$.proposedPatchUri??null,$.approvedBy??null,$.resolvedAt??null,JSON.stringify($.metadata??{}),I),!0}function RV(_,$){return _.query("SELECT * FROM knowledge_sync_imports WHERE bundle_id = ?").get($)??null}function YV(_,$){let D=$.now??d$();_.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, @@ -928,13 +928,13 @@ ${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{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,D,JSON.stringify({conflicts:$.conflicts,artifacts:$.artifacts,source_workspace_home:$.bundle.source.workspace_home}))}function QV(_){return{ok:!0,protocol_version:k6,min_protocol_version:q6,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(($)=>!sD.has($.table)).map(($)=>({table:$.table,source_rows:$.rows.length,target_rows:_2(_.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 KV(_,$){let D=W4(_.artifacts),I=W4($.artifacts);for(let U of _.tables){if(sD.has(U.table))continue;let E=_2($,U.table),N=VX(_,U.table)?.high_water_hash??GI(U.table,U.rows,D);if(GI(U.table,E?.rows??[],I)!==N)return!1}return!0}async function KI(_){JV(_.bundle),c(_.targetDbPath);let $=[..._.bundle.warnings],D=_.dryRun===!0,I=QX(_.localMachineId),U=_.bundle.source.machine_id??"unknown",E=WV(_.bundle),j=CX(_.bundle),N=_.targetBundle??_U({dbPath:_.targetDbPath,scope:_.targetScope,workspaceHome:_.targetWorkspaceHome,storage:_.targetStorage,machineId:I,includeArtifactContent:!1,recordClocks:!D}),A=w(_.targetDbPath);try{if(!D&&RV(A,E)&&KV(_.bundle,N))return QV({bundle:_.bundle,targetBundle:N,targetScope:_.targetScope,targetWorkspaceHome:_.targetWorkspaceHome,targetStorage:_.targetStorage,direction:_.direction,warnings:$,bundleId:E});let O=await XV({db:A,bundle:_.bundle,targetBundle:N,targetStorage:_.targetStorage,targetStore:_.targetStore,dryRun:D,direction:_.direction,localMachineId:I,warnings:$}),S=W4(_.bundle.artifacts),L=W4(N.artifacts),P=[],z=0,G=0,J=0;for(let R of _.bundle.tables){if(R.table==="storage_objects"||sD.has(R.table))continue;if(!P$(A,R.table))continue;let T=VX(_.bundle,R.table),Y=eD(A,R.table,U),Q=_2(N,R.table),F=PV(R.table,Q?.rows??[]),q=new Set(R.rows.map((U_)=>J4(R.table,U_))),Z=nF(A,R.table,U),f=[],l={table:R.table,source_rows:R.rows.length,target_rows:Q?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!T)$.push(`legacy_clock_missing:${R.table}`);else if(hF(Y,T)){J+=1,l.skipped+=R.rows.length,l.stale_skipped=R.rows.length,$.push(`stale_table_skipped:${R.table}:${U}:${T.logical_clock}`),P.push(l);continue}for(let U_ of R.rows){let j_=J4(R.table,U_),_$=F.get(j_),G_=L4(U_,S);if(!_$){l.inserted+=1,f.push(ig(U_,O.uriMap));continue}let K$=L4(_$,L);if(K$===G_){l.skipped+=1;continue}let E_=Z.get(j_);if(Z.has(j_)&&E_===K$){l.updated+=1,f.push(ig(U_,O.uriMap));continue}let C_={entityKind:R.table,entityId:j_,localMachineId:I,remoteMachineId:U,localHash:K$,remoteHash:G_,baseHash:Y?.high_water_hash??null,metadata:{direction:_.direction,bundle_id:E,incoming_logical_clock:T?.logical_clock??null,current_logical_clock:Y?.logical_clock??null,source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:tD(_$),remote_row:tD(U_)}};if(og(A,C_)){l.skipped+=1;continue}if(l.conflicts+=1,!D&&tg(A,C_))z+=1}if(!D&&f.length>0){let U_=f.map((j_)=>ig(j_,O.uriMap));cF(A,R.table,U_),iF(A,R.table,U_);for(let j_ of U_)GV(A,{direction:_.direction,sourceMachineId:_.bundle.source.machine_id??"unknown",localMachineId:I,entityKind:R.table,entityId:J4(R.table,j_),nextHash:L4(j_,W4(_.bundle.artifacts)),logicalClock:T?.logical_clock??0,bundleId:E,row:j_})}for(let[U_,j_]of Z){if(q.has(U_))continue;let _$=F.get(U_);if(!_$)continue;let G_=L4(_$,L);if(j_&&G_!==j_){let K$={entityKind:R.table,entityId:U_,localMachineId:I,remoteMachineId:U,localHash:G_,remoteHash:null,baseHash:j_,metadata:{direction:_.direction,bundle_id:E,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:tD(_$),remote_row:null}};if(og(A,K$)){l.skipped+=1;continue}if(l.conflicts+=1,!D&&tg(A,K$))z+=1;continue}if(l.deleted+=1,!D)mF(A,R.table,U_)}if(!D&&T)YI(A,{table:R.table,machineId:U,logicalClock:T.logical_clock,highWaterHash:T.high_water_hash,highWaterBundleId:E,originMachineId:U,updatedByMachineId:I,lastAppliedAt:d$(),metadata:{source:"import",direction:_.direction,row_count:R.rows.length,inserted:l.inserted,updated:l.updated,deleted:l.deleted,skipped:l.skipped,conflicts:l.conflicts}}),G+=1;P.push(l)}for(let R of O.conflicts)if(!D){if(tg(A,{...R,baseHash:R.baseHash??null,metadata:{...R.metadata,bundle_id:E}}))z+=1}let W=P.reduce((R,T)=>R+T.inserted,0),X=P.reduce((R,T)=>R+T.conflicts,0)+O.result.conflicts;if(!D)YV(A,{bundle:_.bundle,bundleId:E,contentHash:j,sourceMachineId:U,targetMachineId:I,direction:_.direction,status:X===0?"applied":"conflicted",tableResults:P,conflicts:X,artifacts:O.result});return{ok:X===0,protocol_version:k6,min_protocol_version:q6,dry_run:D,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:r_(A),artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:P,artifacts:O.result,conflicts_created:z,bundle_id:E,replayed:!1,clocks:{advanced:G,stale_tables:J},warnings:$,message:`${_.dryRun?"Would import":"Imported"} ${W} row(s), copied ${O.result.copied} artifact(s), ${X} conflict(s)`}}finally{A.close()}}function vX(_){c(_.dbPath);let $=w(_.dbPath),D=d$(_.now);try{let I=_.topology?SV($,_.topology,D):0,U=bX($),E=F_(sF($)),j=_.machineId??_.topology?.local_machine_id??"unknown",N=F_(_.storage.artifact_store.uri_prefix),A=F_(_.workspaceHome),O=oD(Z0({machine_id:j,scope:_.scope,workspace_home:A,sqlite_schema_version:r_($),artifact_root_uri:N,tables:U,artifacts:E})),S={id:eg("syncsnap"),machine_id:j,scope:_.scope,workspace_home:A,sqlite_schema_version:r_($),artifact_root_uri:N,content_hash:O,tables_json:JSON.stringify(U),artifact_hashes_json:JSON.stringify(E),created_at:D};$.query(` + `).run($.bundleId,$.sourceMachineId,$.targetMachineId,$.direction,$.status,$.contentHash,JSON.stringify($.bundle.table_clocks??[]),JSON.stringify($.tableResults),$.bundle.generated_at,D,JSON.stringify({conflicts:$.conflicts,artifacts:$.artifacts,source_workspace_home:$.bundle.source.workspace_home}))}function QV(_){return{ok:!0,protocol_version:q6,min_protocol_version:k6,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(($)=>!sD.has($.table)).map(($)=>({table:$.table,source_rows:$.rows.length,target_rows:_A(_.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 KV(_,$){let D=z4(_.artifacts),I=z4($.artifacts);for(let U of _.tables){if(sD.has(U.table))continue;let E=_A($,U.table),N=BX(_,U.table)?.high_water_hash??RI(U.table,U.rows,D);if(RI(U.table,E?.rows??[],I)!==N)return!1}return!0}async function TI(_){JV(_.bundle),c(_.targetDbPath);let $=[..._.bundle.warnings],D=_.dryRun===!0,I=KX(_.localMachineId),U=_.bundle.source.machine_id??"unknown",E=PV(_.bundle),j=vX(_.bundle),N=_.targetBundle??_U({dbPath:_.targetDbPath,scope:_.targetScope,workspaceHome:_.targetWorkspaceHome,storage:_.targetStorage,machineId:I,includeArtifactContent:!1,recordClocks:!D}),O=w(_.targetDbPath);try{if(!D&&RV(O,E)&&KV(_.bundle,N))return QV({bundle:_.bundle,targetBundle:N,targetScope:_.targetScope,targetWorkspaceHome:_.targetWorkspaceHome,targetStorage:_.targetStorage,direction:_.direction,warnings:$,bundleId:E});let S=await XV({db:O,bundle:_.bundle,targetBundle:N,targetStorage:_.targetStorage,targetStore:_.targetStore,dryRun:D,direction:_.direction,localMachineId:I,warnings:$}),L=z4(_.bundle.artifacts),W=z4(N.artifacts),g=[],z=0,G=0,J=0;for(let R of _.bundle.tables){if(R.table==="storage_objects"||sD.has(R.table))continue;if(!z$(O,R.table))continue;let T=BX(_.bundle,R.table),Y=eD(O,R.table,U),Q=_A(N,R.table),F=zV(R.table,Q?.rows??[]),B=new Set(R.rows.map((U_)=>P4(R.table,U_))),b=nF(O,R.table,U),f=[],l={table:R.table,source_rows:R.rows.length,target_rows:Q?.rows.length??0,inserted:0,updated:0,deleted:0,skipped:0,conflicts:0,stale_skipped:0};if(!T)$.push(`legacy_clock_missing:${R.table}`);else if(hF(Y,T)){J+=1,l.skipped+=R.rows.length,l.stale_skipped=R.rows.length,$.push(`stale_table_skipped:${R.table}:${U}:${T.logical_clock}`),g.push(l);continue}for(let U_ of R.rows){let j_=P4(R.table,U_),_$=F.get(j_),G_=J4(U_,L);if(!_$){l.inserted+=1,f.push(i2(U_,S.uriMap));continue}let K$=J4(_$,W);if(K$===G_){l.skipped+=1;continue}let E_=b.get(j_);if(b.has(j_)&&E_===K$){l.updated+=1,f.push(i2(U_,S.uriMap));continue}let v_={entityKind:R.table,entityId:j_,localMachineId:I,remoteMachineId:U,localHash:K$,remoteHash:G_,baseHash:Y?.high_water_hash??null,metadata:{direction:_.direction,bundle_id:E,incoming_logical_clock:T?.logical_clock??null,current_logical_clock:Y?.logical_clock??null,source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:tD(_$),remote_row:tD(U_)}};if(o2(O,v_)){l.skipped+=1;continue}if(l.conflicts+=1,!D&&t2(O,v_))z+=1}if(!D&&f.length>0){let U_=f.map((j_)=>i2(j_,S.uriMap));cF(O,R.table,U_),iF(O,R.table,U_);for(let j_ of U_)GV(O,{direction:_.direction,sourceMachineId:_.bundle.source.machine_id??"unknown",localMachineId:I,entityKind:R.table,entityId:P4(R.table,j_),nextHash:J4(j_,z4(_.bundle.artifacts)),logicalClock:T?.logical_clock??0,bundleId:E,row:j_})}for(let[U_,j_]of b){if(B.has(U_))continue;let _$=F.get(U_);if(!_$)continue;let G_=J4(_$,W);if(j_&&G_!==j_){let K$={entityKind:R.table,entityId:U_,localMachineId:I,remoteMachineId:U,localHash:G_,remoteHash:null,baseHash:j_,metadata:{direction:_.direction,bundle_id:E,reason:"remote_owned_row_missing_from_incoming_bundle",source_workspace_home:_.bundle.source.workspace_home,target_workspace_home:_.targetWorkspaceHome,local_row:tD(_$),remote_row:null}};if(o2(O,K$)){l.skipped+=1;continue}if(l.conflicts+=1,!D&&t2(O,K$))z+=1;continue}if(l.deleted+=1,!D)mF(O,R.table,U_)}if(!D&&T)QI(O,{table:R.table,machineId:U,logicalClock:T.logical_clock,highWaterHash:T.high_water_hash,highWaterBundleId:E,originMachineId:U,updatedByMachineId:I,lastAppliedAt:d$(),metadata:{source:"import",direction:_.direction,row_count:R.rows.length,inserted:l.inserted,updated:l.updated,deleted:l.deleted,skipped:l.skipped,conflicts:l.conflicts}}),G+=1;g.push(l)}for(let R of S.conflicts)if(!D){if(t2(O,{...R,baseHash:R.baseHash??null,metadata:{...R.metadata,bundle_id:E}}))z+=1}let P=g.reduce((R,T)=>R+T.inserted,0),X=g.reduce((R,T)=>R+T.conflicts,0)+S.result.conflicts;if(!D)YV(O,{bundle:_.bundle,bundleId:E,contentHash:j,sourceMachineId:U,targetMachineId:I,direction:_.direction,status:X===0?"applied":"conflicted",tableResults:g,conflicts:X,artifacts:S.result});return{ok:X===0,protocol_version:q6,min_protocol_version:k6,dry_run:D,direction:_.direction,source:_.bundle.source,target:{scope:_.targetScope,workspace_home:_.targetWorkspaceHome,sqlite_schema_version:r_(O),artifact_root_uri:_.targetStorage.artifact_store.uri_prefix},tables:g,artifacts:S.result,conflicts_created:z,bundle_id:E,replayed:!1,clocks:{advanced:G,stale_tables:J},warnings:$,message:`${_.dryRun?"Would import":"Imported"} ${P} row(s), copied ${S.result.copied} artifact(s), ${X} conflict(s)`}}finally{O.close()}}function wX(_){c(_.dbPath);let $=w(_.dbPath),D=d$(_.now);try{let I=_.topology?LV($,_.topology,D):0,U=HX($),E=F_(sF($)),j=_.machineId??_.topology?.local_machine_id??"unknown",N=F_(_.storage.artifact_store.uri_prefix),O=F_(_.workspaceHome),S=oD(q0({machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:r_($),artifact_root_uri:N,tables:U,artifacts:E})),L={id:e2("syncsnap"),machine_id:j,scope:_.scope,workspace_home:O,sqlite_schema_version:r_($),artifact_root_uri:N,content_hash:S,tables_json:JSON.stringify(U),artifact_hashes_json:JSON.stringify(E),created_at:D};$.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(S.id,S.machine_id,S.scope,S.workspace_home,S.sqlite_schema_version,S.artifact_root_uri,S.content_hash,S.tables_json,S.artifact_hashes_json,S.created_at);let L=new Map;for(let P of KX($,TX()).filter((z)=>!sD.has(z))){let z=FX($,P).map((X)=>F_(X)),G=GI(P,z,L),J=eD($,P,j),W=J?.high_water_hash===G?J.logical_clock:(J?.logical_clock??0)+1;YI($,{table:P,machineId:j,logicalClock:W,highWaterHash:G,highWaterBundleId:S.id,originMachineId:J?.origin_machine_id??j,updatedByMachineId:j,lastAppliedAt:D,metadata:{source:"snapshot",row_count:z.length},now:D})}return{ok:!0,snapshot:{...S,tables:U,artifact_hashes:E},machines_upserted:I,message:`Recorded sync snapshot ${S.id}`}}finally{$.close()}}function wX(_){c(_.dbPath);let $=w(_.dbPath);try{let D=$.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(),I=$.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get()??null,U=$.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(),E=$.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(),j=xF($),N=$.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get()??null,A=U.reduce((S,L)=>S+L.count,0),O=U.filter((S)=>S.status!=="resolved"&&S.status!=="ignored").reduce((S,L)=>S+L.count,0);return{ok:!0,scope:_.scope,workspace_home:F_(_.workspaceHome),sqlite_schema_version:r_($),local_machine_id:_.localMachineId??null,machines:{total:D.length,rows:F_(D)},snapshots:{total:PI($,"knowledge_sync_snapshots"),latest:F_(I)},changes:{total:PI($,"knowledge_sync_changes"),by_operation:E},clocks:{total:j.length,rows:j},imports:{total:PI($,"knowledge_sync_imports"),latest:F_(N)},conflicts:{total:A,by_status:U,open:O},table_counts:bX($),message:`${D.length} machine(s), ${O} open sync conflict(s)`}}finally{$.close()}}function $2(_){return{..._,metadata:RI(_.metadata_json,{})}}function TI(_,$){c(_);let D=w(_);try{let I=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($);return I?$2(I):null}finally{D.close()}}function rX(_,$={}){c(_);let D=w(_),I=Math.max(1,Math.min($.limit??50,200));try{return($.status?D.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all($.status,I):D.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(I)).map($2)}finally{D.close()}}function TV(_){return XI.includes(_)?_:null}function FV(_,$){let D=TV($.entity_kind);if(!D||!P$(_,D))return null;let I=BX(D,$.entity_id);if(!I)return null;let U=MX(D);return _.query(`SELECT * FROM ${A$(D)} WHERE ${U} LIMIT 1`).get(...I)}function VV(_,$){for(let D of $){let I=_[D];if(I&&typeof I==="object"&&!Array.isArray(I))return tD(I)}return null}function XX(_,$){if(typeof $!=="string")return;let D=$.trim();if(!D)return;if(D.startsWith("open-files://")||D.startsWith("s3://")||D.startsWith("file://")||D.startsWith("https://")||D.startsWith("http://"))_.add(D)}function pg(_,$=new Set,D=0){if(D>8||_===null||_===void 0)return $;if(typeof _==="string")return XX($,_),$;if(Array.isArray(_)){for(let I of _)pg(I,$,D+1);return $}if(typeof _==="object")for(let[I,U]of Object.entries(_)){if(I==="source_ref"||I==="source_uri"||I==="artifact_uri"||I.endsWith("_uri"))XX($,U);pg(U,$,D+1)}return $}function fX(_){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((D,I)=>{$.push({id:`source-${I+1}`,kind:D.startsWith("file://")||D.startsWith("s3://")?"artifact":"source_ref",ref:D,hash:null,quote:null})}),$}function xX(_,$){let D=TI(_,$);if(!D)throw Error(`Sync conflict not found: ${$}`);c(_);let I=w(_);try{let U=tD(FV(I,D)),E=VV(D.metadata,["remote_row","source_row","incoming_row"]),N=[...pg({conflict:{entity_kind:D.entity_kind,entity_id:D.entity_id,metadata:D.metadata},local_row:U,remote_row:E})].slice(0,25),A=[{name:"knowledge_sync_conflict_get",input:{id:$},output_summary:`${D.entity_kind}:${D.entity_id} status=${D.status}`},{name:"knowledge_catalog_row_get",input:{table:D.entity_kind,key:D.entity_id},output_summary:U?"local row found":"local row unavailable"},{name:"knowledge_source_ref_extract",input:{id:$},output_summary:`${N.length} source/artifact ref(s) found`}];return{conflict:D,local_row:U,remote_row:E,source_refs:N,citations:fX({conflict:D,localRow:U,remoteRow:E,sourceRefs:N}),read_only_tools:A}}finally{I.close()}}function $U(_,$){let D=TI(_,$);if(!D)throw Error(`Sync conflict not found: ${$}`);let I=D.entity_kind==="wiki_pages"?"manual-merge":"review-and-select",U=[`Conflict ${D.id} affects ${D.entity_kind}:${D.entity_id}.`,`Local machine ${D.local_machine_id} has ${D.local_hash??"unknown hash"}.`,`Remote machine ${D.remote_machine_id} has ${D.remote_hash??"unknown hash"}.`].join(" "),E=["Review this knowledge sync conflict before any durable write.",`Entity: ${D.entity_kind}:${D.entity_id}`,`Local machine/hash: ${D.local_machine_id} / ${D.local_hash??"unknown"}`,`Remote machine/hash: ${D.remote_machine_id} / ${D.remote_hash??"unknown"}`,`Base hash: ${D.base_hash??"unknown"}`,`Metadata: ${JSON.stringify(D.metadata)}`,"Return a concise merge recommendation with citations to the competing records. Do not write changes without approval."].join(` -`);return{ok:!0,conflict:D,requires_approval:!0,mode:"deterministic",proposed_strategy:I,summary:U,merge_prompt:E,proposed_patch:null,citations:fX({conflict:D,localRow:null,remoteRow:null,sourceRefs:[]}),confidence:null,agent:null,warnings:D.status==="resolved"?["conflict_already_resolved"]:[],message:`Prepared approval-gated merge proposal for ${D.id}`}}function uX(_,$){c(_);let D=w(_),I=d$();try{let U=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!U)throw Error(`Sync conflict not found: ${$.id}`);D.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 W=new Map;for(let g of TX($,FX()).filter((z)=>!sD.has(z))){let z=VX($,g).map((X)=>F_(X)),G=RI(g,z,W),J=eD($,g,j),P=J?.high_water_hash===G?J.logical_clock:(J?.logical_clock??0)+1;QI($,{table:g,machineId:j,logicalClock:P,highWaterHash:G,highWaterBundleId:L.id,originMachineId:J?.origin_machine_id??j,updatedByMachineId:j,lastAppliedAt:D,metadata:{source:"snapshot",row_count:z.length},now:D})}return{ok:!0,snapshot:{...L,tables:U,artifact_hashes:E},machines_upserted:I,message:`Recorded sync snapshot ${L.id}`}}finally{$.close()}}function rX(_){c(_.dbPath);let $=w(_.dbPath);try{let D=$.query("SELECT * FROM knowledge_machines ORDER BY machine_id ASC").all(),I=$.query("SELECT * FROM knowledge_sync_snapshots ORDER BY created_at DESC LIMIT 1").get()??null,U=$.query("SELECT status, COUNT(*) AS count FROM knowledge_sync_conflicts GROUP BY status ORDER BY status").all(),E=$.query("SELECT operation, COUNT(*) AS count FROM knowledge_sync_changes GROUP BY operation ORDER BY operation").all(),j=xF($),N=$.query("SELECT * FROM knowledge_sync_imports ORDER BY applied_at DESC LIMIT 1").get()??null,O=U.reduce((L,W)=>L+W.count,0),S=U.filter((L)=>L.status!=="resolved"&&L.status!=="ignored").reduce((L,W)=>L+W.count,0);return{ok:!0,scope:_.scope,workspace_home:F_(_.workspaceHome),sqlite_schema_version:r_($),local_machine_id:_.localMachineId??null,machines:{total:D.length,rows:F_(D)},snapshots:{total:gI($,"knowledge_sync_snapshots"),latest:F_(I)},changes:{total:gI($,"knowledge_sync_changes"),by_operation:E},clocks:{total:j.length,rows:j},imports:{total:gI($,"knowledge_sync_imports"),latest:F_(N)},conflicts:{total:O,by_status:U,open:S},table_counts:HX($),message:`${D.length} machine(s), ${S} open sync conflict(s)`}}finally{$.close()}}function $A(_){return{..._,metadata:YI(_.metadata_json,{})}}function FI(_,$){c(_);let D=w(_);try{let I=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($);return I?$A(I):null}finally{D.close()}}function fX(_,$={}){c(_);let D=w(_),I=Math.max(1,Math.min($.limit??50,200));try{return($.status?D.query("SELECT * FROM knowledge_sync_conflicts WHERE status = ? ORDER BY created_at DESC LIMIT ?").all($.status,I):D.query("SELECT * FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ?").all(I)).map($A)}finally{D.close()}}function TV(_){return GI.includes(_)?_:null}function FV(_,$){let D=TV($.entity_kind);if(!D||!z$(_,D))return null;let I=MX(D,$.entity_id);if(!I)return null;let U=ZX(D);return _.query(`SELECT * FROM ${O$(D)} WHERE ${U} LIMIT 1`).get(...I)}function VV(_,$){for(let D of $){let I=_[D];if(I&&typeof I==="object"&&!Array.isArray(I))return tD(I)}return null}function GX(_,$){if(typeof $!=="string")return;let D=$.trim();if(!D)return;if(D.startsWith("open-files://")||D.startsWith("s3://")||D.startsWith("file://")||D.startsWith("https://")||D.startsWith("http://"))_.add(D)}function p2(_,$=new Set,D=0){if(D>8||_===null||_===void 0)return $;if(typeof _==="string")return GX($,_),$;if(Array.isArray(_)){for(let I of _)p2(I,$,D+1);return $}if(typeof _==="object")for(let[I,U]of Object.entries(_)){if(I==="source_ref"||I==="source_uri"||I==="artifact_uri"||I.endsWith("_uri"))GX($,U);p2(U,$,D+1)}return $}function xX(_){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((D,I)=>{$.push({id:`source-${I+1}`,kind:D.startsWith("file://")||D.startsWith("s3://")?"artifact":"source_ref",ref:D,hash:null,quote:null})}),$}function uX(_,$){let D=FI(_,$);if(!D)throw Error(`Sync conflict not found: ${$}`);c(_);let I=w(_);try{let U=tD(FV(I,D)),E=VV(D.metadata,["remote_row","source_row","incoming_row"]),N=[...p2({conflict:{entity_kind:D.entity_kind,entity_id:D.entity_id,metadata:D.metadata},local_row:U,remote_row:E})].slice(0,25),O=[{name:"knowledge_sync_conflict_get",input:{id:$},output_summary:`${D.entity_kind}:${D.entity_id} status=${D.status}`},{name:"knowledge_catalog_row_get",input:{table:D.entity_kind,key:D.entity_id},output_summary:U?"local row found":"local row unavailable"},{name:"knowledge_source_ref_extract",input:{id:$},output_summary:`${N.length} source/artifact ref(s) found`}];return{conflict:D,local_row:U,remote_row:E,source_refs:N,citations:xX({conflict:D,localRow:U,remoteRow:E,sourceRefs:N}),read_only_tools:O}}finally{I.close()}}function $U(_,$){let D=FI(_,$);if(!D)throw Error(`Sync conflict not found: ${$}`);let I=D.entity_kind==="wiki_pages"?"manual-merge":"review-and-select",U=[`Conflict ${D.id} affects ${D.entity_kind}:${D.entity_id}.`,`Local machine ${D.local_machine_id} has ${D.local_hash??"unknown hash"}.`,`Remote machine ${D.remote_machine_id} has ${D.remote_hash??"unknown hash"}.`].join(" "),E=["Review this knowledge sync conflict before any durable write.",`Entity: ${D.entity_kind}:${D.entity_id}`,`Local machine/hash: ${D.local_machine_id} / ${D.local_hash??"unknown"}`,`Remote machine/hash: ${D.remote_machine_id} / ${D.remote_hash??"unknown"}`,`Base hash: ${D.base_hash??"unknown"}`,`Metadata: ${JSON.stringify(D.metadata)}`,"Return a concise merge recommendation with citations to the competing records. Do not write changes without approval."].join(` +`);return{ok:!0,conflict:D,requires_approval:!0,mode:"deterministic",proposed_strategy:I,summary:U,merge_prompt:E,proposed_patch:null,citations:xX({conflict:D,localRow:null,remoteRow:null,sourceRefs:[]}),confidence:null,agent:null,warnings:D.status==="resolved"?["conflict_already_resolved"]:[],message:`Prepared approval-gated merge proposal for ${D.id}`}}function yX(_,$){c(_);let D=w(_),I=d$();try{let U=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!U)throw Error(`Sync conflict not found: ${$.id}`);D.query(` UPDATE knowledge_sync_conflicts SET status = 'resolved', resolution_strategy = ?, @@ -942,27 +942,27 @@ ${z}`;else{let{generateText:Q}=await import("ai"),F=await lD(E,{config:$.config, approved_by = ?, resolved_at = ? WHERE id = ? - `).run($.strategy,$.proposedPatchUri??U.proposed_patch_uri,$.approvedBy,I,$.id);let E=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!E)throw Error(`Sync conflict not found after resolve: ${$.id}`);return $2(E)}finally{D.close()}}function WW(_){let D=(typeof _==="string"?_:JSON.stringify(_)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(D*1.25))}function Jb(_){let $=w(_.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 wG(_){let $=w(_.dbPath);try{$.run(`UPDATE runs + `).run($.strategy,$.proposedPatchUri??U.proposed_patch_uri,$.approvedBy,I,$.id);let E=D.query("SELECT * FROM knowledge_sync_conflicts WHERE id = ?").get($.id);if(!E)throw Error(`Sync conflict not found after resolve: ${$.id}`);return $A(E)}finally{D.close()}}function PP(_){let D=(typeof _==="string"?_:JSON.stringify(_)).trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil(D*1.25))}function JZ(_){let $=w(_.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 rG(_){let $=w(_.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 PW(_){let $=w(_.dbPath);try{$.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`event_${rG()}`,_.runId,_.level,_.event,JSON.stringify(_.metadata),_.now])}finally{$.close()}}function Wb(_,$,D,I){let U=w(_);try{Q0(U,{...D,run_id:$,created_at:I})}finally{U.close()}}function Pb(_){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 zP(_){let $=w(_.dbPath);try{$.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`event_${fG()}`,_.runId,_.level,_.event,JSON.stringify(_.metadata),_.now])}finally{$.close()}}function PZ(_,$,D,I){let U=w(_);try{T0(U,{...D,run_id:$,created_at:I})}finally{U.close()}}function zZ(_){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 zb(_){let $=typeof _==="number"&&Number.isFinite(_)?_:0.5;return Math.max(0,Math.min(1,$))}function Xb(_,$){let D=_.kind==="choose_local"||_.kind==="choose_remote"||_.kind==="no_op"||_.kind==="custom"||_.kind==="manual_merge"?_.kind:"manual_merge";return{kind:D,target:typeof _.target==="string"&&_.target?_.target:$,strategy:typeof _.strategy==="string"&&_.strategy?_.strategy:D.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 Gb(_){let $=`${_.conflict.entity_kind}:${_.conflict.entity_id}`,D=Boolean(_.local_row&&_.remote_row);return{kind:D?"manual_merge":"custom",target:$,strategy:D?"manual-merge":"review-and-select",summary:D?`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:D?[`--- ${$} 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 fG(_){let $=(_.now??new Date).toISOString();c(_.dbPath);let D=$U(_.dbPath,_.id),I=xX(_.dbPath,_.id),U=T$(_.modelRef??"default",_.config),E=f_(U),j=`run_${rG()}`,N=Pb({deterministic:D,evidence:I});Jb({dbPath:_.dbPath,runId:j,prompt:N,provider:E.provider,model:E.model,status:_.fake?"dry_run":"running",metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,read_only_tools:I.read_only_tools.map((P)=>P.name)},now:$}),PW({dbPath:_.dbPath,runId:j,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:I.citations.length,source_refs:I.source_refs.length,read_only_tools:I.read_only_tools},now:$});let A,O,S=0.5,L={input_tokens:WW(N),output_tokens:0,cost_usd:0};if(_.fake)A=Gb(I),O=A.summary,L.output_tokens=WW(O)+WW(A.diff??"");else try{let{generateObject:P}=await import("ai"),{z}=await Promise.resolve().then(() => (vG(),CG)),G=await lD(U,{config:_.config,env:_.env}),J=z.object({summary:z.string(),confidence:z.number().min(0).max(1),proposed_patch:z.object({kind:z.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:z.string(),strategy:z.string(),summary:z.string(),diff:z.string().nullable(),metadata:z.record(z.string(),z.unknown()).default({})})}),W=await P({model:G,schema:J,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:N});O=W.object.summary,S=zb(W.object.confidence),A=Xb(W.object.proposed_patch,`${I.conflict.entity_kind}:${I.conflict.entity_id}`);let X=O4({provider:E.provider,model:E.model,usage:W.usage,providerMetadata:W.providerMetadata});L={input_tokens:X.input_tokens,output_tokens:X.output_tokens,cost_usd:X.cost_usd},Wb(_.dbPath,j,X,$)}catch(P){throw PW({dbPath:_.dbPath,runId:j,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:P instanceof Error?P.message:String(P)},now:$}),wG({dbPath:_.dbPath,runId:j,status:"failed",provider:E.provider,model:E.model,usage:L,metadata:{conflict_id:_.id,mode:"ai",error:P instanceof Error?P.message:String(P)},now:$}),P}return wG({dbPath:_.dbPath,runId:j,status:_.fake?"dry_run":"completed",provider:E.provider,model:E.model,usage:L,metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,confidence:S,proposed_strategy:A.strategy,citation_count:I.citations.length},now:$}),PW({dbPath:_.dbPath,runId:j,level:"info",event:_.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:A.strategy,confidence:S,patch_kind:A.kind},now:$}),{...D,mode:"ai",proposed_strategy:A.strategy,summary:O,proposed_patch:A,citations:I.citations,confidence:S,agent:{generated:!0,provider:E.provider,model:E.model,run_id:j,read_only_tools:I.read_only_tools,usage:L},warnings:[...D.warnings,...I.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${_.id}`}}import{createHash as Rb,randomUUID as Yb}from"crypto";import{existsSync as Qb,readFileSync as Kb}from"fs";import{basename as Tb}from"path";function rj(_,$){return`${_}_${Rb("sha256").update($).digest("hex").slice(0,20)}`}function DD(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function z_(_){return typeof _==="string"&&_.length>0?_:void 0}function Fb(_){let $=z_(_.source_ref)??z_(_.source_uri)??z_(_.uri);if($)return $;let D=z_(_.file_id);if(D){let E=z_(_.revision_id)??z_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return E?`${j}/revision/${encodeURIComponent(E)}`:j}let I=z_(_.source_id),U=z_(_.path);if(I&&U)return`open-files://source/${encodeURIComponent(I)}/path/${encodeURIComponent(U)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function Vb(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function Bb(_){return z_(_.hash)??z_(_.checksum)??z_(_.sha256)??null}function Mb(_,$,D){return z_(_.revision_id)??z_(_.revision)??z_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??null}function bb(_){return z_(_.previous_revision_id)??z_(_.previous_revision)??z_(_.previous_version_id)??null}function Zb(_){return(z_(_.event_type)??z_(_.event)??z_(_.type)??z_(_.action)??z_(_.change_type)??"changed").toLowerCase()}function Hb(_){let $=z_(_.path);return z_(_.title)??z_(_.name)??($?Tb($):null)}function kb(_,$){let D=Fb(_),I=J$(D),U=Bb(_);return{raw:_,eventType:Zb(_),sourceRef:D,sourceUri:Vb(D,I),kind:I.kind,title:Hb(_),revision:Mb(_,I,U),previousRevision:bb(_),hash:U,status:z_(_.status)?.toLowerCase()??null,updatedAt:z_(_.updated_at)??$,acl:_.permissions??_.acl??void 0}}function qb(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Outbox array parse failed.");return D.map((I)=>{let U=DD(I);if(!U)throw Error("Outbox array entries must be objects.");return U})}if($.startsWith("{"))try{let D=JSON.parse($),I=DD(D);if(!I)throw Error("Outbox object parse failed.");if(Array.isArray(I.events))return I.events.map((U)=>{let E=DD(U);if(!E)throw Error("Outbox events entries must be objects.");return E});if("source_ref"in I||"source_uri"in I||"file_id"in I)return[I]}catch(D){let I=$.split(/\r?\n/).filter((U)=>U.trim().length>0);if(I.length<=1)throw D;return I.map((U)=>{let E=DD(JSON.parse(U));if(!E)throw Error("Outbox JSONL entries must be objects.");return E})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let I=DD(JSON.parse(D));if(!I)throw Error("Outbox JSONL entries must be objects.");return I})}async function Cb(_,$,D){let I=new URL(_),U=I.hostname,E=decodeURIComponent(I.pathname.replace(/^\/+/,""));if(!U||!E)throw Error(`Invalid S3 outbox URI: ${_}`);if(D)b6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:A}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),O=$?.storage.type==="s3"&&$.storage.s3?.bucket===U?$.storage.s3:void 0,L=await new j({region:O?.region,credentials:O?.profile?A({profile:O.profile}):void 0,maxAttempts:O?.max_attempts}).send(new N({Bucket:U,Key:E}));if(!L.Body)return"";return await L.Body.transformToString()}async function vb(_,$,D){if(_.startsWith("s3://"))return Cb(_,$,D);if(!Qb(_))throw Error(`Outbox not found: ${_}`);return Kb(_,"utf8")}function xG(_,$){let D={};if(_)try{D=DD(JSON.parse(_))??{}}catch{D={}}return JSON.stringify({...D,...$})}function wb(_,$,D){let I=rj("src",$.sourceUri);_.run(`INSERT INTO sources (id, uri, kind, title, metadata_json, acl_json, created_at, updated_at) +`)}function gZ(_){let $=typeof _==="number"&&Number.isFinite(_)?_:0.5;return Math.max(0,Math.min(1,$))}function XZ(_,$){let D=_.kind==="choose_local"||_.kind==="choose_remote"||_.kind==="no_op"||_.kind==="custom"||_.kind==="manual_merge"?_.kind:"manual_merge";return{kind:D,target:typeof _.target==="string"&&_.target?_.target:$,strategy:typeof _.strategy==="string"&&_.strategy?_.strategy:D.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 GZ(_){let $=`${_.conflict.entity_kind}:${_.conflict.entity_id}`,D=Boolean(_.local_row&&_.remote_row);return{kind:D?"manual_merge":"custom",target:$,strategy:D?"manual-merge":"review-and-select",summary:D?`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:D?[`--- ${$} 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 xG(_){let $=(_.now??new Date).toISOString();c(_.dbPath);let D=$U(_.dbPath,_.id),I=uX(_.dbPath,_.id),U=T$(_.modelRef??"default",_.config),E=f_(U),j=`run_${fG()}`,N=zZ({deterministic:D,evidence:I});JZ({dbPath:_.dbPath,runId:j,prompt:N,provider:E.provider,model:E.model,status:_.fake?"dry_run":"running",metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,read_only_tools:I.read_only_tools.map((g)=>g.name)},now:$}),zP({dbPath:_.dbPath,runId:j,level:"info",event:"conflict_evidence_retrieved",metadata:{citations:I.citations.length,source_refs:I.source_refs.length,read_only_tools:I.read_only_tools},now:$});let O,S,L=0.5,W={input_tokens:PP(N),output_tokens:0,cost_usd:0};if(_.fake)O=GZ(I),S=O.summary,W.output_tokens=PP(S)+PP(O.diff??"");else try{let{generateObject:g}=await import("ai"),{z}=await Promise.resolve().then(() => (wG(),vG)),G=await lD(U,{config:_.config,env:_.env}),J=z.object({summary:z.string(),confidence:z.number().min(0).max(1),proposed_patch:z.object({kind:z.enum(["manual_merge","choose_local","choose_remote","no_op","custom"]),target:z.string(),strategy:z.string(),summary:z.string(),diff:z.string().nullable(),metadata:z.record(z.string(),z.unknown()).default({})})}),P=await g({model:G,schema:J,system:"You are a read-only knowledge sync conflict proposal agent. You produce reviewable proposals only; never approve or apply writes.",prompt:N});S=P.object.summary,L=gZ(P.object.confidence),O=XZ(P.object.proposed_patch,`${I.conflict.entity_kind}:${I.conflict.entity_id}`);let X=L4({provider:E.provider,model:E.model,usage:P.usage,providerMetadata:P.providerMetadata});W={input_tokens:X.input_tokens,output_tokens:X.output_tokens,cost_usd:X.cost_usd},PZ(_.dbPath,j,X,$)}catch(g){throw zP({dbPath:_.dbPath,runId:j,level:"error",event:"conflict_proposal_generation_failed",metadata:{message:g instanceof Error?g.message:String(g)},now:$}),rG({dbPath:_.dbPath,runId:j,status:"failed",provider:E.provider,model:E.model,usage:W,metadata:{conflict_id:_.id,mode:"ai",error:g instanceof Error?g.message:String(g)},now:$}),g}return rG({dbPath:_.dbPath,runId:j,status:_.fake?"dry_run":"completed",provider:E.provider,model:E.model,usage:W,metadata:{conflict_id:_.id,mode:"ai",fake:_.fake===!0,confidence:L,proposed_strategy:O.strategy,citation_count:I.citations.length},now:$}),zP({dbPath:_.dbPath,runId:j,level:"info",event:_.fake?"fake_conflict_proposal_generated":"conflict_proposal_generated",metadata:{strategy:O.strategy,confidence:L,patch_kind:O.kind},now:$}),{...D,mode:"ai",proposed_strategy:O.strategy,summary:S,proposed_patch:O,citations:I.citations,confidence:L,agent:{generated:!0,provider:E.provider,model:E.model,run_id:j,read_only_tools:I.read_only_tools,usage:W},warnings:[...D.warnings,...I.remote_row?[]:["remote_row_snapshot_unavailable"]],message:`Prepared AI SDK approval-gated merge proposal for ${_.id}`}}import{createHash as RZ,randomUUID as YZ}from"crypto";import{existsSync as QZ,readFileSync as KZ}from"fs";import{basename as TZ}from"path";function fj(_,$){return`${_}_${RZ("sha256").update($).digest("hex").slice(0,20)}`}function ID(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:void 0}function g_(_){return typeof _==="string"&&_.length>0?_:void 0}function FZ(_){let $=g_(_.source_ref)??g_(_.source_uri)??g_(_.uri);if($)return $;let D=g_(_.file_id);if(D){let E=g_(_.revision_id)??g_(_.revision),j=`open-files://file/${encodeURIComponent(D)}`;return E?`${j}/revision/${encodeURIComponent(E)}`:j}let I=g_(_.source_id),U=g_(_.path);if(I&&U)return`open-files://source/${encodeURIComponent(I)}/path/${encodeURIComponent(U)}`;throw Error("Outbox event is missing source_ref, file_id, or source_id/path.")}function VZ(_,$){if($.kind==="open-files"&&$.entity==="file"&&$.revision_id)return _.replace(/\/revision\/[^/]+$/,"");return _}function BZ(_){return g_(_.hash)??g_(_.checksum)??g_(_.sha256)??null}function MZ(_,$,D){return g_(_.revision_id)??g_(_.revision)??g_(_.version_id)??($.kind==="open-files"?$.revision_id:void 0)??D??null}function ZZ(_){return g_(_.previous_revision_id)??g_(_.previous_revision)??g_(_.previous_version_id)??null}function HZ(_){return(g_(_.event_type)??g_(_.event)??g_(_.type)??g_(_.action)??g_(_.change_type)??"changed").toLowerCase()}function bZ(_){let $=g_(_.path);return g_(_.title)??g_(_.name)??($?TZ($):null)}function qZ(_,$){let D=FZ(_),I=J$(D),U=BZ(_);return{raw:_,eventType:HZ(_),sourceRef:D,sourceUri:VZ(D,I),kind:I.kind,title:bZ(_),revision:MZ(_,I,U),previousRevision:ZZ(_),hash:U,status:g_(_.status)?.toLowerCase()??null,updatedAt:g_(_.updated_at)??$,acl:_.permissions??_.acl??void 0}}function kZ(_){let $=_.trim();if(!$)return[];if($.startsWith("[")){let D=JSON.parse($);if(!Array.isArray(D))throw Error("Outbox array parse failed.");return D.map((I)=>{let U=ID(I);if(!U)throw Error("Outbox array entries must be objects.");return U})}if($.startsWith("{"))try{let D=JSON.parse($),I=ID(D);if(!I)throw Error("Outbox object parse failed.");if(Array.isArray(I.events))return I.events.map((U)=>{let E=ID(U);if(!E)throw Error("Outbox events entries must be objects.");return E});if("source_ref"in I||"source_uri"in I||"file_id"in I)return[I]}catch(D){let I=$.split(/\r?\n/).filter((U)=>U.trim().length>0);if(I.length<=1)throw D;return I.map((U)=>{let E=ID(JSON.parse(U));if(!E)throw Error("Outbox JSONL entries must be objects.");return E})}return $.split(/\r?\n/).filter((D)=>D.trim().length>0).map((D)=>{let I=ID(JSON.parse(D));if(!I)throw Error("Outbox JSONL entries must be objects.");return I})}async function CZ(_,$,D){let I=new URL(_),U=I.hostname,E=decodeURIComponent(I.pathname.replace(/^\/+/,""));if(!U||!E)throw Error(`Invalid S3 outbox URI: ${_}`);if(D)Z6(_,D);let[{S3Client:j,GetObjectCommand:N},{fromIni:O}]=await Promise.all([import("@aws-sdk/client-s3"),import("@aws-sdk/credential-providers")]),S=$?.storage.type==="s3"&&$.storage.s3?.bucket===U?$.storage.s3:void 0,W=await new j({region:S?.region,credentials:S?.profile?O({profile:S.profile}):void 0,maxAttempts:S?.max_attempts}).send(new N({Bucket:U,Key:E}));if(!W.Body)return"";return await W.Body.transformToString()}async function vZ(_,$,D){if(_.startsWith("s3://"))return CZ(_,$,D);if(!QZ(_))throw Error(`Outbox not found: ${_}`);return KZ(_,"utf8")}function uG(_,$){let D={};if(_)try{D=ID(JSON.parse(_))??{}}catch{D={}}return JSON.stringify({...D,...$})}function wZ(_,$,D){let I=fj("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`,[I,$.sourceUri,$.kind,$.title,JSON.stringify({source_ref:$.sourceRef,source_uri:$.sourceUri,status:$.status,last_outbox_event:$.eventType}),JSON.stringify($.acl??{}),D,$.updatedAt]);let U=_.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get($.sourceUri);if(!U)throw Error(`Failed to upsert source for outbox event: ${$.sourceUri}`);let E={source_ref:$.sourceRef,source_uri:$.sourceUri,last_outbox_event:$.eventType,last_outbox_at:$.updatedAt};if($.status)E.status=$.status;if(z_($.raw.path))E.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 = ?",[xG(U.metadata_json,E),$.acl===void 0?null:JSON.stringify($.acl),$.acl===void 0?null:JSON.stringify($.acl),$.updatedAt,U.id]),U.id}function rb(_,$,D,I){if(!D.revision)return null;let U=rj("rev",`${$}\x00${D.revision}`),E={source_ref:D.sourceRef,source_uri:D.sourceUri,status:D.status,last_outbox_event:D.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`,[I,$.sourceUri,$.kind,$.title,JSON.stringify({source_ref:$.sourceRef,source_uri:$.sourceUri,status:$.status,last_outbox_event:$.eventType}),JSON.stringify($.acl??{}),D,$.updatedAt]);let U=_.query("SELECT id, metadata_json, acl_json FROM sources WHERE uri = ?").get($.sourceUri);if(!U)throw Error(`Failed to upsert source for outbox event: ${$.sourceUri}`);let E={source_ref:$.sourceRef,source_uri:$.sourceUri,last_outbox_event:$.eventType,last_outbox_at:$.updatedAt};if($.status)E.status=$.status;if(g_($.raw.path))E.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 = ?",[uG(U.metadata_json,E),$.acl===void 0?null:JSON.stringify($.acl),$.acl===void 0?null:JSON.stringify($.acl),$.updatedAt,U.id]),U.id}function rZ(_,$,D,I){if(!D.revision)return null;let U=fj("rev",`${$}\x00${D.revision}`),E={source_ref:D.sourceRef,source_uri:D.sourceUri,status:D.status,last_outbox_event:D.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`,[U,$,D.revision,D.hash,z_(D.raw.extracted_text_ref)??null,JSON.stringify(E),I]),_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get($,D.revision)?.id??null}function fb(_,$,D){if(D.previousRevision){let I=_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,D.previousRevision).map((U)=>U.id);if(I.length>0)return I}if(D.revision)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,D.revision).map((I)=>I.id);if(D.hash)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all($,D.hash).map((I)=>I.id);return _.query("SELECT id FROM source_revisions WHERE source_id = ?").all($).map((I)=>I.id)}function xb(_,$){let D=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($),I=0,U=0;for(let j of D){let N=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(j.id);I+=N?.n??0;let A=_.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(j.id);U+=A?.n??0,_.run("DELETE FROM vector_index_entries WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[j.id])}_.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]);let E=_.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get($);return _.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?",[xG(E?.metadata_json,{reindex_required:!0,invalidated_at:new Date().toISOString()}),$]),{chunksDeleted:D.length,embeddingsDeleted:I,vectorEntriesDeleted:U}}function ub(_,$){return $==="deleted"||["delete","deleted","remove","removed"].includes(_)}function yb(_){return["move","moved","rename","renamed","path_changed","canonical_key_changed"].includes(_)}function hb(_){return["permission","permissions","permission_changed","acl_changed","acl_revoked"].includes(_)}async function uG(_){let $=(_.now??new Date).toISOString();if(_.safetyPolicy)N6(_.dbPath,_.safetyPolicy);c(_.dbPath);let D=await vb(_.input,_.config,_.safetyPolicy),I=qb(D),U=w(_.dbPath),E=`run_${Yb()}`;try{return U.transaction(()=>{U.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,"open-files-outbox",_.input,"completed","local","open-files-outbox",JSON.stringify({path:_.input,events:I.length}),$,$]);let j=new Set,N=new Set,A=0,O=0,S=0,L=0,P=0,z=0,G=0;return R_(U,{event_type:"source_read",action:_.input.startsWith("s3://")?"s3_outbox_read":"local_outbox_read",target_uri:_.input,decision:"allow",metadata:{events:I.length,read_only:!0},created_at:$}),I.forEach((J,W)=>{let X=kb(J,$),R=wb(U,X,$);j.add(R);let T=rb(U,R,X,$);if(T)N.add(T);let Y=fb(U,R,X);for(let Q of Y){N.add(Q);let F=xb(U,Q);A+=F.chunksDeleted,O+=F.embeddingsDeleted,S+=F.vectorEntriesDeleted,L+=1}if(ub(X.eventType,X.status))P+=1;if(yb(X.eventType))z+=1;if(hb(X.eventType)||X.acl!==void 0)G+=1;U.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[rj("evt",`${E}\x00${W}\x00${X.sourceRef}\x00${X.eventType}`),E,"info",X.eventType,JSON.stringify({source_ref:X.sourceRef,source_uri:X.sourceUri,revision:X.revision,hash:X.hash,status:X.status,affected_revisions:Y.length}),X.updatedAt])}),U.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) - VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[rj("usage",E),E,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),$]),R_(U,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:_.dbPath,decision:"allow",metadata:{run_id:E,events:I.length,sources:j.size,revisions:N.size,chunks_deleted:A,embeddings_deleted:O,vector_entries_deleted:S},created_at:$}),{path:_.input,db_path:_.dbPath,run_id:E,events_seen:I.length,sources_touched:j.size,revisions_touched:N.size,chunks_deleted:A,embeddings_deleted:O,vector_entries_deleted:S,stale_revisions:L,deleted_sources:P,moved_sources:z,permission_updates:G}})()}finally{U.close()}}import{spawnSync as cG}from"child_process";import{hostname as n4,platform as nG,userInfo as cb}from"os";var nb=1,db="@hasna/machines",mb="@hasna/machines/consumer";function m(_){return typeof _==="string"&&_.length>0?_:null}function m6(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function d_(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function cj(_){return typeof _==="boolean"?_:null}function lb(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function nj(_=nG()){let $=_.toLowerCase();if($==="darwin"||$==="macos")return"macos";if($==="win32"||$==="windows")return"windows";if($==="linux")return"linux";return _}function S1(_){let $=cG("bash",["-c",_],{encoding:"utf8",env:process.env});return{stdout:$.stdout||"",stderr:$.stderr||"",exitCode:$.status??1}}async function UD(_,$){return await _($)}async function L1(_,$){return(await UD($,`command -v ${_} >/dev/null 2>&1`)).exitCode===0}function ib(_){try{let $=JSON.parse(_);if(!$||typeof $!=="object")return null;return $}catch{return null}}function yG(_){if(!_)return null;return _.HostName??_.DNSName?.split(".")[0]??null}async function tb(_,$){let D=new Map;if(!await L1("tailscale",_))return $.push("tailscale_not_available"),{peers:D,selfKey:null};let I=await UD(_,"tailscale status --json");if(I.exitCode!==0)return $.push(`tailscale_status_failed:${I.stderr.trim()||I.exitCode}`),{peers:D,selfKey:null};let U=ib(I.stdout);if(!U)return $.push("tailscale_status_invalid_json"),{peers:D,selfKey:null};let E=(j)=>{let N=yG(j);if(N&&j)D.set(N,j)};E(U.Self);for(let j of Object.values(U.Peer??{}))E(j);return{peers:D,selfKey:yG(U.Self)}}function ob(_){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??_??n4()}function pb(_){let $=_.machineId===_.localMachineId||_.machineId===n4(),D=_.peer?.DNSName?.replace(/\.$/,"")??null,I=D??_.peer?.TailscaleIPs?.[0]??null,U=[];if($)U.push({kind:"local",target:"localhost",reachable:!0});if(I)U.push({kind:"tailscale",target:I,reachable:_.peer?.Online??null});let E=U.find((j)=>j.kind==="local")??U.find((j)=>j.kind==="tailscale")??null;return{machine_id:_.machineId,hostname:_.peer?.HostName??($?n4():_.machineId),local:$,platform:_.peer?.OS?nj(_.peer.OS):$?nj():null,os:_.peer?.OS??($?nG():null),user:$?cb().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:D,ips:_.peer?.TailscaleIPs??[],online:_.peer?.Online??null,active:_.peer?.Active??null,last_seen:_.peer?.LastSeen??null},ssh:{address:null,route:E?.kind==="local"?"local":E?.kind==="tailscale"?"tailscale":"unknown",command_target:E?.target??null},route_hints:U,tags:[],metadata:{},source:"local"}}function eb(_){if(!Array.isArray(_))return[];return _.map(($)=>{let D=d_($),I=m(D.kind)??"unknown";return{kind:I==="local"||I==="lan"||I==="tailscale"||I==="ssh"?I:"unknown",target:m(D.target)??"",reachable:cj(D.reachable)}}).filter(($)=>$.target.length>0)}function ab(_,$){let D=m(_.machine_id)??m(_.hostname)??"unknown",I=d_(_.tailscale),U=d_(_.ssh),E=m(_.heartbeat_status),j=m(U.route);return{machine_id:D,hostname:m(_.hostname),local:D===$,platform:m(_.platform),os:m(_.os),user:m(_.user),workspace_path:m(_.workspace_path),manifest_declared:_.manifest_declared===!0,heartbeat_status:E==="online"||E==="offline"?E:"unknown",last_heartbeat_at:m(_.last_heartbeat_at),tailscale:{dns_name:m(I.dns_name),ips:m6(I.ips),online:cj(I.online),active:cj(I.active),last_seen:m(I.last_seen)},ssh:{address:m(U.address),route:j==="local"||j==="lan"||j==="tailscale"?j:"unknown",command_target:m(U.command_target)},route_hints:eb(_.route_hints),tags:m6(_.tags),metadata:d_(_.metadata),source:"open-machines"}}function sb(_,$){return`${$} machine${$===1?"":"s"} discovered via ${_}`}function S$(_){let $=_ instanceof Error?_.message:String(_);return $.includes("Cannot find module '@hasna/machines'")||$.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":$}function J1(_){return _.adapterMode??"auto"}function dG(_){let $=_?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof $==="number")return $;let D=_?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof D==="number"?D:null}function dj(_){return typeof _.schema_version==="number"?_.schema_version:null}function W1(_){return typeof _==="number"&&_>nb?_:null}function mj(_){return{package:db,entrypoint:mb,mode:_.mode,implementation:_.implementation,contract_version:_.contractVersion??null,available:_.available,error:_.error??null}}function g_(_,$="adapter_disabled"){return mj({mode:_,implementation:"disabled",available:!1,error:$})}function lj(_,$){let D=W1(dG($));if(!D)return null;return mj({mode:_,implementation:"disabled",available:!1,error:`unsupported_contract_version:${D}`,contractVersion:D})}function ij(_){return mj({mode:_,implementation:"cli",available:!0})}function tj(_,$){return mj({mode:_,implementation:"sdk",available:!0,contractVersion:dG($)})}function oj(_){try{return JSON.parse(_)}catch{return null}}function d4(_){return`'${_.replace(/'/g,"'\\''")}'`}function pj(_){return["machines",..._].map(d4).join(" ")}function ej(_){return _==="local"||_==="localhost"||_===n4()||_===process.env.HASNA_MACHINE_ID||_===process.env.OPEN_MACHINES_MACHINE_ID||_===process.env.MACHINE_ID}function _Z(_,$){let D=ej(_),I=D?$:`ssh ${d4(_)} ${d4($)}`,U=cG("bash",["-c",I],{encoding:"utf8",env:process.env});return{stdout:U.stdout||"",stderr:U.stderr||"",exitCode:U.status??1,source:D?"local":"ssh"}}async function mG(_,$,D){return await _($,D)}function h4(_,$){if($)return"ok";return _===!1?"warn":"fail"}function c4(_){return _.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function $Z(_){if(_==="@hasna/knowledge")return"knowledge";if(_==="@hasna/machines")return"machines";return _.split("/").pop()??_}function DZ(_){return _.trim().split(/\r?\n/).find(Boolean)??""}function lG(_){return _.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function iG(_){let $={};for(let D of _.split(/\r?\n/)){let I=D.indexOf("=");if(I<=0)continue;$[D.slice(0,I)]=D.slice(I+1)}return $}function G6(_){return{id:_.id,kind:_.kind,status:_.status,target:_.target,expected:_.expected??null,actual:_.actual??null,detail:_.detail,source:_.source}}async function tG(_,$,D){let I=[`cmd=${d4($.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("; "),U=await mG(D,_,I),E=iG(U.stdout);return{path:E.path||null,version:E.version?DZ(E.version):null,stderr:U.stderr,source:U.source??(ej(_)?"local":"ssh")}}function hG(_){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 UZ(_,$,D){let I=[`path=${d4($.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" "$(${hG("name")})"; printf "version=%s\\n" "$(${hG("version")})"; fi`].join("; "),U=await mG(D,_,I),E=iG(U.stdout);return{exists:E.exists==="yes",packageJson:E.package_json==="yes",packageName:E.package_name||null,version:E.version||null,stderr:U.stderr,source:U.source??(ej(_)?"local":"ssh")}}async function IZ(_,$,D){let I=await tG(_,$,D),U=Boolean(I.path),E=[G6({id:`command:${c4($.command)}:path`,kind:"command",status:h4($.required,U),target:$.command,expected:"available",actual:I.path??"missing",detail:U?`found at ${I.path}`:I.stderr||"command missing",source:I.source})];if($.expectedVersion){let j=lG(I.version??"");E.push(G6({id:`command:${c4($.command)}:version`,kind:"command",status:j===$.expectedVersion?"ok":h4($.required,!1),target:$.command,expected:$.expectedVersion,actual:j??I.version??"missing",detail:j?`version output: ${I.version}`:"version unavailable",source:I.source}))}return E}async function EZ(_,$,D){let I=$.command??$Z($.name),U=await tG(_,{command:I,expectedVersion:$.expectedVersion,required:$.required},D),E=Boolean(U.path),j=[G6({id:`package:${c4($.name)}:command`,kind:"package",status:h4($.required,E),target:$.name,expected:I,actual:U.path??"missing",detail:E?`${I} found at ${U.path}`:`${I} command missing`,source:U.source})];if($.expectedVersion){let N=lG(U.version??"");j.push(G6({id:`package:${c4($.name)}:version`,kind:"package",status:N===$.expectedVersion?"ok":h4($.required,!1),target:$.name,expected:$.expectedVersion,actual:N??U.version??"missing",detail:N?`version output: ${U.version}`:"version unavailable",source:U.source}))}return j}async function jZ(_,$,D){let I=await UZ(_,$,D),U=$.label??$.path,E=[G6({id:`workspace:${c4(U)}:path`,kind:"workspace",status:h4($.required,I.exists),target:U,expected:$.path,actual:I.exists?"exists":"missing",detail:I.exists?`workspace exists at ${$.path}`:I.stderr||`workspace missing at ${$.path}`,source:I.source})];if($.expectedPackageName)E.push(G6({id:`workspace:${c4(U)}:package-name`,kind:"workspace",status:I.packageName===$.expectedPackageName?"ok":h4($.required,!1),target:U,expected:$.expectedPackageName,actual:I.packageName??(I.packageJson?"missing-name":"missing-package-json"),detail:I.packageJson?"package.json inspected":"package.json missing",source:I.source}));if($.expectedVersion)E.push(G6({id:`workspace:${c4(U)}:version`,kind:"workspace",status:I.version===$.expectedVersion?"ok":h4($.required,!1),target:U,expected:$.expectedVersion,actual:I.version??(I.packageJson?"missing-version":"missing-package-json"),detail:I.packageJson?"package.json inspected":"package.json missing",source:I.source}));return E}function oG(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:s$,workspace_home:$.knowledge?.workspace_home??null},message:sb(_.source,_.machines.length)}}async function aj(){try{return await import("@hasna/machines/consumer")}catch(_){if(S$(_)!=="module_not_found")throw _;return await import("@hasna/machines")}}function pG(_,$,D){let I=d_(_);if(W1(dj(I)))return null;let U=Array.isArray(I.machines)?I.machines:null,E=m(I.local_machine_id);if(!U||!E)return null;let j={ok:!0,source:"open-machines",generated_at:m(I.generated_at)??($.now??new Date).toISOString(),local_machine_id:E,local_hostname:m(I.local_hostname)??n4(),current_platform:m(I.current_platform)??nj(),machines:U.map((N)=>ab(N,E)),warnings:m6(I.warnings),adapter:D};return oG(j,$)}function fj(_){return _==="local"||_==="lan"||_==="tailscale"||_==="ssh"||_==="unknown"?_:null}function eG(_){let $=d_(_),D=m($.observed_at),I=m($.source_authority);if(!D||!I)return null;return{observed_at:D,verified_at:m($.verified_at),expires_at:m($.expires_at),ttl_ms:lb($.ttl_ms),source_authority:I,confidence:m($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:m6($.reasons)}}function aG(_,$){let D=d_(_);if(W1(dj(D)))return null;let I=m(D.target)??m(D.command_target);if(D.ok!==!0||!I)return null;let U=typeof D.evidence==="object"&&D.evidence!==null?D.evidence:null,E=typeof U?.selected_hint==="object"&&U.selected_hint!==null?U.selected_hint:null;return{target:I,route:fj(D.route),targetKind:fj(E?.kind)??fj(D.source)??fj(D.route),confidence:m(D.confidence),source:"open-machines",adapter:$,evidence:U,cacheability:eG(D.cacheability),warnings:m6(D.warnings)}}function zW(_){let $=d_(_);return{path:m($.path),source:m($.source)??"unresolved"}}function NZ(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=d_($),I=m(D.id),U=m(D.status),E=m(D.severity),j=m(D.message);if(!I||!U||!E||!j)return[];return[{id:I,status:U,severity:E,message:j,path:m(D.path),source:m(D.source)??"unknown",path_exists:cj(D.path_exists)}]})}function gZ(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=d_($),I=m(D.id),U=m(D.reason),E=m6(D.command),j=m(D.shell_command),N=m6(D.apply_command),A=m(D.apply_shell_command);if(!I||!U||!E.length||!j||!N.length||!A)return[];return[{id:I,reason:U,command:E,shell_command:j,apply_command:N,apply_shell_command:A}]})}function AZ(_){if(!(_.projectRootSource==="inferred"||_.openFilesRootSource==="inferred"||_.trustStatus==="untrusted"||_.authStatus==="unknown"||_.warnings.some((U)=>U.includes("inferred")||U.includes("untrusted")||U.includes("unknown_auth")||U.includes("missing"))))return[];let D=["machines","workspace","repair","--machine",_.requestedMachineId,"--project",_.projectId,"--repo",_.repoName,"--open-files-repo",_.openFilesRepoName??"open-files","--json"],I=[...D,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:D,shell_command:D.map(d4).join(" "),apply_command:I,apply_shell_command:I.map(d4).join(" ")}]}function sG(_,$,D){let I=d_(_);if(W1(dj(I)))return null;let U=d_(I.paths),E=d_(I.project),j=d_(I.machine),N=zW(U.project_root),A=zW(U.workspace_root),O=zW(U.open_files_root);if(I.ok!==!0||!N.path)return null;let S=typeof I.evidence==="object"&&I.evidence!==null?I.evidence:null,L=m(I.requested_machine_id)??$.machineId,P=m(E.project_id)??$.projectId??"open-knowledge",z=m(E.repo_name)??$.repoName??$.projectId??"open-knowledge",G=m(j.trust_status)??"unknown",J=m(j.auth_status)??"unknown",W=m6(I.warnings),X=NZ(I.diagnostics),R=gZ(I.repair_hints);return{ok:!0,source:"open-machines",adapter:D,requested_machine_id:L,machine_id:m(I.machine_id),project_id:P,repo_name:z,project_root:N.path,project_root_source:N.source,workspace_root:A.path,workspace_root_source:A.source,open_files_root:O.path,open_files_root_source:O.source,trust_status:G,auth_status:J,current:j.current===!0,primary:j.primary===!0,diagnostics:X,repair_hints:R.length?R:AZ({requestedMachineId:L,projectId:P,repoName:z,openFilesRepoName:$.openFilesRepoName,warnings:W,projectRootSource:N.source,openFilesRootSource:O.source,trustStatus:G,authStatus:J}),evidence:S,cacheability:eG(I.cacheability),warnings:W}}async function xj(_,$){let D=_.runner??S1;if(!await L1("machines",D))return null;let I=["topology","--json"];if(_.includeTailscale===!1)I.push("--no-tailscale");let U=await UD(D,pj(I));if(U.exitCode!==0)return null;return pG(oj(U.stdout),_,$)}async function W6(_,$){let D=[];if($.error)D.push(`open_machines_unavailable:${$.error}`);let I=_.runner??S1,U=_.includeTailscale===!1?{peers:new Map,selfKey:null}:await tb(I,D),E=ob(U.selfKey),N=[...new Set([E,...U.peers.keys()])].sort().map((A)=>pb({machineId:A,localMachineId:E,peer:U.peers.get(A)}));return oG({ok:!0,source:"local",generated_at:(_.now??new Date).toISOString(),local_machine_id:E,local_hostname:n4(),current_platform:nj(),machines:N,warnings:D,adapter:$},_)}async function _R(_={}){let $=J1(_);if($==="disabled")return await W6(_,g_($));let D=ij($);try{if($!=="cli"){let U=await(_.loadOpenMachines??aj)(),E=lj($,U);if(E)return await W6(_,E);let j=tj($,U);if(U?.discoverMachineTopology){let N=U.discoverMachineTopology({includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),A=pG(N,_,j);if(A)return A;if($==="sdk")return await W6(_,g_($,"invalid_topology_shape"));return await xj(_,D)??await W6(_,g_($,"invalid_topology_shape"))}if($==="sdk")return await W6(_,g_($,"missing_discoverMachineTopology"));return await xj(_,D)??await W6(_,g_($,"missing_discoverMachineTopology"))}return await xj(_,D)??await W6(_,g_($,"machines_cli_unavailable"))}catch(I){if($==="sdk")return await W6(_,g_($,S$(I)));return await xj(_,D)??await W6(_,g_($,S$(I)))}}async function uj(_,$){let D=_.runner??S1;if(!await L1("machines",D))return null;let I=["route","--machine",_.machineId,"--json"];if(_.includeTailscale===!1)I.push("--no-tailscale");let U=await UD(D,pj(I));if(U.exitCode!==0)return null;return aG(oj(U.stdout),$)}function P6(_,$){return{target:_,route:null,targetKind:null,confidence:null,source:"raw",adapter:$,evidence:null,cacheability:null,warnings:[]}}async function XW(_){let $=J1(_);if($==="disabled")return P6(_.machineId,g_($));let D=ij($);try{if($!=="cli"){let U=await(_.loadOpenMachines??aj)(),E=lj($,U);if(E)return P6(_.machineId,E);let j=tj($,U);if(U?.resolveMachineRoute){let N=aG(U.resolveMachineRoute(_.machineId,{includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),j);if(N)return N;if($==="sdk")return P6(_.machineId,g_($,"invalid_route_shape"));return await uj(_,D)??P6(_.machineId,g_($,"invalid_route_shape"))}if($==="sdk")return P6(_.machineId,g_($,"missing_resolveMachineRoute"));return await uj(_,D)??P6(_.machineId,g_($,"missing_resolveMachineRoute"))}return await uj(_,D)??P6(_.machineId,g_($,"machines_cli_unavailable"))}catch(I){if($==="sdk")return{...P6(_.machineId,g_($,S$(I))),warnings:[S$(I)]};return await uj(_,D)??{...P6(_.machineId,g_($,S$(I))),warnings:[S$(I)]}}}async function yj(_,$){let D=_.runner??S1;if(!await L1("machines",D))return null;let I=_.projectId??"open-knowledge",U=_.repoName??"open-knowledge",E=["workspace","resolve","--machine",_.machineId,"--project",I,"--repo",U,"--open-files-repo",_.openFilesRepoName??"open-files","--json"];if(_.includeTailscale===!1)E.push("--no-tailscale");let j=await UD(D,pj(E));if(j.exitCode!==0)return null;return sG(oj(j.stdout),_,$)}function OZ(_){let $=_.peerWorkspace?.trim();if(!$)return null;return{ok:!0,source:"argument",adapter:g_(J1(_),"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 z6(_,$,D){return{ok:!1,source:"raw",adapter:D,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 sj(_){let $=OZ(_);if($)return $;let D=J1(_);if(D==="disabled")return z6(_,["adapter_disabled"],g_(D));let I=ij(D);try{if(D!=="cli"){let E=await(_.loadOpenMachines??aj)(),j=lj(D,E);if(j)return z6(_,[`unsupported_contract_version:${j.contract_version}`],j);let N=tj(D,E);if(E?.resolveMachineWorkspace){let A=sG(E.resolveMachineWorkspace({machineId:_.machineId,projectId:_.projectId??"open-knowledge",repoName:_.repoName??"open-knowledge",openFilesRepoName:_.openFilesRepoName??"open-files",includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),_,N);if(A)return A;if(D==="sdk")return z6(_,["invalid_workspace_shape"],g_(D,"invalid_workspace_shape"));return await yj(_,I)??z6(_,["invalid_workspace_shape"],g_(D,"invalid_workspace_shape"))}if(D==="sdk")return z6(_,["missing_resolveMachineWorkspace"],g_(D,"missing_resolveMachineWorkspace"));return await yj(_,I)??z6(_,["missing_resolveMachineWorkspace"],g_(D,"missing_resolveMachineWorkspace"))}return await yj(_,I)??z6(_,["machines_cli_unavailable"],g_(D,"machines_cli_unavailable"))}catch(U){if(D==="sdk")return z6(_,[S$(U)],g_(D,S$(U)));return await yj(_,I)??z6(_,[S$(U)],g_(D,S$(U)))}}function $R(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:s$,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 DR(_,$,D){let I=d_(_);if(W1(dj(I)))return null;let U=Array.isArray(I.checks)?I.checks:null,E=m(I.machine_id)??m(I.machineId);if(!U||!E)return null;let j=U.map((A)=>{let O=d_(A),S=m(O.status),L=m(O.kind),P=m(O.source);return G6({id:m(O.id)??"unknown",kind:L==="command"||L==="package"||L==="workspace"?L:"command",status:S==="ok"||S==="warn"||S==="fail"?S:"fail",target:m(O.target)??"unknown",expected:m(O.expected),actual:m(O.actual),detail:m(O.detail)??"",source:P==="local"||P==="ssh"||P==="open-machines"?P:"open-machines"})}),N={ok:j.filter((A)=>A.status==="ok").length,warn:j.filter((A)=>A.status==="warn").length,fail:j.filter((A)=>A.status==="fail").length};return $R({ok:N.fail===0,source:"open-machines",machine_id:E,generated_at:m(I.generated_at)??($.now??new Date).toISOString(),checks:j,summary:N,adapter:D},$)}function SZ(_){if(!_.runner)return S1;return async($)=>{let D=await _.runner?.("local",$);return{stdout:D?.stdout??"",stderr:D?.stderr??"",exitCode:D?.exitCode??1}}}function LZ(_){return[_.name,_.command,_.expectedVersion].filter(($)=>Boolean($)).join(":")}function JZ(_){let $=[_.expectedPackageName,_.expectedVersion].filter((I)=>Boolean(I)).join(":"),D=$?`${_.path}:${$}`:_.path;return _.label?`${_.label}=${D}`:D}async function hj(_,$){let D=SZ(_);if(!await L1("machines",D))return null;let I=["compatibility","--json","--machine",_.machineId??"local"];for(let E of _.commands??[])I.push("--command",E.expectedVersion?`${E.command}:${E.expectedVersion}`:E.command);for(let E of _.packages??[])I.push("--package",LZ(E));for(let E of _.workspaces??[])I.push("--workspace",JZ(E));let U=await UD(D,pj(I));if(U.exitCode!==0)return null;return DR(oj(U.stdout),_,$)}async function X6(_,$){let D=_.machineId??n4(),I=_.runner??_Z,U=_.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],E=_.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],j=_.workspaces??[],N=[];for(let O of U)N.push(...await IZ(D,O,I));for(let O of E)N.push(...await EZ(D,O,I));for(let O of j)N.push(...await jZ(D,O,I));if($.error)N.push(G6({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:$.error,detail:"Using knowledge local/ssh compatibility fallback",source:ej(D)?"local":"ssh"}));let A={ok:N.filter((O)=>O.status==="ok").length,warn:N.filter((O)=>O.status==="warn").length,fail:N.filter((O)=>O.status==="fail").length};return $R({ok:A.fail===0,source:"local",machine_id:D,generated_at:(_.now??new Date).toISOString(),checks:N,summary:A,adapter:$},_)}async function UR(_={}){let $=J1(_);if($==="disabled")return await X6(_,g_($));let D=ij($);try{if($!=="cli"){let U=await(_.loadOpenMachines??aj)(),E=lj($,U);if(E)return await X6(_,E);let j=tj($,U);if(U?.checkMachineCompatibility){let N=U.checkMachineCompatibility({machineId:_.machineId,commands:_.commands,packages:_.packages,workspaces:_.workspaces,runner:_.runner,now:_.now}),A=DR(N,_,j);if(A)return A;if($==="sdk")return await X6(_,g_($,"invalid_compatibility_shape"));return await hj(_,D)??await X6(_,g_($,"invalid_compatibility_shape"))}if($==="sdk")return await X6(_,g_($,"missing_checkMachineCompatibility"));return await hj(_,D)??await X6(_,g_($,"missing_checkMachineCompatibility"))}return await hj(_,D)??await X6(_,g_($,"machines_cli_unavailable"))}catch(I){if($==="sdk")return await X6(_,g_($,S$(I)));return await hj(_,D)??await X6(_,g_($,S$(I)))}}import{createHash as IR}from"crypto";function RW(_,$,D=24){return`${_}_${IR("sha256").update($).digest("hex").slice(0,D)}`}function ID(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function WZ(_){return ID(_).toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")}function Z$(_,$){try{return JSON.parse(_)}catch{return $}}function l6(_){return{..._,record_kind:_.record_kind,source_kind:_.source_kind,status:_.status,source_refs:Z$(_.source_refs_json,[]),evidence_refs:Z$(_.evidence_refs_json,[]),requires_approval:_.requires_approval===1,checks:Z$(_.checks_json,ER()),metadata:Z$(_.metadata_json,{})}}function YW(_){return{..._,record_kind:_.record_kind,source_refs:Z$(_.source_refs_json,[]),evidence_refs:Z$(_.evidence_refs_json,[]),metadata:Z$(_.metadata_json,{})}}function ER(){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 PZ(_){let $=typeof _==="string"?{ref:_}:_;return{ref:ID($.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 jR(_){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 _N(_){return["deleted","stale","invalidated","reindex_required","expired","superseded"].includes((_??"").toLowerCase())}function GW(_){if(!_)return null;let $=Z$(_,{});if($.stale===!0)return"stale";return typeof $.status==="string"?$.status:null}function zZ(_){if(_.citation_id)return _.citation_id;return _.ref.match(/^(?:cite|citation):(.+)$/)?.[1]??null}function XZ(_){if(_.chunk_id)return _.chunk_id;return _.ref.match(/^chunk:(.+)$/)?.[1]??null}function GZ(_,$,D){let I=_N($.status)||Boolean($.expires_at&&$.expires_at<=D);if(!$.ref||!jR($.ref))return{ref:$.ref,valid:!1,resolved_by:"none",stale:I,reason:"invalid_reference"};let U=zZ($),E=_.query(`SELECT c.id, c.source_uri, c.chunk_id, ch.metadata_json AS chunk_metadata_json, + metadata_json = excluded.metadata_json`,[U,$,D.revision,D.hash,g_(D.raw.extracted_text_ref)??null,JSON.stringify(E),I]),_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").get($,D.revision)?.id??null}function fZ(_,$,D){if(D.previousRevision){let I=_.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,D.previousRevision).map((U)=>U.id);if(I.length>0)return I}if(D.revision)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND revision = ?").all($,D.revision).map((I)=>I.id);if(D.hash)return _.query("SELECT id FROM source_revisions WHERE source_id = ? AND hash = ?").all($,D.hash).map((I)=>I.id);return _.query("SELECT id FROM source_revisions WHERE source_id = ?").all($).map((I)=>I.id)}function xZ(_,$){let D=_.query("SELECT id FROM chunks WHERE source_revision_id = ?").all($),I=0,U=0;for(let j of D){let N=_.query("SELECT COUNT(*) AS n FROM chunk_embeddings WHERE chunk_id = ?").get(j.id);I+=N?.n??0;let O=_.query("SELECT COUNT(*) AS n FROM vector_index_entries WHERE chunk_id = ?").get(j.id);U+=O?.n??0,_.run("DELETE FROM vector_index_entries WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunk_embeddings WHERE chunk_id = ?",[j.id]),_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[j.id])}_.run("DELETE FROM chunks WHERE source_revision_id = ?",[$]);let E=_.query("SELECT metadata_json FROM source_revisions WHERE id = ?").get($);return _.run("UPDATE source_revisions SET metadata_json = ? WHERE id = ?",[uG(E?.metadata_json,{reindex_required:!0,invalidated_at:new Date().toISOString()}),$]),{chunksDeleted:D.length,embeddingsDeleted:I,vectorEntriesDeleted:U}}function uZ(_,$){return $==="deleted"||["delete","deleted","remove","removed"].includes(_)}function yZ(_){return["move","moved","rename","renamed","path_changed","canonical_key_changed"].includes(_)}function hZ(_){return["permission","permissions","permission_changed","acl_changed","acl_revoked"].includes(_)}async function yG(_){let $=(_.now??new Date).toISOString();if(_.safetyPolicy)N6(_.dbPath,_.safetyPolicy);c(_.dbPath);let D=await vZ(_.input,_.config,_.safetyPolicy),I=kZ(D),U=w(_.dbPath),E=`run_${YZ()}`;try{return U.transaction(()=>{U.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[E,"open-files-outbox",_.input,"completed","local","open-files-outbox",JSON.stringify({path:_.input,events:I.length}),$,$]);let j=new Set,N=new Set,O=0,S=0,L=0,W=0,g=0,z=0,G=0;return R_(U,{event_type:"source_read",action:_.input.startsWith("s3://")?"s3_outbox_read":"local_outbox_read",target_uri:_.input,decision:"allow",metadata:{events:I.length,read_only:!0},created_at:$}),I.forEach((J,P)=>{let X=qZ(J,$),R=wZ(U,X,$);j.add(R);let T=rZ(U,R,X,$);if(T)N.add(T);let Y=fZ(U,R,X);for(let Q of Y){N.add(Q);let F=xZ(U,Q);O+=F.chunksDeleted,S+=F.embeddingsDeleted,L+=F.vectorEntriesDeleted,W+=1}if(uZ(X.eventType,X.status))g+=1;if(yZ(X.eventType))z+=1;if(hZ(X.eventType)||X.acl!==void 0)G+=1;U.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[fj("evt",`${E}\x00${P}\x00${X.sourceRef}\x00${X.eventType}`),E,"info",X.eventType,JSON.stringify({source_ref:X.sourceRef,source_uri:X.sourceUri,revision:X.revision,hash:X.hash,status:X.status,affected_revisions:Y.length}),X.updatedAt])}),U.run(`INSERT INTO provider_usage (id, run_id, provider, model, input_tokens, output_tokens, cost_usd, metadata_json, created_at) + VALUES (?, ?, ?, ?, 0, 0, 0, ?, ?)`,[fj("usage",E),E,"local","open-files-outbox",JSON.stringify({note:"No model provider used for outbox invalidation."}),$]),R_(U,{event_type:"write",action:"knowledge_outbox_invalidation",target_uri:_.dbPath,decision:"allow",metadata:{run_id:E,events:I.length,sources:j.size,revisions:N.size,chunks_deleted:O,embeddings_deleted:S,vector_entries_deleted:L},created_at:$}),{path:_.input,db_path:_.dbPath,run_id:E,events_seen:I.length,sources_touched:j.size,revisions_touched:N.size,chunks_deleted:O,embeddings_deleted:S,vector_entries_deleted:L,stale_revisions:W,deleted_sources:g,moved_sources:z,permission_updates:G}})()}finally{U.close()}}import{spawnSync as nG}from"child_process";import{hostname as d4,platform as dG,userInfo as cZ}from"os";var nZ=1,dZ="@hasna/machines",mZ="@hasna/machines/consumer";function m(_){return typeof _==="string"&&_.length>0?_:null}function m6(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function d_(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function nj(_){return typeof _==="boolean"?_:null}function lZ(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function dj(_=dG()){let $=_.toLowerCase();if($==="darwin"||$==="macos")return"macos";if($==="win32"||$==="windows")return"windows";if($==="linux")return"linux";return _}function L1(_){let $=nG("bash",["-c",_],{encoding:"utf8",env:process.env});return{stdout:$.stdout||"",stderr:$.stderr||"",exitCode:$.status??1}}async function ED(_,$){return await _($)}async function W1(_,$){return(await ED($,`command -v ${_} >/dev/null 2>&1`)).exitCode===0}function iZ(_){try{let $=JSON.parse(_);if(!$||typeof $!=="object")return null;return $}catch{return null}}function hG(_){if(!_)return null;return _.HostName??_.DNSName?.split(".")[0]??null}async function tZ(_,$){let D=new Map;if(!await W1("tailscale",_))return $.push("tailscale_not_available"),{peers:D,selfKey:null};let I=await ED(_,"tailscale status --json");if(I.exitCode!==0)return $.push(`tailscale_status_failed:${I.stderr.trim()||I.exitCode}`),{peers:D,selfKey:null};let U=iZ(I.stdout);if(!U)return $.push("tailscale_status_invalid_json"),{peers:D,selfKey:null};let E=(j)=>{let N=hG(j);if(N&&j)D.set(N,j)};E(U.Self);for(let j of Object.values(U.Peer??{}))E(j);return{peers:D,selfKey:hG(U.Self)}}function oZ(_){return process.env.HASNA_MACHINE_ID??process.env.OPEN_MACHINES_MACHINE_ID??process.env.MACHINE_ID??_??d4()}function pZ(_){let $=_.machineId===_.localMachineId||_.machineId===d4(),D=_.peer?.DNSName?.replace(/\.$/,"")??null,I=D??_.peer?.TailscaleIPs?.[0]??null,U=[];if($)U.push({kind:"local",target:"localhost",reachable:!0});if(I)U.push({kind:"tailscale",target:I,reachable:_.peer?.Online??null});let E=U.find((j)=>j.kind==="local")??U.find((j)=>j.kind==="tailscale")??null;return{machine_id:_.machineId,hostname:_.peer?.HostName??($?d4():_.machineId),local:$,platform:_.peer?.OS?dj(_.peer.OS):$?dj():null,os:_.peer?.OS??($?dG():null),user:$?cZ().username:null,workspace_path:null,manifest_declared:!1,heartbeat_status:"unknown",last_heartbeat_at:null,tailscale:{dns_name:D,ips:_.peer?.TailscaleIPs??[],online:_.peer?.Online??null,active:_.peer?.Active??null,last_seen:_.peer?.LastSeen??null},ssh:{address:null,route:E?.kind==="local"?"local":E?.kind==="tailscale"?"tailscale":"unknown",command_target:E?.target??null},route_hints:U,tags:[],metadata:{},source:"local"}}function eZ(_){if(!Array.isArray(_))return[];return _.map(($)=>{let D=d_($),I=m(D.kind)??"unknown";return{kind:I==="local"||I==="lan"||I==="tailscale"||I==="ssh"?I:"unknown",target:m(D.target)??"",reachable:nj(D.reachable)}}).filter(($)=>$.target.length>0)}function aZ(_,$){let D=m(_.machine_id)??m(_.hostname)??"unknown",I=d_(_.tailscale),U=d_(_.ssh),E=m(_.heartbeat_status),j=m(U.route);return{machine_id:D,hostname:m(_.hostname),local:D===$,platform:m(_.platform),os:m(_.os),user:m(_.user),workspace_path:m(_.workspace_path),manifest_declared:_.manifest_declared===!0,heartbeat_status:E==="online"||E==="offline"?E:"unknown",last_heartbeat_at:m(_.last_heartbeat_at),tailscale:{dns_name:m(I.dns_name),ips:m6(I.ips),online:nj(I.online),active:nj(I.active),last_seen:m(I.last_seen)},ssh:{address:m(U.address),route:j==="local"||j==="lan"||j==="tailscale"?j:"unknown",command_target:m(U.command_target)},route_hints:eZ(_.route_hints),tags:m6(_.tags),metadata:d_(_.metadata),source:"open-machines"}}function sZ(_,$){return`${$} machine${$===1?"":"s"} discovered via ${_}`}function L$(_){let $=_ instanceof Error?_.message:String(_);return $.includes("Cannot find module '@hasna/machines'")||$.includes("Cannot find module '@hasna/machines/consumer'")?"module_not_found":$}function J1(_){return _.adapterMode??"auto"}function mG(_){let $=_?.MACHINES_CONSUMER_CONTRACT?.schema_version;if(typeof $==="number")return $;let D=_?.MACHINES_CONSUMER_CONTRACT_VERSION;return typeof D==="number"?D:null}function mj(_){return typeof _.schema_version==="number"?_.schema_version:null}function P1(_){return typeof _==="number"&&_>nZ?_:null}function lj(_){return{package:dZ,entrypoint:mZ,mode:_.mode,implementation:_.implementation,contract_version:_.contractVersion??null,available:_.available,error:_.error??null}}function A_(_,$="adapter_disabled"){return lj({mode:_,implementation:"disabled",available:!1,error:$})}function ij(_,$){let D=P1(mG($));if(!D)return null;return lj({mode:_,implementation:"disabled",available:!1,error:`unsupported_contract_version:${D}`,contractVersion:D})}function tj(_){return lj({mode:_,implementation:"cli",available:!0})}function oj(_,$){return lj({mode:_,implementation:"sdk",available:!0,contractVersion:mG($)})}function pj(_){try{return JSON.parse(_)}catch{return null}}function m4(_){return`'${_.replace(/'/g,"'\\''")}'`}function ej(_){return["machines",..._].map(m4).join(" ")}function aj(_){return _==="local"||_==="localhost"||_===d4()||_===process.env.HASNA_MACHINE_ID||_===process.env.OPEN_MACHINES_MACHINE_ID||_===process.env.MACHINE_ID}function _H(_,$){let D=aj(_),I=D?$:`ssh ${m4(_)} ${m4($)}`,U=nG("bash",["-c",I],{encoding:"utf8",env:process.env});return{stdout:U.stdout||"",stderr:U.stderr||"",exitCode:U.status??1,source:D?"local":"ssh"}}async function lG(_,$,D){return await _($,D)}function c4(_,$){if($)return"ok";return _===!1?"warn":"fail"}function n4(_){return _.replace(/[^a-zA-Z0-9_.@/-]+/g,"-").replace(/^-+|-+$/g,"")}function $H(_){if(_==="@hasna/knowledge")return"knowledge";if(_==="@hasna/machines")return"machines";return _.split("/").pop()??_}function DH(_){return _.trim().split(/\r?\n/).find(Boolean)??""}function iG(_){return _.match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0]??null}function tG(_){let $={};for(let D of _.split(/\r?\n/)){let I=D.indexOf("=");if(I<=0)continue;$[D.slice(0,I)]=D.slice(I+1)}return $}function G6(_){return{id:_.id,kind:_.kind,status:_.status,target:_.target,expected:_.expected??null,actual:_.actual??null,detail:_.detail,source:_.source}}async function oG(_,$,D){let I=[`cmd=${m4($.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("; "),U=await lG(D,_,I),E=tG(U.stdout);return{path:E.path||null,version:E.version?DH(E.version):null,stderr:U.stderr,source:U.source??(aj(_)?"local":"ssh")}}function cG(_){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 UH(_,$,D){let I=[`path=${m4($.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" "$(${cG("name")})"; printf "version=%s\\n" "$(${cG("version")})"; fi`].join("; "),U=await lG(D,_,I),E=tG(U.stdout);return{exists:E.exists==="yes",packageJson:E.package_json==="yes",packageName:E.package_name||null,version:E.version||null,stderr:U.stderr,source:U.source??(aj(_)?"local":"ssh")}}async function IH(_,$,D){let I=await oG(_,$,D),U=Boolean(I.path),E=[G6({id:`command:${n4($.command)}:path`,kind:"command",status:c4($.required,U),target:$.command,expected:"available",actual:I.path??"missing",detail:U?`found at ${I.path}`:I.stderr||"command missing",source:I.source})];if($.expectedVersion){let j=iG(I.version??"");E.push(G6({id:`command:${n4($.command)}:version`,kind:"command",status:j===$.expectedVersion?"ok":c4($.required,!1),target:$.command,expected:$.expectedVersion,actual:j??I.version??"missing",detail:j?`version output: ${I.version}`:"version unavailable",source:I.source}))}return E}async function EH(_,$,D){let I=$.command??$H($.name),U=await oG(_,{command:I,expectedVersion:$.expectedVersion,required:$.required},D),E=Boolean(U.path),j=[G6({id:`package:${n4($.name)}:command`,kind:"package",status:c4($.required,E),target:$.name,expected:I,actual:U.path??"missing",detail:E?`${I} found at ${U.path}`:`${I} command missing`,source:U.source})];if($.expectedVersion){let N=iG(U.version??"");j.push(G6({id:`package:${n4($.name)}:version`,kind:"package",status:N===$.expectedVersion?"ok":c4($.required,!1),target:$.name,expected:$.expectedVersion,actual:N??U.version??"missing",detail:N?`version output: ${U.version}`:"version unavailable",source:U.source}))}return j}async function jH(_,$,D){let I=await UH(_,$,D),U=$.label??$.path,E=[G6({id:`workspace:${n4(U)}:path`,kind:"workspace",status:c4($.required,I.exists),target:U,expected:$.path,actual:I.exists?"exists":"missing",detail:I.exists?`workspace exists at ${$.path}`:I.stderr||`workspace missing at ${$.path}`,source:I.source})];if($.expectedPackageName)E.push(G6({id:`workspace:${n4(U)}:package-name`,kind:"workspace",status:I.packageName===$.expectedPackageName?"ok":c4($.required,!1),target:U,expected:$.expectedPackageName,actual:I.packageName??(I.packageJson?"missing-name":"missing-package-json"),detail:I.packageJson?"package.json inspected":"package.json missing",source:I.source}));if($.expectedVersion)E.push(G6({id:`workspace:${n4(U)}:version`,kind:"workspace",status:I.version===$.expectedVersion?"ok":c4($.required,!1),target:U,expected:$.expectedVersion,actual:I.version??(I.packageJson?"missing-version":"missing-package-json"),detail:I.packageJson?"package.json inspected":"package.json missing",source:I.source}));return E}function pG(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:s$,workspace_home:$.knowledge?.workspace_home??null},message:sZ(_.source,_.machines.length)}}async function sj(){try{return await import("@hasna/machines/consumer")}catch(_){if(L$(_)!=="module_not_found")throw _;return await import("@hasna/machines")}}function eG(_,$,D){let I=d_(_);if(P1(mj(I)))return null;let U=Array.isArray(I.machines)?I.machines:null,E=m(I.local_machine_id);if(!U||!E)return null;let j={ok:!0,source:"open-machines",generated_at:m(I.generated_at)??($.now??new Date).toISOString(),local_machine_id:E,local_hostname:m(I.local_hostname)??d4(),current_platform:m(I.current_platform)??dj(),machines:U.map((N)=>aZ(N,E)),warnings:m6(I.warnings),adapter:D};return pG(j,$)}function xj(_){return _==="local"||_==="lan"||_==="tailscale"||_==="ssh"||_==="unknown"?_:null}function aG(_){let $=d_(_),D=m($.observed_at),I=m($.source_authority);if(!D||!I)return null;return{observed_at:D,verified_at:m($.verified_at),expires_at:m($.expires_at),ttl_ms:lZ($.ttl_ms),source_authority:I,confidence:m($.confidence),cacheable:$.cacheable===!0,stale:$.stale===!0,reasons:m6($.reasons)}}function sG(_,$){let D=d_(_);if(P1(mj(D)))return null;let I=m(D.target)??m(D.command_target);if(D.ok!==!0||!I)return null;let U=typeof D.evidence==="object"&&D.evidence!==null?D.evidence:null,E=typeof U?.selected_hint==="object"&&U.selected_hint!==null?U.selected_hint:null;return{target:I,route:xj(D.route),targetKind:xj(E?.kind)??xj(D.source)??xj(D.route),confidence:m(D.confidence),source:"open-machines",adapter:$,evidence:U,cacheability:aG(D.cacheability),warnings:m6(D.warnings)}}function gP(_){let $=d_(_);return{path:m($.path),source:m($.source)??"unresolved"}}function NH(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=d_($),I=m(D.id),U=m(D.status),E=m(D.severity),j=m(D.message);if(!I||!U||!E||!j)return[];return[{id:I,status:U,severity:E,message:j,path:m(D.path),source:m(D.source)??"unknown",path_exists:nj(D.path_exists)}]})}function AH(_){if(!Array.isArray(_))return[];return _.flatMap(($)=>{let D=d_($),I=m(D.id),U=m(D.reason),E=m6(D.command),j=m(D.shell_command),N=m6(D.apply_command),O=m(D.apply_shell_command);if(!I||!U||!E.length||!j||!N.length||!O)return[];return[{id:I,reason:U,command:E,shell_command:j,apply_command:N,apply_shell_command:O}]})}function OH(_){if(!(_.projectRootSource==="inferred"||_.openFilesRootSource==="inferred"||_.trustStatus==="untrusted"||_.authStatus==="unknown"||_.warnings.some((U)=>U.includes("inferred")||U.includes("untrusted")||U.includes("unknown_auth")||U.includes("missing"))))return[];let D=["machines","workspace","repair","--machine",_.requestedMachineId,"--project",_.projectId,"--repo",_.repoName,"--open-files-repo",_.openFilesRepoName??"open-files","--json"],I=[...D,"--apply"];return[{id:"machines_workspace_repair",reason:"Workspace paths or trust metadata need confirmation before remote knowledge sync.",command:D,shell_command:D.map(m4).join(" "),apply_command:I,apply_shell_command:I.map(m4).join(" ")}]}function _R(_,$,D){let I=d_(_);if(P1(mj(I)))return null;let U=d_(I.paths),E=d_(I.project),j=d_(I.machine),N=gP(U.project_root),O=gP(U.workspace_root),S=gP(U.open_files_root);if(I.ok!==!0||!N.path)return null;let L=typeof I.evidence==="object"&&I.evidence!==null?I.evidence:null,W=m(I.requested_machine_id)??$.machineId,g=m(E.project_id)??$.projectId??"open-knowledge",z=m(E.repo_name)??$.repoName??$.projectId??"open-knowledge",G=m(j.trust_status)??"unknown",J=m(j.auth_status)??"unknown",P=m6(I.warnings),X=NH(I.diagnostics),R=AH(I.repair_hints);return{ok:!0,source:"open-machines",adapter:D,requested_machine_id:W,machine_id:m(I.machine_id),project_id:g,repo_name:z,project_root:N.path,project_root_source:N.source,workspace_root:O.path,workspace_root_source:O.source,open_files_root:S.path,open_files_root_source:S.source,trust_status:G,auth_status:J,current:j.current===!0,primary:j.primary===!0,diagnostics:X,repair_hints:R.length?R:OH({requestedMachineId:W,projectId:g,repoName:z,openFilesRepoName:$.openFilesRepoName,warnings:P,projectRootSource:N.source,openFilesRootSource:S.source,trustStatus:G,authStatus:J}),evidence:L,cacheability:aG(I.cacheability),warnings:P}}async function uj(_,$){let D=_.runner??L1;if(!await W1("machines",D))return null;let I=["topology","--json"];if(_.includeTailscale===!1)I.push("--no-tailscale");let U=await ED(D,ej(I));if(U.exitCode!==0)return null;return eG(pj(U.stdout),_,$)}async function P6(_,$){let D=[];if($.error)D.push(`open_machines_unavailable:${$.error}`);let I=_.runner??L1,U=_.includeTailscale===!1?{peers:new Map,selfKey:null}:await tZ(I,D),E=oZ(U.selfKey),N=[...new Set([E,...U.peers.keys()])].sort().map((O)=>pZ({machineId:O,localMachineId:E,peer:U.peers.get(O)}));return pG({ok:!0,source:"local",generated_at:(_.now??new Date).toISOString(),local_machine_id:E,local_hostname:d4(),current_platform:dj(),machines:N,warnings:D,adapter:$},_)}async function $R(_={}){let $=J1(_);if($==="disabled")return await P6(_,A_($));let D=tj($);try{if($!=="cli"){let U=await(_.loadOpenMachines??sj)(),E=ij($,U);if(E)return await P6(_,E);let j=oj($,U);if(U?.discoverMachineTopology){let N=U.discoverMachineTopology({includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),O=eG(N,_,j);if(O)return O;if($==="sdk")return await P6(_,A_($,"invalid_topology_shape"));return await uj(_,D)??await P6(_,A_($,"invalid_topology_shape"))}if($==="sdk")return await P6(_,A_($,"missing_discoverMachineTopology"));return await uj(_,D)??await P6(_,A_($,"missing_discoverMachineTopology"))}return await uj(_,D)??await P6(_,A_($,"machines_cli_unavailable"))}catch(I){if($==="sdk")return await P6(_,A_($,L$(I)));return await uj(_,D)??await P6(_,A_($,L$(I)))}}async function yj(_,$){let D=_.runner??L1;if(!await W1("machines",D))return null;let I=["route","--machine",_.machineId,"--json"];if(_.includeTailscale===!1)I.push("--no-tailscale");let U=await ED(D,ej(I));if(U.exitCode!==0)return null;return sG(pj(U.stdout),$)}function z6(_,$){return{target:_,route:null,targetKind:null,confidence:null,source:"raw",adapter:$,evidence:null,cacheability:null,warnings:[]}}async function XP(_){let $=J1(_);if($==="disabled")return z6(_.machineId,A_($));let D=tj($);try{if($!=="cli"){let U=await(_.loadOpenMachines??sj)(),E=ij($,U);if(E)return z6(_.machineId,E);let j=oj($,U);if(U?.resolveMachineRoute){let N=sG(U.resolveMachineRoute(_.machineId,{includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),j);if(N)return N;if($==="sdk")return z6(_.machineId,A_($,"invalid_route_shape"));return await yj(_,D)??z6(_.machineId,A_($,"invalid_route_shape"))}if($==="sdk")return z6(_.machineId,A_($,"missing_resolveMachineRoute"));return await yj(_,D)??z6(_.machineId,A_($,"missing_resolveMachineRoute"))}return await yj(_,D)??z6(_.machineId,A_($,"machines_cli_unavailable"))}catch(I){if($==="sdk")return{...z6(_.machineId,A_($,L$(I))),warnings:[L$(I)]};return await yj(_,D)??{...z6(_.machineId,A_($,L$(I))),warnings:[L$(I)]}}}async function hj(_,$){let D=_.runner??L1;if(!await W1("machines",D))return null;let I=_.projectId??"open-knowledge",U=_.repoName??"open-knowledge",E=["workspace","resolve","--machine",_.machineId,"--project",I,"--repo",U,"--open-files-repo",_.openFilesRepoName??"open-files","--json"];if(_.includeTailscale===!1)E.push("--no-tailscale");let j=await ED(D,ej(E));if(j.exitCode!==0)return null;return _R(pj(j.stdout),_,$)}function SH(_){let $=_.peerWorkspace?.trim();if(!$)return null;return{ok:!0,source:"argument",adapter:A_(J1(_),"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 g6(_,$,D){return{ok:!1,source:"raw",adapter:D,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 _N(_){let $=SH(_);if($)return $;let D=J1(_);if(D==="disabled")return g6(_,["adapter_disabled"],A_(D));let I=tj(D);try{if(D!=="cli"){let E=await(_.loadOpenMachines??sj)(),j=ij(D,E);if(j)return g6(_,[`unsupported_contract_version:${j.contract_version}`],j);let N=oj(D,E);if(E?.resolveMachineWorkspace){let O=_R(E.resolveMachineWorkspace({machineId:_.machineId,projectId:_.projectId??"open-knowledge",repoName:_.repoName??"open-knowledge",openFilesRepoName:_.openFilesRepoName??"open-files",includeTailscale:_.includeTailscale,runner:_.runner,now:_.now}),_,N);if(O)return O;if(D==="sdk")return g6(_,["invalid_workspace_shape"],A_(D,"invalid_workspace_shape"));return await hj(_,I)??g6(_,["invalid_workspace_shape"],A_(D,"invalid_workspace_shape"))}if(D==="sdk")return g6(_,["missing_resolveMachineWorkspace"],A_(D,"missing_resolveMachineWorkspace"));return await hj(_,I)??g6(_,["missing_resolveMachineWorkspace"],A_(D,"missing_resolveMachineWorkspace"))}return await hj(_,I)??g6(_,["machines_cli_unavailable"],A_(D,"machines_cli_unavailable"))}catch(U){if(D==="sdk")return g6(_,[L$(U)],A_(D,L$(U)));return await hj(_,I)??g6(_,[L$(U)],A_(D,L$(U)))}}function DR(_,$){return{..._,knowledge:{scope:$.knowledge?.scope??"global",app_path:s$,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 UR(_,$,D){let I=d_(_);if(P1(mj(I)))return null;let U=Array.isArray(I.checks)?I.checks:null,E=m(I.machine_id)??m(I.machineId);if(!U||!E)return null;let j=U.map((O)=>{let S=d_(O),L=m(S.status),W=m(S.kind),g=m(S.source);return G6({id:m(S.id)??"unknown",kind:W==="command"||W==="package"||W==="workspace"?W:"command",status:L==="ok"||L==="warn"||L==="fail"?L:"fail",target:m(S.target)??"unknown",expected:m(S.expected),actual:m(S.actual),detail:m(S.detail)??"",source:g==="local"||g==="ssh"||g==="open-machines"?g:"open-machines"})}),N={ok:j.filter((O)=>O.status==="ok").length,warn:j.filter((O)=>O.status==="warn").length,fail:j.filter((O)=>O.status==="fail").length};return DR({ok:N.fail===0,source:"open-machines",machine_id:E,generated_at:m(I.generated_at)??($.now??new Date).toISOString(),checks:j,summary:N,adapter:D},$)}function LH(_){if(!_.runner)return L1;return async($)=>{let D=await _.runner?.("local",$);return{stdout:D?.stdout??"",stderr:D?.stderr??"",exitCode:D?.exitCode??1}}}function WH(_){return[_.name,_.command,_.expectedVersion].filter(($)=>Boolean($)).join(":")}function JH(_){let $=[_.expectedPackageName,_.expectedVersion].filter((I)=>Boolean(I)).join(":"),D=$?`${_.path}:${$}`:_.path;return _.label?`${_.label}=${D}`:D}async function cj(_,$){let D=LH(_);if(!await W1("machines",D))return null;let I=["compatibility","--json","--machine",_.machineId??"local"];for(let E of _.commands??[])I.push("--command",E.expectedVersion?`${E.command}:${E.expectedVersion}`:E.command);for(let E of _.packages??[])I.push("--package",WH(E));for(let E of _.workspaces??[])I.push("--workspace",JH(E));let U=await ED(D,ej(I));if(U.exitCode!==0)return null;return UR(pj(U.stdout),_,$)}async function X6(_,$){let D=_.machineId??d4(),I=_.runner??_H,U=_.commands??[{command:"bun",required:!0},{command:"knowledge",required:!0}],E=_.packages??[{name:"@hasna/knowledge",command:"knowledge",required:!0}],j=_.workspaces??[],N=[];for(let S of U)N.push(...await IH(D,S,I));for(let S of E)N.push(...await EH(D,S,I));for(let S of j)N.push(...await jH(D,S,I));if($.error)N.push(G6({id:"adapter:@hasna/machines",kind:"package",status:"warn",target:"@hasna/machines",expected:"optional",actual:$.error,detail:"Using knowledge local/ssh compatibility fallback",source:aj(D)?"local":"ssh"}));let O={ok:N.filter((S)=>S.status==="ok").length,warn:N.filter((S)=>S.status==="warn").length,fail:N.filter((S)=>S.status==="fail").length};return DR({ok:O.fail===0,source:"local",machine_id:D,generated_at:(_.now??new Date).toISOString(),checks:N,summary:O,adapter:$},_)}async function IR(_={}){let $=J1(_);if($==="disabled")return await X6(_,A_($));let D=tj($);try{if($!=="cli"){let U=await(_.loadOpenMachines??sj)(),E=ij($,U);if(E)return await X6(_,E);let j=oj($,U);if(U?.checkMachineCompatibility){let N=U.checkMachineCompatibility({machineId:_.machineId,commands:_.commands,packages:_.packages,workspaces:_.workspaces,runner:_.runner,now:_.now}),O=UR(N,_,j);if(O)return O;if($==="sdk")return await X6(_,A_($,"invalid_compatibility_shape"));return await cj(_,D)??await X6(_,A_($,"invalid_compatibility_shape"))}if($==="sdk")return await X6(_,A_($,"missing_checkMachineCompatibility"));return await cj(_,D)??await X6(_,A_($,"missing_checkMachineCompatibility"))}return await cj(_,D)??await X6(_,A_($,"machines_cli_unavailable"))}catch(I){if($==="sdk")return await X6(_,A_($,L$(I)));return await cj(_,D)??await X6(_,A_($,L$(I)))}}import{createHash as ER}from"crypto";function RP(_,$,D=24){return`${_}_${ER("sha256").update($).digest("hex").slice(0,D)}`}function jD(_){return _.normalize("NFKC").trim().replace(/\s+/g," ")}function PH(_){return jD(_).toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")}function H$(_,$){try{return JSON.parse(_)}catch{return $}}function l6(_){return{..._,record_kind:_.record_kind,source_kind:_.source_kind,status:_.status,source_refs:H$(_.source_refs_json,[]),evidence_refs:H$(_.evidence_refs_json,[]),requires_approval:_.requires_approval===1,checks:H$(_.checks_json,jR()),metadata:H$(_.metadata_json,{})}}function YP(_){return{..._,record_kind:_.record_kind,source_refs:H$(_.source_refs_json,[]),evidence_refs:H$(_.evidence_refs_json,[]),metadata:H$(_.metadata_json,{})}}function jR(){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 zH(_){let $=typeof _==="string"?{ref:_}:_;return{ref:jD($.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 NR(_){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 $N(_){return["deleted","stale","invalidated","reindex_required","expired","superseded"].includes((_??"").toLowerCase())}function GP(_){if(!_)return null;let $=H$(_,{});if($.stale===!0)return"stale";return typeof $.status==="string"?$.status:null}function gH(_){if(_.citation_id)return _.citation_id;return _.ref.match(/^(?:cite|citation):(.+)$/)?.[1]??null}function XH(_){if(_.chunk_id)return _.chunk_id;return _.ref.match(/^chunk:(.+)$/)?.[1]??null}function GH(_,$,D){let I=$N($.status)||Boolean($.expires_at&&$.expires_at<=D);if(!$.ref||!NR($.ref))return{ref:$.ref,valid:!1,resolved_by:"none",stale:I,reason:"invalid_reference"};let U=gH($),E=_.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 @@ -971,46 +971,46 @@ ${JSON.stringify(_.evidence,null,2)}`].join(` 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(U,$.ref);if(E){let O=Boolean($.hash&&E.revision_hash&&$.hash!==E.revision_hash),S=Boolean($.revision&&E.revision&&$.revision!==E.revision),L=Boolean(E.revision_created_at&&E.latest_revision_at&&E.revision_created_at!jR(L)),j.citations.entries=I.map((L)=>GZ(_,L,D)),j.citations.provided=I.length,j.citations.valid=j.citations.entries.filter((L)=>L.valid).length,j.citations.invalid=j.citations.entries.length-j.citations.valid,j.stale_refs=j.citations.entries.filter((L)=>L.stale).map((L)=>L.ref),j.duplicate_record_ids=_.query(`SELECT id FROM durable_knowledge_records + WHERE ch.id = ?`).get(j);if(!S)return{ref:$.ref,valid:!1,resolved_by:"none",stale:I,reason:"chunk_not_found"};let L=Boolean($.hash&&S.hash&&$.hash!==S.hash||$.revision&&S.revision&&$.revision!==S.revision),W=I||$N(GP(S.metadata_json))||L;return{ref:$.ref,valid:!0,resolved_by:"chunk",stale:W,reason:L?"source_version_mismatch":W?"stale_chunk":null}}let N=_.query("SELECT metadata_json FROM sources WHERE uri = ? LIMIT 1").get($.ref);if(N){let S=I||$N(GP(N.metadata_json));return{ref:$.ref,valid:!0,resolved_by:"source",stale:S,reason:S?"stale_source":null}}let O=$.ref.match(/^knowledge:\/\/project\/runs\/([^/?#]+)/);if(O){if(!_.query("SELECT id FROM runs WHERE id = ?").get(decodeURIComponent(O[1])))return{ref:$.ref,valid:!1,resolved_by:"none",stale:I,reason:"run_not_found"};return{ref:$.ref,valid:!0,resolved_by:"run",stale:I,reason:I?"expired_evidence":null}}return{ref:$.ref,valid:!0,resolved_by:"external_uri",stale:I,reason:I?"expired_evidence":null}}function i6(_,$){return _.query("SELECT * FROM knowledge_promotion_candidates WHERE id = ?").get($)??null}function QP(_,$,D){let I=H$($.evidence_refs_json,[]),U=H$($.source_refs_json,[]),E=H$($.metadata_json,{}),j=jR();j.invalid_source_refs=U.filter((W)=>!NR(W)),j.citations.entries=I.map((W)=>GH(_,W,D)),j.citations.provided=I.length,j.citations.valid=j.citations.entries.filter((W)=>W.valid).length,j.citations.invalid=j.citations.entries.length-j.citations.valid,j.stale_refs=j.citations.entries.filter((W)=>W.stale).map((W)=>W.ref),j.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((L)=>L.id),j.duplicate_candidate_ids=_.query(`SELECT id FROM knowledge_promotion_candidates + ORDER BY created_at`).all($.record_kind,$.content_hash).map((W)=>W.id),j.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((L)=>L.id),j.conflicting_record_ids=_.query(`SELECT id FROM durable_knowledge_records + ORDER BY created_at`).all($.id,$.record_kind,$.content_hash).map((W)=>W.id),j.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((L)=>L.id),j.conflicting_candidate_ids=_.query(`SELECT id FROM knowledge_promotion_candidates + ORDER BY created_at`).all($.record_kind,$.canonical_key,$.content_hash).map((W)=>W.id),j.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((L)=>L.id);let N=j.duplicate_record_ids[0]??j.duplicate_candidate_ids[0]??null,A=U.length===0||I.length===0||j.invalid_source_refs.length>0||j.citations.invalid>0;if($.record_kind==="decision"||$.record_kind==="claim")j.approval_reasons.push(`${$.record_kind}_requires_review`);if(E.requested_approval===!0)j.approval_reasons.push("explicit_approval_request");if(j.stale_refs.length>0)j.approval_reasons.push("stale_evidence");if(j.conflicting_record_ids.length>0||j.conflicting_candidate_ids.length>0)j.approval_reasons.push("conflicting_knowledge");let O=j.approval_reasons.length>0,S=N?"duplicate":A?"blocked":O?"needs_approval":"ready";return _.run(`UPDATE knowledge_promotion_candidates + ORDER BY created_at`).all($.id,$.record_kind,$.canonical_key,$.content_hash).map((W)=>W.id);let N=j.duplicate_record_ids[0]??j.duplicate_candidate_ids[0]??null,O=U.length===0||I.length===0||j.invalid_source_refs.length>0||j.citations.invalid>0;if($.record_kind==="decision"||$.record_kind==="claim")j.approval_reasons.push(`${$.record_kind}_requires_review`);if(E.requested_approval===!0)j.approval_reasons.push("explicit_approval_request");if(j.stale_refs.length>0)j.approval_reasons.push("stale_evidence");if(j.conflicting_record_ids.length>0||j.conflicting_candidate_ids.length>0)j.approval_reasons.push("conflicting_knowledge");let S=j.approval_reasons.length>0,L=N?"duplicate":O?"blocked":S?"needs_approval":"ready";return _.run(`UPDATE knowledge_promotion_candidates SET status = ?, requires_approval = ?, checks_json = ?, duplicate_of = ?, updated_at = ?, reviewed_at = ? - WHERE id = ?`,[S,O?1:0,JSON.stringify(j),N,D,D,$.id]),l6(i6(_,$.id))}function NR(_,$){let D=["lesson","decision","claim"],I=["memento","session","report"];if(!D.includes($.kind))throw Error("Promotion kind must be lesson, decision, or claim.");if(!I.includes($.sourceKind))throw Error("Promotion source kind must be memento, session, or report.");let U=u_(ID($.title)),E=u_(ID($.content));if(!U.text)throw Error("Promotion title is required.");if(!E.text)throw Error("Promotion content is required.");let j=Array.from(new Set($.sourceRefs.map(ID).filter(Boolean))).sort(),N=$.evidenceRefs.map(PZ).filter((J)=>J.ref.length>0).sort((J,W)=>J.ref.localeCompare(W.ref)),A=WZ($.canonicalKey??U.text);if(!A)throw Error("Promotion canonical key is empty after normalization.");let O=`sha256:${IR("sha256").update(`${$.kind}\x00${ID(E.text).toLowerCase()}`).digest("hex")}`,S=RW("promote",[$.sourceKind,$.kind,A,O,...j].join("\x00")),L=RW("promotion",S),P=($.now??new Date).toISOString(),z={...$.metadata??{},requested_approval:$.requiresApproval===!0,confidence:$.confidence??null,valid_from:$.validFrom??P,valid_to:$.validTo??null,redactions:U.findings.length+E.findings.length};c(_);let G=w(_);try{let J=G.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(S);if(J)return{created:!1,candidate:l6(J)};G.run(`INSERT INTO knowledge_promotion_candidates ( + WHERE id = ?`,[L,S?1:0,JSON.stringify(j),N,D,D,$.id]),l6(i6(_,$.id))}function AR(_,$){let D=["lesson","decision","claim"],I=["memento","session","report"];if(!D.includes($.kind))throw Error("Promotion kind must be lesson, decision, or claim.");if(!I.includes($.sourceKind))throw Error("Promotion source kind must be memento, session, or report.");let U=u_(jD($.title)),E=u_(jD($.content));if(!U.text)throw Error("Promotion title is required.");if(!E.text)throw Error("Promotion content is required.");let j=Array.from(new Set($.sourceRefs.map(jD).filter(Boolean))).sort(),N=$.evidenceRefs.map(zH).filter((J)=>J.ref.length>0).sort((J,P)=>J.ref.localeCompare(P.ref)),O=PH($.canonicalKey??U.text);if(!O)throw Error("Promotion canonical key is empty after normalization.");let S=`sha256:${ER("sha256").update(`${$.kind}\x00${jD(E.text).toLowerCase()}`).digest("hex")}`,L=RP("promote",[$.sourceKind,$.kind,O,S,...j].join("\x00")),W=RP("promotion",L),g=($.now??new Date).toISOString(),z={...$.metadata??{},requested_approval:$.requiresApproval===!0,confidence:$.confidence??null,valid_from:$.validFrom??g,valid_to:$.validTo??null,redactions:U.findings.length+E.findings.length};c(_);let G=w(_);try{let J=G.query("SELECT * FROM knowledge_promotion_candidates WHERE idempotency_key = ?").get(L);if(J)return{created:!1,candidate:l6(J)};G.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, '{}', ?, ?, ?, ?)`,[L,$.kind,U.text,E.text,A,O,$.sourceKind,JSON.stringify(j),JSON.stringify(N),S,JSON.stringify(z),P,P]);let W=[...U.findings,...E.findings];if(W.length>0)R0(G,{source_uri:j[0]??`knowledge://promotion/${L}`,findings:W,metadata:{promotion_candidate_id:L},created_at:P});return R_(G,{event_type:"knowledge_promotion",action:"enqueue_promotion",target_uri:`knowledge://promotion/${L}`,decision:"info",metadata:{record_kind:$.kind,source_kind:$.sourceKind,source_refs:j},created_at:P}),{created:!0,candidate:QW(G,i6(G,L),P)}}finally{G.close()}}function gR(_,$){c(_);let D=w(_);try{let I=i6(D,$);return I?l6(I):null}finally{D.close()}}function AR(_,$={}){c(_);let D=Math.max(1,Math.min($.limit??50,200)),I=[],U=[];if($.status==="inbox"||!$.status)I.push("status IN ('ready', 'needs_approval', 'blocked')");else I.push("status = ?"),U.push($.status);if($.kind)I.push("record_kind = ?"),U.push($.kind);let E=w(_);try{return E.query(`SELECT * FROM knowledge_promotion_candidates + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, '{}', ?, ?, ?, ?)`,[W,$.kind,U.text,E.text,O,S,$.sourceKind,JSON.stringify(j),JSON.stringify(N),L,JSON.stringify(z),g,g]);let P=[...U.findings,...E.findings];if(P.length>0)Q0(G,{source_uri:j[0]??`knowledge://promotion/${W}`,findings:P,metadata:{promotion_candidate_id:W},created_at:g});return R_(G,{event_type:"knowledge_promotion",action:"enqueue_promotion",target_uri:`knowledge://promotion/${W}`,decision:"info",metadata:{record_kind:$.kind,source_kind:$.sourceKind,source_refs:j},created_at:g}),{created:!0,candidate:QP(G,i6(G,W),g)}}finally{G.close()}}function OR(_,$){c(_);let D=w(_);try{let I=i6(D,$);return I?l6(I):null}finally{D.close()}}function SR(_,$={}){c(_);let D=Math.max(1,Math.min($.limit??50,200)),I=[],U=[];if($.status==="inbox"||!$.status)I.push("status IN ('ready', 'needs_approval', 'blocked')");else I.push("status = ?"),U.push($.status);if($.kind)I.push("record_kind = ?"),U.push($.kind);let E=w(_);try{return E.query(`SELECT * FROM knowledge_promotion_candidates WHERE ${I.join(" AND ")} ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(...U,D).map(l6)}finally{E.close()}}function OR(_,$,D=new Date){c(_);let I=w(_);try{let U=i6(I,$);if(!U)throw Error(`Promotion candidate not found: ${$}`);if(U.status==="promoted"||U.status==="rejected")return l6(U);return QW(I,U,D.toISOString())}finally{I.close()}}function SR(_,$,D={}){c(_);let I=w(_),U=(D.now??new Date).toISOString();try{let E=i6(I,$);if(!E)throw Error(`Promotion candidate not found: ${$}`);if(E.status==="promoted"&&E.promoted_record_id){let z=I.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(E.promoted_record_id);return{ok:!0,promoted:!1,requires_approval:E.requires_approval===1,candidate:l6(E),record:z?YW(z):null,approval_id:null,reason:"already_promoted"}}if(E.status==="rejected")throw Error(`Promotion candidate ${$} was rejected.`);let j=QW(I,E,U);if(j.status==="duplicate")return{ok:!0,promoted:!1,requires_approval:!1,candidate:j,record:null,approval_id:null,reason:"duplicate"};if(j.status==="blocked")return{ok:!1,promoted:!1,requires_approval:!1,candidate:j,record:null,approval_id:null,reason:"citation_check_failed"};if(j.requires_approval&&!D.approveWrite)return{ok:!1,promoted:!1,requires_approval:!0,candidate:j,record:null,approval_id:null,reason:"approval_required"};if(j.requires_approval&&!D.approvedBy?.trim())throw Error("Promotion approval requires --approved-by .");let N=j.requires_approval?D.approvedBy.trim():null,A=null;if(j.requires_approval)A=s1(I,{action:"promote_durable_knowledge",target_uri:`knowledge://promotion/${j.id}`,reason:j.checks.approval_reasons.join(", "),approved_by:N,metadata:{promotion_candidate_id:j.id,checks:j.checks},created_at:U}).id;let O=RW("durable",j.id),S={...j.metadata,promotion_candidate_id:j.id,source_kind:j.source_kind,checks:j.checks,approval_id:A,provenance:N$({generated_from:`knowledge://promotion/${j.id}`,artifact_key:`durable/${j.record_kind}/${j.canonical_key}`,source_refs:j.source_refs,citation_required:!0})};I.run(`INSERT INTO durable_knowledge_records ( + LIMIT ?`).all(...U,D).map(l6)}finally{E.close()}}function LR(_,$,D=new Date){c(_);let I=w(_);try{let U=i6(I,$);if(!U)throw Error(`Promotion candidate not found: ${$}`);if(U.status==="promoted"||U.status==="rejected")return l6(U);return QP(I,U,D.toISOString())}finally{I.close()}}function WR(_,$,D={}){c(_);let I=w(_),U=(D.now??new Date).toISOString();try{let E=i6(I,$);if(!E)throw Error(`Promotion candidate not found: ${$}`);if(E.status==="promoted"&&E.promoted_record_id){let z=I.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(E.promoted_record_id);return{ok:!0,promoted:!1,requires_approval:E.requires_approval===1,candidate:l6(E),record:z?YP(z):null,approval_id:null,reason:"already_promoted"}}if(E.status==="rejected")throw Error(`Promotion candidate ${$} was rejected.`);let j=QP(I,E,U);if(j.status==="duplicate")return{ok:!0,promoted:!1,requires_approval:!1,candidate:j,record:null,approval_id:null,reason:"duplicate"};if(j.status==="blocked")return{ok:!1,promoted:!1,requires_approval:!1,candidate:j,record:null,approval_id:null,reason:"citation_check_failed"};if(j.requires_approval&&!D.approveWrite)return{ok:!1,promoted:!1,requires_approval:!0,candidate:j,record:null,approval_id:null,reason:"approval_required"};if(j.requires_approval&&!D.approvedBy?.trim())throw Error("Promotion approval requires --approved-by .");let N=j.requires_approval?D.approvedBy.trim():null,O=null;if(j.requires_approval)O=_I(I,{action:"promote_durable_knowledge",target_uri:`knowledge://promotion/${j.id}`,reason:j.checks.approval_reasons.join(", "),approved_by:N,metadata:{promotion_candidate_id:j.id,checks:j.checks},created_at:U}).id;let S=RP("durable",j.id),L={...j.metadata,promotion_candidate_id:j.id,source_kind:j.source_kind,checks:j.checks,approval_id:O,provenance:N$({generated_from:`knowledge://promotion/${j.id}`,artifact_key:`durable/${j.record_kind}/${j.canonical_key}`,source_refs:j.source_refs,citation_required:!0})};I.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[O,j.record_kind,j.title,j.content,j.canonical_key,j.content_hash,j.checks.conflicting_record_ids.length>0?"conflicted":"active",JSON.stringify(j.source_refs),JSON.stringify(j.evidence_refs),typeof j.metadata.confidence==="number"?j.metadata.confidence:null,typeof j.metadata.valid_from==="string"?j.metadata.valid_from:U,typeof j.metadata.valid_to==="string"?j.metadata.valid_to:null,j.id,N,JSON.stringify(S),U,U]),I.run(`UPDATE knowledge_promotion_candidates + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[S,j.record_kind,j.title,j.content,j.canonical_key,j.content_hash,j.checks.conflicting_record_ids.length>0?"conflicted":"active",JSON.stringify(j.source_refs),JSON.stringify(j.evidence_refs),typeof j.metadata.confidence==="number"?j.metadata.confidence:null,typeof j.metadata.valid_from==="string"?j.metadata.valid_from:U,typeof j.metadata.valid_to==="string"?j.metadata.valid_to:null,j.id,N,JSON.stringify(L),U,U]),I.run(`UPDATE knowledge_promotion_candidates SET status = 'promoted', approved_by = ?, promoted_record_id = ?, promoted_at = ?, updated_at = ? - WHERE id = ?`,[N,O,U,U,j.id]),R_(I,{event_type:"knowledge_promotion",action:"promote_durable_knowledge",target_uri:`knowledge://durable/${O}`,decision:"allow",metadata:{promotion_candidate_id:j.id,approval_id:A,source_refs:j.source_refs},created_at:U});let L=l6(i6(I,j.id)),P=I.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(O);return{ok:!0,promoted:!0,requires_approval:j.requires_approval,candidate:L,record:YW(P),approval_id:A,reason:null}}finally{I.close()}}function LR(_,$,D={}){c(_);let I=w(_),U=(D.now??new Date).toISOString();try{let E=i6(I,$);if(!E)throw Error(`Promotion candidate not found: ${$}`);if(E.status==="promoted")throw Error(`Promotion candidate ${$} is already promoted.`);return I.run(`UPDATE knowledge_promotion_candidates + WHERE id = ?`,[N,S,U,U,j.id]),R_(I,{event_type:"knowledge_promotion",action:"promote_durable_knowledge",target_uri:`knowledge://durable/${S}`,decision:"allow",metadata:{promotion_candidate_id:j.id,approval_id:O,source_refs:j.source_refs},created_at:U});let W=l6(i6(I,j.id)),g=I.query("SELECT * FROM durable_knowledge_records WHERE id = ?").get(S);return{ok:!0,promoted:!0,requires_approval:j.requires_approval,candidate:W,record:YP(g),approval_id:O,reason:null}}finally{I.close()}}function JR(_,$,D={}){c(_);let I=w(_),U=(D.now??new Date).toISOString();try{let E=i6(I,$);if(!E)throw Error(`Promotion candidate not found: ${$}`);if(E.status==="promoted")throw Error(`Promotion candidate ${$} is already promoted.`);return I.run(`UPDATE knowledge_promotion_candidates SET status = 'rejected', approved_by = ?, updated_at = ?, reviewed_at = ? - WHERE id = ?`,[D.rejectedBy?.trim()||null,U,U,$]),R_(I,{event_type:"knowledge_promotion",action:"reject_promotion",target_uri:`knowledge://promotion/${$}`,decision:"deny",metadata:{rejected_by:D.rejectedBy??null},created_at:U}),l6(i6(I,$))}finally{I.close()}}function JR(_,$={}){c(_);let D=[],I=[];if($.kind)D.push("record_kind = ?"),I.push($.kind);if($.status)D.push("status = ?"),I.push($.status);let U=Math.max(1,Math.min($.limit??50,200)),E=w(_);try{return E.query(`SELECT * FROM durable_knowledge_records + WHERE id = ?`,[D.rejectedBy?.trim()||null,U,U,$]),R_(I,{event_type:"knowledge_promotion",action:"reject_promotion",target_uri:`knowledge://promotion/${$}`,decision:"deny",metadata:{rejected_by:D.rejectedBy??null},created_at:U}),l6(i6(I,$))}finally{I.close()}}function PR(_,$={}){c(_);let D=[],I=[];if($.kind)D.push("record_kind = ?"),I.push($.kind);if($.status)D.push("status = ?"),I.push($.status);let U=Math.max(1,Math.min($.limit??50,200)),E=w(_);try{return E.query(`SELECT * FROM durable_knowledge_records ${D.length?`WHERE ${D.join(" AND ")}`:""} ORDER BY updated_at DESC, created_at DESC - LIMIT ?`).all(...I,U).map(YW)}finally{E.close()}}import{createHash as RZ,randomUUID as WR}from"crypto";function YZ(_,$){return`${_}_${RZ("sha256").update($).digest("hex").slice(0,20)}`}function QZ(_){let $=w(_);try{let D=$.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(D.map((I)=>[I.status,I.n]))}finally{$.close()}}function PR(_,$){let D=S4($.modelRef,$.config),I=f_(D),U=w(_);try{return U.query(`SELECT c.id AS chunk_id, c.source_revision_id, s.uri AS source_uri + LIMIT ?`).all(...I,U).map(YP)}finally{E.close()}}import{createHash as RH,randomUUID as zR}from"crypto";function YH(_,$){return`${_}_${RH("sha256").update($).digest("hex").slice(0,20)}`}function QH(_){let $=w(_);try{let D=$.query("SELECT status, COUNT(*) AS n FROM reindex_queue GROUP BY status ORDER BY status").all();return Object.fromEntries(D.map((I)=>[I.status,I.n]))}finally{$.close()}}function gR(_,$){let D=W4($.modelRef,$.config),I=f_(D),U=w(_);try{return U.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(I.provider,I.model)}finally{U.close()}}function zR(_){c(_.dbPath);let $=w(_.dbPath);try{let D=$.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0,I=$.query("SELECT COUNT(*) AS n FROM chunks").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,E=PR(_.dbPath,_).length,j=$.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:D,chunks:I,vector_entries:U,missing_embeddings:E,queued:QZ(_.dbPath),stale_revisions:j}}finally{$.close()}}function KW(_){c(_.dbPath);let $=(_.now??new Date).toISOString(),D=_.reason??"missing_embedding",I=PR(_.dbPath,_),U=w(_.dbPath),E=0,j=0;try{U.transaction(()=>{for(let A of I){let O=YZ("rq",`embedding\x00${A.chunk_id}\x00${D}`);if(U.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding",A.chunk_id,D)){j+=1;continue}U.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[O,"embedding",A.chunk_id,A.source_uri,D,"pending",JSON.stringify({source_revision_id:A.source_revision_id}),$,$]),E+=1}})()}finally{U.close()}return{enqueued:E,already_queued:j,reason:D}}function KZ(_){let $=w(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,I=$.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:D,vectorEntries:I}}finally{$.close()}}function TZ(_,$,D){let I=S4($.modelRef,$.config),U=f_(I),E=w(_);try{return E.run(`UPDATE reindex_queue + ORDER BY c.created_at ASC, c.ordinal ASC`).all(I.provider,I.model)}finally{U.close()}}function XR(_){c(_.dbPath);let $=w(_.dbPath);try{let D=$.query("SELECT MAX(version) AS version FROM schema_versions").get()?.version??0,I=$.query("SELECT COUNT(*) AS n FROM chunks").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM vector_index_entries").get()?.n??0,E=gR(_.dbPath,_).length,j=$.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:D,chunks:I,vector_entries:U,missing_embeddings:E,queued:QH(_.dbPath),stale_revisions:j}}finally{$.close()}}function KP(_){c(_.dbPath);let $=(_.now??new Date).toISOString(),D=_.reason??"missing_embedding",I=gR(_.dbPath,_),U=w(_.dbPath),E=0,j=0;try{U.transaction(()=>{for(let O of I){let S=YH("rq",`embedding\x00${O.chunk_id}\x00${D}`);if(U.query("SELECT id FROM reindex_queue WHERE kind = ? AND target_id = ? AND reason = ?").get("embedding",O.chunk_id,D)){j+=1;continue}U.run(`INSERT INTO reindex_queue (id, kind, target_id, source_uri, reason, status, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[S,"embedding",O.chunk_id,O.source_uri,D,"pending",JSON.stringify({source_revision_id:O.source_revision_id}),$,$]),E+=1}})()}finally{U.close()}return{enqueued:E,already_queued:j,reason:D}}function KH(_){let $=w(_);try{let D=$.query("SELECT COUNT(*) AS n FROM chunk_embeddings").get()?.n??0,I=$.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:D,vectorEntries:I}}finally{$.close()}}function TH(_,$,D){let I=W4($.modelRef,$.config),U=f_(I),E=w(_);try{return E.run(`UPDATE reindex_queue SET status = ?, updated_at = ? WHERE kind = ? AND status = ? @@ -1019,13 +1019,13 @@ ${JSON.stringify(_.evidence,null,2)}`].join(` WHERE v.chunk_id = reindex_queue.target_id AND v.provider = ? AND v.model = ? - )`,["completed",D,"embedding","pending",U.provider,U.model]).changes}finally{E.close()}}async function XR(_){c(_.dbPath);let $=(_.now??new Date).toISOString(),D=`run_${WR()}`,I=_.full?KZ(_.dbPath):{embeddings:0,vectorEntries:0},U=KW({..._,reason:_.full?"full_embedding_rebuild":"missing_embedding"}),E=w(_.dbPath);try{E.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,"embedding-refresh",_.full?"full":"incremental","running","local",S4(_.modelRef,_.config),JSON.stringify({full:_.full===!0,queued:U}),$,$])}finally{E.close()}let j=await NI({dbPath:_.dbPath,config:_.config,env:_.env,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake,limit:_.limit,now:_.now}),N=TZ(_.dbPath,_,$),A=w(_.dbPath);try{A.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({full:_.full===!0,queued:U,indexed:j,completed_queue_items:N}),$,D]),A.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${WR()}`,D,"info","embedding_refresh_completed",JSON.stringify({queued:U,indexed:j,completed_queue_items:N}),$])}finally{A.close()}return{run_id:D,full:_.full===!0,deleted_embeddings:I.embeddings,deleted_vector_entries:I.vectorEntries,queued:U,indexed:j,completed_queue_items:N}}import{createHash as YR}from"crypto";import{existsSync as QR,lstatSync as FZ,readdirSync as VZ,readFileSync as BZ,statSync as MZ}from"fs";import{basename as ED,extname as bZ,join as ZZ,relative as HZ,resolve as BW,sep as kZ}from"path";import{pathToFileURL as GR}from"url";var qZ=100,CZ=25,vZ=262144,wZ=5,rZ=new Set([".md",".mdx",".txt",".json",".jsonc",".toml",".yaml",".yml"]),TW=new Set(["CODEWITH.md","AGENTS.md","CLAUDE.md","RULES.md","INSTRUCTIONS.md"]),fZ=new Set([".git","node_modules","dist","build",".codewith-worktrees",".connect",".secrets",".tmp","tmp","auth_profiles","profiles","preserved","backup","backups","cache","logs","runs"]),xZ=/(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i,$N=/(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i;function FW(_){return`sha256:${YR("sha256").update(_).digest("hex")}`}function uZ(_){return`sha256:${YR("sha256").update(_).digest("hex")}`}function P1(_){return _.split(kZ).join("/")}function VW(_,$){let D=HZ(_,$);return D?P1(D):ED($)}function t6(_){return rZ.has(bZ(_).toLowerCase())}function RR(_){return P1(_).split("/").some(($)=>xZ.test($))}function KR(_,$=220){let D=_.normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function TR(_){if(!_)return 0;return _.split(/\r\n|\n|\r/).length}function FR(_){return{source_ref:_.sourceRef,source_path:_.sourcePath,line_start:_.lineCount>0?1:0,line_end:_.lineCount,content_hash:_.contentHash}}function yZ(){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:(_)=>TW.has(_)}},{base:".codewith",spec:{family:"codewith",owner:"codewith",scope:"global",precedence:{rank:20,label:"codewith"},tags:["global-rules","codewith","agent-instructions"],include:(_)=>{let $=P1(_),D=ED($);if(TW.has(D)||$==="config.toml")return!0;if($.endsWith("/SKILL.md"))return!0;if(/^(rules|instructions|prompts|plans)\//.test($)&&t6($))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 $=P1(_);return $==="CLAUDE.md"||/^rules\//.test($)&&t6($)}}},{base:".codex",spec:{family:"codex",owner:"codex",scope:"global",precedence:{rank:40,label:"codex"},tags:["global-rules","codex","agent-instructions"],include:(_)=>{let $=P1(_),D=ED($);if(TW.has(D)||D==="config.toml")return!0;return/^(rules|instructions|prompts)\//.test($)&&t6($)}}},{base:".opencode",spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode"},tags:["global-rules","opencode","agent-instructions"],include:(_)=>$N.test(_)&&t6(_)}},{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:(_)=>$N.test(_)&&t6(_)}},{base:".hasna/plans",spec:{family:"plan",owner:"hasna",scope:"global",precedence:{rank:65,label:"selected-plans"},tags:["global-rules","plan"],include:(_)=>$N.test(_)&&t6(_)}},{base:"docs",spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:70,label:"rule-docs"},tags:["global-rules","rule-doc"],include:(_)=>$N.test(_)&&t6(_)}}]}function hZ(_,$){let D=new Map;for(let I of yZ()){let U=BW(_,I.base);if(!QR(U))continue;if(MZ(U).isFile()){let j=ED(U);if(I.spec.include(j))D.set(U,{...I.spec,absPath:U});continue}VR({basePath:U,depth:0,maxDepth:I.maxDepth??wZ,spec:I.spec,candidates:D,skipped:$})}return[...D.values()].sort((I,U)=>{if(I.precedence.rank!==U.precedence.rank)return I.precedence.rank-U.precedence.rank;return I.absPath.localeCompare(U.absPath)})}function VR(_){let $=_.rootBasePath??_.basePath;if(_.depth>_.maxDepth)return;for(let D of VZ(_.basePath,{withFileTypes:!0})){let I=ZZ(_.basePath,D.name),U=VW($,I);if(D.isSymbolicLink())continue;if(D.isDirectory()){if(fZ.has(D.name))continue;if(RR(U)){_.skipped.push({source_family:_.spec.family,source_path:I,reason:"sensitive_path"});continue}VR({..._,rootBasePath:$,basePath:I,depth:_.depth+1});continue}if(!D.isFile())continue;let E=VW(BW($),I);if(RR(E)){_.skipped.push({source_family:_.spec.family,source_path:I,reason:"sensitive_path"});continue}if(!_.spec.include(E))continue;if(!t6(I))continue;_.candidates.set(I,{..._.spec,absPath:I})}}function cZ(_){if((_.tags??[]).map((I)=>I.toLowerCase()).some((I)=>["rule","rules","agent","instructions","global-rules","global-agent-rules"].includes(I)))return!0;let D=`${_.title} -${_.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(D)}function BR(_,$){let D={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:D,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 nZ(_){let $=FZ(_.candidate.absPath),D=_.candidate.absPath,I=VW(_.root,D);if($.size>_.maxBytesPerFile){let z=GR(D).href;return{evidence:{source_family:_.candidate.family,title:ED(D),source_path:D,source_path_ref:I,source_ref:z,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 U=BZ(D),E=U.toString("utf8"),j=u_(E,_.safetyPolicy),A=j.findings.some((z)=>z.severity==="high")?"refused":j.findings.length>0?"redacted":"clean",O=FW(j.text),S=GR(D).href,L=TR(j.text),P={source_family:_.candidate.family,title:ED(D),source_path:D,source_path_ref:I,source_ref:S,owner:_.candidate.owner,scope:_.candidate.scope,precedence:_.candidate.precedence,source_hash:uZ(U),content_hash:O,discovered_at:_.discoveredAt,tags:[..._.candidate.tags],redaction_status:A,redactions:j.findings.map((z)=>({type:z.type,severity:z.severity})),citations:[FR({sourceRef:S,sourcePath:D,lineCount:L,contentHash:O})],bytes:U.byteLength,line_count:L,importable:A!=="refused",skipped_reason:A==="refused"?"secret_refused":null,preview:A==="refused"?null:KR(j.text)};return{evidence:P,text:j.text,manifest:P.importable?BR(P,j.text):null}}function dZ(_){let $=u_(_.item.content,_.safetyPolicy),I=$.findings.some((O)=>O.severity==="high")?"refused":$.findings.length>0?"redacted":"clean",U=`open-files://source/legacy-json/path/${encodeURIComponent(_.item.id)}`,E=FW($.text),j=FW(_.item.content),N=TR($.text),A={source_family:"legacy_json",title:_.item.title,source_path:_.legacyStorePath,source_path_ref:`legacy-json:${_.item.id}`,source_ref:U,owner:"legacy-json",scope:_.scope,precedence:{rank:90,label:"legacy-json-note"},source_hash:j,content_hash:E,discovered_at:_.discoveredAt,tags:[...new Set(["global-rules","legacy-json",..._.item.tags??[]])],redaction_status:I,redactions:$.findings.map((O)=>({type:O.type,severity:O.severity})),citations:[FR({sourceRef:U,sourcePath:_.legacyStorePath,lineCount:N,contentHash:E})],bytes:Buffer.byteLength(_.item.content),line_count:N,importable:I!=="refused",skipped_reason:I==="refused"?"secret_refused":null,preview:I==="refused"?null:KR($.text),legacy_json_id:_.item.id};return{evidence:A,text:$.text,manifest:A.importable?BR(A,$.text):null}}function mZ(_){if(!_.legacyStorePath||!QR(_.legacyStorePath))return 0;let $=new Map(_.records.filter((D)=>D.legacy_json_id&&D.importable).map((D)=>[D.legacy_json_id,D]));if($.size===0)return 0;return y$(_.legacyStorePath,()=>{let D=U4(_.legacyStorePath);if(!D.exists)return 0;let I=0;for(let U of D.items){let E=$.get(U.id);if(!E)continue;let j=U.metadata??{};U.archived=!0,U.metadata={...j,knowledge_rules_import:{status:"deprecated_after_source_backed_promotion",deprecated_at:_.now,source_ref:E.source_ref,source_hash:E.source_hash,content_hash:E.content_hash,data_loss:!1}},U.tags=[...new Set([...U.tags??[],"deprecated:knowledge-rules-import"])],U.updated_at=_.now,I+=1}if(I>0)_6(_.legacyStorePath,{items:D.items});return I})}async function MR(_={}){let $=BW(_.root??process.cwd()),D=_.scope??"global",I=_.owner??"global-agent-rules-standard",U=_.dryRun!==!1,E=(_.now??new Date).toISOString(),j=Math.max(1,Math.min(_.maxItems??qZ,1000)),N=Math.max(1,Math.min(_.limit??CZ,100)),A=Math.max(1024,Math.min(_.maxBytesPerFile??vZ,2097152)),O=[],L=hZ($,O).slice(0,j).map((Z)=>nZ({root:$,candidate:{...Z,owner:Z.owner==="repository"?I:Z.owner,scope:D},discoveredAt:E,maxBytesPerFile:A,safetyPolicy:_.safetyPolicy})),z=(_.includeLegacy===!1||!_.legacyStorePath?{exists:!1,items:[]}:U4(_.legacyStorePath)).items.filter((Z)=>Z.archived!==!0&&cZ(Z)).slice(0,j),G=z.map((Z)=>dZ({item:Z,legacyStorePath:_.legacyStorePath,discoveredAt:E,scope:D,safetyPolicy:_.safetyPolicy})),J=[...L,...G].slice(0,j),W=J.map((Z)=>Z.evidence),R=J.filter((Z)=>Z.manifest).map((Z)=>Z.manifest),T=W.filter((Z)=>Z.redaction_status==="refused").length,Y=W.slice(0,N),Q=O.slice(0,N),F=null,q=0;if(!U){if(!_.dbPath)throw Error("rules provenance apply mode requires dbPath.");if(R.length>0)F=await N4({dbPath:_.dbPath,items:R,sourceLabel:"knowledge://rules-provenance/global-agent-rules",readAction:"rules_provenance_import",allowFileSourceRefs:!0,safetyPolicy:_.safetyPolicy,now:_.now,maxItems:j});if(_.deprecateLegacy!==!1)q=mZ({legacyStorePath:_.legacyStorePath,records:W,now:E})}return{ok:T===0||R.length>0||U,workflow:"global-rules-provenance-import",dry_run:U,writes_performed:!U,root:$,scope:D,owner:I,discovered_at:E,max_items:j,evidence_limit:N,records_seen:W.length,records_importable:R.length,records_refused:T,records_skipped:O.length,evidence_truncated:W.length>Y.length,skipped_truncated:O.length>Q.length,evidence:Y,skipped:Q,import_result:F,legacy:{store_path:_.legacyStorePath??null,candidates:z.length,promoted:G.filter((Z)=>Z.manifest).length,deprecated:q,data_loss:!1},message:U?`Discovered ${W.length} rule source(s); ${R.length} importable, ${T} refused`:`Imported ${F?.items_seen??0} rule source(s); ${q} legacy note(s) deprecated`}}import{createHash as lZ,randomUUID as bR}from"crypto";function iZ(_){return`sha256:${lZ("sha256").update(_).digest("hex")}`}function ZR(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function HR(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function o6(_){return typeof _==="string"&&_.length>0?_:null}function tZ(_){let $=HR(_),D=o6($.url)??o6($.uri)??o6($.sourceUrl);if(!D)return null;return{url:D,title:o6($.title)??o6($.name),snippet:o6($.snippet)??o6($.text)??o6($.description),provider_metadata:$}}function DN(_,$){if(Array.isArray(_)){for(let U of _)DN(U,$);return}let D=tZ(_);if(D)$.set(D.url,D);let I=HR(_);for(let U of["sources","results","citations","annotations","output"])if(I[U])DN(I[U],$)}function oZ(_,$){return Array.from({length:Math.min($,3)},(D,I)=>({url:`https://example.com/knowledge-web-${I+1}`,title:`Fake web source ${I+1}`,snippet:`Deterministic web-search fixture for "${_}"`,provider_metadata:{fake:!0,rank:I+1}}))}async function pZ(_){let{generateText:$}=await import("ai"),{createOpenAI:D}=await import("@ai-sdk/openai"),I=g6(_.config,"openai"),U=D({apiKey:_.env[I.api_key_env],baseURL:I.base_url}),E=U.tools?.webSearch;if(!E)throw Error("OpenAI provider does not expose tools.webSearch.");return $({model:U(_.model),prompt:_.query,tools:{web_search:E({externalWebAccess:!0,searchContextSize:"medium",..._.domains.length>0?{allowedDomains:_.domains}:{}})},toolChoice:{type:"tool",toolName:"web_search"}})}async function eZ(_){let{generateText:$}=await import("ai"),{createAnthropic:D}=await import("@ai-sdk/anthropic"),I=g6(_.config,"anthropic"),U=D({apiKey:_.env[I.api_key_env],baseURL:I.base_url}),E=U.tools?.webSearch_20250305??U.tools?.webSearch;if(!E)throw Error("Anthropic provider does not expose a web search tool.");return $({model:U(_.model),prompt:_.query,tools:{web_search:E({maxUses:_.maxUses,..._.domains.length>0?{allowedDomains:_.domains}:{}})}})}async function aZ(_,$,D){if(!_.fileResults||$.length===0)return 0;let I=$.map((E)=>{let j=[E.title,E.snippet,E.url].filter(Boolean).join(` -`),N=iZ(j);return{source_ref:E.url,name:E.title??E.url,url:E.url,mime:"text/plain",hash:N,revision:N,status:"active",updated_at:D,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:E.url,content_source:"provider_web_search",provider_metadata:E.provider_metadata},extracted_text:j}});return(await N4({dbPath:_.dbPath,items:I,sourceLabel:`web-search:${_.query}`,readAction:"provider_web_search_file_results",safetyPolicy:_.safetyPolicy,now:new Date(D)})).sources_upserted}async function kR(_){let $=_.query.trim();if(!$)throw Error("Web search query is required.");let D=_.env??process.env,I=(_.now??new Date).toISOString(),U=Math.max(1,Math.min(_.limit??5,20)),E=Math.max(1,Math.min(_.maxUses??3,10)),j=_.domains??[],N=T$(_.modelRef??(_.provider?`${_.provider}:${g6(_.config,_.provider).default_model}`:"default"),_.config),A=f_(N),O=_.provider??A.provider,S=A.provider===O?A.model:g6(_.config,O).default_model,L=`run_${bR()}`;if(!_.fake&&_.safetyPolicy)G0(_.safetyPolicy);if(!_.fake&&O!=="openai"&&O!=="anthropic")throw Error(`Provider ${O} does not expose native web search yet.`);if(!_.fake)A4(O,_.config,D);c(_.dbPath);let P=w(_.dbPath);try{P.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[L,"provider-web-search",$,"running",O,S,JSON.stringify({domains:j,max_uses:E,fake:_.fake===!0}),I,I]),R_(P,{event_type:"source_read",action:_.fake?"fake_provider_web_search":"provider_web_search",target_uri:$,decision:"allow",metadata:{provider:O,model:S,domains:j,max_uses:E},created_at:I})}finally{P.close()}let z="",G=[],J={input_tokens:ZR($),output_tokens:0,cost_usd:0},W=[];if(_.fake)G=oZ($,U),z=`Fake web search answer for: ${$}`,J.output_tokens=ZR(z);else{let T=O==="openai"?await pZ({query:$,model:S,config:_.config,env:D,maxUses:E,domains:j}):await eZ({query:$,model:S,config:_.config,env:D,maxUses:E,domains:j});z=T.text;let Y=new Map;DN(T.sources,Y),DN(T.toolResults,Y),G=Array.from(Y.values()).slice(0,U);let Q=O4({provider:O,model:S,usage:T.usage,providerMetadata:T.providerMetadata});J={input_tokens:Q.input_tokens,output_tokens:Q.output_tokens,cost_usd:Q.cost_usd}}let X=await aZ(_,G,I),R=w(_.dbPath);try{R.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({domains:j,max_uses:E,sources:G.length,filed_sources:X,fake:_.fake===!0}),I,L]),R.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${bR()}`,L,"info","provider_web_search_completed",JSON.stringify({sources:G.length,filed_sources:X}),I]),Q0(R,{run_id:L,provider:O,model:S,input_tokens:J.input_tokens,output_tokens:J.output_tokens,cost_usd:J.cost_usd,metadata:{web_search:!0,sources:G.length,filed_sources:X},created_at:I})}finally{R.close()}if(G.length===0)W.push("no_web_sources_returned");return{run_id:L,query:$,provider:O,model:S,answer:z,sources:G,filed_sources:X,usage:J,warnings:W}}import{createHash as sZ,randomUUID as _H}from"crypto";function jD(_,$){return`${_}_${sZ("sha256").update($).digest("hex").slice(0,20)}`}function MW(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"knowledge-page"}function $H(_){return{year:String(_.getUTCFullYear()),month:String(_.getUTCMonth()+1).padStart(2,"0"),day:String(_.getUTCDate()).padStart(2,"0")}}function DH(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function qR(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function UH(_){return Array.from(new Set((_??"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,12)}function CR(_){return _.replace(/[\\%_]/g,($)=>`\\${$}`)}function IH(_,$){let D=Math.max(1,Math.min($.limit??10,50)),I=$.sourceRefs??[],U=UH($.query),E=["c.kind = 'source'"],j=[];if(I.length>0){E.push(`(${I.map(()=>"(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`);for(let N of I)j.push(N,`%${CR(N)}%`)}if(U.length>0){E.push(`(${U.map(()=>"lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`);for(let N of U)j.push(`%${CR(N)}%`)}return j.push(D),_.query(`SELECT + )`,["completed",D,"embedding","pending",U.provider,U.model]).changes}finally{E.close()}}async function GR(_){c(_.dbPath);let $=(_.now??new Date).toISOString(),D=`run_${zR()}`,I=_.full?KH(_.dbPath):{embeddings:0,vectorEntries:0},U=KP({..._,reason:_.full?"full_embedding_rebuild":"missing_embedding"}),E=w(_.dbPath);try{E.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,"embedding-refresh",_.full?"full":"incremental","running","local",W4(_.modelRef,_.config),JSON.stringify({full:_.full===!0,queued:U}),$,$])}finally{E.close()}let j=await AI({dbPath:_.dbPath,config:_.config,env:_.env,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake,limit:_.limit,now:_.now}),N=TH(_.dbPath,_,$),O=w(_.dbPath);try{O.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({full:_.full===!0,queued:U,indexed:j,completed_queue_items:N}),$,D]),O.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${zR()}`,D,"info","embedding_refresh_completed",JSON.stringify({queued:U,indexed:j,completed_queue_items:N}),$])}finally{O.close()}return{run_id:D,full:_.full===!0,deleted_embeddings:I.embeddings,deleted_vector_entries:I.vectorEntries,queued:U,indexed:j,completed_queue_items:N}}import{createHash as QR}from"crypto";import{existsSync as KR,lstatSync as FH,readdirSync as VH,readFileSync as BH,statSync as MH}from"fs";import{basename as ND,extname as ZH,join as HH,relative as bH,resolve as BP,sep as qH}from"path";import{pathToFileURL as RR}from"url";var kH=100,CH=25,vH=262144,wH=5,rH=new Set([".md",".mdx",".txt",".json",".jsonc",".toml",".yaml",".yml"]),TP=new Set(["CODEWITH.md","AGENTS.md","CLAUDE.md","RULES.md","INSTRUCTIONS.md"]),fH=new Set([".git","node_modules","dist","build",".codewith-worktrees",".connect",".secrets",".tmp","tmp","auth_profiles","profiles","preserved","backup","backups","cache","logs","runs"]),xH=/(^|[._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|private[_-]?key|id_rsa)([._-]|$)/i,DN=/(agent|rule|rules|instruction|instructions|global|operating|standard|knowledge)/i;function FP(_){return`sha256:${QR("sha256").update(_).digest("hex")}`}function uH(_){return`sha256:${QR("sha256").update(_).digest("hex")}`}function z1(_){return _.split(qH).join("/")}function VP(_,$){let D=bH(_,$);return D?z1(D):ND($)}function t6(_){return rH.has(ZH(_).toLowerCase())}function YR(_){return z1(_).split("/").some(($)=>xH.test($))}function TR(_,$=220){let D=_.normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function FR(_){if(!_)return 0;return _.split(/\r\n|\n|\r/).length}function VR(_){return{source_ref:_.sourceRef,source_path:_.sourcePath,line_start:_.lineCount>0?1:0,line_end:_.lineCount,content_hash:_.contentHash}}function yH(){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:(_)=>TP.has(_)}},{base:".codewith",spec:{family:"codewith",owner:"codewith",scope:"global",precedence:{rank:20,label:"codewith"},tags:["global-rules","codewith","agent-instructions"],include:(_)=>{let $=z1(_),D=ND($);if(TP.has(D)||$==="config.toml")return!0;if($.endsWith("/SKILL.md"))return!0;if(/^(rules|instructions|prompts|plans)\//.test($)&&t6($))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 $=z1(_);return $==="CLAUDE.md"||/^rules\//.test($)&&t6($)}}},{base:".codex",spec:{family:"codex",owner:"codex",scope:"global",precedence:{rank:40,label:"codex"},tags:["global-rules","codex","agent-instructions"],include:(_)=>{let $=z1(_),D=ND($);if(TP.has(D)||D==="config.toml")return!0;return/^(rules|instructions|prompts)\//.test($)&&t6($)}}},{base:".opencode",spec:{family:"opencode",owner:"opencode",scope:"global",precedence:{rank:50,label:"opencode"},tags:["global-rules","opencode","agent-instructions"],include:(_)=>DN.test(_)&&t6(_)}},{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:(_)=>DN.test(_)&&t6(_)}},{base:".hasna/plans",spec:{family:"plan",owner:"hasna",scope:"global",precedence:{rank:65,label:"selected-plans"},tags:["global-rules","plan"],include:(_)=>DN.test(_)&&t6(_)}},{base:"docs",spec:{family:"rule_doc",owner:"repository",scope:"global",precedence:{rank:70,label:"rule-docs"},tags:["global-rules","rule-doc"],include:(_)=>DN.test(_)&&t6(_)}}]}function hH(_,$){let D=new Map;for(let I of yH()){let U=BP(_,I.base);if(!KR(U))continue;if(MH(U).isFile()){let j=ND(U);if(I.spec.include(j))D.set(U,{...I.spec,absPath:U});continue}BR({basePath:U,depth:0,maxDepth:I.maxDepth??wH,spec:I.spec,candidates:D,skipped:$})}return[...D.values()].sort((I,U)=>{if(I.precedence.rank!==U.precedence.rank)return I.precedence.rank-U.precedence.rank;return I.absPath.localeCompare(U.absPath)})}function BR(_){let $=_.rootBasePath??_.basePath;if(_.depth>_.maxDepth)return;for(let D of VH(_.basePath,{withFileTypes:!0})){let I=HH(_.basePath,D.name),U=VP($,I);if(D.isSymbolicLink())continue;if(D.isDirectory()){if(fH.has(D.name))continue;if(YR(U)){_.skipped.push({source_family:_.spec.family,source_path:I,reason:"sensitive_path"});continue}BR({..._,rootBasePath:$,basePath:I,depth:_.depth+1});continue}if(!D.isFile())continue;let E=VP(BP($),I);if(YR(E)){_.skipped.push({source_family:_.spec.family,source_path:I,reason:"sensitive_path"});continue}if(!_.spec.include(E))continue;if(!t6(I))continue;_.candidates.set(I,{..._.spec,absPath:I})}}function cH(_){if((_.tags??[]).map((I)=>I.toLowerCase()).some((I)=>["rule","rules","agent","instructions","global-rules","global-agent-rules"].includes(I)))return!0;let D=`${_.title} +${_.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction|instructions|codewith|claude|codex|opencode)\b/.test(D)}function MR(_,$){let D={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:D,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 nH(_){let $=FH(_.candidate.absPath),D=_.candidate.absPath,I=VP(_.root,D);if($.size>_.maxBytesPerFile){let z=RR(D).href;return{evidence:{source_family:_.candidate.family,title:ND(D),source_path:D,source_path_ref:I,source_ref:z,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 U=BH(D),E=U.toString("utf8"),j=u_(E,_.safetyPolicy),O=j.findings.some((z)=>z.severity==="high")?"refused":j.findings.length>0?"redacted":"clean",S=FP(j.text),L=RR(D).href,W=FR(j.text),g={source_family:_.candidate.family,title:ND(D),source_path:D,source_path_ref:I,source_ref:L,owner:_.candidate.owner,scope:_.candidate.scope,precedence:_.candidate.precedence,source_hash:uH(U),content_hash:S,discovered_at:_.discoveredAt,tags:[..._.candidate.tags],redaction_status:O,redactions:j.findings.map((z)=>({type:z.type,severity:z.severity})),citations:[VR({sourceRef:L,sourcePath:D,lineCount:W,contentHash:S})],bytes:U.byteLength,line_count:W,importable:O!=="refused",skipped_reason:O==="refused"?"secret_refused":null,preview:O==="refused"?null:TR(j.text)};return{evidence:g,text:j.text,manifest:g.importable?MR(g,j.text):null}}function dH(_){let $=u_(_.item.content,_.safetyPolicy),I=$.findings.some((S)=>S.severity==="high")?"refused":$.findings.length>0?"redacted":"clean",U=`open-files://source/legacy-json/path/${encodeURIComponent(_.item.id)}`,E=FP($.text),j=FP(_.item.content),N=FR($.text),O={source_family:"legacy_json",title:_.item.title,source_path:_.legacyStorePath,source_path_ref:`legacy-json:${_.item.id}`,source_ref:U,owner:"legacy-json",scope:_.scope,precedence:{rank:90,label:"legacy-json-note"},source_hash:j,content_hash:E,discovered_at:_.discoveredAt,tags:[...new Set(["global-rules","legacy-json",..._.item.tags??[]])],redaction_status:I,redactions:$.findings.map((S)=>({type:S.type,severity:S.severity})),citations:[VR({sourceRef:U,sourcePath:_.legacyStorePath,lineCount:N,contentHash:E})],bytes:Buffer.byteLength(_.item.content),line_count:N,importable:I!=="refused",skipped_reason:I==="refused"?"secret_refused":null,preview:I==="refused"?null:TR($.text),legacy_json_id:_.item.id};return{evidence:O,text:$.text,manifest:O.importable?MR(O,$.text):null}}function mH(_){if(!_.legacyStorePath||!KR(_.legacyStorePath))return 0;let $=new Map(_.records.filter((D)=>D.legacy_json_id&&D.importable).map((D)=>[D.legacy_json_id,D]));if($.size===0)return 0;return y$(_.legacyStorePath,()=>{let D=I4(_.legacyStorePath);if(!D.exists)return 0;let I=0;for(let U of D.items){let E=$.get(U.id);if(!E)continue;let j=U.metadata??{};U.archived=!0,U.metadata={...j,knowledge_rules_import:{status:"deprecated_after_source_backed_promotion",deprecated_at:_.now,source_ref:E.source_ref,source_hash:E.source_hash,content_hash:E.content_hash,data_loss:!1}},U.tags=[...new Set([...U.tags??[],"deprecated:knowledge-rules-import"])],U.updated_at=_.now,I+=1}if(I>0)_6(_.legacyStorePath,{items:D.items});return I})}async function ZR(_={}){let $=BP(_.root??process.cwd()),D=_.scope??"global",I=_.owner??"global-agent-rules-standard",U=_.dryRun!==!1,E=(_.now??new Date).toISOString(),j=Math.max(1,Math.min(_.maxItems??kH,1000)),N=Math.max(1,Math.min(_.limit??CH,100)),O=Math.max(1024,Math.min(_.maxBytesPerFile??vH,2097152)),S=[],W=hH($,S).slice(0,j).map((b)=>nH({root:$,candidate:{...b,owner:b.owner==="repository"?I:b.owner,scope:D},discoveredAt:E,maxBytesPerFile:O,safetyPolicy:_.safetyPolicy})),z=(_.includeLegacy===!1||!_.legacyStorePath?{exists:!1,items:[]}:I4(_.legacyStorePath)).items.filter((b)=>b.archived!==!0&&cH(b)).slice(0,j),G=z.map((b)=>dH({item:b,legacyStorePath:_.legacyStorePath,discoveredAt:E,scope:D,safetyPolicy:_.safetyPolicy})),J=[...W,...G].slice(0,j),P=J.map((b)=>b.evidence),R=J.filter((b)=>b.manifest).map((b)=>b.manifest),T=P.filter((b)=>b.redaction_status==="refused").length,Y=P.slice(0,N),Q=S.slice(0,N),F=null,B=0;if(!U){if(!_.dbPath)throw Error("rules provenance apply mode requires dbPath.");if(R.length>0)F=await A4({dbPath:_.dbPath,items:R,sourceLabel:"knowledge://rules-provenance/global-agent-rules",readAction:"rules_provenance_import",allowFileSourceRefs:!0,safetyPolicy:_.safetyPolicy,now:_.now,maxItems:j});if(_.deprecateLegacy!==!1)B=mH({legacyStorePath:_.legacyStorePath,records:P,now:E})}return{ok:T===0||R.length>0||U,workflow:"global-rules-provenance-import",dry_run:U,writes_performed:!U,root:$,scope:D,owner:I,discovered_at:E,max_items:j,evidence_limit:N,records_seen:P.length,records_importable:R.length,records_refused:T,records_skipped:S.length,evidence_truncated:P.length>Y.length,skipped_truncated:S.length>Q.length,evidence:Y,skipped:Q,import_result:F,legacy:{store_path:_.legacyStorePath??null,candidates:z.length,promoted:G.filter((b)=>b.manifest).length,deprecated:B,data_loss:!1},message:U?`Discovered ${P.length} rule source(s); ${R.length} importable, ${T} refused`:`Imported ${F?.items_seen??0} rule source(s); ${B} legacy note(s) deprecated`}}import{createHash as lH,randomUUID as HR}from"crypto";function iH(_){return`sha256:${lH("sha256").update(_).digest("hex")}`}function bR(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function qR(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function o6(_){return typeof _==="string"&&_.length>0?_:null}function tH(_){let $=qR(_),D=o6($.url)??o6($.uri)??o6($.sourceUrl);if(!D)return null;return{url:D,title:o6($.title)??o6($.name),snippet:o6($.snippet)??o6($.text)??o6($.description),provider_metadata:$}}function UN(_,$){if(Array.isArray(_)){for(let U of _)UN(U,$);return}let D=tH(_);if(D)$.set(D.url,D);let I=qR(_);for(let U of["sources","results","citations","annotations","output"])if(I[U])UN(I[U],$)}function oH(_,$){return Array.from({length:Math.min($,3)},(D,I)=>({url:`https://example.com/knowledge-web-${I+1}`,title:`Fake web source ${I+1}`,snippet:`Deterministic web-search fixture for "${_}"`,provider_metadata:{fake:!0,rank:I+1}}))}async function pH(_){let{generateText:$}=await import("ai"),{createOpenAI:D}=await import("@ai-sdk/openai"),I=A6(_.config,"openai"),U=D({apiKey:_.env[I.api_key_env],baseURL:I.base_url}),E=U.tools?.webSearch;if(!E)throw Error("OpenAI provider does not expose tools.webSearch.");return $({model:U(_.model),prompt:_.query,tools:{web_search:E({externalWebAccess:!0,searchContextSize:"medium",..._.domains.length>0?{allowedDomains:_.domains}:{}})},toolChoice:{type:"tool",toolName:"web_search"}})}async function eH(_){let{generateText:$}=await import("ai"),{createAnthropic:D}=await import("@ai-sdk/anthropic"),I=A6(_.config,"anthropic"),U=D({apiKey:_.env[I.api_key_env],baseURL:I.base_url}),E=U.tools?.webSearch_20250305??U.tools?.webSearch;if(!E)throw Error("Anthropic provider does not expose a web search tool.");return $({model:U(_.model),prompt:_.query,tools:{web_search:E({maxUses:_.maxUses,..._.domains.length>0?{allowedDomains:_.domains}:{}})}})}async function aH(_,$,D){if(!_.fileResults||$.length===0)return 0;let I=$.map((E)=>{let j=[E.title,E.snippet,E.url].filter(Boolean).join(` +`),N=iH(j);return{source_ref:E.url,name:E.title??E.url,url:E.url,mime:"text/plain",hash:N,revision:N,status:"active",updated_at:D,permissions:{mode:"read_only",allowed_purposes:["knowledge_answer","knowledge_index"]},metadata:{source_ref:E.url,content_source:"provider_web_search",provider_metadata:E.provider_metadata},extracted_text:j}});return(await A4({dbPath:_.dbPath,items:I,sourceLabel:`web-search:${_.query}`,readAction:"provider_web_search_file_results",safetyPolicy:_.safetyPolicy,now:new Date(D)})).sources_upserted}async function kR(_){let $=_.query.trim();if(!$)throw Error("Web search query is required.");let D=_.env??process.env,I=(_.now??new Date).toISOString(),U=Math.max(1,Math.min(_.limit??5,20)),E=Math.max(1,Math.min(_.maxUses??3,10)),j=_.domains??[],N=T$(_.modelRef??(_.provider?`${_.provider}:${A6(_.config,_.provider).default_model}`:"default"),_.config),O=f_(N),S=_.provider??O.provider,L=O.provider===S?O.model:A6(_.config,S).default_model,W=`run_${HR()}`;if(!_.fake&&_.safetyPolicy)Y0(_.safetyPolicy);if(!_.fake&&S!=="openai"&&S!=="anthropic")throw Error(`Provider ${S} does not expose native web search yet.`);if(!_.fake)S4(S,_.config,D);c(_.dbPath);let g=w(_.dbPath);try{g.run(`INSERT INTO runs (id, type, prompt, status, provider, model, metadata_json, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[W,"provider-web-search",$,"running",S,L,JSON.stringify({domains:j,max_uses:E,fake:_.fake===!0}),I,I]),R_(g,{event_type:"source_read",action:_.fake?"fake_provider_web_search":"provider_web_search",target_uri:$,decision:"allow",metadata:{provider:S,model:L,domains:j,max_uses:E},created_at:I})}finally{g.close()}let z="",G=[],J={input_tokens:bR($),output_tokens:0,cost_usd:0},P=[];if(_.fake)G=oH($,U),z=`Fake web search answer for: ${$}`,J.output_tokens=bR(z);else{let T=S==="openai"?await pH({query:$,model:L,config:_.config,env:D,maxUses:E,domains:j}):await eH({query:$,model:L,config:_.config,env:D,maxUses:E,domains:j});z=T.text;let Y=new Map;UN(T.sources,Y),UN(T.toolResults,Y),G=Array.from(Y.values()).slice(0,U);let Q=L4({provider:S,model:L,usage:T.usage,providerMetadata:T.providerMetadata});J={input_tokens:Q.input_tokens,output_tokens:Q.output_tokens,cost_usd:Q.cost_usd}}let X=await aH(_,G,I),R=w(_.dbPath);try{R.run("UPDATE runs SET status = ?, metadata_json = ?, updated_at = ? WHERE id = ?",["completed",JSON.stringify({domains:j,max_uses:E,sources:G.length,filed_sources:X,fake:_.fake===!0}),I,W]),R.run(`INSERT INTO run_events (id, run_id, level, event, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?)`,[`evt_${HR()}`,W,"info","provider_web_search_completed",JSON.stringify({sources:G.length,filed_sources:X}),I]),T0(R,{run_id:W,provider:S,model:L,input_tokens:J.input_tokens,output_tokens:J.output_tokens,cost_usd:J.cost_usd,metadata:{web_search:!0,sources:G.length,filed_sources:X},created_at:I})}finally{R.close()}if(G.length===0)P.push("no_web_sources_returned");return{run_id:W,query:$,provider:S,model:L,answer:z,sources:G,filed_sources:X,usage:J,warnings:P}}import{createHash as sH,randomUUID as _b}from"crypto";function AD(_,$){return`${_}_${sH("sha256").update($).digest("hex").slice(0,20)}`}function MP(_){return _.normalize("NFKC").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"knowledge-page"}function $b(_){return{year:String(_.getUTCFullYear()),month:String(_.getUTCMonth()+1).padStart(2,"0"),day:String(_.getUTCDate()).padStart(2,"0")}}function Db(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function CR(_){if(!_)return{};try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function Ub(_){return Array.from(new Set((_??"").toLowerCase().match(/[\p{L}\p{N}_]+/gu)??[])).slice(0,12)}function vR(_){return _.replace(/[\\%_]/g,($)=>`\\${$}`)}function Ib(_,$){let D=Math.max(1,Math.min($.limit??10,50)),I=$.sourceRefs??[],U=Ub($.query),E=["c.kind = 'source'"],j=[];if(I.length>0){E.push(`(${I.map(()=>"(s.uri = ? OR c.metadata_json LIKE ?)").join(" OR ")})`);for(let N of I)j.push(N,`%${vR(N)}%`)}if(U.length>0){E.push(`(${U.map(()=>"lower(c.text) LIKE ? ESCAPE '\\'").join(" OR ")})`);for(let N of U)j.push(`%${vR(N)}%`)}return j.push(D),_.query(`SELECT c.id AS chunk_id, c.text, c.start_offset, @@ -1041,10 +1041,10 @@ ${_.content.slice(0,500)}`.toLowerCase();return/\b(agent|rule|rules|instruction| JOIN sources s ON s.id = sr.source_id WHERE ${E.join(" AND ")} ORDER BY c.created_at ASC, c.ordinal ASC - LIMIT ?`).all(...j)}function vR(_,$=420){let D=_.replace(/\s+/g," ").trim();return D.length<=$?D:`${D.slice(0,$-1).trim()}...`}function EH(_,$){if(_.title?.trim())return _.title.trim();if(_.query?.trim())return _.query.trim();return $[0]?.source_title??"Compiled Knowledge"}function jH(_,$,D){let I=$.map((E,j)=>{return`- [${`S${j+1}`}] ${E.source_title??E.source_uri??"Source"} (${E.source_uri??"unknown"}, revision ${E.revision??"unknown"}, hash ${E.hash??"unknown"})`}),U=$.map((E,j)=>{let N=`S${j+1}`;return[`## ${E.source_title??`Source ${j+1}`}`,"",vR(E.text),"",`Citation: [${N}]`].join(` + LIMIT ?`).all(...j)}function wR(_,$=420){let D=_.replace(/\s+/g," ").trim();return D.length<=$?D:`${D.slice(0,$-1).trim()}...`}function Eb(_,$){if(_.title?.trim())return _.title.trim();if(_.query?.trim())return _.query.trim();return $[0]?.source_title??"Compiled Knowledge"}function jb(_,$,D){let I=$.map((E,j)=>{return`- [${`S${j+1}`}] ${E.source_title??E.source_uri??"Source"} (${E.source_uri??"unknown"}, revision ${E.revision??"unknown"}, hash ${E.hash??"unknown"})`}),U=$.map((E,j)=>{let N=`S${j+1}`;return[`## ${E.source_title??`Source ${j+1}`}`,"",wR(E.text),"",`Citation: [${N}]`].join(` `)});return[`# ${_}`,"",`Generated at: ${D}`,"","## Sources","",...I,"",...U,""].join(` -`)}async function UN(_,$){let D=await _.put($);return{key:D.key,uri:D.uri,kind:$.key.startsWith("logs/")?"log":"wiki_page",content_type:$.content_type,modified_at:D.modified_at,...X0($.body),metadata:{...$.metadata??{}}}}async function wR(_,$,D){let{year:I,month:U,day:E}=$H(D),j=`logs/${I}/${U}/${E}.jsonl`,N="";try{N=await _.getText(j)}catch{N=""}return UN(_,{key:j,body:`${N}${JSON.stringify($)} -`,content_type:"application/x-ndjson",metadata:{provenance:N$({generated_from:String($.event??"wiki_log"),artifact_key:j})}})}function bW(_,$){_.run(`INSERT INTO wiki_pages (id, path, title, artifact_uri, content_hash, status, metadata_json, created_at, updated_at) +`)}async function IN(_,$){let D=await _.put($);return{key:D.key,uri:D.uri,kind:$.key.startsWith("logs/")?"log":"wiki_page",content_type:$.content_type,modified_at:D.modified_at,...R0($.body),metadata:{...$.metadata??{}}}}async function rR(_,$,D){let{year:I,month:U,day:E}=$b(D),j=`logs/${I}/${U}/${E}.jsonl`,N="";try{N=await _.getText(j)}catch{N=""}return IN(_,{key:j,body:`${N}${JSON.stringify($)} +`,content_type:"application/x-ndjson",metadata:{provenance:N$({generated_from:String($.event??"wiki_log"),artifact_key:j})}})}function ZP(_,$){_.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,41 +1052,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 D=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($.pageId);for(let U of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$.pageId]);let I=jD("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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,$.pageId,"wiki",0,$.body,DH($.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 (?, ?, ?, ?)",[I,$.body,$.title,$.artifactUri])}function rR(_,$,D,I){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);for(let U of D)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[jD("cit",`${$}\x00${U.source_uri}\x00${U.chunk_id??_H()}`),$,U.chunk_id,U.source_uri,U.quote,U.start_offset,U.end_offset,JSON.stringify(U.metadata),I]);return D.length}function fR(_,$){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 D=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($.pageId);for(let U of D)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[U.id]);_.run("DELETE FROM chunks WHERE wiki_page_id = ?",[$.pageId]);let I=AD("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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[I,$.pageId,"wiki",0,$.body,Db($.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 (?, ?, ?, ?)",[I,$.body,$.title,$.artifactUri])}function fR(_,$,D,I){_.run("DELETE FROM citations WHERE wiki_page_id = ?",[$]);for(let U of D)_.run(`INSERT INTO citations (id, wiki_page_id, chunk_id, source_uri, quote, start_offset, end_offset, metadata_json, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[AD("cit",`${$}\x00${U.source_uri}\x00${U.chunk_id??_b()}`),$,U.chunk_id,U.source_uri,U.quote,U.start_offset,U.end_offset,JSON.stringify(U.metadata),I]);return D.length}function xR(_,$){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`,[jD("idx",`wiki-topic\x00${$.path}`),"wiki_topic",$.title,$.artifactUri,$.path,JSON.stringify({artifact_key:$.path,content_hash:$.contentHash}),$.now,$.now]),1}function NH(_){return _.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0]??"knowledge"}async function xR(_){let $=_.now??new Date,D=$.toISOString();c(_.dbPath);let I=w(_.dbPath),U;try{U=IH(I,_)}finally{I.close()}if(U.length===0)throw Error("No source chunks matched wiki compile input.");let E=EH(_,U),N=`wiki/generated/${MW(E)}.md`,A=jH(E,U,D),O=U.map((F)=>{let q=qR(F.metadata_json);return typeof q.source_ref==="string"?q.source_ref:F.source_uri}).filter((F)=>Boolean(F)),S=N$({generated_from:"wiki_compile",artifact_key:N,source_refs:O}),L=await UN(_.store,{key:N,body:A,content_type:"text/markdown",metadata:{generated_from:"wiki_compile"}}),P=jD("wiki",N),z=U.map((F)=>({chunk_id:F.chunk_id,source_uri:F.source_uri??"unknown",quote:vR(F.text,240),start_offset:F.start_offset,end_offset:F.end_offset,metadata:{source_revision_id:F.source_revision_id,revision:F.revision,hash:F.hash,source_ref:qR(F.metadata_json).source_ref??F.source_uri}})),G=NH(E),J=`wiki/concepts/${MW(G)}.md`,W=[`# ${G}`,"",`Related page: [[${N}]]`,""].join(` -`),X=N$({generated_from:"wiki_compile_concept",artifact_key:J,source_refs:O}),R=await UN(_.store,{key:J,body:W,content_type:"text/markdown",metadata:{generated_from:"wiki_compile_concept"}}),T=jD("wiki",J),Y=await wR(_.store,{ts:D,event:"wiki_compile_completed",page_key:N,source_refs:O,chunks_seen:U.length},$),Q=w(_.dbPath);try{j6(Q,[L,R,Y],$),bW(Q,{pageId:P,path:N,title:E,artifactUri:L.uri,contentHash:L.hash??"",body:A,provenance:S,now:D}),bW(Q,{pageId:T,path:J,title:G,artifactUri:R.uri,contentHash:R.hash??"",body:W,provenance:X,now:D}),Q.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) - VALUES (?, ?, ?, ?)`,[P,T,"concept",D]);let F=rR(Q,P,z,D),q=fR(Q,{title:E,path:N,artifactUri:L.uri,contentHash:L.hash??"",now:D});return{page_id:P,path:N,artifact_uri:L.uri,content_hash:L.hash??"",chunks_seen:U.length,citations_written:F,concept_page_id:T,indexes_updated:q,log_key:Y.key,warnings:[]}}finally{Q.close()}}async function uR(_){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,D=$.toISOString(),I=_.prompt.length>80?`${_.prompt.slice(0,77)}...`:_.prompt,E=`wiki/answers/${MW(I)}.md`,j=_.context.citations,N=[`# ${I}`,"",_.answer,"","## Citations","",...j.map((G,J)=>`- [C${J+1}] ${G.source_ref??G.source_uri??G.artifact_path??G.artifact_uri??"unknown"} ${G.hash?`(hash ${G.hash})`:""}`),""].join(` -`),A=j.map((G)=>G.source_ref??G.source_uri).filter((G)=>Boolean(G)),O=N$({generated_from:"knowledge_answer",artifact_key:E,source_refs:A}),S=await UN(_.store,{key:E,body:N,content_type:"text/markdown",metadata:{generated_from:"knowledge_answer"}}),L=await wR(_.store,{ts:D,event:"wiki_answer_filed",page_key:E,prompt:_.prompt,citations:j.length},$),P=jD("wiki",E),z=w(_.dbPath);try{j6(z,[S,L],$),bW(z,{pageId:P,path:E,title:I,artifactUri:S.uri,contentHash:S.hash??"",body:N,provenance:O,now:D});let G=rR(z,P,j.map((J)=>({chunk_id:J.chunk_id,source_uri:J.source_uri??J.artifact_uri??"unknown",quote:J.quote,start_offset:J.start_offset,end_offset:J.end_offset,metadata:{source_ref:J.source_ref,artifact_path:J.artifact_path,revision:J.revision,hash:J.hash}})),D);return fR(z,{title:I,path:E,artifactUri:S.uri,contentHash:S.hash??"",now:D}),{approved:!0,durable_writes_performed:!0,page_id:P,path:E,artifact_uri:S.uri,citations_written:G,log_key:L.key,message:`Filed answer to ${E}`}}finally{z.close()}}function m4(_,$){_.push($)}function yR(_){c(_.dbPath);let $=w(_.dbPath),D=[];try{let I=$.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM citations").get()?.n??0,E=$.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n??0,j=$.query(`SELECT wp.id, wp.path + updated_at = excluded.updated_at`,[AD("idx",`wiki-topic\x00${$.path}`),"wiki_topic",$.title,$.artifactUri,$.path,JSON.stringify({artifact_key:$.path,content_hash:$.contentHash}),$.now,$.now]),1}function Nb(_){return _.toLowerCase().match(/[a-z0-9][a-z0-9-]{2,}/)?.[0]??"knowledge"}async function uR(_){let $=_.now??new Date,D=$.toISOString();c(_.dbPath);let I=w(_.dbPath),U;try{U=Ib(I,_)}finally{I.close()}if(U.length===0)throw Error("No source chunks matched wiki compile input.");let E=Eb(_,U),N=`wiki/generated/${MP(E)}.md`,O=jb(E,U,D),S=U.map((F)=>{let B=CR(F.metadata_json);return typeof B.source_ref==="string"?B.source_ref:F.source_uri}).filter((F)=>Boolean(F)),L=N$({generated_from:"wiki_compile",artifact_key:N,source_refs:S}),W=await IN(_.store,{key:N,body:O,content_type:"text/markdown",metadata:{generated_from:"wiki_compile"}}),g=AD("wiki",N),z=U.map((F)=>({chunk_id:F.chunk_id,source_uri:F.source_uri??"unknown",quote:wR(F.text,240),start_offset:F.start_offset,end_offset:F.end_offset,metadata:{source_revision_id:F.source_revision_id,revision:F.revision,hash:F.hash,source_ref:CR(F.metadata_json).source_ref??F.source_uri}})),G=Nb(E),J=`wiki/concepts/${MP(G)}.md`,P=[`# ${G}`,"",`Related page: [[${N}]]`,""].join(` +`),X=N$({generated_from:"wiki_compile_concept",artifact_key:J,source_refs:S}),R=await IN(_.store,{key:J,body:P,content_type:"text/markdown",metadata:{generated_from:"wiki_compile_concept"}}),T=AD("wiki",J),Y=await rR(_.store,{ts:D,event:"wiki_compile_completed",page_key:N,source_refs:S,chunks_seen:U.length},$),Q=w(_.dbPath);try{j6(Q,[W,R,Y],$),ZP(Q,{pageId:g,path:N,title:E,artifactUri:W.uri,contentHash:W.hash??"",body:O,provenance:L,now:D}),ZP(Q,{pageId:T,path:J,title:G,artifactUri:R.uri,contentHash:R.hash??"",body:P,provenance:X,now:D}),Q.run(`INSERT OR REPLACE INTO wiki_backlinks (from_page_id, to_page_id, label, created_at) + VALUES (?, ?, ?, ?)`,[g,T,"concept",D]);let F=fR(Q,g,z,D),B=xR(Q,{title:E,path:N,artifactUri:W.uri,contentHash:W.hash??"",now:D});return{page_id:g,path:N,artifact_uri:W.uri,content_hash:W.hash??"",chunks_seen:U.length,citations_written:F,concept_page_id:T,indexes_updated:B,log_key:Y.key,warnings:[]}}finally{Q.close()}}async function yR(_){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,D=$.toISOString(),I=_.prompt.length>80?`${_.prompt.slice(0,77)}...`:_.prompt,E=`wiki/answers/${MP(I)}.md`,j=_.context.citations,N=[`# ${I}`,"",_.answer,"","## Citations","",...j.map((G,J)=>`- [C${J+1}] ${G.source_ref??G.source_uri??G.artifact_path??G.artifact_uri??"unknown"} ${G.hash?`(hash ${G.hash})`:""}`),""].join(` +`),O=j.map((G)=>G.source_ref??G.source_uri).filter((G)=>Boolean(G)),S=N$({generated_from:"knowledge_answer",artifact_key:E,source_refs:O}),L=await IN(_.store,{key:E,body:N,content_type:"text/markdown",metadata:{generated_from:"knowledge_answer"}}),W=await rR(_.store,{ts:D,event:"wiki_answer_filed",page_key:E,prompt:_.prompt,citations:j.length},$),g=AD("wiki",E),z=w(_.dbPath);try{j6(z,[L,W],$),ZP(z,{pageId:g,path:E,title:I,artifactUri:L.uri,contentHash:L.hash??"",body:N,provenance:S,now:D});let G=fR(z,g,j.map((J)=>({chunk_id:J.chunk_id,source_uri:J.source_uri??J.artifact_uri??"unknown",quote:J.quote,start_offset:J.start_offset,end_offset:J.end_offset,metadata:{source_ref:J.source_ref,artifact_path:J.artifact_path,revision:J.revision,hash:J.hash}})),D);return xR(z,{title:I,path:E,artifactUri:L.uri,contentHash:L.hash??"",now:D}),{approved:!0,durable_writes_performed:!0,page_id:g,path:E,artifact_uri:L.uri,citations_written:G,log_key:W.key,message:`Filed answer to ${E}`}}finally{z.close()}}function l4(_,$){_.push($)}function hR(_){c(_.dbPath);let $=w(_.dbPath),D=[];try{let I=$.query("SELECT COUNT(*) AS n FROM wiki_pages WHERE status = 'active'").get()?.n??0,U=$.query("SELECT COUNT(*) AS n FROM citations").get()?.n??0,E=$.query("SELECT COUNT(*) AS n FROM wiki_backlinks").get()?.n??0,j=$.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 z of j)m4(D,{type:"missing_citation",severity:"error",page_id:z.id,path:z.path,message:"Generated wiki page has no citations."});let N=$.query(`SELECT wp.id AS page_id, wp.path, c.source_uri, c.chunk_id + HAVING COUNT(c.id) = 0`).all();for(let z of j)l4(D,{type:"missing_citation",severity:"error",page_id:z.id,path:z.path,message:"Generated wiki page has no citations."});let N=$.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 z of N)m4(D,{type:"stale_citation",severity:"warn",page_id:z.page_id,path:z.path,source_uri:z.source_uri,chunk_id:z.chunk_id??void 0,message:"Page cites a stale or deleted source chunk."});let A=$.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 z of N)l4(D,{type:"stale_citation",severity:"warn",page_id:z.page_id,path:z.path,source_uri:z.source_uri,chunk_id:z.chunk_id??void 0,message:"Page cites a stale or deleted source chunk."});let O=$.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 z of A)m4(D,{type:"duplicate_page",severity:"warn",message:`Duplicate active wiki title: ${z.title} (${z.n} pages).`});let O=$.query(`SELECT wp.id, wp.path + HAVING COUNT(*) > 1`).all();for(let z of O)l4(D,{type:"duplicate_page",severity:"warn",message:`Duplicate active wiki title: ${z.title} (${z.n} pages).`});let S=$.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 z of O)m4(D,{type:"orphan_page",severity:"info",page_id:z.id,path:z.path,message:"Wiki page has no backlinks."});let S=$.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 z of S)l4(D,{type:"orphan_page",severity:"info",page_id:z.id,path:z.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 z of S)m4(D,{type:"unresolved_source_ref",severity:"error",page_id:z.page_id,path:z.path,source_uri:z.source_uri,message:"Citation source URI cannot be resolved to a known or allowed source ref."});let L=$.query("SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'").all();for(let z of L)m4(D,{type:"contradiction_marker",severity:"warn",page_id:z.id,path:z.path,message:"Page metadata contains a contradiction marker."});let P=$.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 z of L)l4(D,{type:"unresolved_source_ref",severity:"error",page_id:z.page_id,path:z.path,source_uri:z.source_uri,message:"Citation source URI cannot be resolved to a known or allowed source ref."});let W=$.query("SELECT id, path FROM wiki_pages WHERE lower(metadata_json) LIKE '%contradiction%'").all();for(let z of W)l4(D,{type:"contradiction_marker",severity:"warn",page_id:z.id,path:z.path,message:"Page metadata contains a contradiction marker."});let g=$.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 @@ -1094,7 +1094,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 z of P)m4(D,{type:"new_article_candidate",severity:"info",chunk_id:z.chunk_id,source_uri:z.source_uri??void 0,message:"Source chunk is indexed but not cited by any wiki page yet."});return{ok:D.every((z)=>z.severity!=="error"),issue_count:D.length,issues:D,counts:{active_pages:I,citations:U,backlinks:E,new_article_candidates:P.length}}}finally{$.close()}}import{createHash as gH}from"crypto";function AH(_){let $=String(_.getUTCFullYear()),D=String(_.getUTCMonth()+1).padStart(2,"0"),I=String(_.getUTCDate()).padStart(2,"0");return{year:$,month:D,day:I}}function ZW(_,$){return`${_}_${gH("sha256").update($).digest("hex").slice(0,20)}`}function OH(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function SH(){return`# Knowledge Agent Schema v1 + LIMIT 25`).all();for(let z of g)l4(D,{type:"new_article_candidate",severity:"info",chunk_id:z.chunk_id,source_uri:z.source_uri??void 0,message:"Source chunk is indexed but not cited by any wiki page yet."});return{ok:D.every((z)=>z.severity!=="error"),issue_count:D.length,issues:D,counts:{active_pages:I,citations:U,backlinks:E,new_article_candidates:g.length}}}finally{$.close()}}import{createHash as Ab}from"crypto";function Ob(_){let $=String(_.getUTCFullYear()),D=String(_.getUTCMonth()+1).padStart(2,"0"),I=String(_.getUTCDate()).padStart(2,"0");return{year:$,month:D,day:I}}function HP(_,$){return`${_}_${Ab("sha256").update($).digest("hex").slice(0,20)}`}function Sb(_){let $=_.trim().split(/\s+/).filter(Boolean).length;return Math.max(1,Math.ceil($*1.25))}function Lb(){return`# Knowledge Agent Schema v1 ## Source Rules @@ -1119,7 +1119,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 LH(){return`# Knowledge Index +`}function Wb(){return`# Knowledge Index This is a compact orientation index for agents. It is not the full search index. @@ -1134,19 +1134,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 hR(){return`# Wiki +`}function cR(){return`# Wiki Generated durable knowledge pages live here. Pages should be concise, cited, and organized for both humans and agents. -`}async function cR(_,$=new Date){let{year:D,month:I,day:U}=AH($),E="schemas/v1.md",j="indexes/root.md",N="wiki/README.md",A=`logs/${D}/${I}/${U}.jsonl`,O={ts:$.toISOString(),event:"wiki_layout_initialized",schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md"},S=[{key:"schemas/v1.md",body:SH(),content_type:"text/markdown"},{key:"indexes/root.md",body:LH(),content_type:"text/markdown"},{key:"wiki/README.md",body:hR(),content_type:"text/markdown"},{key:A,body:`${JSON.stringify(O)} -`,content_type:"application/x-ndjson"}],L=await Promise.all(S.map(async(P)=>{let z=await _.put(P);return{key:z.key,uri:z.uri,kind:pz(P.key),content_type:P.content_type,modified_at:z.modified_at,metadata:{provenance:N$({generated_from:"wiki_layout_init",artifact_key:P.key,citation_required:P.key.startsWith("wiki/")||P.key.startsWith("indexes/")})},...X0(P.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:A,artifacts:L,written:["schemas/v1.md","indexes/root.md","wiki/README.md",A]}}function HW(_){let $=_.metadata?.provenance;if($&&typeof $==="object"&&!Array.isArray($))return $;return N$({generated_from:"wiki_layout_init",artifact_key:_.key})}function JH(_,$,D,I,U,E){let j=HW(I),N=ZW("chk",`${$}\x00${I.hash??I.uri}`),A=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($);for(let O of A)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[O.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,$,"wiki",0,U,OH(U),0,U.length,JSON.stringify({artifact_key:I.key,artifact_uri:I.uri,content_hash:I.hash??null,provenance:j}),E]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[N,U,D,I.uri])}function nR(_,$,D=new Date){let I=D.toISOString(),U=$.find((j)=>j.key.endsWith("indexes/root.md")),E=$.find((j)=>j.key.endsWith("wiki/README.md"));if(U)_.run(`INSERT INTO knowledge_indexes (id, kind, name, artifact_uri, shard_key, metadata_json, created_at, updated_at) +`}async function nR(_,$=new Date){let{year:D,month:I,day:U}=Ob($),E="schemas/v1.md",j="indexes/root.md",N="wiki/README.md",O=`logs/${D}/${I}/${U}.jsonl`,S={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:Lb(),content_type:"text/markdown"},{key:"indexes/root.md",body:Wb(),content_type:"text/markdown"},{key:"wiki/README.md",body:cR(),content_type:"text/markdown"},{key:O,body:`${JSON.stringify(S)} +`,content_type:"application/x-ndjson"}],W=await Promise.all(L.map(async(g)=>{let z=await _.put(g);return{key:z.key,uri:z.uri,kind:e3(g.key),content_type:g.content_type,modified_at:z.modified_at,metadata:{provenance:N$({generated_from:"wiki_layout_init",artifact_key:g.key,citation_required:g.key.startsWith("wiki/")||g.key.startsWith("indexes/")})},...R0(g.body)}}));return{schema_key:"schemas/v1.md",root_index_key:"indexes/root.md",wiki_readme_key:"wiki/README.md",log_key:O,artifacts:W,written:["schemas/v1.md","indexes/root.md","wiki/README.md",O]}}function bP(_){let $=_.metadata?.provenance;if($&&typeof $==="object"&&!Array.isArray($))return $;return N$({generated_from:"wiki_layout_init",artifact_key:_.key})}function Jb(_,$,D,I,U,E){let j=bP(I),N=HP("chk",`${$}\x00${I.hash??I.uri}`),O=_.query("SELECT id FROM chunks WHERE wiki_page_id = ?").all($);for(let S of O)_.run("DELETE FROM chunks_fts WHERE chunk_id = ?",[S.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[N,$,"wiki",0,U,Sb(U),0,U.length,JSON.stringify({artifact_key:I.key,artifact_uri:I.uri,content_hash:I.hash??null,provenance:j}),E]),_.run("INSERT INTO chunks_fts (chunk_id, text, title, source_uri) VALUES (?, ?, ?, ?)",[N,U,D,I.uri])}function dR(_,$,D=new Date){let I=D.toISOString(),U=$.find((j)=>j.key.endsWith("indexes/root.md")),E=$.find((j)=>j.key.endsWith("wiki/README.md"));if(U)_.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`,[ZW("idx","root:indexes/root.md"),"root","root",U.uri,"root",JSON.stringify({artifact_key:U.key,content_hash:U.hash??null,provenance:HW(U)}),I,I]);if(E){let j=ZW("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`,[HP("idx","root:indexes/root.md"),"root","root",U.uri,"root",JSON.stringify({artifact_key:U.key,content_hash:U.hash??null,provenance:bP(U)}),I,I]);if(E){let j=HP("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, @@ -1154,9 +1154,9 @@ 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`,[j,"wiki/README.md","Wiki",E.uri,E.hash??null,"active",JSON.stringify({artifact_key:E.key,provenance:HW(E)}),I,I]),JH(_,j,"Wiki",E,hR(),I)}}import{createHash as dR}from"crypto";import{cpSync as fW,chmodSync as qW,existsSync as H$,lstatSync as oR,mkdirSync as IN,readdirSync as xW,readFileSync as z1,renameSync as WH,rmSync as jN,writeFileSync as mR}from"fs";import{dirname as CW,join as R6,relative as PH}from"path";function vW(_,$=_){if(!H$(_))return[];let D=oR(_);if(D.isFile())return[PH($,_)||"."];if(!D.isDirectory())return[];return xW(_).flatMap((I)=>vW(R6(_,I),$)).sort()}function lR(_,$){if($.length===0)return{sha256:null,bytes:0};let D=dR("sha256"),I=0;for(let U of $){let E=R6(_,U),j=z1(E),N=dR("sha256").update(j).digest("hex");I+=j.byteLength,D.update(U),D.update("\x00"),D.update(N),D.update("\x00")}return{sha256:D.digest("hex"),bytes:I}}function zH(_){if(!H$(_))return null;let $=JSON.parse(z1(_,"utf8"));return Array.isArray($.items)?$.items.length:null}function XH(_){if(!H$(_))return{exists:!1,integrity_check:null,table_counts:{}};let $=rz(_);try{let D=$.query("PRAGMA integrity_check").get(),I=D?Object.values(D)[0]??null:null,U=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),E={};for(let j of U){let N=`"${j.name.replaceAll('"','""')}"`,A=$.query(`SELECT COUNT(*) AS n FROM ${N}`).get();E[j.name]=A?.n??0}return{exists:!0,integrity_check:I,table_counts:E}}finally{$.close()}}function m_(_,$={}){let D=vW(_.home),I=lR(_.home,D),U=vW(_.artifactsDir),E=lR(_.artifactsDir,U),j=H$(_.knowledgeDbPath);return{path:_.home,exists:H$(_.home),file_count:D.length,total_bytes:I.bytes,tree_sha256:I.sha256,json_items:zH(_.jsonStorePath),sqlite:$.includeSqlite===!1?{exists:j,integrity_check:null,table_counts:{}}:XH(_.knowledgeDbPath),artifacts:{exists:H$(_.artifactsDir),file_count:U.length,total_bytes:E.bytes,tree_sha256:E.sha256},files:D}}function GH(_,$){if(!$.exists)return!0;if($.files.filter((I)=>I!=="config.json").length>0)return!1;if(!$.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(z1(_.configPath,"utf8")))===JSON.stringify(vD())}catch{return!1}}function wW(_,$){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 EN(_){return _.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function rW(_){if(Array.isArray(_))return`[${_.map(rW).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>`${JSON.stringify($)}:${rW(D)}`).join(",")}}`;return JSON.stringify(_)}function iR(_){return rW(_)}function kW(_){return typeof _.short_id==="string"&&_.short_id.trim().length>0?_.short_id:null}function l4(_){if(!H$(_))return{items:[]};let $=JSON.parse(z1(_,"utf8"));if(!$||!Array.isArray($.items))throw Error(`Invalid knowledge JSON store shape at ${_}`);return{items:$.items}}function tR(_,$){let D=new Map(_.items.map((S)=>[S.id,S])),I=new Map;for(let S of _.items){let L=I.get(S.id);if(L&&L.item.id!==S.id);I.set(S.id,{item:S,keyKind:"id",source:"current"});let P=kW(S);if(P&&!I.has(P))I.set(P,{item:S,keyKind:"short_id",source:"current"})}let U=[],E=0,j=0,N=0,A=[];for(let S of $.items){let L=D.get(S.id);if(L){if(iR(L)===iR(S))E+=1;else j+=1,U.push({type:"id_conflict",id:S.id,legacy_title:S.title,current_title:L.title});continue}let P=[{key:S.id,keyKind:"id"},...kW(S)?[{key:kW(S),keyKind:"short_id"}]:[]],z=!1;for(let{key:G,keyKind:J}of P){let W=I.get(G);if(!W)continue;if(J==="id"&&W.keyKind==="id")j+=1,U.push({type:"id_conflict",id:G,legacy_id:S.id,current_id:W.item.id,legacy_title:S.title,current_title:W.item.title});else N+=1,U.push({type:"short_id_conflict",id:G,legacy_id:S.id,current_id:W.item.id,legacy_title:S.title,current_title:W.item.title});z=!0}if(z)continue;A.push(S);for(let{key:G,keyKind:J}of P)I.set(G,{item:S,keyKind:J,source:"legacy"})}let O={items:[..._.items,...A]};return{stats:{current_items:_.items.length,legacy_items:$.items.length,duplicate_ids_identical:E,duplicate_ids_conflicting:j,short_id_conflicts:N,stranded_items:A.length,merged_items:U.length===0?A.length:0,expected_total_items:_.items.length+A.length,final_items:null},conflicts:U,mergedStore:O}}function RH(_,$){let D=[...new Set(_)].sort(),I=(U)=>{if(U>=D.length)return $();return y$(D[U],()=>I(U+1),{createParent:!0})};return I(0)}function pR(_){let $=_.now??new Date,D=_.approveWrite!==!0,I=m_(_.legacy),U=m_(_.current),E={legacy_exists:I.exists,legacy_store_exists:H$(_.legacy.jsonStorePath),current_store_exists:H$(_.current.jsonStorePath),approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},j=[];if(!I.exists||!E.legacy_store_exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:I,current_before:U,backup_after:null,current_after:U,merge:{current_items:l4(_.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:l4(_.current.jsonStorePath).items.length,final_items:U.json_items},conflicts:[],checks:{...E,no_conflicts:!0,final_count_matches_expected:!0},warnings:j,message:`No legacy knowledge JSON store found at ${_.legacy.jsonStorePath}`};let N=l4(_.current.jsonStorePath),A=l4(_.legacy.jsonStorePath),O=tR(N,A);if(E.no_conflicts=O.conflicts.length===0,O.conflicts.length>0)j.push("merge_conflicts_detected");if(!E.approval_present)j.push("write_approval_required");if(D||!E.approval_present||O.conflicts.length>0)return{ok:O.conflicts.length===0,dry_run:!0,approval_required:!E.approval_present,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.merge-backup-${EN($)}`,legacy_before:I,current_before:U,backup_after:null,current_after:null,merge:O.stats,conflicts:O.conflicts,checks:E,warnings:j,message:O.conflicts.length===0?`Dry run: would merge ${O.stats.stranded_items} legacy item(s) into ${_.current.jsonStorePath}`:`Refusing legacy merge with ${O.conflicts.length} conflict(s)`};return RH([_.current.jsonStorePath,_.legacy.jsonStorePath],()=>{let S=l4(_.current.jsonStorePath),L=l4(_.legacy.jsonStorePath),P=tR(S,L);if(E.no_conflicts=P.conflicts.length===0,P.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:m_(_.legacy),current_before:m_(_.current),backup_after:null,current_after:null,merge:P.stats,conflicts:P.conflicts,checks:E,warnings:[...j,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${P.conflicts.length} conflict(s)`};if(P.stats.stranded_items===0)return P.stats.final_items=S.items.length,E.final_count_matches_expected=S.items.length===P.stats.expected_total_items,{ok:E.no_conflicts&&E.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:m_(_.legacy),current_before:m_(_.current),backup_after:null,current_after:m_(_.current),merge:P.stats,conflicts:[],checks:E,warnings:j,message:`Legacy merge already up to date for ${_.current.jsonStorePath}`};let z=`${_.legacy.home}.merge-backup-${EN($)}`;IN(CW(z),{recursive:!0}),fW(_.legacy.home,z,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let G=j$(z),J=m_(G);if(E.legacy_backup_written=wW(m_(_.legacy),J),!E.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${z}`);_6(_.current.jsonStorePath,P.mergedStore);let W=l4(_.current.jsonStorePath);P.stats.final_items=W.items.length,E.final_count_matches_expected=W.items.length===P.stats.expected_total_items;let X=m_(_.current),R=E.legacy_backup_written&&E.no_conflicts&&E.final_count_matches_expected;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:z,legacy_before:I,current_before:U,backup_after:J,current_after:X,merge:P.stats,conflicts:[],checks:E,warnings:j,message:R?`Merged ${P.stats.merged_items} legacy item(s) into ${_.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${_.current.jsonStorePath}`}})}function YH(_){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,_)}function uW(_){return _ instanceof Error&&/\b(EBUSY|EPERM)\b/.test(_.message)}function QH(_){let $;for(let D=0;D<8;D+=1)try{jN(_,{recursive:!0,force:!1});return}catch(I){if($=I,!uW(I))throw I;YH(50*(D+1))}throw $}function eR(_){if(!H$(_))return;let $=oR(_);if(qW(_,$.isDirectory()?448:384),!$.isDirectory())return;for(let D of xW(_))eR(R6(_,D))}function KH(_){return _==="TOMBSTONE.md"||_==="migration.json"||_==="knowledge.db"||_==="knowledge.db-shm"||_==="knowledge.db-wal"||_==="knowledge.db-journal"}function TH(_){for(let $ of xW(_)){if($==="TOMBSTONE.md"||$==="migration.json")continue;try{jN(R6(_,$),{recursive:!0,force:!1})}catch(D){if(!uW(D)||!$.startsWith("knowledge.db"))throw D}}}function FH(_,$){try{WH(_,$);return}catch(D){fW(_,$,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{QH(_)}catch(I){if(uW(I)){TH(_);return}throw jN($,{recursive:!0,force:!0}),I}if(D instanceof Error&&D.message.includes("EXDEV"))return}}function VH(_,$,D){if(!$.exists)return!1;if(!$.files.includes("TOMBSTONE.md")||!$.files.includes("migration.json"))return!1;if($.files.some((I)=>!KH(I)))return!1;try{let I=JSON.parse(z1(R6(_.home,"migration.json"),"utf8"));return I.new_path===D&&typeof I.backup_path==="string"}catch{return!1}}function aR(_){let $=_.now??new Date,D=_.approveWrite!==!0,I=m_(_.current),U=GH(_.current,I),E=_.approveWrite===!0&&Boolean(_.approvedBy)&&(!I.exists||U),j=m_(_.legacy,{includeSqlite:!E}),N={legacy_exists:j.exists,current_absent_or_default_scaffold:!I.exists||U,approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},A=[];if(!j.exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:null,legacy_before:j,current_before:I,backup_after:null,current_after:null,checks:N,warnings:A,message:`No legacy knowledge workspace found at ${_.legacy.home}`};if(N.legacy_is_tombstone=VH(_.legacy,j,_.current.home),N.legacy_is_tombstone)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:R6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:I,backup_after:null,current_after:I,checks:{...N,tombstone_written:!0},warnings:A,message:`Legacy knowledge workspace already migrated to ${_.current.home}`};if(!N.current_absent_or_default_scaffold)A.push("current_workspace_contains_data");if(!N.approval_present)A.push("write_approval_required");if(D||!N.current_absent_or_default_scaffold||!N.approval_present)return{ok:N.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-${EN($)}`,tombstone_path:R6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:I,backup_after:null,current_after:null,checks:N,warnings:A,message:N.current_absent_or_default_scaffold?`Dry run: would migrate ${_.legacy.home} to ${_.current.home}`:`Cannot migrate while ${_.current.home} contains data`};let O=`${_.legacy.home}.backup-${EN($)}`;IN(CW(_.current.home),{recursive:!0}),IN(CW(O),{recursive:!0}),fW(_.legacy.home,O,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),eR(O);let S=j$(O),L=m_(S,{includeSqlite:!1});if(N.backup_matches_legacy=wW(j,L),!N.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${O}`);if(I.exists&&U)jN(_.current.home,{recursive:!0,force:!0});FH(_.legacy.home,_.current.home);let P=m_(_.current,{includeSqlite:!1});N.migrated_matches_backup=wW(L,P);let z=m_(S),G=m_(_.current),J={...z,path:_.legacy.home};IN(_.legacy.home,{recursive:!0});let W=R6(_.legacy.home,"TOMBSTONE.md");mR(W,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${$.toISOString()}`,`Approved by: ${_.approvedBy}`,`New path: ${_.current.home}`,`Backup path: ${O}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` -`),{mode:384}),qW(W,384);let X=R6(_.legacy.home,"migration.json");mR(X,`${JSON.stringify({migrated_at:$.toISOString(),approved_by:_.approvedBy,new_path:_.current.home,backup_path:O,legacy_before:J,backup_after:z,current_after:G},null,2)} -`,{mode:384}),qW(X,384),N.tombstone_written=H$(W);let R=N.backup_matches_legacy&&N.migrated_matches_backup&&N.tombstone_written;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:O,tombstone_path:W,legacy_before:J,current_before:I,backup_after:z,current_after:G,checks:N,warnings:A,message:R?`Migrated legacy knowledge workspace to ${_.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${_.current.home}`}}import{createHash as D9}from"crypto";import{Database as BH}from"bun:sqlite";var k$="knowledge.project-registration.v1",sR="knowledge.project-resources.v1",MH=1,ND="explicit_collection_binding";class a extends Error{code;details;constructor(_,$,D={}){super($);this.code=_;this.details=D;this.name="KnowledgeProjectLinksError"}}class U9{db;tail=Promise.resolve();closed=!1;constructor(_){this.db=_}async close(){if(await this.tail,this.closed)return;this.closed=!0,this.db.close()}async get(_,$=[]){return this.db.query(_).get(...$)??null}async many(_,$=[]){return this.db.query(_).all(...$)}async run(_,$=[]){let D=this.db.query(_).run(...$);return{changes:Number(D.changes)}}transaction(_){let $=this.tail.then(async()=>{this.db.exec("BEGIN IMMEDIATE");try{let D=await _(this);return this.db.exec("COMMIT"),D}catch(D){throw this.db.exec("ROLLBACK"),D}});return this.tail=$.then(()=>{return},()=>{return}),$}}function bH(){return` + updated_at = excluded.updated_at`,[j,"wiki/README.md","Wiki",E.uri,E.hash??null,"active",JSON.stringify({artifact_key:E.key,provenance:bP(E)}),I,I]),Jb(_,j,"Wiki",E,cR(),I)}}import{createHash as mR}from"crypto";import{cpSync as fP,chmodSync as kP,existsSync as b$,lstatSync as pR,mkdirSync as EN,readdirSync as xP,readFileSync as g1,renameSync as Pb,rmSync as NN,writeFileSync as lR}from"fs";import{dirname as CP,join as R6,relative as zb}from"path";function vP(_,$=_){if(!b$(_))return[];let D=pR(_);if(D.isFile())return[zb($,_)||"."];if(!D.isDirectory())return[];return xP(_).flatMap((I)=>vP(R6(_,I),$)).sort()}function iR(_,$){if($.length===0)return{sha256:null,bytes:0};let D=mR("sha256"),I=0;for(let U of $){let E=R6(_,U),j=g1(E),N=mR("sha256").update(j).digest("hex");I+=j.byteLength,D.update(U),D.update("\x00"),D.update(N),D.update("\x00")}return{sha256:D.digest("hex"),bytes:I}}function gb(_){if(!b$(_))return null;let $=JSON.parse(g1(_,"utf8"));return Array.isArray($.items)?$.items.length:null}function Xb(_){if(!b$(_))return{exists:!1,integrity_check:null,table_counts:{}};let $=f3(_);try{let D=$.query("PRAGMA integrity_check").get(),I=D?Object.values(D)[0]??null:null,U=$.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),E={};for(let j of U){let N=`"${j.name.replaceAll('"','""')}"`,O=$.query(`SELECT COUNT(*) AS n FROM ${N}`).get();E[j.name]=O?.n??0}return{exists:!0,integrity_check:I,table_counts:E}}finally{$.close()}}function m_(_,$={}){let D=vP(_.home),I=iR(_.home,D),U=vP(_.artifactsDir),E=iR(_.artifactsDir,U),j=b$(_.knowledgeDbPath);return{path:_.home,exists:b$(_.home),file_count:D.length,total_bytes:I.bytes,tree_sha256:I.sha256,json_items:gb(_.jsonStorePath),sqlite:$.includeSqlite===!1?{exists:j,integrity_check:null,table_counts:{}}:Xb(_.knowledgeDbPath),artifacts:{exists:b$(_.artifactsDir),file_count:U.length,total_bytes:E.bytes,tree_sha256:E.sha256},files:D}}function Gb(_,$){if(!$.exists)return!0;if($.files.filter((I)=>I!=="config.json").length>0)return!1;if(!$.files.includes("config.json"))return!0;try{return JSON.stringify(JSON.parse(g1(_.configPath,"utf8")))===JSON.stringify(vD())}catch{return!1}}function wP(_,$){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 jN(_){return _.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"Z")}function rP(_){if(Array.isArray(_))return`[${_.map(rP).join(",")}]`;if(_&&typeof _==="object")return`{${Object.entries(_).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>`${JSON.stringify($)}:${rP(D)}`).join(",")}}`;return JSON.stringify(_)}function tR(_){return rP(_)}function qP(_){return typeof _.short_id==="string"&&_.short_id.trim().length>0?_.short_id:null}function i4(_){if(!b$(_))return{items:[]};let $=JSON.parse(g1(_,"utf8"));if(!$||!Array.isArray($.items))throw Error(`Invalid knowledge JSON store shape at ${_}`);return{items:$.items}}function oR(_,$){let D=new Map(_.items.map((L)=>[L.id,L])),I=new Map;for(let L of _.items){let W=I.get(L.id);if(W&&W.item.id!==L.id);I.set(L.id,{item:L,keyKind:"id",source:"current"});let g=qP(L);if(g&&!I.has(g))I.set(g,{item:L,keyKind:"short_id",source:"current"})}let U=[],E=0,j=0,N=0,O=[];for(let L of $.items){let W=D.get(L.id);if(W){if(tR(W)===tR(L))E+=1;else j+=1,U.push({type:"id_conflict",id:L.id,legacy_title:L.title,current_title:W.title});continue}let g=[{key:L.id,keyKind:"id"},...qP(L)?[{key:qP(L),keyKind:"short_id"}]:[]],z=!1;for(let{key:G,keyKind:J}of g){let P=I.get(G);if(!P)continue;if(J==="id"&&P.keyKind==="id")j+=1,U.push({type:"id_conflict",id:G,legacy_id:L.id,current_id:P.item.id,legacy_title:L.title,current_title:P.item.title});else N+=1,U.push({type:"short_id_conflict",id:G,legacy_id:L.id,current_id:P.item.id,legacy_title:L.title,current_title:P.item.title});z=!0}if(z)continue;O.push(L);for(let{key:G,keyKind:J}of g)I.set(G,{item:L,keyKind:J,source:"legacy"})}let S={items:[..._.items,...O]};return{stats:{current_items:_.items.length,legacy_items:$.items.length,duplicate_ids_identical:E,duplicate_ids_conflicting:j,short_id_conflicts:N,stranded_items:O.length,merged_items:U.length===0?O.length:0,expected_total_items:_.items.length+O.length,final_items:null},conflicts:U,mergedStore:S}}function Rb(_,$){let D=[...new Set(_)].sort(),I=(U)=>{if(U>=D.length)return $();return y$(D[U],()=>I(U+1),{createParent:!0})};return I(0)}function eR(_){let $=_.now??new Date,D=_.approveWrite!==!0,I=m_(_.legacy),U=m_(_.current),E={legacy_exists:I.exists,legacy_store_exists:b$(_.legacy.jsonStorePath),current_store_exists:b$(_.current.jsonStorePath),approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_backup_written:!1,no_conflicts:!1,final_count_matches_expected:!1},j=[];if(!I.exists||!E.legacy_store_exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,legacy_before:I,current_before:U,backup_after:null,current_after:U,merge:{current_items:i4(_.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:i4(_.current.jsonStorePath).items.length,final_items:U.json_items},conflicts:[],checks:{...E,no_conflicts:!0,final_count_matches_expected:!0},warnings:j,message:`No legacy knowledge JSON store found at ${_.legacy.jsonStorePath}`};let N=i4(_.current.jsonStorePath),O=i4(_.legacy.jsonStorePath),S=oR(N,O);if(E.no_conflicts=S.conflicts.length===0,S.conflicts.length>0)j.push("merge_conflicts_detected");if(!E.approval_present)j.push("write_approval_required");if(D||!E.approval_present||S.conflicts.length>0)return{ok:S.conflicts.length===0,dry_run:!0,approval_required:!E.approval_present,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:`${_.legacy.home}.merge-backup-${jN($)}`,legacy_before:I,current_before:U,backup_after:null,current_after:null,merge:S.stats,conflicts:S.conflicts,checks:E,warnings:j,message:S.conflicts.length===0?`Dry run: would merge ${S.stats.stranded_items} legacy item(s) into ${_.current.jsonStorePath}`:`Refusing legacy merge with ${S.conflicts.length} conflict(s)`};return Rb([_.current.jsonStorePath,_.legacy.jsonStorePath],()=>{let L=i4(_.current.jsonStorePath),W=i4(_.legacy.jsonStorePath),g=oR(L,W);if(E.no_conflicts=g.conflicts.length===0,g.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:m_(_.legacy),current_before:m_(_.current),backup_after:null,current_after:null,merge:g.stats,conflicts:g.conflicts,checks:E,warnings:[...j,"merge_conflicts_detected_after_lock"],message:`Refusing legacy merge with ${g.conflicts.length} conflict(s)`};if(g.stats.stranded_items===0)return g.stats.final_items=L.items.length,E.final_count_matches_expected=L.items.length===g.stats.expected_total_items,{ok:E.no_conflicts&&E.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:m_(_.legacy),current_before:m_(_.current),backup_after:null,current_after:m_(_.current),merge:g.stats,conflicts:[],checks:E,warnings:j,message:`Legacy merge already up to date for ${_.current.jsonStorePath}`};let z=`${_.legacy.home}.merge-backup-${jN($)}`;EN(CP(z),{recursive:!0}),fP(_.legacy.home,z,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});let G=j$(z),J=m_(G);if(E.legacy_backup_written=wP(m_(_.legacy),J),!E.legacy_backup_written)throw Error(`Legacy knowledge merge backup verification failed: ${z}`);_6(_.current.jsonStorePath,g.mergedStore);let P=i4(_.current.jsonStorePath);g.stats.final_items=P.items.length,E.final_count_matches_expected=P.items.length===g.stats.expected_total_items;let X=m_(_.current),R=E.legacy_backup_written&&E.no_conflicts&&E.final_count_matches_expected;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:z,legacy_before:I,current_before:U,backup_after:J,current_after:X,merge:g.stats,conflicts:[],checks:E,warnings:j,message:R?`Merged ${g.stats.merged_items} legacy item(s) into ${_.current.jsonStorePath}`:`Merged legacy knowledge store, but verification failed for ${_.current.jsonStorePath}`}})}function Yb(_){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,_)}function uP(_){return _ instanceof Error&&/\b(EBUSY|EPERM)\b/.test(_.message)}function Qb(_){let $;for(let D=0;D<8;D+=1)try{NN(_,{recursive:!0,force:!1});return}catch(I){if($=I,!uP(I))throw I;Yb(50*(D+1))}throw $}function aR(_){if(!b$(_))return;let $=pR(_);if(kP(_,$.isDirectory()?448:384),!$.isDirectory())return;for(let D of xP(_))aR(R6(_,D))}function Kb(_){return _==="TOMBSTONE.md"||_==="migration.json"||_==="knowledge.db"||_==="knowledge.db-shm"||_==="knowledge.db-wal"||_==="knowledge.db-journal"}function Tb(_){for(let $ of xP(_)){if($==="TOMBSTONE.md"||$==="migration.json")continue;try{NN(R6(_,$),{recursive:!0,force:!1})}catch(D){if(!uP(D)||!$.startsWith("knowledge.db"))throw D}}}function Fb(_,$){try{Pb(_,$);return}catch(D){fP(_,$,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0});try{Qb(_)}catch(I){if(uP(I)){Tb(_);return}throw NN($,{recursive:!0,force:!0}),I}if(D instanceof Error&&D.message.includes("EXDEV"))return}}function Vb(_,$,D){if(!$.exists)return!1;if(!$.files.includes("TOMBSTONE.md")||!$.files.includes("migration.json"))return!1;if($.files.some((I)=>!Kb(I)))return!1;try{let I=JSON.parse(g1(R6(_.home,"migration.json"),"utf8"));return I.new_path===D&&typeof I.backup_path==="string"}catch{return!1}}function sR(_){let $=_.now??new Date,D=_.approveWrite!==!0,I=m_(_.current),U=Gb(_.current,I),E=_.approveWrite===!0&&Boolean(_.approvedBy)&&(!I.exists||U),j=m_(_.legacy,{includeSqlite:!E}),N={legacy_exists:j.exists,current_absent_or_default_scaffold:!I.exists||U,approval_present:_.approveWrite===!0&&Boolean(_.approvedBy),legacy_is_tombstone:!1,backup_matches_legacy:!1,migrated_matches_backup:!1,tombstone_written:!1},O=[];if(!j.exists)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:null,legacy_before:j,current_before:I,backup_after:null,current_after:null,checks:N,warnings:O,message:`No legacy knowledge workspace found at ${_.legacy.home}`};if(N.legacy_is_tombstone=Vb(_.legacy,j,_.current.home),N.legacy_is_tombstone)return{ok:!0,dry_run:D,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:null,tombstone_path:R6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:I,backup_after:null,current_after:I,checks:{...N,tombstone_written:!0},warnings:O,message:`Legacy knowledge workspace already migrated to ${_.current.home}`};if(!N.current_absent_or_default_scaffold)O.push("current_workspace_contains_data");if(!N.approval_present)O.push("write_approval_required");if(D||!N.current_absent_or_default_scaffold||!N.approval_present)return{ok:N.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-${jN($)}`,tombstone_path:R6(_.legacy.home,"TOMBSTONE.md"),legacy_before:j,current_before:I,backup_after:null,current_after:null,checks:N,warnings:O,message:N.current_absent_or_default_scaffold?`Dry run: would migrate ${_.legacy.home} to ${_.current.home}`:`Cannot migrate while ${_.current.home} contains data`};let S=`${_.legacy.home}.backup-${jN($)}`;EN(CP(_.current.home),{recursive:!0}),EN(CP(S),{recursive:!0}),fP(_.legacy.home,S,{recursive:!0,force:!1,errorOnExist:!0,preserveTimestamps:!0}),aR(S);let L=j$(S),W=m_(L,{includeSqlite:!1});if(N.backup_matches_legacy=wP(j,W),!N.backup_matches_legacy)throw Error(`Legacy knowledge backup verification failed: ${S}`);if(I.exists&&U)NN(_.current.home,{recursive:!0,force:!0});Fb(_.legacy.home,_.current.home);let g=m_(_.current,{includeSqlite:!1});N.migrated_matches_backup=wP(W,g);let z=m_(L),G=m_(_.current),J={...z,path:_.legacy.home};EN(_.legacy.home,{recursive:!0});let P=R6(_.legacy.home,"TOMBSTONE.md");lR(P,["# Migrated OpenKnowledge Workspace","",`Migrated at: ${$.toISOString()}`,`Approved by: ${_.approvedBy}`,`New path: ${_.current.home}`,`Backup path: ${S}`,"","This directory is a diagnostic tombstone only. OpenKnowledge reads and writes the canonical .hasna/knowledge workspace.",""].join(` +`),{mode:384}),kP(P,384);let X=R6(_.legacy.home,"migration.json");lR(X,`${JSON.stringify({migrated_at:$.toISOString(),approved_by:_.approvedBy,new_path:_.current.home,backup_path:S,legacy_before:J,backup_after:z,current_after:G},null,2)} +`,{mode:384}),kP(X,384),N.tombstone_written=b$(P);let R=N.backup_matches_legacy&&N.migrated_matches_backup&&N.tombstone_written;return{ok:R,dry_run:!1,approval_required:!1,scope:_.scope,current_home:_.current.home,legacy_home:_.legacy.home,backup_home:S,tombstone_path:P,legacy_before:J,current_before:I,backup_after:z,current_after:G,checks:N,warnings:O,message:R?`Migrated legacy knowledge workspace to ${_.current.home}`:`Migrated legacy knowledge workspace, but verification failed for ${_.current.home}`}}import{createHash as D9}from"crypto";var q$="knowledge.project-registration.v1",yP="knowledge.project-resources.v1",Bb=1,t4="explicit_collection_binding",Mb=1;class o extends Error{code;details;constructor(_,$,D={}){super($);this.code=_;this.details=D;this.name="KnowledgeProjectLinksError"}}class U9{db;kind="sqlite";tail=Promise.resolve();closed=!1;constructor(_){this.db=_}async close(){if(await this.tail,this.closed)return;this.closed=!0,this.db.close()}async get(_,$=[]){return this.db.query(_).get(...$)??null}async many(_,$=[]){return this.db.query(_).all(...$)}async run(_,$=[]){let D=this.db.query(_).run(...$);return{changes:Number(D.changes)}}async lock(_){}transaction(_){let $=this.tail.then(async()=>{this.db.exec("BEGIN IMMEDIATE");try{let D=await _(this);return this.db.exec("COMMIT"),D}catch(D){throw this.db.exec("ROLLBACK"),D}});return this.tail=$.then(()=>{return},()=>{return}),$}}function Zb(){return` PRAGMA foreign_keys = ON; CREATE TABLE IF NOT EXISTS knowledge_projects ( authority_id TEXT NOT NULL, @@ -1331,13 +1331,13 @@ Pages should be concise, cited, and organized for both humans and agents. $$`,`DROP TRIGGER IF EXISTS knowledge_project_link_receipts_immutable ON knowledge_project_link_receipts`,`CREATE TRIGGER knowledge_project_link_receipts_immutable BEFORE UPDATE OR DELETE ON knowledge_project_link_receipts - FOR EACH ROW EXECUTE FUNCTION knowledge_project_link_receipts_immutable()`]}function yW(_){if(Array.isArray(_))return _.map(yW);if(_&&typeof _==="object")return Object.fromEntries(Object.entries(_).filter(([,$])=>$!==void 0).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>[$,yW(D)]));return _}function gD(_){return JSON.stringify(yW(_))}function v_(_){return D9("sha256").update(gD(_)).digest("hex")}function NN(_){let $=D9("sha256").update(_).digest("hex").slice(0,32).split("");$[12]="5",$[16]=(Number.parseInt($[16],16)&3|8).toString(16);let D=$.join("");return`${D.slice(0,8)}-${D.slice(8,12)}-${D.slice(12,16)}-${D.slice(16,20)}-${D.slice(20)}`}function k_(_,$){if(typeof _!=="string"||_.trim().length===0)throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT",`${$} must be a non-empty string.`);return _.trim()}function ZH(_){let $=_??100;if(!Number.isInteger($)||$<1||$>200)throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","limit must be an integer between 1 and 200.");return $}function HH(_){let $=["project","collection","item","taxonomy"];if(!_||_.length===0)return $;let D=[...new Set(_)];for(let I of D)if(!$.includes(I))throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT",`unsupported project resource kind: ${I}`);return D.sort((I,U)=>$.indexOf(I)-$.indexOf(U))}function _9(_){return{receipt_id:_.receipt_id,authority:"knowledge",route:k$,package_version:_.package_version,authority_id:_.authority_id,tenant_id:_.tenant_id,corpus_id:_.corpus_id,operation_id:_.operation_id,step_id:_.step_id,action:_.action,resource_kind:_.resource_kind,direction:_.direction,idempotency_key:_.idempotency_key,request_digest:_.request_digest,precondition_digest:_.precondition_digest,outcome:_.outcome,reason:_.reason,source_project_id:_.source_project_id,project_id:_.project_id,collection_id:_.collection_id,item_id:_.item_id,result_revision:_.result_revision,result_digest:_.result_digest,accepted_receipt_id:_.accepted_receipt_id,created_by_operation:Number(_.created_by_operation)===1,created_at:_.created_at}}function $9(_){let $={source_project_id:_.source_project_id,project_id:_.project_id,project_slug:_.project_slug,project_name:_.project_name,collection_id:_.collection_id,collection_slug:_.collection_slug,collection_name:_.collection_name,membership_rule:ND,revision:`r${Number(_.revision)}`,created_at:_.created_at,updated_at:_.updated_at};return{...$,digest:v_($)}}function gN(_){return[_.receipt_id,_.authority,_.route,_.package_version,_.authority_id,_.tenant_id,_.corpus_id,_.operation_id,_.step_id,_.action,_.resource_kind,_.direction,_.idempotency_key,_.request_digest,_.precondition_digest,_.outcome,_.reason,_.source_project_id,_.project_id,_.collection_id,_.item_id,_.result_revision,_.result_digest,_.accepted_receipt_id,_.created_by_operation?1:0,_.created_at]}var AN=`INSERT INTO knowledge_project_link_receipts ( + FOR EACH ROW EXECUTE FUNCTION knowledge_project_link_receipts_immutable()`]}function hP(_){if(Array.isArray(_))return _.map(hP);if(_&&typeof _==="object")return Object.fromEntries(Object.entries(_).filter(([,$])=>$!==void 0).sort(([$],[D])=>$.localeCompare(D)).map(([$,D])=>[$,hP(D)]));return _}function p6(_){return JSON.stringify(hP(_))}function V_(_){return D9("sha256").update(p6(_)).digest("hex")}function X1(_){let $=D9("sha256").update(_).digest("hex").slice(0,32).split("");$[12]="5",$[16]=(Number.parseInt($[16],16)&3|8).toString(16);let D=$.join("");return`${D.slice(0,8)}-${D.slice(8,12)}-${D.slice(12,16)}-${D.slice(16,20)}-${D.slice(20)}`}function k_(_,$){if(typeof _!=="string"||_.trim().length===0)throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT",`${$} must be a non-empty string.`);return _.trim()}function Hb(_){let $=_??100;if(!Number.isInteger($)||$<1||$>200)throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","limit must be an integer between 1 and 200.");return $}function bb(_){let $=["project","collection","item","taxonomy"];if(!_||_.length===0)return $;let D=[...new Set(_)];for(let I of D)if(!$.includes(I))throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT",`unsupported project resource kind: ${I}`);return D.sort((I,U)=>$.indexOf(I)-$.indexOf(U))}function _9(_){return{receipt_id:_.receipt_id,authority:"knowledge",route:q$,package_version:_.package_version,authority_id:_.authority_id,tenant_id:_.tenant_id,corpus_id:_.corpus_id,operation_id:_.operation_id,step_id:_.step_id,action:_.action,resource_kind:_.resource_kind,direction:_.direction,idempotency_key:_.idempotency_key,request_digest:_.request_digest,precondition_digest:_.precondition_digest,outcome:_.outcome,reason:_.reason,source_project_id:_.source_project_id,project_id:_.project_id,collection_id:_.collection_id,item_id:_.item_id,result_revision:_.result_revision,result_digest:_.result_digest,accepted_receipt_id:_.accepted_receipt_id,created_by_operation:Number(_.created_by_operation)===1,created_at:_.created_at}}function $9(_){let $={source_project_id:_.source_project_id,project_id:_.project_id,project_slug:_.project_slug,project_name:_.project_name,collection_id:_.collection_id,collection_slug:_.collection_slug,collection_name:_.collection_name,membership_rule:t4,revision:`r${Number(_.revision)}`,created_at:_.created_at,updated_at:_.updated_at};return{...$,digest:V_($)}}function AN(_){return[_.receipt_id,_.authority,_.route,_.package_version,_.authority_id,_.tenant_id,_.corpus_id,_.operation_id,_.step_id,_.action,_.resource_kind,_.direction,_.idempotency_key,_.request_digest,_.precondition_digest,_.outcome,_.reason,_.source_project_id,_.project_id,_.collection_id,_.item_id,_.result_revision,_.result_digest,_.accepted_receipt_id,_.created_by_operation?1:0,_.created_at]}var ON=`INSERT INTO knowledge_project_link_receipts ( receipt_id, authority, route, package_version, authority_id, tenant_id, corpus_id, operation_id, step_id, action, resource_kind, direction, idempotency_key, request_digest, precondition_digest, outcome, reason, source_project_id, project_id, collection_id, item_id, result_revision, result_digest, accepted_receipt_id, created_by_operation, created_at -) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`;class E9{sql;itemResolver;options;identity;now;constructor(_,$,D){this.sql=_;this.itemResolver=$;this.options=D;this.identity={authority_id:k_(D.authorityId,"authority_id"),tenant_id:k_(D.tenantId,"tenant_id"),corpus_id:k_(D.corpusId,"corpus_id")},this.now=D.now??(()=>new Date().toISOString())}async close(){await this.sql.close()}capabilityValue(){return{authority:"knowledge",route:k$,resource_route:sR,package_version:this.options.packageVersion,schema_version:MH,...this.identity,registration_resource:"collection",supported_resources:["project","collection","item","taxonomy"],stable_project_ids:!0,stable_collection_ids:!0,explicit_membership:!0,membership_rule:ND,later_child_binding_required:!0,bind_existing_items:!0,immutable_receipts:!0,exact_terminal_lookup:!0,exact_readback:!0,conditional_inverse:!0,complete_keyset_pagination:!0,revision_bound_cursors:!0}}async capability(){return this.capabilityValue()}assertIdentity(_){let $=this.capabilityValue();if(_.authority_route!==$.route||_.package_version!==$.package_version||_.authority_id!==$.authority_id||_.tenant_id!==$.tenant_id||_.corpus_id!==$.corpus_id)throw new a("KNOWLEDGE_PROJECT_LINKS_CAPABILITY_MISMATCH","request does not match the current Knowledge project-registration capability identity.")}stableProjectId(_){return NN(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00project\x00${_}`)}stableCollectionId(_,$){return NN(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00collection\x00${_}\x00${$}`)}stableReceiptId(_,$,D,I){return NN(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00receipt\x00${_}\x00${$}\x00${D}\x00${I}`)}async getAggregateBySource(_,$){return _.get(`SELECT p.source_project_id, p.project_id, p.project_slug, p.project_name, +) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`;class E9{sql;itemResolver;options;identity;now;constructor(_,$,D){this.sql=_;this.itemResolver=$;this.options=D;this.identity={authority_id:k_(D.authorityId,"authority_id"),tenant_id:k_(D.tenantId,"tenant_id"),corpus_id:k_(D.corpusId,"corpus_id")},this.now=D.now??(()=>new Date().toISOString())}async close(){await this.sql.close()}capabilityValue(){return{authority:"knowledge",route:q$,resource_route:yP,package_version:this.options.packageVersion,schema_version:Bb,...this.identity,registration_resource:"collection",supported_resources:["project","collection","item","taxonomy"],stable_project_ids:!0,stable_collection_ids:!0,explicit_membership:!0,membership_rule:t4,later_child_binding_required:!0,bind_existing_items:!0,immutable_receipts:!0,exact_terminal_lookup:!0,exact_readback:!0,conditional_inverse:!0,complete_keyset_pagination:!0,revision_bound_cursors:!0}}async capability(){return this.capabilityValue()}assertIdentity(_){let $=this.capabilityValue();if(_.authority_route!==$.route||_.package_version!==$.package_version||_.authority_id!==$.authority_id||_.tenant_id!==$.tenant_id||_.corpus_id!==$.corpus_id)throw new o("KNOWLEDGE_PROJECT_LINKS_CAPABILITY_MISMATCH","request does not match the current Knowledge project-registration capability identity.")}stableProjectId(_){return X1(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00project\x00${_}`)}stableCollectionId(_,$){return X1(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00collection\x00${_}\x00${$}`)}collectionFence(_){return["knowledge-project-links",this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,"collection",_].join("\x1F")}membershipFence(_,$){return["knowledge-project-links",this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,"membership",_,$].join("\x1F")}stableReceiptId(_,$,D,I){return X1(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00receipt\x00${_}\x00${$}\x00${D}\x00${I}`)}async getAggregateBySource(_,$){return _.get(`SELECT p.source_project_id, p.project_id, p.project_slug, p.project_name, c.collection_id, c.collection_slug, c.collection_name, c.membership_rule, c.revision, c.created_at, c.updated_at FROM knowledge_projects p @@ -1369,23 +1369,23 @@ Pages should be concise, cited, and organized for both humans and agents. WHERE p.authority_id = ? AND p.tenant_id = ? AND p.corpus_id = ? AND (p.source_project_id = ? OR p.project_id = ?)`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$,$])}async getReceiptByAttempt(_,$){let D=await _.get(`SELECT * FROM knowledge_project_link_receipts WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? - AND operation_id = ? AND step_id = ? AND action = ? AND direction = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.operation_id,$.step_id,$.action,$.direction]);return D?_9(D):null}assertIdempotent(_,$){if(_.idempotency_key!==$.idempotency_key||$.request_digest!==void 0&&_.request_digest!==$.request_digest||$.precondition_digest!==void 0&&_.precondition_digest!==$.precondition_digest||$.accepted_receipt_id!==void 0&&_.accepted_receipt_id!==$.accepted_receipt_id)throw new a("KNOWLEDGE_PROJECT_LINKS_IDEMPOTENCY_MISMATCH","operation and step identity are already bound to a different Knowledge project-link request.",{receipt_id:_.receipt_id})}async registerCollection(_){if(this.assertIdentity(_),_.resource_kind!=="collection"||_.direction!=="forward")throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","collection registration requires resource_kind=collection and direction=forward.");let $=k_(_.project_id,"project_id"),D=k_(_.project_slug,"project_slug"),I=k_(_.project_name,"project_name");if(k_(_.target_selector,"target_selector")!==$)throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","target_selector must equal the exact source project id.");let E=k_(_.desired.collection_slug??`${D}-knowledge`,"desired.collection_slug"),j=k_(_.desired.collection_name??`${I} Knowledge`,"desired.collection_name"),N=v_({action:"register_collection",source_project_id:$,project_slug:D,project_name:I,collection_slug:E,collection_name:j,membership_rule:ND});if(_.request_digest!==N)throw new a("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH","request_digest does not bind the normalized collection-registration request.",{expected_request_digest:N});return this.sql.transaction(async(A)=>{let O=await this.getReceiptByAttempt(A,{operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",direction:"forward"});if(O)return this.assertIdempotent(O,_),O;let S=await this.getAggregateBySource(A,$),L=S===null;if(!S){let G=this.now(),J=this.stableProjectId($),W=this.stableCollectionId($,E);await A.run(`INSERT INTO knowledge_projects ( + AND operation_id = ? AND step_id = ? AND action = ? AND direction = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.operation_id,$.step_id,$.action,$.direction]);return D?_9(D):null}assertIdempotent(_,$){if(_.idempotency_key!==$.idempotency_key||$.request_digest!==void 0&&_.request_digest!==$.request_digest||$.precondition_digest!==void 0&&_.precondition_digest!==$.precondition_digest||$.accepted_receipt_id!==void 0&&_.accepted_receipt_id!==$.accepted_receipt_id)throw new o("KNOWLEDGE_PROJECT_LINKS_IDEMPOTENCY_MISMATCH","operation and step identity are already bound to a different Knowledge project-link request.",{receipt_id:_.receipt_id})}async registerCollection(_){if(this.assertIdentity(_),_.resource_kind!=="collection"||_.direction!=="forward")throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","collection registration requires resource_kind=collection and direction=forward.");let $=k_(_.project_id,"project_id"),D=k_(_.project_slug,"project_slug"),I=k_(_.project_name,"project_name");if(k_(_.target_selector,"target_selector")!==$)throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","target_selector must equal the exact source project id.");let E=k_(_.desired.collection_slug??`${D}-knowledge`,"desired.collection_slug"),j=k_(_.desired.collection_name??`${I} Knowledge`,"desired.collection_name"),N=V_({action:"register_collection",source_project_id:$,project_slug:D,project_name:I,collection_slug:E,collection_name:j,membership_rule:t4});if(_.request_digest!==N)throw new o("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH","request_digest does not bind the normalized collection-registration request.",{expected_request_digest:N});let O=this.stableCollectionId($,E);return this.sql.transaction(async(S)=>{let L=await this.getReceiptByAttempt(S,{operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",direction:"forward"});if(L)return this.assertIdempotent(L,_),L;await S.lock(this.collectionFence(O));let W=await this.getAggregateBySource(S,$),g=W===null;if(!W){let J=this.now(),P=this.stableProjectId($),X=O;await S.run(`INSERT INTO knowledge_projects ( authority_id, tenant_id, corpus_id, source_project_id, project_id, project_slug, project_name, created_at, updated_at - ) VALUES (?,?,?,?,?,?,?,?,?)`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$,J,D,I,G,G]),await A.run(`INSERT INTO knowledge_project_collections ( + ) VALUES (?,?,?,?,?,?,?,?,?)`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$,P,D,I,J,J]),await S.run(`INSERT INTO knowledge_project_collections ( authority_id, tenant_id, corpus_id, collection_id, project_id, collection_slug, collection_name, membership_rule, revision, created_at, updated_at - ) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,W,J,E,j,ND,1,G,G]),S=await this.getAggregateByCollection(A,W)}else if(S.project_slug!==D||S.project_name!==I||S.collection_slug!==E||S.collection_name!==j||S.membership_rule!==ND)throw new a("KNOWLEDGE_PROJECT_LINKS_CONFLICT","the source project is already bound to a different Knowledge collection aggregate.",{source_project_id:$,collection_id:S.collection_id});if(!S)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","collection registration committed but exact aggregate readback was unavailable.");let P=$9(S),z={receipt_id:this.stableReceiptId(_.operation_id,_.step_id,"register_collection","forward"),authority:"knowledge",route:k$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",resource_kind:"collection",direction:"forward",idempotency_key:k_(_.idempotency_key,"idempotency_key"),request_digest:_.request_digest,precondition_digest:k_(_.precondition_digest,"precondition_digest"),outcome:"accepted",reason:L?null:"adopted_existing_collection",source_project_id:P.source_project_id,project_id:P.project_id,collection_id:P.collection_id,item_id:null,result_revision:P.revision,result_digest:P.digest,accepted_receipt_id:null,created_by_operation:L,created_at:this.now()};return await A.run(AN,gN(z)),z})}async readCollection(_){let $=await this.getAggregateByCollection(this.sql,k_(_,"collection_id"));if(!$)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge collection was not found by exact id.");return $9($)}async lookupReceipt(_){if(_.max_items!==1)throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","exact terminal receipt lookup requires max_items=1.");if(_.authority_id!==this.identity.authority_id||_.tenant_id!==this.identity.tenant_id||_.corpus_id!==this.identity.corpus_id)throw new a("KNOWLEDGE_PROJECT_LINKS_CAPABILITY_MISMATCH","receipt lookup does not match this authority identity.");let $=await this.getReceiptByAttempt(this.sql,_);if(!$||$.idempotency_key!==_.idempotency_key)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","exact Knowledge project-link receipt was not found.");return $}async receiptById(_,$){let D=await _.get(`SELECT * FROM knowledge_project_link_receipts + ) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,X,P,E,j,t4,1,J,J]),W=await this.getAggregateByCollection(S,X)}else if(W.project_slug!==D||W.project_name!==I||W.collection_slug!==E||W.collection_name!==j||W.membership_rule!==t4)throw new o("KNOWLEDGE_PROJECT_LINKS_CONFLICT","the source project is already bound to a different Knowledge collection aggregate.",{source_project_id:$,collection_id:W.collection_id});if(!W)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","collection registration committed but exact aggregate readback was unavailable.");let z=$9(W),G={receipt_id:this.stableReceiptId(_.operation_id,_.step_id,"register_collection","forward"),authority:"knowledge",route:q$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",resource_kind:"collection",direction:"forward",idempotency_key:k_(_.idempotency_key,"idempotency_key"),request_digest:_.request_digest,precondition_digest:k_(_.precondition_digest,"precondition_digest"),outcome:"accepted",reason:g?null:"adopted_existing_collection",source_project_id:z.source_project_id,project_id:z.project_id,collection_id:z.collection_id,item_id:null,result_revision:z.revision,result_digest:z.digest,accepted_receipt_id:null,created_by_operation:g,created_at:this.now()};return await S.run(ON,AN(G)),G})}async readCollection(_){let $=await this.getAggregateByCollection(this.sql,k_(_,"collection_id"));if(!$)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge collection was not found by exact id.");return $9($)}async lookupReceipt(_){if(_.max_items!==1)throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","exact terminal receipt lookup requires max_items=1.");if(_.authority_id!==this.identity.authority_id||_.tenant_id!==this.identity.tenant_id||_.corpus_id!==this.identity.corpus_id)throw new o("KNOWLEDGE_PROJECT_LINKS_CAPABILITY_MISMATCH","receipt lookup does not match this authority identity.");let $=await this.getReceiptByAttempt(this.sql,_);if(!$||$.idempotency_key!==_.idempotency_key)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","exact Knowledge project-link receipt was not found.");return $}async receiptById(_,$){let D=await _.get(`SELECT * FROM knowledge_project_link_receipts WHERE receipt_id = ? AND authority_id = ? AND tenant_id = ? AND corpus_id = ?`,[$,this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id]);return D?_9(D):null}async hasOtherAcceptedForwardReceipt(_,$){let D=$.action==="bind_item"?"AND item_id = ?":"AND item_id IS NULL";return await _.get(`SELECT receipt_id FROM knowledge_project_link_receipts WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND action = ? AND direction = 'forward' AND outcome = 'accepted' AND collection_id = ? AND receipt_id <> ? ${D} - LIMIT 1`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.action,$.collection_id,$.receipt_id,...$.action==="bind_item"?[$.item_id]:[]])!==null}assertInverseIdentity(_){this.assertIdentity(_),k_(_.accepted_receipt_id,"accepted_receipt_id"),k_(_.idempotency_key,"idempotency_key")}async compensateRegistration(_){return this.assertInverseIdentity(_),this.sql.transaction(async($)=>{let D=await this.getReceiptByAttempt($,{operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",direction:"inverse"});if(D)return this.assertIdempotent(D,_),D;let I=await this.receiptById($,_.accepted_receipt_id);if(!I||I.action!=="register_collection"||I.direction!=="forward"||I.outcome!=="accepted")throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted collection-registration receipt was not found.");let U=I.collection_id?await this.getAggregateByCollection($,I.collection_id):null,E="accepted",j=null;if(!I.created_by_operation)E="terminal_nonacceptance",j="adopted_collection_is_not_inverse_owned";else if(!U)E="terminal_nonacceptance",j="accepted_collection_is_already_absent";else if(await this.hasOtherAcceptedForwardReceipt($,I))E="terminal_nonacceptance",j="collection_has_later_accepted_adopter";else{let O=await $.get(`SELECT COUNT(*) AS count + LIMIT 1`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.action,$.collection_id,$.receipt_id,...$.action==="bind_item"?[$.item_id]:[]])!==null}assertInverseIdentity(_){this.assertIdentity(_),k_(_.accepted_receipt_id,"accepted_receipt_id"),k_(_.idempotency_key,"idempotency_key")}async compensateRegistration(_){return this.assertInverseIdentity(_),this.sql.transaction(async($)=>{let D=await this.getReceiptByAttempt($,{operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",direction:"inverse"});if(D)return this.assertIdempotent(D,_),D;let I=await this.receiptById($,_.accepted_receipt_id);if(!I||I.action!=="register_collection"||I.direction!=="forward"||I.outcome!=="accepted")throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted collection-registration receipt was not found.");if(I.collection_id)await $.lock(this.collectionFence(I.collection_id));let U=I.collection_id?await this.getAggregateByCollection($,I.collection_id):null,E="accepted",j=null;if(!I.created_by_operation)E="terminal_nonacceptance",j="adopted_collection_is_not_inverse_owned";else if(!U)E="terminal_nonacceptance",j="accepted_collection_is_already_absent";else if(await this.hasOtherAcceptedForwardReceipt($,I))E="terminal_nonacceptance",j="collection_has_later_accepted_adopter";else{let S=await $.get(`SELECT COUNT(*) AS count FROM knowledge_project_collection_memberships - WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,U.collection_id]);if(Number(O?.count??0)>0)E="terminal_nonacceptance",j="collection_has_bound_items";else await $.run(`DELETE FROM knowledge_project_collections + WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,U.collection_id]);if(Number(S?.count??0)>0)E="terminal_nonacceptance",j="collection_has_bound_items";else await $.run(`DELETE FROM knowledge_project_collections WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,U.collection_id]),await $.run(`DELETE FROM knowledge_projects WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND project_id = ? AND NOT EXISTS ( @@ -1394,30 +1394,133 @@ Pages should be concise, cited, and organized for both humans and agents. AND c.tenant_id = knowledge_projects.tenant_id AND c.corpus_id = knowledge_projects.corpus_id AND c.project_id = knowledge_projects.project_id - )`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,U.project_id])}let N={accepted_receipt_id:I.receipt_id,collection_id:I.collection_id,absent:E==="accepted"},A={receipt_id:this.stableReceiptId(_.operation_id,_.step_id,"register_collection","inverse"),authority:"knowledge",route:k$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",resource_kind:"collection",direction:"inverse",idempotency_key:_.idempotency_key,request_digest:v_({accepted_receipt_id:I.receipt_id,collection_id:I.collection_id}),precondition_digest:I.result_digest??"",outcome:E,reason:j,source_project_id:I.source_project_id,project_id:I.project_id,collection_id:I.collection_id,item_id:null,result_revision:E==="accepted"?"absent":I.result_revision,result_digest:v_(N),accepted_receipt_id:I.receipt_id,created_by_operation:!1,created_at:this.now()};return await $.run(AN,gN(A)),A})}async verifyRegistrationInverse(_){this.assertInverseIdentity(_);let $=await this.getReceiptByAttempt(this.sql,{operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",direction:"inverse"});if(!$||$.outcome!=="accepted"||$.accepted_receipt_id!==_.accepted_receipt_id)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted collection inverse receipt was not found.");if($.collection_id?await this.getAggregateByCollection(this.sql,$.collection_id):null)throw new a("KNOWLEDGE_PROJECT_LINKS_CONFLICT","collection inverse verification found the target still present.");return{accepted_receipt_id:_.accepted_receipt_id,target_id:$.collection_id,absent:!0,digest:$.result_digest}}async bindItem(_){if(this.assertIdentity(_),_.direction!=="forward")throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","item binding requires direction=forward.");let $=k_(_.collection_id,"collection_id"),D=k_(_.item_id,"item_id"),I=await this.itemResolver(D);if(!I||I.id!==D)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","bind-existing requires an exact existing Knowledge item id.",{item_id:D});let U=v_({action:"bind_item",collection_id:$,item_id:D});if(_.request_digest!==U)throw new a("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH","request_digest does not bind the normalized item-membership request.",{expected_request_digest:U});return this.sql.transaction(async(E)=>{let j=await this.getReceiptByAttempt(E,{operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",direction:"forward"});if(j)return this.assertIdempotent(j,_),j;if(!await this.getAggregateByCollection(E,$))throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge collection was not found by exact id.");let A=await E.get(`SELECT * FROM knowledge_project_collection_memberships + )`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,U.project_id])}let N={accepted_receipt_id:I.receipt_id,collection_id:I.collection_id,absent:E==="accepted"},O={receipt_id:this.stableReceiptId(_.operation_id,_.step_id,"register_collection","inverse"),authority:"knowledge",route:q$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",resource_kind:"collection",direction:"inverse",idempotency_key:_.idempotency_key,request_digest:V_({accepted_receipt_id:I.receipt_id,collection_id:I.collection_id}),precondition_digest:I.result_digest??"",outcome:E,reason:j,source_project_id:I.source_project_id,project_id:I.project_id,collection_id:I.collection_id,item_id:null,result_revision:E==="accepted"?"absent":I.result_revision,result_digest:V_(N),accepted_receipt_id:I.receipt_id,created_by_operation:!1,created_at:this.now()};return await $.run(ON,AN(O)),O})}async verifyRegistrationInverse(_){this.assertInverseIdentity(_);let $=await this.getReceiptByAttempt(this.sql,{operation_id:_.operation_id,step_id:_.step_id,action:"register_collection",direction:"inverse"});if(!$||$.outcome!=="accepted"||$.accepted_receipt_id!==_.accepted_receipt_id)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted collection inverse receipt was not found.");if($.collection_id?await this.getAggregateByCollection(this.sql,$.collection_id):null)throw new o("KNOWLEDGE_PROJECT_LINKS_CONFLICT","collection inverse verification found the target still present.");return{accepted_receipt_id:_.accepted_receipt_id,target_id:$.collection_id,absent:!0,digest:$.result_digest}}async bindItem(_){if(this.assertIdentity(_),_.direction!=="forward")throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","item binding requires direction=forward.");let $=k_(_.collection_id,"collection_id"),D=k_(_.item_id,"item_id"),I=await this.itemResolver(D);if(!I||I.id!==D)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","bind-existing requires an exact existing Knowledge item id.",{item_id:D});let U=V_({action:"bind_item",collection_id:$,item_id:D});if(_.request_digest!==U)throw new o("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH","request_digest does not bind the normalized item-membership request.",{expected_request_digest:U});return this.sql.transaction(async(E)=>{let j=await this.getReceiptByAttempt(E,{operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",direction:"forward"});if(j)return this.assertIdempotent(j,_),j;if(await E.lock(this.collectionFence($)),await E.lock(this.membershipFence($,D)),!await this.getAggregateByCollection(E,$))throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge collection was not found by exact id.");let O=await E.get(`SELECT * FROM knowledge_project_collection_memberships WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? - AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$,D]),O=A===null,S=this.now(),L=this.stableReceiptId(_.operation_id,_.step_id,"bind_item","forward");if(!A)await E.run(`INSERT INTO knowledge_project_collection_memberships ( + AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$,D]),S=O===null,L=this.now(),W=this.stableReceiptId(_.operation_id,_.step_id,"bind_item","forward");if(!O)await E.run(`INSERT INTO knowledge_project_collection_memberships ( authority_id, tenant_id, corpus_id, collection_id, item_id, bound_receipt_id, created_by_operation, bound_at - ) VALUES (?,?,?,?,?,?,?,?)`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$,D,L,1,S]),await E.run(`UPDATE knowledge_project_collections + ) VALUES (?,?,?,?,?,?,?,?)`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$,D,W,1,L]),await E.run(`UPDATE knowledge_project_collections SET revision = revision + 1, updated_at = ? - WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ?`,[S,this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$]);let P=await this.getAggregateByCollection(E,$);if(!P)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","item binding committed but collection readback was unavailable.");let z={collection_id:$,item_id:D,collection_revision:`r${Number(P.revision)}`,item_revision:`v${I.version??1}`},G={receipt_id:L,authority:"knowledge",route:k$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",resource_kind:"item",direction:"forward",idempotency_key:k_(_.idempotency_key,"idempotency_key"),request_digest:_.request_digest,precondition_digest:k_(_.precondition_digest,"precondition_digest"),outcome:"accepted",reason:O?null:"adopted_existing_membership",source_project_id:P.source_project_id,project_id:P.project_id,collection_id:$,item_id:D,result_revision:z.collection_revision,result_digest:v_(z),accepted_receipt_id:null,created_by_operation:O,created_at:S};return await E.run(AN,gN(G)),G})}async readItemBinding(_,$){let D=await this.sql.get(`SELECT * FROM knowledge_project_collection_memberships + WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ?`,[L,this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$]);let g=await this.getAggregateByCollection(E,$);if(!g)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","item binding committed but collection readback was unavailable.");let z={collection_id:$,item_id:D,collection_revision:`r${Number(g.revision)}`,item_revision:`v${I.version??1}`},G={receipt_id:W,authority:"knowledge",route:q$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",resource_kind:"item",direction:"forward",idempotency_key:k_(_.idempotency_key,"idempotency_key"),request_digest:_.request_digest,precondition_digest:k_(_.precondition_digest,"precondition_digest"),outcome:"accepted",reason:S?null:"adopted_existing_membership",source_project_id:g.source_project_id,project_id:g.project_id,collection_id:$,item_id:D,result_revision:z.collection_revision,result_digest:V_(z),accepted_receipt_id:null,created_by_operation:S,created_at:L};return await E.run(ON,AN(G)),G})}async readItemBinding(_,$){let D=await this.sql.get(`SELECT * FROM knowledge_project_collection_memberships WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? - AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,k_(_,"collection_id"),k_($,"item_id")]);if(!D)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge collection membership was not found by exact ids.");let I=await this.getAggregateByCollection(this.sql,_);if(!I)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","membership exists without its collection aggregate.");let U={collection_id:_,item_id:$,revision:`r${Number(I.revision)}`,bound_at:D.bound_at};return{...U,digest:v_(U)}}async compensateItemBinding(_){return this.assertInverseIdentity(_),this.sql.transaction(async($)=>{let D=await this.getReceiptByAttempt($,{operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",direction:"inverse"});if(D)return this.assertIdempotent(D,_),D;let I=await this.receiptById($,_.accepted_receipt_id);if(!I||I.action!=="bind_item"||I.direction!=="forward"||I.outcome!=="accepted")throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted item-binding receipt was not found.");let U="accepted",E=null,j=await $.get(`SELECT * FROM knowledge_project_collection_memberships + AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,k_(_,"collection_id"),k_($,"item_id")]);if(!D)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge collection membership was not found by exact ids.");let I=await this.getAggregateByCollection(this.sql,_);if(!I)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","membership exists without its collection aggregate.");let U={collection_id:_,item_id:$,revision:`r${Number(I.revision)}`,bound_at:D.bound_at};return{...U,digest:V_(U)}}async compensateItemBinding(_){return this.assertInverseIdentity(_),this.sql.transaction(async($)=>{let D=await this.getReceiptByAttempt($,{operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",direction:"inverse"});if(D)return this.assertIdempotent(D,_),D;let I=await this.receiptById($,_.accepted_receipt_id);if(!I||I.action!=="bind_item"||I.direction!=="forward"||I.outcome!=="accepted")throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted item-binding receipt was not found.");if(I.collection_id)await $.lock(this.collectionFence(I.collection_id));if(I.collection_id&&I.item_id)await $.lock(this.membershipFence(I.collection_id,I.item_id));let U="accepted",E=null,j=await $.get(`SELECT * FROM knowledge_project_collection_memberships WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,I.collection_id,I.item_id]);if(!I.created_by_operation)U="terminal_nonacceptance",E="adopted_membership_is_not_inverse_owned";else if(!j)U="terminal_nonacceptance",E="accepted_membership_is_already_absent";else if(await this.hasOtherAcceptedForwardReceipt($,I))U="terminal_nonacceptance",E="membership_has_later_accepted_adopter";else if(j.bound_receipt_id!==I.receipt_id||Number(j.created_by_operation)!==1)U="terminal_nonacceptance",E="membership_is_owned_by_a_different_receipt";else await $.run(`DELETE FROM knowledge_project_collection_memberships WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ? AND item_id = ? AND bound_receipt_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,I.collection_id,I.item_id,I.receipt_id]),await $.run(`UPDATE knowledge_project_collections SET revision = revision + 1, updated_at = ? - WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ?`,[this.now(),this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,I.collection_id]);let N=I.collection_id?await this.getAggregateByCollection($,I.collection_id):null,A={accepted_receipt_id:I.receipt_id,collection_id:I.collection_id,item_id:I.item_id,absent:U==="accepted"},O={receipt_id:this.stableReceiptId(_.operation_id,_.step_id,"bind_item","inverse"),authority:"knowledge",route:k$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",resource_kind:"item",direction:"inverse",idempotency_key:_.idempotency_key,request_digest:v_({accepted_receipt_id:I.receipt_id,collection_id:I.collection_id,item_id:I.item_id}),precondition_digest:I.result_digest??"",outcome:U,reason:E,source_project_id:I.source_project_id,project_id:I.project_id,collection_id:I.collection_id,item_id:I.item_id,result_revision:U==="accepted"&&N?`r${Number(N.revision)}`:I.result_revision,result_digest:v_(A),accepted_receipt_id:I.receipt_id,created_by_operation:!1,created_at:this.now()};return await $.run(AN,gN(O)),O})}async verifyItemBindingInverse(_){this.assertInverseIdentity(_);let $=await this.getReceiptByAttempt(this.sql,{operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",direction:"inverse"});if(!$||$.outcome!=="accepted"||$.accepted_receipt_id!==_.accepted_receipt_id)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted item-binding inverse receipt was not found.");if(await this.sql.get(`SELECT item_id FROM knowledge_project_collection_memberships + WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ?`,[this.now(),this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,I.collection_id]);let N=I.collection_id?await this.getAggregateByCollection($,I.collection_id):null,O={accepted_receipt_id:I.receipt_id,collection_id:I.collection_id,item_id:I.item_id,absent:U==="accepted"},S={receipt_id:this.stableReceiptId(_.operation_id,_.step_id,"bind_item","inverse"),authority:"knowledge",route:q$,package_version:this.options.packageVersion,...this.identity,operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",resource_kind:"item",direction:"inverse",idempotency_key:_.idempotency_key,request_digest:V_({accepted_receipt_id:I.receipt_id,collection_id:I.collection_id,item_id:I.item_id}),precondition_digest:I.result_digest??"",outcome:U,reason:E,source_project_id:I.source_project_id,project_id:I.project_id,collection_id:I.collection_id,item_id:I.item_id,result_revision:U==="accepted"&&N?`r${Number(N.revision)}`:I.result_revision,result_digest:V_(O),accepted_receipt_id:I.receipt_id,created_by_operation:!1,created_at:this.now()};return await $.run(ON,AN(S)),S})}async verifyItemBindingInverse(_){this.assertInverseIdentity(_);let $=await this.getReceiptByAttempt(this.sql,{operation_id:_.operation_id,step_id:_.step_id,action:"bind_item",direction:"inverse"});if(!$||$.outcome!=="accepted"||$.accepted_receipt_id!==_.accepted_receipt_id)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","accepted item-binding inverse receipt was not found.");if(await this.sql.get(`SELECT item_id FROM knowledge_project_collection_memberships WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? - AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.collection_id,$.item_id]))throw new a("KNOWLEDGE_PROJECT_LINKS_CONFLICT","item-binding inverse verification found the membership still present.");return{accepted_receipt_id:_.accepted_receipt_id,target_id:$.item_id,absent:!0,digest:$.result_digest}}async buildResources(_){let $=await this.getAggregateByProject(this.sql,k_(_,"project_id"));if(!$)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project aggregate was not found by source or stable project id.");let D=await this.sql.many(`SELECT * FROM knowledge_project_collection_memberships + AND collection_id = ? AND item_id = ?`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.collection_id,$.item_id]))throw new o("KNOWLEDGE_PROJECT_LINKS_CONFLICT","item-binding inverse verification found the membership still present.");return{accepted_receipt_id:_.accepted_receipt_id,target_id:$.item_id,absent:!0,digest:$.result_digest}}resourceBase(_){return{project_id:_.project_id,source_project_id:_.source_project_id,collection_id:_.collection_id,revision:`r${Number(_.revision)}`}}projectResource(_){let $={...this.resourceBase(_),kind:"project",id:_.project_id,title:_.project_name,locator:{kind:"canonical_uri",value:`knowledge:project:${_.project_id}`},metadata:{source_project_id:_.source_project_id,slug:_.project_slug,collection_count:1}};return{...$,key:`project:${_.project_id}`,digest:V_($)}}collectionResource(_,$){let D={...this.resourceBase(_),kind:"collection",id:_.collection_id,title:_.collection_name,locator:{kind:"external_uuid",value:_.collection_id},metadata:{slug:_.collection_slug,membership_rule:t4,member_count:$}};return{...D,key:`collection:${_.collection_id}`,digest:V_(D)}}itemResource(_,$){let D={...this.resourceBase(_),kind:"item",id:$.id,revision:`v${$.version??1}`,title:$.title,locator:{kind:"canonical_uri",value:`knowledge:item:${encodeURIComponent($.id)}`},metadata:{tags:[...$.tags??[]],archived:$.archived===!0,updated_at:$.updated_at}};return{...D,key:`item:${$.id}`,digest:V_(D)}}taxonomyResource(_,$,D){let I=X1(`${_.collection_id}\x00taxonomy\x00${$}`),U={...this.resourceBase(_),kind:"taxonomy",id:I,title:D.label,locator:{kind:"external_uuid",value:I},metadata:{tag:D.label,normalized_tag:$,item_count:D.itemCount,member_digest:D.memberDigest}};return{...U,key:`taxonomy:${I}`,digest:V_(U)}}postgresItem(_){let $=(D,I)=>{if(D==null)return I;if(typeof D==="string")try{return JSON.parse(D)}catch{return I}return D};return{id:String(_.id),short_id:_.short_id??null,title:String(_.title??""),content:String(_.content??""),url:_.url??null,tags:$(_.tags,[]),metadata:$(_.metadata,{}),archived:Boolean(_.archived),created_at:String(_.created_at),updated_at:String(_.updated_at),version:_.version==null?1:Number(_.version)}}resourceCursorAfter(_){if(!_.cursor)return"";let $;try{$=JSON.parse(Buffer.from(_.cursor,"base64url").toString("utf8"))}catch{throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","cursor is not a valid Knowledge project-resources cursor.")}if($.version!==1||$.project_id!==_.aggregate.project_id||$.collection_id!==_.aggregate.collection_id||$.collection_revision!==_.revision||$.population_digest!==_.populationDigest||p6($.kinds)!==p6(_.kinds)||typeof $.after!=="string")throw new o("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed or the cursor belongs to a different project/kind selection; restart from the first page.");return $.after}async listPostgresProjectResources(_,$,D,I){let U=await this.getAggregateByProject(this.sql,k_(_,"project_id"));if(!U)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project aggregate was not found by source or stable project id.");let E=[this.identity.tenant_id,this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,U.collection_id],j=await this.sql.get(`SELECT + COUNT(*)::text AS membership_count, + COUNT(i.id)::text AS visible_item_count, + encode(sha256(convert_to(COALESCE(string_agg( + m.item_id || E'\\x1f' + || COALESCE(i.title, '') || E'\\x1f' + || COALESCE(i.updated_at, '') || E'\\x1f' + || COALESCE(i.version::text, '1') || E'\\x1f' + || COALESCE(i.tags::text, '[]') || E'\\x1f' + || COALESCE(i.archived::text, 'false'), + E'\\x1e' ORDER BY m.item_id + ), ''), 'UTF8')), 'hex') AS item_snapshot_digest + FROM knowledge_project_collection_memberships m + LEFT JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ?`,[this.identity.tenant_id,this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,U.collection_id]),N=Number(j?.membership_count??0),O=Number(j?.visible_item_count??0);if(N!==O)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","collection membership points at a missing or inaccessible Knowledge item; refusing a partial resource population.",{collection_id:U.collection_id,membership_count:N,visible_item_count:O});let S=await this.sql.get(`SELECT COUNT(*)::text AS taxonomy_count + FROM ( + SELECT LOWER(BTRIM(tag.value)) AS normalized_tag + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) AS tag(value) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + GROUP BY LOWER(BTRIM(tag.value)) + ) taxonomy`,E),L=Number(S?.taxonomy_count??0),W=`r${Number(U.revision)}`,g=V_({collection_revision:W,kinds:I,item_snapshot_digest:I.includes("item")||I.includes("taxonomy")?j?.item_snapshot_digest??"":null,taxonomy_count:I.includes("taxonomy")?L:null}),z=this.resourceCursorAfter({cursor:$.cursor,aggregate:U,revision:W,populationDigest:g,kinds:I}),G=D+Mb,J=[],P=(Q)=>{if(J.lengthz)J.push(Q)};if(P(this.collectionResource(U,N)),I.includes("item")&&J.length ? + ORDER BY m.item_id ASC + LIMIT ${G-J.length}`,[...E,Q]);for(let B of F)P(this.itemResource(U,this.postgresItem(B)))}if(P(this.projectResource(U)),I.includes("taxonomy")&&J.length '' + ), + grouped AS ( + SELECT + normalized_tag, + (array_agg(label ORDER BY item_id, ordinality))[1] AS label, + COUNT(*)::text AS item_count, + encode(sha256(convert_to( + jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + 'UTF8' + )), 'hex') AS member_digest, + encode(sha256( + convert_to(?, 'UTF8') + || decode('00', 'hex') + || convert_to('taxonomy', 'UTF8') + || decode('00', 'hex') + || convert_to(normalized_tag, 'UTF8') + ), 'hex') AS stable_hex + FROM tagged + GROUP BY normalized_tag + ), + mutated AS ( + SELECT + *, + overlay( + overlay(substr(stable_hex, 1, 32) placing '5' from 13 for 1) + placing substr( + '89ab', + ((strpos('0123456789abcdef', substr(stable_hex, 17, 1)) - 1) % 4) + 1, + 1 + ) + from 17 for 1 + ) AS stable_uuid_hex + FROM grouped + ), + keyed AS ( + SELECT + normalized_tag, + label, + item_count, + member_digest, + substr(stable_uuid_hex, 1, 8) + || '-' || substr(stable_uuid_hex, 9, 4) + || '-' || substr(stable_uuid_hex, 13, 4) + || '-' || substr(stable_uuid_hex, 17, 4) + || '-' || substr(stable_uuid_hex, 21, 12) AS taxonomy_id + FROM mutated + ) + SELECT normalized_tag, label, item_count, member_digest + FROM keyed + WHERE 'taxonomy:' || taxonomy_id > ? + ORDER BY taxonomy_id ASC + LIMIT ${G-J.length}`,[...E,U.collection_id,Q]);for(let B of F)P(this.taxonomyResource(U,B.normalized_tag,{label:B.label,itemCount:Number(B.item_count),memberDigest:B.member_digest}))}let X=(I.includes("collection")?1:0)+(I.includes("item")?N:0)+(I.includes("project")?1:0)+(I.includes("taxonomy")?L:0),R=J.slice(0,D),T=J.length>R.length,Y=T&&R.length>0?Buffer.from(JSON.stringify({version:1,project_id:U.project_id,collection_id:U.collection_id,collection_revision:W,population_digest:g,kinds:I,after:R.at(-1).key})).toString("base64url"):null;return{schema:"knowledge.project-resources.page.v1",authority:"knowledge",route:yP,...this.identity,project_id:U.project_id,source_project_id:U.source_project_id,collection_id:U.collection_id,collection_revision:W,population_digest:g,resource_kinds:I,resources:R,count:R.length,total:X,limit:D,cursor:$.cursor??null,next_cursor:Y,has_more:T,complete:!T,truncated:!1}}async buildResources(_){let $=await this.getAggregateByProject(this.sql,k_(_,"project_id"));if(!$)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project aggregate was not found by source or stable project id.");let D=await this.sql.many(`SELECT * FROM knowledge_project_collection_memberships WHERE authority_id = ? AND tenant_id = ? AND corpus_id = ? AND collection_id = ? - ORDER BY item_id ASC`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.collection_id]),I=await Promise.all(D.map(async(S)=>{let L=await this.itemResolver(S.item_id);if(!L||L.id!==S.item_id)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","collection membership points at a missing Knowledge item; refusing a partial resource population.",{collection_id:$.collection_id,item_id:S.item_id});return L})),U=`r${Number($.revision)}`,E={project_id:$.project_id,source_project_id:$.source_project_id,collection_id:$.collection_id,revision:U},j=[],N={...E,kind:"project",id:$.project_id,title:$.project_name,locator:{kind:"canonical_uri",value:`knowledge:project:${$.project_id}`},metadata:{source_project_id:$.source_project_id,slug:$.project_slug,collection_count:1}};j.push({...N,key:`project:${$.project_id}`,digest:v_(N)});let A={...E,kind:"collection",id:$.collection_id,title:$.collection_name,locator:{kind:"external_uuid",value:$.collection_id},metadata:{slug:$.collection_slug,membership_rule:ND,member_count:I.length}};j.push({...A,key:`collection:${$.collection_id}`,digest:v_(A)});for(let S of I){let L={...E,kind:"item",id:S.id,revision:`v${S.version??1}`,title:S.title,locator:{kind:"canonical_uri",value:`knowledge:item:${encodeURIComponent(S.id)}`},metadata:{tags:[...S.tags??[]],archived:S.archived===!0,updated_at:S.updated_at}};j.push({...L,key:`item:${S.id}`,digest:v_(L)})}let O=new Map;for(let S of I)for(let L of S.tags??[]){let P=L.trim().toLowerCase();if(!P)continue;let z=O.get(P)??{label:L.trim(),itemIds:[]};z.itemIds.push(S.id),O.set(P,z)}for(let[S,L]of[...O.entries()].sort(([P],[z])=>P.localeCompare(z))){let P=NN(`${$.collection_id}\x00taxonomy\x00${S}`),z={...E,kind:"taxonomy",id:P,title:L.label,locator:{kind:"external_uuid",value:P},metadata:{tag:L.label,normalized_tag:S,item_count:L.itemIds.length,member_digest:v_([...L.itemIds].sort())}};j.push({...z,key:`taxonomy:${P}`,digest:v_(z)})}return j.sort((S,L)=>S.key.localeCompare(L.key)),{aggregate:$,resources:j}}async listProjectResources(_,$={}){let D=ZH($.limit),I=HH($.kinds),{aggregate:U,resources:E}=await this.buildResources(_),j=`r${Number(U.revision)}`,N=E.filter((G)=>I.includes(G.kind)),A=v_(N.map((G)=>({key:G.key,digest:G.digest}))),O="";if($.cursor){let G;try{G=JSON.parse(Buffer.from($.cursor,"base64url").toString("utf8"))}catch{throw new a("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","cursor is not a valid Knowledge project-resources cursor.")}if(G.version!==1||G.project_id!==U.project_id||G.collection_id!==U.collection_id||G.collection_revision!==j||G.population_digest!==A||gD(G.kinds)!==gD(I)||typeof G.after!=="string")throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed or the cursor belongs to a different project/kind selection; restart from the first page.");O=G.after}let S=O?N.filter((G)=>G.key>O):N,L=S.slice(0,D),P=S.length>L.length,z=P&&L.length>0?Buffer.from(JSON.stringify({version:1,project_id:U.project_id,collection_id:U.collection_id,collection_revision:j,population_digest:A,kinds:I,after:L.at(-1).key})).toString("base64url"):null;return{schema:"knowledge.project-resources.page.v1",authority:"knowledge",route:sR,...this.identity,project_id:U.project_id,source_project_id:U.source_project_id,collection_id:U.collection_id,collection_revision:j,population_digest:A,resource_kinds:I,resources:L,count:L.length,total:N.length,limit:D,cursor:$.cursor??null,next_cursor:z,has_more:P,complete:!P,truncated:!1}}async readProjectResource(_,$,D){let{resources:I}=await this.buildResources(_),U=I.find((E)=>E.kind===$&&E.id===D);if(!U)throw new a("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project resource was not found by exact kind and id.");return U}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null;do{let j=await this.listProjectResources(_,{...$,cursor:U}),N={project_id:j.project_id,collection_id:j.collection_id,collection_revision:j.collection_revision,population_digest:j.population_digest,total:j.total,kinds:gD(j.resource_kinds)};if(E&&gD(E)!==gD(N))throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete population was being read.");E??=N;for(let A of j.resources){if(I.has(A.key))throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource pagination returned a duplicate stable resource key.",{key:A.key});I.add(A.key),D.push(A)}if(j.has_more&&!j.next_cursor)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource page claims more data without a continuation cursor.");U=j.next_cursor}while(U);if(!E||D.length!==E.total)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete project resource enumeration did not match the producer total.",{expected_total:E?.total??null,received:D.length});return D}}function ON(_){if(_.databasePath!==":memory:")u$(_.databasePath);let $=new BH(_.databasePath,{create:!0});return $.exec(bH()),new E9(new U9($),(D)=>_.itemStore.get(D),_.options)}class j9{options;fetchImpl;root;constructor(_){this.options=_;this.fetchImpl=_.fetch??P0,this.root=_.baseUrl.replace(/\/+$/,"")}async close(){}headers(_={}){let $=new Headers(this.options.headers);if($.set("accept","application/json"),this.options.apiKey)$.set("x-api-key",this.options.apiKey);for(let[D,I]of Object.entries(_))$.set(D,I);return $}async request(_,$={}){let D=await this.fetchImpl(`${this.root}${_}`,{...$,headers:this.headers($.body?{"content-type":"application/json"}:{})}),I=await D.json().catch(()=>({}));if(!D.ok)throw new a(typeof I.error==="string"?I.error:"KNOWLEDGE_PROJECT_LINKS_CONFLICT",typeof I.message==="string"?I.message:`Knowledge project-links HTTP ${D.status}`,I.details&&typeof I.details==="object"?I.details:{});return I}async capability(){return(await this.request("/v1/project-registration/capability")).capability}async registerCollection(_){return(await this.request("/v1/project-registration/create",{method:"POST",body:JSON.stringify(_)})).receipt}async readCollection(_){return(await this.request("/v1/project-registration/read-exact",{method:"POST",body:JSON.stringify({collection_id:_})})).record}async lookupReceipt(_){return(await this.request("/v1/project-registration/receipts/lookup",{method:"POST",body:JSON.stringify(_)})).receipt}async compensateRegistration(_){return(await this.request("/v1/project-registration/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyRegistrationInverse(_){return(await this.request("/v1/project-registration/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async bindItem(_){return(await this.request("/v1/project-registration/items/bind",{method:"POST",body:JSON.stringify(_)})).receipt}async readItemBinding(_,$){return(await this.request("/v1/project-registration/items/read-exact",{method:"POST",body:JSON.stringify({collection_id:_,item_id:$})})).record}async compensateItemBinding(_){return(await this.request("/v1/project-registration/items/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyItemBindingInverse(_){return(await this.request("/v1/project-registration/items/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async listProjectResources(_,$={}){let D=new URLSearchParams;if($.limit!==void 0)D.set("limit",String($.limit));if($.cursor)D.set("cursor",$.cursor);for(let U of $.kinds??[])D.append("kind",U);let I=D.size>0?`?${D.toString()}`:"";return this.request(`/v1/projects/${encodeURIComponent(_)}/resources${I}`)}async readProjectResource(_,$,D){return(await this.request(`/v1/projects/${encodeURIComponent(_)}/resources/${$}/${encodeURIComponent(D)}`)).resource}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null,j=null,N=null;do{let A=await this.listProjectResources(_,{...$,cursor:U});if(E??=A.total,j??=A.collection_revision,N??=A.population_digest,A.total!==E||A.collection_revision!==j||A.population_digest!==N)throw new a("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete HTTP population was being read.");for(let O of A.resources){if(I.has(O.key))throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP pagination returned a duplicate stable key.");I.add(O.key),D.push(O)}if(A.has_more&&!A.next_cursor)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP page claims more data without a cursor.");U=A.next_cursor}while(U);if(E===null||D.length!==E)throw new a("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete HTTP resource enumeration did not match the producer total.");return D}}function N9(_){return new j9(_)}var E$={name:"@hasna/knowledge",version:"0.2.102",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/live-private-query.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","live:private-query":"bun scripts/live-private-query.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs","contracts:conformance":"contracts conformance fixtures",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 contracts:conformance && contracts no-cloud-scan . && 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.8.5","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};function wH(_){let $=K9(_);if(X_(g9($,"knowledge.db"))||X_(g9($,"config.json")))return g0($);return g0(j$(xN($)).home)}function hW(_){return`${vH()}:${G1("sha256").update(_.home).digest("hex").slice(0,12)}`}function dW(_){return`'${_.replace(/'/g,"'\\''")}'`}function rH(_){return["knowledge",..._].map(dW).join(" ")}function A9(_,$){return`cd ${dW(_)} && knowledge ${$.map(dW).join(" ")}`}function T9(_){return!_||_==="local"||_==="localhost"}function X1(_,$){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 cW(_){return{source:_.source,adapter:_.adapter,target:_.target,route:_.route,target_kind:_.targetKind,confidence:_.confidence,evidence:_.evidence,cacheability:_.cacheability}}function fH(_){try{let $=JSON.parse(_);return Array.isArray($)?$.filter((D)=>typeof D==="string"):[]}catch{return[]}}function R1(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function q_(_){return typeof _==="string"&&_.length>0?_:null}function xH(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function SN(_){return typeof _==="boolean"?_:null}function uH(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function F9(_,$,D){let I=R1(_),U=q_(I.observed_at)??q_($[`${D}_observed_at`]),E=q_(I.source_authority)??q_($[`${D}_source_authority`]);if(!U||!E)return null;return{observed_at:U,verified_at:q_(I.verified_at),expires_at:q_(I.expires_at)??q_($[`${D}_expires_at`]),ttl_ms:xH(I.ttl_ms),source_authority:E,confidence:q_(I.confidence)??(D==="route"?q_($.route_confidence):null),cacheable:SN(I.cacheable)??SN($[`${D}_cacheable`])??!1,stale:SN(I.stale)??SN($[`${D}_stale`])??!1,reasons:uH(I.reasons)}}function yH(_,$){return _.machine_id===$||_.hostname===$||_.ssh_target===$||_.tailscale_dns===$||fH(_.tailscale_ips_json).includes($)}function O9(_,$){return sg(_).find((D)=>yH(D,$))??null}function V9(_){return R1(i4(_.metadata_json).resolver_evidence)}function Y1(_){return R1(i4(_.capabilities_json).resolver)}function B9(_){let $=Y1(_),D=q_($.route_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;if(_.tailscale_dns&&_.ssh_target===_.tailscale_dns)return"tailscale";return _.ssh_target?"ssh":"unknown"}function hH(_){let $=Y1(_),D=q_($.route_target_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;return B9(_)}function cH(_){return q_(Y1(_).route_confidence)??"medium"}function S9(_,$,D){let I=V9(_),U=R1(I.route),E=Y1(_);return{target:_.ssh_target??_.tailscale_dns??_.hostname??_.machine_id,route:B9(_),targetKind:hH(_),confidence:cH(_),source:"registry",adapter:D.adapter,evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,route:U},cacheability:F9(U.cacheability,E,"route")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_route_fallback"])]}}function L9(_,$,D){if(!_.workspace_home)return null;let I=V9(_),U=R1(I.workspace),E=Y1(_);return{ok:!0,source:"registry",adapter:D.adapter,requested_machine_id:$,machine_id:_.machine_id,project_id:q_(U.project_id)??D.project_id,repo_name:q_(U.repo_name)??D.repo_name,project_root:_.workspace_home,project_root_source:q_(E.project_root_source)??"registry",workspace_root:q_(U.workspace_root),workspace_root_source:q_(E.workspace_root_source)??"registry",open_files_root:q_(U.open_files_root),open_files_root_source:q_(E.open_files_root_source)??"registry",trust_status:q_(E.trust_status)??"unknown",auth_status:q_(E.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:U},cacheability:F9(U.cacheability,E,"workspace")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_workspace_fallback"])]}}function J9(_){if(!_)return null;let $=_.diagnostics.filter((I)=>I.severity!=="ok"),D=_.repair_hints[0];if(!$.length&&!_.warnings.length&&!D)return null;return[$.length?`workspace diagnostics: ${$.map((I)=>`${I.id}=${I.status}`).join(", ")}`:null,_.warnings.length?`warnings: ${_.warnings.join(", ")}`:null,D?`repair: ${D.shell_command}`:null].filter(Boolean).join("; ")}function LN(_){return{id:_.id,reason:_.reason,command:["knowledge",..._.args],shell_command:rH(_.args)}}function JN(_,$){let D=w(_);try{return Number(D.query($).get()?.count??0)}finally{D.close()}}function nH(_,$){let D=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),I=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),U=JN(_,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),E=JN(_,["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(" ")),j=E===0;return{ok:j,source_of_truth:"open-files",configured_root:$?.open_files_root??null,configured_root_source:$?.open_files_root_source??null,source_refs:{open_files:D,metadata_mentions:I},extracted_text_artifacts:U,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:E,message:j?`${D} open-files source ref(s); raw source bytes remain owned by open-files`:`${E} raw source payload metadata sentinel(s) found`}}var dH=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function mW(_,$=0){if($>8)return!1;if(!_||typeof _!=="object")return!1;if(Array.isArray(_))return _.some((D)=>mW(D,$+1));for(let[D,I]of Object.entries(_)){if(dH.has(D.toLowerCase()))return!0;if(mW(I,$+1))return!0}return!1}function i4(_){try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function W9(_,$=20,D=200){if(!Number.isFinite(_)||_<=0)return $;return Math.min(Math.floor(_),D)}function mH(_,$=220){let D=_??"";return D.length>$?`${D.slice(0,$)}...`:D}function G$(_,$=["metadata_json"]){return _.map((D)=>{let I={...D};for(let U of $){let E=I[U];if(typeof E==="string"){let j=U.endsWith("_json")?U.slice(0,-5):U;I[j]=i4(E),delete I[U]}}return I})}function PN(_){if(typeof _!=="string")return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function lW(_){if(typeof _!=="string")return{};return i4(_)}function lH(_){let $={..._};return $.source_refs=PN($.source_refs_json),$.evidence_refs=PN($.evidence_refs_json),$.requires_approval=$.requires_approval===1||$.requires_approval===!0,$.checks=lW($.checks_json),$.metadata=lW($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.checks_json,delete $.metadata_json,$}function iH(_){let $={..._};return $.source_refs=PN($.source_refs_json),$.evidence_refs=PN($.evidence_refs_json),$.metadata=lW($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.metadata_json,$}function e_(_,$,D=[]){return _.query($).all(...D)}function tH(_){if(!X_(_))return{exists:!1,read_error:null,items:[]};try{let $=JSON.parse(CH(_,"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 P9(_){return{id:_.id,short_id:_.short_id??null,title:_.title,content_preview:mH(_.content),url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:_.archived===!0,created_at:_.created_at,updated_at:_.updated_at}}function z9(){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 M9(_,$,D=!1){return{query:_,limit:$,offset:0,mode:{keyword:!0,catalog:!0,semantic:D},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 oH(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function pH(_,$,D=!1){let I=M9(_,$,D);return{query:_,normalized_query:oH(_),created_at:new Date().toISOString(),mode:I.mode,warnings:I.warnings,search_counts:I.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function nW(_,$,D){let I=D??$.jsonStorePath;if(X_(I))return I;if(_==="global"){let U=CD();if(X_(U))return U}return I}function eH(_){let $=JSON.stringify(_);return Math.max(1,Math.ceil($.length/4))}function iW(_,$){let D=(_??"").normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function X9(_,$,D){let I=u_(iW(_,D),$);return{text:I.text,redactions:I.findings.length}}function G9(_,$,D){let I=_.now??new Date,U=_.source??"search",E=_.purpose??(U==="loops"||U==="runs"?"proposal":"agent_context"),j=(_.query??_.topic??$.query).normalize("NFKC").trim().replace(/\s+/g," "),N=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),A=Math.max(500,Math.min(_.maxTokens??6000,1e5)),O=0,S=$.citations.slice(0,Math.max(N*2,N)).map((R,T)=>{let Y=X9(R.quote,D,T<3?220:140);O+=Y.redactions;let Q=R.source_ref??R.source_uri??R.artifact_path??R.artifact_uri??R.id;return{id:`cite_${G1("sha256").update(`${R.id}\x00${Q}`).digest("hex").slice(0,12)}`,kind:R.artifact_uri||R.artifact_path?"artifact":"source",ref:Q,source_ref:R.source_ref,source_uri:R.source_uri,artifact_uri:R.artifact_uri,artifact_path:R.artifact_path,run_id:null,run_event_id:null,revision:R.revision,hash:R.hash,chunk_id:R.chunk_id,offsets:{start:R.start_offset,end:R.end_offset},quote_preview:Y.text}}),L=new Map($.citations.map((R,T)=>[R.id,S[T]])),P=$.excerpts.slice(0,Math.max(N*2,N)).map((R)=>{let T=$.results.find((F)=>F.id===R.result_id),Y=R.citation_id?L.get(R.citation_id):void 0,Q=X9(R.text,D,520);return O+=Q.redactions,{id:`ev_${G1("sha256").update(`${R.kind}\x00${R.result_id}\x00${R.citation_id??""}`).digest("hex").slice(0,14)}`,kind:R.kind,title:iW(T?.title??Y?.ref??R.kind,100),text_preview:Q.text,score:Number(R.score.toFixed(6)),citation_ids:Y?[Y.id]:[],provenance:{source:U,record_ref:`${R.kind}:${R.result_id}`,created_at:$.created_at,updated_at:null,metadata_keys:[]}}}).sort((R,T)=>T.score-R.score||R.id.localeCompare(T.id)).slice(0,N),z=new Set(P.flatMap((R)=>R.citation_ids)),G=S.filter((R)=>z.has(R.id)),J=Array.from(new Set($.warnings)),W=`ctx_${G1("sha256").update([U,E,j,J.join(","),P.map((R)=>R.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,X={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:I.toISOString(),source:U,purpose:E,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:W,budgets:{max_tokens:A,estimated_tokens:0,max_items:N,items_included:P.length,items_available:$.excerpts.length,items_truncated:Math.max(0,$.excerpts.length-P.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:O,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:G,evidence:P,duplicate_candidates:[],outline:{title:j?`Knowledge context: ${iW(j,80)}`:"Knowledge context",bullets:P.length>0?P.slice(0,5).map((R)=>`${R.id}: ${R.title}`):["No matching bounded evidence was found."],evidence_ids:P.slice(0,8).map((R)=>R.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:J,message:`${P.length} bounded evidence item(s), estimated under ${A} token(s)`};return X.budgets.estimated_tokens=eH(X),X.budgets.token_budget_exceeded=X.budgets.estimated_tokens>A,X.message=`${X.evidence.length} bounded evidence item(s), estimated ${X.budgets.estimated_tokens}/${A} token(s)`,X}function aH(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function sH(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function _k(_){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 R9(_){let $=_.now??new Date,D=_.source??"search",I=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),U=(_.query??_.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),E=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),j=Math.max(500,Math.min(_.maxTokens??6000,1e5)),N=`ctx_${G1("sha256").update(["empty",D,I,U,_.topic??"",_.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:I,query:U,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:N,budgets:{max_tokens:j,estimated_tokens:0,max_items:E,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:U?`Context for ${U}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${j} token(s)`}}function tW(_){let $=_.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return $?`${$}/`:null}function $k(_,$){let D=w(_);try{let I=D.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json + ORDER BY item_id ASC`,[this.identity.authority_id,this.identity.tenant_id,this.identity.corpus_id,$.collection_id]),I=await Promise.all(D.map(async(L)=>{let W=await this.itemResolver(L.item_id);if(!W||W.id!==L.item_id)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","collection membership points at a missing Knowledge item; refusing a partial resource population.",{collection_id:$.collection_id,item_id:L.item_id});return W})),U=`r${Number($.revision)}`,E={project_id:$.project_id,source_project_id:$.source_project_id,collection_id:$.collection_id,revision:U},j=[],N={...E,kind:"project",id:$.project_id,title:$.project_name,locator:{kind:"canonical_uri",value:`knowledge:project:${$.project_id}`},metadata:{source_project_id:$.source_project_id,slug:$.project_slug,collection_count:1}};j.push({...N,key:`project:${$.project_id}`,digest:V_(N)});let O={...E,kind:"collection",id:$.collection_id,title:$.collection_name,locator:{kind:"external_uuid",value:$.collection_id},metadata:{slug:$.collection_slug,membership_rule:t4,member_count:I.length}};j.push({...O,key:`collection:${$.collection_id}`,digest:V_(O)});for(let L of I){let W={...E,kind:"item",id:L.id,revision:`v${L.version??1}`,title:L.title,locator:{kind:"canonical_uri",value:`knowledge:item:${encodeURIComponent(L.id)}`},metadata:{tags:[...L.tags??[]],archived:L.archived===!0,updated_at:L.updated_at}};j.push({...W,key:`item:${L.id}`,digest:V_(W)})}let S=new Map;for(let L of I)for(let W of L.tags??[]){let g=W.trim().toLowerCase();if(!g)continue;let z=S.get(g)??{label:W.trim(),itemIds:[]};z.itemIds.push(L.id),S.set(g,z)}for(let[L,W]of[...S.entries()].sort(([g],[z])=>g.localeCompare(z))){let g=X1(`${$.collection_id}\x00taxonomy\x00${L}`),z={...E,kind:"taxonomy",id:g,title:W.label,locator:{kind:"external_uuid",value:g},metadata:{tag:W.label,normalized_tag:L,item_count:W.itemIds.length,member_digest:V_([...W.itemIds].sort())}};j.push({...z,key:`taxonomy:${g}`,digest:V_(z)})}return j.sort((L,W)=>L.key.localeCompare(W.key)),{aggregate:$,resources:j}}async listProjectResources(_,$={}){let D=Hb($.limit),I=bb($.kinds);if(this.sql.kind==="postgres")return this.listPostgresProjectResources(_,$,D,I);let{aggregate:U,resources:E}=await this.buildResources(_),j=`r${Number(U.revision)}`,N=E.filter((G)=>I.includes(G.kind)),O=V_(N.map((G)=>({key:G.key,digest:G.digest}))),S="";if($.cursor){let G;try{G=JSON.parse(Buffer.from($.cursor,"base64url").toString("utf8"))}catch{throw new o("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT","cursor is not a valid Knowledge project-resources cursor.")}if(G.version!==1||G.project_id!==U.project_id||G.collection_id!==U.collection_id||G.collection_revision!==j||G.population_digest!==O||p6(G.kinds)!==p6(I)||typeof G.after!=="string")throw new o("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed or the cursor belongs to a different project/kind selection; restart from the first page.");S=G.after}let L=S?N.filter((G)=>G.key>S):N,W=L.slice(0,D),g=L.length>W.length,z=g&&W.length>0?Buffer.from(JSON.stringify({version:1,project_id:U.project_id,collection_id:U.collection_id,collection_revision:j,population_digest:O,kinds:I,after:W.at(-1).key})).toString("base64url"):null;return{schema:"knowledge.project-resources.page.v1",authority:"knowledge",route:yP,...this.identity,project_id:U.project_id,source_project_id:U.source_project_id,collection_id:U.collection_id,collection_revision:j,population_digest:O,resource_kinds:I,resources:W,count:W.length,total:N.length,limit:D,cursor:$.cursor??null,next_cursor:z,has_more:g,complete:!g,truncated:!1}}async readProjectResource(_,$,D){let{resources:I}=await this.buildResources(_),U=I.find((E)=>E.kind===$&&E.id===D);if(!U)throw new o("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND","Knowledge project resource was not found by exact kind and id.");return U}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null;do{let j=await this.listProjectResources(_,{...$,cursor:U}),N={project_id:j.project_id,collection_id:j.collection_id,collection_revision:j.collection_revision,population_digest:j.population_digest,total:j.total,kinds:p6(j.resource_kinds)};if(E&&p6(E)!==p6(N))throw new o("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete population was being read.");E??=N;for(let O of j.resources){if(I.has(O.key))throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource pagination returned a duplicate stable resource key.",{key:O.key});I.add(O.key),D.push(O)}if(j.has_more&&!j.next_cursor)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resource page claims more data without a continuation cursor.");U=j.next_cursor}while(U);if(!E||D.length!==E.total)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete project resource enumeration did not match the producer total.",{expected_total:E?.total??null,received:D.length});return D}}function SN(_){if(_.databasePath!==":memory:")u$(_.databasePath);let $=import.meta.require;if(typeof $!=="function")throw new o("KNOWLEDGE_PROJECT_LINKS_CONFLICT","the local Knowledge project-links authority requires the Bun runtime.");let{Database:D}=$("bun:sqlite"),I=new D(_.databasePath,{create:!0});return I.exec(Zb()),new E9(new U9(I),(U)=>_.itemStore.get(U),_.options)}class j9{options;fetchImpl;root;constructor(_){this.options=_;this.fetchImpl=_.fetch??X0,this.root=_.baseUrl.replace(/\/+$/,"")}async close(){}headers(_={}){let $=new Headers(this.options.headers);if($.set("accept","application/json"),this.options.apiKey)$.set("x-api-key",this.options.apiKey);for(let[D,I]of Object.entries(_))$.set(D,I);return $}async request(_,$={}){let D=await this.fetchImpl(`${this.root}${_}`,{...$,headers:this.headers($.body?{"content-type":"application/json"}:{})}),I=await D.json().catch(()=>({}));if(!D.ok)throw new o(typeof I.error==="string"?I.error:"KNOWLEDGE_PROJECT_LINKS_CONFLICT",typeof I.message==="string"?I.message:`Knowledge project-links HTTP ${D.status}`,I.details&&typeof I.details==="object"?I.details:{});return I}async capability(){return(await this.request("/v1/project-registration/capability")).capability}async registerCollection(_){return(await this.request("/v1/project-registration/create",{method:"POST",body:JSON.stringify(_)})).receipt}async readCollection(_){return(await this.request("/v1/project-registration/read-exact",{method:"POST",body:JSON.stringify({collection_id:_})})).record}async lookupReceipt(_){return(await this.request("/v1/project-registration/receipts/lookup",{method:"POST",body:JSON.stringify(_)})).receipt}async compensateRegistration(_){return(await this.request("/v1/project-registration/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyRegistrationInverse(_){return(await this.request("/v1/project-registration/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async bindItem(_){return(await this.request("/v1/project-registration/items/bind",{method:"POST",body:JSON.stringify(_)})).receipt}async readItemBinding(_,$){return(await this.request("/v1/project-registration/items/read-exact",{method:"POST",body:JSON.stringify({collection_id:_,item_id:$})})).record}async compensateItemBinding(_){return(await this.request("/v1/project-registration/items/compensate",{method:"POST",body:JSON.stringify(_)})).receipt}async verifyItemBindingInverse(_){return(await this.request("/v1/project-registration/items/verify-inverse",{method:"POST",body:JSON.stringify(_)})).verification}async listProjectResources(_,$={}){let D=new URLSearchParams;if($.limit!==void 0)D.set("limit",String($.limit));if($.cursor)D.set("cursor",$.cursor);for(let U of $.kinds??[])D.append("kind",U);let I=D.size>0?`?${D.toString()}`:"";return this.request(`/v1/projects/${encodeURIComponent(_)}/resources${I}`)}async readProjectResource(_,$,D){return(await this.request(`/v1/projects/${encodeURIComponent(_)}/resources/${$}/${encodeURIComponent(D)}`)).resource}async readAllProjectResources(_,$={}){let D=[],I=new Set,U=null,E=null,j=null,N=null;do{let O=await this.listProjectResources(_,{...$,cursor:U});if(E??=O.total,j??=O.collection_revision,N??=O.population_digest,O.total!==E||O.collection_revision!==j||O.population_digest!==N)throw new o("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE","project resources changed while the complete HTTP population was being read.");for(let S of O.resources){if(I.has(S.key))throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP pagination returned a duplicate stable key.");I.add(S.key),D.push(S)}if(O.has_more&&!O.next_cursor)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","project resources HTTP page claims more data without a cursor.");U=O.next_cursor}while(U);if(E===null||D.length!==E)throw new o("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION","complete HTTP resource enumeration did not match the producer total.");return D}}function N9(_){return new j9(_)}var E$={name:"@hasna/knowledge",version:"0.2.102",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/live-private-query.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","live:private-query":"bun scripts/live-private-query.mjs",serve:"bun src/serve-entry.ts","verify:generated":"bun scripts/verify-generated-artifacts.mjs","contracts:conformance":"contracts conformance fixtures",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 contracts:conformance && contracts no-cloud-scan . && 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.8.5","@types/bun":"^1.3.14","@types/pg":"^8.15.6"}};function wb(_){let $=K9(_);if(X_(A9($,"knowledge.db"))||X_(A9($,"config.json")))return S0($);return S0(j$(xN($)).home)}function cP(_){return`${vb()}:${R1("sha256").update(_.home).digest("hex").slice(0,12)}`}function mP(_){return`'${_.replace(/'/g,"'\\''")}'`}function rb(_){return["knowledge",..._].map(mP).join(" ")}function O9(_,$){return`cd ${mP(_)} && knowledge ${$.map(mP).join(" ")}`}function T9(_){return!_||_==="local"||_==="localhost"}function G1(_,$){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 nP(_){return{source:_.source,adapter:_.adapter,target:_.target,route:_.route,target_kind:_.targetKind,confidence:_.confidence,evidence:_.evidence,cacheability:_.cacheability}}function fb(_){try{let $=JSON.parse(_);return Array.isArray($)?$.filter((D)=>typeof D==="string"):[]}catch{return[]}}function Y1(_){return _&&typeof _==="object"&&!Array.isArray(_)?_:{}}function C_(_){return typeof _==="string"&&_.length>0?_:null}function xb(_){return typeof _==="number"&&Number.isFinite(_)?_:null}function LN(_){return typeof _==="boolean"?_:null}function ub(_){return Array.isArray(_)?_.filter(($)=>typeof $==="string"):[]}function F9(_,$,D){let I=Y1(_),U=C_(I.observed_at)??C_($[`${D}_observed_at`]),E=C_(I.source_authority)??C_($[`${D}_source_authority`]);if(!U||!E)return null;return{observed_at:U,verified_at:C_(I.verified_at),expires_at:C_(I.expires_at)??C_($[`${D}_expires_at`]),ttl_ms:xb(I.ttl_ms),source_authority:E,confidence:C_(I.confidence)??(D==="route"?C_($.route_confidence):null),cacheable:LN(I.cacheable)??LN($[`${D}_cacheable`])??!1,stale:LN(I.stale)??LN($[`${D}_stale`])??!1,reasons:ub(I.reasons)}}function yb(_,$){return _.machine_id===$||_.hostname===$||_.ssh_target===$||_.tailscale_dns===$||fb(_.tailscale_ips_json).includes($)}function S9(_,$){return s2(_).find((D)=>yb(D,$))??null}function V9(_){return Y1(o4(_.metadata_json).resolver_evidence)}function Q1(_){return Y1(o4(_.capabilities_json).resolver)}function B9(_){let $=Q1(_),D=C_($.route_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;if(_.tailscale_dns&&_.ssh_target===_.tailscale_dns)return"tailscale";return _.ssh_target?"ssh":"unknown"}function hb(_){let $=Q1(_),D=C_($.route_target_kind);if(D==="local"||D==="lan"||D==="tailscale"||D==="ssh"||D==="unknown")return D;return B9(_)}function cb(_){return C_(Q1(_).route_confidence)??"medium"}function L9(_,$,D){let I=V9(_),U=Y1(I.route),E=Q1(_);return{target:_.ssh_target??_.tailscale_dns??_.hostname??_.machine_id,route:B9(_),targetKind:hb(_),confidence:cb(_),source:"registry",adapter:D.adapter,evidence:{registry:!0,requested_machine_id:$,machine_id:_.machine_id,recorded_at:_.updated_at,route:U},cacheability:F9(U.cacheability,E,"route")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_route_fallback"])]}}function W9(_,$,D){if(!_.workspace_home)return null;let I=V9(_),U=Y1(I.workspace),E=Q1(_);return{ok:!0,source:"registry",adapter:D.adapter,requested_machine_id:$,machine_id:_.machine_id,project_id:C_(U.project_id)??D.project_id,repo_name:C_(U.repo_name)??D.repo_name,project_root:_.workspace_home,project_root_source:C_(E.project_root_source)??"registry",workspace_root:C_(U.workspace_root),workspace_root_source:C_(E.workspace_root_source)??"registry",open_files_root:C_(U.open_files_root),open_files_root_source:C_(E.open_files_root_source)??"registry",trust_status:C_(E.trust_status)??"unknown",auth_status:C_(E.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:U},cacheability:F9(U.cacheability,E,"workspace")??D.cacheability,warnings:[...new Set([...D.warnings,"registry_workspace_fallback"])]}}function J9(_){if(!_)return null;let $=_.diagnostics.filter((I)=>I.severity!=="ok"),D=_.repair_hints[0];if(!$.length&&!_.warnings.length&&!D)return null;return[$.length?`workspace diagnostics: ${$.map((I)=>`${I.id}=${I.status}`).join(", ")}`:null,_.warnings.length?`warnings: ${_.warnings.join(", ")}`:null,D?`repair: ${D.shell_command}`:null].filter(Boolean).join("; ")}function WN(_){return{id:_.id,reason:_.reason,command:["knowledge",..._.args],shell_command:rb(_.args)}}function JN(_,$){let D=w(_);try{return Number(D.query($).get()?.count??0)}finally{D.close()}}function nb(_,$){let D=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE uri LIKE 'open-files://%'"),I=JN(_,"SELECT COUNT(*) AS count FROM sources WHERE metadata_json LIKE '%open-files://%' OR metadata_json LIKE '%source_ref%'"),U=JN(_,"SELECT COUNT(*) AS count FROM source_revisions WHERE extracted_text_uri IS NOT NULL"),E=JN(_,["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(" ")),j=E===0;return{ok:j,source_of_truth:"open-files",configured_root:$?.open_files_root??null,configured_root_source:$?.open_files_root_source??null,source_refs:{open_files:D,metadata_mentions:I},extracted_text_artifacts:U,raw_source_bytes_owned_by:"open-files",raw_payload_sentinel_hits:E,message:j?`${D} open-files source ref(s); raw source bytes remain owned by open-files`:`${E} raw source payload metadata sentinel(s) found`}}var db=new Set(["raw","raw_bytes","raw_content","content_base64","source_bytes","source_content","body","body_bytes"]);function lP(_,$=0){if($>8)return!1;if(!_||typeof _!=="object")return!1;if(Array.isArray(_))return _.some((D)=>lP(D,$+1));for(let[D,I]of Object.entries(_)){if(db.has(D.toLowerCase()))return!0;if(lP(I,$+1))return!0}return!1}function o4(_){try{let $=JSON.parse(_);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function P9(_,$=20,D=200){if(!Number.isFinite(_)||_<=0)return $;return Math.min(Math.floor(_),D)}function mb(_,$=220){let D=_??"";return D.length>$?`${D.slice(0,$)}...`:D}function G$(_,$=["metadata_json"]){return _.map((D)=>{let I={...D};for(let U of $){let E=I[U];if(typeof E==="string"){let j=U.endsWith("_json")?U.slice(0,-5):U;I[j]=o4(E),delete I[U]}}return I})}function zN(_){if(typeof _!=="string")return[];try{let $=JSON.parse(_);return Array.isArray($)?$:[]}catch{return[]}}function iP(_){if(typeof _!=="string")return{};return o4(_)}function lb(_){let $={..._};return $.source_refs=zN($.source_refs_json),$.evidence_refs=zN($.evidence_refs_json),$.requires_approval=$.requires_approval===1||$.requires_approval===!0,$.checks=iP($.checks_json),$.metadata=iP($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.checks_json,delete $.metadata_json,$}function ib(_){let $={..._};return $.source_refs=zN($.source_refs_json),$.evidence_refs=zN($.evidence_refs_json),$.metadata=iP($.metadata_json),delete $.source_refs_json,delete $.evidence_refs_json,delete $.metadata_json,$}function e_(_,$,D=[]){return _.query($).all(...D)}function tb(_){if(!X_(_))return{exists:!1,read_error:null,items:[]};try{let $=JSON.parse(Cb(_,"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 z9(_){return{id:_.id,short_id:_.short_id??null,title:_.title,content_preview:mb(_.content),url:_.url??null,tags:_.tags??[],metadata:_.metadata??{},archived:_.archived===!0,created_at:_.created_at,updated_at:_.updated_at}}function g9(){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 M9(_,$,D=!1){return{query:_,limit:$,offset:0,mode:{keyword:!0,catalog:!0,semantic:D},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 ob(_){return _.normalize("NFKC").trim().replace(/\s+/g," ").toLowerCase()}function pb(_,$,D=!1){let I=M9(_,$,D);return{query:_,normalized_query:ob(_),created_at:new Date().toISOString(),mode:I.mode,warnings:I.warnings,search_counts:I.counts,results:[],citations:[],excerpts:[],graph:{citations:[],backlinks:[]},notes:{permissions:[],freshness:[]}}}function dP(_,$,D){let I=D??$.jsonStorePath;if(X_(I))return I;if(_==="global"){let U=CD();if(X_(U))return U}return I}function eb(_){let $=JSON.stringify(_);return Math.max(1,Math.ceil($.length/4))}function tP(_,$){let D=(_??"").normalize("NFKC").trim().replace(/\s+/g," ");if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-1)).trim()}...`}function X9(_,$,D){let I=u_(tP(_,D),$);return{text:I.text,redactions:I.findings.length}}function G9(_,$,D){let I=_.now??new Date,U=_.source??"search",E=_.purpose??(U==="loops"||U==="runs"?"proposal":"agent_context"),j=(_.query??_.topic??$.query).normalize("NFKC").trim().replace(/\s+/g," "),N=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),O=Math.max(500,Math.min(_.maxTokens??6000,1e5)),S=0,L=$.citations.slice(0,Math.max(N*2,N)).map((R,T)=>{let Y=X9(R.quote,D,T<3?220:140);S+=Y.redactions;let Q=R.source_ref??R.source_uri??R.artifact_path??R.artifact_uri??R.id;return{id:`cite_${R1("sha256").update(`${R.id}\x00${Q}`).digest("hex").slice(0,12)}`,kind:R.artifact_uri||R.artifact_path?"artifact":"source",ref:Q,source_ref:R.source_ref,source_uri:R.source_uri,artifact_uri:R.artifact_uri,artifact_path:R.artifact_path,run_id:null,run_event_id:null,revision:R.revision,hash:R.hash,chunk_id:R.chunk_id,offsets:{start:R.start_offset,end:R.end_offset},quote_preview:Y.text}}),W=new Map($.citations.map((R,T)=>[R.id,L[T]])),g=$.excerpts.slice(0,Math.max(N*2,N)).map((R)=>{let T=$.results.find((F)=>F.id===R.result_id),Y=R.citation_id?W.get(R.citation_id):void 0,Q=X9(R.text,D,520);return S+=Q.redactions,{id:`ev_${R1("sha256").update(`${R.kind}\x00${R.result_id}\x00${R.citation_id??""}`).digest("hex").slice(0,14)}`,kind:R.kind,title:tP(T?.title??Y?.ref??R.kind,100),text_preview:Q.text,score:Number(R.score.toFixed(6)),citation_ids:Y?[Y.id]:[],provenance:{source:U,record_ref:`${R.kind}:${R.result_id}`,created_at:$.created_at,updated_at:null,metadata_keys:[]}}}).sort((R,T)=>T.score-R.score||R.id.localeCompare(T.id)).slice(0,N),z=new Set(g.flatMap((R)=>R.citation_ids)),G=L.filter((R)=>z.has(R.id)),J=Array.from(new Set($.warnings)),P=`ctx_${R1("sha256").update([U,E,j,J.join(","),g.map((R)=>R.id).join(",")].join("\x00")).digest("hex").slice(0,20)}`,X={ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:I.toISOString(),source:U,purpose:E,query:j,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:P,budgets:{max_tokens:O,estimated_tokens:0,max_items:N,items_included:g.length,items_available:$.excerpts.length,items_truncated:Math.max(0,$.excerpts.length-g.length),token_budget_exceeded:!1},safety:{raw_artifact_content_included:!1,durable_writes_performed:!1,redactions:S,reminders:["This pack is read-only and performs no durable writes.","Legacy JSON note evidence is bounded and redacted before inclusion."]},citations:G,evidence:g,duplicate_candidates:[],outline:{title:j?`Knowledge context: ${tP(j,80)}`:"Knowledge context",bullets:g.length>0?g.slice(0,5).map((R)=>`${R.id}: ${R.title}`):["No matching bounded evidence was found."],evidence_ids:g.slice(0,8).map((R)=>R.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:J,message:`${g.length} bounded evidence item(s), estimated under ${O} token(s)`};return X.budgets.estimated_tokens=eb(X),X.budgets.token_budget_exceeded=X.budgets.estimated_tokens>O,X.message=`${X.evidence.length} bounded evidence item(s), estimated ${X.budgets.estimated_tokens}/${O} token(s)`,X}function ab(){return{schema_version:0,chunks:0,vector_entries:0,missing_embeddings:0,queued:{},stale_revisions:0}}function sb(){return{total_embeddings:0,total_vector_entries:0,indexes:[]}}function _q(_){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 R9(_){let $=_.now??new Date,D=_.source??"search",I=_.purpose??(D==="loops"||D==="runs"?"proposal":"agent_context"),U=(_.query??_.topic??"").normalize("NFKC").trim().replace(/\s+/g," "),E=Math.max(1,Math.min(_.maxItems??_.limit??8,50)),j=Math.max(500,Math.min(_.maxTokens??6000,1e5)),N=`ctx_${R1("sha256").update(["empty",D,I,U,_.topic??"",_.since??""].join("\x00")).digest("hex").slice(0,20)}`;return{ok:!0,format:"knowledge-agent-context-pack",version:1,created_at:$.toISOString(),source:D,purpose:I,query:U,topic:_.topic??null,since:_.since??null,dry_run:!0,idempotency_key:N,budgets:{max_tokens:j,estimated_tokens:0,max_items:E,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:U?`Context for ${U}`:"Knowledge context",bullets:[],evidence_ids:[],duplicate_candidate_ids:[],next_actions:[]},warnings:["knowledge_db_missing"],message:`0 bounded evidence item(s), estimated 0/${j} token(s)`}}function oP(_){let $=_.artifact_store.s3?.prefix?.replace(/^\/+|\/+$/g,"");return $?`${$}/`:null}function $q(_,$){let D=w(_);try{let I=D.query(`SELECT artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all(),U=new Map,E=0,j=0,N=0,A=0,O=0,S=0,L=0,P=0,z=0,G=0,J=0,W=0,X=new Map,R=[],T=[],Y=[],Q=[],F=$.artifact_store.uri_prefix,q=tW($);for(let E_ of I){if(U.set(E_.kind,(U.get(E_.kind)??0)+1),E_.hash?.startsWith("sha256:"))E+=1;if(typeof E_.size_bytes==="number"&&E_.size_bytes>=0)j+=1,N+=E_.size_bytes;if(E_.artifact_uri.startsWith(F))A+=1;else if(R.length<5)R.push(E_.artifact_uri);let C_=i4(E_.metadata_json);if(mW(C_))L+=1;let N0=typeof C_.key==="string"?C_.key:null;if(!N0)O+=1;else if(q&&N0.startsWith(q)){if(S+=1,T.length<5)T.push(N0)}let ZP=typeof C_.artifact_modified_at==="string"?C_.artifact_modified_at:null;if(ZP)if(Number.isNaN(Date.parse(ZP))){if(z+=1,Y.length<5)Y.push(E_.artifact_uri)}else P+=1;let qD=C_.provenance&&typeof C_.provenance==="object"&&!Array.isArray(C_.provenance)?C_.provenance:null;if(qD){G+=1;let vN=typeof qD.artifact_key==="string"?qD.artifact_key:null,HP=typeof qD.generated_from==="string"?qD.generated_from:"unknown";if(X.set(HP,(X.get(HP)??0)+1),vN){if(J+=1,N0&&vN!==N0){if(W+=1,Q.length<5)Q.push(`${E_.artifact_uri}:provenance.artifact_key=${vN}:key=${N0}`)}}else if(Q.length<5)Q.push(`${E_.artifact_uri}:missing_provenance_artifact_key`)}else if(Q.length<5)Q.push(`${E_.artifact_uri}:missing_provenance`)}let Z=I.length-E,f=I.length-j,l=I.length-P-z,U_=I.length-G,j_=G-J,_$=I.length-A,G_=[Z>0?`artifact_manifest_missing_hash:${Z}`:null,f>0?`artifact_manifest_missing_size:${f}`:null,O>0?`artifact_manifest_missing_key:${O}`:null,_$>0?`artifact_manifest_uri_prefix_mismatch:${_$}`:null,S>0?`artifact_manifest_s3_key_contains_storage_prefix:${S}`:null,z>0?`artifact_manifest_invalid_modified_at:${z}`:null,U_>0?`artifact_manifest_missing_provenance:${U_}`:null,j_>0?`artifact_manifest_missing_provenance_artifact_key:${j_}`:null,W>0?`artifact_manifest_provenance_key_mismatch:${W}`:null,L>0?`artifact_manifest_raw_payload_sentinels:${L}`:null].filter((E_)=>Boolean(E_)),K$=G_.length===0;return{ok:K$,read_only:!0,storage_type:$.storage_type,artifact_uri_prefix:F,s3:$.artifact_store.s3,artifacts:{total:I.length,by_kind:[...U.entries()].map(([E_,C_])=>({kind:E_,count:C_})).sort((E_,C_)=>E_.kind.localeCompare(C_.kind)),with_hash:E,missing_hash:Z,with_size:j,missing_size:f,total_size_bytes:N},modified_time:{with_modified_at:P,missing_modified_at:l,invalid_modified_at:z,examples:Y},provenance:{with_provenance:G,missing_provenance:U_,with_artifact_key:J,missing_artifact_key:j_,artifact_key_mismatches:W,generated_from:[...X.entries()].map(([E_,C_])=>({value:E_,count:C_})).sort((E_,C_)=>E_.value.localeCompare(C_.value)),examples:Q},uri_prefix:{matching:A,mismatched:_$,examples:R},keys:{with_key:I.length-O,missing_key:O,prefixed_with_storage_prefix:S,prefixed_examples:T},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:S===0&&O===0,tracks_modified_time:P>0&&z===0,preserves_provenance:U_===0&&j_===0&&W===0},raw_payload_sentinel_hits:L,warnings:G_,message:K$?`${I.length} generated artifact manifest row(s) ready for ${$.storage_type} sync`:`Generated artifact manifest needs attention: ${G_.join(", ")}`}}finally{D.close()}}function Dk(_,$){let D=tW($);if(!D)return[];let I=w(_);try{let U=I.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json + ORDER BY artifact_uri ASC`).all(),U=new Map,E=0,j=0,N=0,O=0,S=0,L=0,W=0,g=0,z=0,G=0,J=0,P=0,X=new Map,R=[],T=[],Y=[],Q=[],F=$.artifact_store.uri_prefix,B=oP($);for(let E_ of I){if(U.set(E_.kind,(U.get(E_.kind)??0)+1),E_.hash?.startsWith("sha256:"))E+=1;if(typeof E_.size_bytes==="number"&&E_.size_bytes>=0)j+=1,N+=E_.size_bytes;if(E_.artifact_uri.startsWith(F))O+=1;else if(R.length<5)R.push(E_.artifact_uri);let v_=o4(E_.metadata_json);if(lP(v_))W+=1;let O0=typeof v_.key==="string"?v_.key:null;if(!O0)S+=1;else if(B&&O0.startsWith(B)){if(L+=1,T.length<5)T.push(O0)}let bz=typeof v_.artifact_modified_at==="string"?v_.artifact_modified_at:null;if(bz)if(Number.isNaN(Date.parse(bz))){if(z+=1,Y.length<5)Y.push(E_.artifact_uri)}else g+=1;let kD=v_.provenance&&typeof v_.provenance==="object"&&!Array.isArray(v_.provenance)?v_.provenance:null;if(kD){G+=1;let vN=typeof kD.artifact_key==="string"?kD.artifact_key:null,qz=typeof kD.generated_from==="string"?kD.generated_from:"unknown";if(X.set(qz,(X.get(qz)??0)+1),vN){if(J+=1,O0&&vN!==O0){if(P+=1,Q.length<5)Q.push(`${E_.artifact_uri}:provenance.artifact_key=${vN}:key=${O0}`)}}else if(Q.length<5)Q.push(`${E_.artifact_uri}:missing_provenance_artifact_key`)}else if(Q.length<5)Q.push(`${E_.artifact_uri}:missing_provenance`)}let b=I.length-E,f=I.length-j,l=I.length-g-z,U_=I.length-G,j_=G-J,_$=I.length-O,G_=[b>0?`artifact_manifest_missing_hash:${b}`:null,f>0?`artifact_manifest_missing_size:${f}`:null,S>0?`artifact_manifest_missing_key:${S}`:null,_$>0?`artifact_manifest_uri_prefix_mismatch:${_$}`:null,L>0?`artifact_manifest_s3_key_contains_storage_prefix:${L}`:null,z>0?`artifact_manifest_invalid_modified_at:${z}`:null,U_>0?`artifact_manifest_missing_provenance:${U_}`:null,j_>0?`artifact_manifest_missing_provenance_artifact_key:${j_}`:null,P>0?`artifact_manifest_provenance_key_mismatch:${P}`:null,W>0?`artifact_manifest_raw_payload_sentinels:${W}`:null].filter((E_)=>Boolean(E_)),K$=G_.length===0;return{ok:K$,read_only:!0,storage_type:$.storage_type,artifact_uri_prefix:F,s3:$.artifact_store.s3,artifacts:{total:I.length,by_kind:[...U.entries()].map(([E_,v_])=>({kind:E_,count:v_})).sort((E_,v_)=>E_.kind.localeCompare(v_.kind)),with_hash:E,missing_hash:b,with_size:j,missing_size:f,total_size_bytes:N},modified_time:{with_modified_at:g,missing_modified_at:l,invalid_modified_at:z,examples:Y},provenance:{with_provenance:G,missing_provenance:U_,with_artifact_key:J,missing_artifact_key:j_,artifact_key_mismatches:P,generated_from:[...X.entries()].map(([E_,v_])=>({value:E_,count:v_})).sort((E_,v_)=>E_.value.localeCompare(v_.value)),examples:Q},uri_prefix:{matching:O,mismatched:_$,examples:R},keys:{with_key:I.length-S,missing_key:S,prefixed_with_storage_prefix:L,prefixed_examples:T},sync_manifest:{copied_by_sync:!0,generated_artifacts_only:!0,includes_raw_source_bytes:!1,hash_algorithm:"sha256",portable_keys:L===0&&S===0,tracks_modified_time:g>0&&z===0,preserves_provenance:U_===0&&j_===0&&P===0},raw_payload_sentinel_hits:W,warnings:G_,message:K$?`${I.length} generated artifact manifest row(s) ready for ${$.storage_type} sync`:`Generated artifact manifest needs attention: ${G_.join(", ")}`}}finally{D.close()}}function Dq(_,$){let D=oP($);if(!D)return[];let I=w(_);try{let U=I.query(`SELECT id, artifact_uri, kind, hash, size_bytes, metadata_json FROM storage_objects - ORDER BY artifact_uri ASC`).all(),E=[];for(let j of U){let N=i4(j.metadata_json),A=typeof N.key==="string"?N.key:null;if(!A?.startsWith(D))continue;let O=A.slice(D.length);if(!O)continue;E.push({id:j.id,artifact_uri:j.artifact_uri,kind:j.kind,current_key:A,repaired_key:c$(O),hash:j.hash,size_bytes:j.size_bytes})}return E}finally{I.close()}}function Uk(_){let $=["--scope",_.scope,"--json"],D=_.tables?.length?["--tables",_.tables.join(",")]:[],I=[LN({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",...$]})];if(_.machine&&!T9(_.machine))I.push(LN({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",_.machine,..._.peerWorkspace?["--peer-workspace",_.peerWorkspace]:[],...D,...$]}));else if(_.peerWorkspace)I.push(LN({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",_.peerWorkspace,...D,...$]}));for(let U of _.resolvedWorkspace?.repair_hints??[])I.push({id:U.id,reason:U.reason,command:U.command,shell_command:U.shell_command});if(_.openConflicts>0)I.push(LN({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",...$]}));return I}function Ik(){let _=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",$=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!$)return{command:_,argsPrefix:[]};let D;try{D=JSON.parse($)}catch(I){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${I instanceof Error?I.message:String(I)}`)}if(!Array.isArray(D)||!D.every((I)=>typeof I==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:_,argsPrefix:D}}function Y9(_,$,D,I){let U=Ik(),E=qH(U.command,[...U.argsPrefix,I.target,$],{encoding:"utf8",env:process.env,input:D,maxBuffer:67108864});if((E.status??1)!==0){let j=I.source==="open-machines"?` via ${I.route??"resolved"}:${I.target}`:"";throw Error(`ssh ${_}${j} failed: ${(E.stderr||E.stdout||String(E.status)).trim()}`)}return E.stdout||""}function Q9(_,$,D){try{return JSON.parse(D)}catch(I){let U=D.trim().slice(0,240);throw Error(`Remote knowledge ${$} on ${_} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${U||String(I)}`)}}function Ek(_,$){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:D,min_protocol_version:I}=$;if(typeof D!=="number"||typeof I!=="number"||Dk6)throw Error(`Remote knowledge sync export on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function jk(_,$){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:D,min_protocol_version:I}=$;if(typeof D!=="number"||typeof I!=="number"||Dk6)throw Error(`Remote knowledge sync import on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Nk(_){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 WN extends Error{code="semantic_query_unavailable";constructor(){super("semantic_query_unavailable: the hosted Knowledge item store has no configured vector index.");this.name="KnowledgeSemanticSearchUnavailableError"}}class b9{options;ensuredWorkspace;cachedConfig;cachedProjectLinksAuthority;constructor(_={}){this.options=_}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??f1(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=g0(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let _=this.ensureWorkspace();return t1({storePath:_.jsonStorePath,storePathOverridden:!1})}projectLinksAuthority(){if(this.options.projectLinksAuthority)return this.options.projectLinksAuthority;if(this.cachedProjectLinksAuthority)return this.cachedProjectLinksAuthority;if(h$()){let{apiKey:$}=Gg(process.env);if(!$)throw Error("Knowledge project links require the configured API credential in postgres mode.");return this.cachedProjectLinksAuthority=N9({baseUrl:p1(this.config(),process.env),apiKey:$}),this.cachedProjectLinksAuthority}let _=this.ensureWorkspace();return this.cachedProjectLinksAuthority=ON({databasePath:_.knowledgeDbPath,itemStore:this.itemStore(),options:{packageVersion:E$.version,authorityId:this.options.projectLinksIdentity?.authorityId??process.env.HASNA_KNOWLEDGE_PROJECT_AUTHORITY_ID??"knowledge",tenantId:this.options.projectLinksIdentity?.tenantId??process.env.HASNA_KNOWLEDGE_PROJECT_TENANT_ID??"local",corpusId:this.options.projectLinksIdentity?.corpusId??process.env.HASNA_KNOWLEDGE_PROJECT_CORPUS_ID??"knowledge"}}),this.cachedProjectLinksAuthority}async close(){let _=this.cachedProjectLinksAuthority;this.cachedProjectLinksAuthority=void 0,await _?.close()}async listItems(_={}){return this.itemStore().list(_)}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||X_($.configPath))this.cachedConfig=X_($.configPath)?yN($.configPath):vD();return this.cachedConfig}safetyPolicy(){return U3(this.config(),this.workspace)}artifactStore(){return zg(this.config(),this.ensureWorkspace())}storageContract(){return a1(this.config(),this.workspace,this.scope)}validateStorage(){return Yg(this.config(),this.workspace)}assertStorageValid(_){let $=this.validateStorage();if(!$.ok)throw Error(`Storage contract invalid before ${_}: ${$.errors.join("; ")}`)}migrateLegacyPath(_={}){let $=this.workspace,D=uN(this.options.scope,this.options.cwd),I=aR({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!I.dry_run&&I.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return I}mergeLegacyPath(_={}){let $=this.workspace,D=uN(this.options.scope,this.options.cwd),I=pR({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!I.dry_run&&I.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return I}setup(_={}){let $=this.ensureWorkspace(),D=this.config({ensure:!0}),I=Nk(_.mode)??D.mode,U=_.apiUrl?E6(_.apiUrl):D.hosted?.api_url?E6(D.hosted.api_url):null,E={...D,mode:I,hosted:{...D.hosted??{},...U?{api_url:U}:{}},storage:_.canonicalExample?wP():D.storage};rP($.configPath,E),this.cachedConfig=E;let j=a1(E,$,this.scope);return{ok:!0,mode:I,api_url:E.hosted?.api_url??null,storage_type:E.storage.type,artifact_uri_prefix:j.artifact_store.uri_prefix,canonical_example:j.canonical_example,config_path:$.configPath,next:I==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${I}`}}authStatus(_=process.env){return mz(this.config(),_)}saveAuth(_,$=process.env){let D=_.apiUrl??this.config().hosted?.api_url;return nz({api_key:_.apiKey,email:_.email,org_id:_.orgId,org_slug:_.orgSlug,user_id:_.userId,api_url:D},$)}clearAuth(_=process.env){return dz(_)}paths(){let _=this.workspace;return{ok:!0,scope:this.scope,home:_.home,exists:X_(_.home),config_path:_.configPath,config_exists:X_(_.configPath),json_store_path:_.jsonStorePath,json_store_exists:X_(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:X_(_.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 c(this.ensureWorkspace().knowledgeDbPath)}dbStats(){o1("reading knowledge.db stats");let _=this.workspace;if(!X_(_.knowledgeDbPath))return z9();return Jg(_.knowledgeDbPath)}enqueuePromotion(_){return NR(this.ensureWorkspace().knowledgeDbPath,_)}promotionInbox(_={}){return AR(this.ensureWorkspace().knowledgeDbPath,_)}getPromotion(_){return gR(this.ensureWorkspace().knowledgeDbPath,_)}reviewPromotion(_,$){return OR(this.ensureWorkspace().knowledgeDbPath,_,$)}promoteCandidate(_,$={}){return SR(this.ensureWorkspace().knowledgeDbPath,_,$)}rejectPromotion(_,$={}){return LR(this.ensureWorkspace().knowledgeDbPath,_,$)}durableRecords(_={}){return JR(this.ensureWorkspace().knowledgeDbPath,_)}itemOnlyInventory(_){let $=this.workspace,{items:D,limit:I,includeArchived:U,storePath:E,storeExists:j,storeReadError:N}=_,A=D.filter((P)=>P.archived!==!0),O=U?D:A,S=z9(),L={legacy_items:D.length,active_items:A.length,archived_items:D.length-A.length,schema_version:S.schema_version,sources:S.sources,source_revisions:S.source_revisions,chunks:S.chunks,wiki_pages:S.wiki_pages,citations:S.citations,indexes:S.indexes,runs:S.runs,run_events:S.run_events,storage_objects:S.storage_objects,embeddings:S.embeddings,vector_entries:S.vector_entries,reindex_queue:S.reindex_queue,redaction_findings:S.redaction_findings,audit_events:S.audit_events,approval_gates:S.approval_gates,knowledge_machines:S.knowledge_machines,sync_snapshots:S.sync_snapshots,sync_changes:S.sync_changes,sync_conflicts:S.sync_conflicts,sync_table_clocks:S.sync_table_clocks,sync_imports:S.sync_imports,promotion_candidates:S.promotion_candidates,durable_records:S.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:I,paths:{json_store_path:$.jsonStorePath,json_store_exists:X_($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:X_($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:L,legacy_store:{path:E,exists:j,read_error:N,total_items:D.length,active_items:A.length,archived_items:D.length-A.length,items_returned:Math.min(O.length,I)},items:O.slice(0,I).map(P9),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:`${D.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory(_={}){let $=W9(_.limit),D=await this.fetchCloudItems(),I=dD();return this.itemOnlyInventory({items:D,limit:$,includeArchived:_.includeArchived??!1,storePath:I?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory(_={}){let $=this.workspace,D=W9(_.limit),I=_.storePath??$.jsonStorePath,U=tH(I),E=U.items.filter((S)=>S.archived!==!0),j=_.includeArchived?U.items:E;if(!X_($.knowledgeDbPath))return this.itemOnlyInventory({items:U.items,limit:D,includeArchived:_.includeArchived??!1,storePath:I,storeExists:U.exists,storeReadError:U.read_error});c($.knowledgeDbPath);let A=Jg($.knowledgeDbPath),O=w($.knowledgeDbPath);try{let S=G$(e_(O,` + ORDER BY artifact_uri ASC`).all(),E=[];for(let j of U){let N=o4(j.metadata_json),O=typeof N.key==="string"?N.key:null;if(!O?.startsWith(D))continue;let S=O.slice(D.length);if(!S)continue;E.push({id:j.id,artifact_uri:j.artifact_uri,kind:j.kind,current_key:O,repaired_key:c$(S),hash:j.hash,size_bytes:j.size_bytes})}return E}finally{I.close()}}function Uq(_){let $=["--scope",_.scope,"--json"],D=_.tables?.length?["--tables",_.tables.join(",")]:[],I=[WN({id:"sync_status",reason:"Inspect local sync registry, clocks, snapshots, and conflicts.",args:["sync","status",...$]})];if(_.machine&&!T9(_.machine))I.push(WN({id:"sync_dry_run_remote",reason:"Preview remote machine sync before changing either workspace.",args:["sync","dry-run","--machine",_.machine,..._.peerWorkspace?["--peer-workspace",_.peerWorkspace]:[],...D,...$]}));else if(_.peerWorkspace)I.push(WN({id:"sync_dry_run_peer",reason:"Preview local peer sync before changing either workspace.",args:["sync","dry-run","--peer-workspace",_.peerWorkspace,...D,...$]}));for(let U of _.resolvedWorkspace?.repair_hints??[])I.push({id:U.id,reason:U.reason,command:U.command,shell_command:U.shell_command});if(_.openConflicts>0)I.push(WN({id:"sync_conflicts",reason:"Review open conflicts before relying on bidirectional sync.",args:["sync","conflicts",...$]}));return I}function Iq(){let _=process.env.KNOWLEDGE_SSH_COMMAND?.trim()||"ssh",$=process.env.KNOWLEDGE_SSH_COMMAND_ARGS_JSON;if(!$)return{command:_,argsPrefix:[]};let D;try{D=JSON.parse($)}catch(I){throw Error(`KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array: ${I instanceof Error?I.message:String(I)}`)}if(!Array.isArray(D)||!D.every((I)=>typeof I==="string"))throw Error("KNOWLEDGE_SSH_COMMAND_ARGS_JSON must be a JSON string array.");return{command:_,argsPrefix:D}}function Y9(_,$,D,I){let U=Iq(),E=kb(U.command,[...U.argsPrefix,I.target,$],{encoding:"utf8",env:process.env,input:D,maxBuffer:67108864});if((E.status??1)!==0){let j=I.source==="open-machines"?` via ${I.route??"resolved"}:${I.target}`:"";throw Error(`ssh ${_}${j} failed: ${(E.stderr||E.stdout||String(E.status)).trim()}`)}return E.stdout||""}function Q9(_,$,D){try{return JSON.parse(D)}catch(I){let U=D.trim().slice(0,240);throw Error(`Remote knowledge ${$} on ${_} did not return JSON. Install a compatible @hasna/knowledge CLI on the remote machine. Output: ${U||String(I)}`)}}function Eq(_,$){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:D,min_protocol_version:I}=$;if(typeof D!=="number"||typeof I!=="number"||Dq6)throw Error(`Remote knowledge sync export on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function jq(_,$){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:D,min_protocol_version:I}=$;if(typeof D!=="number"||typeof I!=="number"||Dq6)throw Error(`Remote knowledge sync import on ${_} uses an unsupported sync protocol. Install @hasna/knowledge 0.2.32 or newer on both machines.`)}function Nq(_){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 PN extends Error{code="semantic_query_unavailable";constructor(){super("semantic_query_unavailable: the hosted Knowledge item store has no configured vector index.");this.name="KnowledgeSemanticSearchUnavailableError"}}class Z9{options;ensuredWorkspace;cachedConfig;cachedProjectLinksAuthority;constructor(_={}){this.options=_}get scope(){return this.options.scope??"global"}get workspace(){return this.ensuredWorkspace??x1(this.options.scope,this.options.cwd)}ensureWorkspace(){if(!this.ensuredWorkspace)this.ensuredWorkspace=S0(this.workspace.home);return this.ensuredWorkspace}jsonStorePath(){return this.ensureWorkspace().jsonStorePath}itemStore(){let _=this.ensureWorkspace();return o1({storePath:_.jsonStorePath,storePathOverridden:!1})}projectLinksAuthority(){if(this.options.projectLinksAuthority)return this.options.projectLinksAuthority;if(this.cachedProjectLinksAuthority)return this.cachedProjectLinksAuthority;if(h$()){let{apiKey:$}=G2(process.env);if(!$)throw Error("Knowledge project links require the configured API credential in postgres mode.");return this.cachedProjectLinksAuthority=N9({baseUrl:e1(this.config(),process.env),apiKey:$}),this.cachedProjectLinksAuthority}let _=this.ensureWorkspace();return this.cachedProjectLinksAuthority=SN({databasePath:_.knowledgeDbPath,itemStore:this.itemStore(),options:{packageVersion:E$.version,authorityId:this.options.projectLinksIdentity?.authorityId??process.env.HASNA_KNOWLEDGE_PROJECT_AUTHORITY_ID??"knowledge",tenantId:this.options.projectLinksIdentity?.tenantId??process.env.HASNA_KNOWLEDGE_PROJECT_TENANT_ID??"local",corpusId:this.options.projectLinksIdentity?.corpusId??process.env.HASNA_KNOWLEDGE_PROJECT_CORPUS_ID??"knowledge"}}),this.cachedProjectLinksAuthority}async close(){let _=this.cachedProjectLinksAuthority;this.cachedProjectLinksAuthority=void 0,await _?.close()}async listItems(_={}){return this.itemStore().list(_)}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||X_($.configPath))this.cachedConfig=X_($.configPath)?yN($.configPath):vD();return this.cachedConfig}safetyPolicy(){return Ig(this.config(),this.workspace)}artifactStore(){return g2(this.config(),this.ensureWorkspace())}storageContract(){return s1(this.config(),this.workspace,this.scope)}validateStorage(){return Y2(this.config(),this.workspace)}assertStorageValid(_){let $=this.validateStorage();if(!$.ok)throw Error(`Storage contract invalid before ${_}: ${$.errors.join("; ")}`)}migrateLegacyPath(_={}){let $=this.workspace,D=uN(this.options.scope,this.options.cwd),I=sR({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!I.dry_run&&I.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return I}mergeLegacyPath(_={}){let $=this.workspace,D=uN(this.options.scope,this.options.cwd),I=eR({scope:this.scope,current:$,legacy:D,approveWrite:_.approveWrite,approvedBy:_.approvedBy});if(!I.dry_run&&I.ok)this.ensuredWorkspace=void 0,this.cachedConfig=void 0;return I}setup(_={}){let $=this.ensureWorkspace(),D=this.config({ensure:!0}),I=Nq(_.mode)??D.mode,U=_.apiUrl?E6(_.apiUrl):D.hosted?.api_url?E6(D.hosted.api_url):null,E={...D,mode:I,hosted:{...D.hosted??{},...U?{api_url:U}:{}},storage:_.canonicalExample?rz():D.storage};fz($.configPath,E),this.cachedConfig=E;let j=s1(E,$,this.scope);return{ok:!0,mode:I,api_url:E.hosted?.api_url??null,storage_type:E.storage.type,artifact_uri_prefix:j.artifact_store.uri_prefix,canonical_example:j.canonical_example,config_path:$.configPath,next:I==="hosted"?["knowledge auth login --api-key ","knowledge storage status --json"]:["knowledge search ","knowledge "],message:`Set knowledge mode to ${I}`}}authStatus(_=process.env){return l3(this.config(),_)}saveAuth(_,$=process.env){let D=_.apiUrl??this.config().hosted?.api_url;return d3({api_key:_.apiKey,email:_.email,org_id:_.orgId,org_slug:_.orgSlug,user_id:_.userId,api_url:D},$)}clearAuth(_=process.env){return m3(_)}paths(){let _=this.workspace;return{ok:!0,scope:this.scope,home:_.home,exists:X_(_.home),config_path:_.configPath,config_exists:X_(_.configPath),json_store_path:_.jsonStorePath,json_store_exists:X_(_.jsonStorePath),knowledge_db_path:_.knowledgeDbPath,knowledge_db_exists:X_(_.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 c(this.ensureWorkspace().knowledgeDbPath)}dbStats(){p1("reading knowledge.db stats");let _=this.workspace;if(!X_(_.knowledgeDbPath))return g9();return J2(_.knowledgeDbPath)}enqueuePromotion(_){return AR(this.ensureWorkspace().knowledgeDbPath,_)}promotionInbox(_={}){return SR(this.ensureWorkspace().knowledgeDbPath,_)}getPromotion(_){return OR(this.ensureWorkspace().knowledgeDbPath,_)}reviewPromotion(_,$){return LR(this.ensureWorkspace().knowledgeDbPath,_,$)}promoteCandidate(_,$={}){return WR(this.ensureWorkspace().knowledgeDbPath,_,$)}rejectPromotion(_,$={}){return JR(this.ensureWorkspace().knowledgeDbPath,_,$)}durableRecords(_={}){return PR(this.ensureWorkspace().knowledgeDbPath,_)}itemOnlyInventory(_){let $=this.workspace,{items:D,limit:I,includeArchived:U,storePath:E,storeExists:j,storeReadError:N}=_,O=D.filter((g)=>g.archived!==!0),S=U?D:O,L=g9(),W={legacy_items:D.length,active_items:O.length,archived_items:D.length-O.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:I,paths:{json_store_path:$.jsonStorePath,json_store_exists:X_($.jsonStorePath),knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:X_($.knowledgeDbPath),artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:W,legacy_store:{path:E,exists:j,read_error:N,total_items:D.length,active_items:O.length,archived_items:D.length-O.length,items_returned:Math.min(S.length,I)},items:S.slice(0,I).map(z9),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:`${D.length} item(s), 0 source(s), 0 chunk(s), 0 wiki page(s), 0 artifact(s)`}}async cloudInventory(_={}){let $=P9(_.limit),D=await this.fetchCloudItems(),I=dD();return this.itemOnlyInventory({items:D,limit:$,includeArchived:_.includeArchived??!1,storePath:I?.baseUrl??"cloud",storeExists:!0,storeReadError:null})}inventory(_={}){let $=this.workspace,D=P9(_.limit),I=_.storePath??$.jsonStorePath,U=tb(I),E=U.items.filter((L)=>L.archived!==!0),j=_.includeArchived?U.items:E;if(!X_($.knowledgeDbPath))return this.itemOnlyInventory({items:U.items,limit:D,includeArchived:_.includeArchived??!1,storePath:I,storeExists:U.exists,storeReadError:U.read_error});c($.knowledgeDbPath);let O=J2($.knowledgeDbPath),S=w($.knowledgeDbPath);try{let L=G$(e_(S,` SELECT s.id, s.uri, @@ -1435,7 +1538,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 ? - `,[D]),["metadata_json","acl_json"]),L=G$(e_(O,` + `,[D]),["metadata_json","acl_json"]),W=G$(e_(S,` SELECT sr.id, s.uri AS source_uri, @@ -1448,7 +1551,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 ? - `,[D])),P=G$(e_(O,` + `,[D])),g=G$(e_(S,` SELECT c.id, c.kind, @@ -1469,22 +1572,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 ? - `,[D])),z=G$(e_(O,` + `,[D])),z=G$(e_(S,` 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 ? - `,[D])),G=G$(e_(O,` + `,[D])),G=G$(e_(S,` 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 ? - `,[D])),J=G$(e_(O,` + `,[D])),J=G$(e_(S,` 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 ? - `,[D])),W=G$(e_(O,` + `,[D])),P=G$(e_(S,` SELECT id, type, @@ -1500,18 +1603,18 @@ Pages should be concise, cited, and organized for both humans and agents. FROM runs ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[D])),X=e_(O,` + `,[D])),X=e_(S,` SELECT provider, model, dimensions, status, COUNT(*) AS entries FROM vector_index_entries GROUP BY provider, model, dimensions, status ORDER BY entries DESC LIMIT ? - `,[D]),R=G$(e_(O,` + `,[D]),R=G$(e_(S,` 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 ? - `,[D])),T=G$(e_(O,` + `,[D])),T=G$(e_(S,` SELECT machine_id, hostname, @@ -1529,7 +1632,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 ? - `,[D]),["tailscale_ips_json","capabilities_json","metadata_json"]),Y=G$(e_(O,` + `,[D]),["tailscale_ips_json","capabilities_json","metadata_json"]),Y=G$(e_(S,` SELECT id, entity_kind, @@ -1546,17 +1649,17 @@ Pages should be concise, cited, and organized for both humans and agents. FROM knowledge_sync_conflicts ORDER BY created_at DESC LIMIT ? - `,[D])),Q=G$(e_(O,` + `,[D])),Q=G$(e_(S,` 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 ? - `,[D])),F=G$(e_(O,` + `,[D])),F=G$(e_(S,` SELECT id, event_type, action, target_uri, decision, metadata_json, created_at FROM audit_events ORDER BY created_at DESC LIMIT ? - `,[D])),q=e_(O,` + `,[D])),B=e_(S,` SELECT id, record_kind, @@ -1581,7 +1684,7 @@ Pages should be concise, cited, and organized for both humans and agents. FROM knowledge_promotion_candidates ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[D]).map(lH),Z=e_(O,` + `,[D]).map(lb),b=e_(S,` SELECT id, record_kind, @@ -1603,15 +1706,15 @@ Pages should be concise, cited, and organized for both humans and agents. FROM durable_knowledge_records ORDER BY updated_at DESC, created_at DESC LIMIT ? - `,[D]).map(iH),f={legacy_items:U.items.length,active_items:E.length,archived_items:U.items.length-E.length,schema_version:A.schema_version,sources:A.sources,source_revisions:A.source_revisions,chunks:A.chunks,wiki_pages:A.wiki_pages,citations:A.citations,indexes:A.indexes,runs:A.runs,run_events:A.run_events,storage_objects:A.storage_objects,embeddings:A.embeddings,vector_entries:A.vector_entries,reindex_queue:A.reindex_queue,redaction_findings:A.redaction_findings,audit_events:A.audit_events,approval_gates:A.approval_gates,knowledge_machines:A.knowledge_machines,sync_snapshots:A.sync_snapshots,sync_changes:A.sync_changes,sync_conflicts:A.sync_conflicts,sync_table_clocks:A.sync_table_clocks,sync_imports:A.sync_imports,promotion_candidates:A.promotion_candidates,durable_records:A.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:D,paths:{json_store_path:I,json_store_exists:U.exists,knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:f,legacy_store:{path:I,exists:U.exists,read_error:U.read_error,total_items:U.items.length,active_items:E.length,archived_items:U.items.length-E.length,items_returned:Math.min(j.length,D)},items:j.slice(0,D).map(P9),sources:S,source_revisions:L,chunks:P,wiki_pages:z,indexes:G,storage_objects:J,runs:W,vector_indexes:X,reindex_queue:R,machines:T,sync_conflicts:Y,approval_gates:Q,audit_events:F,promotion_candidates:q,durable_records:Z,message:`${U.items.length} item(s), ${A.sources} source(s), ${A.chunks} chunk(s), ${A.wiki_pages} wiki page(s), ${A.storage_objects} artifact(s)`}}finally{O.close()}}assertAppWikiWrite(_){mD({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:_})}async initAppWiki(_={}){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return Q3({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async addAppWikiNote(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return K3({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(!X_($.knowledgeDbPath))return[];return T3({dbPath:$.knowledgeDbPath,limit:_.limit})}async getAppWikiNote(_,$={}){let D=this.workspace;if(!X_(D.knowledgeDbPath))return null;return F3({dbPath:D.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();c(_.knowledgeDbPath);let $=await cR(this.artifactStore()),D=w(_.knowledgeDbPath);try{j6(D,$.artifacts),nR(D,$.artifacts)}finally{D.close()}return $}async compileWiki(_={}){let $=this.ensureWorkspace();return xR({..._,dbPath:$.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer(_){let $=this.ensureWorkspace(),D=await this.retrieveContext({query:_.prompt,limit:_.limit,semantic:_.semantic,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake});return uR({dbPath:$.knowledgeDbPath,store:this.artifactStore(),prompt:_.prompt,answer:_.answer,context:D,approveWrite:_.approveWrite})}lintWiki(){let _=this.ensureWorkspace();return yR({dbPath:_.knowledgeDbPath})}async ingestManifest(_){let $=this.ensureWorkspace();return z3({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource(_,$){let D=this.ensureWorkspace();return II({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance(_={}){let $=_.dryRun!==!1,D=$?this.workspace:this.ensureWorkspace();return MR({root:_.root??this.options.cwd??process.cwd(),scope:this.scope,owner:_.owner,dryRun:$,deprecateLegacy:_.deprecateLegacy,includeLegacy:_.includeLegacy,legacyStorePath:D.jsonStorePath,dbPath:D.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:_.maxItems,limit:_.limit})}async resolveSource(_,$={}){let D=this.ensureWorkspace();return $I({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$.purpose,limit:$.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox(_){let $=this.ensureWorkspace();return uG({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth(_={}){let $=this.workspace;if(!X_($.knowledgeDbPath))return aH();return zR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}enqueueReindex(_={}){let $=this.ensureWorkspace();return KW({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async refreshEmbeddings(_={}){let $=this.ensureWorkspace();return XR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}providerStatus(_=process.env){return H3(this.config(),_)}modelRegistry(){return kg(this.config())}embeddingStatus(){let _=this.workspace;if(!X_(_.knowledgeDbPath))return sH();return r3(_.knowledgeDbPath)}async indexEmbeddings(_={}){let $=this.ensureWorkspace();return NI({..._,dbPath:$.knowledgeDbPath,config:this.config()})}isApiMode(){return h$()}cloudStore(){let _=dD();if(!_)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return _}async fetchCloudItems(){return i1(this.cloudStore())}async semanticSearch(_){let $=this.workspace;if(this.isApiMode())throw new WN;if(!X_($.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:[]};return gI({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async search(_){let $=this.workspace;if(this.isApiMode()){if(_.semantic===!0||_.fake===!0||Boolean(_.modelRef))throw new WN;let I=await this.cloudStore().search({query:_.query,archive:"active",limit:_.limit,offset:_.offset});return xg(I.items,_,[],I.total)}let D=nW(this.scope,$,_.legacyStorePath);if(!X_($.knowledgeDbPath)){if(X_(D))return LI({..._,legacyStorePath:D,config:this.config()});return M9(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return SI({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async retrieveContext(_){let $=this.workspace;if(this.isApiMode()){let I=await this.search(_);return A6(I,{contextChars:_.contextChars})}let D=nW(this.scope,$,_.legacyStorePath);if(!X_($.knowledgeDbPath)){if(X_(D)){let I=await LI({..._,legacyStorePath:D,config:this.config()});return A6(I,{contextChars:_.contextChars})}return pH(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return F0({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async contextPack(_){let $=this.workspace;if(this.isApiMode()){let I=(_.query??_.topic??"").trim();if(I&&_.source!=="loops"&&_.source!=="runs"){let U=await this.search({..._,query:I}),E=A6(U,{contextChars:_.contextChars});return G9(_,E,this.safetyPolicy())}return R9(_)}let D=nW(this.scope,$,_.legacyStorePath);if(!X_($.knowledgeDbPath)){let I=(_.query??_.topic??"").trim();if(I&&_.source!=="loops"&&_.source!=="runs"&&X_(D)){let U=await LI({..._,query:I,legacyStorePath:D,config:this.config()}),E=A6(U,{contextChars:_.contextChars});return G9(_,E,this.safetyPolicy())}return R9(_)}return LX({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt(_){if(this.isApiMode()){if(_.semantic===!0||_.fake===!0||Boolean(_.modelRef))throw new WN;let I=await this.cloudStore().search({query:_.prompt,archive:"active",limit:_.limit,offset:_.offset}),U=xg(I.items,{query:_.prompt,limit:_.limit,offset:_.offset,semantic:!1},[],I.total);return UX(I.items.map((E)=>E.item),{..._,config:this.config()},U)}let $=this.ensureWorkspace(),D=_.legacyStorePath??$.jsonStorePath;if(!_.legacyStorePath)xD(D);return DX({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async webSearch(_){let $=this.ensureWorkspace();return kR({..._,dbPath:$.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology(_={}){let $=this.workspace;return _R({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}async machinePreflight(_={}){let $=this.workspace;return UR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}syncStatus(){let _=this.workspace;if(!X_(_.knowledgeDbPath))return _k({scope:this.scope,workspaceHome:_.home});return wX({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home})}async syncDoctor(_={}){let $=this.ensureWorkspace();c($.knowledgeDbPath);let D=this.syncStatus(),I=this.storageContract(),U=this.validateStorage(),E=$k($.knowledgeDbPath,I),j=_.machine?.trim()||null,N=_.peerWorkspace?.trim()||null,A=[],O=null,S=null;if(j&&!T9(j)){let J=await XW({machineId:j,includeTailscale:_.includeTailscale});O=cW(J),A.push(...J.warnings)}if(j||N){let J=await sj({machineId:j??hW($),peerWorkspace:N,includeTailscale:_.includeTailscale});if(j&&!N&&(O?.source==="raw"||!J.ok||!J.project_root)){let W=O9($.knowledgeDbPath,j);if(W){if(O?.source==="raw"&&W.ssh_target)O=cW(S9(W,j,{target:O.target,route:O.route,targetKind:O.target_kind,confidence:O.confidence,source:O.source,adapter:O.adapter,evidence:O.evidence,cacheability:O.cacheability,warnings:[]}));if(!J.ok||!J.project_root){let X=L9(W,j,J);if(X)S=X1(X,X.project_root),A.push(...X.warnings)}}}S=J.ok&&J.project_root?X1(J,J.project_root):S??{...X1(J,N??""),project_root:J.project_root??N??""},A.push(...J.warnings)}if(!U.ok)A.push(...U.errors.map((J)=>`storage:${J}`));let L=nH($.knowledgeDbPath,S);if(!L.ok)A.push("open_files_boundary_raw_payload_sentinels");if(!E.ok)A.push(...E.warnings);let P=S?.diagnostics.filter((J)=>J.severity==="fail")??[],z=U.ok&&E.ok&&L.ok&&P.length===0&&(S?.project_root!==""||!S),G=Uk({scope:this.scope,machine:j,peerWorkspace:N,tables:_.tables,resolvedWorkspace:S,openConflicts:D.conflicts.open});return{ok:z,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:$.home,database:{sqlite_schema_version:D.sqlite_schema_version,table_counts:D.table_counts},storage:{contract:I,validation:U,artifact_manifest:E},sync:{machines:D.machines.total,snapshots:D.snapshots.total,clocks:D.clocks.total,imports:D.imports.total,open_conflicts:D.conflicts.open,table_clocks:D.clocks.rows},open_files:L,resolved_route:O,resolved_workspace:S,recommended_commands:G,warnings:[...new Set(A)],message:z?`Sync readiness ok: ${D.clocks.total} table clock(s), ${D.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(A)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys(_={}){let $=this.ensureWorkspace();c($.knowledgeDbPath);let D=this.storageContract(),I=tW(D),U=Dk($.knowledgeDbPath,D),E=_.dryRun===!0||_.approveWrite!==!0;if(U.length===0)return{ok:!0,dry_run:E,approval_required:!1,storage_type:D.storage_type,storage_prefix:I,candidates:U,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:D.storage_type,storage_prefix:I,candidates:U,repaired:0,audit_event_id:null,message:`Would repair ${U.length} legacy S3 artifact manifest key(s)`};if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:D.storage_type,storage_prefix:I,candidates:U,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let j=w($.knowledgeDbPath);try{let N=new Date().toISOString();j.transaction((S)=>{let L=j.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),P=j.query("SELECT id, metadata_json FROM storage_objects").all(),z=new Map(P.map((G)=>[G.id,i4(G.metadata_json)]));for(let G of S){let J=z.get(G.id)??{};J.key=G.repaired_key,L.run(JSON.stringify(J),N,G.id)}})(U);let O=R_(j,{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:U.length,storage_type:D.storage_type,storage_prefix:I,artifact_uris:U.map((S)=>S.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:D.storage_type,storage_prefix:I,candidates:U,repaired:U.length,audit_event_id:O,message:`Repaired ${U.length} legacy S3 artifact manifest key(s)`}}finally{j.close()}}async createSyncSnapshot(_={}){let $=this.ensureWorkspace(),D=await this.machineTopology({includeTailscale:_.includeTailscale!==!1});return vX({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),topology:D,machineId:_.machineId})}syncConflicts(_={}){let $=this.workspace;if(!X_($.knowledgeDbPath))return[];return rX($.knowledgeDbPath,_)}syncConflict(_){let $=this.ensureWorkspace(),D=TI($.knowledgeDbPath,_);if(!D)throw Error(`Sync conflict not found: ${_}`);return D}proposeSyncConflictResolution(_){let $=this.ensureWorkspace();return $U($.knowledgeDbPath,_)}async proposeSyncConflictResolutionWithAi(_){let $=this.ensureWorkspace();return fG({dbPath:$.knowledgeDbPath,id:_.id,config:this.config(),modelRef:_.modelRef,fake:_.fake,env:_.env})}resolveSyncConflict(_){let $=this.ensureWorkspace(),D=$U($.knowledgeDbPath,_.id);if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,approval_required:!0,conflict:D.conflict,proposal:D,message:"Sync conflict resolution requires --approve-write and --approved-by "};let I=uX($.knowledgeDbPath,{id:_.id,strategy:_.strategy??D.proposed_strategy,approvedBy:_.approvedBy,proposedPatchUri:_.proposedPatchUri}),U=w($.knowledgeDbPath);try{let E=R_(U,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${_.id}`,decision:"allow",metadata:{conflict_id:_.id,entity_kind:I.entity_kind,entity_id:I.entity_id,strategy:I.resolution_strategy,approved_by:I.approved_by,proposed_patch_uri:I.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:I,audit_event_id:E,message:`Resolved sync conflict ${_.id}`}}finally{U.close()}}syncMachines(){let _=this.workspace;if(!X_(_.knowledgeDbPath))return[];return sg(_.knowledgeDbPath)}exportSyncBundle(_={}){let $=this.ensureWorkspace();return this.assertStorageValid("sync export"),c($.knowledgeDbPath),_U({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"),c($.knowledgeDbPath),KI({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",D=_.dryRun===!0,I=this.ensureWorkspace();c(I.knowledgeDbPath);let U=_.tables?.length?["--tables",_.tables.join(",")]:[],E=_.includeArtifactContent===!1?["--no-artifact-content"]:[],j=["--scope",this.scope,"--json"],N=await XW({machineId:_.machine,includeTailscale:_.includeTailscale}),A=await sj({machineId:_.machine,peerWorkspace:_.peerWorkspace,includeTailscale:_.includeTailscale});if(!_.peerWorkspace&&N.source==="raw"||!A.ok||!A.project_root){let z=O9(I.knowledgeDbPath,_.machine);if(z){if(!_.peerWorkspace&&N.source==="raw"&&z.ssh_target)N=S9(z,_.machine,N);if(!A.ok||!A.project_root){let G=L9(z,_.machine,A);if(G)A=G}}}if(!A.ok||!A.project_root)throw Error([`Unable to resolve peer workspace for ${_.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",A.warnings.length?`Warnings: ${A.warnings.join(", ")}`:null].filter(Boolean).join(" "));let O=A.project_root,S={ok:!0,dry_run:D,direction:$,transport:"ssh",machine:_.machine,resolved_machine:N.target,resolved_route:cW(N),resolved_workspace:X1(A,A.project_root),peer_workspace:O,message:""},L=!1,P=()=>{if(D||L)return;kX(I.knowledgeDbPath,{machineId:_.machine,route:N,workspace:A}),L=!0};if($==="pull"||$==="both"){let z=A9(O,["sync","export",...j,...U,...E]),G=Y9(_.machine,z,void 0,N),J=Q9(_.machine,"sync export",G);Ek(_.machine,J),S.pull=await this.importSyncBundle({bundle:J,dryRun:D,direction:"pull",machineId:_.machineId??null})}if($==="push"||$==="both"){P();let z=this.exportSyncBundle({machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:!D}),G=A9(O,["sync","import",...j,...D?["--dry-run"]:[]]),J=Q9(_.machine,"sync import",Y9(_.machine,G,JSON.stringify(z),N));jk(_.machine,J),S.push=J}return S.ok=(S.pull?.ok??!0)&&(S.push?.ok??!0),P(),S.message=[J9(S.resolved_workspace),S.pull?`pull: ${S.pull.message}`:null,S.push?`push: ${S.push.message}`:null].filter(Boolean).join("; "),S}async syncPeer(_){let $=_.direction??"both",D=this.ensureWorkspace();c(D.knowledgeDbPath);let I=K9(_.peerWorkspace),U=wH(I);c(U.knowledgeDbPath);let E=yN(U.configPath),j=a1(E,U,this.scope),N=zg(E,U),A=_.machineId??hW(D),O=hW(U),S=await sj({machineId:_.machineId??O,peerWorkspace:I,includeTailscale:!1}),L=()=>_U({dbPath:D.knowledgeDbPath,scope:this.scope,workspaceHome:D.home,storage:this.storageContract(),machineId:A,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),P=()=>_U({dbPath:U.knowledgeDbPath,scope:this.scope,workspaceHome:U.home,storage:j,machineId:O,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),z={ok:!0,dry_run:_.dryRun===!0,direction:$,resolved_workspace:X1(S,S.project_root??I),message:""};if($==="pull"||$==="both")z.pull=await KI({targetDbPath:D.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:D.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:P(),targetBundle:L(),direction:"pull",dryRun:_.dryRun,localMachineId:A});if($==="push"||$==="both")z.push=await KI({targetDbPath:U.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:U.home,targetStorage:j,targetStore:N,bundle:L(),targetBundle:P(),direction:"push",dryRun:_.dryRun,localMachineId:O});return z.ok=(z.pull?.ok??!0)&&(z.push?.ok??!0),z.message=[J9(z.resolved_workspace),z.pull?`pull: ${z.pull.message}`:null,z.push?`push: ${z.push.message}`:null].filter(Boolean).join("; "),z}}function zN(_={}){return new b9(_)}import{createHash as Z9}from"crypto";var gk=Object.defineProperty,Ak=(_)=>_;function Ok(_,$){this[_]=Ak.bind(null,$)}var Sk=(_,$)=>{for(var D in $)gk(_,D,{get:$[D],enumerable:!0,configurable:!0,set:Ok.bind($,D)})},g={};Sk(g,{void:()=>ok,util:()=>N_,unknown:()=>ik,union:()=>sk,undefined:()=>dk,tuple:()=>Dq,transformer:()=>q9,symbol:()=>nk,string:()=>l9,strictObject:()=>ak,setErrorMap:()=>Wk,set:()=>Eq,record:()=>Uq,quotelessJson:()=>Lk,promise:()=>Sq,preprocess:()=>Wq,pipeline:()=>Pq,ostring:()=>zq,optional:()=>Lq,onumber:()=>Xq,oboolean:()=>Gq,objectUtil:()=>eW,object:()=>ek,number:()=>i9,nullable:()=>Jq,null:()=>mk,never:()=>tk,nativeEnum:()=>Oq,nan:()=>yk,map:()=>Iq,makeIssue:()=>RN,literal:()=>gq,lazy:()=>Nq,late:()=>xk,isValid:()=>t4,isDirty:()=>sW,isAsync:()=>Q1,isAborted:()=>aW,intersection:()=>$q,instanceof:()=>uk,getParsedType:()=>Q6,getErrorMap:()=>GN,function:()=>jq,enum:()=>Aq,effect:()=>q9,discriminatedUnion:()=>_q,defaultErrorMap:()=>PD,datetimeRegex:()=>n9,date:()=>ck,custom:()=>m9,coerce:()=>Rq,boolean:()=>t9,bigint:()=>hk,array:()=>pk,any:()=>lk,addIssueToContext:()=>u,ZodVoid:()=>T1,ZodUnknown:()=>p6,ZodUnion:()=>RD,ZodUndefined:()=>XD,ZodType:()=>$_,ZodTuple:()=>p$,ZodTransformer:()=>Q$,ZodSymbol:()=>K1,ZodString:()=>q$,ZodSet:()=>e4,ZodSchema:()=>$_,ZodRecord:()=>F1,ZodReadonly:()=>BD,ZodPromise:()=>a4,ZodPipeline:()=>M1,ZodParsedType:()=>h,ZodOptional:()=>v$,ZodObject:()=>H_,ZodNumber:()=>e6,ZodNullable:()=>K6,ZodNull:()=>GD,ZodNever:()=>o$,ZodNativeEnum:()=>TD,ZodNaN:()=>B1,ZodMap:()=>V1,ZodLiteral:()=>KD,ZodLazy:()=>QD,ZodIssueCode:()=>C,ZodIntersection:()=>YD,ZodFunction:()=>JD,ZodFirstPartyTypeKind:()=>t,ZodError:()=>L$,ZodEnum:()=>s6,ZodEffects:()=>Q$,ZodDiscriminatedUnion:()=>KN,ZodDefault:()=>FD,ZodDate:()=>o4,ZodCatch:()=>VD,ZodBranded:()=>TN,ZodBoolean:()=>zD,ZodBigInt:()=>a6,ZodArray:()=>C$,ZodAny:()=>p4,Schema:()=>$_,ParseStatus:()=>l_,OK:()=>s_,NEVER:()=>Yq,INVALID:()=>i,EMPTY_PATH:()=>Pk,DIRTY:()=>LD,BRAND:()=>fk});var N_;(function(_){_.assertEqual=(U)=>{};function $(U){}_.assertIs=$;function D(U){throw Error()}_.assertNever=D,_.arrayToEnum=(U)=>{let E={};for(let j of U)E[j]=j;return E},_.getValidEnumValues=(U)=>{let E=_.objectKeys(U).filter((N)=>typeof U[U[N]]!=="number"),j={};for(let N of E)j[N]=U[N];return _.objectValues(j)},_.objectValues=(U)=>{return _.objectKeys(U).map(function(E){return U[E]})},_.objectKeys=typeof Object.keys==="function"?(U)=>Object.keys(U):(U)=>{let E=[];for(let j in U)if(Object.prototype.hasOwnProperty.call(U,j))E.push(j);return E},_.find=(U,E)=>{for(let j of U)if(E(j))return j;return},_.isInteger=typeof Number.isInteger==="function"?(U)=>Number.isInteger(U):(U)=>typeof U==="number"&&Number.isFinite(U)&&Math.floor(U)===U;function I(U,E=" | "){return U.map((j)=>typeof j==="string"?`'${j}'`:j).join(E)}_.joinValues=I,_.jsonStringifyReplacer=(U,E)=>{if(typeof E==="bigint")return E.toString();return E}})(N_||(N_={}));var eW;(function(_){_.mergeShapes=($,D)=>{return{...$,...D}}})(eW||(eW={}));var h=N_.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Q6=(_)=>{switch(typeof _){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(_)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":if(Array.isArray(_))return h.array;if(_===null)return h.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return h.promise;if(typeof Map<"u"&&_ instanceof Map)return h.map;if(typeof Set<"u"&&_ instanceof Set)return h.set;if(typeof Date<"u"&&_ instanceof Date)return h.date;return h.object;default:return h.unknown}},C=N_.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"]),Lk=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class L$ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=(D)=>{this.issues=[...this.issues,D]},this.addIssues=(D=[])=>{this.issues=[...this.issues,...D]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=_}format(_){let $=_||function(U){return U.message},D={_errors:[]},I=(U)=>{for(let E of U.issues)if(E.code==="invalid_union")E.unionErrors.map(I);else if(E.code==="invalid_return_type")I(E.returnTypeError);else if(E.code==="invalid_arguments")I(E.argumentsError);else if(E.path.length===0)D._errors.push($(E));else{let j=D,N=0;while(N$.message){let $={},D=[];for(let I of this.issues)if(I.path.length>0){let U=I.path[0];$[U]=$[U]||[],$[U].push(_(I))}else D.push(_(I));return{formErrors:D,fieldErrors:$}}get formErrors(){return this.flatten()}}L$.create=(_)=>{return new L$(_)};var Jk=(_,$)=>{let D;switch(_.code){case C.invalid_type:if(_.received===h.undefined)D="Required";else D=`Expected ${_.expected}, received ${_.received}`;break;case C.invalid_literal:D=`Invalid literal value, expected ${JSON.stringify(_.expected,N_.jsonStringifyReplacer)}`;break;case C.unrecognized_keys:D=`Unrecognized key(s) in object: ${N_.joinValues(_.keys,", ")}`;break;case C.invalid_union:D="Invalid input";break;case C.invalid_union_discriminator:D=`Invalid discriminator value. Expected ${N_.joinValues(_.options)}`;break;case C.invalid_enum_value:D=`Invalid enum value. Expected ${N_.joinValues(_.options)}, received '${_.received}'`;break;case C.invalid_arguments:D="Invalid function arguments";break;case C.invalid_return_type:D="Invalid function return type";break;case C.invalid_date:D="Invalid date";break;case C.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if(D=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")D=`${D} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)D=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)D=`Invalid input: must end with "${_.validation.endsWith}"`;else N_.assertNever(_.validation);else if(_.validation!=="regex")D=`Invalid ${_.validation}`;else D="Invalid";break;case C.too_small:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else D="Invalid input";break;case C.too_big:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")D=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else D="Invalid input";break;case C.custom:D="Invalid input";break;case C.invalid_intersection_types:D="Intersection results could not be merged";break;case C.not_multiple_of:D=`Number must be a multiple of ${_.multipleOf}`;break;case C.not_finite:D="Number must be finite";break;default:D=$.defaultError,N_.assertNever(_)}return{message:D}},PD=Jk,y9=PD;function Wk(_){y9=_}function GN(){return y9}var RN=(_)=>{let{data:$,path:D,errorMaps:I,issueData:U}=_,E=[...D,...U.path||[]],j={...U,path:E};if(U.message!==void 0)return{...U,path:E,message:U.message};let N="",A=I.filter((O)=>!!O).slice().reverse();for(let O of A)N=O(j,{data:$,defaultError:N}).message;return{...U,path:E,message:N}},Pk=[];function u(_,$){let D=GN(),I=RN({issueData:$,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,D,D===PD?void 0:PD].filter((U)=>!!U)});_.common.issues.push(I)}class l_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,$){let D=[];for(let I of $){if(I.status==="aborted")return i;if(I.status==="dirty")_.dirty();D.push(I.value)}return{status:_.value,value:D}}static async mergeObjectAsync(_,$){let D=[];for(let I of $){let U=await I.key,E=await I.value;D.push({key:U,value:E})}return l_.mergeObjectSync(_,D)}static mergeObjectSync(_,$){let D={};for(let I of $){let{key:U,value:E}=I;if(U.status==="aborted")return i;if(E.status==="aborted")return i;if(U.status==="dirty")_.dirty();if(E.status==="dirty")_.dirty();if(U.value!=="__proto__"&&(typeof E.value<"u"||I.alwaysSet))D[U.value]=E.value}return{status:_.value,value:D}}}var i=Object.freeze({status:"aborted"}),LD=(_)=>({status:"dirty",value:_}),s_=(_)=>({status:"valid",value:_}),aW=(_)=>_.status==="aborted",sW=(_)=>_.status==="dirty",t4=(_)=>_.status==="valid",Q1=(_)=>typeof Promise<"u"&&_ instanceof Promise,d;(function(_){_.errToObj=($)=>typeof $==="string"?{message:$}:$||{},_.toString=($)=>typeof $==="string"?$:$?.message})(d||(d={}));class w${constructor(_,$,D,I){this._cachedPath=[],this.parent=_,this.data=$,this._path=D,this._key=I}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 H9=(_,$)=>{if(t4($))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 D=new L$(_.common.issues);return this._error=D,this._error}}}};function s(_){if(!_)return{};let{errorMap:$,invalid_type_error:D,required_error:I,description:U}=_;if($&&(D||I))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:U};return{errorMap:(j,N)=>{let{message:A}=_;if(j.code==="invalid_enum_value")return{message:A??N.defaultError};if(typeof N.data>"u")return{message:A??I??N.defaultError};if(j.code!=="invalid_type")return{message:N.defaultError};return{message:A??D??N.defaultError}},description:U}}class $_{get description(){return this._def.description}_getType(_){return Q6(_.data)}_getOrReturnCtx(_,$){return $||{common:_.parent.common,data:_.data,parsedType:Q6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new l_,ctx:{common:_.parent.common,data:_.data,parsedType:Q6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let $=this._parse(_);if(Q1($))throw Error("Synchronous parse encountered promise.");return $}_parseAsync(_){let $=this._parse(_);return Promise.resolve($)}parse(_,$){let D=this.safeParse(_,$);if(D.success)return D.data;throw D.error}safeParse(_,$){let D={common:{issues:[],async:$?.async??!1,contextualErrorMap:$?.errorMap},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Q6(_)},I=this._parseSync({data:_,path:D.path,parent:D});return H9(D,I)}"~validate"(_){let $={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Q6(_)};if(!this["~standard"].async)try{let D=this._parseSync({data:_,path:[],parent:$});return t4(D)?{value:D.value}:{issues:$.common.issues}}catch(D){if(D?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;$.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:$}).then((D)=>t4(D)?{value:D.value}:{issues:$.common.issues})}async parseAsync(_,$){let D=await this.safeParseAsync(_,$);if(D.success)return D.data;throw D.error}async safeParseAsync(_,$){let D={common:{issues:[],contextualErrorMap:$?.errorMap,async:!0},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Q6(_)},I=this._parse({data:_,path:D.path,parent:D}),U=await(Q1(I)?I:Promise.resolve(I));return H9(D,U)}refine(_,$){let D=(I)=>{if(typeof $==="string"||typeof $>"u")return{message:$};else if(typeof $==="function")return $(I);else return $};return this._refinement((I,U)=>{let E=_(I),j=()=>U.addIssue({code:C.custom,...D(I)});if(typeof Promise<"u"&&E instanceof Promise)return E.then((N)=>{if(!N)return j(),!1;else return!0});if(!E)return j(),!1;else return!0})}refinement(_,$){return this._refinement((D,I)=>{if(!_(D))return I.addIssue(typeof $==="function"?$(D,I):$),!1;else return!0})}_refinement(_){return new Q$({schema:this,typeName:t.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 v$.create(this,this._def)}nullable(){return K6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return C$.create(this)}promise(){return a4.create(this,this._def)}or(_){return RD.create([this,_],this._def)}and(_){return YD.create(this,_,this._def)}transform(_){return new Q$({...s(this._def),schema:this,typeName:t.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let $=typeof _==="function"?_:()=>_;return new FD({...s(this._def),innerType:this,defaultValue:$,typeName:t.ZodDefault})}brand(){return new TN({typeName:t.ZodBranded,type:this,...s(this._def)})}catch(_){let $=typeof _==="function"?_:()=>_;return new VD({...s(this._def),innerType:this,catchValue:$,typeName:t.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return M1.create(this,_)}readonly(){return BD.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var zk=/^c[^\s-]{8,}$/i,Xk=/^[0-9a-z]+$/,Gk=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rk=/^[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,Yk=/^[a-z0-9_-]{21}$/i,Qk=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Kk=/^[-+]?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)?)??$/,Tk=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fk="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",oW,Vk=/^(?:(?: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])$/,Bk=/^(?:(?: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])$/,Mk=/^(([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]))$/,bk=/^(([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])$/,Zk=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hk=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,h9="((\\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])))",kk=new RegExp(`^${h9}$`);function c9(_){let $="[0-5]\\d";if(_.precision)$=`${$}\\.\\d{${_.precision}}`;else if(_.precision==null)$=`${$}(\\.\\d+)?`;let D=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${D}`}function qk(_){return new RegExp(`^${c9(_)}$`)}function n9(_){let $=`${h9}T${c9(_)}`,D=[];if(D.push(_.local?"Z?":"Z"),_.offset)D.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${D.join("|")})`,new RegExp(`^${$}$`)}function Ck(_,$){if(($==="v4"||!$)&&Vk.test(_))return!0;if(($==="v6"||!$)&&Mk.test(_))return!0;return!1}function vk(_,$){if(!Qk.test(_))return!1;try{let[D]=_.split(".");if(!D)return!1;let I=D.replace(/-/g,"+").replace(/_/g,"/").padEnd(D.length+(4-D.length%4)%4,"="),U=JSON.parse(atob(I));if(typeof U!=="object"||U===null)return!1;if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if($&&U.alg!==$)return!1;return!0}catch{return!1}}function wk(_,$){if(($==="v4"||!$)&&Bk.test(_))return!0;if(($==="v6"||!$)&&bk.test(_))return!0;return!1}class q$ extends $_{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==h.string){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_type,expected:h.string,received:U.parsedType}),i}let D=new l_,I=void 0;for(let U of this._def.checks)if(U.kind==="min"){if(_.data.lengthU.value)I=this._getOrReturnCtx(_,I),u(I,{code:C.too_big,maximum:U.value,type:"string",inclusive:!0,exact:!1,message:U.message}),D.dirty()}else if(U.kind==="length"){let E=_.data.length>U.value,j=_.data.length_.test(I),{validation:$,code:C.invalid_string,...d.errToObj(D)})}_addCheck(_){return new q$({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...d.errToObj(_)})}url(_){return this._addCheck({kind:"url",...d.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...d.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...d.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...d.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...d.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...d.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...d.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...d.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...d.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...d.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...d.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...d.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,...d.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,...d.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...d.errToObj(_)})}regex(_,$){return this._addCheck({kind:"regex",regex:_,...d.errToObj($)})}includes(_,$){return this._addCheck({kind:"includes",value:_,position:$?.position,...d.errToObj($?.message)})}startsWith(_,$){return this._addCheck({kind:"startsWith",value:_,...d.errToObj($)})}endsWith(_,$){return this._addCheck({kind:"endsWith",value:_,...d.errToObj($)})}min(_,$){return this._addCheck({kind:"min",value:_,...d.errToObj($)})}max(_,$){return this._addCheck({kind:"max",value:_,...d.errToObj($)})}length(_,$){return this._addCheck({kind:"length",value:_,...d.errToObj($)})}nonempty(_){return this.min(1,d.errToObj(_))}trim(){return new q$({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new q$({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new q$({...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 _}}q$.create=(_)=>{return new q$({checks:[],typeName:t.ZodString,coerce:_?.coerce??!1,...s(_)})};function rk(_,$){let D=(_.toString().split(".")[1]||"").length,I=($.toString().split(".")[1]||"").length,U=D>I?D:I,E=Number.parseInt(_.toFixed(U).replace(".","")),j=Number.parseInt($.toFixed(U).replace(".",""));return E%j/10**U}class e6 extends $_{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(_)!==h.number){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_type,expected:h.number,received:U.parsedType}),i}let D=void 0,I=new l_;for(let U of this._def.checks)if(U.kind==="int"){if(!N_.isInteger(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:C.invalid_type,expected:"integer",received:"float",message:U.message}),I.dirty()}else if(U.kind==="min"){if(U.inclusive?_.dataU.value:_.data>=U.value)D=this._getOrReturnCtx(_,D),u(D,{code:C.too_big,maximum:U.value,type:"number",inclusive:U.inclusive,exact:!1,message:U.message}),I.dirty()}else if(U.kind==="multipleOf"){if(rk(_.data,U.value)!==0)D=this._getOrReturnCtx(_,D),u(D,{code:C.not_multiple_of,multipleOf:U.value,message:U.message}),I.dirty()}else if(U.kind==="finite"){if(!Number.isFinite(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:C.not_finite,message:U.message}),I.dirty()}else N_.assertNever(U);return{status:I.value,value:_.data}}gte(_,$){return this.setLimit("min",_,!0,d.toString($))}gt(_,$){return this.setLimit("min",_,!1,d.toString($))}lte(_,$){return this.setLimit("max",_,!0,d.toString($))}lt(_,$){return this.setLimit("max",_,!1,d.toString($))}setLimit(_,$,D,I){return new e6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:d.toString(I)}]})}_addCheck(_){return new e6({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:d.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:d.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:d.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:d.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:d.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:d.toString($)})}finite(_){return this._addCheck({kind:"finite",message:d.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:d.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:d.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"&&N_.isInteger(_.value))}get isFinite(){let _=null,$=null;for(let D of this._def.checks)if(D.kind==="finite"||D.kind==="int"||D.kind==="multipleOf")return!0;else if(D.kind==="min"){if($===null||D.value>$)$=D.value}else if(D.kind==="max"){if(_===null||D.value<_)_=D.value}return Number.isFinite($)&&Number.isFinite(_)}}e6.create=(_)=>{return new e6({checks:[],typeName:t.ZodNumber,coerce:_?.coerce||!1,...s(_)})};class a6 extends $_{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(_)!==h.bigint)return this._getInvalidInput(_);let D=void 0,I=new l_;for(let U of this._def.checks)if(U.kind==="min"){if(U.inclusive?_.dataU.value:_.data>=U.value)D=this._getOrReturnCtx(_,D),u(D,{code:C.too_big,type:"bigint",maximum:U.value,inclusive:U.inclusive,message:U.message}),I.dirty()}else if(U.kind==="multipleOf"){if(_.data%U.value!==BigInt(0))D=this._getOrReturnCtx(_,D),u(D,{code:C.not_multiple_of,multipleOf:U.value,message:U.message}),I.dirty()}else N_.assertNever(U);return{status:I.value,value:_.data}}_getInvalidInput(_){let $=this._getOrReturnCtx(_);return u($,{code:C.invalid_type,expected:h.bigint,received:$.parsedType}),i}gte(_,$){return this.setLimit("min",_,!0,d.toString($))}gt(_,$){return this.setLimit("min",_,!1,d.toString($))}lte(_,$){return this.setLimit("max",_,!0,d.toString($))}lt(_,$){return this.setLimit("max",_,!1,d.toString($))}setLimit(_,$,D,I){return new a6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:d.toString(I)}]})}_addCheck(_){return new a6({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:d.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:d.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:d.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:d.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:d.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 _}}a6.create=(_)=>{return new a6({checks:[],typeName:t.ZodBigInt,coerce:_?.coerce??!1,...s(_)})};class zD extends $_{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==h.boolean){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.boolean,received:D.parsedType}),i}return s_(_.data)}}zD.create=(_)=>{return new zD({typeName:t.ZodBoolean,coerce:_?.coerce||!1,...s(_)})};class o4 extends $_{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==h.date){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_type,expected:h.date,received:U.parsedType}),i}if(Number.isNaN(_.data.getTime())){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_date}),i}let D=new l_,I=void 0;for(let U of this._def.checks)if(U.kind==="min"){if(_.data.getTime()U.value)I=this._getOrReturnCtx(_,I),u(I,{code:C.too_big,message:U.message,inclusive:!0,exact:!1,maximum:U.value,type:"date"}),D.dirty()}else N_.assertNever(U);return{status:D.value,value:new Date(_.data.getTime())}}_addCheck(_){return new o4({...this._def,checks:[...this._def.checks,_]})}min(_,$){return this._addCheck({kind:"min",value:_.getTime(),message:d.toString($)})}max(_,$){return this._addCheck({kind:"max",value:_.getTime(),message:d.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}}o4.create=(_)=>{return new o4({checks:[],coerce:_?.coerce||!1,typeName:t.ZodDate,...s(_)})};class K1 extends $_{_parse(_){if(this._getType(_)!==h.symbol){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.symbol,received:D.parsedType}),i}return s_(_.data)}}K1.create=(_)=>{return new K1({typeName:t.ZodSymbol,...s(_)})};class XD extends $_{_parse(_){if(this._getType(_)!==h.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.undefined,received:D.parsedType}),i}return s_(_.data)}}XD.create=(_)=>{return new XD({typeName:t.ZodUndefined,...s(_)})};class GD extends $_{_parse(_){if(this._getType(_)!==h.null){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.null,received:D.parsedType}),i}return s_(_.data)}}GD.create=(_)=>{return new GD({typeName:t.ZodNull,...s(_)})};class p4 extends $_{constructor(){super(...arguments);this._any=!0}_parse(_){return s_(_.data)}}p4.create=(_)=>{return new p4({typeName:t.ZodAny,...s(_)})};class p6 extends $_{constructor(){super(...arguments);this._unknown=!0}_parse(_){return s_(_.data)}}p6.create=(_)=>{return new p6({typeName:t.ZodUnknown,...s(_)})};class o$ extends $_{_parse(_){let $=this._getOrReturnCtx(_);return u($,{code:C.invalid_type,expected:h.never,received:$.parsedType}),i}}o$.create=(_)=>{return new o$({typeName:t.ZodNever,...s(_)})};class T1 extends $_{_parse(_){if(this._getType(_)!==h.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.void,received:D.parsedType}),i}return s_(_.data)}}T1.create=(_)=>{return new T1({typeName:t.ZodVoid,...s(_)})};class C$ extends $_{_parse(_){let{ctx:$,status:D}=this._processInputParams(_),I=this._def;if($.parsedType!==h.array)return u($,{code:C.invalid_type,expected:h.array,received:$.parsedType}),i;if(I.exactLength!==null){let E=$.data.length>I.exactLength.value,j=$.data.lengthI.maxLength.value)u($,{code:C.too_big,maximum:I.maxLength.value,type:"array",inclusive:!0,exact:!1,message:I.maxLength.message}),D.dirty()}if($.common.async)return Promise.all([...$.data].map((E,j)=>{return I.type._parseAsync(new w$($,E,$.path,j))})).then((E)=>{return l_.mergeArray(D,E)});let U=[...$.data].map((E,j)=>{return I.type._parseSync(new w$($,E,$.path,j))});return l_.mergeArray(D,U)}get element(){return this._def.type}min(_,$){return new C$({...this._def,minLength:{value:_,message:d.toString($)}})}max(_,$){return new C$({...this._def,maxLength:{value:_,message:d.toString($)}})}length(_,$){return new C$({...this._def,exactLength:{value:_,message:d.toString($)}})}nonempty(_){return this.min(1,_)}}C$.create=(_,$)=>{return new C$({type:_,minLength:null,maxLength:null,exactLength:null,typeName:t.ZodArray,...s($)})};function OD(_){if(_ instanceof H_){let $={};for(let D in _.shape){let I=_.shape[D];$[D]=v$.create(OD(I))}return new H_({..._._def,shape:()=>$})}else if(_ instanceof C$)return new C$({..._._def,type:OD(_.element)});else if(_ instanceof v$)return v$.create(OD(_.unwrap()));else if(_ instanceof K6)return K6.create(OD(_.unwrap()));else if(_ instanceof p$)return p$.create(_.items.map(($)=>OD($)));else return _}class H_ extends $_{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(),$=N_.objectKeys(_);return this._cached={shape:_,keys:$},this._cached}_parse(_){if(this._getType(_)!==h.object){let A=this._getOrReturnCtx(_);return u(A,{code:C.invalid_type,expected:h.object,received:A.parsedType}),i}let{status:D,ctx:I}=this._processInputParams(_),{shape:U,keys:E}=this._getCached(),j=[];if(!(this._def.catchall instanceof o$&&this._def.unknownKeys==="strip")){for(let A in I.data)if(!E.includes(A))j.push(A)}let N=[];for(let A of E){let O=U[A],S=I.data[A];N.push({key:{status:"valid",value:A},value:O._parse(new w$(I,S,I.path,A)),alwaysSet:A in I.data})}if(this._def.catchall instanceof o$){let A=this._def.unknownKeys;if(A==="passthrough")for(let O of j)N.push({key:{status:"valid",value:O},value:{status:"valid",value:I.data[O]}});else if(A==="strict"){if(j.length>0)u(I,{code:C.unrecognized_keys,keys:j}),D.dirty()}else if(A==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let A=this._def.catchall;for(let O of j){let S=I.data[O];N.push({key:{status:"valid",value:O},value:A._parse(new w$(I,S,I.path,O)),alwaysSet:O in I.data})}}if(I.common.async)return Promise.resolve().then(async()=>{let A=[];for(let O of N){let S=await O.key,L=await O.value;A.push({key:S,value:L,alwaysSet:O.alwaysSet})}return A}).then((A)=>{return l_.mergeObjectSync(D,A)});else return l_.mergeObjectSync(D,N)}get shape(){return this._def.shape()}strict(_){return d.errToObj,new H_({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:($,D)=>{let I=this._def.errorMap?.($,D).message??D.defaultError;if($.code==="unrecognized_keys")return{message:d.errToObj(_).message??I};return{message:I}}}:{}})}strip(){return new H_({...this._def,unknownKeys:"strip"})}passthrough(){return new H_({...this._def,unknownKeys:"passthrough"})}extend(_){return new H_({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new H_({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:t.ZodObject})}setKey(_,$){return this.augment({[_]:$})}catchall(_){return new H_({...this._def,catchall:_})}pick(_){let $={};for(let D of N_.objectKeys(_))if(_[D]&&this.shape[D])$[D]=this.shape[D];return new H_({...this._def,shape:()=>$})}omit(_){let $={};for(let D of N_.objectKeys(this.shape))if(!_[D])$[D]=this.shape[D];return new H_({...this._def,shape:()=>$})}deepPartial(){return OD(this)}partial(_){let $={};for(let D of N_.objectKeys(this.shape)){let I=this.shape[D];if(_&&!_[D])$[D]=I;else $[D]=I.optional()}return new H_({...this._def,shape:()=>$})}required(_){let $={};for(let D of N_.objectKeys(this.shape))if(_&&!_[D])$[D]=this.shape[D];else{let U=this.shape[D];while(U instanceof v$)U=U._def.innerType;$[D]=U}return new H_({...this._def,shape:()=>$})}keyof(){return d9(N_.objectKeys(this.shape))}}H_.create=(_,$)=>{return new H_({shape:()=>_,unknownKeys:"strip",catchall:o$.create(),typeName:t.ZodObject,...s($)})};H_.strictCreate=(_,$)=>{return new H_({shape:()=>_,unknownKeys:"strict",catchall:o$.create(),typeName:t.ZodObject,...s($)})};H_.lazycreate=(_,$)=>{return new H_({shape:_,unknownKeys:"strip",catchall:o$.create(),typeName:t.ZodObject,...s($)})};class RD extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D=this._def.options;function I(U){for(let j of U)if(j.result.status==="valid")return j.result;for(let j of U)if(j.result.status==="dirty")return $.common.issues.push(...j.ctx.common.issues),j.result;let E=U.map((j)=>new L$(j.ctx.common.issues));return u($,{code:C.invalid_union,unionErrors:E}),i}if($.common.async)return Promise.all(D.map(async(U)=>{let E={...$,common:{...$.common,issues:[]},parent:null};return{result:await U._parseAsync({data:$.data,path:$.path,parent:E}),ctx:E}})).then(I);else{let U=void 0,E=[];for(let N of D){let A={...$,common:{...$.common,issues:[]},parent:null},O=N._parseSync({data:$.data,path:$.path,parent:A});if(O.status==="valid")return O;else if(O.status==="dirty"&&!U)U={result:O,ctx:A};if(A.common.issues.length)E.push(A.common.issues)}if(U)return $.common.issues.push(...U.ctx.common.issues),U.result;let j=E.map((N)=>new L$(N));return u($,{code:C.invalid_union,unionErrors:j}),i}}get options(){return this._def.options}}RD.create=(_,$)=>{return new RD({options:_,typeName:t.ZodUnion,...s($)})};var Y6=(_)=>{if(_ instanceof QD)return Y6(_.schema);else if(_ instanceof Q$)return Y6(_.innerType());else if(_ instanceof KD)return[_.value];else if(_ instanceof s6)return _.options;else if(_ instanceof TD)return N_.objectValues(_.enum);else if(_ instanceof FD)return Y6(_._def.innerType);else if(_ instanceof XD)return[void 0];else if(_ instanceof GD)return[null];else if(_ instanceof v$)return[void 0,...Y6(_.unwrap())];else if(_ instanceof K6)return[null,...Y6(_.unwrap())];else if(_ instanceof TN)return Y6(_.unwrap());else if(_ instanceof BD)return Y6(_.unwrap());else if(_ instanceof VD)return Y6(_._def.innerType);else return[]};class KN extends $_{_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==h.object)return u($,{code:C.invalid_type,expected:h.object,received:$.parsedType}),i;let D=this.discriminator,I=$.data[D],U=this.optionsMap.get(I);if(!U)return u($,{code:C.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[D]}),i;if($.common.async)return U._parseAsync({data:$.data,path:$.path,parent:$});else return U._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(_,$,D){let I=new Map;for(let U of $){let E=Y6(U.shape[_]);if(!E.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let j of E){if(I.has(j))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(j)}`);I.set(j,U)}}return new KN({typeName:t.ZodDiscriminatedUnion,discriminator:_,options:$,optionsMap:I,...s(D)})}}function _P(_,$){let D=Q6(_),I=Q6($);if(_===$)return{valid:!0,data:_};else if(D===h.object&&I===h.object){let U=N_.objectKeys($),E=N_.objectKeys(_).filter((N)=>U.indexOf(N)!==-1),j={..._,...$};for(let N of E){let A=_P(_[N],$[N]);if(!A.valid)return{valid:!1};j[N]=A.data}return{valid:!0,data:j}}else if(D===h.array&&I===h.array){if(_.length!==$.length)return{valid:!1};let U=[];for(let E=0;E<_.length;E++){let j=_[E],N=$[E],A=_P(j,N);if(!A.valid)return{valid:!1};U.push(A.data)}return{valid:!0,data:U}}else if(D===h.date&&I===h.date&&+_===+$)return{valid:!0,data:_};else return{valid:!1}}class YD extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_),I=(U,E)=>{if(aW(U)||aW(E))return i;let j=_P(U.value,E.value);if(!j.valid)return u(D,{code:C.invalid_intersection_types}),i;if(sW(U)||sW(E))$.dirty();return{status:$.value,value:j.data}};if(D.common.async)return Promise.all([this._def.left._parseAsync({data:D.data,path:D.path,parent:D}),this._def.right._parseAsync({data:D.data,path:D.path,parent:D})]).then(([U,E])=>I(U,E));else return I(this._def.left._parseSync({data:D.data,path:D.path,parent:D}),this._def.right._parseSync({data:D.data,path:D.path,parent:D}))}}YD.create=(_,$,D)=>{return new YD({left:_,right:$,typeName:t.ZodIntersection,...s(D)})};class p$ extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.array)return u(D,{code:C.invalid_type,expected:h.array,received:D.parsedType}),i;if(D.data.lengththis._def.items.length)u(D,{code:C.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let U=[...D.data].map((E,j)=>{let N=this._def.items[j]||this._def.rest;if(!N)return null;return N._parse(new w$(D,E,D.path,j))}).filter((E)=>!!E);if(D.common.async)return Promise.all(U).then((E)=>{return l_.mergeArray($,E)});else return l_.mergeArray($,U)}get items(){return this._def.items}rest(_){return new p$({...this._def,rest:_})}}p$.create=(_,$)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new p$({items:_,typeName:t.ZodTuple,rest:null,...s($)})};class F1 extends $_{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.object)return u(D,{code:C.invalid_type,expected:h.object,received:D.parsedType}),i;let I=[],U=this._def.keyType,E=this._def.valueType;for(let j in D.data)I.push({key:U._parse(new w$(D,j,D.path,j)),value:E._parse(new w$(D,D.data[j],D.path,j)),alwaysSet:j in D.data});if(D.common.async)return l_.mergeObjectAsync($,I);else return l_.mergeObjectSync($,I)}get element(){return this._def.valueType}static create(_,$,D){if($ instanceof $_)return new F1({keyType:_,valueType:$,typeName:t.ZodRecord,...s(D)});return new F1({keyType:q$.create(),valueType:_,typeName:t.ZodRecord,...s($)})}}class V1 extends $_{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.map)return u(D,{code:C.invalid_type,expected:h.map,received:D.parsedType}),i;let I=this._def.keyType,U=this._def.valueType,E=[...D.data.entries()].map(([j,N],A)=>{return{key:I._parse(new w$(D,j,D.path,[A,"key"])),value:U._parse(new w$(D,N,D.path,[A,"value"]))}});if(D.common.async){let j=new Map;return Promise.resolve().then(async()=>{for(let N of E){let A=await N.key,O=await N.value;if(A.status==="aborted"||O.status==="aborted")return i;if(A.status==="dirty"||O.status==="dirty")$.dirty();j.set(A.value,O.value)}return{status:$.value,value:j}})}else{let j=new Map;for(let N of E){let{key:A,value:O}=N;if(A.status==="aborted"||O.status==="aborted")return i;if(A.status==="dirty"||O.status==="dirty")$.dirty();j.set(A.value,O.value)}return{status:$.value,value:j}}}}V1.create=(_,$,D)=>{return new V1({valueType:$,keyType:_,typeName:t.ZodMap,...s(D)})};class e4 extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.set)return u(D,{code:C.invalid_type,expected:h.set,received:D.parsedType}),i;let I=this._def;if(I.minSize!==null){if(D.data.sizeI.maxSize.value)u(D,{code:C.too_big,maximum:I.maxSize.value,type:"set",inclusive:!0,exact:!1,message:I.maxSize.message}),$.dirty()}let U=this._def.valueType;function E(N){let A=new Set;for(let O of N){if(O.status==="aborted")return i;if(O.status==="dirty")$.dirty();A.add(O.value)}return{status:$.value,value:A}}let j=[...D.data.values()].map((N,A)=>U._parse(new w$(D,N,D.path,A)));if(D.common.async)return Promise.all(j).then((N)=>E(N));else return E(j)}min(_,$){return new e4({...this._def,minSize:{value:_,message:d.toString($)}})}max(_,$){return new e4({...this._def,maxSize:{value:_,message:d.toString($)}})}size(_,$){return this.min(_,$).max(_,$)}nonempty(_){return this.min(1,_)}}e4.create=(_,$)=>{return new e4({valueType:_,minSize:null,maxSize:null,typeName:t.ZodSet,...s($)})};class JD extends $_{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==h.function)return u($,{code:C.invalid_type,expected:h.function,received:$.parsedType}),i;function D(j,N){return RN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,GN(),PD].filter((A)=>!!A),issueData:{code:C.invalid_arguments,argumentsError:N}})}function I(j,N){return RN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,GN(),PD].filter((A)=>!!A),issueData:{code:C.invalid_return_type,returnTypeError:N}})}let U={errorMap:$.common.contextualErrorMap},E=$.data;if(this._def.returns instanceof a4){let j=this;return s_(async function(...N){let A=new L$([]),O=await j._def.args.parseAsync(N,U).catch((P)=>{throw A.addIssue(D(N,P)),A}),S=await Reflect.apply(E,this,O);return await j._def.returns._def.type.parseAsync(S,U).catch((P)=>{throw A.addIssue(I(S,P)),A})})}else{let j=this;return s_(function(...N){let A=j._def.args.safeParse(N,U);if(!A.success)throw new L$([D(N,A.error)]);let O=Reflect.apply(E,this,A.data),S=j._def.returns.safeParse(O,U);if(!S.success)throw new L$([I(O,S.error)]);return S.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new JD({...this._def,args:p$.create(_).rest(p6.create())})}returns(_){return new JD({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,$,D){return new JD({args:_?_:p$.create([]).rest(p6.create()),returns:$||p6.create(),typeName:t.ZodFunction,...s(D)})}}class QD extends $_{get schema(){return this._def.getter()}_parse(_){let{ctx:$}=this._processInputParams(_);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}QD.create=(_,$)=>{return new QD({getter:_,typeName:t.ZodLazy,...s($)})};class KD extends $_{_parse(_){if(_.data!==this._def.value){let $=this._getOrReturnCtx(_);return u($,{received:$.data,code:C.invalid_literal,expected:this._def.value}),i}return{status:"valid",value:_.data}}get value(){return this._def.value}}KD.create=(_,$)=>{return new KD({value:_,typeName:t.ZodLiteral,...s($)})};function d9(_,$){return new s6({values:_,typeName:t.ZodEnum,...s($)})}class s6 extends $_{_parse(_){if(typeof _.data!=="string"){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{expected:N_.joinValues(D),received:$.parsedType,code:C.invalid_type}),i}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{received:$.data,code:C.invalid_enum_value,options:D}),i}return s_(_.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 s6.create(_,{...this._def,...$})}exclude(_,$=this._def){return s6.create(this.options.filter((D)=>!_.includes(D)),{...this._def,...$})}}s6.create=d9;class TD extends $_{_parse(_){let $=N_.getValidEnumValues(this._def.values),D=this._getOrReturnCtx(_);if(D.parsedType!==h.string&&D.parsedType!==h.number){let I=N_.objectValues($);return u(D,{expected:N_.joinValues(I),received:D.parsedType,code:C.invalid_type}),i}if(!this._cache)this._cache=new Set(N_.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let I=N_.objectValues($);return u(D,{received:D.data,code:C.invalid_enum_value,options:I}),i}return s_(_.data)}get enum(){return this._def.values}}TD.create=(_,$)=>{return new TD({values:_,typeName:t.ZodNativeEnum,...s($)})};class a4 extends $_{unwrap(){return this._def.type}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==h.promise&&$.common.async===!1)return u($,{code:C.invalid_type,expected:h.promise,received:$.parsedType}),i;let D=$.parsedType===h.promise?$.data:Promise.resolve($.data);return s_(D.then((I)=>{return this._def.type.parseAsync(I,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}a4.create=(_,$)=>{return new a4({type:_,typeName:t.ZodPromise,...s($)})};class Q$ extends $_{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===t.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:$,ctx:D}=this._processInputParams(_),I=this._def.effect||null,U={addIssue:(E)=>{if(u(D,E),E.fatal)$.abort();else $.dirty()},get path(){return D.path}};if(U.addIssue=U.addIssue.bind(U),I.type==="preprocess"){let E=I.transform(D.data,U);if(D.common.async)return Promise.resolve(E).then(async(j)=>{if($.value==="aborted")return i;let N=await this._def.schema._parseAsync({data:j,path:D.path,parent:D});if(N.status==="aborted")return i;if(N.status==="dirty")return LD(N.value);if($.value==="dirty")return LD(N.value);return N});else{if($.value==="aborted")return i;let j=this._def.schema._parseSync({data:E,path:D.path,parent:D});if(j.status==="aborted")return i;if(j.status==="dirty")return LD(j.value);if($.value==="dirty")return LD(j.value);return j}}if(I.type==="refinement"){let E=(j)=>{let N=I.refinement(j,U);if(D.common.async)return Promise.resolve(N);if(N instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return j};if(D.common.async===!1){let j=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(j.status==="aborted")return i;if(j.status==="dirty")$.dirty();return E(j.value),{status:$.value,value:j.value}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((j)=>{if(j.status==="aborted")return i;if(j.status==="dirty")$.dirty();return E(j.value).then(()=>{return{status:$.value,value:j.value}})})}if(I.type==="transform")if(D.common.async===!1){let E=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(!t4(E))return i;let j=I.transform(E.value,U);if(j instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:j}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((E)=>{if(!t4(E))return i;return Promise.resolve(I.transform(E.value,U)).then((j)=>({status:$.value,value:j}))});N_.assertNever(I)}}Q$.create=(_,$,D)=>{return new Q$({schema:_,typeName:t.ZodEffects,effect:$,...s(D)})};Q$.createWithPreprocess=(_,$,D)=>{return new Q$({schema:$,effect:{type:"preprocess",transform:_},typeName:t.ZodEffects,...s(D)})};class v$ extends $_{_parse(_){if(this._getType(_)===h.undefined)return s_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}v$.create=(_,$)=>{return new v$({innerType:_,typeName:t.ZodOptional,...s($)})};class K6 extends $_{_parse(_){if(this._getType(_)===h.null)return s_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}K6.create=(_,$)=>{return new K6({innerType:_,typeName:t.ZodNullable,...s($)})};class FD extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;if($.parsedType===h.undefined)D=this._def.defaultValue();return this._def.innerType._parse({data:D,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}FD.create=(_,$)=>{return new FD({innerType:_,typeName:t.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...s($)})};class VD extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D={...$,common:{...$.common,issues:[]}},I=this._def.innerType._parse({data:D.data,path:D.path,parent:{...D}});if(Q1(I))return I.then((U)=>{return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new L$(D.common.issues)},input:D.data})}});else return{status:"valid",value:I.status==="valid"?I.value:this._def.catchValue({get error(){return new L$(D.common.issues)},input:D.data})}}removeCatch(){return this._def.innerType}}VD.create=(_,$)=>{return new VD({innerType:_,typeName:t.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...s($)})};class B1 extends $_{_parse(_){if(this._getType(_)!==h.nan){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.nan,received:D.parsedType}),i}return{status:"valid",value:_.data}}}B1.create=(_)=>{return new B1({typeName:t.ZodNaN,...s(_)})};var fk=Symbol("zod_brand");class TN extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;return this._def.type._parse({data:D,path:$.path,parent:$})}unwrap(){return this._def.type}}class M1 extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.common.async)return(async()=>{let U=await this._def.in._parseAsync({data:D.data,path:D.path,parent:D});if(U.status==="aborted")return i;if(U.status==="dirty")return $.dirty(),LD(U.value);else return this._def.out._parseAsync({data:U.value,path:D.path,parent:D})})();else{let I=this._def.in._parseSync({data:D.data,path:D.path,parent:D});if(I.status==="aborted")return i;if(I.status==="dirty")return $.dirty(),{status:"dirty",value:I.value};else return this._def.out._parseSync({data:I.value,path:D.path,parent:D})}}static create(_,$){return new M1({in:_,out:$,typeName:t.ZodPipeline})}}class BD extends $_{_parse(_){let $=this._def.innerType._parse(_),D=(I)=>{if(t4(I))I.value=Object.freeze(I.value);return I};return Q1($)?$.then((I)=>D(I)):D($)}unwrap(){return this._def.innerType}}BD.create=(_,$)=>{return new BD({innerType:_,typeName:t.ZodReadonly,...s($)})};function k9(_,$){let D=typeof _==="function"?_($):typeof _==="string"?{message:_}:_;return typeof D==="string"?{message:D}:D}function m9(_,$={},D){if(_)return p4.create().superRefine((I,U)=>{let E=_(I);if(E instanceof Promise)return E.then((j)=>{if(!j){let N=k9($,I),A=N.fatal??D??!0;U.addIssue({code:"custom",...N,fatal:A})}});if(!E){let j=k9($,I),N=j.fatal??D??!0;U.addIssue({code:"custom",...j,fatal:N})}return});return p4.create()}var xk={object:H_.lazycreate},t;(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"})(t||(t={}));var uk=(_,$={message:`Input not instance of ${_.name}`})=>m9((D)=>D instanceof _,$),l9=q$.create,i9=e6.create,yk=B1.create,hk=a6.create,t9=zD.create,ck=o4.create,nk=K1.create,dk=XD.create,mk=GD.create,lk=p4.create,ik=p6.create,tk=o$.create,ok=T1.create,pk=C$.create,ek=H_.create,ak=H_.strictCreate,sk=RD.create,_q=KN.create,$q=YD.create,Dq=p$.create,Uq=F1.create,Iq=V1.create,Eq=e4.create,jq=JD.create,Nq=QD.create,gq=KD.create,Aq=s6.create,Oq=TD.create,Sq=a4.create,q9=Q$.create,Lq=v$.create,Jq=K6.create,Wq=Q$.createWithPreprocess,Pq=M1.create,zq=()=>l9().optional(),Xq=()=>i9().optional(),Gq=()=>t9().optional(),Rq={string:(_)=>q$.create({..._,coerce:!0}),number:(_)=>e6.create({..._,coerce:!0}),boolean:(_)=>zD.create({..._,coerce:!0}),bigint:(_)=>a6.create({..._,coerce:!0}),date:(_)=>o4.create({..._,coerce:!0})},Yq=i;var y={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",taskToPrProjection:"hasna.task_to_pr_projection.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",secureLocalStorePolicy:"hasna.secure_local_store_policy.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"},DP=g.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),B_=g.string().datetime(),p=g.string().trim().min(1),r$=p.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://"),o9=g.string().regex(/^[a-fA-F0-9]{64}$/),p9=g.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),_4=g.record(g.unknown()),ZD=g.array(g.string().min(1)).default([]),s4=B_.nullable().optional(),Qq=new Set(["succeeded","failed","cancelled","blocked","skipped"]),D0=g.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function J_(_){return g.object({schema:g.literal(_),id:g.string().min(1),createdAt:B_,updatedAt:s4,metadata:_4.optional()}).strict()}var Sm=g.object({schema:DP,id:g.string().min(1),createdAt:B_,updatedAt:s4,metadata:_4.optional()}).strict(),e9=g.enum(["agent","human","service","model","workflow","system"]),Kq=J_(y.actorRef).extend({kind:e9,name:g.string().min(1).optional(),provider:g.string().min(1).optional(),accountId:g.string().min(1).optional(),machineId:g.string().min(1).optional(),capabilities:g.array(g.string().min(1)).default([])}).strict(),e$=g.object({kind:e9,id:g.string().min(1),name:g.string().min(1).optional(),provider:g.string().min(1).optional(),accountId:g.string().min(1).optional(),machineId:g.string().min(1).optional()}).strict(),a9=g.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"]),Tq=J_(y.resourceRef).extend({kind:a9,name:g.string().min(1).optional(),uri:r$.optional(),externalId:p.optional(),sourcePackage:p.optional(),tags:ZD}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.externalId&&_.sourcePackage))$.addIssue({code:g.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),__=g.object({kind:a9,id:g.string().min(1),name:g.string().min(1).optional(),uri:r$.optional(),externalId:p.optional(),sourcePackage:p.optional(),tags:ZD}).strict().superRefine((_,$)=>{if(!_.uri&&Boolean(_.externalId)!==Boolean(_.sourcePackage))$.addIssue({code:g.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:_.externalId?["sourcePackage"]:["externalId"]})}),UP=g.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),Fq=g.enum(["none","partial","full","unknown"]),Vq=J_(y.evidenceRef).extend({kind:UP,uri:r$,sha256:o9.optional(),summary:g.string().min(1).optional(),contentType:g.string().min(1).optional(),sizeBytes:g.number().int().nonnegative().optional(),redaction:Fq.default("unknown"),producer:e$.optional(),resourceRefs:g.array(__).default([]),tags:ZD}).strict(),T_=g.object({id:g.string().min(1),kind:UP.optional(),uri:r$.optional(),sha256:o9.optional(),summary:g.string().min(1).optional()}).strict(),b1=J_(y.costEstimate).extend({currency:g.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:g.number().int().nonnegative(),provider:g.string().min(1).optional(),model:g.string().min(1).optional(),accountId:g.string().min(1).optional(),promptTokens:g.number().int().nonnegative().optional(),completionTokens:g.number().int().nonnegative().optional(),totalTokens:g.number().int().nonnegative().optional(),basis:g.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:g.array(__).default([])}).strict().superRefine((_,$)=>{if(_.promptTokens!==void 0&&_.completionTokens!==void 0&&_.totalTokens!==void 0&&_.totalTokens!==_.promptTokens+_.completionTokens)$.addIssue({code:g.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),Bq=g.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),s9=J_(y.decisionEnvelope).extend({decisionType:g.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:Bq,actor:e$.optional(),traceId:g.string().min(1).optional(),inputHash:p9.optional(),policyBundleId:g.string().min(1).optional(),selected:g.array(__).default([]),skipped:g.array(__).default([]),reason:g.string().min(1),obligations:g.array(g.string().min(1)).default([]),redactions:g.array(g.string().min(1)).default([]),costEstimate:b1.optional(),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.status==="selected"&&_.selected.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if(_.status==="skipped"&&_.skipped.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if(_.status==="denied"){if(_.selected.length>0)$.addIssue({code:g.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!_.policyBundleId&&_.evidenceRefs.length===0&&_.obligations.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if(_.status==="approval_required"&&_.obligations.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),Mq=J_(y.capabilityCard).extend({kind:g.enum(["model","tool","machine","agent","lane","connector","service"]),name:g.string().min(1),version:g.string().min(1).optional(),status:g.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:g.array(g.string().min(1)).default([]),limitations:g.array(g.string().min(1)).default([]),riskLevel:g.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:b1.optional(),evidenceRefs:g.array(T_).default([])}).strict(),MD=g.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),bq=g.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"]),Zq=g.object({refName:p,requiredForModes:g.array(MD).min(1),allowedSecretInputs:g.array(g.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:p,revocationCheck:g.boolean().default(!0)}).strict(),Hq=g.object({operation:p,supportedModes:g.array(MD).min(1),sideEffectClass:bq,requiresApproval:g.boolean().default(!1),requiresIdempotencyKey:g.boolean().default(!1),requiresSandboxEvidence:g.boolean().default(!1),requiresRollbackOrRevocation:g.boolean().default(!1),rollbackOrRevocation:p.optional(),noSideEffectSmoke:p.optional(),reconciliation:p.optional()}).strict().superRefine((_,$)=>{if(_.supportedModes.includes("live_mutating")){if(_.sideEffectClass==="none"||_.sideEffectClass==="read_only")$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!_.requiresApproval)$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!_.requiresIdempotencyKey)$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!_.requiresSandboxEvidence)$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!_.requiresRollbackOrRevocation||!_.rollbackOrRevocation)$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!_.reconciliation)$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),kq=g.object({providerId:p,appId:p,adapterId:p,ownerPackage:p,modes:g.array(MD).min(1),defaultMode:MD,credentialRequirements:g.array(Zq).default([]),operations:g.array(Hq).min(1),rateLimitPosture:p,costPosture:p.optional(),auditEvents:g.array(p).default([]),redactionRules:g.array(p).default([]),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{if(!_.modes.includes(_.defaultMode))$.addIssue({code:g.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let D=new Set(_.operations.flatMap((I)=>I.supportedModes));for(let I of D)if(!_.modes.includes(I))$.addIssue({code:g.ZodIssueCode.custom,message:`operation mode ${I} is not declared in provider modes`,path:["operations"]});if(D.has("live_mutating")){if(!_.credentialRequirements.some((U)=>U.requiredForModes.includes("live_mutating")))$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if(_.auditEvents.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),qq=g.object({appId:p,repo:p,priority:g.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:g.array(p).min(1),firstOperations:g.array(p).min(1),blockedUntil:g.array(p).default([])}).strict(),Cq=J_(y.providerLiveModeStandard).extend({name:p,version:p,modes:g.array(MD).refine((_)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every(($)=>_.includes($)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:g.array(p).min(1),liveMutationGate:g.object({requiredMode:g.literal("live_mutating"),requiredChecks:g.array(p).min(1),forbiddenBypassSignals:g.array(p).min(1),disabledLiveSmoke:p}).strict(),noSideEffectSmoke:g.object({requiredForModes:g.array(MD).min(1),commandEvidence:g.array(p).min(1),secretOutputScan:g.boolean().default(!0)}).strict(),credentialPolicy:g.object({acceptedInputs:g.array(g.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:g.literal(!1),missingCredentialBehavior:g.literal("fail_closed"),revocationCheckRequired:g.boolean().default(!0)}).strict(),operationCards:g.array(kq).min(1),firstAdoptionTargets:g.array(qq).min(1),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set(_.firstAdoptionTargets.map((U)=>U.appId)),I=new Set(_.operationCards.map((U)=>U.appId));for(let U of D)if(!I.has(U))$.addIssue({code:g.ZodIssueCode.custom,message:`first adoption target ${U} requires a provider capability card`,path:["firstAdoptionTargets"]})}),vq=g.object({id:g.string().min(1),title:g.string().min(1).optional(),summary:g.string().min(1),text:g.string().optional(),tokens:g.number().int().nonnegative().optional(),source:T_,resourceRefs:g.array(__).default([])}).strict(),_8=J_(y.contextPack).extend({objective:g.string().min(1),budget:g.object({maxTokens:g.number().int().positive().optional(),maxBytes:g.number().int().positive().optional()}).strict().optional(),items:g.array(vq).default([]),citations:g.array(T_).default([]),freshness:g.enum(["fresh","stale","unknown"]).default("unknown"),permissions:g.array(g.string().min(1)).default([]),redactions:g.array(g.string().min(1)).default([]),conflicts:g.array(g.string().min(1)).default([]),uncertainty:g.string().min(1).optional()}).strict(),R$=p.refine((_)=>!_.startsWith("/")&&!_.includes("\\")&&!_.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),_0=g.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),wq=g.enum(["public","internal","private","sensitive"]),rq=g.enum(["draft","active","paused","archived"]),IP=g.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),$8=J_(y.integrationRef).extend({kind:IP,name:g.string().min(1),projectId:_0.optional(),sourcePackage:p.optional(),externalId:p.optional(),uri:r$.optional(),enabled:g.boolean().default(!0),readOnly:g.boolean().default(!0),capabilities:g.array(g.string().min(1)).default([]),freshness:g.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:__.optional(),evidenceRefs:g.array(T_).default([]),config:_4.optional()}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.sourcePackage&&_.externalId)&&!_.resourceRef)$.addIssue({code:g.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),fq=g.object({schemaRoot:R$.default(".hasna/project"),dashboardManifest:R$.default(".hasna/project/dashboard.render.json"),snapshotsDir:R$.default(".hasna/project/snapshots"),documentsDir:R$.default("documents"),reportsDir:R$.default("reports"),evidenceDir:R$.default(".hasna/project/evidence"),privateDir:R$.default(".hasna/project/private")}).strict(),xq=J_(y.projectManifest).extend({projectId:_0,slug:_0,name:g.string().min(1),summary:g.string().min(1).optional(),status:rq.default("active"),classification:wq.default("private"),owner:e$.optional(),layout:fq.default({}),integrations:g.array($8).default([]),renderManifests:g.array(__).default([]),resourceRefs:g.array(__).default([]),evidenceRefs:g.array(T_).default([]),tags:ZD}).strict().superRefine((_,$)=>{let D=new Set,I=new Set;if(_.projectId!==_.slug)$.addIssue({code:g.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[U,E]of _.integrations.entries()){if(D.has(E.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",U,"id"]});if(D.add(E.id),E.projectId&&E.projectId!==_.projectId)$.addIssue({code:g.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",U,"projectId"]})}for(let[U,E]of _.renderManifests.entries()){if(E.kind!=="render")$.addIssue({code:g.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",U,"kind"]});if(I.has(E.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",U,"id"]});I.add(E.id)}}),uq=g.enum(["local","package","provider","url"]),EP=g.object({id:g.string().min(1),kind:uq,specifier:g.string().min(1),path:R$.optional(),packageName:g.string().min(1).optional(),uri:r$.optional(),provider:IP.optional(),schemaId:DP.optional(),integrity:p9.optional(),resourceRef:__.optional(),optional:g.boolean().default(!1)}).strict().superRefine((_,$)=>{if(_.kind==="local"&&!_.path)$.addIssue({code:g.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if(_.kind==="package"&&!_.packageName)$.addIssue({code:g.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if(_.kind==="provider"&&!_.provider)$.addIssue({code:g.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if(_.kind==="url"&&!_.uri)$.addIssue({code:g.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),yq=g.enum(["dashboard","canvas","panel","report","document","custom"]),hq=g.object({id:g.string().min(1),title:g.string().min(1),kind:yq,default:g.boolean().default(!1),entry:R$.optional(),imports:g.array(EP).default([]),panelRefs:g.array(__).default([]),dataRefs:g.array(__).default([]),layout:_4.optional()}).strict(),cq=J_(y.renderManifest).extend({projectId:_0,name:g.string().min(1),version:g.string().min(1),manifestPath:R$.default(".hasna/project/dashboard.render.json"),renderer:g.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:g.array(hq).min(1),imports:g.array(EP).default([]),theme:_4.optional(),compatibility:g.object({minProjectsVersion:g.string().min(1).optional(),minContractsVersion:g.string().min(1).optional()}).strict().optional(),resourceRefs:g.array(__).default([]),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{let D=_.views.filter((E)=>E.default),I=new Set,U=new Set;if(D.length>1)$.addIssue({code:g.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[E,j]of _.imports.entries()){if(U.has(j.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",E,"id"]});U.add(j.id)}for(let[E,j]of _.views.entries()){if(I.has(j.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",E,"id"]});I.add(j.id);let N=new Set;for(let[A,O]of j.imports.entries()){if(N.has(O.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",E,"imports",A,"id"]});N.add(O.id)}for(let[A,O]of j.panelRefs.entries())if(O.kind!=="panel")$.addIssue({code:g.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",E,"panelRefs",A,"kind"]})}}),nq=g.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),dq=g.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),mq=g.object({id:g.string().min(1),label:g.string().min(1),value:g.union([g.string(),g.number(),g.boolean()]),unit:g.string().min(1).optional(),status:g.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:g.array(__).default([])}).strict(),lq=g.object({id:g.string().min(1),title:g.string().min(1),summary:g.string().min(1).optional(),status:g.string().min(1).optional(),priority:g.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:B_.optional(),resourceRefs:g.array(__).default([]),evidenceRefs:g.array(T_).default([]),metadata:_4.optional()}).strict(),iq=g.object({renderer:g.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:g.string().min(1).optional(),entry:R$.optional(),imports:g.array(EP).default([]),spec:_4.default({})}).strict(),D8=J_(y.projectPanel).extend({projectId:_0,provider:g.object({kind:IP,id:g.string().min(1),name:g.string().min(1).optional(),sourcePackage:p.optional(),externalId:p.optional()}).strict(),kind:dq,title:g.string().min(1),summary:g.string().min(1).optional(),state:nq.default("ready"),stateReason:g.string().min(1).optional(),generatedAt:B_,freshness:g.enum(["fresh","stale","unknown"]).default("unknown"),metrics:g.array(mq).default([]),items:g.array(lq).default([]),actions:g.array(__).default([]),resourceRefs:g.array(__).default([]),evidenceRefs:g.array(T_).default([]),renderFragment:iq.optional(),warnings:g.array(g.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set(["error","auth_required","unavailable","stale"]),I=new Set,U=new Set;if(D.has(_.state)&&!_.stateReason)$.addIssue({code:g.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if(_.state==="ready"&&_.metrics.length===0&&_.items.length===0&&!_.renderFragment)$.addIssue({code:g.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[E,j]of _.metrics.entries()){if(I.has(j.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",E,"id"]});I.add(j.id)}for(let[E,j]of _.items.entries()){if(U.has(j.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",E,"id"]});U.add(j.id)}for(let[E,j]of _.actions.entries())if(j.kind!=="action")$.addIssue({code:g.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",E,"kind"]})}),tq=J_(y.projectSnapshot).extend({projectId:_0,generatedAt:B_,status:D0.default("unknown"),manifestRef:__,renderManifestRef:__.optional(),panels:g.array(D8).default([]),contextPacks:g.array(_8).default([]),proofBundleRefs:g.array(__).default([]),resourceRefs:g.array(__).default([]),evidenceRefs:g.array(T_).default([]),warnings:g.array(g.string().min(1)).default([]),freshness:g.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{let D=new Set,I=new Set;if(_.manifestRef.kind!=="project")$.addIssue({code:g.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if(_.renderManifestRef&&_.renderManifestRef.kind!=="render")$.addIssue({code:g.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[U,E]of _.proofBundleRefs.entries())if(E.kind!=="proof_bundle")$.addIssue({code:g.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",U,"kind"]});for(let[U,E]of _.panels.entries()){if(E.projectId!==_.projectId)$.addIssue({code:g.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",U,"projectId"]});if(D.has(E.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",U,"id"]});D.add(E.id)}for(let[U,E]of _.contextPacks.entries()){if(I.has(E.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",U,"id"]});I.add(E.id)}}),U8=g.object({id:g.string().min(1),kind:g.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:g.boolean().default(!0),command:g.string().min(1).optional(),expected:g.string().min(1).optional(),timeoutMs:g.number().int().positive().optional(),resourceRefs:g.array(__).default([])}).strict().superRefine((_,$)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has(_.kind)&&!_.command&&!_.expected)$.addIssue({code:g.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),oq=J_(y.validationPlan).extend({objective:g.string().min(1),subject:__.optional(),checks:g.array(U8).min(1),verifier:e$.optional(),requiredEvidenceKinds:g.array(UP).default([])}).strict(),pq=g.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),eq=g.enum(["draft","active","deprecated","archived"]),aq=g.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"]),sq=g.object({key:g.string().regex(/^[A-Z][A-Z0-9_]*$/),description:g.string().min(1),required:g.boolean().default(!1),["secret"]:g.boolean().default(!1),group:g.string().min(1).optional(),default:g.string().optional()}).strict().superRefine((_,$)=>{if(_.secret&&_.default!==void 0)$.addIssue({code:g.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),_C=g.object({name:g.string().min(1),command:g.string().min(1),description:g.string().min(1).optional(),required:g.boolean().default(!1)}).strict(),$C=g.object({packageManager:g.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:g.array(g.string().min(1)).default([]),requiredFiles:g.array(g.string().min(1)).default([]),requiredDirectories:g.array(g.string().min(1)).default([]),optionalDirectories:g.array(g.string().min(1)).default([])}).strict(),DC=J_(y.scaffoldManifest).extend({name:g.string().min(1),version:g.string().min(1),summary:g.string().min(1),type:pq,status:eq.default("draft"),capabilities:g.array(aq).default([]),techStack:g.array(g.string().min(1)).default([]),tags:ZD,source:__.optional(),output:$C,env:g.array(sq).default([]),scripts:g.array(_C).default([]),validationChecks:g.array(U8).default([]),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.source?.uri?.startsWith("file://"))$.addIssue({code:g.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if(_.status==="active"&&_.validationChecks.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if(_.status==="active"&&_.output.requiredFiles.length===0&&_.output.requiredDirectories.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),UC=g.enum(["installed","failed","cancelled","partial","unknown"]),IC=J_(y.scaffoldInstallRecord).extend({scaffoldId:g.string().min(1),scaffoldVersion:g.string().min(1).optional(),manifestRef:__.optional(),target:__,status:UC,installedAt:B_.optional(),installer:e$.optional(),packageManager:g.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:_4.optional(),generatedFiles:g.array(__).default([]),evidenceRefs:g.array(T_).default([]),proofBundleRefs:g.array(__).default([])}).strict().superRefine((_,$)=>{if(_.status==="installed"&&!_.installedAt)$.addIssue({code:g.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if(_.status==="installed"&&_.generatedFiles.length===0&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:g.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:g.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),bD=g.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),jP=g.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),I8=g.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"),EC=g.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),jC=p.refine((_)=>_.startsWith("https://github.com/")||_.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),NC=g.enum(["active","stub","deprecated","archived"]),gC=g.enum(["stable","beta","canary","internal"]),AC=g.object({transport:g.enum(["http","stdio"]).default("http"),bin:g.string().min(1).optional(),url:r$.optional()}).strict(),OC=g.object({healthPath:g.string().min(1).default("/health"),port:g.number().int().positive().optional(),baseUrl:r$.optional()}).strict(),SC=g.object({bins:g.array(g.string().min(1)).default([]),mcp:AC.optional(),http:OC.optional()}).strict(),LC=J_(y.app).extend({appId:bD,npmName:jP,repoFolder:bD,githubUrl:jC,projectSlug:_0,surfaces:SC.default({}),lifecycle:NC,releaseChannel:gC.default("stable"),summary:g.string().min(1).optional(),tags:ZD}).strict().superRefine((_,$)=>{let D=new Set;for(let[I,U]of _.surfaces.bins.entries()){if(D.has(U))$.addIssue({code:g.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",I]});D.add(U)}}),JC=g.enum(["skill","ci","backfilled"]),WC=J_(y.release).extend({appId:bD,package:jP,version:I8,gitSha:EC,publishedAt:B_,publishPath:JC,changelogRef:__.optional(),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.publishPath!=="backfilled"&&_.evidenceRefs.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),PC=g.enum(["install","update","rollback","freeze-blocked"]),zC=g.object({cliVersion:g.string().min(1).optional(),mcpHealth:g.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine((_,$)=>{if(!_.cliVersion&&_.mcpHealth===void 0)$.addIssue({code:g.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),XC=J_(y.rolloutRecord).extend({appId:bD,package:jP,version:I8,machine:p,action:PC,result:D0,verifiedBy:zC.optional(),at:B_,evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.action==="freeze-blocked"&&_.result!=="blocked"&&_.result!=="skipped")$.addIssue({code:g.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let D=Boolean(_.verifiedBy?.cliVersion)||_.verifiedBy?.mcpHealth!==void 0&&_.verifiedBy.mcpHealth!=="not_checked",I=_.verifiedBy?Object.keys(_.verifiedBy).length>0:!1;if((_.action==="install"||_.action==="update")&&_.result==="succeeded"&&(!_.verifiedBy||I&&!D))$.addIssue({code:g.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),GC=g.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),RC=g.enum(["pending","queued","sent","failed","skipped","suppressed"]),YC=g.object({channel:GC,status:RC,deliveredAt:B_.optional(),detail:g.string().min(1).optional()}).strict().superRefine((_,$)=>{if(_.status==="sent"&&!_.deliveredAt)$.addIssue({code:g.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if(_.status==="failed"&&!_.detail)$.addIssue({code:g.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),QC=J_(y.announcement).extend({campaignId:p,appId:bD.optional(),releaseRef:__.optional(),channels:g.array(YC).min(1),audienceRef:__,sentAt:B_}).strict().superRefine((_,$)=>{if(_.releaseRef&&_.releaseRef.kind!=="release")$.addIssue({code:g.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if(_.audienceRef.kind!=="audience")$.addIssue({code:g.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),KC=g.enum(["tag","attribute","group"]),TC=g.enum(["eq","neq","in","not_in","exists","not_exists"]),C9=g.union([g.string(),g.number(),g.boolean()]),FC=g.object({kind:KC,key:g.string().min(1).optional(),op:TC.default("eq"),value:C9.optional(),values:g.array(C9).default([])}).strict().superRefine((_,$)=>{if(_.kind==="attribute"&&!_.key)$.addIssue({code:g.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if((_.op==="eq"||_.op==="neq")&&_.value===void 0)$.addIssue({code:g.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if((_.op==="in"||_.op==="not_in")&&_.values.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),VC=g.object({match:g.enum(["all","any"]).default("all"),predicates:g.array(FC).min(1)}).strict(),BC=g.enum(["opt_in","opt_out","transactional","none"]),MC=J_(y.audience).extend({audienceId:bD,name:p,definition:VC,consentPolicy:BC,suppressionSyncedAt:s4}).strict(),XN=["@hasna/cloud","open-cloud"],bC=g.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),ZC=g.object({id:g.string().min(1),provider:bC,kind:g.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:g.string().min(1),region:g.string().min(1).optional(),accountId:g.string().min(1).optional(),uri:r$.optional(),machineScoped:g.boolean().default(!1)}).strict(),E8=J_(y.appCloudManifest).extend({packageName:g.string().min(1),packageVersion:g.string().min(1).optional(),appId:g.string().min(1),repository:__.optional(),storageMode:g.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:g.enum(["none","app_owned","external_service","local_cache"]),cloudResources:g.array(ZC).default([]),localCache:g.object({path:g.string().min(1).optional(),pullMode:g.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:g.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:g.array(g.string().min(1)).default([...XN]),dependencies:g.array(g.string().min(1)).default([]),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set([...XN,..._.forbiddenSharedRuntimes]);if(D.has(_.packageName))$.addIssue({code:g.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let I of XN)if(!_.forbiddenSharedRuntimes.includes(I))$.addIssue({code:g.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${I}`,path:["forbiddenSharedRuntimes"]});for(let I of D)if(_.dependencies.includes(I))$.addIssue({code:g.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${I}`,path:["dependencies"]});if(_.storageMode==="local_only"&&_.cloudBoundary!=="none")$.addIssue({code:g.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if(_.storageMode==="app_owned_cloud"&&_.cloudBoundary!=="app_owned")$.addIssue({code:g.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if(_.storageMode==="hybrid_local_cache"){if(_.cloudBoundary!=="local_cache")$.addIssue({code:g.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!_.localCache)$.addIssue({code:g.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if(_.storageMode==="external_service"){if(_.cloudBoundary!=="external_service")$.addIssue({code:g.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if(_.cloudResources.length>0)$.addIssue({code:g.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:g.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if(_.cloudBoundary==="none"&&_.cloudResources.length>0)$.addIssue({code:g.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});_.cloudResources.forEach((I,U)=>{if(I.ownerPackage!==_.packageName)$.addIssue({code:g.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",U,"ownerPackage"]})})}),j8=g.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),HC=g.enum(["low","medium","high","critical"]),N8=g.object({id:g.string().min(1),kind:j8,severity:HC,path:g.string().min(1).optional(),packageName:g.string().min(1).optional(),pattern:g.string().min(1),message:g.string().min(1),evidenceRefs:g.array(T_).default([])}).strict(),kC=g.object({id:g.string().min(1),kind:j8,status:D0,target:g.string().min(1),command:g.string().min(1).optional(),evidenceRefs:g.array(T_).default([]),findings:g.array(N8).default([])}).strict(),qC=J_(y.noCloudEvidencePack).extend({subject:__,packageName:g.string().min(1).optional(),packageVersion:g.string().min(1).optional(),generatedBy:e$.optional(),scanMode:g.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:D0,verdict:g.enum(["passed","failed","warning","not_run"]),appCloudManifest:E8.optional(),checks:g.array(kC).min(1),findings:g.array(N8).default([]),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{let D=[..._.findings,..._.checks.flatMap((U)=>U.findings)],I=D.filter((U)=>U.severity==="high"||U.severity==="critical");if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:g.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(I.length>0)$.addIssue({code:g.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if(_.checks.some((U)=>U.status!=="succeeded"))$.addIssue({code:g.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if(_.verdict==="failed"&&D.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if(_.status==="succeeded"&&_.checks.some((U)=>U.status==="failed"))$.addIssue({code:g.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});_.checks.forEach((U,E)=>{let j=U.findings.filter((N)=>N.severity==="high"||N.severity==="critical");if(U.status==="succeeded"&&j.length>0)$.addIssue({code:g.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",E,"findings"]})})}),CC=g.object({checkId:g.string().min(1),status:D0,summary:g.string().min(1).optional(),startedAt:s4,finishedAt:s4,evidenceRefs:g.array(T_).default([])}).strict(),vC=J_(y.proofBundle).extend({subject:__,validationPlanRef:__.optional(),status:D0,verdict:g.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:g.array(CC).default([]),verifier:e$.optional(),evidenceRefs:g.array(T_).default([]),residualRisks:g.array(g.string().min(1)).default([]),freshness:g.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:g.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if(_.checks.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if(_.checks.forEach((I,U)=>{if(I.status!=="succeeded")$.addIssue({code:g.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",U,"status"]})}),!(_.evidenceRefs.length>0||_.checks.some((I)=>I.evidenceRefs.length>0)))$.addIssue({code:g.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!_.verifier)$.addIssue({code:g.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if(_.verdict==="not_run"&&_.checks.length>0)$.addIssue({code:g.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if(_.verdict==="failed"&&!_.checks.some((D)=>D.status==="failed")&&_.evidenceRefs.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),wC=J_(y.workRun).extend({objective:g.string().min(1),status:D0,actor:e$,traceId:g.string().min(1).optional(),startedAt:s4,finishedAt:s4,constraints:g.array(g.string().min(1)).default([]),resourceRefs:g.array(__).default([]),decisions:g.array(s9).default([]),costEstimates:g.array(b1).default([]),evidenceRefs:g.array(T_).default([]),validationPlanRefs:g.array(__).default([]),proofBundleRefs:g.array(__).default([])}).strict().superRefine((_,$)=>{if(_.startedAt&&_.finishedAt&&Date.parse(_.finishedAt)0||_.proofBundleRefs.length>0;if(_.status==="succeeded"&&!D)$.addIssue({code:g.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if((_.status==="failed"||_.status==="blocked")&&!D&&_.decisions.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),rC=Object.freeze({work_run:Object.freeze(["codewith"]),root_request:Object.freeze(["todos"]),pr_group:Object.freeze(["todos"]),leaf_task:Object.freeze(["todos"]),attempt:Object.freeze(["todos"]),writer_generation:Object.freeze(["todos"]),writer_lease:Object.freeze(["repos"]),writer_fence:Object.freeze(["repos"]),provider_profile:Object.freeze(["codewith"]),provider_route:Object.freeze(["codewith"]),admission:Object.freeze(["codewith"]),worker_actor:Object.freeze(["codewith"]),worker:Object.freeze(["codewith"]),runtime:Object.freeze(["codewith"]),repo:Object.freeze(["repos"]),worktree:Object.freeze(["repos"]),branch:Object.freeze(["repos"]),event_stream:Object.freeze(["todos"]),replay_cursor:Object.freeze(["todos"]),handoff:Object.freeze(["todos"]),pull_request:Object.freeze(["todos"]),commit:Object.freeze(["repos"]),review:Object.freeze(["review"]),reviewer:Object.freeze(["review"]),review_run:Object.freeze(["review"]),proof_bundle:Object.freeze(["review"]),repair_cycle:Object.freeze(["todos"]),merge_guard:Object.freeze(["todos"]),merge_operator:Object.freeze(["merge_provider"]),merge_operator_run:Object.freeze(["merge_provider"]),merge_guard_receipt:Object.freeze(["merge_provider"]),merge_outcome:Object.freeze(["merge_provider"]),recovery:Object.freeze(["todos"]),cancellation:Object.freeze(["todos"]),cleanup_eligibility:Object.freeze(["repos"]),cleanup_outcome:Object.freeze(["repos"]),rollback_plan:Object.freeze(["todos"]),rollback_outcome:Object.freeze(["repos"]),terminal_disposition:Object.freeze(["todos"]),openloops_invocation:Object.freeze(["openloops"]),adapter_extension:Object.freeze(["adapter"])}),fC=g.enum(["work_run","root_request","pr_group","leaf_task","attempt","writer_generation","writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","repo","worktree","branch","event_stream","replay_cursor","handoff","pull_request","commit","review","reviewer","review_run","proof_bundle","repair_cycle","merge_guard","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","recovery","cancellation","cleanup_eligibility","cleanup_outcome","rollback_plan","rollback_outcome","terminal_disposition","openloops_invocation","adapter_extension"]),xC=g.enum(["todos","codewith","repos","review","merge_provider","openloops","adapter"]),$0=g.string().regex(/^[a-f0-9]{64}$/),FN=g.string().trim().min(3).max(256),g8=/^[a-f0-9]{32}$/;function uC(_,$,D){return`${_}:${$}:opaque-${D.slice(0,32)}`}function yC(_){return`evidence:opaque-${_.slice(0,32)}`}var A8=FN.refine((_)=>{let D=_.startsWith("task_to_pr_projection:opaque-")?_.slice(29):"";return g8.test(D)},"Projection ids must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),NP=FN.refine((_)=>{let D=_.startsWith("attempt_nonce:opaque-")?_.slice(21):"";return g8.test(D)},"Attempt nonces must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),hC=new Set(["writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","worktree","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","openloops_invocation","adapter_extension"]),gP=g.object({role:fC,authority:xC,id:FN,digest:$0,redaction:g.enum(["none","partial","full"])}).strict().superRefine((_,$)=>{let D=rC[_.role];if(!D.includes(_.authority))$.addIssue({code:g.ZodIssueCode.custom,message:`${_.role} refs must be owned by ${D.join(" or ")}`,path:["authority"]});if(hC.has(_.role)&&_.redaction==="none")$.addIssue({code:g.ZodIssueCode.custom,message:`${_.role} refs must be redacted and cannot carry a raw locator or credential`,path:["redaction"]});let I=uC(_.role,_.authority,_.digest);if(_.id!==I)$.addIssue({code:g.ZodIssueCode.custom,message:"Reference ids must be nonsemantic authority-bound surrogates derived from the canonical role, authority, and owner-record digest",path:["id"]})}),Y$=g.object({id:FN,digest:$0,redaction:g.enum(["partial","full"])}).strict().superRefine((_,$)=>{if(_.id!==yC(_.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Evidence ids must be nonsemantic owner-resolvable surrogates derived from their canonical digest",path:["id"]})});function O8(_,$,D,I){if(_.id===$.id||_.digest===$.digest)D.addIssue({code:g.ZodIssueCode.custom,message:"Stop and lease-revocation facts require distinct evidence identities and digests",path:I})}function b(_){return gP.refine(($)=>$.role===_,{message:`Reference must use role ${_}`,path:["role"]})}function V_(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id&&_.digest===$.digest&&_.redaction===$.redaction}function AP(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id}function WD(_,$,D,I,U){if(AP(_,$))D.addIssue({code:g.ZodIssueCode.custom,message:`${U} requires a fresh canonical role/authority/id`,path:I});if(_.digest===$.digest)D.addIssue({code:g.ZodIssueCode.custom,message:`${U} requires a fresh canonical digest`,path:I})}function YN(_){return`${_.role}\x00${_.authority}\x00${_.id}`}function a_(_,$){return _.algorithm===$.algorithm&&_.value===$.value}var K_=g.object({algorithm:g.enum(["sha1","sha256"]),value:g.string().regex(/^[a-f0-9]+$/)}).strict().superRefine((_,$)=>{let D=_.algorithm==="sha1"?40:64;if(_.value.length!==D)$.addIssue({code:g.ZodIssueCode.custom,message:`${_.algorithm} object ids must contain exactly ${D} lowercase hex characters`,path:["value"]})});function v9(_){if(_.canonicalizationVersion===1){let D=JSON.stringify(["hasna.task_to_pr_projection.binding.v1",_.canonicalizationVersion,_.rootRequestRef.id,_.rootRequestRef.digest,_.prGroupRef.id,_.prGroupRef.digest,_.leafTaskRef.id,_.leafTaskRef.digest,_.repoRef.id,_.repoRef.digest,_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return Z9("sha256").update(D,"utf8").digest("hex")}let $=JSON.stringify(["hasna.task_to_pr_projection.binding.v2",_.canonicalizationVersion,...[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repoRef,_.worktreeRef,_.branchRef].flatMap((D)=>[D.role,D.authority,D.id,D.digest]),_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return Z9("sha256").update($,"utf8").digest("hex")}var cC=g.object({ref:b("attempt"),nonce:NP,admissionRef:b("admission"),admissionWriterGenerationRef:b("writer_generation"),workerActorRef:b("worker_actor"),workerRef:b("worker"),runtimeRef:b("runtime"),writerGenerationRef:b("writer_generation"),writerLeaseRef:b("writer_lease"),writerFenceRef:b("writer_fence"),providerProfileRef:b("provider_profile"),providerRouteRef:b("provider_route")}).strict(),nC=g.object({repoRef:b("repo"),worktreeRef:b("worktree"),branchRef:b("branch"),baseHead:K_,branchHead:K_}).strict(),dC=g.object({streamRef:b("event_stream"),replayCursorRef:b("replay_cursor"),sequence:g.number().int().safe().nonnegative(),prefixDigest:$0}).strict(),mC=g.object({ref:b("handoff"),previousAttemptRef:b("attempt"),nextAttemptRef:b("attempt"),previousWriterGenerationRef:b("writer_generation"),nextWriterGenerationRef:b("writer_generation"),stoppedWorkRunRef:b("work_run"),stopEvidenceRef:Y$,leaseRevocationEvidenceRef:Y$}).strict().superRefine((_,$)=>{WD(_.previousAttemptRef,_.nextAttemptRef,$,["nextAttemptRef"],"Handoff attempt rotation"),WD(_.previousWriterGenerationRef,_.nextWriterGenerationRef,$,["nextWriterGenerationRef"],"Handoff writer-generation rotation"),O8(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),lC=g.object({ref:b("review"),pullRequestRef:b("pull_request"),base:K_,head:K_,reviewerRef:b("reviewer"),reviewRunRef:b("review_run"),proofBundleRef:b("proof_bundle"),verdict:g.enum(["approved","changes_requested","blocked"]),reviewedAt:B_}).strict(),iC=g.object({pullRequestRef:b("pull_request"),remoteBranchRef:b("branch"),expectedBase:K_,providerPullRequestBase:K_,localHead:K_,remoteHead:K_,providerPullRequestHead:K_,equalityProofRef:b("proof_bundle"),ciProofBundleRefs:g.array(b("proof_bundle")).min(1),verifiedAt:B_}).strict().superRefine((_,$)=>{if(!a_(_.expectedBase,_.providerPullRequestBase))$.addIssue({code:g.ZodIssueCode.custom,message:"Expected and provider-observed pull-request bases must be exactly equal",path:["providerPullRequestBase"]});if(!a_(_.localHead,_.remoteHead)||!a_(_.localHead,_.providerPullRequestHead))$.addIssue({code:g.ZodIssueCode.custom,message:"Local, remote, and provider pull-request heads must be exactly equal",path:["providerPullRequestHead"]});let D=_.ciProofBundleRefs.map(YN);if(new Set(D).size!==D.length)$.addIssue({code:g.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical identities",path:["ciProofBundleRefs"]});let I=_.ciProofBundleRefs.map((U)=>U.digest);if(new Set(I).size!==I.length)$.addIssue({code:g.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical digests",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((U)=>AP(U,_.equalityProofRef)))$.addIssue({code:g.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical identities",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((U)=>U.digest===_.equalityProofRef.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical digests",path:["ciProofBundleRefs"]})}),tC=g.object({ref:b("repair_cycle"),cycle:g.number().int().min(0).max(2),cap:g.literal(2),exhausted:g.boolean(),latestRepairRef:b("repair_cycle").optional()}).strict().superRefine((_,$)=>{if(_.exhausted!==(_.cycle===_.cap))$.addIssue({code:g.ZodIssueCode.custom,message:"Repair exhaustion must equal the cumulative cycle cap",path:["exhausted"]});if(_.cycle===0&&_.latestRepairRef)$.addIssue({code:g.ZodIssueCode.custom,message:"Cycle zero cannot reference a repair",path:["latestRepairRef"]});if(_.cycle>0&&!_.latestRepairRef)$.addIssue({code:g.ZodIssueCode.custom,message:"Non-zero repair state requires the latest immutable repair ref",path:["latestRepairRef"]});if(_.latestRepairRef&&AP(_.ref,_.latestRepairRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must be distinct canonical records",path:["latestRepairRef"]});if(_.latestRepairRef&&_.ref.digest===_.latestRepairRef.digest)$.addIssue({code:g.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must have distinct canonical digests",path:["latestRepairRef"]})}),oC=g.object({ref:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:K_,expectedHead:K_,reviewRefs:g.array(b("review")).min(1),proofBundleRefs:g.array(b("proof_bundle")).min(1),operatorRef:b("merge_operator"),operatorRunRef:b("merge_operator_run"),providerGuardReceiptRef:b("merge_guard_receipt"),mechanism:g.enum(["compare_and_swap","queue_expected_head"]),decision:g.enum(["eligible","denied","consumed","revoked"]),evaluatedAt:B_}).strict().superRefine((_,$)=>{if(new Set(_.reviewRefs.map((E)=>E.id)).size!==_.reviewRefs.length)$.addIssue({code:g.ZodIssueCode.custom,message:"Merge guard review refs must be unique",path:["reviewRefs"]});if(new Set(_.proofBundleRefs.map(YN)).size!==_.proofBundleRefs.length)$.addIssue({code:g.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical identities",path:["proofBundleRefs"]});if(new Set(_.proofBundleRefs.map((E)=>E.digest)).size!==_.proofBundleRefs.length)$.addIssue({code:g.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical digests",path:["proofBundleRefs"]})}),pC=g.object({ref:b("merge_outcome"),guardRef:b("merge_guard"),pullRequestRef:b("pull_request"),expectedBase:K_,observedBase:K_,expectedHead:K_,observedHead:K_,status:g.enum(["merged","closed_unmerged","refused","head_drift","base_drift"]),mergeCommitRef:b("commit").optional(),finishedAt:B_,evidenceRefs:g.array(Y$).min(1)}).strict().superRefine((_,$)=>{let D=a_(_.expectedBase,_.observedBase),I=a_(_.expectedHead,_.observedHead);if(_.status==="merged"){if(!D||!I)$.addIssue({code:g.ZodIssueCode.custom,message:"Merged outcomes require observed base and head to equal the guarded values",path:[!D?"observedBase":"observedHead"]});if(!_.mergeCommitRef)$.addIssue({code:g.ZodIssueCode.custom,message:"Merged outcomes require an immutable merge commit ref",path:["mergeCommitRef"]})}else if(_.mergeCommitRef)$.addIssue({code:g.ZodIssueCode.custom,message:"Unmerged outcomes cannot claim a merge commit",path:["mergeCommitRef"]});if(_.status==="head_drift"&&I)$.addIssue({code:g.ZodIssueCode.custom,message:"Head-drift outcomes require distinct expected and observed heads",path:["observedHead"]});if(_.status==="head_drift"&&!D)$.addIssue({code:g.ZodIssueCode.custom,message:"Head-drift outcomes cannot also carry an unclassified base drift",path:["observedBase"]});if(_.status==="base_drift"&&D)$.addIssue({code:g.ZodIssueCode.custom,message:"Base-drift outcomes require distinct expected and observed bases",path:["observedBase"]});if(_.status==="base_drift"&&!I)$.addIssue({code:g.ZodIssueCode.custom,message:"Base-drift outcomes cannot also carry an unclassified head drift",path:["observedHead"]});if(!I&&_.status!=="head_drift")$.addIssue({code:g.ZodIssueCode.custom,message:"Only a head_drift outcome may record an observed head that differs from the expected head",path:["observedHead"]});if(!D&&_.status!=="base_drift")$.addIssue({code:g.ZodIssueCode.custom,message:"Only a base_drift outcome may record an observed base that differs from the expected base",path:["observedBase"]})}),eC=g.object({guard:oC,outcome:pC.optional()}).strict(),aC=g.object({ref:b("recovery"),priorAttemptRef:b("attempt"),priorWriterGenerationRef:b("writer_generation"),priorWorkRunRef:b("work_run"),successorAttemptNonce:NP,successorWriterGenerationRef:b("writer_generation"),preservedStateRefs:g.array(gP).min(1),stopEvidenceRef:Y$,leaseRevocationEvidenceRef:Y$}).strict().superRefine((_,$)=>{WD(_.priorWriterGenerationRef,_.successorWriterGenerationRef,$,["successorWriterGenerationRef"],"Recovery writer-generation rotation"),O8(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),sC=g.object({ref:b("cancellation"),cancelledAttemptRef:b("attempt"),preservedStateRefs:g.array(gP).min(1),evidenceRefs:g.array(Y$).min(1)}).strict(),_v=g.object({ref:b("cleanup_eligibility"),status:g.enum(["not_ready","preserved","blocked","eligible"]),targetWorktreeRef:b("worktree"),eventCursorRef:b("replay_cursor"),terminalDispositionRef:b("terminal_disposition"),writerLeaseRef:b("writer_lease"),leaseRevocationEvidenceRef:Y$,consumedEventEvidenceRef:Y$,evaluatedAt:B_,evidenceRefs:g.array(Y$).min(1)}).strict().superRefine((_,$)=>{if(_.leaseRevocationEvidenceRef.id===_.consumedEventEvidenceRef.id||_.leaseRevocationEvidenceRef.digest===_.consumedEventEvidenceRef.digest)$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup lease-revocation and consumed-event facts require distinct evidence identities and digests",path:["consumedEventEvidenceRef"]})}),$v=g.object({ref:b("cleanup_outcome"),eligibilityRef:b("cleanup_eligibility"),targetWorktreeRef:b("worktree"),status:g.enum(["preserved","deleted","failed","skipped"]),finishedAt:B_,evidenceRefs:g.array(Y$).min(1)}).strict(),Dv=g.object({eligibility:_v,outcome:$v.optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!V_(_.outcome.eligibilityRef,_.eligibility.ref))$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup outcomes must bind the exact eligibility decision",path:["outcome","eligibilityRef"]});if(_.outcome&&!V_(_.outcome.targetWorktreeRef,_.eligibility.targetWorktreeRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup eligibility and outcome must bind the same target worktree",path:["outcome","targetWorktreeRef"]});if(_.outcome?.status==="deleted"&&_.eligibility.status!=="eligible")$.addIssue({code:g.ZodIssueCode.custom,message:"Deletion requires an eligible cleanup decision",path:["outcome","status"]})}),Uv=g.object({plan:g.object({ref:b("rollback_plan"),targetRef:g.union([b("commit"),b("branch")]),createdAt:B_}).strict(),outcome:g.object({ref:b("rollback_outcome"),planRef:b("rollback_plan"),targetRef:g.union([b("commit"),b("branch")]),status:g.enum(["not_run","succeeded","failed","cancelled"]),finishedAt:B_,evidenceRefs:g.array(Y$).min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!V_(_.outcome.planRef,_.plan.ref))$.addIssue({code:g.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback plan",path:["outcome","planRef"]});if(_.outcome&&!V_(_.outcome.targetRef,_.plan.targetRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback target",path:["outcome","targetRef"]});if(_.outcome&&Date.parse(_.outcome.finishedAt)({category:"ci_proof",ref:$,base:_.exactHead.expectedBase,head:_.exactHead.localHead}))]:[],..._.reviews.flatMap(($)=>[{category:"review_proof",ref:$.proofBundleRef,base:$.base,head:$.head},{category:"review_record",ref:$.ref,base:$.base,head:$.head},{category:"review_run",ref:$.reviewRunRef,base:$.base,head:$.head}]),..._.merge?[{category:"merge_guard",ref:_.merge.guard.ref},{category:"provider_guard_receipt",ref:_.merge.guard.providerGuardReceiptRef,base:_.merge.guard.expectedBase,head:_.merge.guard.expectedHead}]:[],..._.cleanup?[{category:"cleanup_eligibility",ref:_.cleanup.eligibility.ref}]:[],..._.rollback?[{category:"rollback_plan",ref:_.rollback.plan.ref}]:[],..._.terminalDispositionRef?[{category:"terminal_disposition",ref:_.terminalDispositionRef}]:[]]}function jv(_,$){if(_.category!==$.category)return!1;if(_.category==="projection_id"&&$.category==="projection_id")return _.projectionId===$.projectionId;if(_.category==="attempt_nonce"&&$.category==="attempt_nonce")return _.nonce===$.nonce;if(_.category==="replay_prefix"&&$.category==="replay_prefix")return _.sequence===$.sequence&&_.prefixDigest===$.prefixDigest;if(!("ref"in _)||!("ref"in $))return!1;return V_(_.ref,$.ref)&&(("head"in _)&&("head"in $)&&("base"in _)&&("base"in $)&&a_(_.base,$.base)&&a_(_.head,$.head)||!("head"in _)&&!("head"in $)&&!("base"in _)&&!("base"in $))}var Nv="hasna.task_to_pr_adapter_extension.",gv=g.object({mode:g.enum(["local","cloud"]),schema:DP,ref:b("adapter_extension"),digest:$0}).strict().superRefine((_,$)=>{if(!_.schema.startsWith(Nv))$.addIssue({code:g.ZodIssueCode.custom,message:"Adapter extension schema ids must use the permanently reserved task-to-PR adapter-extension namespace",path:["schema"]})}),Av=g.enum(["admitted","running","handed_off","reviewing","repairing","merge_ready","merged","closed_unmerged","failed","blocked","cancelled","recovering","cleanup_complete","rolled_back"]),w9=new Set(["admitted","running","handed_off"]),r9=new Set(["merged","closed_unmerged","failed","blocked","cancelled","cleanup_complete","rolled_back"]),Ov={admitted:new Set(["absent","denied:none","revoked:none"]),running:new Set(["absent","denied:none","revoked:none"]),handed_off:new Set(["absent","denied:none","revoked:none"]),reviewing:new Set(["absent","denied:none","revoked:none"]),repairing:new Set(["absent","denied:none","revoked:none"]),merge_ready:new Set(["eligible:none"]),merged:new Set(["consumed:merged"]),closed_unmerged:new Set(["consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),failed:new Set(["absent","revoked:none"]),blocked:new Set(["absent","revoked:none"]),cancelled:new Set(["absent","revoked:none"]),recovering:new Set(["absent","denied:none","revoked:none"]),cleanup_complete:new Set(["absent","revoked:none","consumed:merged","consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),rolled_back:new Set(["consumed:merged"])},Sv=g.object({schema:g.literal(y.taskToPrProjection),id:A8,createdAt:B_,canonicalizationVersion:g.union([g.literal(1),g.literal(2)]),identityDigest:$0,frozenScopeDigest:$0,state:Av,workRunRef:b("work_run"),rootRequestRef:b("root_request"),prGroupRef:b("pr_group"),leafTaskRef:b("leaf_task"),attempt:cC,repository:nC,events:dC,openLoopsInvocationRef:b("openloops_invocation").optional(),pullRequestRef:b("pull_request").optional(),exactHead:iC.optional(),handoff:mC.optional(),reviews:g.array(lC).default([]),repair:tC,merge:eC.optional(),recovery:aC.optional(),cancellation:sC.optional(),cleanup:Dv.optional(),rollback:Uv.optional(),terminalDispositionRef:b("terminal_disposition").optional(),provenanceLedger:g.array(Iv),adapterExtensions:g.array(gv).default([]),evidenceRefs:g.array(Y$).default([])}).strict().superRefine((_,$)=>{let D=_.canonicalizationVersion===1?v9({canonicalizationVersion:1,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest}):v9({canonicalizationVersion:2,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,worktreeRef:_.repository.worktreeRef,branchRef:_.repository.branchRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest});if(_.identityDigest!==D)$.addIssue({code:g.ZodIssueCode.custom,message:"identityDigest must equal the selected v1 compatibility or v2 branch/worktree-bound canonical identity digest",path:["identityDigest"]});let I=new Set,U=new Set,E=new Set,j=new Set,N=new Set,A=new Set;for(let[Q,F]of _.provenanceLedger.entries()){if("ref"in F){if(I.has(F.ref.id))$.addIssue({code:g.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical owner id across categories or generations",path:["provenanceLedger",Q,"ref","id"]});if(I.add(F.ref.id),U.has(F.ref.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical digest across categories or generations",path:["provenanceLedger",Q,"ref","digest"]});U.add(F.ref.digest);continue}if(F.category==="projection_id"){if(E.has(F.projectionId))$.addIssue({code:g.ZodIssueCode.custom,message:"Projection identity provenance tombstones must be globally unique",path:["provenanceLedger",Q,"projectionId"]});E.add(F.projectionId);continue}if(F.category==="attempt_nonce"){if(j.has(F.nonce))$.addIssue({code:g.ZodIssueCode.custom,message:"Attempt nonce provenance tombstones must be globally unique",path:["provenanceLedger",Q,"nonce"]});j.add(F.nonce);continue}if(N.has(F.prefixDigest))$.addIssue({code:g.ZodIssueCode.custom,message:"Replay prefix provenance tombstones must be globally unique",path:["provenanceLedger",Q,"prefixDigest"]});if(N.add(F.prefixDigest),A.has(F.sequence))$.addIssue({code:g.ZodIssueCode.custom,message:"Replay prefix provenance entries must bind globally unique replay sequences",path:["provenanceLedger",Q,"sequence"]});A.add(F.sequence)}for(let Q of Ev(_))if(!_.provenanceLedger.some((F)=>jv(F,Q)))$.addIssue({code:g.ZodIssueCode.custom,message:`The active ${Q.category} identity must be represented exactly in the monotonic provenance ledger`,path:["provenanceLedger"]});let O=[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repository.repoRef,_.repository.worktreeRef,_.repository.branchRef,_.events.streamRef,..._.pullRequestRef?[_.pullRequestRef]:[]],S=(Q,F,q,Z)=>{let f=new Set(F.map((U_)=>U_.role)),l=new Set;for(let[U_,j_]of Q.entries()){if(!f.has(j_.role))$.addIssue({code:g.ZodIssueCode.custom,message:`${Z} cannot preserve an unrecognized ${j_.role} role`,path:[...q,U_]});if(l.has(j_.role))$.addIssue({code:g.ZodIssueCode.custom,message:`${Z} must preserve exactly one canonical ref per role`,path:[...q,U_]});l.add(j_.role)}if(Q.length!==F.length)$.addIssue({code:g.ZodIssueCode.custom,message:`${Z} preservation refs must exactly equal the required canonical role set`,path:q});for(let U_ of F)if(!Q.some((j_)=>V_(j_,U_)))$.addIssue({code:g.ZodIssueCode.custom,message:`${Z} must preserve ${U_.role}`,path:q})};if(_.handoff&&!V_(_.handoff.nextWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Handoff next generation must be the current attempt writer generation",path:["handoff","nextWriterGenerationRef"]});if(_.handoff&&!V_(_.handoff.nextAttemptRef,_.attempt.ref))$.addIssue({code:g.ZodIssueCode.custom,message:"Handoff next attempt must be the current attempt",path:["handoff","nextAttemptRef"]});if(_.handoff)WD(_.handoff.stoppedWorkRunRef,_.workRunRef,$,["handoff","stoppedWorkRunRef"],"Handoff WorkRun rotation");if(_.recovery){if(_.recovery.successorAttemptNonce!==_.attempt.nonce)$.addIssue({code:g.ZodIssueCode.custom,message:"Recovery successor nonce must equal the current attempt nonce",path:["recovery","successorAttemptNonce"]});if(!V_(_.recovery.successorWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Recovery successor generation must equal the current writer generation",path:["recovery","successorWriterGenerationRef"]});WD(_.recovery.priorAttemptRef,_.attempt.ref,$,["recovery","priorAttemptRef"],"Recovery attempt rotation"),WD(_.recovery.priorWorkRunRef,_.workRunRef,$,["recovery","priorWorkRunRef"],"Recovery WorkRun rotation"),S(_.recovery.preservedStateRefs,[_.recovery.priorWorkRunRef,...O],["recovery","preservedStateRefs"],"Recovery")}if(_.cancellation&&!V_(_.cancellation.cancelledAttemptRef,_.attempt.ref))$.addIssue({code:g.ZodIssueCode.custom,message:"Cancellation must bind the current attempt",path:["cancellation","cancelledAttemptRef"]});if(_.cancellation)S(_.cancellation.preservedStateRefs,[_.workRunRef,_.attempt.ref,...O],["cancellation","preservedStateRefs"],"Cancellation");if(_.cancellation&&_.recovery)$.addIssue({code:g.ZodIssueCode.custom,message:"A projection cannot be both the cancellation and recovery snapshot",path:["recovery"]});if(_.handoff&&_.recovery)$.addIssue({code:g.ZodIssueCode.custom,message:"A projection cannot be both the handoff and recovery snapshot",path:["recovery"]});if(_.cleanup&&!V_(_.cleanup.eligibility.eventCursorRef,_.events.replayCursorRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup eligibility must bind the current canonical replay cursor",path:["cleanup","eligibility","eventCursorRef"]});if(_.cleanup&&(!_.terminalDispositionRef||!V_(_.cleanup.eligibility.terminalDispositionRef,_.terminalDispositionRef)))$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact durable terminal owner fact",path:["cleanup","eligibility","terminalDispositionRef"]});if(_.cleanup&&!V_(_.cleanup.eligibility.writerLeaseRef,_.attempt.writerLeaseRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact writer lease being revoked",path:["cleanup","eligibility","writerLeaseRef"]});if(_.cleanup&&!V_(_.cleanup.eligibility.targetWorktreeRef,_.repository.worktreeRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup eligibility must bind the canonical worktree",path:["cleanup","eligibility","targetWorktreeRef"]});if(_.pullRequestRef){if(_.exactHead&&!V_(_.exactHead.pullRequestRef,_.pullRequestRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Exact-head proof must bind the canonical pull request ref",path:["exactHead","pullRequestRef"]});for(let[Q,F]of _.reviews.entries())if(!V_(F.pullRequestRef,_.pullRequestRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Every review must bind the canonical pull request ref",path:["reviews",Q,"pullRequestRef"]});if(_.merge&&!V_(_.merge.guard.pullRequestRef,_.pullRequestRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Merge guard must bind the canonical pull request ref",path:["merge","guard","pullRequestRef"]});if(_.merge?.outcome&&!V_(_.merge.outcome.pullRequestRef,_.pullRequestRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Merge outcome must bind the canonical pull request ref",path:["merge","outcome","pullRequestRef"]})}else if(_.exactHead||_.reviews.length>0||_.merge)$.addIssue({code:g.ZodIssueCode.custom,message:"Review and merge state require a canonical pull request ref",path:["pullRequestRef"]});if(_.exactHead&&!a_(_.exactHead.localHead,_.repository.branchHead))$.addIssue({code:g.ZodIssueCode.custom,message:"Exact local head must equal the canonical branch head",path:["exactHead","localHead"]});if(_.exactHead&&!a_(_.exactHead.expectedBase,_.repository.baseHead))$.addIssue({code:g.ZodIssueCode.custom,message:"Exact-head expected base must equal the canonical repository base",path:["exactHead","expectedBase"]});if(_.exactHead&&!V_(_.exactHead.remoteBranchRef,_.repository.branchRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Exact-head remote branch ref must equal the canonical repository branch ref",path:["exactHead","remoteBranchRef"]});if(_.exactHead&&Date.parse(_.exactHead.verifiedAt)0&&!_.exactHead)$.addIssue({code:g.ZodIssueCode.custom,message:"Reviews require local/remote/provider exact-head proof",path:["exactHead"]});if(_.exactHead){let Q=[{ref:_.exactHead.equalityProofRef,path:["exactHead","equalityProofRef"]},..._.exactHead.ciProofBundleRefs.map((Z,f)=>({ref:Z,path:["exactHead","ciProofBundleRefs",f]})),..._.reviews.map((Z,f)=>({ref:Z.proofBundleRef,path:["reviews",f,"proofBundleRef"]}))],F=new Set,q=new Set;for(let Z of Q){let f=YN(Z.ref);if(F.has(f))$.addIssue({code:g.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical identities",path:Z.path});if(F.add(f),q.has(Z.ref.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical digests",path:Z.path});q.add(Z.ref.digest)}}let L=new Set,P=new Set,z=new Set,G=new Set,J=new Set,W=new Set,X=new Set,R=new Set;for(let[Q,F]of _.reviews.entries()){if(!a_(F.base,_.repository.baseHead))$.addIssue({code:g.ZodIssueCode.custom,message:"Review base must equal the exact canonical pull-request base",path:["reviews",Q,"base"]});if(!a_(F.head,_.repository.branchHead))$.addIssue({code:g.ZodIssueCode.custom,message:"Review head must equal the exact canonical branch head",path:["reviews",Q,"head"]});for(let[Z,f,l]of[[F.ref.id,L,"ref"],[F.reviewerRef.id,z,"reviewerRef"],[F.reviewRunRef.id,J,"reviewRunRef"]]){if(f.has(Z))$.addIssue({code:g.ZodIssueCode.custom,message:"Review, reviewer, and review-run refs must each be unique",path:["reviews",Q,l]});f.add(Z)}if(P.has(F.ref.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Review refs must resolve to distinct canonical record digests",path:["reviews",Q,"ref"]});if(P.add(F.ref.digest),G.has(F.reviewerRef.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Reviewer refs must resolve to distinct canonical actor digests",path:["reviews",Q,"reviewerRef"]});if(G.add(F.reviewerRef.digest),W.has(F.reviewRunRef.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Review-run refs must resolve to distinct canonical run digests",path:["reviews",Q,"reviewRunRef"]});W.add(F.reviewRunRef.digest);let q=YN(F.proofBundleRef);if(X.has(q))$.addIssue({code:g.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical identities",path:["reviews",Q,"proofBundleRef"]});if(X.add(q),R.has(F.proofBundleRef.digest))$.addIssue({code:g.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical digests",path:["reviews",Q,"proofBundleRef"]});if(R.add(F.proofBundleRef.digest),F.reviewerRef.digest===_.attempt.workerRef.digest)$.addIssue({code:g.ZodIssueCode.custom,message:"Worker and reviewer identities must resolve to distinct canonical digests",path:["reviews",Q,"reviewerRef"]});if(F.reviewRunRef.digest===_.attempt.runtimeRef.digest)$.addIssue({code:g.ZodIssueCode.custom,message:"Worker runtime and review run must resolve to distinct canonical digests",path:["reviews",Q,"reviewRunRef"]});if(_.exactHead&&Date.parse(F.reviewedAt)Date.parse(_.merge.guard.evaluatedAt)Q.verdict!=="approved"))$.addIssue({code:g.ZodIssueCode.custom,message:"Eligible merge guards require at least one review and all reviews approved",path:["merge","guard","decision"]});if(_.merge.guard.reviewRefs.length!==_.reviews.length||_.merge.guard.reviewRefs.some((Q)=>!_.reviews.some((F)=>V_(Q,F.ref))))$.addIssue({code:g.ZodIssueCode.custom,message:"Eligible merge guard review refs must exactly equal the projected approved review refs as a canonical set",path:["merge","guard","reviewRefs"]});for(let Q of _.reviews)if(!_.merge.guard.proofBundleRefs.some((F)=>V_(F,Q.proofBundleRef)))$.addIssue({code:g.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact review proof bundle",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&!_.merge.guard.proofBundleRefs.some((Q)=>V_(Q,_.exactHead.equalityProofRef)))$.addIssue({code:g.ZodIssueCode.custom,message:"Eligible merge guards must bind the exact-head equality proof",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&_.exactHead.ciProofBundleRefs.some((Q)=>!_.merge.guard.proofBundleRefs.some((F)=>V_(F,Q))))$.addIssue({code:g.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact-head CI proof",path:["merge","guard","proofBundleRefs"]})}}if(_.merge?.outcome){if(!V_(_.merge.outcome.guardRef,_.merge.guard.ref))$.addIssue({code:g.ZodIssueCode.custom,message:"Merge outcome must bind the exact immutable merge guard",path:["merge","outcome","guardRef"]});if(!a_(_.merge.outcome.expectedHead,_.merge.guard.expectedHead))$.addIssue({code:g.ZodIssueCode.custom,message:"Merge outcome expected head must equal the guarded expected head",path:["merge","outcome","expectedHead"]});if(!a_(_.merge.outcome.expectedBase,_.merge.guard.expectedBase))$.addIssue({code:g.ZodIssueCode.custom,message:"Merge outcome expected base must equal the guarded expected base",path:["merge","outcome","expectedBase"]});if(_.merge.guard.decision!=="consumed")$.addIssue({code:g.ZodIssueCode.custom,message:"Every merge outcome requires an explicitly consumed merge guard",path:["merge","guard","decision"]});if(Date.parse(_.merge.outcome.finishedAt)0)$.addIssue({code:g.ZodIssueCode.custom,message:`${_.state} projections cannot carry review bindings before review authority is active`,path:["reviews"]});if((w9.has(_.state)||_.state==="recovering")&&(_.merge?.guard.reviewRefs.length??0)>0)$.addIssue({code:g.ZodIssueCode.custom,message:`${_.state} projections cannot hide review bindings in a merge guard before review authority is active`,path:["merge","guard","reviewRefs"]});let T=_.merge?`${_.merge.guard.decision}:${_.merge.outcome?.status??"none"}`:"absent";if(!Ov[_.state].has(T))$.addIssue({code:g.ZodIssueCode.custom,message:`State ${_.state} is incompatible with merge authority ${T}`,path:["merge"]});if(r9.has(_.state)&&!_.terminalDispositionRef)$.addIssue({code:g.ZodIssueCode.custom,message:`${_.state} projections require a durable Todos terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(!r9.has(_.state)&&_.terminalDispositionRef)$.addIssue({code:g.ZodIssueCode.custom,message:`${_.state} projections cannot carry a terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(_.state==="reviewing"&&_.reviews.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Reviewing projections require review refs",path:["reviews"]});if(_.state==="cancelled"&&!_.cancellation)$.addIssue({code:g.ZodIssueCode.custom,message:"Cancelled projections require preservation state",path:["cancellation"]});if(_.cancellation&&_.merge?.outcome)$.addIssue({code:g.ZodIssueCode.custom,message:"Cancellation cannot coexist with a terminal merge outcome",path:["cancellation"]});if(_.state==="recovering"&&!_.recovery)$.addIssue({code:g.ZodIssueCode.custom,message:"Recovering projections require recovery state",path:["recovery"]});if(_.state==="repairing"&&_.repair.cycle===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Repairing projections require a non-zero repair cycle",path:["repair","cycle"]});if(_.merge&&(_.merge.guard.decision==="eligible"||_.merge.guard.decision==="consumed")&&!V_(_.attempt.admissionWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:g.ZodIssueCode.custom,message:"Merge eligibility requires admission from the current writer generation",path:["attempt","admissionWriterGenerationRef"]});if(_.state==="merge_ready"&&_.merge?.guard.decision!=="eligible")$.addIssue({code:g.ZodIssueCode.custom,message:"Merge-ready projections require an eligible guard",path:["merge"]});if(_.state==="merged"&&_.merge?.outcome?.status!=="merged")$.addIssue({code:g.ZodIssueCode.custom,message:"Merged projections require a merged immutable outcome",path:["merge"]});if(_.state==="closed_unmerged"&&!_.merge?.outcome?.status.match(/^(closed_unmerged|refused|head_drift|base_drift)$/))$.addIssue({code:g.ZodIssueCode.custom,message:"Closed-unmerged projections require a non-merged terminal outcome",path:["merge"]});if(_.state==="cleanup_complete"&&(!_.cleanup?.outcome||!["deleted","preserved","skipped"].includes(_.cleanup.outcome.status)))$.addIssue({code:g.ZodIssueCode.custom,message:"Cleanup-complete projections require an immutable cleanup outcome",path:["cleanup"]});if(_.state==="rolled_back"&&_.rollback?.outcome?.status!=="succeeded")$.addIssue({code:g.ZodIssueCode.custom,message:"Rolled-back projections require a successful rollback outcome",path:["rollback"]});if((_.state==="failed"||_.state==="blocked")&&_.evidenceRefs.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Failed and blocked projections require redacted evidence refs",path:["evidenceRefs"]});if(["admitted","running","handed_off","reviewing","repairing","merge_ready","recovering"].includes(_.state)&&(_.merge?.outcome||_.cancellation||_.cleanup?.outcome||_.rollback?.outcome))$.addIssue({code:g.ZodIssueCode.custom,message:"Non-terminal projections cannot carry terminal owner outcomes",path:["state"]});let Y=new Set;for(let[Q,F]of _.adapterExtensions.entries()){let q=`${F.mode}:${F.schema}`;if(Y.has(q))$.addIssue({code:g.ZodIssueCode.custom,message:"Adapter extensions must be unique per local/cloud mode and schema",path:["adapterExtensions",Q]});Y.add(q)}});var Lv=g.object({id:g.string().min(1),at:B_,kind:g.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:g.string().min(1),resourceRefs:g.array(__).default([]),evidenceRefs:g.array(T_).default([]),costEstimate:b1.optional()}).strict(),Jv=J_(y.agentTrajectory).extend({actor:e$,workRunRef:__.optional(),events:g.array(Lv).default([]),outcome:g.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:__.optional()}).strict(),Wv="v1",Pv=g.enum(["library","cli-with-store","service","saas"]),zv=["user-hosted","hasna-saas"],Xv=g.enum(zv),Gv=["api","sdk","mcp","cli"],S8=g.enum(Gv),Rv=g.enum(["supported","deferred","unsupported"]),Yv=g.enum(["none","local-only","api-key","session","service-token","custom"]),pW=g.object({method:g.enum(["GET","POST","PUT","PATCH","DELETE"]),path:g.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:g.boolean().default(!1),description:g.string().min(1).optional()}).strict(),Qv=g.object({id:g.string().min(1),kind:g.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:g.boolean().default(!0),command:g.string().min(1).optional(),evidenceRef:T_.optional(),status:g.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:g.string().min(1).optional()}).strict().superRefine((_,$)=>{if((_.status==="passed"||_.status==="failed"||_.status==="blocked")&&!_.command&&!_.evidenceRef&&!_.summary)$.addIssue({code:g.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),Kv=g.object({name:g.string().min(1),kind:S8.optional(),status:Rv,bin:g.string().min(1).optional(),mcpBin:g.string().min(1).optional(),authMode:Yv,health:pW.optional(),readiness:pW.optional(),version:pW.optional(),apiBasePath:g.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:g.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),exportSubpath:g.string().regex(/^\.(?:\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*)?$/,"SDK export subpaths must be package export keys such as . or ./sdk").optional(),generatedFrom:g.string().regex(/^\/[A-Za-z0-9_./:-]*$/,"SDK generatedFrom must reference an absolute OpenAPI path").optional(),clientClassName:g.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).optional(),deferReason:g.string().min(1).optional(),readinessGates:g.array(Qv).default([])}).strict().superRefine((_,$)=>{if(_.status==="supported"){if(!_.kind||_.kind==="api"){if(!_.bin)$.addIssue({code:g.ZodIssueCode.custom,message:"Supported API surfaces require a serve bin",path:["bin"]});if(!_.health)$.addIssue({code:g.ZodIssueCode.custom,message:"Supported API surfaces require a health endpoint",path:["health"]});if(!_.readiness)$.addIssue({code:g.ZodIssueCode.custom,message:"Supported API surfaces require a readiness endpoint",path:["readiness"]});if(!_.version)$.addIssue({code:g.ZodIssueCode.custom,message:"Supported API surfaces require a version endpoint",path:["version"]})}if(_.kind==="cli"&&!_.bin)$.addIssue({code:g.ZodIssueCode.custom,message:"Supported CLI surfaces require a bin",path:["bin"]});if(_.kind==="mcp"&&!_.mcpBin)$.addIssue({code:g.ZodIssueCode.custom,message:"Supported MCP surfaces require an mcpBin",path:["mcpBin"]});if(_.kind==="sdk"&&!_.exportSubpath)$.addIssue({code:g.ZodIssueCode.custom,message:"Supported SDK surfaces require an exportSubpath",path:["exportSubpath"]})}if((_.status==="deferred"||_.status==="unsupported")&&!_.deferReason)$.addIssue({code:g.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if(_.health&&_.health.path!=="/health")$.addIssue({code:g.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if(_.health&&_.health.method!=="GET")$.addIssue({code:g.ZodIssueCode.custom,message:"Health endpoint must use GET",path:["health","method"]});if(_.readiness&&_.readiness.path!=="/ready")$.addIssue({code:g.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if(_.readiness&&_.readiness.method!=="GET")$.addIssue({code:g.ZodIssueCode.custom,message:"Readiness endpoint must use GET",path:["readiness","method"]});if(_.version&&_.version.path!=="/version")$.addIssue({code:g.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]});if(_.version&&_.version.method!=="GET")$.addIssue({code:g.ZodIssueCode.custom,message:"Version endpoint must use GET",path:["version","method"]})}),Tv=["sqlite","postgres"],L8=g.enum(Tv),J8=["sqlite","postgres"],Fv=g.enum(J8),$P=["postgres"],Vv=g.object({kind:S8,reason:g.string().trim().min(1)}).strict(),OP=500,SP=200,QN=(_)=>g.string().trim().min(1).max(_).regex(/^[^\u0000-\u001f\u007f]+$/,"Waiver text must not contain control characters"),Bv=["domain","host","ip","email"],Mv=g.object({kind:g.enum(Bv),reason:QN(OP),reviewedBy:QN(SP),expiresAt:B_}).strict(),bv=g.object({engine:g.enum($P),reason:QN(OP),reviewedBy:QN(SP).optional(),expiresAt:B_.optional()}).strict();function Zv(_){if(_.class!=="cli-with-store")return`storage waivers are not permitted for class ${_.class}`;if(_.bins.includes(`${_.name}-serve`))return`storage waivers are not permitted for a service-capable cli-with-store repo shipping ${_.name}-serve`;if(_.storageMode==="postgres")return"storage waivers are not permitted while storage.mode is postgres, which reads and writes PostgreSQL directly";if(_.hosting.includes("hasna-saas"))return"storage waivers are not permitted for a repo declaring the hasna-saas product story";return null}var Hv=g.object({conformance:g.object({waivedSurfaces:g.array(Vv).default([]),waiverProfile:g.literal("non-node-monorepo").optional(),waivedStorageEngines:g.array(bv).default([]),waivedAssetInventories:g.array(Mv).default([])}).catchall(g.unknown()).optional(),release:g.object({artifactScan:g.object({script:g.string().trim().min(1)}).strict().optional()}).catchall(g.unknown()).optional()}).catchall(g.unknown()),kv=g.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),qv=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function Cv(_){return qv.map(($)=>`${_}${$}`)}function f9(_){return`hasna/oss/${_}/database-url`}var vv=g.object({mode:L8,engines:g.array(Fv).min(1).optional(),envPrefix:g.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:g.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:g.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:g.string().min(1).endsWith(".db","storage.sqlitePath must end in .db").optional(),pgTestGate:g.object({envVar:g.string().regex(/^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$/),command:g.string().trim().min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.engines&&new Set(_.engines).size!==_.engines.length)$.addIssue({code:g.ZodIssueCode.custom,message:"storage.engines must not contain duplicates",path:["engines"]});if(_.engines?.includes("postgres")&&!_.envPrefix)$.addIssue({code:g.ZodIssueCode.custom,message:"storage.engines containing postgres requires envPrefix for the HASNA__DATABASE_URL contract",path:["envPrefix"]})}),W8=g.enum(["0600"]),P8=g.enum(["0700"]),z8=g.enum([".hasna",".codewith"]),wv=g.enum(["directory","file","sqlite_db","sqlite_wal","sqlite_shm","backup","export","report","tmp","log","session","snapshot"]),SD=R$.refine((_)=>!_.startsWith("~"),"Local store path patterns must be relative to their declared root"),rv=g.object({id:g.string().min(1),source:g.enum(["sqlite","manifest","index","runtime","package_adapter"]),table:g.string().min(1).optional(),column:g.string().min(1).optional(),description:g.string().min(1),required:g.boolean().default(!0)}).strict(),fv=g.object({safeWhen:g.enum(["exclusive_access","offline_only","never"]),operations:g.array(g.enum(["wal_checkpoint_truncate","incremental_vacuum","optimize","vacuum"])).default([])}).strict().superRefine((_,$)=>{if(_.safeWhen==="never"&&_.operations.length>0)$.addIssue({code:g.ZodIssueCode.custom,message:"sqliteMaintenance.safeWhen=never cannot declare operations",path:["operations"]})}),xv=g.object({id:g.string().min(1),description:g.string().min(1),ttlDays:g.number().int().nonnegative().optional(),artifactClasses:g.array(wv).min(1),allowlistGlobs:g.array(SD).min(1),activeRecordExclusions:g.array(rv).default([]),sqliteMaintenance:fv.optional()}).strict(),uv=g.object({storeId:g.string().regex(/^[a-z][a-z0-9-]*$/),packageName:g.string().min(1),displayName:g.string().min(1),root:z8,relativePath:SD,directoryMode:P8.default("0700"),fileMode:W8.default("0600"),sqliteDatabaseGlobs:g.array(SD).default([]),sensitiveFileGlobs:g.array(SD).default([]),backupGlobs:g.array(SD).default([]),exportGlobs:g.array(SD).default([]),retentionAdapters:g.array(xv).default([]),notes:g.array(g.string().min(1)).default([])}).strict().superRefine((_,$)=>{if(_.relativePath.includes("*"))$.addIssue({code:g.ZodIssueCode.custom,message:"store relativePath must be a concrete directory; use glob fields for files",path:["relativePath"]});let D=new Set;for(let[I,U]of _.retentionAdapters.entries()){if(D.has(U.id))$.addIssue({code:g.ZodIssueCode.custom,message:"retention adapter ids must be unique within a store",path:["retentionAdapters",I,"id"]});D.add(U.id)}}),X8=J_(y.secureLocalStorePolicy).extend({version:g.string().min(1),scope:g.array(z8).min(1),defaults:g.object({directoryMode:P8.default("0700"),fileMode:W8.default("0600"),dryRunDefault:g.literal(!0),requireExplicitApply:g.literal(!0),includeSqliteSidecars:g.literal(!0),redactedEvidenceOnly:g.literal(!0)}).strict(),stores:g.array(uv).min(1),lifecycle:g.object({retentionDryRunDefault:g.literal(!0),requireActiveRecordExclusionProof:g.literal(!0),requireArtifactAllowlist:g.literal(!0),sqliteMaintenanceRequiresExclusiveAccess:g.literal(!0)}).strict(),warnings:g.array(g.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set;for(let[I,U]of _.stores.entries()){if(D.has(U.storeId))$.addIssue({code:g.ZodIssueCode.custom,message:"store ids must be unique",path:["stores",I,"storeId"]});if(D.add(U.storeId),!_.scope.includes(U.root))$.addIssue({code:g.ZodIssueCode.custom,message:"store root must be listed in policy scope",path:["stores",I,"root"]})}}),yv=g.object({$schema:g.string().min(1).optional(),schema:g.literal(y.serviceContract),name:kv,class:Pv,contractVersion:g.literal(Wv),kitVersion:g.string().min(1),description:g.string().min(1).optional(),bins:g.array(g.string().min(1)).default([]),storage:vv.optional(),hosting:g.array(Xv).min(1).default(["user-hosted"]),serviceSurfaces:g.array(Kv).default([]),metadata:Hv.optional()}).strict().superRefine((_,$)=>{if(new Set(_.hosting).size!==_.hosting.length)$.addIssue({code:g.ZodIssueCode.custom,message:"hosting must not contain duplicates",path:["hosting"]});let D=new Set(Cv(_.name)),I=new Set;for(let[O,S]of _.bins.entries()){if(I.has(S))$.addIssue({code:g.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",O]});if(I.add(S),!D.has(S))$.addIssue({code:g.ZodIssueCode.custom,message:`Bin "${S}" is not allowlisted for app "${_.name}"; allowed: ${[...D].join(", ")}`,path:["bins",O]})}let U=(O)=>I.has(`${_.name}${O}`);if(_.storage){let O=_.name.toUpperCase().replace(/-/g,"_");if(_.storage.envPrefix&&_.storage.envPrefix!==`HASNA_${O}_`)$.addIssue({code:g.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${O}_`,path:["storage","envPrefix"]});if(_.storage.databaseUrlSecretRef&&_.storage.databaseUrlSecretRef!==f9(_.name))$.addIssue({code:g.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${f9(_.name)}`,path:["storage","databaseUrlSecretRef"]})}if(_.class==="library"){if(_.storage)$.addIssue({code:g.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(U("-serve")||U("-mcp"))$.addIssue({code:g.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if(_.class==="cli-with-store"){if(!_.storage)$.addIssue({code:g.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else{if(_.storage.mode==="sqlite"&&!_.storage.sqlitePath)$.addIssue({code:g.ZodIssueCode.custom,message:"sqlite cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(_.storage.engines){let O=new Set(_.storage.engines),S=_.metadata?.conformance?.waivedStorageEngines??[],L=Zv({class:_.class,name:_.name,bins:_.bins,hosting:_.hosting,storageMode:_.storage.mode}),P=new Set(L?[]:S.map((G)=>G.engine)),z=J8.filter((G)=>!O.has(G)&&!P.has(G));if(z.length>0){let G=L&&S.length>0?`; declared waiver ignored: ${L}`:"";$.addIssue({code:g.ZodIssueCode.custom,message:`cli-with-store storage.engines must declare both sqlite and postgres unless the engine carries a metadata.conformance.waivedStorageEngines waiver; missing: ${z.join(", ")}${G}`,path:["storage","engines"]})}}}if(!I.has(_.name))$.addIssue({code:g.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${_.name}" bin`,path:["bins"]})}if(_.class==="service"){if(!_.storage)$.addIssue({code:g.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});else if(_.storage.engines&&(!_.storage.engines.includes("sqlite")||!_.storage.engines.includes("postgres")))$.addIssue({code:g.ZodIssueCode.custom,message:"service storage.engines must declare both sqlite and postgres",path:["storage","engines"]});if(!U("-serve"))$.addIssue({code:g.ZodIssueCode.custom,message:`service repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if(_.class==="saas"){if(!_.storage)$.addIssue({code:g.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else{if(_.storage.mode!=="postgres")$.addIssue({code:g.ZodIssueCode.custom,message:"saas repos must use the postgres storage backend",path:["storage","mode"]});if(!_.storage.envPrefix)$.addIssue({code:g.ZodIssueCode.custom,message:"saas storage requires envPrefix for the public DATABASE_URL contract",path:["storage","envPrefix"]})}if(!U("-serve"))$.addIssue({code:g.ZodIssueCode.custom,message:`saas repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[O,S]of _.serviceSurfaces.entries()){if(S.bin&&!I.has(S.bin))$.addIssue({code:g.ZodIssueCode.custom,message:`Service surface bin "${S.bin}" must be declared in bins`,path:["serviceSurfaces",O,"bin"]});if(S.mcpBin&&!I.has(S.mcpBin))$.addIssue({code:g.ZodIssueCode.custom,message:`Service surface MCP bin "${S.mcpBin}" must be declared in bins`,path:["serviceSurfaces",O,"mcpBin"]})}let E=_.metadata?.conformance?.waivedSurfaces??[],j=new Set;for(let[O,S]of E.entries()){if(j.has(S.kind))$.addIssue({code:g.ZodIssueCode.custom,message:`Duplicate conformance waiver for ${S.kind}`,path:["metadata","conformance","waivedSurfaces",O,"kind"]});j.add(S.kind)}let N=_.metadata?.conformance?.waivedStorageEngines??[],A=new Set;for(let[O,S]of N.entries()){if(A.has(S.engine))$.addIssue({code:g.ZodIssueCode.custom,message:`Duplicate storage-engine waiver for ${S.engine}`,path:["metadata","conformance","waivedStorageEngines",O,"engine"]});A.add(S.engine)}}),Lm=g.object({status:g.enum(["ok","degraded","unavailable"]),version:g.string().min(1),mode:L8}).strict(),Jm=g.object({ready:g.boolean(),reason:g.string().min(1).optional()}).strict(),Wm=g.object({version:g.string().min(1)}).strict(),hv=g.enum(["info","notice","breaking","critical"]),cv=g.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 (..)"),nv=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],dv=g.enum(nv);var mv=g.enum(["fleet","package","machine"]),G8=J_(y.commsEventEnvelope).extend({type:cv,severity:hv,scope:mv,summary:g.string().min(1).optional(),source:e$.optional(),affected_packages:g.array(p).default([]),affected_machines:g.array(p).default([]),action_required:g.boolean().default(!1),ack_by:B_.optional(),dedupe_key:p,resourceRefs:g.array(__).default([]),evidenceRefs:g.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.scope==="package"&&_.affected_packages.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if(_.scope==="machine"&&_.affected_machines.length===0)$.addIssue({code:g.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if(_.ack_by&&!_.action_required)$.addIssue({code:g.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:g.ZodIssueCode.custom,message:`${_.type} events are always critical`,path:["severity"]});if(_.scope!=="fleet")$.addIssue({code:g.ZodIssueCode.custom,message:`${_.type} events are always fleet-scoped`,path:["scope"]});if(!_.action_required)$.addIssue({code:g.ZodIssueCode.custom,message:`${_.type} events require action_required`,path:["action_required"]})}}),lv=g.enum(["fleet","package","product","loop-lane","initiative","personal"]),iv=g.enum(["quiet","work","firehose"]),tv=p.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:)"),ov=J_(y.commsChannelMetadata).extend({class:lv,noise:iv.optional(),owner:p.optional(),until:tv.optional(),successor:p.optional()}).strict().superRefine((_,$)=>{if(_.class==="initiative"){if(!_.owner)$.addIssue({code:g.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!_.until)$.addIssue({code:g.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),x9={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}},pv=J_(y.commsMessageMetadata).extend({tag:dv,envelope:G8}).strict().superRefine((_,$)=>{let D=x9[_.tag];if(!D.allowedSeverities.includes(_.envelope.severity))$.addIssue({code:g.ZodIssueCode.custom,message:`[${_.tag}] posts allow severities ${D.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(D.requiredEventType&&_.envelope.type!==D.requiredEventType)$.addIssue({code:g.ZodIssueCode.custom,message:`[${_.tag}] posts require event type ${D.requiredEventType}`,path:["envelope","type"]});for(let[I,U]of Object.entries(x9))if(U.requiredEventType===_.envelope.type&&_.tag!==I)$.addIssue({code:g.ZodIssueCode.custom,message:`${_.envelope.type} events must use the [${I}] tag`,path:["tag"]})});var ev={[y.actorRef]:Kq,[y.resourceRef]:Tq,[y.evidenceRef]:Vq,[y.workRun]:wC,[y.taskToPrProjection]:Sv,[y.decisionEnvelope]:s9,[y.costEstimate]:b1,[y.capabilityCard]:Mq,[y.providerLiveModeStandard]:Cq,[y.contextPack]:_8,[y.integrationRef]:$8,[y.projectManifest]:xq,[y.projectPanel]:D8,[y.projectSnapshot]:tq,[y.renderManifest]:cq,[y.agentTrajectory]:Jv,[y.validationPlan]:oq,[y.proofBundle]:vC,[y.scaffoldManifest]:DC,[y.scaffoldInstallRecord]:IC,[y.appCloudManifest]:E8,[y.noCloudEvidencePack]:qC,[y.secureLocalStorePolicy]:X8,[y.serviceContract]:yv,[y.commsEventEnvelope]:G8,[y.commsChannelMetadata]:ov,[y.commsMessageMetadata]:pv,[y.app]:LC,[y.release]:WC,[y.rolloutRecord]:XC,[y.announcement]:QC,[y.audience]:MC};class R8 extends Error{schemaId;issues;constructor(_,$){super(`Contract validation failed for ${_}`);this.name="ContractValidationError",this.schemaId=_,this.issues=$}}function Y8(_,$){let I=ev[_].safeParse($);if(!I.success)throw new R8(_,I.error.issues);return I.data}var Pm=String.raw`(?:^|[^\w$])(?:_*(?:import|require)|createRequire|Module\s*\.\s*_load)`;var LP=[{pattern:"@hasna/cloud",kind:"module",message:"Shared @hasna/cloud runtime reference is forbidden"},{pattern:"open-cloud",kind:"module",message:"Shared open-cloud runtime reference is forbidden"},{pattern:"cloud-mcp",kind:"module",message:"Legacy cloud-mcp runtime surface is forbidden"},{pattern:"registerCloudTools",kind:"symbol",message:"Legacy registerCloudTools runtime surface is forbidden"},{pattern:"registerCloudCommands",kind:"symbol",message:"Legacy registerCloudCommands runtime surface is forbidden"},{pattern:".hasna/cloud",kind:"config",checkKind:"runtime_config",message:"Legacy .hasna/cloud runtime config is forbidden"},{pattern:"HASNA_CLOUD_",kind:"config",message:"Shared HASNA_CLOUD_* runtime config is forbidden"},{pattern:"HASNA_RDS_PASSWORD",kind:"config",message:"Legacy shared RDS credential config is forbidden"}],zm=LP.filter((_)=>("checkKind"in _)),av=LP.filter((_)=>_.kind==="module"),Xm=[...new Set([...XN,...av.map((_)=>_.pattern)])],Gm=LP.filter((_)=>_.kind==="config");var u9="^[^\\u0000-\\u001f\\u007f]*$",Rm={$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. Hosting story, product surfaces, and storage capabilities are separate declarations; the storage backend (sqlite | postgres) is the only runtime switch.",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],allOf:[{if:{required:["class"],properties:{class:{const:"saas"}}},then:{required:["storage"],properties:{storage:{required:["mode","envPrefix"],properties:{mode:{const:"postgres"}}}}}}],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:y.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."},hosting:{type:"array",items:{enum:["user-hosted","hasna-saas"]},minItems:1,uniqueItems:!0,description:"Customer-facing product stories. Public OSS cores include user-hosted; add hasna-saas only when a managed control plane exists."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode"],allOf:[{if:{required:["status"],properties:{status:{const:"supported"},kind:{const:"api"}}},then:{required:["bin","health","readiness","version"]}}],properties:{name:{type:"string",minLength:1},kind:{enum:["api","sdk","mcp","cli"]},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"]},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},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:{const:"GET"},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:{const:"GET"},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_./:-]*$"},exportSubpath:{type:"string",pattern:"^\\.(?:\\/[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)*)?$",description:"SDK package export key such as . or ./sdk."},generatedFrom:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$",description:"OpenAPI path used to generate the SDK."},clientClassName:{type:"string",pattern:"^[A-Za-z_$][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 API, SDK, MCP, and CLI product surfaces. Legacy entries without kind remain parseable; new manifests declare kind explicitly."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["sqlite","postgres"],description:"Active data backend. sqlite|postgres ONLY \u2014 the single runtime switch."},engines:{type:"array",items:{enum:["sqlite","postgres"]},minItems:1,uniqueItems:!0,description:"Supported storage engines; capability metadata independent of the active backend."},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:"Legacy/private-tier database secret ref. Public conformance rejects this field."},sqlitePath:{type:"string",pattern:"\\.db$",description:"Local sqlite path (~/.hasna//.db)."},pgTestGate:{type:"object",additionalProperties:!1,required:["envVar","command"],properties:{envVar:{type:"string",pattern:"^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$"},command:{type:"string",minLength:1}},description:"Environment-gated live PostgreSQL test command."}}},metadata:{type:"object",additionalProperties:!0,properties:{conformance:{type:"object",additionalProperties:!0,properties:{waiverProfile:{const:"non-node-monorepo",description:"Explicit surface-waiver eligibility for exceptional non-Node monorepos. Libraries are eligible for API/MCP waivers without this profile."},waivedSurfaces:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["kind","reason"],properties:{kind:{enum:["api","sdk","mcp","cli"]},reason:{type:"string",minLength:1}}}},waivedStorageEngines:{type:"array",uniqueItems:!0,maxItems:$P.length,items:{type:"object",additionalProperties:!1,required:["engine","reason"],properties:{engine:{enum:[...$P]},reason:{type:"string",minLength:1,maxLength:OP,allOf:[{pattern:"\\S"},{pattern:u9}]},reviewedBy:{type:"string",minLength:1,maxLength:SP,allOf:[{pattern:"\\S"},{pattern:u9}]},expiresAt:{type:"string",format:"date-time"}}},description:"Explicit storage-engine exceptions, at most one per engine. Only a CLI-only cli-with-store repo (no -serve bin, storage.mode sqlite, no hasna-saas story) may waive postgres; sqlite is never waivable, expiresAt is a UTC RFC 3339 timestamp, and conformance stops honouring a waiver once it has passed."}}}}}}};var sv="2026-07-06";function t$(_,$,D,I,U,E=[],j){return{id:_,description:$,ttlDays:D,artifactClasses:I,allowlistGlobs:U,activeRecordExclusions:E.map((N)=>({...N,required:N.required??!0})),sqliteMaintenance:j}}var Ym=X8.parse({schema:y.secureLocalStorePolicy,id:"hasna-secure-local-store-defaults",createdAt:"2026-07-06T00:00:00.000Z",version:sv,scope:[".hasna",".codewith"],defaults:{directoryMode:"0700",fileMode:"0600",dryRunDefault:!0,requireExplicitApply:!0,includeSqliteSidecars:!0,redactedEvidenceOnly:!0},lifecycle:{retentionDryRunDefault:!0,requireActiveRecordExclusionProof:!0,requireArtifactAllowlist:!0,sqliteMaintenanceRequiresExclusiveAccess:!0},stores:[{storeId:"codewith",packageName:"codewith",displayName:"Codewith native state",root:".codewith",relativePath:".",sqliteDatabaseGlobs:["logs_*.sqlite","state_*.sqlite","goals_*.sqlite"],sensitiveFileGlobs:["sessions/**/*.jsonl","shell_snapshots/**/*","logs*.sqlite","state*.sqlite","goals*.sqlite"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("codewith-session-snapshots","Codewith sessions, shell snapshots, logs, monitor output, mailbox payloads, and scheduler state need package-owned redaction before retention applies.",30,["session","snapshot","log"],["sessions/**/*.jsonl","shell_snapshots/**/*","logs/**/*"],[{id:"codewith-active-session",source:"package_adapter",description:"Exclude currently active sessions, leased schedules, monitors, pending interactions, and active goal rows."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})],notes:["Includes native .codewith DBs and transcript-like artifacts; redaction-before-persistence remains package-owned."]},{storeId:"todos",packageName:"@hasna/todos",displayName:"Todos",root:".hasna",relativePath:"todos",sqliteDatabaseGlobs:["todos.db"],sensitiveFileGlobs:["todos.db","todos.db-wal","todos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak","*.backup"],exportGlobs:["exports/**/*","*.jsonl","*.csv"],retentionAdapters:[t$("todos-exports-backups","Todos backups and exports are deleted only after package redaction and active task/evidence references are excluded.",14,["backup","export"],["backups/**/*","exports/**/*"],[{id:"todos-active-evidence",source:"sqlite",table:"task_files",column:"path",description:"Exclude files still referenced by active tasks, verification evidence, task comments, or handoff records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"conversations",packageName:"@hasna/conversations",displayName:"Conversations",root:".hasna",relativePath:"conversations",sqliteDatabaseGlobs:["messages.db"],sensitiveFileGlobs:["messages.db","messages.db-wal","messages.db-shm","exports/**/*","attachments/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*","*.json","*.csv"],retentionAdapters:[t$("conversations-exports-attachments","Conversation exports and attachments require message-id redaction and active attachment reference checks before deletion.",14,["export","backup"],["exports/**/*","backups/**/*","attachments/**/*"],[{id:"conversations-active-attachments",source:"sqlite",table:"messages",column:"attachments",description:"Exclude attachments still referenced by retained messages or audited redaction records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"mementos",packageName:"@hasna/mementos",displayName:"Mementos",root:".hasna",relativePath:"mementos",sqliteDatabaseGlobs:["mementos.db"],sensitiveFileGlobs:["mementos.db","mementos.db-wal","mementos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("mementos-audit-search-history","Mementos retention must preserve active memory versions while compacting audit/search surfaces through package-owned adapters.",30,["backup","export","log"],["backups/**/*","exports/**/*","audit/**/*"],[{id:"mementos-active-memory-versions",source:"sqlite",table:"memory_versions",column:"memory_id",description:"Exclude current memory versions and audit entries required for provenance."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"knowledge",packageName:"@hasna/knowledge",displayName:"Knowledge",root:".hasna",relativePath:"knowledge",sqliteDatabaseGlobs:["knowledge.db"],sensitiveFileGlobs:["knowledge.db","knowledge.db-wal","knowledge.db-shm","db.json","migration-exports/**/*","*.bak"],backupGlobs:["*.bak","backups/**/*","*.pre-cloud-*"],exportGlobs:["migration-exports/**/*","exports/**/*","*.jsonl"],retentionAdapters:[t$("knowledge-migrations-exports","Knowledge migration exports and pre-cloud backups require replacement, encryption, or redaction before retention deletion.",14,["backup","export"],["migration-exports/**/*","exports/**/*","*.bak","*.pre-cloud-*"],[{id:"knowledge-current-catalog",source:"manifest",description:"Exclude files referenced by the active catalog or migration ledger."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"projects",packageName:"@hasna/projects",displayName:"Projects",root:".hasna",relativePath:"projects",sqliteDatabaseGlobs:["projects.db","data/*/project.db"],sensitiveFileGlobs:["projects.db","projects.db-wal","projects.db-shm","data/*/project.db","data/*/project.db-wal","data/*/project.db-shm","reports/**/*"],backupGlobs:["backups/**/*","data/*/backups/**/*"],exportGlobs:["reports/**/*","exports/**/*"],retentionAdapters:[t$("projects-reports-workspaces","Project reports, dashboards, workspaces, and per-project DBs need active workspace/location references before cleanup.",30,["backup","export","report","tmp"],["backups/**/*","reports/**/*","workspaces/**/*","data/*/backups/**/*"],[{id:"projects-active-workspaces",source:"sqlite",table:"workspaces",column:"primary_path",description:"Exclude active workspace paths, locations, linked reports, and project store artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"browser",packageName:"@hasna/browser",displayName:"Browser",root:".hasna",relativePath:"browser",sqliteDatabaseGlobs:["browser.db"],sensitiveFileGlobs:["browser.db","browser.db-wal","browser.db-shm","profiles/**/cookies.json","states/**/*.json","auth/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*","traces/**/*","har/**/*"],retentionAdapters:[t$("browser-auth-traces","Browser state, trace, HAR, and auth artifacts require session invalidation or redaction before deletion.",7,["backup","export","session","snapshot"],["profiles/**/*","states/**/*","traces/**/*","har/**/*","exports/**/*"],[{id:"browser-active-profiles",source:"sqlite",table:"sessions",column:"profile_path",description:"Exclude profiles, cookies, and storage state used by active browser sessions."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"terminal",packageName:"@hasna/terminal",displayName:"Terminal",root:".hasna",relativePath:"terminal",sqliteDatabaseGlobs:["sessions.db"],sensitiveFileGlobs:["sessions.db","sessions.db-wal","sessions.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("terminal-sessions","Terminal sessions and interactions need active session exclusion plus command-output redaction before retention.",30,["backup","export","session","log"],["backups/**/*","exports/**/*","sessions/**/*"],[{id:"terminal-active-sessions",source:"sqlite",table:"sessions",column:"id",description:"Exclude active terminal session records and any linked interaction artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"logs",packageName:"@hasna/logs",displayName:"Logs",root:".hasna",relativePath:"logs",sqliteDatabaseGlobs:["logs.db"],sensitiveFileGlobs:["logs.db","logs.db-wal","logs.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("logs-retention","Logs require redaction before compaction and must preserve active incident/evidence references.",14,["backup","export","log"],["backups/**/*","exports/**/*","*.log","logs/**/*"],[{id:"logs-active-evidence",source:"sqlite",table:"logs",column:"id",description:"Exclude log rows or files linked to active incidents, tasks, or proof bundles."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"loops",packageName:"@hasna/loops",displayName:"OpenLoops",root:".hasna",relativePath:"loops",sqliteDatabaseGlobs:["loops.db","state.db","*.sqlite"],sensitiveFileGlobs:["*.db","*.sqlite","*.db-wal","*.db-shm","reports/**/*","tmp/**/*","runs/**/*"],backupGlobs:["backups/**/*","tmp/**/*"],exportGlobs:["reports/**/*","runs/**/*","exports/**/*"],retentionAdapters:[t$("loops-reports-tmp","Loop reports, tmp files, workflow artifacts, and command output need run-state checks and redaction before retention deletion.",14,["backup","export","report","tmp","log"],["reports/**/*","tmp/**/*","runs/**/*","exports/**/*"],[{id:"loops-active-runs",source:"sqlite",table:"loop_runs",column:"id",description:"Exclude active, leased, recently failed, or evidence-linked loop and workflow run artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]}],warnings:["This package publishes declarations only; each owning package implements and verifies its own local-store lifecycle.","Retention and redaction evidence remain package-owned and must preserve active-record exclusions.","SQLite maintenance is descriptive policy metadata only and is never executed by @hasna/contracts."]});var _w=64,Qm=new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${_w-1}}$`),AD="[0-9a-fA-F]",Km=new RegExp(`^\\{?(?:${AD}{8}-${AD}{4}-${AD}{4}-${AD}{4}-${AD}{12}|${AD}{32})\\}?$`);var $w=/^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/;var Tm=new RegExp($w.source.replace(/^\^/,"\\b").replace(/\$$/,"\\b"));var Q8="@hasna/knowledge";function Dw(_){if(!Number.isFinite(_??0))return 20;return Math.max(1,Math.min(100,Math.trunc(_??20)))}function Uw(_){return _.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function Z1(_,$=180){let D=String(_??"").replace(/\s+/g," ").trim();if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-3))}...`}function w_(_,$=""){return typeof _==="string"&&_.length>0?_:$}function H1(_){return typeof _==="number"&&Number.isFinite(_)?_:0}function HD(_){if(typeof _!=="string"||_.length===0)return;let $=_.includes("T")?_:`${_.replace(" ","T")}Z`,D=new Date($);return Number.isNaN(D.valueOf())?void 0:D.toISOString()}function VN(_){return r$.safeParse(_).success}function f$(_,$,D,I,U=[]){return{kind:_,id:$,name:D,uri:I&&VN(I)?I:void 0,externalId:$,sourcePackage:Q8,tags:U}}function Iw(_){return[..._.items.flatMap((D)=>[D.updated_at,D.created_at]),..._.sources.flatMap((D)=>[D.updated_at,D.created_at]),..._.chunks.map((D)=>D.created_at),..._.wiki_pages.flatMap((D)=>[D.updated_at,D.created_at]),..._.storage_objects.flatMap((D)=>[D.updated_at,D.created_at]),..._.runs.flatMap((D)=>[D.updated_at,D.created_at]),..._.reindex_queue.flatMap((D)=>[D.updated_at,D.created_at]),..._.sync_conflicts.map((D)=>D.created_at),..._.approval_gates.flatMap((D)=>[D.updated_at,D.created_at])].map(HD).filter(Boolean).sort((D,I)=>I.localeCompare(D))[0]}function Ew(_){if(!_)return"unknown";let $=Date.now()-new Date(_).valueOf();if(!Number.isFinite($))return"unknown";return $>2592000000?"stale":"fresh"}function jw(_){let $=(D)=>{let I=String(D??"").toLowerCase();return I!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(I)};return _.reindex_queue.filter((D)=>$(D.status)).length+_.sync_conflicts.filter((D)=>$(D.status)).length+_.approval_gates.filter((D)=>$(D.status)).length}function Nw(_,$){let D=[];for(let I of _.items.slice(0,$))D.push({id:`item_${I.id}`,title:I.title,summary:Z1(I.content_preview),status:I.archived?"archived":"active",priority:"medium",timestamp:HD(I.updated_at??I.created_at),resourceRefs:[f$("knowledge",I.id,I.title,`knowledge://item/${encodeURIComponent(I.id)}`,I.tags)],evidenceRefs:I.url&&VN(I.url)?[{id:`url_${I.id}`,kind:"url",uri:I.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:I.archived,tags:I.tags,url:I.url||void 0}});for(let I of _.sources.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,w_(I.uri,"source")),E=w_(I.title,w_(I.uri,U)),j=w_(I.uri,`knowledge://source/${encodeURIComponent(U)}`);D.push({id:`source_${U}`,title:E,summary:Z1(`${H1(I.chunks)} chunk(s), ${H1(I.revisions)} revision(s)`),status:H1(I.chunks)>0?"indexed":"source",priority:"medium",timestamp:HD(I.updated_at??I.created_at),resourceRefs:[f$("document",U,E,j)],evidenceRefs:VN(j)?[{id:`source_${U}`,kind:"url",uri:j,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:I.kind,chunks:H1(I.chunks),revisions:H1(I.revisions)}})}for(let I of _.chunks.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,"chunk"),E=w_(I.source_uri);D.push({id:`chunk_${U}`,title:w_(I.wiki_title,E?`Chunk from ${E}`:`Knowledge chunk ${U}`),summary:Z1(I.text_preview),status:"chunk",priority:"low",timestamp:HD(I.created_at),resourceRefs:[f$("context_pack",U,w_(I.wiki_title,U),`knowledge://chunk/${encodeURIComponent(U)}`)],evidenceRefs:E&&VN(E)?[{id:`chunk_source_${U}`,kind:"url",uri:E,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:E||void 0,token_count:I.token_count,ordinal:I.ordinal}})}for(let I of _.sync_conflicts.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,"sync_conflict");D.push({id:`sync_conflict_${U}`,title:`Sync conflict: ${w_(I.entity_kind,"entity")}/${w_(I.entity_id,U)}`,summary:Z1(`Status ${w_(I.status,"unknown")}; strategy ${w_(I.resolution_strategy,"none")}.`),status:w_(I.status,"unknown"),priority:"critical",timestamp:HD(I.created_at),resourceRefs:[f$("finding",U,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(U)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:I.local_machine_id,remote_machine_id:I.remote_machine_id}})}for(let I of _.reindex_queue.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,"reindex");D.push({id:`reindex_${U}`,title:`Reindex ${w_(I.kind,"item")}: ${w_(I.target_id,U)}`,summary:Z1(I.reason),status:w_(I.status,"unknown"),priority:w_(I.status).toLowerCase()==="failed"?"high":"medium",timestamp:HD(I.updated_at??I.created_at),resourceRefs:[f$("action",U,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(U)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:I.attempts,source_uri:I.source_uri}})}return D.slice(0,$)}async function K8(_,$={}){let D=Dw($.limit),I=new Date().toISOString(),U=Uw(_),j=await($.service??zN({scope:$.scope??"project",cwd:$.cwd})).resolveInventory({limit:D,storePath:$.storePath,includeArchived:$.includeArchived}),N=Iw(j),A=Ew(N),O=j.summary.active_items+j.summary.sources+j.summary.chunks+j.summary.wiki_pages+j.summary.storage_objects,S=jw(j),L=O===0?"empty":A==="stale"?"stale":"ready",P=Nw(j,D),z={schema:y.projectPanel,id:`knowledge_panel_${U}`,createdAt:I,projectId:U,provider:{kind:"knowledge",id:`knowledge_${U}`,name:"Knowledge",sourcePackage:Q8,externalId:j.home},kind:"knowledge",title:"Knowledge",summary:L==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${j.summary.active_items} active note(s), ${j.summary.sources} source(s), ${j.summary.chunks} chunk(s), and ${j.summary.wiki_pages} wiki page(s).`,state:L,stateReason:L==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:I,freshness:A,metrics:[{id:"active_items",label:"Active notes",value:j.summary.active_items,status:j.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:j.summary.sources,status:j.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:j.summary.chunks,status:j.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:j.summary.wiki_pages,status:j.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:j.summary.storage_objects,status:j.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:j.summary.vector_entries,status:j.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:S,status:S>0?"warning":"good"}],items:P,actions:[f$("action","knowledge:inventory","Inspect knowledge inventory"),f$("action","knowledge:context-pack","Build cited context pack"),f$("action","knowledge:ingest","Ingest project source")],resourceRefs:[f$("project",U,_,`project://${U}`),f$("knowledge",`home_${U}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(U)}`),f$("artifact",`db_${U}`,"Knowledge database",`knowledge://db/${encodeURIComponent(U)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:D}},metadata:{scope:j.scope,home:j.home,json_store_exists:j.paths.json_store_exists,latest_activity_at:N}};return Y8(y.projectPanel,z)}function T8(_){let $=[`${_.title}: ${_.state}`,_.summary??"",..._.metrics.map((D)=>`${D.label}: ${D.value}`)].filter(Boolean);if(_.items.length>0){$.push("Items:");for(let D of _.items.slice(0,10))if($.push(`- ${D.title}${D.status?` [${D.status}]`:""}`),D.summary)$.push(` ${D.summary}`)}return $.join(` -`)}var B8=["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 M8="HASNA_KNOWLEDGE_STORAGE_MODE",b8="KNOWLEDGE_STORAGE_MODE";function F8(_){return process.env[_]?.trim()||void 0}function V8(_){let $=_?.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return"sqlite";if($==="postgres"||$==="postgresql")return"postgres";return}function gw(_={}){let $=g0(f1(_.scope,_.cwd).home);return c($.knowledgeDbPath),{db:w($.knowledgeDbPath),path:$.knowledgeDbPath,scope:_.scope??"global"}}function Z8(){let _=V8(F8(M8))??V8(F8(b8));if(_)return _;return"sqlite"}function JP(_={}){let $=gw(_);try{Aw($.db);let D=$.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all();return{mode:Z8(),service:"knowledge",scope:$.scope,databasePath:$.path,tables:B8,sync:D}}finally{$.db.close()}}function Aw(_){_.exec(` + `,[D]).map(ib),f={legacy_items:U.items.length,active_items:E.length,archived_items:U.items.length-E.length,schema_version:O.schema_version,sources:O.sources,source_revisions:O.source_revisions,chunks:O.chunks,wiki_pages:O.wiki_pages,citations:O.citations,indexes:O.indexes,runs:O.runs,run_events:O.run_events,storage_objects:O.storage_objects,embeddings:O.embeddings,vector_entries:O.vector_entries,reindex_queue:O.reindex_queue,redaction_findings:O.redaction_findings,audit_events:O.audit_events,approval_gates:O.approval_gates,knowledge_machines:O.knowledge_machines,sync_snapshots:O.sync_snapshots,sync_changes:O.sync_changes,sync_conflicts:O.sync_conflicts,sync_table_clocks:O.sync_table_clocks,sync_imports:O.sync_imports,promotion_candidates:O.promotion_candidates,durable_records:O.durable_records};return{ok:!0,scope:this.scope,home:$.home,limit:D,paths:{json_store_path:I,json_store_exists:U.exists,knowledge_db_path:$.knowledgeDbPath,knowledge_db_exists:!0,artifacts_dir:$.artifactsDir,indexes_dir:$.indexesDir,logs_dir:$.logsDir,wiki_dir:$.wikiDir},summary:f,legacy_store:{path:I,exists:U.exists,read_error:U.read_error,total_items:U.items.length,active_items:E.length,archived_items:U.items.length-E.length,items_returned:Math.min(j.length,D)},items:j.slice(0,D).map(z9),sources:L,source_revisions:W,chunks:g,wiki_pages:z,indexes:G,storage_objects:J,runs:P,vector_indexes:X,reindex_queue:R,machines:T,sync_conflicts:Y,approval_gates:Q,audit_events:F,promotion_candidates:B,durable_records:b,message:`${U.items.length} item(s), ${O.sources} source(s), ${O.chunks} chunk(s), ${O.wiki_pages} wiki page(s), ${O.storage_objects} artifact(s)`}}finally{S.close()}}assertAppWikiWrite(_){mD({scope:this.scope,workspace:this.workspace,safetyPolicy:this.safetyPolicy(),allowGlobal:_})}async initAppWiki(_={}){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return Kg({scope:this.scope,workspace:$,store:this.artifactStore(),safetyPolicy:this.safetyPolicy(),allowGlobal:_.allowGlobal})}async addAppWikiNote(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return Tg({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(!X_($.knowledgeDbPath))return[];return Fg({dbPath:$.knowledgeDbPath,limit:_.limit})}async getAppWikiNote(_,$={}){let D=this.workspace;if(!X_(D.knowledgeDbPath))return null;return Vg({dbPath:D.knowledgeDbPath,store:this.artifactStore(),id:_,includeContent:$.includeContent})}async addAppWikiSourceRef(_){this.assertAppWikiWrite(_.allowGlobal);let $=this.ensureWorkspace();return Bg({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();c(_.knowledgeDbPath);let $=await nR(this.artifactStore()),D=w(_.knowledgeDbPath);try{j6(D,$.artifacts),dR(D,$.artifacts)}finally{D.close()}return $}async compileWiki(_={}){let $=this.ensureWorkspace();return uR({..._,dbPath:$.knowledgeDbPath,store:this.artifactStore()})}async fileAnswer(_){let $=this.ensureWorkspace(),D=await this.retrieveContext({query:_.prompt,limit:_.limit,semantic:_.semantic,modelRef:_.modelRef,dimensions:_.dimensions,fake:_.fake});return yR({dbPath:$.knowledgeDbPath,store:this.artifactStore(),prompt:_.prompt,answer:_.answer,context:D,approveWrite:_.approveWrite})}lintWiki(){let _=this.ensureWorkspace();return hR({dbPath:_.knowledgeDbPath})}async ingestManifest(_){let $=this.ensureWorkspace();return Xg({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}async ingestSource(_,$){let D=this.ensureWorkspace();return EI({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$,config:this.config(),safetyPolicy:this.safetyPolicy()})}async importRulesProvenance(_={}){let $=_.dryRun!==!1,D=$?this.workspace:this.ensureWorkspace();return ZR({root:_.root??this.options.cwd??process.cwd(),scope:this.scope,owner:_.owner,dryRun:$,deprecateLegacy:_.deprecateLegacy,includeLegacy:_.includeLegacy,legacyStorePath:D.jsonStorePath,dbPath:D.knowledgeDbPath,safetyPolicy:this.safetyPolicy(),maxItems:_.maxItems,limit:_.limit})}async resolveSource(_,$={}){let D=this.ensureWorkspace();return DI({dbPath:D.knowledgeDbPath,sourceRef:_,purpose:$.purpose,limit:$.limit,safetyPolicy:this.safetyPolicy()})}async consumeOutbox(_){let $=this.ensureWorkspace();return yG({dbPath:$.knowledgeDbPath,input:_,config:this.config(),safetyPolicy:this.safetyPolicy()})}reindexHealth(_={}){let $=this.workspace;if(!X_($.knowledgeDbPath))return ab();return XR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}enqueueReindex(_={}){let $=this.ensureWorkspace();return KP({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async refreshEmbeddings(_={}){let $=this.ensureWorkspace();return GR({..._,dbPath:$.knowledgeDbPath,config:this.config()})}providerStatus(_=process.env){return qg(this.config(),_)}modelRegistry(){return q2(this.config())}embeddingStatus(){let _=this.workspace;if(!X_(_.knowledgeDbPath))return sb();return fg(_.knowledgeDbPath)}async indexEmbeddings(_={}){let $=this.ensureWorkspace();return AI({..._,dbPath:$.knowledgeDbPath,config:this.config()})}isApiMode(){return h$()}cloudStore(){let _=dD();if(!_)throw Error("knowledge: cloud store requested but not resolvable (check HASNA_KNOWLEDGE_API_URL + HASNA_KNOWLEDGE_API_KEY).");return _}async fetchCloudItems(){return t1(this.cloudStore())}async semanticSearch(_){let $=this.workspace;if(this.isApiMode())throw new PN;if(!X_($.knowledgeDbPath))return{provider:"openai",model:"text-embedding-3-small",dimensions:_.dimensions??1536,query:_.query,results:[]};return OI({..._,dbPath:$.knowledgeDbPath,config:this.config()})}async search(_){let $=this.workspace;if(this.isApiMode()){if(_.semantic===!0||_.fake===!0||Boolean(_.modelRef))throw new PN;let I=await this.cloudStore().search({query:_.query,archive:"active",limit:_.limit,offset:_.offset});return x2(I.items,_,[],I.total)}let D=dP(this.scope,$,_.legacyStorePath);if(!X_($.knowledgeDbPath)){if(X_(D))return JI({..._,legacyStorePath:D,config:this.config()});return M9(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return WI({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async retrieveContext(_){let $=this.workspace;if(this.isApiMode()){let I=await this.search(_);return O6(I,{contextChars:_.contextChars})}let D=dP(this.scope,$,_.legacyStorePath);if(!X_($.knowledgeDbPath)){if(X_(D)){let I=await JI({..._,legacyStorePath:D,config:this.config()});return O6(I,{contextChars:_.contextChars})}return pb(_.query,Math.max(1,Math.min(_.limit??10,100)),_.semantic===!0||_.fake===!0||Boolean(_.modelRef))}return B0({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async contextPack(_){let $=this.workspace;if(this.isApiMode()){let I=(_.query??_.topic??"").trim();if(I&&_.source!=="loops"&&_.source!=="runs"){let U=await this.search({..._,query:I}),E=O6(U,{contextChars:_.contextChars});return G9(_,E,this.safetyPolicy())}return R9(_)}let D=dP(this.scope,$,_.legacyStorePath);if(!X_($.knowledgeDbPath)){let I=(_.query??_.topic??"").trim();if(I&&_.source!=="loops"&&_.source!=="runs"&&X_(D)){let U=await JI({..._,query:I,legacyStorePath:D,config:this.config()}),E=O6(U,{contextChars:_.contextChars});return G9(_,E,this.safetyPolicy())}return R9(_)}return JX({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config(),safetyPolicy:this.safetyPolicy()})}async runPrompt(_){if(this.isApiMode()){if(_.semantic===!0||_.fake===!0||Boolean(_.modelRef))throw new PN;let I=await this.cloudStore().search({query:_.prompt,archive:"active",limit:_.limit,offset:_.offset}),U=x2(I.items,{query:_.prompt,limit:_.limit,offset:_.offset,semantic:!1},[],I.total);return IX(I.items.map((E)=>E.item),{..._,config:this.config()},U)}let $=this.ensureWorkspace(),D=_.legacyStorePath??$.jsonStorePath;if(!_.legacyStorePath)xD(D);return UX({..._,dbPath:$.knowledgeDbPath,legacyStorePath:D,config:this.config()})}async webSearch(_){let $=this.ensureWorkspace();return kR({..._,dbPath:$.knowledgeDbPath,config:this.config(),safetyPolicy:this.safetyPolicy()})}async machineTopology(_={}){let $=this.workspace;return $R({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}async machinePreflight(_={}){let $=this.workspace;return IR({..._,knowledge:{scope:this.scope,workspace_home:$.home}})}syncStatus(){let _=this.workspace;if(!X_(_.knowledgeDbPath))return _q({scope:this.scope,workspaceHome:_.home});return rX({dbPath:_.knowledgeDbPath,scope:this.scope,workspaceHome:_.home})}async syncDoctor(_={}){let $=this.ensureWorkspace();c($.knowledgeDbPath);let D=this.syncStatus(),I=this.storageContract(),U=this.validateStorage(),E=$q($.knowledgeDbPath,I),j=_.machine?.trim()||null,N=_.peerWorkspace?.trim()||null,O=[],S=null,L=null;if(j&&!T9(j)){let J=await XP({machineId:j,includeTailscale:_.includeTailscale});S=nP(J),O.push(...J.warnings)}if(j||N){let J=await _N({machineId:j??cP($),peerWorkspace:N,includeTailscale:_.includeTailscale});if(j&&!N&&(S?.source==="raw"||!J.ok||!J.project_root)){let P=S9($.knowledgeDbPath,j);if(P){if(S?.source==="raw"&&P.ssh_target)S=nP(L9(P,j,{target:S.target,route:S.route,targetKind:S.target_kind,confidence:S.confidence,source:S.source,adapter:S.adapter,evidence:S.evidence,cacheability:S.cacheability,warnings:[]}));if(!J.ok||!J.project_root){let X=W9(P,j,J);if(X)L=G1(X,X.project_root),O.push(...X.warnings)}}}L=J.ok&&J.project_root?G1(J,J.project_root):L??{...G1(J,N??""),project_root:J.project_root??N??""},O.push(...J.warnings)}if(!U.ok)O.push(...U.errors.map((J)=>`storage:${J}`));let W=nb($.knowledgeDbPath,L);if(!W.ok)O.push("open_files_boundary_raw_payload_sentinels");if(!E.ok)O.push(...E.warnings);let g=L?.diagnostics.filter((J)=>J.severity==="fail")??[],z=U.ok&&E.ok&&W.ok&&g.length===0&&(L?.project_root!==""||!L),G=Uq({scope:this.scope,machine:j,peerWorkspace:N,tables:_.tables,resolvedWorkspace:L,openConflicts:D.conflicts.open});return{ok:z,read_only:!0,generated_at:new Date().toISOString(),scope:this.scope,workspace_home:$.home,database:{sqlite_schema_version:D.sqlite_schema_version,table_counts:D.table_counts},storage:{contract:I,validation:U,artifact_manifest:E},sync:{machines:D.machines.total,snapshots:D.snapshots.total,clocks:D.clocks.total,imports:D.imports.total,open_conflicts:D.conflicts.open,table_clocks:D.clocks.rows},open_files:W,resolved_route:S,resolved_workspace:L,recommended_commands:G,warnings:[...new Set(O)],message:z?`Sync readiness ok: ${D.clocks.total} table clock(s), ${D.conflicts.open} open conflict(s)`:`Sync readiness needs attention: ${[...new Set(O)].join(", ")||"workspace diagnostics failed"}`}}repairArtifactManifestKeys(_={}){let $=this.ensureWorkspace();c($.knowledgeDbPath);let D=this.storageContract(),I=oP(D),U=Dq($.knowledgeDbPath,D),E=_.dryRun===!0||_.approveWrite!==!0;if(U.length===0)return{ok:!0,dry_run:E,approval_required:!1,storage_type:D.storage_type,storage_prefix:I,candidates:U,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:D.storage_type,storage_prefix:I,candidates:U,repaired:0,audit_event_id:null,message:`Would repair ${U.length} legacy S3 artifact manifest key(s)`};if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,dry_run:!0,approval_required:!0,storage_type:D.storage_type,storage_prefix:I,candidates:U,repaired:0,audit_event_id:null,message:"Artifact key repair requires --approve-write and --approved-by "};let j=w($.knowledgeDbPath);try{let N=new Date().toISOString();j.transaction((L)=>{let W=j.query("UPDATE storage_objects SET metadata_json = ?, updated_at = ? WHERE id = ?"),g=j.query("SELECT id, metadata_json FROM storage_objects").all(),z=new Map(g.map((G)=>[G.id,o4(G.metadata_json)]));for(let G of L){let J=z.get(G.id)??{};J.key=G.repaired_key,W.run(JSON.stringify(J),N,G.id)}})(U);let S=R_(j,{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:U.length,storage_type:D.storage_type,storage_prefix:I,artifact_uris:U.map((L)=>L.artifact_uri)}});return{ok:!0,dry_run:!1,approval_required:!1,storage_type:D.storage_type,storage_prefix:I,candidates:U,repaired:U.length,audit_event_id:S,message:`Repaired ${U.length} legacy S3 artifact manifest key(s)`}}finally{j.close()}}async createSyncSnapshot(_={}){let $=this.ensureWorkspace(),D=await this.machineTopology({includeTailscale:_.includeTailscale!==!1});return wX({dbPath:$.knowledgeDbPath,scope:this.scope,workspaceHome:$.home,storage:this.storageContract(),topology:D,machineId:_.machineId})}syncConflicts(_={}){let $=this.workspace;if(!X_($.knowledgeDbPath))return[];return fX($.knowledgeDbPath,_)}syncConflict(_){let $=this.ensureWorkspace(),D=FI($.knowledgeDbPath,_);if(!D)throw Error(`Sync conflict not found: ${_}`);return D}proposeSyncConflictResolution(_){let $=this.ensureWorkspace();return $U($.knowledgeDbPath,_)}async proposeSyncConflictResolutionWithAi(_){let $=this.ensureWorkspace();return xG({dbPath:$.knowledgeDbPath,id:_.id,config:this.config(),modelRef:_.modelRef,fake:_.fake,env:_.env})}resolveSyncConflict(_){let $=this.ensureWorkspace(),D=$U($.knowledgeDbPath,_.id);if(_.approveWrite!==!0||!_.approvedBy)return{ok:!1,approval_required:!0,conflict:D.conflict,proposal:D,message:"Sync conflict resolution requires --approve-write and --approved-by "};let I=yX($.knowledgeDbPath,{id:_.id,strategy:_.strategy??D.proposed_strategy,approvedBy:_.approvedBy,proposedPatchUri:_.proposedPatchUri}),U=w($.knowledgeDbPath);try{let E=R_(U,{event_type:"sync_conflict_resolution",action:"sync.conflict.resolve",target_uri:`knowledge-sync-conflict://${_.id}`,decision:"allow",metadata:{conflict_id:_.id,entity_kind:I.entity_kind,entity_id:I.entity_id,strategy:I.resolution_strategy,approved_by:I.approved_by,proposed_patch_uri:I.proposed_patch_uri}});return{ok:!0,approval_required:!1,conflict:I,audit_event_id:E,message:`Resolved sync conflict ${_.id}`}}finally{U.close()}}syncMachines(){let _=this.workspace;if(!X_(_.knowledgeDbPath))return[];return s2(_.knowledgeDbPath)}exportSyncBundle(_={}){let $=this.ensureWorkspace();return this.assertStorageValid("sync export"),c($.knowledgeDbPath),_U({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"),c($.knowledgeDbPath),TI({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",D=_.dryRun===!0,I=this.ensureWorkspace();c(I.knowledgeDbPath);let U=_.tables?.length?["--tables",_.tables.join(",")]:[],E=_.includeArtifactContent===!1?["--no-artifact-content"]:[],j=["--scope",this.scope,"--json"],N=await XP({machineId:_.machine,includeTailscale:_.includeTailscale}),O=await _N({machineId:_.machine,peerWorkspace:_.peerWorkspace,includeTailscale:_.includeTailscale});if(!_.peerWorkspace&&N.source==="raw"||!O.ok||!O.project_root){let z=S9(I.knowledgeDbPath,_.machine);if(z){if(!_.peerWorkspace&&N.source==="raw"&&z.ssh_target)N=L9(z,_.machine,N);if(!O.ok||!O.project_root){let G=W9(z,_.machine,O);if(G)O=G}}}if(!O.ok||!O.project_root)throw Error([`Unable to resolve peer workspace for ${_.machine}.`,"Pass --peer-workspace or configure workspace path mapping in machines.",O.warnings.length?`Warnings: ${O.warnings.join(", ")}`:null].filter(Boolean).join(" "));let S=O.project_root,L={ok:!0,dry_run:D,direction:$,transport:"ssh",machine:_.machine,resolved_machine:N.target,resolved_route:nP(N),resolved_workspace:G1(O,O.project_root),peer_workspace:S,message:""},W=!1,g=()=>{if(D||W)return;kX(I.knowledgeDbPath,{machineId:_.machine,route:N,workspace:O}),W=!0};if($==="pull"||$==="both"){let z=O9(S,["sync","export",...j,...U,...E]),G=Y9(_.machine,z,void 0,N),J=Q9(_.machine,"sync export",G);Eq(_.machine,J),L.pull=await this.importSyncBundle({bundle:J,dryRun:D,direction:"pull",machineId:_.machineId??null})}if($==="push"||$==="both"){g();let z=this.exportSyncBundle({machineId:_.machineId??null,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:!D}),G=O9(S,["sync","import",...j,...D?["--dry-run"]:[]]),J=Q9(_.machine,"sync import",Y9(_.machine,G,JSON.stringify(z),N));jq(_.machine,J),L.push=J}return L.ok=(L.pull?.ok??!0)&&(L.push?.ok??!0),g(),L.message=[J9(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",D=this.ensureWorkspace();c(D.knowledgeDbPath);let I=K9(_.peerWorkspace),U=wb(I);c(U.knowledgeDbPath);let E=yN(U.configPath),j=s1(E,U,this.scope),N=g2(E,U),O=_.machineId??cP(D),S=cP(U),L=await _N({machineId:_.machineId??S,peerWorkspace:I,includeTailscale:!1}),W=()=>_U({dbPath:D.knowledgeDbPath,scope:this.scope,workspaceHome:D.home,storage:this.storageContract(),machineId:O,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),g=()=>_U({dbPath:U.knowledgeDbPath,scope:this.scope,workspaceHome:U.home,storage:j,machineId:S,tables:_.tables,includeArtifactContent:_.includeArtifactContent,recordClocks:_.dryRun!==!0}),z={ok:!0,dry_run:_.dryRun===!0,direction:$,resolved_workspace:G1(L,L.project_root??I),message:""};if($==="pull"||$==="both")z.pull=await TI({targetDbPath:D.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:D.home,targetStorage:this.storageContract(),targetStore:this.artifactStore(),bundle:g(),targetBundle:W(),direction:"pull",dryRun:_.dryRun,localMachineId:O});if($==="push"||$==="both")z.push=await TI({targetDbPath:U.knowledgeDbPath,targetScope:this.scope,targetWorkspaceHome:U.home,targetStorage:j,targetStore:N,bundle:W(),targetBundle:g(),direction:"push",dryRun:_.dryRun,localMachineId:S});return z.ok=(z.pull?.ok??!0)&&(z.push?.ok??!0),z.message=[J9(z.resolved_workspace),z.pull?`pull: ${z.pull.message}`:null,z.push?`push: ${z.push.message}`:null].filter(Boolean).join("; "),z}}function gN(_={}){return new Z9(_)}import{createHash as H9}from"crypto";var Aq=Object.defineProperty,Oq=(_)=>_;function Sq(_,$){this[_]=Oq.bind(null,$)}var Lq=(_,$)=>{for(var D in $)Aq(_,D,{get:$[D],enumerable:!0,configurable:!0,set:Sq.bind($,D)})},A={};Lq(A,{void:()=>oq,util:()=>N_,unknown:()=>iq,union:()=>sq,undefined:()=>dq,tuple:()=>Dk,transformer:()=>k9,symbol:()=>nq,string:()=>l9,strictObject:()=>aq,setErrorMap:()=>Pq,set:()=>Ek,record:()=>Uk,quotelessJson:()=>Wq,promise:()=>Lk,preprocess:()=>Pk,pipeline:()=>zk,ostring:()=>gk,optional:()=>Wk,onumber:()=>Xk,oboolean:()=>Gk,objectUtil:()=>aP,object:()=>eq,number:()=>i9,nullable:()=>Jk,null:()=>mq,never:()=>tq,nativeEnum:()=>Sk,nan:()=>yq,map:()=>Ik,makeIssue:()=>RN,literal:()=>Ak,lazy:()=>Nk,late:()=>xq,isValid:()=>p4,isDirty:()=>_z,isAsync:()=>K1,isAborted:()=>sP,intersection:()=>$k,instanceof:()=>uq,getParsedType:()=>Q6,getErrorMap:()=>GN,function:()=>jk,enum:()=>Ok,effect:()=>k9,discriminatedUnion:()=>_k,defaultErrorMap:()=>zD,datetimeRegex:()=>n9,date:()=>cq,custom:()=>m9,coerce:()=>Rk,boolean:()=>t9,bigint:()=>hq,array:()=>pq,any:()=>lq,addIssueToContext:()=>u,ZodVoid:()=>F1,ZodUnknown:()=>e6,ZodUnion:()=>RD,ZodUndefined:()=>XD,ZodType:()=>$_,ZodTuple:()=>p$,ZodTransformer:()=>Q$,ZodSymbol:()=>T1,ZodString:()=>k$,ZodSet:()=>s4,ZodSchema:()=>$_,ZodRecord:()=>V1,ZodReadonly:()=>BD,ZodPromise:()=>_0,ZodPipeline:()=>Z1,ZodParsedType:()=>h,ZodOptional:()=>v$,ZodObject:()=>q_,ZodNumber:()=>a6,ZodNullable:()=>K6,ZodNull:()=>GD,ZodNever:()=>o$,ZodNativeEnum:()=>TD,ZodNaN:()=>M1,ZodMap:()=>B1,ZodLiteral:()=>KD,ZodLazy:()=>QD,ZodIssueCode:()=>C,ZodIntersection:()=>YD,ZodFunction:()=>JD,ZodFirstPartyTypeKind:()=>t,ZodError:()=>W$,ZodEnum:()=>_4,ZodEffects:()=>Q$,ZodDiscriminatedUnion:()=>KN,ZodDefault:()=>FD,ZodDate:()=>e4,ZodCatch:()=>VD,ZodBranded:()=>TN,ZodBoolean:()=>gD,ZodBigInt:()=>s6,ZodArray:()=>C$,ZodAny:()=>a4,Schema:()=>$_,ParseStatus:()=>l_,OK:()=>s_,NEVER:()=>Yk,INVALID:()=>i,EMPTY_PATH:()=>zq,DIRTY:()=>WD,BRAND:()=>fq});var N_;(function(_){_.assertEqual=(U)=>{};function $(U){}_.assertIs=$;function D(U){throw Error()}_.assertNever=D,_.arrayToEnum=(U)=>{let E={};for(let j of U)E[j]=j;return E},_.getValidEnumValues=(U)=>{let E=_.objectKeys(U).filter((N)=>typeof U[U[N]]!=="number"),j={};for(let N of E)j[N]=U[N];return _.objectValues(j)},_.objectValues=(U)=>{return _.objectKeys(U).map(function(E){return U[E]})},_.objectKeys=typeof Object.keys==="function"?(U)=>Object.keys(U):(U)=>{let E=[];for(let j in U)if(Object.prototype.hasOwnProperty.call(U,j))E.push(j);return E},_.find=(U,E)=>{for(let j of U)if(E(j))return j;return},_.isInteger=typeof Number.isInteger==="function"?(U)=>Number.isInteger(U):(U)=>typeof U==="number"&&Number.isFinite(U)&&Math.floor(U)===U;function I(U,E=" | "){return U.map((j)=>typeof j==="string"?`'${j}'`:j).join(E)}_.joinValues=I,_.jsonStringifyReplacer=(U,E)=>{if(typeof E==="bigint")return E.toString();return E}})(N_||(N_={}));var aP;(function(_){_.mergeShapes=($,D)=>{return{...$,...D}}})(aP||(aP={}));var h=N_.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Q6=(_)=>{switch(typeof _){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(_)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":if(Array.isArray(_))return h.array;if(_===null)return h.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return h.promise;if(typeof Map<"u"&&_ instanceof Map)return h.map;if(typeof Set<"u"&&_ instanceof Set)return h.set;if(typeof Date<"u"&&_ instanceof Date)return h.date;return h.object;default:return h.unknown}},C=N_.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"]),Wq=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class W$ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=(D)=>{this.issues=[...this.issues,D]},this.addIssues=(D=[])=>{this.issues=[...this.issues,...D]};let $=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,$);else this.__proto__=$;this.name="ZodError",this.issues=_}format(_){let $=_||function(U){return U.message},D={_errors:[]},I=(U)=>{for(let E of U.issues)if(E.code==="invalid_union")E.unionErrors.map(I);else if(E.code==="invalid_return_type")I(E.returnTypeError);else if(E.code==="invalid_arguments")I(E.argumentsError);else if(E.path.length===0)D._errors.push($(E));else{let j=D,N=0;while(N$.message){let $={},D=[];for(let I of this.issues)if(I.path.length>0){let U=I.path[0];$[U]=$[U]||[],$[U].push(_(I))}else D.push(_(I));return{formErrors:D,fieldErrors:$}}get formErrors(){return this.flatten()}}W$.create=(_)=>{return new W$(_)};var Jq=(_,$)=>{let D;switch(_.code){case C.invalid_type:if(_.received===h.undefined)D="Required";else D=`Expected ${_.expected}, received ${_.received}`;break;case C.invalid_literal:D=`Invalid literal value, expected ${JSON.stringify(_.expected,N_.jsonStringifyReplacer)}`;break;case C.unrecognized_keys:D=`Unrecognized key(s) in object: ${N_.joinValues(_.keys,", ")}`;break;case C.invalid_union:D="Invalid input";break;case C.invalid_union_discriminator:D=`Invalid discriminator value. Expected ${N_.joinValues(_.options)}`;break;case C.invalid_enum_value:D=`Invalid enum value. Expected ${N_.joinValues(_.options)}, received '${_.received}'`;break;case C.invalid_arguments:D="Invalid function arguments";break;case C.invalid_return_type:D="Invalid function return type";break;case C.invalid_date:D="Invalid date";break;case C.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if(D=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")D=`${D} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)D=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)D=`Invalid input: must end with "${_.validation.endsWith}"`;else N_.assertNever(_.validation);else if(_.validation!=="regex")D=`Invalid ${_.validation}`;else D="Invalid";break;case C.too_small:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")D=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else D="Invalid input";break;case C.too_big:if(_.type==="array")D=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")D=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")D=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")D=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")D=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else D="Invalid input";break;case C.custom:D="Invalid input";break;case C.invalid_intersection_types:D="Intersection results could not be merged";break;case C.not_multiple_of:D=`Number must be a multiple of ${_.multipleOf}`;break;case C.not_finite:D="Number must be finite";break;default:D=$.defaultError,N_.assertNever(_)}return{message:D}},zD=Jq,y9=zD;function Pq(_){y9=_}function GN(){return y9}var RN=(_)=>{let{data:$,path:D,errorMaps:I,issueData:U}=_,E=[...D,...U.path||[]],j={...U,path:E};if(U.message!==void 0)return{...U,path:E,message:U.message};let N="",O=I.filter((S)=>!!S).slice().reverse();for(let S of O)N=S(j,{data:$,defaultError:N}).message;return{...U,path:E,message:N}},zq=[];function u(_,$){let D=GN(),I=RN({issueData:$,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,D,D===zD?void 0:zD].filter((U)=>!!U)});_.common.issues.push(I)}class l_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,$){let D=[];for(let I of $){if(I.status==="aborted")return i;if(I.status==="dirty")_.dirty();D.push(I.value)}return{status:_.value,value:D}}static async mergeObjectAsync(_,$){let D=[];for(let I of $){let U=await I.key,E=await I.value;D.push({key:U,value:E})}return l_.mergeObjectSync(_,D)}static mergeObjectSync(_,$){let D={};for(let I of $){let{key:U,value:E}=I;if(U.status==="aborted")return i;if(E.status==="aborted")return i;if(U.status==="dirty")_.dirty();if(E.status==="dirty")_.dirty();if(U.value!=="__proto__"&&(typeof E.value<"u"||I.alwaysSet))D[U.value]=E.value}return{status:_.value,value:D}}}var i=Object.freeze({status:"aborted"}),WD=(_)=>({status:"dirty",value:_}),s_=(_)=>({status:"valid",value:_}),sP=(_)=>_.status==="aborted",_z=(_)=>_.status==="dirty",p4=(_)=>_.status==="valid",K1=(_)=>typeof Promise<"u"&&_ instanceof Promise,d;(function(_){_.errToObj=($)=>typeof $==="string"?{message:$}:$||{},_.toString=($)=>typeof $==="string"?$:$?.message})(d||(d={}));class w${constructor(_,$,D,I){this._cachedPath=[],this.parent=_,this.data=$,this._path=D,this._key=I}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 b9=(_,$)=>{if(p4($))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 D=new W$(_.common.issues);return this._error=D,this._error}}}};function s(_){if(!_)return{};let{errorMap:$,invalid_type_error:D,required_error:I,description:U}=_;if($&&(D||I))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if($)return{errorMap:$,description:U};return{errorMap:(j,N)=>{let{message:O}=_;if(j.code==="invalid_enum_value")return{message:O??N.defaultError};if(typeof N.data>"u")return{message:O??I??N.defaultError};if(j.code!=="invalid_type")return{message:N.defaultError};return{message:O??D??N.defaultError}},description:U}}class $_{get description(){return this._def.description}_getType(_){return Q6(_.data)}_getOrReturnCtx(_,$){return $||{common:_.parent.common,data:_.data,parsedType:Q6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new l_,ctx:{common:_.parent.common,data:_.data,parsedType:Q6(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let $=this._parse(_);if(K1($))throw Error("Synchronous parse encountered promise.");return $}_parseAsync(_){let $=this._parse(_);return Promise.resolve($)}parse(_,$){let D=this.safeParse(_,$);if(D.success)return D.data;throw D.error}safeParse(_,$){let D={common:{issues:[],async:$?.async??!1,contextualErrorMap:$?.errorMap},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Q6(_)},I=this._parseSync({data:_,path:D.path,parent:D});return b9(D,I)}"~validate"(_){let $={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Q6(_)};if(!this["~standard"].async)try{let D=this._parseSync({data:_,path:[],parent:$});return p4(D)?{value:D.value}:{issues:$.common.issues}}catch(D){if(D?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;$.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:$}).then((D)=>p4(D)?{value:D.value}:{issues:$.common.issues})}async parseAsync(_,$){let D=await this.safeParseAsync(_,$);if(D.success)return D.data;throw D.error}async safeParseAsync(_,$){let D={common:{issues:[],contextualErrorMap:$?.errorMap,async:!0},path:$?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Q6(_)},I=this._parse({data:_,path:D.path,parent:D}),U=await(K1(I)?I:Promise.resolve(I));return b9(D,U)}refine(_,$){let D=(I)=>{if(typeof $==="string"||typeof $>"u")return{message:$};else if(typeof $==="function")return $(I);else return $};return this._refinement((I,U)=>{let E=_(I),j=()=>U.addIssue({code:C.custom,...D(I)});if(typeof Promise<"u"&&E instanceof Promise)return E.then((N)=>{if(!N)return j(),!1;else return!0});if(!E)return j(),!1;else return!0})}refinement(_,$){return this._refinement((D,I)=>{if(!_(D))return I.addIssue(typeof $==="function"?$(D,I):$),!1;else return!0})}_refinement(_){return new Q$({schema:this,typeName:t.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 v$.create(this,this._def)}nullable(){return K6.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return C$.create(this)}promise(){return _0.create(this,this._def)}or(_){return RD.create([this,_],this._def)}and(_){return YD.create(this,_,this._def)}transform(_){return new Q$({...s(this._def),schema:this,typeName:t.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let $=typeof _==="function"?_:()=>_;return new FD({...s(this._def),innerType:this,defaultValue:$,typeName:t.ZodDefault})}brand(){return new TN({typeName:t.ZodBranded,type:this,...s(this._def)})}catch(_){let $=typeof _==="function"?_:()=>_;return new VD({...s(this._def),innerType:this,catchValue:$,typeName:t.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return Z1.create(this,_)}readonly(){return BD.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var gq=/^c[^\s-]{8,}$/i,Xq=/^[0-9a-z]+$/,Gq=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Rq=/^[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,Yq=/^[a-z0-9_-]{21}$/i,Qq=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Kq=/^[-+]?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)?)??$/,Tq=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Fq="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",pP,Vq=/^(?:(?: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])$/,Bq=/^(?:(?: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])$/,Mq=/^(([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]))$/,Zq=/^(([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])$/,Hq=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bq=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,h9="((\\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])))",qq=new RegExp(`^${h9}$`);function c9(_){let $="[0-5]\\d";if(_.precision)$=`${$}\\.\\d{${_.precision}}`;else if(_.precision==null)$=`${$}(\\.\\d+)?`;let D=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${$})${D}`}function kq(_){return new RegExp(`^${c9(_)}$`)}function n9(_){let $=`${h9}T${c9(_)}`,D=[];if(D.push(_.local?"Z?":"Z"),_.offset)D.push("([+-]\\d{2}:?\\d{2})");return $=`${$}(${D.join("|")})`,new RegExp(`^${$}$`)}function Cq(_,$){if(($==="v4"||!$)&&Vq.test(_))return!0;if(($==="v6"||!$)&&Mq.test(_))return!0;return!1}function vq(_,$){if(!Qq.test(_))return!1;try{let[D]=_.split(".");if(!D)return!1;let I=D.replace(/-/g,"+").replace(/_/g,"/").padEnd(D.length+(4-D.length%4)%4,"="),U=JSON.parse(atob(I));if(typeof U!=="object"||U===null)return!1;if("typ"in U&&U?.typ!=="JWT")return!1;if(!U.alg)return!1;if($&&U.alg!==$)return!1;return!0}catch{return!1}}function wq(_,$){if(($==="v4"||!$)&&Bq.test(_))return!0;if(($==="v6"||!$)&&Zq.test(_))return!0;return!1}class k$ extends $_{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==h.string){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_type,expected:h.string,received:U.parsedType}),i}let D=new l_,I=void 0;for(let U of this._def.checks)if(U.kind==="min"){if(_.data.lengthU.value)I=this._getOrReturnCtx(_,I),u(I,{code:C.too_big,maximum:U.value,type:"string",inclusive:!0,exact:!1,message:U.message}),D.dirty()}else if(U.kind==="length"){let E=_.data.length>U.value,j=_.data.length_.test(I),{validation:$,code:C.invalid_string,...d.errToObj(D)})}_addCheck(_){return new k$({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...d.errToObj(_)})}url(_){return this._addCheck({kind:"url",...d.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...d.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...d.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...d.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...d.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...d.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...d.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...d.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...d.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...d.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...d.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...d.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,...d.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,...d.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...d.errToObj(_)})}regex(_,$){return this._addCheck({kind:"regex",regex:_,...d.errToObj($)})}includes(_,$){return this._addCheck({kind:"includes",value:_,position:$?.position,...d.errToObj($?.message)})}startsWith(_,$){return this._addCheck({kind:"startsWith",value:_,...d.errToObj($)})}endsWith(_,$){return this._addCheck({kind:"endsWith",value:_,...d.errToObj($)})}min(_,$){return this._addCheck({kind:"min",value:_,...d.errToObj($)})}max(_,$){return this._addCheck({kind:"max",value:_,...d.errToObj($)})}length(_,$){return this._addCheck({kind:"length",value:_,...d.errToObj($)})}nonempty(_){return this.min(1,d.errToObj(_))}trim(){return new k$({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new k$({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new k$({...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 _}}k$.create=(_)=>{return new k$({checks:[],typeName:t.ZodString,coerce:_?.coerce??!1,...s(_)})};function rq(_,$){let D=(_.toString().split(".")[1]||"").length,I=($.toString().split(".")[1]||"").length,U=D>I?D:I,E=Number.parseInt(_.toFixed(U).replace(".","")),j=Number.parseInt($.toFixed(U).replace(".",""));return E%j/10**U}class a6 extends $_{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(_)!==h.number){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_type,expected:h.number,received:U.parsedType}),i}let D=void 0,I=new l_;for(let U of this._def.checks)if(U.kind==="int"){if(!N_.isInteger(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:C.invalid_type,expected:"integer",received:"float",message:U.message}),I.dirty()}else if(U.kind==="min"){if(U.inclusive?_.dataU.value:_.data>=U.value)D=this._getOrReturnCtx(_,D),u(D,{code:C.too_big,maximum:U.value,type:"number",inclusive:U.inclusive,exact:!1,message:U.message}),I.dirty()}else if(U.kind==="multipleOf"){if(rq(_.data,U.value)!==0)D=this._getOrReturnCtx(_,D),u(D,{code:C.not_multiple_of,multipleOf:U.value,message:U.message}),I.dirty()}else if(U.kind==="finite"){if(!Number.isFinite(_.data))D=this._getOrReturnCtx(_,D),u(D,{code:C.not_finite,message:U.message}),I.dirty()}else N_.assertNever(U);return{status:I.value,value:_.data}}gte(_,$){return this.setLimit("min",_,!0,d.toString($))}gt(_,$){return this.setLimit("min",_,!1,d.toString($))}lte(_,$){return this.setLimit("max",_,!0,d.toString($))}lt(_,$){return this.setLimit("max",_,!1,d.toString($))}setLimit(_,$,D,I){return new a6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:d.toString(I)}]})}_addCheck(_){return new a6({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:d.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:d.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:d.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:d.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:d.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:d.toString($)})}finite(_){return this._addCheck({kind:"finite",message:d.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:d.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:d.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"&&N_.isInteger(_.value))}get isFinite(){let _=null,$=null;for(let D of this._def.checks)if(D.kind==="finite"||D.kind==="int"||D.kind==="multipleOf")return!0;else if(D.kind==="min"){if($===null||D.value>$)$=D.value}else if(D.kind==="max"){if(_===null||D.value<_)_=D.value}return Number.isFinite($)&&Number.isFinite(_)}}a6.create=(_)=>{return new a6({checks:[],typeName:t.ZodNumber,coerce:_?.coerce||!1,...s(_)})};class s6 extends $_{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(_)!==h.bigint)return this._getInvalidInput(_);let D=void 0,I=new l_;for(let U of this._def.checks)if(U.kind==="min"){if(U.inclusive?_.dataU.value:_.data>=U.value)D=this._getOrReturnCtx(_,D),u(D,{code:C.too_big,type:"bigint",maximum:U.value,inclusive:U.inclusive,message:U.message}),I.dirty()}else if(U.kind==="multipleOf"){if(_.data%U.value!==BigInt(0))D=this._getOrReturnCtx(_,D),u(D,{code:C.not_multiple_of,multipleOf:U.value,message:U.message}),I.dirty()}else N_.assertNever(U);return{status:I.value,value:_.data}}_getInvalidInput(_){let $=this._getOrReturnCtx(_);return u($,{code:C.invalid_type,expected:h.bigint,received:$.parsedType}),i}gte(_,$){return this.setLimit("min",_,!0,d.toString($))}gt(_,$){return this.setLimit("min",_,!1,d.toString($))}lte(_,$){return this.setLimit("max",_,!0,d.toString($))}lt(_,$){return this.setLimit("max",_,!1,d.toString($))}setLimit(_,$,D,I){return new s6({...this._def,checks:[...this._def.checks,{kind:_,value:$,inclusive:D,message:d.toString(I)}]})}_addCheck(_){return new s6({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:d.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:d.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:d.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:d.toString(_)})}multipleOf(_,$){return this._addCheck({kind:"multipleOf",value:_,message:d.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 _}}s6.create=(_)=>{return new s6({checks:[],typeName:t.ZodBigInt,coerce:_?.coerce??!1,...s(_)})};class gD extends $_{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==h.boolean){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.boolean,received:D.parsedType}),i}return s_(_.data)}}gD.create=(_)=>{return new gD({typeName:t.ZodBoolean,coerce:_?.coerce||!1,...s(_)})};class e4 extends $_{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==h.date){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_type,expected:h.date,received:U.parsedType}),i}if(Number.isNaN(_.data.getTime())){let U=this._getOrReturnCtx(_);return u(U,{code:C.invalid_date}),i}let D=new l_,I=void 0;for(let U of this._def.checks)if(U.kind==="min"){if(_.data.getTime()U.value)I=this._getOrReturnCtx(_,I),u(I,{code:C.too_big,message:U.message,inclusive:!0,exact:!1,maximum:U.value,type:"date"}),D.dirty()}else N_.assertNever(U);return{status:D.value,value:new Date(_.data.getTime())}}_addCheck(_){return new e4({...this._def,checks:[...this._def.checks,_]})}min(_,$){return this._addCheck({kind:"min",value:_.getTime(),message:d.toString($)})}max(_,$){return this._addCheck({kind:"max",value:_.getTime(),message:d.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}}e4.create=(_)=>{return new e4({checks:[],coerce:_?.coerce||!1,typeName:t.ZodDate,...s(_)})};class T1 extends $_{_parse(_){if(this._getType(_)!==h.symbol){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.symbol,received:D.parsedType}),i}return s_(_.data)}}T1.create=(_)=>{return new T1({typeName:t.ZodSymbol,...s(_)})};class XD extends $_{_parse(_){if(this._getType(_)!==h.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.undefined,received:D.parsedType}),i}return s_(_.data)}}XD.create=(_)=>{return new XD({typeName:t.ZodUndefined,...s(_)})};class GD extends $_{_parse(_){if(this._getType(_)!==h.null){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.null,received:D.parsedType}),i}return s_(_.data)}}GD.create=(_)=>{return new GD({typeName:t.ZodNull,...s(_)})};class a4 extends $_{constructor(){super(...arguments);this._any=!0}_parse(_){return s_(_.data)}}a4.create=(_)=>{return new a4({typeName:t.ZodAny,...s(_)})};class e6 extends $_{constructor(){super(...arguments);this._unknown=!0}_parse(_){return s_(_.data)}}e6.create=(_)=>{return new e6({typeName:t.ZodUnknown,...s(_)})};class o$ extends $_{_parse(_){let $=this._getOrReturnCtx(_);return u($,{code:C.invalid_type,expected:h.never,received:$.parsedType}),i}}o$.create=(_)=>{return new o$({typeName:t.ZodNever,...s(_)})};class F1 extends $_{_parse(_){if(this._getType(_)!==h.undefined){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.void,received:D.parsedType}),i}return s_(_.data)}}F1.create=(_)=>{return new F1({typeName:t.ZodVoid,...s(_)})};class C$ extends $_{_parse(_){let{ctx:$,status:D}=this._processInputParams(_),I=this._def;if($.parsedType!==h.array)return u($,{code:C.invalid_type,expected:h.array,received:$.parsedType}),i;if(I.exactLength!==null){let E=$.data.length>I.exactLength.value,j=$.data.lengthI.maxLength.value)u($,{code:C.too_big,maximum:I.maxLength.value,type:"array",inclusive:!0,exact:!1,message:I.maxLength.message}),D.dirty()}if($.common.async)return Promise.all([...$.data].map((E,j)=>{return I.type._parseAsync(new w$($,E,$.path,j))})).then((E)=>{return l_.mergeArray(D,E)});let U=[...$.data].map((E,j)=>{return I.type._parseSync(new w$($,E,$.path,j))});return l_.mergeArray(D,U)}get element(){return this._def.type}min(_,$){return new C$({...this._def,minLength:{value:_,message:d.toString($)}})}max(_,$){return new C$({...this._def,maxLength:{value:_,message:d.toString($)}})}length(_,$){return new C$({...this._def,exactLength:{value:_,message:d.toString($)}})}nonempty(_){return this.min(1,_)}}C$.create=(_,$)=>{return new C$({type:_,minLength:null,maxLength:null,exactLength:null,typeName:t.ZodArray,...s($)})};function SD(_){if(_ instanceof q_){let $={};for(let D in _.shape){let I=_.shape[D];$[D]=v$.create(SD(I))}return new q_({..._._def,shape:()=>$})}else if(_ instanceof C$)return new C$({..._._def,type:SD(_.element)});else if(_ instanceof v$)return v$.create(SD(_.unwrap()));else if(_ instanceof K6)return K6.create(SD(_.unwrap()));else if(_ instanceof p$)return p$.create(_.items.map(($)=>SD($)));else return _}class q_ extends $_{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(),$=N_.objectKeys(_);return this._cached={shape:_,keys:$},this._cached}_parse(_){if(this._getType(_)!==h.object){let O=this._getOrReturnCtx(_);return u(O,{code:C.invalid_type,expected:h.object,received:O.parsedType}),i}let{status:D,ctx:I}=this._processInputParams(_),{shape:U,keys:E}=this._getCached(),j=[];if(!(this._def.catchall instanceof o$&&this._def.unknownKeys==="strip")){for(let O in I.data)if(!E.includes(O))j.push(O)}let N=[];for(let O of E){let S=U[O],L=I.data[O];N.push({key:{status:"valid",value:O},value:S._parse(new w$(I,L,I.path,O)),alwaysSet:O in I.data})}if(this._def.catchall instanceof o$){let O=this._def.unknownKeys;if(O==="passthrough")for(let S of j)N.push({key:{status:"valid",value:S},value:{status:"valid",value:I.data[S]}});else if(O==="strict"){if(j.length>0)u(I,{code:C.unrecognized_keys,keys:j}),D.dirty()}else if(O==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let O=this._def.catchall;for(let S of j){let L=I.data[S];N.push({key:{status:"valid",value:S},value:O._parse(new w$(I,L,I.path,S)),alwaysSet:S in I.data})}}if(I.common.async)return Promise.resolve().then(async()=>{let O=[];for(let S of N){let L=await S.key,W=await S.value;O.push({key:L,value:W,alwaysSet:S.alwaysSet})}return O}).then((O)=>{return l_.mergeObjectSync(D,O)});else return l_.mergeObjectSync(D,N)}get shape(){return this._def.shape()}strict(_){return d.errToObj,new q_({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:($,D)=>{let I=this._def.errorMap?.($,D).message??D.defaultError;if($.code==="unrecognized_keys")return{message:d.errToObj(_).message??I};return{message:I}}}:{}})}strip(){return new q_({...this._def,unknownKeys:"strip"})}passthrough(){return new q_({...this._def,unknownKeys:"passthrough"})}extend(_){return new q_({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new q_({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:t.ZodObject})}setKey(_,$){return this.augment({[_]:$})}catchall(_){return new q_({...this._def,catchall:_})}pick(_){let $={};for(let D of N_.objectKeys(_))if(_[D]&&this.shape[D])$[D]=this.shape[D];return new q_({...this._def,shape:()=>$})}omit(_){let $={};for(let D of N_.objectKeys(this.shape))if(!_[D])$[D]=this.shape[D];return new q_({...this._def,shape:()=>$})}deepPartial(){return SD(this)}partial(_){let $={};for(let D of N_.objectKeys(this.shape)){let I=this.shape[D];if(_&&!_[D])$[D]=I;else $[D]=I.optional()}return new q_({...this._def,shape:()=>$})}required(_){let $={};for(let D of N_.objectKeys(this.shape))if(_&&!_[D])$[D]=this.shape[D];else{let U=this.shape[D];while(U instanceof v$)U=U._def.innerType;$[D]=U}return new q_({...this._def,shape:()=>$})}keyof(){return d9(N_.objectKeys(this.shape))}}q_.create=(_,$)=>{return new q_({shape:()=>_,unknownKeys:"strip",catchall:o$.create(),typeName:t.ZodObject,...s($)})};q_.strictCreate=(_,$)=>{return new q_({shape:()=>_,unknownKeys:"strict",catchall:o$.create(),typeName:t.ZodObject,...s($)})};q_.lazycreate=(_,$)=>{return new q_({shape:_,unknownKeys:"strip",catchall:o$.create(),typeName:t.ZodObject,...s($)})};class RD extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D=this._def.options;function I(U){for(let j of U)if(j.result.status==="valid")return j.result;for(let j of U)if(j.result.status==="dirty")return $.common.issues.push(...j.ctx.common.issues),j.result;let E=U.map((j)=>new W$(j.ctx.common.issues));return u($,{code:C.invalid_union,unionErrors:E}),i}if($.common.async)return Promise.all(D.map(async(U)=>{let E={...$,common:{...$.common,issues:[]},parent:null};return{result:await U._parseAsync({data:$.data,path:$.path,parent:E}),ctx:E}})).then(I);else{let U=void 0,E=[];for(let N of D){let O={...$,common:{...$.common,issues:[]},parent:null},S=N._parseSync({data:$.data,path:$.path,parent:O});if(S.status==="valid")return S;else if(S.status==="dirty"&&!U)U={result:S,ctx:O};if(O.common.issues.length)E.push(O.common.issues)}if(U)return $.common.issues.push(...U.ctx.common.issues),U.result;let j=E.map((N)=>new W$(N));return u($,{code:C.invalid_union,unionErrors:j}),i}}get options(){return this._def.options}}RD.create=(_,$)=>{return new RD({options:_,typeName:t.ZodUnion,...s($)})};var Y6=(_)=>{if(_ instanceof QD)return Y6(_.schema);else if(_ instanceof Q$)return Y6(_.innerType());else if(_ instanceof KD)return[_.value];else if(_ instanceof _4)return _.options;else if(_ instanceof TD)return N_.objectValues(_.enum);else if(_ instanceof FD)return Y6(_._def.innerType);else if(_ instanceof XD)return[void 0];else if(_ instanceof GD)return[null];else if(_ instanceof v$)return[void 0,...Y6(_.unwrap())];else if(_ instanceof K6)return[null,...Y6(_.unwrap())];else if(_ instanceof TN)return Y6(_.unwrap());else if(_ instanceof BD)return Y6(_.unwrap());else if(_ instanceof VD)return Y6(_._def.innerType);else return[]};class KN extends $_{_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==h.object)return u($,{code:C.invalid_type,expected:h.object,received:$.parsedType}),i;let D=this.discriminator,I=$.data[D],U=this.optionsMap.get(I);if(!U)return u($,{code:C.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[D]}),i;if($.common.async)return U._parseAsync({data:$.data,path:$.path,parent:$});else return U._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(_,$,D){let I=new Map;for(let U of $){let E=Y6(U.shape[_]);if(!E.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let j of E){if(I.has(j))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(j)}`);I.set(j,U)}}return new KN({typeName:t.ZodDiscriminatedUnion,discriminator:_,options:$,optionsMap:I,...s(D)})}}function $z(_,$){let D=Q6(_),I=Q6($);if(_===$)return{valid:!0,data:_};else if(D===h.object&&I===h.object){let U=N_.objectKeys($),E=N_.objectKeys(_).filter((N)=>U.indexOf(N)!==-1),j={..._,...$};for(let N of E){let O=$z(_[N],$[N]);if(!O.valid)return{valid:!1};j[N]=O.data}return{valid:!0,data:j}}else if(D===h.array&&I===h.array){if(_.length!==$.length)return{valid:!1};let U=[];for(let E=0;E<_.length;E++){let j=_[E],N=$[E],O=$z(j,N);if(!O.valid)return{valid:!1};U.push(O.data)}return{valid:!0,data:U}}else if(D===h.date&&I===h.date&&+_===+$)return{valid:!0,data:_};else return{valid:!1}}class YD extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_),I=(U,E)=>{if(sP(U)||sP(E))return i;let j=$z(U.value,E.value);if(!j.valid)return u(D,{code:C.invalid_intersection_types}),i;if(_z(U)||_z(E))$.dirty();return{status:$.value,value:j.data}};if(D.common.async)return Promise.all([this._def.left._parseAsync({data:D.data,path:D.path,parent:D}),this._def.right._parseAsync({data:D.data,path:D.path,parent:D})]).then(([U,E])=>I(U,E));else return I(this._def.left._parseSync({data:D.data,path:D.path,parent:D}),this._def.right._parseSync({data:D.data,path:D.path,parent:D}))}}YD.create=(_,$,D)=>{return new YD({left:_,right:$,typeName:t.ZodIntersection,...s(D)})};class p$ extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.array)return u(D,{code:C.invalid_type,expected:h.array,received:D.parsedType}),i;if(D.data.lengththis._def.items.length)u(D,{code:C.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),$.dirty();let U=[...D.data].map((E,j)=>{let N=this._def.items[j]||this._def.rest;if(!N)return null;return N._parse(new w$(D,E,D.path,j))}).filter((E)=>!!E);if(D.common.async)return Promise.all(U).then((E)=>{return l_.mergeArray($,E)});else return l_.mergeArray($,U)}get items(){return this._def.items}rest(_){return new p$({...this._def,rest:_})}}p$.create=(_,$)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new p$({items:_,typeName:t.ZodTuple,rest:null,...s($)})};class V1 extends $_{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.object)return u(D,{code:C.invalid_type,expected:h.object,received:D.parsedType}),i;let I=[],U=this._def.keyType,E=this._def.valueType;for(let j in D.data)I.push({key:U._parse(new w$(D,j,D.path,j)),value:E._parse(new w$(D,D.data[j],D.path,j)),alwaysSet:j in D.data});if(D.common.async)return l_.mergeObjectAsync($,I);else return l_.mergeObjectSync($,I)}get element(){return this._def.valueType}static create(_,$,D){if($ instanceof $_)return new V1({keyType:_,valueType:$,typeName:t.ZodRecord,...s(D)});return new V1({keyType:k$.create(),valueType:_,typeName:t.ZodRecord,...s($)})}}class B1 extends $_{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.map)return u(D,{code:C.invalid_type,expected:h.map,received:D.parsedType}),i;let I=this._def.keyType,U=this._def.valueType,E=[...D.data.entries()].map(([j,N],O)=>{return{key:I._parse(new w$(D,j,D.path,[O,"key"])),value:U._parse(new w$(D,N,D.path,[O,"value"]))}});if(D.common.async){let j=new Map;return Promise.resolve().then(async()=>{for(let N of E){let O=await N.key,S=await N.value;if(O.status==="aborted"||S.status==="aborted")return i;if(O.status==="dirty"||S.status==="dirty")$.dirty();j.set(O.value,S.value)}return{status:$.value,value:j}})}else{let j=new Map;for(let N of E){let{key:O,value:S}=N;if(O.status==="aborted"||S.status==="aborted")return i;if(O.status==="dirty"||S.status==="dirty")$.dirty();j.set(O.value,S.value)}return{status:$.value,value:j}}}}B1.create=(_,$,D)=>{return new B1({valueType:$,keyType:_,typeName:t.ZodMap,...s(D)})};class s4 extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.parsedType!==h.set)return u(D,{code:C.invalid_type,expected:h.set,received:D.parsedType}),i;let I=this._def;if(I.minSize!==null){if(D.data.sizeI.maxSize.value)u(D,{code:C.too_big,maximum:I.maxSize.value,type:"set",inclusive:!0,exact:!1,message:I.maxSize.message}),$.dirty()}let U=this._def.valueType;function E(N){let O=new Set;for(let S of N){if(S.status==="aborted")return i;if(S.status==="dirty")$.dirty();O.add(S.value)}return{status:$.value,value:O}}let j=[...D.data.values()].map((N,O)=>U._parse(new w$(D,N,D.path,O)));if(D.common.async)return Promise.all(j).then((N)=>E(N));else return E(j)}min(_,$){return new s4({...this._def,minSize:{value:_,message:d.toString($)}})}max(_,$){return new s4({...this._def,maxSize:{value:_,message:d.toString($)}})}size(_,$){return this.min(_,$).max(_,$)}nonempty(_){return this.min(1,_)}}s4.create=(_,$)=>{return new s4({valueType:_,minSize:null,maxSize:null,typeName:t.ZodSet,...s($)})};class JD extends $_{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==h.function)return u($,{code:C.invalid_type,expected:h.function,received:$.parsedType}),i;function D(j,N){return RN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,GN(),zD].filter((O)=>!!O),issueData:{code:C.invalid_arguments,argumentsError:N}})}function I(j,N){return RN({data:j,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,GN(),zD].filter((O)=>!!O),issueData:{code:C.invalid_return_type,returnTypeError:N}})}let U={errorMap:$.common.contextualErrorMap},E=$.data;if(this._def.returns instanceof _0){let j=this;return s_(async function(...N){let O=new W$([]),S=await j._def.args.parseAsync(N,U).catch((g)=>{throw O.addIssue(D(N,g)),O}),L=await Reflect.apply(E,this,S);return await j._def.returns._def.type.parseAsync(L,U).catch((g)=>{throw O.addIssue(I(L,g)),O})})}else{let j=this;return s_(function(...N){let O=j._def.args.safeParse(N,U);if(!O.success)throw new W$([D(N,O.error)]);let S=Reflect.apply(E,this,O.data),L=j._def.returns.safeParse(S,U);if(!L.success)throw new W$([I(S,L.error)]);return L.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new JD({...this._def,args:p$.create(_).rest(e6.create())})}returns(_){return new JD({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,$,D){return new JD({args:_?_:p$.create([]).rest(e6.create()),returns:$||e6.create(),typeName:t.ZodFunction,...s(D)})}}class QD extends $_{get schema(){return this._def.getter()}_parse(_){let{ctx:$}=this._processInputParams(_);return this._def.getter()._parse({data:$.data,path:$.path,parent:$})}}QD.create=(_,$)=>{return new QD({getter:_,typeName:t.ZodLazy,...s($)})};class KD extends $_{_parse(_){if(_.data!==this._def.value){let $=this._getOrReturnCtx(_);return u($,{received:$.data,code:C.invalid_literal,expected:this._def.value}),i}return{status:"valid",value:_.data}}get value(){return this._def.value}}KD.create=(_,$)=>{return new KD({value:_,typeName:t.ZodLiteral,...s($)})};function d9(_,$){return new _4({values:_,typeName:t.ZodEnum,...s($)})}class _4 extends $_{_parse(_){if(typeof _.data!=="string"){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{expected:N_.joinValues(D),received:$.parsedType,code:C.invalid_type}),i}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let $=this._getOrReturnCtx(_),D=this._def.values;return u($,{received:$.data,code:C.invalid_enum_value,options:D}),i}return s_(_.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 _4.create(_,{...this._def,...$})}exclude(_,$=this._def){return _4.create(this.options.filter((D)=>!_.includes(D)),{...this._def,...$})}}_4.create=d9;class TD extends $_{_parse(_){let $=N_.getValidEnumValues(this._def.values),D=this._getOrReturnCtx(_);if(D.parsedType!==h.string&&D.parsedType!==h.number){let I=N_.objectValues($);return u(D,{expected:N_.joinValues(I),received:D.parsedType,code:C.invalid_type}),i}if(!this._cache)this._cache=new Set(N_.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let I=N_.objectValues($);return u(D,{received:D.data,code:C.invalid_enum_value,options:I}),i}return s_(_.data)}get enum(){return this._def.values}}TD.create=(_,$)=>{return new TD({values:_,typeName:t.ZodNativeEnum,...s($)})};class _0 extends $_{unwrap(){return this._def.type}_parse(_){let{ctx:$}=this._processInputParams(_);if($.parsedType!==h.promise&&$.common.async===!1)return u($,{code:C.invalid_type,expected:h.promise,received:$.parsedType}),i;let D=$.parsedType===h.promise?$.data:Promise.resolve($.data);return s_(D.then((I)=>{return this._def.type.parseAsync(I,{path:$.path,errorMap:$.common.contextualErrorMap})}))}}_0.create=(_,$)=>{return new _0({type:_,typeName:t.ZodPromise,...s($)})};class Q$ extends $_{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===t.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:$,ctx:D}=this._processInputParams(_),I=this._def.effect||null,U={addIssue:(E)=>{if(u(D,E),E.fatal)$.abort();else $.dirty()},get path(){return D.path}};if(U.addIssue=U.addIssue.bind(U),I.type==="preprocess"){let E=I.transform(D.data,U);if(D.common.async)return Promise.resolve(E).then(async(j)=>{if($.value==="aborted")return i;let N=await this._def.schema._parseAsync({data:j,path:D.path,parent:D});if(N.status==="aborted")return i;if(N.status==="dirty")return WD(N.value);if($.value==="dirty")return WD(N.value);return N});else{if($.value==="aborted")return i;let j=this._def.schema._parseSync({data:E,path:D.path,parent:D});if(j.status==="aborted")return i;if(j.status==="dirty")return WD(j.value);if($.value==="dirty")return WD(j.value);return j}}if(I.type==="refinement"){let E=(j)=>{let N=I.refinement(j,U);if(D.common.async)return Promise.resolve(N);if(N instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return j};if(D.common.async===!1){let j=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(j.status==="aborted")return i;if(j.status==="dirty")$.dirty();return E(j.value),{status:$.value,value:j.value}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((j)=>{if(j.status==="aborted")return i;if(j.status==="dirty")$.dirty();return E(j.value).then(()=>{return{status:$.value,value:j.value}})})}if(I.type==="transform")if(D.common.async===!1){let E=this._def.schema._parseSync({data:D.data,path:D.path,parent:D});if(!p4(E))return i;let j=I.transform(E.value,U);if(j instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:$.value,value:j}}else return this._def.schema._parseAsync({data:D.data,path:D.path,parent:D}).then((E)=>{if(!p4(E))return i;return Promise.resolve(I.transform(E.value,U)).then((j)=>({status:$.value,value:j}))});N_.assertNever(I)}}Q$.create=(_,$,D)=>{return new Q$({schema:_,typeName:t.ZodEffects,effect:$,...s(D)})};Q$.createWithPreprocess=(_,$,D)=>{return new Q$({schema:$,effect:{type:"preprocess",transform:_},typeName:t.ZodEffects,...s(D)})};class v$ extends $_{_parse(_){if(this._getType(_)===h.undefined)return s_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}v$.create=(_,$)=>{return new v$({innerType:_,typeName:t.ZodOptional,...s($)})};class K6 extends $_{_parse(_){if(this._getType(_)===h.null)return s_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}K6.create=(_,$)=>{return new K6({innerType:_,typeName:t.ZodNullable,...s($)})};class FD extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;if($.parsedType===h.undefined)D=this._def.defaultValue();return this._def.innerType._parse({data:D,path:$.path,parent:$})}removeDefault(){return this._def.innerType}}FD.create=(_,$)=>{return new FD({innerType:_,typeName:t.ZodDefault,defaultValue:typeof $.default==="function"?$.default:()=>$.default,...s($)})};class VD extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D={...$,common:{...$.common,issues:[]}},I=this._def.innerType._parse({data:D.data,path:D.path,parent:{...D}});if(K1(I))return I.then((U)=>{return{status:"valid",value:U.status==="valid"?U.value:this._def.catchValue({get error(){return new W$(D.common.issues)},input:D.data})}});else return{status:"valid",value:I.status==="valid"?I.value:this._def.catchValue({get error(){return new W$(D.common.issues)},input:D.data})}}removeCatch(){return this._def.innerType}}VD.create=(_,$)=>{return new VD({innerType:_,typeName:t.ZodCatch,catchValue:typeof $.catch==="function"?$.catch:()=>$.catch,...s($)})};class M1 extends $_{_parse(_){if(this._getType(_)!==h.nan){let D=this._getOrReturnCtx(_);return u(D,{code:C.invalid_type,expected:h.nan,received:D.parsedType}),i}return{status:"valid",value:_.data}}}M1.create=(_)=>{return new M1({typeName:t.ZodNaN,...s(_)})};var fq=Symbol("zod_brand");class TN extends $_{_parse(_){let{ctx:$}=this._processInputParams(_),D=$.data;return this._def.type._parse({data:D,path:$.path,parent:$})}unwrap(){return this._def.type}}class Z1 extends $_{_parse(_){let{status:$,ctx:D}=this._processInputParams(_);if(D.common.async)return(async()=>{let U=await this._def.in._parseAsync({data:D.data,path:D.path,parent:D});if(U.status==="aborted")return i;if(U.status==="dirty")return $.dirty(),WD(U.value);else return this._def.out._parseAsync({data:U.value,path:D.path,parent:D})})();else{let I=this._def.in._parseSync({data:D.data,path:D.path,parent:D});if(I.status==="aborted")return i;if(I.status==="dirty")return $.dirty(),{status:"dirty",value:I.value};else return this._def.out._parseSync({data:I.value,path:D.path,parent:D})}}static create(_,$){return new Z1({in:_,out:$,typeName:t.ZodPipeline})}}class BD extends $_{_parse(_){let $=this._def.innerType._parse(_),D=(I)=>{if(p4(I))I.value=Object.freeze(I.value);return I};return K1($)?$.then((I)=>D(I)):D($)}unwrap(){return this._def.innerType}}BD.create=(_,$)=>{return new BD({innerType:_,typeName:t.ZodReadonly,...s($)})};function q9(_,$){let D=typeof _==="function"?_($):typeof _==="string"?{message:_}:_;return typeof D==="string"?{message:D}:D}function m9(_,$={},D){if(_)return a4.create().superRefine((I,U)=>{let E=_(I);if(E instanceof Promise)return E.then((j)=>{if(!j){let N=q9($,I),O=N.fatal??D??!0;U.addIssue({code:"custom",...N,fatal:O})}});if(!E){let j=q9($,I),N=j.fatal??D??!0;U.addIssue({code:"custom",...j,fatal:N})}return});return a4.create()}var xq={object:q_.lazycreate},t;(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"})(t||(t={}));var uq=(_,$={message:`Input not instance of ${_.name}`})=>m9((D)=>D instanceof _,$),l9=k$.create,i9=a6.create,yq=M1.create,hq=s6.create,t9=gD.create,cq=e4.create,nq=T1.create,dq=XD.create,mq=GD.create,lq=a4.create,iq=e6.create,tq=o$.create,oq=F1.create,pq=C$.create,eq=q_.create,aq=q_.strictCreate,sq=RD.create,_k=KN.create,$k=YD.create,Dk=p$.create,Uk=V1.create,Ik=B1.create,Ek=s4.create,jk=JD.create,Nk=QD.create,Ak=KD.create,Ok=_4.create,Sk=TD.create,Lk=_0.create,k9=Q$.create,Wk=v$.create,Jk=K6.create,Pk=Q$.createWithPreprocess,zk=Z1.create,gk=()=>l9().optional(),Xk=()=>i9().optional(),Gk=()=>t9().optional(),Rk={string:(_)=>k$.create({..._,coerce:!0}),number:(_)=>a6.create({..._,coerce:!0}),boolean:(_)=>gD.create({..._,coerce:!0}),bigint:(_)=>s6.create({..._,coerce:!0}),date:(_)=>e4.create({..._,coerce:!0})},Yk=i;var y={actorRef:"hasna.actor_ref.v1",resourceRef:"hasna.resource_ref.v1",evidenceRef:"hasna.evidence_ref.v1",workRun:"hasna.work_run.v1",taskToPrProjection:"hasna.task_to_pr_projection.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",secureLocalStorePolicy:"hasna.secure_local_store_policy.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"},Uz=A.string().regex(/^hasna\.[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*\.v[0-9]+$/),M_=A.string().datetime(),e=A.string().trim().min(1),r$=e.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://"),o9=A.string().regex(/^[a-fA-F0-9]{64}$/),p9=A.string().regex(/^(sha256:)?[a-fA-F0-9]{64}$/),$4=A.record(A.unknown()),HD=A.array(A.string().min(1)).default([]),$0=M_.nullable().optional(),Qk=new Set(["succeeded","failed","cancelled","blocked","skipped"]),I0=A.enum(["pending","running","succeeded","failed","cancelled","blocked","skipped","unknown"]);function J_(_){return A.object({schema:A.literal(_),id:A.string().min(1),createdAt:M_,updatedAt:$0,metadata:$4.optional()}).strict()}var Sm=A.object({schema:Uz,id:A.string().min(1),createdAt:M_,updatedAt:$0,metadata:$4.optional()}).strict(),e9=A.enum(["agent","human","service","model","workflow","system"]),Kk=J_(y.actorRef).extend({kind:e9,name:A.string().min(1).optional(),provider:A.string().min(1).optional(),accountId:A.string().min(1).optional(),machineId:A.string().min(1).optional(),capabilities:A.array(A.string().min(1)).default([])}).strict(),e$=A.object({kind:e9,id:A.string().min(1),name:A.string().min(1).optional(),provider:A.string().min(1).optional(),accountId:A.string().min(1).optional(),machineId:A.string().min(1).optional()}).strict(),a9=A.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"]),Tk=J_(y.resourceRef).extend({kind:a9,name:A.string().min(1).optional(),uri:r$.optional(),externalId:e.optional(),sourcePackage:e.optional(),tags:HD}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.externalId&&_.sourcePackage))$.addIssue({code:A.ZodIssueCode.custom,message:"Resource refs require uri or both sourcePackage and externalId",path:["uri"]})}),__=A.object({kind:a9,id:A.string().min(1),name:A.string().min(1).optional(),uri:r$.optional(),externalId:e.optional(),sourcePackage:e.optional(),tags:HD}).strict().superRefine((_,$)=>{if(!_.uri&&Boolean(_.externalId)!==Boolean(_.sourcePackage))$.addIssue({code:A.ZodIssueCode.custom,message:"Resource pointers with external package locators require both sourcePackage and externalId",path:_.externalId?["sourcePackage"]:["externalId"]})}),Iz=A.enum(["file","command_output","screenshot","log","diff","report","artifact","url","video","har","test_result","metric","trace","other"]),Fk=A.enum(["none","partial","full","unknown"]),Vk=J_(y.evidenceRef).extend({kind:Iz,uri:r$,sha256:o9.optional(),summary:A.string().min(1).optional(),contentType:A.string().min(1).optional(),sizeBytes:A.number().int().nonnegative().optional(),redaction:Fk.default("unknown"),producer:e$.optional(),resourceRefs:A.array(__).default([]),tags:HD}).strict(),T_=A.object({id:A.string().min(1),kind:Iz.optional(),uri:r$.optional(),sha256:o9.optional(),summary:A.string().min(1).optional()}).strict(),H1=J_(y.costEstimate).extend({currency:A.string().regex(/^[A-Z]{3}$/).default("USD"),amountMicros:A.number().int().nonnegative(),provider:A.string().min(1).optional(),model:A.string().min(1).optional(),accountId:A.string().min(1).optional(),promptTokens:A.number().int().nonnegative().optional(),completionTokens:A.number().int().nonnegative().optional(),totalTokens:A.number().int().nonnegative().optional(),basis:A.enum(["actual","estimated","budget","limit"]).default("estimated"),resourceRefs:A.array(__).default([])}).strict().superRefine((_,$)=>{if(_.promptTokens!==void 0&&_.completionTokens!==void 0&&_.totalTokens!==void 0&&_.totalTokens!==_.promptTokens+_.completionTokens)$.addIssue({code:A.ZodIssueCode.custom,message:"totalTokens must equal promptTokens plus completionTokens when all are present",path:["totalTokens"]})}),Bk=A.enum(["allowed","denied","warned","approval_required","selected","skipped","unknown"]),s9=J_(y.decisionEnvelope).extend({decisionType:A.enum(["guardrail","model_route","tool_select","budget","secret_access","approval","policy","other"]),status:Bk,actor:e$.optional(),traceId:A.string().min(1).optional(),inputHash:p9.optional(),policyBundleId:A.string().min(1).optional(),selected:A.array(__).default([]),skipped:A.array(__).default([]),reason:A.string().min(1),obligations:A.array(A.string().min(1)).default([]),redactions:A.array(A.string().min(1)).default([]),costEstimate:H1.optional(),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.status==="selected"&&_.selected.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Selected decisions require at least one selected resource",path:["selected"]});if(_.status==="skipped"&&_.skipped.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Skipped decisions require at least one skipped resource",path:["skipped"]});if(_.status==="denied"){if(_.selected.length>0)$.addIssue({code:A.ZodIssueCode.custom,message:"Denied decisions cannot include selected resources",path:["selected"]});if(!_.policyBundleId&&_.evidenceRefs.length===0&&_.obligations.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Denied decisions require policy, evidence, or obligations",path:["policyBundleId"]})}if(_.status==="approval_required"&&_.obligations.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Approval-required decisions require actionable obligations",path:["obligations"]})}),Mk=J_(y.capabilityCard).extend({kind:A.enum(["model","tool","machine","agent","lane","connector","service"]),name:A.string().min(1),version:A.string().min(1).optional(),status:A.enum(["available","unavailable","degraded","unknown"]).default("unknown"),capabilities:A.array(A.string().min(1)).default([]),limitations:A.array(A.string().min(1)).default([]),riskLevel:A.enum(["low","medium","high","critical","unknown"]).default("unknown"),costEstimate:H1.optional(),evidenceRefs:A.array(T_).default([])}).strict(),MD=A.enum(["mock","fixture","sandbox","read_only_live","live_mutating"]),Zk=A.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"]),Hk=A.object({refName:e,requiredForModes:A.array(MD).min(1),allowedSecretInputs:A.array(A.enum(["credential_ref","lease_ref"])).min(1).default(["credential_ref"]),failClosedDiagnostic:e,revocationCheck:A.boolean().default(!0)}).strict(),bk=A.object({operation:e,supportedModes:A.array(MD).min(1),sideEffectClass:Zk,requiresApproval:A.boolean().default(!1),requiresIdempotencyKey:A.boolean().default(!1),requiresSandboxEvidence:A.boolean().default(!1),requiresRollbackOrRevocation:A.boolean().default(!1),rollbackOrRevocation:e.optional(),noSideEffectSmoke:e.optional(),reconciliation:e.optional()}).strict().superRefine((_,$)=>{if(_.supportedModes.includes("live_mutating")){if(_.sideEffectClass==="none"||_.sideEffectClass==="read_only")$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating operations must declare a side-effecting class",path:["sideEffectClass"]});if(!_.requiresApproval)$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating operations require approval",path:["requiresApproval"]});if(!_.requiresIdempotencyKey)$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating operations require idempotency keys",path:["requiresIdempotencyKey"]});if(!_.requiresSandboxEvidence)$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating operations require sandbox evidence before live proof",path:["requiresSandboxEvidence"]});if(!_.requiresRollbackOrRevocation||!_.rollbackOrRevocation)$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating operations require rollback or revocation instructions",path:["rollbackOrRevocation"]});if(!_.reconciliation)$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating operations require reconciliation behavior",path:["reconciliation"]})}}),qk=A.object({providerId:e,appId:e,adapterId:e,ownerPackage:e,modes:A.array(MD).min(1),defaultMode:MD,credentialRequirements:A.array(Hk).default([]),operations:A.array(bk).min(1),rateLimitPosture:e,costPosture:e.optional(),auditEvents:A.array(e).default([]),redactionRules:A.array(e).default([]),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{if(!_.modes.includes(_.defaultMode))$.addIssue({code:A.ZodIssueCode.custom,message:"defaultMode must be one of modes",path:["defaultMode"]});let D=new Set(_.operations.flatMap((I)=>I.supportedModes));for(let I of D)if(!_.modes.includes(I))$.addIssue({code:A.ZodIssueCode.custom,message:`operation mode ${I} is not declared in provider modes`,path:["operations"]});if(D.has("live_mutating")){if(!_.credentialRequirements.some((U)=>U.requiredForModes.includes("live_mutating")))$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating providers require at least one live credential reference requirement",path:["credentialRequirements"]});if(_.auditEvents.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"live_mutating providers require audit events",path:["auditEvents"]})}}),kk=A.object({appId:e,repo:e,priority:A.enum(["p0","p1","p2"]).default("p1"),requiredEvidence:A.array(e).min(1),firstOperations:A.array(e).min(1),blockedUntil:A.array(e).default([])}).strict(),Ck=J_(y.providerLiveModeStandard).extend({name:e,version:e,modes:A.array(MD).refine((_)=>["mock","fixture","sandbox","read_only_live","live_mutating"].every(($)=>_.includes($)),"provider live-mode standard must include every canonical provider mode"),requiredCapabilityFields:A.array(e).min(1),liveMutationGate:A.object({requiredMode:A.literal("live_mutating"),requiredChecks:A.array(e).min(1),forbiddenBypassSignals:A.array(e).min(1),disabledLiveSmoke:e}).strict(),noSideEffectSmoke:A.object({requiredForModes:A.array(MD).min(1),commandEvidence:A.array(e).min(1),secretOutputScan:A.boolean().default(!0)}).strict(),credentialPolicy:A.object({acceptedInputs:A.array(A.enum(["credential_ref","lease_ref"])).min(1),rawSecretInputsAllowed:A.literal(!1),missingCredentialBehavior:A.literal("fail_closed"),revocationCheckRequired:A.boolean().default(!0)}).strict(),operationCards:A.array(qk).min(1),firstAdoptionTargets:A.array(kk).min(1),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set(_.firstAdoptionTargets.map((U)=>U.appId)),I=new Set(_.operationCards.map((U)=>U.appId));for(let U of D)if(!I.has(U))$.addIssue({code:A.ZodIssueCode.custom,message:`first adoption target ${U} requires a provider capability card`,path:["firstAdoptionTargets"]})}),vk=A.object({id:A.string().min(1),title:A.string().min(1).optional(),summary:A.string().min(1),text:A.string().optional(),tokens:A.number().int().nonnegative().optional(),source:T_,resourceRefs:A.array(__).default([])}).strict(),_8=J_(y.contextPack).extend({objective:A.string().min(1),budget:A.object({maxTokens:A.number().int().positive().optional(),maxBytes:A.number().int().positive().optional()}).strict().optional(),items:A.array(vk).default([]),citations:A.array(T_).default([]),freshness:A.enum(["fresh","stale","unknown"]).default("unknown"),permissions:A.array(A.string().min(1)).default([]),redactions:A.array(A.string().min(1)).default([]),conflicts:A.array(A.string().min(1)).default([]),uncertainty:A.string().min(1).optional()}).strict(),R$=e.refine((_)=>!_.startsWith("/")&&!_.includes("\\")&&!_.split("/").includes(".."),"Project paths must be relative and cannot contain parent-directory segments"),D0=A.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Project slugs must be lowercase dashed identifiers"),wk=A.enum(["public","internal","private","sensitive"]),rk=A.enum(["draft","active","paused","archived"]),Ez=A.enum(["todos","files","mailery","conversations","knowledge","mementos","reports","actions","render","contracts","custom"]),$8=J_(y.integrationRef).extend({kind:Ez,name:A.string().min(1),projectId:D0.optional(),sourcePackage:e.optional(),externalId:e.optional(),uri:r$.optional(),enabled:A.boolean().default(!0),readOnly:A.boolean().default(!0),capabilities:A.array(A.string().min(1)).default([]),freshness:A.enum(["fresh","stale","unknown"]).default("unknown"),resourceRef:__.optional(),evidenceRefs:A.array(T_).default([]),config:$4.optional()}).strict().superRefine((_,$)=>{if(!_.uri&&!(_.sourcePackage&&_.externalId)&&!_.resourceRef)$.addIssue({code:A.ZodIssueCode.custom,message:"Integration refs require uri, resourceRef, or both sourcePackage and externalId",path:["uri"]})}),fk=A.object({schemaRoot:R$.default(".hasna/project"),dashboardManifest:R$.default(".hasna/project/dashboard.render.json"),snapshotsDir:R$.default(".hasna/project/snapshots"),documentsDir:R$.default("documents"),reportsDir:R$.default("reports"),evidenceDir:R$.default(".hasna/project/evidence"),privateDir:R$.default(".hasna/project/private")}).strict(),xk=J_(y.projectManifest).extend({projectId:D0,slug:D0,name:A.string().min(1),summary:A.string().min(1).optional(),status:rk.default("active"),classification:wk.default("private"),owner:e$.optional(),layout:fk.default({}),integrations:A.array($8).default([]),renderManifests:A.array(__).default([]),resourceRefs:A.array(__).default([]),evidenceRefs:A.array(T_).default([]),tags:HD}).strict().superRefine((_,$)=>{let D=new Set,I=new Set;if(_.projectId!==_.slug)$.addIssue({code:A.ZodIssueCode.custom,message:"projectId and slug must match for canonical project manifests",path:["slug"]});for(let[U,E]of _.integrations.entries()){if(D.has(E.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Project manifest integration ids must be unique",path:["integrations",U,"id"]});if(D.add(E.id),E.projectId&&E.projectId!==_.projectId)$.addIssue({code:A.ZodIssueCode.custom,message:"Integration projectId must match the manifest projectId",path:["integrations",U,"projectId"]})}for(let[U,E]of _.renderManifests.entries()){if(E.kind!=="render")$.addIssue({code:A.ZodIssueCode.custom,message:"Project renderManifests must use resource kind render",path:["renderManifests",U,"kind"]});if(I.has(E.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Project renderManifest refs must be unique",path:["renderManifests",U,"id"]});I.add(E.id)}}),uk=A.enum(["local","package","provider","url"]),jz=A.object({id:A.string().min(1),kind:uk,specifier:A.string().min(1),path:R$.optional(),packageName:A.string().min(1).optional(),uri:r$.optional(),provider:Ez.optional(),schemaId:Uz.optional(),integrity:p9.optional(),resourceRef:__.optional(),optional:A.boolean().default(!1)}).strict().superRefine((_,$)=>{if(_.kind==="local"&&!_.path)$.addIssue({code:A.ZodIssueCode.custom,message:"Local render imports require path",path:["path"]});if(_.kind==="package"&&!_.packageName)$.addIssue({code:A.ZodIssueCode.custom,message:"Package render imports require packageName",path:["packageName"]});if(_.kind==="provider"&&!_.provider)$.addIssue({code:A.ZodIssueCode.custom,message:"Provider render imports require provider",path:["provider"]});if(_.kind==="url"&&!_.uri)$.addIssue({code:A.ZodIssueCode.custom,message:"URL render imports require uri",path:["uri"]})}),yk=A.enum(["dashboard","canvas","panel","report","document","custom"]),hk=A.object({id:A.string().min(1),title:A.string().min(1),kind:yk,default:A.boolean().default(!1),entry:R$.optional(),imports:A.array(jz).default([]),panelRefs:A.array(__).default([]),dataRefs:A.array(__).default([]),layout:$4.optional()}).strict(),ck=J_(y.renderManifest).extend({projectId:D0,name:A.string().min(1),version:A.string().min(1),manifestPath:R$.default(".hasna/project/dashboard.render.json"),renderer:A.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),views:A.array(hk).min(1),imports:A.array(jz).default([]),theme:$4.optional(),compatibility:A.object({minProjectsVersion:A.string().min(1).optional(),minContractsVersion:A.string().min(1).optional()}).strict().optional(),resourceRefs:A.array(__).default([]),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{let D=_.views.filter((E)=>E.default),I=new Set,U=new Set;if(D.length>1)$.addIssue({code:A.ZodIssueCode.custom,message:"Render manifests can have at most one default view",path:["views"]});for(let[E,j]of _.imports.entries()){if(U.has(j.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Render manifest import ids must be unique",path:["imports",E,"id"]});U.add(j.id)}for(let[E,j]of _.views.entries()){if(I.has(j.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Render manifest view ids must be unique",path:["views",E,"id"]});I.add(j.id);let N=new Set;for(let[O,S]of j.imports.entries()){if(N.has(S.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Render view import ids must be unique",path:["views",E,"imports",O,"id"]});N.add(S.id)}for(let[O,S]of j.panelRefs.entries())if(S.kind!=="panel")$.addIssue({code:A.ZodIssueCode.custom,message:"Render view panelRefs must use resource kind panel",path:["views",E,"panelRefs",O,"kind"]})}}),nk=A.enum(["ready","empty","loading","error","auth_required","unavailable","stale"]),dk=A.enum(["overview","tasks","files","mailery","conversations","knowledge","mementos","reports","actions","timeline","risks","documents","custom"]),mk=A.object({id:A.string().min(1),label:A.string().min(1),value:A.union([A.string(),A.number(),A.boolean()]),unit:A.string().min(1).optional(),status:A.enum(["good","warning","critical","unknown"]).default("unknown"),resourceRefs:A.array(__).default([])}).strict(),lk=A.object({id:A.string().min(1),title:A.string().min(1),summary:A.string().min(1).optional(),status:A.string().min(1).optional(),priority:A.enum(["low","medium","high","critical","unknown"]).default("unknown"),timestamp:M_.optional(),resourceRefs:A.array(__).default([]),evidenceRefs:A.array(T_).default([]),metadata:$4.optional()}).strict(),ik=A.object({renderer:A.enum(["json_render","react_flow","markdown","html","custom"]).default("json_render"),title:A.string().min(1).optional(),entry:R$.optional(),imports:A.array(jz).default([]),spec:$4.default({})}).strict(),D8=J_(y.projectPanel).extend({projectId:D0,provider:A.object({kind:Ez,id:A.string().min(1),name:A.string().min(1).optional(),sourcePackage:e.optional(),externalId:e.optional()}).strict(),kind:dk,title:A.string().min(1),summary:A.string().min(1).optional(),state:nk.default("ready"),stateReason:A.string().min(1).optional(),generatedAt:M_,freshness:A.enum(["fresh","stale","unknown"]).default("unknown"),metrics:A.array(mk).default([]),items:A.array(lk).default([]),actions:A.array(__).default([]),resourceRefs:A.array(__).default([]),evidenceRefs:A.array(T_).default([]),renderFragment:ik.optional(),warnings:A.array(A.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set(["error","auth_required","unavailable","stale"]),I=new Set,U=new Set;if(D.has(_.state)&&!_.stateReason)$.addIssue({code:A.ZodIssueCode.custom,message:"Non-ready provider states require stateReason",path:["stateReason"]});if(_.state==="ready"&&_.metrics.length===0&&_.items.length===0&&!_.renderFragment)$.addIssue({code:A.ZodIssueCode.custom,message:"Ready panels require metrics, items, or a renderFragment; use state=empty for empty panels",path:["state"]});for(let[E,j]of _.metrics.entries()){if(I.has(j.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Project panel metric ids must be unique",path:["metrics",E,"id"]});I.add(j.id)}for(let[E,j]of _.items.entries()){if(U.has(j.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Project panel item ids must be unique",path:["items",E,"id"]});U.add(j.id)}for(let[E,j]of _.actions.entries())if(j.kind!=="action")$.addIssue({code:A.ZodIssueCode.custom,message:"Project panel actions must use resource kind action",path:["actions",E,"kind"]})}),tk=J_(y.projectSnapshot).extend({projectId:D0,generatedAt:M_,status:I0.default("unknown"),manifestRef:__,renderManifestRef:__.optional(),panels:A.array(D8).default([]),contextPacks:A.array(_8).default([]),proofBundleRefs:A.array(__).default([]),resourceRefs:A.array(__).default([]),evidenceRefs:A.array(T_).default([]),warnings:A.array(A.string().min(1)).default([]),freshness:A.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{let D=new Set,I=new Set;if(_.manifestRef.kind!=="project")$.addIssue({code:A.ZodIssueCode.custom,message:"Project snapshot manifestRef must use resource kind project",path:["manifestRef","kind"]});if(_.renderManifestRef&&_.renderManifestRef.kind!=="render")$.addIssue({code:A.ZodIssueCode.custom,message:"Project snapshot renderManifestRef must use resource kind render",path:["renderManifestRef","kind"]});for(let[U,E]of _.proofBundleRefs.entries())if(E.kind!=="proof_bundle")$.addIssue({code:A.ZodIssueCode.custom,message:"Project snapshot proofBundleRefs must use resource kind proof_bundle",path:["proofBundleRefs",U,"kind"]});for(let[U,E]of _.panels.entries()){if(E.projectId!==_.projectId)$.addIssue({code:A.ZodIssueCode.custom,message:"Panel projectId must match snapshot projectId",path:["panels",U,"projectId"]});if(D.has(E.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Project snapshot panel ids must be unique",path:["panels",U,"id"]});D.add(E.id)}for(let[U,E]of _.contextPacks.entries()){if(I.has(E.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Project snapshot context pack ids must be unique",path:["contextPacks",U,"id"]});I.add(E.id)}}),U8=A.object({id:A.string().min(1),kind:A.enum(["command","test","typecheck","lint","eval","security","review","deploy","smoke","manual","other"]),required:A.boolean().default(!0),command:A.string().min(1).optional(),expected:A.string().min(1).optional(),timeoutMs:A.number().int().positive().optional(),resourceRefs:A.array(__).default([])}).strict().superRefine((_,$)=>{if(new Set(["command","test","typecheck","lint","smoke","eval"]).has(_.kind)&&!_.command&&!_.expected)$.addIssue({code:A.ZodIssueCode.custom,message:"Actionable validation checks require command or expected",path:["command"]})}),ok=J_(y.validationPlan).extend({objective:A.string().min(1),subject:__.optional(),checks:A.array(U8).min(1),verifier:e$.optional(),requiredEvidenceKinds:A.array(Iz).default([])}).strict(),pk=A.enum(["open_source","internal_app","platform","app","agent","content","overlay","other"]),ek=A.enum(["draft","active","deprecated","archived"]),ak=A.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"]),sk=A.object({key:A.string().regex(/^[A-Z][A-Z0-9_]*$/),description:A.string().min(1),required:A.boolean().default(!1),["secret"]:A.boolean().default(!1),group:A.string().min(1).optional(),default:A.string().optional()}).strict().superRefine((_,$)=>{if(_.secret&&_.default!==void 0)$.addIssue({code:A.ZodIssueCode.custom,message:"Secret scaffold env vars cannot include defaults",path:["default"]})}),_C=A.object({name:A.string().min(1),command:A.string().min(1),description:A.string().min(1).optional(),required:A.boolean().default(!1)}).strict(),$C=A.object({packageManager:A.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),languages:A.array(A.string().min(1)).default([]),requiredFiles:A.array(A.string().min(1)).default([]),requiredDirectories:A.array(A.string().min(1)).default([]),optionalDirectories:A.array(A.string().min(1)).default([])}).strict(),DC=J_(y.scaffoldManifest).extend({name:A.string().min(1),version:A.string().min(1),summary:A.string().min(1),type:pk,status:ek.default("draft"),capabilities:A.array(ak).default([]),techStack:A.array(A.string().min(1)).default([]),tags:HD,source:__.optional(),output:$C,env:A.array(sk).default([]),scripts:A.array(_C).default([]),validationChecks:A.array(U8).default([]),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.source?.uri?.startsWith("file://"))$.addIssue({code:A.ZodIssueCode.custom,message:"Public scaffold manifest source refs cannot use local file:// URIs",path:["source","uri"]});if(_.status==="active"&&_.validationChecks.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Active scaffold manifests require validation checks",path:["validationChecks"]});if(_.status==="active"&&_.output.requiredFiles.length===0&&_.output.requiredDirectories.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Active scaffold manifests require at least one required file or directory",path:["output"]})}),UC=A.enum(["installed","failed","cancelled","partial","unknown"]),IC=J_(y.scaffoldInstallRecord).extend({scaffoldId:A.string().min(1),scaffoldVersion:A.string().min(1).optional(),manifestRef:__.optional(),target:__,status:UC,installedAt:M_.optional(),installer:e$.optional(),packageManager:A.enum(["bun","npm","pnpm","yarn","cargo","pip","other"]).optional(),options:$4.optional(),generatedFiles:A.array(__).default([]),evidenceRefs:A.array(T_).default([]),proofBundleRefs:A.array(__).default([])}).strict().superRefine((_,$)=>{if(_.status==="installed"&&!_.installedAt)$.addIssue({code:A.ZodIssueCode.custom,message:"Installed scaffold records require installedAt",path:["installedAt"]});if(_.status==="installed"&&_.generatedFiles.length===0&&_.evidenceRefs.length===0&&_.proofBundleRefs.length===0)$.addIssue({code:A.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:A.ZodIssueCode.custom,message:"Failed or partial scaffold records require evidence or proof bundle refs",path:["evidenceRefs"]})}),ZD=A.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"App ids must be lowercase dashed identifiers"),Nz=A.string().regex(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,"Must be a valid npm package name"),I8=A.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"),EC=A.string().regex(/^[0-9a-f]{7,40}$/,"Must be a lowercase git sha (7-40 hex chars)"),jC=e.refine((_)=>_.startsWith("https://github.com/")||_.startsWith("git+https://github.com/"),"GitHub URLs must start with https://github.com/ or git+https://github.com/"),NC=A.enum(["active","stub","deprecated","archived"]),AC=A.enum(["stable","beta","canary","internal"]),OC=A.object({transport:A.enum(["http","stdio"]).default("http"),bin:A.string().min(1).optional(),url:r$.optional()}).strict(),SC=A.object({healthPath:A.string().min(1).default("/health"),port:A.number().int().positive().optional(),baseUrl:r$.optional()}).strict(),LC=A.object({bins:A.array(A.string().min(1)).default([]),mcp:OC.optional(),http:SC.optional()}).strict(),WC=J_(y.app).extend({appId:ZD,npmName:Nz,repoFolder:ZD,githubUrl:jC,projectSlug:D0,surfaces:LC.default({}),lifecycle:NC,releaseChannel:AC.default("stable"),summary:A.string().min(1).optional(),tags:HD}).strict().superRefine((_,$)=>{let D=new Set;for(let[I,U]of _.surfaces.bins.entries()){if(D.has(U))$.addIssue({code:A.ZodIssueCode.custom,message:"App surface bins must be unique",path:["surfaces","bins",I]});D.add(U)}}),JC=A.enum(["skill","ci","backfilled"]),PC=J_(y.release).extend({appId:ZD,package:Nz,version:I8,gitSha:EC,publishedAt:M_,publishPath:JC,changelogRef:__.optional(),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.publishPath!=="backfilled"&&_.evidenceRefs.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"skill and ci releases require publish evidence; only backfilled releases may omit it",path:["evidenceRefs"]})}),zC=A.enum(["install","update","rollback","freeze-blocked"]),gC=A.object({cliVersion:A.string().min(1).optional(),mcpHealth:A.enum(["ok","degraded","unavailable","not_checked"]).optional()}).strict().superRefine((_,$)=>{if(!_.cliVersion&&_.mcpHealth===void 0)$.addIssue({code:A.ZodIssueCode.custom,message:"Rollout verification requires at least one concrete verifier field"})}),XC=J_(y.rolloutRecord).extend({appId:ZD,package:Nz,version:I8,machine:e,action:zC,result:I0,verifiedBy:gC.optional(),at:M_,evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.action==="freeze-blocked"&&_.result!=="blocked"&&_.result!=="skipped")$.addIssue({code:A.ZodIssueCode.custom,message:"freeze-blocked rollout records must report result blocked or skipped",path:["result"]});let D=Boolean(_.verifiedBy?.cliVersion)||_.verifiedBy?.mcpHealth!==void 0&&_.verifiedBy.mcpHealth!=="not_checked",I=_.verifiedBy?Object.keys(_.verifiedBy).length>0:!1;if((_.action==="install"||_.action==="update")&&_.result==="succeeded"&&(!_.verifiedBy||I&&!D))$.addIssue({code:A.ZodIssueCode.custom,message:"Succeeded install/update rollout records require concrete verification",path:["verifiedBy"]})}),GC=A.enum(["email","telegram","slack","discord","x","blog","rss","webhook","github","other"]),RC=A.enum(["pending","queued","sent","failed","skipped","suppressed"]),YC=A.object({channel:GC,status:RC,deliveredAt:M_.optional(),detail:A.string().min(1).optional()}).strict().superRefine((_,$)=>{if(_.status==="sent"&&!_.deliveredAt)$.addIssue({code:A.ZodIssueCode.custom,message:"Sent announcement channels require deliveredAt",path:["deliveredAt"]});if(_.status==="failed"&&!_.detail)$.addIssue({code:A.ZodIssueCode.custom,message:"Failed announcement channels require detail",path:["detail"]})}),QC=J_(y.announcement).extend({campaignId:e,appId:ZD.optional(),releaseRef:__.optional(),channels:A.array(YC).min(1),audienceRef:__,sentAt:M_}).strict().superRefine((_,$)=>{if(_.releaseRef&&_.releaseRef.kind!=="release")$.addIssue({code:A.ZodIssueCode.custom,message:"Announcement releaseRef must use resource kind release",path:["releaseRef","kind"]});if(_.audienceRef.kind!=="audience")$.addIssue({code:A.ZodIssueCode.custom,message:"Announcement audienceRef must use resource kind audience",path:["audienceRef","kind"]})}),KC=A.enum(["tag","attribute","group"]),TC=A.enum(["eq","neq","in","not_in","exists","not_exists"]),C9=A.union([A.string(),A.number(),A.boolean()]),FC=A.object({kind:KC,key:A.string().min(1).optional(),op:TC.default("eq"),value:C9.optional(),values:A.array(C9).default([])}).strict().superRefine((_,$)=>{if(_.kind==="attribute"&&!_.key)$.addIssue({code:A.ZodIssueCode.custom,message:"Attribute predicates require key",path:["key"]});if((_.op==="eq"||_.op==="neq")&&_.value===void 0)$.addIssue({code:A.ZodIssueCode.custom,message:"eq/neq predicates require value",path:["value"]});if((_.op==="in"||_.op==="not_in")&&_.values.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"in/not_in predicates require values",path:["values"]})}),VC=A.object({match:A.enum(["all","any"]).default("all"),predicates:A.array(FC).min(1)}).strict(),BC=A.enum(["opt_in","opt_out","transactional","none"]),MC=J_(y.audience).extend({audienceId:ZD,name:e,definition:VC,consentPolicy:BC,suppressionSyncedAt:$0}).strict(),XN=["@hasna/cloud","open-cloud"],ZC=A.enum(["aws","gcp","azure","cloudflare","vercel","neon","supabase","postgres","s3","rds","other"]),HC=A.object({id:A.string().min(1),provider:ZC,kind:A.enum(["database","bucket","queue","secret","function","worker","cache","topic","scheduler","object_store","other"]),ownerPackage:A.string().min(1),region:A.string().min(1).optional(),accountId:A.string().min(1).optional(),uri:r$.optional(),machineScoped:A.boolean().default(!1)}).strict(),E8=J_(y.appCloudManifest).extend({packageName:A.string().min(1),packageVersion:A.string().min(1).optional(),appId:A.string().min(1),repository:__.optional(),storageMode:A.enum(["local_only","app_owned_cloud","hybrid_local_cache","external_service"]),cloudBoundary:A.enum(["none","app_owned","external_service","local_cache"]),cloudResources:A.array(HC).default([]),localCache:A.object({path:A.string().min(1).optional(),pullMode:A.enum(["manual","daemon","ci","none"]).default("manual"),conflictPolicy:A.enum(["cloud_wins","local_wins","merge","manual_review"]).default("manual_review")}).strict().optional(),forbiddenSharedRuntimes:A.array(A.string().min(1)).default([...XN]),dependencies:A.array(A.string().min(1)).default([]),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{let D=new Set([...XN,..._.forbiddenSharedRuntimes]);if(D.has(_.packageName))$.addIssue({code:A.ZodIssueCode.custom,message:"App-owned cloud manifests cannot be for a forbidden runtime",path:["packageName"]});for(let I of XN)if(!_.forbiddenSharedRuntimes.includes(I))$.addIssue({code:A.ZodIssueCode.custom,message:`forbiddenSharedRuntimes must include ${I}`,path:["forbiddenSharedRuntimes"]});for(let I of D)if(_.dependencies.includes(I))$.addIssue({code:A.ZodIssueCode.custom,message:`App-owned cloud manifests cannot depend on ${I}`,path:["dependencies"]});if(_.storageMode==="local_only"&&_.cloudBoundary!=="none")$.addIssue({code:A.ZodIssueCode.custom,message:"local_only storage requires cloudBoundary none",path:["cloudBoundary"]});if(_.storageMode==="app_owned_cloud"&&_.cloudBoundary!=="app_owned")$.addIssue({code:A.ZodIssueCode.custom,message:"app_owned_cloud storage requires cloudBoundary app_owned",path:["cloudBoundary"]});if(_.storageMode==="hybrid_local_cache"){if(_.cloudBoundary!=="local_cache")$.addIssue({code:A.ZodIssueCode.custom,message:"hybrid_local_cache storage requires cloudBoundary local_cache",path:["cloudBoundary"]});if(!_.localCache)$.addIssue({code:A.ZodIssueCode.custom,message:"hybrid_local_cache storage requires localCache settings",path:["localCache"]})}if(_.storageMode==="external_service"){if(_.cloudBoundary!=="external_service")$.addIssue({code:A.ZodIssueCode.custom,message:"external_service storage requires cloudBoundary external_service",path:["cloudBoundary"]});if(_.cloudResources.length>0)$.addIssue({code:A.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:A.ZodIssueCode.custom,message:"Cloud-backed storage modes require explicit app-owned cloudResources",path:["cloudResources"]});if(_.cloudBoundary==="none"&&_.cloudResources.length>0)$.addIssue({code:A.ZodIssueCode.custom,message:"cloudBoundary none cannot declare cloudResources",path:["cloudResources"]});_.cloudResources.forEach((I,U)=>{if(I.ownerPackage!==_.packageName)$.addIssue({code:A.ZodIssueCode.custom,message:"Cloud resources must be owned by the app package that declares the manifest",path:["cloudResources",U,"ownerPackage"]})})}),j8=A.enum(["package_manifest","lockfile","source_import","runtime_config","packed_artifact","published_metadata","app_cloud_manifest","remote_config","boundary_doc","other"]),bC=A.enum(["low","medium","high","critical"]),N8=A.object({id:A.string().min(1),kind:j8,severity:bC,path:A.string().min(1).optional(),packageName:A.string().min(1).optional(),pattern:A.string().min(1),message:A.string().min(1),evidenceRefs:A.array(T_).default([])}).strict(),qC=A.object({id:A.string().min(1),kind:j8,status:I0,target:A.string().min(1),command:A.string().min(1).optional(),evidenceRefs:A.array(T_).default([]),findings:A.array(N8).default([])}).strict(),kC=J_(y.noCloudEvidencePack).extend({subject:__,packageName:A.string().min(1).optional(),packageVersion:A.string().min(1).optional(),generatedBy:e$.optional(),scanMode:A.enum(["source_tree","packed_artifact","published_metadata","runtime_config","workspace","ci"]),status:I0,verdict:A.enum(["passed","failed","warning","not_run"]),appCloudManifest:E8.optional(),checks:A.array(qC).min(1),findings:A.array(N8).default([]),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{let D=[..._.findings,..._.checks.flatMap((U)=>U.findings)],I=D.filter((U)=>U.severity==="high"||U.severity==="critical");if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:A.ZodIssueCode.custom,message:"Passed no-cloud evidence requires succeeded status",path:["status"]});if(I.length>0)$.addIssue({code:A.ZodIssueCode.custom,message:"Passed no-cloud evidence cannot include high or critical findings",path:["findings"]});if(_.checks.some((U)=>U.status!=="succeeded"))$.addIssue({code:A.ZodIssueCode.custom,message:"Passed no-cloud evidence requires every check to be succeeded",path:["checks"]})}if(_.verdict==="failed"&&D.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Failed no-cloud evidence requires findings",path:["findings"]});if(_.status==="succeeded"&&_.checks.some((U)=>U.status==="failed"))$.addIssue({code:A.ZodIssueCode.custom,message:"Succeeded no-cloud evidence cannot contain failed checks",path:["checks"]});_.checks.forEach((U,E)=>{let j=U.findings.filter((N)=>N.severity==="high"||N.severity==="critical");if(U.status==="succeeded"&&j.length>0)$.addIssue({code:A.ZodIssueCode.custom,message:"Succeeded no-cloud checks cannot contain high or critical findings",path:["checks",E,"findings"]})})}),CC=A.object({checkId:A.string().min(1),status:I0,summary:A.string().min(1).optional(),startedAt:$0,finishedAt:$0,evidenceRefs:A.array(T_).default([])}).strict(),vC=J_(y.proofBundle).extend({subject:__,validationPlanRef:__.optional(),status:I0,verdict:A.enum(["passed","failed","inconclusive","not_run"]).default("inconclusive"),checks:A.array(CC).default([]),verifier:e$.optional(),evidenceRefs:A.array(T_).default([]),residualRisks:A.array(A.string().min(1)).default([]),freshness:A.enum(["fresh","stale","unknown"]).default("unknown")}).strict().superRefine((_,$)=>{if(_.verdict==="passed"){if(_.status!=="succeeded")$.addIssue({code:A.ZodIssueCode.custom,message:"Passed proof bundles must have status succeeded",path:["status"]});if(_.checks.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Passed proof bundles require at least one check result",path:["checks"]});if(_.checks.forEach((I,U)=>{if(I.status!=="succeeded")$.addIssue({code:A.ZodIssueCode.custom,message:"Passed proof bundles require all checks to have status succeeded",path:["checks",U,"status"]})}),!(_.evidenceRefs.length>0||_.checks.some((I)=>I.evidenceRefs.length>0)))$.addIssue({code:A.ZodIssueCode.custom,message:"Passed proof bundles require evidence",path:["evidenceRefs"]});if(!_.verifier)$.addIssue({code:A.ZodIssueCode.custom,message:"Passed proof bundles require a verifier",path:["verifier"]})}if(_.verdict==="not_run"&&_.checks.length>0)$.addIssue({code:A.ZodIssueCode.custom,message:"Not-run proof bundles cannot include check results",path:["checks"]});if(_.verdict==="failed"&&!_.checks.some((D)=>D.status==="failed")&&_.evidenceRefs.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Failed proof bundles require a failed check or evidence",path:["checks"]})}),wC=J_(y.workRun).extend({objective:A.string().min(1),status:I0,actor:e$,traceId:A.string().min(1).optional(),startedAt:$0,finishedAt:$0,constraints:A.array(A.string().min(1)).default([]),resourceRefs:A.array(__).default([]),decisions:A.array(s9).default([]),costEstimates:A.array(H1).default([]),evidenceRefs:A.array(T_).default([]),validationPlanRefs:A.array(__).default([]),proofBundleRefs:A.array(__).default([])}).strict().superRefine((_,$)=>{if(_.startedAt&&_.finishedAt&&Date.parse(_.finishedAt)0||_.proofBundleRefs.length>0;if(_.status==="succeeded"&&!D)$.addIssue({code:A.ZodIssueCode.custom,message:"Succeeded work runs require evidence or a proof bundle",path:["evidenceRefs"]});if((_.status==="failed"||_.status==="blocked")&&!D&&_.decisions.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Failed or blocked work runs require evidence, a proof bundle, or a decision record",path:["evidenceRefs"]})}),rC=Object.freeze({work_run:Object.freeze(["codewith"]),root_request:Object.freeze(["todos"]),pr_group:Object.freeze(["todos"]),leaf_task:Object.freeze(["todos"]),attempt:Object.freeze(["todos"]),writer_generation:Object.freeze(["todos"]),writer_lease:Object.freeze(["repos"]),writer_fence:Object.freeze(["repos"]),provider_profile:Object.freeze(["codewith"]),provider_route:Object.freeze(["codewith"]),admission:Object.freeze(["codewith"]),worker_actor:Object.freeze(["codewith"]),worker:Object.freeze(["codewith"]),runtime:Object.freeze(["codewith"]),repo:Object.freeze(["repos"]),worktree:Object.freeze(["repos"]),branch:Object.freeze(["repos"]),event_stream:Object.freeze(["todos"]),replay_cursor:Object.freeze(["todos"]),handoff:Object.freeze(["todos"]),pull_request:Object.freeze(["todos"]),commit:Object.freeze(["repos"]),review:Object.freeze(["review"]),reviewer:Object.freeze(["review"]),review_run:Object.freeze(["review"]),proof_bundle:Object.freeze(["review"]),repair_cycle:Object.freeze(["todos"]),merge_guard:Object.freeze(["todos"]),merge_operator:Object.freeze(["merge_provider"]),merge_operator_run:Object.freeze(["merge_provider"]),merge_guard_receipt:Object.freeze(["merge_provider"]),merge_outcome:Object.freeze(["merge_provider"]),recovery:Object.freeze(["todos"]),cancellation:Object.freeze(["todos"]),cleanup_eligibility:Object.freeze(["repos"]),cleanup_outcome:Object.freeze(["repos"]),rollback_plan:Object.freeze(["todos"]),rollback_outcome:Object.freeze(["repos"]),terminal_disposition:Object.freeze(["todos"]),openloops_invocation:Object.freeze(["openloops"]),adapter_extension:Object.freeze(["adapter"])}),fC=A.enum(["work_run","root_request","pr_group","leaf_task","attempt","writer_generation","writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","repo","worktree","branch","event_stream","replay_cursor","handoff","pull_request","commit","review","reviewer","review_run","proof_bundle","repair_cycle","merge_guard","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","recovery","cancellation","cleanup_eligibility","cleanup_outcome","rollback_plan","rollback_outcome","terminal_disposition","openloops_invocation","adapter_extension"]),xC=A.enum(["todos","codewith","repos","review","merge_provider","openloops","adapter"]),U0=A.string().regex(/^[a-f0-9]{64}$/),FN=A.string().trim().min(3).max(256),A8=/^[a-f0-9]{32}$/;function uC(_,$,D){return`${_}:${$}:opaque-${D.slice(0,32)}`}function yC(_){return`evidence:opaque-${_.slice(0,32)}`}var O8=FN.refine((_)=>{let D=_.startsWith("task_to_pr_projection:opaque-")?_.slice(29):"";return A8.test(D)},"Projection ids must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),Az=FN.refine((_)=>{let D=_.startsWith("attempt_nonce:opaque-")?_.slice(21):"";return A8.test(D)},"Attempt nonces must use a nonsemantic 128-bit lowercase hexadecimal surrogate"),hC=new Set(["writer_lease","writer_fence","provider_profile","provider_route","admission","worker_actor","worker","runtime","worktree","merge_operator","merge_operator_run","merge_guard_receipt","merge_outcome","openloops_invocation","adapter_extension"]),Oz=A.object({role:fC,authority:xC,id:FN,digest:U0,redaction:A.enum(["none","partial","full"])}).strict().superRefine((_,$)=>{let D=rC[_.role];if(!D.includes(_.authority))$.addIssue({code:A.ZodIssueCode.custom,message:`${_.role} refs must be owned by ${D.join(" or ")}`,path:["authority"]});if(hC.has(_.role)&&_.redaction==="none")$.addIssue({code:A.ZodIssueCode.custom,message:`${_.role} refs must be redacted and cannot carry a raw locator or credential`,path:["redaction"]});let I=uC(_.role,_.authority,_.digest);if(_.id!==I)$.addIssue({code:A.ZodIssueCode.custom,message:"Reference ids must be nonsemantic authority-bound surrogates derived from the canonical role, authority, and owner-record digest",path:["id"]})}),Y$=A.object({id:FN,digest:U0,redaction:A.enum(["partial","full"])}).strict().superRefine((_,$)=>{if(_.id!==yC(_.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Evidence ids must be nonsemantic owner-resolvable surrogates derived from their canonical digest",path:["id"]})});function S8(_,$,D,I){if(_.id===$.id||_.digest===$.digest)D.addIssue({code:A.ZodIssueCode.custom,message:"Stop and lease-revocation facts require distinct evidence identities and digests",path:I})}function H(_){return Oz.refine(($)=>$.role===_,{message:`Reference must use role ${_}`,path:["role"]})}function B_(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id&&_.digest===$.digest&&_.redaction===$.redaction}function Sz(_,$){return _.role===$.role&&_.authority===$.authority&&_.id===$.id}function PD(_,$,D,I,U){if(Sz(_,$))D.addIssue({code:A.ZodIssueCode.custom,message:`${U} requires a fresh canonical role/authority/id`,path:I});if(_.digest===$.digest)D.addIssue({code:A.ZodIssueCode.custom,message:`${U} requires a fresh canonical digest`,path:I})}function YN(_){return`${_.role}\x00${_.authority}\x00${_.id}`}function a_(_,$){return _.algorithm===$.algorithm&&_.value===$.value}var K_=A.object({algorithm:A.enum(["sha1","sha256"]),value:A.string().regex(/^[a-f0-9]+$/)}).strict().superRefine((_,$)=>{let D=_.algorithm==="sha1"?40:64;if(_.value.length!==D)$.addIssue({code:A.ZodIssueCode.custom,message:`${_.algorithm} object ids must contain exactly ${D} lowercase hex characters`,path:["value"]})});function v9(_){if(_.canonicalizationVersion===1){let D=JSON.stringify(["hasna.task_to_pr_projection.binding.v1",_.canonicalizationVersion,_.rootRequestRef.id,_.rootRequestRef.digest,_.prGroupRef.id,_.prGroupRef.digest,_.leafTaskRef.id,_.leafTaskRef.digest,_.repoRef.id,_.repoRef.digest,_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return H9("sha256").update(D,"utf8").digest("hex")}let $=JSON.stringify(["hasna.task_to_pr_projection.binding.v2",_.canonicalizationVersion,...[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repoRef,_.worktreeRef,_.branchRef].flatMap((D)=>[D.role,D.authority,D.id,D.digest]),_.baseHead.algorithm,_.baseHead.value,_.frozenScopeDigest]);return H9("sha256").update($,"utf8").digest("hex")}var cC=A.object({ref:H("attempt"),nonce:Az,admissionRef:H("admission"),admissionWriterGenerationRef:H("writer_generation"),workerActorRef:H("worker_actor"),workerRef:H("worker"),runtimeRef:H("runtime"),writerGenerationRef:H("writer_generation"),writerLeaseRef:H("writer_lease"),writerFenceRef:H("writer_fence"),providerProfileRef:H("provider_profile"),providerRouteRef:H("provider_route")}).strict(),nC=A.object({repoRef:H("repo"),worktreeRef:H("worktree"),branchRef:H("branch"),baseHead:K_,branchHead:K_}).strict(),dC=A.object({streamRef:H("event_stream"),replayCursorRef:H("replay_cursor"),sequence:A.number().int().safe().nonnegative(),prefixDigest:U0}).strict(),mC=A.object({ref:H("handoff"),previousAttemptRef:H("attempt"),nextAttemptRef:H("attempt"),previousWriterGenerationRef:H("writer_generation"),nextWriterGenerationRef:H("writer_generation"),stoppedWorkRunRef:H("work_run"),stopEvidenceRef:Y$,leaseRevocationEvidenceRef:Y$}).strict().superRefine((_,$)=>{PD(_.previousAttemptRef,_.nextAttemptRef,$,["nextAttemptRef"],"Handoff attempt rotation"),PD(_.previousWriterGenerationRef,_.nextWriterGenerationRef,$,["nextWriterGenerationRef"],"Handoff writer-generation rotation"),S8(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),lC=A.object({ref:H("review"),pullRequestRef:H("pull_request"),base:K_,head:K_,reviewerRef:H("reviewer"),reviewRunRef:H("review_run"),proofBundleRef:H("proof_bundle"),verdict:A.enum(["approved","changes_requested","blocked"]),reviewedAt:M_}).strict(),iC=A.object({pullRequestRef:H("pull_request"),remoteBranchRef:H("branch"),expectedBase:K_,providerPullRequestBase:K_,localHead:K_,remoteHead:K_,providerPullRequestHead:K_,equalityProofRef:H("proof_bundle"),ciProofBundleRefs:A.array(H("proof_bundle")).min(1),verifiedAt:M_}).strict().superRefine((_,$)=>{if(!a_(_.expectedBase,_.providerPullRequestBase))$.addIssue({code:A.ZodIssueCode.custom,message:"Expected and provider-observed pull-request bases must be exactly equal",path:["providerPullRequestBase"]});if(!a_(_.localHead,_.remoteHead)||!a_(_.localHead,_.providerPullRequestHead))$.addIssue({code:A.ZodIssueCode.custom,message:"Local, remote, and provider pull-request heads must be exactly equal",path:["providerPullRequestHead"]});let D=_.ciProofBundleRefs.map(YN);if(new Set(D).size!==D.length)$.addIssue({code:A.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical identities",path:["ciProofBundleRefs"]});let I=_.ciProofBundleRefs.map((U)=>U.digest);if(new Set(I).size!==I.length)$.addIssue({code:A.ZodIssueCode.custom,message:"CI proof bundle refs must have unique canonical digests",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((U)=>Sz(U,_.equalityProofRef)))$.addIssue({code:A.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical identities",path:["ciProofBundleRefs"]});if(_.ciProofBundleRefs.some((U)=>U.digest===_.equalityProofRef.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Head-equality and CI proof refs must have distinct canonical digests",path:["ciProofBundleRefs"]})}),tC=A.object({ref:H("repair_cycle"),cycle:A.number().int().min(0).max(2),cap:A.literal(2),exhausted:A.boolean(),latestRepairRef:H("repair_cycle").optional()}).strict().superRefine((_,$)=>{if(_.exhausted!==(_.cycle===_.cap))$.addIssue({code:A.ZodIssueCode.custom,message:"Repair exhaustion must equal the cumulative cycle cap",path:["exhausted"]});if(_.cycle===0&&_.latestRepairRef)$.addIssue({code:A.ZodIssueCode.custom,message:"Cycle zero cannot reference a repair",path:["latestRepairRef"]});if(_.cycle>0&&!_.latestRepairRef)$.addIssue({code:A.ZodIssueCode.custom,message:"Non-zero repair state requires the latest immutable repair ref",path:["latestRepairRef"]});if(_.latestRepairRef&&Sz(_.ref,_.latestRepairRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must be distinct canonical records",path:["latestRepairRef"]});if(_.latestRepairRef&&_.ref.digest===_.latestRepairRef.digest)$.addIssue({code:A.ZodIssueCode.custom,message:"Repair-state and latest-repair refs must have distinct canonical digests",path:["latestRepairRef"]})}),oC=A.object({ref:H("merge_guard"),pullRequestRef:H("pull_request"),expectedBase:K_,expectedHead:K_,reviewRefs:A.array(H("review")).min(1),proofBundleRefs:A.array(H("proof_bundle")).min(1),operatorRef:H("merge_operator"),operatorRunRef:H("merge_operator_run"),providerGuardReceiptRef:H("merge_guard_receipt"),mechanism:A.enum(["compare_and_swap","queue_expected_head"]),decision:A.enum(["eligible","denied","consumed","revoked"]),evaluatedAt:M_}).strict().superRefine((_,$)=>{if(new Set(_.reviewRefs.map((E)=>E.id)).size!==_.reviewRefs.length)$.addIssue({code:A.ZodIssueCode.custom,message:"Merge guard review refs must be unique",path:["reviewRefs"]});if(new Set(_.proofBundleRefs.map(YN)).size!==_.proofBundleRefs.length)$.addIssue({code:A.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical identities",path:["proofBundleRefs"]});if(new Set(_.proofBundleRefs.map((E)=>E.digest)).size!==_.proofBundleRefs.length)$.addIssue({code:A.ZodIssueCode.custom,message:"Merge guard proof refs must have unique canonical digests",path:["proofBundleRefs"]})}),pC=A.object({ref:H("merge_outcome"),guardRef:H("merge_guard"),pullRequestRef:H("pull_request"),expectedBase:K_,observedBase:K_,expectedHead:K_,observedHead:K_,status:A.enum(["merged","closed_unmerged","refused","head_drift","base_drift"]),mergeCommitRef:H("commit").optional(),finishedAt:M_,evidenceRefs:A.array(Y$).min(1)}).strict().superRefine((_,$)=>{let D=a_(_.expectedBase,_.observedBase),I=a_(_.expectedHead,_.observedHead);if(_.status==="merged"){if(!D||!I)$.addIssue({code:A.ZodIssueCode.custom,message:"Merged outcomes require observed base and head to equal the guarded values",path:[!D?"observedBase":"observedHead"]});if(!_.mergeCommitRef)$.addIssue({code:A.ZodIssueCode.custom,message:"Merged outcomes require an immutable merge commit ref",path:["mergeCommitRef"]})}else if(_.mergeCommitRef)$.addIssue({code:A.ZodIssueCode.custom,message:"Unmerged outcomes cannot claim a merge commit",path:["mergeCommitRef"]});if(_.status==="head_drift"&&I)$.addIssue({code:A.ZodIssueCode.custom,message:"Head-drift outcomes require distinct expected and observed heads",path:["observedHead"]});if(_.status==="head_drift"&&!D)$.addIssue({code:A.ZodIssueCode.custom,message:"Head-drift outcomes cannot also carry an unclassified base drift",path:["observedBase"]});if(_.status==="base_drift"&&D)$.addIssue({code:A.ZodIssueCode.custom,message:"Base-drift outcomes require distinct expected and observed bases",path:["observedBase"]});if(_.status==="base_drift"&&!I)$.addIssue({code:A.ZodIssueCode.custom,message:"Base-drift outcomes cannot also carry an unclassified head drift",path:["observedHead"]});if(!I&&_.status!=="head_drift")$.addIssue({code:A.ZodIssueCode.custom,message:"Only a head_drift outcome may record an observed head that differs from the expected head",path:["observedHead"]});if(!D&&_.status!=="base_drift")$.addIssue({code:A.ZodIssueCode.custom,message:"Only a base_drift outcome may record an observed base that differs from the expected base",path:["observedBase"]})}),eC=A.object({guard:oC,outcome:pC.optional()}).strict(),aC=A.object({ref:H("recovery"),priorAttemptRef:H("attempt"),priorWriterGenerationRef:H("writer_generation"),priorWorkRunRef:H("work_run"),successorAttemptNonce:Az,successorWriterGenerationRef:H("writer_generation"),preservedStateRefs:A.array(Oz).min(1),stopEvidenceRef:Y$,leaseRevocationEvidenceRef:Y$}).strict().superRefine((_,$)=>{PD(_.priorWriterGenerationRef,_.successorWriterGenerationRef,$,["successorWriterGenerationRef"],"Recovery writer-generation rotation"),S8(_.stopEvidenceRef,_.leaseRevocationEvidenceRef,$,["leaseRevocationEvidenceRef"])}),sC=A.object({ref:H("cancellation"),cancelledAttemptRef:H("attempt"),preservedStateRefs:A.array(Oz).min(1),evidenceRefs:A.array(Y$).min(1)}).strict(),_v=A.object({ref:H("cleanup_eligibility"),status:A.enum(["not_ready","preserved","blocked","eligible"]),targetWorktreeRef:H("worktree"),eventCursorRef:H("replay_cursor"),terminalDispositionRef:H("terminal_disposition"),writerLeaseRef:H("writer_lease"),leaseRevocationEvidenceRef:Y$,consumedEventEvidenceRef:Y$,evaluatedAt:M_,evidenceRefs:A.array(Y$).min(1)}).strict().superRefine((_,$)=>{if(_.leaseRevocationEvidenceRef.id===_.consumedEventEvidenceRef.id||_.leaseRevocationEvidenceRef.digest===_.consumedEventEvidenceRef.digest)$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup lease-revocation and consumed-event facts require distinct evidence identities and digests",path:["consumedEventEvidenceRef"]})}),$v=A.object({ref:H("cleanup_outcome"),eligibilityRef:H("cleanup_eligibility"),targetWorktreeRef:H("worktree"),status:A.enum(["preserved","deleted","failed","skipped"]),finishedAt:M_,evidenceRefs:A.array(Y$).min(1)}).strict(),Dv=A.object({eligibility:_v,outcome:$v.optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.eligibilityRef,_.eligibility.ref))$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup outcomes must bind the exact eligibility decision",path:["outcome","eligibilityRef"]});if(_.outcome&&!B_(_.outcome.targetWorktreeRef,_.eligibility.targetWorktreeRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup eligibility and outcome must bind the same target worktree",path:["outcome","targetWorktreeRef"]});if(_.outcome?.status==="deleted"&&_.eligibility.status!=="eligible")$.addIssue({code:A.ZodIssueCode.custom,message:"Deletion requires an eligible cleanup decision",path:["outcome","status"]})}),Uv=A.object({plan:A.object({ref:H("rollback_plan"),targetRef:A.union([H("commit"),H("branch")]),createdAt:M_}).strict(),outcome:A.object({ref:H("rollback_outcome"),planRef:H("rollback_plan"),targetRef:A.union([H("commit"),H("branch")]),status:A.enum(["not_run","succeeded","failed","cancelled"]),finishedAt:M_,evidenceRefs:A.array(Y$).min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.outcome&&!B_(_.outcome.planRef,_.plan.ref))$.addIssue({code:A.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback plan",path:["outcome","planRef"]});if(_.outcome&&!B_(_.outcome.targetRef,_.plan.targetRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Rollback outcomes must bind the exact rollback target",path:["outcome","targetRef"]});if(_.outcome&&Date.parse(_.outcome.finishedAt)({category:"ci_proof",ref:$,base:_.exactHead.expectedBase,head:_.exactHead.localHead}))]:[],..._.reviews.flatMap(($)=>[{category:"review_proof",ref:$.proofBundleRef,base:$.base,head:$.head},{category:"review_record",ref:$.ref,base:$.base,head:$.head},{category:"review_run",ref:$.reviewRunRef,base:$.base,head:$.head}]),..._.merge?[{category:"merge_guard",ref:_.merge.guard.ref},{category:"provider_guard_receipt",ref:_.merge.guard.providerGuardReceiptRef,base:_.merge.guard.expectedBase,head:_.merge.guard.expectedHead}]:[],..._.cleanup?[{category:"cleanup_eligibility",ref:_.cleanup.eligibility.ref}]:[],..._.rollback?[{category:"rollback_plan",ref:_.rollback.plan.ref}]:[],..._.terminalDispositionRef?[{category:"terminal_disposition",ref:_.terminalDispositionRef}]:[]]}function jv(_,$){if(_.category!==$.category)return!1;if(_.category==="projection_id"&&$.category==="projection_id")return _.projectionId===$.projectionId;if(_.category==="attempt_nonce"&&$.category==="attempt_nonce")return _.nonce===$.nonce;if(_.category==="replay_prefix"&&$.category==="replay_prefix")return _.sequence===$.sequence&&_.prefixDigest===$.prefixDigest;if(!("ref"in _)||!("ref"in $))return!1;return B_(_.ref,$.ref)&&(("head"in _)&&("head"in $)&&("base"in _)&&("base"in $)&&a_(_.base,$.base)&&a_(_.head,$.head)||!("head"in _)&&!("head"in $)&&!("base"in _)&&!("base"in $))}var Nv="hasna.task_to_pr_adapter_extension.",Av=A.object({mode:A.enum(["local","cloud"]),schema:Uz,ref:H("adapter_extension"),digest:U0}).strict().superRefine((_,$)=>{if(!_.schema.startsWith(Nv))$.addIssue({code:A.ZodIssueCode.custom,message:"Adapter extension schema ids must use the permanently reserved task-to-PR adapter-extension namespace",path:["schema"]})}),Ov=A.enum(["admitted","running","handed_off","reviewing","repairing","merge_ready","merged","closed_unmerged","failed","blocked","cancelled","recovering","cleanup_complete","rolled_back"]),w9=new Set(["admitted","running","handed_off"]),r9=new Set(["merged","closed_unmerged","failed","blocked","cancelled","cleanup_complete","rolled_back"]),Sv={admitted:new Set(["absent","denied:none","revoked:none"]),running:new Set(["absent","denied:none","revoked:none"]),handed_off:new Set(["absent","denied:none","revoked:none"]),reviewing:new Set(["absent","denied:none","revoked:none"]),repairing:new Set(["absent","denied:none","revoked:none"]),merge_ready:new Set(["eligible:none"]),merged:new Set(["consumed:merged"]),closed_unmerged:new Set(["consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),failed:new Set(["absent","revoked:none"]),blocked:new Set(["absent","revoked:none"]),cancelled:new Set(["absent","revoked:none"]),recovering:new Set(["absent","denied:none","revoked:none"]),cleanup_complete:new Set(["absent","revoked:none","consumed:merged","consumed:closed_unmerged","consumed:refused","consumed:head_drift","consumed:base_drift"]),rolled_back:new Set(["consumed:merged"])},Lv=A.object({schema:A.literal(y.taskToPrProjection),id:O8,createdAt:M_,canonicalizationVersion:A.union([A.literal(1),A.literal(2)]),identityDigest:U0,frozenScopeDigest:U0,state:Ov,workRunRef:H("work_run"),rootRequestRef:H("root_request"),prGroupRef:H("pr_group"),leafTaskRef:H("leaf_task"),attempt:cC,repository:nC,events:dC,openLoopsInvocationRef:H("openloops_invocation").optional(),pullRequestRef:H("pull_request").optional(),exactHead:iC.optional(),handoff:mC.optional(),reviews:A.array(lC).default([]),repair:tC,merge:eC.optional(),recovery:aC.optional(),cancellation:sC.optional(),cleanup:Dv.optional(),rollback:Uv.optional(),terminalDispositionRef:H("terminal_disposition").optional(),provenanceLedger:A.array(Iv),adapterExtensions:A.array(Av).default([]),evidenceRefs:A.array(Y$).default([])}).strict().superRefine((_,$)=>{let D=_.canonicalizationVersion===1?v9({canonicalizationVersion:1,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest}):v9({canonicalizationVersion:2,rootRequestRef:_.rootRequestRef,prGroupRef:_.prGroupRef,leafTaskRef:_.leafTaskRef,repoRef:_.repository.repoRef,worktreeRef:_.repository.worktreeRef,branchRef:_.repository.branchRef,baseHead:_.repository.baseHead,frozenScopeDigest:_.frozenScopeDigest});if(_.identityDigest!==D)$.addIssue({code:A.ZodIssueCode.custom,message:"identityDigest must equal the selected v1 compatibility or v2 branch/worktree-bound canonical identity digest",path:["identityDigest"]});let I=new Set,U=new Set,E=new Set,j=new Set,N=new Set,O=new Set;for(let[Q,F]of _.provenanceLedger.entries()){if("ref"in F){if(I.has(F.ref.id))$.addIssue({code:A.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical owner id across categories or generations",path:["provenanceLedger",Q,"ref","id"]});if(I.add(F.ref.id),U.has(F.ref.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Provenance entries cannot reuse a canonical digest across categories or generations",path:["provenanceLedger",Q,"ref","digest"]});U.add(F.ref.digest);continue}if(F.category==="projection_id"){if(E.has(F.projectionId))$.addIssue({code:A.ZodIssueCode.custom,message:"Projection identity provenance tombstones must be globally unique",path:["provenanceLedger",Q,"projectionId"]});E.add(F.projectionId);continue}if(F.category==="attempt_nonce"){if(j.has(F.nonce))$.addIssue({code:A.ZodIssueCode.custom,message:"Attempt nonce provenance tombstones must be globally unique",path:["provenanceLedger",Q,"nonce"]});j.add(F.nonce);continue}if(N.has(F.prefixDigest))$.addIssue({code:A.ZodIssueCode.custom,message:"Replay prefix provenance tombstones must be globally unique",path:["provenanceLedger",Q,"prefixDigest"]});if(N.add(F.prefixDigest),O.has(F.sequence))$.addIssue({code:A.ZodIssueCode.custom,message:"Replay prefix provenance entries must bind globally unique replay sequences",path:["provenanceLedger",Q,"sequence"]});O.add(F.sequence)}for(let Q of Ev(_))if(!_.provenanceLedger.some((F)=>jv(F,Q)))$.addIssue({code:A.ZodIssueCode.custom,message:`The active ${Q.category} identity must be represented exactly in the monotonic provenance ledger`,path:["provenanceLedger"]});let S=[_.rootRequestRef,_.prGroupRef,_.leafTaskRef,_.repository.repoRef,_.repository.worktreeRef,_.repository.branchRef,_.events.streamRef,..._.pullRequestRef?[_.pullRequestRef]:[]],L=(Q,F,B,b)=>{let f=new Set(F.map((U_)=>U_.role)),l=new Set;for(let[U_,j_]of Q.entries()){if(!f.has(j_.role))$.addIssue({code:A.ZodIssueCode.custom,message:`${b} cannot preserve an unrecognized ${j_.role} role`,path:[...B,U_]});if(l.has(j_.role))$.addIssue({code:A.ZodIssueCode.custom,message:`${b} must preserve exactly one canonical ref per role`,path:[...B,U_]});l.add(j_.role)}if(Q.length!==F.length)$.addIssue({code:A.ZodIssueCode.custom,message:`${b} preservation refs must exactly equal the required canonical role set`,path:B});for(let U_ of F)if(!Q.some((j_)=>B_(j_,U_)))$.addIssue({code:A.ZodIssueCode.custom,message:`${b} must preserve ${U_.role}`,path:B})};if(_.handoff&&!B_(_.handoff.nextWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Handoff next generation must be the current attempt writer generation",path:["handoff","nextWriterGenerationRef"]});if(_.handoff&&!B_(_.handoff.nextAttemptRef,_.attempt.ref))$.addIssue({code:A.ZodIssueCode.custom,message:"Handoff next attempt must be the current attempt",path:["handoff","nextAttemptRef"]});if(_.handoff)PD(_.handoff.stoppedWorkRunRef,_.workRunRef,$,["handoff","stoppedWorkRunRef"],"Handoff WorkRun rotation");if(_.recovery){if(_.recovery.successorAttemptNonce!==_.attempt.nonce)$.addIssue({code:A.ZodIssueCode.custom,message:"Recovery successor nonce must equal the current attempt nonce",path:["recovery","successorAttemptNonce"]});if(!B_(_.recovery.successorWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Recovery successor generation must equal the current writer generation",path:["recovery","successorWriterGenerationRef"]});PD(_.recovery.priorAttemptRef,_.attempt.ref,$,["recovery","priorAttemptRef"],"Recovery attempt rotation"),PD(_.recovery.priorWorkRunRef,_.workRunRef,$,["recovery","priorWorkRunRef"],"Recovery WorkRun rotation"),L(_.recovery.preservedStateRefs,[_.recovery.priorWorkRunRef,...S],["recovery","preservedStateRefs"],"Recovery")}if(_.cancellation&&!B_(_.cancellation.cancelledAttemptRef,_.attempt.ref))$.addIssue({code:A.ZodIssueCode.custom,message:"Cancellation must bind the current attempt",path:["cancellation","cancelledAttemptRef"]});if(_.cancellation)L(_.cancellation.preservedStateRefs,[_.workRunRef,_.attempt.ref,...S],["cancellation","preservedStateRefs"],"Cancellation");if(_.cancellation&&_.recovery)$.addIssue({code:A.ZodIssueCode.custom,message:"A projection cannot be both the cancellation and recovery snapshot",path:["recovery"]});if(_.handoff&&_.recovery)$.addIssue({code:A.ZodIssueCode.custom,message:"A projection cannot be both the handoff and recovery snapshot",path:["recovery"]});if(_.cleanup&&!B_(_.cleanup.eligibility.eventCursorRef,_.events.replayCursorRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup eligibility must bind the current canonical replay cursor",path:["cleanup","eligibility","eventCursorRef"]});if(_.cleanup&&(!_.terminalDispositionRef||!B_(_.cleanup.eligibility.terminalDispositionRef,_.terminalDispositionRef)))$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact durable terminal owner fact",path:["cleanup","eligibility","terminalDispositionRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.writerLeaseRef,_.attempt.writerLeaseRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup eligibility must bind the exact writer lease being revoked",path:["cleanup","eligibility","writerLeaseRef"]});if(_.cleanup&&!B_(_.cleanup.eligibility.targetWorktreeRef,_.repository.worktreeRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup eligibility must bind the canonical worktree",path:["cleanup","eligibility","targetWorktreeRef"]});if(_.pullRequestRef){if(_.exactHead&&!B_(_.exactHead.pullRequestRef,_.pullRequestRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Exact-head proof must bind the canonical pull request ref",path:["exactHead","pullRequestRef"]});for(let[Q,F]of _.reviews.entries())if(!B_(F.pullRequestRef,_.pullRequestRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Every review must bind the canonical pull request ref",path:["reviews",Q,"pullRequestRef"]});if(_.merge&&!B_(_.merge.guard.pullRequestRef,_.pullRequestRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Merge guard must bind the canonical pull request ref",path:["merge","guard","pullRequestRef"]});if(_.merge?.outcome&&!B_(_.merge.outcome.pullRequestRef,_.pullRequestRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Merge outcome must bind the canonical pull request ref",path:["merge","outcome","pullRequestRef"]})}else if(_.exactHead||_.reviews.length>0||_.merge)$.addIssue({code:A.ZodIssueCode.custom,message:"Review and merge state require a canonical pull request ref",path:["pullRequestRef"]});if(_.exactHead&&!a_(_.exactHead.localHead,_.repository.branchHead))$.addIssue({code:A.ZodIssueCode.custom,message:"Exact local head must equal the canonical branch head",path:["exactHead","localHead"]});if(_.exactHead&&!a_(_.exactHead.expectedBase,_.repository.baseHead))$.addIssue({code:A.ZodIssueCode.custom,message:"Exact-head expected base must equal the canonical repository base",path:["exactHead","expectedBase"]});if(_.exactHead&&!B_(_.exactHead.remoteBranchRef,_.repository.branchRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Exact-head remote branch ref must equal the canonical repository branch ref",path:["exactHead","remoteBranchRef"]});if(_.exactHead&&Date.parse(_.exactHead.verifiedAt)0&&!_.exactHead)$.addIssue({code:A.ZodIssueCode.custom,message:"Reviews require local/remote/provider exact-head proof",path:["exactHead"]});if(_.exactHead){let Q=[{ref:_.exactHead.equalityProofRef,path:["exactHead","equalityProofRef"]},..._.exactHead.ciProofBundleRefs.map((b,f)=>({ref:b,path:["exactHead","ciProofBundleRefs",f]})),..._.reviews.map((b,f)=>({ref:b.proofBundleRef,path:["reviews",f,"proofBundleRef"]}))],F=new Set,B=new Set;for(let b of Q){let f=YN(b.ref);if(F.has(f))$.addIssue({code:A.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical identities",path:b.path});if(F.add(f),B.has(b.ref.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Exact-head equality, CI, and review proof obligations require globally unique canonical digests",path:b.path});B.add(b.ref.digest)}}let W=new Set,g=new Set,z=new Set,G=new Set,J=new Set,P=new Set,X=new Set,R=new Set;for(let[Q,F]of _.reviews.entries()){if(!a_(F.base,_.repository.baseHead))$.addIssue({code:A.ZodIssueCode.custom,message:"Review base must equal the exact canonical pull-request base",path:["reviews",Q,"base"]});if(!a_(F.head,_.repository.branchHead))$.addIssue({code:A.ZodIssueCode.custom,message:"Review head must equal the exact canonical branch head",path:["reviews",Q,"head"]});for(let[b,f,l]of[[F.ref.id,W,"ref"],[F.reviewerRef.id,z,"reviewerRef"],[F.reviewRunRef.id,J,"reviewRunRef"]]){if(f.has(b))$.addIssue({code:A.ZodIssueCode.custom,message:"Review, reviewer, and review-run refs must each be unique",path:["reviews",Q,l]});f.add(b)}if(g.has(F.ref.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Review refs must resolve to distinct canonical record digests",path:["reviews",Q,"ref"]});if(g.add(F.ref.digest),G.has(F.reviewerRef.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Reviewer refs must resolve to distinct canonical actor digests",path:["reviews",Q,"reviewerRef"]});if(G.add(F.reviewerRef.digest),P.has(F.reviewRunRef.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Review-run refs must resolve to distinct canonical run digests",path:["reviews",Q,"reviewRunRef"]});P.add(F.reviewRunRef.digest);let B=YN(F.proofBundleRef);if(X.has(B))$.addIssue({code:A.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical identities",path:["reviews",Q,"proofBundleRef"]});if(X.add(B),R.has(F.proofBundleRef.digest))$.addIssue({code:A.ZodIssueCode.custom,message:"Review proof bundles must have unique canonical digests",path:["reviews",Q,"proofBundleRef"]});if(R.add(F.proofBundleRef.digest),F.reviewerRef.digest===_.attempt.workerRef.digest)$.addIssue({code:A.ZodIssueCode.custom,message:"Worker and reviewer identities must resolve to distinct canonical digests",path:["reviews",Q,"reviewerRef"]});if(F.reviewRunRef.digest===_.attempt.runtimeRef.digest)$.addIssue({code:A.ZodIssueCode.custom,message:"Worker runtime and review run must resolve to distinct canonical digests",path:["reviews",Q,"reviewRunRef"]});if(_.exactHead&&Date.parse(F.reviewedAt)Date.parse(_.merge.guard.evaluatedAt)Q.verdict!=="approved"))$.addIssue({code:A.ZodIssueCode.custom,message:"Eligible merge guards require at least one review and all reviews approved",path:["merge","guard","decision"]});if(_.merge.guard.reviewRefs.length!==_.reviews.length||_.merge.guard.reviewRefs.some((Q)=>!_.reviews.some((F)=>B_(Q,F.ref))))$.addIssue({code:A.ZodIssueCode.custom,message:"Eligible merge guard review refs must exactly equal the projected approved review refs as a canonical set",path:["merge","guard","reviewRefs"]});for(let Q of _.reviews)if(!_.merge.guard.proofBundleRefs.some((F)=>B_(F,Q.proofBundleRef)))$.addIssue({code:A.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact review proof bundle",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&!_.merge.guard.proofBundleRefs.some((Q)=>B_(Q,_.exactHead.equalityProofRef)))$.addIssue({code:A.ZodIssueCode.custom,message:"Eligible merge guards must bind the exact-head equality proof",path:["merge","guard","proofBundleRefs"]});if(_.exactHead&&_.exactHead.ciProofBundleRefs.some((Q)=>!_.merge.guard.proofBundleRefs.some((F)=>B_(F,Q))))$.addIssue({code:A.ZodIssueCode.custom,message:"Eligible merge guards must bind every exact-head CI proof",path:["merge","guard","proofBundleRefs"]})}}if(_.merge?.outcome){if(!B_(_.merge.outcome.guardRef,_.merge.guard.ref))$.addIssue({code:A.ZodIssueCode.custom,message:"Merge outcome must bind the exact immutable merge guard",path:["merge","outcome","guardRef"]});if(!a_(_.merge.outcome.expectedHead,_.merge.guard.expectedHead))$.addIssue({code:A.ZodIssueCode.custom,message:"Merge outcome expected head must equal the guarded expected head",path:["merge","outcome","expectedHead"]});if(!a_(_.merge.outcome.expectedBase,_.merge.guard.expectedBase))$.addIssue({code:A.ZodIssueCode.custom,message:"Merge outcome expected base must equal the guarded expected base",path:["merge","outcome","expectedBase"]});if(_.merge.guard.decision!=="consumed")$.addIssue({code:A.ZodIssueCode.custom,message:"Every merge outcome requires an explicitly consumed merge guard",path:["merge","guard","decision"]});if(Date.parse(_.merge.outcome.finishedAt)0)$.addIssue({code:A.ZodIssueCode.custom,message:`${_.state} projections cannot carry review bindings before review authority is active`,path:["reviews"]});if((w9.has(_.state)||_.state==="recovering")&&(_.merge?.guard.reviewRefs.length??0)>0)$.addIssue({code:A.ZodIssueCode.custom,message:`${_.state} projections cannot hide review bindings in a merge guard before review authority is active`,path:["merge","guard","reviewRefs"]});let T=_.merge?`${_.merge.guard.decision}:${_.merge.outcome?.status??"none"}`:"absent";if(!Sv[_.state].has(T))$.addIssue({code:A.ZodIssueCode.custom,message:`State ${_.state} is incompatible with merge authority ${T}`,path:["merge"]});if(r9.has(_.state)&&!_.terminalDispositionRef)$.addIssue({code:A.ZodIssueCode.custom,message:`${_.state} projections require a durable Todos terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(!r9.has(_.state)&&_.terminalDispositionRef)$.addIssue({code:A.ZodIssueCode.custom,message:`${_.state} projections cannot carry a terminal-disposition owner ref`,path:["terminalDispositionRef"]});if(_.state==="reviewing"&&_.reviews.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Reviewing projections require review refs",path:["reviews"]});if(_.state==="cancelled"&&!_.cancellation)$.addIssue({code:A.ZodIssueCode.custom,message:"Cancelled projections require preservation state",path:["cancellation"]});if(_.cancellation&&_.merge?.outcome)$.addIssue({code:A.ZodIssueCode.custom,message:"Cancellation cannot coexist with a terminal merge outcome",path:["cancellation"]});if(_.state==="recovering"&&!_.recovery)$.addIssue({code:A.ZodIssueCode.custom,message:"Recovering projections require recovery state",path:["recovery"]});if(_.state==="repairing"&&_.repair.cycle===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Repairing projections require a non-zero repair cycle",path:["repair","cycle"]});if(_.merge&&(_.merge.guard.decision==="eligible"||_.merge.guard.decision==="consumed")&&!B_(_.attempt.admissionWriterGenerationRef,_.attempt.writerGenerationRef))$.addIssue({code:A.ZodIssueCode.custom,message:"Merge eligibility requires admission from the current writer generation",path:["attempt","admissionWriterGenerationRef"]});if(_.state==="merge_ready"&&_.merge?.guard.decision!=="eligible")$.addIssue({code:A.ZodIssueCode.custom,message:"Merge-ready projections require an eligible guard",path:["merge"]});if(_.state==="merged"&&_.merge?.outcome?.status!=="merged")$.addIssue({code:A.ZodIssueCode.custom,message:"Merged projections require a merged immutable outcome",path:["merge"]});if(_.state==="closed_unmerged"&&!_.merge?.outcome?.status.match(/^(closed_unmerged|refused|head_drift|base_drift)$/))$.addIssue({code:A.ZodIssueCode.custom,message:"Closed-unmerged projections require a non-merged terminal outcome",path:["merge"]});if(_.state==="cleanup_complete"&&(!_.cleanup?.outcome||!["deleted","preserved","skipped"].includes(_.cleanup.outcome.status)))$.addIssue({code:A.ZodIssueCode.custom,message:"Cleanup-complete projections require an immutable cleanup outcome",path:["cleanup"]});if(_.state==="rolled_back"&&_.rollback?.outcome?.status!=="succeeded")$.addIssue({code:A.ZodIssueCode.custom,message:"Rolled-back projections require a successful rollback outcome",path:["rollback"]});if((_.state==="failed"||_.state==="blocked")&&_.evidenceRefs.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Failed and blocked projections require redacted evidence refs",path:["evidenceRefs"]});if(["admitted","running","handed_off","reviewing","repairing","merge_ready","recovering"].includes(_.state)&&(_.merge?.outcome||_.cancellation||_.cleanup?.outcome||_.rollback?.outcome))$.addIssue({code:A.ZodIssueCode.custom,message:"Non-terminal projections cannot carry terminal owner outcomes",path:["state"]});let Y=new Set;for(let[Q,F]of _.adapterExtensions.entries()){let B=`${F.mode}:${F.schema}`;if(Y.has(B))$.addIssue({code:A.ZodIssueCode.custom,message:"Adapter extensions must be unique per local/cloud mode and schema",path:["adapterExtensions",Q]});Y.add(B)}});var Wv=A.object({id:A.string().min(1),at:M_,kind:A.enum(["message","tool_call","command","file_change","error","test","decision","verification","status","other"]),summary:A.string().min(1),resourceRefs:A.array(__).default([]),evidenceRefs:A.array(T_).default([]),costEstimate:H1.optional()}).strict(),Jv=J_(y.agentTrajectory).extend({actor:e$,workRunRef:__.optional(),events:A.array(Wv).default([]),outcome:A.enum(["succeeded","failed","cancelled","blocked","unknown"]).default("unknown"),proofBundleRef:__.optional()}).strict(),Pv="v1",zv=A.enum(["library","cli-with-store","service","saas"]),gv=["user-hosted","hasna-saas"],Xv=A.enum(gv),Gv=["api","sdk","mcp","cli"],L8=A.enum(Gv),Rv=A.enum(["supported","deferred","unsupported"]),Yv=A.enum(["none","local-only","api-key","session","service-token","custom"]),eP=A.object({method:A.enum(["GET","POST","PUT","PATCH","DELETE"]),path:A.string().regex(/^\/[A-Za-z0-9_./:*-]*$/,"Endpoint paths must be absolute HTTP paths"),public:A.boolean().default(!1),description:A.string().min(1).optional()}).strict(),Qv=A.object({id:A.string().min(1),kind:A.enum(["auth","storage","secret-ref","migration","health","readiness","redaction","smoke","operator","other"]),required:A.boolean().default(!0),command:A.string().min(1).optional(),evidenceRef:T_.optional(),status:A.enum(["pending","passed","failed","blocked","deferred"]).default("pending"),summary:A.string().min(1).optional()}).strict().superRefine((_,$)=>{if((_.status==="passed"||_.status==="failed"||_.status==="blocked")&&!_.command&&!_.evidenceRef&&!_.summary)$.addIssue({code:A.ZodIssueCode.custom,message:"Terminal readiness gates require command, evidenceRef, or summary",path:["status"]})}),Kv=A.object({name:A.string().min(1),kind:L8.optional(),status:Rv,bin:A.string().min(1).optional(),mcpBin:A.string().min(1).optional(),authMode:Yv,health:eP.optional(),readiness:eP.optional(),version:eP.optional(),apiBasePath:A.string().regex(/^\/v[0-9]+$/,"Stable API base path must be /vN").optional(),openApiPath:A.string().regex(/^\/[A-Za-z0-9_./:-]*$/).optional(),exportSubpath:A.string().regex(/^\.(?:\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*)?$/,"SDK export subpaths must be package export keys such as . or ./sdk").optional(),generatedFrom:A.string().regex(/^\/[A-Za-z0-9_./:-]*$/,"SDK generatedFrom must reference an absolute OpenAPI path").optional(),clientClassName:A.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).optional(),deferReason:A.string().min(1).optional(),readinessGates:A.array(Qv).default([])}).strict().superRefine((_,$)=>{if(_.status==="supported"){if(!_.kind||_.kind==="api"){if(!_.bin)$.addIssue({code:A.ZodIssueCode.custom,message:"Supported API surfaces require a serve bin",path:["bin"]});if(!_.health)$.addIssue({code:A.ZodIssueCode.custom,message:"Supported API surfaces require a health endpoint",path:["health"]});if(!_.readiness)$.addIssue({code:A.ZodIssueCode.custom,message:"Supported API surfaces require a readiness endpoint",path:["readiness"]});if(!_.version)$.addIssue({code:A.ZodIssueCode.custom,message:"Supported API surfaces require a version endpoint",path:["version"]})}if(_.kind==="cli"&&!_.bin)$.addIssue({code:A.ZodIssueCode.custom,message:"Supported CLI surfaces require a bin",path:["bin"]});if(_.kind==="mcp"&&!_.mcpBin)$.addIssue({code:A.ZodIssueCode.custom,message:"Supported MCP surfaces require an mcpBin",path:["mcpBin"]});if(_.kind==="sdk"&&!_.exportSubpath)$.addIssue({code:A.ZodIssueCode.custom,message:"Supported SDK surfaces require an exportSubpath",path:["exportSubpath"]})}if((_.status==="deferred"||_.status==="unsupported")&&!_.deferReason)$.addIssue({code:A.ZodIssueCode.custom,message:"Deferred or unsupported service surfaces require a deferReason",path:["deferReason"]});if(_.health&&_.health.path!=="/health")$.addIssue({code:A.ZodIssueCode.custom,message:"Health endpoint must be /health",path:["health","path"]});if(_.health&&_.health.method!=="GET")$.addIssue({code:A.ZodIssueCode.custom,message:"Health endpoint must use GET",path:["health","method"]});if(_.readiness&&_.readiness.path!=="/ready")$.addIssue({code:A.ZodIssueCode.custom,message:"Readiness endpoint must be /ready",path:["readiness","path"]});if(_.readiness&&_.readiness.method!=="GET")$.addIssue({code:A.ZodIssueCode.custom,message:"Readiness endpoint must use GET",path:["readiness","method"]});if(_.version&&_.version.path!=="/version")$.addIssue({code:A.ZodIssueCode.custom,message:"Version endpoint must be /version",path:["version","path"]});if(_.version&&_.version.method!=="GET")$.addIssue({code:A.ZodIssueCode.custom,message:"Version endpoint must use GET",path:["version","method"]})}),Tv=["sqlite","postgres"],W8=A.enum(Tv),J8=["sqlite","postgres"],Fv=A.enum(J8),Dz=["postgres"],Vv=A.object({kind:L8,reason:A.string().trim().min(1)}).strict(),Lz=500,Wz=200,QN=(_)=>A.string().trim().min(1).max(_).regex(/^[^\u0000-\u001f\u007f]+$/,"Waiver text must not contain control characters"),Bv=["domain","host","ip","email"],Mv=A.object({kind:A.enum(Bv),reason:QN(Lz),reviewedBy:QN(Wz),expiresAt:M_}).strict(),Zv=A.object({engine:A.enum(Dz),reason:QN(Lz),reviewedBy:QN(Wz).optional(),expiresAt:M_.optional()}).strict();function Hv(_){if(_.class!=="cli-with-store")return`storage waivers are not permitted for class ${_.class}`;if(_.bins.includes(`${_.name}-serve`))return`storage waivers are not permitted for a service-capable cli-with-store repo shipping ${_.name}-serve`;if(_.storageMode==="postgres")return"storage waivers are not permitted while storage.mode is postgres, which reads and writes PostgreSQL directly";if(_.hosting.includes("hasna-saas"))return"storage waivers are not permitted for a repo declaring the hasna-saas product story";return null}var bv=A.object({conformance:A.object({waivedSurfaces:A.array(Vv).default([]),waiverProfile:A.literal("non-node-monorepo").optional(),waivedStorageEngines:A.array(Zv).default([]),waivedAssetInventories:A.array(Mv).default([])}).catchall(A.unknown()).optional(),release:A.object({artifactScan:A.object({script:A.string().trim().min(1)}).strict().optional()}).catchall(A.unknown()).optional()}).catchall(A.unknown()),qv=A.string().regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"App names must be lowercase dashed identifiers"),kv=["","-cli","-mcp","-serve","-worker","-runner","-daemon","-migrate","-doctor"];function Cv(_){return kv.map(($)=>`${_}${$}`)}function f9(_){return`hasna/oss/${_}/database-url`}var vv=A.object({mode:W8,engines:A.array(Fv).min(1).optional(),envPrefix:A.string().regex(/^HASNA_[A-Z][A-Z0-9]*_$/).optional(),aliasEnvPrefix:A.string().regex(/^[A-Z][A-Z0-9]*_$/).optional(),databaseUrlSecretRef:A.string().regex(/^hasna\/oss\/[a-z0-9-]+\/database-url$/).optional(),sqlitePath:A.string().min(1).endsWith(".db","storage.sqlitePath must end in .db").optional(),pgTestGate:A.object({envVar:A.string().regex(/^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$/),command:A.string().trim().min(1)}).strict().optional()}).strict().superRefine((_,$)=>{if(_.engines&&new Set(_.engines).size!==_.engines.length)$.addIssue({code:A.ZodIssueCode.custom,message:"storage.engines must not contain duplicates",path:["engines"]});if(_.engines?.includes("postgres")&&!_.envPrefix)$.addIssue({code:A.ZodIssueCode.custom,message:"storage.engines containing postgres requires envPrefix for the HASNA__DATABASE_URL contract",path:["envPrefix"]})}),P8=A.enum(["0600"]),z8=A.enum(["0700"]),g8=A.enum([".hasna",".codewith"]),wv=A.enum(["directory","file","sqlite_db","sqlite_wal","sqlite_shm","backup","export","report","tmp","log","session","snapshot"]),LD=R$.refine((_)=>!_.startsWith("~"),"Local store path patterns must be relative to their declared root"),rv=A.object({id:A.string().min(1),source:A.enum(["sqlite","manifest","index","runtime","package_adapter"]),table:A.string().min(1).optional(),column:A.string().min(1).optional(),description:A.string().min(1),required:A.boolean().default(!0)}).strict(),fv=A.object({safeWhen:A.enum(["exclusive_access","offline_only","never"]),operations:A.array(A.enum(["wal_checkpoint_truncate","incremental_vacuum","optimize","vacuum"])).default([])}).strict().superRefine((_,$)=>{if(_.safeWhen==="never"&&_.operations.length>0)$.addIssue({code:A.ZodIssueCode.custom,message:"sqliteMaintenance.safeWhen=never cannot declare operations",path:["operations"]})}),xv=A.object({id:A.string().min(1),description:A.string().min(1),ttlDays:A.number().int().nonnegative().optional(),artifactClasses:A.array(wv).min(1),allowlistGlobs:A.array(LD).min(1),activeRecordExclusions:A.array(rv).default([]),sqliteMaintenance:fv.optional()}).strict(),uv=A.object({storeId:A.string().regex(/^[a-z][a-z0-9-]*$/),packageName:A.string().min(1),displayName:A.string().min(1),root:g8,relativePath:LD,directoryMode:z8.default("0700"),fileMode:P8.default("0600"),sqliteDatabaseGlobs:A.array(LD).default([]),sensitiveFileGlobs:A.array(LD).default([]),backupGlobs:A.array(LD).default([]),exportGlobs:A.array(LD).default([]),retentionAdapters:A.array(xv).default([]),notes:A.array(A.string().min(1)).default([])}).strict().superRefine((_,$)=>{if(_.relativePath.includes("*"))$.addIssue({code:A.ZodIssueCode.custom,message:"store relativePath must be a concrete directory; use glob fields for files",path:["relativePath"]});let D=new Set;for(let[I,U]of _.retentionAdapters.entries()){if(D.has(U.id))$.addIssue({code:A.ZodIssueCode.custom,message:"retention adapter ids must be unique within a store",path:["retentionAdapters",I,"id"]});D.add(U.id)}}),X8=J_(y.secureLocalStorePolicy).extend({version:A.string().min(1),scope:A.array(g8).min(1),defaults:A.object({directoryMode:z8.default("0700"),fileMode:P8.default("0600"),dryRunDefault:A.literal(!0),requireExplicitApply:A.literal(!0),includeSqliteSidecars:A.literal(!0),redactedEvidenceOnly:A.literal(!0)}).strict(),stores:A.array(uv).min(1),lifecycle:A.object({retentionDryRunDefault:A.literal(!0),requireActiveRecordExclusionProof:A.literal(!0),requireArtifactAllowlist:A.literal(!0),sqliteMaintenanceRequiresExclusiveAccess:A.literal(!0)}).strict(),warnings:A.array(A.string().min(1)).default([])}).strict().superRefine((_,$)=>{let D=new Set;for(let[I,U]of _.stores.entries()){if(D.has(U.storeId))$.addIssue({code:A.ZodIssueCode.custom,message:"store ids must be unique",path:["stores",I,"storeId"]});if(D.add(U.storeId),!_.scope.includes(U.root))$.addIssue({code:A.ZodIssueCode.custom,message:"store root must be listed in policy scope",path:["stores",I,"root"]})}}),yv=A.object({$schema:A.string().min(1).optional(),schema:A.literal(y.serviceContract),name:qv,class:zv,contractVersion:A.literal(Pv),kitVersion:A.string().min(1),description:A.string().min(1).optional(),bins:A.array(A.string().min(1)).default([]),storage:vv.optional(),hosting:A.array(Xv).min(1).default(["user-hosted"]),serviceSurfaces:A.array(Kv).default([]),metadata:bv.optional()}).strict().superRefine((_,$)=>{if(new Set(_.hosting).size!==_.hosting.length)$.addIssue({code:A.ZodIssueCode.custom,message:"hosting must not contain duplicates",path:["hosting"]});let D=new Set(Cv(_.name)),I=new Set;for(let[S,L]of _.bins.entries()){if(I.has(L))$.addIssue({code:A.ZodIssueCode.custom,message:"Duplicate bin declaration",path:["bins",S]});if(I.add(L),!D.has(L))$.addIssue({code:A.ZodIssueCode.custom,message:`Bin "${L}" is not allowlisted for app "${_.name}"; allowed: ${[...D].join(", ")}`,path:["bins",S]})}let U=(S)=>I.has(`${_.name}${S}`);if(_.storage){let S=_.name.toUpperCase().replace(/-/g,"_");if(_.storage.envPrefix&&_.storage.envPrefix!==`HASNA_${S}_`)$.addIssue({code:A.ZodIssueCode.custom,message:`storage.envPrefix must be HASNA_${S}_`,path:["storage","envPrefix"]});if(_.storage.databaseUrlSecretRef&&_.storage.databaseUrlSecretRef!==f9(_.name))$.addIssue({code:A.ZodIssueCode.custom,message:`storage.databaseUrlSecretRef must be ${f9(_.name)}`,path:["storage","databaseUrlSecretRef"]})}if(_.class==="library"){if(_.storage)$.addIssue({code:A.ZodIssueCode.custom,message:"library repos must not declare storage",path:["storage"]});if(U("-serve")||U("-mcp"))$.addIssue({code:A.ZodIssueCode.custom,message:"library repos must not ship a -serve or -mcp bin",path:["bins"]})}if(_.class==="cli-with-store"){if(!_.storage)$.addIssue({code:A.ZodIssueCode.custom,message:"cli-with-store repos must declare storage",path:["storage"]});else{if(_.storage.mode==="sqlite"&&!_.storage.sqlitePath)$.addIssue({code:A.ZodIssueCode.custom,message:"sqlite cli-with-store storage requires sqlitePath (~/.hasna//.db)",path:["storage","sqlitePath"]});if(_.storage.engines){let S=new Set(_.storage.engines),L=_.metadata?.conformance?.waivedStorageEngines??[],W=Hv({class:_.class,name:_.name,bins:_.bins,hosting:_.hosting,storageMode:_.storage.mode}),g=new Set(W?[]:L.map((G)=>G.engine)),z=J8.filter((G)=>!S.has(G)&&!g.has(G));if(z.length>0){let G=W&&L.length>0?`; declared waiver ignored: ${W}`:"";$.addIssue({code:A.ZodIssueCode.custom,message:`cli-with-store storage.engines must declare both sqlite and postgres unless the engine carries a metadata.conformance.waivedStorageEngines waiver; missing: ${z.join(", ")}${G}`,path:["storage","engines"]})}}}if(!I.has(_.name))$.addIssue({code:A.ZodIssueCode.custom,message:`cli-with-store repos must ship the "${_.name}" bin`,path:["bins"]})}if(_.class==="service"){if(!_.storage)$.addIssue({code:A.ZodIssueCode.custom,message:"service repos must declare storage",path:["storage"]});else if(_.storage.engines&&(!_.storage.engines.includes("sqlite")||!_.storage.engines.includes("postgres")))$.addIssue({code:A.ZodIssueCode.custom,message:"service storage.engines must declare both sqlite and postgres",path:["storage","engines"]});if(!U("-serve"))$.addIssue({code:A.ZodIssueCode.custom,message:`service repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"service repos must declare at least one service surface",path:["serviceSurfaces"]})}if(_.class==="saas"){if(!_.storage)$.addIssue({code:A.ZodIssueCode.custom,message:"saas repos must declare storage",path:["storage"]});else{if(_.storage.mode!=="postgres")$.addIssue({code:A.ZodIssueCode.custom,message:"saas repos must use the postgres storage backend",path:["storage","mode"]});if(!_.storage.envPrefix)$.addIssue({code:A.ZodIssueCode.custom,message:"saas storage requires envPrefix for the public DATABASE_URL contract",path:["storage","envPrefix"]})}if(!U("-serve"))$.addIssue({code:A.ZodIssueCode.custom,message:`saas repos must ship the "${_.name}-serve" bin`,path:["bins"]});if(_.serviceSurfaces.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"saas repos must declare at least one service surface",path:["serviceSurfaces"]})}for(let[S,L]of _.serviceSurfaces.entries()){if(L.bin&&!I.has(L.bin))$.addIssue({code:A.ZodIssueCode.custom,message:`Service surface bin "${L.bin}" must be declared in bins`,path:["serviceSurfaces",S,"bin"]});if(L.mcpBin&&!I.has(L.mcpBin))$.addIssue({code:A.ZodIssueCode.custom,message:`Service surface MCP bin "${L.mcpBin}" must be declared in bins`,path:["serviceSurfaces",S,"mcpBin"]})}let E=_.metadata?.conformance?.waivedSurfaces??[],j=new Set;for(let[S,L]of E.entries()){if(j.has(L.kind))$.addIssue({code:A.ZodIssueCode.custom,message:`Duplicate conformance waiver for ${L.kind}`,path:["metadata","conformance","waivedSurfaces",S,"kind"]});j.add(L.kind)}let N=_.metadata?.conformance?.waivedStorageEngines??[],O=new Set;for(let[S,L]of N.entries()){if(O.has(L.engine))$.addIssue({code:A.ZodIssueCode.custom,message:`Duplicate storage-engine waiver for ${L.engine}`,path:["metadata","conformance","waivedStorageEngines",S,"engine"]});O.add(L.engine)}}),Lm=A.object({status:A.enum(["ok","degraded","unavailable"]),version:A.string().min(1),mode:W8}).strict(),Wm=A.object({ready:A.boolean(),reason:A.string().min(1).optional()}).strict(),Jm=A.object({version:A.string().min(1)}).strict(),hv=A.enum(["info","notice","breaking","critical"]),cv=A.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 (..)"),nv=["FREEZE","UNFREEZE","BREAKING","CUTOVER","POLICY","RELEASE"],dv=A.enum(nv);var mv=A.enum(["fleet","package","machine"]),G8=J_(y.commsEventEnvelope).extend({type:cv,severity:hv,scope:mv,summary:A.string().min(1).optional(),source:e$.optional(),affected_packages:A.array(e).default([]),affected_machines:A.array(e).default([]),action_required:A.boolean().default(!1),ack_by:M_.optional(),dedupe_key:e,resourceRefs:A.array(__).default([]),evidenceRefs:A.array(T_).default([])}).strict().superRefine((_,$)=>{if(_.scope==="package"&&_.affected_packages.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Package-scoped comms events require affected_packages",path:["affected_packages"]});if(_.scope==="machine"&&_.affected_machines.length===0)$.addIssue({code:A.ZodIssueCode.custom,message:"Machine-scoped comms events require affected_machines",path:["affected_machines"]});if(_.ack_by&&!_.action_required)$.addIssue({code:A.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:A.ZodIssueCode.custom,message:`${_.type} events are always critical`,path:["severity"]});if(_.scope!=="fleet")$.addIssue({code:A.ZodIssueCode.custom,message:`${_.type} events are always fleet-scoped`,path:["scope"]});if(!_.action_required)$.addIssue({code:A.ZodIssueCode.custom,message:`${_.type} events require action_required`,path:["action_required"]})}}),lv=A.enum(["fleet","package","product","loop-lane","initiative","personal"]),iv=A.enum(["quiet","work","firehose"]),tv=e.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:)"),ov=J_(y.commsChannelMetadata).extend({class:lv,noise:iv.optional(),owner:e.optional(),until:tv.optional(),successor:e.optional()}).strict().superRefine((_,$)=>{if(_.class==="initiative"){if(!_.owner)$.addIssue({code:A.ZodIssueCode.custom,message:"Initiative channels require an owner",path:["owner"]});if(!_.until)$.addIssue({code:A.ZodIssueCode.custom,message:"Initiative channels require an until horizon (date or gate id)",path:["until"]})}}),x9={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}},pv=J_(y.commsMessageMetadata).extend({tag:dv,envelope:G8}).strict().superRefine((_,$)=>{let D=x9[_.tag];if(!D.allowedSeverities.includes(_.envelope.severity))$.addIssue({code:A.ZodIssueCode.custom,message:`[${_.tag}] posts allow severities ${D.allowedSeverities.join(", ")}`,path:["envelope","severity"]});if(D.requiredEventType&&_.envelope.type!==D.requiredEventType)$.addIssue({code:A.ZodIssueCode.custom,message:`[${_.tag}] posts require event type ${D.requiredEventType}`,path:["envelope","type"]});for(let[I,U]of Object.entries(x9))if(U.requiredEventType===_.envelope.type&&_.tag!==I)$.addIssue({code:A.ZodIssueCode.custom,message:`${_.envelope.type} events must use the [${I}] tag`,path:["tag"]})});var ev={[y.actorRef]:Kk,[y.resourceRef]:Tk,[y.evidenceRef]:Vk,[y.workRun]:wC,[y.taskToPrProjection]:Lv,[y.decisionEnvelope]:s9,[y.costEstimate]:H1,[y.capabilityCard]:Mk,[y.providerLiveModeStandard]:Ck,[y.contextPack]:_8,[y.integrationRef]:$8,[y.projectManifest]:xk,[y.projectPanel]:D8,[y.projectSnapshot]:tk,[y.renderManifest]:ck,[y.agentTrajectory]:Jv,[y.validationPlan]:ok,[y.proofBundle]:vC,[y.scaffoldManifest]:DC,[y.scaffoldInstallRecord]:IC,[y.appCloudManifest]:E8,[y.noCloudEvidencePack]:kC,[y.secureLocalStorePolicy]:X8,[y.serviceContract]:yv,[y.commsEventEnvelope]:G8,[y.commsChannelMetadata]:ov,[y.commsMessageMetadata]:pv,[y.app]:WC,[y.release]:PC,[y.rolloutRecord]:XC,[y.announcement]:QC,[y.audience]:MC};class R8 extends Error{schemaId;issues;constructor(_,$){super(`Contract validation failed for ${_}`);this.name="ContractValidationError",this.schemaId=_,this.issues=$}}function Y8(_,$){let I=ev[_].safeParse($);if(!I.success)throw new R8(_,I.error.issues);return I.data}var Pm=String.raw`(?:^|[^\w$])(?:_*(?:import|require)|createRequire|Module\s*\.\s*_load)`;var Jz=[{pattern:"@hasna/cloud",kind:"module",message:"Shared @hasna/cloud runtime reference is forbidden"},{pattern:"open-cloud",kind:"module",message:"Shared open-cloud runtime reference is forbidden"},{pattern:"cloud-mcp",kind:"module",message:"Legacy cloud-mcp runtime surface is forbidden"},{pattern:"registerCloudTools",kind:"symbol",message:"Legacy registerCloudTools runtime surface is forbidden"},{pattern:"registerCloudCommands",kind:"symbol",message:"Legacy registerCloudCommands runtime surface is forbidden"},{pattern:".hasna/cloud",kind:"config",checkKind:"runtime_config",message:"Legacy .hasna/cloud runtime config is forbidden"},{pattern:"HASNA_CLOUD_",kind:"config",message:"Shared HASNA_CLOUD_* runtime config is forbidden"},{pattern:"HASNA_RDS_PASSWORD",kind:"config",message:"Legacy shared RDS credential config is forbidden"}],zm=Jz.filter((_)=>("checkKind"in _)),av=Jz.filter((_)=>_.kind==="module"),gm=[...new Set([...XN,...av.map((_)=>_.pattern)])],Xm=Jz.filter((_)=>_.kind==="config");var u9="^[^\\u0000-\\u001f\\u007f]*$",Gm={$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. Hosting story, product surfaces, and storage capabilities are separate declarations; the storage backend (sqlite | postgres) is the only runtime switch.",type:"object",additionalProperties:!1,required:["schema","name","class","contractVersion","kitVersion"],allOf:[{if:{required:["class"],properties:{class:{const:"saas"}}},then:{required:["storage"],properties:{storage:{required:["mode","envPrefix"],properties:{mode:{const:"postgres"}}}}}}],properties:{$schema:{type:"string",description:"Optional editor hint pointing at this JSON Schema."},schema:{const:y.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."},hosting:{type:"array",items:{enum:["user-hosted","hasna-saas"]},minItems:1,uniqueItems:!0,description:"Customer-facing product stories. Public OSS cores include user-hosted; add hasna-saas only when a managed control plane exists."},serviceSurfaces:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","status","authMode"],allOf:[{if:{required:["status"],properties:{status:{const:"supported"},kind:{const:"api"}}},then:{required:["bin","health","readiness","version"]}}],properties:{name:{type:"string",minLength:1},kind:{enum:["api","sdk","mcp","cli"]},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"]},health:{type:"object",additionalProperties:!1,required:["method","path"],properties:{method:{const:"GET"},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:{const:"GET"},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:{const:"GET"},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_./:-]*$"},exportSubpath:{type:"string",pattern:"^\\.(?:\\/[A-Za-z0-9_.-]+(?:\\/[A-Za-z0-9_.-]+)*)?$",description:"SDK package export key such as . or ./sdk."},generatedFrom:{type:"string",pattern:"^/[A-Za-z0-9_./:-]*$",description:"OpenAPI path used to generate the SDK."},clientClassName:{type:"string",pattern:"^[A-Za-z_$][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 API, SDK, MCP, and CLI product surfaces. Legacy entries without kind remain parseable; new manifests declare kind explicitly."},storage:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["sqlite","postgres"],description:"Active data backend. sqlite|postgres ONLY \u2014 the single runtime switch."},engines:{type:"array",items:{enum:["sqlite","postgres"]},minItems:1,uniqueItems:!0,description:"Supported storage engines; capability metadata independent of the active backend."},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:"Legacy/private-tier database secret ref. Public conformance rejects this field."},sqlitePath:{type:"string",pattern:"\\.db$",description:"Local sqlite path (~/.hasna//.db)."},pgTestGate:{type:"object",additionalProperties:!1,required:["envVar","command"],properties:{envVar:{type:"string",pattern:"^[A-Z][A-Z0-9_]*_TEST_DATABASE_URL$"},command:{type:"string",minLength:1}},description:"Environment-gated live PostgreSQL test command."}}},metadata:{type:"object",additionalProperties:!0,properties:{conformance:{type:"object",additionalProperties:!0,properties:{waiverProfile:{const:"non-node-monorepo",description:"Explicit surface-waiver eligibility for exceptional non-Node monorepos. Libraries are eligible for API/MCP waivers without this profile."},waivedSurfaces:{type:"array",uniqueItems:!0,items:{type:"object",additionalProperties:!1,required:["kind","reason"],properties:{kind:{enum:["api","sdk","mcp","cli"]},reason:{type:"string",minLength:1}}}},waivedStorageEngines:{type:"array",uniqueItems:!0,maxItems:Dz.length,items:{type:"object",additionalProperties:!1,required:["engine","reason"],properties:{engine:{enum:[...Dz]},reason:{type:"string",minLength:1,maxLength:Lz,allOf:[{pattern:"\\S"},{pattern:u9}]},reviewedBy:{type:"string",minLength:1,maxLength:Wz,allOf:[{pattern:"\\S"},{pattern:u9}]},expiresAt:{type:"string",format:"date-time"}}},description:"Explicit storage-engine exceptions, at most one per engine. Only a CLI-only cli-with-store repo (no -serve bin, storage.mode sqlite, no hasna-saas story) may waive postgres; sqlite is never waivable, expiresAt is a UTC RFC 3339 timestamp, and conformance stops honouring a waiver once it has passed."}}}}}}};var sv="2026-07-06";function t$(_,$,D,I,U,E=[],j){return{id:_,description:$,ttlDays:D,artifactClasses:I,allowlistGlobs:U,activeRecordExclusions:E.map((N)=>({...N,required:N.required??!0})),sqliteMaintenance:j}}var Rm=X8.parse({schema:y.secureLocalStorePolicy,id:"hasna-secure-local-store-defaults",createdAt:"2026-07-06T00:00:00.000Z",version:sv,scope:[".hasna",".codewith"],defaults:{directoryMode:"0700",fileMode:"0600",dryRunDefault:!0,requireExplicitApply:!0,includeSqliteSidecars:!0,redactedEvidenceOnly:!0},lifecycle:{retentionDryRunDefault:!0,requireActiveRecordExclusionProof:!0,requireArtifactAllowlist:!0,sqliteMaintenanceRequiresExclusiveAccess:!0},stores:[{storeId:"codewith",packageName:"codewith",displayName:"Codewith native state",root:".codewith",relativePath:".",sqliteDatabaseGlobs:["logs_*.sqlite","state_*.sqlite","goals_*.sqlite"],sensitiveFileGlobs:["sessions/**/*.jsonl","shell_snapshots/**/*","logs*.sqlite","state*.sqlite","goals*.sqlite"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("codewith-session-snapshots","Codewith sessions, shell snapshots, logs, monitor output, mailbox payloads, and scheduler state need package-owned redaction before retention applies.",30,["session","snapshot","log"],["sessions/**/*.jsonl","shell_snapshots/**/*","logs/**/*"],[{id:"codewith-active-session",source:"package_adapter",description:"Exclude currently active sessions, leased schedules, monitors, pending interactions, and active goal rows."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})],notes:["Includes native .codewith DBs and transcript-like artifacts; redaction-before-persistence remains package-owned."]},{storeId:"todos",packageName:"@hasna/todos",displayName:"Todos",root:".hasna",relativePath:"todos",sqliteDatabaseGlobs:["todos.db"],sensitiveFileGlobs:["todos.db","todos.db-wal","todos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak","*.backup"],exportGlobs:["exports/**/*","*.jsonl","*.csv"],retentionAdapters:[t$("todos-exports-backups","Todos backups and exports are deleted only after package redaction and active task/evidence references are excluded.",14,["backup","export"],["backups/**/*","exports/**/*"],[{id:"todos-active-evidence",source:"sqlite",table:"task_files",column:"path",description:"Exclude files still referenced by active tasks, verification evidence, task comments, or handoff records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"conversations",packageName:"@hasna/conversations",displayName:"Conversations",root:".hasna",relativePath:"conversations",sqliteDatabaseGlobs:["messages.db"],sensitiveFileGlobs:["messages.db","messages.db-wal","messages.db-shm","exports/**/*","attachments/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*","*.json","*.csv"],retentionAdapters:[t$("conversations-exports-attachments","Conversation exports and attachments require message-id redaction and active attachment reference checks before deletion.",14,["export","backup"],["exports/**/*","backups/**/*","attachments/**/*"],[{id:"conversations-active-attachments",source:"sqlite",table:"messages",column:"attachments",description:"Exclude attachments still referenced by retained messages or audited redaction records."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"mementos",packageName:"@hasna/mementos",displayName:"Mementos",root:".hasna",relativePath:"mementos",sqliteDatabaseGlobs:["mementos.db"],sensitiveFileGlobs:["mementos.db","mementos.db-wal","mementos.db-shm","exports/**/*","backups/**/*"],backupGlobs:["backups/**/*","*.bak"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("mementos-audit-search-history","Mementos retention must preserve active memory versions while compacting audit/search surfaces through package-owned adapters.",30,["backup","export","log"],["backups/**/*","exports/**/*","audit/**/*"],[{id:"mementos-active-memory-versions",source:"sqlite",table:"memory_versions",column:"memory_id",description:"Exclude current memory versions and audit entries required for provenance."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"knowledge",packageName:"@hasna/knowledge",displayName:"Knowledge",root:".hasna",relativePath:"knowledge",sqliteDatabaseGlobs:["knowledge.db"],sensitiveFileGlobs:["knowledge.db","knowledge.db-wal","knowledge.db-shm","db.json","migration-exports/**/*","*.bak"],backupGlobs:["*.bak","backups/**/*","*.pre-cloud-*"],exportGlobs:["migration-exports/**/*","exports/**/*","*.jsonl"],retentionAdapters:[t$("knowledge-migrations-exports","Knowledge migration exports and pre-cloud backups require replacement, encryption, or redaction before retention deletion.",14,["backup","export"],["migration-exports/**/*","exports/**/*","*.bak","*.pre-cloud-*"],[{id:"knowledge-current-catalog",source:"manifest",description:"Exclude files referenced by the active catalog or migration ledger."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"projects",packageName:"@hasna/projects",displayName:"Projects",root:".hasna",relativePath:"projects",sqliteDatabaseGlobs:["projects.db","data/*/project.db"],sensitiveFileGlobs:["projects.db","projects.db-wal","projects.db-shm","data/*/project.db","data/*/project.db-wal","data/*/project.db-shm","reports/**/*"],backupGlobs:["backups/**/*","data/*/backups/**/*"],exportGlobs:["reports/**/*","exports/**/*"],retentionAdapters:[t$("projects-reports-workspaces","Project reports, dashboards, workspaces, and per-project DBs need active workspace/location references before cleanup.",30,["backup","export","report","tmp"],["backups/**/*","reports/**/*","workspaces/**/*","data/*/backups/**/*"],[{id:"projects-active-workspaces",source:"sqlite",table:"workspaces",column:"primary_path",description:"Exclude active workspace paths, locations, linked reports, and project store artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"browser",packageName:"@hasna/browser",displayName:"Browser",root:".hasna",relativePath:"browser",sqliteDatabaseGlobs:["browser.db"],sensitiveFileGlobs:["browser.db","browser.db-wal","browser.db-shm","profiles/**/cookies.json","states/**/*.json","auth/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*","traces/**/*","har/**/*"],retentionAdapters:[t$("browser-auth-traces","Browser state, trace, HAR, and auth artifacts require session invalidation or redaction before deletion.",7,["backup","export","session","snapshot"],["profiles/**/*","states/**/*","traces/**/*","har/**/*","exports/**/*"],[{id:"browser-active-profiles",source:"sqlite",table:"sessions",column:"profile_path",description:"Exclude profiles, cookies, and storage state used by active browser sessions."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"terminal",packageName:"@hasna/terminal",displayName:"Terminal",root:".hasna",relativePath:"terminal",sqliteDatabaseGlobs:["sessions.db"],sensitiveFileGlobs:["sessions.db","sessions.db-wal","sessions.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("terminal-sessions","Terminal sessions and interactions need active session exclusion plus command-output redaction before retention.",30,["backup","export","session","log"],["backups/**/*","exports/**/*","sessions/**/*"],[{id:"terminal-active-sessions",source:"sqlite",table:"sessions",column:"id",description:"Exclude active terminal session records and any linked interaction artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"logs",packageName:"@hasna/logs",displayName:"Logs",root:".hasna",relativePath:"logs",sqliteDatabaseGlobs:["logs.db"],sensitiveFileGlobs:["logs.db","logs.db-wal","logs.db-shm","exports/**/*"],backupGlobs:["backups/**/*"],exportGlobs:["exports/**/*"],retentionAdapters:[t$("logs-retention","Logs require redaction before compaction and must preserve active incident/evidence references.",14,["backup","export","log"],["backups/**/*","exports/**/*","*.log","logs/**/*"],[{id:"logs-active-evidence",source:"sqlite",table:"logs",column:"id",description:"Exclude log rows or files linked to active incidents, tasks, or proof bundles."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]},{storeId:"loops",packageName:"@hasna/loops",displayName:"OpenLoops",root:".hasna",relativePath:"loops",sqliteDatabaseGlobs:["loops.db","state.db","*.sqlite"],sensitiveFileGlobs:["*.db","*.sqlite","*.db-wal","*.db-shm","reports/**/*","tmp/**/*","runs/**/*"],backupGlobs:["backups/**/*","tmp/**/*"],exportGlobs:["reports/**/*","runs/**/*","exports/**/*"],retentionAdapters:[t$("loops-reports-tmp","Loop reports, tmp files, workflow artifacts, and command output need run-state checks and redaction before retention deletion.",14,["backup","export","report","tmp","log"],["reports/**/*","tmp/**/*","runs/**/*","exports/**/*"],[{id:"loops-active-runs",source:"sqlite",table:"loop_runs",column:"id",description:"Exclude active, leased, recently failed, or evidence-linked loop and workflow run artifacts."}],{safeWhen:"exclusive_access",operations:["wal_checkpoint_truncate","optimize"]})]}],warnings:["This package publishes declarations only; each owning package implements and verifies its own local-store lifecycle.","Retention and redaction evidence remain package-owned and must preserve active-record exclusions.","SQLite maintenance is descriptive policy metadata only and is never executed by @hasna/contracts."]});var _w=64,Ym=new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${_w-1}}$`),OD="[0-9a-fA-F]",Qm=new RegExp(`^\\{?(?:${OD}{8}-${OD}{4}-${OD}{4}-${OD}{4}-${OD}{12}|${OD}{32})\\}?$`);var $w=/^hasna_([a-z][a-z0-9-]*)_([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/;var Km=new RegExp($w.source.replace(/^\^/,"\\b").replace(/\$$/,"\\b"));var Q8="@hasna/knowledge";function Dw(_){if(!Number.isFinite(_??0))return 20;return Math.max(1,Math.min(100,Math.trunc(_??20)))}function Uw(_){return _.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"project"}function b1(_,$=180){let D=String(_??"").replace(/\s+/g," ").trim();if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-3))}...`}function w_(_,$=""){return typeof _==="string"&&_.length>0?_:$}function q1(_){return typeof _==="number"&&Number.isFinite(_)?_:0}function bD(_){if(typeof _!=="string"||_.length===0)return;let $=_.includes("T")?_:`${_.replace(" ","T")}Z`,D=new Date($);return Number.isNaN(D.valueOf())?void 0:D.toISOString()}function VN(_){return r$.safeParse(_).success}function f$(_,$,D,I,U=[]){return{kind:_,id:$,name:D,uri:I&&VN(I)?I:void 0,externalId:$,sourcePackage:Q8,tags:U}}function Iw(_){return[..._.items.flatMap((D)=>[D.updated_at,D.created_at]),..._.sources.flatMap((D)=>[D.updated_at,D.created_at]),..._.chunks.map((D)=>D.created_at),..._.wiki_pages.flatMap((D)=>[D.updated_at,D.created_at]),..._.storage_objects.flatMap((D)=>[D.updated_at,D.created_at]),..._.runs.flatMap((D)=>[D.updated_at,D.created_at]),..._.reindex_queue.flatMap((D)=>[D.updated_at,D.created_at]),..._.sync_conflicts.map((D)=>D.created_at),..._.approval_gates.flatMap((D)=>[D.updated_at,D.created_at])].map(bD).filter(Boolean).sort((D,I)=>I.localeCompare(D))[0]}function Ew(_){if(!_)return"unknown";let $=Date.now()-new Date(_).valueOf();if(!Number.isFinite($))return"unknown";return $>2592000000?"stale":"fresh"}function jw(_){let $=(D)=>{let I=String(D??"").toLowerCase();return I!==""&&!["done","complete","completed","resolved","succeeded","skipped"].includes(I)};return _.reindex_queue.filter((D)=>$(D.status)).length+_.sync_conflicts.filter((D)=>$(D.status)).length+_.approval_gates.filter((D)=>$(D.status)).length}function Nw(_,$){let D=[];for(let I of _.items.slice(0,$))D.push({id:`item_${I.id}`,title:I.title,summary:b1(I.content_preview),status:I.archived?"archived":"active",priority:"medium",timestamp:bD(I.updated_at??I.created_at),resourceRefs:[f$("knowledge",I.id,I.title,`knowledge://item/${encodeURIComponent(I.id)}`,I.tags)],evidenceRefs:I.url&&VN(I.url)?[{id:`url_${I.id}`,kind:"url",uri:I.url,summary:"Source URL for this knowledge item."}]:[],metadata:{source:"legacy_store",archived:I.archived,tags:I.tags,url:I.url||void 0}});for(let I of _.sources.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,w_(I.uri,"source")),E=w_(I.title,w_(I.uri,U)),j=w_(I.uri,`knowledge://source/${encodeURIComponent(U)}`);D.push({id:`source_${U}`,title:E,summary:b1(`${q1(I.chunks)} chunk(s), ${q1(I.revisions)} revision(s)`),status:q1(I.chunks)>0?"indexed":"source",priority:"medium",timestamp:bD(I.updated_at??I.created_at),resourceRefs:[f$("document",U,E,j)],evidenceRefs:VN(j)?[{id:`source_${U}`,kind:"url",uri:j,summary:"Source reference."}]:[],metadata:{source:"knowledge_db.sources",kind:I.kind,chunks:q1(I.chunks),revisions:q1(I.revisions)}})}for(let I of _.chunks.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,"chunk"),E=w_(I.source_uri);D.push({id:`chunk_${U}`,title:w_(I.wiki_title,E?`Chunk from ${E}`:`Knowledge chunk ${U}`),summary:b1(I.text_preview),status:"chunk",priority:"low",timestamp:bD(I.created_at),resourceRefs:[f$("context_pack",U,w_(I.wiki_title,U),`knowledge://chunk/${encodeURIComponent(U)}`)],evidenceRefs:E&&VN(E)?[{id:`chunk_source_${U}`,kind:"url",uri:E,summary:"Chunk source reference."}]:[],metadata:{source:"knowledge_db.chunks",source_uri:E||void 0,token_count:I.token_count,ordinal:I.ordinal}})}for(let I of _.sync_conflicts.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,"sync_conflict");D.push({id:`sync_conflict_${U}`,title:`Sync conflict: ${w_(I.entity_kind,"entity")}/${w_(I.entity_id,U)}`,summary:b1(`Status ${w_(I.status,"unknown")}; strategy ${w_(I.resolution_strategy,"none")}.`),status:w_(I.status,"unknown"),priority:"critical",timestamp:bD(I.created_at),resourceRefs:[f$("finding",U,"Knowledge sync conflict",`knowledge://sync-conflict/${encodeURIComponent(U)}`)],metadata:{source:"knowledge_db.sync_conflicts",local_machine_id:I.local_machine_id,remote_machine_id:I.remote_machine_id}})}for(let I of _.reindex_queue.slice(0,Math.max(0,$-D.length))){let U=w_(I.id,"reindex");D.push({id:`reindex_${U}`,title:`Reindex ${w_(I.kind,"item")}: ${w_(I.target_id,U)}`,summary:b1(I.reason),status:w_(I.status,"unknown"),priority:w_(I.status).toLowerCase()==="failed"?"high":"medium",timestamp:bD(I.updated_at??I.created_at),resourceRefs:[f$("action",U,"Knowledge reindex work item",`knowledge://reindex/${encodeURIComponent(U)}`)],metadata:{source:"knowledge_db.reindex_queue",attempts:I.attempts,source_uri:I.source_uri}})}return D.slice(0,$)}async function K8(_,$={}){let D=Dw($.limit),I=new Date().toISOString(),U=Uw(_),j=await($.service??gN({scope:$.scope??"project",cwd:$.cwd})).resolveInventory({limit:D,storePath:$.storePath,includeArchived:$.includeArchived}),N=Iw(j),O=Ew(N),S=j.summary.active_items+j.summary.sources+j.summary.chunks+j.summary.wiki_pages+j.summary.storage_objects,L=jw(j),W=S===0?"empty":O==="stale"?"stale":"ready",g=Nw(j,D),z={schema:y.projectPanel,id:`knowledge_panel_${U}`,createdAt:I,projectId:U,provider:{kind:"knowledge",id:`knowledge_${U}`,name:"Knowledge",sourcePackage:Q8,externalId:j.home},kind:"knowledge",title:"Knowledge",summary:W==="empty"?"No project knowledge items, sources, chunks, or wiki pages are available yet.":`${j.summary.active_items} active note(s), ${j.summary.sources} source(s), ${j.summary.chunks} chunk(s), and ${j.summary.wiki_pages} wiki page(s).`,state:W,stateReason:W==="stale"?"Latest indexed knowledge activity is older than 30 days.":void 0,generatedAt:I,freshness:O,metrics:[{id:"active_items",label:"Active notes",value:j.summary.active_items,status:j.summary.active_items>0?"good":"unknown"},{id:"sources",label:"Sources",value:j.summary.sources,status:j.summary.sources>0?"good":"unknown"},{id:"chunks",label:"Chunks",value:j.summary.chunks,status:j.summary.chunks>0?"good":"unknown"},{id:"wiki_pages",label:"Wiki pages",value:j.summary.wiki_pages,status:j.summary.wiki_pages>0?"good":"unknown"},{id:"artifacts",label:"Artifacts",value:j.summary.storage_objects,status:j.summary.storage_objects>0?"good":"unknown"},{id:"vector_entries",label:"Vector entries",value:j.summary.vector_entries,status:j.summary.vector_entries>0?"good":"unknown"},{id:"unresolved",label:"Unresolved",value:L,status:L>0?"warning":"good"}],items:g,actions:[f$("action","knowledge:inventory","Inspect knowledge inventory"),f$("action","knowledge:context-pack","Build cited context pack"),f$("action","knowledge:ingest","Ingest project source")],resourceRefs:[f$("project",U,_,`project://${U}`),f$("knowledge",`home_${U}`,"Knowledge workspace",`knowledge://workspace/${encodeURIComponent(U)}`),f$("artifact",`db_${U}`,"Knowledge database",`knowledge://db/${encodeURIComponent(U)}`)],renderFragment:{renderer:"json_render",title:"Knowledge",spec:{component:"project.knowledge.summary",metrics:["active_items","sources","chunks","wiki_pages","unresolved"],itemLimit:D}},metadata:{scope:j.scope,home:j.home,json_store_exists:j.paths.json_store_exists,latest_activity_at:N}};return Y8(y.projectPanel,z)}function T8(_){let $=[`${_.title}: ${_.state}`,_.summary??"",..._.metrics.map((D)=>`${D.label}: ${D.value}`)].filter(Boolean);if(_.items.length>0){$.push("Items:");for(let D of _.items.slice(0,10))if($.push(`- ${D.title}${D.status?` [${D.status}]`:""}`),D.summary)$.push(` ${D.summary}`)}return $.join(` +`)}var B8=["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 M8="HASNA_KNOWLEDGE_STORAGE_MODE",Z8="KNOWLEDGE_STORAGE_MODE";function F8(_){return process.env[_]?.trim()||void 0}function V8(_){let $=_?.trim().toLowerCase().replace(/-/g,"_");if($==="sqlite")return"sqlite";if($==="postgres"||$==="postgresql")return"postgres";return}function Aw(_={}){let $=S0(x1(_.scope,_.cwd).home);return c($.knowledgeDbPath),{db:w($.knowledgeDbPath),path:$.knowledgeDbPath,scope:_.scope??"global"}}function H8(){let _=V8(F8(M8))??V8(F8(Z8));if(_)return _;return"sqlite"}function Pz(_={}){let $=Aw(_);try{Ow($.db);let D=$.db.query("SELECT table_name, last_synced_at, direction FROM _knowledge_sync_meta ORDER BY table_name, direction").all();return{mode:H8(),service:"knowledge",scope:$.scope,databasePath:$.path,tables:B8,sync:D}}finally{$.db.close()}}function Ow(_){_.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 Ow=[`CREATE TABLE IF NOT EXISTS sources ( + `)}var Sw=[`CREATE TABLE IF NOT EXISTS sources ( id TEXT PRIMARY KEY, uri TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, @@ -2767,9 +2870,9 @@ Pages should be concise, cited, and organized for both humans and agents. archived, id ) WHERE metadata #>> '{hasna_knowledge_relations,schema}' - = 'hasna.knowledge.relations.v1'`,...I9()];var l8=HY(m8(),1),{program:Al,createCommand:Ol,createArgument:Sl,createOption:Ll,CommanderError:Jl,InvalidArgumentError:Wl,InvalidOptionArgumentError:Pl,Command:i8,Argument:zl,Option:Xl,Help:Gl}=l8.default;import{chmod as KP,mkdir as Ar,readFile as Or,rename as Sr,writeFile as e8}from"fs/promises";import{Buffer as EY}from"buffer";import{existsSync as jY}from"fs";import{homedir as Lr}from"os";import{join as v1}from"path";import{createHmac as Gr,timingSafeEqual as Bl}from"crypto";import{randomUUID as Qr}from"crypto";import{spawn as Kr}from"child_process";import{randomUUID as br}from"crypto";function $r(_,$){return $.split(".").reduce((D,I)=>{if(D&&typeof D==="object"&&I in D)return D[I];return},_)}function Dr(_,$){let D=[],I=(E)=>{if(!D.some((j)=>Object.is(j,E)))D.push(E)};if($.includes(".")&&$ in _)I(_[$]);let U=$r(_,$);if(U!==void 0||!$.includes("."))I(U);return D}function Ur(_,$={}){let D="";for(let I=0;I<_.length;I+=1){let U=_[I];if(U==="*")if(_[I+1]==="*")D+=".*",I+=1;else D+=$.segmentSafe?"[^/]*":".*";else D+=U.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${D}$`)}function q1(_,$,D={}){if($===void 0)return!0;if(_===void 0)return!1;return(Array.isArray($)?$:[$]).some((U)=>Ur(U,D).test(_))}function t8(_,$){if(!$)return!0;return Object.entries($).every(([D,I])=>{let U=Dr(_,D);return Ir(U,I,D)})}function Ir(_,$,D){if(Nr($))return!_.some((I)=>o8(I,$.not,D));return _.some((I)=>o8(I,$,D))}function o8(_,$,D){if(typeof $==="string"||Array.isArray($))return Er(_).some((I)=>q1(I,$,{segmentSafe:D.endsWith("_path")||D.endsWith(".path")}));if(Array.isArray(_))return _.some((I)=>I===$);return _===$}function Er(_){if(_===void 0)return[];if(Array.isArray(_))return _.flatMap(($)=>jr($)?[String($)]:[]);return[String(_)]}function jr(_){return _===null||typeof _==="string"||typeof _==="number"||typeof _==="boolean"}function Nr(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_)&&"not"in _)}function gr(_,$){return q1(_.source,$.source)&&q1(_.type,$.type)&&q1(_.subject,$.subject)&&q1(_.severity,$.severity)&&t8(_.data,$.data)&&t8(_.metadata,$.metadata)}function p8(_,$){if(!_.enabled)return!1;if(!_.filters||_.filters.length===0)return!0;return _.filters.some((D)=>gr($,D))}var ZN="HASNA_EVENTS_DIR",HN="HASNA_EVENTS_HOME",BP="local-json-v1:",Jr=100,Wr=1000;function NY(_){return _||process.env[ZN]||process.env[HN]||v1(Lr(),".hasna","events")}function Pr(){if(process.env[ZN])return ZN;if(process.env[HN])return HN;return null}class kN{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor(_=NY()){this.dataDir=_,this.runtime=zr(_),this.channelsPath=v1(_,"channels.json"),this.eventsPath=v1(_,"events.json"),this.deliveriesPath=v1(_,"deliveries.json")}async init(){await Ar(this.dataDir,{recursive:!0,mode:448}),await KP(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,[]),D=$.findIndex((I)=>I.id===_.id);if(D>=0)$[D]={..._,createdAt:$[D].createdAt,updatedAt:new Date().toISOString()};else $.push(_);return await this.writeJson(this.channelsPath,$),D>=0?$[D]:_}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel(_){return(await this.listChannels()).find((D)=>D.id===_)}async removeChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),D=$.filter((I)=>I.id!==_);return await this.writeJson(this.channelsPath,D),D.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 D=await this.readJson(this.eventsPath,[]);if($.dedupe!==!1){let U=s8(D,{id:_.id,dedupeKey:_.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}return D.push(_),await this.writeJson(this.eventsPath,D),{event:_,stored:!0,deduped:!1,identity:{id:_.id,dedupeKey:_.dedupeKey}}}async listEvents(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]);return a8($,_)}async listEventsPage(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]),D=a8($,{eventId:_.eventId,source:_.source,type:_.type}),I=qN(_.cursor,_),U=CN(_.limit),E=D.slice(I,I+U),j=I+E.length,N=j{return})}async readJson(_,$){try{let D=await Or(_,"utf-8");if(!D.trim())return $;return JSON.parse(D)}catch(D){if(D.code==="ENOENT")return $;throw D}}async writeJson(_,$){let D=`${_}.${process.pid}.${Date.now()}.tmp`;await e8(D,`${JSON.stringify($,null,2)} -`,{encoding:"utf-8",mode:384}),await Sr(D,_),await KP(_,384).catch(()=>{return})}}function zr(_=NY()){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 gY(_,$={}){if(!Number.isInteger(_)||_<0)throw Error(`Invalid event cursor offset: ${_}`);let D={offset:_,eventId:$.eventId,source:$.source,type:$.type};return`${BP}${EY.from(JSON.stringify(D),"utf-8").toString("base64url")}`}function qN(_,$={}){if(!_)return 0;if(!_.startsWith(BP))throw Error(`Invalid local JSON event cursor: ${_}`);let D=_.slice(BP.length),I;try{I=JSON.parse(EY.from(D,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${_}`)}let U=I.offset;if(!Number.isInteger(U)||U<0)throw Error(`Invalid local JSON event cursor: ${_}`);return TP("eventId",I.eventId,$.eventId),TP("source",I.source,$.source),TP("type",I.type,$.type),U}function CN(_){if(_===void 0)return Jr;if(!Number.isInteger(_)||_<1)throw Error(`Event page limit must be a positive integer, got ${_}`);return Math.min(_,Wr)}function a8(_,$){let D=_;if($.eventId)D=D.filter((I)=>I.id===$.eventId);if($.source)D=D.filter((I)=>I.source===$.source);if($.type)D=D.filter((I)=>I.type===$.type);if($.cursor){let I=qN($.cursor,$);D=D.slice(I)}if($.limit!==void 0)D=D.slice(0,CN($.limit));return D}function TP(_,$,D){if($!==D)throw Error(`Local JSON event cursor ${_} filter mismatch`)}function s8(_,$){return _.find((D)=>$.id!==void 0&&D.id===$.id||$.dedupeKey!==void 0&&D.dedupeKey===$.dedupeKey)}async function Xr(_){let $=new kN(_);await $.init();let[D,I,U]=await Promise.all([$.listChannels(),$.listEvents(),$.listDeliveries()]),E=D.reduce((j,N)=>{return j[N.transport]=(j[N.transport]??0)+1,j},{});return{service:"events",schemaVersion:"1.0",dataDir:$.dataDir,storage:$.runtime,env:{primary:ZN,fallback:HN,active:Pr()},files:{channels:FP($.dataDir,"channels.json",D.length),events:FP($.dataDir,"events.json",I.length),deliveries:FP($.dataDir,"deliveries.json",U.length)},counts:{channels:D.length,enabledChannels:D.filter((j)=>j.enabled).length,disabledChannels:D.filter((j)=>!j.enabled).length,events:I.length,deliveries:U.length},transports:E,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function FP(_,$,D){let I=v1(_,$);return{path:I,exists:jY(I),records:D}}function Rr(_,$){return`${_}.${$}`}function Yr(_,$,D){return`sha256=${Gr("sha256",_).update(Rr($,D)).digest("hex")}`}function a$(){return new Date().toISOString()}function C1(_,$=4096){return _.length>$?`${_.slice(0,$)}...`:_}function Tr(_,$){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let D=JSON.stringify(_),I=_.time,U={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":_.id,"X-Hasna-Event-Type":_.type,"X-Hasna-Timestamp":I,...$.webhook.headers};if($.webhook.secret)U["X-Hasna-Signature"]=Yr($.webhook.secret,I,D);return{body:D,headers:U}}async function Fr(_,$,D={}){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let I=a$(),{body:U,headers:E}=Tr(_,$),j=new AbortController,N=setTimeout(()=>j.abort(),$.webhook.timeoutMs??15000);try{let A=await(D.fetchImpl??fetch)($.webhook.url,{method:"POST",headers:E,body:U,signal:j.signal}),O=C1(await A.text());return{attempt:1,status:A.ok?"success":"failed",startedAt:I,completedAt:a$(),responseStatus:A.status,responseBody:O,error:A.ok?void 0:`Webhook returned HTTP ${A.status}`}}catch(A){return{attempt:1,status:"failed",startedAt:I,completedAt:a$(),error:A instanceof Error?A.message:String(A)}}finally{clearTimeout(N)}}async function Vr(_,$){if(!$.command)throw Error(`Channel ${$.id} has no command config`);let D=a$(),I=JSON.stringify(_),U={...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:I};return new Promise((E)=>{let j=Kr($.command.command,$.command.args??[],{cwd:$.command.cwd,env:U,stdio:["pipe","pipe","pipe"]}),N="",A="",O=setTimeout(()=>j.kill("SIGTERM"),$.command.timeoutMs??15000);j.stdin.end(I),j.stdout.on("data",(S)=>{N+=S.toString()}),j.stderr.on("data",(S)=>{A+=S.toString()}),j.on("error",(S)=>{clearTimeout(O),E({attempt:1,status:"failed",startedAt:D,completedAt:a$(),stdout:C1(N),stderr:C1(A),error:S.message})}),j.on("close",(S,L)=>{clearTimeout(O);let P=S===0;E({attempt:1,status:P?"success":"failed",startedAt:D,completedAt:a$(),stdout:C1(N),stderr:C1(A),error:P?void 0:`Command exited with ${L?`signal ${L}`:`code ${S}`}`})})})}async function Br(_,$,D={}){if($.transport==="webhook")return Fr(_,$,D);if($.transport==="command")return Vr(_,$);return{attempt:1,status:"skipped",startedAt:a$(),completedAt:a$(),error:`Unsupported transport: ${$.transport}`}}function _Y(_,$,D){let I=D.some((U)=>U.status==="success")?"success":D.every((U)=>U.status==="skipped")?"skipped":"failed";return{id:Qr(),eventId:_.id,channelId:$.id,transport:$.transport,status:I,attempts:D,createdAt:D[0]?.startedAt??a$(),completedAt:D.at(-1)?.completedAt??a$()}}class AY extends Error{eventType;issues;constructor(_,$){let D=$.map((I)=>`${I.path||""}: ${I.message}`).join("; ");super(`Event validation failed for type "${_}": ${D}`);this.name="EventValidationError",this.eventType=_,this.issues=$}}class OY{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 AY(_.type,$.issues)}}var Mr=new OY;function VP(_){return{id:_.id??br(),source:_.source,type:_.type,time:Cr(_.time),subject:_.subject,severity:_.severity??"info",data:_.data??{},message:_.message,dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion??"1.0",metadata:_.metadata??{}}}class SY{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor(_={}){this.store=_.store??new kN(_.dataDir),this.redactors=_.redactors??[],this.transportOptions={fetchImpl:_.fetchImpl},this.catalog=_.catalog??Mr,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 D=$.redactSensitiveData===!1?VP(_):kr(VP(_));if($.validate??this.validateCatalogTypes)this.catalog.assertEventValid(D);let I=await this.appendEvent(D,{dedupe:$.dedupe!==!1});if(I.deduped)return{event:I.event,deliveries:[],deduped:!0};let U=$.deliver===!1?[]:await this.deliver(I.event);return{event:I.event,deliveries:U,deduped:!1}}async listEvents(_={}){if(Object.keys(_).length===0)return this.store.listEvents();return $Y(await this.store.listEvents(),_)}async listEventsPage(_={}){if(this.store.listEventsPage)return this.store.listEventsPage(_);let $=$Y(await this.store.listEvents(),{eventId:_.eventId,source:_.source,type:_.type}),D=qN(_.cursor,_),I=CN(_.limit),U=$.slice(D,D+I),E=D+U.length,j=E<$.length;return{events:U,cursor:_.cursor,nextCursor:j?gY(E,_):void 0,hasMore:j}}async listDeliveries(){return this.store.listDeliveries()}async deliver(_){let D=(await this.store.listChannels()).filter((U)=>p8(U,_)),I=[];for(let U of D){let E=await this.applyRedaction(_,U),j=await this.deliverWithRetry(E,U);await this.store.appendDelivery(j),I.push(j)}return I}async matchChannel(_,$={}){let D=await this.store.getChannel(_);if(!D)throw Error(`Channel not found: ${_}`);let I=VP({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}),U=p8(D,I);return{channelId:D.id,matched:U,event:I,filters:D.filters,reason:U?void 0:D.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel(_,$={},D={}){let I=await this.store.getChannel(_);if(!I)throw Error(`Channel not found: ${_}`);let U=await this.matchChannel(_,$),E=U.event;if(D.honorFilters&&!U.matched){let A=new Date().toISOString(),O=_Y(E,I,[{attempt:1,status:"skipped",startedAt:A,completedAt:A,error:U.reason}]);return O.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(O),O}let j=await this.applyRedaction(E,I),N=await this.deliverWithRetry(j,I);return await this.store.appendDelivery(N),N}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 D=[];for(let I of $.events)D.push(...await this.deliver(I));return{events:$.events,deliveries:D,cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore}}async appendEvent(_,$){if(this.store.appendEventOnce)return this.store.appendEventOnce(_,{dedupe:$.dedupe});if($.dedupe){let I=await this.store.findEventByIdentity({id:_.id,dedupeKey:_.dedupeKey});if(I)return{event:I,stored:!1,deduped:!0,identity:{id:I.id,dedupeKey:I.dedupeKey}}}let D=await this.store.appendEvent(_);return{event:D,stored:!0,deduped:!1,identity:{id:D.id,dedupeKey:D.dedupeKey}}}async applyRedaction(_,$){let D=Zr(_,$.redact?.paths??[],$.redact?.replacement??"[REDACTED]");for(let I of this.redactors)D=await I(D,$);return D}async deliverWithRetry(_,$){let D=vr($.retry),I=[];for(let U=0;U[D,JY(D)?"[REDACTED]":I]));return $}function Hr(_){return _.map(LY)}function kr(_,$="[REDACTED]"){return MP(_,$)}function JY(_){return/secret|token|password|api[_-]?key|authorization/i.test(_)}function MP(_,$){if(Array.isArray(_))return _.map((D)=>MP(D,$));if(!_||typeof _!=="object")return _;return Object.fromEntries(Object.entries(_).map(([D,I])=>[D,JY(D)?$:MP(I,$)]))}function qr(_,$,D){let I=$.split("."),U=_;for(let j of I.slice(0,-1)){let N=U[j];if(!N||typeof N!=="object")return;U=N}let E=I.at(-1);if(E&&E in U)U[E]=D}function $Y(_,$){let D=_;if($.eventId)D=D.filter((I)=>I.id===$.eventId);if($.source)D=D.filter((I)=>I.source===$.source);if($.type)D=D.filter((I)=>I.type===$.type);if($.cursor)D=D.slice(qN($.cursor,$));if($.limit!==void 0)D=D.slice(0,CN($.limit));return D}function Cr(_){if(!_)return new Date().toISOString();return _ instanceof Date?_.toISOString():_}function vr(_){return{maxAttempts:Math.max(1,_?.maxAttempts??1),backoffMs:Math.max(0,_?.backoffMs??250),multiplier:Math.max(1,_?.multiplier??2)}}function bN(_,$,D=!1){if(!_?.length)return;let I={};for(let U of _){let E=fr(U,$),j=E.path;if(j in I)throw Error(`Duplicate ${$} filter path: ${j}`);let N=D?rr(E.rawValue,$):E.rawValue;I[j]=E.negated?{not:N}:N}return I}function wr(_){let $={};if(_.source)$.source=_.source;if(_.type)$.type=_.type;if(_.subject)$.subject=_.subject;if(_.severity)$.severity=_.severity;let D=DY(bN(_.data,"data"),bN(_.dataJson,"data-json",!0)),I=DY(bN(_.metadata,"metadata"),bN(_.metadataJson,"metadata-json",!0));if(Object.keys(D).length>0)$.data=D;if(Object.keys(I).length>0)$.metadata=I;return Object.keys($).length>0?[$]:void 0}function DY(..._){let $={};for(let D of _){if(!D)continue;for(let[I,U]of Object.entries(D)){if(I in $)throw Error(`Duplicate filter path: ${I}`);$[I]=U}}return $}function rr(_,$){let D=JSON.parse(_);if(D===null||typeof D==="string"||typeof D==="number"||typeof D==="boolean"||Array.isArray(D)&&D.every((I)=>typeof I==="string"))return D;throw Error(`${$} filter JSON values must be string, string[], number, boolean, or null`)}function fr(_,$){let D=_.indexOf("!=");if(D>0)return{path:_.slice(0,D),rawValue:_.slice(D+2),negated:!0};let I=_.indexOf("=");if(I<=0)throw Error(`Invalid ${$} filter, expected path=value or path!=value: ${_}`);return{path:_.slice(0,I),rawValue:_.slice(I+1),negated:!1}}var xr=100;function kD(_,$){if(!_)return $;let D=JSON.parse(_);if(!D||typeof D!=="object"||Array.isArray(D))throw Error("Expected a JSON object");return D}function ur(_){if(!_?.length)return;let $={};for(let D of _){let I=D.indexOf("=");if(I===-1)throw Error(`Invalid header, expected name=value: ${D}`);$[D.slice(0,I)]=D.slice(I+1)}return $}function $4(_){if(_.createClient)return _.createClient();return new SY({store:new kN(_.dataDir)})}function I0(_,$,D){if($)console.log(JSON.stringify(_,null,2));else console.log(D)}function UY(_,$){let D=_ instanceof Error?_.message:String(_);if($)console.log(JSON.stringify({error:D},null,2));else console.error(D);process.exitCode=1}function IY(_){return Boolean(_?.json||_?.opts?.().json||_?.optsWithGlobals?.().json||_?.parent?.opts?.().json||_?.parent?.optsWithGlobals?.().json)}function F6(_,$){return IY(_)||IY($)}function yr(_,$){let D=_.command($.channelsCommandName??"channels").description("Manage Hasna event channels");return D.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",U0,[]).option("--metadata ","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",U0,[]).option("--data-json ","Event data field filter with typed JSON value; path!=json negatives supported",U0,[]).option("--metadata-json ","Event metadata field filter with typed JSON value; path!=json negatives supported",U0,[]).option("--secret ","Webhook HMAC secret").option("--header ","Webhook header",U0,[]).option("--arg ","Command argument",U0,[]).option("--timeout-ms ","Transport timeout in milliseconds",w1).option("--retry-attempts ","Maximum delivery attempts",w1).option("--retry-backoff-ms ","Initial retry backoff in milliseconds",w1).option("--redact ","Event field path to redact before delivery",U0,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(I,U,E)=>{let j=new Date().toISOString(),N={id:U.id,name:U.name,enabled:!U.disabled,transport:U.transport,filters:wr(U),retry:U.retryAttempts||U.retryBackoffMs?{maxAttempts:U.retryAttempts,backoffMs:U.retryBackoffMs}:void 0,redact:U.redact?.length?{paths:U.redact}:void 0,createdAt:j,updatedAt:j};if(U.transport==="webhook")N.webhook={url:I,secret:U.secret,headers:ur(U.header),timeoutMs:U.timeoutMs};else if(U.transport==="command")N.command={command:I,args:U.arg??[],timeoutMs:U.timeoutMs};else throw Error(`Transport ${U.transport} is reserved for future use and cannot be added yet`);let A=await $4($).addChannel(N);I0(LY(A),F6(U,E),`Added ${A.transport} channel ${A.id}`)}),D.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(I,U)=>{let E=await $4($).listChannels();if(F6(I,U)){console.log(JSON.stringify(Hr(E),null,2));return}if(!E.length){console.log("No channels configured.");return}for(let j of E)console.log(`${j.id} ${j.enabled?"enabled":"disabled"} ${j.transport} ${j.webhook?.url??j.command?.command??j.transport}`)}),D.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(I,U)=>{let E=await Xr($.dataDir);I0(E,F6(I,U),`events dataDir: ${E.dataDir}`)}),D.command("remove").description("Remove a channel").argument("","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(I,U,E)=>{let j=await $4($).removeChannel(I);I0({removed:j},F6(U,E),j?`Removed ${I}`:`Channel not found: ${I}`)}),D.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(I,U,E)=>{let j=F6(U,E);try{let N=await $4($).testChannel(I,{source:U.source??$.source,type:U.type,subject:U.subject??I,message:U.message,data:kD(U.data,{test:!0}),metadata:kD(U.metadata,{})},{honorFilters:U.honorFilters});I0(N,j,`${N.status}: ${N.channelId}`)}catch(N){UY(N,j)}}),D.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(I,U,E)=>{let j=F6(U,E);try{let N=await $4($).matchChannel(I,{source:U.source??$.source,type:U.type,subject:U.subject??I,message:U.message,data:kD(U.data,{test:!0}),metadata:kD(U.metadata,{})});I0(N,j,`${N.matched?"matched":"skipped"}: ${N.channelId}`)}catch(N){UY(N,j)}}),D}function hr(_,$){let D=_.command($.eventsCommandName??"events").description("Emit, list, and replay Hasna events");D.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(U,E,j)=>{let N=await $4($).emit({source:E.source??$.source,type:U,subject:E.subject,severity:E.severity,message:E.message,dedupeKey:E.dedupeKey,data:kD(E.data,{}),metadata:kD(E.metadata,{})},{deliver:E.deliver,dedupe:E.dedupe});I0(N,F6(E,j),`${N.deduped?"Deduped":"Emitted"} ${N.event.id} to ${N.deliveries.length} channel(s)`)});let I=$.defaultEventListLimit??xr;return D.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 ${I}; use 0 for all)`,w1,I).option("-j, --json","Print JSON output",!1).action(async(U,E)=>{let j=await $4($).listEvents();if(U.source)j=j.filter((N)=>N.source===U.source);if(U.type)j=j.filter((N)=>N.type===U.type);if(U.limit)j=j.slice(-U.limit);if(F6(U,E)){console.log(JSON.stringify(j,null,2));return}if(!j.length){console.log("No events recorded.");return}for(let N of j)console.log(`${N.time} ${N.id} ${N.source} ${N.type} ${N.severity}`)}),D.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",w1).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(U,E)=>{let j=await $4($).replay({eventId:U.id,source:U.source,type:U.type,cursor:U.cursor,limit:U.limit,dryRun:U.dryRun});I0(j,F6(U,E),cr(j.events.length,j.deliveries.length,j.nextCursor))}),D}function WY(_,$){yr(_,$),hr(_,$)}function w1(_){let $=Number(_);if(!Number.isFinite($))throw Error(`Expected a number, got ${_}`);return $}function U0(_,$){return $.push(_),$}function cr(_,$,D){let I=D?`, next cursor: ${D}`:"";return`Replayed ${_} event(s), ${$} delivery result(s)${I}`}import{basename as nr,dirname as dr,join as mr}from"path";var PY={debug:0,info:1,warn:2,error:3},lr=()=>{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 j0(_,$,D){if(PY[_]I.toLowerCase()));return $.filter((I)=>!D.has(I.toLowerCase()))}function bP(_,$,D){if(D===void 0)return{..._,message:$};return{..._,added:D.length,message:`${$} (added ${D.length} tag${D.length===1?"":"s"})`}}function pr(_,$){if($===void 0)throw Error("Missing value for --tag. Example: knowledge add <content> -t <tag> -t <tag>");let D=$.split(",").map((I)=>I.trim()).filter((I)=>I.length>0);if(D.length===0)throw Error(`Invalid --tag value ${JSON.stringify($)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return or([..._??[],...D])}function er(_){let $=[],D={},I=!1;for(let U=0;U<_.length;U+=1){let E=_[U];if(I){$.push(E);continue}if(E==="--"){I=!0;continue}if(!E.startsWith("-")||$[0]==="add"&&$.length===2&&E.startsWith("---")){$.push(E);continue}switch(E){case"--json":D.json=!0;break;case"--verbose":D.verbose=!0;break;case"--yes":case"-y":D.yes=!0;break;case"--help":case"-h":D.help=!0;break;case"--version":case"-v":D.version=!0;break;case"--desc":D.desc=!0;break;case"--page":case"-p":D.page=Number(_[U+1]),U+=1;break;case"--limit":case"-l":D.limit=Number(_[U+1]),U+=1;break;case"--search":case"-s":D.search=_[U+1],U+=1;break;case"--sort":D.sort=_[U+1],U+=1;break;case"--id":D.id=_[U+1],U+=1;break;case"--store":D.store=_[U+1],U+=1;break;case"--title":D.title=_[U+1],U+=1;break;case"--content":D.content=_[U+1],U+=1;break;case"--url":D.url=_[U+1],U+=1;break;case"--tag":case"-t":D.tag=pr(D.tag,_[U+1]),D.tagRaw=[...D.tagRaw??[],_[U+1]],U+=1;break;case"--format":D.format=_[U+1],U+=1;break;case"--completions":D.completions=_[U+1],U+=1;break;case"--purpose":D.purpose=_[U+1],U+=1;break;case"--model":D.model=_[U+1],U+=1;break;case"--strategy":D.strategy=_[U+1],U+=1;break;case"--dimensions":D.dimensions=Number(_[U+1]),U+=1;break;case"--semantic":D.semantic=!0;break;case"--context":D.context=!0;break;case"--max-tokens":D.maxTokens=Number(_[U+1]),U+=1;break;case"--max-items":D.maxItems=Number(_[U+1]),U+=1;break;case"--from":D.from=_[U+1],U+=1;break;case"--to":D.to=_[U+1],U+=1;break;case"--rev":D.rev=Number(_[U+1]),U+=1;break;case"--if-version":D.ifVersion=Number(_[U+1]),U+=1;break;case"--since":D.since=_[U+1],U+=1;break;case"--topic":D.topic=_[U+1],U+=1;break;case"--dedupe":D.dedupe=!0;break;case"--generate":D.generate=!0;break;case"--approve-write":D.approveWrite=!0;break;case"--provider":D.provider=_[U+1],U+=1;break;case"--mode":D.mode=_[U+1],U+=1;break;case"--machine":D.machine=_[U+1],U+=1;break;case"--workspace":D.workspace=_[U+1],U+=1;break;case"--api-url":D.apiUrl=_[U+1],U+=1;break;case"--canonical-example":D.canonicalExample=!0;break;case"--api-key":D.apiKey=_[U+1],U+=1;break;case"--email":D.email=_[U+1],U+=1;break;case"--org":D.org=_[U+1],U+=1;break;case"--org-id":D.orgId=_[U+1],U+=1;break;case"--user-id":D.userId=_[U+1],U+=1;break;case"--owner":D.owner=_[U+1],U+=1;break;case"--approved-by":D.approvedBy=_[U+1],U+=1;break;case"--patch-uri":D.patchUri=_[U+1],U+=1;break;case"--domain":D.domain=[...D.domain??[],_[U+1]],U+=1;break;case"--file-results":D.fileResults=!0;break;case"--full":D.full=!0;break;case"--dry-run":D.dryRun=!0;break;case"--fake":D.fake=!0;break;case"--no-tailscale":D.tailscale=!1;break;case"--no-artifact-content":D.artifactContent=!1;break;case"--no-color":D.noColor=!0;break;case"--scope":D.scope=_[U+1],U+=1;break;case"--tables":D.tables=_[U+1],U+=1;break;case"--peer-workspace":D.peerWorkspace=_[U+1],U+=1;break;case"--older-than":D.olderThan=Number(_[U+1]),U+=1;break;case"--empty":D.empty=!0;break;case"--archived":D.archived=!0;break;case"--include-archived":D.includeArchived=!0;break;case"--project":D.project=_[U+1],U+=1;break;case"--contract":D.contract=!0;break;case"--source-ref":D.sourceRef=[...D.sourceRef??[],_[U+1]],U+=1;break;case"--allow-global":D.allowGlobal=!0;break;case"--operation-id":D.operationId=_[U+1],U+=1;break;case"--step-id":D.stepId=_[U+1],U+=1;break;case"--idempotency-key":D.idempotencyKey=_[U+1],U+=1;break;case"--collection-id":D.collectionId=_[U+1],U+=1;break;case"--item-id":D.itemId=_[U+1],U+=1;break;case"--receipt-id":D.receiptId=_[U+1],U+=1;break;case"--cursor":D.cursor=_[U+1],U+=1;break;case"--kind":D.kind=[...D.kind??[],_[U+1]],U+=1;break;case"--all":D.all=!0;break;case"--slug":D.slug=_[U+1],U+=1;break;case"--name":D.name=_[U+1],U+=1;break;case"--collection-slug":D.collectionSlug=_[U+1],U+=1;break;case"--collection-name":D.collectionName=_[U+1],U+=1;break;default:throw Error(`Unknown flag: ${E}. Run 'knowledge --help' for valid options.`)}}return{positional:$,flags:D}}function ar(_){if(!_)return"";return KY[_]??_}function sr(_,$){let D=Array.from({length:_.length+1},()=>Array($.length+1).fill(0));for(let I=0;I<=_.length;I+=1)D[I][0]=I;for(let I=0;I<=$.length;I+=1)D[0][I]=I;for(let I=1;I<=_.length;I+=1)for(let U=1;U<=$.length;U+=1){let E=_[I-1]===$[U-1]?0:1;D[I][U]=Math.min(D[I-1][U]+1,D[I][U-1]+1,D[I-1][U-1]+E)}return D[_.length][$.length]}function _f(_){if(!_)return"";let $=[...QY,...Object.keys(KY)],D="",I=Number.POSITIVE_INFINITY;for(let U of $){let E=sr(_,U);if(E<I)I=E,D=U}return I<=3?D:""}function $f(){return nr(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function Df(_){if(!YY.includes(_[0]??""))return!1;let $=new i8;return $.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),WY($,{source:"knowledge"}),await $.parseAsync(_,{from:"user"}),!0}function Uf(){console.log(`knowledge - local agent knowledge store + = 'hasna.knowledge.relations.v1'`,...I9()];var l8=bY(m8(),1),{program:Al,createCommand:Ol,createArgument:Sl,createOption:Ll,CommanderError:Wl,InvalidArgumentError:Jl,InvalidOptionArgumentError:Pl,Command:i8,Argument:zl,Option:gl,Help:Xl}=l8.default;import{chmod as Tz,mkdir as Or,readFile as Sr,rename as Lr,writeFile as e8}from"fs/promises";import{Buffer as EY}from"buffer";import{existsSync as jY}from"fs";import{homedir as Wr}from"os";import{join as w1}from"path";import{createHmac as Gr,timingSafeEqual as Vl}from"crypto";import{randomUUID as Qr}from"crypto";import{spawn as Kr}from"child_process";import{randomUUID as Zr}from"crypto";function $r(_,$){return $.split(".").reduce((D,I)=>{if(D&&typeof D==="object"&&I in D)return D[I];return},_)}function Dr(_,$){let D=[],I=(E)=>{if(!D.some((j)=>Object.is(j,E)))D.push(E)};if($.includes(".")&&$ in _)I(_[$]);let U=$r(_,$);if(U!==void 0||!$.includes("."))I(U);return D}function Ur(_,$={}){let D="";for(let I=0;I<_.length;I+=1){let U=_[I];if(U==="*")if(_[I+1]==="*")D+=".*",I+=1;else D+=$.segmentSafe?"[^/]*":".*";else D+=U.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}return new RegExp(`^${D}$`)}function C1(_,$,D={}){if($===void 0)return!0;if(_===void 0)return!1;return(Array.isArray($)?$:[$]).some((U)=>Ur(U,D).test(_))}function t8(_,$){if(!$)return!0;return Object.entries($).every(([D,I])=>{let U=Dr(_,D);return Ir(U,I,D)})}function Ir(_,$,D){if(Nr($))return!_.some((I)=>o8(I,$.not,D));return _.some((I)=>o8(I,$,D))}function o8(_,$,D){if(typeof $==="string"||Array.isArray($))return Er(_).some((I)=>C1(I,$,{segmentSafe:D.endsWith("_path")||D.endsWith(".path")}));if(Array.isArray(_))return _.some((I)=>I===$);return _===$}function Er(_){if(_===void 0)return[];if(Array.isArray(_))return _.flatMap(($)=>jr($)?[String($)]:[]);return[String(_)]}function jr(_){return _===null||typeof _==="string"||typeof _==="number"||typeof _==="boolean"}function Nr(_){return Boolean(_&&typeof _==="object"&&!Array.isArray(_)&&"not"in _)}function Ar(_,$){return C1(_.source,$.source)&&C1(_.type,$.type)&&C1(_.subject,$.subject)&&C1(_.severity,$.severity)&&t8(_.data,$.data)&&t8(_.metadata,$.metadata)}function p8(_,$){if(!_.enabled)return!1;if(!_.filters||_.filters.length===0)return!0;return _.filters.some((D)=>Ar($,D))}var HN="HASNA_EVENTS_DIR",bN="HASNA_EVENTS_HOME",Mz="local-json-v1:",Jr=100,Pr=1000;function NY(_){return _||process.env[HN]||process.env[bN]||w1(Wr(),".hasna","events")}function zr(){if(process.env[HN])return HN;if(process.env[bN])return bN;return null}class qN{dataDir;runtime;channelsPath;eventsPath;deliveriesPath;constructor(_=NY()){this.dataDir=_,this.runtime=gr(_),this.channelsPath=w1(_,"channels.json"),this.eventsPath=w1(_,"events.json"),this.deliveriesPath=w1(_,"deliveries.json")}async init(){await Or(this.dataDir,{recursive:!0,mode:448}),await Tz(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,[]),D=$.findIndex((I)=>I.id===_.id);if(D>=0)$[D]={..._,createdAt:$[D].createdAt,updatedAt:new Date().toISOString()};else $.push(_);return await this.writeJson(this.channelsPath,$),D>=0?$[D]:_}async listChannels(){return await this.init(),this.readJson(this.channelsPath,[])}async getChannel(_){return(await this.listChannels()).find((D)=>D.id===_)}async removeChannel(_){await this.init();let $=await this.readJson(this.channelsPath,[]),D=$.filter((I)=>I.id!==_);return await this.writeJson(this.channelsPath,D),D.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 D=await this.readJson(this.eventsPath,[]);if($.dedupe!==!1){let U=s8(D,{id:_.id,dedupeKey:_.dedupeKey});if(U)return{event:U,stored:!1,deduped:!0,identity:{id:U.id,dedupeKey:U.dedupeKey}}}return D.push(_),await this.writeJson(this.eventsPath,D),{event:_,stored:!0,deduped:!1,identity:{id:_.id,dedupeKey:_.dedupeKey}}}async listEvents(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]);return a8($,_)}async listEventsPage(_={}){await this.init();let $=await this.readJson(this.eventsPath,[]),D=a8($,{eventId:_.eventId,source:_.source,type:_.type}),I=kN(_.cursor,_),U=CN(_.limit),E=D.slice(I,I+U),j=I+E.length,N=j<D.length;return{events:E,cursor:_.cursor,nextCursor:N?AY(j,_):void 0,hasMore:N}}async findEventByIdentity(_){let $=await this.listEvents();return s8($,_)}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(!jY(_))await e8(_,`[] +`,{encoding:"utf-8",mode:384});await Tz(_,384).catch(()=>{return})}async readJson(_,$){try{let D=await Sr(_,"utf-8");if(!D.trim())return $;return JSON.parse(D)}catch(D){if(D.code==="ENOENT")return $;throw D}}async writeJson(_,$){let D=`${_}.${process.pid}.${Date.now()}.tmp`;await e8(D,`${JSON.stringify($,null,2)} +`,{encoding:"utf-8",mode:384}),await Lr(D,_),await Tz(_,384).catch(()=>{return})}}function gr(_=NY()){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 AY(_,$={}){if(!Number.isInteger(_)||_<0)throw Error(`Invalid event cursor offset: ${_}`);let D={offset:_,eventId:$.eventId,source:$.source,type:$.type};return`${Mz}${EY.from(JSON.stringify(D),"utf-8").toString("base64url")}`}function kN(_,$={}){if(!_)return 0;if(!_.startsWith(Mz))throw Error(`Invalid local JSON event cursor: ${_}`);let D=_.slice(Mz.length),I;try{I=JSON.parse(EY.from(D,"base64url").toString("utf-8"))}catch{throw Error(`Invalid local JSON event cursor: ${_}`)}let U=I.offset;if(!Number.isInteger(U)||U<0)throw Error(`Invalid local JSON event cursor: ${_}`);return Fz("eventId",I.eventId,$.eventId),Fz("source",I.source,$.source),Fz("type",I.type,$.type),U}function CN(_){if(_===void 0)return Jr;if(!Number.isInteger(_)||_<1)throw Error(`Event page limit must be a positive integer, got ${_}`);return Math.min(_,Pr)}function a8(_,$){let D=_;if($.eventId)D=D.filter((I)=>I.id===$.eventId);if($.source)D=D.filter((I)=>I.source===$.source);if($.type)D=D.filter((I)=>I.type===$.type);if($.cursor){let I=kN($.cursor,$);D=D.slice(I)}if($.limit!==void 0)D=D.slice(0,CN($.limit));return D}function Fz(_,$,D){if($!==D)throw Error(`Local JSON event cursor ${_} filter mismatch`)}function s8(_,$){return _.find((D)=>$.id!==void 0&&D.id===$.id||$.dedupeKey!==void 0&&D.dedupeKey===$.dedupeKey)}async function Xr(_){let $=new qN(_);await $.init();let[D,I,U]=await Promise.all([$.listChannels(),$.listEvents(),$.listDeliveries()]),E=D.reduce((j,N)=>{return j[N.transport]=(j[N.transport]??0)+1,j},{});return{service:"events",schemaVersion:"1.0",dataDir:$.dataDir,storage:$.runtime,env:{primary:HN,fallback:bN,active:zr()},files:{channels:Vz($.dataDir,"channels.json",D.length),events:Vz($.dataDir,"events.json",I.length),deliveries:Vz($.dataDir,"deliveries.json",U.length)},counts:{channels:D.length,enabledChannels:D.filter((j)=>j.enabled).length,disabledChannels:D.filter((j)=>!j.enabled).length,events:I.length,deliveries:U.length},transports:E,safety:{includesEventPayloads:!1,includesWebhookSecrets:!1,listOutputsRedactSecrets:!0,statusOutputIsMetadataOnly:!0}}}function Vz(_,$,D){let I=w1(_,$);return{path:I,exists:jY(I),records:D}}function Rr(_,$){return`${_}.${$}`}function Yr(_,$,D){return`sha256=${Gr("sha256",_).update(Rr($,D)).digest("hex")}`}function a$(){return new Date().toISOString()}function v1(_,$=4096){return _.length>$?`${_.slice(0,$)}...`:_}function Tr(_,$){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let D=JSON.stringify(_),I=_.time,U={"Content-Type":"application/json","User-Agent":"@hasna/events","X-Hasna-Event-Id":_.id,"X-Hasna-Event-Type":_.type,"X-Hasna-Timestamp":I,...$.webhook.headers};if($.webhook.secret)U["X-Hasna-Signature"]=Yr($.webhook.secret,I,D);return{body:D,headers:U}}async function Fr(_,$,D={}){if(!$.webhook)throw Error(`Channel ${$.id} has no webhook config`);let I=a$(),{body:U,headers:E}=Tr(_,$),j=new AbortController,N=setTimeout(()=>j.abort(),$.webhook.timeoutMs??15000);try{let O=await(D.fetchImpl??fetch)($.webhook.url,{method:"POST",headers:E,body:U,signal:j.signal}),S=v1(await O.text());return{attempt:1,status:O.ok?"success":"failed",startedAt:I,completedAt:a$(),responseStatus:O.status,responseBody:S,error:O.ok?void 0:`Webhook returned HTTP ${O.status}`}}catch(O){return{attempt:1,status:"failed",startedAt:I,completedAt:a$(),error:O instanceof Error?O.message:String(O)}}finally{clearTimeout(N)}}async function Vr(_,$){if(!$.command)throw Error(`Channel ${$.id} has no command config`);let D=a$(),I=JSON.stringify(_),U={...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:I};return new Promise((E)=>{let j=Kr($.command.command,$.command.args??[],{cwd:$.command.cwd,env:U,stdio:["pipe","pipe","pipe"]}),N="",O="",S=setTimeout(()=>j.kill("SIGTERM"),$.command.timeoutMs??15000);j.stdin.end(I),j.stdout.on("data",(L)=>{N+=L.toString()}),j.stderr.on("data",(L)=>{O+=L.toString()}),j.on("error",(L)=>{clearTimeout(S),E({attempt:1,status:"failed",startedAt:D,completedAt:a$(),stdout:v1(N),stderr:v1(O),error:L.message})}),j.on("close",(L,W)=>{clearTimeout(S);let g=L===0;E({attempt:1,status:g?"success":"failed",startedAt:D,completedAt:a$(),stdout:v1(N),stderr:v1(O),error:g?void 0:`Command exited with ${W?`signal ${W}`:`code ${L}`}`})})})}async function Br(_,$,D={}){if($.transport==="webhook")return Fr(_,$,D);if($.transport==="command")return Vr(_,$);return{attempt:1,status:"skipped",startedAt:a$(),completedAt:a$(),error:`Unsupported transport: ${$.transport}`}}function _Y(_,$,D){let I=D.some((U)=>U.status==="success")?"success":D.every((U)=>U.status==="skipped")?"skipped":"failed";return{id:Qr(),eventId:_.id,channelId:$.id,transport:$.transport,status:I,attempts:D,createdAt:D[0]?.startedAt??a$(),completedAt:D.at(-1)?.completedAt??a$()}}class OY extends Error{eventType;issues;constructor(_,$){let D=$.map((I)=>`${I.path||"<root>"}: ${I.message}`).join("; ");super(`Event validation failed for type "${_}": ${D}`);this.name="EventValidationError",this.eventType=_,this.issues=$}}class SY{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 OY(_.type,$.issues)}}var Mr=new SY;function Bz(_){return{id:_.id??Zr(),source:_.source,type:_.type,time:Cr(_.time),subject:_.subject,severity:_.severity??"info",data:_.data??{},message:_.message,dedupeKey:_.dedupeKey,schemaVersion:_.schemaVersion??"1.0",metadata:_.metadata??{}}}class LY{store;redactors;transportOptions;catalog;validateCatalogTypes;constructor(_={}){this.store=_.store??new qN(_.dataDir),this.redactors=_.redactors??[],this.transportOptions={fetchImpl:_.fetchImpl},this.catalog=_.catalog??Mr,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 D=$.redactSensitiveData===!1?Bz(_):qr(Bz(_));if($.validate??this.validateCatalogTypes)this.catalog.assertEventValid(D);let I=await this.appendEvent(D,{dedupe:$.dedupe!==!1});if(I.deduped)return{event:I.event,deliveries:[],deduped:!0};let U=$.deliver===!1?[]:await this.deliver(I.event);return{event:I.event,deliveries:U,deduped:!1}}async listEvents(_={}){if(Object.keys(_).length===0)return this.store.listEvents();return $Y(await this.store.listEvents(),_)}async listEventsPage(_={}){if(this.store.listEventsPage)return this.store.listEventsPage(_);let $=$Y(await this.store.listEvents(),{eventId:_.eventId,source:_.source,type:_.type}),D=kN(_.cursor,_),I=CN(_.limit),U=$.slice(D,D+I),E=D+U.length,j=E<$.length;return{events:U,cursor:_.cursor,nextCursor:j?AY(E,_):void 0,hasMore:j}}async listDeliveries(){return this.store.listDeliveries()}async deliver(_){let D=(await this.store.listChannels()).filter((U)=>p8(U,_)),I=[];for(let U of D){let E=await this.applyRedaction(_,U),j=await this.deliverWithRetry(E,U);await this.store.appendDelivery(j),I.push(j)}return I}async matchChannel(_,$={}){let D=await this.store.getChannel(_);if(!D)throw Error(`Channel not found: ${_}`);let I=Bz({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}),U=p8(D,I);return{channelId:D.id,matched:U,event:I,filters:D.filters,reason:U?void 0:D.enabled?"event did not match channel filters":"channel is disabled"}}async testChannel(_,$={},D={}){let I=await this.store.getChannel(_);if(!I)throw Error(`Channel not found: ${_}`);let U=await this.matchChannel(_,$),E=U.event;if(D.honorFilters&&!U.matched){let O=new Date().toISOString(),S=_Y(E,I,[{attempt:1,status:"skipped",startedAt:O,completedAt:O,error:U.reason}]);return S.metadata={reason:"filter_mismatch"},await this.store.appendDelivery(S),S}let j=await this.applyRedaction(E,I),N=await this.deliverWithRetry(j,I);return await this.store.appendDelivery(N),N}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 D=[];for(let I of $.events)D.push(...await this.deliver(I));return{events:$.events,deliveries:D,cursor:$.cursor,nextCursor:$.nextCursor,hasMore:$.hasMore}}async appendEvent(_,$){if(this.store.appendEventOnce)return this.store.appendEventOnce(_,{dedupe:$.dedupe});if($.dedupe){let I=await this.store.findEventByIdentity({id:_.id,dedupeKey:_.dedupeKey});if(I)return{event:I,stored:!1,deduped:!0,identity:{id:I.id,dedupeKey:I.dedupeKey}}}let D=await this.store.appendEvent(_);return{event:D,stored:!0,deduped:!1,identity:{id:D.id,dedupeKey:D.dedupeKey}}}async applyRedaction(_,$){let D=Hr(_,$.redact?.paths??[],$.redact?.replacement??"[REDACTED]");for(let I of this.redactors)D=await I(D,$);return D}async deliverWithRetry(_,$){let D=vr($.retry),I=[];for(let U=0;U<D.maxAttempts;U+=1){let E=await Br(_,$,this.transportOptions);if(E.attempt=U+1,E.status==="failed"&&U+1<D.maxAttempts)E.nextBackoffMs=Math.round(D.backoffMs*D.multiplier**U);if(I.push(E),E.status!=="failed")break;if(E.nextBackoffMs)await Bun.sleep(E.nextBackoffMs)}return _Y(_,$,I)}}function Hr(_,$,D="[REDACTED]"){if($.length===0)return _;let I=structuredClone(_);for(let U of $)kr(I,U,D);return I}function WY(_){let $=structuredClone(_);if($.webhook?.secret)$.webhook.secret="[REDACTED]";if($.command?.env)$.command.env=Object.fromEntries(Object.entries($.command.env).map(([D,I])=>[D,JY(D)?"[REDACTED]":I]));return $}function br(_){return _.map(WY)}function qr(_,$="[REDACTED]"){return Zz(_,$)}function JY(_){return/secret|token|password|api[_-]?key|authorization/i.test(_)}function Zz(_,$){if(Array.isArray(_))return _.map((D)=>Zz(D,$));if(!_||typeof _!=="object")return _;return Object.fromEntries(Object.entries(_).map(([D,I])=>[D,JY(D)?$:Zz(I,$)]))}function kr(_,$,D){let I=$.split("."),U=_;for(let j of I.slice(0,-1)){let N=U[j];if(!N||typeof N!=="object")return;U=N}let E=I.at(-1);if(E&&E in U)U[E]=D}function $Y(_,$){let D=_;if($.eventId)D=D.filter((I)=>I.id===$.eventId);if($.source)D=D.filter((I)=>I.source===$.source);if($.type)D=D.filter((I)=>I.type===$.type);if($.cursor)D=D.slice(kN($.cursor,$));if($.limit!==void 0)D=D.slice(0,CN($.limit));return D}function Cr(_){if(!_)return new Date().toISOString();return _ instanceof Date?_.toISOString():_}function vr(_){return{maxAttempts:Math.max(1,_?.maxAttempts??1),backoffMs:Math.max(0,_?.backoffMs??250),multiplier:Math.max(1,_?.multiplier??2)}}function ZN(_,$,D=!1){if(!_?.length)return;let I={};for(let U of _){let E=fr(U,$),j=E.path;if(j in I)throw Error(`Duplicate ${$} filter path: ${j}`);let N=D?rr(E.rawValue,$):E.rawValue;I[j]=E.negated?{not:N}:N}return I}function wr(_){let $={};if(_.source)$.source=_.source;if(_.type)$.type=_.type;if(_.subject)$.subject=_.subject;if(_.severity)$.severity=_.severity;let D=DY(ZN(_.data,"data"),ZN(_.dataJson,"data-json",!0)),I=DY(ZN(_.metadata,"metadata"),ZN(_.metadataJson,"metadata-json",!0));if(Object.keys(D).length>0)$.data=D;if(Object.keys(I).length>0)$.metadata=I;return Object.keys($).length>0?[$]:void 0}function DY(..._){let $={};for(let D of _){if(!D)continue;for(let[I,U]of Object.entries(D)){if(I in $)throw Error(`Duplicate filter path: ${I}`);$[I]=U}}return $}function rr(_,$){let D=JSON.parse(_);if(D===null||typeof D==="string"||typeof D==="number"||typeof D==="boolean"||Array.isArray(D)&&D.every((I)=>typeof I==="string"))return D;throw Error(`${$} filter JSON values must be string, string[], number, boolean, or null`)}function fr(_,$){let D=_.indexOf("!=");if(D>0)return{path:_.slice(0,D),rawValue:_.slice(D+2),negated:!0};let I=_.indexOf("=");if(I<=0)throw Error(`Invalid ${$} filter, expected path=value or path!=value: ${_}`);return{path:_.slice(0,I),rawValue:_.slice(I+1),negated:!1}}var xr=100;function qD(_,$){if(!_)return $;let D=JSON.parse(_);if(!D||typeof D!=="object"||Array.isArray(D))throw Error("Expected a JSON object");return D}function ur(_){if(!_?.length)return;let $={};for(let D of _){let I=D.indexOf("=");if(I===-1)throw Error(`Invalid header, expected name=value: ${D}`);$[D.slice(0,I)]=D.slice(I+1)}return $}function D4(_){if(_.createClient)return _.createClient();return new LY({store:new qN(_.dataDir)})}function j0(_,$,D){if($)console.log(JSON.stringify(_,null,2));else console.log(D)}function UY(_,$){let D=_ instanceof Error?_.message:String(_);if($)console.log(JSON.stringify({error:D},null,2));else console.error(D);process.exitCode=1}function IY(_){return Boolean(_?.json||_?.opts?.().json||_?.optsWithGlobals?.().json||_?.parent?.opts?.().json||_?.parent?.optsWithGlobals?.().json)}function F6(_,$){return IY(_)||IY($)}function yr(_,$){let D=_.command($.channelsCommandName??"channels").description("Manage Hasna event channels");return D.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",E0,[]).option("--metadata <path=value...>","Event metadata field filter; string values, path!=value negatives, array-member matching, dot paths, * segment wildcard, ** recursive wildcard",E0,[]).option("--data-json <path=json...>","Event data field filter with typed JSON value; path!=json negatives supported",E0,[]).option("--metadata-json <path=json...>","Event metadata field filter with typed JSON value; path!=json negatives supported",E0,[]).option("--secret <secret>","Webhook HMAC secret").option("--header <name=value...>","Webhook header",E0,[]).option("--arg <arg...>","Command argument",E0,[]).option("--timeout-ms <ms>","Transport timeout in milliseconds",r1).option("--retry-attempts <n>","Maximum delivery attempts",r1).option("--retry-backoff-ms <ms>","Initial retry backoff in milliseconds",r1).option("--redact <path...>","Event field path to redact before delivery",E0,[]).option("--disabled","Create channel disabled",!1).option("-j, --json","Print JSON output",!1).action(async(I,U,E)=>{let j=new Date().toISOString(),N={id:U.id,name:U.name,enabled:!U.disabled,transport:U.transport,filters:wr(U),retry:U.retryAttempts||U.retryBackoffMs?{maxAttempts:U.retryAttempts,backoffMs:U.retryBackoffMs}:void 0,redact:U.redact?.length?{paths:U.redact}:void 0,createdAt:j,updatedAt:j};if(U.transport==="webhook")N.webhook={url:I,secret:U.secret,headers:ur(U.header),timeoutMs:U.timeoutMs};else if(U.transport==="command")N.command={command:I,args:U.arg??[],timeoutMs:U.timeoutMs};else throw Error(`Transport ${U.transport} is reserved for future use and cannot be added yet`);let O=await D4($).addChannel(N);j0(WY(O),F6(U,E),`Added ${O.transport} channel ${O.id}`)}),D.command("list").description("List configured channels").option("-j, --json","Print JSON output",!1).action(async(I,U)=>{let E=await D4($).listChannels();if(F6(I,U)){console.log(JSON.stringify(br(E),null,2));return}if(!E.length){console.log("No channels configured.");return}for(let j of E)console.log(`${j.id} ${j.enabled?"enabled":"disabled"} ${j.transport} ${j.webhook?.url??j.command?.command??j.transport}`)}),D.command("status").description("Show events channel storage status").option("-j, --json","Print JSON output",!1).action(async(I,U)=>{let E=await Xr($.dataDir);j0(E,F6(I,U),`events dataDir: ${E.dataDir}`)}),D.command("remove").description("Remove a channel").argument("<id>","Channel identifier").option("-j, --json","Print JSON output",!1).action(async(I,U,E)=>{let j=await D4($).removeChannel(I);j0({removed:j},F6(U,E),j?`Removed ${I}`:`Channel not found: ${I}`)}),D.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(I,U,E)=>{let j=F6(U,E);try{let N=await D4($).testChannel(I,{source:U.source??$.source,type:U.type,subject:U.subject??I,message:U.message,data:qD(U.data,{test:!0}),metadata:qD(U.metadata,{})},{honorFilters:U.honorFilters});j0(N,j,`${N.status}: ${N.channelId}`)}catch(N){UY(N,j)}}),D.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(I,U,E)=>{let j=F6(U,E);try{let N=await D4($).matchChannel(I,{source:U.source??$.source,type:U.type,subject:U.subject??I,message:U.message,data:qD(U.data,{test:!0}),metadata:qD(U.metadata,{})});j0(N,j,`${N.matched?"matched":"skipped"}: ${N.channelId}`)}catch(N){UY(N,j)}}),D}function hr(_,$){let D=_.command($.eventsCommandName??"events").description("Emit, list, and replay Hasna events");D.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(U,E,j)=>{let N=await D4($).emit({source:E.source??$.source,type:U,subject:E.subject,severity:E.severity,message:E.message,dedupeKey:E.dedupeKey,data:qD(E.data,{}),metadata:qD(E.metadata,{})},{deliver:E.deliver,dedupe:E.dedupe});j0(N,F6(E,j),`${N.deduped?"Deduped":"Emitted"} ${N.event.id} to ${N.deliveries.length} channel(s)`)});let I=$.defaultEventListLimit??xr;return D.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 ${I}; use 0 for all)`,r1,I).option("-j, --json","Print JSON output",!1).action(async(U,E)=>{let j=await D4($).listEvents();if(U.source)j=j.filter((N)=>N.source===U.source);if(U.type)j=j.filter((N)=>N.type===U.type);if(U.limit)j=j.slice(-U.limit);if(F6(U,E)){console.log(JSON.stringify(j,null,2));return}if(!j.length){console.log("No events recorded.");return}for(let N of j)console.log(`${N.time} ${N.id} ${N.source} ${N.type} ${N.severity}`)}),D.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",r1).option("--dry-run","Preview without delivery",!1).option("-j, --json","Print JSON output",!1).action(async(U,E)=>{let j=await D4($).replay({eventId:U.id,source:U.source,type:U.type,cursor:U.cursor,limit:U.limit,dryRun:U.dryRun});j0(j,F6(U,E),cr(j.events.length,j.deliveries.length,j.nextCursor))}),D}function PY(_,$){yr(_,$),hr(_,$)}function r1(_){let $=Number(_);if(!Number.isFinite($))throw Error(`Expected a number, got ${_}`);return $}function E0(_,$){return $.push(_),$}function cr(_,$,D){let I=D?`, next cursor: ${D}`:"";return`Replayed ${_} event(s), ${$} delivery result(s)${I}`}import{basename as nr,dirname as dr,join as mr}from"path";var zY={debug:0,info:1,warn:2,error:3},lr=()=>{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 A0(_,$,D){if(zY[_]<zY[lr()])return;let I={debug:"[DEBUG]",info:"[INFO]",warn:"[WARN]",error:"[ERROR]"}[_],U=D?`${I} ${$} ${JSON.stringify(D)}`:`${I} ${$}`;if(_==="error")console.error(U);else console.error(U)}var YY=["events","webhooks"],QY=["add","list","get","delete","update","archive","restore","upsert","untag","versions","diff","export","prune","dedupe","stats","inventory","project-panel","project-registration","project-membership","project-resources","project-resource","paths","mode","guarded","setup","auth","storage","machines","sync","db","wiki","app-wiki","source","ingest","reindex","search","context","proposals","web","ask","build","embeddings","providers","safety","help",...YY],KY={ls:"list",rm:"delete",edit:"update",unarchive:"restore"},ir=/^k_[A-Za-z0-9][A-Za-z0-9_-]*$/;async function tr(_,$,D){if(/\s/.test($))return!0;if(_.length<=1)return!1;let I=_[1]??"";if(ir.test(I))return!1;return await D.get(I)===null}function or(_){let $=new Set,D=[];for(let I of _){let U=I.toLowerCase();if($.has(U))continue;$.add(U),D.push(I)}return D}function gY(_,$){let D=new Set((_??[]).map((I)=>I.toLowerCase()));return $.filter((I)=>!D.has(I.toLowerCase()))}function Hz(_,$,D){if(D===void 0)return{..._,message:$};return{..._,added:D.length,message:`${$} (added ${D.length} tag${D.length===1?"":"s"})`}}function pr(_,$){if($===void 0)throw Error("Missing value for --tag. Example: knowledge add <title> <content> -t <tag> -t <tag>");let D=$.split(",").map((I)=>I.trim()).filter((I)=>I.length>0);if(D.length===0)throw Error(`Invalid --tag value ${JSON.stringify($)}: no tag name found. Example: knowledge add <title> <content> -t <tag> -t <tag>`);return or([..._??[],...D])}function er(_){let $=[],D={},I=!1;for(let U=0;U<_.length;U+=1){let E=_[U];if(I){$.push(E);continue}if(E==="--"){I=!0;continue}if(!E.startsWith("-")||$[0]==="add"&&$.length===2&&E.startsWith("---")){$.push(E);continue}switch(E){case"--json":D.json=!0;break;case"--verbose":D.verbose=!0;break;case"--yes":case"-y":D.yes=!0;break;case"--help":case"-h":D.help=!0;break;case"--version":case"-v":D.version=!0;break;case"--desc":D.desc=!0;break;case"--page":case"-p":D.page=Number(_[U+1]),U+=1;break;case"--limit":case"-l":D.limit=Number(_[U+1]),U+=1;break;case"--search":case"-s":D.search=_[U+1],U+=1;break;case"--sort":D.sort=_[U+1],U+=1;break;case"--id":D.id=_[U+1],U+=1;break;case"--store":D.store=_[U+1],U+=1;break;case"--title":D.title=_[U+1],U+=1;break;case"--content":D.content=_[U+1],U+=1;break;case"--url":D.url=_[U+1],U+=1;break;case"--tag":case"-t":D.tag=pr(D.tag,_[U+1]),D.tagRaw=[...D.tagRaw??[],_[U+1]],U+=1;break;case"--format":D.format=_[U+1],U+=1;break;case"--completions":D.completions=_[U+1],U+=1;break;case"--purpose":D.purpose=_[U+1],U+=1;break;case"--model":D.model=_[U+1],U+=1;break;case"--strategy":D.strategy=_[U+1],U+=1;break;case"--dimensions":D.dimensions=Number(_[U+1]),U+=1;break;case"--semantic":D.semantic=!0;break;case"--context":D.context=!0;break;case"--max-tokens":D.maxTokens=Number(_[U+1]),U+=1;break;case"--max-items":D.maxItems=Number(_[U+1]),U+=1;break;case"--from":D.from=_[U+1],U+=1;break;case"--to":D.to=_[U+1],U+=1;break;case"--rev":D.rev=Number(_[U+1]),U+=1;break;case"--if-version":D.ifVersion=Number(_[U+1]),U+=1;break;case"--since":D.since=_[U+1],U+=1;break;case"--topic":D.topic=_[U+1],U+=1;break;case"--dedupe":D.dedupe=!0;break;case"--generate":D.generate=!0;break;case"--approve-write":D.approveWrite=!0;break;case"--provider":D.provider=_[U+1],U+=1;break;case"--mode":D.mode=_[U+1],U+=1;break;case"--machine":D.machine=_[U+1],U+=1;break;case"--workspace":D.workspace=_[U+1],U+=1;break;case"--api-url":D.apiUrl=_[U+1],U+=1;break;case"--canonical-example":D.canonicalExample=!0;break;case"--api-key":D.apiKey=_[U+1],U+=1;break;case"--email":D.email=_[U+1],U+=1;break;case"--org":D.org=_[U+1],U+=1;break;case"--org-id":D.orgId=_[U+1],U+=1;break;case"--user-id":D.userId=_[U+1],U+=1;break;case"--owner":D.owner=_[U+1],U+=1;break;case"--approved-by":D.approvedBy=_[U+1],U+=1;break;case"--patch-uri":D.patchUri=_[U+1],U+=1;break;case"--domain":D.domain=[...D.domain??[],_[U+1]],U+=1;break;case"--file-results":D.fileResults=!0;break;case"--full":D.full=!0;break;case"--dry-run":D.dryRun=!0;break;case"--fake":D.fake=!0;break;case"--no-tailscale":D.tailscale=!1;break;case"--no-artifact-content":D.artifactContent=!1;break;case"--no-color":D.noColor=!0;break;case"--scope":D.scope=_[U+1],U+=1;break;case"--tables":D.tables=_[U+1],U+=1;break;case"--peer-workspace":D.peerWorkspace=_[U+1],U+=1;break;case"--older-than":D.olderThan=Number(_[U+1]),U+=1;break;case"--empty":D.empty=!0;break;case"--archived":D.archived=!0;break;case"--include-archived":D.includeArchived=!0;break;case"--project":D.project=_[U+1],U+=1;break;case"--contract":D.contract=!0;break;case"--source-ref":D.sourceRef=[...D.sourceRef??[],_[U+1]],U+=1;break;case"--allow-global":D.allowGlobal=!0;break;case"--operation-id":D.operationId=_[U+1],U+=1;break;case"--step-id":D.stepId=_[U+1],U+=1;break;case"--idempotency-key":D.idempotencyKey=_[U+1],U+=1;break;case"--collection-id":D.collectionId=_[U+1],U+=1;break;case"--item-id":D.itemId=_[U+1],U+=1;break;case"--receipt-id":D.receiptId=_[U+1],U+=1;break;case"--cursor":D.cursor=_[U+1],U+=1;break;case"--kind":D.kind=[...D.kind??[],_[U+1]],U+=1;break;case"--all":D.all=!0;break;case"--slug":D.slug=_[U+1],U+=1;break;case"--name":D.name=_[U+1],U+=1;break;case"--collection-slug":D.collectionSlug=_[U+1],U+=1;break;case"--collection-name":D.collectionName=_[U+1],U+=1;break;default:throw Error(`Unknown flag: ${E}. Run 'knowledge --help' for valid options.`)}}return{positional:$,flags:D}}function ar(_){if(!_)return"";return KY[_]??_}function sr(_,$){let D=Array.from({length:_.length+1},()=>Array($.length+1).fill(0));for(let I=0;I<=_.length;I+=1)D[I][0]=I;for(let I=0;I<=$.length;I+=1)D[0][I]=I;for(let I=1;I<=_.length;I+=1)for(let U=1;U<=$.length;U+=1){let E=_[I-1]===$[U-1]?0:1;D[I][U]=Math.min(D[I-1][U]+1,D[I][U-1]+1,D[I-1][U-1]+E)}return D[_.length][$.length]}function _f(_){if(!_)return"";let $=[...QY,...Object.keys(KY)],D="",I=Number.POSITIVE_INFINITY;for(let U of $){let E=sr(_,U);if(E<I)I=E,D=U}return I<=3?D:""}function $f(){return nr(process.argv[1]??"").replace(/\.(?:js|ts|mjs|cjs)$/,"")==="knowledge"}async function Df(_){if(!YY.includes(_[0]??""))return!1;let $=new i8;return $.name("knowledge").description("Agent-friendly local knowledge CLI with JSON output, pagination, and safe destructive actions"),PY($,{source:"knowledge"}),await $.parseAsync(_,{from:"user"}),!0}function Uf(){console.log(`knowledge - local agent knowledge store Usage: knowledge <command> [options] @@ -2959,7 +3062,7 @@ Prune Options: 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 ${$6[0]}=sqlite|postgres. Setting only - ${d1[0]} / ${m1[0]} does NOT switch backends; + ${m1[0]} / ${l1[0]} does NOT switch backends; those are reported as present-but-ignored pointers. Env var NAMES are printed, never values.`);return}if(_==="guarded"){console.log(`Usage: knowledge guarded capabilities [--json] Reports metadata-only FCAME-1 private input, private result, and exact-title lookup support.`);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] @@ -2967,22 +3070,22 @@ Prune Options: 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}Uf()}function Ef(_){if(_.noColor||process.env.NO_COLOR)return!1;if(process.env.FORCE_COLOR)return!0;return process.stdout.isTTY===!0}function k(_,$,D){if($){console.log(JSON.stringify(_,null,2));return}if(typeof _==="string"){console.log(_);return}if(D?.verbose){console.log(JSON.stringify(_,null,2));return}let I=_.message;console.log(I?`${I} ${i_()}`:jf(_))}function i_(_="full details"){return`Hint: use --verbose for ${_}, or --json for machine-readable output.`}function I_(_,$=120){let D=_===null||_===void 0?"":String(_).replace(/\s+/g," ").trim();if(D.length<=$)return D;return`${D.slice(0,Math.max(0,$-3))}...`}function jf(_){if(!_||typeof _!=="object")return String(_);let $=_,D=[$.ok===!1?"Result: not ok":"Result: ok"];for(let[I,U]of Object.entries($).slice(0,8)){if(I==="ok"||I==="message")continue;if(Array.isArray(U))D.push(`${I}: ${U.length} item(s)`);else if(U&&typeof U==="object")D.push(`${I}: ${Object.keys(U).length} field(s)`);else D.push(`${I}: ${I_(U,100)}`)}return D.push(i_()),D.join(` `)}function Nf(_){let $=_.mode==="postgres"?"postgres (HTTP /v1 API)":"sqlite (on-box store)",D=_.source.kind==="env"?`selected by ${_.source.name}=${_.source.value}`:`default (no mode var set; set ${$6[0]}=postgres to use the API)`,I=[`Knowledge mode: ${$}`,` ${D}`];if(_.pointer_env_present.length>0){let U=_.pointer_ignored?"present but IGNORED for mode selection":"present";I.push(` Pointer env ${U}: ${_.pointer_env_present.join(", ")}`)}if(_.network_guard_active)I.push(" Outbound guard: ACTIVE (NODE_ENV=test) \u2014 non-loopback requests are refused.");if(_.warning)I.push(` Note: ${_.warning}`);return I.join(` -`)}function gf(_){return[`Knowledge paths (${_.scope})`,`Home: ${_.home}`,`SQLite: ${_.knowledge_db_path}`,`JSON store: ${_.json_store_path}`,`Wiki: ${_.wiki_dir}`,i_("config and all paths")].join(` -`)}function XY(_){console.log(JSON.stringify(_))}function Af(_){let $=_.summary,D=[`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)`],I=(U,E,j)=>{if(E.length===0)return;D.push("",`${U}:`);for(let N of E.slice(0,_.limit))D.push(`- ${j(N)}`)};return I("Items",_.items,(U)=>`${U.id}: ${U.title}`),I("Sources",_.sources,(U)=>`${U.kind??"source"} ${U.uri} (${U.chunks??0} chunk(s))`),I("Chunks",_.chunks,(U)=>`${U.kind??"chunk"} ${U.id}: ${U.text_preview??""}`),I("Wiki pages",_.wiki_pages,(U)=>`${U.path}: ${U.title}`),I("Indexes",_.indexes,(U)=>`${U.kind??"index"} ${U.name}${U.shard_key?` (${U.shard_key})`:""}`),I("Artifacts",_.storage_objects,(U)=>`${U.kind??"artifact"} ${U.artifact_uri}`),I("Runs",_.runs,(U)=>`${U.type??"run"} ${U.id}: ${U.status??"unknown"}`),I("Machines",_.machines,(U)=>`${U.machine_id}${U.workspace_home?` ${U.workspace_home}`:""}`),I("Sync conflicts",_.sync_conflicts,(U)=>`${U.id}: ${U.entity_kind}/${U.entity_id} ${U.status}`),D.join(` -`)}function Of(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} search result(s) for "${I_(_.query,80)}"${_.mode?.semantic?" (semantic enabled)":""}`];for(let I of $.slice(0,_.limit??10)){let U=I.source?.uri??I.provenance?.source_uri??I.artifact?.path??I.artifact?.uri??I.id,E=typeof I.score==="number"?` score=${I.score.toFixed(3)}`:"";if(D.push(`- ${I.kind??"result"} ${I_(I.title??I.id,80)}${E}`),U)D.push(` source: ${I_(U,120)}`);if(I.text)D.push(` text: ${I_(I.text,180)}`)}if($.length===0)D.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(D.push(i_("scores, provenance, and full result objects")),!_.context)D.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return D.join(` -`)}function Sf(_){let $=Array.isArray(_.excerpts)?_.excerpts:[],D=Array.isArray(_.citations)?_.citations:[],I=[`${$.length} context excerpt(s) for "${I_(_.query??_.normalized_query,80)}"`];for(let U of $.slice(0,10)){let E=D.find((A)=>A.id===U.citation_id||A.result_id===U.result_id),j=E?.source_uri??E?.artifact_path??U.result_id,N=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(I.push(`- ${U.kind??"excerpt"} ${I_(U.id,44)}${N}`),j)I.push(` source: ${I_(j,120)}`);I.push(` text: ${I_(U.text,220)}`)}return I.push(`Citations: ${D.length}`),I.push(i_("citations, graph, notes, and full excerpts")),I.join(` -`)}function Lf(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} semantic result(s) for "${I_(_.query,80)}"`,`Index: ${_.provider??"unknown"}:${_.model??"unknown"} (${_.dimensions??"?"} dimensions)`];for(let I of $.slice(0,_.limit??10)){let U=typeof I.score==="number"?` score=${I.score.toFixed(3)}`:"";if(D.push(`- ${I_(I.chunk_id,44)}${U}`),I.source_uri)D.push(` source: ${I_(I.source_uri,120)}`);if(I.text)D.push(` text: ${I_(I.text,180)}`)}return D.push(i_("provenance and full vector result objects")),D.join(` +`)}function Af(_){return[`Knowledge paths (${_.scope})`,`Home: ${_.home}`,`SQLite: ${_.knowledge_db_path}`,`JSON store: ${_.json_store_path}`,`Wiki: ${_.wiki_dir}`,i_("config and all paths")].join(` +`)}function XY(_){console.log(JSON.stringify(_))}function Of(_){let $=_.summary,D=[`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)`],I=(U,E,j)=>{if(E.length===0)return;D.push("",`${U}:`);for(let N of E.slice(0,_.limit))D.push(`- ${j(N)}`)};return I("Items",_.items,(U)=>`${U.id}: ${U.title}`),I("Sources",_.sources,(U)=>`${U.kind??"source"} ${U.uri} (${U.chunks??0} chunk(s))`),I("Chunks",_.chunks,(U)=>`${U.kind??"chunk"} ${U.id}: ${U.text_preview??""}`),I("Wiki pages",_.wiki_pages,(U)=>`${U.path}: ${U.title}`),I("Indexes",_.indexes,(U)=>`${U.kind??"index"} ${U.name}${U.shard_key?` (${U.shard_key})`:""}`),I("Artifacts",_.storage_objects,(U)=>`${U.kind??"artifact"} ${U.artifact_uri}`),I("Runs",_.runs,(U)=>`${U.type??"run"} ${U.id}: ${U.status??"unknown"}`),I("Machines",_.machines,(U)=>`${U.machine_id}${U.workspace_home?` ${U.workspace_home}`:""}`),I("Sync conflicts",_.sync_conflicts,(U)=>`${U.id}: ${U.entity_kind}/${U.entity_id} ${U.status}`),D.join(` +`)}function Sf(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} search result(s) for "${I_(_.query,80)}"${_.mode?.semantic?" (semantic enabled)":""}`];for(let I of $.slice(0,_.limit??10)){let U=I.source?.uri??I.provenance?.source_uri??I.artifact?.path??I.artifact?.uri??I.id,E=typeof I.score==="number"?` score=${I.score.toFixed(3)}`:"";if(D.push(`- ${I.kind??"result"} ${I_(I.title??I.id,80)}${E}`),U)D.push(` source: ${I_(U,120)}`);if(I.text)D.push(` text: ${I_(I.text,180)}`)}if($.length===0)D.push("- No matches. Try a broader query or run `knowledge inventory --scope project`.");if(D.push(i_("scores, provenance, and full result objects")),!_.context)D.push("Next: use --context for an agent-ready citation pack, or --limit <n> to change the result count.");return D.join(` +`)}function Lf(_){let $=Array.isArray(_.excerpts)?_.excerpts:[],D=Array.isArray(_.citations)?_.citations:[],I=[`${$.length} context excerpt(s) for "${I_(_.query??_.normalized_query,80)}"`];for(let U of $.slice(0,10)){let E=D.find((O)=>O.id===U.citation_id||O.result_id===U.result_id),j=E?.source_uri??E?.artifact_path??U.result_id,N=typeof U.score==="number"?` score=${U.score.toFixed(3)}`:"";if(I.push(`- ${U.kind??"excerpt"} ${I_(U.id,44)}${N}`),j)I.push(` source: ${I_(j,120)}`);I.push(` text: ${I_(U.text,220)}`)}return I.push(`Citations: ${D.length}`),I.push(i_("citations, graph, notes, and full excerpts")),I.join(` +`)}function Wf(_){let $=Array.isArray(_.results)?_.results:[],D=[`${$.length} semantic result(s) for "${I_(_.query,80)}"`,`Index: ${_.provider??"unknown"}:${_.model??"unknown"} (${_.dimensions??"?"} dimensions)`];for(let I of $.slice(0,_.limit??10)){let U=typeof I.score==="number"?` score=${I.score.toFixed(3)}`:"";if(D.push(`- ${I_(I.chunk_id,44)}${U}`),I.source_uri)D.push(` source: ${I_(I.source_uri,120)}`);if(I.text)D.push(` text: ${I_(I.text,180)}`)}return D.push(i_("provenance and full vector result objects")),D.join(` `)}function Jf(_){let $=Array.isArray(_.sources)?_.sources:[],D=[`${$.length} web source(s) for "${I_(_.query,80)}"`,`Provider: ${_.provider??"unknown"}${_.model?` (${_.model})`:""}`];for(let I of $.slice(0,_.limit??10)){D.push(`- ${I_(I.title??I.url??I.uri??"source",100)}`);let U=I.url??I.uri??I.source_ref;if(U)D.push(` url: ${I_(U,140)}`);if(I.snippet)D.push(` snippet: ${I_(I.snippet,180)}`)}return D.push(i_("provider payloads and filed source refs")),D.join(` -`)}function Wf(_){let $=Array.isArray(_.machines)?_.machines:[],D=[`${$.length} machine(s) discovered via ${_.source??"unknown"}`,`Adapter: ${_.adapter?.package??"@hasna/machines"} ${_.adapter?.available?"available":"unavailable"}`];for(let I of $.slice(0,10)){let U=I.local?" local":"",E=I.tailscale_dns??I.ssh_target??I.hostname??"";D.push(`- ${I_(I.machine_id??I.id??"unknown",48)}${U}${E?` -> ${I_(E,80)}`:""}`)}if($.length>10)D.push(`... ${$.length-10} more machine(s).`);if(Array.isArray(_.warnings)&&_.warnings.length>0)D.push(`Warnings: ${_.warnings.slice(0,3).join("; ")}`);return D.push(i_("full topology, route hints, and adapter evidence")),D.join(` -`)}function Pf(_){let $=Array.isArray(_.checks)?_.checks:[],D=$.filter((E)=>E.status==="fail"||E.severity==="fail"),I=$.filter((E)=>E.status==="warn"||E.severity==="warn"),U=[`Machine preflight ${_.ok?"passed":"needs attention"} for ${_.machine_id??_.requested_machine_id??"local"}`,`Checks: ${$.length} total, ${D.length} failed, ${I.length} warning(s)`];for(let E of[...D,...I].slice(0,8))U.push(`- ${E.status??E.severity??"check"} ${I_(E.id??E.kind??"check",72)}: ${I_(E.message??E.detail??"",140)}`);return U.push(i_("all checks and repair hints")),U.join(` -`)}function zf(_){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(([D,I])=>`${D}=${I}`).join(", ")||"none"}`,i_("registry rows, clocks, snapshots, imports, and conflicts")].join(` +`)}function Pf(_){let $=Array.isArray(_.machines)?_.machines:[],D=[`${$.length} machine(s) discovered via ${_.source??"unknown"}`,`Adapter: ${_.adapter?.package??"@hasna/machines"} ${_.adapter?.available?"available":"unavailable"}`];for(let I of $.slice(0,10)){let U=I.local?" local":"",E=I.tailscale_dns??I.ssh_target??I.hostname??"";D.push(`- ${I_(I.machine_id??I.id??"unknown",48)}${U}${E?` -> ${I_(E,80)}`:""}`)}if($.length>10)D.push(`... ${$.length-10} more machine(s).`);if(Array.isArray(_.warnings)&&_.warnings.length>0)D.push(`Warnings: ${_.warnings.slice(0,3).join("; ")}`);return D.push(i_("full topology, route hints, and adapter evidence")),D.join(` +`)}function zf(_){let $=Array.isArray(_.checks)?_.checks:[],D=$.filter((E)=>E.status==="fail"||E.severity==="fail"),I=$.filter((E)=>E.status==="warn"||E.severity==="warn"),U=[`Machine preflight ${_.ok?"passed":"needs attention"} for ${_.machine_id??_.requested_machine_id??"local"}`,`Checks: ${$.length} total, ${D.length} failed, ${I.length} warning(s)`];for(let E of[...D,...I].slice(0,8))U.push(`- ${E.status??E.severity??"check"} ${I_(E.id??E.kind??"check",72)}: ${I_(E.message??E.detail??"",140)}`);return U.push(i_("all checks and repair hints")),U.join(` +`)}function gf(_){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(([D,I])=>`${D}=${I}`).join(", ")||"none"}`,i_("registry rows, clocks, snapshots, imports, and conflicts")].join(` `)}function Xf(_){let $=Array.isArray(_.warnings)?_.warnings:[],D=Array.isArray(_.recommended_commands)?_.recommended_commands:[],I=[_.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)I.push(`Warnings: ${$.slice(0,5).join("; ")}`);for(let U of D.slice(0,5))I.push(`- next: ${I_(U.shell_command??U.command?.join(" ")??U.id,160)}`);return I.push(i_("diagnostics, route evidence, and all recommended commands")),I.join(` `)}function Gf(_){let $=_.snapshot??{};return[`Sync snapshot ${_.ok?"recorded":"failed"}`,`Snapshot: ${I_($.id??$.snapshot_id??"unknown",80)} ${$.content_hash?`(${I_($.content_hash,80)})`:""}`,`Machines upserted: ${_.machines_upserted??0}; machine: ${_.machine_id??$.machine_id??"unknown"}`,i_("snapshot payload and topology evidence")].join(` `)}function Rf(_){let $=Array.isArray(_.conflicts)?_.conflicts:[],D=[`${$.length} sync conflict(s)`];for(let I of $.slice(0,10))D.push(`- ${I_(I.id,48)} ${I.status??"unknown"} ${I.entity_kind??""}/${I_(I.entity_id,80)}`);return D.push("Next: use `knowledge sync conflicts show <id> --json` for one conflict."),D.push(i_("full conflict objects")),D.join(` `)}function Yf(_){let $=Array.isArray(_.machines)?_.machines:[],D=[`${$.length} registered sync machine(s)`];for(let I of $.slice(0,10))D.push(`- ${I_(I.machine_id,48)} ${I_(I.hostname??I.workspace_home??"",100)}`);return D.push(i_("machine registry rows")),D.join(` -`)}function GY(_,$){let D=[`Sync ${$} ${_.ok===!1?"needs attention":"completed"}${_.dry_run?" (dry run)":""}`],I=(U,E)=>{if(!E)return;let N=(Array.isArray(E.tables)?E.tables:[]).reduce((S,L)=>S+(L.inserted??0)+(L.updated??0)+(L.deleted??0),0),A=E.artifacts?.copied??0,O=Array.isArray(E.errors)?E.errors.length:0;D.push(`${U}: ${N} table row change(s), ${A} artifact(s), ${O} error(s)`)};if(I("pull",_.pull),I("push",_.push),Array.isArray(_.errors)&&_.errors.length>0)D.push(`Errors: ${_.errors.slice(0,3).map((U)=>I_(U,120)).join("; ")}`);return D.push(i_("per-table rows, artifacts, clocks, and errors")),D.join(` +`)}function GY(_,$){let D=[`Sync ${$} ${_.ok===!1?"needs attention":"completed"}${_.dry_run?" (dry run)":""}`],I=(U,E)=>{if(!E)return;let N=(Array.isArray(E.tables)?E.tables:[]).reduce((L,W)=>L+(W.inserted??0)+(W.updated??0)+(W.deleted??0),0),O=E.artifacts?.copied??0,S=Array.isArray(E.errors)?E.errors.length:0;D.push(`${U}: ${N} table row change(s), ${O} artifact(s), ${S} error(s)`)};if(I("pull",_.pull),I("push",_.push),Array.isArray(_.errors)&&_.errors.length>0)D.push(`Errors: ${_.errors.slice(0,3).map((U)=>I_(U,120)).join("; ")}`);return D.push(i_("per-table rows, artifacts, clocks, and errors")),D.join(` `)}function Qf(_){let $=Array.isArray(_.citations)?_.citations:[],D=Array.isArray(_.context?.excerpts)?_.context.excerpts:Array.isArray(_.excerpts)?_.excerpts:[],I=[_.generated?"Generated answer with citations":"Prepared citation context draft",`Citations: ${$.length}; excerpts: ${D.length}`];if(_.answer)I.push(`Answer: ${I_(_.answer,500)}`);for(let U of $.slice(0,5))I.push(`- ${I_(U.source_uri??U.ref??U.id,120)}`);return I.push(i_("full answer payload, context, citations, and run ledger")),I.join(` `)}function Kf(_,$){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 RY(_){return!_||_==="local"||_==="localhost"}function E0(_){if(!_.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function Tf(_,$){let D=$.sort??"created";if(D!=="created"&&D!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let I=[..._].sort((U,E)=>{if(D==="title")return U.title.localeCompare(E.title);return U.created_at.localeCompare(E.created_at)});if($.desc)I.reverse();return{sorted:I,sort:D,direction:$.desc?"desc":"asc"}}async function Ff(_){if(await Df(_))return;let{positional:$,flags:D}=er(_);if(j0("debug","CLI invoked",{command:$[0],flags:{json:D.json,store:D.store}}),D.version){console.log(D.json?JSON.stringify({name:E$.name,version:E$.version},null,2):`${E$.name} ${E$.version}`);return}if(D.completions){let O=D.completions;if(O==="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 project-registration project-membership project-resources project-resource paths mode guarded 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 --operation-id --step-id --idempotency-key --slug --name --collection-id --collection-slug --collection-name --item-id --receipt-id --cursor --kind --all --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(O==="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 project-registration project-membership project-resources project-resource paths mode guarded 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" "(--all)--all" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(--search)--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]:" "(--operation-id)--operation-id[registration operation id]:" "(--step-id)--step-id[registration step id]:" "(--idempotency-key)--idempotency-key[caller idempotency key]:" "(--slug)--slug[project slug]:" "(--name)--name[project name]:" "(--collection-id)--collection-id[exact collection id]:" "(--collection-slug)--collection-slug[collection slug]:" "(--collection-name)--collection-name[collection name]:" "(--item-id)--item-id[exact item id]:" "(--receipt-id)--receipt-id[exact receipt id]:" "(--cursor)--cursor[resource cursor]:" "(--kind)--kind[resource kind]:(project collection item taxonomy):" "(--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(O==="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 project-registration project-membership project-resources project-resource paths mode guarded 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 operation-id; complete -c knowledge -l step-id; complete -c knowledge -l idempotency-key; complete -c knowledge -l slug; complete -c knowledge -l name; complete -c knowledge -l collection-id; complete -c knowledge -l collection-slug; complete -c knowledge -l collection-name; complete -c knowledge -l item-id; complete -c knowledge -l receipt-id; complete -c knowledge -l cursor; complete -c knowledge -l kind -a "project collection item taxonomy"; complete -c knowledge -l all; 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 I=ar($[0]),U=1,E=$f()&&I&&!QY.includes(I);if(!I||D.help||I==="help"){let O=I==="help"?$[1]:I||$[1];If(O);return}if(I==="mode"){let O=Vz(process.env);k(D.json||D.verbose?{ok:!0,...O}:Nf(O),D.json,D);return}if(I==="guarded"){if(($[1]??"capabilities")!=="capabilities")throw Error("Usage: knowledge guarded capabilities [--json]");k({ok:!0,contract:"FCAME-1",private_input:!0,private_result:!0,exact_title_lookup:!0,private_transport_body_output:!1},D.json,D);return}Fz(process.env,{storePathOverridden:Boolean(D.store)});let j=I==="project-panel"||I==="app-wiki"?D.scope??"project":D.scope,N=zN({scope:j}),A;try{if(I==="storage"){let J=$[1]??"status";if(J==="import-legacy"){if(D.scope&&D.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let W=oN({dryRun:D.dryRun});if(k(W,D.json),!W.ok)process.exitCode=1;return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let W=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(W,D.json),!W.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let W=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(W,D.json),!W.ok&&!D.json)process.exitCode=1;return}}let O=Boolean(D.store),S=D.store;if(!S)if(j==="project"||j==="local")S=N.workspace.jsonStorePath;else S=u1();let L=t1({storePath:S,storePathOverridden:O});if(E&&await tr($,I,L))I="ask",U=0;if(!O&&(I==="ask"||I==="build")&&!h$())xD(S);let P=()=>{if(!O||h$())return N.projectLinksAuthority();return A??=ON({databasePath:mr(dr(S),"knowledge.db"),itemStore:L,options:{packageVersion:E$.version,authorityId:process.env.HASNA_KNOWLEDGE_PROJECT_AUTHORITY_ID??"knowledge",tenantId:process.env.HASNA_KNOWLEDGE_PROJECT_TENANT_ID??"local",corpusId:process.env.HASNA_KNOWLEDGE_PROJECT_CORPUS_ID??"knowledge"}}),A};if(I==="project-registration"){let J=$[1]??"capability",W=P();if(J==="capability"){k({ok:!0,capability:await W.capability()},D.json,D);return}if(J==="create"){let X=await W.capability(),R=D.project,T=D.slug,Y=D.name;if(!D.operationId||!D.stepId||!D.idempotencyKey||!R||!T||!Y)throw Error("Usage: knowledge project-registration create --operation-id <id> --step-id <id> --idempotency-key <key> --project <id> --slug <slug> --name <name> [--collection-slug <slug>] [--collection-name <name>] [--json]");let Q={collection_slug:D.collectionSlug??`${T}-knowledge`,collection_name:D.collectionName??`${Y} Knowledge`},F=v_({action:"register_collection",source_project_id:R,project_slug:T,project_name:Y,collection_slug:Q.collection_slug,collection_name:Q.collection_name,membership_rule:"explicit_collection_binding"}),q=await W.registerCollection({operation_id:D.operationId,step_id:D.stepId,resource_kind:"collection",direction:"forward",authority_route:k$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,target_selector:R,idempotency_key:D.idempotencyKey,request_digest:F,precondition_digest:v_({source_project_id:R,expected:"absent_or_exact_match"}),project_id:R,project_slug:T,project_name:Y,desired:Q});k({ok:q.outcome==="accepted",receipt:q},D.json,D);return}if(J==="read-exact"){if(!D.collectionId)throw Error("Usage: knowledge project-registration read-exact --collection-id <uuid> [--json]");k({ok:!0,record:await W.readCollection(D.collectionId)},D.json,D);return}if(J==="receipt"){let X=$[2],R=$[3];if(!D.operationId||!D.stepId||!D.idempotencyKey||!X||!R)throw Error("Usage: knowledge project-registration receipt <register_collection|bind_item> <forward|inverse> --operation-id <id> --step-id <id> --idempotency-key <key> [--json]");let T=await W.capability(),Y=await W.lookupReceipt({authority_id:T.authority_id,tenant_id:T.tenant_id,corpus_id:T.corpus_id,operation_id:D.operationId,step_id:D.stepId,action:X,direction:R,idempotency_key:D.idempotencyKey,max_items:1});k({ok:!0,receipt:Y},D.json,D);return}if(J==="compensate"||J==="verify-inverse"){if(!D.operationId||!D.stepId||!D.idempotencyKey||!D.receiptId)throw Error(`Usage: knowledge project-registration ${J} --operation-id <id> --step-id <id> --idempotency-key <key> --receipt-id <accepted-receipt-id> [--json]`);let X=await W.capability(),R={operation_id:D.operationId,step_id:D.stepId,authority_route:k$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,idempotency_key:D.idempotencyKey,accepted_receipt_id:D.receiptId},T=J==="compensate"?{receipt:await W.compensateRegistration(R)}:{verification:await W.verifyRegistrationInverse(R)};k({ok:!0,...T},D.json,D);return}throw Error("Invalid project-registration action. Use capability, create, read-exact, receipt, compensate, or verify-inverse.")}if(I==="project-membership"){let J=$[1]??"read-exact",W=P();if(J==="bind"){if(!D.operationId||!D.stepId||!D.idempotencyKey||!D.collectionId||!D.itemId)throw Error("Usage: knowledge project-membership bind --operation-id <id> --step-id <id> --idempotency-key <key> --collection-id <uuid> --item-id <id> [--json]");let X=await W.capability(),R=await W.bindItem({operation_id:D.operationId,step_id:D.stepId,direction:"forward",authority_route:k$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,idempotency_key:D.idempotencyKey,request_digest:v_({action:"bind_item",collection_id:D.collectionId,item_id:D.itemId}),precondition_digest:v_({collection_id:D.collectionId,item_id:D.itemId,expected:"unbound_or_exact_membership"}),collection_id:D.collectionId,item_id:D.itemId});k({ok:R.outcome==="accepted",receipt:R},D.json,D);return}if(J==="read-exact"){if(!D.collectionId||!D.itemId)throw Error("Usage: knowledge project-membership read-exact --collection-id <uuid> --item-id <id> [--json]");k({ok:!0,record:await W.readItemBinding(D.collectionId,D.itemId)},D.json,D);return}if(J==="compensate"||J==="verify-inverse"){if(!D.operationId||!D.stepId||!D.idempotencyKey||!D.receiptId)throw Error(`Usage: knowledge project-membership ${J} --operation-id <id> --step-id <id> --idempotency-key <key> --receipt-id <accepted-receipt-id> [--json]`);let X=await W.capability(),R={operation_id:D.operationId,step_id:D.stepId,authority_route:k$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,idempotency_key:D.idempotencyKey,accepted_receipt_id:D.receiptId},T=J==="compensate"?{receipt:await W.compensateItemBinding(R)}:{verification:await W.verifyItemBindingInverse(R)};k({ok:!0,...T},D.json,D);return}throw Error("Invalid project-membership action. Use bind, read-exact, compensate, or verify-inverse.")}if(I==="project-resources"){let J=D.project??$[1];if(!J)throw Error("Usage: knowledge project-resources <project-id> [--kind <kind>]... [--limit <n>] [--cursor <cursor>] [--all] [--json]");let W=P(),X=D.kind,R=D.all?{resources:await W.readAllProjectResources(J,{limit:D.limit,kinds:X})}:await W.listProjectResources(J,{limit:D.limit,cursor:D.cursor,kinds:X});k({ok:!0,...R},D.json,D);return}if(I==="project-resource"){let J=D.project??$[1],W=$[2],X=$[3];if(!J||!W||!X)throw Error("Usage: knowledge project-resource <project-id> <project|collection|item|taxonomy> <resource-id> [--json]");k({ok:!0,resource:await P().readProjectResource(J,W,X)},D.json,D);return}if(I==="inventory"){let J=await N.resolveInventory({limit:D.limit,includeArchived:D.includeArchived||D.archived,storePath:h$()?void 0:S});k(D.json||D.verbose?J:Af(J),D.json,D);return}if(I==="project-panel"){let J=D.project??$[1];if(!J)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let W=await K8(J,{service:N,limit:D.limit,storePath:h$()?void 0:S,includeArchived:D.includeArchived||D.archived});k(D.json||D.contract?W:T8(W),D.json||D.contract);return}if(I==="paths"){let J=N.paths();k(D.json||D.verbose?J:gf(J),D.json,D);return}if(I==="setup"){let J=N.setup({mode:D.mode,apiUrl:D.apiUrl,canonicalExample:D.canonicalExample});k(J,D.json,D);return}if(I==="auth"){let J=$[1]??"whoami";if(J==="whoami"||J==="status"){let W=N.authStatus(process.env);k({ok:!0,...W,message:W.authenticated?`Authenticated via ${W.source}`:"Not authenticated"},D.json,D);return}if(J==="login"){let W=D.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!W)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let X=N.saveAuth({apiKey:W,email:D.email,orgSlug:D.org,orgId:D.orgId,userId:D.userId,apiUrl:D.apiUrl},process.env);k({ok:!0,authenticated:!0,email:X.email??null,org_slug:X.org_slug??null,api_url:X.api_url??N.authStatus(process.env).api_url,auth_path:N.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${X.email??"API key"}`},D.json,D);return}if(J==="logout"){let W=N.clearAuth(process.env);k({ok:!0,removed:W,message:W?"Removed hosted credentials":"No hosted credentials found"},D.json,D);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(I==="storage"){let J=$[1]??"status";if(J==="status"){let W=N.storageContract(),X=N.validateStorage();k({ok:X.ok,...W,validation:X,message:`${W.storage_type} artifact storage at ${W.artifact_store.uri_prefix}`},D.json,D);return}if(J==="validate"){let W=N.validateStorage();if(k({ok:W.ok,validation:W,message:W.ok?"Storage contract valid":`Storage contract invalid: ${W.errors.join("; ")}`},D.json,D),!W.ok)process.exitCode=1;return}if(J==="repair-artifact-keys"||J==="repair-keys"){let W=N.repairArtifactManifestKeys({approveWrite:D.approveWrite,approvedBy:D.approvedBy,dryRun:D.dryRun});k(W,D.json,D);return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let W=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(W,D.json),!W.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let W=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(W,D.json),!W.ok&&!D.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(I==="machines"){let J=$[1]??"topology";if(J==="topology"||J==="status"){let W=await N.machineTopology({includeTailscale:D.tailscale!==!1});k(D.json||D.verbose?W:Wf(W),D.json,D);return}if(J==="preflight"||J==="check"){let W=$[2]??D.machine??"local",X=D.workspace??process.cwd(),R=await N.machinePreflight({machineId:W,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:E$.name,command:"knowledge",expectedVersion:E$.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:X,expectedPackageName:E$.name,expectedVersion:E$.version,required:!0}]});if(k(D.json||D.verbose?R:Pf(R),D.json,D),!R.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(I==="sync"){let J=$[1]??"status",W=D.tables?D.tables.split(",").map((X)=>X.trim()).filter(Boolean):void 0;if(J==="status"){let X=N.syncStatus();k(D.json||D.verbose?X:zf(X),D.json,D);return}if(J==="doctor"||J==="readiness"||J==="preflight"){let X=await N.syncDoctor({machine:D.machine??null,peerWorkspace:D.peerWorkspace??null,includeTailscale:D.tailscale!==!1,tables:W}),R={package:{name:E$.name,version:E$.version},...X};if(k(D.json||D.verbose?R:Xf(R),D.json,D),!X.ok&&!D.json)process.exitCode=1;return}if(J==="snapshot"||J==="record"){let X=await N.createSyncSnapshot({includeTailscale:D.tailscale!==!1,machineId:D.machine});k(D.json||D.verbose?X:Gf(X),D.json,D);return}if(J==="conflicts"||J==="conflict"){let X=$[2];if(X==="show"||X==="get"){let Y=$[3]??D.id;if(!Y)throw Error("Usage: knowledge sync conflicts show <id>");let Q=N.syncConflict(Y);k({ok:!0,conflict:Q,message:`Sync conflict ${Y}`},D.json,D);return}if(X==="propose"||X==="proposal"){let Y=$[3]??D.id;if(!Y)throw Error("Usage: knowledge sync conflicts propose <id>");k(D.mode==="ai"?await N.proposeSyncConflictResolutionWithAi({id:Y,modelRef:D.model,fake:D.fake}):N.proposeSyncConflictResolution(Y),D.json,D);return}if(X==="resolve"){let Y=$[3]??D.id;if(!Y)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let Q=N.resolveSyncConflict({id:Y,strategy:D.strategy,approvedBy:D.approvedBy,approveWrite:D.approveWrite,proposedPatchUri:D.patchUri});if(k(Q,D.json,D),!Q.ok&&!D.json)process.exitCode=1;return}let R=N.syncConflicts({status:X,limit:D.limit}),T={ok:!0,conflicts:R,message:`${R.length} sync conflict(s)`};k(D.json||D.verbose?T:Rf(T),D.json,D);return}if(J==="machines"||J==="registry"){let X=N.syncMachines(),R={ok:!0,machines:X,message:`${X.length} registered sync machine(s)`};k(D.json||D.verbose?R:Yf(R),D.json,D);return}if(J==="export"){let X=N.exportSyncBundle({machineId:D.machine??null,tables:W,includeArtifactContent:D.artifactContent!==!1});k(X,!0);return}if(J==="import"){let X=await Bun.stdin.text();if(!X.trim())throw Error("Usage: knowledge sync import < bundle.json");let R=await N.importSyncBundle({bundle:JSON.parse(X),dryRun:D.dryRun,direction:"import",machineId:D.machine??null});k(D.json||D.verbose?R:GY(R,J),D.json,D);return}if(J==="dry-run"||J==="pull"||J==="push"||J==="sync"){if(!D.peerWorkspace&&RY(D.machine))throw Error(`Usage: knowledge sync ${J} --peer-workspace <repo-or-knowledge-home> [--scope project] -Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let X=J==="dry-run"?"both":J==="sync"?"both":J,R=!RY(D.machine)?await N.syncRemotePeer({direction:X,machine:D.machine,peerWorkspace:D.peerWorkspace,tables:W,dryRun:D.dryRun===!0||J==="dry-run",includeArtifactContent:D.artifactContent!==!1,includeTailscale:D.tailscale!==!1}):await N.syncPeer({peerWorkspace:D.peerWorkspace,direction:X,dryRun:D.dryRun===!0||J==="dry-run",tables:W,includeArtifactContent:D.artifactContent!==!1,machineId:D.machine??null});if(k(D.json||D.verbose?R:GY(R,J),D.json,D),!R.ok&&!D.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(I==="db"){let J=$[1]??"init";if(J==="init"){let W=N.initDb();k({ok:!0,...W,message:`Initialized ${W.path}`},D.json,D);return}if(J==="stats"){let W=N.dbStats();k({ok:!0,path:N.workspace.knowledgeDbPath,...W,message:`knowledge.db schema v${W.schema_version}`},D.json,D);return}if(J==="storage"){if(($[2]??"status")==="status"){let X=JP({scope:D.scope});k({ok:!0,...X,message:`knowledge.db storage mode ${X.mode}`},D.json,D);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(I==="app-wiki"){let J=$[1]??"init";if(J==="paths"||J==="status"){k({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...N.paths()},D.json);return}if(J==="init"||J==="open"){let W=await N.initAppWiki({allowGlobal:D.allowGlobal});k(W,D.json);return}if(J==="note"||J==="notes"){let W=$[2]??"list";if(W==="add"||W==="create"){let X=D.title??$[3],R=D.content??$.slice(4).join(" ");if(!X||!R)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let T=await N.addAppWikiNote({title:X,content:R,tags:D.tag,sourceRefs:D.sourceRef,allowGlobal:D.allowGlobal});k(T,D.json);return}if(W==="list"||W==="ls"){let X=N.listAppWikiNotes({limit:D.limit});k({ok:!0,scope:N.scope,home:N.workspace.home,notes:X,message:`${X.length} app wiki note(s)`},D.json);return}if(W==="get"||W==="show"){let X=$[3]??D.id;if(!X)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let R=await N.getAppWikiNote(X,{includeContent:!0});if(!R)throw Error(`App wiki note not found: ${X}`);k(R,D.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(J==="source"||J==="sources"){let W=$[2]??"add";if(W!=="add"&&W!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let X=$[3]??D.sourceRef?.[0];if(!X)throw Error("Usage: knowledge app-wiki source add <source-ref>");let R=await N.addAppWikiSourceRef({sourceRef:X,purpose:D.purpose,allowGlobal:D.allowGlobal});k({ok:!0,...R,message:`Added app wiki source ${R.source_ref}`},D.json);return}if(J==="search"){let W=$.slice(2).join(" ");if(!W)throw Error("Usage: knowledge app-wiki search <query>");let X=await N.searchAppWiki({query:W,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...X,message:`${X.results.length} app wiki result(s)`},D.json);return}if(J==="query"||J==="context"){let W=$.slice(2).join(" ");if(!W)throw Error("Usage: knowledge app-wiki query <query>");let X=await N.queryAppWiki({query:W,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...X,message:`${X.excerpts.length} app wiki excerpt(s)`},D.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(I==="wiki"){let J=$[1]??"init";if(J==="init"){let W=await N.initWiki();k({ok:!0,...W,message:`Initialized wiki layout in ${N.workspace.home}`},D.json,D);return}if(J==="compile"){let W=$.slice(2),X=W.filter((Y)=>/^(open-files|file|s3|https?):\/\//.test(Y)),R=W.filter((Y)=>!/^(open-files|file|s3|https?):\/\//.test(Y)).join(" "),T=await N.compileWiki({title:D.title,query:R||D.search,sourceRefs:X.length>0?X:void 0,limit:D.limit});k({ok:!0,...T,message:`Compiled wiki page ${T.path}`},D.json,D);return}if(J==="file-answer"||J==="answer"){let W=$.slice(2).join(" ");if(!W)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!D.content)throw Error("Missing --content <answer> for wiki file-answer.");let X=await N.fileAnswer({prompt:W,answer:D.content,approveWrite:D.approveWrite,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...X},D.json,D);return}if(J==="lint"){let W=N.lintWiki();k({ok:W.ok,...W,message:W.ok?"Wiki lint passed":`Wiki lint found ${W.issue_count} issue(s)`},D.json,D);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(I==="safety"){let J=$[1]??"status",W=N.ensureWorkspace(),X=N.safetyPolicy();N.initDb();let R=w(W.knowledgeDbPath);try{if(J==="status"){k({ok:!0,mode:X.mode,workspace:W.home,allow_write_roots:X.allowWriteRoots,read_only_source_access:X.readOnlySourceAccess,network:X.network,redaction:X.redaction,approvals:X.approvals,message:`Safety policy: ${X.mode}`},D.json,D);return}if(J==="check"){let T=$[2]??"generated_write",Y=$[3]??null,Q;try{if(T==="web_search")G0(X),Q={action:T,target_uri:Y,approval_required:!1,approved:!0,decision:"allow"};else if(T==="s3_read"){if(!Y)throw Error("safety check s3_read requires an s3:// target.");b6(Y,X),Q={action:T,target_uri:Y,approval_required:!1,approved:!0,decision:"allow"}}else Q=E3(R,X,T,Y);R_(R,{event_type:"safety_check",action:T,target_uri:Y,decision:Q.decision==="allow"?"allow":"requires_approval",metadata:Q}),k({ok:!0,...Q,message:`Safety check ${Q.decision}`},D.json,D);return}catch(F){throw R_(R,{event_type:"safety_check",action:T,target_uri:Y,decision:"deny",metadata:{error:F instanceof Error?F.message:String(F)}}),F}}if(J==="approve"){let T=$[2]??"generated_write",Y=$[3]??null,Q=s1(R,{action:T,target_uri:Y,reason:"local-cli approval",metadata:{scope:D.scope??"global"}});R_(R,{event_type:"approval",action:T,target_uri:Y,decision:"allow",metadata:{approval_id:Q.id}}),k({ok:!0,...Q,action:T,target_uri:Y,message:`Approved ${T}`},D.json,D);return}if(J==="audit"){let T=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((Y)=>({id:Y.id,event_type:Y.event_type,action:Y.action,target_uri:Y.target_uri,decision:Y.decision,metadata:JSON.parse(Y.metadata_json),created_at:Y.created_at}));k({ok:!0,events:T,message:`${T.length} audit event(s)`},D.json,D);return}if(J==="redact"){let T=$.slice(2).join(" ");if(!T)throw Error("Usage: knowledge safety redact <text>");let Y=u_(T,X);if(Y.findings.length>0)R0(R,{source_uri:"safety://redact",findings:Y.findings,metadata:{command:"safety redact"}});R_(R,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:Y.findings.length>0?"redacted":"allow",metadata:{findings:Y.findings.length}}),k({ok:!0,text:Y.text,findings:Y.findings,message:`Redacted ${Y.findings.length} finding(s)`},D.json,D);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{R.close()}}if(I==="source"){if(($[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let W=$[2];if(!W)throw Error("Usage: knowledge source resolve <source-ref>");let X=await N.resolveSource(W,{purpose:D.purpose,limit:D.limit});k({ok:!0,...X,message:X.resolved?`Resolved ${X.source_ref} (${X.content.chunks_returned}/${X.content.chunks_total} chunks)`:`Source not indexed: ${W}`},D.json,D);return}if(I==="ingest"){let J=$[1]??"";if(J==="rules"||J==="global-rules"||J==="agent-rules"){let W=await N.importRulesProvenance({root:D.workspace??process.cwd(),owner:D.owner,dryRun:D.dryRun===!0,maxItems:D.maxItems,limit:D.limit});k({ok:!0,...W},D.json);return}if(J==="manifest"){let W=$[2];if(!W)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let X=await N.ingestManifest(W);k({ok:!0,...X,message:`Ingested ${X.items_seen} manifest item(s)`},D.json,D);return}if(J==="source"){let W=$[2];if(!W)throw Error("Usage: knowledge ingest source <source-ref>");let X=await N.ingestSource(W,D.purpose);k({ok:!0,...X,message:`Ingested source ${X.source_ref} (${X.chunks_inserted} chunks)`},D.json,D);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(I==="reindex"){let J=$[1]??"status";if(J==="status"){let W=N.reindexHealth({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...W,message:`${W.missing_embeddings} chunk(s) missing embeddings`},D.json,D);return}if(J==="enqueue"){let W=N.enqueueReindex({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...W,message:`Queued ${W.enqueued} embedding refresh item(s)`},D.json,D);return}if(J==="embeddings"){let W=await N.refreshEmbeddings({full:D.full,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...W,message:`Embedded ${W.indexed.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="outbox"){let W=$[2];if(!W)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let X=await N.consumeOutbox(W);k({ok:!0,...X,message:`Consumed ${X.events_seen} outbox event(s)`},D.json,D);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(I==="embeddings"){let J=$[1]??"status";if(J==="status"){let W=N.embeddingStatus();k({ok:!0,...W,message:`${W.total_vector_entries} vector index entries`},D.json,D);return}if(J==="index"){let W=await N.indexEmbeddings({limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...W,message:`Embedded ${W.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="search"){let W=$.slice(2).join(" ");if(!W)throw Error("Usage: knowledge embeddings search <query>");let X=await N.semanticSearch({query:W,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake}),R={ok:!0,...X,message:`${X.results.length} semantic result(s)`};k(D.json||D.verbose?R:Lf(R),D.json,D);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(I==="context"){if(($[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let W=D.from??"search";if(!["search","loops","runs"].includes(W))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let X=$.slice(2).join(" ")||D.topic||"",R=await N.contextPack({source:W,purpose:W==="loops"||W==="runs"?"proposal":"agent_context",query:X,topic:D.topic,since:D.since,dedupe:D.dedupe,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:S});XY({ok:!0,...R,message:R.message});return}if(I==="proposals"){if(($[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let W=D.from??"loops";if(!["loops","runs"].includes(W))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let X=D.topic??$.slice(2).join(" ");if(!X.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let R=await N.contextPack({source:W,purpose:"proposal",query:X,topic:X,since:D.since,dedupe:D.dedupe??!0,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit});XY({ok:!0,...R,message:R.message});return}if(I==="search"){let J=$.slice(1).join(" ");if(!J)throw Error("Usage: knowledge search <query>");if(D.context){let R=await N.retrieveContext({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:S}),T={ok:!0,...R,message:`${R.excerpts.length} context excerpt(s)`};k(D.json||D.verbose?T:Sf(T),D.json,D);return}let W=await N.search({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:S}),X={ok:!0,...W,message:`${W.results.length} search result(s)`};k(D.json||D.verbose?X:Of(X),D.json,D);return}if(I==="web"){if(($[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let W=$.slice(2).join(" ");if(!W)throw Error("Usage: knowledge web search <query>");let X=await N.webSearch({query:W,limit:D.limit,modelRef:D.model,provider:D.provider,domains:D.domain,fake:D.fake,fileResults:D.fileResults}),R={ok:!0,...X,message:`${X.sources.length} web source(s)`};k(D.json||D.verbose?R:Jf(R),D.json,D);return}if(I==="ask"||I==="build"){let J=$.slice(U).join(" ");if(!J)throw Error("Usage: knowledge ask <prompt>");let W=await N.runPrompt({prompt:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,generate:D.generate,approveWrite:D.approveWrite,legacyStorePath:S}),X={ok:!0,...W,message:W.generated?"Generated answer with citations":"Prepared citation context draft"};k(D.json||D.verbose?X:Qf(X),D.json,D);return}if(I==="providers"){let J=$[1]??"status";if(J==="status"){let W=N.providerStatus(),X=W.providers.filter((R)=>R.configured).length;k({ok:!0,...W,message:`${X}/${W.providers.length} provider credential(s) configured`},D.json,D);return}if(J==="models"){let W=N.modelRegistry();k({ok:!0,models:W,message:`${W.length} model alias(es)`},D.json,D);return}if(J==="check"){let W=$[2]??"default",X=T$(W,N.config()),R=f_(X),T=A4(R.provider,N.config());k({ok:!0,target:W,model_ref:X,provider:R.provider,model:R.model,credential:T,message:`${R.provider} credentials configured`},D.json,D);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(I==="add"){let J=$[1],W=$[2];if(!J||!W)throw Error("Usage: knowledge add <title> <content>");let X=await L.create({title:J,content:W,url:D.url??null,tags:D.tag??[]});j0("info","Item added",{id:X.id,title:X.title,tags:X.tags?.length??0,transport:L.kind}),k({ok:!0,item:X,message:`Added ${X.id}`},D.json,D);return}if(I==="list"){if(D.format!==void 0&&D.format!=="table"&&D.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");if(D.page!==void 0&&(!Number.isFinite(D.page)||!Number.isInteger(D.page)||D.page<1))throw Error("--page must be a positive integer.");if(D.limit!==void 0&&(!Number.isFinite(D.limit)||!Number.isInteger(D.limit)||D.limit<1||D.limit>200))throw Error("--limit must be an integer between 1 and 200.");let J=D.page??1,W=D.limit??20,X=D.search?String(D.search).toLowerCase():"",R=D.tagRaw??D.tag??[],T=D.tag?.length?D.tag.map((G_)=>G_.toLowerCase()).join(","):"none",Y=D.format==="table"||!D.json&&!D.format&&Ef(D),Q=D.json||D.format==="json",F=D.archived?"archived":D.includeArchived?"all":"active",{sort:q,direction:Z}=Tf([],D),f=(J-1)*W;if(f>1e4)throw Error("The requested page exceeds the maximum bounded offset of 10000.");let l=await L.list({search:X,tags:R,archive:F,sort:q,direction:Z,limit:W,offset:f}),U_=l.items,j_=Math.max(1,Math.ceil(l.total/W)),_$={ok:!0,page:J,limit:W,total:l.total,total_pages:j_,sort:q,direction:Z,items:U_,store_exists:l.exists};if(Q){k(_$,!0);return}if(D.verbose){k(_$,!1,D);return}if(U_.length===0){k(`No items found (search=${X||"none"}, tag=${T})`,!1);return}if(Y){let G_=(E_)=>E_,K$=`${G_("ID")} ${G_("TITLE")} ${G_("CREATED")} ${G_("URL")} ${G_("TAGS")}`;console.log(K$);for(let E_ of U_)console.log(`${E_.id} ${G_(I_(E_.title,80))} ${E_.created_at} ${E_.url?G_(I_(E_.url,90)):""} ${E_.tags?.length?G_(I_(`[${E_.tags.join(", ")}]`,80)):""}`);console.log(`Page ${J}/${j_} | showing ${U_.length} of ${l.total} | sort=${q} ${Z} | search=${X||"none"} | tag=${T}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let G_ of U_)console.log(`${G_.id} ${I_(G_.title,80)} ${G_.created_at}${G_.url?` ${I_(G_.url,90)}`:""}${G_.tags?.length?` ${I_(`[${G_.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${J}/${j_} | showing ${U_.length} of ${l.total} | sort=${q} ${Z} | search=${X||"none"} | tag=${T}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(I==="get"){E0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);k({ok:!0,item:J,store_exists:L.exists,message:`${J.id}: ${J.title}`},D.json,D);return}if(I==="versions"){E0(D);let J=Number.isFinite(D.page)&&D.page>0?D.page:1,W=Number.isFinite(D.limit)&&D.limit>0?D.limit:void 0,X=await L.listVersions(D.id,{limit:W,offset:(J-1)*(W??50)});if(!X)throw Error(`Item not found: ${D.id}`);let R={ok:!0,id:X.item_id,current_version:X.current_version,total:X.total,page:J,store:L.location,versions:X.items,message:X.total===0?`${X.item_id} is at version ${X.current_version} with no retained prior versions`:`${X.item_id} is at version ${X.current_version}; ${X.total} prior version(s) retained`};if(D.json||D.verbose){k(R,D.json,D);return}console.log(R.message);for(let T of X.items){let Y=T.actor?` by ${T.actor}`:"",Q=T.reason?` (${T.reason})`:"";console.log(`v${T.version} ${T.valid_to}${Y}${Q} ${T.content_bytes} bytes ${T.content_hash.slice(0,12)}`)}if(X.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(I==="diff"){E0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.rev!==void 0&&(D.from!==void 0||D.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let W=()=>({title:J.title,content:J.content,url:J.url,tags:J.tags??[],metadata:J.metadata??{},archived:J.archived??!1}),X=`v${J.version??"?"} (current)`,R=async(Z)=>{if(Z==="current")return{label:X,snapshot:W()};let f=Number(Z);if(!Number.isInteger(f)||f<1)throw Error(`Not a version number: ${Z}`);if(J.version!==void 0&&f===J.version)return{label:X,snapshot:W()};let l=await L.getVersion(J.id,f);if(!l)throw Error(`No version ${f} retained for ${J.id} (it is at version ${J.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${l.version}`,snapshot:{title:l.title,content:l.content,url:l.url,tags:l.tags,metadata:l.metadata,archived:l.archived}}},T,Y;if(D.rev!==void 0){if(!Number.isInteger(D.rev)||D.rev<1)throw Error("--rev must be a positive version number.");if(D.rev===1)throw Error("Version 1 has no predecessor to diff against.");T=String(D.rev-1),Y=String(D.rev)}else if(D.from!==void 0||D.to!==void 0){if(D.from===void 0||D.to===void 0)throw Error("--from and --to must be given together.");T=D.from,Y=D.to}else{let Z=await L.listVersions(J.id,{limit:1});if(!Z)throw Error(`Item not found: ${D.id}`);if(Z.items.length===0)throw Error(`${J.id} is at version ${Z.current_version} with no retained prior versions to diff against.`);T=String(Z.items[0].version),Y="current"}let Q=await R(T),F=await R(Y),q=kz(Q.snapshot,F.snapshot);if(D.json||D.verbose){k({ok:!0,id:J.id,from:Q.label,to:F.label,...q},D.json,D);return}console.log(qz(q,`${J.id} ${Q.label}`,`${J.id} ${F.label}`));return}if(I==="update"){E0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.ifVersion!==void 0&&(!Number.isInteger(D.ifVersion)||D.ifVersion<1))throw Error(`Invalid --if-version ${JSON.stringify(String(D.ifVersion))}: must be a positive integer version number, e.g. the "version" field from a prior 'knowledge get'.`);let W={};if(D.title!==void 0)W.title=D.title;if(D.content!==void 0)W.content=D.content;if(D.url!==void 0)W.url=D.url;let X;if(D.tag!==void 0){if(X=zY(J.tags,D.tag),X.length>0)W.tags=[...J.tags??[],...X]}let R=D.ifVersion!==void 0?D.ifVersion:J.version,T=await L.update(J.id,W,{expectedVersion:R});k(bP({ok:!0,item:T},`Updated ${T?.id??J.id}`,X),D.json,D);return}if(I==="archive"||I==="restore"){E0(D);let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let W=await L.update(J.id,{archived:I==="archive"},{expectedVersion:J.version});k({ok:!0,item:W,message:`${I==="archive"?"Archived":"Restored"} ${W?.id??J.id}`},D.json,D);return}if(I==="untag"){if(E0(D),!D.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let J=await L.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let W=J.tags??[],X=new Set(W.map((f)=>f.toLowerCase())),R=new Set;for(let f of D.tagRaw??D.tag){let l=f.trim().toLowerCase();if(l.length>0&&X.has(l)){R.add(l);continue}for(let U_ of f.split(",").map((j_)=>j_.trim().toLowerCase()).filter((j_)=>j_.length>0))R.add(U_)}let T=W.filter((f)=>!R.has(f.toLowerCase())),Y=W.length-T.length,Q=[...R].filter((f)=>!X.has(f));if(Y===0)throw Error(`No matching tag on ${J.id}: ${Q.map((f)=>JSON.stringify(f)).join(", ")} not in [${W.map((f)=>JSON.stringify(f)).join(", ")}]`);let F=await L.update(J.id,{tags:T},{expectedVersion:J.version}),q=Q.length>0?` (not found: ${Q.map((f)=>JSON.stringify(f)).join(", ")})`:"",Z={ok:!0,item:F,removed:Y,message:`Removed ${Y} tag${Y===1?"":"s"} from ${F?.id??J.id}${q}`};if(Q.length>0)Z.not_found=Q;k(Z,D.json,D);return}if(I==="upsert"){let J=D.title??$[1],W=D.content??$[2],X=D.id?await L.get(D.id):null;if(!X){if(!J||!W)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let Q=await L.create({id:D.id,title:J,content:W,url:D.url??null,tags:D.tag??[]});k(bP({ok:!0,created:!0,item:Q},`Upserted ${Q.id}`,D.tag),D.json,D);return}let R={};if(J!==void 0)R.title=J;if(W!==void 0)R.content=W;if(D.url!==void 0)R.url=D.url;let T;if(D.tag!==void 0){if(T=zY(X.tags,D.tag),T.length>0)R.tags=[...X.tags??[],...T]}let Y=await L.update(X.id,R,{expectedVersion:X.version});k(bP({ok:!0,created:!1,item:Y},`Upserted ${Y?.id??X.id}`,T),D.json,D);return}if(I==="delete"){if(E0(D),!D.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await L.delete(D.id))throw Error(`Item not found: ${D.id}`);j0("info","Item deleted",{id:D.id,transport:L.kind}),k({ok:!0,deleted_id:D.id,message:`Deleted ${D.id}`},D.json,D);return}if(I==="export"){let J=D.format??"json";if(J!=="json"&&J!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let W=await L.listAll();if(J==="jsonl")for(let X of W.items)console.log(JSON.stringify(X));else if(D.json||D.format==="json"||D.verbose)k({ok:!0,items:W.items,store_exists:W.exists},D.json||D.format==="json",D);else k(Kf(W.items,J),!1);return}if(I==="prune"){if(!D.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:J}=await L.listAll(),W=D.olderThan!==void 0?new Date(Date.now()-D.olderThan*86400000):null,X=J.filter((Y)=>W!==null&&new Date(Y.created_at)<W||D.empty&&Y.content.trim().length===0),R=await L.deleteMany(X.map((Y)=>Y.id)),T=J.length-R;j0("info","Prune completed",{pruned:R,remaining:T,transport:L.kind}),k({ok:!0,pruned:R,remaining:T,message:`Pruned ${R} item(s)`},D.json,D);return}if(I==="dedupe"){if(!D.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:J}=await L.listAll(),W=new Set,X=[];for(let Y of J){let Q=`${Y.title}\x00${Y.content}`;if(W.has(Q))X.push(Y);else W.add(Q)}let R=await L.deleteMany(X.map((Y)=>Y.id)),T=J.length-R;j0("info","Dedupe completed",{removed:R,remaining:T,transport:L.kind}),k({ok:!0,removed:R,remaining:T,message:`Dedupe removed ${R} duplicate(s)`},D.json,D);return}if(I==="stats"){let J=await L.listAll(),W=J.items.filter((f)=>!f.archived),X=W.length,R=J.items.length-X,T=W.filter((f)=>f.url).length,Y=W.filter((f)=>f.tags&&f.tags.length>0).length,Q=X>0?W.map((f)=>f.created_at).sort()[0]:null,F=X>0?W.map((f)=>f.created_at).sort()[X-1]:null,q={};for(let f of W)for(let l of f.tags||[])q[l]=(q[l]||0)+1;let Z=Object.entries(q).sort((f,l)=>l[1]-f[1]).slice(0,5).map(([f,l])=>({tag:f,count:l}));k({ok:!0,total:X,archived:R,with_url:T,with_tags:Y,oldest:Q,newest:F,top_tags:Z,store_exists:J.exists,message:`${X} items | ${T} with URL | ${Y} with tags`},D.json,D);return}let z=_f($[0]),G=z?` Did you mean '${z}'?`:"";throw j0("warn","Unknown command",{input:$[0],suggestion:z}),Error(`Unknown command: ${$[0]}.${G} Run 'knowledge --help' for available commands.`)}finally{await A?.close(),await N.close()}}function Vf(_,$){let D=_ instanceof Error?_.message:String(_);j0("debug","CLI error",{message:D,stack:_ instanceof Error?_.stack:void 0}),console.error(`Error: ${D}`);let I=_ instanceof z0?_:null;if($.includes("--json"))k({ok:!1,error:D,message:D,...I?{code:"version_conflict",expected:I.expected,current:I.current}:{}},!0);process.exitCode=I?2:1}if(import.meta.main){let _=process.argv.slice(2);Ff(_).catch(($)=>Vf($,_))}export{_f as suggestCommand,Tf as sortItems,Ff as run,er as parseArgs,Vf as emitCliError}; +`)}function RY(_){return!_||_==="local"||_==="localhost"}function N0(_){if(!_.id)throw Error("Missing required --id. Example: knowledge get --id <id>")}function Tf(_,$){let D=$.sort??"created";if(D!=="created"&&D!=="title")throw Error("Invalid --sort value. Use 'created' or 'title'.");let I=[..._].sort((U,E)=>{if(D==="title")return U.title.localeCompare(E.title);return U.created_at.localeCompare(E.created_at)});if($.desc)I.reverse();return{sorted:I,sort:D,direction:$.desc?"desc":"asc"}}async function Ff(_){if(await Df(_))return;let{positional:$,flags:D}=er(_);if(A0("debug","CLI invoked",{command:$[0],flags:{json:D.json,store:D.store}}),D.version){console.log(D.json?JSON.stringify({name:E$.name,version:E$.version},null,2):`${E$.name} ${E$.version}`);return}if(D.completions){let S=D.completions;if(S==="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 project-registration project-membership project-resources project-resource paths mode guarded 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 --operation-id --step-id --idempotency-key --slug --name --collection-id --collection-slug --collection-name --item-id --receipt-id --cursor --kind --all --contract --source-ref --allow-global" -- "$cur")); }; complete -F _knowledge knowledge');else if(S==="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 project-registration project-membership project-resources project-resource paths mode guarded 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" "(--all)--all" "(--contract)--contract" "(--allow-global)--allow-global" "(-p --page)"{-p,--page}"[page number]:number:" "(-l --limit)"{-l,--limit}"[items per page]:number:" "(--search)--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]:" "(--operation-id)--operation-id[registration operation id]:" "(--step-id)--step-id[registration step id]:" "(--idempotency-key)--idempotency-key[caller idempotency key]:" "(--slug)--slug[project slug]:" "(--name)--name[project name]:" "(--collection-id)--collection-id[exact collection id]:" "(--collection-slug)--collection-slug[collection slug]:" "(--collection-name)--collection-name[collection name]:" "(--item-id)--item-id[exact item id]:" "(--receipt-id)--receipt-id[exact receipt id]:" "(--cursor)--cursor[resource cursor]:" "(--kind)--kind[resource kind]:(project collection item taxonomy):" "(--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(S==="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 project-registration project-membership project-resources project-resource paths mode guarded 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 operation-id; complete -c knowledge -l step-id; complete -c knowledge -l idempotency-key; complete -c knowledge -l slug; complete -c knowledge -l name; complete -c knowledge -l collection-id; complete -c knowledge -l collection-slug; complete -c knowledge -l collection-name; complete -c knowledge -l item-id; complete -c knowledge -l receipt-id; complete -c knowledge -l cursor; complete -c knowledge -l kind -a "project collection item taxonomy"; complete -c knowledge -l all; 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 I=ar($[0]),U=1,E=$f()&&I&&!QY.includes(I);if(!I||D.help||I==="help"){let S=I==="help"?$[1]:I||$[1];If(S);return}if(I==="mode"){let S=B3(process.env);k(D.json||D.verbose?{ok:!0,...S}:Nf(S),D.json,D);return}if(I==="guarded"){if(($[1]??"capabilities")!=="capabilities")throw Error("Usage: knowledge guarded capabilities [--json]");k({ok:!0,contract:"FCAME-1",private_input:!0,private_result:!0,exact_title_lookup:!0,private_transport_body_output:!1},D.json,D);return}V3(process.env,{storePathOverridden:Boolean(D.store)});let j=I==="project-panel"||I==="app-wiki"?D.scope??"project":D.scope,N=gN({scope:j}),O;try{if(I==="storage"){let J=$[1]??"status";if(J==="import-legacy"){if(D.scope&&D.scope!=="global")throw Error("knowledge storage import-legacy only supports --scope global because ~/.open-knowledge is a global legacy store.");let P=oN({dryRun:D.dryRun});if(k(P,D.json),!P.ok)process.exitCode=1;return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}}let S=Boolean(D.store),L=D.store;if(!L)if(j==="project"||j==="local")L=N.workspace.jsonStorePath;else L=y1();let W=o1({storePath:L,storePathOverridden:S});if(E&&await tr($,I,W))I="ask",U=0;if(!S&&(I==="ask"||I==="build")&&!h$())xD(L);let g=()=>{if(!S||h$())return N.projectLinksAuthority();return O??=SN({databasePath:mr(dr(L),"knowledge.db"),itemStore:W,options:{packageVersion:E$.version,authorityId:process.env.HASNA_KNOWLEDGE_PROJECT_AUTHORITY_ID??"knowledge",tenantId:process.env.HASNA_KNOWLEDGE_PROJECT_TENANT_ID??"local",corpusId:process.env.HASNA_KNOWLEDGE_PROJECT_CORPUS_ID??"knowledge"}}),O};if(I==="project-registration"){let J=$[1]??"capability",P=g();if(J==="capability"){k({ok:!0,capability:await P.capability()},D.json,D);return}if(J==="create"){let X=await P.capability(),R=D.project,T=D.slug,Y=D.name;if(!D.operationId||!D.stepId||!D.idempotencyKey||!R||!T||!Y)throw Error("Usage: knowledge project-registration create --operation-id <id> --step-id <id> --idempotency-key <key> --project <id> --slug <slug> --name <name> [--collection-slug <slug>] [--collection-name <name>] [--json]");let Q={collection_slug:D.collectionSlug??`${T}-knowledge`,collection_name:D.collectionName??`${Y} Knowledge`},F=V_({action:"register_collection",source_project_id:R,project_slug:T,project_name:Y,collection_slug:Q.collection_slug,collection_name:Q.collection_name,membership_rule:"explicit_collection_binding"}),B=await P.registerCollection({operation_id:D.operationId,step_id:D.stepId,resource_kind:"collection",direction:"forward",authority_route:q$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,target_selector:R,idempotency_key:D.idempotencyKey,request_digest:F,precondition_digest:V_({source_project_id:R,expected:"absent_or_exact_match"}),project_id:R,project_slug:T,project_name:Y,desired:Q});k({ok:B.outcome==="accepted",receipt:B},D.json,D);return}if(J==="read-exact"){if(!D.collectionId)throw Error("Usage: knowledge project-registration read-exact --collection-id <uuid> [--json]");k({ok:!0,record:await P.readCollection(D.collectionId)},D.json,D);return}if(J==="receipt"){let X=$[2],R=$[3];if(!D.operationId||!D.stepId||!D.idempotencyKey||!X||!R)throw Error("Usage: knowledge project-registration receipt <register_collection|bind_item> <forward|inverse> --operation-id <id> --step-id <id> --idempotency-key <key> [--json]");let T=await P.capability(),Y=await P.lookupReceipt({authority_id:T.authority_id,tenant_id:T.tenant_id,corpus_id:T.corpus_id,operation_id:D.operationId,step_id:D.stepId,action:X,direction:R,idempotency_key:D.idempotencyKey,max_items:1});k({ok:!0,receipt:Y},D.json,D);return}if(J==="compensate"||J==="verify-inverse"){if(!D.operationId||!D.stepId||!D.idempotencyKey||!D.receiptId)throw Error(`Usage: knowledge project-registration ${J} --operation-id <id> --step-id <id> --idempotency-key <key> --receipt-id <accepted-receipt-id> [--json]`);let X=await P.capability(),R={operation_id:D.operationId,step_id:D.stepId,authority_route:q$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,idempotency_key:D.idempotencyKey,accepted_receipt_id:D.receiptId},T=J==="compensate"?{receipt:await P.compensateRegistration(R)}:{verification:await P.verifyRegistrationInverse(R)};k({ok:!0,...T},D.json,D);return}throw Error("Invalid project-registration action. Use capability, create, read-exact, receipt, compensate, or verify-inverse.")}if(I==="project-membership"){let J=$[1]??"read-exact",P=g();if(J==="bind"){if(!D.operationId||!D.stepId||!D.idempotencyKey||!D.collectionId||!D.itemId)throw Error("Usage: knowledge project-membership bind --operation-id <id> --step-id <id> --idempotency-key <key> --collection-id <uuid> --item-id <id> [--json]");let X=await P.capability(),R=await P.bindItem({operation_id:D.operationId,step_id:D.stepId,direction:"forward",authority_route:q$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,idempotency_key:D.idempotencyKey,request_digest:V_({action:"bind_item",collection_id:D.collectionId,item_id:D.itemId}),precondition_digest:V_({collection_id:D.collectionId,item_id:D.itemId,expected:"unbound_or_exact_membership"}),collection_id:D.collectionId,item_id:D.itemId});k({ok:R.outcome==="accepted",receipt:R},D.json,D);return}if(J==="read-exact"){if(!D.collectionId||!D.itemId)throw Error("Usage: knowledge project-membership read-exact --collection-id <uuid> --item-id <id> [--json]");k({ok:!0,record:await P.readItemBinding(D.collectionId,D.itemId)},D.json,D);return}if(J==="compensate"||J==="verify-inverse"){if(!D.operationId||!D.stepId||!D.idempotencyKey||!D.receiptId)throw Error(`Usage: knowledge project-membership ${J} --operation-id <id> --step-id <id> --idempotency-key <key> --receipt-id <accepted-receipt-id> [--json]`);let X=await P.capability(),R={operation_id:D.operationId,step_id:D.stepId,authority_route:q$,package_version:X.package_version,authority_id:X.authority_id,tenant_id:X.tenant_id,corpus_id:X.corpus_id,idempotency_key:D.idempotencyKey,accepted_receipt_id:D.receiptId},T=J==="compensate"?{receipt:await P.compensateItemBinding(R)}:{verification:await P.verifyItemBindingInverse(R)};k({ok:!0,...T},D.json,D);return}throw Error("Invalid project-membership action. Use bind, read-exact, compensate, or verify-inverse.")}if(I==="project-resources"){let J=D.project??$[1];if(!J)throw Error("Usage: knowledge project-resources <project-id> [--kind <kind>]... [--limit <n>] [--cursor <cursor>] [--all] [--json]");let P=g(),X=D.kind,R=D.all?{resources:await P.readAllProjectResources(J,{limit:D.limit,kinds:X})}:await P.listProjectResources(J,{limit:D.limit,cursor:D.cursor,kinds:X});k({ok:!0,...R},D.json,D);return}if(I==="project-resource"){let J=D.project??$[1],P=$[2],X=$[3];if(!J||!P||!X)throw Error("Usage: knowledge project-resource <project-id> <project|collection|item|taxonomy> <resource-id> [--json]");k({ok:!0,resource:await g().readProjectResource(J,P,X)},D.json,D);return}if(I==="inventory"){let J=await N.resolveInventory({limit:D.limit,includeArchived:D.includeArchived||D.archived,storePath:h$()?void 0:L});k(D.json||D.verbose?J:Of(J),D.json,D);return}if(I==="project-panel"){let J=D.project??$[1];if(!J)throw Error("Usage: knowledge project-panel --project <id|name|slug> [--json|--contract]");let P=await K8(J,{service:N,limit:D.limit,storePath:h$()?void 0:L,includeArchived:D.includeArchived||D.archived});k(D.json||D.contract?P:T8(P),D.json||D.contract);return}if(I==="paths"){let J=N.paths();k(D.json||D.verbose?J:Af(J),D.json,D);return}if(I==="setup"){let J=N.setup({mode:D.mode,apiUrl:D.apiUrl,canonicalExample:D.canonicalExample});k(J,D.json,D);return}if(I==="auth"){let J=$[1]??"whoami";if(J==="whoami"||J==="status"){let P=N.authStatus(process.env);k({ok:!0,...P,message:P.authenticated?`Authenticated via ${P.source}`:"Not authenticated"},D.json,D);return}if(J==="login"){let P=D.apiKey??process.env.KNOWLEDGE_API_KEY??process.env.HASNA_KNOWLEDGE_API_KEY;if(!P)throw Error("Usage: knowledge auth login --api-key <key> [--email <email>]");let X=N.saveAuth({apiKey:P,email:D.email,orgSlug:D.org,orgId:D.orgId,userId:D.userId,apiUrl:D.apiUrl},process.env);k({ok:!0,authenticated:!0,email:X.email??null,org_slug:X.org_slug??null,api_url:X.api_url??N.authStatus(process.env).api_url,auth_path:N.authStatus(process.env).auth_path,message:`Saved hosted credentials for ${X.email??"API key"}`},D.json,D);return}if(J==="logout"){let P=N.clearAuth(process.env);k({ok:!0,removed:P,message:P?"Removed hosted credentials":"No hosted credentials found"},D.json,D);return}throw Error("Invalid auth action. Use 'login', 'whoami', or 'logout'.")}if(I==="storage"){let J=$[1]??"status";if(J==="status"){let P=N.storageContract(),X=N.validateStorage();k({ok:X.ok,...P,validation:X,message:`${P.storage_type} artifact storage at ${P.artifact_store.uri_prefix}`},D.json,D);return}if(J==="validate"){let P=N.validateStorage();if(k({ok:P.ok,validation:P,message:P.ok?"Storage contract valid":`Storage contract invalid: ${P.errors.join("; ")}`},D.json,D),!P.ok)process.exitCode=1;return}if(J==="repair-artifact-keys"||J==="repair-keys"){let P=N.repairArtifactManifestKeys({approveWrite:D.approveWrite,approvedBy:D.approvedBy,dryRun:D.dryRun});k(P,D.json,D);return}if(J==="migrate-legacy-path"||J==="migrate-legacy"||J==="migrate-path"){let P=N.migrateLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(P,D.json),!P.ok&&!D.json)process.exitCode=1;return}if(J==="merge-legacy-path"||J==="merge-legacy"||J==="merge-path"){let P=N.mergeLegacyPath({approveWrite:D.approveWrite,approvedBy:D.approvedBy});if(k(P,D.json),!P.ok&&!D.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(I==="machines"){let J=$[1]??"topology";if(J==="topology"||J==="status"){let P=await N.machineTopology({includeTailscale:D.tailscale!==!1});k(D.json||D.verbose?P:Pf(P),D.json,D);return}if(J==="preflight"||J==="check"){let P=$[2]??D.machine??"local",X=D.workspace??process.cwd(),R=await N.machinePreflight({machineId:P,commands:[{command:"bun",required:!0},{command:"knowledge",required:!0}],packages:[{name:E$.name,command:"knowledge",expectedVersion:E$.version,required:!0},{name:"@hasna/machines",command:"machines",required:!1}],workspaces:[{label:"open-knowledge",path:X,expectedPackageName:E$.name,expectedVersion:E$.version,required:!0}]});if(k(D.json||D.verbose?R:zf(R),D.json,D),!R.ok&&!D.json)process.exitCode=1;return}throw Error("Invalid machines action. Use 'topology' or 'preflight'.")}if(I==="sync"){let J=$[1]??"status",P=D.tables?D.tables.split(",").map((X)=>X.trim()).filter(Boolean):void 0;if(J==="status"){let X=N.syncStatus();k(D.json||D.verbose?X:gf(X),D.json,D);return}if(J==="doctor"||J==="readiness"||J==="preflight"){let X=await N.syncDoctor({machine:D.machine??null,peerWorkspace:D.peerWorkspace??null,includeTailscale:D.tailscale!==!1,tables:P}),R={package:{name:E$.name,version:E$.version},...X};if(k(D.json||D.verbose?R:Xf(R),D.json,D),!X.ok&&!D.json)process.exitCode=1;return}if(J==="snapshot"||J==="record"){let X=await N.createSyncSnapshot({includeTailscale:D.tailscale!==!1,machineId:D.machine});k(D.json||D.verbose?X:Gf(X),D.json,D);return}if(J==="conflicts"||J==="conflict"){let X=$[2];if(X==="show"||X==="get"){let Y=$[3]??D.id;if(!Y)throw Error("Usage: knowledge sync conflicts show <id>");let Q=N.syncConflict(Y);k({ok:!0,conflict:Q,message:`Sync conflict ${Y}`},D.json,D);return}if(X==="propose"||X==="proposal"){let Y=$[3]??D.id;if(!Y)throw Error("Usage: knowledge sync conflicts propose <id>");k(D.mode==="ai"?await N.proposeSyncConflictResolutionWithAi({id:Y,modelRef:D.model,fake:D.fake}):N.proposeSyncConflictResolution(Y),D.json,D);return}if(X==="resolve"){let Y=$[3]??D.id;if(!Y)throw Error("Usage: knowledge sync conflicts resolve <id> --approve-write --approved-by <name> [--strategy <name>]");let Q=N.resolveSyncConflict({id:Y,strategy:D.strategy,approvedBy:D.approvedBy,approveWrite:D.approveWrite,proposedPatchUri:D.patchUri});if(k(Q,D.json,D),!Q.ok&&!D.json)process.exitCode=1;return}let R=N.syncConflicts({status:X,limit:D.limit}),T={ok:!0,conflicts:R,message:`${R.length} sync conflict(s)`};k(D.json||D.verbose?T:Rf(T),D.json,D);return}if(J==="machines"||J==="registry"){let X=N.syncMachines(),R={ok:!0,machines:X,message:`${X.length} registered sync machine(s)`};k(D.json||D.verbose?R:Yf(R),D.json,D);return}if(J==="export"){let X=N.exportSyncBundle({machineId:D.machine??null,tables:P,includeArtifactContent:D.artifactContent!==!1});k(X,!0);return}if(J==="import"){let X=await Bun.stdin.text();if(!X.trim())throw Error("Usage: knowledge sync import < bundle.json");let R=await N.importSyncBundle({bundle:JSON.parse(X),dryRun:D.dryRun,direction:"import",machineId:D.machine??null});k(D.json||D.verbose?R:GY(R,J),D.json,D);return}if(J==="dry-run"||J==="pull"||J==="push"||J==="sync"){if(!D.peerWorkspace&&RY(D.machine))throw Error(`Usage: knowledge sync ${J} --peer-workspace <repo-or-knowledge-home> [--scope project] +Remote machine sync can omit --peer-workspace when machines path mapping is configured.`);let X=J==="dry-run"?"both":J==="sync"?"both":J,R=!RY(D.machine)?await N.syncRemotePeer({direction:X,machine:D.machine,peerWorkspace:D.peerWorkspace,tables:P,dryRun:D.dryRun===!0||J==="dry-run",includeArtifactContent:D.artifactContent!==!1,includeTailscale:D.tailscale!==!1}):await N.syncPeer({peerWorkspace:D.peerWorkspace,direction:X,dryRun:D.dryRun===!0||J==="dry-run",tables:P,includeArtifactContent:D.artifactContent!==!1,machineId:D.machine??null});if(k(D.json||D.verbose?R:GY(R,J),D.json,D),!R.ok&&!D.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(I==="db"){let J=$[1]??"init";if(J==="init"){let P=N.initDb();k({ok:!0,...P,message:`Initialized ${P.path}`},D.json,D);return}if(J==="stats"){let P=N.dbStats();k({ok:!0,path:N.workspace.knowledgeDbPath,...P,message:`knowledge.db schema v${P.schema_version}`},D.json,D);return}if(J==="storage"){if(($[2]??"status")==="status"){let X=Pz({scope:D.scope});k({ok:!0,...X,message:`knowledge.db storage mode ${X.mode}`},D.json,D);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(I==="app-wiki"){let J=$[1]??"init";if(J==="paths"||J==="status"){k({ok:!0,standard:"hasna-app-wiki.v1",default_scope:"project",global_writes_require:"--allow-global",...N.paths()},D.json);return}if(J==="init"||J==="open"){let P=await N.initAppWiki({allowGlobal:D.allowGlobal});k(P,D.json);return}if(J==="note"||J==="notes"){let P=$[2]??"list";if(P==="add"||P==="create"){let X=D.title??$[3],R=D.content??$.slice(4).join(" ");if(!X||!R)throw Error("Usage: knowledge app-wiki note add --title <title> --content <text> [--source-ref <uri>]");let T=await N.addAppWikiNote({title:X,content:R,tags:D.tag,sourceRefs:D.sourceRef,allowGlobal:D.allowGlobal});k(T,D.json);return}if(P==="list"||P==="ls"){let X=N.listAppWikiNotes({limit:D.limit});k({ok:!0,scope:N.scope,home:N.workspace.home,notes:X,message:`${X.length} app wiki note(s)`},D.json);return}if(P==="get"||P==="show"){let X=$[3]??D.id;if(!X)throw Error("Usage: knowledge app-wiki note get <id-or-path>");let R=await N.getAppWikiNote(X,{includeContent:!0});if(!R)throw Error(`App wiki note not found: ${X}`);k(R,D.json);return}throw Error("Invalid app-wiki note action. Use 'add', 'list', or 'get'.")}if(J==="source"||J==="sources"){let P=$[2]??"add";if(P!=="add"&&P!=="ingest")throw Error("Invalid app-wiki source action. Use 'add'.");let X=$[3]??D.sourceRef?.[0];if(!X)throw Error("Usage: knowledge app-wiki source add <source-ref>");let R=await N.addAppWikiSourceRef({sourceRef:X,purpose:D.purpose,allowGlobal:D.allowGlobal});k({ok:!0,...R,message:`Added app wiki source ${R.source_ref}`},D.json);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki search <query>");let X=await N.searchAppWiki({query:P,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...X,message:`${X.results.length} app wiki result(s)`},D.json);return}if(J==="query"||J==="context"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge app-wiki query <query>");let X=await N.queryAppWiki({query:P,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...X,message:`${X.excerpts.length} app wiki excerpt(s)`},D.json);return}throw Error("Invalid app-wiki action. Use 'init', 'paths', 'note', 'source', 'search', or 'query'.")}if(I==="wiki"){let J=$[1]??"init";if(J==="init"){let P=await N.initWiki();k({ok:!0,...P,message:`Initialized wiki layout in ${N.workspace.home}`},D.json,D);return}if(J==="compile"){let P=$.slice(2),X=P.filter((Y)=>/^(open-files|file|s3|https?):\/\//.test(Y)),R=P.filter((Y)=>!/^(open-files|file|s3|https?):\/\//.test(Y)).join(" "),T=await N.compileWiki({title:D.title,query:R||D.search,sourceRefs:X.length>0?X:void 0,limit:D.limit});k({ok:!0,...T,message:`Compiled wiki page ${T.path}`},D.json,D);return}if(J==="file-answer"||J==="answer"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge wiki file-answer <prompt> --content <answer> --approve-write");if(!D.content)throw Error("Missing --content <answer> for wiki file-answer.");let X=await N.fileAnswer({prompt:P,answer:D.content,approveWrite:D.approveWrite,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...X},D.json,D);return}if(J==="lint"){let P=N.lintWiki();k({ok:P.ok,...P,message:P.ok?"Wiki lint passed":`Wiki lint found ${P.issue_count} issue(s)`},D.json,D);return}throw Error("Invalid wiki action. Use 'init', 'compile', 'file-answer', or 'lint'.")}if(I==="safety"){let J=$[1]??"status",P=N.ensureWorkspace(),X=N.safetyPolicy();N.initDb();let R=w(P.knowledgeDbPath);try{if(J==="status"){k({ok:!0,mode:X.mode,workspace:P.home,allow_write_roots:X.allowWriteRoots,read_only_source_access:X.readOnlySourceAccess,network:X.network,redaction:X.redaction,approvals:X.approvals,message:`Safety policy: ${X.mode}`},D.json,D);return}if(J==="check"){let T=$[2]??"generated_write",Y=$[3]??null,Q;try{if(T==="web_search")Y0(X),Q={action:T,target_uri:Y,approval_required:!1,approved:!0,decision:"allow"};else if(T==="s3_read"){if(!Y)throw Error("safety check s3_read requires an s3:// target.");Z6(Y,X),Q={action:T,target_uri:Y,approval_required:!1,approved:!0,decision:"allow"}}else Q=jg(R,X,T,Y);R_(R,{event_type:"safety_check",action:T,target_uri:Y,decision:Q.decision==="allow"?"allow":"requires_approval",metadata:Q}),k({ok:!0,...Q,message:`Safety check ${Q.decision}`},D.json,D);return}catch(F){throw R_(R,{event_type:"safety_check",action:T,target_uri:Y,decision:"deny",metadata:{error:F instanceof Error?F.message:String(F)}}),F}}if(J==="approve"){let T=$[2]??"generated_write",Y=$[3]??null,Q=_I(R,{action:T,target_uri:Y,reason:"local-cli approval",metadata:{scope:D.scope??"global"}});R_(R,{event_type:"approval",action:T,target_uri:Y,decision:"allow",metadata:{approval_id:Q.id}}),k({ok:!0,...Q,action:T,target_uri:Y,message:`Approved ${T}`},D.json,D);return}if(J==="audit"){let T=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((Y)=>({id:Y.id,event_type:Y.event_type,action:Y.action,target_uri:Y.target_uri,decision:Y.decision,metadata:JSON.parse(Y.metadata_json),created_at:Y.created_at}));k({ok:!0,events:T,message:`${T.length} audit event(s)`},D.json,D);return}if(J==="redact"){let T=$.slice(2).join(" ");if(!T)throw Error("Usage: knowledge safety redact <text>");let Y=u_(T,X);if(Y.findings.length>0)Q0(R,{source_uri:"safety://redact",findings:Y.findings,metadata:{command:"safety redact"}});R_(R,{event_type:"redaction",action:"safety_redact",target_uri:"safety://redact",decision:Y.findings.length>0?"redacted":"allow",metadata:{findings:Y.findings.length}}),k({ok:!0,text:Y.text,findings:Y.findings,message:`Redacted ${Y.findings.length} finding(s)`},D.json,D);return}throw Error("Invalid safety action. Use 'status', 'check', 'approve', 'audit', or 'redact'.")}finally{R.close()}}if(I==="source"){if(($[1]??"")!=="resolve")throw Error("Invalid source action. Use 'resolve'.");let P=$[2];if(!P)throw Error("Usage: knowledge source resolve <source-ref>");let X=await N.resolveSource(P,{purpose:D.purpose,limit:D.limit});k({ok:!0,...X,message:X.resolved?`Resolved ${X.source_ref} (${X.content.chunks_returned}/${X.content.chunks_total} chunks)`:`Source not indexed: ${P}`},D.json,D);return}if(I==="ingest"){let J=$[1]??"";if(J==="rules"||J==="global-rules"||J==="agent-rules"){let P=await N.importRulesProvenance({root:D.workspace??process.cwd(),owner:D.owner,dryRun:D.dryRun===!0,maxItems:D.maxItems,limit:D.limit});k({ok:!0,...P},D.json);return}if(J==="manifest"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest manifest <file|s3://bucket/key>");let X=await N.ingestManifest(P);k({ok:!0,...X,message:`Ingested ${X.items_seen} manifest item(s)`},D.json,D);return}if(J==="source"){let P=$[2];if(!P)throw Error("Usage: knowledge ingest source <source-ref>");let X=await N.ingestSource(P,D.purpose);k({ok:!0,...X,message:`Ingested source ${X.source_ref} (${X.chunks_inserted} chunks)`},D.json,D);return}throw Error("Invalid ingest action. Use 'manifest' or 'source'.")}if(I==="reindex"){let J=$[1]??"status";if(J==="status"){let P=N.reindexHealth({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...P,message:`${P.missing_embeddings} chunk(s) missing embeddings`},D.json,D);return}if(J==="enqueue"){let P=N.enqueueReindex({modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...P,message:`Queued ${P.enqueued} embedding refresh item(s)`},D.json,D);return}if(J==="embeddings"){let P=await N.refreshEmbeddings({full:D.full,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...P,message:`Embedded ${P.indexed.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="outbox"){let P=$[2];if(!P)throw Error("Usage: knowledge reindex outbox <file|s3://bucket/key>");let X=await N.consumeOutbox(P);k({ok:!0,...X,message:`Consumed ${X.events_seen} outbox event(s)`},D.json,D);return}throw Error("Invalid reindex action. Use 'status', 'enqueue', 'embeddings', or 'outbox'.")}if(I==="embeddings"){let J=$[1]??"status";if(J==="status"){let P=N.embeddingStatus();k({ok:!0,...P,message:`${P.total_vector_entries} vector index entries`},D.json,D);return}if(J==="index"){let P=await N.indexEmbeddings({limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake});k({ok:!0,...P,message:`Embedded ${P.chunks_embedded} chunk(s)`},D.json,D);return}if(J==="search"){let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge embeddings search <query>");let X=await N.semanticSearch({query:P,limit:D.limit,modelRef:D.model,dimensions:D.dimensions,fake:D.fake}),R={ok:!0,...X,message:`${X.results.length} semantic result(s)`};k(D.json||D.verbose?R:Wf(R),D.json,D);return}throw Error("Invalid embeddings action. Use 'status', 'index', or 'search'.")}if(I==="context"){if(($[1]??"pack")!=="pack")throw Error("Invalid context action. Use 'pack'.");let P=D.from??"search";if(!["search","loops","runs"].includes(P))throw Error("Invalid --from value. Use 'search', 'loops', or 'runs'.");let X=$.slice(2).join(" ")||D.topic||"",R=await N.contextPack({source:P,purpose:P==="loops"||P==="runs"?"proposal":"agent_context",query:X,topic:D.topic,since:D.since,dedupe:D.dedupe,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:L});XY({ok:!0,...R,message:R.message});return}if(I==="proposals"){if(($[1]??"context")!=="context")throw Error("Invalid proposals action. Use 'context'.");let P=D.from??"loops";if(!["loops","runs"].includes(P))throw Error("Invalid --from value for proposals. Use 'loops' or 'runs'.");let X=D.topic??$.slice(2).join(" ");if(!X.trim())throw Error("Usage: knowledge proposals context --from loops --topic <text>");let R=await N.contextPack({source:P,purpose:"proposal",query:X,topic:X,since:D.since,dedupe:D.dedupe??!0,maxTokens:D.maxTokens,maxItems:D.maxItems,limit:D.limit});XY({ok:!0,...R,message:R.message});return}if(I==="search"){let J=$.slice(1).join(" ");if(!J)throw Error("Usage: knowledge search <query>");if(D.context){let R=await N.retrieveContext({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:L}),T={ok:!0,...R,message:`${R.excerpts.length} context excerpt(s)`};k(D.json||D.verbose?T:Lf(T),D.json,D);return}let P=await N.search({query:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,legacyStorePath:L}),X={ok:!0,...P,message:`${P.results.length} search result(s)`};k(D.json||D.verbose?X:Sf(X),D.json,D);return}if(I==="web"){if(($[1]??"search")!=="search")throw Error("Invalid web action. Use 'search'.");let P=$.slice(2).join(" ");if(!P)throw Error("Usage: knowledge web search <query>");let X=await N.webSearch({query:P,limit:D.limit,modelRef:D.model,provider:D.provider,domains:D.domain,fake:D.fake,fileResults:D.fileResults}),R={ok:!0,...X,message:`${X.sources.length} web source(s)`};k(D.json||D.verbose?R:Jf(R),D.json,D);return}if(I==="ask"||I==="build"){let J=$.slice(U).join(" ");if(!J)throw Error("Usage: knowledge ask <prompt>");let P=await N.runPrompt({prompt:J,limit:D.limit,semantic:D.semantic,modelRef:D.model,dimensions:D.dimensions,fake:D.fake,generate:D.generate,approveWrite:D.approveWrite,legacyStorePath:L}),X={ok:!0,...P,message:P.generated?"Generated answer with citations":"Prepared citation context draft"};k(D.json||D.verbose?X:Qf(X),D.json,D);return}if(I==="providers"){let J=$[1]??"status";if(J==="status"){let P=N.providerStatus(),X=P.providers.filter((R)=>R.configured).length;k({ok:!0,...P,message:`${X}/${P.providers.length} provider credential(s) configured`},D.json,D);return}if(J==="models"){let P=N.modelRegistry();k({ok:!0,models:P,message:`${P.length} model alias(es)`},D.json,D);return}if(J==="check"){let P=$[2]??"default",X=T$(P,N.config()),R=f_(X),T=S4(R.provider,N.config());k({ok:!0,target:P,model_ref:X,provider:R.provider,model:R.model,credential:T,message:`${R.provider} credentials configured`},D.json,D);return}throw Error("Invalid providers action. Use 'status', 'models', or 'check'.")}if(I==="add"){let J=$[1],P=$[2];if(!J||!P)throw Error("Usage: knowledge add <title> <content>");let X=await W.create({title:J,content:P,url:D.url??null,tags:D.tag??[]});A0("info","Item added",{id:X.id,title:X.title,tags:X.tags?.length??0,transport:W.kind}),k({ok:!0,item:X,message:`Added ${X.id}`},D.json,D);return}if(I==="list"){if(D.format!==void 0&&D.format!=="table"&&D.format!=="json")throw Error("Invalid --format value for list. Use 'table' or 'json'.");if(D.page!==void 0&&(!Number.isFinite(D.page)||!Number.isInteger(D.page)||D.page<1))throw Error("--page must be a positive integer.");if(D.limit!==void 0&&(!Number.isFinite(D.limit)||!Number.isInteger(D.limit)||D.limit<1||D.limit>200))throw Error("--limit must be an integer between 1 and 200.");let J=D.page??1,P=D.limit??20,X=D.search?String(D.search).toLowerCase():"",R=D.tagRaw??D.tag??[],T=D.tag?.length?D.tag.map((G_)=>G_.toLowerCase()).join(","):"none",Y=D.format==="table"||!D.json&&!D.format&&Ef(D),Q=D.json||D.format==="json",F=D.archived?"archived":D.includeArchived?"all":"active",{sort:B,direction:b}=Tf([],D),f=(J-1)*P;if(f>1e4)throw Error("The requested page exceeds the maximum bounded offset of 10000.");let l=await W.list({search:X,tags:R,archive:F,sort:B,direction:b,limit:P,offset:f}),U_=l.items,j_=Math.max(1,Math.ceil(l.total/P)),_$={ok:!0,page:J,limit:P,total:l.total,total_pages:j_,sort:B,direction:b,items:U_,store_exists:l.exists};if(Q){k(_$,!0);return}if(D.verbose){k(_$,!1,D);return}if(U_.length===0){k(`No items found (search=${X||"none"}, tag=${T})`,!1);return}if(Y){let G_=(E_)=>E_,K$=`${G_("ID")} ${G_("TITLE")} ${G_("CREATED")} ${G_("URL")} ${G_("TAGS")}`;console.log(K$);for(let E_ of U_)console.log(`${E_.id} ${G_(I_(E_.title,80))} ${E_.created_at} ${E_.url?G_(I_(E_.url,90)):""} ${E_.tags?.length?G_(I_(`[${E_.tags.join(", ")}]`,80)):""}`);console.log(`Page ${J}/${j_} | showing ${U_.length} of ${l.total} | sort=${B} ${b} | search=${X||"none"} | tag=${T}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}else{for(let G_ of U_)console.log(`${G_.id} ${I_(G_.title,80)} ${G_.created_at}${G_.url?` ${I_(G_.url,90)}`:""}${G_.tags?.length?` ${I_(`[${G_.tags.join(", ")}]`,80)}`:""}`);console.log(`Page ${J}/${j_} | showing ${U_.length} of ${l.total} | sort=${B} ${b} | search=${X||"none"} | tag=${T}`),console.log("Hint: use `knowledge get --id <id> --json` for full item content.")}return}if(I==="get"){N0(D);let J=await W.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);k({ok:!0,item:J,store_exists:W.exists,message:`${J.id}: ${J.title}`},D.json,D);return}if(I==="versions"){N0(D);let J=Number.isFinite(D.page)&&D.page>0?D.page:1,P=Number.isFinite(D.limit)&&D.limit>0?D.limit:void 0,X=await W.listVersions(D.id,{limit:P,offset:(J-1)*(P??50)});if(!X)throw Error(`Item not found: ${D.id}`);let R={ok:!0,id:X.item_id,current_version:X.current_version,total:X.total,page:J,store:W.location,versions:X.items,message:X.total===0?`${X.item_id} is at version ${X.current_version} with no retained prior versions`:`${X.item_id} is at version ${X.current_version}; ${X.total} prior version(s) retained`};if(D.json||D.verbose){k(R,D.json,D);return}console.log(R.message);for(let T of X.items){let Y=T.actor?` by ${T.actor}`:"",Q=T.reason?` (${T.reason})`:"";console.log(`v${T.version} ${T.valid_to}${Y}${Q} ${T.content_bytes} bytes ${T.content_hash.slice(0,12)}`)}if(X.items.length>0)console.log("Hint: `knowledge diff --id <id> --rev <n>` shows what changed.");return}if(I==="diff"){N0(D);let J=await W.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.rev!==void 0&&(D.from!==void 0||D.to!==void 0))throw Error("Use either --rev <n> or --from <a> --to <b>, not both.");let P=()=>({title:J.title,content:J.content,url:J.url,tags:J.tags??[],metadata:J.metadata??{},archived:J.archived??!1}),X=`v${J.version??"?"} (current)`,R=async(b)=>{if(b==="current")return{label:X,snapshot:P()};let f=Number(b);if(!Number.isInteger(f)||f<1)throw Error(`Not a version number: ${b}`);if(J.version!==void 0&&f===J.version)return{label:X,snapshot:P()};let l=await W.getVersion(J.id,f);if(!l)throw Error(`No version ${f} retained for ${J.id} (it is at version ${J.version??"?"}). Run \`knowledge versions --id <id>\` to see what is retained.`);return{label:`v${l.version}`,snapshot:{title:l.title,content:l.content,url:l.url,tags:l.tags,metadata:l.metadata,archived:l.archived}}},T,Y;if(D.rev!==void 0){if(!Number.isInteger(D.rev)||D.rev<1)throw Error("--rev must be a positive version number.");if(D.rev===1)throw Error("Version 1 has no predecessor to diff against.");T=String(D.rev-1),Y=String(D.rev)}else if(D.from!==void 0||D.to!==void 0){if(D.from===void 0||D.to===void 0)throw Error("--from and --to must be given together.");T=D.from,Y=D.to}else{let b=await W.listVersions(J.id,{limit:1});if(!b)throw Error(`Item not found: ${D.id}`);if(b.items.length===0)throw Error(`${J.id} is at version ${b.current_version} with no retained prior versions to diff against.`);T=String(b.items[0].version),Y="current"}let Q=await R(T),F=await R(Y),B=k3(Q.snapshot,F.snapshot);if(D.json||D.verbose){k({ok:!0,id:J.id,from:Q.label,to:F.label,...B},D.json,D);return}console.log(C3(B,`${J.id} ${Q.label}`,`${J.id} ${F.label}`));return}if(I==="update"){N0(D);let J=await W.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);if(D.ifVersion!==void 0&&(!Number.isInteger(D.ifVersion)||D.ifVersion<1))throw Error(`Invalid --if-version ${JSON.stringify(String(D.ifVersion))}: must be a positive integer version number, e.g. the "version" field from a prior 'knowledge get'.`);let P={};if(D.title!==void 0)P.title=D.title;if(D.content!==void 0)P.content=D.content;if(D.url!==void 0)P.url=D.url;let X;if(D.tag!==void 0){if(X=gY(J.tags,D.tag),X.length>0)P.tags=[...J.tags??[],...X]}let R=D.ifVersion!==void 0?D.ifVersion:J.version,T=await W.update(J.id,P,{expectedVersion:R});k(Hz({ok:!0,item:T},`Updated ${T?.id??J.id}`,X),D.json,D);return}if(I==="archive"||I==="restore"){N0(D);let J=await W.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let P=await W.update(J.id,{archived:I==="archive"},{expectedVersion:J.version});k({ok:!0,item:P,message:`${I==="archive"?"Archived":"Restored"} ${P?.id??J.id}`},D.json,D);return}if(I==="untag"){if(N0(D),!D.tag?.length)throw Error("Missing required --tag. Example: knowledge untag --id <id> -t <tag>");let J=await W.get(D.id);if(!J)throw Error(`Item not found: ${D.id}`);let P=J.tags??[],X=new Set(P.map((f)=>f.toLowerCase())),R=new Set;for(let f of D.tagRaw??D.tag){let l=f.trim().toLowerCase();if(l.length>0&&X.has(l)){R.add(l);continue}for(let U_ of f.split(",").map((j_)=>j_.trim().toLowerCase()).filter((j_)=>j_.length>0))R.add(U_)}let T=P.filter((f)=>!R.has(f.toLowerCase())),Y=P.length-T.length,Q=[...R].filter((f)=>!X.has(f));if(Y===0)throw Error(`No matching tag on ${J.id}: ${Q.map((f)=>JSON.stringify(f)).join(", ")} not in [${P.map((f)=>JSON.stringify(f)).join(", ")}]`);let F=await W.update(J.id,{tags:T},{expectedVersion:J.version}),B=Q.length>0?` (not found: ${Q.map((f)=>JSON.stringify(f)).join(", ")})`:"",b={ok:!0,item:F,removed:Y,message:`Removed ${Y} tag${Y===1?"":"s"} from ${F?.id??J.id}${B}`};if(Q.length>0)b.not_found=Q;k(b,D.json,D);return}if(I==="upsert"){let J=D.title??$[1],P=D.content??$[2],X=D.id?await W.get(D.id):null;if(!X){if(!J||!P)throw Error("New item requires title and content. Example: knowledge upsert <title> <content> [--id <id>]");let Q=await W.create({id:D.id,title:J,content:P,url:D.url??null,tags:D.tag??[]});k(Hz({ok:!0,created:!0,item:Q},`Upserted ${Q.id}`,D.tag),D.json,D);return}let R={};if(J!==void 0)R.title=J;if(P!==void 0)R.content=P;if(D.url!==void 0)R.url=D.url;let T;if(D.tag!==void 0){if(T=gY(X.tags,D.tag),T.length>0)R.tags=[...X.tags??[],...T]}let Y=await W.update(X.id,R,{expectedVersion:X.version});k(Hz({ok:!0,created:!1,item:Y},`Upserted ${Y?.id??X.id}`,T),D.json,D);return}if(I==="delete"){if(N0(D),!D.yes)throw Error("Refusing delete without --yes. Re-run with: knowledge delete --id <id> --yes");if(!await W.delete(D.id))throw Error(`Item not found: ${D.id}`);A0("info","Item deleted",{id:D.id,transport:W.kind}),k({ok:!0,deleted_id:D.id,message:`Deleted ${D.id}`},D.json,D);return}if(I==="export"){let J=D.format??"json";if(J!=="json"&&J!=="jsonl")throw Error("Invalid --format. Use 'json' or 'jsonl'.");let P=await W.listAll();if(J==="jsonl")for(let X of P.items)console.log(JSON.stringify(X));else if(D.json||D.format==="json"||D.verbose)k({ok:!0,items:P.items,store_exists:P.exists},D.json||D.format==="json",D);else k(Kf(P.items,J),!1);return}if(I==="prune"){if(!D.yes)throw Error("Refusing prune without --yes. Re-run with: knowledge prune --yes [--older-than <days>] [--empty]");let{items:J}=await W.listAll(),P=D.olderThan!==void 0?new Date(Date.now()-D.olderThan*86400000):null,X=J.filter((Y)=>P!==null&&new Date(Y.created_at)<P||D.empty&&Y.content.trim().length===0),R=await W.deleteMany(X.map((Y)=>Y.id)),T=J.length-R;A0("info","Prune completed",{pruned:R,remaining:T,transport:W.kind}),k({ok:!0,pruned:R,remaining:T,message:`Pruned ${R} item(s)`},D.json,D);return}if(I==="dedupe"){if(!D.yes)throw Error("Refusing dedupe without --yes. Re-run with: knowledge dedupe --yes [--json]");let{items:J}=await W.listAll(),P=new Set,X=[];for(let Y of J){let Q=`${Y.title}\x00${Y.content}`;if(P.has(Q))X.push(Y);else P.add(Q)}let R=await W.deleteMany(X.map((Y)=>Y.id)),T=J.length-R;A0("info","Dedupe completed",{removed:R,remaining:T,transport:W.kind}),k({ok:!0,removed:R,remaining:T,message:`Dedupe removed ${R} duplicate(s)`},D.json,D);return}if(I==="stats"){let J=await W.listAll(),P=J.items.filter((f)=>!f.archived),X=P.length,R=J.items.length-X,T=P.filter((f)=>f.url).length,Y=P.filter((f)=>f.tags&&f.tags.length>0).length,Q=X>0?P.map((f)=>f.created_at).sort()[0]:null,F=X>0?P.map((f)=>f.created_at).sort()[X-1]:null,B={};for(let f of P)for(let l of f.tags||[])B[l]=(B[l]||0)+1;let b=Object.entries(B).sort((f,l)=>l[1]-f[1]).slice(0,5).map(([f,l])=>({tag:f,count:l}));k({ok:!0,total:X,archived:R,with_url:T,with_tags:Y,oldest:Q,newest:F,top_tags:b,store_exists:J.exists,message:`${X} items | ${T} with URL | ${Y} with tags`},D.json,D);return}let z=_f($[0]),G=z?` Did you mean '${z}'?`:"";throw A0("warn","Unknown command",{input:$[0],suggestion:z}),Error(`Unknown command: ${$[0]}.${G} Run 'knowledge --help' for available commands.`)}finally{await O?.close(),await N.close()}}function Vf(_,$){let D=_ instanceof Error?_.message:String(_);A0("debug","CLI error",{message:D,stack:_ instanceof Error?_.stack:void 0}),console.error(`Error: ${D}`);let I=_ instanceof G0?_:null;if($.includes("--json"))k({ok:!1,error:D,message:D,...I?{code:"version_conflict",expected:I.expected,current:I.current}:{}},!0);process.exitCode=I?2:1}if(import.meta.main){let _=process.argv.slice(2);Ff(_).catch(($)=>Vf($,_))}export{_f as suggestCommand,Tf as sortItems,Ff as run,er as parseArgs,Vf as emitCliError}; diff --git a/dist/index.js b/dist/index.js index dce37fa..4cd8614 100644 --- a/dist/index.js +++ b/dist/index.js @@ -17524,11 +17524,11 @@ function createKnowledgeCloudClient() { } // src/project-links.ts import { createHash as createHash2 } from "crypto"; -import { Database as Database2 } from "bun:sqlite"; var KNOWLEDGE_PROJECT_REGISTRATION_ROUTE = "knowledge.project-registration.v1"; var KNOWLEDGE_PROJECT_RESOURCES_ROUTE = "knowledge.project-resources.v1"; var KNOWLEDGE_PROJECT_REGISTRATION_SCHEMA_VERSION = 1; var KNOWLEDGE_PROJECT_MEMBERSHIP_RULE = "explicit_collection_binding"; +var KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD = 1; class KnowledgeProjectLinksError extends Error { code; @@ -17548,6 +17548,7 @@ function postgresSql(sql) { class PostgresProjectLinksSql { client; transactionClient; + kind = "postgres"; constructor(client, transactionClient) { this.client = client; this.transactionClient = transactionClient; @@ -17563,6 +17564,9 @@ class PostgresProjectLinksSql { const result = await this.client.query(postgresSql(sql), params); return { changes: result.rowCount }; } + async lock(key) { + await this.client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [key]); + } async transaction(fn) { if (!this.transactionClient) return fn(this); @@ -17572,6 +17576,7 @@ class PostgresProjectLinksSql { class SqliteProjectLinksSql { db; + kind = "sqlite"; tail = Promise.resolve(); closed = false; constructor(db) { @@ -17594,6 +17599,7 @@ class SqliteProjectLinksSql { const result = this.db.query(sql).run(...params); return { changes: Number(result.changes) }; } + async lock(_key) {} transaction(fn) { const run = this.tail.then(async () => { this.db.exec("BEGIN IMMEDIATE"); @@ -17993,6 +17999,27 @@ class PackageOwnedKnowledgeProjectLinksAuthority { stableCollectionId(sourceProjectId, collectionSlug) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00collection\x00${sourceProjectId}\x00${collectionSlug}`); } + collectionFence(collectionId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "collection", + collectionId + ].join("\x1F"); + } + membershipFence(collectionId, itemId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "membership", + collectionId, + itemId + ].join("\x1F"); + } stableReceiptId(operationId, stepId, action, direction) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00receipt\x00${operationId}\x00${stepId}\x00${action}\x00${direction}`); } @@ -18086,6 +18113,7 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (request.request_digest !== expectedRequestDigest) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH", "request_digest does not bind the normalized collection-registration request.", { expected_request_digest: expectedRequestDigest }); } + const stableCollectionId = this.stableCollectionId(sourceProjectId, collectionSlug); return this.sql.transaction(async (tx) => { const duplicate = await this.getReceiptByAttempt(tx, { operation_id: request.operation_id, @@ -18097,12 +18125,13 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(stableCollectionId)); let aggregate = await this.getAggregateBySource(tx, sourceProjectId); const createdByOperation = aggregate === null; if (!aggregate) { const now = this.now(); const projectId = this.stableProjectId(sourceProjectId); - const collectionId = this.stableCollectionId(sourceProjectId, collectionSlug); + const collectionId = stableCollectionId; await tx.run(`INSERT INTO knowledge_projects ( authority_id, tenant_id, corpus_id, source_project_id, project_id, project_slug, project_name, created_at, updated_at @@ -18246,6 +18275,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "register_collection" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted collection-registration receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } const aggregate = accepted.collection_id ? await this.getAggregateByCollection(tx, accepted.collection_id) : null; let outcome = "accepted"; let reason = null; @@ -18385,6 +18417,8 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(collectionId)); + await tx.lock(this.membershipFence(collectionId, itemId)); const aggregate = await this.getAggregateByCollection(tx, collectionId); if (!aggregate) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge collection was not found by exact id."); @@ -18507,6 +18541,12 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "bind_item" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted item-binding receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } + if (accepted.collection_id && accepted.item_id) { + await tx.lock(this.membershipFence(accepted.collection_id, accepted.item_id)); + } let outcome = "accepted"; let reason = null; const membership = await tx.get(`SELECT * FROM knowledge_project_collection_memberships @@ -18622,6 +18662,341 @@ class PackageOwnedKnowledgeProjectLinksAuthority { digest: inverse.result_digest }; } + resourceBase(aggregate) { + return { + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + revision: `r${Number(aggregate.revision)}` + }; + } + projectResource(aggregate) { + const body = { + ...this.resourceBase(aggregate), + kind: "project", + id: aggregate.project_id, + title: aggregate.project_name, + locator: { kind: "canonical_uri", value: `knowledge:project:${aggregate.project_id}` }, + metadata: { + source_project_id: aggregate.source_project_id, + slug: aggregate.project_slug, + collection_count: 1 + } + }; + return { + ...body, + key: `project:${aggregate.project_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + collectionResource(aggregate, memberCount) { + const body = { + ...this.resourceBase(aggregate), + kind: "collection", + id: aggregate.collection_id, + title: aggregate.collection_name, + locator: { kind: "external_uuid", value: aggregate.collection_id }, + metadata: { + slug: aggregate.collection_slug, + membership_rule: KNOWLEDGE_PROJECT_MEMBERSHIP_RULE, + member_count: memberCount + } + }; + return { + ...body, + key: `collection:${aggregate.collection_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + itemResource(aggregate, item) { + const body = { + ...this.resourceBase(aggregate), + kind: "item", + id: item.id, + revision: `v${item.version ?? 1}`, + title: item.title, + locator: { kind: "canonical_uri", value: `knowledge:item:${encodeURIComponent(item.id)}` }, + metadata: { + tags: [...item.tags ?? []], + archived: item.archived === true, + updated_at: item.updated_at + } + }; + return { + ...body, + key: `item:${item.id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + taxonomyResource(aggregate, normalized, input) { + const taxonomyId = stableUuid(`${aggregate.collection_id}\x00taxonomy\x00${normalized}`); + const body = { + ...this.resourceBase(aggregate), + kind: "taxonomy", + id: taxonomyId, + title: input.label, + locator: { kind: "external_uuid", value: taxonomyId }, + metadata: { + tag: input.label, + normalized_tag: normalized, + item_count: input.itemCount, + member_digest: input.memberDigest + } + }; + return { + ...body, + key: `taxonomy:${taxonomyId}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + postgresItem(row) { + const parseJson = (value, fallback) => { + if (value == null) + return fallback; + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return fallback; + } + } + return value; + }; + return { + id: String(row.id), + short_id: row.short_id ?? null, + title: String(row.title ?? ""), + content: String(row.content ?? ""), + url: row.url ?? null, + tags: parseJson(row.tags, []), + metadata: parseJson(row.metadata, {}), + archived: Boolean(row.archived), + created_at: String(row.created_at), + updated_at: String(row.updated_at), + version: row.version == null ? 1 : Number(row.version) + }; + } + resourceCursorAfter(input) { + if (!input.cursor) + return ""; + let decoded; + try { + decoded = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")); + } catch { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT", "cursor is not a valid Knowledge project-resources cursor."); + } + if (decoded.version !== 1 || decoded.project_id !== input.aggregate.project_id || decoded.collection_id !== input.aggregate.collection_id || decoded.collection_revision !== input.revision || decoded.population_digest !== input.populationDigest || canonicalKnowledgeProjectLinksJson(decoded.kinds) !== canonicalKnowledgeProjectLinksJson(input.kinds) || typeof decoded.after !== "string") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE", "project resources changed or the cursor belongs to a different project/kind selection; restart from the first page."); + } + return decoded.after; + } + async listPostgresProjectResources(projectId, options, limit, kinds) { + const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); + if (!aggregate) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge project aggregate was not found by source or stable project id."); + } + const identityParams = [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]; + const population = await this.sql.get(`SELECT + COUNT(*)::text AS membership_count, + COUNT(i.id)::text AS visible_item_count, + encode(sha256(convert_to(COALESCE(string_agg( + m.item_id || E'\\x1f' + || COALESCE(i.title, '') || E'\\x1f' + || COALESCE(i.updated_at, '') || E'\\x1f' + || COALESCE(i.version::text, '1') || E'\\x1f' + || COALESCE(i.tags::text, '[]') || E'\\x1f' + || COALESCE(i.archived::text, 'false'), + E'\\x1e' ORDER BY m.item_id + ), ''), 'UTF8')), 'hex') AS item_snapshot_digest + FROM knowledge_project_collection_memberships m + LEFT JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ?`, [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]); + const membershipCount = Number(population?.membership_count ?? 0); + const visibleItemCount = Number(population?.visible_item_count ?? 0); + if (membershipCount !== visibleItemCount) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION", "collection membership points at a missing or inaccessible Knowledge item; refusing a partial resource population.", { + collection_id: aggregate.collection_id, + membership_count: membershipCount, + visible_item_count: visibleItemCount + }); + } + const taxonomyCountRow = await this.sql.get(`SELECT COUNT(*)::text AS taxonomy_count + FROM ( + SELECT LOWER(BTRIM(tag.value)) AS normalized_tag + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) AS tag(value) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + GROUP BY LOWER(BTRIM(tag.value)) + ) taxonomy`, identityParams); + const taxonomyCount = Number(taxonomyCountRow?.taxonomy_count ?? 0); + const revision = `r${Number(aggregate.revision)}`; + const populationDigest = digestKnowledgeProjectLinksValue({ + collection_revision: revision, + kinds, + item_snapshot_digest: kinds.includes("item") || kinds.includes("taxonomy") ? population?.item_snapshot_digest ?? "" : null, + taxonomy_count: kinds.includes("taxonomy") ? taxonomyCount : null + }); + const after = this.resourceCursorAfter({ + cursor: options.cursor, + aggregate, + revision, + populationDigest, + kinds + }); + const targetCount = limit + KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD; + const candidates = []; + const append = (resource) => { + if (candidates.length < targetCount && kinds.includes(resource.kind) && resource.key > after) { + candidates.push(resource); + } + }; + append(this.collectionResource(aggregate, membershipCount)); + if (kinds.includes("item") && candidates.length < targetCount && after < "project:") { + const itemAfter = after.startsWith("item:") ? after.slice("item:".length) : ""; + const rows = await this.sql.many(`SELECT i.* + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? AND m.item_id > ? + ORDER BY m.item_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, itemAfter]); + for (const row of rows) + append(this.itemResource(aggregate, this.postgresItem(row))); + } + append(this.projectResource(aggregate)); + if (kinds.includes("taxonomy") && candidates.length < targetCount) { + const taxonomyAfter = after.startsWith("taxonomy:") ? after : "taxonomy:"; + const rows = await this.sql.many(`WITH tagged AS ( + SELECT + m.item_id, + BTRIM(tag.value) AS label, + LOWER(BTRIM(tag.value)) AS normalized_tag, + tag.ordinality + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) + WITH ORDINALITY AS tag(value, ordinality) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + ), + grouped AS ( + SELECT + normalized_tag, + (array_agg(label ORDER BY item_id, ordinality))[1] AS label, + COUNT(*)::text AS item_count, + encode(sha256(convert_to( + jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + 'UTF8' + )), 'hex') AS member_digest, + encode(sha256( + convert_to(?, 'UTF8') + || decode('00', 'hex') + || convert_to('taxonomy', 'UTF8') + || decode('00', 'hex') + || convert_to(normalized_tag, 'UTF8') + ), 'hex') AS stable_hex + FROM tagged + GROUP BY normalized_tag + ), + mutated AS ( + SELECT + *, + overlay( + overlay(substr(stable_hex, 1, 32) placing '5' from 13 for 1) + placing substr( + '89ab', + ((strpos('0123456789abcdef', substr(stable_hex, 17, 1)) - 1) % 4) + 1, + 1 + ) + from 17 for 1 + ) AS stable_uuid_hex + FROM grouped + ), + keyed AS ( + SELECT + normalized_tag, + label, + item_count, + member_digest, + substr(stable_uuid_hex, 1, 8) + || '-' || substr(stable_uuid_hex, 9, 4) + || '-' || substr(stable_uuid_hex, 13, 4) + || '-' || substr(stable_uuid_hex, 17, 4) + || '-' || substr(stable_uuid_hex, 21, 12) AS taxonomy_id + FROM mutated + ) + SELECT normalized_tag, label, item_count, member_digest + FROM keyed + WHERE 'taxonomy:' || taxonomy_id > ? + ORDER BY taxonomy_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, aggregate.collection_id, taxonomyAfter]); + for (const row of rows) { + append(this.taxonomyResource(aggregate, row.normalized_tag, { + label: row.label, + itemCount: Number(row.item_count), + memberDigest: row.member_digest + })); + } + } + const total = (kinds.includes("collection") ? 1 : 0) + (kinds.includes("item") ? membershipCount : 0) + (kinds.includes("project") ? 1 : 0) + (kinds.includes("taxonomy") ? taxonomyCount : 0); + const pageResources = candidates.slice(0, limit); + const hasMore = candidates.length > pageResources.length; + const nextCursor = hasMore && pageResources.length > 0 ? Buffer.from(JSON.stringify({ + version: 1, + project_id: aggregate.project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + kinds, + after: pageResources.at(-1).key + })).toString("base64url") : null; + return { + schema: "knowledge.project-resources.page.v1", + authority: "knowledge", + route: KNOWLEDGE_PROJECT_RESOURCES_ROUTE, + ...this.identity, + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + resource_kinds: kinds, + resources: pageResources, + count: pageResources.length, + total, + limit, + cursor: options.cursor ?? null, + next_cursor: nextCursor, + has_more: hasMore, + complete: !hasMore, + truncated: false + }; + } async buildResources(projectId) { const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); if (!aggregate) { @@ -18742,6 +19117,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { async listProjectResources(projectId, options = {}) { const limit = boundedLimit(options.limit); const kinds = normalizeKinds(options.kinds); + if (this.sql.kind === "postgres") { + return this.listPostgresProjectResources(projectId, options, limit, kinds); + } const { aggregate, resources } = await this.buildResources(projectId); const revision = `r${Number(aggregate.revision)}`; const population = resources.filter((resource) => kinds.includes(resource.kind)); @@ -18842,7 +19220,12 @@ function createLocalKnowledgeProjectLinksAuthority(input) { if (input.databasePath !== ":memory:") { ensureParentDir(input.databasePath); } - const db = new Database2(input.databasePath, { create: true }); + const require2 = import.meta.require; + if (typeof require2 !== "function") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CONFLICT", "the local Knowledge project-links authority requires the Bun runtime."); + } + const { Database: BunDatabase } = require2("bun:sqlite"); + const db = new BunDatabase(input.databasePath, { create: true }); db.exec(sqliteKnowledgeProjectLinksSchemaSql()); return new PackageOwnedKnowledgeProjectLinksAuthority(new SqliteProjectLinksSql(db), (id) => input.itemStore.get(id), input.options); } diff --git a/dist/project-links.d.ts b/dist/project-links.d.ts index 1e2e0d1..9281ec4 100644 --- a/dist/project-links.d.ts +++ b/dist/project-links.d.ts @@ -5,6 +5,12 @@ export declare const KNOWLEDGE_PROJECT_REGISTRATION_ROUTE: 'knowledge.project-re export declare const KNOWLEDGE_PROJECT_RESOURCES_ROUTE: 'knowledge.project-resources.v1'; export declare const KNOWLEDGE_PROJECT_REGISTRATION_SCHEMA_VERSION: 1; export declare const KNOWLEDGE_PROJECT_MEMBERSHIP_RULE: 'explicit_collection_binding'; +/** + * Keyset pages fetch exactly one extra producer row to decide whether a + * continuation cursor is required. Scalar snapshot/count queries are separate + * and never materialize the resource population. + */ +export declare const KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD: 1; export type KnowledgeProjectResourceKind = 'project' | 'collection' | 'item' | 'taxonomy'; export type KnowledgeProjectRegistrationDirection = 'forward' | 'inverse'; export type KnowledgeProjectReceiptAction = 'register_collection' | 'bind_item'; diff --git a/dist/serve.js b/dist/serve.js index 85c7056..ce47fb5 100644 --- a/dist/serve.js +++ b/dist/serve.js @@ -2371,7 +2371,6 @@ function hasKnowledgeBoundedQueryCapability(value) { // src/project-links.ts import { createHash as createHash4 } from "crypto"; -import { Database } from "bun:sqlite"; // src/net-guard.ts var NETWORK_GUARD_ENV = "NODE_ENV"; @@ -2484,6 +2483,7 @@ var KNOWLEDGE_PROJECT_REGISTRATION_ROUTE = "knowledge.project-registration.v1"; var KNOWLEDGE_PROJECT_RESOURCES_ROUTE = "knowledge.project-resources.v1"; var KNOWLEDGE_PROJECT_REGISTRATION_SCHEMA_VERSION = 1; var KNOWLEDGE_PROJECT_MEMBERSHIP_RULE = "explicit_collection_binding"; +var KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD = 1; class KnowledgeProjectLinksError extends Error { code; @@ -2503,6 +2503,7 @@ function postgresSql(sql) { class PostgresProjectLinksSql { client; transactionClient; + kind = "postgres"; constructor(client, transactionClient) { this.client = client; this.transactionClient = transactionClient; @@ -2518,6 +2519,9 @@ class PostgresProjectLinksSql { const result = await this.client.query(postgresSql(sql), params); return { changes: result.rowCount }; } + async lock(key) { + await this.client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [key]); + } async transaction(fn) { if (!this.transactionClient) return fn(this); @@ -2527,6 +2531,7 @@ class PostgresProjectLinksSql { class SqliteProjectLinksSql { db; + kind = "sqlite"; tail = Promise.resolve(); closed = false; constructor(db) { @@ -2549,6 +2554,7 @@ class SqliteProjectLinksSql { const result = this.db.query(sql).run(...params); return { changes: Number(result.changes) }; } + async lock(_key) {} transaction(fn) { const run = this.tail.then(async () => { this.db.exec("BEGIN IMMEDIATE"); @@ -2948,6 +2954,27 @@ class PackageOwnedKnowledgeProjectLinksAuthority { stableCollectionId(sourceProjectId, collectionSlug) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00collection\x00${sourceProjectId}\x00${collectionSlug}`); } + collectionFence(collectionId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "collection", + collectionId + ].join("\x1F"); + } + membershipFence(collectionId, itemId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "membership", + collectionId, + itemId + ].join("\x1F"); + } stableReceiptId(operationId, stepId, action, direction) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00receipt\x00${operationId}\x00${stepId}\x00${action}\x00${direction}`); } @@ -3041,6 +3068,7 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (request.request_digest !== expectedRequestDigest) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH", "request_digest does not bind the normalized collection-registration request.", { expected_request_digest: expectedRequestDigest }); } + const stableCollectionId = this.stableCollectionId(sourceProjectId, collectionSlug); return this.sql.transaction(async (tx) => { const duplicate = await this.getReceiptByAttempt(tx, { operation_id: request.operation_id, @@ -3052,12 +3080,13 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(stableCollectionId)); let aggregate = await this.getAggregateBySource(tx, sourceProjectId); const createdByOperation = aggregate === null; if (!aggregate) { const now = this.now(); const projectId = this.stableProjectId(sourceProjectId); - const collectionId = this.stableCollectionId(sourceProjectId, collectionSlug); + const collectionId = stableCollectionId; await tx.run(`INSERT INTO knowledge_projects ( authority_id, tenant_id, corpus_id, source_project_id, project_id, project_slug, project_name, created_at, updated_at @@ -3201,6 +3230,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "register_collection" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted collection-registration receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } const aggregate = accepted.collection_id ? await this.getAggregateByCollection(tx, accepted.collection_id) : null; let outcome = "accepted"; let reason = null; @@ -3340,6 +3372,8 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(collectionId)); + await tx.lock(this.membershipFence(collectionId, itemId)); const aggregate = await this.getAggregateByCollection(tx, collectionId); if (!aggregate) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge collection was not found by exact id."); @@ -3462,6 +3496,12 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "bind_item" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted item-binding receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } + if (accepted.collection_id && accepted.item_id) { + await tx.lock(this.membershipFence(accepted.collection_id, accepted.item_id)); + } let outcome = "accepted"; let reason = null; const membership = await tx.get(`SELECT * FROM knowledge_project_collection_memberships @@ -3577,6 +3617,341 @@ class PackageOwnedKnowledgeProjectLinksAuthority { digest: inverse.result_digest }; } + resourceBase(aggregate) { + return { + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + revision: `r${Number(aggregate.revision)}` + }; + } + projectResource(aggregate) { + const body = { + ...this.resourceBase(aggregate), + kind: "project", + id: aggregate.project_id, + title: aggregate.project_name, + locator: { kind: "canonical_uri", value: `knowledge:project:${aggregate.project_id}` }, + metadata: { + source_project_id: aggregate.source_project_id, + slug: aggregate.project_slug, + collection_count: 1 + } + }; + return { + ...body, + key: `project:${aggregate.project_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + collectionResource(aggregate, memberCount) { + const body = { + ...this.resourceBase(aggregate), + kind: "collection", + id: aggregate.collection_id, + title: aggregate.collection_name, + locator: { kind: "external_uuid", value: aggregate.collection_id }, + metadata: { + slug: aggregate.collection_slug, + membership_rule: KNOWLEDGE_PROJECT_MEMBERSHIP_RULE, + member_count: memberCount + } + }; + return { + ...body, + key: `collection:${aggregate.collection_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + itemResource(aggregate, item) { + const body = { + ...this.resourceBase(aggregate), + kind: "item", + id: item.id, + revision: `v${item.version ?? 1}`, + title: item.title, + locator: { kind: "canonical_uri", value: `knowledge:item:${encodeURIComponent(item.id)}` }, + metadata: { + tags: [...item.tags ?? []], + archived: item.archived === true, + updated_at: item.updated_at + } + }; + return { + ...body, + key: `item:${item.id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + taxonomyResource(aggregate, normalized, input) { + const taxonomyId = stableUuid(`${aggregate.collection_id}\x00taxonomy\x00${normalized}`); + const body = { + ...this.resourceBase(aggregate), + kind: "taxonomy", + id: taxonomyId, + title: input.label, + locator: { kind: "external_uuid", value: taxonomyId }, + metadata: { + tag: input.label, + normalized_tag: normalized, + item_count: input.itemCount, + member_digest: input.memberDigest + } + }; + return { + ...body, + key: `taxonomy:${taxonomyId}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + postgresItem(row) { + const parseJson = (value, fallback) => { + if (value == null) + return fallback; + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return fallback; + } + } + return value; + }; + return { + id: String(row.id), + short_id: row.short_id ?? null, + title: String(row.title ?? ""), + content: String(row.content ?? ""), + url: row.url ?? null, + tags: parseJson(row.tags, []), + metadata: parseJson(row.metadata, {}), + archived: Boolean(row.archived), + created_at: String(row.created_at), + updated_at: String(row.updated_at), + version: row.version == null ? 1 : Number(row.version) + }; + } + resourceCursorAfter(input) { + if (!input.cursor) + return ""; + let decoded; + try { + decoded = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")); + } catch { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT", "cursor is not a valid Knowledge project-resources cursor."); + } + if (decoded.version !== 1 || decoded.project_id !== input.aggregate.project_id || decoded.collection_id !== input.aggregate.collection_id || decoded.collection_revision !== input.revision || decoded.population_digest !== input.populationDigest || canonicalKnowledgeProjectLinksJson(decoded.kinds) !== canonicalKnowledgeProjectLinksJson(input.kinds) || typeof decoded.after !== "string") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE", "project resources changed or the cursor belongs to a different project/kind selection; restart from the first page."); + } + return decoded.after; + } + async listPostgresProjectResources(projectId, options, limit, kinds) { + const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); + if (!aggregate) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge project aggregate was not found by source or stable project id."); + } + const identityParams = [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]; + const population = await this.sql.get(`SELECT + COUNT(*)::text AS membership_count, + COUNT(i.id)::text AS visible_item_count, + encode(sha256(convert_to(COALESCE(string_agg( + m.item_id || E'\\x1f' + || COALESCE(i.title, '') || E'\\x1f' + || COALESCE(i.updated_at, '') || E'\\x1f' + || COALESCE(i.version::text, '1') || E'\\x1f' + || COALESCE(i.tags::text, '[]') || E'\\x1f' + || COALESCE(i.archived::text, 'false'), + E'\\x1e' ORDER BY m.item_id + ), ''), 'UTF8')), 'hex') AS item_snapshot_digest + FROM knowledge_project_collection_memberships m + LEFT JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ?`, [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]); + const membershipCount = Number(population?.membership_count ?? 0); + const visibleItemCount = Number(population?.visible_item_count ?? 0); + if (membershipCount !== visibleItemCount) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION", "collection membership points at a missing or inaccessible Knowledge item; refusing a partial resource population.", { + collection_id: aggregate.collection_id, + membership_count: membershipCount, + visible_item_count: visibleItemCount + }); + } + const taxonomyCountRow = await this.sql.get(`SELECT COUNT(*)::text AS taxonomy_count + FROM ( + SELECT LOWER(BTRIM(tag.value)) AS normalized_tag + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) AS tag(value) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + GROUP BY LOWER(BTRIM(tag.value)) + ) taxonomy`, identityParams); + const taxonomyCount = Number(taxonomyCountRow?.taxonomy_count ?? 0); + const revision = `r${Number(aggregate.revision)}`; + const populationDigest = digestKnowledgeProjectLinksValue({ + collection_revision: revision, + kinds, + item_snapshot_digest: kinds.includes("item") || kinds.includes("taxonomy") ? population?.item_snapshot_digest ?? "" : null, + taxonomy_count: kinds.includes("taxonomy") ? taxonomyCount : null + }); + const after = this.resourceCursorAfter({ + cursor: options.cursor, + aggregate, + revision, + populationDigest, + kinds + }); + const targetCount = limit + KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD; + const candidates = []; + const append = (resource) => { + if (candidates.length < targetCount && kinds.includes(resource.kind) && resource.key > after) { + candidates.push(resource); + } + }; + append(this.collectionResource(aggregate, membershipCount)); + if (kinds.includes("item") && candidates.length < targetCount && after < "project:") { + const itemAfter = after.startsWith("item:") ? after.slice("item:".length) : ""; + const rows = await this.sql.many(`SELECT i.* + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? AND m.item_id > ? + ORDER BY m.item_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, itemAfter]); + for (const row of rows) + append(this.itemResource(aggregate, this.postgresItem(row))); + } + append(this.projectResource(aggregate)); + if (kinds.includes("taxonomy") && candidates.length < targetCount) { + const taxonomyAfter = after.startsWith("taxonomy:") ? after : "taxonomy:"; + const rows = await this.sql.many(`WITH tagged AS ( + SELECT + m.item_id, + BTRIM(tag.value) AS label, + LOWER(BTRIM(tag.value)) AS normalized_tag, + tag.ordinality + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) + WITH ORDINALITY AS tag(value, ordinality) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + ), + grouped AS ( + SELECT + normalized_tag, + (array_agg(label ORDER BY item_id, ordinality))[1] AS label, + COUNT(*)::text AS item_count, + encode(sha256(convert_to( + jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + 'UTF8' + )), 'hex') AS member_digest, + encode(sha256( + convert_to(?, 'UTF8') + || decode('00', 'hex') + || convert_to('taxonomy', 'UTF8') + || decode('00', 'hex') + || convert_to(normalized_tag, 'UTF8') + ), 'hex') AS stable_hex + FROM tagged + GROUP BY normalized_tag + ), + mutated AS ( + SELECT + *, + overlay( + overlay(substr(stable_hex, 1, 32) placing '5' from 13 for 1) + placing substr( + '89ab', + ((strpos('0123456789abcdef', substr(stable_hex, 17, 1)) - 1) % 4) + 1, + 1 + ) + from 17 for 1 + ) AS stable_uuid_hex + FROM grouped + ), + keyed AS ( + SELECT + normalized_tag, + label, + item_count, + member_digest, + substr(stable_uuid_hex, 1, 8) + || '-' || substr(stable_uuid_hex, 9, 4) + || '-' || substr(stable_uuid_hex, 13, 4) + || '-' || substr(stable_uuid_hex, 17, 4) + || '-' || substr(stable_uuid_hex, 21, 12) AS taxonomy_id + FROM mutated + ) + SELECT normalized_tag, label, item_count, member_digest + FROM keyed + WHERE 'taxonomy:' || taxonomy_id > ? + ORDER BY taxonomy_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, aggregate.collection_id, taxonomyAfter]); + for (const row of rows) { + append(this.taxonomyResource(aggregate, row.normalized_tag, { + label: row.label, + itemCount: Number(row.item_count), + memberDigest: row.member_digest + })); + } + } + const total = (kinds.includes("collection") ? 1 : 0) + (kinds.includes("item") ? membershipCount : 0) + (kinds.includes("project") ? 1 : 0) + (kinds.includes("taxonomy") ? taxonomyCount : 0); + const pageResources = candidates.slice(0, limit); + const hasMore = candidates.length > pageResources.length; + const nextCursor = hasMore && pageResources.length > 0 ? Buffer.from(JSON.stringify({ + version: 1, + project_id: aggregate.project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + kinds, + after: pageResources.at(-1).key + })).toString("base64url") : null; + return { + schema: "knowledge.project-resources.page.v1", + authority: "knowledge", + route: KNOWLEDGE_PROJECT_RESOURCES_ROUTE, + ...this.identity, + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + resource_kinds: kinds, + resources: pageResources, + count: pageResources.length, + total, + limit, + cursor: options.cursor ?? null, + next_cursor: nextCursor, + has_more: hasMore, + complete: !hasMore, + truncated: false + }; + } async buildResources(projectId) { const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); if (!aggregate) { @@ -3697,6 +4072,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { async listProjectResources(projectId, options = {}) { const limit = boundedLimit(options.limit); const kinds = normalizeKinds(options.kinds); + if (this.sql.kind === "postgres") { + return this.listPostgresProjectResources(projectId, options, limit, kinds); + } const { aggregate, resources } = await this.buildResources(projectId); const revision = `r${Number(aggregate.revision)}`; const population = resources.filter((resource) => kinds.includes(resource.kind)); @@ -3797,7 +4175,12 @@ function createLocalKnowledgeProjectLinksAuthority(input) { if (input.databasePath !== ":memory:") { ensureParentDir(input.databasePath); } - const db = new Database(input.databasePath, { create: true }); + const require2 = import.meta.require; + if (typeof require2 !== "function") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CONFLICT", "the local Knowledge project-links authority requires the Bun runtime."); + } + const { Database: BunDatabase } = require2("bun:sqlite"); + const db = new BunDatabase(input.databasePath, { create: true }); db.exec(sqliteKnowledgeProjectLinksSchemaSql()); return new PackageOwnedKnowledgeProjectLinksAuthority(new SqliteProjectLinksSql(db), (id) => input.itemStore.get(id), input.options); } diff --git a/dist/storage.js b/dist/storage.js index 5b83c3c..f5ebdcd 100644 --- a/dist/storage.js +++ b/dist/storage.js @@ -2654,11 +2654,11 @@ function createKnowledgeCloudClient() { } // src/project-links.ts import { createHash as createHash2 } from "crypto"; -import { Database as Database2 } from "bun:sqlite"; var KNOWLEDGE_PROJECT_REGISTRATION_ROUTE = "knowledge.project-registration.v1"; var KNOWLEDGE_PROJECT_RESOURCES_ROUTE = "knowledge.project-resources.v1"; var KNOWLEDGE_PROJECT_REGISTRATION_SCHEMA_VERSION = 1; var KNOWLEDGE_PROJECT_MEMBERSHIP_RULE = "explicit_collection_binding"; +var KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD = 1; class KnowledgeProjectLinksError extends Error { code; @@ -2678,6 +2678,7 @@ function postgresSql(sql) { class PostgresProjectLinksSql { client; transactionClient; + kind = "postgres"; constructor(client, transactionClient) { this.client = client; this.transactionClient = transactionClient; @@ -2693,6 +2694,9 @@ class PostgresProjectLinksSql { const result = await this.client.query(postgresSql(sql), params); return { changes: result.rowCount }; } + async lock(key) { + await this.client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [key]); + } async transaction(fn) { if (!this.transactionClient) return fn(this); @@ -2702,6 +2706,7 @@ class PostgresProjectLinksSql { class SqliteProjectLinksSql { db; + kind = "sqlite"; tail = Promise.resolve(); closed = false; constructor(db) { @@ -2724,6 +2729,7 @@ class SqliteProjectLinksSql { const result = this.db.query(sql).run(...params); return { changes: Number(result.changes) }; } + async lock(_key) {} transaction(fn) { const run = this.tail.then(async () => { this.db.exec("BEGIN IMMEDIATE"); @@ -3123,6 +3129,27 @@ class PackageOwnedKnowledgeProjectLinksAuthority { stableCollectionId(sourceProjectId, collectionSlug) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00collection\x00${sourceProjectId}\x00${collectionSlug}`); } + collectionFence(collectionId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "collection", + collectionId + ].join("\x1F"); + } + membershipFence(collectionId, itemId) { + return [ + "knowledge-project-links", + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + "membership", + collectionId, + itemId + ].join("\x1F"); + } stableReceiptId(operationId, stepId, action, direction) { return stableUuid(`${this.identity.authority_id}\x00${this.identity.tenant_id}\x00${this.identity.corpus_id}\x00receipt\x00${operationId}\x00${stepId}\x00${action}\x00${direction}`); } @@ -3216,6 +3243,7 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (request.request_digest !== expectedRequestDigest) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_DIGEST_MISMATCH", "request_digest does not bind the normalized collection-registration request.", { expected_request_digest: expectedRequestDigest }); } + const stableCollectionId = this.stableCollectionId(sourceProjectId, collectionSlug); return this.sql.transaction(async (tx) => { const duplicate = await this.getReceiptByAttempt(tx, { operation_id: request.operation_id, @@ -3227,12 +3255,13 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(stableCollectionId)); let aggregate = await this.getAggregateBySource(tx, sourceProjectId); const createdByOperation = aggregate === null; if (!aggregate) { const now = this.now(); const projectId = this.stableProjectId(sourceProjectId); - const collectionId = this.stableCollectionId(sourceProjectId, collectionSlug); + const collectionId = stableCollectionId; await tx.run(`INSERT INTO knowledge_projects ( authority_id, tenant_id, corpus_id, source_project_id, project_id, project_slug, project_name, created_at, updated_at @@ -3376,6 +3405,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "register_collection" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted collection-registration receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } const aggregate = accepted.collection_id ? await this.getAggregateByCollection(tx, accepted.collection_id) : null; let outcome = "accepted"; let reason = null; @@ -3515,6 +3547,8 @@ class PackageOwnedKnowledgeProjectLinksAuthority { this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(collectionId)); + await tx.lock(this.membershipFence(collectionId, itemId)); const aggregate = await this.getAggregateByCollection(tx, collectionId); if (!aggregate) { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge collection was not found by exact id."); @@ -3637,6 +3671,12 @@ class PackageOwnedKnowledgeProjectLinksAuthority { if (!accepted || accepted.action !== "bind_item" || accepted.direction !== "forward" || accepted.outcome !== "accepted") { throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "accepted item-binding receipt was not found."); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } + if (accepted.collection_id && accepted.item_id) { + await tx.lock(this.membershipFence(accepted.collection_id, accepted.item_id)); + } let outcome = "accepted"; let reason = null; const membership = await tx.get(`SELECT * FROM knowledge_project_collection_memberships @@ -3752,6 +3792,341 @@ class PackageOwnedKnowledgeProjectLinksAuthority { digest: inverse.result_digest }; } + resourceBase(aggregate) { + return { + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + revision: `r${Number(aggregate.revision)}` + }; + } + projectResource(aggregate) { + const body = { + ...this.resourceBase(aggregate), + kind: "project", + id: aggregate.project_id, + title: aggregate.project_name, + locator: { kind: "canonical_uri", value: `knowledge:project:${aggregate.project_id}` }, + metadata: { + source_project_id: aggregate.source_project_id, + slug: aggregate.project_slug, + collection_count: 1 + } + }; + return { + ...body, + key: `project:${aggregate.project_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + collectionResource(aggregate, memberCount) { + const body = { + ...this.resourceBase(aggregate), + kind: "collection", + id: aggregate.collection_id, + title: aggregate.collection_name, + locator: { kind: "external_uuid", value: aggregate.collection_id }, + metadata: { + slug: aggregate.collection_slug, + membership_rule: KNOWLEDGE_PROJECT_MEMBERSHIP_RULE, + member_count: memberCount + } + }; + return { + ...body, + key: `collection:${aggregate.collection_id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + itemResource(aggregate, item) { + const body = { + ...this.resourceBase(aggregate), + kind: "item", + id: item.id, + revision: `v${item.version ?? 1}`, + title: item.title, + locator: { kind: "canonical_uri", value: `knowledge:item:${encodeURIComponent(item.id)}` }, + metadata: { + tags: [...item.tags ?? []], + archived: item.archived === true, + updated_at: item.updated_at + } + }; + return { + ...body, + key: `item:${item.id}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + taxonomyResource(aggregate, normalized, input) { + const taxonomyId = stableUuid(`${aggregate.collection_id}\x00taxonomy\x00${normalized}`); + const body = { + ...this.resourceBase(aggregate), + kind: "taxonomy", + id: taxonomyId, + title: input.label, + locator: { kind: "external_uuid", value: taxonomyId }, + metadata: { + tag: input.label, + normalized_tag: normalized, + item_count: input.itemCount, + member_digest: input.memberDigest + } + }; + return { + ...body, + key: `taxonomy:${taxonomyId}`, + digest: digestKnowledgeProjectLinksValue(body) + }; + } + postgresItem(row) { + const parseJson = (value, fallback) => { + if (value == null) + return fallback; + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return fallback; + } + } + return value; + }; + return { + id: String(row.id), + short_id: row.short_id ?? null, + title: String(row.title ?? ""), + content: String(row.content ?? ""), + url: row.url ?? null, + tags: parseJson(row.tags, []), + metadata: parseJson(row.metadata, {}), + archived: Boolean(row.archived), + created_at: String(row.created_at), + updated_at: String(row.updated_at), + version: row.version == null ? 1 : Number(row.version) + }; + } + resourceCursorAfter(input) { + if (!input.cursor) + return ""; + let decoded; + try { + decoded = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")); + } catch { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT", "cursor is not a valid Knowledge project-resources cursor."); + } + if (decoded.version !== 1 || decoded.project_id !== input.aggregate.project_id || decoded.collection_id !== input.aggregate.collection_id || decoded.collection_revision !== input.revision || decoded.population_digest !== input.populationDigest || canonicalKnowledgeProjectLinksJson(decoded.kinds) !== canonicalKnowledgeProjectLinksJson(input.kinds) || typeof decoded.after !== "string") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE", "project resources changed or the cursor belongs to a different project/kind selection; restart from the first page."); + } + return decoded.after; + } + async listPostgresProjectResources(projectId, options, limit, kinds) { + const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); + if (!aggregate) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_NOT_FOUND", "Knowledge project aggregate was not found by source or stable project id."); + } + const identityParams = [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]; + const population = await this.sql.get(`SELECT + COUNT(*)::text AS membership_count, + COUNT(i.id)::text AS visible_item_count, + encode(sha256(convert_to(COALESCE(string_agg( + m.item_id || E'\\x1f' + || COALESCE(i.title, '') || E'\\x1f' + || COALESCE(i.updated_at, '') || E'\\x1f' + || COALESCE(i.version::text, '1') || E'\\x1f' + || COALESCE(i.tags::text, '[]') || E'\\x1f' + || COALESCE(i.archived::text, 'false'), + E'\\x1e' ORDER BY m.item_id + ), ''), 'UTF8')), 'hex') AS item_snapshot_digest + FROM knowledge_project_collection_memberships m + LEFT JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ?`, [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id + ]); + const membershipCount = Number(population?.membership_count ?? 0); + const visibleItemCount = Number(population?.visible_item_count ?? 0); + if (membershipCount !== visibleItemCount) { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION", "collection membership points at a missing or inaccessible Knowledge item; refusing a partial resource population.", { + collection_id: aggregate.collection_id, + membership_count: membershipCount, + visible_item_count: visibleItemCount + }); + } + const taxonomyCountRow = await this.sql.get(`SELECT COUNT(*)::text AS taxonomy_count + FROM ( + SELECT LOWER(BTRIM(tag.value)) AS normalized_tag + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) AS tag(value) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + GROUP BY LOWER(BTRIM(tag.value)) + ) taxonomy`, identityParams); + const taxonomyCount = Number(taxonomyCountRow?.taxonomy_count ?? 0); + const revision = `r${Number(aggregate.revision)}`; + const populationDigest = digestKnowledgeProjectLinksValue({ + collection_revision: revision, + kinds, + item_snapshot_digest: kinds.includes("item") || kinds.includes("taxonomy") ? population?.item_snapshot_digest ?? "" : null, + taxonomy_count: kinds.includes("taxonomy") ? taxonomyCount : null + }); + const after = this.resourceCursorAfter({ + cursor: options.cursor, + aggregate, + revision, + populationDigest, + kinds + }); + const targetCount = limit + KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD; + const candidates = []; + const append = (resource) => { + if (candidates.length < targetCount && kinds.includes(resource.kind) && resource.key > after) { + candidates.push(resource); + } + }; + append(this.collectionResource(aggregate, membershipCount)); + if (kinds.includes("item") && candidates.length < targetCount && after < "project:") { + const itemAfter = after.startsWith("item:") ? after.slice("item:".length) : ""; + const rows = await this.sql.many(`SELECT i.* + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? AND m.item_id > ? + ORDER BY m.item_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, itemAfter]); + for (const row of rows) + append(this.itemResource(aggregate, this.postgresItem(row))); + } + append(this.projectResource(aggregate)); + if (kinds.includes("taxonomy") && candidates.length < targetCount) { + const taxonomyAfter = after.startsWith("taxonomy:") ? after : "taxonomy:"; + const rows = await this.sql.many(`WITH tagged AS ( + SELECT + m.item_id, + BTRIM(tag.value) AS label, + LOWER(BTRIM(tag.value)) AS normalized_tag, + tag.ordinality + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) + WITH ORDINALITY AS tag(value, ordinality) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + ), + grouped AS ( + SELECT + normalized_tag, + (array_agg(label ORDER BY item_id, ordinality))[1] AS label, + COUNT(*)::text AS item_count, + encode(sha256(convert_to( + jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + 'UTF8' + )), 'hex') AS member_digest, + encode(sha256( + convert_to(?, 'UTF8') + || decode('00', 'hex') + || convert_to('taxonomy', 'UTF8') + || decode('00', 'hex') + || convert_to(normalized_tag, 'UTF8') + ), 'hex') AS stable_hex + FROM tagged + GROUP BY normalized_tag + ), + mutated AS ( + SELECT + *, + overlay( + overlay(substr(stable_hex, 1, 32) placing '5' from 13 for 1) + placing substr( + '89ab', + ((strpos('0123456789abcdef', substr(stable_hex, 17, 1)) - 1) % 4) + 1, + 1 + ) + from 17 for 1 + ) AS stable_uuid_hex + FROM grouped + ), + keyed AS ( + SELECT + normalized_tag, + label, + item_count, + member_digest, + substr(stable_uuid_hex, 1, 8) + || '-' || substr(stable_uuid_hex, 9, 4) + || '-' || substr(stable_uuid_hex, 13, 4) + || '-' || substr(stable_uuid_hex, 17, 4) + || '-' || substr(stable_uuid_hex, 21, 12) AS taxonomy_id + FROM mutated + ) + SELECT normalized_tag, label, item_count, member_digest + FROM keyed + WHERE 'taxonomy:' || taxonomy_id > ? + ORDER BY taxonomy_id ASC + LIMIT ${targetCount - candidates.length}`, [...identityParams, aggregate.collection_id, taxonomyAfter]); + for (const row of rows) { + append(this.taxonomyResource(aggregate, row.normalized_tag, { + label: row.label, + itemCount: Number(row.item_count), + memberDigest: row.member_digest + })); + } + } + const total = (kinds.includes("collection") ? 1 : 0) + (kinds.includes("item") ? membershipCount : 0) + (kinds.includes("project") ? 1 : 0) + (kinds.includes("taxonomy") ? taxonomyCount : 0); + const pageResources = candidates.slice(0, limit); + const hasMore = candidates.length > pageResources.length; + const nextCursor = hasMore && pageResources.length > 0 ? Buffer.from(JSON.stringify({ + version: 1, + project_id: aggregate.project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + kinds, + after: pageResources.at(-1).key + })).toString("base64url") : null; + return { + schema: "knowledge.project-resources.page.v1", + authority: "knowledge", + route: KNOWLEDGE_PROJECT_RESOURCES_ROUTE, + ...this.identity, + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + resource_kinds: kinds, + resources: pageResources, + count: pageResources.length, + total, + limit, + cursor: options.cursor ?? null, + next_cursor: nextCursor, + has_more: hasMore, + complete: !hasMore, + truncated: false + }; + } async buildResources(projectId) { const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, "project_id")); if (!aggregate) { @@ -3872,6 +4247,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority { async listProjectResources(projectId, options = {}) { const limit = boundedLimit(options.limit); const kinds = normalizeKinds(options.kinds); + if (this.sql.kind === "postgres") { + return this.listPostgresProjectResources(projectId, options, limit, kinds); + } const { aggregate, resources } = await this.buildResources(projectId); const revision = `r${Number(aggregate.revision)}`; const population = resources.filter((resource) => kinds.includes(resource.kind)); @@ -3972,7 +4350,12 @@ function createLocalKnowledgeProjectLinksAuthority(input) { if (input.databasePath !== ":memory:") { ensureParentDir(input.databasePath); } - const db = new Database2(input.databasePath, { create: true }); + const require2 = import.meta.require; + if (typeof require2 !== "function") { + throw new KnowledgeProjectLinksError("KNOWLEDGE_PROJECT_LINKS_CONFLICT", "the local Knowledge project-links authority requires the Bun runtime."); + } + const { Database: BunDatabase } = require2("bun:sqlite"); + const db = new BunDatabase(input.databasePath, { create: true }); db.exec(sqliteKnowledgeProjectLinksSchemaSql()); return new PackageOwnedKnowledgeProjectLinksAuthority(new SqliteProjectLinksSql(db), (id) => input.itemStore.get(id), input.options); } diff --git a/src/project-links.ts b/src/project-links.ts index 073b45b..65a0350 100644 --- a/src/project-links.ts +++ b/src/project-links.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto'; -import { Database, type SQLQueryBindings } from 'bun:sqlite'; +import type { Database, SQLQueryBindings } from 'bun:sqlite'; import { ensureParentDir } from './workspace.js'; import type { ItemStore } from './item-store.js'; import type { KnowledgeItem } from './store.js'; @@ -10,6 +10,12 @@ export const KNOWLEDGE_PROJECT_REGISTRATION_ROUTE = 'knowledge.project-registrat export const KNOWLEDGE_PROJECT_RESOURCES_ROUTE = 'knowledge.project-resources.v1' as const; export const KNOWLEDGE_PROJECT_REGISTRATION_SCHEMA_VERSION = 1 as const; export const KNOWLEDGE_PROJECT_MEMBERSHIP_RULE = 'explicit_collection_binding' as const; +/** + * Keyset pages fetch exactly one extra producer row to decide whether a + * continuation cursor is required. Scalar snapshot/count queries are separate + * and never materialize the resource population. + */ +export const KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD = 1 as const; export type KnowledgeProjectResourceKind = 'project' | 'collection' | 'item' | 'taxonomy'; export type KnowledgeProjectRegistrationDirection = 'forward' | 'inverse'; @@ -276,6 +282,23 @@ interface MembershipRow { bound_at: string; } +interface ProjectResourcePopulationRow { + membership_count: number | string; + visible_item_count: number | string; + item_snapshot_digest: string; +} + +interface ProjectResourceTaxonomyCountRow { + taxonomy_count: number | string; +} + +interface ProjectResourceTaxonomyRow { + normalized_tag: string; + label: string; + item_count: number | string; + member_digest: string; +} + interface ReceiptRow { receipt_id: string; authority_id: string; @@ -308,10 +331,12 @@ interface SqlRunResult { } interface ProjectLinksSql { + readonly kind: 'sqlite' | 'postgres'; close(): Promise<void>; get<T extends Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<T | null>; many<T extends Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<T[]>; run(sql: string, params?: readonly unknown[]): Promise<SqlRunResult>; + lock(key: string): Promise<void>; transaction<T>(fn: (tx: ProjectLinksSql) => Promise<T>): Promise<T>; } @@ -321,6 +346,8 @@ function postgresSql(sql: string): string { } class PostgresProjectLinksSql implements ProjectLinksSql { + readonly kind = 'postgres' as const; + constructor( private readonly client: TypedQueryClient, private readonly transactionClient?: PoolQueryClient, @@ -341,6 +368,13 @@ class PostgresProjectLinksSql implements ProjectLinksSql { return { changes: result.rowCount }; } + async lock(key: string): Promise<void> { + await this.client.query( + 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', + [key], + ); + } + async transaction<T>(fn: (tx: ProjectLinksSql) => Promise<T>): Promise<T> { if (!this.transactionClient) return fn(this); return this.transactionClient.transaction( @@ -350,6 +384,7 @@ class PostgresProjectLinksSql implements ProjectLinksSql { } class SqliteProjectLinksSql implements ProjectLinksSql { + readonly kind = 'sqlite' as const; private tail: Promise<void> = Promise.resolve(); private closed = false; @@ -375,6 +410,8 @@ class SqliteProjectLinksSql implements ProjectLinksSql { return { changes: Number(result.changes) }; } + async lock(_key: string): Promise<void> {} + transaction<T>(fn: (tx: ProjectLinksSql) => Promise<T>): Promise<T> { const run = this.tail.then(async () => { this.db.exec('BEGIN IMMEDIATE'); @@ -817,6 +854,29 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink ); } + private collectionFence(collectionId: string): string { + return [ + 'knowledge-project-links', + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + 'collection', + collectionId, + ].join('\u001f'); + } + + private membershipFence(collectionId: string, itemId: string): string { + return [ + 'knowledge-project-links', + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + 'membership', + collectionId, + itemId, + ].join('\u001f'); + } + private stableReceiptId( operationId: string, stepId: string, @@ -978,6 +1038,7 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink { expected_request_digest: expectedRequestDigest }, ); } + const stableCollectionId = this.stableCollectionId(sourceProjectId, collectionSlug); return this.sql.transaction(async (tx) => { const duplicate = await this.getReceiptByAttempt(tx, { @@ -991,12 +1052,13 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink return duplicate; } + await tx.lock(this.collectionFence(stableCollectionId)); let aggregate = await this.getAggregateBySource(tx, sourceProjectId); const createdByOperation = aggregate === null; if (!aggregate) { const now = this.now(); const projectId = this.stableProjectId(sourceProjectId); - const collectionId = this.stableCollectionId(sourceProjectId, collectionSlug); + const collectionId = stableCollectionId; await tx.run( `INSERT INTO knowledge_projects ( authority_id, tenant_id, corpus_id, source_project_id, project_id, @@ -1204,6 +1266,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink 'accepted collection-registration receipt was not found.', ); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } const aggregate = accepted.collection_id ? await this.getAggregateByCollection(tx, accepted.collection_id) : null; @@ -1385,6 +1450,8 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink this.assertIdempotent(duplicate, request); return duplicate; } + await tx.lock(this.collectionFence(collectionId)); + await tx.lock(this.membershipFence(collectionId, itemId)); const aggregate = await this.getAggregateByCollection(tx, collectionId); if (!aggregate) { throw new KnowledgeProjectLinksError( @@ -1543,6 +1610,12 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink 'accepted item-binding receipt was not found.', ); } + if (accepted.collection_id) { + await tx.lock(this.collectionFence(accepted.collection_id)); + } + if (accepted.collection_id && accepted.item_id) { + await tx.lock(this.membershipFence(accepted.collection_id, accepted.item_id)); + } let outcome: KnowledgeProjectReceiptOutcome = 'accepted'; let reason: string | null = null; const membership = await tx.get<MembershipRow & Record<string, unknown>>( @@ -1690,6 +1763,419 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink }; } + private resourceBase(aggregate: AggregateRow) { + return { + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + revision: `r${Number(aggregate.revision)}`, + }; + } + + private projectResource(aggregate: AggregateRow): KnowledgeProjectResource { + const body = { + ...this.resourceBase(aggregate), + kind: 'project' as const, + id: aggregate.project_id, + title: aggregate.project_name, + locator: { kind: 'canonical_uri' as const, value: `knowledge:project:${aggregate.project_id}` }, + metadata: { + source_project_id: aggregate.source_project_id, + slug: aggregate.project_slug, + collection_count: 1, + }, + }; + return { + ...body, + key: `project:${aggregate.project_id}`, + digest: digestKnowledgeProjectLinksValue(body), + }; + } + + private collectionResource(aggregate: AggregateRow, memberCount: number): KnowledgeProjectResource { + const body = { + ...this.resourceBase(aggregate), + kind: 'collection' as const, + id: aggregate.collection_id, + title: aggregate.collection_name, + locator: { kind: 'external_uuid' as const, value: aggregate.collection_id }, + metadata: { + slug: aggregate.collection_slug, + membership_rule: KNOWLEDGE_PROJECT_MEMBERSHIP_RULE, + member_count: memberCount, + }, + }; + return { + ...body, + key: `collection:${aggregate.collection_id}`, + digest: digestKnowledgeProjectLinksValue(body), + }; + } + + private itemResource(aggregate: AggregateRow, item: KnowledgeItem): KnowledgeProjectResource { + const body = { + ...this.resourceBase(aggregate), + kind: 'item' as const, + id: item.id, + revision: `v${item.version ?? 1}`, + title: item.title, + locator: { kind: 'canonical_uri' as const, value: `knowledge:item:${encodeURIComponent(item.id)}` }, + metadata: { + tags: [...(item.tags ?? [])], + archived: item.archived === true, + updated_at: item.updated_at, + }, + }; + return { + ...body, + key: `item:${item.id}`, + digest: digestKnowledgeProjectLinksValue(body), + }; + } + + private taxonomyResource( + aggregate: AggregateRow, + normalized: string, + input: { + label: string; + itemCount: number; + memberDigest: string; + }, + ): KnowledgeProjectResource { + const taxonomyId = stableUuid(`${aggregate.collection_id}\0taxonomy\0${normalized}`); + const body = { + ...this.resourceBase(aggregate), + kind: 'taxonomy' as const, + id: taxonomyId, + title: input.label, + locator: { kind: 'external_uuid' as const, value: taxonomyId }, + metadata: { + tag: input.label, + normalized_tag: normalized, + item_count: input.itemCount, + member_digest: input.memberDigest, + }, + }; + return { + ...body, + key: `taxonomy:${taxonomyId}`, + digest: digestKnowledgeProjectLinksValue(body), + }; + } + + private postgresItem(row: Record<string, unknown>): KnowledgeItem { + const parseJson = <T>(value: unknown, fallback: T): T => { + if (value == null) return fallback; + if (typeof value === 'string') { + try { + return JSON.parse(value) as T; + } catch { + return fallback; + } + } + return value as T; + }; + return { + id: String(row.id), + short_id: (row.short_id as string | null) ?? null, + title: String(row.title ?? ''), + content: String(row.content ?? ''), + url: (row.url as string | null) ?? null, + tags: parseJson<string[]>(row.tags, []), + metadata: parseJson<Record<string, unknown>>(row.metadata, {}), + archived: Boolean(row.archived), + created_at: String(row.created_at), + updated_at: String(row.updated_at), + version: row.version == null ? 1 : Number(row.version), + }; + } + + private resourceCursorAfter(input: { + cursor?: string | null; + aggregate: AggregateRow; + revision: string; + populationDigest: string; + kinds: KnowledgeProjectResourceKind[]; + }): string { + if (!input.cursor) return ''; + let decoded: { + version?: number; + project_id?: string; + collection_id?: string; + collection_revision?: string; + population_digest?: string; + kinds?: KnowledgeProjectResourceKind[]; + after?: string; + }; + try { + decoded = JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8')) as typeof decoded; + } catch { + throw new KnowledgeProjectLinksError( + 'KNOWLEDGE_PROJECT_LINKS_INVALID_INPUT', + 'cursor is not a valid Knowledge project-resources cursor.', + ); + } + if ( + decoded.version !== 1 + || decoded.project_id !== input.aggregate.project_id + || decoded.collection_id !== input.aggregate.collection_id + || decoded.collection_revision !== input.revision + || decoded.population_digest !== input.populationDigest + || canonicalKnowledgeProjectLinksJson(decoded.kinds) !== canonicalKnowledgeProjectLinksJson(input.kinds) + || typeof decoded.after !== 'string' + ) { + throw new KnowledgeProjectLinksError( + 'KNOWLEDGE_PROJECT_LINKS_CURSOR_STALE', + 'project resources changed or the cursor belongs to a different project/kind selection; restart from the first page.', + ); + } + return decoded.after; + } + + private async listPostgresProjectResources( + projectId: string, + options: KnowledgeProjectResourceListOptions, + limit: number, + kinds: KnowledgeProjectResourceKind[], + ): Promise<KnowledgeProjectResourcePage> { + const aggregate = await this.getAggregateByProject(this.sql, requiredString(projectId, 'project_id')); + if (!aggregate) { + throw new KnowledgeProjectLinksError( + 'KNOWLEDGE_PROJECT_LINKS_NOT_FOUND', + 'Knowledge project aggregate was not found by source or stable project id.', + ); + } + const identityParams = [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id, + ]; + const population = await this.sql.get<ProjectResourcePopulationRow & Record<string, unknown>>( + `SELECT + COUNT(*)::text AS membership_count, + COUNT(i.id)::text AS visible_item_count, + encode(sha256(convert_to(COALESCE(string_agg( + m.item_id || E'\\x1f' + || COALESCE(i.title, '') || E'\\x1f' + || COALESCE(i.updated_at, '') || E'\\x1f' + || COALESCE(i.version::text, '1') || E'\\x1f' + || COALESCE(i.tags::text, '[]') || E'\\x1f' + || COALESCE(i.archived::text, 'false'), + E'\\x1e' ORDER BY m.item_id + ), ''), 'UTF8')), 'hex') AS item_snapshot_digest + FROM knowledge_project_collection_memberships m + LEFT JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ?`, + [ + this.identity.tenant_id, + this.identity.authority_id, + this.identity.tenant_id, + this.identity.corpus_id, + aggregate.collection_id, + ], + ); + const membershipCount = Number(population?.membership_count ?? 0); + const visibleItemCount = Number(population?.visible_item_count ?? 0); + if (membershipCount !== visibleItemCount) { + throw new KnowledgeProjectLinksError( + 'KNOWLEDGE_PROJECT_LINKS_INCOMPLETE_POPULATION', + 'collection membership points at a missing or inaccessible Knowledge item; refusing a partial resource population.', + { + collection_id: aggregate.collection_id, + membership_count: membershipCount, + visible_item_count: visibleItemCount, + }, + ); + } + const taxonomyCountRow = await this.sql.get<ProjectResourceTaxonomyCountRow & Record<string, unknown>>( + `SELECT COUNT(*)::text AS taxonomy_count + FROM ( + SELECT LOWER(BTRIM(tag.value)) AS normalized_tag + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) AS tag(value) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + GROUP BY LOWER(BTRIM(tag.value)) + ) taxonomy`, + identityParams, + ); + const taxonomyCount = Number(taxonomyCountRow?.taxonomy_count ?? 0); + const revision = `r${Number(aggregate.revision)}`; + const populationDigest = digestKnowledgeProjectLinksValue({ + collection_revision: revision, + kinds, + item_snapshot_digest: kinds.includes('item') || kinds.includes('taxonomy') + ? population?.item_snapshot_digest ?? '' + : null, + taxonomy_count: kinds.includes('taxonomy') ? taxonomyCount : null, + }); + const after = this.resourceCursorAfter({ + cursor: options.cursor, + aggregate, + revision, + populationDigest, + kinds, + }); + const targetCount = limit + KNOWLEDGE_PROJECT_RESOURCE_PAGE_LOOKAHEAD; + const candidates: KnowledgeProjectResource[] = []; + const append = (resource: KnowledgeProjectResource) => { + if ( + candidates.length < targetCount + && kinds.includes(resource.kind) + && resource.key > after + ) { + candidates.push(resource); + } + }; + + append(this.collectionResource(aggregate, membershipCount)); + if (kinds.includes('item') && candidates.length < targetCount && after < 'project:') { + const itemAfter = after.startsWith('item:') ? after.slice('item:'.length) : ''; + const rows = await this.sql.many<Record<string, unknown>>( + `SELECT i.* + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? AND m.item_id > ? + ORDER BY m.item_id ASC + LIMIT ${targetCount - candidates.length}`, + [...identityParams, itemAfter], + ); + for (const row of rows) append(this.itemResource(aggregate, this.postgresItem(row))); + } + append(this.projectResource(aggregate)); + if (kinds.includes('taxonomy') && candidates.length < targetCount) { + const taxonomyAfter = after.startsWith('taxonomy:') ? after : 'taxonomy:'; + const rows = await this.sql.many<ProjectResourceTaxonomyRow & Record<string, unknown>>( + `WITH tagged AS ( + SELECT + m.item_id, + BTRIM(tag.value) AS label, + LOWER(BTRIM(tag.value)) AS normalized_tag, + tag.ordinality + FROM knowledge_project_collection_memberships m + JOIN knowledge_items i + ON i.id = m.item_id + AND (i.authority_classification IS NULL OR i.tenant_id::text = ?) + CROSS JOIN LATERAL jsonb_array_elements_text(i.tags) + WITH ORDINALITY AS tag(value, ordinality) + WHERE m.authority_id = ? AND m.tenant_id = ? AND m.corpus_id = ? + AND m.collection_id = ? + AND BTRIM(tag.value) <> '' + ), + grouped AS ( + SELECT + normalized_tag, + (array_agg(label ORDER BY item_id, ordinality))[1] AS label, + COUNT(*)::text AS item_count, + encode(sha256(convert_to( + jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + 'UTF8' + )), 'hex') AS member_digest, + encode(sha256( + convert_to(?, 'UTF8') + || decode('00', 'hex') + || convert_to('taxonomy', 'UTF8') + || decode('00', 'hex') + || convert_to(normalized_tag, 'UTF8') + ), 'hex') AS stable_hex + FROM tagged + GROUP BY normalized_tag + ), + mutated AS ( + SELECT + *, + overlay( + overlay(substr(stable_hex, 1, 32) placing '5' from 13 for 1) + placing substr( + '89ab', + ((strpos('0123456789abcdef', substr(stable_hex, 17, 1)) - 1) % 4) + 1, + 1 + ) + from 17 for 1 + ) AS stable_uuid_hex + FROM grouped + ), + keyed AS ( + SELECT + normalized_tag, + label, + item_count, + member_digest, + substr(stable_uuid_hex, 1, 8) + || '-' || substr(stable_uuid_hex, 9, 4) + || '-' || substr(stable_uuid_hex, 13, 4) + || '-' || substr(stable_uuid_hex, 17, 4) + || '-' || substr(stable_uuid_hex, 21, 12) AS taxonomy_id + FROM mutated + ) + SELECT normalized_tag, label, item_count, member_digest + FROM keyed + WHERE 'taxonomy:' || taxonomy_id > ? + ORDER BY taxonomy_id ASC + LIMIT ${targetCount - candidates.length}`, + [...identityParams, aggregate.collection_id, taxonomyAfter], + ); + for (const row of rows) { + append(this.taxonomyResource(aggregate, row.normalized_tag, { + label: row.label, + itemCount: Number(row.item_count), + memberDigest: row.member_digest, + })); + } + } + + const total = (kinds.includes('collection') ? 1 : 0) + + (kinds.includes('item') ? membershipCount : 0) + + (kinds.includes('project') ? 1 : 0) + + (kinds.includes('taxonomy') ? taxonomyCount : 0); + const pageResources = candidates.slice(0, limit); + const hasMore = candidates.length > pageResources.length; + const nextCursor = hasMore && pageResources.length > 0 + ? Buffer.from(JSON.stringify({ + version: 1, + project_id: aggregate.project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + kinds, + after: pageResources.at(-1)!.key, + })).toString('base64url') + : null; + return { + schema: 'knowledge.project-resources.page.v1', + authority: 'knowledge', + route: KNOWLEDGE_PROJECT_RESOURCES_ROUTE, + ...this.identity, + project_id: aggregate.project_id, + source_project_id: aggregate.source_project_id, + collection_id: aggregate.collection_id, + collection_revision: revision, + population_digest: populationDigest, + resource_kinds: kinds, + resources: pageResources, + count: pageResources.length, + total, + limit, + cursor: options.cursor ?? null, + next_cursor: nextCursor, + has_more: hasMore, + complete: !hasMore, + truncated: false, + }; + } + private async buildResources(projectId: string): Promise<{ aggregate: AggregateRow; resources: KnowledgeProjectResource[]; @@ -1826,6 +2312,9 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink ): Promise<KnowledgeProjectResourcePage> { const limit = boundedLimit(options.limit); const kinds = normalizeKinds(options.kinds); + if (this.sql.kind === 'postgres') { + return this.listPostgresProjectResources(projectId, options, limit, kinds); + } const { aggregate, resources } = await this.buildResources(projectId); const revision = `r${Number(aggregate.revision)}`; const population = resources.filter((resource) => kinds.includes(resource.kind)); @@ -1990,7 +2479,17 @@ export function createLocalKnowledgeProjectLinksAuthority(input: { if (input.databasePath !== ':memory:') { ensureParentDir(input.databasePath); } - const db = new Database(input.databasePath, { create: true }); + const require = (import.meta as ImportMeta & { + require?: (specifier: string) => unknown; + }).require; + if (typeof require !== 'function') { + throw new KnowledgeProjectLinksError( + 'KNOWLEDGE_PROJECT_LINKS_CONFLICT', + 'the local Knowledge project-links authority requires the Bun runtime.', + ); + } + const { Database: BunDatabase } = require('bun:sqlite') as typeof import('bun:sqlite'); + const db = new BunDatabase(input.databasePath, { create: true }); db.exec(sqliteKnowledgeProjectLinksSchemaSql()); return new PackageOwnedKnowledgeProjectLinksAuthority( new SqliteProjectLinksSql(db), diff --git a/tests/package-release.test.ts b/tests/package-release.test.ts index 205e73d..e7667b4 100644 --- a/tests/package-release.test.ts +++ b/tests/package-release.test.ts @@ -320,6 +320,32 @@ describe('public package release safety', () => { } }); + test('the published serve entry imports under Node', () => { + const result = spawnSync( + 'node', + ['--input-type=module', '--eval', "await import('./dist/serve.js')"], + { + cwd: repoRoot, + encoding: 'utf8', + maxBuffer: 4 * 1024 * 1024, + }, + ); + + expect( + { + status: result.status, + signal: result.signal, + stdout: result.stdout, + stderr: result.stderr, + }, + ).toEqual({ + status: 0, + signal: null, + stdout: '', + stderr: '', + }); + }); + test('npm pack dry-run includes only public docs', () => { const result = spawnSync('node', ['scripts/validate-public-package.mjs', '--json'], { cwd: repoRoot, diff --git a/tests/project-links-release-blockers.test.ts b/tests/project-links-release-blockers.test.ts new file mode 100644 index 0000000..a624b41 --- /dev/null +++ b/tests/project-links-release-blockers.test.ts @@ -0,0 +1,498 @@ +import { describe, expect, test } from 'bun:test'; +import type { PGlite } from '@electric-sql/pglite'; +import { + KNOWLEDGE_PROJECT_REGISTRATION_ROUTE, + createPostgresKnowledgeProjectLinksAuthority, + digestKnowledgeProjectLinksValue, + type KnowledgeProjectLinksAuthority, + type KnowledgeProjectRegistrationCapability, + type KnowledgeProjectRegistrationReceipt, +} from '../src/project-links'; +import type { + PoolQueryClient, + QueryResult, + TypedQueryClient, +} from '../src/generated/storage-kit/index.js'; +import type { KnowledgeItem } from '../src/store'; +import { createMigratedPglite, pgliteClient } from './fixtures/pglite-client'; + +const fixedNow = () => '2026-08-10T12:00:00.000Z'; +const options = { + packageVersion: '9.9.9', + authorityId: 'knowledge-test', + tenantId: 'tenant-test', + corpusId: 'corpus-test', + now: fixedNow, +}; + +function item(id: string, tags: string[] = []): KnowledgeItem { + return { + id, + short_id: id.slice(0, 8), + title: `Item ${id}`, + content: `Body ${id}`, + url: null, + tags, + metadata: {}, + archived: false, + created_at: fixedNow(), + updated_at: fixedNow(), + version: 1, + }; +} + +async function insertItem(db: PGlite, value: KnowledgeItem): Promise<void> { + await db.query( + `INSERT INTO knowledge_items ( + id, short_id, title, content, url, tags, metadata, archived, created_at, updated_at + ) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7::jsonb,$8,$9,$10)`, + [ + value.id, + value.short_id, + value.title, + value.content, + value.url, + JSON.stringify(value.tags), + JSON.stringify(value.metadata), + value.archived, + value.created_at, + value.updated_at, + ], + ); +} + +async function registrationRequest( + authority: KnowledgeProjectLinksAuthority, + input: { + operationId?: string; + stepId?: string; + idempotencyKey?: string; + } = {}, +) { + const capability = await authority.capability(); + return { + operation_id: input.operationId ?? 'op-register-alpha', + step_id: input.stepId ?? 'step-register-alpha', + resource_kind: 'collection' as const, + direction: 'forward' as const, + authority_route: KNOWLEDGE_PROJECT_REGISTRATION_ROUTE, + package_version: capability.package_version, + authority_id: capability.authority_id, + tenant_id: capability.tenant_id, + corpus_id: capability.corpus_id, + target_selector: 'wks_project_alpha', + idempotency_key: input.idempotencyKey ?? 'idem-register-alpha', + request_digest: digestKnowledgeProjectLinksValue({ + action: 'register_collection', + source_project_id: 'wks_project_alpha', + project_slug: 'alpha', + project_name: 'Alpha', + collection_slug: 'alpha-knowledge', + collection_name: 'Alpha Knowledge', + membership_rule: 'explicit_collection_binding', + }), + precondition_digest: digestKnowledgeProjectLinksValue({ + source_project_id: 'wks_project_alpha', + expected: 'absent_or_exact_match', + }), + project_id: 'wks_project_alpha', + project_slug: 'alpha', + project_name: 'Alpha', + desired: { + collection_slug: 'alpha-knowledge', + collection_name: 'Alpha Knowledge', + }, + }; +} + +async function bindingRequest( + authority: KnowledgeProjectLinksAuthority, + collectionId: string, + itemId: string, + input: { + operationId?: string; + stepId?: string; + idempotencyKey?: string; + } = {}, +) { + const capability = await authority.capability(); + return { + operation_id: input.operationId ?? `op-bind-${itemId}`, + step_id: input.stepId ?? `step-bind-${itemId}`, + direction: 'forward' as const, + authority_route: KNOWLEDGE_PROJECT_REGISTRATION_ROUTE, + package_version: capability.package_version, + authority_id: capability.authority_id, + tenant_id: capability.tenant_id, + corpus_id: capability.corpus_id, + idempotency_key: input.idempotencyKey ?? `idem-bind-${itemId}`, + request_digest: digestKnowledgeProjectLinksValue({ + action: 'bind_item', + collection_id: collectionId, + item_id: itemId, + }), + precondition_digest: digestKnowledgeProjectLinksValue({ + collection_id: collectionId, + item_id: itemId, + expected: 'unbound_or_exact_membership', + }), + collection_id: collectionId, + item_id: itemId, + }; +} + +async function inverseRequest( + capability: KnowledgeProjectRegistrationCapability, + receipt: KnowledgeProjectRegistrationReceipt, + suffix: string, +) { + return { + operation_id: `op-inverse-${suffix}`, + step_id: `step-inverse-${suffix}`, + authority_route: KNOWLEDGE_PROJECT_REGISTRATION_ROUTE, + package_version: capability.package_version, + authority_id: capability.authority_id, + tenant_id: capability.tenant_id, + corpus_id: capability.corpus_id, + idempotency_key: `idem-inverse-${suffix}`, + accepted_receipt_id: receipt.receipt_id, + }; +} + +interface Deferred<T> { + promise: Promise<T>; + resolve(value: T): void; +} + +function deferred<T>(): Deferred<T> { + let resolve!: (value: T) => void; + const promise = new Promise<T>((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +interface RaceControl { + target: 'collection' | 'membership'; + forwardRead: Deferred<void>; + resumeForward: Deferred<void>; + inverseBlocked: Deferred<void>; + paused: boolean; +} + +function raceControl(target: RaceControl['target']): RaceControl { + return { + target, + forwardRead: deferred<void>(), + resumeForward: deferred<void>(), + inverseBlocked: deferred<void>(), + paused: false, + }; +} + +class AdvisoryTransactionLocks { + private readonly locks = new Map<string, Array<() => void>>(); + + async acquire(key: string, lane: 'forward' | 'inverse', control: RaceControl): Promise<() => void> { + const waiters = this.locks.get(key); + if (!waiters) { + this.locks.set(key, []); + } else { + if (lane === 'inverse') control.inverseBlocked.resolve(); + await new Promise<void>((resolve) => waiters.push(resolve)); + } + + return () => { + const current = this.locks.get(key); + const next = current?.shift(); + if (next) next(); + else this.locks.delete(key); + }; + } +} + +function isForwardTargetRead(sql: string, target: RaceControl['target']): boolean { + if (target === 'collection') { + return sql.includes('FROM knowledge_projects p') + && sql.includes('p.source_project_id ='); + } + return sql.includes('FROM knowledge_project_collection_memberships') + && sql.includes('SELECT *') + && sql.includes('item_id ='); +} + +function interleavingClient( + db: PGlite, + lane: 'forward' | 'inverse', + control: RaceControl, + locks: AdvisoryTransactionLocks, +): PoolQueryClient { + const transaction = async <T>(fn: (client: TypedQueryClient) => Promise<T>): Promise<T> => { + const releases: Array<() => void> = []; + + const execute = async <T extends Record<string, unknown>>( + sql: string, + params: readonly unknown[] = [], + ): Promise<QueryResult<T>> => { + if (sql.includes('pg_advisory_xact_lock')) { + const release = await locks.acquire(String(params[0]), lane, control); + releases.push(release); + return { + rows: [{ pg_advisory_xact_lock: null } as T], + rowCount: 1, + }; + } + + const result = await db.query<T>(sql, params as unknown[]); + const rows = result.rows; + if ( + lane === 'forward' + && !control.paused + && rows.length > 0 + && isForwardTargetRead(sql, control.target) + ) { + control.paused = true; + control.forwardRead.resolve(); + await control.resumeForward.promise; + } + return { + rows, + rowCount: result.affectedRows ?? rows.length, + }; + }; + + const typed: TypedQueryClient = { + query: execute, + async many<T extends Record<string, unknown>>(sql: string, params: readonly unknown[] = []) { + return (await execute<T>(sql, params)).rows; + }, + async get<T extends Record<string, unknown>>(sql: string, params: readonly unknown[] = []) { + return (await execute<T>(sql, params)).rows[0] ?? null; + }, + async one<T extends Record<string, unknown>>(sql: string, params: readonly unknown[] = []) { + const rows = (await execute<T>(sql, params)).rows; + if (rows.length !== 1) throw new Error(`expected one row, got ${rows.length}`); + return rows[0]!; + }, + async execute(sql: string, params: readonly unknown[] = []) { + await execute(sql, params); + }, + }; + + try { + return await fn(typed); + } finally { + for (const release of releases.reverse()) release(); + } + }; + + const root = pgliteClient(db); + return { + ...root, + transaction, + }; +} + +interface PageMetrics { + manyRows: number; + maxManyRows: number; +} + +function measuredClient(base: PoolQueryClient, metrics: PageMetrics): PoolQueryClient { + const wrap = (client: TypedQueryClient): TypedQueryClient => ({ + query: client.query.bind(client), + async many<T extends Record<string, unknown>>(sql: string, params: readonly unknown[] = []) { + const rows = await client.many<T>(sql, params); + metrics.manyRows += rows.length; + metrics.maxManyRows = Math.max(metrics.maxManyRows, rows.length); + return rows; + }, + get: client.get.bind(client), + one: client.one.bind(client), + execute: client.execute.bind(client), + }); + const root = wrap(base); + return { + ...root, + get pool() { + return base.pool; + }, + async transaction<T>(fn: (client: TypedQueryClient) => Promise<T>) { + return base.transaction((client) => fn(wrap(client))); + }, + close: base.close.bind(base), + }; +} + +async function startInverseWhileForwardPaused<T>( + inverse: Promise<T>, + control: RaceControl, +): Promise<T> { + const first = await Promise.race([ + inverse.then(() => 'inverse-completed' as const), + control.inverseBlocked.promise.then(() => 'inverse-blocked' as const), + ]); + control.resumeForward.resolve(); + if (first === 'inverse-completed') return inverse; + return inverse; +} + +describe('Knowledge project-links release blockers', () => { + test('PostgreSQL serializes collection adoption against creator compensation', async () => { + const { db, client } = await createMigratedPglite(); + const resolver = async () => null; + const setup = createPostgresKnowledgeProjectLinksAuthority({ client, itemResolver: resolver, options }); + const ownerReceipt = await setup.registerCollection(await registrationRequest(setup)); + const capability = await setup.capability(); + const control = raceControl('collection'); + const locks = new AdvisoryTransactionLocks(); + const forward = createPostgresKnowledgeProjectLinksAuthority({ + client: interleavingClient(db, 'forward', control, locks), + itemResolver: resolver, + options, + }); + const inverse = createPostgresKnowledgeProjectLinksAuthority({ + client: interleavingClient(db, 'inverse', control, locks), + itemResolver: resolver, + options, + }); + + const adoptionPromise = forward.registerCollection(await registrationRequest(forward, { + operationId: 'op-adopt-collection-race', + stepId: 'step-adopt-collection-race', + idempotencyKey: 'idem-adopt-collection-race', + })); + await control.forwardRead.promise; + const inversePromise = inverse.compensateRegistration( + await inverseRequest(capability, ownerReceipt, 'collection-race'), + ); + const inverseReceiptPromise = startInverseWhileForwardPaused(inversePromise, control); + const [adoption, inverseReceipt] = await Promise.all([adoptionPromise, inverseReceiptPromise]); + + expect(adoption).toMatchObject({ + outcome: 'accepted', + reason: 'adopted_existing_collection', + created_by_operation: false, + }); + expect(inverseReceipt).toMatchObject({ + outcome: 'terminal_nonacceptance', + reason: 'collection_has_later_accepted_adopter', + }); + expect(await setup.readCollection(ownerReceipt.collection_id!)) + .toMatchObject({ collection_id: ownerReceipt.collection_id }); + await setup.close(); + await db.close(); + }); + + test('PostgreSQL serializes membership adoption against creator compensation', async () => { + const { db, client } = await createMigratedPglite(); + const value = item('k_membership_race'); + await insertItem(db, value); + const resolver = async (id: string) => id === value.id ? value : null; + const setup = createPostgresKnowledgeProjectLinksAuthority({ client, itemResolver: resolver, options }); + const registration = await setup.registerCollection(await registrationRequest(setup)); + const ownerReceipt = await setup.bindItem( + await bindingRequest(setup, registration.collection_id!, value.id), + ); + const capability = await setup.capability(); + const control = raceControl('membership'); + const locks = new AdvisoryTransactionLocks(); + const forward = createPostgresKnowledgeProjectLinksAuthority({ + client: interleavingClient(db, 'forward', control, locks), + itemResolver: resolver, + options, + }); + const inverse = createPostgresKnowledgeProjectLinksAuthority({ + client: interleavingClient(db, 'inverse', control, locks), + itemResolver: resolver, + options, + }); + + const adoptionPromise = forward.bindItem( + await bindingRequest(forward, registration.collection_id!, value.id, { + operationId: 'op-adopt-membership-race', + stepId: 'step-adopt-membership-race', + idempotencyKey: 'idem-adopt-membership-race', + }), + ); + await control.forwardRead.promise; + const inversePromise = inverse.compensateItemBinding( + await inverseRequest(capability, ownerReceipt, 'membership-race'), + ); + const inverseReceiptPromise = startInverseWhileForwardPaused(inversePromise, control); + const [adoption, inverseReceipt] = await Promise.all([adoptionPromise, inverseReceiptPromise]); + + expect(adoption).toMatchObject({ + outcome: 'accepted', + reason: 'adopted_existing_membership', + created_by_operation: false, + }); + expect(inverseReceipt).toMatchObject({ + outcome: 'terminal_nonacceptance', + reason: 'membership_has_later_accepted_adopter', + }); + expect(await setup.readItemBinding(registration.collection_id!, value.id)) + .toMatchObject({ item_id: value.id }); + await setup.close(); + await db.close(); + }); + + test('PostgreSQL resource pages bound returned rows and resolver calls to limit plus one', async () => { + const { db, client } = await createMigratedPglite(); + const values = new Map<string, KnowledgeItem>(); + for (let index = 0; index < 12; index += 1) { + const value = item( + `k_page_${String(index).padStart(2, '0')}`, + [`Tag ${index % 5}`, index % 2 === 0 ? 'Shared' : 'Odd'], + ); + values.set(value.id, value); + await insertItem(db, value); + } + const metrics: PageMetrics = { manyRows: 0, maxManyRows: 0 }; + let resolverCalls = 0; + const authority = createPostgresKnowledgeProjectLinksAuthority({ + client: measuredClient(client, metrics), + itemResolver: async (id) => { + resolverCalls += 1; + return values.get(id) ?? null; + }, + options, + }); + const registration = await authority.registerCollection(await registrationRequest(authority)); + for (const value of values.values()) { + await authority.bindItem( + await bindingRequest(authority, registration.collection_id!, value.id), + ); + } + + const limit = 3; + const workBound = limit + 1; + const resources = []; + let cursor: string | null = null; + let expectedTotal: number | null = null; + do { + metrics.manyRows = 0; + metrics.maxManyRows = 0; + resolverCalls = 0; + const page = await authority.listProjectResources('wks_project_alpha', { limit, cursor }); + expectedTotal ??= page.total; + expect(page.total).toBe(expectedTotal); + expect(metrics.manyRows).toBeLessThanOrEqual(workBound); + expect(metrics.maxManyRows).toBeLessThanOrEqual(workBound); + expect(resolverCalls).toBeLessThanOrEqual(workBound); + resources.push(...page.resources); + cursor = page.next_cursor; + } while (cursor); + + const keys = resources.map((resource) => resource.key); + expect(keys).toEqual([...keys].sort((left, right) => left.localeCompare(right))); + expect(new Set(keys).size).toBe(keys.length); + expect(resources.length).toBe(expectedTotal); + expect(resources.filter((resource) => resource.kind === 'item')).toHaveLength(values.size); + for (const resource of resources.filter((entry) => entry.kind === 'taxonomy')) { + expect(resource.key).toBe(`taxonomy:${resource.id}`); + } + await authority.close(); + await db.close(); + }); +}); diff --git a/tests/project-links.test.ts b/tests/project-links.test.ts index 4dafc86..3841f8b 100644 --- a/tests/project-links.test.ts +++ b/tests/project-links.test.ts @@ -576,6 +576,23 @@ describe('Knowledge Projects resource-link producer', () => { test('Postgres executes the same aggregate, membership, receipt, and resource semantics', async () => { const { db, client } = await createMigratedPglite(); const pgItem = item('k_pg', 'Postgres Item', ['Postgres']); + await db.query( + `INSERT INTO knowledge_items ( + id, short_id, title, content, url, tags, metadata, archived, created_at, updated_at + ) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7::jsonb,$8,$9,$10)`, + [ + pgItem.id, + pgItem.short_id, + pgItem.title, + pgItem.content, + pgItem.url, + JSON.stringify(pgItem.tags), + JSON.stringify(pgItem.metadata), + pgItem.archived, + pgItem.created_at, + pgItem.updated_at, + ], + ); const authority = createPostgresKnowledgeProjectLinksAuthority({ client, itemResolver: async (id) => id === pgItem.id ? pgItem : null, From 5513e228e4e3f6e8eb06b4e2261b8b71d1366b90 Mon Sep 17 00:00:00 2001 From: Andrei Hasna <andrei@hasna.com> Date: Tue, 11 Aug 2026 03:29:00 +0300 Subject: [PATCH 2/2] fix: preserve taxonomy digest parity Hash PostgreSQL taxonomy membership as canonical compact JSON and assert the producer digest matches the shared cross-backend contract. Agent: Straton --- bin/knowledge-mcp.js | 5 ++++- bin/knowledge-serve.js | 5 ++++- bin/knowledge.js | 5 ++++- dist/index.js | 5 ++++- dist/serve.js | 5 ++++- dist/storage.js | 5 ++++- src/project-links.ts | 5 ++++- tests/project-links-release-blockers.test.ts | 8 ++++++++ 8 files changed, 36 insertions(+), 7 deletions(-) diff --git a/bin/knowledge-mcp.js b/bin/knowledge-mcp.js index a51e810..7eeb196 100755 --- a/bin/knowledge-mcp.js +++ b/bin/knowledge-mcp.js @@ -30585,7 +30585,10 @@ class PackageOwnedKnowledgeProjectLinksAuthority { (array_agg(label ORDER BY item_id, ordinality))[1] AS label, COUNT(*)::text AS item_count, encode(sha256(convert_to( - jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + '[' || string_agg( + to_json(item_id)::text, + ',' ORDER BY item_id, ordinality + ) || ']', 'UTF8' )), 'hex') AS member_digest, encode(sha256( diff --git a/bin/knowledge-serve.js b/bin/knowledge-serve.js index 997cc21..954777d 100755 --- a/bin/knowledge-serve.js +++ b/bin/knowledge-serve.js @@ -2563,7 +2563,10 @@ class PackageOwnedKnowledgeProjectLinksAuthority { (array_agg(label ORDER BY item_id, ordinality))[1] AS label, COUNT(*)::text AS item_count, encode(sha256(convert_to( - jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + '[' || string_agg( + to_json(item_id)::text, + ',' ORDER BY item_id, ordinality + ) || ']', 'UTF8' )), 'hex') AS member_digest, encode(sha256( diff --git a/bin/knowledge.js b/bin/knowledge.js index 2dde0bc..3c8e911 100755 --- a/bin/knowledge.js +++ b/bin/knowledge.js @@ -1470,7 +1470,10 @@ Pages should be concise, cited, and organized for both humans and agents. (array_agg(label ORDER BY item_id, ordinality))[1] AS label, COUNT(*)::text AS item_count, encode(sha256(convert_to( - jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + '[' || string_agg( + to_json(item_id)::text, + ',' ORDER BY item_id, ordinality + ) || ']', 'UTF8' )), 'hex') AS member_digest, encode(sha256( diff --git a/dist/index.js b/dist/index.js index 4cd8614..880198c 100644 --- a/dist/index.js +++ b/dist/index.js @@ -18910,7 +18910,10 @@ class PackageOwnedKnowledgeProjectLinksAuthority { (array_agg(label ORDER BY item_id, ordinality))[1] AS label, COUNT(*)::text AS item_count, encode(sha256(convert_to( - jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + '[' || string_agg( + to_json(item_id)::text, + ',' ORDER BY item_id, ordinality + ) || ']', 'UTF8' )), 'hex') AS member_digest, encode(sha256( diff --git a/dist/serve.js b/dist/serve.js index ce47fb5..c5f9300 100644 --- a/dist/serve.js +++ b/dist/serve.js @@ -3865,7 +3865,10 @@ class PackageOwnedKnowledgeProjectLinksAuthority { (array_agg(label ORDER BY item_id, ordinality))[1] AS label, COUNT(*)::text AS item_count, encode(sha256(convert_to( - jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + '[' || string_agg( + to_json(item_id)::text, + ',' ORDER BY item_id, ordinality + ) || ']', 'UTF8' )), 'hex') AS member_digest, encode(sha256( diff --git a/dist/storage.js b/dist/storage.js index f5ebdcd..97e3593 100644 --- a/dist/storage.js +++ b/dist/storage.js @@ -4040,7 +4040,10 @@ class PackageOwnedKnowledgeProjectLinksAuthority { (array_agg(label ORDER BY item_id, ordinality))[1] AS label, COUNT(*)::text AS item_count, encode(sha256(convert_to( - jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + '[' || string_agg( + to_json(item_id)::text, + ',' ORDER BY item_id, ordinality + ) || ']', 'UTF8' )), 'hex') AS member_digest, encode(sha256( diff --git a/src/project-links.ts b/src/project-links.ts index 65a0350..6c72824 100644 --- a/src/project-links.ts +++ b/src/project-links.ts @@ -2080,7 +2080,10 @@ class PackageOwnedKnowledgeProjectLinksAuthority implements KnowledgeProjectLink (array_agg(label ORDER BY item_id, ordinality))[1] AS label, COUNT(*)::text AS item_count, encode(sha256(convert_to( - jsonb_agg(item_id ORDER BY item_id, ordinality)::text, + '[' || string_agg( + to_json(item_id)::text, + ',' ORDER BY item_id, ordinality + ) || ']', 'UTF8' )), 'hex') AS member_digest, encode(sha256( diff --git a/tests/project-links-release-blockers.test.ts b/tests/project-links-release-blockers.test.ts index a624b41..8cd5350 100644 --- a/tests/project-links-release-blockers.test.ts +++ b/tests/project-links-release-blockers.test.ts @@ -491,6 +491,14 @@ describe('Knowledge project-links release blockers', () => { expect(resources.filter((resource) => resource.kind === 'item')).toHaveLength(values.size); for (const resource of resources.filter((entry) => entry.kind === 'taxonomy')) { expect(resource.key).toBe(`taxonomy:${resource.id}`); + const normalizedTag = String(resource.metadata.normalized_tag); + const expectedMemberIds = [...values.values()] + .flatMap((value) => (value.tags ?? []) + .filter((tag) => tag.trim().toLowerCase() === normalizedTag) + .map(() => value.id)) + .sort(); + expect(resource.metadata.member_digest) + .toBe(digestKnowledgeProjectLinksValue(expectedMemberIds)); } await authority.close(); await db.close();