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,988 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import http from "node:http";
4
+ import path from "node:path";
5
+ import { VibecodeError } from "./errors.js";
6
+ import { compileMockRoutes } from "./mock-server.js";
7
+ import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
8
+ const HAR_VERSION = "1.2";
9
+ const CREATOR_NAME = "vibecode-anything";
10
+ const CREATOR_VERSION = "0.4.0";
11
+ const DEFAULT_BASE_URL = "http://127.0.0.1:8080";
12
+ const DEFAULT_TITLE = "vibecode-har-archive";
13
+ const DETERMINISTIC_EPOCH_MS = Date.UTC(2025, 0, 1, 0, 0, 0, 0);
14
+ const HAR_INGEST_MAX_BODY_BYTES = 128 * 1024;
15
+ const MAX_SCHEMA_DEPTH = 16;
16
+ const MAX_BODY_DEPTH = 32;
17
+ const MAX_PRETTY_ENTRIES = 20;
18
+ const MAX_PRETTY_WARNINGS = 10;
19
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
20
+ const TRANSPORT_SKIP_HEADERS = new Set(["content-length", "transfer-encoding", "connection"]);
21
+ const BODY_FORBIDDEN_METHODS = new Set(["GET", "HEAD"]);
22
+ const HEADER_NAME_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
23
+ const HTTP_METHOD_TOKEN_RE = /^[A-Z][A-Z0-9!#$%&'*+\-.^_`|~]*$/;
24
+ const SENSITIVE_HEADER_NAME_RE = /(?:authorization|proxy[-_]?authorization|cookie|set[-_]?cookie|api[-_]?key|apikey|token|secret|bearer|csrf|xsrf|password|passwd|passphrase|credential|private[-_]?key|session[-_]?id|jwt|(?:^|[-_])auth(?:$|[-_]))/i;
25
+ const EXTRA_SENSITIVE_QUERY_RE = /(?:token|api[-_]?key|apikey|secret|password|passwd|passphrase|jwt|session[-_]?id|private[-_]?key|authorization|cookie|csrf|xsrf|bearer|credential|(?:^|[-_])(?:auth|sig|signature)(?:$|[-_]))/i;
26
+ const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credentials?|bearer|csrf|xsrf)/i;
27
+ const AUTH_SCHEME_VALUE_RE = /^(?:\s*(?:bearer|basic|token|digest|apikey)\s+\S+)|\bbearer\s+\S+/i;
28
+ const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
29
+ const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
30
+ const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
31
+ const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
32
+ const INLINE_BASIC_TOKEN_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{4,}/gi;
33
+ const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey|TOKEN|APIKEY|apiKey)\s+[A-Za-z0-9._~+/=:-]{4,}|\b(token)\s+(?=[A-Za-z0-9._~+/=:-]*[0-9A-Z._~+/=:-])[A-Za-z0-9._~+/=:-]{4,}|\b(apikey)\s+[A-Za-z0-9._~+/=:-]{4,}/g;
34
+ const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*|[A-Za-z0-9._~+/:-]{6,}={0,2})/gi;
35
+ const ANSI = {
36
+ reset: "\x1b[0m",
37
+ bold: "\x1b[1m",
38
+ dim: "\x1b[2m",
39
+ red: "\x1b[31m",
40
+ green: "\x1b[32m",
41
+ yellow: "\x1b[33m",
42
+ cyan: "\x1b[36m"
43
+ };
44
+ function isRecord(value) {
45
+ return value !== null && typeof value === "object" && !Array.isArray(value);
46
+ }
47
+ function isForbiddenKey(key) {
48
+ return FORBIDDEN_KEYS.has(key);
49
+ }
50
+ function isSensitiveHeaderName(name) {
51
+ const trimmed = String(name).trim();
52
+ return isSensitiveHeader(trimmed) || SENSITIVE_HEADER_NAME_RE.test(trimmed);
53
+ }
54
+ function isSensitiveQueryName(name) {
55
+ const trimmed = String(name).trim();
56
+ return (isSensitiveQueryParam(trimmed) ||
57
+ EXTRA_SENSITIVE_QUERY_RE.test(trimmed) ||
58
+ isSensitiveHeaderName(trimmed));
59
+ }
60
+ function isSecretFieldName(name) {
61
+ const trimmed = String(name).trim();
62
+ return (SECRET_FIELD_NAME_RE.test(trimmed) ||
63
+ isSensitiveHeaderName(trimmed) ||
64
+ isSensitiveQueryName(trimmed));
65
+ }
66
+ function hasAuthSchemeValue(value) {
67
+ return AUTH_SCHEME_VALUE_RE.test(value);
68
+ }
69
+ function redactVaultPaths(text) {
70
+ return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
71
+ }
72
+ function sanitizeUrlInText(rawUrl) {
73
+ const withoutVault = redactVaultPaths(rawUrl);
74
+ const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
75
+ try {
76
+ const parsed = new URL(withoutAuth);
77
+ const hasAuth = Boolean(parsed.username || parsed.password);
78
+ const hasHash = parsed.hash.length > 0;
79
+ let hasModifiedParam = false;
80
+ const safeParams = new URLSearchParams();
81
+ for (const [k, v] of parsed.searchParams.entries()) {
82
+ const trimmedKey = k.trim();
83
+ if (!trimmedKey ||
84
+ isForbiddenKey(trimmedKey) ||
85
+ isSensitiveQueryName(trimmedKey) ||
86
+ /\.vibecode-vault/i.test(trimmedKey) ||
87
+ hasAuthSchemeValue(v)) {
88
+ hasModifiedParam = true;
89
+ continue;
90
+ }
91
+ const cleanVal = redactVaultPaths(v);
92
+ if (cleanVal !== v)
93
+ hasModifiedParam = true;
94
+ safeParams.append(k, cleanVal);
95
+ }
96
+ if (!hasAuth && !hasHash && !hasModifiedParam) {
97
+ return withoutAuth;
98
+ }
99
+ parsed.username = "";
100
+ parsed.password = "";
101
+ parsed.hash = "";
102
+ const serialized = safeParams.toString();
103
+ parsed.search = serialized ? `?${serialized}` : "";
104
+ return parsed.toString();
105
+ }
106
+ catch {
107
+ const noHash = withoutAuth.split("#")[0] || withoutAuth;
108
+ const qIdx = noHash.indexOf("?");
109
+ if (qIdx < 0)
110
+ return noHash;
111
+ const basePart = noHash.slice(0, qIdx);
112
+ const params = new URLSearchParams(noHash.slice(qIdx + 1));
113
+ const safeParams = new URLSearchParams();
114
+ for (const [k, v] of params.entries()) {
115
+ const trimmedKey = k.trim();
116
+ if (!trimmedKey ||
117
+ isForbiddenKey(trimmedKey) ||
118
+ isSensitiveQueryName(trimmedKey) ||
119
+ /\.vibecode-vault/i.test(trimmedKey) ||
120
+ hasAuthSchemeValue(v)) {
121
+ continue;
122
+ }
123
+ safeParams.append(k, redactVaultPaths(v));
124
+ }
125
+ const serialized = safeParams.toString();
126
+ return serialized ? `${basePart}?${serialized}` : basePart;
127
+ }
128
+ }
129
+ function sanitizeText(raw) {
130
+ const noNul = raw.replace(/\0/g, "");
131
+ const noVault = redactVaultPaths(noNul);
132
+ const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
133
+ const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
134
+ const noBearer = noBasicAuth.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
135
+ const noBasic = noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
136
+ const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, (_m, s1, s2, s3) => `${s1 || s2 || s3} [REDACTED]`);
137
+ return noScheme.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
138
+ }
139
+ function sanitizeSingleLine(raw) {
140
+ return sanitizeText(raw)
141
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
142
+ .replace(/\s+/g, " ")
143
+ .trim();
144
+ }
145
+ function sanitizeBaseUrl(raw) {
146
+ const cleaned = raw.replace(/[\r\n\0]+/g, "").trim();
147
+ if (!cleaned || /\.vibecode-vault/i.test(cleaned))
148
+ return null;
149
+ const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
150
+ try {
151
+ const parsed = new URL(withoutAuth);
152
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
153
+ return null;
154
+ parsed.username = "";
155
+ parsed.password = "";
156
+ parsed.search = "";
157
+ parsed.hash = "";
158
+ const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
159
+ return `${parsed.origin}${cleanPath}`;
160
+ }
161
+ catch {
162
+ return null;
163
+ }
164
+ }
165
+ function resolveBaseUrl(contract, options, warnings) {
166
+ if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
167
+ const sanitized = sanitizeBaseUrl(options.baseUrl);
168
+ if (sanitized)
169
+ return sanitized;
170
+ warnings.push("Ignored invalid or unsafe baseUrl option; fell back to contract source or default.");
171
+ }
172
+ if (isRecord(contract.target) && Array.isArray(contract.target.sources) && contract.target.sources.length > 0) {
173
+ const firstSource = contract.target.sources[0];
174
+ if (isRecord(firstSource)) {
175
+ if (typeof firstSource.ref === "string" && /^https?:\/\//i.test(firstSource.ref.trim())) {
176
+ const sanitized = sanitizeBaseUrl(firstSource.ref);
177
+ if (sanitized)
178
+ return sanitized;
179
+ }
180
+ if (isRecord(firstSource.meta) &&
181
+ typeof firstSource.meta.baseUrl === "string" &&
182
+ /^https?:\/\//i.test(firstSource.meta.baseUrl.trim())) {
183
+ const sanitized = sanitizeBaseUrl(firstSource.meta.baseUrl);
184
+ if (sanitized)
185
+ return sanitized;
186
+ }
187
+ }
188
+ }
189
+ return DEFAULT_BASE_URL;
190
+ }
191
+ function sanitizeJsonValue(value, diag, depth = 0, seen = new WeakSet()) {
192
+ if (value === null || value === undefined)
193
+ return value;
194
+ if (typeof value === "boolean")
195
+ return value;
196
+ if (typeof value === "number")
197
+ return Number.isFinite(value) ? value : null;
198
+ if (typeof value === "string") {
199
+ const trimmed = value.trim();
200
+ if (depth < MAX_BODY_DEPTH &&
201
+ ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
202
+ (trimmed.startsWith("[") && trimmed.endsWith("]")))) {
203
+ try {
204
+ const parsed = JSON.parse(trimmed);
205
+ if (parsed !== null && typeof parsed === "object") {
206
+ return JSON.stringify(sanitizeJsonValue(parsed, diag, depth + 1, seen));
207
+ }
208
+ }
209
+ catch {
210
+ // Fall through to plain text sanitization.
211
+ }
212
+ }
213
+ return sanitizeText(value);
214
+ }
215
+ if (depth >= MAX_BODY_DEPTH) {
216
+ diag.hadDepthLimit = true;
217
+ return "[TRUNCATED]";
218
+ }
219
+ if (typeof value !== "object")
220
+ return undefined;
221
+ if (seen.has(value)) {
222
+ diag.hadCircular = true;
223
+ return "[CIRCULAR]";
224
+ }
225
+ seen.add(value);
226
+ try {
227
+ if (Array.isArray(value)) {
228
+ return value.map((item) => sanitizeJsonValue(item, diag, depth + 1, seen));
229
+ }
230
+ const out = {};
231
+ for (const key of Object.keys(value)) {
232
+ if (isForbiddenKey(key))
233
+ continue;
234
+ const cleanKey = sanitizeText(key).replace(/\0/g, "");
235
+ if (!cleanKey || isForbiddenKey(cleanKey))
236
+ continue;
237
+ const rawVal = value[key];
238
+ if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol") {
239
+ continue;
240
+ }
241
+ if (isSecretFieldName(key) || isSecretFieldName(cleanKey)) {
242
+ out[cleanKey] = "[REDACTED]";
243
+ }
244
+ else {
245
+ out[cleanKey] = sanitizeJsonValue(rawVal, diag, depth + 1, seen);
246
+ }
247
+ }
248
+ return out;
249
+ }
250
+ finally {
251
+ seen.delete(value);
252
+ }
253
+ }
254
+ function sanitizeJsonSchema(rawSchema, diag, depth = 0, seen = new WeakSet(), insideSecret = false) {
255
+ if (!isRecord(rawSchema))
256
+ return {};
257
+ if (depth >= MAX_SCHEMA_DEPTH) {
258
+ diag.hadDepthLimit = true;
259
+ return {};
260
+ }
261
+ if (seen.has(rawSchema)) {
262
+ diag.hadCircular = true;
263
+ return {};
264
+ }
265
+ seen.add(rawSchema);
266
+ try {
267
+ const out = {};
268
+ for (const key of Object.keys(rawSchema)) {
269
+ if (isForbiddenKey(key))
270
+ continue;
271
+ const val = rawSchema[key];
272
+ if (val === undefined || typeof val === "function" || typeof val === "symbol")
273
+ continue;
274
+ if (key === "properties" && isRecord(val)) {
275
+ const props = {};
276
+ for (const propKey of Object.keys(val)) {
277
+ if (isForbiddenKey(propKey))
278
+ continue;
279
+ const cleanPropKey = sanitizeText(propKey).replace(/\0/g, "");
280
+ if (!cleanPropKey || isForbiddenKey(cleanPropKey))
281
+ continue;
282
+ const propSchema = val[propKey];
283
+ if (isRecord(propSchema)) {
284
+ props[cleanPropKey] = sanitizeJsonSchema(propSchema, diag, depth + 1, seen, insideSecret || isSecretFieldName(propKey) || isSecretFieldName(cleanPropKey));
285
+ }
286
+ }
287
+ out.properties = props;
288
+ continue;
289
+ }
290
+ if (key === "required" && Array.isArray(val)) {
291
+ out.required = val.filter((k) => typeof k === "string" && !isForbiddenKey(k));
292
+ continue;
293
+ }
294
+ if (key === "items") {
295
+ if (Array.isArray(val)) {
296
+ out.items = val.map((item) => sanitizeJsonSchema(item, diag, depth + 1, seen, insideSecret));
297
+ }
298
+ else if (isRecord(val)) {
299
+ out.items = sanitizeJsonSchema(val, diag, depth + 1, seen, insideSecret);
300
+ }
301
+ continue;
302
+ }
303
+ if (key === "additionalProperties") {
304
+ if (typeof val === "boolean") {
305
+ out.additionalProperties = val;
306
+ }
307
+ else if (isRecord(val)) {
308
+ out.additionalProperties = sanitizeJsonSchema(val, diag, depth + 1, seen, insideSecret);
309
+ }
310
+ continue;
311
+ }
312
+ if ((key === "allOf" || key === "anyOf" || key === "oneOf") && Array.isArray(val)) {
313
+ out[key] = val
314
+ .filter((item) => isRecord(item))
315
+ .map((item) => sanitizeJsonSchema(item, diag, depth + 1, seen, insideSecret));
316
+ continue;
317
+ }
318
+ if (key === "not" && isRecord(val)) {
319
+ out.not = sanitizeJsonSchema(val, diag, depth + 1, seen, insideSecret);
320
+ continue;
321
+ }
322
+ if (key === "const" || key === "example" || key === "default") {
323
+ out[key] = insideSecret ? "[REDACTED]" : sanitizeJsonValue(val, diag, depth + 1, seen);
324
+ continue;
325
+ }
326
+ if (key === "enum" && Array.isArray(val)) {
327
+ out.enum = insideSecret
328
+ ? ["[REDACTED]"]
329
+ : val.map((item) => sanitizeJsonValue(item, diag, depth + 1, seen));
330
+ continue;
331
+ }
332
+ if (key === "pattern" && typeof val === "string") {
333
+ if (!insideSecret) {
334
+ out.pattern = sanitizeText(val);
335
+ }
336
+ continue;
337
+ }
338
+ if (typeof val === "string") {
339
+ out[key] = sanitizeText(val);
340
+ }
341
+ else if (typeof val === "number" || typeof val === "boolean" || val === null) {
342
+ out[key] = val;
343
+ }
344
+ else if (Array.isArray(val)) {
345
+ out[key] = sanitizeJsonValue(val, diag, depth + 1, seen);
346
+ }
347
+ else if (isRecord(val)) {
348
+ out[key] = sanitizeJsonSchema(val, diag, depth + 1, seen, insideSecret);
349
+ }
350
+ }
351
+ return out;
352
+ }
353
+ finally {
354
+ seen.delete(rawSchema);
355
+ }
356
+ }
357
+ function sanitizeJsonPathAssertions(rawPaths, diag) {
358
+ if (!Array.isArray(rawPaths))
359
+ return undefined;
360
+ const out = [];
361
+ for (const item of rawPaths) {
362
+ if (!isRecord(item) || typeof item.path !== "string")
363
+ continue;
364
+ const cleanPath = sanitizeSingleLine(item.path);
365
+ if (!cleanPath)
366
+ continue;
367
+ const segments = cleanPath.split(/[.[\]'"]+/).filter(Boolean);
368
+ if (segments.some((seg) => isForbiddenKey(seg)))
369
+ continue;
370
+ const lastSegment = segments[segments.length - 1] || "";
371
+ const isSecretTarget = isSecretFieldName(lastSegment);
372
+ const next = { path: cleanPath };
373
+ if (Object.prototype.hasOwnProperty.call(item, "equals")) {
374
+ next.equals = isSecretTarget ? "[REDACTED]" : sanitizeJsonValue(item.equals, diag);
375
+ }
376
+ if (typeof item.matches === "string" && !isSecretTarget) {
377
+ next.matches = sanitizeText(item.matches);
378
+ }
379
+ out.push(next);
380
+ }
381
+ return out;
382
+ }
383
+ function sanitizeHeaders(rawHeaders, skipTransportHeaders) {
384
+ if (!isRecord(rawHeaders))
385
+ return [];
386
+ const byLower = new Map();
387
+ for (const rawKey of Object.keys(rawHeaders)) {
388
+ const cleanName = rawKey.replace(/[\r\n\u2028\u2029\0\x00-\x1f\x7f]+/g, "").trim();
389
+ if (!cleanName || isForbiddenKey(cleanName) || isForbiddenKey(cleanName.toLowerCase()))
390
+ continue;
391
+ if (cleanName.startsWith(":") || !HEADER_NAME_TOKEN_RE.test(cleanName))
392
+ continue;
393
+ const lower = cleanName.toLowerCase();
394
+ if (skipTransportHeaders && TRANSPORT_SKIP_HEADERS.has(lower))
395
+ continue;
396
+ if (isSensitiveHeaderName(cleanName))
397
+ continue;
398
+ const rawVal = rawHeaders[rawKey];
399
+ if (rawVal === undefined || rawVal === null)
400
+ continue;
401
+ const singleLine = String(rawVal)
402
+ .replace(/\0/g, "")
403
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
404
+ .trim();
405
+ if (!singleLine || hasAuthSchemeValue(singleLine))
406
+ continue;
407
+ const cleanVal = sanitizeSingleLine(singleLine);
408
+ if (!cleanVal)
409
+ continue;
410
+ byLower.set(lower, { name: cleanName, value: cleanVal });
411
+ }
412
+ return [...byLower.values()];
413
+ }
414
+ function sanitizePathname(rawPathname) {
415
+ const noHash = rawPathname.split("#")[0] || "";
416
+ const noControl = sanitizeText(noHash)
417
+ .replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, "")
418
+ .trim();
419
+ if (!noControl)
420
+ return "/";
421
+ const encodedSpaces = noControl.replace(/\s+/g, "%20");
422
+ return encodedSpaces.startsWith("/") ? encodedSpaces : `/${encodedSpaces}`;
423
+ }
424
+ function splitRelativePathAndQuery(raw) {
425
+ const hashIdx = raw.indexOf("#");
426
+ const withoutHash = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
427
+ const qIdx = withoutHash.indexOf("?");
428
+ const rawPathPart = qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash;
429
+ const rawQueryPart = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
430
+ const inlineQuery = [];
431
+ if (rawQueryPart) {
432
+ const params = new URLSearchParams(rawQueryPart);
433
+ for (const [k, v] of params.entries()) {
434
+ inlineQuery.push([k, v]);
435
+ }
436
+ }
437
+ return {
438
+ pathname: sanitizePathname(rawPathPart),
439
+ inlineQuery
440
+ };
441
+ }
442
+ function parsePathAndInlineQuery(rawPath) {
443
+ if (typeof rawPath !== "string") {
444
+ return { pathname: "/", inlineQuery: [] };
445
+ }
446
+ const cleaned = rawPath.replace(/[\r\n\0]+/g, "").trim();
447
+ if (!cleaned) {
448
+ return { pathname: "/", inlineQuery: [] };
449
+ }
450
+ if (/^https?:\/\//i.test(cleaned)) {
451
+ const withoutAuth = cleaned.replace(URL_BASIC_AUTH_RE, "$1");
452
+ try {
453
+ const parsed = new URL(withoutAuth);
454
+ const inlineQuery = [];
455
+ for (const [k, v] of parsed.searchParams.entries()) {
456
+ inlineQuery.push([k, v]);
457
+ }
458
+ return {
459
+ pathname: sanitizePathname(parsed.pathname || "/"),
460
+ inlineQuery
461
+ };
462
+ }
463
+ catch {
464
+ const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
465
+ return splitRelativePathAndQuery(stripped);
466
+ }
467
+ }
468
+ return splitRelativePathAndQuery(cleaned);
469
+ }
470
+ function sanitizeQueryEntries(inlineQuery, structuredQuery) {
471
+ const merged = new Map();
472
+ const consider = (rawKey, rawVal) => {
473
+ const cleanKey = rawKey.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
474
+ if (!cleanKey || isForbiddenKey(cleanKey))
475
+ return;
476
+ if (isSensitiveQueryName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
477
+ return;
478
+ if (hasAuthSchemeValue(rawVal))
479
+ return;
480
+ const cleanVal = sanitizeText(rawVal).replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, "");
481
+ if (hasAuthSchemeValue(cleanVal))
482
+ return;
483
+ merged.set(cleanKey, cleanVal);
484
+ };
485
+ for (const [k, v] of inlineQuery) {
486
+ consider(k, v);
487
+ }
488
+ if (isRecord(structuredQuery)) {
489
+ for (const key of Object.keys(structuredQuery)) {
490
+ if (isForbiddenKey(key))
491
+ continue;
492
+ const val = structuredQuery[key];
493
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
494
+ if (typeof val === "number" && !Number.isFinite(val))
495
+ continue;
496
+ consider(key, String(val));
497
+ }
498
+ }
499
+ }
500
+ return [...merged.entries()].map(([name, value]) => ({ name, value }));
501
+ }
502
+ function findHeaderValue(headers, target) {
503
+ const lower = target.toLowerCase();
504
+ for (const h of headers) {
505
+ if (h.name.toLowerCase() === lower)
506
+ return h.value;
507
+ }
508
+ return undefined;
509
+ }
510
+ function buildPostData(rawBody, reqHeaders, diag) {
511
+ if (rawBody === undefined || rawBody === null)
512
+ return undefined;
513
+ const existingCt = findHeaderValue(reqHeaders, "content-type");
514
+ if (typeof rawBody === "string") {
515
+ if (rawBody.length === 0)
516
+ return undefined;
517
+ const trimmed = rawBody.trim();
518
+ if ((trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
519
+ try {
520
+ const parsed = JSON.parse(trimmed);
521
+ if (parsed !== null && typeof parsed === "object") {
522
+ const sanitized = sanitizeJsonValue(parsed, diag);
523
+ return {
524
+ mimeType: existingCt || "application/json",
525
+ text: JSON.stringify(sanitized)
526
+ };
527
+ }
528
+ }
529
+ catch {
530
+ // Fall through to plain text.
531
+ }
532
+ }
533
+ if (existingCt && existingCt.toLowerCase().includes("application/x-www-form-urlencoded")) {
534
+ const params = new URLSearchParams(rawBody);
535
+ const safeParams = new URLSearchParams();
536
+ for (const [k, v] of params.entries()) {
537
+ if (isForbiddenKey(k))
538
+ continue;
539
+ if (isSecretFieldName(k) || hasAuthSchemeValue(v)) {
540
+ safeParams.append(k, "[REDACTED]");
541
+ }
542
+ else {
543
+ safeParams.append(k, sanitizeText(v));
544
+ }
545
+ }
546
+ const serialized = safeParams.toString();
547
+ if (!serialized)
548
+ return undefined;
549
+ return {
550
+ mimeType: existingCt,
551
+ text: serialized
552
+ };
553
+ }
554
+ const cleanText = sanitizeText(rawBody);
555
+ if (cleanText.length === 0)
556
+ return undefined;
557
+ return {
558
+ mimeType: existingCt || "text/plain; charset=utf-8",
559
+ text: cleanText
560
+ };
561
+ }
562
+ if (typeof rawBody === "object") {
563
+ const sanitized = sanitizeJsonValue(rawBody, diag);
564
+ return {
565
+ mimeType: existingCt || "application/json",
566
+ text: JSON.stringify(sanitized)
567
+ };
568
+ }
569
+ if (typeof rawBody === "boolean" || typeof rawBody === "number") {
570
+ const val = typeof rawBody === "number" && !Number.isFinite(rawBody) ? null : rawBody;
571
+ return {
572
+ mimeType: existingCt || "application/json",
573
+ text: JSON.stringify(val)
574
+ };
575
+ }
576
+ return undefined;
577
+ }
578
+ function sanitizeResponseBody(rawBody, contentType, diag) {
579
+ if (!rawBody)
580
+ return "";
581
+ const lowerCt = contentType.toLowerCase();
582
+ const trimmed = rawBody.trim();
583
+ const looksJson = lowerCt.includes("json") ||
584
+ ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
585
+ (trimmed.startsWith("[") && trimmed.endsWith("]")));
586
+ if (looksJson && trimmed) {
587
+ try {
588
+ const parsed = JSON.parse(trimmed);
589
+ if (parsed !== null && typeof parsed === "object") {
590
+ const sanitized = sanitizeJsonValue(parsed, diag);
591
+ return JSON.stringify(sanitized);
592
+ }
593
+ }
594
+ catch {
595
+ // Not valid JSON; sanitize as plain text below.
596
+ }
597
+ }
598
+ return sanitizeText(rawBody);
599
+ }
600
+ function sanitizeInvariantForCompilation(inv, diag) {
601
+ const rawInput = isRecord(inv.input) ? inv.input : {};
602
+ const rawExpected = isRecord(inv.expected) ? inv.expected : {};
603
+ const safeHeaders = {};
604
+ for (const h of sanitizeHeaders(rawExpected.headers, true)) {
605
+ safeHeaders[h.name.toLowerCase()] = h.value;
606
+ }
607
+ const safeExpected = {
608
+ ...rawExpected,
609
+ headers: safeHeaders
610
+ };
611
+ if (isRecord(rawExpected.jsonSchema)) {
612
+ safeExpected.jsonSchema = sanitizeJsonSchema(rawExpected.jsonSchema, diag);
613
+ }
614
+ if (rawExpected.jsonSubset !== undefined) {
615
+ safeExpected.jsonSubset = sanitizeJsonValue(rawExpected.jsonSubset, diag);
616
+ }
617
+ if (Array.isArray(rawExpected.jsonPaths)) {
618
+ safeExpected.jsonPaths = sanitizeJsonPathAssertions(rawExpected.jsonPaths, diag);
619
+ }
620
+ if (typeof rawExpected.bodyExact === "string") {
621
+ safeExpected.bodyExact = sanitizeResponseBody(rawExpected.bodyExact, safeHeaders["content-type"] || "", diag);
622
+ }
623
+ if (typeof rawExpected.bodyContains === "string") {
624
+ safeExpected.bodyContains = sanitizeText(rawExpected.bodyContains);
625
+ }
626
+ else if (Array.isArray(rawExpected.bodyContains)) {
627
+ safeExpected.bodyContains = rawExpected.bodyContains.map((s) => typeof s === "string" ? sanitizeText(s) : "");
628
+ }
629
+ if (typeof rawExpected.titleContains === "string") {
630
+ safeExpected.titleContains = sanitizeText(rawExpected.titleContains);
631
+ }
632
+ return {
633
+ ...inv,
634
+ input: { ...rawInput },
635
+ expected: safeExpected
636
+ };
637
+ }
638
+ function resolveStatusText(status) {
639
+ const fromStdlib = http.STATUS_CODES[status];
640
+ if (typeof fromStdlib === "string" && fromStdlib.length > 0) {
641
+ return fromStdlib;
642
+ }
643
+ if (status >= 200 && status < 300)
644
+ return "OK";
645
+ if (status >= 300 && status < 400)
646
+ return "Redirect";
647
+ if (status >= 400 && status < 500)
648
+ return "Client Error";
649
+ if (status >= 500 && status < 600)
650
+ return "Server Error";
651
+ return "";
652
+ }
653
+ function buildEntryUrl(baseUrl, pathname, queryString) {
654
+ const params = new URLSearchParams();
655
+ for (const item of queryString) {
656
+ params.append(item.name, item.value);
657
+ }
658
+ const serialized = params.toString();
659
+ const raw = `${baseUrl}${pathname}${serialized ? `?${serialized}` : ""}`;
660
+ try {
661
+ const parsed = new URL(raw);
662
+ parsed.username = "";
663
+ parsed.password = "";
664
+ parsed.hash = "";
665
+ return parsed.toString();
666
+ }
667
+ catch {
668
+ return raw.split("#")[0] || raw;
669
+ }
670
+ }
671
+ /**
672
+ * Export visible HTTP (and optionally web_route) invariants from a ContractV02 into a
673
+ * W3C HAR 1.2 archive compatible with Chrome DevTools, Playwright `page.routeFromHAR`,
674
+ * and lossless `vibecode-anything` HAR re-ingestion.
675
+ */
676
+ export function exportHarArchive(contract, options = {}) {
677
+ if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
678
+ throw new VibecodeError("CONTRACT_INVALID", "exportHarArchive requires a valid contract object with an invariants array.");
679
+ }
680
+ const includeWebRoutes = options.includeWebRoutes !== false;
681
+ const includeSkippedComments = options.includeSkippedComments !== false;
682
+ const pretty = options.pretty !== false;
683
+ const warnings = [];
684
+ const baseUrl = resolveBaseUrl(contract, options, warnings);
685
+ const rawTitle = (typeof options.title === "string" && options.title.trim()) ||
686
+ (isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()) ||
687
+ DEFAULT_TITLE;
688
+ const title = sanitizeSingleLine(rawTitle) || DEFAULT_TITLE;
689
+ const exportableOriginals = [];
690
+ const exportableSanitized = [];
691
+ const skippedIds = [];
692
+ for (let i = 0; i < contract.invariants.length; i++) {
693
+ const inv = contract.invariants[i];
694
+ if (!isRecord(inv))
695
+ continue;
696
+ // Holdout zero-leakage: completely invisible in entries, skippedCount, comments, and warnings.
697
+ if (inv.holdout === true) {
698
+ continue;
699
+ }
700
+ const invId = sanitizeSingleLine(typeof inv.id === "string" && inv.id.trim() ? inv.id.trim() : `inv-${i + 1}`);
701
+ const invType = typeof inv.type === "string" ? inv.type : "";
702
+ if (invType === "http" || (invType === "web_route" && includeWebRoutes)) {
703
+ const diag = { hadCircular: false, hadDepthLimit: false };
704
+ exportableOriginals.push(inv);
705
+ exportableSanitized.push(sanitizeInvariantForCompilation(inv, diag));
706
+ if (diag.hadCircular) {
707
+ warnings.push(`Sanitized circular reference while compiling invariant ${invId}.`);
708
+ }
709
+ if (diag.hadDepthLimit) {
710
+ warnings.push(`Truncated overly deep schema/payload while compiling invariant ${invId}.`);
711
+ }
712
+ }
713
+ else {
714
+ skippedIds.push(invId);
715
+ }
716
+ }
717
+ const sanitizedTarget = isRecord(contract.target)
718
+ ? {
719
+ ...contract.target,
720
+ name: sanitizeSingleLine(typeof contract.target.name === "string" ? contract.target.name : title) || title
721
+ }
722
+ : { name: title, domains: ["api"], sources: [] };
723
+ const compiled = compileMockRoutes({
724
+ ...contract,
725
+ target: sanitizedTarget,
726
+ invariants: exportableSanitized
727
+ });
728
+ const entries = [];
729
+ const seenKeys = new Set();
730
+ const pageId = "page_1";
731
+ const pageStartedDateTime = new Date(DETERMINISTIC_EPOCH_MS).toISOString();
732
+ for (let idx = 0; idx < compiled.routes.length; idx++) {
733
+ const route = compiled.routes[idx];
734
+ const original = exportableOriginals[idx];
735
+ const rawInput = isRecord(original?.input) ? original.input : {};
736
+ const invId = sanitizeSingleLine(route.invariantId || `inv-${idx + 1}`);
737
+ const diag = { hadCircular: false, hadDepthLimit: false };
738
+ const rawMethod = String(route.method || "GET")
739
+ .replace(/[\r\n\0]+/g, "")
740
+ .trim()
741
+ .toUpperCase();
742
+ const method = HTTP_METHOD_TOKEN_RE.test(rawMethod) ? rawMethod : "GET";
743
+ const rawPath = original?.type === "web_route"
744
+ ? (typeof rawInput.urlPath === "string" && rawInput.urlPath.trim() ? rawInput.urlPath : undefined) ??
745
+ (typeof rawInput.path === "string" && rawInput.path.trim() ? rawInput.path : undefined) ??
746
+ route.path
747
+ : (typeof rawInput.path === "string" && rawInput.path.trim() ? rawInput.path : undefined) ??
748
+ (typeof rawInput.urlPath === "string" && rawInput.urlPath.trim() ? rawInput.urlPath : undefined) ??
749
+ route.path;
750
+ const { pathname, inlineQuery } = parsePathAndInlineQuery(rawPath);
751
+ const queryString = sanitizeQueryEntries(inlineQuery, rawInput.query);
752
+ const entryUrl = buildEntryUrl(baseUrl, pathname, queryString);
753
+ const reqHeaders = sanitizeHeaders(rawInput.headers, true);
754
+ let postData;
755
+ if (!BODY_FORBIDDEN_METHODS.has(method)) {
756
+ postData = buildPostData(rawInput.body, reqHeaders, diag);
757
+ if (postData && !findHeaderValue(reqHeaders, "content-type")) {
758
+ reqHeaders.push({ name: "Content-Type", value: postData.mimeType });
759
+ }
760
+ }
761
+ const reqBodySize = postData ? Buffer.byteLength(postData.text, "utf8") : 0;
762
+ if (reqBodySize > HAR_INGEST_MAX_BODY_BYTES) {
763
+ warnings.push(`Request body for ${method} ${pathname} exceeds 128 KiB (${reqBodySize} bytes).`);
764
+ }
765
+ const cleanContentType = sanitizeSingleLine(route.contentType || "application/json; charset=utf-8") ||
766
+ "application/json; charset=utf-8";
767
+ const respHeaders = sanitizeHeaders(route.headers, true);
768
+ const hasRespCt = respHeaders.some((h) => h.name.toLowerCase() === "content-type");
769
+ if (!hasRespCt) {
770
+ respHeaders.push({ name: "Content-Type", value: cleanContentType });
771
+ }
772
+ const isNoBodyStatus = route.status === 204 || route.status === 304;
773
+ const finalBody = isNoBodyStatus
774
+ ? ""
775
+ : sanitizeResponseBody(route.body, cleanContentType, diag);
776
+ const bodyBytes = Buffer.byteLength(finalBody, "utf8");
777
+ if (!isNoBodyStatus) {
778
+ respHeaders.push({ name: "Content-Length", value: String(bodyBytes) });
779
+ }
780
+ if (bodyBytes > HAR_INGEST_MAX_BODY_BYTES) {
781
+ warnings.push(`Response body for ${method} ${pathname} exceeds 128 KiB (${bodyBytes} bytes).`);
782
+ }
783
+ if (diag.hadCircular) {
784
+ warnings.push(`Sanitized circular reference in payload for invariant ${invId}.`);
785
+ }
786
+ if (diag.hadDepthLimit) {
787
+ warnings.push(`Truncated deeply nested payload for invariant ${invId}.`);
788
+ }
789
+ const dedupeKey = `${method} ${entryUrl}`;
790
+ if (seenKeys.has(dedupeKey)) {
791
+ warnings.push(`Duplicate HAR entry for ${method} ${pathname} (${invId}); re-ingestion deduplicates identical requests.`);
792
+ }
793
+ seenKeys.add(dedupeKey);
794
+ const requestObj = {
795
+ method,
796
+ url: entryUrl,
797
+ httpVersion: "HTTP/1.1",
798
+ cookies: [],
799
+ headers: reqHeaders,
800
+ queryString,
801
+ ...(postData ? { postData } : {}),
802
+ headersSize: -1,
803
+ bodySize: reqBodySize
804
+ };
805
+ const responseObj = {
806
+ status: route.status,
807
+ statusText: resolveStatusText(route.status),
808
+ httpVersion: "HTTP/1.1",
809
+ cookies: [],
810
+ headers: respHeaders,
811
+ content: {
812
+ size: bodyBytes,
813
+ mimeType: cleanContentType,
814
+ text: finalBody
815
+ },
816
+ redirectURL: "",
817
+ headersSize: -1,
818
+ bodySize: bodyBytes
819
+ };
820
+ const rawDesc = typeof original?.description === "string" && original.description.trim()
821
+ ? sanitizeSingleLine(original.description)
822
+ : "";
823
+ const entryComment = rawDesc ? `${invId}: ${rawDesc}` : invId;
824
+ entries.push({
825
+ pageref: pageId,
826
+ startedDateTime: new Date(DETERMINISTIC_EPOCH_MS + idx * 10).toISOString(),
827
+ time: 1,
828
+ request: requestObj,
829
+ response: responseObj,
830
+ cache: {},
831
+ timings: {
832
+ blocked: -1,
833
+ dns: -1,
834
+ connect: -1,
835
+ send: 0,
836
+ wait: 1,
837
+ receive: 0,
838
+ ssl: -1
839
+ },
840
+ comment: entryComment
841
+ });
842
+ }
843
+ const log = {
844
+ version: HAR_VERSION,
845
+ creator: {
846
+ name: CREATOR_NAME,
847
+ version: CREATOR_VERSION
848
+ },
849
+ pages: [
850
+ {
851
+ startedDateTime: pageStartedDateTime,
852
+ id: pageId,
853
+ title,
854
+ pageTimings: {
855
+ onContentLoad: -1,
856
+ onLoad: -1
857
+ }
858
+ }
859
+ ],
860
+ entries
861
+ };
862
+ if (includeSkippedComments && skippedIds.length > 0) {
863
+ log.comment = `Skipped ${skippedIds.length} non-HTTP ${skippedIds.length === 1 ? "invariant" : "invariants"}: ${skippedIds.join(", ")}`;
864
+ }
865
+ const har = { log };
866
+ const content = `${pretty ? JSON.stringify(har, null, 2) : JSON.stringify(har)}\n`;
867
+ return {
868
+ content,
869
+ har,
870
+ exportedCount: entries.length,
871
+ skippedCount: skippedIds.length,
872
+ warnings
873
+ };
874
+ }
875
+ /**
876
+ * Export and atomically write a W3C HAR 1.2 archive to disk (temp file + rename in parent dir).
877
+ */
878
+ export function writeHarArchive(contract, outPath, options = {}) {
879
+ if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
880
+ throw new VibecodeError("CONTRACT_INVALID", "writeHarArchive requires a valid non-empty outPath without NUL bytes.");
881
+ }
882
+ const result = exportHarArchive(contract, options);
883
+ const resolvedOut = path.resolve(outPath.trim());
884
+ const parentDir = path.dirname(resolvedOut);
885
+ fs.mkdirSync(parentDir, { recursive: true });
886
+ const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
887
+ try {
888
+ fs.writeFileSync(tmpPath, result.content, "utf8");
889
+ fs.renameSync(tmpPath, resolvedOut);
890
+ }
891
+ catch (err) {
892
+ try {
893
+ if (fs.existsSync(tmpPath)) {
894
+ fs.rmSync(tmpPath, { force: true });
895
+ }
896
+ }
897
+ catch {
898
+ // ignore cleanup failure
899
+ }
900
+ throw err;
901
+ }
902
+ return result;
903
+ }
904
+ function style(text, codes, useColor) {
905
+ return useColor ? `${codes}${text}${ANSI.reset}` : text;
906
+ }
907
+ function methodColor(method) {
908
+ switch (method.toUpperCase()) {
909
+ case "GET":
910
+ return ANSI.green;
911
+ case "POST":
912
+ case "PUT":
913
+ case "PATCH":
914
+ return ANSI.yellow;
915
+ case "DELETE":
916
+ return ANSI.red;
917
+ default:
918
+ return ANSI.cyan;
919
+ }
920
+ }
921
+ function statusColor(status) {
922
+ if (status >= 500)
923
+ return ANSI.red;
924
+ if (status >= 400)
925
+ return ANSI.yellow;
926
+ if (status >= 300)
927
+ return ANSI.cyan;
928
+ return ANSI.green;
929
+ }
930
+ /**
931
+ * Format a concise, sanitized terminal summary for a HAR 1.2 export result.
932
+ */
933
+ export function formatPrettyHarExport(result, outPath, color) {
934
+ const useColor = color === true;
935
+ const lines = [];
936
+ const banner = style("[HAR EXPORT]", `${ANSI.bold}${ANSI.cyan}`, useColor);
937
+ const specLabel = style("W3C HAR 1.2", ANSI.bold, useColor);
938
+ lines.push(`${banner} ${specLabel}`);
939
+ if (typeof outPath === "string" && outPath.trim().length > 0) {
940
+ lines.push(`Output: ${sanitizeSingleLine(outPath)}`);
941
+ }
942
+ const totalBytes = Buffer.byteLength(result.content || "", "utf8");
943
+ const entryLabel = result.exportedCount === 1 ? "entry" : "entries";
944
+ const summaryParts = [`${result.exportedCount} ${entryLabel}`];
945
+ if (result.skippedCount > 0) {
946
+ summaryParts.push(`${result.skippedCount} skipped`);
947
+ }
948
+ summaryParts.push(`${totalBytes} bytes`);
949
+ lines.push(`Summary: ${summaryParts.join(", ")}`);
950
+ const logObj = isRecord(result.har) && isRecord(result.har.log) ? result.har.log : null;
951
+ const rawEntries = logObj && Array.isArray(logObj.entries) ? logObj.entries : [];
952
+ if (rawEntries.length > 0) {
953
+ lines.push("Entries:");
954
+ const shown = rawEntries.slice(0, MAX_PRETTY_ENTRIES);
955
+ for (const rawEntry of shown) {
956
+ if (!isRecord(rawEntry))
957
+ continue;
958
+ const req = isRecord(rawEntry.request) ? rawEntry.request : {};
959
+ const res = isRecord(rawEntry.response) ? rawEntry.response : {};
960
+ const content = isRecord(res.content) ? res.content : {};
961
+ const method = sanitizeSingleLine(typeof req.method === "string" ? req.method : "GET");
962
+ const url = sanitizeSingleLine(typeof req.url === "string" ? req.url : "/");
963
+ const status = typeof res.status === "number" && Number.isFinite(res.status) ? res.status : 200;
964
+ const mimeType = sanitizeSingleLine(typeof content.mimeType === "string" ? content.mimeType : "application/octet-stream");
965
+ const size = typeof content.size === "number" && Number.isFinite(content.size) ? content.size : 0;
966
+ const m = style(method.padEnd(6), `${ANSI.bold}${methodColor(method)}`, useColor);
967
+ const st = style(String(status), statusColor(status), useColor);
968
+ const meta = style(`(${mimeType}, ${size} B)`, ANSI.dim, useColor);
969
+ lines.push(` - ${m} ${url} -> ${st} ${meta}`);
970
+ }
971
+ if (rawEntries.length > MAX_PRETTY_ENTRIES) {
972
+ lines.push(` ${style(`... and ${rawEntries.length - MAX_PRETTY_ENTRIES} more`, ANSI.dim, useColor)}`);
973
+ }
974
+ }
975
+ else {
976
+ lines.push(`Entries: ${style("none", ANSI.dim, useColor)}`);
977
+ }
978
+ if (Array.isArray(result.warnings) && result.warnings.length > 0) {
979
+ lines.push("Warnings:");
980
+ for (const warning of result.warnings.slice(0, MAX_PRETTY_WARNINGS)) {
981
+ lines.push(` - ${style(sanitizeSingleLine(warning), ANSI.yellow, useColor)}`);
982
+ }
983
+ if (result.warnings.length > MAX_PRETTY_WARNINGS) {
984
+ lines.push(` ${style(`... and ${result.warnings.length - MAX_PRETTY_WARNINGS} more`, ANSI.dim, useColor)}`);
985
+ }
986
+ }
987
+ return lines.join("\n");
988
+ }