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.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,3198 @@
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 { queryJsonPath, validateJsonSchema } from "./schema.js";
6
+ import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
7
+ const VALID_FORMATS = new Set(["node-http", "express-ts", "python-http"]);
8
+ const SUPPORTED_HTTP_METHODS = new Set([
9
+ "GET",
10
+ "POST",
11
+ "PUT",
12
+ "PATCH",
13
+ "DELETE",
14
+ "HEAD",
15
+ "OPTIONS"
16
+ ]);
17
+ const BODY_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
18
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
19
+ const TRANSPORT_SKIP_HEADERS = new Set([
20
+ "content-length",
21
+ "transfer-encoding",
22
+ "connection",
23
+ "host"
24
+ ]);
25
+ const DEFAULT_PORT = 3000;
26
+ const MAX_SCHEMA_DEPTH = 12;
27
+ const MAX_SYNTH_NODES = 1024;
28
+ const MAX_ARRAY_ITEMS = 32;
29
+ const MAX_OBJECT_EXTRA_KEYS = 32;
30
+ const MAX_SCHEMA_PROPERTIES = 128;
31
+ const MAX_ENUM_VALUES = 64;
32
+ const MAX_JSON_PATH_INDEX = 64;
33
+ const MAX_PRETTY_WARNINGS = 10;
34
+ const HEADER_NAME_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
35
+ const SAFE_PATH_PARAM_RE = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
36
+ const SAFE_HTML_TAG_RE = /^[a-z][a-z0-9-]*$/;
37
+ const DISALLOWED_LANDMARK_TAGS = new Set([
38
+ "html",
39
+ "head",
40
+ "body",
41
+ "title",
42
+ "script",
43
+ "style",
44
+ "iframe",
45
+ "object",
46
+ "embed"
47
+ ]);
48
+ const LANDMARK_EXTRACTOR_TAGS = new Set([
49
+ "header",
50
+ "nav",
51
+ "main",
52
+ "footer",
53
+ "h1",
54
+ "h2",
55
+ "form",
56
+ "table",
57
+ "ul"
58
+ ]);
59
+ const VALID_JSON_SCHEMA_TYPES = new Set([
60
+ "string",
61
+ "number",
62
+ "integer",
63
+ "boolean",
64
+ "object",
65
+ "array",
66
+ "null"
67
+ ]);
68
+ 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|hmac|signature|signing[_-]?key|private[_-]?key)/i;
69
+ 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|hmac|webhook[-_]?secret|(?:^|[_-])(?:auth|sig|signature)(?:$|[_-]))/i;
70
+ 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|hmac|signature|auth(?:orization|entication|[_-]?(?:token|header|key|secret|code|pass))|(?:^|[_-])auth(?:$|[_-]))/i;
71
+ const AUTH_SCHEME_VALUE_RE = /\b(?:bearer|basic|token|digest|apikey|hmac)\s+\S+/i;
72
+ const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
73
+ const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>()[\]{}]+/g;
74
+ const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
75
+ const PROTO_REL_BASIC_AUTH_RE = /(^|[\s"'`(])(\/\/)([^/\s"'`<>]+:[^/\s"'`<>]+)@/g;
76
+ const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
77
+ const INLINE_BASIC_TOKEN_RE = /\b([Bb][Aa][Ss][Ii][Cc])\s+(?![A-Z]?[a-z]+(?:[\s,.;:]|$))[A-Za-z0-9._~+/=-]{4,}/g;
78
+ const INLINE_SCHEME_TOKEN_RE = /\b([Tt][Oo][Kk][Ee][Nn]|[Aa][Pp][Ii][Kk][Ee][Yy]|[Hh][Mm][Aa][Cc])\s+(?![A-Z]?[a-z]+(?:[\s,.;:]|$))[A-Za-z0-9._~+/=:-]{4,}/g;
79
+ const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*|(?!auth\b|mode\b|header\b)[A-Za-z0-9._~+/:-]{6,})/gi;
80
+ const INLINE_SENSITIVE_HEADER_RE = /\b(?:(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;]+(?:\s*;\s*[A-Za-z0-9_.-]+(?:=[^\s,\r\n;]+)?)*|(Authorization|Proxy-Authorization)\s*[:=]\s*(?:[A-Za-z][A-Za-z0-9_-]*\s+(?:\[REDACTED\]|[^\s,;]+)|\[REDACTED\]|[^\s,;]+)|(X-[A-Za-z0-9_-]*(?:API[-_]?Key|Auth[-_]?Token|Access[-_]?Token|Session[-_]?Token|Secret|Token|CSRF[-_]?Token|XSRF[-_]?Token|Signature(?:-\d+)?|HMAC(?:-[A-Za-z0-9]+)?)|CSRF-Token|XSRF-Token)\s*[:=]\s*(?:(?:Bearer|Basic|Token|ApiKey|Digest|HMAC)\s+(?:\[REDACTED\]|[^\s,;]+)|\[REDACTED\]|[^\s,;]+))/gi;
81
+ const INLINE_SENSITIVE_QUERY_RE = /([?&])([^=&\s#]+)=([^&\s#]+)/g;
82
+ const INLINE_JSON_SECRET_KV_RE = /(["'])([A-Za-z_][A-Za-z0-9_.-]*)\1\s*:\s*(?:(")(?:\\.|[^"\\\r\n])*"|(')(?:\\.|[^'\\\r\n])*')/g;
83
+ const INLINE_SENSITIVE_ENV_RE = /\b([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;`"']+)/g;
84
+ const ANSI = {
85
+ reset: "\x1b[0m",
86
+ bold: "\x1b[1m",
87
+ dim: "\x1b[2m",
88
+ green: "\x1b[32m",
89
+ yellow: "\x1b[33m",
90
+ cyan: "\x1b[36m"
91
+ };
92
+ // ============================================================================
93
+ // Core Guards & Day-1 Secret / Injection / Prototype-Pollution Sanitization
94
+ // ============================================================================
95
+ function isPlainObject(v) {
96
+ return v !== null && typeof v === "object" && !Array.isArray(v);
97
+ }
98
+ function hasOwn(obj, key) {
99
+ return Object.prototype.hasOwnProperty.call(obj, key);
100
+ }
101
+ function isForbiddenKey(key) {
102
+ return FORBIDDEN_KEYS.has(key);
103
+ }
104
+ function isSensitiveHeaderName(name) {
105
+ const trimmed = String(name).trim();
106
+ if (!trimmed)
107
+ return false;
108
+ return isSensitiveHeader(trimmed) || SENSITIVE_HEADER_RE.test(trimmed);
109
+ }
110
+ function isSensitiveQueryName(name) {
111
+ const trimmed = String(name).trim();
112
+ if (!trimmed)
113
+ return false;
114
+ return (isSensitiveQueryParam(trimmed) ||
115
+ SENSITIVE_QUERY_RE.test(trimmed) ||
116
+ isSensitiveHeaderName(trimmed));
117
+ }
118
+ function isSecretFieldName(name) {
119
+ const trimmed = String(name).trim();
120
+ if (!trimmed)
121
+ return false;
122
+ const segments = trimmed.split(/[.\[\]'"]+/).filter(Boolean);
123
+ for (const seg of segments.length > 0 ? segments : [trimmed]) {
124
+ if (SECRET_FIELD_NAME_RE.test(seg) ||
125
+ isSensitiveHeaderName(seg) ||
126
+ isSensitiveQueryName(seg)) {
127
+ return true;
128
+ }
129
+ }
130
+ return false;
131
+ }
132
+ function isAuthSchemeValue(value) {
133
+ return AUTH_SCHEME_VALUE_RE.test(value);
134
+ }
135
+ function stripControlChars(raw) {
136
+ return raw
137
+ .replace(/\0/g, "")
138
+ .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
139
+ .replace(/[\u2028\u2029\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
140
+ }
141
+ function redactVaultPaths(text) {
142
+ return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT]");
143
+ }
144
+ function scrubInlineSecrets(text) {
145
+ const noDigest = text.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
146
+ const noBearer = noDigest.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
147
+ const noBasic = noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
148
+ const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
149
+ const noSensHeader = noScheme.replace(INLINE_SENSITIVE_HEADER_RE, (_m, cookieHdr, authHdr, otherHdr) => `${cookieHdr || authHdr || otherHdr}: [REDACTED]`);
150
+ const noJsonSecret = noSensHeader.replace(INLINE_JSON_SECRET_KV_RE, (match, q1, key, dq, sq) => {
151
+ const q2 = dq ?? sq ?? '"';
152
+ return isSecretFieldName(key) ? `${q1}${key}${q1}: ${q2}[REDACTED]${q2}` : match;
153
+ });
154
+ return noJsonSecret.replace(INLINE_SENSITIVE_ENV_RE, (match, key) => isSecretFieldName(key) ? `${key}=[REDACTED]` : match);
155
+ }
156
+ function sanitizeUrlInText(rawUrl) {
157
+ const withoutVault = redactVaultPaths(rawUrl);
158
+ const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
159
+ try {
160
+ const parsed = new URL(withoutAuth);
161
+ parsed.username = "";
162
+ parsed.password = "";
163
+ parsed.hash = "";
164
+ const safeParams = new URLSearchParams();
165
+ for (const [k, v] of parsed.searchParams.entries()) {
166
+ const trimmedKey = k.trim();
167
+ if (!trimmedKey ||
168
+ isForbiddenKey(trimmedKey) ||
169
+ isSensitiveQueryName(trimmedKey) ||
170
+ /\.vibecode-vault/i.test(trimmedKey) ||
171
+ isAuthSchemeValue(trimmedKey) ||
172
+ URL_BASIC_AUTH_RE.test(trimmedKey) ||
173
+ PROTO_REL_BASIC_AUTH_RE.test(trimmedKey)) {
174
+ URL_BASIC_AUTH_RE.lastIndex = 0;
175
+ PROTO_REL_BASIC_AUTH_RE.lastIndex = 0;
176
+ continue;
177
+ }
178
+ URL_BASIC_AUTH_RE.lastIndex = 0;
179
+ PROTO_REL_BASIC_AUTH_RE.lastIndex = 0;
180
+ if (isAuthSchemeValue(v) ||
181
+ /\.vibecode-vault/i.test(v) ||
182
+ URL_BASIC_AUTH_RE.test(v) ||
183
+ PROTO_REL_BASIC_AUTH_RE.test(v)) {
184
+ URL_BASIC_AUTH_RE.lastIndex = 0;
185
+ PROTO_REL_BASIC_AUTH_RE.lastIndex = 0;
186
+ continue;
187
+ }
188
+ URL_BASIC_AUTH_RE.lastIndex = 0;
189
+ PROTO_REL_BASIC_AUTH_RE.lastIndex = 0;
190
+ const scrubbedVal = scrubInlineSecrets(redactVaultPaths(v));
191
+ if (scrubbedVal.includes("[REDACTED"))
192
+ continue;
193
+ safeParams.append(k, scrubbedVal);
194
+ }
195
+ const serialized = safeParams.toString();
196
+ parsed.search = serialized ? `?${serialized}` : "";
197
+ return parsed.toString();
198
+ }
199
+ catch {
200
+ const hashIdx = withoutAuth.indexOf("#");
201
+ const noHash = hashIdx >= 0 ? withoutAuth.slice(0, hashIdx) : withoutAuth;
202
+ return noHash
203
+ .replace(URL_BASIC_AUTH_RE, "$1")
204
+ .replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key, val) => {
205
+ if (isSensitiveQueryName(key) || isAuthSchemeValue(val) || /\.vibecode-vault/i.test(val)) {
206
+ return `${sep}${key}=[REDACTED]`;
207
+ }
208
+ return match;
209
+ });
210
+ }
211
+ }
212
+ function sanitizeText(raw) {
213
+ const cleaned = stripControlChars(raw);
214
+ const noVault = redactVaultPaths(cleaned);
215
+ const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
216
+ const noBasicAuth = noUrls
217
+ .replace(URL_BASIC_AUTH_RE, "$1")
218
+ .replace(PROTO_REL_BASIC_AUTH_RE, "$1$2");
219
+ const noSensQuery = noBasicAuth.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key, val) => {
220
+ if (isSensitiveQueryName(key) || isAuthSchemeValue(val) || /\.vibecode-vault/i.test(val)) {
221
+ return `${sep}${key}=[REDACTED]`;
222
+ }
223
+ return match;
224
+ });
225
+ return scrubInlineSecrets(noSensQuery);
226
+ }
227
+ function sanitizeSingleLine(raw, maxLen = 240) {
228
+ const cleaned = sanitizeText(raw)
229
+ .replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, " ")
230
+ .replace(/\s+/g, " ")
231
+ .trim();
232
+ if (cleaned.length <= maxLen)
233
+ return cleaned;
234
+ return `${cleaned.slice(0, Math.max(1, maxLen - 3))}...`;
235
+ }
236
+ function sanitizeCommentLine(raw, maxLen = 160) {
237
+ return sanitizeSingleLine(raw, maxLen)
238
+ .replace(/\*\//g, "* /")
239
+ .replace(/\/\*/g, "/ *");
240
+ }
241
+ function sanitizeHeaderValue(raw) {
242
+ return sanitizeSingleLine(raw, 256)
243
+ .replace(/[^\x09\x20-\x7e\xa0-\xff]+/g, "")
244
+ .replace(/\s+/g, " ")
245
+ .trim();
246
+ }
247
+ function sanitizeJsonValue(value, depth = 0, seen = new Set(), warnings, inSecretContext = false) {
248
+ if (value === null || value === undefined)
249
+ return value === undefined ? null : null;
250
+ if (typeof value === "boolean")
251
+ return inSecretContext ? "[REDACTED]" : value;
252
+ if (typeof value === "number") {
253
+ if (inSecretContext)
254
+ return "[REDACTED]";
255
+ return Number.isFinite(value) ? value : 0;
256
+ }
257
+ if (typeof value === "string") {
258
+ if (inSecretContext)
259
+ return "[REDACTED]";
260
+ const trimmed = value.trim();
261
+ if (depth < MAX_SCHEMA_DEPTH &&
262
+ ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
263
+ (trimmed.startsWith("[") && trimmed.endsWith("]")))) {
264
+ try {
265
+ const parsed = JSON.parse(trimmed);
266
+ if (parsed !== null && typeof parsed === "object") {
267
+ return JSON.stringify(sanitizeJsonValue(parsed, depth + 1, seen, warnings, false));
268
+ }
269
+ }
270
+ catch {
271
+ // fall through to plain text scrubbing
272
+ }
273
+ }
274
+ return sanitizeText(value);
275
+ }
276
+ if (depth >= MAX_SCHEMA_DEPTH) {
277
+ warnings?.push(`Payload nesting exceeded maximum depth (${MAX_SCHEMA_DEPTH}); deeper nodes were truncated.`);
278
+ return null;
279
+ }
280
+ if (typeof value !== "object")
281
+ return null;
282
+ if (seen.has(value)) {
283
+ warnings?.push("Detected circular payload reference; replaced cycle with null.");
284
+ return null;
285
+ }
286
+ seen.add(value);
287
+ try {
288
+ if (Array.isArray(value)) {
289
+ return value
290
+ .slice(0, MAX_ARRAY_ITEMS)
291
+ .map((item) => sanitizeJsonValue(item, depth + 1, seen, warnings, inSecretContext));
292
+ }
293
+ const out = Object.create(null);
294
+ let propCount = 0;
295
+ for (const key of Object.keys(value)) {
296
+ if (isForbiddenKey(key))
297
+ continue;
298
+ if (propCount >= MAX_SCHEMA_PROPERTIES)
299
+ break;
300
+ const rawVal = value[key];
301
+ if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol")
302
+ continue;
303
+ const cleanKey = sanitizeText(key).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
304
+ if (!cleanKey || isForbiddenKey(cleanKey))
305
+ continue;
306
+ propCount += 1;
307
+ const secretKey = inSecretContext || isSecretFieldName(key) || isSecretFieldName(cleanKey);
308
+ if (secretKey && (typeof rawVal === "string" || typeof rawVal === "number" || typeof rawVal === "boolean")) {
309
+ out[cleanKey] = "[REDACTED]";
310
+ continue;
311
+ }
312
+ out[cleanKey] = sanitizeJsonValue(rawVal, depth + 1, seen, warnings, secretKey);
313
+ }
314
+ return out;
315
+ }
316
+ finally {
317
+ seen.delete(value);
318
+ }
319
+ }
320
+ function escapeHtmlText(raw) {
321
+ return stripControlChars(raw)
322
+ .replace(/&/g, "&amp;")
323
+ .replace(/</g, "&lt;")
324
+ .replace(/>/g, "&gt;");
325
+ }
326
+ function escapeHtmlAttr(raw) {
327
+ return escapeHtmlText(raw)
328
+ .replace(/"/g, "&quot;")
329
+ .replace(/'/g, "&#39;")
330
+ .replace(/`/g, "&#96;");
331
+ }
332
+ function safeJsJson(value, space) {
333
+ const raw = JSON.stringify(value, null, space) ?? "null";
334
+ return raw
335
+ .replace(/\0/g, "")
336
+ .replace(/\u2028/g, "\\u2028")
337
+ .replace(/\u2029/g, "\\u2029")
338
+ .replace(/<\//g, "<\\/");
339
+ }
340
+ function safePyString(raw) {
341
+ let out = '"';
342
+ for (let i = 0; i < raw.length; i++) {
343
+ const ch = raw[i];
344
+ const code = raw.charCodeAt(i);
345
+ if (ch === "\\")
346
+ out += "\\\\";
347
+ else if (ch === '"')
348
+ out += '\\"';
349
+ else if (ch === "\n")
350
+ out += "\\n";
351
+ else if (ch === "\r")
352
+ out += "\\r";
353
+ else if (ch === "\t")
354
+ out += "\\t";
355
+ else if (code === 0)
356
+ out += "\\x00";
357
+ else if (code < 0x20 || code === 0x7f) {
358
+ out += `\\x${code.toString(16).padStart(2, "0")}`;
359
+ }
360
+ else if (code === 0x2028 || code === 0x2029 || code > 0x7e) {
361
+ out += `\\u${code.toString(16).padStart(4, "0")}`;
362
+ }
363
+ else {
364
+ out += ch;
365
+ }
366
+ }
367
+ out += '"';
368
+ return out;
369
+ }
370
+ function toPythonLiteral(value, indent = 0) {
371
+ if (value === null || value === undefined)
372
+ return "None";
373
+ if (typeof value === "boolean")
374
+ return value ? "True" : "False";
375
+ if (typeof value === "number")
376
+ return Number.isFinite(value) ? String(value) : "0";
377
+ if (typeof value === "string")
378
+ return safePyString(value);
379
+ const pad = " ".repeat(indent);
380
+ const innerPad = " ".repeat(indent + 4);
381
+ if (Array.isArray(value)) {
382
+ if (value.length === 0)
383
+ return "[]";
384
+ const items = value.map((item) => `${innerPad}${toPythonLiteral(item, indent + 4)}`);
385
+ return `[\n${items.join(",\n")}\n${pad}]`;
386
+ }
387
+ if (typeof value === "object") {
388
+ const entries = Object.entries(value).filter(([k, v]) => !isForbiddenKey(k) && v !== undefined);
389
+ if (entries.length === 0)
390
+ return "{}";
391
+ const parts = entries.map(([k, v]) => `${innerPad}${safePyString(k)}: ${toPythonLiteral(v, indent + 4)}`);
392
+ return `{\n${parts.join(",\n")}\n${pad}}`;
393
+ }
394
+ return "None";
395
+ }
396
+ // ============================================================================
397
+ // Path, Query, Header & Status Normalization
398
+ // ============================================================================
399
+ function sanitizePathname(rawPathname) {
400
+ const noHash = rawPathname.split("#")[0] ?? "";
401
+ const noControl = sanitizeText(noHash)
402
+ .replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "")
403
+ .trim();
404
+ if (!noControl)
405
+ return "/";
406
+ const encodedSpaces = noControl.replace(/\s+/g, "%20");
407
+ const rawSegments = encodedSpaces.split("/");
408
+ const stack = [];
409
+ for (const seg of rawSegments) {
410
+ if (!seg || seg === ".")
411
+ continue;
412
+ if (seg === "..") {
413
+ if (stack.length > 0)
414
+ stack.pop();
415
+ continue;
416
+ }
417
+ stack.push(seg);
418
+ }
419
+ return stack.length === 0 ? "/" : `/${stack.join("/")}`;
420
+ }
421
+ function parseSegmentSpec(seg) {
422
+ if (seg.startsWith("{") && seg.endsWith("}") && seg.length > 2) {
423
+ const inner = seg.slice(1, -1);
424
+ if (SAFE_PATH_PARAM_RE.test(inner) && !isForbiddenKey(inner)) {
425
+ return { raw: seg, isParam: true, paramName: inner };
426
+ }
427
+ }
428
+ else if (seg.startsWith(":") && seg.length > 1) {
429
+ const inner = seg.slice(1);
430
+ if (SAFE_PATH_PARAM_RE.test(inner) && !isForbiddenKey(inner)) {
431
+ return { raw: seg, isParam: true, paramName: inner };
432
+ }
433
+ }
434
+ return { raw: seg, isParam: false };
435
+ }
436
+ function compilePathSegments(pathname) {
437
+ if (pathname === "/") {
438
+ return { segments: [], expressPath: "/", staticSegmentCount: 0, paramCount: 0 };
439
+ }
440
+ const parts = pathname.split("/").filter(Boolean);
441
+ const segments = [];
442
+ const expressParts = [];
443
+ let staticSegmentCount = 0;
444
+ let paramCount = 0;
445
+ for (const part of parts) {
446
+ const spec = parseSegmentSpec(part);
447
+ segments.push(spec);
448
+ if (spec.isParam && spec.paramName) {
449
+ paramCount += 1;
450
+ expressParts.push(`:${spec.paramName}`);
451
+ }
452
+ else {
453
+ staticSegmentCount += 1;
454
+ expressParts.push(part);
455
+ }
456
+ }
457
+ return {
458
+ segments,
459
+ expressPath: expressParts.length === 0 ? "/" : `/${expressParts.join("/")}`,
460
+ staticSegmentCount,
461
+ paramCount
462
+ };
463
+ }
464
+ function sanitizeQueryParamValue(rawKey, rawVal) {
465
+ const rawCleanKey = stripControlChars(rawKey).replace(/[\r\n]+/g, "").trim();
466
+ if (!rawCleanKey || isForbiddenKey(rawCleanKey))
467
+ return null;
468
+ if (/\.vibecode-vault/i.test(rawCleanKey) || isAuthSchemeValue(rawCleanKey))
469
+ return null;
470
+ if (/@/.test(rawCleanKey) && (/:\/\//.test(rawCleanKey) || rawCleanKey.includes("//")))
471
+ return null;
472
+ const cleanKey = sanitizeText(rawCleanKey).replace(/[\r\n]+/g, "").trim();
473
+ if (!cleanKey || isForbiddenKey(cleanKey))
474
+ return null;
475
+ if (isSensitiveQueryName(cleanKey) || /\.vibecode-vault/i.test(cleanKey) || isAuthSchemeValue(cleanKey)) {
476
+ return null;
477
+ }
478
+ if (/\.vibecode-vault/i.test(rawVal) || isAuthSchemeValue(rawVal))
479
+ return null;
480
+ if (/@/.test(rawVal) && (/:\/\//.test(rawVal) || rawVal.includes("//")))
481
+ return null;
482
+ const cleanVal = sanitizeText(rawVal).replace(/[\r\n]+/g, "").trim();
483
+ if (isAuthSchemeValue(cleanVal) || cleanVal.includes("[REDACTED"))
484
+ return null;
485
+ return [cleanKey, cleanVal];
486
+ }
487
+ function parsePathAndQuery(rawPath, extraQuery) {
488
+ let pathname = "/";
489
+ const query = Object.create(null);
490
+ const cleaned = typeof rawPath === "string"
491
+ ? stripControlChars(rawPath).replace(/[\r\n]+/g, "").trim()
492
+ : "";
493
+ if (cleaned && !/^(?:javascript|vbscript|data):/i.test(cleaned)) {
494
+ const noVault = redactVaultPaths(cleaned);
495
+ const noAuth = noVault.replace(URL_BASIC_AUTH_RE, "$1");
496
+ if (/^https?:\/\//i.test(noAuth)) {
497
+ try {
498
+ const parsed = new URL(noAuth);
499
+ pathname = sanitizePathname(parsed.pathname || "/");
500
+ for (const [k, v] of parsed.searchParams.entries()) {
501
+ const safe = sanitizeQueryParamValue(k, v);
502
+ if (safe)
503
+ query[safe[0]] = safe[1];
504
+ }
505
+ }
506
+ catch {
507
+ const stripped = noAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
508
+ const noHash = stripped.split("#")[0] ?? "/";
509
+ const qIdx = noHash.indexOf("?");
510
+ pathname = sanitizePathname(qIdx >= 0 ? noHash.slice(0, qIdx) : noHash);
511
+ if (qIdx >= 0) {
512
+ const params = new URLSearchParams(noHash.slice(qIdx + 1));
513
+ for (const [k, v] of params.entries()) {
514
+ const safe = sanitizeQueryParamValue(k, v);
515
+ if (safe)
516
+ query[safe[0]] = safe[1];
517
+ }
518
+ }
519
+ }
520
+ }
521
+ else {
522
+ const noHash = noAuth.split("#")[0] ?? "/";
523
+ const qIdx = noHash.indexOf("?");
524
+ pathname = sanitizePathname(qIdx >= 0 ? noHash.slice(0, qIdx) : noHash);
525
+ if (qIdx >= 0) {
526
+ const params = new URLSearchParams(noHash.slice(qIdx + 1));
527
+ for (const [k, v] of params.entries()) {
528
+ const safe = sanitizeQueryParamValue(k, v);
529
+ if (safe)
530
+ query[safe[0]] = safe[1];
531
+ }
532
+ }
533
+ }
534
+ }
535
+ if (isPlainObject(extraQuery)) {
536
+ for (const key of Object.keys(extraQuery)) {
537
+ if (isForbiddenKey(key))
538
+ continue;
539
+ const val = extraQuery[key];
540
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
541
+ if (typeof val === "number" && !Number.isFinite(val))
542
+ continue;
543
+ const safe = sanitizeQueryParamValue(key, String(val));
544
+ if (safe)
545
+ query[safe[0]] = safe[1];
546
+ }
547
+ }
548
+ }
549
+ const plainQuery = {};
550
+ for (const k of Object.keys(query)) {
551
+ plainQuery[k] = query[k];
552
+ }
553
+ return { path: pathname || "/", query: plainQuery };
554
+ }
555
+ function resolveExpectedStatus(expectedStatus) {
556
+ if (typeof expectedStatus === "number" &&
557
+ Number.isInteger(expectedStatus) &&
558
+ expectedStatus >= 100 &&
559
+ expectedStatus <= 599) {
560
+ return expectedStatus;
561
+ }
562
+ if (Array.isArray(expectedStatus)) {
563
+ for (const candidate of expectedStatus) {
564
+ if (typeof candidate === "number" &&
565
+ Number.isInteger(candidate) &&
566
+ candidate >= 100 &&
567
+ candidate <= 599) {
568
+ return candidate;
569
+ }
570
+ }
571
+ }
572
+ return 200;
573
+ }
574
+ function sanitizeResponseHeaders(rawHeaders) {
575
+ const out = {};
576
+ if (!isPlainObject(rawHeaders))
577
+ return out;
578
+ for (const rawKey of Object.keys(rawHeaders)) {
579
+ if (isForbiddenKey(rawKey))
580
+ continue;
581
+ const rawVal = rawHeaders[rawKey];
582
+ if (rawVal === undefined || rawVal === null)
583
+ continue;
584
+ const key = stripControlChars(rawKey).replace(/[\r\n]+/g, "").trim().toLowerCase();
585
+ if (!key || isForbiddenKey(key) || !HEADER_NAME_TOKEN_RE.test(key))
586
+ continue;
587
+ if (TRANSPORT_SKIP_HEADERS.has(key))
588
+ continue;
589
+ if (isSensitiveHeaderName(key) || /\.vibecode-vault/i.test(key))
590
+ continue;
591
+ const valStr = String(rawVal);
592
+ if (isAuthSchemeValue(valStr) || /\.vibecode-vault/i.test(valStr))
593
+ continue;
594
+ const cleaned = sanitizeHeaderValue(valStr);
595
+ if (!cleaned || cleaned === "[REDACTED]" || cleaned.includes("[REDACTED_VAULT]"))
596
+ continue;
597
+ out[key] = cleaned;
598
+ }
599
+ return out;
600
+ }
601
+ // ============================================================================
602
+ // Draft 2020-12 Schema Sanitization, $ref Resolution & Deterministic Synthesis
603
+ // ============================================================================
604
+ function canonicalJson(v, seen = new Set()) {
605
+ if (v === null)
606
+ return "null";
607
+ if (typeof v === "boolean" || typeof v === "string")
608
+ return JSON.stringify(v);
609
+ if (typeof v === "number")
610
+ return Number.isFinite(v) ? JSON.stringify(v) : "null";
611
+ if (typeof v === "undefined")
612
+ return "undefined";
613
+ if (Array.isArray(v)) {
614
+ if (seen.has(v))
615
+ return '"[Circular]"';
616
+ seen.add(v);
617
+ const parts = v.map((item) => (item === undefined ? "null" : canonicalJson(item, seen)));
618
+ seen.delete(v);
619
+ return `[${parts.join(",")}]`;
620
+ }
621
+ if (typeof v === "object") {
622
+ if (seen.has(v))
623
+ return '"[Circular]"';
624
+ seen.add(v);
625
+ const obj = v;
626
+ const keys = Object.keys(obj).sort();
627
+ const parts = [];
628
+ for (const k of keys) {
629
+ if (isForbiddenKey(k) || obj[k] === undefined)
630
+ continue;
631
+ parts.push(`${JSON.stringify(k)}:${canonicalJson(obj[k], seen)}`);
632
+ }
633
+ seen.delete(v);
634
+ return `{${parts.join(",")}}`;
635
+ }
636
+ return JSON.stringify(String(v));
637
+ }
638
+ function refPointsToSecret(ref) {
639
+ if (!ref.startsWith("#/"))
640
+ return true;
641
+ const segments = ref
642
+ .slice(2)
643
+ .split("/")
644
+ .map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
645
+ for (const seg of segments) {
646
+ if (!seg || isForbiddenKey(seg) || isSecretFieldName(seg)) {
647
+ return true;
648
+ }
649
+ }
650
+ return false;
651
+ }
652
+ function resolveLocalRef(rootSchema, ref) {
653
+ if (!rootSchema || !ref.startsWith("#/") || refPointsToSecret(ref))
654
+ return undefined;
655
+ const parts = ref
656
+ .slice(2)
657
+ .split("/")
658
+ .map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
659
+ let current = rootSchema;
660
+ for (const part of parts) {
661
+ if (!part || isForbiddenKey(part) || isSecretFieldName(part))
662
+ return undefined;
663
+ if (!isPlainObject(current) || !hasOwn(current, part))
664
+ return undefined;
665
+ current = current[part];
666
+ }
667
+ return isPlainObject(current) ? current : undefined;
668
+ }
669
+ function sanitizeSchemaForSynthesis(schema, depth = 0, seen = new Set(), budget = { nodes: 0 }, warnings, inSecretProp = false) {
670
+ if (!isPlainObject(schema))
671
+ return undefined;
672
+ if (depth >= MAX_SCHEMA_DEPTH) {
673
+ warnings?.push(`Schema nesting exceeded maximum depth (${MAX_SCHEMA_DEPTH}); truncated branch.`);
674
+ return {};
675
+ }
676
+ if (budget.nodes >= MAX_SYNTH_NODES) {
677
+ warnings?.push(`Schema exceeded maximum node budget (${MAX_SYNTH_NODES}); truncated branch.`);
678
+ return {};
679
+ }
680
+ if (seen.has(schema)) {
681
+ warnings?.push("Detected circular schema object reference; replaced cycle with empty schema.");
682
+ return {};
683
+ }
684
+ budget.nodes += 1;
685
+ seen.add(schema);
686
+ try {
687
+ const out = {};
688
+ for (const key of Object.keys(schema)) {
689
+ if (isForbiddenKey(key))
690
+ continue;
691
+ const val = schema[key];
692
+ if (val === undefined)
693
+ continue;
694
+ if (key === "type") {
695
+ if (typeof val === "string") {
696
+ const cleanType = sanitizeSingleLine(val, 32).toLowerCase();
697
+ if (VALID_JSON_SCHEMA_TYPES.has(cleanType))
698
+ out.type = cleanType;
699
+ }
700
+ else if (Array.isArray(val)) {
701
+ const types = val
702
+ .filter((t) => typeof t === "string")
703
+ .map((t) => sanitizeSingleLine(t, 32).toLowerCase())
704
+ .filter((t) => VALID_JSON_SCHEMA_TYPES.has(t));
705
+ if (types.length > 0)
706
+ out.type = types;
707
+ }
708
+ }
709
+ else if (key === "nullable" && typeof val === "boolean") {
710
+ out.nullable = val;
711
+ }
712
+ else if (key === "format" && typeof val === "string") {
713
+ const fmt = sanitizeSingleLine(val, 64);
714
+ if (fmt)
715
+ out.format = fmt;
716
+ }
717
+ else if (key === "$ref" && typeof val === "string") {
718
+ const cleanRef = sanitizeSingleLine(val, 200);
719
+ if (cleanRef.startsWith("#/") && !refPointsToSecret(cleanRef)) {
720
+ out.$ref = cleanRef;
721
+ }
722
+ }
723
+ else if ((key === "minLength" ||
724
+ key === "maxLength" ||
725
+ key === "minItems" ||
726
+ key === "maxItems" ||
727
+ key === "minProperties" ||
728
+ key === "maxProperties") &&
729
+ typeof val === "number" &&
730
+ Number.isInteger(val) &&
731
+ val >= 0) {
732
+ out[key] = val;
733
+ }
734
+ else if ((key === "minimum" ||
735
+ key === "maximum" ||
736
+ key === "exclusiveMinimum" ||
737
+ key === "exclusiveMaximum") &&
738
+ typeof val === "number" &&
739
+ Number.isFinite(val)) {
740
+ out[key] = val;
741
+ }
742
+ else if (key === "multipleOf" && typeof val === "number" && Number.isFinite(val) && val > 0) {
743
+ out.multipleOf = val;
744
+ }
745
+ else if (key === "uniqueItems" && typeof val === "boolean") {
746
+ out.uniqueItems = val;
747
+ }
748
+ else if (key === "pattern" && !inSecretProp && typeof val === "string" && val.length <= 256 && !val.includes("\0")) {
749
+ const pat = sanitizeSingleLine(val, 256);
750
+ if (pat && !pat.includes("[REDACTED"))
751
+ out.pattern = pat;
752
+ }
753
+ else if (key === "required" && Array.isArray(val)) {
754
+ const reqs = val
755
+ .filter((item) => typeof item === "string" && item.length > 0 && !isForbiddenKey(item))
756
+ .map((item) => sanitizeSingleLine(item, 80))
757
+ .filter((item) => item.length > 0 && !isForbiddenKey(item));
758
+ if (reqs.length > 0)
759
+ out.required = [...new Set(reqs)];
760
+ }
761
+ else if (key === "properties" && isPlainObject(val)) {
762
+ const props = Object.create(null);
763
+ let count = 0;
764
+ for (const propKey of Object.keys(val)) {
765
+ if (isForbiddenKey(propKey))
766
+ continue;
767
+ if (count >= MAX_SCHEMA_PROPERTIES)
768
+ break;
769
+ const cleanPropKey = sanitizeText(propKey).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
770
+ if (!cleanPropKey || isForbiddenKey(cleanPropKey))
771
+ continue;
772
+ count += 1;
773
+ const propIsSecret = inSecretProp || isSecretFieldName(propKey) || isSecretFieldName(cleanPropKey);
774
+ const sanitizedProp = sanitizeSchemaForSynthesis(val[propKey], depth + 1, seen, budget, warnings, propIsSecret);
775
+ props[cleanPropKey] = sanitizedProp ?? {};
776
+ }
777
+ out.properties = props;
778
+ }
779
+ else if (key === "additionalProperties") {
780
+ if (typeof val === "boolean") {
781
+ out.additionalProperties = val;
782
+ }
783
+ else if (isPlainObject(val)) {
784
+ out.additionalProperties =
785
+ sanitizeSchemaForSynthesis(val, depth + 1, seen, budget, warnings, inSecretProp) ?? {};
786
+ }
787
+ }
788
+ else if (key === "items") {
789
+ if (Array.isArray(val)) {
790
+ out.items = val
791
+ .slice(0, MAX_ARRAY_ITEMS)
792
+ .map((item) => sanitizeSchemaForSynthesis(item, depth + 1, seen, budget, warnings, inSecretProp) ?? {});
793
+ }
794
+ else if (isPlainObject(val)) {
795
+ out.items = sanitizeSchemaForSynthesis(val, depth + 1, seen, budget, warnings, inSecretProp) ?? {};
796
+ }
797
+ }
798
+ else if (key === "allOf" || key === "anyOf" || key === "oneOf") {
799
+ if (Array.isArray(val)) {
800
+ const branches = val
801
+ .map((item) => sanitizeSchemaForSynthesis(item, depth + 1, seen, budget, warnings, inSecretProp))
802
+ .filter((item) => item !== undefined);
803
+ if (branches.length > 0)
804
+ out[key] = branches;
805
+ }
806
+ }
807
+ else if (key === "not" && isPlainObject(val)) {
808
+ const notSchema = sanitizeSchemaForSynthesis(val, depth + 1, seen, budget, warnings, inSecretProp);
809
+ if (notSchema)
810
+ out.not = notSchema;
811
+ }
812
+ else if (key === "const") {
813
+ out.const = sanitizeJsonValue(val, depth + 1, seen, warnings, inSecretProp);
814
+ }
815
+ else if (key === "enum" && Array.isArray(val)) {
816
+ const cleanedEnum = val
817
+ .slice(0, MAX_ENUM_VALUES)
818
+ .map((item) => sanitizeJsonValue(item, depth + 1, seen, warnings, inSecretProp));
819
+ if (cleanedEnum.length > 0)
820
+ out.enum = cleanedEnum;
821
+ }
822
+ else if ((key === "example" || key === "default") && !inSecretProp) {
823
+ out[key] = sanitizeJsonValue(val, depth + 1, seen, warnings, false);
824
+ }
825
+ else if ((key === "$defs" || key === "definitions") && isPlainObject(val)) {
826
+ const defs = Object.create(null);
827
+ for (const defKey of Object.keys(val)) {
828
+ if (isForbiddenKey(defKey) || isSecretFieldName(defKey))
829
+ continue;
830
+ const cleanDefKey = sanitizeText(defKey).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
831
+ if (!cleanDefKey || isForbiddenKey(cleanDefKey) || isSecretFieldName(cleanDefKey))
832
+ continue;
833
+ const defSchema = sanitizeSchemaForSynthesis(val[defKey], depth + 1, seen, budget, warnings, false);
834
+ if (defSchema)
835
+ defs[cleanDefKey] = defSchema;
836
+ }
837
+ out[key] = defs;
838
+ }
839
+ }
840
+ return out;
841
+ }
842
+ finally {
843
+ seen.delete(schema);
844
+ }
845
+ }
846
+ function mergeTwoSchemas(a, b, depth = 0) {
847
+ if (depth >= MAX_SCHEMA_DEPTH)
848
+ return { ...a };
849
+ const merged = {};
850
+ const typesA = a.type === undefined ? null : (Array.isArray(a.type) ? a.type : [a.type]);
851
+ const typesB = b.type === undefined ? null : (Array.isArray(b.type) ? b.type : [b.type]);
852
+ if (typesA && typesB) {
853
+ const inter = typesA.filter((t) => typesB.includes(t));
854
+ if (inter.length === 1)
855
+ merged.type = inter[0];
856
+ else if (inter.length > 1)
857
+ merged.type = inter;
858
+ else if (typesA.includes("integer") && typesB.includes("number"))
859
+ merged.type = "integer";
860
+ else if (typesB.includes("integer") && typesA.includes("number"))
861
+ merged.type = "integer";
862
+ else
863
+ merged.type = b.type;
864
+ }
865
+ else if (typesA) {
866
+ merged.type = a.type;
867
+ }
868
+ else if (typesB) {
869
+ merged.type = b.type;
870
+ }
871
+ if (a.const !== undefined)
872
+ merged.const = a.const;
873
+ else if (b.const !== undefined)
874
+ merged.const = b.const;
875
+ if (Array.isArray(a.enum) && Array.isArray(b.enum)) {
876
+ const bSet = new Set(b.enum.map((item) => canonicalJson(item)));
877
+ const inter = a.enum.filter((item) => bSet.has(canonicalJson(item)));
878
+ merged.enum = inter.length > 0 ? inter : a.enum;
879
+ }
880
+ else if (Array.isArray(a.enum)) {
881
+ merged.enum = a.enum;
882
+ }
883
+ else if (Array.isArray(b.enum)) {
884
+ merged.enum = b.enum;
885
+ }
886
+ if (typeof a.format === "string")
887
+ merged.format = a.format;
888
+ if (typeof b.format === "string")
889
+ merged.format = b.format;
890
+ if (typeof a.pattern === "string")
891
+ merged.pattern = a.pattern;
892
+ if (typeof b.pattern === "string")
893
+ merged.pattern = b.pattern;
894
+ if (typeof a.minLength === "number" || typeof b.minLength === "number") {
895
+ merged.minLength = Math.max(a.minLength ?? 0, b.minLength ?? 0);
896
+ }
897
+ if (typeof a.maxLength === "number" || typeof b.maxLength === "number") {
898
+ merged.maxLength = Math.min(a.maxLength ?? Infinity, b.maxLength ?? Infinity);
899
+ }
900
+ if (typeof a.minimum === "number" || typeof b.minimum === "number") {
901
+ merged.minimum = Math.max(a.minimum ?? -Infinity, b.minimum ?? -Infinity);
902
+ }
903
+ if (typeof a.maximum === "number" || typeof b.maximum === "number") {
904
+ merged.maximum = Math.min(a.maximum ?? Infinity, b.maximum ?? Infinity);
905
+ }
906
+ if (typeof a.exclusiveMinimum === "number" || typeof b.exclusiveMinimum === "number") {
907
+ merged.exclusiveMinimum = Math.max(a.exclusiveMinimum ?? -Infinity, b.exclusiveMinimum ?? -Infinity);
908
+ }
909
+ if (typeof a.exclusiveMaximum === "number" || typeof b.exclusiveMaximum === "number") {
910
+ merged.exclusiveMaximum = Math.min(a.exclusiveMaximum ?? Infinity, b.exclusiveMaximum ?? Infinity);
911
+ }
912
+ if (typeof b.multipleOf === "number")
913
+ merged.multipleOf = b.multipleOf;
914
+ else if (typeof a.multipleOf === "number")
915
+ merged.multipleOf = a.multipleOf;
916
+ if (typeof a.minItems === "number" || typeof b.minItems === "number") {
917
+ merged.minItems = Math.max(a.minItems ?? 0, b.minItems ?? 0);
918
+ }
919
+ if (typeof a.maxItems === "number" || typeof b.maxItems === "number") {
920
+ merged.maxItems = Math.min(a.maxItems ?? Infinity, b.maxItems ?? Infinity);
921
+ }
922
+ if (a.uniqueItems === true || b.uniqueItems === true)
923
+ merged.uniqueItems = true;
924
+ if (isPlainObject(a.items) && isPlainObject(b.items)) {
925
+ merged.items = mergeTwoSchemas(a.items, b.items, depth + 1);
926
+ }
927
+ else if (b.items !== undefined) {
928
+ merged.items = b.items;
929
+ }
930
+ else if (a.items !== undefined) {
931
+ merged.items = a.items;
932
+ }
933
+ if (typeof a.minProperties === "number" || typeof b.minProperties === "number") {
934
+ merged.minProperties = Math.max(a.minProperties ?? 0, b.minProperties ?? 0);
935
+ }
936
+ if (typeof a.maxProperties === "number" || typeof b.maxProperties === "number") {
937
+ merged.maxProperties = Math.min(a.maxProperties ?? Infinity, b.maxProperties ?? Infinity);
938
+ }
939
+ if (Array.isArray(a.required) || Array.isArray(b.required)) {
940
+ const reqSet = new Set();
941
+ for (const k of a.required || []) {
942
+ if (typeof k === "string" && !isForbiddenKey(k))
943
+ reqSet.add(k);
944
+ }
945
+ for (const k of b.required || []) {
946
+ if (typeof k === "string" && !isForbiddenKey(k))
947
+ reqSet.add(k);
948
+ }
949
+ merged.required = [...reqSet];
950
+ }
951
+ if (isPlainObject(a.properties) || isPlainObject(b.properties)) {
952
+ const props = Object.create(null);
953
+ if (isPlainObject(a.properties)) {
954
+ for (const k of Object.keys(a.properties)) {
955
+ if (isForbiddenKey(k))
956
+ continue;
957
+ props[k] = a.properties[k];
958
+ }
959
+ }
960
+ if (isPlainObject(b.properties)) {
961
+ for (const k of Object.keys(b.properties)) {
962
+ if (isForbiddenKey(k))
963
+ continue;
964
+ const sub = b.properties[k];
965
+ if (hasOwn(props, k) && isPlainObject(props[k]) && isPlainObject(sub)) {
966
+ props[k] = mergeTwoSchemas(props[k], sub, depth + 1);
967
+ }
968
+ else {
969
+ props[k] = sub;
970
+ }
971
+ }
972
+ }
973
+ merged.properties = props;
974
+ }
975
+ if (a.additionalProperties === false || b.additionalProperties === false) {
976
+ merged.additionalProperties = false;
977
+ }
978
+ else if (isPlainObject(a.additionalProperties) && isPlainObject(b.additionalProperties)) {
979
+ merged.additionalProperties = mergeTwoSchemas(a.additionalProperties, b.additionalProperties, depth + 1);
980
+ }
981
+ else if (b.additionalProperties !== undefined) {
982
+ merged.additionalProperties = b.additionalProperties;
983
+ }
984
+ else if (a.additionalProperties !== undefined) {
985
+ merged.additionalProperties = a.additionalProperties;
986
+ }
987
+ if (a.nullable === true && b.nullable === true)
988
+ merged.nullable = true;
989
+ if (b.example !== undefined)
990
+ merged.example = b.example;
991
+ else if (a.example !== undefined)
992
+ merged.example = a.example;
993
+ if (b.default !== undefined)
994
+ merged.default = b.default;
995
+ else if (a.default !== undefined)
996
+ merged.default = a.default;
997
+ if (Array.isArray(b.anyOf))
998
+ merged.anyOf = b.anyOf;
999
+ else if (Array.isArray(a.anyOf))
1000
+ merged.anyOf = a.anyOf;
1001
+ if (Array.isArray(b.oneOf))
1002
+ merged.oneOf = b.oneOf;
1003
+ else if (Array.isArray(a.oneOf))
1004
+ merged.oneOf = a.oneOf;
1005
+ if (isPlainObject(b.not))
1006
+ merged.not = b.not;
1007
+ else if (isPlainObject(a.not))
1008
+ merged.not = a.not;
1009
+ if (typeof b.$ref === "string")
1010
+ merged.$ref = b.$ref;
1011
+ else if (typeof a.$ref === "string")
1012
+ merged.$ref = a.$ref;
1013
+ return merged;
1014
+ }
1015
+ function flattenAllOf(schema, rootSchema, depth = 0) {
1016
+ if (depth >= MAX_SCHEMA_DEPTH || !Array.isArray(schema.allOf) || schema.allOf.length === 0) {
1017
+ return schema;
1018
+ }
1019
+ const rest = {};
1020
+ for (const k of Object.keys(schema)) {
1021
+ if (k === "allOf" || isForbiddenKey(k))
1022
+ continue;
1023
+ rest[k] = schema[k];
1024
+ }
1025
+ let acc = rest;
1026
+ for (const sub of schema.allOf) {
1027
+ if (!isPlainObject(sub))
1028
+ continue;
1029
+ let resolvedSub = sub;
1030
+ if (typeof resolvedSub.$ref === "string") {
1031
+ const target = resolveLocalRef(rootSchema, resolvedSub.$ref);
1032
+ if (target)
1033
+ resolvedSub = target;
1034
+ }
1035
+ const flatSub = flattenAllOf(resolvedSub, rootSchema, depth + 1);
1036
+ acc = mergeTwoSchemas(acc, flatSub, depth + 1);
1037
+ }
1038
+ return acc;
1039
+ }
1040
+ function synthesizeStringForRegex(pattern) {
1041
+ let re;
1042
+ try {
1043
+ re = new RegExp(pattern);
1044
+ }
1045
+ catch {
1046
+ return null;
1047
+ }
1048
+ const probeCandidates = [
1049
+ "sample",
1050
+ "active",
1051
+ "ok",
1052
+ "1",
1053
+ "0",
1054
+ "123",
1055
+ "abc",
1056
+ "ABC",
1057
+ "item-1",
1058
+ "11111111-1111-4111-8111-111111111111",
1059
+ "user@example.com",
1060
+ "2026-01-15",
1061
+ "2026-01-15T00:00:00.000Z",
1062
+ "https://example.com/resource",
1063
+ "127.0.0.1"
1064
+ ];
1065
+ for (const c of probeCandidates) {
1066
+ if (re.test(c))
1067
+ return c;
1068
+ }
1069
+ let src = pattern.trim();
1070
+ if (src.startsWith("^"))
1071
+ src = src.slice(1);
1072
+ if (src.endsWith("$"))
1073
+ src = src.slice(0, -1);
1074
+ if (src.startsWith("(") && src.endsWith(")")) {
1075
+ const inner = src.slice(1, -1);
1076
+ if (!inner.includes("(") && !inner.includes(")")) {
1077
+ src = inner.split("|")[0] ?? inner;
1078
+ }
1079
+ }
1080
+ else if (!src.includes("(") && src.includes("|")) {
1081
+ src = src.split("|")[0] ?? src;
1082
+ }
1083
+ let out = "";
1084
+ let i = 0;
1085
+ while (i < src.length && out.length < 64) {
1086
+ let token = "";
1087
+ const ch = src[i];
1088
+ if (ch === "\\" && i + 1 < src.length) {
1089
+ const next = src[i + 1];
1090
+ i += 2;
1091
+ if (next === "d")
1092
+ token = "1";
1093
+ else if (next === "w")
1094
+ token = "a";
1095
+ else if (next === "s")
1096
+ token = " ";
1097
+ else if (next === "D")
1098
+ token = "a";
1099
+ else if (next === "W")
1100
+ token = "-";
1101
+ else if (next === "S")
1102
+ token = "a";
1103
+ else
1104
+ token = next;
1105
+ }
1106
+ else if (ch === "[") {
1107
+ const end = src.indexOf("]", i + 1);
1108
+ if (end > i) {
1109
+ const cls = src.slice(i + 1, end);
1110
+ i = end + 1;
1111
+ if (cls.startsWith("^"))
1112
+ token = "a";
1113
+ else if (cls.includes("0-9"))
1114
+ token = "1";
1115
+ else if (cls.includes("a-z") || cls.includes("a-f"))
1116
+ token = "a";
1117
+ else if (cls.includes("A-Z") || cls.includes("A-F"))
1118
+ token = "A";
1119
+ else
1120
+ token = cls[0] || "a";
1121
+ }
1122
+ else {
1123
+ i += 1;
1124
+ token = "a";
1125
+ }
1126
+ }
1127
+ else if (ch === "(") {
1128
+ const end = src.indexOf(")", i + 1);
1129
+ if (end > i) {
1130
+ const group = src.slice(i + 1, end).replace(/^\?:/, "");
1131
+ i = end + 1;
1132
+ token = (group.split("|")[0] || "a").replace(/\\(.)/g, "$1");
1133
+ }
1134
+ else {
1135
+ i += 1;
1136
+ }
1137
+ }
1138
+ else if (ch === ".") {
1139
+ i += 1;
1140
+ token = "a";
1141
+ }
1142
+ else if (ch === "^" || ch === "$") {
1143
+ i += 1;
1144
+ continue;
1145
+ }
1146
+ else {
1147
+ i += 1;
1148
+ token = ch;
1149
+ }
1150
+ let repeat = 1;
1151
+ if (i < src.length) {
1152
+ const q = src[i];
1153
+ if (q === "+" || q === "*" || q === "?") {
1154
+ repeat = 1;
1155
+ i += 1;
1156
+ }
1157
+ else if (q === "{") {
1158
+ const closeBrace = src.indexOf("}", i + 1);
1159
+ if (closeBrace > i) {
1160
+ const spec = src.slice(i + 1, closeBrace);
1161
+ const m = /^(\d+)(?:,(\d*))?$/.exec(spec);
1162
+ if (m) {
1163
+ repeat = Math.min(Math.max(Number(m[1]), 0), 16);
1164
+ i = closeBrace + 1;
1165
+ }
1166
+ }
1167
+ }
1168
+ if (i < src.length && src[i] === "?")
1169
+ i += 1;
1170
+ }
1171
+ out += token.repeat(repeat);
1172
+ }
1173
+ return re.test(out) ? out : null;
1174
+ }
1175
+ function synthesizeString(schema, variantIndex) {
1176
+ if (typeof schema.format === "string") {
1177
+ switch (schema.format) {
1178
+ case "uuid": {
1179
+ if (variantIndex === 0)
1180
+ return "11111111-1111-4111-8111-111111111111";
1181
+ const tail = (variantIndex + 1).toString(16).padStart(12, "0").slice(-12);
1182
+ return `11111111-1111-4111-8111-${tail}`;
1183
+ }
1184
+ case "email":
1185
+ return variantIndex === 0 ? "user@example.com" : `user${variantIndex}@example.com`;
1186
+ case "date": {
1187
+ if (variantIndex === 0)
1188
+ return "2026-01-15";
1189
+ const offset = 14 + variantIndex;
1190
+ const day = (offset % 28) + 1;
1191
+ const month = (Math.floor(offset / 28) % 12) + 1;
1192
+ return `2026-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1193
+ }
1194
+ case "date-time": {
1195
+ if (variantIndex === 0)
1196
+ return "2026-01-15T00:00:00.000Z";
1197
+ const sec = variantIndex % 60;
1198
+ const min = Math.floor(variantIndex / 60) % 60;
1199
+ const hr = Math.floor(variantIndex / 3600) % 24;
1200
+ return `2026-01-15T${String(hr).padStart(2, "0")}:${String(min).padStart(2, "0")}:${String(sec).padStart(2, "0")}.000Z`;
1201
+ }
1202
+ case "uri":
1203
+ return variantIndex === 0 ? "https://example.com/resource" : `https://example.com/resource/${variantIndex}`;
1204
+ case "ipv4":
1205
+ return variantIndex === 0 ? "127.0.0.1" : `127.0.0.${(variantIndex % 254) + 1}`;
1206
+ default:
1207
+ break;
1208
+ }
1209
+ }
1210
+ if (typeof schema.pattern === "string") {
1211
+ const matched = synthesizeStringForRegex(schema.pattern);
1212
+ if (matched !== null)
1213
+ return matched;
1214
+ }
1215
+ let value = variantIndex === 0 ? "sample" : `sample-${variantIndex}`;
1216
+ const minLen = typeof schema.minLength === "number" && Number.isFinite(schema.minLength) && schema.minLength > 0
1217
+ ? Math.min(Math.ceil(schema.minLength), 256)
1218
+ : 0;
1219
+ const maxLen = typeof schema.maxLength === "number" && Number.isFinite(schema.maxLength) && schema.maxLength >= 0
1220
+ ? Math.floor(schema.maxLength)
1221
+ : Infinity;
1222
+ if (value.length < minLen) {
1223
+ const padChar = String.fromCharCode(97 + (variantIndex % 26));
1224
+ value = value + padChar.repeat(minLen - value.length);
1225
+ }
1226
+ if (value.length > maxLen) {
1227
+ if (maxLen === 0) {
1228
+ value = "";
1229
+ }
1230
+ else if (variantIndex > 0) {
1231
+ const suffix = variantIndex.toString(36);
1232
+ value = suffix.length >= maxLen ? suffix.slice(-maxLen) : value.slice(0, maxLen - suffix.length) + suffix;
1233
+ }
1234
+ else {
1235
+ value = value.slice(0, maxLen);
1236
+ }
1237
+ }
1238
+ return value;
1239
+ }
1240
+ function synthesizeNumber(schema, isInt, variantIndex) {
1241
+ const hasMin = typeof schema.minimum === "number" && Number.isFinite(schema.minimum);
1242
+ const hasMax = typeof schema.maximum === "number" && Number.isFinite(schema.maximum);
1243
+ const hasExMin = typeof schema.exclusiveMinimum === "number" && Number.isFinite(schema.exclusiveMinimum);
1244
+ const hasExMax = typeof schema.exclusiveMaximum === "number" && Number.isFinite(schema.exclusiveMaximum);
1245
+ const step = typeof schema.multipleOf === "number" && Number.isFinite(schema.multipleOf) && schema.multipleOf > 0
1246
+ ? schema.multipleOf
1247
+ : undefined;
1248
+ let lo = -Infinity;
1249
+ if (hasMin)
1250
+ lo = Math.max(lo, schema.minimum);
1251
+ if (hasExMin)
1252
+ lo = Math.max(lo, isInt ? Math.floor(schema.exclusiveMinimum) + 1 : schema.exclusiveMinimum);
1253
+ let hi = Infinity;
1254
+ if (hasMax)
1255
+ hi = Math.min(hi, schema.maximum);
1256
+ if (hasExMax)
1257
+ hi = Math.min(hi, isInt ? Math.ceil(schema.exclusiveMaximum) - 1 : schema.exclusiveMaximum);
1258
+ const isValid = (n) => {
1259
+ if (!Number.isFinite(n))
1260
+ return false;
1261
+ if (isInt && !Number.isInteger(n))
1262
+ return false;
1263
+ if (hasMin && n < schema.minimum)
1264
+ return false;
1265
+ if (hasMax && n > schema.maximum)
1266
+ return false;
1267
+ if (hasExMin && n <= schema.exclusiveMinimum)
1268
+ return false;
1269
+ if (hasExMax && n >= schema.exclusiveMaximum)
1270
+ return false;
1271
+ if (step !== undefined) {
1272
+ const q = n / step;
1273
+ if (!Number.isFinite(q) || Math.abs(q - Math.round(q)) > 1e-9)
1274
+ return false;
1275
+ }
1276
+ return true;
1277
+ };
1278
+ if (step !== undefined) {
1279
+ const unitStep = isInt && !Number.isInteger(step) ? Math.max(1, Math.round(step)) : step;
1280
+ let kLo = Number.isFinite(lo) ? Math.ceil((lo - 1e-9) / unitStep) : 0;
1281
+ if (hasExMin && kLo * unitStep <= schema.exclusiveMinimum)
1282
+ kLo += 1;
1283
+ let kHi = Number.isFinite(hi) ? Math.floor((hi + 1e-9) / unitStep) : Infinity;
1284
+ if (hasExMax && Number.isFinite(kHi) && kHi * unitStep >= schema.exclusiveMaximum)
1285
+ kHi -= 1;
1286
+ let k;
1287
+ if (Number.isFinite(lo) && Number.isFinite(hi)) {
1288
+ k = Math.max(kLo, Math.min(kLo + variantIndex, kHi));
1289
+ }
1290
+ else if (Number.isFinite(lo)) {
1291
+ k = kLo + variantIndex;
1292
+ }
1293
+ else if (Number.isFinite(hi)) {
1294
+ k = kHi - variantIndex;
1295
+ }
1296
+ else {
1297
+ k = variantIndex + 1;
1298
+ }
1299
+ const candidate = isInt ? Math.round(k * unitStep) : Number((k * unitStep).toPrecision(12));
1300
+ if (isValid(candidate))
1301
+ return candidate;
1302
+ }
1303
+ let candidate;
1304
+ if (Number.isFinite(lo) && Number.isFinite(hi)) {
1305
+ if (isInt) {
1306
+ candidate = Math.min(Math.ceil(lo) + variantIndex, Math.floor(hi));
1307
+ }
1308
+ else {
1309
+ const span = hi - lo;
1310
+ if (hasExMin || hasExMax) {
1311
+ candidate = lo + span * ((variantIndex + 1) / (variantIndex + 2));
1312
+ }
1313
+ else {
1314
+ candidate = variantIndex === 0 ? lo : Math.min(lo + variantIndex, hi);
1315
+ }
1316
+ }
1317
+ }
1318
+ else if (Number.isFinite(lo)) {
1319
+ const base = isInt ? Math.ceil(lo) : hasExMin ? lo + 1 : lo;
1320
+ candidate = base + variantIndex;
1321
+ }
1322
+ else if (Number.isFinite(hi)) {
1323
+ const base = isInt ? Math.floor(hi) : hasExMax ? hi - 1 : hi;
1324
+ candidate = base - variantIndex;
1325
+ }
1326
+ else {
1327
+ candidate = variantIndex + 1;
1328
+ }
1329
+ return isInt ? Math.round(candidate) : candidate;
1330
+ }
1331
+ function inferSchemaType(schema, isRoot) {
1332
+ if (typeof schema.type === "string")
1333
+ return schema.type;
1334
+ if (Array.isArray(schema.type) && schema.type.length > 0) {
1335
+ const primary = schema.type.find((t) => t !== "null");
1336
+ return primary || schema.type[0] || (isRoot ? "object" : "string");
1337
+ }
1338
+ if (isPlainObject(schema.properties) ||
1339
+ Array.isArray(schema.required) ||
1340
+ schema.additionalProperties !== undefined ||
1341
+ typeof schema.minProperties === "number" ||
1342
+ typeof schema.maxProperties === "number") {
1343
+ return "object";
1344
+ }
1345
+ if (schema.items !== undefined ||
1346
+ typeof schema.minItems === "number" ||
1347
+ typeof schema.maxItems === "number" ||
1348
+ schema.uniqueItems === true) {
1349
+ return "array";
1350
+ }
1351
+ if (typeof schema.minimum === "number" ||
1352
+ typeof schema.maximum === "number" ||
1353
+ typeof schema.exclusiveMinimum === "number" ||
1354
+ typeof schema.exclusiveMaximum === "number" ||
1355
+ typeof schema.multipleOf === "number") {
1356
+ return "number";
1357
+ }
1358
+ if (typeof schema.minLength === "number" ||
1359
+ typeof schema.maxLength === "number" ||
1360
+ typeof schema.pattern === "string" ||
1361
+ typeof schema.format === "string") {
1362
+ return "string";
1363
+ }
1364
+ return isRoot ? "object" : "string";
1365
+ }
1366
+ function cycleFallbackForSchema(rawSchema, isRoot) {
1367
+ const primaryType = isPlainObject(rawSchema)
1368
+ ? inferSchemaType(rawSchema, isRoot)
1369
+ : isRoot
1370
+ ? "object"
1371
+ : "string";
1372
+ if (primaryType === "object")
1373
+ return {};
1374
+ if (primaryType === "array")
1375
+ return [];
1376
+ if (primaryType === "integer" || primaryType === "number")
1377
+ return 0;
1378
+ if (primaryType === "boolean")
1379
+ return false;
1380
+ if (primaryType === "null")
1381
+ return null;
1382
+ return "sample";
1383
+ }
1384
+ function synthesizeFromJsonSchema(rawSchema, rootSchema, depth = 0, variantIndex = 0, isRoot = true, state = { seen: new Set(), seenRefs: new Set(), nodes: 0, warnings: [] }) {
1385
+ if (depth >= MAX_SCHEMA_DEPTH ||
1386
+ !isPlainObject(rawSchema) ||
1387
+ state.nodes >= MAX_SYNTH_NODES ||
1388
+ state.seen.has(rawSchema)) {
1389
+ return cycleFallbackForSchema(rawSchema, isRoot);
1390
+ }
1391
+ state.nodes += 1;
1392
+ state.seen.add(rawSchema);
1393
+ try {
1394
+ let activeSchema = rawSchema;
1395
+ let activeRef = null;
1396
+ if (typeof rawSchema.$ref === "string") {
1397
+ const refStr = rawSchema.$ref;
1398
+ if (state.seenRefs.has(refStr)) {
1399
+ state.warnings.push(`Detected circular $ref "${sanitizeSingleLine(refStr, 80)}"; using fallback value.`);
1400
+ return cycleFallbackForSchema(rawSchema, isRoot);
1401
+ }
1402
+ const target = resolveLocalRef(rootSchema, refStr);
1403
+ if (target) {
1404
+ activeRef = refStr;
1405
+ state.seenRefs.add(refStr);
1406
+ const withoutRef = {};
1407
+ for (const k of Object.keys(rawSchema)) {
1408
+ if (k === "$ref" || isForbiddenKey(k))
1409
+ continue;
1410
+ withoutRef[k] = rawSchema[k];
1411
+ }
1412
+ activeSchema = Object.keys(withoutRef).length > 0 ? mergeTwoSchemas(target, withoutRef, depth + 1) : target;
1413
+ }
1414
+ }
1415
+ try {
1416
+ const schema = flattenAllOf(activeSchema, rootSchema, depth);
1417
+ if (schema.const !== undefined) {
1418
+ return sanitizeJsonValue(schema.const, depth + 1, new Set(), state.warnings);
1419
+ }
1420
+ if (Array.isArray(schema.enum) && schema.enum.length > 0) {
1421
+ const start = variantIndex % schema.enum.length;
1422
+ for (let offset = 0; offset < schema.enum.length; offset++) {
1423
+ const candidate = sanitizeJsonValue(schema.enum[(start + offset) % schema.enum.length], depth + 1, new Set(), state.warnings);
1424
+ if (validateJsonSchema(candidate, schema).length === 0)
1425
+ return candidate;
1426
+ }
1427
+ return sanitizeJsonValue(schema.enum[start], depth + 1, new Set(), state.warnings);
1428
+ }
1429
+ if (variantIndex === 0 && schema.example !== undefined) {
1430
+ const candidate = sanitizeJsonValue(schema.example, depth + 1, new Set(), state.warnings);
1431
+ if (validateJsonSchema(candidate, schema).length === 0)
1432
+ return candidate;
1433
+ }
1434
+ if (variantIndex === 0 && schema.default !== undefined) {
1435
+ const candidate = sanitizeJsonValue(schema.default, depth + 1, new Set(), state.warnings);
1436
+ if (validateJsonSchema(candidate, schema).length === 0)
1437
+ return candidate;
1438
+ }
1439
+ if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
1440
+ const baseWithoutOneOf = {};
1441
+ for (const k of Object.keys(schema)) {
1442
+ if (k === "oneOf" || isForbiddenKey(k))
1443
+ continue;
1444
+ baseWithoutOneOf[k] = schema[k];
1445
+ }
1446
+ for (const sub of schema.oneOf) {
1447
+ if (!isPlainObject(sub) || state.seen.has(sub))
1448
+ continue;
1449
+ const combined = mergeTwoSchemas(baseWithoutOneOf, sub, depth + 1);
1450
+ const candidate = synthesizeFromJsonSchema(combined, rootSchema, depth + 1, variantIndex, isRoot, state);
1451
+ if (validateJsonSchema(candidate, schema).length === 0)
1452
+ return candidate;
1453
+ }
1454
+ const firstSub = schema.oneOf.find((s) => isPlainObject(s) && !state.seen.has(s));
1455
+ if (firstSub) {
1456
+ return synthesizeFromJsonSchema(mergeTwoSchemas(baseWithoutOneOf, firstSub, depth + 1), rootSchema, depth + 1, variantIndex, isRoot, state);
1457
+ }
1458
+ }
1459
+ if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
1460
+ const baseWithoutAnyOf = {};
1461
+ for (const k of Object.keys(schema)) {
1462
+ if (k === "anyOf" || isForbiddenKey(k))
1463
+ continue;
1464
+ baseWithoutAnyOf[k] = schema[k];
1465
+ }
1466
+ for (const sub of schema.anyOf) {
1467
+ if (!isPlainObject(sub) || state.seen.has(sub))
1468
+ continue;
1469
+ const combined = mergeTwoSchemas(baseWithoutAnyOf, sub, depth + 1);
1470
+ const candidate = synthesizeFromJsonSchema(combined, rootSchema, depth + 1, variantIndex, isRoot, state);
1471
+ if (validateJsonSchema(candidate, schema).length === 0)
1472
+ return candidate;
1473
+ }
1474
+ const firstSub = schema.anyOf.find((s) => isPlainObject(s) && !state.seen.has(s));
1475
+ if (firstSub) {
1476
+ return synthesizeFromJsonSchema(mergeTwoSchemas(baseWithoutAnyOf, firstSub, depth + 1), rootSchema, depth + 1, variantIndex, isRoot, state);
1477
+ }
1478
+ }
1479
+ const synthForVariant = (vIdx) => {
1480
+ const primaryType = inferSchemaType(schema, isRoot);
1481
+ switch (primaryType) {
1482
+ case "null":
1483
+ return null;
1484
+ case "boolean":
1485
+ return vIdx % 2 === 0;
1486
+ case "integer":
1487
+ return synthesizeNumber(schema, true, vIdx);
1488
+ case "number":
1489
+ return synthesizeNumber(schema, false, vIdx);
1490
+ case "string":
1491
+ return synthesizeString(schema, vIdx);
1492
+ case "array": {
1493
+ const minItems = typeof schema.minItems === "number" && Number.isFinite(schema.minItems) && schema.minItems >= 0
1494
+ ? Math.ceil(schema.minItems)
1495
+ : 0;
1496
+ const maxItems = typeof schema.maxItems === "number" && Number.isFinite(schema.maxItems) && schema.maxItems >= 0
1497
+ ? Math.floor(schema.maxItems)
1498
+ : Infinity;
1499
+ let count = minItems;
1500
+ if (count === 0 && maxItems > 0 && schema.items !== undefined)
1501
+ count = 1;
1502
+ count = Math.min(count, maxItems, MAX_ARRAY_ITEMS);
1503
+ const result = [];
1504
+ const seenCanon = new Set();
1505
+ for (let i = 0; i < count; i++) {
1506
+ const itemSchema = Array.isArray(schema.items)
1507
+ ? isPlainObject(schema.items[i])
1508
+ ? schema.items[i]
1509
+ : {}
1510
+ : isPlainObject(schema.items)
1511
+ ? schema.items
1512
+ : { type: "string" };
1513
+ let attemptVariant = vIdx * MAX_ARRAY_ITEMS + i;
1514
+ let item = synthesizeFromJsonSchema(itemSchema, rootSchema, depth + 1, attemptVariant, false, state);
1515
+ if (schema.uniqueItems === true) {
1516
+ let tries = 0;
1517
+ while (seenCanon.has(canonicalJson(item)) && tries < 16) {
1518
+ tries += 1;
1519
+ attemptVariant += 1;
1520
+ item = synthesizeFromJsonSchema(itemSchema, rootSchema, depth + 1, attemptVariant, false, state);
1521
+ }
1522
+ seenCanon.add(canonicalJson(item));
1523
+ }
1524
+ result.push(item);
1525
+ }
1526
+ return result;
1527
+ }
1528
+ case "object":
1529
+ default: {
1530
+ const out = Object.create(null);
1531
+ const declaredProps = isPlainObject(schema.properties)
1532
+ ? schema.properties
1533
+ : {};
1534
+ const requiredKeys = Array.isArray(schema.required)
1535
+ ? schema.required.filter((k) => typeof k === "string" && !isForbiddenKey(k))
1536
+ : [];
1537
+ const maxProps = typeof schema.maxProperties === "number" && Number.isFinite(schema.maxProperties) && schema.maxProperties >= 0
1538
+ ? Math.floor(schema.maxProperties)
1539
+ : Infinity;
1540
+ const minProps = typeof schema.minProperties === "number" && Number.isFinite(schema.minProperties) && schema.minProperties >= 0
1541
+ ? Math.min(Math.ceil(schema.minProperties), MAX_OBJECT_EXTRA_KEYS)
1542
+ : 0;
1543
+ for (const key of requiredKeys) {
1544
+ if (Object.keys(out).length >= maxProps)
1545
+ break;
1546
+ if (schema.additionalProperties === false && !hasOwn(declaredProps, key))
1547
+ continue;
1548
+ const propSchema = hasOwn(declaredProps, key)
1549
+ ? declaredProps[key]
1550
+ : isPlainObject(schema.additionalProperties)
1551
+ ? schema.additionalProperties
1552
+ : { type: "string" };
1553
+ out[key] = synthesizeFromJsonSchema(propSchema, rootSchema, depth + 1, vIdx, false, state);
1554
+ }
1555
+ for (const key of Object.keys(declaredProps)) {
1556
+ if (Object.keys(out).length >= maxProps)
1557
+ break;
1558
+ if (isForbiddenKey(key) || hasOwn(out, key))
1559
+ continue;
1560
+ out[key] = synthesizeFromJsonSchema(declaredProps[key], rootSchema, depth + 1, vIdx, false, state);
1561
+ }
1562
+ if (schema.additionalProperties !== false && Object.keys(out).length < minProps) {
1563
+ const extraSchema = isPlainObject(schema.additionalProperties)
1564
+ ? schema.additionalProperties
1565
+ : { type: "string" };
1566
+ let idx = 1;
1567
+ while (Object.keys(out).length < minProps &&
1568
+ Object.keys(out).length < maxProps &&
1569
+ idx <= MAX_OBJECT_EXTRA_KEYS) {
1570
+ const key = `field_${idx}`;
1571
+ idx += 1;
1572
+ if (!hasOwn(out, key)) {
1573
+ out[key] = synthesizeFromJsonSchema(extraSchema, rootSchema, depth + 1, vIdx + idx, false, state);
1574
+ }
1575
+ }
1576
+ }
1577
+ return out;
1578
+ }
1579
+ }
1580
+ };
1581
+ let result = synthForVariant(variantIndex);
1582
+ if (isPlainObject(schema.not)) {
1583
+ for (let attempt = 1; attempt <= 6; attempt++) {
1584
+ if (validateJsonSchema(result, schema.not).length > 0)
1585
+ break;
1586
+ result = synthForVariant(variantIndex + attempt);
1587
+ }
1588
+ if (validateJsonSchema(result, schema.not).length === 0 && schema.type === undefined) {
1589
+ const fallbacks = ["other", 42, true, [], {}];
1590
+ for (const fb of fallbacks) {
1591
+ if (validateJsonSchema(fb, schema).length === 0) {
1592
+ result = fb;
1593
+ break;
1594
+ }
1595
+ }
1596
+ }
1597
+ }
1598
+ return result;
1599
+ }
1600
+ finally {
1601
+ if (activeRef !== null) {
1602
+ state.seenRefs.delete(activeRef);
1603
+ }
1604
+ }
1605
+ }
1606
+ finally {
1607
+ state.seen.delete(rawSchema);
1608
+ }
1609
+ }
1610
+ function deepMergeJson(base, overlay, depth = 0, warnings) {
1611
+ if (depth >= MAX_SCHEMA_DEPTH)
1612
+ return sanitizeJsonValue(overlay, depth, new Set(), warnings);
1613
+ const cleanOverlay = sanitizeJsonValue(overlay, 0, new Set(), warnings);
1614
+ if (Array.isArray(cleanOverlay)) {
1615
+ if (!Array.isArray(base))
1616
+ return cleanOverlay;
1617
+ const merged = base.slice();
1618
+ for (let i = 0; i < cleanOverlay.length; i++) {
1619
+ merged[i] = i < merged.length ? deepMergeJson(merged[i], cleanOverlay[i], depth + 1, warnings) : cleanOverlay[i];
1620
+ }
1621
+ return merged;
1622
+ }
1623
+ if (isPlainObject(cleanOverlay)) {
1624
+ const out = Object.create(null);
1625
+ if (isPlainObject(base)) {
1626
+ for (const k of Object.keys(base)) {
1627
+ if (!isForbiddenKey(k))
1628
+ out[k] = base[k];
1629
+ }
1630
+ }
1631
+ for (const k of Object.keys(cleanOverlay)) {
1632
+ if (isForbiddenKey(k) || cleanOverlay[k] === undefined)
1633
+ continue;
1634
+ out[k] = hasOwn(out, k) ? deepMergeJson(out[k], cleanOverlay[k], depth + 1, warnings) : cleanOverlay[k];
1635
+ }
1636
+ return out;
1637
+ }
1638
+ return cleanOverlay;
1639
+ }
1640
+ function tokenizeJsonPath(expr) {
1641
+ if (typeof expr !== "string" || !expr.startsWith("$"))
1642
+ return null;
1643
+ const tokens = [];
1644
+ const re = /\.([A-Za-z_$][A-Za-z0-9_$-]*)|\[(\d+)\]|\[(?:"([^"]*)"|'([^']*)')\]/g;
1645
+ let i = 1;
1646
+ while (i < expr.length) {
1647
+ re.lastIndex = i;
1648
+ const m = re.exec(expr);
1649
+ if (!m || m.index !== i)
1650
+ return null;
1651
+ if (m[1] !== undefined) {
1652
+ if (isForbiddenKey(m[1]))
1653
+ return null;
1654
+ tokens.push(m[1]);
1655
+ }
1656
+ else if (m[2] !== undefined) {
1657
+ const idx = Number(m[2]);
1658
+ if (!Number.isInteger(idx) || idx < 0 || idx > MAX_JSON_PATH_INDEX)
1659
+ return null;
1660
+ tokens.push(idx);
1661
+ }
1662
+ else if (m[3] !== undefined) {
1663
+ if (isForbiddenKey(m[3]))
1664
+ return null;
1665
+ tokens.push(m[3]);
1666
+ }
1667
+ else if (m[4] !== undefined) {
1668
+ if (isForbiddenKey(m[4]))
1669
+ return null;
1670
+ tokens.push(m[4]);
1671
+ }
1672
+ i = re.lastIndex;
1673
+ }
1674
+ return tokens;
1675
+ }
1676
+ function setJsonPathValue(root, tokens, value) {
1677
+ if (tokens.length === 0)
1678
+ return value;
1679
+ const first = tokens[0];
1680
+ const container = typeof first === "number"
1681
+ ? Array.isArray(root)
1682
+ ? root
1683
+ : []
1684
+ : isPlainObject(root)
1685
+ ? root
1686
+ : Object.create(null);
1687
+ let cur = container;
1688
+ for (let i = 0; i < tokens.length - 1; i++) {
1689
+ const tok = tokens[i];
1690
+ const nextTok = tokens[i + 1];
1691
+ if (typeof tok === "number") {
1692
+ const arr = cur;
1693
+ while (arr.length <= tok)
1694
+ arr.push(null);
1695
+ const existing = arr[tok];
1696
+ if (typeof nextTok === "number") {
1697
+ if (!Array.isArray(existing))
1698
+ arr[tok] = [];
1699
+ }
1700
+ else if (!isPlainObject(existing)) {
1701
+ arr[tok] = Object.create(null);
1702
+ }
1703
+ cur = arr[tok];
1704
+ }
1705
+ else {
1706
+ const obj = cur;
1707
+ const existing = obj[tok];
1708
+ if (typeof nextTok === "number") {
1709
+ if (!Array.isArray(existing))
1710
+ obj[tok] = [];
1711
+ }
1712
+ else if (!isPlainObject(existing)) {
1713
+ obj[tok] = Object.create(null);
1714
+ }
1715
+ cur = obj[tok];
1716
+ }
1717
+ }
1718
+ const last = tokens[tokens.length - 1];
1719
+ if (typeof last === "number") {
1720
+ const arr = cur;
1721
+ while (arr.length <= last)
1722
+ arr.push(null);
1723
+ arr[last] = value;
1724
+ }
1725
+ else {
1726
+ const obj = cur;
1727
+ obj[last] = value;
1728
+ }
1729
+ return container;
1730
+ }
1731
+ function applyJsonPathAssertions(root, assertions, warnings) {
1732
+ let current = root;
1733
+ for (const assertion of assertions) {
1734
+ if (!isPlainObject(assertion) || typeof assertion.path !== "string")
1735
+ continue;
1736
+ const tokens = tokenizeJsonPath(assertion.path);
1737
+ if (!tokens)
1738
+ continue;
1739
+ if (hasOwn(assertion, "equals")) {
1740
+ const lastTok = tokens[tokens.length - 1];
1741
+ const rawVal = assertion.equals;
1742
+ const isSecretTok = typeof lastTok === "string" && isSecretFieldName(lastTok);
1743
+ const sanitizedVal = isSecretTok && (typeof rawVal === "string" || typeof rawVal === "number" || typeof rawVal === "boolean")
1744
+ ? "[REDACTED]"
1745
+ : sanitizeJsonValue(rawVal, 0, new Set(), warnings, isSecretTok);
1746
+ current = setJsonPathValue(current, tokens, sanitizedVal);
1747
+ }
1748
+ else if (hasOwn(assertion, "matches") &&
1749
+ typeof assertion.matches === "string") {
1750
+ const existing = queryJsonPath(current, assertion.path);
1751
+ let alreadyMatches = false;
1752
+ if (existing.found) {
1753
+ try {
1754
+ alreadyMatches = new RegExp(assertion.matches).test(String(existing.value));
1755
+ }
1756
+ catch {
1757
+ alreadyMatches = false;
1758
+ }
1759
+ }
1760
+ if (!alreadyMatches) {
1761
+ const synthesized = synthesizeStringForRegex(assertion.matches) ?? "sample";
1762
+ current = setJsonPathValue(current, tokens, sanitizeText(synthesized));
1763
+ }
1764
+ }
1765
+ else {
1766
+ const existing = queryJsonPath(current, assertion.path);
1767
+ if (!existing.found) {
1768
+ current = setJsonPathValue(current, tokens, "ok");
1769
+ }
1770
+ }
1771
+ }
1772
+ return current;
1773
+ }
1774
+ // ============================================================================
1775
+ // Request Schema Inference (for --strict Request Body Validation)
1776
+ // ============================================================================
1777
+ function inferRequestSchemaFromValue(value, depth = 0, seen = new Set()) {
1778
+ if (depth >= MAX_SCHEMA_DEPTH)
1779
+ return undefined;
1780
+ if (value === null)
1781
+ return { type: "null" };
1782
+ if (typeof value === "boolean")
1783
+ return { type: "boolean" };
1784
+ if (typeof value === "number") {
1785
+ if (!Number.isFinite(value))
1786
+ return undefined;
1787
+ return { type: "number" };
1788
+ }
1789
+ if (typeof value === "string")
1790
+ return { type: "string" };
1791
+ if (typeof value !== "object")
1792
+ return undefined;
1793
+ if (seen.has(value))
1794
+ return undefined;
1795
+ seen.add(value);
1796
+ try {
1797
+ if (Array.isArray(value)) {
1798
+ const firstItem = value.length > 0 ? inferRequestSchemaFromValue(value[0], depth + 1, seen) : undefined;
1799
+ return {
1800
+ type: "array",
1801
+ ...(firstItem ? { items: firstItem } : {})
1802
+ };
1803
+ }
1804
+ const obj = value;
1805
+ const properties = {};
1806
+ const required = [];
1807
+ let count = 0;
1808
+ for (const key of Object.keys(obj)) {
1809
+ if (isForbiddenKey(key) || isSecretFieldName(key))
1810
+ continue;
1811
+ if (count >= MAX_SCHEMA_PROPERTIES)
1812
+ break;
1813
+ const cleanKey = sanitizeText(key).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
1814
+ if (!cleanKey || isForbiddenKey(cleanKey) || isSecretFieldName(cleanKey))
1815
+ continue;
1816
+ const val = obj[key];
1817
+ if (val === undefined || typeof val === "function" || typeof val === "symbol")
1818
+ continue;
1819
+ const childSpec = inferRequestSchemaFromValue(val, depth + 1, seen);
1820
+ if (!childSpec)
1821
+ continue;
1822
+ count += 1;
1823
+ properties[cleanKey] = childSpec;
1824
+ if (val !== null)
1825
+ required.push(cleanKey);
1826
+ }
1827
+ return {
1828
+ type: "object",
1829
+ ...(required.length > 0 ? { required } : {}),
1830
+ ...(Object.keys(properties).length > 0 ? { properties } : {})
1831
+ };
1832
+ }
1833
+ finally {
1834
+ seen.delete(value);
1835
+ }
1836
+ }
1837
+ function buildRequestSchemaFromJsonSchema(schema, depth = 0, seen = new Set()) {
1838
+ if (depth >= MAX_SCHEMA_DEPTH || !isPlainObject(schema) || seen.has(schema))
1839
+ return undefined;
1840
+ seen.add(schema);
1841
+ try {
1842
+ const primaryType = inferSchemaType(schema, depth === 0);
1843
+ const normalizedType = (VALID_JSON_SCHEMA_TYPES.has(primaryType) ? primaryType : "object");
1844
+ if (normalizedType === "object") {
1845
+ const properties = {};
1846
+ if (isPlainObject(schema.properties)) {
1847
+ let count = 0;
1848
+ for (const key of Object.keys(schema.properties)) {
1849
+ if (isForbiddenKey(key) || isSecretFieldName(key))
1850
+ continue;
1851
+ if (count >= MAX_SCHEMA_PROPERTIES)
1852
+ break;
1853
+ const cleanKey = sanitizeText(key).replace(/[\r\n\0\u2028\u2029]+/g, "").trim();
1854
+ if (!cleanKey || isForbiddenKey(cleanKey) || isSecretFieldName(cleanKey))
1855
+ continue;
1856
+ const propSpec = buildRequestSchemaFromJsonSchema(schema.properties[key], depth + 1, seen);
1857
+ if (propSpec) {
1858
+ count += 1;
1859
+ properties[cleanKey] = propSpec;
1860
+ }
1861
+ }
1862
+ }
1863
+ const required = Array.isArray(schema.required)
1864
+ ? schema.required.filter((k) => typeof k === "string" && !isForbiddenKey(k) && !isSecretFieldName(k) && hasOwn(properties, k))
1865
+ : [];
1866
+ return {
1867
+ type: "object",
1868
+ ...(required.length > 0 ? { required } : {}),
1869
+ ...(Object.keys(properties).length > 0 ? { properties } : {}),
1870
+ ...(schema.additionalProperties === false ? { additionalProperties: false } : {})
1871
+ };
1872
+ }
1873
+ if (normalizedType === "array") {
1874
+ const itemSpec = isPlainObject(schema.items)
1875
+ ? buildRequestSchemaFromJsonSchema(schema.items, depth + 1, seen)
1876
+ : undefined;
1877
+ return {
1878
+ type: "array",
1879
+ ...(itemSpec ? { items: itemSpec } : {})
1880
+ };
1881
+ }
1882
+ return { type: normalizedType };
1883
+ }
1884
+ finally {
1885
+ seen.delete(schema);
1886
+ }
1887
+ }
1888
+ function deriveRequestSchema(input, method, warnings) {
1889
+ if (!BODY_HTTP_METHODS.has(method))
1890
+ return undefined;
1891
+ const rawSchema = isPlainObject(input.bodySchema)
1892
+ ? input.bodySchema
1893
+ : isPlainObject(input.jsonSchema)
1894
+ ? input.jsonSchema
1895
+ : undefined;
1896
+ if (rawSchema) {
1897
+ const sanitized = sanitizeSchemaForSynthesis(rawSchema, 0, new Set(), { nodes: 0 }, warnings);
1898
+ if (sanitized)
1899
+ return buildRequestSchemaFromJsonSchema(sanitized);
1900
+ }
1901
+ if (input.body !== undefined && input.body !== null) {
1902
+ if (typeof input.body === "string") {
1903
+ const trimmed = input.body.trim();
1904
+ if ((trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
1905
+ try {
1906
+ const parsed = JSON.parse(trimmed);
1907
+ if (parsed !== null && typeof parsed === "object") {
1908
+ return inferRequestSchemaFromValue(parsed);
1909
+ }
1910
+ }
1911
+ catch {
1912
+ return undefined;
1913
+ }
1914
+ }
1915
+ return undefined;
1916
+ }
1917
+ if (typeof input.body === "object") {
1918
+ return inferRequestSchemaFromValue(input.body);
1919
+ }
1920
+ }
1921
+ return undefined;
1922
+ }
1923
+ // ============================================================================
1924
+ // HTTP & Web Route Payload Synthesis
1925
+ // ============================================================================
1926
+ function inferContentTypeForExactBody(body, headerContentType) {
1927
+ if (headerContentType)
1928
+ return headerContentType;
1929
+ const trimmed = body.trim();
1930
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1931
+ try {
1932
+ JSON.parse(trimmed);
1933
+ return "application/json; charset=utf-8";
1934
+ }
1935
+ catch {
1936
+ // not valid JSON
1937
+ }
1938
+ }
1939
+ return "text/plain; charset=utf-8";
1940
+ }
1941
+ function synthesizeHttpResponse(invariant, status, headers, warnings) {
1942
+ const expected = isPlainObject(invariant.expected) ? invariant.expected : {};
1943
+ const headerContentType = headers["content-type"];
1944
+ if (typeof expected.bodyExact === "string") {
1945
+ const rawTrimmed = expected.bodyExact.trim();
1946
+ if (rawTrimmed.startsWith("{") || rawTrimmed.startsWith("[")) {
1947
+ try {
1948
+ const parsedExact = JSON.parse(rawTrimmed);
1949
+ const sanitizedObj = sanitizeJsonValue(parsedExact, 0, new Set(), warnings);
1950
+ return {
1951
+ bodyKind: "json",
1952
+ jsonBody: sanitizedObj,
1953
+ textBody: JSON.stringify(sanitizedObj),
1954
+ contentType: headerContentType || "application/json; charset=utf-8"
1955
+ };
1956
+ }
1957
+ catch {
1958
+ // fall through to plain text
1959
+ }
1960
+ }
1961
+ const body = sanitizeText(expected.bodyExact);
1962
+ return {
1963
+ bodyKind: "text",
1964
+ textBody: body,
1965
+ contentType: inferContentTypeForExactBody(body, headerContentType)
1966
+ };
1967
+ }
1968
+ const hasJsonSchema = isPlainObject(expected.jsonSchema);
1969
+ const hasJsonSubset = expected.jsonSubset !== undefined;
1970
+ const hasJsonPaths = Array.isArray(expected.jsonPaths) && expected.jsonPaths.length > 0;
1971
+ if (hasJsonSchema || hasJsonSubset || hasJsonPaths) {
1972
+ let payload;
1973
+ if (hasJsonSchema) {
1974
+ const sanitizedSchema = sanitizeSchemaForSynthesis(expected.jsonSchema, 0, new Set(), { nodes: 0 }, warnings) ?? {};
1975
+ const state = { seen: new Set(), seenRefs: new Set(), nodes: 0, warnings };
1976
+ payload = synthesizeFromJsonSchema(sanitizedSchema, sanitizedSchema, 0, 0, true, state);
1977
+ }
1978
+ else if (hasJsonSubset) {
1979
+ payload = sanitizeJsonValue(expected.jsonSubset, 0, new Set(), warnings);
1980
+ }
1981
+ else {
1982
+ const firstPath = expected.jsonPaths[0]?.path;
1983
+ payload = typeof firstPath === "string" && firstPath.startsWith("$[") ? [] : {};
1984
+ }
1985
+ if (hasJsonSchema && hasJsonSubset) {
1986
+ payload = deepMergeJson(payload, expected.jsonSubset, 0, warnings);
1987
+ }
1988
+ if (hasJsonPaths) {
1989
+ payload = applyJsonPathAssertions(payload, expected.jsonPaths, warnings);
1990
+ }
1991
+ payload = sanitizeJsonValue(payload, 0, new Set(), warnings);
1992
+ return {
1993
+ bodyKind: "json",
1994
+ jsonBody: payload,
1995
+ textBody: JSON.stringify(payload),
1996
+ contentType: headerContentType || "application/json; charset=utf-8"
1997
+ };
1998
+ }
1999
+ const containsList = typeof expected.bodyContains === "string"
2000
+ ? expected.bodyContains.length > 0
2001
+ ? [expected.bodyContains]
2002
+ : []
2003
+ : Array.isArray(expected.bodyContains)
2004
+ ? expected.bodyContains.filter((s) => typeof s === "string" && s.length > 0)
2005
+ : [];
2006
+ if (containsList.length > 0) {
2007
+ return {
2008
+ bodyKind: "text",
2009
+ textBody: containsList.map((snippet) => sanitizeText(snippet)).join("\n"),
2010
+ contentType: headerContentType || "text/plain; charset=utf-8"
2011
+ };
2012
+ }
2013
+ if (status === 204 || status === 304) {
2014
+ return {
2015
+ bodyKind: "empty",
2016
+ textBody: "",
2017
+ contentType: headerContentType || "text/plain; charset=utf-8"
2018
+ };
2019
+ }
2020
+ return {
2021
+ bodyKind: "json",
2022
+ jsonBody: {},
2023
+ textBody: "{}",
2024
+ contentType: headerContentType || "application/json; charset=utf-8"
2025
+ };
2026
+ }
2027
+ function renderLandmarkHtml(landmark, extraInnerHtml = "") {
2028
+ const rawTag = String(landmark.tag || "").trim().toLowerCase();
2029
+ if (!rawTag || !SAFE_HTML_TAG_RE.test(rawTag) || DISALLOWED_LANDMARK_TAGS.has(rawTag)) {
2030
+ return "";
2031
+ }
2032
+ const text = typeof landmark.textContains === "string" && landmark.textContains.length > 0
2033
+ ? sanitizeText(landmark.textContains)
2034
+ : rawTag;
2035
+ const escapedText = escapeHtmlText(text);
2036
+ if (rawTag === "ul") {
2037
+ return ` <ul><li>${escapedText}</li>${extraInnerHtml}</ul>`;
2038
+ }
2039
+ if (rawTag === "table") {
2040
+ return ` <table><tbody><tr><td>${escapedText}</td></tr></tbody></table>`;
2041
+ }
2042
+ if (rawTag === "form") {
2043
+ return ` <form><span>${escapedText}</span>${extraInnerHtml}</form>`;
2044
+ }
2045
+ return ` <${rawTag}>${escapedText}${extraInnerHtml}</${rawTag}>`;
2046
+ }
2047
+ function renderInteractiveLandmarkHtml(item) {
2048
+ const tag = String(item.tag || "").trim().toLowerCase();
2049
+ const role = String(item.role || "").trim().toLowerCase();
2050
+ const name = typeof item.name === "string" && item.name.trim().length > 0 ? sanitizeText(item.name.trim()) : "";
2051
+ const ariaAttr = name ? ` aria-label="${escapeHtmlAttr(name)}"` : "";
2052
+ if (tag === "a" || (!tag && role === "link")) {
2053
+ const roleAttr = role && role !== "link" ? ` role="${escapeHtmlAttr(role)}"` : "";
2054
+ return ` <a href="#"${roleAttr}${ariaAttr}>${escapeHtmlText(name || "Link")}</a>`;
2055
+ }
2056
+ if (tag === "button" || (!tag && role === "button")) {
2057
+ const roleAttr = role && role !== "button" ? ` role="${escapeHtmlAttr(role)}"` : "";
2058
+ return ` <button type="button"${roleAttr}${ariaAttr}>${escapeHtmlText(name || "Action")}</button>`;
2059
+ }
2060
+ if (tag === "input" || (!tag && (role === "textbox" || role === "checkbox" || role === "radio"))) {
2061
+ const inputType = role === "checkbox" ? "checkbox" : role === "radio" ? "radio" : role === "button" ? "button" : "text";
2062
+ const placeholderAttr = name ? ` placeholder="${escapeHtmlAttr(name)}"` : "";
2063
+ return ` <input type="${inputType}"${ariaAttr}${placeholderAttr} />`;
2064
+ }
2065
+ if (tag === "select" || (!tag && role === "combobox")) {
2066
+ return ` <select${ariaAttr}><option>${escapeHtmlText(name || "Option")}</option></select>`;
2067
+ }
2068
+ if (tag === "textarea") {
2069
+ const placeholderAttr = name ? ` placeholder="${escapeHtmlAttr(name)}"` : "";
2070
+ return ` <textarea${ariaAttr}${placeholderAttr}></textarea>`;
2071
+ }
2072
+ const safeTag = tag && SAFE_HTML_TAG_RE.test(tag) && !DISALLOWED_LANDMARK_TAGS.has(tag) ? tag : "div";
2073
+ const roleAttr = role ? ` role="${escapeHtmlAttr(role)}"` : "";
2074
+ return ` <${safeTag}${roleAttr}${ariaAttr}>${escapeHtmlText(name || role || "Control")}</${safeTag}>`;
2075
+ }
2076
+ function synthesizeWebRouteHtml(fallbackTitle, invariant) {
2077
+ const expected = isPlainObject(invariant.expected) ? invariant.expected : {};
2078
+ const rawTitle = (typeof expected.titleContains === "string" && expected.titleContains.length > 0
2079
+ ? expected.titleContains
2080
+ : undefined) || fallbackTitle;
2081
+ const title = sanitizeSingleLine(rawTitle, 160) || "Contract Server";
2082
+ const requiredLandmarks = Array.isArray(expected.landmarks)
2083
+ ? expected.landmarks.filter((lm) => isPlainObject(lm) &&
2084
+ typeof lm.tag === "string" &&
2085
+ lm.required !== false &&
2086
+ SAFE_HTML_TAG_RE.test(lm.tag.trim().toLowerCase()) &&
2087
+ !DISALLOWED_LANDMARK_TAGS.has(lm.tag.trim().toLowerCase()))
2088
+ : [];
2089
+ const interactiveLandmarks = Array.isArray(expected.interactiveLandmarks)
2090
+ ? expected.interactiveLandmarks.filter((il) => isPlainObject(il) && (typeof il.role === "string" || typeof il.tag === "string"))
2091
+ : [];
2092
+ const visibleSnippets = [];
2093
+ if (Array.isArray(expected.visibleText)) {
2094
+ for (const s of expected.visibleText) {
2095
+ if (typeof s === "string" && s.length > 0)
2096
+ visibleSnippets.push(sanitizeText(s));
2097
+ }
2098
+ }
2099
+ if (typeof expected.bodyContains === "string" && expected.bodyContains.length > 0) {
2100
+ visibleSnippets.push(sanitizeText(expected.bodyContains));
2101
+ }
2102
+ else if (Array.isArray(expected.bodyContains)) {
2103
+ for (const s of expected.bodyContains) {
2104
+ if (typeof s === "string" && s.length > 0)
2105
+ visibleSnippets.push(sanitizeText(s));
2106
+ }
2107
+ }
2108
+ const hasMainLandmark = requiredLandmarks.some((lm) => lm.tag.trim().toLowerCase() === "main");
2109
+ const hasOnlyParagraphLandmarks = requiredLandmarks.length > 0 &&
2110
+ requiredLandmarks.every((lm) => !LANDMARK_EXTRACTOR_TAGS.has(lm.tag.trim().toLowerCase()));
2111
+ const extraSnippetsHtml = visibleSnippets.map((s) => ` <div>${escapeHtmlText(s)}</div>`).join("\n");
2112
+ const interactiveHtml = interactiveLandmarks.map((il) => renderInteractiveLandmarkHtml(il)).join("\n");
2113
+ const bodyLines = [];
2114
+ let appendedMainExtras = false;
2115
+ for (const lm of requiredLandmarks) {
2116
+ const tag = lm.tag.trim().toLowerCase();
2117
+ if (tag === "main" && !appendedMainExtras && (extraSnippetsHtml || interactiveHtml)) {
2118
+ appendedMainExtras = true;
2119
+ const innerParts = [extraSnippetsHtml, interactiveHtml].filter(Boolean).join("\n");
2120
+ bodyLines.push(renderLandmarkHtml(lm, `\n${innerParts}\n `));
2121
+ }
2122
+ else {
2123
+ const rendered = renderLandmarkHtml(lm);
2124
+ if (rendered)
2125
+ bodyLines.push(rendered);
2126
+ }
2127
+ }
2128
+ if (!hasMainLandmark) {
2129
+ if (extraSnippetsHtml || interactiveHtml) {
2130
+ if (hasOnlyParagraphLandmarks && !extraSnippetsHtml) {
2131
+ bodyLines.push(` <div data-scaffold-controls="true">\n${interactiveHtml}\n </div>`);
2132
+ }
2133
+ else {
2134
+ const innerParts = [extraSnippetsHtml, interactiveHtml].filter(Boolean).join("\n");
2135
+ bodyLines.push(` <main>\n${innerParts}\n </main>`);
2136
+ }
2137
+ }
2138
+ else if (bodyLines.length === 0) {
2139
+ bodyLines.push(` <main>${escapeHtmlText(title)}</main>`);
2140
+ }
2141
+ }
2142
+ return [
2143
+ "<!DOCTYPE html>",
2144
+ '<html lang="en">',
2145
+ "<head>",
2146
+ ' <meta charset="utf-8">',
2147
+ ` <title>${escapeHtmlText(title)}</title>`,
2148
+ "</head>",
2149
+ "<body>",
2150
+ ...bodyLines,
2151
+ "</body>",
2152
+ "</html>"
2153
+ ].join("\n");
2154
+ }
2155
+ // ============================================================================
2156
+ // Contract Normalization
2157
+ // ============================================================================
2158
+ function normalizeServerModel(contract, options) {
2159
+ if (!isPlainObject(contract) || !Array.isArray(contract.invariants)) {
2160
+ throw new VibecodeError("CONTRACT_INVALID", "exportServerScaffold requires a valid contract object with an invariants array.", { fallbackHint: "Load or normalize a ContractV02 object before exporting a server scaffold." });
2161
+ }
2162
+ let port = DEFAULT_PORT;
2163
+ if (options.port !== undefined) {
2164
+ if (typeof options.port !== "number" ||
2165
+ !Number.isInteger(options.port) ||
2166
+ options.port < 0 ||
2167
+ options.port > 65535) {
2168
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid server port "${sanitizeSingleLine(String(options.port), 64)}". Port must be an integer between 0 and 65535.`, { fallbackHint: "Pass an integer port such as 3000 or 0 for ephemeral binding." });
2169
+ }
2170
+ port = options.port;
2171
+ }
2172
+ const strict = options.strict === true;
2173
+ const targetNameRaw = isPlainObject(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()
2174
+ ? contract.target.name.trim()
2175
+ : "Contract Target";
2176
+ const targetName = sanitizeSingleLine(targetNameRaw, 120) || "Contract Target";
2177
+ const titleRaw = typeof options.title === "string" && options.title.trim()
2178
+ ? options.title.trim()
2179
+ : `${targetName} Server`;
2180
+ const title = sanitizeSingleLine(titleRaw, 160) || "Contract Server";
2181
+ const routes = [];
2182
+ const skippedInvariants = [];
2183
+ const warnings = [];
2184
+ let httpCount = 0;
2185
+ let webCount = 0;
2186
+ for (let i = 0; i < contract.invariants.length; i++) {
2187
+ const inv = contract.invariants[i];
2188
+ if (!isPlainObject(inv))
2189
+ continue;
2190
+ // 100% Holdout Invisibility: never emit routes, counts, warnings, or skippedInvariants.
2191
+ if (inv.holdout === true) {
2192
+ continue;
2193
+ }
2194
+ const invId = typeof inv.id === "string" && inv.id.trim()
2195
+ ? sanitizeSingleLine(inv.id.trim(), 80)
2196
+ : `inv-${i + 1}`;
2197
+ const type = typeof inv.type === "string" ? inv.type : "";
2198
+ const input = isPlainObject(inv.input) ? inv.input : {};
2199
+ const expected = isPlainObject(inv.expected) ? inv.expected : {};
2200
+ const description = typeof inv.description === "string" && inv.description.trim()
2201
+ ? sanitizeSingleLine(inv.description.trim(), 180)
2202
+ : invId;
2203
+ if (type === "http") {
2204
+ const rawMethod = typeof input.method === "string" && input.method.trim()
2205
+ ? input.method.trim().toUpperCase()
2206
+ : "GET";
2207
+ if (!SUPPORTED_HTTP_METHODS.has(rawMethod)) {
2208
+ skippedInvariants.push({
2209
+ id: invId,
2210
+ reason: `Unsupported HTTP method "${sanitizeSingleLine(rawMethod, 32)}"`
2211
+ });
2212
+ warnings.push(`Skipped HTTP invariant "${invId}" due to unsupported HTTP method.`);
2213
+ continue;
2214
+ }
2215
+ const rawPath = (typeof input.path === "string" && input.path.trim() ? input.path : undefined) ??
2216
+ (typeof input.urlPath === "string" && input.urlPath.trim() ? input.urlPath : undefined) ??
2217
+ "/";
2218
+ const { path: cleanPath, query } = parsePathAndQuery(rawPath, isPlainObject(input.query) ? input.query : undefined);
2219
+ const compiledPath = compilePathSegments(cleanPath);
2220
+ const status = resolveExpectedStatus(expected.status);
2221
+ const headers = sanitizeResponseHeaders(expected.headers);
2222
+ const synthesized = synthesizeHttpResponse(inv, status, headers, warnings);
2223
+ const requestSchema = strict ? deriveRequestSchema(input, rawMethod, warnings) : undefined;
2224
+ routes.push({
2225
+ id: invId,
2226
+ kind: "http",
2227
+ description,
2228
+ method: rawMethod,
2229
+ path: cleanPath,
2230
+ expressPath: compiledPath.expressPath,
2231
+ segments: compiledPath.segments,
2232
+ staticSegmentCount: compiledPath.staticSegmentCount,
2233
+ paramCount: compiledPath.paramCount,
2234
+ query,
2235
+ status,
2236
+ headers,
2237
+ contentType: synthesized.contentType,
2238
+ bodyKind: synthesized.bodyKind,
2239
+ ...(synthesized.bodyKind === "json" ? { jsonBody: synthesized.jsonBody } : {}),
2240
+ textBody: synthesized.textBody,
2241
+ ...(requestSchema ? { requestSchema } : {})
2242
+ });
2243
+ httpCount += 1;
2244
+ }
2245
+ else if (type === "web_route") {
2246
+ const rawPath = (typeof input.urlPath === "string" && input.urlPath.trim() ? input.urlPath : undefined) ??
2247
+ (typeof input.path === "string" && input.path.trim() ? input.path : undefined) ??
2248
+ "/";
2249
+ const { path: cleanPath, query } = parsePathAndQuery(rawPath, isPlainObject(input.query) ? input.query : undefined);
2250
+ const compiledPath = compilePathSegments(cleanPath);
2251
+ const status = resolveExpectedStatus(expected.status);
2252
+ const headers = sanitizeResponseHeaders(expected.headers);
2253
+ const htmlBody = synthesizeWebRouteHtml(title, inv);
2254
+ const contentType = headers["content-type"] || "text/html; charset=utf-8";
2255
+ routes.push({
2256
+ id: invId,
2257
+ kind: "web_route",
2258
+ description,
2259
+ method: "GET",
2260
+ path: cleanPath,
2261
+ expressPath: compiledPath.expressPath,
2262
+ segments: compiledPath.segments,
2263
+ staticSegmentCount: compiledPath.staticSegmentCount,
2264
+ paramCount: compiledPath.paramCount,
2265
+ query,
2266
+ status,
2267
+ headers,
2268
+ contentType,
2269
+ bodyKind: "html",
2270
+ textBody: htmlBody
2271
+ });
2272
+ webCount += 1;
2273
+ }
2274
+ else {
2275
+ const safeType = sanitizeSingleLine(type || "unknown", 48) || "unknown";
2276
+ skippedInvariants.push({
2277
+ id: invId,
2278
+ reason: `Unsupported invariant type "${safeType}" for server scaffold`
2279
+ });
2280
+ }
2281
+ }
2282
+ if (routes.length === 0) {
2283
+ warnings.push("No visible http or web_route invariants were found to scaffold; server responds 404 to all requests.");
2284
+ }
2285
+ return {
2286
+ title,
2287
+ targetName,
2288
+ port,
2289
+ strict,
2290
+ routes,
2291
+ httpCount,
2292
+ webCount,
2293
+ skippedInvariants,
2294
+ warnings: [...new Set(warnings)]
2295
+ };
2296
+ }
2297
+ // ============================================================================
2298
+ // Renderer 1: Zero-Dep Standalone Node.js HTTP ESM Server (server.mjs)
2299
+ // ============================================================================
2300
+ function renderNodeHttpScaffold(model) {
2301
+ const serializedRoutes = model.routes.map((r) => ({
2302
+ id: r.id,
2303
+ kind: r.kind,
2304
+ method: r.method,
2305
+ path: r.path,
2306
+ segments: r.segments.map((s) => (s.isParam ? { p: true, n: s.paramName ?? "param" } : { p: false, v: s.raw })),
2307
+ staticCount: r.staticSegmentCount,
2308
+ paramCount: r.paramCount,
2309
+ query: r.query,
2310
+ status: r.status,
2311
+ headers: r.headers,
2312
+ contentType: r.contentType,
2313
+ bodyKind: r.bodyKind,
2314
+ body: r.bodyKind === "json" ? r.jsonBody : r.textBody,
2315
+ ...(r.requestSchema ? { requestSchema: r.requestSchema } : {})
2316
+ }));
2317
+ const lines = [
2318
+ "#!/usr/bin/env node",
2319
+ `// ${sanitizeCommentLine(model.title)} — Zero-Dependency Node.js HTTP Server Scaffold`,
2320
+ `// Generated by vibecode-anything (${model.routes.length} routes: ${model.httpCount} HTTP, ${model.webCount} Web; strict=${model.strict})`,
2321
+ `// Run: PORT=${model.port} node server.mjs`,
2322
+ "",
2323
+ 'import http from "node:http";',
2324
+ "",
2325
+ 'const HOST = "127.0.0.1";',
2326
+ `const DEFAULT_PORT = ${model.port};`,
2327
+ `const STRICT_MODE = ${model.strict ? "true" : "false"};`,
2328
+ "const MAX_BODY_BYTES = 1024 * 1024;",
2329
+ `const SERVER_TITLE = ${safeJsJson(model.title)};`,
2330
+ "",
2331
+ `const ROUTES = ${safeJsJson(serializedRoutes, 2)};`,
2332
+ "",
2333
+ "function resolvePort() {",
2334
+ ' const envVal = process.env.PORT;',
2335
+ ' if (envVal === undefined || envVal === "") return DEFAULT_PORT;',
2336
+ " const parsed = Number(envVal);",
2337
+ " return Number.isInteger(parsed) && parsed >= 0 && parsed <= 65535 ? parsed : DEFAULT_PORT;",
2338
+ "}",
2339
+ "",
2340
+ "function splitPathname(pathname) {",
2341
+ ' if (!pathname || pathname === "/") return [];',
2342
+ ' return pathname.split("/").filter(Boolean);',
2343
+ "}",
2344
+ "",
2345
+ "function matchRoutePath(route, reqSegments) {",
2346
+ " if (route.segments.length !== reqSegments.length) return null;",
2347
+ " const params = Object.create(null);",
2348
+ " for (let i = 0; i < route.segments.length; i++) {",
2349
+ " const seg = route.segments[i];",
2350
+ " const actual = reqSegments[i];",
2351
+ " if (seg.p) {",
2352
+ " if (!actual) return null;",
2353
+ " params[seg.n] = actual;",
2354
+ " } else if (seg.v !== actual) {",
2355
+ " return null;",
2356
+ " }",
2357
+ " }",
2358
+ " return params;",
2359
+ "}",
2360
+ "",
2361
+ "function scoreQueryMatch(routeQuery, searchParams) {",
2362
+ " const entries = Object.entries(routeQuery || {});",
2363
+ " if (entries.length === 0) return 0;",
2364
+ " let matched = 0;",
2365
+ " for (const [key, expectedVal] of entries) {",
2366
+ " if (!searchParams.has(key)) return -1;",
2367
+ " if (!searchParams.getAll(key).includes(expectedVal)) return -1;",
2368
+ " matched += 1;",
2369
+ " }",
2370
+ " return matched;",
2371
+ "}",
2372
+ "",
2373
+ "function selectRoute(method, pathname, searchParams) {",
2374
+ " const reqSegments = splitPathname(pathname);",
2375
+ " let best = null;",
2376
+ " let bestPathRank = -Infinity;",
2377
+ " let bestQueryScore = -Infinity;",
2378
+ " for (const route of ROUTES) {",
2379
+ " if (route.method !== method) continue;",
2380
+ " const params = matchRoutePath(route, reqSegments);",
2381
+ " if (params === null) continue;",
2382
+ " const queryScore = scoreQueryMatch(route.query, searchParams);",
2383
+ " const pathRank = (route.paramCount === 0 ? 100000 : 0) + route.staticCount * 100 - route.paramCount;",
2384
+ " if (pathRank > bestPathRank || (pathRank === bestPathRank && queryScore > bestQueryScore)) {",
2385
+ " bestPathRank = pathRank;",
2386
+ " bestQueryScore = queryScore;",
2387
+ " best = { route, params };",
2388
+ " }",
2389
+ " }",
2390
+ " return best;",
2391
+ "}",
2392
+ "",
2393
+ "function validateValueAgainstSchema(value, schema, path) {",
2394
+ " const errors = [];",
2395
+ " if (!schema || typeof schema !== 'object') return errors;",
2396
+ " const expectedType = schema.type;",
2397
+ " if (expectedType === 'null') {",
2398
+ " if (value !== null) errors.push(`${path}: expected null`);",
2399
+ " return errors;",
2400
+ " }",
2401
+ " if (expectedType === 'boolean') {",
2402
+ " if (typeof value !== 'boolean') errors.push(`${path}: expected boolean`);",
2403
+ " return errors;",
2404
+ " }",
2405
+ " if (expectedType === 'integer') {",
2406
+ " if (typeof value !== 'number' || !Number.isInteger(value)) errors.push(`${path}: expected integer`);",
2407
+ " return errors;",
2408
+ " }",
2409
+ " if (expectedType === 'number') {",
2410
+ " if (typeof value !== 'number' || !Number.isFinite(value)) errors.push(`${path}: expected number`);",
2411
+ " return errors;",
2412
+ " }",
2413
+ " if (expectedType === 'string') {",
2414
+ " if (typeof value !== 'string') errors.push(`${path}: expected string`);",
2415
+ " return errors;",
2416
+ " }",
2417
+ " if (expectedType === 'array') {",
2418
+ " if (!Array.isArray(value)) {",
2419
+ " errors.push(`${path}: expected array`);",
2420
+ " return errors;",
2421
+ " }",
2422
+ " if (schema.items) {",
2423
+ " for (let i = 0; i < value.length; i++) {",
2424
+ " errors.push(...validateValueAgainstSchema(value[i], schema.items, `${path}[${i}]`));",
2425
+ " }",
2426
+ " }",
2427
+ " return errors;",
2428
+ " }",
2429
+ " if (expectedType === 'object') {",
2430
+ " if (value === null || typeof value !== 'object' || Array.isArray(value)) {",
2431
+ " errors.push(`${path}: expected object`);",
2432
+ " return errors;",
2433
+ " }",
2434
+ " if (Array.isArray(schema.required)) {",
2435
+ " for (const reqKey of schema.required) {",
2436
+ " if (!Object.prototype.hasOwnProperty.call(value, reqKey)) {",
2437
+ " errors.push(`${path}.${reqKey}: required`);",
2438
+ " }",
2439
+ " }",
2440
+ " }",
2441
+ " if (schema.properties && typeof schema.properties === 'object') {",
2442
+ " for (const [propKey, propSchema] of Object.entries(schema.properties)) {",
2443
+ " if (Object.prototype.hasOwnProperty.call(value, propKey)) {",
2444
+ " errors.push(...validateValueAgainstSchema(value[propKey], propSchema, `${path}.${propKey}`));",
2445
+ " }",
2446
+ " }",
2447
+ " }",
2448
+ " if (schema.additionalProperties === false) {",
2449
+ " const declared = schema.properties && typeof schema.properties === 'object' ? schema.properties : {};",
2450
+ " for (const key of Object.keys(value)) {",
2451
+ " if (!Object.prototype.hasOwnProperty.call(declared, key)) {",
2452
+ " errors.push(`${path}.${key}: unexpected additional property`);",
2453
+ " }",
2454
+ " }",
2455
+ " }",
2456
+ " }",
2457
+ " return errors;",
2458
+ "}",
2459
+ "",
2460
+ "function readRequestBody(req) {",
2461
+ " return new Promise((resolve, reject) => {",
2462
+ " if (req.complete || req.readableEnded) {",
2463
+ ' resolve("");',
2464
+ " return;",
2465
+ " }",
2466
+ " const chunks = [];",
2467
+ " let total = 0;",
2468
+ " let aborted = false;",
2469
+ " req.on('data', (chunk) => {",
2470
+ " if (aborted) return;",
2471
+ " total += chunk.length;",
2472
+ " if (total > MAX_BODY_BYTES) {",
2473
+ " aborted = true;",
2474
+ " reject(new Error('Request body too large'));",
2475
+ " return;",
2476
+ " }",
2477
+ " chunks.push(chunk);",
2478
+ " });",
2479
+ " req.once('end', () => {",
2480
+ " if (!aborted) resolve(Buffer.concat(chunks).toString('utf8'));",
2481
+ " });",
2482
+ " req.once('error', (err) => {",
2483
+ " if (!aborted) reject(err);",
2484
+ " });",
2485
+ " });",
2486
+ "}",
2487
+ "",
2488
+ "function drainRequestBody(req) {",
2489
+ " return new Promise((resolve) => {",
2490
+ " if (req.complete || req.readableEnded) {",
2491
+ " resolve();",
2492
+ " return;",
2493
+ " }",
2494
+ " req.on('data', () => {});",
2495
+ " req.once('end', () => resolve());",
2496
+ " req.once('error', () => resolve());",
2497
+ " });",
2498
+ "}",
2499
+ "",
2500
+ "function sendJson(res, status, payload, extraHeaders = {}, isHead = false) {",
2501
+ " const text = JSON.stringify(payload);",
2502
+ " const headers = {",
2503
+ " ...extraHeaders,",
2504
+ ' "content-type": extraHeaders["content-type"] || "application/json; charset=utf-8",',
2505
+ ' "content-length": String(Buffer.byteLength(text, "utf8"))',
2506
+ " };",
2507
+ " res.writeHead(status, headers);",
2508
+ " res.end(isHead ? undefined : text);",
2509
+ "}",
2510
+ "",
2511
+ "export const server = http.createServer(async (req, res) => {",
2512
+ ' const method = String(req.method || "GET").trim().toUpperCase() || "GET";',
2513
+ ' let pathname = "/";',
2514
+ " let searchParams = new URLSearchParams();",
2515
+ " try {",
2516
+ ' const rawUrl = typeof req.url === "string" && req.url.length > 0 ? req.url : "/";',
2517
+ ' const safeUrl = rawUrl.startsWith("/") ? rawUrl.replace(/^\\/+/, "/") : `/${rawUrl}`;',
2518
+ ' const parsed = new URL(safeUrl, "http://127.0.0.1");',
2519
+ ' pathname = parsed.pathname || "/";',
2520
+ " searchParams = parsed.searchParams;",
2521
+ " } catch {",
2522
+ ' pathname = "/";',
2523
+ " }",
2524
+ "",
2525
+ " const match = selectRoute(method, pathname, searchParams);",
2526
+ " if (!match) {",
2527
+ " await drainRequestBody(req);",
2528
+ ' sendJson(res, 404, { error: "not_found", server: SERVER_TITLE, method, path: pathname }, {}, method === "HEAD");',
2529
+ " return;",
2530
+ " }",
2531
+ "",
2532
+ " const { route } = match;",
2533
+ ' const reqContentType = String(req.headers["content-type"] || "").toLowerCase();',
2534
+ ' const isWriteMethod = method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE";',
2535
+ ' if (STRICT_MODE && (route.requestSchema || (isWriteMethod && reqContentType.includes("application/json")))) {',
2536
+ " let rawBody = '';",
2537
+ " try {",
2538
+ " rawBody = await readRequestBody(req);",
2539
+ " } catch (err) {",
2540
+ ' sendJson(res, 400, { error: "invalid_request_body", details: [String(err?.message || "Failed to read request body")] });',
2541
+ " return;",
2542
+ " }",
2543
+ " const trimmed = rawBody.trim();",
2544
+ " if (!trimmed) {",
2545
+ " if (route.requestSchema) {",
2546
+ ' sendJson(res, 400, { error: "invalid_request_body", details: ["$: request body is required"] });',
2547
+ " return;",
2548
+ " }",
2549
+ " } else {",
2550
+ " let parsedBody;",
2551
+ " try {",
2552
+ " parsedBody = JSON.parse(trimmed);",
2553
+ " } catch {",
2554
+ ' sendJson(res, 400, { error: "invalid_request_body", details: ["$: body must be valid JSON"] });',
2555
+ " return;",
2556
+ " }",
2557
+ " if (route.requestSchema) {",
2558
+ ' const validationErrors = validateValueAgainstSchema(parsedBody, route.requestSchema, "$");',
2559
+ " if (validationErrors.length > 0) {",
2560
+ ' sendJson(res, 400, { error: "invalid_request_body", details: validationErrors });',
2561
+ " return;",
2562
+ " }",
2563
+ " }",
2564
+ " }",
2565
+ " } else {",
2566
+ " await drainRequestBody(req);",
2567
+ " }",
2568
+ "",
2569
+ " if (route.status === 204 || route.status === 304) {",
2570
+ " const headers = { ...route.headers };",
2571
+ " res.writeHead(route.status, headers);",
2572
+ " res.end();",
2573
+ " return;",
2574
+ " }",
2575
+ "",
2576
+ ' const isHead = method === "HEAD";',
2577
+ ' if (route.bodyKind === "json") {',
2578
+ " sendJson(",
2579
+ " res,",
2580
+ " route.status,",
2581
+ " route.body,",
2582
+ ' { ...route.headers, "content-type": route.contentType },',
2583
+ " isHead",
2584
+ " );",
2585
+ " return;",
2586
+ " }",
2587
+ "",
2588
+ ' const bodyText = typeof route.body === "string" ? route.body : "";',
2589
+ " const outHeaders = {",
2590
+ " ...route.headers,",
2591
+ ' "content-type": route.contentType,',
2592
+ ' "content-length": String(Buffer.byteLength(bodyText, "utf8"))',
2593
+ " };",
2594
+ " res.writeHead(route.status, outHeaders);",
2595
+ " res.end(isHead ? undefined : bodyText);",
2596
+ "});",
2597
+ "",
2598
+ "const listenPort = resolvePort();",
2599
+ "server.listen(listenPort, HOST, () => {",
2600
+ " const addr = server.address();",
2601
+ ' const boundPort = addr && typeof addr === "object" ? addr.port : listenPort;',
2602
+ ' process.stdout.write(JSON.stringify({ ok: true, url: `http://${HOST}:${boundPort}` }) + "\\n");',
2603
+ "});",
2604
+ "",
2605
+ "for (const sig of ['SIGINT', 'SIGTERM']) {",
2606
+ " process.on(sig, () => {",
2607
+ " server.close(() => process.exit(0));",
2608
+ " server.closeAllConnections?.();",
2609
+ " });",
2610
+ "}",
2611
+ ""
2612
+ ];
2613
+ return lines.join("\n");
2614
+ }
2615
+ function groupRoutesForExpress(routes) {
2616
+ const map = new Map();
2617
+ for (const route of routes) {
2618
+ const key = `${route.method} ${route.expressPath}`;
2619
+ let group = map.get(key);
2620
+ if (!group) {
2621
+ group = {
2622
+ method: route.method,
2623
+ expressPath: route.expressPath,
2624
+ staticSegmentCount: route.staticSegmentCount,
2625
+ paramCount: route.paramCount,
2626
+ variants: []
2627
+ };
2628
+ map.set(key, group);
2629
+ }
2630
+ group.variants.push(route);
2631
+ }
2632
+ const groups = [...map.values()];
2633
+ // Register static paths before parameterized paths so Express matches specific routes first.
2634
+ groups.sort((a, b) => {
2635
+ const aStatic = a.paramCount === 0 ? 1 : 0;
2636
+ const bStatic = b.paramCount === 0 ? 1 : 0;
2637
+ if (aStatic !== bStatic)
2638
+ return bStatic - aStatic;
2639
+ if (a.staticSegmentCount !== b.staticSegmentCount)
2640
+ return b.staticSegmentCount - a.staticSegmentCount;
2641
+ return a.paramCount - b.paramCount;
2642
+ });
2643
+ return groups;
2644
+ }
2645
+ function expressMethodName(method) {
2646
+ switch (method) {
2647
+ case "GET":
2648
+ return "get";
2649
+ case "POST":
2650
+ return "post";
2651
+ case "PUT":
2652
+ return "put";
2653
+ case "PATCH":
2654
+ return "patch";
2655
+ case "DELETE":
2656
+ return "delete";
2657
+ case "HEAD":
2658
+ return "head";
2659
+ case "OPTIONS":
2660
+ return "options";
2661
+ default:
2662
+ return "all";
2663
+ }
2664
+ }
2665
+ function renderExpressTsScaffold(model) {
2666
+ const groups = groupRoutesForExpress(model.routes);
2667
+ const lines = [
2668
+ `// ${sanitizeCommentLine(model.title)} — Strict TypeScript Express Server Scaffold`,
2669
+ `// Generated by vibecode-anything (${model.routes.length} routes: ${model.httpCount} HTTP, ${model.webCount} Web; strict=${model.strict})`,
2670
+ "// Install dependencies: npm install express && npm install -D @types/express typescript",
2671
+ `// Run: PORT=${model.port} npx tsx server.ts`,
2672
+ "",
2673
+ 'import express from "express";',
2674
+ 'import type { NextFunction, Request, RequestHandler, Response } from "express";',
2675
+ "",
2676
+ 'const HOST = "127.0.0.1";',
2677
+ `const DEFAULT_PORT = ${model.port};`,
2678
+ `const SERVER_TITLE = ${safeJsJson(model.title)};`,
2679
+ "",
2680
+ "export interface RequestBodySchema {",
2681
+ ' type: "object" | "array" | "string" | "number" | "integer" | "boolean" | "null";',
2682
+ " required?: string[];",
2683
+ " properties?: Record<string, RequestBodySchema>;",
2684
+ " items?: RequestBodySchema;",
2685
+ " additionalProperties?: boolean;",
2686
+ "}",
2687
+ "",
2688
+ "export interface RouteVariant {",
2689
+ " id: string;",
2690
+ " query: Record<string, string>;",
2691
+ " status: number;",
2692
+ " headers: Record<string, string>;",
2693
+ " contentType: string;",
2694
+ ' bodyKind: "json" | "text" | "html" | "empty";',
2695
+ " body: unknown;",
2696
+ " requestSchema?: RequestBodySchema;",
2697
+ "}",
2698
+ "",
2699
+ "function resolvePort(): number {",
2700
+ " const envVal = process.env.PORT;",
2701
+ ' if (envVal === undefined || envVal === "") return DEFAULT_PORT;',
2702
+ " const parsed = Number(envVal);",
2703
+ " return Number.isInteger(parsed) && parsed >= 0 && parsed <= 65535 ? parsed : DEFAULT_PORT;",
2704
+ "}",
2705
+ "",
2706
+ "function queryValuesForKey(queryObj: Request['query'], key: string): string[] {",
2707
+ " const raw = queryObj[key];",
2708
+ " if (typeof raw === 'string') return [raw];",
2709
+ " if (Array.isArray(raw)) {",
2710
+ " return raw.filter((item): item is string => typeof item === 'string');",
2711
+ " }",
2712
+ " return [];",
2713
+ "}",
2714
+ "",
2715
+ "function selectVariant(variants: readonly RouteVariant[], reqQuery: Request['query']): RouteVariant {",
2716
+ " let best = variants[0];",
2717
+ " let bestScore = -Infinity;",
2718
+ " for (const variant of variants) {",
2719
+ " const entries = Object.entries(variant.query);",
2720
+ " let score = 0;",
2721
+ " if (entries.length > 0) {",
2722
+ " for (const [k, expected] of entries) {",
2723
+ " const actual = queryValuesForKey(reqQuery, k);",
2724
+ " if (!actual.includes(expected)) {",
2725
+ " score = -1;",
2726
+ " break;",
2727
+ " }",
2728
+ " score += 1;",
2729
+ " }",
2730
+ " }",
2731
+ " if (score > bestScore) {",
2732
+ " bestScore = score;",
2733
+ " best = variant;",
2734
+ " }",
2735
+ " }",
2736
+ " return best;",
2737
+ "}",
2738
+ "",
2739
+ "function sendVariantResponse(req: Request, res: Response, variant: RouteVariant): void {",
2740
+ " for (const [k, v] of Object.entries(variant.headers)) {",
2741
+ " res.setHeader(k, v);",
2742
+ " }",
2743
+ " if (variant.status === 204 || variant.status === 304) {",
2744
+ " res.status(variant.status).end();",
2745
+ " return;",
2746
+ " }",
2747
+ ' res.setHeader("content-type", variant.contentType);',
2748
+ ' if (req.method.toUpperCase() === "HEAD") {',
2749
+ " res.status(variant.status).end();",
2750
+ " return;",
2751
+ " }",
2752
+ ' if (variant.bodyKind === "json") {',
2753
+ " res.status(variant.status).send(JSON.stringify(variant.body));",
2754
+ " return;",
2755
+ " }",
2756
+ ' res.status(variant.status).send(typeof variant.body === "string" ? variant.body : "");',
2757
+ "}"
2758
+ ];
2759
+ if (model.strict) {
2760
+ lines.push("", "function validateValue(value: unknown, schema: RequestBodySchema, path: string): string[] {", " const errors: string[] = [];", ' if (schema.type === "null") {', ' if (value !== null) errors.push(`${path}: expected null`);', " return errors;", " }", ' if (schema.type === "boolean") {', ' if (typeof value !== "boolean") errors.push(`${path}: expected boolean`);', " return errors;", " }", ' if (schema.type === "integer") {', ' if (typeof value !== "number" || !Number.isInteger(value)) errors.push(`${path}: expected integer`);', " return errors;", " }", ' if (schema.type === "number") {', ' if (typeof value !== "number" || !Number.isFinite(value)) errors.push(`${path}: expected number`);', " return errors;", " }", ' if (schema.type === "string") {', ' if (typeof value !== "string") errors.push(`${path}: expected string`);', " return errors;", " }", ' if (schema.type === "array") {', " if (!Array.isArray(value)) {", ' errors.push(`${path}: expected array`);', " return errors;", " }", " if (schema.items) {", " for (let i = 0; i < value.length; i++) {", " errors.push(...validateValue(value[i], schema.items, `${path}[${i}]`));", " }", " }", " return errors;", " }", ' if (value === null || typeof value !== "object" || Array.isArray(value)) {', ' errors.push(`${path}: expected object`);', " return errors;", " }", " const record = value as Record<string, unknown>;", " if (Array.isArray(schema.required)) {", " for (const reqKey of schema.required) {", " if (!Object.prototype.hasOwnProperty.call(record, reqKey)) {", ' errors.push(`${path}.${reqKey}: required`);', " }", " }", " }", " if (schema.properties) {", " for (const [propKey, propSchema] of Object.entries(schema.properties)) {", " if (Object.prototype.hasOwnProperty.call(record, propKey)) {", " errors.push(...validateValue(record[propKey], propSchema, `${path}.${propKey}`));", " }", " }", " }", " if (schema.additionalProperties === false) {", " const declared = schema.properties ?? {};", " for (const key of Object.keys(record)) {", " if (!Object.prototype.hasOwnProperty.call(declared, key)) {", ' errors.push(`${path}.${key}: unexpected additional property`);', " }", " }", " }", " return errors;", "}", "", "export function validateRequestBody(schema: RequestBodySchema): RequestHandler {", " return (req: Request, res: Response, next: NextFunction): void => {", " const errors = validateValue(req.body, schema, '$');", " if (errors.length > 0) {", ' res.status(400).json({ error: "invalid_request_body", details: errors });', " return;", " }", " next();", " };", "}");
2761
+ }
2762
+ lines.push("", "export const app = express();", 'app.use(express.json({ limit: "1mb" }));');
2763
+ if (model.strict) {
2764
+ lines.push("app.use((err: unknown, _req: Request, res: Response, next: NextFunction): void => {", " if (err instanceof SyntaxError) {", ' res.status(400).json({ error: "invalid_request_body", details: ["$: body must be valid JSON"] });', " return;", " }", " next(err);", "});");
2765
+ }
2766
+ lines.push("");
2767
+ for (let i = 0; i < groups.length; i++) {
2768
+ const group = groups[i];
2769
+ const fnMethod = expressMethodName(group.method);
2770
+ const variantsPayload = group.variants.map((v) => ({
2771
+ id: v.id,
2772
+ query: v.query,
2773
+ status: v.status,
2774
+ headers: v.headers,
2775
+ contentType: v.contentType,
2776
+ bodyKind: v.bodyKind,
2777
+ body: v.bodyKind === "json" ? v.jsonBody : v.textBody,
2778
+ ...(v.requestSchema ? { requestSchema: v.requestSchema } : {})
2779
+ }));
2780
+ const varName = `routeVariants_${i + 1}`;
2781
+ const firstDesc = sanitizeCommentLine(group.variants[0]?.description || `${group.method} ${group.expressPath}`);
2782
+ lines.push(`// ${group.method} ${sanitizeCommentLine(group.expressPath)} — ${firstDesc}`);
2783
+ lines.push(`const ${varName}: readonly RouteVariant[] = ${safeJsJson(variantsPayload, 2)};`);
2784
+ const singleStrictSchema = model.strict && group.variants.length === 1 && group.variants[0].requestSchema
2785
+ ? group.variants[0].requestSchema
2786
+ : undefined;
2787
+ if (singleStrictSchema) {
2788
+ lines.push(`app.${fnMethod}(`, ` ${safeJsJson(group.expressPath)},`, ` validateRequestBody(${safeJsJson(singleStrictSchema)}),`, " (req: Request, res: Response): void => {", ` const variant = selectVariant(${varName}, req.query);`, " sendVariantResponse(req, res, variant);", " }", ");");
2789
+ }
2790
+ else if (model.strict && group.variants.some((v) => v.requestSchema !== undefined)) {
2791
+ lines.push(`app.${fnMethod}(${safeJsJson(group.expressPath)}, (req: Request, res: Response): void => {`, ` const variant = selectVariant(${varName}, req.query);`, " if (variant.requestSchema) {", " const errors = validateValue(req.body, variant.requestSchema, '$');", " if (errors.length > 0) {", ' res.status(400).json({ error: "invalid_request_body", details: errors });', " return;", " }", " }", " sendVariantResponse(req, res, variant);", "});");
2792
+ }
2793
+ else {
2794
+ lines.push(`app.${fnMethod}(${safeJsJson(group.expressPath)}, (req: Request, res: Response): void => {`, ` const variant = selectVariant(${varName}, req.query);`, " sendVariantResponse(req, res, variant);", "});");
2795
+ }
2796
+ lines.push("");
2797
+ }
2798
+ lines.push("app.use((req: Request, res: Response): void => {", " res.status(404).json({", ' error: "not_found",', " server: SERVER_TITLE,", " method: req.method.toUpperCase(),", " path: req.path", " });", "});", "", "const listenPort = resolvePort();", "export const server = app.listen(listenPort, HOST, () => {", " const addr = server.address();", ' const boundPort = addr && typeof addr === "object" ? addr.port : listenPort;', ' process.stdout.write(JSON.stringify({ ok: true, url: `http://${HOST}:${boundPort}` }) + "\\n");', "});", "");
2799
+ return lines.join("\n");
2800
+ }
2801
+ // ============================================================================
2802
+ // Renderer 3: Zero-Dep Python 3 ThreadingHTTPServer Scaffold (server.py)
2803
+ // ============================================================================
2804
+ function renderPythonHttpScaffold(model) {
2805
+ const pyRoutes = model.routes.map((r) => ({
2806
+ id: r.id,
2807
+ kind: r.kind,
2808
+ method: r.method,
2809
+ path: r.path,
2810
+ segments: r.segments.map((s) => s.isParam ? { is_param: true, name: s.paramName ?? "param" } : { is_param: false, value: s.raw }),
2811
+ static_count: r.staticSegmentCount,
2812
+ param_count: r.paramCount,
2813
+ query: r.query,
2814
+ status: r.status,
2815
+ headers: r.headers,
2816
+ content_type: r.contentType,
2817
+ body_kind: r.bodyKind,
2818
+ body: r.bodyKind === "json" ? r.jsonBody : r.textBody,
2819
+ request_schema: r.requestSchema ?? null
2820
+ }));
2821
+ const lines = [
2822
+ "#!/usr/bin/env python3",
2823
+ `# ${sanitizeSingleLine(model.title, 160)} — Zero-Dependency Python 3 HTTP Server Scaffold`,
2824
+ `# Generated by vibecode-anything (${model.routes.length} routes: ${model.httpCount} HTTP, ${model.webCount} Web; strict=${model.strict})`,
2825
+ `# Run: PORT=${model.port} python3 server.py`,
2826
+ "",
2827
+ "import json",
2828
+ "import os",
2829
+ "import sys",
2830
+ "from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer",
2831
+ "from urllib.parse import parse_qs, urlsplit",
2832
+ "",
2833
+ 'HOST = "127.0.0.1"',
2834
+ `DEFAULT_PORT = ${model.port}`,
2835
+ `STRICT_MODE = ${model.strict ? "True" : "False"}`,
2836
+ "MAX_BODY_BYTES = 1024 * 1024",
2837
+ `SERVER_TITLE = ${safePyString(model.title)}`,
2838
+ "",
2839
+ `ROUTES = ${toPythonLiteral(pyRoutes, 0)}`,
2840
+ "",
2841
+ "",
2842
+ "def resolve_port() -> int:",
2843
+ ' raw = os.environ.get("PORT", "")',
2844
+ ' if raw == "":',
2845
+ " return DEFAULT_PORT",
2846
+ " try:",
2847
+ " port = int(raw)",
2848
+ " except ValueError:",
2849
+ " return DEFAULT_PORT",
2850
+ " return port if 0 <= port <= 65535 else DEFAULT_PORT",
2851
+ "",
2852
+ "",
2853
+ "def split_pathname(pathname: str) -> list:",
2854
+ ' if not pathname or pathname == "/":',
2855
+ " return []",
2856
+ ' return [seg for seg in pathname.split("/") if seg]',
2857
+ "",
2858
+ "",
2859
+ "def match_route_path(route: dict, req_segments: list):",
2860
+ ' segments = route["segments"]',
2861
+ " if len(segments) != len(req_segments):",
2862
+ " return None",
2863
+ " params = {}",
2864
+ " for seg, actual in zip(segments, req_segments):",
2865
+ ' if seg["is_param"]:',
2866
+ " if not actual:",
2867
+ " return None",
2868
+ ' params[seg["name"]] = actual',
2869
+ ' elif seg["value"] != actual:',
2870
+ " return None",
2871
+ " return params",
2872
+ "",
2873
+ "",
2874
+ "def score_query_match(route_query: dict, parsed_query: dict) -> int:",
2875
+ " if not route_query:",
2876
+ " return 0",
2877
+ " matched = 0",
2878
+ " for key, expected_val in route_query.items():",
2879
+ " actual_values = parsed_query.get(key)",
2880
+ " if not actual_values or expected_val not in actual_values:",
2881
+ " return -1",
2882
+ " matched += 1",
2883
+ " return matched",
2884
+ "",
2885
+ "",
2886
+ "def select_route(method: str, pathname: str, parsed_query: dict):",
2887
+ " req_segments = split_pathname(pathname)",
2888
+ " best = None",
2889
+ " best_path_rank = -10**9",
2890
+ " best_query_score = -10**9",
2891
+ " for route in ROUTES:",
2892
+ ' if route["method"] != method:',
2893
+ " continue",
2894
+ " params = match_route_path(route, req_segments)",
2895
+ " if params is None:",
2896
+ " continue",
2897
+ ' query_score = score_query_match(route["query"], parsed_query)',
2898
+ ' path_rank = (100000 if route["param_count"] == 0 else 0) + route["static_count"] * 100 - route["param_count"]',
2899
+ " if path_rank > best_path_rank or (path_rank == best_path_rank and query_score > best_query_score):",
2900
+ " best_path_rank = path_rank",
2901
+ " best_query_score = query_score",
2902
+ " best = (route, params)",
2903
+ " return best",
2904
+ "",
2905
+ "",
2906
+ "def validate_value(value, schema: dict, path: str) -> list:",
2907
+ " errors = []",
2908
+ " if not isinstance(schema, dict):",
2909
+ " return errors",
2910
+ ' expected_type = schema.get("type")',
2911
+ ' if expected_type == "null":',
2912
+ " if value is not None:",
2913
+ ' errors.append(f"{path}: expected null")',
2914
+ " return errors",
2915
+ ' if expected_type == "boolean":',
2916
+ " if not isinstance(value, bool):",
2917
+ ' errors.append(f"{path}: expected boolean")',
2918
+ " return errors",
2919
+ ' if expected_type == "integer":',
2920
+ " if isinstance(value, bool) or not isinstance(value, int):",
2921
+ ' errors.append(f"{path}: expected integer")',
2922
+ " return errors",
2923
+ ' if expected_type == "number":',
2924
+ " if isinstance(value, bool) or not isinstance(value, (int, float)):",
2925
+ ' errors.append(f"{path}: expected number")',
2926
+ " return errors",
2927
+ ' if expected_type == "string":',
2928
+ " if not isinstance(value, str):",
2929
+ ' errors.append(f"{path}: expected string")',
2930
+ " return errors",
2931
+ ' if expected_type == "array":',
2932
+ " if not isinstance(value, list):",
2933
+ ' errors.append(f"{path}: expected array")',
2934
+ " return errors",
2935
+ ' item_schema = schema.get("items")',
2936
+ " if isinstance(item_schema, dict):",
2937
+ " for idx, item in enumerate(value):",
2938
+ ' errors.extend(validate_value(item, item_schema, f"{path}[{idx}]"))',
2939
+ " return errors",
2940
+ ' if expected_type == "object":',
2941
+ " if not isinstance(value, dict):",
2942
+ ' errors.append(f"{path}: expected object")',
2943
+ " return errors",
2944
+ ' for req_key in schema.get("required") or []:',
2945
+ " if req_key not in value:",
2946
+ ' errors.append(f"{path}.{req_key}: required")',
2947
+ ' props = schema.get("properties") or {}',
2948
+ " for prop_key, prop_schema in props.items():",
2949
+ " if prop_key in value:",
2950
+ ' errors.extend(validate_value(value[prop_key], prop_schema, f"{path}.{prop_key}"))',
2951
+ ' if schema.get("additionalProperties") is False:',
2952
+ " for key in value.keys():",
2953
+ " if key not in props:",
2954
+ ' errors.append(f"{path}.{key}: unexpected additional property")',
2955
+ " return errors",
2956
+ "",
2957
+ "",
2958
+ "class ScaffoldHandler(BaseHTTPRequestHandler):",
2959
+ " def log_message(self, format, *args):",
2960
+ " return",
2961
+ "",
2962
+ " def _send_bytes(self, status: int, content_type: str, payload: bytes, extra_headers=None, is_head=False):",
2963
+ " self.send_response(status)",
2964
+ " if extra_headers:",
2965
+ " for k, v in extra_headers.items():",
2966
+ ' if k.lower() in ("content-type", "content-length"):',
2967
+ " continue",
2968
+ " self.send_header(k, str(v))",
2969
+ " if status not in (204, 304):",
2970
+ ' self.send_header("Content-Type", content_type)',
2971
+ ' self.send_header("Content-Length", str(len(payload)))',
2972
+ " self.end_headers()",
2973
+ " if status not in (204, 304) and not is_head:",
2974
+ " self.wfile.write(payload)",
2975
+ "",
2976
+ " def _handle_request(self, method: str):",
2977
+ " parsed = urlsplit(self.path or '/')",
2978
+ ' pathname = parsed.path or "/"',
2979
+ " parsed_query = parse_qs(parsed.query, keep_blank_values=True)",
2980
+ ' is_head = method == "HEAD"',
2981
+ "",
2982
+ " content_length = 0",
2983
+ ' raw_len = self.headers.get("Content-Length")',
2984
+ " if raw_len:",
2985
+ " try:",
2986
+ " content_length = max(0, int(raw_len))",
2987
+ " except ValueError:",
2988
+ " content_length = 0",
2989
+ " raw_body = b''",
2990
+ " if content_length > 0:",
2991
+ " if content_length > MAX_BODY_BYTES:",
2992
+ ' err_bytes = json.dumps({"error": "invalid_request_body", "details": ["Request body too large"]}).encode("utf-8")',
2993
+ ' self._send_bytes(400, "application/json; charset=utf-8", err_bytes, is_head=is_head)',
2994
+ " return",
2995
+ " raw_body = self.rfile.read(content_length)",
2996
+ "",
2997
+ " match = select_route(method, pathname, parsed_query)",
2998
+ " if match is None:",
2999
+ " not_found = json.dumps({",
3000
+ ' "error": "not_found",',
3001
+ ' "server": SERVER_TITLE,',
3002
+ ' "method": method,',
3003
+ ' "path": pathname,',
3004
+ ' }).encode("utf-8")',
3005
+ ' self._send_bytes(404, "application/json; charset=utf-8", not_found, is_head=is_head)',
3006
+ " return",
3007
+ "",
3008
+ " route, _params = match",
3009
+ ' req_schema = route.get("request_schema")',
3010
+ " if STRICT_MODE and req_schema is not None:",
3011
+ ' text = raw_body.decode("utf-8", errors="replace").strip()',
3012
+ " if not text:",
3013
+ ' err = json.dumps({"error": "invalid_request_body", "details": ["$: request body is required"]}).encode("utf-8")',
3014
+ ' self._send_bytes(400, "application/json; charset=utf-8", err, is_head=is_head)',
3015
+ " return",
3016
+ " try:",
3017
+ " parsed_body = json.loads(text)",
3018
+ " except json.JSONDecodeError:",
3019
+ ' err = json.dumps({"error": "invalid_request_body", "details": ["$: body must be valid JSON"]}).encode("utf-8")',
3020
+ ' self._send_bytes(400, "application/json; charset=utf-8", err, is_head=is_head)',
3021
+ " return",
3022
+ ' errors = validate_value(parsed_body, req_schema, "$")',
3023
+ " if errors:",
3024
+ ' err = json.dumps({"error": "invalid_request_body", "details": errors}).encode("utf-8")',
3025
+ ' self._send_bytes(400, "application/json; charset=utf-8", err, is_head=is_head)',
3026
+ " return",
3027
+ "",
3028
+ ' status = route["status"]',
3029
+ ' if status in (204, 304):',
3030
+ ' self._send_bytes(status, route["content_type"], b"", extra_headers=route["headers"], is_head=is_head)',
3031
+ " return",
3032
+ "",
3033
+ ' if route["body_kind"] == "json":',
3034
+ ' payload = json.dumps(route["body"]).encode("utf-8")',
3035
+ " else:",
3036
+ ' body_val = route["body"] if isinstance(route["body"], str) else ""',
3037
+ ' payload = body_val.encode("utf-8")',
3038
+ ' self._send_bytes(status, route["content_type"], payload, extra_headers=route["headers"], is_head=is_head)',
3039
+ "",
3040
+ ' def do_GET(self): self._handle_request("GET")',
3041
+ ' def do_POST(self): self._handle_request("POST")',
3042
+ ' def do_PUT(self): self._handle_request("PUT")',
3043
+ ' def do_PATCH(self): self._handle_request("PATCH")',
3044
+ ' def do_DELETE(self): self._handle_request("DELETE")',
3045
+ ' def do_HEAD(self): self._handle_request("HEAD")',
3046
+ ' def do_OPTIONS(self): self._handle_request("OPTIONS")',
3047
+ "",
3048
+ "",
3049
+ "def main() -> None:",
3050
+ " port = resolve_port()",
3051
+ " httpd = ThreadingHTTPServer((HOST, port), ScaffoldHandler)",
3052
+ " bound_port = httpd.server_address[1]",
3053
+ ' print(json.dumps({"ok": True, "url": f"http://{HOST}:{bound_port}"}), flush=True)',
3054
+ " try:",
3055
+ " httpd.serve_forever()",
3056
+ " except KeyboardInterrupt:",
3057
+ " pass",
3058
+ " finally:",
3059
+ " httpd.server_close()",
3060
+ "",
3061
+ "",
3062
+ 'if __name__ == "__main__":',
3063
+ " main()",
3064
+ ""
3065
+ ];
3066
+ return lines.join("\n");
3067
+ }
3068
+ // ============================================================================
3069
+ // Public Export API, Atomic Writer & Pretty Terminal Formatter
3070
+ // ============================================================================
3071
+ function formatMeta(format) {
3072
+ switch (format) {
3073
+ case "node-http":
3074
+ return { fileExtension: ".mjs", defaultFileName: "server.mjs" };
3075
+ case "express-ts":
3076
+ return { fileExtension: ".ts", defaultFileName: "server.ts" };
3077
+ case "python-http":
3078
+ return { fileExtension: ".py", defaultFileName: "server.py" };
3079
+ }
3080
+ }
3081
+ /**
3082
+ * Export a ContractV02 into a runnable standalone server scaffold
3083
+ * (`node-http`, `express-ts`, or `python-http`) with 100% holdout invisibility
3084
+ * and Day-1 secret/injection/prototype-pollution hardening.
3085
+ */
3086
+ export function exportServerScaffold(contract, options = {}) {
3087
+ const safeOptions = isPlainObject(options) ? options : {};
3088
+ const formatRaw = safeOptions.format ?? "node-http";
3089
+ if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
3090
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported server export format "${sanitizeSingleLine(String(formatRaw), 64)}". Supported formats: node-http, express-ts, python-http.`, { fallbackHint: 'Pass format: "node-http", "express-ts", or "python-http".' });
3091
+ }
3092
+ const format = formatRaw;
3093
+ const model = normalizeServerModel(contract, safeOptions);
3094
+ const { fileExtension, defaultFileName } = formatMeta(format);
3095
+ let content;
3096
+ if (format === "express-ts") {
3097
+ content = renderExpressTsScaffold(model);
3098
+ }
3099
+ else if (format === "python-http") {
3100
+ content = renderPythonHttpScaffold(model);
3101
+ }
3102
+ else {
3103
+ content = renderNodeHttpScaffold(model);
3104
+ }
3105
+ return {
3106
+ format,
3107
+ content,
3108
+ fileExtension,
3109
+ defaultFileName,
3110
+ routeCount: model.routes.length,
3111
+ httpCount: model.httpCount,
3112
+ webCount: model.webCount,
3113
+ skippedInvariants: model.skippedInvariants,
3114
+ warnings: model.warnings
3115
+ };
3116
+ }
3117
+ /**
3118
+ * Generate and atomically write a server scaffold to disk via temp file + rename.
3119
+ * Validates `outPath` upfront before running compilation or touching the filesystem.
3120
+ */
3121
+ export function writeServerScaffold(contract, outPath, options = {}) {
3122
+ if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
3123
+ throw new VibecodeError("CONTRACT_INVALID", "writeServerScaffold requires a valid non-empty outPath without NUL bytes.", { fallbackHint: "Pass a file path such as ./server.mjs, ./server.ts, or ./server.py." });
3124
+ }
3125
+ const resolvedOut = path.resolve(outPath.trim());
3126
+ if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
3127
+ throw new VibecodeError("CONTRACT_INVALID", `Cannot write server scaffold: "${sanitizeSingleLine(resolvedOut, 240)}" is a directory.`, { fallbackHint: "Pass a file path (for example `./server.mjs`), not a directory." });
3128
+ }
3129
+ const result = exportServerScaffold(contract, options);
3130
+ const parentDir = path.dirname(resolvedOut);
3131
+ fs.mkdirSync(parentDir, { recursive: true });
3132
+ const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
3133
+ try {
3134
+ fs.writeFileSync(tmpPath, result.content, "utf8");
3135
+ fs.renameSync(tmpPath, resolvedOut);
3136
+ }
3137
+ catch (err) {
3138
+ try {
3139
+ if (fs.existsSync(tmpPath)) {
3140
+ fs.rmSync(tmpPath, { force: true });
3141
+ }
3142
+ }
3143
+ catch {
3144
+ // ignore cleanup error
3145
+ }
3146
+ throw err;
3147
+ }
3148
+ return {
3149
+ ...result,
3150
+ outPath: resolvedOut
3151
+ };
3152
+ }
3153
+ function style(text, codes, useColor) {
3154
+ return useColor ? `${codes}${text}${ANSI.reset}` : text;
3155
+ }
3156
+ /**
3157
+ * Format a concise, sanitized terminal summary for a server scaffold export result.
3158
+ */
3159
+ export function formatPrettyServerExport(result, outPath, color = false) {
3160
+ const useColor = color === true;
3161
+ const lines = [];
3162
+ const banner = style("[SERVER EXPORT]", `${ANSI.bold}${ANSI.cyan}`, useColor);
3163
+ const fmtLabel = result.format === "express-ts"
3164
+ ? "Express TypeScript"
3165
+ : result.format === "python-http"
3166
+ ? "Python HTTP"
3167
+ : "Node.js HTTP";
3168
+ const safeExt = sanitizeSingleLine(result.fileExtension || "", 16);
3169
+ lines.push(`${banner} ${style(fmtLabel, ANSI.bold, useColor)} (${safeExt})`);
3170
+ const effectiveOut = (typeof outPath === "string" && outPath.trim()) ||
3171
+ (typeof result.outPath === "string" && result.outPath.trim()) ||
3172
+ "";
3173
+ if (effectiveOut) {
3174
+ lines.push(`Output: ${sanitizeSingleLine(effectiveOut, 240)}`);
3175
+ }
3176
+ const totalBytes = Buffer.byteLength(result.content || "", "utf8");
3177
+ const routeCountStr = style(`${result.routeCount} ${result.routeCount === 1 ? "route" : "routes"}`, result.routeCount > 0 ? ANSI.green : ANSI.yellow, useColor);
3178
+ const summaryParts = [
3179
+ routeCountStr,
3180
+ `${result.httpCount} HTTP`,
3181
+ `${result.webCount} Web`
3182
+ ];
3183
+ if (Array.isArray(result.skippedInvariants) && result.skippedInvariants.length > 0) {
3184
+ summaryParts.push(`${result.skippedInvariants.length} skipped`);
3185
+ }
3186
+ summaryParts.push(`${totalBytes} bytes`);
3187
+ lines.push(`Summary: ${summaryParts.join(", ")}`);
3188
+ if (Array.isArray(result.warnings) && result.warnings.length > 0) {
3189
+ lines.push("Warnings:");
3190
+ for (const warning of result.warnings.slice(0, MAX_PRETTY_WARNINGS)) {
3191
+ lines.push(` - ${style(sanitizeSingleLine(warning, 200), ANSI.yellow, useColor)}`);
3192
+ }
3193
+ if (result.warnings.length > MAX_PRETTY_WARNINGS) {
3194
+ lines.push(` ${style(`... and ${result.warnings.length - MAX_PRETTY_WARNINGS} more`, ANSI.dim, useColor)}`);
3195
+ }
3196
+ }
3197
+ return lines.join("\n");
3198
+ }