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,2335 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { VibecodeError, errorMessage } from "../core/errors.js";
4
+ import { validateContract } from "../core/schema.js";
5
+ import { parseYaml } from "../core/yaml.js";
6
+ import { isSensitiveHeader, isSensitiveQueryParam, mergeHeaders, redactHeaders } from "./trace.js";
7
+ const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
8
+ const MAX_REQUESTS = 50;
9
+ const MAX_WALK_FILES = 500;
10
+ const MAX_DIR_DEPTH = 5;
11
+ const MAX_FOLDER_DEPTH = 16;
12
+ const MAX_JSON_SCHEMA_DEPTH = 16;
13
+ const MAX_JSON_SCHEMA_KEYS = 200;
14
+ const MAX_SANITIZE_DEPTH = 32;
15
+ const DEFAULT_PROBE_TIMEOUT_MS = 10000;
16
+ const MAX_BODY_CONTAINS_SNIPPET = 120;
17
+ const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
18
+ const ALL_HTTP_METHODS = new Set([
19
+ "GET",
20
+ "POST",
21
+ "PUT",
22
+ "PATCH",
23
+ "DELETE",
24
+ "HEAD",
25
+ "OPTIONS"
26
+ ]);
27
+ const IGNORED_DIRS = new Set(["node_modules", ".git", "environments"]);
28
+ const BRUNO_AUTH_BLOCKS = new Set([
29
+ "auth:bearer",
30
+ "auth:basic",
31
+ "auth:apikey",
32
+ "auth:oauth2",
33
+ "auth:digest",
34
+ "auth:awsv4",
35
+ "auth:ntlm",
36
+ "auth:wsse"
37
+ ]);
38
+ const SECRET_VAR_NAME_RE = /token|secret|password|passwd|api[_-]?key|apikey|auth|jwt|private[_-]?key|cookie/i;
39
+ const SENSITIVE_HEADER_RE = /(?:^x-secret|secret|token|password|passwd|api[-_]?key|apikey|auth|jwt|cookie|csrf|xsrf|private[-_]?key)/i;
40
+ const TEMPLATE_VAR_RE = /\{\{\s*([^{}\s][^{}]*?)\s*\}\}/g;
41
+ const TEMPLATE_VAR_TEST_RE = /\{\{\s*([^{}\s][^{}]*?)\s*\}\}/;
42
+ const BRUNO_BLOCK_HEADER_RE = /^([A-Za-z][A-Za-z0-9_:-]*)\s*(\{|\[)\s*(?:\/\/.*)?$/;
43
+ const BRUNO_ASSERT_OP_RE = /^(eq|neq|gt|gte|lt|lte|in|notIn|contains|notContains|length|matches|notMatches|startsWith|endsWith|between|isEmpty|isNull|isUndefined|isDefined|isTruthy|isFalsy|isJson|isNumber|isString|isBoolean|isArray)(?:\s+(.*))?$/;
44
+ const URL_USERINFO_RE = /(https?:\/\/)([^:@/\s]+):([^@/\s]*)@/gi;
45
+ const URL_USERONLY_RE = /(https?:\/\/)([^:@/\s]+)@/gi;
46
+ const SENSITIVE_HEADER_VALUE_RE = /^\s*(?:Bearer|Basic|Token|Digest|ApiKey)\s+\S+/i;
47
+ const INLINE_AUTH_VALUE_RE = /\b(Bearer|Basic|Token|Digest|ApiKey)\s+([^\s"'`<>]+)/gi;
48
+ const SECRET_SENTINEL = "__VIBECODE_SECRET_SENTINEL__";
49
+ function hasOwn(obj, key) {
50
+ return Object.prototype.hasOwnProperty.call(obj, key);
51
+ }
52
+ function isObject(v) {
53
+ return v !== null && typeof v === "object" && !Array.isArray(v);
54
+ }
55
+ function isUnsafeKey(key) {
56
+ return key === "__proto__" || key === "constructor" || key === "prototype";
57
+ }
58
+ function createNullRecord() {
59
+ return Object.create(null);
60
+ }
61
+ function setSafeProp(target, key, value) {
62
+ if (!key || isUnsafeKey(key))
63
+ return;
64
+ target[key] = value;
65
+ }
66
+ function stripBom(raw) {
67
+ return raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw;
68
+ }
69
+ function normalizeNewlines(raw) {
70
+ return stripBom(raw).replace(/\0/g, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
71
+ }
72
+ function isCollectionSensitiveHeader(name) {
73
+ const lower = name.trim().toLowerCase();
74
+ if (!lower)
75
+ return false;
76
+ return isSensitiveHeader(lower) || SENSITIVE_HEADER_RE.test(lower);
77
+ }
78
+ function isCollectionSensitiveQueryParam(name) {
79
+ const trimmed = name.trim();
80
+ if (!trimmed)
81
+ return false;
82
+ return isSensitiveQueryParam(trimmed) || SECRET_VAR_NAME_RE.test(trimmed);
83
+ }
84
+ function isSecretVarName(name, secretVarNames) {
85
+ const cleaned = normalizeVarName(name);
86
+ if (!cleaned)
87
+ return false;
88
+ if (SECRET_VAR_NAME_RE.test(cleaned))
89
+ return true;
90
+ if (secretVarNames && secretVarNames.has(cleaned.toLowerCase()))
91
+ return true;
92
+ const parts = cleaned.split(".");
93
+ for (const part of parts) {
94
+ if (SECRET_VAR_NAME_RE.test(part))
95
+ return true;
96
+ if (secretVarNames && secretVarNames.has(part.toLowerCase()))
97
+ return true;
98
+ }
99
+ return false;
100
+ }
101
+ function normalizeVarName(raw) {
102
+ const trimmed = raw.trim();
103
+ if (trimmed.startsWith("_."))
104
+ return trimmed.slice(2).trim();
105
+ return trimmed;
106
+ }
107
+ function isUnsafeVarPath(name) {
108
+ const cleaned = normalizeVarName(name);
109
+ if (!cleaned)
110
+ return true;
111
+ for (const seg of cleaned.split(".")) {
112
+ if (isUnsafeKey(seg.trim()))
113
+ return true;
114
+ }
115
+ return false;
116
+ }
117
+ function recordSecretValue(secretValues, raw) {
118
+ if (typeof raw !== "string")
119
+ return;
120
+ const trimmed = raw.trim();
121
+ if (!trimmed)
122
+ return;
123
+ secretValues.add(trimmed);
124
+ const schemeMatch = /^(?:Bearer|Basic|Token|Digest|ApiKey)\s+(.+)$/i.exec(trimmed);
125
+ if (schemeMatch && schemeMatch[1].trim().length > 0) {
126
+ secretValues.add(schemeMatch[1].trim());
127
+ }
128
+ if (trimmed.includes("=")) {
129
+ for (const part of trimmed.split(";")) {
130
+ const eqIdx = part.indexOf("=");
131
+ if (eqIdx > 0) {
132
+ const val = part.slice(eqIdx + 1).trim();
133
+ if (val.length > 0)
134
+ secretValues.add(val);
135
+ }
136
+ }
137
+ }
138
+ }
139
+ function redactKnownSecrets(text, secretValues) {
140
+ let out = text
141
+ .replace(URL_USERINFO_RE, "$1[REDACTED]@")
142
+ .replace(URL_USERONLY_RE, "$1[REDACTED]@")
143
+ .replace(INLINE_AUTH_VALUE_RE, (match, scheme, val) => val === "[REDACTED]" || /^\{\{[^{}]+\}\}$/.test(val) ? match : `${scheme} [REDACTED]`);
144
+ const sorted = [...secretValues].filter((s) => s.length > 0).sort((a, b) => b.length - a.length);
145
+ for (const secret of sorted) {
146
+ if (out.includes(secret)) {
147
+ out = out.replaceAll(secret, "[REDACTED]");
148
+ }
149
+ }
150
+ return out;
151
+ }
152
+ function sanitizeJsonValue(value, depth = 0) {
153
+ if (depth >= MAX_SANITIZE_DEPTH)
154
+ return null;
155
+ if (value === null || typeof value !== "object")
156
+ return value;
157
+ if (Array.isArray(value)) {
158
+ return value.map((item) => sanitizeJsonValue(item, depth + 1));
159
+ }
160
+ const src = value;
161
+ const out = {};
162
+ for (const key of Object.keys(src)) {
163
+ if (isUnsafeKey(key))
164
+ continue;
165
+ out[key] = sanitizeJsonValue(src[key], depth + 1);
166
+ }
167
+ return out;
168
+ }
169
+ function synthesizeSchema(value, depth = 0) {
170
+ if (depth >= MAX_JSON_SCHEMA_DEPTH)
171
+ return {};
172
+ if (value === null)
173
+ return { type: "null" };
174
+ if (Array.isArray(value)) {
175
+ return { type: "array", items: value.length ? synthesizeSchema(value[0], depth + 1) : {} };
176
+ }
177
+ if (isObject(value)) {
178
+ const entries = Object.entries(value)
179
+ .filter(([k]) => !isUnsafeKey(k))
180
+ .slice(0, MAX_JSON_SCHEMA_KEYS);
181
+ const properties = {};
182
+ const required = [];
183
+ for (const [k, v] of entries) {
184
+ properties[k] = synthesizeSchema(v, depth + 1);
185
+ required.push(k);
186
+ }
187
+ return { type: "object", required, properties };
188
+ }
189
+ if (Number.isInteger(value))
190
+ return { type: "integer" };
191
+ return { type: typeof value };
192
+ }
193
+ function extractSafeBodySnippet(text, secretValues) {
194
+ for (const line of text.split(/\r?\n/)) {
195
+ const trimmed = line.trim();
196
+ if (!trimmed)
197
+ continue;
198
+ const snippet = trimmed.slice(0, MAX_BODY_CONTAINS_SNIPPET);
199
+ for (const secret of secretValues) {
200
+ if (secret.length > 0 && snippet.includes(secret)) {
201
+ return null;
202
+ }
203
+ }
204
+ return snippet;
205
+ }
206
+ return null;
207
+ }
208
+ function slugify(text, fallback = "root") {
209
+ const s = String(text || "")
210
+ .toLowerCase()
211
+ .replace(/[^a-z0-9]+/g, "-")
212
+ .replace(/^-+|-+$/g, "")
213
+ .slice(0, 64);
214
+ return s || fallback;
215
+ }
216
+ function uniqueId(base, used) {
217
+ let id = slugify(base, "inv");
218
+ if (!id.startsWith("inv-"))
219
+ id = `inv-${id}`;
220
+ if (!used.has(id)) {
221
+ used.add(id);
222
+ return id;
223
+ }
224
+ let n = 2;
225
+ while (used.has(`${id}-${n}`))
226
+ n += 1;
227
+ const out = `${id}-${n}`;
228
+ used.add(out);
229
+ return out;
230
+ }
231
+ function normalizeTags(extra, base) {
232
+ const out = [];
233
+ for (const t of [...base, ...extra]) {
234
+ const trimmed = t.trim();
235
+ if (trimmed && !out.includes(trimmed))
236
+ out.push(trimmed);
237
+ }
238
+ return out;
239
+ }
240
+ function stripSensitiveHeaders(headers, secretValues) {
241
+ if (!isObject(headers))
242
+ return { safe: {}, redacted: false };
243
+ const candidate = {};
244
+ let redacted = false;
245
+ for (const [rawKey, rawVal] of Object.entries(headers)) {
246
+ const key = rawKey.trim();
247
+ if (!key || isUnsafeKey(key) || rawVal === undefined || rawVal === null)
248
+ continue;
249
+ const valStr = String(rawVal);
250
+ if (isCollectionSensitiveHeader(key) || SENSITIVE_HEADER_VALUE_RE.test(valStr)) {
251
+ redacted = true;
252
+ recordSecretValue(secretValues, valStr);
253
+ continue;
254
+ }
255
+ candidate[key] = valStr;
256
+ }
257
+ const safe = redactHeaders(candidate, "strip");
258
+ if (Object.keys(safe).length < Object.keys(candidate).length) {
259
+ redacted = true;
260
+ }
261
+ return { safe, redacted };
262
+ }
263
+ function deleteHeaderCaseInsensitive(headers, name) {
264
+ const lower = name.toLowerCase();
265
+ for (const k of Object.keys(headers)) {
266
+ if (k.toLowerCase() === lower)
267
+ delete headers[k];
268
+ }
269
+ }
270
+ function hasHeaderCaseInsensitive(headers, name) {
271
+ const lower = name.toLowerCase();
272
+ return Object.keys(headers).some((k) => k.toLowerCase() === lower);
273
+ }
274
+ function sanitizeBaseUrl(rawBase) {
275
+ if (!rawBase || !rawBase.trim())
276
+ return "";
277
+ try {
278
+ const trimmed = rawBase.trim();
279
+ const normalized = /^https?:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
280
+ const u = new URL(normalized);
281
+ if (u.protocol !== "http:" && u.protocol !== "https:")
282
+ return "";
283
+ u.username = "";
284
+ u.password = "";
285
+ const basePath = u.pathname.replace(/\/+$/, "");
286
+ return `${u.origin}${basePath}`;
287
+ }
288
+ catch {
289
+ return "";
290
+ }
291
+ }
292
+ function buildProbeUrl(baseUrl, pathname, query) {
293
+ const normalizedBase = /^https?:\/\//i.test(baseUrl) ? baseUrl : `http://${baseUrl}`;
294
+ const baseObj = new URL(normalizedBase);
295
+ baseObj.username = "";
296
+ baseObj.password = "";
297
+ const basePath = baseObj.pathname.replace(/\/+$/, "");
298
+ const cleanPath = pathname.startsWith("/") ? pathname : `/${pathname}`;
299
+ const url = new URL(baseObj.origin);
300
+ url.pathname = `${basePath}${cleanPath}` || "/";
301
+ for (const [k, v] of Object.entries(query)) {
302
+ if (!isUnsafeKey(k)) {
303
+ url.searchParams.set(k, v);
304
+ }
305
+ }
306
+ return url.toString();
307
+ }
308
+ async function defaultFetchJson(url, { method = "GET", headers = {}, body, timeoutMs = DEFAULT_PROBE_TIMEOUT_MS } = {}) {
309
+ const ctrl = new AbortController();
310
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
311
+ const upperMethod = method.toUpperCase();
312
+ const canHaveBody = upperMethod !== "GET" && upperMethod !== "HEAD";
313
+ const serializedBody = !canHaveBody || body === undefined || body === null
314
+ ? undefined
315
+ : typeof body === "string"
316
+ ? body
317
+ : JSON.stringify(body);
318
+ try {
319
+ const res = await fetch(url, {
320
+ method: upperMethod,
321
+ headers,
322
+ body: serializedBody,
323
+ signal: ctrl.signal
324
+ });
325
+ const text = await res.text();
326
+ let json = null;
327
+ try {
328
+ json = text ? sanitizeJsonValue(JSON.parse(text)) : null;
329
+ }
330
+ catch {
331
+ // non-JSON response body
332
+ }
333
+ const headersObj = {};
334
+ for (const [k, v] of res.headers.entries()) {
335
+ headersObj[k.toLowerCase()] = v;
336
+ }
337
+ return { status: res.status, headers: headersObj, text, json };
338
+ }
339
+ finally {
340
+ clearTimeout(timer);
341
+ }
342
+ }
343
+ function validateInvariantsOrThrow(invariants, kind) {
344
+ const contract = {
345
+ schemaVersion: "0.2.0",
346
+ target: {
347
+ name: kind,
348
+ domains: ["api"],
349
+ sources: [{ id: "src-1", kind, ref: "inline", meta: {} }]
350
+ },
351
+ artifacts: { root: ".vibecode/artifacts", files: {} },
352
+ thresholds: {
353
+ hardBehavioralParity: 1,
354
+ softPerceptualParity: 0.85,
355
+ softGateMode: "warn",
356
+ defaults: {}
357
+ },
358
+ invariants
359
+ };
360
+ const res = validateContract(contract);
361
+ if (!res.ok) {
362
+ const err = res.errors[0];
363
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `${kind} ingestor produced invalid invariant: ${err.path} ${err.message}`, { details: res.errors });
364
+ }
365
+ }
366
+ function interpolateSafeVars(template, ctx, secretReplacement) {
367
+ let out = template;
368
+ let hitSecret = false;
369
+ for (let pass = 0; pass < 2; pass += 1) {
370
+ let changed = false;
371
+ out = out.replace(TEMPLATE_VAR_RE, (full, rawExpr) => {
372
+ if (isUnsafeVarPath(rawExpr)) {
373
+ return full;
374
+ }
375
+ const key = normalizeVarName(rawExpr);
376
+ if (isSecretVarName(key, ctx.secretVarNames)) {
377
+ hitSecret = true;
378
+ return secretReplacement;
379
+ }
380
+ if (hasOwn(ctx.safeVars, key)) {
381
+ changed = true;
382
+ return ctx.safeVars[key];
383
+ }
384
+ return full;
385
+ });
386
+ if (!changed)
387
+ break;
388
+ }
389
+ return { value: out, hitSecret };
390
+ }
391
+ function interpolateJsonValue(value, ctx, depth = 0) {
392
+ if (depth >= MAX_SANITIZE_DEPTH)
393
+ return { value: null, hitSecret: false };
394
+ if (typeof value === "string") {
395
+ return interpolateSafeVars(value, ctx, "[REDACTED]");
396
+ }
397
+ if (Array.isArray(value)) {
398
+ let hitSecret = false;
399
+ const out = value.map((item) => {
400
+ const r = interpolateJsonValue(item, ctx, depth + 1);
401
+ if (r.hitSecret)
402
+ hitSecret = true;
403
+ return r.value;
404
+ });
405
+ return { value: out, hitSecret };
406
+ }
407
+ if (isObject(value)) {
408
+ let hitSecret = false;
409
+ const out = {};
410
+ for (const key of Object.keys(value)) {
411
+ if (isUnsafeKey(key))
412
+ continue;
413
+ const r = interpolateJsonValue(value[key], ctx, depth + 1);
414
+ if (r.hitSecret)
415
+ hitSecret = true;
416
+ out[key] = r.value;
417
+ }
418
+ return { value: out, hitSecret };
419
+ }
420
+ return { value, hitSecret: false };
421
+ }
422
+ function stripRawTemplateUrlSecrets(rawUrl, secretValues, secretVarNames) {
423
+ let redactedSecrets = false;
424
+ let cleaned = rawUrl.trim();
425
+ // Strip basic-auth userinfo even if host contains templates
426
+ cleaned = cleaned.replace(URL_USERINFO_RE, (_m, scheme, user, pass) => {
427
+ redactedSecrets = true;
428
+ try {
429
+ recordSecretValue(secretValues, decodeURIComponent(user));
430
+ recordSecretValue(secretValues, decodeURIComponent(pass));
431
+ }
432
+ catch {
433
+ recordSecretValue(secretValues, user);
434
+ recordSecretValue(secretValues, pass);
435
+ }
436
+ return scheme;
437
+ });
438
+ cleaned = cleaned.replace(URL_USERONLY_RE, (_m, scheme, user) => {
439
+ redactedSecrets = true;
440
+ try {
441
+ recordSecretValue(secretValues, decodeURIComponent(user));
442
+ }
443
+ catch {
444
+ recordSecretValue(secretValues, user);
445
+ }
446
+ return scheme;
447
+ });
448
+ // Separate hash and query
449
+ const hashIdx = cleaned.indexOf("#");
450
+ if (hashIdx >= 0) {
451
+ cleaned = cleaned.slice(0, hashIdx);
452
+ }
453
+ const qIdx = cleaned.indexOf("?");
454
+ const query = {};
455
+ if (qIdx < 0) {
456
+ return { sanitizedUrl: cleaned, query, redactedSecrets };
457
+ }
458
+ const basePart = cleaned.slice(0, qIdx);
459
+ const rawQuery = cleaned.slice(qIdx + 1);
460
+ const safeParams = new URLSearchParams();
461
+ const parsedParams = new URLSearchParams(rawQuery);
462
+ for (const [k, v] of parsedParams.entries()) {
463
+ const trimmedKey = k.trim();
464
+ if (!trimmedKey || isUnsafeKey(trimmedKey))
465
+ continue;
466
+ if (isCollectionSensitiveQueryParam(trimmedKey) ||
467
+ k.includes(SECRET_SENTINEL) ||
468
+ v.includes(SECRET_SENTINEL) ||
469
+ containsSecretPlaceholder(k, secretVarNames) ||
470
+ containsSecretPlaceholder(v, secretVarNames)) {
471
+ redactedSecrets = true;
472
+ recordSecretValue(secretValues, v);
473
+ continue;
474
+ }
475
+ safeParams.append(k, v);
476
+ query[k] = v;
477
+ }
478
+ const serialized = safeParams.toString();
479
+ return {
480
+ sanitizedUrl: serialized ? `${basePart}?${serialized}` : basePart,
481
+ query,
482
+ redactedSecrets
483
+ };
484
+ }
485
+ function parseAndSanitizeUrl(rawUrl, ctx, baseUrlOverride) {
486
+ const interp = interpolateSafeVars(rawUrl.trim(), ctx, SECRET_SENTINEL);
487
+ let redactedSecrets = interp.hitSecret;
488
+ let candidate = interp.value.trim();
489
+ if (!candidate)
490
+ return null;
491
+ // Strip leading unresolved variable placeholder (e.g. {{ _.baseUrl }}/v1/users)
492
+ const leadingVar = /^\{\{\s*([^{}\s][^{}]*?)\s*\}\}/.exec(candidate);
493
+ if (leadingVar) {
494
+ if (isSecretVarName(leadingVar[1], ctx.secretVarNames)) {
495
+ redactedSecrets = true;
496
+ }
497
+ candidate = candidate.slice(leadingVar[0].length) || "/";
498
+ }
499
+ else if (candidate.startsWith(SECRET_SENTINEL)) {
500
+ redactedSecrets = true;
501
+ candidate = candidate.slice(SECRET_SENTINEL.length) || "/";
502
+ }
503
+ // Strip userinfo before URL parsing in case templates remain in host
504
+ candidate = candidate.replace(URL_USERINFO_RE, (_m, scheme, user, pass) => {
505
+ redactedSecrets = true;
506
+ try {
507
+ recordSecretValue(ctx.secretValues, decodeURIComponent(user));
508
+ recordSecretValue(ctx.secretValues, decodeURIComponent(pass));
509
+ }
510
+ catch {
511
+ recordSecretValue(ctx.secretValues, user);
512
+ recordSecretValue(ctx.secretValues, pass);
513
+ }
514
+ return scheme;
515
+ });
516
+ candidate = candidate.replace(URL_USERONLY_RE, (_m, scheme, user) => {
517
+ redactedSecrets = true;
518
+ try {
519
+ recordSecretValue(ctx.secretValues, decodeURIComponent(user));
520
+ }
521
+ catch {
522
+ recordSecretValue(ctx.secretValues, user);
523
+ }
524
+ return scheme;
525
+ });
526
+ const safeBase = sanitizeBaseUrl(baseUrlOverride);
527
+ let parsed = null;
528
+ let hasExplicitOrigin = false;
529
+ const tryParse = (input) => {
530
+ try {
531
+ const u = new URL(input);
532
+ if (u.protocol !== "http:" && u.protocol !== "https:")
533
+ return null;
534
+ return u;
535
+ }
536
+ catch {
537
+ return null;
538
+ }
539
+ };
540
+ if (/^https?:\/\//i.test(candidate)) {
541
+ parsed = tryParse(candidate);
542
+ if (parsed) {
543
+ hasExplicitOrigin = true;
544
+ }
545
+ else {
546
+ // Salvage path + query when authority contains unresolved template
547
+ const authMatch = /^https?:\/\/[^/?#]*(.*)$/i.exec(candidate);
548
+ const rest = authMatch?.[1] || "/";
549
+ const fallbackOrigin = safeBase || "http://localhost";
550
+ parsed = tryParse(`${fallbackOrigin}${rest.startsWith("/") || rest.startsWith("?") ? rest : `/${rest}`}`);
551
+ hasExplicitOrigin = Boolean(safeBase);
552
+ }
553
+ }
554
+ else if (candidate.startsWith("/") || candidate.startsWith("?")) {
555
+ const base = safeBase || "http://localhost";
556
+ const joined = candidate.startsWith("?") ? `${base}/${candidate}` : `${base}${candidate}`;
557
+ parsed = tryParse(joined);
558
+ hasExplicitOrigin = Boolean(safeBase);
559
+ }
560
+ else {
561
+ // Schemeless host/path like "api.example.com/v1/items" or "localhost:3000/health"
562
+ const hostPart = candidate.split(/[/?#]/)[0] || "";
563
+ const isLocalHost = /^localhost(?::\d+)?$/i.test(hostPart) ||
564
+ /^127\.0\.0\.1(?::\d+)?$/.test(hostPart) ||
565
+ /^\[::1\](?::\d+)?$/.test(hostPart);
566
+ const scheme = isLocalHost ? "http" : "https";
567
+ parsed = tryParse(`${scheme}://${candidate}`);
568
+ if (parsed && !TEMPLATE_VAR_TEST_RE.test(hostPart) && !hostPart.includes(SECRET_SENTINEL)) {
569
+ hasExplicitOrigin = true;
570
+ }
571
+ else {
572
+ const restMatch = /^[^/?#]*(.*)$/.exec(candidate);
573
+ const rest = restMatch?.[1] || "/";
574
+ const fallbackOrigin = safeBase || "http://localhost";
575
+ parsed = tryParse(`${fallbackOrigin}${rest.startsWith("/") || rest.startsWith("?") ? rest : `/${rest}`}`);
576
+ hasExplicitOrigin = Boolean(safeBase);
577
+ }
578
+ }
579
+ if (!parsed)
580
+ return null;
581
+ if (parsed.username || parsed.password) {
582
+ redactedSecrets = true;
583
+ try {
584
+ if (parsed.username)
585
+ recordSecretValue(ctx.secretValues, decodeURIComponent(parsed.username));
586
+ if (parsed.password)
587
+ recordSecretValue(ctx.secretValues, decodeURIComponent(parsed.password));
588
+ }
589
+ catch {
590
+ if (parsed.username)
591
+ recordSecretValue(ctx.secretValues, parsed.username);
592
+ if (parsed.password)
593
+ recordSecretValue(ctx.secretValues, parsed.password);
594
+ }
595
+ parsed.username = "";
596
+ parsed.password = "";
597
+ }
598
+ // Sanitize path segments
599
+ let rawPathname = parsed.pathname || "/";
600
+ try {
601
+ rawPathname = decodeURIComponent(rawPathname);
602
+ }
603
+ catch {
604
+ // keep original pathname
605
+ }
606
+ const pathSegments = [];
607
+ for (const part of rawPathname.split("/").filter((s) => s.length > 0)) {
608
+ if (part.includes(SECRET_SENTINEL)) {
609
+ redactedSecrets = true;
610
+ pathSegments.push("REDACTED");
611
+ continue;
612
+ }
613
+ const cleanPart = part.replace(TEMPLATE_VAR_RE, (full, expr) => {
614
+ if (isSecretVarName(expr, ctx.secretVarNames)) {
615
+ redactedSecrets = true;
616
+ return "REDACTED";
617
+ }
618
+ return "sample";
619
+ });
620
+ pathSegments.push(encodeURIComponent(cleanPart));
621
+ }
622
+ const pathname = pathSegments.length > 0 ? `/${pathSegments.join("/")}` : "/";
623
+ // Sanitize query params
624
+ const safeSearchParams = new URLSearchParams();
625
+ const query = {};
626
+ for (const [k, v] of parsed.searchParams.entries()) {
627
+ const trimmedKey = k.trim();
628
+ if (!trimmedKey || isUnsafeKey(trimmedKey))
629
+ continue;
630
+ if (isCollectionSensitiveQueryParam(trimmedKey) ||
631
+ k.includes(SECRET_SENTINEL) ||
632
+ v.includes(SECRET_SENTINEL) ||
633
+ TEMPLATE_VAR_TEST_RE.test(k) ||
634
+ (TEMPLATE_VAR_TEST_RE.test(v) && containsSecretPlaceholder(v, ctx.secretVarNames))) {
635
+ redactedSecrets = true;
636
+ recordSecretValue(ctx.secretValues, v);
637
+ continue;
638
+ }
639
+ safeSearchParams.append(k, v);
640
+ query[k] = v;
641
+ }
642
+ const origin = hasExplicitOrigin ? parsed.origin : "";
643
+ const searchStr = safeSearchParams.toString();
644
+ const sanitizedUrl = origin
645
+ ? `${origin}${pathname}${searchStr ? `?${searchStr}` : ""}`
646
+ : `${pathname}${searchStr ? `?${searchStr}` : ""}`;
647
+ return {
648
+ origin,
649
+ pathname,
650
+ query,
651
+ sanitizedUrl,
652
+ hasExplicitOrigin,
653
+ redactedSecrets
654
+ };
655
+ }
656
+ function containsSecretPlaceholder(text, secretVarNames) {
657
+ TEMPLATE_VAR_RE.lastIndex = 0;
658
+ let match;
659
+ while ((match = TEMPLATE_VAR_RE.exec(text)) !== null) {
660
+ if (isSecretVarName(match[1], secretVarNames))
661
+ return true;
662
+ }
663
+ return false;
664
+ }
665
+ function collectSecretsFromAuthObject(auth, secretValues) {
666
+ if (!isObject(auth))
667
+ return false;
668
+ let found = false;
669
+ const authType = typeof auth.type === "string" ? auth.type.trim().toLowerCase() : "";
670
+ if (authType && authType !== "none") {
671
+ found = true;
672
+ }
673
+ const secretFields = [
674
+ "token",
675
+ "password",
676
+ "value",
677
+ "key",
678
+ "apiKey",
679
+ "secret",
680
+ "clientSecret",
681
+ "accessToken",
682
+ "refreshToken",
683
+ "privateKey",
684
+ "username"
685
+ ];
686
+ for (const field of secretFields) {
687
+ if (hasOwn(auth, field) && typeof auth[field] === "string" && auth[field].trim().length > 0) {
688
+ found = true;
689
+ recordSecretValue(secretValues, auth[field]);
690
+ }
691
+ }
692
+ return found;
693
+ }
694
+ // ============================================================================
695
+ // 1. Insomnia v4 Export Detection & Ingestor
696
+ // ============================================================================
697
+ export function isInsomniaExportDoc(doc) {
698
+ if (!isObject(doc))
699
+ return false;
700
+ // Reject OpenAPI, Swagger, HAR, Postman, and vibecode contracts via own properties
701
+ if (hasOwn(doc, "openapi") || hasOwn(doc, "swagger"))
702
+ return false;
703
+ if (hasOwn(doc, "paths") && isObject(doc.paths))
704
+ return false;
705
+ if (hasOwn(doc, "log") && isObject(doc.log) && hasOwn(doc.log, "entries") && Array.isArray(doc.log.entries)) {
706
+ return false;
707
+ }
708
+ if (hasOwn(doc, "invariants") || (hasOwn(doc, "contract") && isObject(doc.contract)))
709
+ return false;
710
+ if (hasOwn(doc, "info") && isObject(doc.info) && hasOwn(doc, "item") && Array.isArray(doc.item))
711
+ return false;
712
+ if (!hasOwn(doc, "_type") || doc._type !== "export")
713
+ return false;
714
+ if (!hasOwn(doc, "__export_format"))
715
+ return false;
716
+ const fmt = doc.__export_format;
717
+ if (typeof fmt !== "number" || !Number.isFinite(fmt) || fmt < 4)
718
+ return false;
719
+ if (!hasOwn(doc, "resources") || !Array.isArray(doc.resources))
720
+ return false;
721
+ return doc.resources.some((entry) => isObject(entry) &&
722
+ hasOwn(entry, "_type") &&
723
+ (entry._type === "request" || entry._type === "environment" || entry._type === "base_environment"));
724
+ }
725
+ function flattenEnvData(obj, prefix, ctx, depth = 0) {
726
+ if (depth >= 8)
727
+ return false;
728
+ let redacted = false;
729
+ for (const key of Object.keys(obj)) {
730
+ if (isUnsafeKey(key))
731
+ continue;
732
+ const fullKey = prefix ? `${prefix}.${key}` : key;
733
+ const val = obj[key];
734
+ if (isSecretVarName(fullKey, ctx.secretVarNames) || isSecretVarName(key, ctx.secretVarNames)) {
735
+ ctx.secretVarNames.add(fullKey.toLowerCase());
736
+ ctx.secretVarNames.add(key.toLowerCase());
737
+ redacted = true;
738
+ if (typeof val === "string") {
739
+ recordSecretValue(ctx.secretValues, val);
740
+ }
741
+ else if (isObject(val)) {
742
+ // Record nested secret values without storing them
743
+ for (const v of Object.values(val)) {
744
+ if (typeof v === "string")
745
+ recordSecretValue(ctx.secretValues, v);
746
+ }
747
+ }
748
+ continue;
749
+ }
750
+ if (isObject(val)) {
751
+ if (flattenEnvData(val, fullKey, ctx, depth + 1))
752
+ redacted = true;
753
+ }
754
+ else if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
755
+ setSafeProp(ctx.safeVars, fullKey, String(val));
756
+ }
757
+ }
758
+ return redacted;
759
+ }
760
+ function sortKeyNum(val) {
761
+ return typeof val === "number" && Number.isFinite(val) ? val : Number.POSITIVE_INFINITY;
762
+ }
763
+ function buildInsomniaEnvContext(resources) {
764
+ const ctx = {
765
+ safeVars: createNullRecord(),
766
+ secretVarNames: new Set(),
767
+ secretValues: new Set()
768
+ };
769
+ const envs = [];
770
+ const envIds = new Set();
771
+ resources.forEach((entry, index) => {
772
+ if (!isObject(entry) || !hasOwn(entry, "_type"))
773
+ return;
774
+ if (entry._type === "environment" || entry._type === "base_environment") {
775
+ envs.push({ res: entry, index });
776
+ if (hasOwn(entry, "_id") && typeof entry._id === "string" && entry._id) {
777
+ envIds.add(entry._id);
778
+ }
779
+ }
780
+ });
781
+ // Apply base environments first, then sub-environments deterministically
782
+ envs.sort((a, b) => {
783
+ const aIsBase = a.res._type === "base_environment" ||
784
+ !hasOwn(a.res, "parentId") ||
785
+ typeof a.res.parentId !== "string" ||
786
+ !envIds.has(a.res.parentId);
787
+ const bIsBase = b.res._type === "base_environment" ||
788
+ !hasOwn(b.res, "parentId") ||
789
+ typeof b.res.parentId !== "string" ||
790
+ !envIds.has(b.res.parentId);
791
+ if (aIsBase !== bIsBase)
792
+ return aIsBase ? -1 : 1;
793
+ const sa = sortKeyNum(hasOwn(a.res, "metaSortKey") ? a.res.metaSortKey : undefined);
794
+ const sb = sortKeyNum(hasOwn(b.res, "metaSortKey") ? b.res.metaSortKey : undefined);
795
+ if (sa !== sb)
796
+ return sa - sb;
797
+ const na = hasOwn(a.res, "name") && typeof a.res.name === "string" ? a.res.name : "";
798
+ const nb = hasOwn(b.res, "name") && typeof b.res.name === "string" ? b.res.name : "";
799
+ if (na !== nb)
800
+ return na.localeCompare(nb);
801
+ return a.index - b.index;
802
+ });
803
+ let redactedSecrets = false;
804
+ for (const { res } of envs) {
805
+ if (hasOwn(res, "data") && isObject(res.data)) {
806
+ if (flattenEnvData(res.data, "", ctx, 0))
807
+ redactedSecrets = true;
808
+ }
809
+ }
810
+ return { ctx, redactedSecrets };
811
+ }
812
+ function resolveInsomniaFolderTrail(parentId, groupMap) {
813
+ const trail = [];
814
+ const visited = new Set();
815
+ let curr = typeof parentId === "string" ? parentId : null;
816
+ let depth = 0;
817
+ while (curr && depth < MAX_FOLDER_DEPTH) {
818
+ if (visited.has(curr) || !hasOwn(groupMap, curr))
819
+ break;
820
+ visited.add(curr);
821
+ const group = groupMap[curr];
822
+ if (group.name)
823
+ trail.unshift(group.name);
824
+ curr = group.parentId;
825
+ depth += 1;
826
+ }
827
+ return trail;
828
+ }
829
+ function parseInsomniaRequestBody(rawBody, ctx) {
830
+ if (!isObject(rawBody))
831
+ return { body: undefined, isJson: false, redacted: false };
832
+ const mimeType = hasOwn(rawBody, "mimeType") && typeof rawBody.mimeType === "string"
833
+ ? rawBody.mimeType.trim().toLowerCase()
834
+ : "";
835
+ if (mimeType.includes("application/x-www-form-urlencoded") && hasOwn(rawBody, "params") && Array.isArray(rawBody.params)) {
836
+ const params = new URLSearchParams();
837
+ let redacted = false;
838
+ for (const entry of rawBody.params) {
839
+ if (!isObject(entry) || (hasOwn(entry, "disabled") && entry.disabled === true))
840
+ continue;
841
+ const rawName = hasOwn(entry, "name") && typeof entry.name === "string" ? entry.name.trim() : "";
842
+ const rawVal = hasOwn(entry, "value") && entry.value !== undefined && entry.value !== null ? String(entry.value) : "";
843
+ if (!rawName || isUnsafeKey(rawName))
844
+ continue;
845
+ if (isCollectionSensitiveQueryParam(rawName) ||
846
+ containsSecretPlaceholder(rawName, ctx.secretVarNames) ||
847
+ containsSecretPlaceholder(rawVal, ctx.secretVarNames)) {
848
+ redacted = true;
849
+ recordSecretValue(ctx.secretValues, rawVal);
850
+ continue;
851
+ }
852
+ const interpName = interpolateSafeVars(rawName, ctx, SECRET_SENTINEL);
853
+ const interpVal = interpolateSafeVars(rawVal, ctx, SECRET_SENTINEL);
854
+ if (interpName.hitSecret || interpVal.hitSecret) {
855
+ redacted = true;
856
+ continue;
857
+ }
858
+ params.append(interpName.value, interpVal.value);
859
+ }
860
+ const serialized = params.toString();
861
+ return { body: serialized || undefined, isJson: false, redacted };
862
+ }
863
+ const rawText = hasOwn(rawBody, "text") && typeof rawBody.text === "string" ? rawBody.text : "";
864
+ if (!rawText.trim())
865
+ return { body: undefined, isJson: false, redacted: false };
866
+ const interp = interpolateSafeVars(rawText, ctx, "[REDACTED]");
867
+ const trimmed = interp.value.trim();
868
+ const isGraphqlMime = mimeType.includes("graphql");
869
+ const looksJson = isGraphqlMime ||
870
+ mimeType.includes("json") ||
871
+ trimmed.startsWith("{") ||
872
+ trimmed.startsWith("[");
873
+ if (looksJson) {
874
+ try {
875
+ const parsed = sanitizeJsonValue(JSON.parse(trimmed));
876
+ return { body: parsed, isJson: true, redacted: interp.hitSecret };
877
+ }
878
+ catch {
879
+ return { body: interp.value, isJson: false, redacted: interp.hitSecret };
880
+ }
881
+ }
882
+ return { body: interp.value, isJson: false, redacted: interp.hitSecret };
883
+ }
884
+ function parseJsonOrYamlDoc(rawText, fileExt) {
885
+ const text = stripBom(rawText);
886
+ const trimmed = text.trim();
887
+ if (!trimmed) {
888
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "Insomnia export input is empty");
889
+ }
890
+ const preferJson = fileExt === ".json" || trimmed.startsWith("{") || trimmed.startsWith("[");
891
+ if (preferJson) {
892
+ try {
893
+ return JSON.parse(trimmed);
894
+ }
895
+ catch (jsonErr) {
896
+ if (fileExt === ".json") {
897
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid JSON in Insomnia export: ${errorMessage(jsonErr)}`);
898
+ }
899
+ try {
900
+ return parseYaml(text);
901
+ }
902
+ catch (yamlErr) {
903
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid JSON/YAML in Insomnia export: ${errorMessage(yamlErr)}`);
904
+ }
905
+ }
906
+ }
907
+ try {
908
+ return parseYaml(text);
909
+ }
910
+ catch (yamlErr) {
911
+ try {
912
+ return JSON.parse(trimmed);
913
+ }
914
+ catch {
915
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid YAML in Insomnia export: ${errorMessage(yamlErr)}`);
916
+ }
917
+ }
918
+ }
919
+ export async function importInsomniaExport(source, options = {}, deps = {}) {
920
+ if (typeof source !== "string" || !source.trim()) {
921
+ throw new VibecodeError("TARGET_MISSING", "Insomnia ingestor requires a file path or inline JSON/YAML export");
922
+ }
923
+ const cwd = options.cwd || process.cwd();
924
+ const trimmedSource = source.trim();
925
+ let rawText = "";
926
+ let isFileSource = false;
927
+ let fileExt = "";
928
+ if (!/[\r\n]/.test(trimmedSource)) {
929
+ const candidatePath = path.resolve(cwd, trimmedSource);
930
+ const ext = path.extname(candidatePath).toLowerCase();
931
+ let stat = null;
932
+ try {
933
+ if (fs.existsSync(candidatePath)) {
934
+ stat = fs.statSync(candidatePath);
935
+ }
936
+ }
937
+ catch {
938
+ stat = null;
939
+ }
940
+ if (stat) {
941
+ if (!stat.isFile()) {
942
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Insomnia source is not a regular file: ${trimmedSource}`);
943
+ }
944
+ if (stat.size > MAX_SOURCE_BYTES) {
945
+ throw new VibecodeError("CONTRACT_INVALID", `Insomnia export exceeds maximum size of ${MAX_SOURCE_BYTES} bytes`);
946
+ }
947
+ isFileSource = true;
948
+ fileExt = ext;
949
+ try {
950
+ rawText = fs.readFileSync(candidatePath, "utf8");
951
+ }
952
+ catch (err) {
953
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Failed to read Insomnia export: ${errorMessage(err)}`);
954
+ }
955
+ }
956
+ else if ((ext === ".json" || ext === ".yaml" || ext === ".yml") &&
957
+ !trimmedSource.startsWith("{") &&
958
+ !trimmedSource.includes("_type:")) {
959
+ throw new VibecodeError("TARGET_MISSING", `Insomnia export file not found: ${trimmedSource}`);
960
+ }
961
+ }
962
+ if (!isFileSource) {
963
+ if (Buffer.byteLength(source, "utf8") > MAX_SOURCE_BYTES) {
964
+ throw new VibecodeError("CONTRACT_INVALID", `Inline Insomnia export exceeds maximum size of ${MAX_SOURCE_BYTES} bytes`);
965
+ }
966
+ rawText = source;
967
+ }
968
+ const doc = parseJsonOrYamlDoc(rawText, fileExt);
969
+ if (!isInsomniaExportDoc(doc)) {
970
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "Input is not a valid Insomnia v4 export document");
971
+ }
972
+ const resources = doc.resources;
973
+ const { ctx, redactedSecrets: envRedacted } = buildInsomniaEnvContext(resources);
974
+ let anyRedactedSecrets = envRedacted;
975
+ let workspaceName = "";
976
+ const groupMap = createNullRecord();
977
+ const rawRequests = [];
978
+ resources.forEach((entry, index) => {
979
+ if (!isObject(entry) || !hasOwn(entry, "_type"))
980
+ return;
981
+ if (entry._type === "workspace" && !workspaceName && hasOwn(entry, "name") && typeof entry.name === "string") {
982
+ workspaceName = entry.name.trim();
983
+ }
984
+ else if (entry._type === "request_group" && hasOwn(entry, "_id") && typeof entry._id === "string") {
985
+ const name = hasOwn(entry, "name") && typeof entry.name === "string" ? entry.name.trim() : "";
986
+ const parentId = hasOwn(entry, "parentId") && typeof entry.parentId === "string" && entry.parentId.trim()
987
+ ? entry.parentId.trim()
988
+ : null;
989
+ setSafeProp(groupMap, entry._id, { name, parentId });
990
+ }
991
+ else if (entry._type === "request") {
992
+ rawRequests.push({ res: entry, index });
993
+ }
994
+ });
995
+ // Deterministic ordering by metaSortKey, then name, then _id, then index
996
+ rawRequests.sort((a, b) => {
997
+ const sa = sortKeyNum(hasOwn(a.res, "metaSortKey") ? a.res.metaSortKey : undefined);
998
+ const sb = sortKeyNum(hasOwn(b.res, "metaSortKey") ? b.res.metaSortKey : undefined);
999
+ if (sa !== sb)
1000
+ return sa - sb;
1001
+ const na = hasOwn(a.res, "name") && typeof a.res.name === "string" ? a.res.name : "";
1002
+ const nb = hasOwn(b.res, "name") && typeof b.res.name === "string" ? b.res.name : "";
1003
+ if (na !== nb)
1004
+ return na.localeCompare(nb);
1005
+ const ia = hasOwn(a.res, "_id") && typeof a.res._id === "string" ? a.res._id : "";
1006
+ const ib = hasOwn(b.res, "_id") && typeof b.res._id === "string" ? b.res._id : "";
1007
+ if (ia !== ib)
1008
+ return ia.localeCompare(ib);
1009
+ return a.index - b.index;
1010
+ });
1011
+ const includeMutating = options.includeMutating === true;
1012
+ const offline = options.offline === true;
1013
+ const baseUrlOverride = typeof options.baseUrl === "string" && options.baseUrl.trim() ? options.baseUrl.trim() : "";
1014
+ const globalHeaders = isObject(options.headers) ? options.headers : undefined;
1015
+ const timeoutMs = typeof deps.timeoutMs === "number" && deps.timeoutMs > 0 ? deps.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS;
1016
+ const doFetch = deps.fetchJson || defaultFetchJson;
1017
+ if (globalHeaders) {
1018
+ for (const [k, v] of Object.entries(globalHeaders)) {
1019
+ if (isCollectionSensitiveHeader(k) && typeof v === "string") {
1020
+ recordSecretValue(ctx.secretValues, v);
1021
+ }
1022
+ }
1023
+ }
1024
+ const warnings = [];
1025
+ const invariants = [];
1026
+ const usedIds = new Set();
1027
+ let skippedMutatingCount = 0;
1028
+ let truncatedByCap = false;
1029
+ let firstOrigin = "";
1030
+ for (const { res } of rawRequests) {
1031
+ // Always scrub authentication secrets even for skipped requests
1032
+ if (hasOwn(res, "authentication") && collectSecretsFromAuthObject(res.authentication, ctx.secretValues)) {
1033
+ anyRedactedSecrets = true;
1034
+ }
1035
+ const rawMethod = hasOwn(res, "method") && typeof res.method === "string" && res.method.trim()
1036
+ ? res.method.trim().toUpperCase()
1037
+ : "GET";
1038
+ if (!ALL_HTTP_METHODS.has(rawMethod))
1039
+ continue;
1040
+ if (MUTATING_METHODS.has(rawMethod) && !includeMutating) {
1041
+ skippedMutatingCount += 1;
1042
+ continue;
1043
+ }
1044
+ if (invariants.length >= MAX_REQUESTS) {
1045
+ truncatedByCap = true;
1046
+ break;
1047
+ }
1048
+ const reqName = hasOwn(res, "name") && typeof res.name === "string" ? res.name.trim() : "";
1049
+ const folderTrail = resolveInsomniaFolderTrail(hasOwn(res, "parentId") ? res.parentId : null, groupMap);
1050
+ const rawUrl = hasOwn(res, "url") && typeof res.url === "string" ? res.url : "";
1051
+ const parsedUrl = parseAndSanitizeUrl(rawUrl, ctx, baseUrlOverride || undefined);
1052
+ if (!parsedUrl) {
1053
+ warnings.push({
1054
+ code: "BRIDGE_FORMAT_WARNING",
1055
+ message: `Skipped Insomnia request "${[...folderTrail, reqName || rawMethod].join(" / ")}" with missing or invalid URL.`
1056
+ });
1057
+ continue;
1058
+ }
1059
+ if (parsedUrl.redactedSecrets)
1060
+ anyRedactedSecrets = true;
1061
+ if (!firstOrigin && parsedUrl.origin)
1062
+ firstOrigin = parsedUrl.origin;
1063
+ // Merge Insomnia parameters (query params)
1064
+ const query = { ...parsedUrl.query };
1065
+ if (hasOwn(res, "parameters") && Array.isArray(res.parameters)) {
1066
+ for (const param of res.parameters) {
1067
+ if (!isObject(param) || (hasOwn(param, "disabled") && param.disabled === true))
1068
+ continue;
1069
+ const rawKey = hasOwn(param, "name") && typeof param.name === "string" ? param.name.trim() : "";
1070
+ const rawVal = hasOwn(param, "value") && param.value !== undefined && param.value !== null ? String(param.value) : "";
1071
+ if (!rawKey || isUnsafeKey(rawKey))
1072
+ continue;
1073
+ if (isCollectionSensitiveQueryParam(rawKey) ||
1074
+ containsSecretPlaceholder(rawKey, ctx.secretVarNames) ||
1075
+ containsSecretPlaceholder(rawVal, ctx.secretVarNames)) {
1076
+ anyRedactedSecrets = true;
1077
+ recordSecretValue(ctx.secretValues, rawVal);
1078
+ continue;
1079
+ }
1080
+ const kInterp = interpolateSafeVars(rawKey, ctx, SECRET_SENTINEL);
1081
+ const vInterp = interpolateSafeVars(rawVal, ctx, SECRET_SENTINEL);
1082
+ const resolvedKey = kInterp.value.trim();
1083
+ if (resolvedKey && isUnsafeKey(resolvedKey))
1084
+ continue;
1085
+ if (kInterp.hitSecret || vInterp.hitSecret || isCollectionSensitiveQueryParam(resolvedKey)) {
1086
+ anyRedactedSecrets = true;
1087
+ recordSecretValue(ctx.secretValues, rawVal);
1088
+ continue;
1089
+ }
1090
+ if (resolvedKey) {
1091
+ query[resolvedKey] = vInterp.value;
1092
+ }
1093
+ }
1094
+ }
1095
+ // Collect & sanitize request headers
1096
+ const rawSafeHeaders = {};
1097
+ if (hasOwn(res, "headers") && Array.isArray(res.headers)) {
1098
+ for (const hdr of res.headers) {
1099
+ if (!isObject(hdr) || (hasOwn(hdr, "disabled") && hdr.disabled === true))
1100
+ continue;
1101
+ const rawKey = hasOwn(hdr, "name") && typeof hdr.name === "string" ? hdr.name.trim() : "";
1102
+ const rawVal = hasOwn(hdr, "value") && hdr.value !== undefined && hdr.value !== null ? String(hdr.value) : "";
1103
+ if (!rawKey || isUnsafeKey(rawKey))
1104
+ continue;
1105
+ if (isCollectionSensitiveHeader(rawKey) ||
1106
+ SENSITIVE_HEADER_VALUE_RE.test(rawVal) ||
1107
+ containsSecretPlaceholder(rawKey, ctx.secretVarNames) ||
1108
+ containsSecretPlaceholder(rawVal, ctx.secretVarNames)) {
1109
+ anyRedactedSecrets = true;
1110
+ recordSecretValue(ctx.secretValues, rawVal);
1111
+ continue;
1112
+ }
1113
+ const vInterp = interpolateSafeVars(rawVal, ctx, SECRET_SENTINEL);
1114
+ if (vInterp.hitSecret || vInterp.value.includes(SECRET_SENTINEL) || SENSITIVE_HEADER_VALUE_RE.test(vInterp.value)) {
1115
+ anyRedactedSecrets = true;
1116
+ recordSecretValue(ctx.secretValues, vInterp.value);
1117
+ continue;
1118
+ }
1119
+ rawSafeHeaders[rawKey] = vInterp.value;
1120
+ }
1121
+ }
1122
+ const { body, isJson, redacted: bodyRedacted } = parseInsomniaRequestBody(hasOwn(res, "body") ? res.body : undefined, ctx);
1123
+ if (bodyRedacted)
1124
+ anyRedactedSecrets = true;
1125
+ if (isJson && body !== undefined && !hasHeaderCaseInsensitive(rawSafeHeaders, "content-type")) {
1126
+ rawSafeHeaders["content-type"] = "application/json";
1127
+ }
1128
+ const probeHeaders = mergeHeaders(rawSafeHeaders, globalHeaders);
1129
+ deleteHeaderCaseInsensitive(probeHeaders, "host");
1130
+ const { safe: persistedHeaders, redacted: mergedRedacted } = stripSensitiveHeaders(mergeHeaders(rawSafeHeaders, globalHeaders), ctx.secretValues);
1131
+ deleteHeaderCaseInsensitive(persistedHeaders, "host");
1132
+ if (mergedRedacted)
1133
+ anyRedactedSecrets = true;
1134
+ const effectiveProbeBase = sanitizeBaseUrl(baseUrlOverride) || parsedUrl.origin;
1135
+ let observed = null;
1136
+ let probeFailed = null;
1137
+ if (!offline && effectiveProbeBase) {
1138
+ const probeUrl = buildProbeUrl(effectiveProbeBase, parsedUrl.pathname, query);
1139
+ try {
1140
+ observed = await doFetch(probeUrl, {
1141
+ method: rawMethod,
1142
+ headers: probeHeaders,
1143
+ body,
1144
+ timeoutMs
1145
+ });
1146
+ }
1147
+ catch (err) {
1148
+ probeFailed = err;
1149
+ }
1150
+ }
1151
+ const expected = {};
1152
+ if (observed) {
1153
+ expected.status = observed.status;
1154
+ if (observed.json !== null && (isObject(observed.json) || Array.isArray(observed.json))) {
1155
+ expected.jsonSchema = synthesizeSchema(observed.json);
1156
+ if (isObject(observed.json)) {
1157
+ expected.jsonSubset = observed.json;
1158
+ }
1159
+ }
1160
+ else if (observed.text.trim().length > 0) {
1161
+ const snippet = extractSafeBodySnippet(observed.text, ctx.secretValues);
1162
+ if (snippet)
1163
+ expected.bodyContains = [snippet];
1164
+ }
1165
+ }
1166
+ else {
1167
+ expected.status = 200;
1168
+ if (offline) {
1169
+ warnings.push({
1170
+ code: "ADAPTER_DEGRADED",
1171
+ message: `Offline spec-only mode: emitted ${rawMethod} ${parsedUrl.pathname} without live HTTP probe.`
1172
+ });
1173
+ }
1174
+ else if (!effectiveProbeBase) {
1175
+ warnings.push({
1176
+ code: "ADAPTER_DEGRADED",
1177
+ message: `No reachable baseUrl for ${rawMethod} ${parsedUrl.pathname}; emitted spec-only status 200.`
1178
+ });
1179
+ }
1180
+ else {
1181
+ const safeErr = redactKnownSecrets(probeFailed ? errorMessage(probeFailed) : "unknown error", ctx.secretValues);
1182
+ warnings.push({
1183
+ code: "ADAPTER_DEGRADED",
1184
+ message: `Live probe failed for ${rawMethod} ${parsedUrl.pathname}; fell back to spec-only status 200: ${safeErr}`
1185
+ });
1186
+ }
1187
+ }
1188
+ const input = {
1189
+ method: rawMethod,
1190
+ path: parsedUrl.pathname,
1191
+ ...(Object.keys(query).length > 0 ? { query } : {}),
1192
+ ...(Object.keys(persistedHeaders).length > 0 ? { headers: persistedHeaders } : {}),
1193
+ ...(body !== undefined ? { body } : {})
1194
+ };
1195
+ const breadcrumbParts = [...folderTrail, ...(reqName ? [reqName] : [])];
1196
+ const breadcrumb = breadcrumbParts.join(" / ");
1197
+ const description = breadcrumb
1198
+ ? `Insomnia ${breadcrumb} (${rawMethod} ${parsedUrl.pathname}) matches ${observed ? "observed" : "spec-only"} HTTP contract`
1199
+ : `Insomnia ${rawMethod} ${parsedUrl.pathname} matches ${observed ? "observed" : "spec-only"} HTTP contract`;
1200
+ const folderTags = folderTrail.map((f) => slugify(f)).filter(Boolean);
1201
+ const idSeed = breadcrumbParts.length > 0
1202
+ ? `${rawMethod.toLowerCase()}-${breadcrumbParts.join("-")}`
1203
+ : `${rawMethod.toLowerCase()}-${parsedUrl.pathname}`;
1204
+ invariants.push({
1205
+ id: uniqueId(`inv-insomnia-${slugify(idSeed)}`, usedIds),
1206
+ domain: "api",
1207
+ type: "http",
1208
+ severity: "hard",
1209
+ description,
1210
+ tags: normalizeTags(folderTags, ["api", "insomnia", rawMethod.toLowerCase()]),
1211
+ sourceId: "src-1",
1212
+ input,
1213
+ expected,
1214
+ tolerance: {}
1215
+ });
1216
+ }
1217
+ if (skippedMutatingCount > 0) {
1218
+ warnings.push({
1219
+ code: "BRIDGE_FORMAT_WARNING",
1220
+ message: `Skipped ${skippedMutatingCount} mutating Insomnia request(s) (POST/PUT/PATCH/DELETE); pass includeMutating: true to include them.`,
1221
+ details: { skippedMutatingCount }
1222
+ });
1223
+ }
1224
+ if (truncatedByCap) {
1225
+ warnings.push({
1226
+ code: "BRIDGE_FORMAT_WARNING",
1227
+ message: `Insomnia export exceeded maximum of ${MAX_REQUESTS} emitted invariants; remaining requests were skipped.`
1228
+ });
1229
+ }
1230
+ validateInvariantsOrThrow(invariants, "insomnia");
1231
+ const safeBaseUrl = sanitizeBaseUrl(baseUrlOverride) || firstOrigin || undefined;
1232
+ return {
1233
+ domain: "api",
1234
+ sources: [
1235
+ {
1236
+ id: "src-1",
1237
+ kind: "insomnia",
1238
+ ref: isFileSource ? trimmedSource : safeBaseUrl || "inline",
1239
+ meta: {
1240
+ ...(workspaceName ? { collectionName: workspaceName } : {}),
1241
+ ...(safeBaseUrl ? { baseUrl: safeBaseUrl } : {}),
1242
+ requestCount: rawRequests.length,
1243
+ ...(anyRedactedSecrets ? { redactedSecrets: true } : {})
1244
+ }
1245
+ }
1246
+ ],
1247
+ artifacts: { root: ".vibecode/artifacts", files: {} },
1248
+ invariants,
1249
+ warnings
1250
+ };
1251
+ }
1252
+ // ============================================================================
1253
+ // 2. Bruno (.bru & Collection Directory) Detection, Parser & Ingestor
1254
+ // ============================================================================
1255
+ function stripInlineLineComment(value) {
1256
+ let inSingle = false;
1257
+ let inDouble = false;
1258
+ for (let i = 0; i < value.length; i += 1) {
1259
+ const ch = value[i];
1260
+ if (inSingle) {
1261
+ if (ch === "\\" && i + 1 < value.length) {
1262
+ i += 1;
1263
+ }
1264
+ else if (ch === "'") {
1265
+ inSingle = false;
1266
+ }
1267
+ continue;
1268
+ }
1269
+ if (inDouble) {
1270
+ if (ch === "\\" && i + 1 < value.length) {
1271
+ i += 1;
1272
+ }
1273
+ else if (ch === "\"") {
1274
+ inDouble = false;
1275
+ }
1276
+ continue;
1277
+ }
1278
+ if (ch === "'") {
1279
+ inSingle = true;
1280
+ }
1281
+ else if (ch === "\"") {
1282
+ inDouble = true;
1283
+ }
1284
+ else if (ch === "/" &&
1285
+ value[i + 1] === "/" &&
1286
+ (i === 0 || value[i - 1] === " " || value[i - 1] === "\t")) {
1287
+ return value.slice(0, i).trimEnd();
1288
+ }
1289
+ }
1290
+ return value.trimEnd();
1291
+ }
1292
+ function scanBrunoBlocks(normalizedText) {
1293
+ const lines = normalizedText.split("\n");
1294
+ const blocks = [];
1295
+ let i = 0;
1296
+ while (i < lines.length) {
1297
+ const line = lines[i];
1298
+ const trimmed = line.trim();
1299
+ if (!trimmed || trimmed.startsWith("//")) {
1300
+ i += 1;
1301
+ continue;
1302
+ }
1303
+ const headerMatch = BRUNO_BLOCK_HEADER_RE.exec(trimmed);
1304
+ if (!headerMatch) {
1305
+ i += 1;
1306
+ continue;
1307
+ }
1308
+ const blockName = headerMatch[1].toLowerCase();
1309
+ const openChar = headerMatch[2];
1310
+ const headerIndent = line.length - line.trimStart().length;
1311
+ const kind = openChar === "{" ? "brace" : "bracket";
1312
+ const closeChar = kind === "brace" ? "}" : "]";
1313
+ const isRawTextBlock = blockName === "body:text" ||
1314
+ blockName === "body:xml" ||
1315
+ blockName === "body:sparql" ||
1316
+ blockName === "docs";
1317
+ const isStructuredCodeBlock = blockName === "body:json" ||
1318
+ blockName === "body:graphql" ||
1319
+ blockName === "body:graphql:vars";
1320
+ i += 1;
1321
+ const bodyLines = [];
1322
+ let depth = 1;
1323
+ let inDouble = false;
1324
+ let inTripleDouble = false;
1325
+ while (i < lines.length && depth > 0) {
1326
+ const curLine = lines[i];
1327
+ const curIndent = curLine.length - curLine.trimStart().length;
1328
+ const curTrimmed = curLine.trim();
1329
+ if (isRawTextBlock || (kind === "brace" && !isStructuredCodeBlock)) {
1330
+ // Key-value and raw text blocks close on a closing '}' at or outside the block header's indent
1331
+ if (curIndent <= headerIndent && curTrimmed === "}") {
1332
+ depth = 0;
1333
+ i += 1;
1334
+ break;
1335
+ }
1336
+ bodyLines.push(curLine);
1337
+ i += 1;
1338
+ continue;
1339
+ }
1340
+ if (kind === "bracket") {
1341
+ let closedOnLine = false;
1342
+ for (let c = 0; c < curLine.length; c += 1) {
1343
+ const ch = curLine[c];
1344
+ if (ch === "/" && curLine[c + 1] === "/")
1345
+ break;
1346
+ if (ch === "[")
1347
+ depth += 1;
1348
+ else if (ch === "]") {
1349
+ depth -= 1;
1350
+ if (depth === 0) {
1351
+ const beforeClose = curLine.slice(0, c);
1352
+ if (beforeClose.trim().length > 0)
1353
+ bodyLines.push(beforeClose);
1354
+ closedOnLine = true;
1355
+ break;
1356
+ }
1357
+ }
1358
+ }
1359
+ if (!closedOnLine)
1360
+ bodyLines.push(curLine);
1361
+ i += 1;
1362
+ continue;
1363
+ }
1364
+ // Structured JSON/GraphQL brace block with string-aware nested brace tracking
1365
+ let closedAt = -1;
1366
+ for (let c = 0; c < curLine.length; c += 1) {
1367
+ const ch = curLine[c];
1368
+ if (inTripleDouble) {
1369
+ if (ch === "\"" && curLine[c + 1] === "\"" && curLine[c + 2] === "\"") {
1370
+ inTripleDouble = false;
1371
+ c += 2;
1372
+ }
1373
+ continue;
1374
+ }
1375
+ if (inDouble) {
1376
+ if (ch === "\\" && c + 1 < curLine.length) {
1377
+ c += 1;
1378
+ }
1379
+ else if (ch === "\"") {
1380
+ inDouble = false;
1381
+ }
1382
+ continue;
1383
+ }
1384
+ if (blockName === "body:graphql" && ch === "#") {
1385
+ break;
1386
+ }
1387
+ if (blockName === "body:graphql" && ch === "\"" && curLine[c + 1] === "\"" && curLine[c + 2] === "\"") {
1388
+ inTripleDouble = true;
1389
+ c += 2;
1390
+ continue;
1391
+ }
1392
+ if (ch === "\"") {
1393
+ inDouble = true;
1394
+ continue;
1395
+ }
1396
+ if (ch === "{") {
1397
+ depth += 1;
1398
+ }
1399
+ else if (ch === closeChar) {
1400
+ depth -= 1;
1401
+ if (depth === 0) {
1402
+ closedAt = c;
1403
+ break;
1404
+ }
1405
+ }
1406
+ }
1407
+ if (closedAt >= 0) {
1408
+ const before = curLine.slice(0, closedAt);
1409
+ if (before.trim().length > 0)
1410
+ bodyLines.push(before);
1411
+ i += 1;
1412
+ break;
1413
+ }
1414
+ bodyLines.push(curLine);
1415
+ i += 1;
1416
+ }
1417
+ blocks.push({
1418
+ name: blockName,
1419
+ kind,
1420
+ content: bodyLines.join("\n")
1421
+ });
1422
+ }
1423
+ return blocks;
1424
+ }
1425
+ function parseBrunoKeyValueBlock(content) {
1426
+ const entries = [];
1427
+ for (const rawLine of content.split("\n")) {
1428
+ const trimmed = rawLine.trim();
1429
+ if (!trimmed)
1430
+ continue;
1431
+ if (trimmed.startsWith("//"))
1432
+ continue;
1433
+ if (trimmed.startsWith("~"))
1434
+ continue;
1435
+ const colonIdx = trimmed.indexOf(":");
1436
+ if (colonIdx <= 0)
1437
+ continue;
1438
+ const key = trimmed.slice(0, colonIdx).trim();
1439
+ if (!key || key.startsWith("~") || isUnsafeKey(key))
1440
+ continue;
1441
+ const value = stripInlineLineComment(trimmed.slice(colonIdx + 1)).trim();
1442
+ entries.push({ key, value });
1443
+ }
1444
+ return entries;
1445
+ }
1446
+ function parseBrunoSecretList(content) {
1447
+ const names = [];
1448
+ for (const rawLine of content.split("\n")) {
1449
+ const clean = stripInlineLineComment(rawLine).trim();
1450
+ if (!clean)
1451
+ continue;
1452
+ for (const part of clean.split(",")) {
1453
+ const name = part.trim().replace(/^["']|["']$/g, "");
1454
+ if (name && !name.startsWith("~") && !isUnsafeKey(name)) {
1455
+ names.push(name);
1456
+ }
1457
+ }
1458
+ }
1459
+ return names;
1460
+ }
1461
+ function dedentBlockText(content) {
1462
+ const lines = content.split("\n");
1463
+ while (lines.length > 0 && lines[0].trim() === "")
1464
+ lines.shift();
1465
+ while (lines.length > 0 && lines[lines.length - 1].trim() === "")
1466
+ lines.pop();
1467
+ if (lines.length === 0)
1468
+ return "";
1469
+ let minIndent = Number.POSITIVE_INFINITY;
1470
+ for (const l of lines) {
1471
+ if (!l.trim())
1472
+ continue;
1473
+ const m = /^(\s*)/.exec(l);
1474
+ const indent = m ? m[1].length : 0;
1475
+ if (indent < minIndent)
1476
+ minIndent = indent;
1477
+ }
1478
+ if (!Number.isFinite(minIndent) || minIndent === 0) {
1479
+ return lines.join("\n");
1480
+ }
1481
+ return lines.map((l) => (l.length >= minIndent ? l.slice(minIndent) : l.trimStart())).join("\n");
1482
+ }
1483
+ function parseBrunoScalar(raw) {
1484
+ const trimmed = raw.trim();
1485
+ if (!trimmed)
1486
+ return undefined;
1487
+ if (trimmed === "true")
1488
+ return true;
1489
+ if (trimmed === "false")
1490
+ return false;
1491
+ if (trimmed === "null")
1492
+ return null;
1493
+ if (/^-?\d+(?:\.\d+)?$/.test(trimmed)) {
1494
+ const num = Number(trimmed);
1495
+ if (Number.isFinite(num))
1496
+ return num;
1497
+ }
1498
+ if ((trimmed.startsWith("[") && trimmed.endsWith("]")) ||
1499
+ (trimmed.startsWith("{") && trimmed.endsWith("}"))) {
1500
+ try {
1501
+ return sanitizeJsonValue(JSON.parse(trimmed));
1502
+ }
1503
+ catch {
1504
+ // fall through
1505
+ }
1506
+ }
1507
+ if ((trimmed.startsWith("\"") && trimmed.endsWith("\"") && trimmed.length >= 2) ||
1508
+ (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2)) {
1509
+ return trimmed.slice(1, -1);
1510
+ }
1511
+ return trimmed;
1512
+ }
1513
+ function parseBrunoAssertions(content) {
1514
+ const assertions = [];
1515
+ for (const { key: expr, value: rhs } of parseBrunoKeyValueBlock(content)) {
1516
+ if (!rhs) {
1517
+ assertions.push({ expr });
1518
+ continue;
1519
+ }
1520
+ const opMatch = BRUNO_ASSERT_OP_RE.exec(rhs);
1521
+ if (opMatch) {
1522
+ const op = opMatch[1];
1523
+ const valStr = (opMatch[2] || "").trim();
1524
+ const parsedVal = valStr ? parseBrunoScalar(valStr) : undefined;
1525
+ assertions.push({
1526
+ expr,
1527
+ op,
1528
+ ...(parsedVal !== undefined ? { value: parsedVal } : {})
1529
+ });
1530
+ }
1531
+ else {
1532
+ assertions.push({
1533
+ expr,
1534
+ value: parseBrunoScalar(rhs)
1535
+ });
1536
+ }
1537
+ }
1538
+ return assertions;
1539
+ }
1540
+ export function isBrunoFileText(text) {
1541
+ if (typeof text !== "string" || !text.trim())
1542
+ return false;
1543
+ const normalized = normalizeNewlines(text);
1544
+ const trimmed = normalized.trimStart();
1545
+ // Reject JSON, HTML, cURL, shell scripts, OpenAPI/Swagger, GraphQL SDL
1546
+ if (trimmed.startsWith("{") ||
1547
+ trimmed.startsWith("[") ||
1548
+ trimmed.startsWith("<") ||
1549
+ trimmed.startsWith("#!") ||
1550
+ /^curl\s/i.test(trimmed) ||
1551
+ /^(?:openapi|swagger)\s*:/im.test(trimmed) ||
1552
+ /^\s*(?:type\s+Query|schema)\s*\{/m.test(trimmed)) {
1553
+ return false;
1554
+ }
1555
+ const head = normalized.length > MAX_SOURCE_BYTES ? normalized.slice(0, 65_536) : normalized;
1556
+ const blocks = scanBrunoBlocks(head);
1557
+ let hasMeta = false;
1558
+ let hasMethodWithUrl = false;
1559
+ for (const block of blocks) {
1560
+ if (block.kind !== "brace")
1561
+ continue;
1562
+ if (block.name === "meta") {
1563
+ hasMeta = true;
1564
+ }
1565
+ else if (ALL_HTTP_METHODS.has(block.name.toUpperCase())) {
1566
+ const kvs = parseBrunoKeyValueBlock(block.content);
1567
+ if (kvs.some((kv) => kv.key.toLowerCase() === "url" && kv.value.length > 0)) {
1568
+ hasMethodWithUrl = true;
1569
+ }
1570
+ }
1571
+ }
1572
+ return hasMeta && hasMethodWithUrl;
1573
+ }
1574
+ export function isBrunoCollectionDir(dirPath) {
1575
+ if (typeof dirPath !== "string" || !dirPath.trim())
1576
+ return false;
1577
+ try {
1578
+ const stat = fs.statSync(dirPath);
1579
+ if (!stat.isDirectory())
1580
+ return false;
1581
+ // Check bruno.json first
1582
+ const brunoJsonPath = path.join(dirPath, "bruno.json");
1583
+ if (fs.existsSync(brunoJsonPath)) {
1584
+ const bStat = fs.statSync(brunoJsonPath);
1585
+ if (bStat.isFile() && bStat.size <= MAX_SOURCE_BYTES) {
1586
+ try {
1587
+ const parsed = JSON.parse(stripBom(fs.readFileSync(brunoJsonPath, "utf8")));
1588
+ if (isObject(parsed) &&
1589
+ ((hasOwn(parsed, "type") && parsed.type === "collection") ||
1590
+ (hasOwn(parsed, "name") && typeof parsed.name === "string" && parsed.name.trim().length > 0) ||
1591
+ (hasOwn(parsed, "version") && typeof parsed.version === "string"))) {
1592
+ return true;
1593
+ }
1594
+ }
1595
+ catch {
1596
+ // ignore invalid bruno.json and check .bru files below
1597
+ }
1598
+ }
1599
+ }
1600
+ // Shallow check for .bru files without scanning node_modules/.git
1601
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
1602
+ for (const entry of entries) {
1603
+ if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name))
1604
+ continue;
1605
+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".bru")) {
1606
+ return true;
1607
+ }
1608
+ }
1609
+ return false;
1610
+ }
1611
+ catch {
1612
+ return false;
1613
+ }
1614
+ }
1615
+ function parseBrunoFileInternal(text) {
1616
+ if (typeof text !== "string") {
1617
+ throw new VibecodeError("CONTRACT_INVALID", "Bruno .bru input must be a string");
1618
+ }
1619
+ const normalized = normalizeNewlines(text);
1620
+ if (Buffer.byteLength(normalized, "utf8") > MAX_SOURCE_BYTES) {
1621
+ throw new VibecodeError("CONTRACT_INVALID", `Bruno .bru input exceeds maximum size of ${MAX_SOURCE_BYTES} bytes`);
1622
+ }
1623
+ const blocks = scanBrunoBlocks(normalized);
1624
+ const meta = {};
1625
+ let method = "";
1626
+ let rawUrl = "";
1627
+ let methodBodyHint = "";
1628
+ let hasAuth = false;
1629
+ let redactedSecrets = false;
1630
+ const secretValues = new Set();
1631
+ const secretVarNames = new Set();
1632
+ const rawHeaders = {};
1633
+ const rawQuery = {};
1634
+ const rawVars = {};
1635
+ const assertions = [];
1636
+ let bodyType = "none";
1637
+ let body = undefined;
1638
+ let graphqlVariables = undefined;
1639
+ // First pass: collect vars:secret so they are excluded from vars
1640
+ for (const block of blocks) {
1641
+ if (block.name === "vars:secret") {
1642
+ for (const secretName of parseBrunoSecretList(block.content)) {
1643
+ secretVarNames.add(secretName.toLowerCase());
1644
+ }
1645
+ redactedSecrets = true;
1646
+ }
1647
+ }
1648
+ for (const block of blocks) {
1649
+ if (block.kind === "bracket")
1650
+ continue;
1651
+ if (block.name === "meta") {
1652
+ for (const { key, value } of parseBrunoKeyValueBlock(block.content)) {
1653
+ const lower = key.toLowerCase();
1654
+ if (lower === "name" && value)
1655
+ meta.name = value;
1656
+ else if (lower === "type" && value)
1657
+ meta.type = value;
1658
+ else if (lower === "seq" && value) {
1659
+ const n = Number(value);
1660
+ if (Number.isFinite(n))
1661
+ meta.seq = n;
1662
+ }
1663
+ }
1664
+ continue;
1665
+ }
1666
+ if (ALL_HTTP_METHODS.has(block.name.toUpperCase()) && !method) {
1667
+ method = block.name.toUpperCase();
1668
+ for (const { key, value } of parseBrunoKeyValueBlock(block.content)) {
1669
+ const lower = key.toLowerCase();
1670
+ if (lower === "url")
1671
+ rawUrl = value;
1672
+ else if (lower === "body")
1673
+ methodBodyHint = value.toLowerCase();
1674
+ else if (lower === "auth") {
1675
+ const authMode = value.toLowerCase();
1676
+ if (authMode && authMode !== "none" && authMode !== "inherit") {
1677
+ hasAuth = true;
1678
+ }
1679
+ }
1680
+ }
1681
+ continue;
1682
+ }
1683
+ if (BRUNO_AUTH_BLOCKS.has(block.name)) {
1684
+ hasAuth = true;
1685
+ redactedSecrets = true;
1686
+ for (const { value } of parseBrunoKeyValueBlock(block.content)) {
1687
+ recordSecretValue(secretValues, value);
1688
+ }
1689
+ continue;
1690
+ }
1691
+ if (block.name === "headers") {
1692
+ for (const { key, value } of parseBrunoKeyValueBlock(block.content)) {
1693
+ if (isCollectionSensitiveHeader(key) || SENSITIVE_HEADER_VALUE_RE.test(value)) {
1694
+ hasAuth = true;
1695
+ redactedSecrets = true;
1696
+ recordSecretValue(secretValues, value);
1697
+ continue;
1698
+ }
1699
+ if (containsSecretPlaceholder(value, secretVarNames)) {
1700
+ redactedSecrets = true;
1701
+ continue;
1702
+ }
1703
+ rawHeaders[key] = value;
1704
+ }
1705
+ continue;
1706
+ }
1707
+ if (block.name === "params:query" || block.name === "query") {
1708
+ for (const { key, value } of parseBrunoKeyValueBlock(block.content)) {
1709
+ if (isCollectionSensitiveQueryParam(key) || containsSecretPlaceholder(value, secretVarNames)) {
1710
+ redactedSecrets = true;
1711
+ recordSecretValue(secretValues, value);
1712
+ continue;
1713
+ }
1714
+ rawQuery[key] = value;
1715
+ }
1716
+ continue;
1717
+ }
1718
+ if (block.name === "vars:pre-request" || block.name === "vars") {
1719
+ for (const { key, value } of parseBrunoKeyValueBlock(block.content)) {
1720
+ if (isSecretVarName(key, secretVarNames)) {
1721
+ secretVarNames.add(key.toLowerCase());
1722
+ redactedSecrets = true;
1723
+ recordSecretValue(secretValues, value);
1724
+ continue;
1725
+ }
1726
+ rawVars[key] = value;
1727
+ }
1728
+ continue;
1729
+ }
1730
+ if (block.name === "assert") {
1731
+ assertions.push(...parseBrunoAssertions(block.content));
1732
+ continue;
1733
+ }
1734
+ if (block.name === "body:graphql") {
1735
+ const gqlText = dedentBlockText(block.content);
1736
+ bodyType = "graphql";
1737
+ body = gqlText;
1738
+ continue;
1739
+ }
1740
+ if (block.name === "body:graphql:vars") {
1741
+ const rawVarsText = dedentBlockText(block.content);
1742
+ if (rawVarsText) {
1743
+ try {
1744
+ const parsed = sanitizeJsonValue(JSON.parse(rawVarsText));
1745
+ if (isObject(parsed)) {
1746
+ graphqlVariables = parsed;
1747
+ }
1748
+ }
1749
+ catch {
1750
+ // ignore malformed GraphQL vars JSON
1751
+ }
1752
+ }
1753
+ continue;
1754
+ }
1755
+ if (block.name === "body:json") {
1756
+ const rawJsonText = dedentBlockText(block.content);
1757
+ bodyType = "json";
1758
+ if (rawJsonText) {
1759
+ try {
1760
+ body = sanitizeJsonValue(JSON.parse(rawJsonText));
1761
+ }
1762
+ catch {
1763
+ body = rawJsonText;
1764
+ }
1765
+ }
1766
+ continue;
1767
+ }
1768
+ if (block.name === "body:text") {
1769
+ bodyType = "text";
1770
+ body = dedentBlockText(block.content);
1771
+ continue;
1772
+ }
1773
+ }
1774
+ if (!method || !rawUrl) {
1775
+ throw new VibecodeError("CONTRACT_INVALID", "Bruno .bru file must contain an HTTP method block (get/post/put/patch/delete/head/options) with a url");
1776
+ }
1777
+ if (bodyType === "none" && (methodBodyHint === "json" || methodBodyHint === "text" || methodBodyHint === "graphql")) {
1778
+ bodyType = methodBodyHint;
1779
+ }
1780
+ // Strip secrets from URL and merge non-sensitive query params
1781
+ const urlSanitized = stripRawTemplateUrlSecrets(rawUrl, secretValues, secretVarNames);
1782
+ if (urlSanitized.redactedSecrets)
1783
+ redactedSecrets = true;
1784
+ const mergedQuery = { ...urlSanitized.query, ...rawQuery };
1785
+ const { safe: safeHeaders, redacted: headersRedacted } = stripSensitiveHeaders(rawHeaders, secretValues);
1786
+ if (headersRedacted)
1787
+ redactedSecrets = true;
1788
+ const request = {
1789
+ meta,
1790
+ method,
1791
+ url: urlSanitized.sanitizedUrl,
1792
+ headers: safeHeaders,
1793
+ query: mergedQuery,
1794
+ bodyType,
1795
+ ...(body !== undefined ? { body } : {}),
1796
+ ...(graphqlVariables !== undefined ? { graphqlVariables } : {}),
1797
+ assertions,
1798
+ vars: rawVars,
1799
+ hasAuth
1800
+ };
1801
+ return { request, secretValues, secretVarNames, redactedSecrets };
1802
+ }
1803
+ export function parseBrunoFile(text) {
1804
+ return parseBrunoFileInternal(text).request;
1805
+ }
1806
+ function loadBrunoEnvironmentVars(dirPath, ctx) {
1807
+ const envDir = path.join(dirPath, "environments");
1808
+ let redacted = false;
1809
+ try {
1810
+ if (!fs.existsSync(envDir) || !fs.statSync(envDir).isDirectory())
1811
+ return false;
1812
+ const files = fs
1813
+ .readdirSync(envDir, { withFileTypes: true })
1814
+ .filter((e) => e.isFile() && e.name.toLowerCase().endsWith(".bru"))
1815
+ .map((e) => e.name)
1816
+ .sort((a, b) => a.localeCompare(b));
1817
+ for (const fileName of files) {
1818
+ const fullPath = path.join(envDir, fileName);
1819
+ const st = fs.statSync(fullPath);
1820
+ if (st.size > MAX_SOURCE_BYTES)
1821
+ continue;
1822
+ const content = normalizeNewlines(fs.readFileSync(fullPath, "utf8"));
1823
+ const blocks = scanBrunoBlocks(content);
1824
+ // Collect vars:secret first
1825
+ for (const block of blocks) {
1826
+ if (block.name === "vars:secret") {
1827
+ for (const secretName of parseBrunoSecretList(block.content)) {
1828
+ ctx.secretVarNames.add(secretName.toLowerCase());
1829
+ // Remove any previously loaded value if marked secret
1830
+ for (const existingKey of Object.keys(ctx.safeVars)) {
1831
+ if (existingKey.toLowerCase() === secretName.toLowerCase()) {
1832
+ recordSecretValue(ctx.secretValues, ctx.safeVars[existingKey]);
1833
+ delete ctx.safeVars[existingKey];
1834
+ }
1835
+ }
1836
+ }
1837
+ redacted = true;
1838
+ }
1839
+ }
1840
+ // Collect non-secret vars
1841
+ for (const block of blocks) {
1842
+ if (block.kind === "brace" && block.name === "vars") {
1843
+ for (const { key, value } of parseBrunoKeyValueBlock(block.content)) {
1844
+ if (isSecretVarName(key, ctx.secretVarNames)) {
1845
+ ctx.secretVarNames.add(key.toLowerCase());
1846
+ recordSecretValue(ctx.secretValues, value);
1847
+ redacted = true;
1848
+ continue;
1849
+ }
1850
+ setSafeProp(ctx.safeVars, key, value);
1851
+ }
1852
+ }
1853
+ }
1854
+ }
1855
+ }
1856
+ catch {
1857
+ // ignore unreadable environments directory
1858
+ }
1859
+ return redacted;
1860
+ }
1861
+ function walkBrunoFiles(rootDir, currentDir, folderTrail, depth, collected, state) {
1862
+ let entries;
1863
+ try {
1864
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
1865
+ }
1866
+ catch {
1867
+ return;
1868
+ }
1869
+ entries.sort((a, b) => a.name.localeCompare(b.name));
1870
+ for (const entry of entries) {
1871
+ if (entry.name.startsWith(".") || IGNORED_DIRS.has(entry.name))
1872
+ continue;
1873
+ const fullPath = path.join(currentDir, entry.name);
1874
+ if (entry.isDirectory()) {
1875
+ if (depth >= MAX_DIR_DEPTH) {
1876
+ state.truncatedByDepth = true;
1877
+ continue;
1878
+ }
1879
+ walkBrunoFiles(rootDir, fullPath, [...folderTrail, entry.name], depth + 1, collected, state);
1880
+ }
1881
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith(".bru")) {
1882
+ const lowerName = entry.name.toLowerCase();
1883
+ if (lowerName === "collection.bru" || lowerName === "folder.bru")
1884
+ continue;
1885
+ if (collected.length >= MAX_WALK_FILES) {
1886
+ state.truncatedByCap = true;
1887
+ return;
1888
+ }
1889
+ collected.push({
1890
+ filePath: fullPath,
1891
+ relPath: path.relative(rootDir, fullPath).replace(/\\/g, "/"),
1892
+ folderTrail
1893
+ });
1894
+ }
1895
+ }
1896
+ }
1897
+ function isGraphqlMutationQuery(queryText) {
1898
+ const withoutComments = queryText
1899
+ .split("\n")
1900
+ .map((line) => line.replace(/#.*$/, ""))
1901
+ .join("\n")
1902
+ .trim();
1903
+ return /^mutation\b/i.test(withoutComments);
1904
+ }
1905
+ function extractBrunoAssertionsExpected(assertions, secretValues) {
1906
+ let status = undefined;
1907
+ const jsonPaths = [];
1908
+ for (const assertion of assertions) {
1909
+ const expr = assertion.expr.trim();
1910
+ if (expr === "res.status") {
1911
+ if ((assertion.op === "eq" || assertion.op === undefined) &&
1912
+ typeof assertion.value === "number" &&
1913
+ Number.isInteger(assertion.value) &&
1914
+ assertion.value >= 100 &&
1915
+ assertion.value <= 599) {
1916
+ status = assertion.value;
1917
+ }
1918
+ else if (assertion.op === "in" && Array.isArray(assertion.value)) {
1919
+ const codes = assertion.value.filter((v) => typeof v === "number" && Number.isInteger(v) && v >= 100 && v <= 599);
1920
+ if (codes.length === 1)
1921
+ status = codes[0];
1922
+ else if (codes.length > 1)
1923
+ status = codes;
1924
+ }
1925
+ continue;
1926
+ }
1927
+ if (expr.startsWith("res.body.") && assertion.op === "eq" && assertion.value !== undefined) {
1928
+ const fieldPath = expr.slice("res.body.".length).trim();
1929
+ if (fieldPath && !fieldPath.split(".").some((seg) => isUnsafeKey(seg) || SECRET_VAR_NAME_RE.test(seg))) {
1930
+ const valStr = typeof assertion.value === "string" ? assertion.value : JSON.stringify(assertion.value);
1931
+ let leaks = false;
1932
+ for (const s of secretValues) {
1933
+ if (s.length > 0 && valStr.includes(s)) {
1934
+ leaks = true;
1935
+ break;
1936
+ }
1937
+ }
1938
+ if (!leaks) {
1939
+ jsonPaths.push({ path: `$.${fieldPath}`, equals: assertion.value });
1940
+ }
1941
+ }
1942
+ }
1943
+ }
1944
+ return { status, jsonPaths };
1945
+ }
1946
+ export async function ingestBrunoCollection(source, options = {}, deps = {}) {
1947
+ if (typeof source !== "string" || !source.trim()) {
1948
+ throw new VibecodeError("TARGET_MISSING", "Bruno ingestor requires a .bru file, collection directory, or inline .bru text");
1949
+ }
1950
+ const cwd = options.cwd || process.cwd();
1951
+ const trimmedSource = source.trim();
1952
+ const envCtx = {
1953
+ safeVars: createNullRecord(),
1954
+ secretVarNames: new Set(),
1955
+ secretValues: new Set()
1956
+ };
1957
+ const entries = [];
1958
+ let isPathSource = false;
1959
+ let collectionName = "";
1960
+ let anyRedactedSecrets = false;
1961
+ const walkState = { truncatedByCap: false, truncatedByDepth: false };
1962
+ let stat = null;
1963
+ if (!/[\r\n]/.test(trimmedSource)) {
1964
+ const candidatePath = path.resolve(cwd, trimmedSource);
1965
+ try {
1966
+ if (fs.existsSync(candidatePath)) {
1967
+ stat = fs.statSync(candidatePath);
1968
+ }
1969
+ }
1970
+ catch {
1971
+ stat = null;
1972
+ }
1973
+ if (stat?.isDirectory()) {
1974
+ isPathSource = true;
1975
+ // Read optional bruno.json
1976
+ const brunoJsonPath = path.join(candidatePath, "bruno.json");
1977
+ try {
1978
+ if (fs.existsSync(brunoJsonPath) && fs.statSync(brunoJsonPath).isFile()) {
1979
+ const bStat = fs.statSync(brunoJsonPath);
1980
+ if (bStat.size <= MAX_SOURCE_BYTES) {
1981
+ const bDoc = JSON.parse(stripBom(fs.readFileSync(brunoJsonPath, "utf8")));
1982
+ if (isObject(bDoc) && hasOwn(bDoc, "name") && typeof bDoc.name === "string") {
1983
+ collectionName = bDoc.name.trim();
1984
+ }
1985
+ }
1986
+ }
1987
+ }
1988
+ catch {
1989
+ // ignore invalid bruno.json
1990
+ }
1991
+ if (loadBrunoEnvironmentVars(candidatePath, envCtx)) {
1992
+ anyRedactedSecrets = true;
1993
+ }
1994
+ const foundFiles = [];
1995
+ walkBrunoFiles(candidatePath, candidatePath, [], 0, foundFiles, walkState);
1996
+ for (const fileInfo of foundFiles) {
1997
+ try {
1998
+ const fStat = fs.statSync(fileInfo.filePath);
1999
+ if (fStat.size > MAX_SOURCE_BYTES) {
2000
+ throw new VibecodeError("CONTRACT_INVALID", `Bruno file exceeds maximum size of ${MAX_SOURCE_BYTES} bytes: ${fileInfo.relPath}`);
2001
+ }
2002
+ const content = fs.readFileSync(fileInfo.filePath, "utf8");
2003
+ if (!isBrunoFileText(content))
2004
+ continue;
2005
+ const parsed = parseBrunoFileInternal(content);
2006
+ entries.push({ parsed, folderTrail: fileInfo.folderTrail, relPath: fileInfo.relPath });
2007
+ }
2008
+ catch (err) {
2009
+ if (err instanceof VibecodeError && err.code === "CONTRACT_INVALID")
2010
+ throw err;
2011
+ // skip non-request .bru files
2012
+ }
2013
+ }
2014
+ if (entries.length === 0) {
2015
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `No valid Bruno .bru request files found in directory: ${trimmedSource}`);
2016
+ }
2017
+ }
2018
+ else if (stat?.isFile()) {
2019
+ isPathSource = true;
2020
+ if (stat.size > MAX_SOURCE_BYTES) {
2021
+ throw new VibecodeError("CONTRACT_INVALID", `Bruno file exceeds maximum size of ${MAX_SOURCE_BYTES} bytes: ${trimmedSource}`);
2022
+ }
2023
+ const content = fs.readFileSync(candidatePath, "utf8");
2024
+ const parsed = parseBrunoFileInternal(content);
2025
+ entries.push({ parsed, folderTrail: [], relPath: path.basename(candidatePath) });
2026
+ }
2027
+ else if (path.extname(candidatePath).toLowerCase() === ".bru" && !isBrunoFileText(source)) {
2028
+ throw new VibecodeError("TARGET_MISSING", `Bruno file not found: ${trimmedSource}`);
2029
+ }
2030
+ }
2031
+ if (!isPathSource) {
2032
+ if (Buffer.byteLength(source, "utf8") > MAX_SOURCE_BYTES) {
2033
+ throw new VibecodeError("CONTRACT_INVALID", `Inline Bruno source exceeds maximum size of ${MAX_SOURCE_BYTES} bytes`);
2034
+ }
2035
+ if (!isBrunoFileText(source)) {
2036
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "Source is neither an existing Bruno collection/.bru file nor valid Bruno .bru text");
2037
+ }
2038
+ const parsed = parseBrunoFileInternal(source);
2039
+ entries.push({ parsed, folderTrail: [], relPath: "inline.bru" });
2040
+ }
2041
+ // Deterministic ordering across collection files
2042
+ entries.sort((a, b) => {
2043
+ const fa = a.folderTrail.join("/");
2044
+ const fb = b.folderTrail.join("/");
2045
+ if (fa !== fb)
2046
+ return fa.localeCompare(fb);
2047
+ const sa = typeof a.parsed.request.meta.seq === "number" ? a.parsed.request.meta.seq : Number.POSITIVE_INFINITY;
2048
+ const sb = typeof b.parsed.request.meta.seq === "number" ? b.parsed.request.meta.seq : Number.POSITIVE_INFINITY;
2049
+ if (sa !== sb)
2050
+ return sa - sb;
2051
+ const na = a.parsed.request.meta.name || "";
2052
+ const nb = b.parsed.request.meta.name || "";
2053
+ if (na !== nb)
2054
+ return na.localeCompare(nb);
2055
+ return a.relPath.localeCompare(b.relPath);
2056
+ });
2057
+ const includeMutating = options.includeMutating === true;
2058
+ const offline = options.offline === true;
2059
+ const baseUrlOverride = typeof options.baseUrl === "string" && options.baseUrl.trim() ? options.baseUrl.trim() : "";
2060
+ const globalHeaders = isObject(options.headers) ? options.headers : undefined;
2061
+ const timeoutMs = typeof deps.timeoutMs === "number" && deps.timeoutMs > 0 ? deps.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS;
2062
+ const doFetch = deps.fetchJson || defaultFetchJson;
2063
+ if (globalHeaders) {
2064
+ for (const [k, v] of Object.entries(globalHeaders)) {
2065
+ if (isCollectionSensitiveHeader(k) && typeof v === "string") {
2066
+ recordSecretValue(envCtx.secretValues, v);
2067
+ }
2068
+ }
2069
+ }
2070
+ const warnings = [];
2071
+ const invariants = [];
2072
+ const usedIds = new Set();
2073
+ let skippedMutatingCount = 0;
2074
+ let firstOrigin = "";
2075
+ for (const entry of entries) {
2076
+ const req = entry.parsed.request;
2077
+ if (entry.parsed.redactedSecrets)
2078
+ anyRedactedSecrets = true;
2079
+ // Build per-request merged var context (env vars + request vars:pre-request)
2080
+ const reqCtx = {
2081
+ safeVars: createNullRecord(),
2082
+ secretVarNames: new Set([...envCtx.secretVarNames, ...entry.parsed.secretVarNames]),
2083
+ secretValues: new Set([...envCtx.secretValues, ...entry.parsed.secretValues])
2084
+ };
2085
+ for (const [k, v] of Object.entries(envCtx.safeVars)) {
2086
+ if (!isSecretVarName(k, reqCtx.secretVarNames)) {
2087
+ setSafeProp(reqCtx.safeVars, k, v);
2088
+ }
2089
+ }
2090
+ for (const [k, v] of Object.entries(req.vars)) {
2091
+ if (!isSecretVarName(k, reqCtx.secretVarNames)) {
2092
+ setSafeProp(reqCtx.safeVars, k, v);
2093
+ }
2094
+ }
2095
+ const isGraphql = req.bodyType === "graphql";
2096
+ const isGraphqlReadOnly = isGraphql && typeof req.body === "string" && !isGraphqlMutationQuery(req.body);
2097
+ const effectiveMethod = isGraphql ? "POST" : req.method;
2098
+ if (MUTATING_METHODS.has(effectiveMethod) && !isGraphqlReadOnly && !includeMutating) {
2099
+ skippedMutatingCount += 1;
2100
+ continue;
2101
+ }
2102
+ if (invariants.length >= MAX_REQUESTS) {
2103
+ walkState.truncatedByCap = true;
2104
+ break;
2105
+ }
2106
+ const parsedUrl = parseAndSanitizeUrl(req.url, reqCtx, baseUrlOverride || undefined);
2107
+ if (!parsedUrl) {
2108
+ warnings.push({
2109
+ code: "BRIDGE_FORMAT_WARNING",
2110
+ message: `Skipped Bruno request "${req.meta.name || entry.relPath}" with missing or invalid URL.`
2111
+ });
2112
+ continue;
2113
+ }
2114
+ if (parsedUrl.redactedSecrets)
2115
+ anyRedactedSecrets = true;
2116
+ if (!firstOrigin && parsedUrl.origin)
2117
+ firstOrigin = parsedUrl.origin;
2118
+ // Interpolate and sanitize query params
2119
+ const query = { ...parsedUrl.query };
2120
+ for (const [rawKey, rawVal] of Object.entries(req.query)) {
2121
+ if (isUnsafeKey(rawKey) || isCollectionSensitiveQueryParam(rawKey)) {
2122
+ anyRedactedSecrets = true;
2123
+ recordSecretValue(reqCtx.secretValues, rawVal);
2124
+ continue;
2125
+ }
2126
+ const kInterp = interpolateSafeVars(rawKey, reqCtx, SECRET_SENTINEL);
2127
+ const vInterp = interpolateSafeVars(rawVal, reqCtx, SECRET_SENTINEL);
2128
+ const resolvedKey = kInterp.value.trim();
2129
+ if (resolvedKey && isUnsafeKey(resolvedKey))
2130
+ continue;
2131
+ if (kInterp.hitSecret || vInterp.hitSecret || isCollectionSensitiveQueryParam(resolvedKey)) {
2132
+ anyRedactedSecrets = true;
2133
+ continue;
2134
+ }
2135
+ if (resolvedKey) {
2136
+ query[resolvedKey] = vInterp.value;
2137
+ }
2138
+ }
2139
+ // Interpolate and sanitize headers
2140
+ const rawSafeHeaders = {};
2141
+ for (const [rawKey, rawVal] of Object.entries(req.headers)) {
2142
+ if (isUnsafeKey(rawKey) || isCollectionSensitiveHeader(rawKey) || SENSITIVE_HEADER_VALUE_RE.test(rawVal)) {
2143
+ anyRedactedSecrets = true;
2144
+ recordSecretValue(reqCtx.secretValues, rawVal);
2145
+ continue;
2146
+ }
2147
+ const vInterp = interpolateSafeVars(rawVal, reqCtx, SECRET_SENTINEL);
2148
+ if (vInterp.hitSecret || vInterp.value.includes(SECRET_SENTINEL) || SENSITIVE_HEADER_VALUE_RE.test(vInterp.value)) {
2149
+ anyRedactedSecrets = true;
2150
+ recordSecretValue(reqCtx.secretValues, vInterp.value);
2151
+ continue;
2152
+ }
2153
+ rawSafeHeaders[rawKey] = vInterp.value;
2154
+ }
2155
+ // Build payload
2156
+ let body = undefined;
2157
+ if (isGraphql) {
2158
+ const qInterp = interpolateSafeVars(typeof req.body === "string" ? req.body : "", reqCtx, "[REDACTED]");
2159
+ if (qInterp.hitSecret)
2160
+ anyRedactedSecrets = true;
2161
+ let variables = undefined;
2162
+ if (req.graphqlVariables) {
2163
+ const vInterp = interpolateJsonValue(req.graphqlVariables, reqCtx);
2164
+ if (vInterp.hitSecret)
2165
+ anyRedactedSecrets = true;
2166
+ if (isObject(vInterp.value))
2167
+ variables = vInterp.value;
2168
+ }
2169
+ body = {
2170
+ query: qInterp.value,
2171
+ ...(variables ? { variables } : {})
2172
+ };
2173
+ if (!hasHeaderCaseInsensitive(rawSafeHeaders, "content-type")) {
2174
+ rawSafeHeaders["content-type"] = "application/json";
2175
+ }
2176
+ }
2177
+ else if (req.bodyType === "json" && req.body !== undefined) {
2178
+ const bInterp = interpolateJsonValue(req.body, reqCtx);
2179
+ if (bInterp.hitSecret)
2180
+ anyRedactedSecrets = true;
2181
+ body = bInterp.value;
2182
+ if (!hasHeaderCaseInsensitive(rawSafeHeaders, "content-type")) {
2183
+ rawSafeHeaders["content-type"] = "application/json";
2184
+ }
2185
+ }
2186
+ else if (req.bodyType === "text" && typeof req.body === "string") {
2187
+ const bInterp = interpolateSafeVars(req.body, reqCtx, "[REDACTED]");
2188
+ if (bInterp.hitSecret)
2189
+ anyRedactedSecrets = true;
2190
+ body = bInterp.value;
2191
+ }
2192
+ const probeHeaders = mergeHeaders(rawSafeHeaders, globalHeaders);
2193
+ deleteHeaderCaseInsensitive(probeHeaders, "host");
2194
+ const { safe: persistedHeaders, redacted: mergedRedacted } = stripSensitiveHeaders(mergeHeaders(rawSafeHeaders, globalHeaders), reqCtx.secretValues);
2195
+ deleteHeaderCaseInsensitive(persistedHeaders, "host");
2196
+ if (mergedRedacted)
2197
+ anyRedactedSecrets = true;
2198
+ const assertExpected = extractBrunoAssertionsExpected(req.assertions, reqCtx.secretValues);
2199
+ const effectiveProbeBase = sanitizeBaseUrl(baseUrlOverride) || parsedUrl.origin;
2200
+ let observed = null;
2201
+ let probeFailed = null;
2202
+ if (!offline && effectiveProbeBase) {
2203
+ const probeUrl = buildProbeUrl(effectiveProbeBase, parsedUrl.pathname, query);
2204
+ try {
2205
+ observed = await doFetch(probeUrl, {
2206
+ method: effectiveMethod,
2207
+ headers: probeHeaders,
2208
+ body,
2209
+ timeoutMs
2210
+ });
2211
+ }
2212
+ catch (err) {
2213
+ probeFailed = err;
2214
+ }
2215
+ }
2216
+ const expected = {};
2217
+ if (observed) {
2218
+ if (assertExpected.status !== undefined) {
2219
+ const matchesObserved = Array.isArray(assertExpected.status)
2220
+ ? assertExpected.status.includes(observed.status)
2221
+ : assertExpected.status === observed.status;
2222
+ expected.status = matchesObserved ? assertExpected.status : observed.status;
2223
+ }
2224
+ else {
2225
+ expected.status = observed.status;
2226
+ }
2227
+ if (observed.json !== null && (isObject(observed.json) || Array.isArray(observed.json))) {
2228
+ expected.jsonSchema = synthesizeSchema(observed.json);
2229
+ if (isObject(observed.json)) {
2230
+ expected.jsonSubset = observed.json;
2231
+ }
2232
+ }
2233
+ else if (observed.text.trim().length > 0) {
2234
+ const snippet = extractSafeBodySnippet(observed.text, reqCtx.secretValues);
2235
+ if (snippet)
2236
+ expected.bodyContains = [snippet];
2237
+ }
2238
+ }
2239
+ else {
2240
+ expected.status = assertExpected.status ?? 200;
2241
+ if (assertExpected.jsonPaths.length > 0) {
2242
+ expected.jsonPaths = assertExpected.jsonPaths;
2243
+ }
2244
+ if (offline) {
2245
+ warnings.push({
2246
+ code: "ADAPTER_DEGRADED",
2247
+ message: `Offline spec-only mode: emitted ${effectiveMethod} ${parsedUrl.pathname} without live HTTP probe.`
2248
+ });
2249
+ }
2250
+ else if (!effectiveProbeBase) {
2251
+ warnings.push({
2252
+ code: "ADAPTER_DEGRADED",
2253
+ message: `No reachable baseUrl for ${effectiveMethod} ${parsedUrl.pathname}; emitted spec-only status ${JSON.stringify(expected.status)}.`
2254
+ });
2255
+ }
2256
+ else {
2257
+ const safeErr = redactKnownSecrets(probeFailed ? errorMessage(probeFailed) : "unknown error", reqCtx.secretValues);
2258
+ warnings.push({
2259
+ code: "ADAPTER_DEGRADED",
2260
+ message: `Live probe failed for ${effectiveMethod} ${parsedUrl.pathname}; fell back to spec-only status ${JSON.stringify(expected.status)}: ${safeErr}`
2261
+ });
2262
+ }
2263
+ }
2264
+ const input = {
2265
+ method: effectiveMethod,
2266
+ path: parsedUrl.pathname,
2267
+ ...(Object.keys(query).length > 0 ? { query } : {}),
2268
+ ...(Object.keys(persistedHeaders).length > 0 ? { headers: persistedHeaders } : {}),
2269
+ ...(body !== undefined ? { body } : {})
2270
+ };
2271
+ const reqLabel = req.meta.name || path.basename(entry.relPath, ".bru");
2272
+ const breadcrumbParts = [...entry.folderTrail, ...(reqLabel ? [reqLabel] : [])];
2273
+ const breadcrumb = breadcrumbParts.join(" / ");
2274
+ const description = breadcrumb
2275
+ ? `Bruno ${breadcrumb} (${effectiveMethod} ${parsedUrl.pathname}) matches ${observed ? "observed" : "spec-only"} HTTP contract`
2276
+ : `Bruno ${effectiveMethod} ${parsedUrl.pathname} matches ${observed ? "observed" : "spec-only"} HTTP contract`;
2277
+ const folderTags = entry.folderTrail.map((f) => slugify(f)).filter(Boolean);
2278
+ const extraTags = [...folderTags, ...(isGraphql ? ["graphql"] : [])];
2279
+ const idSeed = breadcrumbParts.length > 0
2280
+ ? `${effectiveMethod.toLowerCase()}-${breadcrumbParts.join("-")}`
2281
+ : `${effectiveMethod.toLowerCase()}-${parsedUrl.pathname}`;
2282
+ invariants.push({
2283
+ id: uniqueId(`inv-bruno-${slugify(idSeed)}`, usedIds),
2284
+ domain: "api",
2285
+ type: "http",
2286
+ severity: "hard",
2287
+ description,
2288
+ tags: normalizeTags(extraTags, ["api", "bruno", effectiveMethod.toLowerCase()]),
2289
+ sourceId: "src-1",
2290
+ input,
2291
+ expected,
2292
+ tolerance: {}
2293
+ });
2294
+ }
2295
+ if (skippedMutatingCount > 0) {
2296
+ warnings.push({
2297
+ code: "BRIDGE_FORMAT_WARNING",
2298
+ message: `Skipped ${skippedMutatingCount} mutating Bruno request(s) (POST/PUT/PATCH/DELETE); pass includeMutating: true to include them.`,
2299
+ details: { skippedMutatingCount }
2300
+ });
2301
+ }
2302
+ if (walkState.truncatedByCap) {
2303
+ warnings.push({
2304
+ code: "BRIDGE_FORMAT_WARNING",
2305
+ message: `Bruno collection exceeded maximum of ${MAX_REQUESTS} emitted invariants; remaining requests were skipped.`
2306
+ });
2307
+ }
2308
+ if (walkState.truncatedByDepth) {
2309
+ warnings.push({
2310
+ code: "BRIDGE_FORMAT_WARNING",
2311
+ message: `Bruno collection folder nesting exceeded maximum depth of ${MAX_DIR_DEPTH}; deeper directories were skipped.`
2312
+ });
2313
+ }
2314
+ validateInvariantsOrThrow(invariants, "bruno");
2315
+ const safeBaseUrl = sanitizeBaseUrl(baseUrlOverride) || firstOrigin || undefined;
2316
+ return {
2317
+ domain: "api",
2318
+ sources: [
2319
+ {
2320
+ id: "src-1",
2321
+ kind: "bruno",
2322
+ ref: isPathSource ? trimmedSource : safeBaseUrl || "inline",
2323
+ meta: {
2324
+ ...(collectionName ? { collectionName } : {}),
2325
+ ...(safeBaseUrl ? { baseUrl: safeBaseUrl } : {}),
2326
+ requestCount: entries.length,
2327
+ ...(anyRedactedSecrets ? { redactedSecrets: true } : {})
2328
+ }
2329
+ }
2330
+ ],
2331
+ artifacts: { root: ".vibecode/artifacts", files: {} },
2332
+ invariants,
2333
+ warnings
2334
+ };
2335
+ }