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,1074 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { VibecodeError } from "./errors.js";
5
+ import { isSensitiveHeader } from "../ingestors/trace.js";
6
+ const DEFAULT_YAML_INDENT = 2;
7
+ const DEFAULT_YAML_MAX_DEPTH = 32;
8
+ const MAX_SCHEMA_DEPTH = 16;
9
+ const MAX_SCHEMA_KEYS = 200;
10
+ const VALID_FORMATS = new Set(["yaml", "json"]);
11
+ const SUPPORTED_HTTP_METHODS = new Set([
12
+ "get",
13
+ "post",
14
+ "put",
15
+ "patch",
16
+ "delete",
17
+ "head",
18
+ "options"
19
+ ]);
20
+ const BODY_HTTP_METHODS = new Set(["post", "put", "patch", "delete"]);
21
+ const TRANSPORT_NOISE_HEADERS = new Set([
22
+ "content-type",
23
+ "accept",
24
+ "host",
25
+ "user-agent",
26
+ "content-length",
27
+ "connection"
28
+ ]);
29
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
30
+ const EXTRA_SENSITIVE_HEADER_RE = /^(?:api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|x[_-]access[_-]token|x[_-]session[_-]token|x[_-]secret|x[_-](?:csrf|xsrf)[_-]token|csrf[_-]token|xsrf[_-]token|authorization|proxy[_-]authorization|cookie|set[_-]cookie)$/i;
31
+ const SENSITIVE_QUERY_PARAM_RE = /^(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|secret|client[_-]?secret|password|passwd|auth|jwt|session[_-]?id|sig|signature|private[_-]?key)$/i;
32
+ const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credential|credentials|bearer)$/i;
33
+ const VAULT_PATH_RE = /(?:[A-Za-z]:)?[^\s"'`<>]*\.vibecode-vault[^\s"'`<>]*/gi;
34
+ const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
35
+ const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s@"'`<>]+)@/g;
36
+ const BEARER_OR_BASIC_VALUE_RE = /^\s*(?:bearer|basic)\s+\S+/i;
37
+ const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+\S+/gi;
38
+ const INLINE_BASIC_TOKEN_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi;
39
+ const YAML_RESERVED_WORD_RE = /^(?:true|false|yes|no|on|off|y|n|null|~)$/i;
40
+ const YAML_NUMBER_LIKE_RE = /^[+-]?(?:(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?|0[xXoObB][0-9a-fA-F_]+|\.(?:inf|nan))$/i;
41
+ const YAML_INDICATOR_START_RE = /^[-?:,[\]{}#&*!|>'"%@`~]/;
42
+ const YAML_CONTROL_OR_MULTILINE_RE = /[\x00-\x1f\x7f\u0085\u2028\u2029]/;
43
+ const YAML_PLAIN_COLON_HAZARD_RE = /:(?:[ \t#]|$)/;
44
+ const YAML_DOC_MARKER_RE = /^(?:---|\.\.\.)(?:$|[ \t])/;
45
+ const YAML_KEY_UNSAFE_CHAR_RE = /[:#[\],"'\\]/;
46
+ const HTTP_STATUS_DESCRIPTIONS = {
47
+ 200: "OK",
48
+ 201: "Created",
49
+ 202: "Accepted",
50
+ 204: "No Content",
51
+ 206: "Partial Content",
52
+ 301: "Moved Permanently",
53
+ 302: "Found",
54
+ 304: "Not Modified",
55
+ 307: "Temporary Redirect",
56
+ 308: "Permanent Redirect",
57
+ 400: "Bad Request",
58
+ 401: "Unauthorized",
59
+ 403: "Forbidden",
60
+ 404: "Not Found",
61
+ 405: "Method Not Allowed",
62
+ 409: "Conflict",
63
+ 410: "Gone",
64
+ 415: "Unsupported Media Type",
65
+ 422: "Unprocessable Entity",
66
+ 429: "Too Many Requests",
67
+ 500: "Internal Server Error",
68
+ 502: "Bad Gateway",
69
+ 503: "Service Unavailable",
70
+ 504: "Gateway Timeout"
71
+ };
72
+ function isRecord(value) {
73
+ return value !== null && typeof value === "object" && !Array.isArray(value);
74
+ }
75
+ function isForbiddenKey(key) {
76
+ return FORBIDDEN_KEYS.has(key);
77
+ }
78
+ function isSensitiveHeaderName(name) {
79
+ const trimmed = String(name).trim();
80
+ return isSensitiveHeader(trimmed) || EXTRA_SENSITIVE_HEADER_RE.test(trimmed);
81
+ }
82
+ function isSensitiveQueryName(name) {
83
+ return SENSITIVE_QUERY_PARAM_RE.test(String(name).trim());
84
+ }
85
+ function isSecretFieldName(name) {
86
+ const trimmed = String(name).trim();
87
+ return (SECRET_FIELD_NAME_RE.test(trimmed) ||
88
+ isSensitiveHeaderName(trimmed) ||
89
+ isSensitiveQueryName(trimmed));
90
+ }
91
+ function isAuthHeaderValue(value) {
92
+ return BEARER_OR_BASIC_VALUE_RE.test(value);
93
+ }
94
+ function redactVaultPaths(text) {
95
+ return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
96
+ }
97
+ function sanitizeUrlInText(rawUrl) {
98
+ const withoutVault = redactVaultPaths(rawUrl);
99
+ const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
100
+ try {
101
+ const parsed = new URL(withoutAuth);
102
+ parsed.username = "";
103
+ parsed.password = "";
104
+ const safeParams = new URLSearchParams();
105
+ for (const [k, v] of parsed.searchParams.entries()) {
106
+ if (isSensitiveQueryName(k))
107
+ continue;
108
+ safeParams.append(k, redactVaultPaths(v));
109
+ }
110
+ const serialized = safeParams.toString();
111
+ parsed.search = serialized ? `?${serialized}` : "";
112
+ return parsed.toString();
113
+ }
114
+ catch {
115
+ return withoutAuth;
116
+ }
117
+ }
118
+ function sanitizeText(raw) {
119
+ const noVault = redactVaultPaths(raw);
120
+ const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
121
+ const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
122
+ const noBearer = noBasicAuth.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
123
+ return noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
124
+ }
125
+ function sanitizeSingleLineText(raw) {
126
+ return sanitizeText(raw)
127
+ .replace(/[\r\n\u2028\u2029]+/g, " ")
128
+ .replace(/\s+/g, " ")
129
+ .trim();
130
+ }
131
+ function sanitizeServerUrl(raw) {
132
+ const trimmed = raw.trim();
133
+ if (!trimmed || /\.vibecode-vault/i.test(trimmed))
134
+ return null;
135
+ const withoutAuth = redactVaultPaths(trimmed).replace(URL_BASIC_AUTH_RE, "$1");
136
+ try {
137
+ const parsed = new URL(withoutAuth);
138
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
139
+ return null;
140
+ parsed.username = "";
141
+ parsed.password = "";
142
+ parsed.search = "";
143
+ parsed.hash = "";
144
+ const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
145
+ return `${parsed.origin}${cleanPath}`;
146
+ }
147
+ catch {
148
+ return null;
149
+ }
150
+ }
151
+ function formatDoubleQuotedYaml(str) {
152
+ let out = "\"";
153
+ for (let i = 0; i < str.length; i++) {
154
+ const ch = str[i];
155
+ const code = str.charCodeAt(i);
156
+ switch (ch) {
157
+ case "\\":
158
+ out += "\\\\";
159
+ break;
160
+ case "\"":
161
+ out += "\\\"";
162
+ break;
163
+ case "\n":
164
+ out += "\\n";
165
+ break;
166
+ case "\r":
167
+ out += "\\r";
168
+ break;
169
+ case "\t":
170
+ out += "\\t";
171
+ break;
172
+ case "\b":
173
+ out += "\\b";
174
+ break;
175
+ case "\f":
176
+ out += "\\f";
177
+ break;
178
+ case "\0":
179
+ out += "\\0";
180
+ break;
181
+ default:
182
+ if (code < 0x20 || code === 0x7f || code === 0x85 || code === 0x2028 || code === 0x2029) {
183
+ out += `\\u${code.toString(16).padStart(4, "0")}`;
184
+ }
185
+ else {
186
+ out += ch;
187
+ }
188
+ break;
189
+ }
190
+ }
191
+ out += "\"";
192
+ return out;
193
+ }
194
+ function needsYamlStringQuoting(str) {
195
+ if (str.length === 0)
196
+ return true;
197
+ if (/^\s|\s$/.test(str))
198
+ return true;
199
+ if (YAML_CONTROL_OR_MULTILINE_RE.test(str))
200
+ return true;
201
+ if (YAML_INDICATOR_START_RE.test(str))
202
+ return true;
203
+ if (YAML_DOC_MARKER_RE.test(str))
204
+ return true;
205
+ if (YAML_RESERVED_WORD_RE.test(str))
206
+ return true;
207
+ if (YAML_NUMBER_LIKE_RE.test(str))
208
+ return true;
209
+ if (YAML_PLAIN_COLON_HAZARD_RE.test(str))
210
+ return true;
211
+ if (str.includes("#"))
212
+ return true;
213
+ return false;
214
+ }
215
+ function needsYamlKeyQuoting(key) {
216
+ if (needsYamlStringQuoting(key))
217
+ return true;
218
+ if (YAML_KEY_UNSAFE_CHAR_RE.test(key))
219
+ return true;
220
+ return false;
221
+ }
222
+ function formatYamlKey(key) {
223
+ return needsYamlKeyQuoting(key) ? formatDoubleQuotedYaml(key) : key;
224
+ }
225
+ function formatYamlScalar(value) {
226
+ if (value === null || value === undefined)
227
+ return "null";
228
+ if (typeof value === "boolean")
229
+ return value ? "true" : "false";
230
+ if (typeof value === "number") {
231
+ if (!Number.isFinite(value))
232
+ return "null";
233
+ return Object.is(value, -0) ? "0" : String(value);
234
+ }
235
+ if (typeof value === "string") {
236
+ return needsYamlStringQuoting(value) ? formatDoubleQuotedYaml(value) : value;
237
+ }
238
+ if (value instanceof Date) {
239
+ return formatDoubleQuotedYaml(value.toISOString());
240
+ }
241
+ return formatDoubleQuotedYaml(String(value));
242
+ }
243
+ function getSafeObjectEntries(obj) {
244
+ const entries = [];
245
+ for (const key of Object.keys(obj)) {
246
+ if (isForbiddenKey(key))
247
+ continue;
248
+ const val = obj[key];
249
+ if (val === undefined || typeof val === "function" || typeof val === "symbol")
250
+ continue;
251
+ entries.push([key, val]);
252
+ }
253
+ return entries;
254
+ }
255
+ function isYamlPrimitive(value) {
256
+ return (value === null ||
257
+ value === undefined ||
258
+ typeof value === "boolean" ||
259
+ typeof value === "number" ||
260
+ typeof value === "string" ||
261
+ typeof value === "bigint" ||
262
+ value instanceof Date);
263
+ }
264
+ function serializeYamlNode(value, indent, indentStep, depth, maxDepth, seen, lines) {
265
+ if (isYamlPrimitive(value)) {
266
+ lines.push(`${" ".repeat(indent)}${formatYamlScalar(value)}`);
267
+ return;
268
+ }
269
+ if (typeof value !== "object" || value === null) {
270
+ lines.push(`${" ".repeat(indent)}null`);
271
+ return;
272
+ }
273
+ if (depth > maxDepth) {
274
+ throw new VibecodeError("CONTRACT_INVALID", `YAML serialization exceeded maximum nesting depth of ${maxDepth}`);
275
+ }
276
+ if (seen.has(value)) {
277
+ throw new VibecodeError("CONTRACT_INVALID", "Cannot serialize circular object reference to YAML");
278
+ }
279
+ seen.add(value);
280
+ try {
281
+ const pad = " ".repeat(indent);
282
+ if (Array.isArray(value)) {
283
+ if (value.length === 0) {
284
+ lines.push(`${pad}[]`);
285
+ return;
286
+ }
287
+ for (const rawItem of value) {
288
+ const item = rawItem === undefined || typeof rawItem === "function" || typeof rawItem === "symbol"
289
+ ? null
290
+ : rawItem;
291
+ if (isYamlPrimitive(item)) {
292
+ lines.push(`${pad}- ${formatYamlScalar(item)}`);
293
+ continue;
294
+ }
295
+ if (Array.isArray(item)) {
296
+ if (item.length === 0) {
297
+ lines.push(`${pad}- []`);
298
+ }
299
+ else {
300
+ lines.push(`${pad}-`);
301
+ serializeYamlNode(item, indent + indentStep, indentStep, depth + 1, maxDepth, seen, lines);
302
+ }
303
+ continue;
304
+ }
305
+ if (isRecord(item)) {
306
+ const entries = getSafeObjectEntries(item);
307
+ if (entries.length === 0) {
308
+ lines.push(`${pad}- {}`);
309
+ continue;
310
+ }
311
+ if (depth + 1 > maxDepth) {
312
+ throw new VibecodeError("CONTRACT_INVALID", `YAML serialization exceeded maximum nesting depth of ${maxDepth}`);
313
+ }
314
+ if (seen.has(item)) {
315
+ throw new VibecodeError("CONTRACT_INVALID", "Cannot serialize circular object reference to YAML");
316
+ }
317
+ seen.add(item);
318
+ try {
319
+ const contentIndent = indent + 2;
320
+ const contentPad = " ".repeat(contentIndent);
321
+ for (let idx = 0; idx < entries.length; idx++) {
322
+ const [k, v] = entries[idx];
323
+ const prefix = idx === 0 ? `${pad}- ` : contentPad;
324
+ emitYamlMappingEntry(k, v, prefix, contentIndent, indentStep, depth + 1, maxDepth, seen, lines);
325
+ }
326
+ }
327
+ finally {
328
+ seen.delete(item);
329
+ }
330
+ continue;
331
+ }
332
+ lines.push(`${pad}- null`);
333
+ }
334
+ return;
335
+ }
336
+ const entries = getSafeObjectEntries(value);
337
+ if (entries.length === 0) {
338
+ lines.push(`${pad}{}`);
339
+ return;
340
+ }
341
+ for (const [k, v] of entries) {
342
+ emitYamlMappingEntry(k, v, pad, indent, indentStep, depth, maxDepth, seen, lines);
343
+ }
344
+ }
345
+ finally {
346
+ seen.delete(value);
347
+ }
348
+ }
349
+ function emitYamlMappingEntry(key, val, linePrefix, keyIndent, indentStep, depth, maxDepth, seen, lines) {
350
+ const formattedKey = formatYamlKey(key);
351
+ if (isYamlPrimitive(val)) {
352
+ lines.push(`${linePrefix}${formattedKey}: ${formatYamlScalar(val)}`);
353
+ return;
354
+ }
355
+ if (Array.isArray(val)) {
356
+ if (val.length === 0) {
357
+ lines.push(`${linePrefix}${formattedKey}: []`);
358
+ }
359
+ else {
360
+ lines.push(`${linePrefix}${formattedKey}:`);
361
+ serializeYamlNode(val, keyIndent + indentStep, indentStep, depth + 1, maxDepth, seen, lines);
362
+ }
363
+ return;
364
+ }
365
+ if (isRecord(val)) {
366
+ const childEntries = getSafeObjectEntries(val);
367
+ if (childEntries.length === 0) {
368
+ lines.push(`${linePrefix}${formattedKey}: {}`);
369
+ }
370
+ else {
371
+ lines.push(`${linePrefix}${formattedKey}:`);
372
+ serializeYamlNode(val, keyIndent + indentStep, indentStep, depth + 1, maxDepth, seen, lines);
373
+ }
374
+ return;
375
+ }
376
+ lines.push(`${linePrefix}${formattedKey}: null`);
377
+ }
378
+ /**
379
+ * Deterministic zero-dependency YAML 1.2 serializer compatible with `parseYaml()`.
380
+ */
381
+ export function serializeYaml(value, options = {}) {
382
+ const indentStep = options.indent ?? DEFAULT_YAML_INDENT;
383
+ const maxDepth = options.maxDepth ?? DEFAULT_YAML_MAX_DEPTH;
384
+ if (!Number.isInteger(indentStep) || indentStep < 1 || indentStep > 16) {
385
+ throw new VibecodeError("CONTRACT_INVALID", "serializeYaml indent must be an integer between 1 and 16.");
386
+ }
387
+ if (!Number.isInteger(maxDepth) || maxDepth < 1 || maxDepth > 128) {
388
+ throw new VibecodeError("CONTRACT_INVALID", "serializeYaml maxDepth must be an integer between 1 and 128.");
389
+ }
390
+ if (value === undefined) {
391
+ return "null\n";
392
+ }
393
+ const lines = [];
394
+ serializeYamlNode(value, 0, indentStep, 1, maxDepth, new Set(), lines);
395
+ return `${lines.join("\n")}\n`;
396
+ }
397
+ function redactExampleValue(value, depth = 0, seen = new Set()) {
398
+ if (value === null || value === undefined)
399
+ return value;
400
+ if (typeof value === "string")
401
+ return sanitizeText(value);
402
+ if (typeof value === "boolean")
403
+ return value;
404
+ if (typeof value === "number")
405
+ return Number.isFinite(value) ? value : null;
406
+ if (depth >= MAX_SCHEMA_DEPTH)
407
+ return "[TRUNCATED]";
408
+ if (typeof value !== "object")
409
+ return undefined;
410
+ if (seen.has(value))
411
+ return "[CIRCULAR]";
412
+ seen.add(value);
413
+ try {
414
+ if (Array.isArray(value)) {
415
+ return value.map((item) => redactExampleValue(item, depth + 1, seen));
416
+ }
417
+ const out = {};
418
+ for (const key of Object.keys(value)) {
419
+ if (isForbiddenKey(key))
420
+ continue;
421
+ const rawVal = value[key];
422
+ if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol")
423
+ continue;
424
+ if (isSecretFieldName(key)) {
425
+ out[key] = "[REDACTED]";
426
+ }
427
+ else {
428
+ out[key] = redactExampleValue(rawVal, depth + 1, seen);
429
+ }
430
+ }
431
+ return out;
432
+ }
433
+ finally {
434
+ seen.delete(value);
435
+ }
436
+ }
437
+ function synthesizeSchemaFromValue(value, depth = 0, seen = new Set()) {
438
+ if (depth >= MAX_SCHEMA_DEPTH)
439
+ return {};
440
+ if (value === null)
441
+ return { type: "string", nullable: true };
442
+ if (typeof value === "boolean")
443
+ return { type: "boolean" };
444
+ if (typeof value === "number") {
445
+ if (!Number.isFinite(value))
446
+ return { type: "number" };
447
+ return { type: Number.isInteger(value) ? "integer" : "number" };
448
+ }
449
+ if (typeof value === "string")
450
+ return { type: "string" };
451
+ if (typeof value !== "object")
452
+ return {};
453
+ if (seen.has(value))
454
+ return { type: "object" };
455
+ seen.add(value);
456
+ try {
457
+ if (Array.isArray(value)) {
458
+ return {
459
+ type: "array",
460
+ items: value.length > 0 ? synthesizeSchemaFromValue(value[0], depth + 1, seen) : {}
461
+ };
462
+ }
463
+ const properties = {};
464
+ const required = [];
465
+ let count = 0;
466
+ for (const key of Object.keys(value)) {
467
+ if (isForbiddenKey(key))
468
+ continue;
469
+ if (count >= MAX_SCHEMA_KEYS)
470
+ break;
471
+ const rawVal = value[key];
472
+ if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol")
473
+ continue;
474
+ properties[key] = synthesizeSchemaFromValue(rawVal, depth + 1, seen);
475
+ required.push(key);
476
+ count += 1;
477
+ }
478
+ const schema = { type: "object", properties };
479
+ if (required.length > 0) {
480
+ schema.required = required;
481
+ }
482
+ return schema;
483
+ }
484
+ finally {
485
+ seen.delete(value);
486
+ }
487
+ }
488
+ function sanitizeJsonSchema(schema, inSecretField = false, depth = 0, seen = new Set()) {
489
+ if (!isRecord(schema) || depth >= MAX_SCHEMA_DEPTH)
490
+ return {};
491
+ if (seen.has(schema))
492
+ return {};
493
+ seen.add(schema);
494
+ try {
495
+ const out = {};
496
+ for (const key of Object.keys(schema)) {
497
+ if (isForbiddenKey(key))
498
+ continue;
499
+ const val = schema[key];
500
+ if (val === undefined || typeof val === "function" || typeof val === "symbol")
501
+ continue;
502
+ if (inSecretField && (key === "example" || key === "examples" || key === "default" || key === "const" || key === "enum")) {
503
+ continue;
504
+ }
505
+ if (key === "properties" && isRecord(val)) {
506
+ const props = {};
507
+ for (const propKey of Object.keys(val)) {
508
+ if (isForbiddenKey(propKey))
509
+ continue;
510
+ props[propKey] = sanitizeJsonSchema(val[propKey], inSecretField || isSecretFieldName(propKey), depth + 1, seen);
511
+ }
512
+ out.properties = props;
513
+ }
514
+ else if (key === "required" && Array.isArray(val)) {
515
+ const filtered = val.filter((item) => typeof item === "string" && !isForbiddenKey(item));
516
+ if (filtered.length > 0)
517
+ out.required = filtered;
518
+ }
519
+ else if (key === "items") {
520
+ if (Array.isArray(val)) {
521
+ out.items = val.map((item) => sanitizeJsonSchema(item, inSecretField, depth + 1, seen));
522
+ }
523
+ else if (isRecord(val)) {
524
+ out.items = sanitizeJsonSchema(val, inSecretField, depth + 1, seen);
525
+ }
526
+ }
527
+ else if ((key === "allOf" || key === "anyOf" || key === "oneOf") && Array.isArray(val)) {
528
+ out[key] = val.map((item) => sanitizeJsonSchema(item, inSecretField, depth + 1, seen));
529
+ }
530
+ else if ((key === "not" || key === "additionalProperties") && isRecord(val)) {
531
+ out[key] = sanitizeJsonSchema(val, inSecretField, depth + 1, seen);
532
+ }
533
+ else if (key === "example" || key === "default" || key === "const") {
534
+ out[key] = redactExampleValue(val, depth + 1);
535
+ }
536
+ else if ((key === "enum" || key === "examples") && Array.isArray(val)) {
537
+ out[key] = val.map((item) => redactExampleValue(item, depth + 1));
538
+ }
539
+ else if (typeof val === "string") {
540
+ out[key] = sanitizeText(val);
541
+ }
542
+ else if (typeof val === "boolean" || (typeof val === "number" && Number.isFinite(val))) {
543
+ out[key] = val;
544
+ }
545
+ else if (Array.isArray(val)) {
546
+ out[key] = val.map((item) => redactExampleValue(item, depth + 1));
547
+ }
548
+ else if (isRecord(val)) {
549
+ out[key] = sanitizeJsonSchema(val, inSecretField, depth + 1, seen);
550
+ }
551
+ }
552
+ return out;
553
+ }
554
+ finally {
555
+ seen.delete(schema);
556
+ }
557
+ }
558
+ function parseHttpPathAndQuery(rawPath) {
559
+ const trimmed = typeof rawPath === "string" ? rawPath.trim() : "";
560
+ if (!trimmed) {
561
+ return { pathKey: "/", inlineQuery: [] };
562
+ }
563
+ if (/^https?:\/\//i.test(trimmed)) {
564
+ const withoutAuth = trimmed.replace(URL_BASIC_AUTH_RE, "$1");
565
+ try {
566
+ const parsed = new URL(withoutAuth);
567
+ const pathname = redactVaultPaths(parsed.pathname || "/");
568
+ const pathKey = pathname.startsWith("/") ? pathname : `/${pathname}`;
569
+ const inlineQuery = [];
570
+ for (const [k, v] of parsed.searchParams.entries()) {
571
+ if (!k || isForbiddenKey(k))
572
+ continue;
573
+ inlineQuery.push([k, v]);
574
+ }
575
+ return { pathKey, inlineQuery };
576
+ }
577
+ catch {
578
+ const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
579
+ return splitRelativePathAndQuery(stripped);
580
+ }
581
+ }
582
+ return splitRelativePathAndQuery(trimmed);
583
+ }
584
+ function splitRelativePathAndQuery(raw) {
585
+ const hashIdx = raw.indexOf("#");
586
+ const withoutHash = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
587
+ const qIdx = withoutHash.indexOf("?");
588
+ const rawPathPart = qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash;
589
+ const rawQueryPart = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
590
+ const cleanPath = redactVaultPaths(rawPathPart.trim());
591
+ const pathKey = !cleanPath ? "/" : cleanPath.startsWith("/") ? cleanPath : `/${cleanPath}`;
592
+ const inlineQuery = [];
593
+ if (rawQueryPart) {
594
+ const params = new URLSearchParams(rawQueryPart);
595
+ for (const [k, v] of params.entries()) {
596
+ if (!k || isForbiddenKey(k))
597
+ continue;
598
+ inlineQuery.push([k, v]);
599
+ }
600
+ }
601
+ return { pathKey, inlineQuery };
602
+ }
603
+ function extractPathParamNames(pathKey) {
604
+ const names = [];
605
+ const seen = new Set();
606
+ const re = /\{([^{}]+)\}/g;
607
+ let match;
608
+ while ((match = re.exec(pathKey)) !== null) {
609
+ const name = match[1].trim();
610
+ if (!name || isForbiddenKey(name) || seen.has(name))
611
+ continue;
612
+ seen.add(name);
613
+ names.push(name);
614
+ }
615
+ return names;
616
+ }
617
+ function extractMediaType(rawContentType) {
618
+ if (typeof rawContentType !== "string")
619
+ return null;
620
+ const base = rawContentType.split(";")[0]?.trim().toLowerCase() ?? "";
621
+ if (!base || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(base)) {
622
+ return null;
623
+ }
624
+ return base;
625
+ }
626
+ function findHeaderValue(headers, targetLower) {
627
+ if (!isRecord(headers))
628
+ return undefined;
629
+ for (const key of Object.keys(headers)) {
630
+ if (isForbiddenKey(key))
631
+ continue;
632
+ if (key.trim().toLowerCase() === targetLower) {
633
+ const val = headers[key];
634
+ if (val !== undefined && val !== null)
635
+ return String(val);
636
+ }
637
+ }
638
+ return undefined;
639
+ }
640
+ function inferQueryParamSchemaAndExample(name, rawValue) {
641
+ if (isSensitiveQueryName(name)) {
642
+ return { schema: { type: "string" } };
643
+ }
644
+ if (typeof rawValue === "boolean") {
645
+ return { schema: { type: "boolean" }, example: rawValue };
646
+ }
647
+ if (typeof rawValue === "number" && Number.isFinite(rawValue)) {
648
+ return {
649
+ schema: { type: Number.isInteger(rawValue) ? "integer" : "number" },
650
+ example: rawValue
651
+ };
652
+ }
653
+ const str = String(rawValue);
654
+ if (isAuthHeaderValue(str)) {
655
+ return { schema: { type: "string" } };
656
+ }
657
+ return {
658
+ schema: { type: "string" },
659
+ example: sanitizeText(str)
660
+ };
661
+ }
662
+ function sanitizeOperationId(rawId, method, pathKey, usedIds) {
663
+ const source = typeof rawId === "string" && rawId.trim()
664
+ ? sanitizeText(rawId.trim())
665
+ : `${method}_${pathKey}`;
666
+ const parts = source
667
+ .replace(/[^A-Za-z0-9]+/g, " ")
668
+ .trim()
669
+ .split(/\s+/)
670
+ .filter(Boolean);
671
+ let base = "";
672
+ if (parts.length > 0) {
673
+ base = parts
674
+ .map((part, idx) => {
675
+ const lower = part.toLowerCase();
676
+ return idx === 0 ? lower : `${lower[0].toUpperCase()}${lower.slice(1)}`;
677
+ })
678
+ .join("");
679
+ }
680
+ if (!base || /^[0-9]/.test(base)) {
681
+ base = `${method}${base ? `${base[0].toUpperCase()}${base.slice(1)}` : "Operation"}`;
682
+ }
683
+ base = base.slice(0, 80);
684
+ if (!usedIds.has(base)) {
685
+ usedIds.add(base);
686
+ return base;
687
+ }
688
+ let suffix = 2;
689
+ while (usedIds.has(`${base}_${suffix}`)) {
690
+ suffix += 1;
691
+ }
692
+ const unique = `${base}_${suffix}`;
693
+ usedIds.add(unique);
694
+ return unique;
695
+ }
696
+ function normalizeStatuses(rawStatus) {
697
+ const result = [];
698
+ const pushValid = (code) => {
699
+ if (typeof code === "number" && Number.isInteger(code) && code >= 100 && code <= 599) {
700
+ if (!result.includes(code))
701
+ result.push(code);
702
+ }
703
+ };
704
+ if (Array.isArray(rawStatus)) {
705
+ for (const item of rawStatus)
706
+ pushValid(item);
707
+ }
708
+ else {
709
+ pushValid(rawStatus);
710
+ }
711
+ return result.length > 0 ? result : [200];
712
+ }
713
+ function statusDescription(code) {
714
+ return HTTP_STATUS_DESCRIPTIONS[code] ?? `HTTP ${code} response`;
715
+ }
716
+ function parameterIdentity(param) {
717
+ const normalizedName = param.in === "header" ? param.name.toLowerCase() : param.name;
718
+ return `${param.in}:${normalizedName}`;
719
+ }
720
+ function buildOperationFromInvariant(inv, method, pathKey, inlineQuery, usedOperationIds) {
721
+ const input = isRecord(inv.input) ? inv.input : {};
722
+ const expected = isRecord(inv.expected) ? inv.expected : {};
723
+ const operationId = sanitizeOperationId(inv.id, method, pathKey, usedOperationIds);
724
+ const summary = typeof inv.description === "string" && inv.description.trim()
725
+ ? sanitizeSingleLineText(inv.description)
726
+ : undefined;
727
+ const tags = [];
728
+ if (Array.isArray(inv.tags)) {
729
+ for (const rawTag of inv.tags) {
730
+ if (typeof rawTag !== "string")
731
+ continue;
732
+ const cleanTag = sanitizeSingleLineText(rawTag);
733
+ if (!cleanTag || /holdout/i.test(cleanTag))
734
+ continue;
735
+ if (!tags.includes(cleanTag))
736
+ tags.push(cleanTag);
737
+ }
738
+ }
739
+ const parameters = [];
740
+ const paramKeys = new Set();
741
+ const addParam = (param) => {
742
+ const id = parameterIdentity(param);
743
+ if (paramKeys.has(id))
744
+ return;
745
+ paramKeys.add(id);
746
+ parameters.push(param);
747
+ };
748
+ // Path template parameters
749
+ for (const pathParam of extractPathParamNames(pathKey)) {
750
+ addParam({
751
+ name: pathParam,
752
+ in: "path",
753
+ required: true,
754
+ schema: { type: "string" }
755
+ });
756
+ }
757
+ // Query parameters (inline + structured; structured overrides inline for richer types)
758
+ const queryMap = new Map();
759
+ for (const [k, v] of inlineQuery) {
760
+ if (!k || isForbiddenKey(k))
761
+ continue;
762
+ queryMap.set(k, v);
763
+ }
764
+ if (isRecord(input.query)) {
765
+ for (const key of Object.keys(input.query)) {
766
+ if (!key || isForbiddenKey(key))
767
+ continue;
768
+ const val = input.query[key];
769
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
770
+ queryMap.set(key, val);
771
+ }
772
+ }
773
+ }
774
+ for (const [name, value] of queryMap.entries()) {
775
+ const inferred = inferQueryParamSchemaAndExample(name, value);
776
+ const param = {
777
+ name,
778
+ in: "query",
779
+ required: false,
780
+ schema: inferred.schema
781
+ };
782
+ if (inferred.example !== undefined) {
783
+ param.example = inferred.example;
784
+ }
785
+ addParam(param);
786
+ }
787
+ // Header parameters (strip sensitive headers, Bearer/Basic values, and transport noise)
788
+ const rawInputHeaders = isRecord(input.headers)
789
+ ? input.headers
790
+ : undefined;
791
+ if (rawInputHeaders) {
792
+ for (const rawName of Object.keys(rawInputHeaders)) {
793
+ if (isForbiddenKey(rawName))
794
+ continue;
795
+ const name = rawName.trim();
796
+ if (!name)
797
+ continue;
798
+ const lower = name.toLowerCase();
799
+ if (TRANSPORT_NOISE_HEADERS.has(lower))
800
+ continue;
801
+ if (isSensitiveHeaderName(name))
802
+ continue;
803
+ const rawVal = rawInputHeaders[rawName];
804
+ if (rawVal === undefined || rawVal === null)
805
+ continue;
806
+ const strVal = String(rawVal);
807
+ if (isAuthHeaderValue(strVal))
808
+ continue;
809
+ addParam({
810
+ name,
811
+ in: "header",
812
+ required: false,
813
+ schema: { type: "string" },
814
+ example: sanitizeText(strVal)
815
+ });
816
+ }
817
+ }
818
+ const operation = {
819
+ operationId,
820
+ ...(summary ? { summary } : {}),
821
+ ...(tags.length > 0 ? { tags } : {}),
822
+ ...(parameters.length > 0 ? { parameters } : {}),
823
+ responses: {}
824
+ };
825
+ // Request body for body-bearing HTTP methods
826
+ if (BODY_HTTP_METHODS.has(method) && input.body !== undefined && input.body !== null) {
827
+ const inputContentType = extractMediaType(findHeaderValue(rawInputHeaders, "content-type")) ?? "application/json";
828
+ let bodyValue = input.body;
829
+ if (typeof bodyValue === "string" && inputContentType.includes("json")) {
830
+ const trimmedBody = bodyValue.trim();
831
+ if (trimmedBody.startsWith("{") || trimmedBody.startsWith("[")) {
832
+ try {
833
+ bodyValue = JSON.parse(trimmedBody);
834
+ }
835
+ catch {
836
+ // Keep original string if not valid JSON
837
+ }
838
+ }
839
+ }
840
+ const bodySchema = synthesizeSchemaFromValue(bodyValue);
841
+ const bodyExample = redactExampleValue(bodyValue);
842
+ const mediaObj = {
843
+ schema: bodySchema
844
+ };
845
+ if (bodyExample !== undefined) {
846
+ mediaObj.example = bodyExample;
847
+ }
848
+ operation.requestBody = {
849
+ required: true,
850
+ content: {
851
+ [inputContentType]: mediaObj
852
+ }
853
+ };
854
+ }
855
+ // Responses
856
+ const statuses = normalizeStatuses(expected.status);
857
+ for (const code of statuses) {
858
+ operation.responses[String(code)] = {
859
+ description: statusDescription(code)
860
+ };
861
+ }
862
+ const primaryStatus = statuses[0];
863
+ const primaryKey = String(primaryStatus);
864
+ const hasJsonSchema = isRecord(expected.jsonSchema);
865
+ const hasJsonSubset = expected.jsonSubset !== undefined;
866
+ const hasJsonPaths = Array.isArray(expected.jsonPaths) && expected.jsonPaths.length > 0;
867
+ const rawExpectedHeaders = isRecord(expected.headers)
868
+ ? expected.headers
869
+ : undefined;
870
+ const detectedExpectedCt = extractMediaType(findHeaderValue(rawExpectedHeaders, "content-type"));
871
+ if (hasJsonSchema || hasJsonSubset || hasJsonPaths) {
872
+ const contentType = detectedExpectedCt && detectedExpectedCt.includes("json")
873
+ ? detectedExpectedCt
874
+ : "application/json";
875
+ let schema;
876
+ if (hasJsonSchema) {
877
+ schema = sanitizeJsonSchema(expected.jsonSchema);
878
+ }
879
+ else if (hasJsonSubset) {
880
+ schema = synthesizeSchemaFromValue(expected.jsonSubset);
881
+ }
882
+ else {
883
+ schema = { type: "object" };
884
+ }
885
+ operation.responses[primaryKey].content = {
886
+ [contentType]: { schema }
887
+ };
888
+ }
889
+ else if (primaryStatus !== 204 &&
890
+ primaryStatus !== 304 &&
891
+ (detectedExpectedCt !== null ||
892
+ expected.bodyExact !== undefined ||
893
+ expected.bodyContains !== undefined)) {
894
+ const contentType = detectedExpectedCt ?? "text/plain";
895
+ operation.responses[primaryKey].content = {
896
+ [contentType]: {
897
+ schema: contentType.includes("json") ? { type: "object" } : { type: "string" }
898
+ }
899
+ };
900
+ }
901
+ return operation;
902
+ }
903
+ function mergeOperations(existing, incoming) {
904
+ if (!existing.summary && incoming.summary) {
905
+ existing.summary = incoming.summary;
906
+ }
907
+ if (incoming.tags && incoming.tags.length > 0) {
908
+ if (!existing.tags)
909
+ existing.tags = [];
910
+ for (const tag of incoming.tags) {
911
+ if (!existing.tags.includes(tag))
912
+ existing.tags.push(tag);
913
+ }
914
+ }
915
+ if (incoming.parameters && incoming.parameters.length > 0) {
916
+ if (!existing.parameters)
917
+ existing.parameters = [];
918
+ const seen = new Set(existing.parameters.map(parameterIdentity));
919
+ for (const param of incoming.parameters) {
920
+ const id = parameterIdentity(param);
921
+ if (!seen.has(id)) {
922
+ seen.add(id);
923
+ existing.parameters.push(param);
924
+ }
925
+ }
926
+ }
927
+ if (!existing.requestBody && incoming.requestBody) {
928
+ existing.requestBody = incoming.requestBody;
929
+ }
930
+ for (const [statusKey, respObj] of Object.entries(incoming.responses)) {
931
+ if (!Object.prototype.hasOwnProperty.call(existing.responses, statusKey)) {
932
+ existing.responses[statusKey] = respObj;
933
+ }
934
+ }
935
+ }
936
+ /**
937
+ * Export visible HTTP invariants from a ContractV02 into an OpenAPI 3.0.3 YAML or JSON spec.
938
+ */
939
+ export function exportOpenApiSpec(contract, options = {}) {
940
+ if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
941
+ throw new VibecodeError("CONTRACT_INVALID", "exportOpenApiSpec requires a valid contract object with an invariants array.");
942
+ }
943
+ const formatRaw = options.format ?? "yaml";
944
+ if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
945
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported OpenAPI export format "${String(formatRaw)}". Supported formats: yaml, json.`);
946
+ }
947
+ const format = formatRaw;
948
+ const paths = {};
949
+ const skippedIds = [];
950
+ const usedOperationIds = new Set();
951
+ let excludedHoldoutCount = 0;
952
+ for (const inv of contract.invariants) {
953
+ if (!isRecord(inv))
954
+ continue;
955
+ if (inv.holdout === true) {
956
+ excludedHoldoutCount += 1;
957
+ continue;
958
+ }
959
+ const invId = typeof inv.id === "string" && inv.id.trim() ? inv.id : "unknown";
960
+ if (inv.type !== "http") {
961
+ skippedIds.push(invId);
962
+ continue;
963
+ }
964
+ const input = isRecord(inv.input) ? inv.input : {};
965
+ const methodRaw = typeof input.method === "string" && input.method.trim()
966
+ ? input.method.trim().toLowerCase()
967
+ : "get";
968
+ if (!SUPPORTED_HTTP_METHODS.has(methodRaw)) {
969
+ skippedIds.push(invId);
970
+ continue;
971
+ }
972
+ const { pathKey, inlineQuery } = parseHttpPathAndQuery(typeof input.path === "string" ? input.path : undefined);
973
+ if (isForbiddenKey(pathKey)) {
974
+ skippedIds.push(invId);
975
+ continue;
976
+ }
977
+ const operation = buildOperationFromInvariant(inv, methodRaw, pathKey, inlineQuery, usedOperationIds);
978
+ if (!Object.prototype.hasOwnProperty.call(paths, pathKey)) {
979
+ paths[pathKey] = {};
980
+ }
981
+ const pathItem = paths[pathKey];
982
+ if (Object.prototype.hasOwnProperty.call(pathItem, methodRaw)) {
983
+ mergeOperations(pathItem[methodRaw], operation);
984
+ }
985
+ else {
986
+ pathItem[methodRaw] = operation;
987
+ }
988
+ }
989
+ const rawTitle = (typeof options.title === "string" && options.title.trim()) ||
990
+ (isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()) ||
991
+ "vibecode-api";
992
+ const title = sanitizeSingleLineText(rawTitle) || "vibecode-api";
993
+ const rawVersion = (typeof options.version === "string" && options.version.trim()) || "1.0.0";
994
+ const version = sanitizeSingleLineText(rawVersion) || "1.0.0";
995
+ const description = typeof options.description === "string" && options.description.trim()
996
+ ? sanitizeText(options.description.trim())
997
+ : undefined;
998
+ let cleanServerUrl = null;
999
+ if (typeof options.serverUrl === "string" && options.serverUrl.trim()) {
1000
+ cleanServerUrl = sanitizeServerUrl(options.serverUrl);
1001
+ }
1002
+ else if (isRecord(contract.target) &&
1003
+ Array.isArray(contract.target.sources) &&
1004
+ contract.target.sources.length > 0 &&
1005
+ isRecord(contract.target.sources[0]) &&
1006
+ typeof contract.target.sources[0].ref === "string" &&
1007
+ /^https?:\/\//i.test(contract.target.sources[0].ref.trim())) {
1008
+ cleanServerUrl = sanitizeServerUrl(contract.target.sources[0].ref);
1009
+ }
1010
+ const spec = {
1011
+ openapi: "3.0.3",
1012
+ info: {
1013
+ title,
1014
+ version,
1015
+ ...(description ? { description } : {})
1016
+ },
1017
+ ...(cleanServerUrl ? { servers: [{ url: cleanServerUrl }] } : {}),
1018
+ paths
1019
+ };
1020
+ let endpointCount = 0;
1021
+ for (const pathItem of Object.values(paths)) {
1022
+ endpointCount += Object.keys(pathItem).length;
1023
+ }
1024
+ const pathCount = Object.keys(paths).length;
1025
+ const content = format === "yaml"
1026
+ ? serializeYaml(spec)
1027
+ : `${JSON.stringify(spec, null, 2)}\n`;
1028
+ return {
1029
+ format,
1030
+ suggestedFilename: format === "yaml" ? "openapi.yaml" : "openapi.json",
1031
+ content,
1032
+ spec,
1033
+ endpointCount,
1034
+ pathCount,
1035
+ skippedCount: skippedIds.length,
1036
+ skippedIds,
1037
+ excludedHoldoutCount
1038
+ };
1039
+ }
1040
+ /**
1041
+ * Export and atomically write an OpenAPI 3.0.3 YAML or JSON spec to disk.
1042
+ */
1043
+ export function writeOpenApiSpec(contract, options) {
1044
+ if (!isRecord(options) ||
1045
+ typeof options.outPath !== "string" ||
1046
+ !options.outPath.trim() ||
1047
+ options.outPath.includes("\0")) {
1048
+ throw new VibecodeError("CONTRACT_INVALID", "writeOpenApiSpec requires a valid non-empty outPath.");
1049
+ }
1050
+ const result = exportOpenApiSpec(contract, options);
1051
+ const resolvedOut = path.resolve(options.outPath.trim());
1052
+ const parentDir = path.dirname(resolvedOut);
1053
+ fs.mkdirSync(parentDir, { recursive: true });
1054
+ const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
1055
+ try {
1056
+ fs.writeFileSync(tmpPath, result.content, "utf8");
1057
+ fs.renameSync(tmpPath, resolvedOut);
1058
+ }
1059
+ catch (err) {
1060
+ try {
1061
+ if (fs.existsSync(tmpPath)) {
1062
+ fs.rmSync(tmpPath, { force: true });
1063
+ }
1064
+ }
1065
+ catch {
1066
+ // ignore cleanup error
1067
+ }
1068
+ throw err;
1069
+ }
1070
+ return {
1071
+ ...result,
1072
+ outPath: resolvedOut
1073
+ };
1074
+ }