vibecode-anything 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +3 -2
- package/dist/core/schema.js +460 -17
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/index.js +486 -6
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,2215 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { VibecodeError } from "./errors.js";
|
|
5
|
+
import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
|
|
6
|
+
const VALID_FORMATS = new Set(["zod", "json-schema", "typescript"]);
|
|
7
|
+
const MAX_SCHEMA_DEPTH = 12;
|
|
8
|
+
const MAX_BODY_DEPTH = 12;
|
|
9
|
+
const MAX_SCHEMA_PROPERTIES = 128;
|
|
10
|
+
const MAX_ENUM_VALUES = 128;
|
|
11
|
+
const MAX_TUPLE_ITEMS = 32;
|
|
12
|
+
const MAX_PATTERN_LENGTH = 512;
|
|
13
|
+
const MAX_ARRAY_INFER_SAMPLES = 16;
|
|
14
|
+
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
15
|
+
const SENSITIVE_HEADER_RE = /(?:authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|api[_-]?key|apikey|auth[_-]?token|access[_-]?token|session[_-]?token|csrf|xsrf|secret|token|passwd|password|passphrase|credential|bearer)/i;
|
|
16
|
+
const SENSITIVE_QUERY_RE = /(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|secret|client[_-]?secret|password|passwd|passphrase|jwt|session[_-]?id|session|private[_-]?key|authorization|cookie|csrf|xsrf|credential|credentials|bearer|(?:^|[_-])(?:auth|sig|signature)(?:$|[_-]))/i;
|
|
17
|
+
// Matches common secret fields and mid-name env/config secret keys without false-positiving on words like `author`.
|
|
18
|
+
const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|access[_-]?key|signing[_-]?key|encryption[_-]?key|master[_-]?key|authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|session[_-]?id|jwt|credentials?|bearer|csrf|xsrf|auth(?:orization|entication|[_-]?(?:token|header|key|secret|code|pass))|(?:^|[_-])auth(?:$|[_-]))/i;
|
|
19
|
+
const AUTH_SCHEME_VALUE_RE = /(?:^|[\s"'=+])(?:bearer|basic|token|digest|apikey)(?:\s+|\+)[^\s&]+/i;
|
|
20
|
+
const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
|
|
21
|
+
const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>()[\]{}]+/g;
|
|
22
|
+
const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
|
|
23
|
+
const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
|
|
24
|
+
const INLINE_BASIC_TOKEN_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{4,}/gi;
|
|
25
|
+
const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey)\s+[A-Za-z0-9._~+/=:-]{3,}/gi;
|
|
26
|
+
const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*|[A-Za-z0-9._~+/:-]{4,}={0,2})/gi;
|
|
27
|
+
const INLINE_COOKIE_HEADER_RE = /\b(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;|]+(?:\s*;\s*[A-Za-z0-9_.-]+=[^\s,\r\n;|]+)*/gi;
|
|
28
|
+
const INLINE_AUTH_HEADER_RE = /\b(Authorization|Proxy-Authorization)\s*[:=]\s*(?:(?:Bearer|Basic|Token|ApiKey|Digest)\s+(?:\[REDACTED\]|[^\s,;|]+)|[A-Za-z0-9._-]+\s+[^\s,;|]+|[^\s,;|]+)/gi;
|
|
29
|
+
const INLINE_SENSITIVE_ASSIGNMENT_RE = /\b([A-Za-z0-9_.-]*(?:secret|token|password|passwd|passphrase|api[_-]?key|apikey|private[_-]?key|access[_-]?key|credential|authorization|cookie|bearer|csrf|xsrf|jwt|session(?:[_-]?id)?)[A-Za-z0-9_.-]*)(["']?)\s*([:=])\s*(?:"[^"]*"|'[^']*'|[^\s,;'"`<>]+)/gi;
|
|
30
|
+
const TS_RESERVED_AND_GLOBALS = new Set([
|
|
31
|
+
"abstract", "any", "as", "asserts", "async", "await", "bigint", "boolean",
|
|
32
|
+
"break", "case", "catch", "class", "const", "constructor", "continue",
|
|
33
|
+
"debugger", "declare", "default", "delete", "do", "else", "enum", "export",
|
|
34
|
+
"extends", "false", "finally", "for", "from", "function", "get", "if",
|
|
35
|
+
"implements", "import", "in", "infer", "instanceof", "interface", "is",
|
|
36
|
+
"keyof", "let", "module", "namespace", "never", "new", "null", "number",
|
|
37
|
+
"object", "of", "package", "private", "protected", "public", "readonly",
|
|
38
|
+
"require", "return", "set", "static", "string", "super", "switch", "symbol",
|
|
39
|
+
"this", "throw", "true", "try", "type", "typeof", "undefined", "unique",
|
|
40
|
+
"unknown", "var", "void", "while", "with", "yield",
|
|
41
|
+
"__proto__", "prototype", "toString", "valueOf", "hasOwnProperty",
|
|
42
|
+
"Object", "Function", "Boolean", "Symbol", "Error", "EvalError", "RangeError",
|
|
43
|
+
"ReferenceError", "SyntaxError", "TypeError", "URIError", "AggregateError",
|
|
44
|
+
"Number", "BigInt", "Math", "Date", "String", "RegExp", "Array", "Int8Array",
|
|
45
|
+
"Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array",
|
|
46
|
+
"Uint32Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array",
|
|
47
|
+
"Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "SharedArrayBuffer",
|
|
48
|
+
"DataView", "Atomics", "JSON", "Promise", "Reflect", "Proxy", "Intl",
|
|
49
|
+
"Record", "Partial", "Required", "Readonly", "Pick", "Omit", "Exclude",
|
|
50
|
+
"Extract", "NonNullable", "Parameters", "ConstructorParameters", "ReturnType",
|
|
51
|
+
"InstanceType", "Awaited", "ReadonlyArray", "ReadonlySet", "ReadonlyMap",
|
|
52
|
+
"URL", "URLSearchParams", "Request", "Response", "Headers", "Fetch",
|
|
53
|
+
"RequestInit", "ResponseInit", "ReadableStream", "WritableStream",
|
|
54
|
+
"TransformStream", "AbortController", "AbortSignal", "Buffer", "Blob", "File",
|
|
55
|
+
"FormData", "Event", "EventTarget", "Console", "Process", "Global", "Window",
|
|
56
|
+
"Document", "Node", "Finite", "NaN", "isFinite", "isNaN", "z", "Schema"
|
|
57
|
+
]);
|
|
58
|
+
const ANSI = {
|
|
59
|
+
reset: "\x1b[0m",
|
|
60
|
+
bold: "\x1b[1m",
|
|
61
|
+
dim: "\x1b[2m",
|
|
62
|
+
green: "\x1b[32m",
|
|
63
|
+
yellow: "\x1b[33m",
|
|
64
|
+
cyan: "\x1b[36m"
|
|
65
|
+
};
|
|
66
|
+
// ============================================================================
|
|
67
|
+
// Core Guards & Secret/Breakout Sanitization
|
|
68
|
+
// ============================================================================
|
|
69
|
+
function isRecord(value) {
|
|
70
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
71
|
+
}
|
|
72
|
+
function hasOwn(obj, key) {
|
|
73
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
74
|
+
}
|
|
75
|
+
function isForbiddenKey(key) {
|
|
76
|
+
return FORBIDDEN_KEYS.has(key);
|
|
77
|
+
}
|
|
78
|
+
function isSensitiveHeaderName(name) {
|
|
79
|
+
const trimmed = String(name).trim();
|
|
80
|
+
if (!trimmed)
|
|
81
|
+
return false;
|
|
82
|
+
return isSensitiveHeader(trimmed) || SENSITIVE_HEADER_RE.test(trimmed);
|
|
83
|
+
}
|
|
84
|
+
function isSensitiveQueryName(name) {
|
|
85
|
+
const trimmed = String(name).trim();
|
|
86
|
+
if (!trimmed)
|
|
87
|
+
return false;
|
|
88
|
+
return (isSensitiveQueryParam(trimmed) ||
|
|
89
|
+
SENSITIVE_QUERY_RE.test(trimmed) ||
|
|
90
|
+
isSensitiveHeaderName(trimmed));
|
|
91
|
+
}
|
|
92
|
+
function isSecretFieldName(name) {
|
|
93
|
+
const trimmed = String(name).trim();
|
|
94
|
+
if (!trimmed)
|
|
95
|
+
return false;
|
|
96
|
+
return (SECRET_FIELD_NAME_RE.test(trimmed) ||
|
|
97
|
+
isSensitiveHeaderName(trimmed) ||
|
|
98
|
+
isSensitiveQueryName(trimmed));
|
|
99
|
+
}
|
|
100
|
+
function isAuthSchemeValue(value) {
|
|
101
|
+
return AUTH_SCHEME_VALUE_RE.test(value);
|
|
102
|
+
}
|
|
103
|
+
function redactVaultPaths(text) {
|
|
104
|
+
return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
|
|
105
|
+
}
|
|
106
|
+
function scrubInlineSecretsOnly(raw) {
|
|
107
|
+
return redactVaultPaths(raw)
|
|
108
|
+
.replace(URL_BASIC_AUTH_RE, "$1")
|
|
109
|
+
.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]")
|
|
110
|
+
.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]")
|
|
111
|
+
.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]")
|
|
112
|
+
.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]")
|
|
113
|
+
.replace(INLINE_COOKIE_HEADER_RE, "$1: [REDACTED]")
|
|
114
|
+
.replace(INLINE_AUTH_HEADER_RE, "$1: [REDACTED]")
|
|
115
|
+
.replace(INLINE_SENSITIVE_ASSIGNMENT_RE, (_m, key, q, sep) => q ? `${key}${q}${sep}"[REDACTED]"` : `${key}${sep}[REDACTED]`);
|
|
116
|
+
}
|
|
117
|
+
function sanitizeUrlInText(rawUrl) {
|
|
118
|
+
const withoutVault = redactVaultPaths(rawUrl);
|
|
119
|
+
const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
|
|
120
|
+
const filterParams = (entries) => {
|
|
121
|
+
const safeParams = new URLSearchParams();
|
|
122
|
+
for (const [k, v] of entries) {
|
|
123
|
+
const trimmedKey = k.trim();
|
|
124
|
+
if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
|
|
125
|
+
continue;
|
|
126
|
+
if (isAuthSchemeValue(v) || /\.vibecode-vault/i.test(v))
|
|
127
|
+
continue;
|
|
128
|
+
const scrubbed = scrubInlineSecretsOnly(v);
|
|
129
|
+
if (/\[REDACTED/i.test(scrubbed))
|
|
130
|
+
continue;
|
|
131
|
+
safeParams.append(k, scrubbed);
|
|
132
|
+
}
|
|
133
|
+
return safeParams.toString();
|
|
134
|
+
};
|
|
135
|
+
try {
|
|
136
|
+
const parsed = new URL(withoutAuth);
|
|
137
|
+
parsed.username = "";
|
|
138
|
+
parsed.password = "";
|
|
139
|
+
parsed.hash = "";
|
|
140
|
+
const serialized = filterParams(parsed.searchParams.entries());
|
|
141
|
+
parsed.search = serialized ? `?${serialized}` : "";
|
|
142
|
+
return parsed.toString();
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
const cleanFallback = withoutAuth.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/?#@]*@+/, "$1");
|
|
146
|
+
const hashIdx = cleanFallback.indexOf("#");
|
|
147
|
+
const noHash = hashIdx >= 0 ? cleanFallback.slice(0, hashIdx) : cleanFallback;
|
|
148
|
+
const qIdx = noHash.indexOf("?");
|
|
149
|
+
if (qIdx < 0)
|
|
150
|
+
return noHash;
|
|
151
|
+
const basePart = noHash.slice(0, qIdx);
|
|
152
|
+
const serialized = filterParams(new URLSearchParams(noHash.slice(qIdx + 1)).entries());
|
|
153
|
+
return serialized ? `${basePart}?${serialized}` : basePart;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function sanitizeText(raw) {
|
|
157
|
+
const noNul = raw.replace(/[\0\u2028\u2029]/g, "");
|
|
158
|
+
const noVault = redactVaultPaths(noNul);
|
|
159
|
+
const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
|
|
160
|
+
return scrubInlineSecretsOnly(noUrls);
|
|
161
|
+
}
|
|
162
|
+
function sanitizeSingleLineText(raw, maxLen = 200) {
|
|
163
|
+
const cleaned = sanitizeText(raw)
|
|
164
|
+
.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
|
|
165
|
+
.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
|
|
166
|
+
.replace(/\*\//g, "* /")
|
|
167
|
+
.replace(/\s+/g, " ")
|
|
168
|
+
.trim();
|
|
169
|
+
if (cleaned.length <= maxLen)
|
|
170
|
+
return cleaned;
|
|
171
|
+
return `${cleaned.slice(0, maxLen - 3)}...`;
|
|
172
|
+
}
|
|
173
|
+
function tsString(raw) {
|
|
174
|
+
return JSON.stringify(raw)
|
|
175
|
+
.replace(/\u2028/g, "\\u2028")
|
|
176
|
+
.replace(/\u2029/g, "\\u2029");
|
|
177
|
+
}
|
|
178
|
+
function isSimpleTsPropKey(key) {
|
|
179
|
+
return (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) &&
|
|
180
|
+
!isForbiddenKey(key));
|
|
181
|
+
}
|
|
182
|
+
function formatTsPropKey(key) {
|
|
183
|
+
return isSimpleTsPropKey(key) ? key : tsString(key);
|
|
184
|
+
}
|
|
185
|
+
function sanitizeRegexPattern(raw, warnings) {
|
|
186
|
+
if (typeof raw !== "string" || raw.length === 0)
|
|
187
|
+
return undefined;
|
|
188
|
+
if (raw.includes("\0") || raw.length > MAX_PATTERN_LENGTH) {
|
|
189
|
+
warnings?.push("Dropped unsafe or excessively long regex pattern from exported schema.");
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
const hasSecret = VAULT_PATH_RE.test(raw) ||
|
|
193
|
+
URL_BASIC_AUTH_RE.test(raw) ||
|
|
194
|
+
INLINE_BEARER_TOKEN_RE.test(raw) ||
|
|
195
|
+
INLINE_BASIC_TOKEN_RE.test(raw) ||
|
|
196
|
+
INLINE_SCHEME_TOKEN_RE.test(raw) ||
|
|
197
|
+
INLINE_DIGEST_TOKEN_RE.test(raw) ||
|
|
198
|
+
INLINE_SENSITIVE_ASSIGNMENT_RE.test(raw);
|
|
199
|
+
VAULT_PATH_RE.lastIndex = 0;
|
|
200
|
+
URL_BASIC_AUTH_RE.lastIndex = 0;
|
|
201
|
+
INLINE_BEARER_TOKEN_RE.lastIndex = 0;
|
|
202
|
+
INLINE_BASIC_TOKEN_RE.lastIndex = 0;
|
|
203
|
+
INLINE_SCHEME_TOKEN_RE.lastIndex = 0;
|
|
204
|
+
INLINE_DIGEST_TOKEN_RE.lastIndex = 0;
|
|
205
|
+
INLINE_SENSITIVE_ASSIGNMENT_RE.lastIndex = 0;
|
|
206
|
+
if (hasSecret) {
|
|
207
|
+
warnings?.push("Dropped regex pattern containing sensitive secret or vault path.");
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
const cleaned = raw.replace(/[\r\n\u2028\u2029]/g, "");
|
|
211
|
+
if (!cleaned)
|
|
212
|
+
return undefined;
|
|
213
|
+
try {
|
|
214
|
+
// Validate syntax at codegen time so emitted code never throws a SyntaxError.
|
|
215
|
+
new RegExp(cleaned);
|
|
216
|
+
return cleaned;
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
warnings?.push("Dropped invalid regex pattern from exported schema.");
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function sanitizeJsonValue(value, depth = 0, seen = new Set()) {
|
|
224
|
+
if (value === null || value === undefined)
|
|
225
|
+
return value;
|
|
226
|
+
if (typeof value === "boolean")
|
|
227
|
+
return value;
|
|
228
|
+
if (typeof value === "number")
|
|
229
|
+
return Number.isFinite(value) ? value : null;
|
|
230
|
+
if (typeof value === "string") {
|
|
231
|
+
const trimmed = value.trim();
|
|
232
|
+
if (depth < MAX_BODY_DEPTH &&
|
|
233
|
+
((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
|
|
234
|
+
(trimmed.startsWith("[") && trimmed.endsWith("]")))) {
|
|
235
|
+
try {
|
|
236
|
+
const parsed = JSON.parse(trimmed);
|
|
237
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
238
|
+
return JSON.stringify(sanitizeJsonValue(parsed, depth + 1, seen));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// Fall through to plain string scrubbing
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return sanitizeText(value);
|
|
246
|
+
}
|
|
247
|
+
if (depth >= MAX_BODY_DEPTH)
|
|
248
|
+
return null;
|
|
249
|
+
if (typeof value !== "object")
|
|
250
|
+
return undefined;
|
|
251
|
+
if (seen.has(value))
|
|
252
|
+
return null;
|
|
253
|
+
seen.add(value);
|
|
254
|
+
try {
|
|
255
|
+
if (Array.isArray(value)) {
|
|
256
|
+
return value.map((item) => sanitizeJsonValue(item, depth + 1, seen));
|
|
257
|
+
}
|
|
258
|
+
const out = Object.create(null);
|
|
259
|
+
const rawObj = value;
|
|
260
|
+
for (const key of Object.keys(rawObj)) {
|
|
261
|
+
if (isForbiddenKey(key))
|
|
262
|
+
continue;
|
|
263
|
+
if (isSecretFieldName(key))
|
|
264
|
+
continue;
|
|
265
|
+
const cleanKey = sanitizeText(key).replace(/\0/g, "");
|
|
266
|
+
if (!cleanKey || isForbiddenKey(cleanKey) || isSecretFieldName(cleanKey))
|
|
267
|
+
continue;
|
|
268
|
+
const rawVal = rawObj[key];
|
|
269
|
+
if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol") {
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
out[cleanKey] = sanitizeJsonValue(rawVal, depth + 1, seen);
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
seen.delete(value);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
function refPointsToSecret(ref) {
|
|
281
|
+
if (!ref.startsWith("#/"))
|
|
282
|
+
return true;
|
|
283
|
+
const segments = ref
|
|
284
|
+
.slice(2)
|
|
285
|
+
.split("/")
|
|
286
|
+
.map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
287
|
+
for (const seg of segments) {
|
|
288
|
+
if (!seg || isForbiddenKey(seg) || isSecretFieldName(seg)) {
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
function sanitizeSchemaNode(schema, depth = 0, seen = new Set(), warnings) {
|
|
295
|
+
if (!isRecord(schema))
|
|
296
|
+
return undefined;
|
|
297
|
+
if (depth >= MAX_SCHEMA_DEPTH) {
|
|
298
|
+
warnings?.push(`Schema nesting exceeded maximum depth (${MAX_SCHEMA_DEPTH}); truncated branch.`);
|
|
299
|
+
return {};
|
|
300
|
+
}
|
|
301
|
+
if (seen.has(schema)) {
|
|
302
|
+
warnings?.push("Detected circular schema object reference; replaced cycle with empty schema.");
|
|
303
|
+
return {};
|
|
304
|
+
}
|
|
305
|
+
seen.add(schema);
|
|
306
|
+
try {
|
|
307
|
+
const out = {};
|
|
308
|
+
let propCount = 0;
|
|
309
|
+
for (const key of Object.keys(schema)) {
|
|
310
|
+
if (isForbiddenKey(key))
|
|
311
|
+
continue;
|
|
312
|
+
// Never retain raw examples or defaults in exported schemas.
|
|
313
|
+
if (key === "example" || key === "examples" || key === "default")
|
|
314
|
+
continue;
|
|
315
|
+
const val = schema[key];
|
|
316
|
+
if (val === undefined)
|
|
317
|
+
continue;
|
|
318
|
+
if (key === "type") {
|
|
319
|
+
const VALID_SCHEMA_TYPES = new Set(["string", "number", "integer", "boolean", "object", "array", "null"]);
|
|
320
|
+
if (typeof val === "string") {
|
|
321
|
+
const cleanType = sanitizeText(val).trim();
|
|
322
|
+
if (VALID_SCHEMA_TYPES.has(cleanType))
|
|
323
|
+
out.type = cleanType;
|
|
324
|
+
}
|
|
325
|
+
else if (Array.isArray(val)) {
|
|
326
|
+
const types = val
|
|
327
|
+
.filter((t) => typeof t === "string")
|
|
328
|
+
.map((t) => sanitizeText(t).trim())
|
|
329
|
+
.filter((t) => VALID_SCHEMA_TYPES.has(t));
|
|
330
|
+
if (types.length > 0)
|
|
331
|
+
out.type = [...new Set(types)];
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
else if (key === "nullable" && typeof val === "boolean") {
|
|
335
|
+
out.nullable = val;
|
|
336
|
+
}
|
|
337
|
+
else if (key === "format" && typeof val === "string") {
|
|
338
|
+
const fmt = sanitizeSingleLineText(val, 64);
|
|
339
|
+
if (fmt)
|
|
340
|
+
out.format = fmt;
|
|
341
|
+
}
|
|
342
|
+
else if (key === "description" && typeof val === "string") {
|
|
343
|
+
const desc = sanitizeSingleLineText(val, 240);
|
|
344
|
+
if (desc)
|
|
345
|
+
out.description = desc;
|
|
346
|
+
}
|
|
347
|
+
else if (key === "title" && typeof val === "string") {
|
|
348
|
+
const t = sanitizeSingleLineText(val, 120);
|
|
349
|
+
if (t)
|
|
350
|
+
out.title = t;
|
|
351
|
+
}
|
|
352
|
+
else if (key === "$ref" && typeof val === "string") {
|
|
353
|
+
const cleanRef = sanitizeSingleLineText(val, 200);
|
|
354
|
+
if (cleanRef.startsWith("#/") && !refPointsToSecret(cleanRef)) {
|
|
355
|
+
out.$ref = cleanRef;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
else if ((key === "minLength" ||
|
|
359
|
+
key === "maxLength" ||
|
|
360
|
+
key === "minItems" ||
|
|
361
|
+
key === "maxItems" ||
|
|
362
|
+
key === "minProperties" ||
|
|
363
|
+
key === "maxProperties") &&
|
|
364
|
+
typeof val === "number" &&
|
|
365
|
+
Number.isInteger(val) &&
|
|
366
|
+
val >= 0) {
|
|
367
|
+
out[key] = val;
|
|
368
|
+
}
|
|
369
|
+
else if ((key === "minimum" ||
|
|
370
|
+
key === "maximum" ||
|
|
371
|
+
key === "exclusiveMinimum" ||
|
|
372
|
+
key === "exclusiveMaximum") &&
|
|
373
|
+
typeof val === "number" &&
|
|
374
|
+
Number.isFinite(val)) {
|
|
375
|
+
out[key] = val;
|
|
376
|
+
}
|
|
377
|
+
else if (key === "multipleOf" && typeof val === "number" && Number.isFinite(val) && val > 0) {
|
|
378
|
+
out.multipleOf = val;
|
|
379
|
+
}
|
|
380
|
+
else if (key === "uniqueItems" && typeof val === "boolean") {
|
|
381
|
+
out.uniqueItems = val;
|
|
382
|
+
}
|
|
383
|
+
else if (key === "pattern") {
|
|
384
|
+
const pat = sanitizeRegexPattern(val, warnings);
|
|
385
|
+
if (pat !== undefined)
|
|
386
|
+
out.pattern = pat;
|
|
387
|
+
}
|
|
388
|
+
else if (key === "required" && Array.isArray(val)) {
|
|
389
|
+
const reqs = [];
|
|
390
|
+
for (const item of val) {
|
|
391
|
+
if (typeof item !== "string" || item.length === 0)
|
|
392
|
+
continue;
|
|
393
|
+
const cleanReq = sanitizeText(item).replace(/[\0\u2028\u2029]/g, "");
|
|
394
|
+
if (!cleanReq ||
|
|
395
|
+
isForbiddenKey(item) ||
|
|
396
|
+
isForbiddenKey(cleanReq) ||
|
|
397
|
+
isSecretFieldName(item) ||
|
|
398
|
+
isSecretFieldName(cleanReq) ||
|
|
399
|
+
/\.vibecode-vault|\[REDACTED/i.test(cleanReq) ||
|
|
400
|
+
isAuthSchemeValue(item)) {
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
if (!reqs.includes(cleanReq))
|
|
404
|
+
reqs.push(cleanReq);
|
|
405
|
+
}
|
|
406
|
+
if (reqs.length > 0)
|
|
407
|
+
out.required = reqs;
|
|
408
|
+
}
|
|
409
|
+
else if (key === "properties" && isRecord(val)) {
|
|
410
|
+
const props = Object.create(null);
|
|
411
|
+
for (const propKey of Object.keys(val)) {
|
|
412
|
+
if (isForbiddenKey(propKey) || isSecretFieldName(propKey))
|
|
413
|
+
continue;
|
|
414
|
+
if (propCount >= MAX_SCHEMA_PROPERTIES)
|
|
415
|
+
break;
|
|
416
|
+
const cleanPropKey = sanitizeText(propKey).replace(/\0/g, "");
|
|
417
|
+
if (!cleanPropKey || isForbiddenKey(cleanPropKey) || isSecretFieldName(cleanPropKey)) {
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
propCount += 1;
|
|
421
|
+
const sanitizedProp = sanitizeSchemaNode(val[propKey], depth + 1, seen, warnings);
|
|
422
|
+
props[cleanPropKey] = sanitizedProp ?? {};
|
|
423
|
+
}
|
|
424
|
+
out.properties = props;
|
|
425
|
+
}
|
|
426
|
+
else if (key === "additionalProperties") {
|
|
427
|
+
if (typeof val === "boolean") {
|
|
428
|
+
out.additionalProperties = val;
|
|
429
|
+
}
|
|
430
|
+
else if (isRecord(val)) {
|
|
431
|
+
out.additionalProperties = sanitizeSchemaNode(val, depth + 1, seen, warnings) ?? {};
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
else if (key === "items") {
|
|
435
|
+
if (Array.isArray(val)) {
|
|
436
|
+
out.items = val
|
|
437
|
+
.slice(0, MAX_TUPLE_ITEMS)
|
|
438
|
+
.map((item) => sanitizeSchemaNode(item, depth + 1, seen, warnings) ?? {});
|
|
439
|
+
}
|
|
440
|
+
else if (isRecord(val)) {
|
|
441
|
+
out.items = sanitizeSchemaNode(val, depth + 1, seen, warnings) ?? {};
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
else if (key === "prefixItems" && Array.isArray(val)) {
|
|
445
|
+
out.prefixItems = val
|
|
446
|
+
.slice(0, MAX_TUPLE_ITEMS)
|
|
447
|
+
.map((item) => sanitizeSchemaNode(item, depth + 1, seen, warnings) ?? {});
|
|
448
|
+
}
|
|
449
|
+
else if (key === "allOf" || key === "anyOf" || key === "oneOf") {
|
|
450
|
+
if (Array.isArray(val)) {
|
|
451
|
+
const branches = val
|
|
452
|
+
.map((item) => sanitizeSchemaNode(item, depth + 1, seen, warnings))
|
|
453
|
+
.filter((item) => item !== undefined);
|
|
454
|
+
if (branches.length > 0)
|
|
455
|
+
out[key] = branches;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
else if (key === "not" && isRecord(val)) {
|
|
459
|
+
const notSchema = sanitizeSchemaNode(val, depth + 1, seen, warnings);
|
|
460
|
+
if (notSchema)
|
|
461
|
+
out.not = notSchema;
|
|
462
|
+
}
|
|
463
|
+
else if (key === "const") {
|
|
464
|
+
out.const = sanitizeJsonValue(val, depth + 1, seen);
|
|
465
|
+
}
|
|
466
|
+
else if (key === "enum" && Array.isArray(val)) {
|
|
467
|
+
const cleanedEnum = val
|
|
468
|
+
.slice(0, MAX_ENUM_VALUES)
|
|
469
|
+
.map((item) => sanitizeJsonValue(item, depth + 1, seen))
|
|
470
|
+
.filter((item) => item !== undefined);
|
|
471
|
+
if (cleanedEnum.length > 0)
|
|
472
|
+
out.enum = cleanedEnum;
|
|
473
|
+
}
|
|
474
|
+
else if ((key === "$defs" || key === "definitions") && isRecord(val)) {
|
|
475
|
+
const defs = Object.create(null);
|
|
476
|
+
for (const defKey of Object.keys(val)) {
|
|
477
|
+
if (isForbiddenKey(defKey) || isSecretFieldName(defKey))
|
|
478
|
+
continue;
|
|
479
|
+
const cleanDefKey = sanitizeText(defKey).replace(/\0/g, "");
|
|
480
|
+
if (!cleanDefKey || isForbiddenKey(cleanDefKey) || isSecretFieldName(cleanDefKey)) {
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
const defSchema = sanitizeSchemaNode(val[defKey], depth + 1, seen, warnings);
|
|
484
|
+
if (defSchema)
|
|
485
|
+
defs[cleanDefKey] = defSchema;
|
|
486
|
+
}
|
|
487
|
+
out[key] = defs;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
// Ensure `required` never references a property that was dropped as secret/forbidden.
|
|
491
|
+
if (Array.isArray(out.required) && isRecord(out.properties)) {
|
|
492
|
+
const kept = out.required.filter((reqKey) => hasOwn(out.properties, reqKey));
|
|
493
|
+
if (kept.length > 0) {
|
|
494
|
+
out.required = kept;
|
|
495
|
+
}
|
|
496
|
+
else {
|
|
497
|
+
delete out.required;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return out;
|
|
501
|
+
}
|
|
502
|
+
finally {
|
|
503
|
+
seen.delete(schema);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
function resolveLocalRef(rootSchema, ref) {
|
|
507
|
+
if (!rootSchema || !ref.startsWith("#/") || refPointsToSecret(ref))
|
|
508
|
+
return undefined;
|
|
509
|
+
const parts = ref
|
|
510
|
+
.slice(2)
|
|
511
|
+
.split("/")
|
|
512
|
+
.map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
513
|
+
let current = rootSchema;
|
|
514
|
+
for (const part of parts) {
|
|
515
|
+
if (!part || isForbiddenKey(part) || isSecretFieldName(part))
|
|
516
|
+
return undefined;
|
|
517
|
+
if (!isRecord(current) || !hasOwn(current, part))
|
|
518
|
+
return undefined;
|
|
519
|
+
current = current[part];
|
|
520
|
+
}
|
|
521
|
+
return isRecord(current) ? current : undefined;
|
|
522
|
+
}
|
|
523
|
+
// ============================================================================
|
|
524
|
+
// Schema Inference from Sample Payloads
|
|
525
|
+
// ============================================================================
|
|
526
|
+
function mergeInferredSchemas(schemas) {
|
|
527
|
+
if (schemas.length === 0)
|
|
528
|
+
return {};
|
|
529
|
+
if (schemas.length === 1)
|
|
530
|
+
return schemas[0];
|
|
531
|
+
const allObjects = schemas.every((s) => s.type === "object" && isRecord(s.properties));
|
|
532
|
+
if (allObjects) {
|
|
533
|
+
const properties = Object.create(null);
|
|
534
|
+
const counts = new Map();
|
|
535
|
+
for (const s of schemas) {
|
|
536
|
+
const props = s.properties;
|
|
537
|
+
for (const k of Object.keys(props)) {
|
|
538
|
+
if (isForbiddenKey(k) || isSecretFieldName(k))
|
|
539
|
+
continue;
|
|
540
|
+
counts.set(k, (counts.get(k) ?? 0) + 1);
|
|
541
|
+
if (!hasOwn(properties, k)) {
|
|
542
|
+
properties[k] = props[k];
|
|
543
|
+
}
|
|
544
|
+
else if (properties[k].type === "integer" && props[k].type === "number") {
|
|
545
|
+
properties[k] = { type: "number" };
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
const required = [...counts.entries()]
|
|
550
|
+
.filter(([, count]) => count === schemas.length)
|
|
551
|
+
.map(([k]) => k);
|
|
552
|
+
return {
|
|
553
|
+
type: "object",
|
|
554
|
+
properties,
|
|
555
|
+
...(required.length > 0 ? { required } : {})
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
const primitiveTypes = new Set();
|
|
559
|
+
let allPrimitive = true;
|
|
560
|
+
for (const s of schemas) {
|
|
561
|
+
if (typeof s.type === "string" &&
|
|
562
|
+
(s.type === "string" ||
|
|
563
|
+
s.type === "number" ||
|
|
564
|
+
s.type === "integer" ||
|
|
565
|
+
s.type === "boolean" ||
|
|
566
|
+
s.type === "null")) {
|
|
567
|
+
primitiveTypes.add(s.type);
|
|
568
|
+
}
|
|
569
|
+
else {
|
|
570
|
+
allPrimitive = false;
|
|
571
|
+
break;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
if (allPrimitive) {
|
|
575
|
+
if (primitiveTypes.has("number") && primitiveTypes.has("integer")) {
|
|
576
|
+
primitiveTypes.delete("integer");
|
|
577
|
+
}
|
|
578
|
+
const types = [...primitiveTypes];
|
|
579
|
+
return types.length === 1 ? { type: types[0] } : { type: types };
|
|
580
|
+
}
|
|
581
|
+
return schemas[0];
|
|
582
|
+
}
|
|
583
|
+
function inferSchemaFromValue(value, depth = 0, seen = new Set()) {
|
|
584
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
585
|
+
return {};
|
|
586
|
+
if (value === null)
|
|
587
|
+
return { type: "null" };
|
|
588
|
+
if (typeof value === "boolean")
|
|
589
|
+
return { type: "boolean" };
|
|
590
|
+
if (typeof value === "number") {
|
|
591
|
+
return { type: Number.isInteger(value) ? "integer" : "number" };
|
|
592
|
+
}
|
|
593
|
+
if (typeof value === "string")
|
|
594
|
+
return { type: "string" };
|
|
595
|
+
if (typeof value !== "object")
|
|
596
|
+
return {};
|
|
597
|
+
if (seen.has(value))
|
|
598
|
+
return {};
|
|
599
|
+
seen.add(value);
|
|
600
|
+
try {
|
|
601
|
+
if (Array.isArray(value)) {
|
|
602
|
+
if (value.length === 0)
|
|
603
|
+
return { type: "array", items: {} };
|
|
604
|
+
const sampleSchemas = value
|
|
605
|
+
.slice(0, MAX_ARRAY_INFER_SAMPLES)
|
|
606
|
+
.map((item) => inferSchemaFromValue(item, depth + 1, seen));
|
|
607
|
+
return { type: "array", items: mergeInferredSchemas(sampleSchemas) };
|
|
608
|
+
}
|
|
609
|
+
const obj = value;
|
|
610
|
+
const properties = Object.create(null);
|
|
611
|
+
const required = [];
|
|
612
|
+
let count = 0;
|
|
613
|
+
for (const key of Object.keys(obj)) {
|
|
614
|
+
if (isForbiddenKey(key) || isSecretFieldName(key))
|
|
615
|
+
continue;
|
|
616
|
+
if (count >= MAX_SCHEMA_PROPERTIES)
|
|
617
|
+
break;
|
|
618
|
+
const cleanKey = sanitizeText(key).replace(/\0/g, "");
|
|
619
|
+
if (!cleanKey || isForbiddenKey(cleanKey) || isSecretFieldName(cleanKey))
|
|
620
|
+
continue;
|
|
621
|
+
const val = obj[key];
|
|
622
|
+
if (val === undefined)
|
|
623
|
+
continue;
|
|
624
|
+
count += 1;
|
|
625
|
+
required.push(cleanKey);
|
|
626
|
+
properties[cleanKey] = inferSchemaFromValue(val, depth + 1, seen);
|
|
627
|
+
}
|
|
628
|
+
return {
|
|
629
|
+
type: "object",
|
|
630
|
+
properties,
|
|
631
|
+
...(required.length > 0 ? { required } : {})
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
finally {
|
|
635
|
+
seen.delete(value);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// ============================================================================
|
|
639
|
+
// Identifier Allocation & Naming
|
|
640
|
+
// ============================================================================
|
|
641
|
+
function splitToAsciiWords(raw) {
|
|
642
|
+
const cleaned = sanitizeSingleLineText(raw, 160);
|
|
643
|
+
if (!cleaned)
|
|
644
|
+
return [];
|
|
645
|
+
const withSpaces = cleaned
|
|
646
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
647
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
|
|
648
|
+
.replace(/[^A-Za-z0-9]+/g, " ")
|
|
649
|
+
.trim();
|
|
650
|
+
if (!withSpaces)
|
|
651
|
+
return [];
|
|
652
|
+
return withSpaces
|
|
653
|
+
.split(/\s+/)
|
|
654
|
+
.map((w) => w.toLowerCase())
|
|
655
|
+
.filter((w) => w.length > 0)
|
|
656
|
+
.slice(0, 10);
|
|
657
|
+
}
|
|
658
|
+
function capitalizeWord(word) {
|
|
659
|
+
if (!word)
|
|
660
|
+
return "";
|
|
661
|
+
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
|
|
662
|
+
}
|
|
663
|
+
function toPascalCase(words, fallback) {
|
|
664
|
+
const clean = words
|
|
665
|
+
.map((w) => w.replace(/[^A-Za-z0-9]/g, ""))
|
|
666
|
+
.filter((w) => w.length > 0);
|
|
667
|
+
if (clean.length === 0)
|
|
668
|
+
return fallback;
|
|
669
|
+
let joined = clean.map(capitalizeWord).join("");
|
|
670
|
+
if (/^[0-9]/.test(joined)) {
|
|
671
|
+
joined = `Schema${joined}`;
|
|
672
|
+
}
|
|
673
|
+
return joined || fallback;
|
|
674
|
+
}
|
|
675
|
+
function allocateSchemaName(baseWords, suffix, usedNames) {
|
|
676
|
+
let base = toPascalCase(baseWords, "ContractItem");
|
|
677
|
+
if (TS_RESERVED_AND_GLOBALS.has(base) || isForbiddenKey(base)) {
|
|
678
|
+
base = `${base}Model`;
|
|
679
|
+
}
|
|
680
|
+
const cleanSuffix = suffix.replace(/[^A-Za-z0-9]/g, "");
|
|
681
|
+
let candidate = base.endsWith(cleanSuffix) ? base : `${base}${cleanSuffix}`;
|
|
682
|
+
if (!candidate ||
|
|
683
|
+
/^[0-9]/.test(candidate) ||
|
|
684
|
+
TS_RESERVED_AND_GLOBALS.has(candidate) ||
|
|
685
|
+
TS_RESERVED_AND_GLOBALS.has(`is${candidate}`) ||
|
|
686
|
+
isForbiddenKey(candidate)) {
|
|
687
|
+
candidate = `${candidate || "Item"}Model`;
|
|
688
|
+
}
|
|
689
|
+
let unique = candidate;
|
|
690
|
+
let seq = 2;
|
|
691
|
+
while (usedNames.has(unique) ||
|
|
692
|
+
TS_RESERVED_AND_GLOBALS.has(unique) ||
|
|
693
|
+
TS_RESERVED_AND_GLOBALS.has(`is${unique}`)) {
|
|
694
|
+
unique = `${candidate}${seq}`;
|
|
695
|
+
seq += 1;
|
|
696
|
+
}
|
|
697
|
+
usedNames.add(unique);
|
|
698
|
+
return unique;
|
|
699
|
+
}
|
|
700
|
+
function deriveBaseWordsFromInvariant(inv, fallbackWords) {
|
|
701
|
+
const idWords = splitToAsciiWords(typeof inv.id === "string" ? inv.id : "");
|
|
702
|
+
const trimmed = idWords.length > 1 && (idWords[0] === "inv" || idWords[0] === "http" || idWords[0] === "cli")
|
|
703
|
+
? idWords.slice(1)
|
|
704
|
+
: idWords;
|
|
705
|
+
const hasMeaningfulWord = trimmed.some((w) => /[a-z]/.test(w));
|
|
706
|
+
if (hasMeaningfulWord) {
|
|
707
|
+
return trimmed;
|
|
708
|
+
}
|
|
709
|
+
if (fallbackWords.length > 0) {
|
|
710
|
+
return [...fallbackWords];
|
|
711
|
+
}
|
|
712
|
+
return trimmed.length > 0 ? trimmed : ["item"];
|
|
713
|
+
}
|
|
714
|
+
// ============================================================================
|
|
715
|
+
// HTTP & CLI Invariant Extraction
|
|
716
|
+
// ============================================================================
|
|
717
|
+
function parsePathAndInlineQuery(rawPath) {
|
|
718
|
+
if (typeof rawPath !== "string") {
|
|
719
|
+
return { pathname: "/", inlineQuery: [] };
|
|
720
|
+
}
|
|
721
|
+
const cleaned = rawPath.replace(/[\r\n\0\x00-\x1f\x7f]+/g, "").trim();
|
|
722
|
+
if (!cleaned) {
|
|
723
|
+
return { pathname: "/", inlineQuery: [] };
|
|
724
|
+
}
|
|
725
|
+
const stripAndSplit = (input) => {
|
|
726
|
+
const hashIdx = input.indexOf("#");
|
|
727
|
+
const withoutHash = hashIdx >= 0 ? input.slice(0, hashIdx) : input;
|
|
728
|
+
const qIdx = withoutHash.indexOf("?");
|
|
729
|
+
const pathname = (qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash) || "/";
|
|
730
|
+
const rawQuery = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
|
|
731
|
+
const inlineQuery = [];
|
|
732
|
+
if (rawQuery) {
|
|
733
|
+
const params = new URLSearchParams(rawQuery);
|
|
734
|
+
for (const [k, v] of params.entries()) {
|
|
735
|
+
inlineQuery.push([k, v]);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return { pathname, inlineQuery };
|
|
739
|
+
};
|
|
740
|
+
if (/^https?:\/\//i.test(cleaned)) {
|
|
741
|
+
const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
|
|
742
|
+
try {
|
|
743
|
+
const parsed = new URL(withoutAuth);
|
|
744
|
+
const inlineQuery = [];
|
|
745
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
746
|
+
inlineQuery.push([k, v]);
|
|
747
|
+
}
|
|
748
|
+
return { pathname: parsed.pathname || "/", inlineQuery };
|
|
749
|
+
}
|
|
750
|
+
catch {
|
|
751
|
+
const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
|
|
752
|
+
return stripAndSplit(stripped);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
return stripAndSplit(cleaned);
|
|
756
|
+
}
|
|
757
|
+
function buildQuerySchema(inlineQuery, structuredQuery) {
|
|
758
|
+
const properties = Object.create(null);
|
|
759
|
+
const required = [];
|
|
760
|
+
const registerParam = (rawKey, valType, rawVal) => {
|
|
761
|
+
const cleanKey = sanitizeText(rawKey)
|
|
762
|
+
.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "")
|
|
763
|
+
.trim();
|
|
764
|
+
if (!cleanKey || isForbiddenKey(cleanKey) || isForbiddenKey(rawKey))
|
|
765
|
+
return;
|
|
766
|
+
if (isSensitiveQueryName(cleanKey) ||
|
|
767
|
+
isSecretFieldName(cleanKey) ||
|
|
768
|
+
/\.vibecode-vault|\[REDACTED/i.test(cleanKey)) {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
if (/\.vibecode-vault/i.test(rawVal) || isAuthSchemeValue(rawVal))
|
|
772
|
+
return;
|
|
773
|
+
if (!hasOwn(properties, cleanKey)) {
|
|
774
|
+
required.push(cleanKey);
|
|
775
|
+
}
|
|
776
|
+
properties[cleanKey] = { type: valType };
|
|
777
|
+
};
|
|
778
|
+
for (const [k, v] of inlineQuery) {
|
|
779
|
+
registerParam(k, "string", v);
|
|
780
|
+
}
|
|
781
|
+
if (isRecord(structuredQuery)) {
|
|
782
|
+
for (const key of Object.keys(structuredQuery)) {
|
|
783
|
+
if (isForbiddenKey(key))
|
|
784
|
+
continue;
|
|
785
|
+
const val = structuredQuery[key];
|
|
786
|
+
if (typeof val === "string") {
|
|
787
|
+
registerParam(key, "string", val);
|
|
788
|
+
}
|
|
789
|
+
else if (typeof val === "number" && Number.isFinite(val)) {
|
|
790
|
+
registerParam(key, Number.isInteger(val) ? "integer" : "number", String(val));
|
|
791
|
+
}
|
|
792
|
+
else if (typeof val === "boolean") {
|
|
793
|
+
registerParam(key, "boolean", String(val));
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
if (required.length === 0)
|
|
798
|
+
return undefined;
|
|
799
|
+
return {
|
|
800
|
+
type: "object",
|
|
801
|
+
properties,
|
|
802
|
+
required
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
function tryParseJsonPayload(raw) {
|
|
806
|
+
const trimmed = raw.trim();
|
|
807
|
+
if (!trimmed)
|
|
808
|
+
return { ok: false };
|
|
809
|
+
if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
|
|
810
|
+
(trimmed.startsWith("[") && trimmed.endsWith("]"))) {
|
|
811
|
+
try {
|
|
812
|
+
const parsed = JSON.parse(trimmed);
|
|
813
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
814
|
+
return { ok: true, value: parsed };
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
catch {
|
|
818
|
+
return { ok: false };
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
return { ok: false };
|
|
822
|
+
}
|
|
823
|
+
function extractHttpInvariantSchemas(inv, invId, usedNames, warnings) {
|
|
824
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
825
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
826
|
+
const method = typeof input.method === "string" && input.method.trim()
|
|
827
|
+
? sanitizeSingleLineText(input.method, 16).toUpperCase()
|
|
828
|
+
: "GET";
|
|
829
|
+
const rawPath = typeof input.path === "string"
|
|
830
|
+
? input.path
|
|
831
|
+
: typeof input.urlPath === "string"
|
|
832
|
+
? input.urlPath
|
|
833
|
+
: undefined;
|
|
834
|
+
const { pathname, inlineQuery } = parsePathAndInlineQuery(rawPath);
|
|
835
|
+
const routeWords = [method.toLowerCase(), ...splitToAsciiWords(pathname)];
|
|
836
|
+
const baseWords = deriveBaseWordsFromInvariant(inv, routeWords);
|
|
837
|
+
const descPrefix = typeof inv.description === "string" && inv.description.trim()
|
|
838
|
+
? sanitizeSingleLineText(inv.description, 160)
|
|
839
|
+
: `${method} ${sanitizeSingleLineText(pathname, 120)}`;
|
|
840
|
+
const entries = [];
|
|
841
|
+
// 1. Query parameters schema
|
|
842
|
+
const querySchema = isRecord(input.querySchema)
|
|
843
|
+
? sanitizeSchemaNode(input.querySchema, 0, new Set(), warnings)
|
|
844
|
+
: buildQuerySchema(inlineQuery, input.query);
|
|
845
|
+
if (querySchema) {
|
|
846
|
+
entries.push({
|
|
847
|
+
name: allocateSchemaName(baseWords, "Query", usedNames),
|
|
848
|
+
invariantId: invId,
|
|
849
|
+
kind: "http-query",
|
|
850
|
+
description: `${descPrefix} (query parameters)`,
|
|
851
|
+
schema: querySchema,
|
|
852
|
+
rootSchema: querySchema
|
|
853
|
+
});
|
|
854
|
+
}
|
|
855
|
+
// 2. Request body schema
|
|
856
|
+
let requestSchema;
|
|
857
|
+
if (isRecord(input.requestSchema)) {
|
|
858
|
+
requestSchema = sanitizeSchemaNode(input.requestSchema, 0, new Set(), warnings);
|
|
859
|
+
}
|
|
860
|
+
else {
|
|
861
|
+
const rawBody = input.body !== undefined ? input.body : input.jsonBody;
|
|
862
|
+
if (rawBody !== undefined && rawBody !== null) {
|
|
863
|
+
if (typeof rawBody === "string") {
|
|
864
|
+
const parsed = tryParseJsonPayload(rawBody);
|
|
865
|
+
if (parsed.ok) {
|
|
866
|
+
requestSchema = inferSchemaFromValue(sanitizeJsonValue(parsed.value));
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
else if (typeof rawBody === "object") {
|
|
870
|
+
requestSchema = inferSchemaFromValue(sanitizeJsonValue(rawBody));
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
if (requestSchema) {
|
|
875
|
+
entries.push({
|
|
876
|
+
name: allocateSchemaName(baseWords, "Request", usedNames),
|
|
877
|
+
invariantId: invId,
|
|
878
|
+
kind: "http-request",
|
|
879
|
+
description: `${descPrefix} (request body)`,
|
|
880
|
+
schema: requestSchema,
|
|
881
|
+
rootSchema: requestSchema
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
// 3. Expected response schema
|
|
885
|
+
let responseSchema;
|
|
886
|
+
if (isRecord(expected.jsonSchema)) {
|
|
887
|
+
responseSchema = sanitizeSchemaNode(expected.jsonSchema, 0, new Set(), warnings);
|
|
888
|
+
}
|
|
889
|
+
else if (expected.jsonSubset !== undefined) {
|
|
890
|
+
responseSchema = inferSchemaFromValue(sanitizeJsonValue(expected.jsonSubset));
|
|
891
|
+
}
|
|
892
|
+
else if (typeof expected.bodyExact === "string") {
|
|
893
|
+
const parsed = tryParseJsonPayload(expected.bodyExact);
|
|
894
|
+
if (parsed.ok) {
|
|
895
|
+
responseSchema = inferSchemaFromValue(sanitizeJsonValue(parsed.value));
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
if (responseSchema) {
|
|
899
|
+
entries.push({
|
|
900
|
+
name: allocateSchemaName(baseWords, "Response", usedNames),
|
|
901
|
+
invariantId: invId,
|
|
902
|
+
kind: "http-response",
|
|
903
|
+
description: `${descPrefix} (response body)`,
|
|
904
|
+
schema: responseSchema,
|
|
905
|
+
rootSchema: responseSchema
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
return entries;
|
|
909
|
+
}
|
|
910
|
+
function extractCliInvariantSchemas(inv, invId, usedNames, warnings) {
|
|
911
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
912
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
913
|
+
const argWords = Array.isArray(input.args)
|
|
914
|
+
? splitToAsciiWords(input.args
|
|
915
|
+
.filter((a) => typeof a === "string" && !isSecretFieldName(a) && !isAuthSchemeValue(a))
|
|
916
|
+
.slice(0, 3)
|
|
917
|
+
.join(" "))
|
|
918
|
+
: [];
|
|
919
|
+
const baseWords = deriveBaseWordsFromInvariant(inv, argWords.length > 0 ? ["cli", ...argWords] : ["cli", "command"]);
|
|
920
|
+
const descPrefix = typeof inv.description === "string" && inv.description.trim()
|
|
921
|
+
? sanitizeSingleLineText(inv.description, 160)
|
|
922
|
+
: `CLI ${invId}`;
|
|
923
|
+
const entries = [];
|
|
924
|
+
// 1. Stdin JSON schema
|
|
925
|
+
let stdinSchema;
|
|
926
|
+
if (isRecord(input.stdinSchema)) {
|
|
927
|
+
stdinSchema = sanitizeSchemaNode(input.stdinSchema, 0, new Set(), warnings);
|
|
928
|
+
}
|
|
929
|
+
else if (typeof input.stdin === "string") {
|
|
930
|
+
const parsed = tryParseJsonPayload(input.stdin);
|
|
931
|
+
if (parsed.ok) {
|
|
932
|
+
stdinSchema = inferSchemaFromValue(sanitizeJsonValue(parsed.value));
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (stdinSchema) {
|
|
936
|
+
entries.push({
|
|
937
|
+
name: allocateSchemaName(baseWords, "Stdin", usedNames),
|
|
938
|
+
invariantId: invId,
|
|
939
|
+
kind: "cli-stdin",
|
|
940
|
+
description: `${descPrefix} (stdin JSON)`,
|
|
941
|
+
schema: stdinSchema,
|
|
942
|
+
rootSchema: stdinSchema
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
// 2. Stdout JSON schema
|
|
946
|
+
let stdoutSchema;
|
|
947
|
+
if (isRecord(expected.jsonSchema)) {
|
|
948
|
+
stdoutSchema = sanitizeSchemaNode(expected.jsonSchema, 0, new Set(), warnings);
|
|
949
|
+
}
|
|
950
|
+
else if (expected.jsonSubset !== undefined) {
|
|
951
|
+
stdoutSchema = inferSchemaFromValue(sanitizeJsonValue(expected.jsonSubset));
|
|
952
|
+
}
|
|
953
|
+
else {
|
|
954
|
+
const rawStdout = typeof expected.stdoutExact === "string"
|
|
955
|
+
? expected.stdoutExact
|
|
956
|
+
: typeof expected.goldenStdout === "string"
|
|
957
|
+
? expected.goldenStdout
|
|
958
|
+
: undefined;
|
|
959
|
+
if (rawStdout !== undefined) {
|
|
960
|
+
const parsed = tryParseJsonPayload(rawStdout);
|
|
961
|
+
if (parsed.ok) {
|
|
962
|
+
stdoutSchema = inferSchemaFromValue(sanitizeJsonValue(parsed.value));
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
if (stdoutSchema) {
|
|
967
|
+
entries.push({
|
|
968
|
+
name: allocateSchemaName(baseWords, "Stdout", usedNames),
|
|
969
|
+
invariantId: invId,
|
|
970
|
+
kind: "cli-stdout",
|
|
971
|
+
description: `${descPrefix} (stdout JSON)`,
|
|
972
|
+
schema: stdoutSchema,
|
|
973
|
+
rootSchema: stdoutSchema
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
return entries;
|
|
977
|
+
}
|
|
978
|
+
// ============================================================================
|
|
979
|
+
// Shared Schema Merging & Dereferencing Helpers
|
|
980
|
+
// ============================================================================
|
|
981
|
+
function mergeAllOfObjectBranches(branches, rootSchema, depth = 0, seenRefs = new Set()) {
|
|
982
|
+
const properties = Object.create(null);
|
|
983
|
+
const required = new Set();
|
|
984
|
+
let allObjects = branches.length > 0;
|
|
985
|
+
let hasAnyProps = false;
|
|
986
|
+
for (const rawBranch of branches) {
|
|
987
|
+
let branch = rawBranch;
|
|
988
|
+
if (typeof rawBranch.$ref === "string" && depth < MAX_SCHEMA_DEPTH && !seenRefs.has(rawBranch.$ref)) {
|
|
989
|
+
const resolved = resolveLocalRef(rootSchema, rawBranch.$ref);
|
|
990
|
+
if (resolved)
|
|
991
|
+
branch = resolved;
|
|
992
|
+
}
|
|
993
|
+
const isObjLike = branch.type === "object" ||
|
|
994
|
+
isRecord(branch.properties) ||
|
|
995
|
+
Array.isArray(branch.required);
|
|
996
|
+
if (!isObjLike) {
|
|
997
|
+
allObjects = false;
|
|
998
|
+
break;
|
|
999
|
+
}
|
|
1000
|
+
if (isRecord(branch.properties)) {
|
|
1001
|
+
for (const k of Object.keys(branch.properties)) {
|
|
1002
|
+
if (isForbiddenKey(k) || isSecretFieldName(k))
|
|
1003
|
+
continue;
|
|
1004
|
+
properties[k] = branch.properties[k];
|
|
1005
|
+
hasAnyProps = true;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
if (Array.isArray(branch.required)) {
|
|
1009
|
+
for (const reqKey of branch.required) {
|
|
1010
|
+
if (typeof reqKey === "string" && !isForbiddenKey(reqKey) && !isSecretFieldName(reqKey)) {
|
|
1011
|
+
required.add(reqKey);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
return {
|
|
1017
|
+
allObjects: allObjects && hasAnyProps,
|
|
1018
|
+
merged: {
|
|
1019
|
+
type: "object",
|
|
1020
|
+
properties,
|
|
1021
|
+
...(required.size > 0 ? { required: [...required] } : {})
|
|
1022
|
+
}
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
function effectiveSchemaType(schema) {
|
|
1026
|
+
if (typeof schema.type === "string")
|
|
1027
|
+
return schema.type;
|
|
1028
|
+
if (isRecord(schema.properties) || schema.additionalProperties !== undefined)
|
|
1029
|
+
return "object";
|
|
1030
|
+
if (schema.items !== undefined || Array.isArray(schema.prefixItems))
|
|
1031
|
+
return "array";
|
|
1032
|
+
return undefined;
|
|
1033
|
+
}
|
|
1034
|
+
// ============================================================================
|
|
1035
|
+
// 1. JSON Schema Draft 2020-12 Emitter
|
|
1036
|
+
// ============================================================================
|
|
1037
|
+
function toPlainJsonObject(value, depth = 0, seen = new Set()) {
|
|
1038
|
+
if (value === null || typeof value !== "object")
|
|
1039
|
+
return value;
|
|
1040
|
+
if (depth >= MAX_SCHEMA_DEPTH + 4 || seen.has(value))
|
|
1041
|
+
return null;
|
|
1042
|
+
seen.add(value);
|
|
1043
|
+
try {
|
|
1044
|
+
if (Array.isArray(value)) {
|
|
1045
|
+
return value.map((item) => toPlainJsonObject(item, depth + 1, seen));
|
|
1046
|
+
}
|
|
1047
|
+
const out = {};
|
|
1048
|
+
for (const key of Object.keys(value)) {
|
|
1049
|
+
if (isForbiddenKey(key))
|
|
1050
|
+
continue;
|
|
1051
|
+
out[key] = toPlainJsonObject(value[key], depth + 1, seen);
|
|
1052
|
+
}
|
|
1053
|
+
return out;
|
|
1054
|
+
}
|
|
1055
|
+
finally {
|
|
1056
|
+
seen.delete(value);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
function materializeJsonSchema(schema, rootSchema, strict, depth = 0, seen = new Set(), seenRefs = new Set()) {
|
|
1060
|
+
if (!schema || !isRecord(schema))
|
|
1061
|
+
return {};
|
|
1062
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1063
|
+
return {};
|
|
1064
|
+
if (seen.has(schema))
|
|
1065
|
+
return {};
|
|
1066
|
+
seen.add(schema);
|
|
1067
|
+
try {
|
|
1068
|
+
if (typeof schema.$ref === "string") {
|
|
1069
|
+
if (seenRefs.has(schema.$ref))
|
|
1070
|
+
return {};
|
|
1071
|
+
const resolved = resolveLocalRef(rootSchema, schema.$ref);
|
|
1072
|
+
if (!resolved)
|
|
1073
|
+
return {};
|
|
1074
|
+
seenRefs.add(schema.$ref);
|
|
1075
|
+
try {
|
|
1076
|
+
return materializeJsonSchema(resolved, rootSchema, strict, depth + 1, seen, seenRefs);
|
|
1077
|
+
}
|
|
1078
|
+
finally {
|
|
1079
|
+
seenRefs.delete(schema.$ref);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
// Merge pure-object allOf branches so strict `additionalProperties: false` works seamlessly with validateJsonSchema().
|
|
1083
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1084
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema, depth, seenRefs);
|
|
1085
|
+
if (allObjects) {
|
|
1086
|
+
const mergedWithMeta = {
|
|
1087
|
+
...merged,
|
|
1088
|
+
...(schema.nullable ? { nullable: true } : {}),
|
|
1089
|
+
...(typeof schema.description === "string" ? { description: schema.description } : {})
|
|
1090
|
+
};
|
|
1091
|
+
return materializeJsonSchema(mergedWithMeta, rootSchema, strict, depth + 1, seen, seenRefs);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
const out = {};
|
|
1095
|
+
if (schema.type !== undefined)
|
|
1096
|
+
out.type = schema.type;
|
|
1097
|
+
if (schema.nullable === true)
|
|
1098
|
+
out.nullable = true;
|
|
1099
|
+
if (typeof schema.title === "string")
|
|
1100
|
+
out.title = schema.title;
|
|
1101
|
+
if (typeof schema.description === "string")
|
|
1102
|
+
out.description = schema.description;
|
|
1103
|
+
if (typeof schema.format === "string")
|
|
1104
|
+
out.format = schema.format;
|
|
1105
|
+
if (schema.const !== undefined)
|
|
1106
|
+
out.const = toPlainJsonObject(schema.const);
|
|
1107
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
1108
|
+
out.enum = schema.enum.map((item) => toPlainJsonObject(item));
|
|
1109
|
+
}
|
|
1110
|
+
if (typeof schema.minLength === "number")
|
|
1111
|
+
out.minLength = schema.minLength;
|
|
1112
|
+
if (typeof schema.maxLength === "number")
|
|
1113
|
+
out.maxLength = schema.maxLength;
|
|
1114
|
+
if (typeof schema.pattern === "string")
|
|
1115
|
+
out.pattern = schema.pattern;
|
|
1116
|
+
if (typeof schema.minimum === "number")
|
|
1117
|
+
out.minimum = schema.minimum;
|
|
1118
|
+
if (typeof schema.maximum === "number")
|
|
1119
|
+
out.maximum = schema.maximum;
|
|
1120
|
+
if (typeof schema.exclusiveMinimum === "number")
|
|
1121
|
+
out.exclusiveMinimum = schema.exclusiveMinimum;
|
|
1122
|
+
if (typeof schema.exclusiveMaximum === "number")
|
|
1123
|
+
out.exclusiveMaximum = schema.exclusiveMaximum;
|
|
1124
|
+
if (typeof schema.multipleOf === "number")
|
|
1125
|
+
out.multipleOf = schema.multipleOf;
|
|
1126
|
+
if (typeof schema.minItems === "number")
|
|
1127
|
+
out.minItems = schema.minItems;
|
|
1128
|
+
if (typeof schema.maxItems === "number")
|
|
1129
|
+
out.maxItems = schema.maxItems;
|
|
1130
|
+
if (typeof schema.uniqueItems === "boolean")
|
|
1131
|
+
out.uniqueItems = schema.uniqueItems;
|
|
1132
|
+
if (typeof schema.minProperties === "number")
|
|
1133
|
+
out.minProperties = schema.minProperties;
|
|
1134
|
+
if (typeof schema.maxProperties === "number")
|
|
1135
|
+
out.maxProperties = schema.maxProperties;
|
|
1136
|
+
if (Array.isArray(schema.prefixItems) && schema.prefixItems.length > 0) {
|
|
1137
|
+
out.prefixItems = schema.prefixItems.map((item) => materializeJsonSchema(item, rootSchema, strict, depth + 1, seen, seenRefs));
|
|
1138
|
+
}
|
|
1139
|
+
if (Array.isArray(schema.items)) {
|
|
1140
|
+
out.items = schema.items.map((item) => materializeJsonSchema(item, rootSchema, strict, depth + 1, seen, seenRefs));
|
|
1141
|
+
}
|
|
1142
|
+
else if (isRecord(schema.items)) {
|
|
1143
|
+
out.items = materializeJsonSchema(schema.items, rootSchema, strict, depth + 1, seen, seenRefs);
|
|
1144
|
+
}
|
|
1145
|
+
const effType = effectiveSchemaType(schema);
|
|
1146
|
+
if (isRecord(schema.properties)) {
|
|
1147
|
+
const propsOut = {};
|
|
1148
|
+
for (const k of Object.keys(schema.properties)) {
|
|
1149
|
+
if (isForbiddenKey(k) || isSecretFieldName(k))
|
|
1150
|
+
continue;
|
|
1151
|
+
propsOut[k] = materializeJsonSchema(schema.properties[k], rootSchema, strict, depth + 1, seen, seenRefs);
|
|
1152
|
+
}
|
|
1153
|
+
out.properties = propsOut;
|
|
1154
|
+
if (out.type === undefined)
|
|
1155
|
+
out.type = "object";
|
|
1156
|
+
}
|
|
1157
|
+
if (Array.isArray(schema.required) && schema.required.length > 0) {
|
|
1158
|
+
const propsRecord = isRecord(out.properties) ? out.properties : undefined;
|
|
1159
|
+
const reqs = schema.required.filter((k) => typeof k === "string" &&
|
|
1160
|
+
!isForbiddenKey(k) &&
|
|
1161
|
+
!isSecretFieldName(k) &&
|
|
1162
|
+
(!propsRecord || hasOwn(propsRecord, k)));
|
|
1163
|
+
if (reqs.length > 0)
|
|
1164
|
+
out.required = reqs;
|
|
1165
|
+
}
|
|
1166
|
+
if (effType === "object" || isRecord(out.properties)) {
|
|
1167
|
+
if (strict) {
|
|
1168
|
+
out.additionalProperties = false;
|
|
1169
|
+
}
|
|
1170
|
+
else if (typeof schema.additionalProperties === "boolean") {
|
|
1171
|
+
out.additionalProperties = schema.additionalProperties;
|
|
1172
|
+
}
|
|
1173
|
+
else if (isRecord(schema.additionalProperties)) {
|
|
1174
|
+
out.additionalProperties = materializeJsonSchema(schema.additionalProperties, rootSchema, strict, depth + 1, seen, seenRefs);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1178
|
+
out.allOf = schema.allOf.map((branch) => materializeJsonSchema(branch, rootSchema, strict, depth + 1, seen, seenRefs));
|
|
1179
|
+
}
|
|
1180
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
1181
|
+
out.anyOf = schema.anyOf.map((branch) => materializeJsonSchema(branch, rootSchema, strict, depth + 1, seen, seenRefs));
|
|
1182
|
+
}
|
|
1183
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
1184
|
+
out.oneOf = schema.oneOf.map((branch) => materializeJsonSchema(branch, rootSchema, strict, depth + 1, seen, seenRefs));
|
|
1185
|
+
}
|
|
1186
|
+
if (isRecord(schema.not)) {
|
|
1187
|
+
out.not = materializeJsonSchema(schema.not, rootSchema, strict, depth + 1, seen, seenRefs);
|
|
1188
|
+
}
|
|
1189
|
+
return out;
|
|
1190
|
+
}
|
|
1191
|
+
finally {
|
|
1192
|
+
seen.delete(schema);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
function emitJsonSchemaBundle(entries, title, strict) {
|
|
1196
|
+
const defs = {};
|
|
1197
|
+
for (const entry of entries) {
|
|
1198
|
+
const materialized = materializeJsonSchema(entry.schema, entry.rootSchema, strict);
|
|
1199
|
+
if (!hasOwn(materialized, "description") && entry.description) {
|
|
1200
|
+
materialized.description = entry.description;
|
|
1201
|
+
}
|
|
1202
|
+
defs[entry.name] = materialized;
|
|
1203
|
+
}
|
|
1204
|
+
const bundle = {
|
|
1205
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
1206
|
+
title,
|
|
1207
|
+
description: "Generated by vibecode-anything contract schema exporter",
|
|
1208
|
+
$defs: defs
|
|
1209
|
+
};
|
|
1210
|
+
return `${JSON.stringify(bundle, null, 2)
|
|
1211
|
+
.replace(/\u2028/g, "\\u2028")
|
|
1212
|
+
.replace(/\u2029/g, "\\u2029")}\n`;
|
|
1213
|
+
}
|
|
1214
|
+
// ============================================================================
|
|
1215
|
+
// 2. Zod Schema Emitter
|
|
1216
|
+
// ============================================================================
|
|
1217
|
+
function renderTsLiteral(value) {
|
|
1218
|
+
if (value === null)
|
|
1219
|
+
return "null";
|
|
1220
|
+
if (typeof value === "boolean")
|
|
1221
|
+
return value ? "true" : "false";
|
|
1222
|
+
if (typeof value === "number")
|
|
1223
|
+
return Number.isFinite(value) ? String(value) : null;
|
|
1224
|
+
if (typeof value === "string")
|
|
1225
|
+
return tsString(value);
|
|
1226
|
+
return null;
|
|
1227
|
+
}
|
|
1228
|
+
function literalValueToZod(value, depth = 0) {
|
|
1229
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1230
|
+
return "z.unknown()";
|
|
1231
|
+
const prim = renderTsLiteral(value);
|
|
1232
|
+
if (prim !== null)
|
|
1233
|
+
return `z.literal(${prim})`;
|
|
1234
|
+
if (Array.isArray(value)) {
|
|
1235
|
+
if (value.length === 0)
|
|
1236
|
+
return "z.tuple([])";
|
|
1237
|
+
return `z.tuple([${value.slice(0, MAX_TUPLE_ITEMS).map((v) => literalValueToZod(v, depth + 1)).join(", ")}])`;
|
|
1238
|
+
}
|
|
1239
|
+
if (isRecord(value)) {
|
|
1240
|
+
const keys = Object.keys(value).filter((k) => !isForbiddenKey(k) && !isSecretFieldName(k));
|
|
1241
|
+
if (keys.length === 0)
|
|
1242
|
+
return "z.object({}).strict()";
|
|
1243
|
+
const fields = keys.map((k) => `${formatTsPropKey(k)}: ${literalValueToZod(value[k], depth + 1)}`);
|
|
1244
|
+
return `z.object({ ${fields.join(", ")} }).strict()`;
|
|
1245
|
+
}
|
|
1246
|
+
return "z.unknown()";
|
|
1247
|
+
}
|
|
1248
|
+
function schemaToZod(schema, rootSchema, strict, depth = 0, seen = new Set(), seenRefs = new Set(), indent = 0) {
|
|
1249
|
+
if (!schema || !isRecord(schema))
|
|
1250
|
+
return "z.unknown()";
|
|
1251
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1252
|
+
return "z.unknown()";
|
|
1253
|
+
if (seen.has(schema))
|
|
1254
|
+
return "z.unknown()";
|
|
1255
|
+
seen.add(schema);
|
|
1256
|
+
try {
|
|
1257
|
+
if (typeof schema.$ref === "string") {
|
|
1258
|
+
if (seenRefs.has(schema.$ref))
|
|
1259
|
+
return "z.unknown()";
|
|
1260
|
+
const resolved = resolveLocalRef(rootSchema, schema.$ref);
|
|
1261
|
+
if (!resolved)
|
|
1262
|
+
return "z.unknown()";
|
|
1263
|
+
seenRefs.add(schema.$ref);
|
|
1264
|
+
try {
|
|
1265
|
+
return schemaToZod(resolved, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1266
|
+
}
|
|
1267
|
+
finally {
|
|
1268
|
+
seenRefs.delete(schema.$ref);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
if (schema.const !== undefined) {
|
|
1272
|
+
const expr = literalValueToZod(schema.const, depth + 1);
|
|
1273
|
+
return schema.nullable && schema.const !== null ? `${expr}.nullable()` : expr;
|
|
1274
|
+
}
|
|
1275
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
1276
|
+
const allStrings = schema.enum.every((item) => typeof item === "string");
|
|
1277
|
+
if (allStrings) {
|
|
1278
|
+
const uniqueStrings = [...new Set(schema.enum)];
|
|
1279
|
+
const expr = `z.enum([${uniqueStrings.map(tsString).join(", ")}])`;
|
|
1280
|
+
return schema.nullable ? `${expr}.nullable()` : expr;
|
|
1281
|
+
}
|
|
1282
|
+
const members = [
|
|
1283
|
+
...new Set(schema.enum.map((item) => literalValueToZod(item, depth + 1)))
|
|
1284
|
+
];
|
|
1285
|
+
const hasNull = schema.enum.includes(null);
|
|
1286
|
+
let expr;
|
|
1287
|
+
if (members.length === 1) {
|
|
1288
|
+
expr = members[0];
|
|
1289
|
+
}
|
|
1290
|
+
else {
|
|
1291
|
+
expr = `z.union([${members.join(", ")}])`;
|
|
1292
|
+
}
|
|
1293
|
+
return schema.nullable && !hasNull ? `${expr}.nullable()` : expr;
|
|
1294
|
+
}
|
|
1295
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
1296
|
+
const branches = schema.oneOf.map((b) => schemaToZod(b, rootSchema, strict, depth + 1, seen, seenRefs, indent));
|
|
1297
|
+
const expr = branches.length === 1 ? branches[0] : `z.union([${branches.join(", ")}])`;
|
|
1298
|
+
return schema.nullable ? `${expr}.nullable()` : expr;
|
|
1299
|
+
}
|
|
1300
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
1301
|
+
const branches = schema.anyOf.map((b) => schemaToZod(b, rootSchema, strict, depth + 1, seen, seenRefs, indent));
|
|
1302
|
+
const expr = branches.length === 1 ? branches[0] : `z.union([${branches.join(", ")}])`;
|
|
1303
|
+
return schema.nullable ? `${expr}.nullable()` : expr;
|
|
1304
|
+
}
|
|
1305
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1306
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema, depth, seenRefs);
|
|
1307
|
+
if (allObjects) {
|
|
1308
|
+
const expr = schemaToZod(merged, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1309
|
+
return schema.nullable ? `${expr}.nullable()` : expr;
|
|
1310
|
+
}
|
|
1311
|
+
const branches = schema.allOf.map((b) => schemaToZod(b, rootSchema, strict, depth + 1, seen, seenRefs, indent));
|
|
1312
|
+
const expr = branches.reduce((acc, cur) => `${acc}.and(${cur})`);
|
|
1313
|
+
return schema.nullable ? `${expr}.nullable()` : expr;
|
|
1314
|
+
}
|
|
1315
|
+
if (Array.isArray(schema.type) && schema.type.length > 0) {
|
|
1316
|
+
const hasNull = schema.type.includes("null");
|
|
1317
|
+
const nonNull = schema.type.filter((t) => t !== "null");
|
|
1318
|
+
if (nonNull.length === 0)
|
|
1319
|
+
return "z.null()";
|
|
1320
|
+
const parts = nonNull.map((singleType) => schemaToZod({ ...schema, type: singleType, nullable: false }, rootSchema, strict, depth + 1, seen, seenRefs, indent));
|
|
1321
|
+
const base = parts.length === 1 ? parts[0] : `z.union([${parts.join(", ")}])`;
|
|
1322
|
+
return hasNull || schema.nullable ? `${base}.nullable()` : base;
|
|
1323
|
+
}
|
|
1324
|
+
const effType = effectiveSchemaType(schema);
|
|
1325
|
+
let expr;
|
|
1326
|
+
if (effType === "string") {
|
|
1327
|
+
expr = "z.string()";
|
|
1328
|
+
if (schema.format === "email")
|
|
1329
|
+
expr += ".email()";
|
|
1330
|
+
else if (schema.format === "uuid")
|
|
1331
|
+
expr += ".uuid()";
|
|
1332
|
+
else if (schema.format === "uri" || schema.format === "url")
|
|
1333
|
+
expr += ".url()";
|
|
1334
|
+
else if (schema.format === "date-time")
|
|
1335
|
+
expr += ".datetime()";
|
|
1336
|
+
if (typeof schema.minLength === "number")
|
|
1337
|
+
expr += `.min(${schema.minLength})`;
|
|
1338
|
+
if (typeof schema.maxLength === "number")
|
|
1339
|
+
expr += `.max(${schema.maxLength})`;
|
|
1340
|
+
if (typeof schema.pattern === "string") {
|
|
1341
|
+
expr += `.regex(new RegExp(${tsString(schema.pattern)}))`;
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
else if (effType === "integer" || effType === "number") {
|
|
1345
|
+
expr = "z.number()";
|
|
1346
|
+
if (effType === "integer")
|
|
1347
|
+
expr += ".int()";
|
|
1348
|
+
if (typeof schema.minimum === "number")
|
|
1349
|
+
expr += `.min(${schema.minimum})`;
|
|
1350
|
+
if (typeof schema.maximum === "number")
|
|
1351
|
+
expr += `.max(${schema.maximum})`;
|
|
1352
|
+
if (typeof schema.exclusiveMinimum === "number")
|
|
1353
|
+
expr += `.gt(${schema.exclusiveMinimum})`;
|
|
1354
|
+
if (typeof schema.exclusiveMaximum === "number")
|
|
1355
|
+
expr += `.lt(${schema.exclusiveMaximum})`;
|
|
1356
|
+
if (typeof schema.multipleOf === "number" && schema.multipleOf > 0) {
|
|
1357
|
+
expr += `.multipleOf(${schema.multipleOf})`;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
else if (effType === "boolean") {
|
|
1361
|
+
expr = "z.boolean()";
|
|
1362
|
+
}
|
|
1363
|
+
else if (effType === "null") {
|
|
1364
|
+
return "z.null()";
|
|
1365
|
+
}
|
|
1366
|
+
else if (effType === "array") {
|
|
1367
|
+
const tupleItems = Array.isArray(schema.prefixItems)
|
|
1368
|
+
? schema.prefixItems
|
|
1369
|
+
: Array.isArray(schema.items)
|
|
1370
|
+
? schema.items
|
|
1371
|
+
: undefined;
|
|
1372
|
+
if (tupleItems && tupleItems.length > 0) {
|
|
1373
|
+
const elems = tupleItems.map((item) => schemaToZod(item, rootSchema, strict, depth + 1, seen, seenRefs, indent));
|
|
1374
|
+
expr = `z.tuple([${elems.join(", ")}])`;
|
|
1375
|
+
}
|
|
1376
|
+
else {
|
|
1377
|
+
const elemExpr = isRecord(schema.items)
|
|
1378
|
+
? schemaToZod(schema.items, rootSchema, strict, depth + 1, seen, seenRefs, indent)
|
|
1379
|
+
: "z.unknown()";
|
|
1380
|
+
expr = `z.array(${elemExpr})`;
|
|
1381
|
+
if (typeof schema.minItems === "number")
|
|
1382
|
+
expr += `.min(${schema.minItems})`;
|
|
1383
|
+
if (typeof schema.maxItems === "number")
|
|
1384
|
+
expr += `.max(${schema.maxItems})`;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
else if (effType === "object") {
|
|
1388
|
+
const props = isRecord(schema.properties) ? schema.properties : undefined;
|
|
1389
|
+
const propKeys = props
|
|
1390
|
+
? Object.keys(props).filter((k) => !isForbiddenKey(k) && !isSecretFieldName(k))
|
|
1391
|
+
: [];
|
|
1392
|
+
if (propKeys.length === 0) {
|
|
1393
|
+
if (strict || schema.additionalProperties === false) {
|
|
1394
|
+
expr = "z.object({}).strict()";
|
|
1395
|
+
}
|
|
1396
|
+
else if (isRecord(schema.additionalProperties)) {
|
|
1397
|
+
const valExpr = schemaToZod(schema.additionalProperties, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1398
|
+
expr = `z.record(z.string(), ${valExpr})`;
|
|
1399
|
+
}
|
|
1400
|
+
else {
|
|
1401
|
+
expr = "z.record(z.string(), z.unknown())";
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
else {
|
|
1405
|
+
const reqSet = new Set(Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === "string") : []);
|
|
1406
|
+
const pad = " ".repeat(indent + 2);
|
|
1407
|
+
const closePad = " ".repeat(indent);
|
|
1408
|
+
const lines = ["z.object({"];
|
|
1409
|
+
for (const key of propKeys) {
|
|
1410
|
+
const propExpr = schemaToZod(props[key], rootSchema, strict, depth + 1, seen, seenRefs, indent + 2);
|
|
1411
|
+
const withOpt = reqSet.has(key) ? propExpr : `${propExpr}.optional()`;
|
|
1412
|
+
lines.push(`${pad}${formatTsPropKey(key)}: ${withOpt},`);
|
|
1413
|
+
}
|
|
1414
|
+
lines.push(`${closePad}})`);
|
|
1415
|
+
expr = lines.join("\n");
|
|
1416
|
+
if (strict || schema.additionalProperties === false) {
|
|
1417
|
+
expr += ".strict()";
|
|
1418
|
+
}
|
|
1419
|
+
else if (isRecord(schema.additionalProperties)) {
|
|
1420
|
+
const catchallExpr = schemaToZod(schema.additionalProperties, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1421
|
+
expr += `.catchall(${catchallExpr})`;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
else {
|
|
1426
|
+
expr = "z.unknown()";
|
|
1427
|
+
}
|
|
1428
|
+
if (schema.nullable && expr !== "z.null()" && expr !== "z.unknown()") {
|
|
1429
|
+
return `${expr}.nullable()`;
|
|
1430
|
+
}
|
|
1431
|
+
return expr;
|
|
1432
|
+
}
|
|
1433
|
+
finally {
|
|
1434
|
+
seen.delete(schema);
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
function emitZodBundle(entries, title, strict, skippedInvariants, includeSkippedComments) {
|
|
1438
|
+
const lines = [
|
|
1439
|
+
"// Generated by vibecode-anything -- Zod Schema Bundle",
|
|
1440
|
+
`// Title: ${sanitizeSingleLineText(title, 160)}`,
|
|
1441
|
+
`// Strict mode: ${strict ? "true" : "false"}`,
|
|
1442
|
+
"",
|
|
1443
|
+
"import { z } from \"zod\";",
|
|
1444
|
+
""
|
|
1445
|
+
];
|
|
1446
|
+
if (entries.length === 0) {
|
|
1447
|
+
lines.push("// No exportable HTTP or CLI JSON schemas were found in this contract.");
|
|
1448
|
+
lines.push("export {};");
|
|
1449
|
+
}
|
|
1450
|
+
else {
|
|
1451
|
+
for (const entry of entries) {
|
|
1452
|
+
const zodExpr = schemaToZod(entry.schema, entry.rootSchema, strict, 0, new Set(), new Set(), 0);
|
|
1453
|
+
lines.push(`// [${entry.kind}] ${sanitizeSingleLineText(entry.invariantId, 80)} -- ${sanitizeSingleLineText(entry.description, 160)}`);
|
|
1454
|
+
lines.push(`export const ${entry.name}Schema = ${zodExpr};`);
|
|
1455
|
+
lines.push(`export type ${entry.name} = z.infer<typeof ${entry.name}Schema>;`);
|
|
1456
|
+
lines.push("");
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
if (includeSkippedComments && skippedInvariants.length > 0) {
|
|
1460
|
+
lines.push("// Skipped visible invariants:");
|
|
1461
|
+
for (const item of skippedInvariants) {
|
|
1462
|
+
lines.push(`// - ${sanitizeSingleLineText(item.id, 80)}: ${sanitizeSingleLineText(item.reason, 160)}`);
|
|
1463
|
+
}
|
|
1464
|
+
lines.push("");
|
|
1465
|
+
}
|
|
1466
|
+
return `${lines.join("\n").replace(/\n+$/, "")}\n`;
|
|
1467
|
+
}
|
|
1468
|
+
// ============================================================================
|
|
1469
|
+
// 3. Zero-Dependency TypeScript Types + Runtime Type Guards Emitter
|
|
1470
|
+
// ============================================================================
|
|
1471
|
+
function literalValueToTsType(value, depth = 0) {
|
|
1472
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1473
|
+
return "unknown";
|
|
1474
|
+
const prim = renderTsLiteral(value);
|
|
1475
|
+
if (prim !== null)
|
|
1476
|
+
return prim;
|
|
1477
|
+
if (Array.isArray(value)) {
|
|
1478
|
+
return `[${value.slice(0, MAX_TUPLE_ITEMS).map((v) => literalValueToTsType(v, depth + 1)).join(", ")}]`;
|
|
1479
|
+
}
|
|
1480
|
+
if (isRecord(value)) {
|
|
1481
|
+
const keys = Object.keys(value).filter((k) => !isForbiddenKey(k) && !isSecretFieldName(k));
|
|
1482
|
+
if (keys.length === 0)
|
|
1483
|
+
return "Record<string, never>";
|
|
1484
|
+
const fields = keys.map((k) => `${formatTsPropKey(k)}: ${literalValueToTsType(value[k], depth + 1)}`);
|
|
1485
|
+
return `{ ${fields.join("; ")} }`;
|
|
1486
|
+
}
|
|
1487
|
+
return "unknown";
|
|
1488
|
+
}
|
|
1489
|
+
function schemaToTsType(schema, rootSchema, strict, depth = 0, seen = new Set(), seenRefs = new Set(), indent = 0) {
|
|
1490
|
+
if (!schema || !isRecord(schema))
|
|
1491
|
+
return "unknown";
|
|
1492
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1493
|
+
return "unknown";
|
|
1494
|
+
if (seen.has(schema))
|
|
1495
|
+
return "unknown";
|
|
1496
|
+
seen.add(schema);
|
|
1497
|
+
try {
|
|
1498
|
+
if (typeof schema.$ref === "string") {
|
|
1499
|
+
if (seenRefs.has(schema.$ref))
|
|
1500
|
+
return "unknown";
|
|
1501
|
+
const resolved = resolveLocalRef(rootSchema, schema.$ref);
|
|
1502
|
+
if (!resolved)
|
|
1503
|
+
return "unknown";
|
|
1504
|
+
seenRefs.add(schema.$ref);
|
|
1505
|
+
try {
|
|
1506
|
+
return schemaToTsType(resolved, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1507
|
+
}
|
|
1508
|
+
finally {
|
|
1509
|
+
seenRefs.delete(schema.$ref);
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
if (schema.const !== undefined) {
|
|
1513
|
+
const lit = literalValueToTsType(schema.const, depth + 1);
|
|
1514
|
+
return schema.nullable && schema.const !== null ? `(${lit}) | null` : lit;
|
|
1515
|
+
}
|
|
1516
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
1517
|
+
const parts = [...new Set(schema.enum.map((item) => literalValueToTsType(item, depth + 1)))];
|
|
1518
|
+
const joined = parts.join(" | ");
|
|
1519
|
+
return schema.nullable && !parts.includes("null") ? `${joined} | null` : joined;
|
|
1520
|
+
}
|
|
1521
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
1522
|
+
const parts = [
|
|
1523
|
+
...new Set(schema.oneOf.map((b) => {
|
|
1524
|
+
const t = schemaToTsType(b, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1525
|
+
return t.includes(" & ") ? `(${t})` : t;
|
|
1526
|
+
}))
|
|
1527
|
+
];
|
|
1528
|
+
const joined = parts.join(" | ");
|
|
1529
|
+
return schema.nullable && !parts.includes("null") ? `(${joined}) | null` : joined;
|
|
1530
|
+
}
|
|
1531
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
1532
|
+
const parts = [
|
|
1533
|
+
...new Set(schema.anyOf.map((b) => {
|
|
1534
|
+
const t = schemaToTsType(b, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1535
|
+
return t.includes(" & ") ? `(${t})` : t;
|
|
1536
|
+
}))
|
|
1537
|
+
];
|
|
1538
|
+
const joined = parts.join(" | ");
|
|
1539
|
+
return schema.nullable && !parts.includes("null") ? `(${joined}) | null` : joined;
|
|
1540
|
+
}
|
|
1541
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1542
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema, depth, seenRefs);
|
|
1543
|
+
if (allObjects) {
|
|
1544
|
+
const mergedType = schemaToTsType(merged, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1545
|
+
return schema.nullable ? `(${mergedType}) | null` : mergedType;
|
|
1546
|
+
}
|
|
1547
|
+
const parts = [
|
|
1548
|
+
...new Set(schema.allOf.map((b) => {
|
|
1549
|
+
const t = schemaToTsType(b, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1550
|
+
return t.includes(" | ") ? `(${t})` : t;
|
|
1551
|
+
}))
|
|
1552
|
+
];
|
|
1553
|
+
const joined = parts.join(" & ");
|
|
1554
|
+
return schema.nullable ? `(${joined}) | null` : joined;
|
|
1555
|
+
}
|
|
1556
|
+
if (Array.isArray(schema.type) && schema.type.length > 0) {
|
|
1557
|
+
const parts = [
|
|
1558
|
+
...new Set(schema.type.map((singleType) => schemaToTsType({ ...schema, type: singleType, nullable: false }, rootSchema, strict, depth + 1, seen, seenRefs, indent)))
|
|
1559
|
+
];
|
|
1560
|
+
const joined = parts.join(" | ");
|
|
1561
|
+
return schema.nullable && !parts.includes("null") ? `${joined} | null` : joined;
|
|
1562
|
+
}
|
|
1563
|
+
const effType = effectiveSchemaType(schema);
|
|
1564
|
+
let result;
|
|
1565
|
+
if (effType === "string") {
|
|
1566
|
+
result = "string";
|
|
1567
|
+
}
|
|
1568
|
+
else if (effType === "number" || effType === "integer") {
|
|
1569
|
+
result = "number";
|
|
1570
|
+
}
|
|
1571
|
+
else if (effType === "boolean") {
|
|
1572
|
+
result = "boolean";
|
|
1573
|
+
}
|
|
1574
|
+
else if (effType === "null") {
|
|
1575
|
+
return "null";
|
|
1576
|
+
}
|
|
1577
|
+
else if (effType === "array") {
|
|
1578
|
+
const tupleItems = Array.isArray(schema.prefixItems)
|
|
1579
|
+
? schema.prefixItems
|
|
1580
|
+
: Array.isArray(schema.items)
|
|
1581
|
+
? schema.items
|
|
1582
|
+
: undefined;
|
|
1583
|
+
if (tupleItems && tupleItems.length > 0) {
|
|
1584
|
+
const elems = tupleItems.map((item) => schemaToTsType(item, rootSchema, strict, depth + 1, seen, seenRefs, indent));
|
|
1585
|
+
result = `[${elems.join(", ")}]`;
|
|
1586
|
+
}
|
|
1587
|
+
else if (isRecord(schema.items)) {
|
|
1588
|
+
const elemType = schemaToTsType(schema.items, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1589
|
+
result =
|
|
1590
|
+
elemType.includes(" | ") || elemType.includes(" & ") || elemType.includes("\n")
|
|
1591
|
+
? `Array<${elemType}>`
|
|
1592
|
+
: `${elemType}[]`;
|
|
1593
|
+
}
|
|
1594
|
+
else {
|
|
1595
|
+
result = "unknown[]";
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
else if (effType === "object") {
|
|
1599
|
+
const props = isRecord(schema.properties) ? schema.properties : undefined;
|
|
1600
|
+
const propKeys = props
|
|
1601
|
+
? Object.keys(props).filter((k) => !isForbiddenKey(k) && !isSecretFieldName(k))
|
|
1602
|
+
: [];
|
|
1603
|
+
if (propKeys.length === 0) {
|
|
1604
|
+
if (strict || schema.additionalProperties === false) {
|
|
1605
|
+
result = "Record<string, never>";
|
|
1606
|
+
}
|
|
1607
|
+
else if (isRecord(schema.additionalProperties)) {
|
|
1608
|
+
const valType = schemaToTsType(schema.additionalProperties, rootSchema, strict, depth + 1, seen, seenRefs, indent);
|
|
1609
|
+
result = `Record<string, ${valType}>`;
|
|
1610
|
+
}
|
|
1611
|
+
else {
|
|
1612
|
+
result = "Record<string, unknown>";
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
else {
|
|
1616
|
+
const reqSet = new Set(Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === "string") : []);
|
|
1617
|
+
const pad = " ".repeat(indent + 2);
|
|
1618
|
+
const closePad = " ".repeat(indent);
|
|
1619
|
+
const lines = ["{"];
|
|
1620
|
+
for (const key of propKeys) {
|
|
1621
|
+
const opt = reqSet.has(key) ? "" : "?";
|
|
1622
|
+
const fieldType = schemaToTsType(props[key], rootSchema, strict, depth + 1, seen, seenRefs, indent + 2);
|
|
1623
|
+
lines.push(`${pad}${formatTsPropKey(key)}${opt}: ${fieldType};`);
|
|
1624
|
+
}
|
|
1625
|
+
lines.push(`${closePad}}`);
|
|
1626
|
+
result = lines.join("\n");
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
else {
|
|
1630
|
+
result = "unknown";
|
|
1631
|
+
}
|
|
1632
|
+
if (schema.nullable && result !== "null" && result !== "unknown") {
|
|
1633
|
+
return result.includes("\n") || result.includes(" & ") ? `(${result}) | null` : `${result} | null`;
|
|
1634
|
+
}
|
|
1635
|
+
return result;
|
|
1636
|
+
}
|
|
1637
|
+
finally {
|
|
1638
|
+
seen.delete(schema);
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
function emitTsInterfaceLines(name, schema, rootSchema, strict) {
|
|
1642
|
+
let target = schema;
|
|
1643
|
+
if (typeof schema.$ref === "string") {
|
|
1644
|
+
const resolved = resolveLocalRef(rootSchema, schema.$ref);
|
|
1645
|
+
if (resolved)
|
|
1646
|
+
target = resolved;
|
|
1647
|
+
}
|
|
1648
|
+
if (Array.isArray(target.allOf) && target.allOf.length > 0) {
|
|
1649
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(target.allOf, rootSchema);
|
|
1650
|
+
if (allObjects)
|
|
1651
|
+
target = merged;
|
|
1652
|
+
}
|
|
1653
|
+
const canBeInterface = !schema.nullable &&
|
|
1654
|
+
!target.nullable &&
|
|
1655
|
+
!Array.isArray(target.oneOf) &&
|
|
1656
|
+
!Array.isArray(target.anyOf) &&
|
|
1657
|
+
!Array.isArray(target.enum) &&
|
|
1658
|
+
target.const === undefined &&
|
|
1659
|
+
effectiveSchemaType(target) === "object" &&
|
|
1660
|
+
isRecord(target.properties);
|
|
1661
|
+
if (canBeInterface) {
|
|
1662
|
+
const propKeys = Object.keys(target.properties).filter((k) => !isForbiddenKey(k) && !isSecretFieldName(k));
|
|
1663
|
+
if (propKeys.length > 0) {
|
|
1664
|
+
const reqSet = new Set(Array.isArray(target.required) ? target.required.filter((r) => typeof r === "string") : []);
|
|
1665
|
+
const lines = [`export interface ${name} {`];
|
|
1666
|
+
for (const key of propKeys) {
|
|
1667
|
+
const opt = reqSet.has(key) ? "" : "?";
|
|
1668
|
+
const fieldType = schemaToTsType(target.properties[key], rootSchema, strict, 1, new Set(), new Set(), 2);
|
|
1669
|
+
lines.push(` ${formatTsPropKey(key)}${opt}: ${fieldType};`);
|
|
1670
|
+
}
|
|
1671
|
+
lines.push("}");
|
|
1672
|
+
return lines;
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
const typeExpr = schemaToTsType(schema, rootSchema, strict, 0, new Set(), new Set(), 0);
|
|
1676
|
+
return [`export type ${name} = ${typeExpr};`];
|
|
1677
|
+
}
|
|
1678
|
+
function schemaToGuardExpr(varExpr, schema, rootSchema, strict, usage, depth = 0, seen = new Set(), seenRefs = new Set()) {
|
|
1679
|
+
if (!schema || !isRecord(schema))
|
|
1680
|
+
return "true";
|
|
1681
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1682
|
+
return "true";
|
|
1683
|
+
if (seen.has(schema))
|
|
1684
|
+
return "true";
|
|
1685
|
+
seen.add(schema);
|
|
1686
|
+
try {
|
|
1687
|
+
if (typeof schema.$ref === "string") {
|
|
1688
|
+
if (seenRefs.has(schema.$ref))
|
|
1689
|
+
return "true";
|
|
1690
|
+
const resolved = resolveLocalRef(rootSchema, schema.$ref);
|
|
1691
|
+
if (!resolved)
|
|
1692
|
+
return "true";
|
|
1693
|
+
seenRefs.add(schema.$ref);
|
|
1694
|
+
try {
|
|
1695
|
+
return schemaToGuardExpr(varExpr, resolved, rootSchema, strict, usage, depth + 1, seen, seenRefs);
|
|
1696
|
+
}
|
|
1697
|
+
finally {
|
|
1698
|
+
seenRefs.delete(schema.$ref);
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
const wrapNullable = (innerExpr) => schema.nullable === true ? `(${varExpr} === null || (${innerExpr}))` : innerExpr;
|
|
1702
|
+
if (schema.const !== undefined) {
|
|
1703
|
+
const prim = renderTsLiteral(schema.const);
|
|
1704
|
+
if (prim !== null) {
|
|
1705
|
+
return wrapNullable(`${varExpr} === ${prim}`);
|
|
1706
|
+
}
|
|
1707
|
+
usage.deepEqual = true;
|
|
1708
|
+
const serialized = tsString(JSON.stringify(toPlainJsonObject(schema.const)));
|
|
1709
|
+
return wrapNullable(`__deepEqual(${varExpr}, JSON.parse(${serialized}))`);
|
|
1710
|
+
}
|
|
1711
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
1712
|
+
const checks = schema.enum.map((item) => {
|
|
1713
|
+
const prim = renderTsLiteral(item);
|
|
1714
|
+
if (prim !== null)
|
|
1715
|
+
return `${varExpr} === ${prim}`;
|
|
1716
|
+
usage.deepEqual = true;
|
|
1717
|
+
const serialized = tsString(JSON.stringify(toPlainJsonObject(item)));
|
|
1718
|
+
return `__deepEqual(${varExpr}, JSON.parse(${serialized}))`;
|
|
1719
|
+
});
|
|
1720
|
+
return wrapNullable(`(${checks.join(" || ")})`);
|
|
1721
|
+
}
|
|
1722
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
1723
|
+
const v = `v${depth}`;
|
|
1724
|
+
const branches = schema.oneOf.map((b) => `(${schemaToGuardExpr(v, b, rootSchema, strict, usage, depth + 1, seen, seenRefs)} ? 1 : 0)`);
|
|
1725
|
+
return wrapNullable(`((${v}: unknown): boolean => (${branches.join(" + ")}) === 1)(${varExpr})`);
|
|
1726
|
+
}
|
|
1727
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
1728
|
+
const v = `v${depth}`;
|
|
1729
|
+
const branches = schema.anyOf.map((b) => `(${schemaToGuardExpr(v, b, rootSchema, strict, usage, depth + 1, seen, seenRefs)})`);
|
|
1730
|
+
return wrapNullable(`((${v}: unknown): boolean => ${branches.join(" || ")})(${varExpr})`);
|
|
1731
|
+
}
|
|
1732
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1733
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema, depth, seenRefs);
|
|
1734
|
+
if (allObjects) {
|
|
1735
|
+
return wrapNullable(schemaToGuardExpr(varExpr, merged, rootSchema, strict, usage, depth + 1, seen, seenRefs));
|
|
1736
|
+
}
|
|
1737
|
+
const v = `v${depth}`;
|
|
1738
|
+
const branches = schema.allOf.map((b) => `(${schemaToGuardExpr(v, b, rootSchema, strict, usage, depth + 1, seen, seenRefs)})`);
|
|
1739
|
+
return wrapNullable(`((${v}: unknown): boolean => ${branches.join(" && ")})(${varExpr})`);
|
|
1740
|
+
}
|
|
1741
|
+
if (Array.isArray(schema.type) && schema.type.length > 0) {
|
|
1742
|
+
const v = `v${depth}`;
|
|
1743
|
+
const checks = schema.type.map((singleType) => `(${schemaToGuardExpr(v, { ...schema, type: singleType, nullable: false }, rootSchema, strict, usage, depth + 1, seen, seenRefs)})`);
|
|
1744
|
+
return wrapNullable(`((${v}: unknown): boolean => ${checks.join(" || ")})(${varExpr})`);
|
|
1745
|
+
}
|
|
1746
|
+
const effType = effectiveSchemaType(schema);
|
|
1747
|
+
const notClause = isRecord(schema.not)
|
|
1748
|
+
? schemaToGuardExpr(varExpr, schema.not, rootSchema, strict, usage, depth + 1, seen, seenRefs)
|
|
1749
|
+
: undefined;
|
|
1750
|
+
let expr;
|
|
1751
|
+
if (effType === "null") {
|
|
1752
|
+
expr = `${varExpr} === null`;
|
|
1753
|
+
}
|
|
1754
|
+
else if (effType === "boolean") {
|
|
1755
|
+
expr = `typeof ${varExpr} === "boolean"`;
|
|
1756
|
+
}
|
|
1757
|
+
else if (effType === "string") {
|
|
1758
|
+
const checks = [];
|
|
1759
|
+
const sv = `s${depth}`;
|
|
1760
|
+
if (typeof schema.minLength === "number")
|
|
1761
|
+
checks.push(`${sv}.length >= ${schema.minLength}`);
|
|
1762
|
+
if (typeof schema.maxLength === "number")
|
|
1763
|
+
checks.push(`${sv}.length <= ${schema.maxLength}`);
|
|
1764
|
+
if (typeof schema.pattern === "string") {
|
|
1765
|
+
checks.push(`new RegExp(${tsString(schema.pattern)}).test(${sv})`);
|
|
1766
|
+
}
|
|
1767
|
+
if (typeof schema.format === "string" && ["email", "uuid", "date", "date-time", "uri", "ipv4"].includes(schema.format)) {
|
|
1768
|
+
usage.formatCheck = true;
|
|
1769
|
+
checks.push(`__checkFormat(${sv}, ${tsString(schema.format)})`);
|
|
1770
|
+
}
|
|
1771
|
+
expr =
|
|
1772
|
+
checks.length === 0
|
|
1773
|
+
? `typeof ${varExpr} === "string"`
|
|
1774
|
+
: `((${sv}: unknown): boolean => typeof ${sv} === "string" && ${checks.join(" && ")})(${varExpr})`;
|
|
1775
|
+
}
|
|
1776
|
+
else if (effType === "integer" || effType === "number") {
|
|
1777
|
+
const nv = `n${depth}`;
|
|
1778
|
+
const checks = [
|
|
1779
|
+
effType === "integer" ? `Number.isInteger(${nv})` : `Number.isFinite(${nv})`
|
|
1780
|
+
];
|
|
1781
|
+
if (typeof schema.minimum === "number")
|
|
1782
|
+
checks.push(`${nv} >= ${schema.minimum}`);
|
|
1783
|
+
if (typeof schema.maximum === "number")
|
|
1784
|
+
checks.push(`${nv} <= ${schema.maximum}`);
|
|
1785
|
+
if (typeof schema.exclusiveMinimum === "number")
|
|
1786
|
+
checks.push(`${nv} > ${schema.exclusiveMinimum}`);
|
|
1787
|
+
if (typeof schema.exclusiveMaximum === "number")
|
|
1788
|
+
checks.push(`${nv} < ${schema.exclusiveMaximum}`);
|
|
1789
|
+
if (typeof schema.multipleOf === "number" && schema.multipleOf > 0) {
|
|
1790
|
+
checks.push(`Math.abs(${nv} / ${schema.multipleOf} - Math.round(${nv} / ${schema.multipleOf})) <= 1e-9`);
|
|
1791
|
+
}
|
|
1792
|
+
expr = `((${nv}: unknown): boolean => typeof ${nv} === "number" && ${checks.join(" && ")})(${varExpr})`;
|
|
1793
|
+
}
|
|
1794
|
+
else if (effType === "array") {
|
|
1795
|
+
const v = `a${depth}`;
|
|
1796
|
+
const stmts = [`if (!Array.isArray(${v})) return false;`];
|
|
1797
|
+
if (typeof schema.minItems === "number")
|
|
1798
|
+
stmts.push(`if (${v}.length < ${schema.minItems}) return false;`);
|
|
1799
|
+
if (typeof schema.maxItems === "number")
|
|
1800
|
+
stmts.push(`if (${v}.length > ${schema.maxItems}) return false;`);
|
|
1801
|
+
if (schema.uniqueItems === true) {
|
|
1802
|
+
usage.uniqueItems = true;
|
|
1803
|
+
stmts.push(`if (!__hasUniqueItems(${v})) return false;`);
|
|
1804
|
+
}
|
|
1805
|
+
const tupleItems = Array.isArray(schema.prefixItems)
|
|
1806
|
+
? schema.prefixItems
|
|
1807
|
+
: Array.isArray(schema.items)
|
|
1808
|
+
? schema.items
|
|
1809
|
+
: undefined;
|
|
1810
|
+
if (tupleItems && tupleItems.length > 0) {
|
|
1811
|
+
stmts.push(`if (${v}.length !== ${tupleItems.length}) return false;`);
|
|
1812
|
+
for (let i = 0; i < tupleItems.length; i++) {
|
|
1813
|
+
const elemCheck = schemaToGuardExpr(`${v}[${i}]`, tupleItems[i], rootSchema, strict, usage, depth + 1, seen, seenRefs);
|
|
1814
|
+
if (elemCheck !== "true") {
|
|
1815
|
+
stmts.push(`if (!(${elemCheck})) return false;`);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
else if (isRecord(schema.items)) {
|
|
1820
|
+
const itemVar = `i${depth}`;
|
|
1821
|
+
const elemCheck = schemaToGuardExpr(itemVar, schema.items, rootSchema, strict, usage, depth + 1, seen, seenRefs);
|
|
1822
|
+
if (elemCheck !== "true") {
|
|
1823
|
+
stmts.push(`for (const ${itemVar} of ${v}) { if (!(${elemCheck})) return false; }`);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
stmts.push("return true;");
|
|
1827
|
+
expr = `((${v}: unknown): boolean => { ${stmts.join(" ")} })(${varExpr})`;
|
|
1828
|
+
}
|
|
1829
|
+
else if (effType === "object") {
|
|
1830
|
+
usage.isSafeRecord = true;
|
|
1831
|
+
const v = `o${depth}`;
|
|
1832
|
+
const stmts = [`if (!__isSafeRecord(${v})) return false;`];
|
|
1833
|
+
if (typeof schema.minProperties === "number") {
|
|
1834
|
+
stmts.push(`if (Object.keys(${v}).length < ${schema.minProperties}) return false;`);
|
|
1835
|
+
}
|
|
1836
|
+
if (typeof schema.maxProperties === "number") {
|
|
1837
|
+
stmts.push(`if (Object.keys(${v}).length > ${schema.maxProperties}) return false;`);
|
|
1838
|
+
}
|
|
1839
|
+
const props = isRecord(schema.properties) ? schema.properties : undefined;
|
|
1840
|
+
const propKeys = props
|
|
1841
|
+
? Object.keys(props).filter((k) => !isForbiddenKey(k) && !isSecretFieldName(k))
|
|
1842
|
+
: [];
|
|
1843
|
+
const reqSet = new Set(Array.isArray(schema.required)
|
|
1844
|
+
? schema.required.filter((r) => typeof r === "string" && !isForbiddenKey(r) && !isSecretFieldName(r))
|
|
1845
|
+
: []);
|
|
1846
|
+
if (strict || schema.additionalProperties === false) {
|
|
1847
|
+
if (propKeys.length === 0) {
|
|
1848
|
+
stmts.push(`if (Object.keys(${v}).length > 0) return false;`);
|
|
1849
|
+
}
|
|
1850
|
+
else {
|
|
1851
|
+
usage.hasOnlyAllowedKeys = true;
|
|
1852
|
+
const allowedLiteral = `[${propKeys.map(tsString).join(", ")}]`;
|
|
1853
|
+
stmts.push(`if (!__hasOnlyAllowedKeys(${v}, new Set<string>(${allowedLiteral}))) return false;`);
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
else if (isRecord(schema.additionalProperties)) {
|
|
1857
|
+
const kVar = `k${depth}`;
|
|
1858
|
+
const addCheck = schemaToGuardExpr(`${v}[${kVar}]`, schema.additionalProperties, rootSchema, strict, usage, depth + 1, seen, seenRefs);
|
|
1859
|
+
if (addCheck !== "true") {
|
|
1860
|
+
const skipDecl = propKeys.length > 0
|
|
1861
|
+
? `const __decl${depth} = new Set<string>([${propKeys.map(tsString).join(", ")}]); `
|
|
1862
|
+
: "";
|
|
1863
|
+
const skipCond = propKeys.length > 0 ? `if (__decl${depth}.has(${kVar})) continue; ` : "";
|
|
1864
|
+
stmts.push(`${skipDecl}for (const ${kVar} of Object.keys(${v})) { ${skipCond}if (!(${addCheck})) return false; }`);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
for (const key of propKeys) {
|
|
1868
|
+
usage.hasOwn = true;
|
|
1869
|
+
const keyLit = tsString(key);
|
|
1870
|
+
const propCheck = schemaToGuardExpr(`${v}[${keyLit}]`, props[key], rootSchema, strict, usage, depth + 1, seen, seenRefs);
|
|
1871
|
+
if (reqSet.has(key)) {
|
|
1872
|
+
stmts.push(`if (!__hasOwn(${v}, ${keyLit})) return false;`);
|
|
1873
|
+
if (propCheck !== "true") {
|
|
1874
|
+
stmts.push(`if (!(${propCheck})) return false;`);
|
|
1875
|
+
}
|
|
1876
|
+
}
|
|
1877
|
+
else if (propCheck !== "true") {
|
|
1878
|
+
stmts.push(`if (__hasOwn(${v}, ${keyLit}) && ${v}[${keyLit}] !== undefined && !(${propCheck})) return false;`);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
// Check any required keys not listed in properties
|
|
1882
|
+
for (const reqKey of reqSet) {
|
|
1883
|
+
if (!propKeys.includes(reqKey)) {
|
|
1884
|
+
usage.hasOwn = true;
|
|
1885
|
+
stmts.push(`if (!__hasOwn(${v}, ${tsString(reqKey)})) return false;`);
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
stmts.push("return true;");
|
|
1889
|
+
expr = `((${v}: unknown): boolean => { ${stmts.join(" ")} })(${varExpr})`;
|
|
1890
|
+
}
|
|
1891
|
+
else {
|
|
1892
|
+
expr = "true";
|
|
1893
|
+
}
|
|
1894
|
+
if (notClause && notClause !== "true") {
|
|
1895
|
+
expr = `((${expr}) && !(${notClause}))`;
|
|
1896
|
+
}
|
|
1897
|
+
return wrapNullable(expr);
|
|
1898
|
+
}
|
|
1899
|
+
finally {
|
|
1900
|
+
seen.delete(schema);
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
function buildRuntimeHelpers(usage) {
|
|
1904
|
+
const lines = [];
|
|
1905
|
+
if (usage.isSafeRecord || usage.deepEqual || usage.uniqueItems) {
|
|
1906
|
+
lines.push("const __FORBIDDEN_KEYS = new Set<string>([\"__proto__\", \"constructor\", \"prototype\"]);");
|
|
1907
|
+
lines.push("");
|
|
1908
|
+
}
|
|
1909
|
+
if (usage.hasOwn) {
|
|
1910
|
+
lines.push("function __hasOwn(obj: Record<string, unknown>, key: string): boolean {");
|
|
1911
|
+
lines.push(" return Object.prototype.hasOwnProperty.call(obj, key);");
|
|
1912
|
+
lines.push("}");
|
|
1913
|
+
lines.push("");
|
|
1914
|
+
}
|
|
1915
|
+
if (usage.isSafeRecord) {
|
|
1916
|
+
lines.push("function __isSafeRecord(value: unknown): value is Record<string, unknown> {");
|
|
1917
|
+
lines.push(" if (value === null || typeof value !== \"object\" || Array.isArray(value)) {");
|
|
1918
|
+
lines.push(" return false;");
|
|
1919
|
+
lines.push(" }");
|
|
1920
|
+
lines.push(" for (const key of Object.getOwnPropertyNames(value)) {");
|
|
1921
|
+
lines.push(" if (__FORBIDDEN_KEYS.has(key)) {");
|
|
1922
|
+
lines.push(" return false;");
|
|
1923
|
+
lines.push(" }");
|
|
1924
|
+
lines.push(" }");
|
|
1925
|
+
lines.push(" return true;");
|
|
1926
|
+
lines.push("}");
|
|
1927
|
+
lines.push("");
|
|
1928
|
+
}
|
|
1929
|
+
if (usage.hasOnlyAllowedKeys) {
|
|
1930
|
+
lines.push("function __hasOnlyAllowedKeys(obj: Record<string, unknown>, allowed: ReadonlySet<string>): boolean {");
|
|
1931
|
+
lines.push(" for (const key of Object.keys(obj)) {");
|
|
1932
|
+
lines.push(" if (!allowed.has(key)) {");
|
|
1933
|
+
lines.push(" return false;");
|
|
1934
|
+
lines.push(" }");
|
|
1935
|
+
lines.push(" }");
|
|
1936
|
+
lines.push(" return true;");
|
|
1937
|
+
lines.push("}");
|
|
1938
|
+
lines.push("");
|
|
1939
|
+
}
|
|
1940
|
+
if (usage.deepEqual || usage.uniqueItems) {
|
|
1941
|
+
lines.push("function __canonicalJson(value: unknown, depth = 0): string {");
|
|
1942
|
+
lines.push(" if (depth > 12) return \"null\";");
|
|
1943
|
+
lines.push(" if (value === null) return \"null\";");
|
|
1944
|
+
lines.push(" if (typeof value === \"boolean\" || typeof value === \"string\") return JSON.stringify(value);");
|
|
1945
|
+
lines.push(" if (typeof value === \"number\") return Number.isFinite(value) ? JSON.stringify(value) : \"null\";");
|
|
1946
|
+
lines.push(" if (Array.isArray(value)) return `[${value.map((v) => __canonicalJson(v, depth + 1)).join(\",\")}]`;");
|
|
1947
|
+
lines.push(" if (typeof value === \"object\") {");
|
|
1948
|
+
lines.push(" const rec = value as Record<string, unknown>;");
|
|
1949
|
+
lines.push(" for (const ownKey of Object.getOwnPropertyNames(rec)) {");
|
|
1950
|
+
lines.push(" if (__FORBIDDEN_KEYS.has(ownKey)) return \"__FORBIDDEN_OBJECT__\";");
|
|
1951
|
+
lines.push(" }");
|
|
1952
|
+
lines.push(" const keys = Object.keys(rec).sort();");
|
|
1953
|
+
lines.push(" return `{${keys.map((k) => `${JSON.stringify(k)}:${__canonicalJson(rec[k], depth + 1)}`).join(\",\")}}`;");
|
|
1954
|
+
lines.push(" }");
|
|
1955
|
+
lines.push(" return \"undefined\";");
|
|
1956
|
+
lines.push("}");
|
|
1957
|
+
lines.push("");
|
|
1958
|
+
}
|
|
1959
|
+
if (usage.deepEqual) {
|
|
1960
|
+
lines.push("function __deepEqual(a: unknown, b: unknown): boolean {");
|
|
1961
|
+
lines.push(" return __canonicalJson(a) === __canonicalJson(b);");
|
|
1962
|
+
lines.push("}");
|
|
1963
|
+
lines.push("");
|
|
1964
|
+
}
|
|
1965
|
+
if (usage.uniqueItems) {
|
|
1966
|
+
lines.push("function __hasUniqueItems(items: readonly unknown[]): boolean {");
|
|
1967
|
+
lines.push(" const seen = new Set<string>();");
|
|
1968
|
+
lines.push(" for (const item of items) {");
|
|
1969
|
+
lines.push(" const key = __canonicalJson(item);");
|
|
1970
|
+
lines.push(" if (seen.has(key)) return false;");
|
|
1971
|
+
lines.push(" seen.add(key);");
|
|
1972
|
+
lines.push(" }");
|
|
1973
|
+
lines.push(" return true;");
|
|
1974
|
+
lines.push("}");
|
|
1975
|
+
lines.push("");
|
|
1976
|
+
}
|
|
1977
|
+
if (usage.formatCheck) {
|
|
1978
|
+
lines.push("const __UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;");
|
|
1979
|
+
lines.push("const __EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;");
|
|
1980
|
+
lines.push("const __DATE_RE = /^\\d{4}-\\d{2}-\\d{2}$/;");
|
|
1981
|
+
lines.push("const __DATETIME_RE = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/i;");
|
|
1982
|
+
lines.push("const __IPV4_RE = /^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/;");
|
|
1983
|
+
lines.push("");
|
|
1984
|
+
lines.push("function __checkFormat(value: string, format: string): boolean {");
|
|
1985
|
+
lines.push(" if (format === \"uuid\") return __UUID_RE.test(value);");
|
|
1986
|
+
lines.push(" if (format === \"email\") return __EMAIL_RE.test(value);");
|
|
1987
|
+
lines.push(" if (format === \"date\") return __DATE_RE.test(value) && !Number.isNaN(Date.parse(value));");
|
|
1988
|
+
lines.push(" if (format === \"date-time\") return __DATETIME_RE.test(value) && !Number.isNaN(Date.parse(value));");
|
|
1989
|
+
lines.push(" if (format === \"uri\") {");
|
|
1990
|
+
lines.push(" try { new URL(value); return true; } catch { return false; }");
|
|
1991
|
+
lines.push(" }");
|
|
1992
|
+
lines.push(" if (format === \"ipv4\") {");
|
|
1993
|
+
lines.push(" const m = __IPV4_RE.exec(value);");
|
|
1994
|
+
lines.push(" if (!m) return false;");
|
|
1995
|
+
lines.push(" for (let i = 1; i <= 4; i++) {");
|
|
1996
|
+
lines.push(" const part = m[i];");
|
|
1997
|
+
lines.push(" if (part.length > 1 && part.startsWith(\"0\")) return false;");
|
|
1998
|
+
lines.push(" const n = Number(part);");
|
|
1999
|
+
lines.push(" if (n < 0 || n > 255) return false;");
|
|
2000
|
+
lines.push(" }");
|
|
2001
|
+
lines.push(" return true;");
|
|
2002
|
+
lines.push(" }");
|
|
2003
|
+
lines.push(" return true;");
|
|
2004
|
+
lines.push("}");
|
|
2005
|
+
lines.push("");
|
|
2006
|
+
}
|
|
2007
|
+
return lines;
|
|
2008
|
+
}
|
|
2009
|
+
function emitTypeScriptBundle(entries, title, strict, skippedInvariants, includeSkippedComments) {
|
|
2010
|
+
const usage = {
|
|
2011
|
+
hasOwn: false,
|
|
2012
|
+
isSafeRecord: false,
|
|
2013
|
+
hasOnlyAllowedKeys: false,
|
|
2014
|
+
deepEqual: false,
|
|
2015
|
+
formatCheck: false,
|
|
2016
|
+
uniqueItems: false
|
|
2017
|
+
};
|
|
2018
|
+
const bodyLines = [];
|
|
2019
|
+
if (entries.length === 0) {
|
|
2020
|
+
bodyLines.push("// No exportable HTTP or CLI JSON schemas were found in this contract.");
|
|
2021
|
+
bodyLines.push("export {};");
|
|
2022
|
+
}
|
|
2023
|
+
else {
|
|
2024
|
+
for (const entry of entries) {
|
|
2025
|
+
bodyLines.push(`// [${entry.kind}] ${sanitizeSingleLineText(entry.invariantId, 80)} -- ${sanitizeSingleLineText(entry.description, 160)}`);
|
|
2026
|
+
bodyLines.push(...emitTsInterfaceLines(entry.name, entry.schema, entry.rootSchema, strict));
|
|
2027
|
+
bodyLines.push("");
|
|
2028
|
+
const guardExpr = schemaToGuardExpr("value", entry.schema, entry.rootSchema, strict, usage, 0, new Set(), new Set());
|
|
2029
|
+
bodyLines.push(`export function is${entry.name}(value: unknown): value is ${entry.name} {`);
|
|
2030
|
+
bodyLines.push(` return ${guardExpr};`);
|
|
2031
|
+
bodyLines.push("}");
|
|
2032
|
+
bodyLines.push("");
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
const headerLines = [
|
|
2036
|
+
"// Generated by vibecode-anything -- TypeScript Types & Runtime Type Guards",
|
|
2037
|
+
`// Title: ${sanitizeSingleLineText(title, 160)}`,
|
|
2038
|
+
`// Strict mode: ${strict ? "true" : "false"}`,
|
|
2039
|
+
"// Zero external dependencies -- compatible with Node 24 native TypeScript and strict tsc.",
|
|
2040
|
+
""
|
|
2041
|
+
];
|
|
2042
|
+
const helperLines = buildRuntimeHelpers(usage);
|
|
2043
|
+
const allLines = [...headerLines, ...helperLines, ...bodyLines];
|
|
2044
|
+
if (includeSkippedComments && skippedInvariants.length > 0) {
|
|
2045
|
+
allLines.push("// Skipped visible invariants:");
|
|
2046
|
+
for (const item of skippedInvariants) {
|
|
2047
|
+
allLines.push(`// - ${sanitizeSingleLineText(item.id, 80)}: ${sanitizeSingleLineText(item.reason, 160)}`);
|
|
2048
|
+
}
|
|
2049
|
+
allLines.push("");
|
|
2050
|
+
}
|
|
2051
|
+
return `${allLines.join("\n").replace(/\n+$/, "")}\n`;
|
|
2052
|
+
}
|
|
2053
|
+
// ============================================================================
|
|
2054
|
+
// Public API
|
|
2055
|
+
// ============================================================================
|
|
2056
|
+
function fileExtensionFor(format) {
|
|
2057
|
+
return format === "json-schema" ? ".json" : ".ts";
|
|
2058
|
+
}
|
|
2059
|
+
export function exportContractSchemas(contract, options = {}) {
|
|
2060
|
+
if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
|
|
2061
|
+
throw new VibecodeError("CONTRACT_INVALID", "exportContractSchemas requires a valid contract object with an invariants array.");
|
|
2062
|
+
}
|
|
2063
|
+
const formatRaw = options.format ?? "zod";
|
|
2064
|
+
if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
|
|
2065
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported schema export format "${String(formatRaw)}". Supported formats: zod, json-schema, typescript.`);
|
|
2066
|
+
}
|
|
2067
|
+
const format = formatRaw;
|
|
2068
|
+
const strict = options.strict === true;
|
|
2069
|
+
const includeSkippedComments = options.includeSkippedComments !== false;
|
|
2070
|
+
const rawTitle = (typeof options.title === "string" && options.title.trim()) ||
|
|
2071
|
+
(isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()) ||
|
|
2072
|
+
"vibecode-contract-schemas";
|
|
2073
|
+
const title = sanitizeSingleLineText(rawTitle, 160) || "vibecode-contract-schemas";
|
|
2074
|
+
const entries = [];
|
|
2075
|
+
const skippedInvariants = [];
|
|
2076
|
+
const warnings = [];
|
|
2077
|
+
const usedNames = new Set();
|
|
2078
|
+
for (const inv of contract.invariants) {
|
|
2079
|
+
if (!isRecord(inv))
|
|
2080
|
+
continue;
|
|
2081
|
+
// 100% Holdout Invisibility: never emit holdout IDs, schemas, comments, counts, or warnings.
|
|
2082
|
+
if (inv.holdout === true) {
|
|
2083
|
+
continue;
|
|
2084
|
+
}
|
|
2085
|
+
const invId = typeof inv.id === "string" && inv.id.trim()
|
|
2086
|
+
? sanitizeSingleLineText(inv.id.trim(), 80)
|
|
2087
|
+
: "unknown";
|
|
2088
|
+
if (inv.type === "http") {
|
|
2089
|
+
const extracted = extractHttpInvariantSchemas(inv, invId, usedNames, warnings);
|
|
2090
|
+
if (extracted.length === 0) {
|
|
2091
|
+
skippedInvariants.push({
|
|
2092
|
+
id: invId,
|
|
2093
|
+
reason: "HTTP invariant has no query, JSON request, or JSON response schema"
|
|
2094
|
+
});
|
|
2095
|
+
}
|
|
2096
|
+
else {
|
|
2097
|
+
entries.push(...extracted);
|
|
2098
|
+
}
|
|
2099
|
+
continue;
|
|
2100
|
+
}
|
|
2101
|
+
if (inv.type === "command") {
|
|
2102
|
+
const extracted = extractCliInvariantSchemas(inv, invId, usedNames, warnings);
|
|
2103
|
+
if (extracted.length === 0) {
|
|
2104
|
+
skippedInvariants.push({
|
|
2105
|
+
id: invId,
|
|
2106
|
+
reason: "CLI invariant has no JSON stdin or stdout schema"
|
|
2107
|
+
});
|
|
2108
|
+
}
|
|
2109
|
+
else {
|
|
2110
|
+
entries.push(...extracted);
|
|
2111
|
+
}
|
|
2112
|
+
continue;
|
|
2113
|
+
}
|
|
2114
|
+
const safeType = sanitizeSingleLineText(String(inv.type ?? "unknown"), 48) || "unknown";
|
|
2115
|
+
skippedInvariants.push({
|
|
2116
|
+
id: invId,
|
|
2117
|
+
reason: `Unsupported invariant type "${safeType}"`
|
|
2118
|
+
});
|
|
2119
|
+
}
|
|
2120
|
+
if (entries.length === 0) {
|
|
2121
|
+
warnings.push("No exportable HTTP or CLI JSON schemas were found in visible invariants.");
|
|
2122
|
+
}
|
|
2123
|
+
let content;
|
|
2124
|
+
if (format === "zod") {
|
|
2125
|
+
content = emitZodBundle(entries, title, strict, skippedInvariants, includeSkippedComments);
|
|
2126
|
+
}
|
|
2127
|
+
else if (format === "json-schema") {
|
|
2128
|
+
content = emitJsonSchemaBundle(entries, title, strict);
|
|
2129
|
+
}
|
|
2130
|
+
else {
|
|
2131
|
+
content = emitTypeScriptBundle(entries, title, strict, skippedInvariants, includeSkippedComments);
|
|
2132
|
+
}
|
|
2133
|
+
return {
|
|
2134
|
+
format,
|
|
2135
|
+
content,
|
|
2136
|
+
fileExtension: fileExtensionFor(format),
|
|
2137
|
+
schemaCount: entries.length,
|
|
2138
|
+
skippedInvariants,
|
|
2139
|
+
warnings
|
|
2140
|
+
};
|
|
2141
|
+
}
|
|
2142
|
+
/**
|
|
2143
|
+
* Compile and atomically write exported contract schemas to disk via temp file + rename.
|
|
2144
|
+
*/
|
|
2145
|
+
export function writeContractSchemas(contract, outPath, options = {}) {
|
|
2146
|
+
if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
|
|
2147
|
+
throw new VibecodeError("CONTRACT_INVALID", "writeContractSchemas requires a valid non-empty outPath without NUL bytes.");
|
|
2148
|
+
}
|
|
2149
|
+
const resolvedOut = path.resolve(outPath.trim());
|
|
2150
|
+
if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
|
|
2151
|
+
throw new VibecodeError("CONTRACT_INVALID", "writeContractSchemas outPath must point to a file, not a directory.");
|
|
2152
|
+
}
|
|
2153
|
+
const result = exportContractSchemas(contract, options);
|
|
2154
|
+
const parentDir = path.dirname(resolvedOut);
|
|
2155
|
+
fs.mkdirSync(parentDir, { recursive: true });
|
|
2156
|
+
const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
2157
|
+
try {
|
|
2158
|
+
fs.writeFileSync(tmpPath, result.content, "utf8");
|
|
2159
|
+
fs.renameSync(tmpPath, resolvedOut);
|
|
2160
|
+
}
|
|
2161
|
+
catch (err) {
|
|
2162
|
+
try {
|
|
2163
|
+
if (fs.existsSync(tmpPath)) {
|
|
2164
|
+
fs.rmSync(tmpPath, { force: true });
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
catch {
|
|
2168
|
+
// ignore cleanup error
|
|
2169
|
+
}
|
|
2170
|
+
throw err;
|
|
2171
|
+
}
|
|
2172
|
+
return {
|
|
2173
|
+
...result,
|
|
2174
|
+
outPath: resolvedOut
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
function style(text, codes, useColor) {
|
|
2178
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Format a clean, sanitized terminal summary for a schema export result.
|
|
2182
|
+
*/
|
|
2183
|
+
export function formatPrettySchemaExport(result, outPath, color = false) {
|
|
2184
|
+
const useColor = color === true;
|
|
2185
|
+
const lines = [];
|
|
2186
|
+
const banner = style("[SCHEMA EXPORT]", `${ANSI.bold}${ANSI.cyan}`, useColor);
|
|
2187
|
+
const formatLabel = style(sanitizeSingleLineText(result.format, 32), ANSI.bold, useColor);
|
|
2188
|
+
const extLabel = sanitizeSingleLineText(result.fileExtension, 16);
|
|
2189
|
+
lines.push(`${banner} ${formatLabel} (${extLabel})`);
|
|
2190
|
+
const effectiveOut = (typeof outPath === "string" && outPath.trim()) ||
|
|
2191
|
+
(typeof result.outPath === "string" && result.outPath.trim()) ||
|
|
2192
|
+
"";
|
|
2193
|
+
if (effectiveOut) {
|
|
2194
|
+
lines.push(`Output: ${sanitizeSingleLineText(effectiveOut, 240)}`);
|
|
2195
|
+
}
|
|
2196
|
+
const totalBytes = Buffer.byteLength(result.content || "", "utf8");
|
|
2197
|
+
const schemaLabel = result.schemaCount === 1 ? "schema" : "schemas";
|
|
2198
|
+
const countText = style(`${result.schemaCount} ${schemaLabel}`, result.schemaCount > 0 ? ANSI.green : ANSI.yellow, useColor);
|
|
2199
|
+
const summaryParts = [countText];
|
|
2200
|
+
if (Array.isArray(result.skippedInvariants) && result.skippedInvariants.length > 0) {
|
|
2201
|
+
summaryParts.push(`${result.skippedInvariants.length} skipped`);
|
|
2202
|
+
}
|
|
2203
|
+
summaryParts.push(`${totalBytes} bytes`);
|
|
2204
|
+
lines.push(`Summary: ${summaryParts.join(", ")}`);
|
|
2205
|
+
if (Array.isArray(result.warnings) && result.warnings.length > 0) {
|
|
2206
|
+
lines.push("Warnings:");
|
|
2207
|
+
for (const warning of result.warnings.slice(0, 10)) {
|
|
2208
|
+
lines.push(` - ${style(sanitizeSingleLineText(warning, 200), ANSI.yellow, useColor)}`);
|
|
2209
|
+
}
|
|
2210
|
+
if (result.warnings.length > 10) {
|
|
2211
|
+
lines.push(` ${style(`... and ${result.warnings.length - 10} more`, ANSI.dim, useColor)}`);
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
return lines.join("\n");
|
|
2215
|
+
}
|