vibecode-anything 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +3 -2
- package/dist/core/schema.js +460 -17
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/index.js +486 -6
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,1918 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { VibecodeError } from "./errors.js";
|
|
5
|
+
import { exportPlaywrightTests } from "./playwright-exporter.js";
|
|
6
|
+
import { isSensitiveHeader } from "../ingestors/trace.js";
|
|
7
|
+
const VALID_FORMATS = new Set(["node-test", "vitest", "pytest", "shell", "playwright"]);
|
|
8
|
+
const SUGGESTED_FILENAMES = {
|
|
9
|
+
"node-test": "vibecode-contract.test.mjs",
|
|
10
|
+
vitest: "vibecode-contract.test.ts",
|
|
11
|
+
pytest: "test_vibecode_contract.py",
|
|
12
|
+
shell: "vibecode-contract.sh",
|
|
13
|
+
playwright: "vibecode-contract.spec.ts"
|
|
14
|
+
};
|
|
15
|
+
const EXPORTABLE_TYPES = new Set(["command", "http", "web_route", "repo_exports"]);
|
|
16
|
+
const SENSITIVE_QUERY_PARAM_RE = /^(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|secret|client[_-]?secret|password|passwd|auth|jwt|session[_-]?id|sig|signature|private[_-]?key)$/i;
|
|
17
|
+
const EXTRA_SENSITIVE_HEADER_RE = /^(?:api[_-]?key|apikey|x[_-]api[_-]?key|x[_-]auth[_-]?token|x[_-]access[_-]?token|x[_-]session[_-]?token|x[_-]secret)$/i;
|
|
18
|
+
const SENSITIVE_ENV_KEY_RE = /(?:^|_)(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|APIKEY|PRIVATE_KEY|AUTH_HEADER|AUTHORIZATION|COOKIE)(?:$|_)/i;
|
|
19
|
+
const VAULT_PATH_RE = /(?:[A-Za-z]:)?[^\s"'`<>]*\.vibecode-vault[^\s"'`<>]*/gi;
|
|
20
|
+
const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
|
|
21
|
+
const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s@"'`<>]+)@/g;
|
|
22
|
+
const BEARER_OR_BASIC_VALUE_RE = /^\s*(?:bearer|basic)\s+\S+/i;
|
|
23
|
+
const INLINE_AUTH_TOKEN_RE = /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi;
|
|
24
|
+
function isRecord(value) {
|
|
25
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
26
|
+
}
|
|
27
|
+
function isSensitiveHeaderName(name) {
|
|
28
|
+
const trimmed = String(name).trim();
|
|
29
|
+
return isSensitiveHeader(trimmed) || EXTRA_SENSITIVE_HEADER_RE.test(trimmed);
|
|
30
|
+
}
|
|
31
|
+
function isSensitiveQueryName(name) {
|
|
32
|
+
return SENSITIVE_QUERY_PARAM_RE.test(String(name).trim());
|
|
33
|
+
}
|
|
34
|
+
function redactVaultPaths(text) {
|
|
35
|
+
return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
|
|
36
|
+
}
|
|
37
|
+
function sanitizeUrlString(rawUrl) {
|
|
38
|
+
const withoutVault = redactVaultPaths(rawUrl);
|
|
39
|
+
const withoutBasicAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
|
|
40
|
+
try {
|
|
41
|
+
const parsed = new URL(withoutBasicAuth);
|
|
42
|
+
parsed.username = "";
|
|
43
|
+
parsed.password = "";
|
|
44
|
+
const safeParams = new URLSearchParams();
|
|
45
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
46
|
+
if (isSensitiveQueryName(k))
|
|
47
|
+
continue;
|
|
48
|
+
safeParams.append(k, redactVaultPaths(v));
|
|
49
|
+
}
|
|
50
|
+
const serialized = safeParams.toString();
|
|
51
|
+
parsed.search = serialized ? `?${serialized}` : "";
|
|
52
|
+
return parsed.toString();
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return withoutBasicAuth;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function sanitizePathWithQuery(rawPath) {
|
|
59
|
+
const cleaned = redactVaultPaths(rawPath.trim());
|
|
60
|
+
if (!cleaned)
|
|
61
|
+
return "/";
|
|
62
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(cleaned)) {
|
|
63
|
+
return sanitizeUrlString(cleaned);
|
|
64
|
+
}
|
|
65
|
+
const withoutAuth = cleaned.replace(URL_BASIC_AUTH_RE, "$1");
|
|
66
|
+
const qIdx = withoutAuth.indexOf("?");
|
|
67
|
+
if (qIdx < 0)
|
|
68
|
+
return withoutAuth;
|
|
69
|
+
const hashIdx = withoutAuth.indexOf("#", qIdx);
|
|
70
|
+
const basePath = withoutAuth.slice(0, qIdx);
|
|
71
|
+
const rawQuery = hashIdx >= 0 ? withoutAuth.slice(qIdx + 1, hashIdx) : withoutAuth.slice(qIdx + 1);
|
|
72
|
+
const hashPart = hashIdx >= 0 ? withoutAuth.slice(hashIdx) : "";
|
|
73
|
+
const rawParams = new URLSearchParams(rawQuery);
|
|
74
|
+
const safeParams = new URLSearchParams();
|
|
75
|
+
for (const [k, v] of rawParams.entries()) {
|
|
76
|
+
if (isSensitiveQueryName(k))
|
|
77
|
+
continue;
|
|
78
|
+
safeParams.append(k, redactVaultPaths(v));
|
|
79
|
+
}
|
|
80
|
+
const serialized = safeParams.toString();
|
|
81
|
+
return `${basePath}${serialized ? `?${serialized}` : ""}${hashPart}`;
|
|
82
|
+
}
|
|
83
|
+
function sanitizeFreeText(text) {
|
|
84
|
+
const noVault = redactVaultPaths(text);
|
|
85
|
+
const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlString(match));
|
|
86
|
+
const noAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
|
|
87
|
+
return noAuth.replace(INLINE_AUTH_TOKEN_RE, "$1 [REDACTED]");
|
|
88
|
+
}
|
|
89
|
+
function sanitizeComment(text, maxLen = 220) {
|
|
90
|
+
const sanitized = sanitizeFreeText(text)
|
|
91
|
+
// eslint-disable-next-line no-control-regex
|
|
92
|
+
.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
|
|
93
|
+
.replace(/[\r\n\u2028\u2029]+/g, " ")
|
|
94
|
+
// eslint-disable-next-line no-control-regex
|
|
95
|
+
.replace(/[\x00-\x1F\x7F]/g, " ")
|
|
96
|
+
.replace(/<\/(script)/gi, "<\\/$1")
|
|
97
|
+
.replace(/\s+/g, " ")
|
|
98
|
+
.trim();
|
|
99
|
+
if (sanitized.length <= maxLen)
|
|
100
|
+
return sanitized;
|
|
101
|
+
return `${sanitized.slice(0, maxLen - 3)}...`;
|
|
102
|
+
}
|
|
103
|
+
function sanitizeTargetString(raw) {
|
|
104
|
+
if (typeof raw !== "string")
|
|
105
|
+
return "";
|
|
106
|
+
const trimmed = raw.trim();
|
|
107
|
+
if (!trimmed)
|
|
108
|
+
return "";
|
|
109
|
+
if (/\.vibecode-vault/i.test(trimmed))
|
|
110
|
+
return "";
|
|
111
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(trimmed)) {
|
|
112
|
+
return sanitizeUrlString(trimmed);
|
|
113
|
+
}
|
|
114
|
+
return sanitizeFreeText(trimmed);
|
|
115
|
+
}
|
|
116
|
+
function sanitizeHeaders(rawHeaders) {
|
|
117
|
+
const headers = {};
|
|
118
|
+
let hadSensitiveHeaders = false;
|
|
119
|
+
if (!isRecord(rawHeaders)) {
|
|
120
|
+
return { headers, hadSensitiveHeaders };
|
|
121
|
+
}
|
|
122
|
+
for (const [rawKey, rawVal] of Object.entries(rawHeaders)) {
|
|
123
|
+
const key = rawKey.trim();
|
|
124
|
+
if (!key || rawVal === undefined || rawVal === null)
|
|
125
|
+
continue;
|
|
126
|
+
const strVal = String(rawVal);
|
|
127
|
+
if (isSensitiveHeaderName(key) ||
|
|
128
|
+
strVal.trim() === "[REDACTED]" ||
|
|
129
|
+
BEARER_OR_BASIC_VALUE_RE.test(strVal)) {
|
|
130
|
+
hadSensitiveHeaders = true;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
headers[key] = sanitizeFreeText(strVal);
|
|
134
|
+
}
|
|
135
|
+
return { headers, hadSensitiveHeaders };
|
|
136
|
+
}
|
|
137
|
+
function sanitizeQueryRecord(rawQuery) {
|
|
138
|
+
const out = {};
|
|
139
|
+
if (!isRecord(rawQuery))
|
|
140
|
+
return out;
|
|
141
|
+
for (const [rawKey, rawVal] of Object.entries(rawQuery)) {
|
|
142
|
+
const key = rawKey.trim();
|
|
143
|
+
if (!key || rawVal === undefined || rawVal === null)
|
|
144
|
+
continue;
|
|
145
|
+
if (isSensitiveQueryName(key))
|
|
146
|
+
continue;
|
|
147
|
+
out[key] = sanitizeFreeText(String(rawVal));
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
function sanitizeEnvRecord(rawEnv) {
|
|
152
|
+
const out = {};
|
|
153
|
+
if (!isRecord(rawEnv))
|
|
154
|
+
return out;
|
|
155
|
+
for (const [rawKey, rawVal] of Object.entries(rawEnv)) {
|
|
156
|
+
const key = rawKey.trim();
|
|
157
|
+
if (!key || rawVal === undefined || rawVal === null)
|
|
158
|
+
continue;
|
|
159
|
+
if (SENSITIVE_ENV_KEY_RE.test(key) || isSensitiveQueryName(key))
|
|
160
|
+
continue;
|
|
161
|
+
const strVal = String(rawVal);
|
|
162
|
+
if (/\.vibecode-vault/i.test(strVal) || BEARER_OR_BASIC_VALUE_RE.test(strVal))
|
|
163
|
+
continue;
|
|
164
|
+
out[key] = sanitizeFreeText(strVal);
|
|
165
|
+
}
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
function sanitizeDeepValue(value, depth = 0) {
|
|
169
|
+
if (depth > 20)
|
|
170
|
+
return null;
|
|
171
|
+
if (typeof value === "string")
|
|
172
|
+
return sanitizeFreeText(value);
|
|
173
|
+
if (Array.isArray(value))
|
|
174
|
+
return value.map((item) => sanitizeDeepValue(item, depth + 1));
|
|
175
|
+
if (isRecord(value)) {
|
|
176
|
+
const out = {};
|
|
177
|
+
for (const [k, v] of Object.entries(value)) {
|
|
178
|
+
if (v === undefined)
|
|
179
|
+
continue;
|
|
180
|
+
out[k] = sanitizeDeepValue(v, depth + 1);
|
|
181
|
+
}
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
186
|
+
function safeJsonLiteral(value) {
|
|
187
|
+
const serialized = JSON.stringify(value === undefined ? null : value) ?? "null";
|
|
188
|
+
return serialized
|
|
189
|
+
.replace(/</g, "\\u003c")
|
|
190
|
+
.replace(/>/g, "\\u003e")
|
|
191
|
+
.replace(/&/g, "\\u0026")
|
|
192
|
+
.replace(/\u2028/g, "\\u2028")
|
|
193
|
+
.replace(/\u2029/g, "\\u2029");
|
|
194
|
+
}
|
|
195
|
+
function safePyString(value) {
|
|
196
|
+
const json = JSON.stringify(String(value)) ?? '""';
|
|
197
|
+
return json
|
|
198
|
+
.replace(/\u2028/g, "\\u2028")
|
|
199
|
+
.replace(/\u2029/g, "\\u2029")
|
|
200
|
+
.replace(/\x7f/g, "\\u007f");
|
|
201
|
+
}
|
|
202
|
+
function safePyLiteral(value) {
|
|
203
|
+
if (value === null || value === undefined)
|
|
204
|
+
return "None";
|
|
205
|
+
if (typeof value === "boolean")
|
|
206
|
+
return value ? "True" : "False";
|
|
207
|
+
if (typeof value === "number")
|
|
208
|
+
return Number.isFinite(value) ? JSON.stringify(value) : "None";
|
|
209
|
+
if (typeof value === "string")
|
|
210
|
+
return safePyString(value);
|
|
211
|
+
if (Array.isArray(value)) {
|
|
212
|
+
return `[${value.map((item) => safePyLiteral(item)).join(", ")}]`;
|
|
213
|
+
}
|
|
214
|
+
if (isRecord(value)) {
|
|
215
|
+
const entries = Object.entries(value)
|
|
216
|
+
.filter(([, v]) => v !== undefined)
|
|
217
|
+
.map(([k, v]) => `${safePyString(k)}: ${safePyLiteral(v)}`);
|
|
218
|
+
return `{${entries.join(", ")}}`;
|
|
219
|
+
}
|
|
220
|
+
return "None";
|
|
221
|
+
}
|
|
222
|
+
function safeShellSingleQuote(value) {
|
|
223
|
+
const clean = String(value).replace(/\0/g, "");
|
|
224
|
+
const escaped = clean.replace(/'/g, "'\\''");
|
|
225
|
+
const quoted = `'${escaped}'`;
|
|
226
|
+
return quoted
|
|
227
|
+
.replace(/\r/g, () => "'$'\\r''")
|
|
228
|
+
.replace(/\n/g, () => "'$'\\n''")
|
|
229
|
+
.replace(/\u2028/g, () => "'$'\\u2028''")
|
|
230
|
+
.replace(/\u2029/g, () => "'$'\\u2029''");
|
|
231
|
+
}
|
|
232
|
+
function toStringArray(value) {
|
|
233
|
+
if (typeof value === "string")
|
|
234
|
+
return [value];
|
|
235
|
+
if (Array.isArray(value))
|
|
236
|
+
return value.filter((item) => typeof item === "string");
|
|
237
|
+
return [];
|
|
238
|
+
}
|
|
239
|
+
function normalizeNumericExpectation(raw) {
|
|
240
|
+
if (typeof raw === "number" && Number.isFinite(raw)) {
|
|
241
|
+
return raw;
|
|
242
|
+
}
|
|
243
|
+
if (Array.isArray(raw)) {
|
|
244
|
+
const nums = raw.filter((item) => typeof item === "number" && Number.isFinite(item));
|
|
245
|
+
return nums.length > 0 ? nums : undefined;
|
|
246
|
+
}
|
|
247
|
+
return undefined;
|
|
248
|
+
}
|
|
249
|
+
function validateContractInput(contract) {
|
|
250
|
+
if (!isRecord(contract)) {
|
|
251
|
+
throw new VibecodeError("CONTRACT_INVALID", "Contract must be a non-null object.");
|
|
252
|
+
}
|
|
253
|
+
if (!Array.isArray(contract.invariants)) {
|
|
254
|
+
throw new VibecodeError("CONTRACT_INVALID", "Contract must contain an invariants array.");
|
|
255
|
+
}
|
|
256
|
+
if (contract.target !== undefined && !isRecord(contract.target)) {
|
|
257
|
+
throw new VibecodeError("CONTRACT_INVALID", "Contract target must be an object when provided.");
|
|
258
|
+
}
|
|
259
|
+
for (let i = 0; i < contract.invariants.length; i++) {
|
|
260
|
+
const inv = contract.invariants[i];
|
|
261
|
+
if (!isRecord(inv) || typeof inv.id !== "string" || typeof inv.type !== "string") {
|
|
262
|
+
throw new VibecodeError("CONTRACT_INVALID", `Contract invariant at index ${i} must be an object with string id and type.`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function resolveDefaultTargetForContract(contract, explicitTarget) {
|
|
267
|
+
const explicit = sanitizeTargetString(explicitTarget);
|
|
268
|
+
if (explicit)
|
|
269
|
+
return explicit;
|
|
270
|
+
const sources = Array.isArray(contract.target?.sources) ? contract.target.sources : [];
|
|
271
|
+
for (const src of sources) {
|
|
272
|
+
if (isRecord(src) && typeof src.ref === "string") {
|
|
273
|
+
const clean = sanitizeTargetString(src.ref);
|
|
274
|
+
if (clean)
|
|
275
|
+
return clean;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return "";
|
|
279
|
+
}
|
|
280
|
+
function resolveInvariantDefaultTarget(contract, inv, explicitTarget) {
|
|
281
|
+
const explicit = sanitizeTargetString(explicitTarget);
|
|
282
|
+
if (explicit)
|
|
283
|
+
return explicit;
|
|
284
|
+
const sources = Array.isArray(contract.target?.sources) ? contract.target.sources : [];
|
|
285
|
+
const kindMatches = (kind) => {
|
|
286
|
+
const k = kind.toLowerCase();
|
|
287
|
+
if (inv.type === "command")
|
|
288
|
+
return k === "cli" || k === "command" || k === "script";
|
|
289
|
+
if (inv.type === "http")
|
|
290
|
+
return k === "api" || k === "http" || k === "web";
|
|
291
|
+
if (inv.type === "web_route")
|
|
292
|
+
return k === "web" || k === "url" || k === "api" || k === "http";
|
|
293
|
+
if (inv.type === "repo_exports")
|
|
294
|
+
return k === "repo";
|
|
295
|
+
return k === inv.domain;
|
|
296
|
+
};
|
|
297
|
+
if (inv.sourceId) {
|
|
298
|
+
const byId = sources.find((s) => isRecord(s) && s.id === inv.sourceId);
|
|
299
|
+
if (byId && typeof byId.ref === "string") {
|
|
300
|
+
const clean = sanitizeTargetString(byId.ref);
|
|
301
|
+
if (clean)
|
|
302
|
+
return clean;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const byKind = sources.find((s) => isRecord(s) && typeof s.kind === "string" && kindMatches(s.kind));
|
|
306
|
+
if (byKind && typeof byKind.ref === "string") {
|
|
307
|
+
const clean = sanitizeTargetString(byKind.ref);
|
|
308
|
+
if (clean)
|
|
309
|
+
return clean;
|
|
310
|
+
}
|
|
311
|
+
return resolveDefaultTargetForContract(contract, explicitTarget);
|
|
312
|
+
}
|
|
313
|
+
function prepareInvariant(contract, inv, explicitTarget) {
|
|
314
|
+
if (!EXPORTABLE_TYPES.has(inv.type))
|
|
315
|
+
return null;
|
|
316
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
317
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
318
|
+
const defaultTarget = resolveInvariantDefaultTarget(contract, inv, explicitTarget);
|
|
319
|
+
const safeId = sanitizeFreeText(inv.id);
|
|
320
|
+
const safeDesc = sanitizeFreeText(inv.description || inv.id);
|
|
321
|
+
if (inv.type === "command") {
|
|
322
|
+
const rawCwd = typeof input.cwd === "string" ? input.cwd.trim() : "";
|
|
323
|
+
const safeCwd = rawCwd && rawCwd !== "." && !/\.vibecode-vault/i.test(rawCwd) ? sanitizeFreeText(rawCwd) : null;
|
|
324
|
+
const args = Array.isArray(input.args) ? input.args.map((a) => sanitizeFreeText(String(a))) : [];
|
|
325
|
+
const normalize = Array.isArray(expected.normalize)
|
|
326
|
+
? expected.normalize.filter((m) => typeof m === "string")
|
|
327
|
+
: [];
|
|
328
|
+
const jsonPaths = Array.isArray(expected.jsonPaths)
|
|
329
|
+
? expected.jsonPaths
|
|
330
|
+
.filter((jp) => isRecord(jp) && typeof jp.path === "string")
|
|
331
|
+
.map((jp) => ({
|
|
332
|
+
path: jp.path,
|
|
333
|
+
...(Object.prototype.hasOwnProperty.call(jp, "equals") ? { equals: sanitizeDeepValue(jp.equals) } : {}),
|
|
334
|
+
...(typeof jp.matches === "string" ? { matches: sanitizeFreeText(jp.matches) } : {})
|
|
335
|
+
}))
|
|
336
|
+
: [];
|
|
337
|
+
const exitCode = normalizeNumericExpectation(expected.exitCode);
|
|
338
|
+
return {
|
|
339
|
+
id: safeId,
|
|
340
|
+
description: safeDesc,
|
|
341
|
+
type: "command",
|
|
342
|
+
defaultTarget,
|
|
343
|
+
args,
|
|
344
|
+
stdin: input.stdin !== undefined && input.stdin !== null ? sanitizeFreeText(String(input.stdin)) : null,
|
|
345
|
+
env: sanitizeEnvRecord(input.env),
|
|
346
|
+
cwd: safeCwd,
|
|
347
|
+
timeoutMs: typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
348
|
+
? input.timeoutMs
|
|
349
|
+
: 10000,
|
|
350
|
+
normalize,
|
|
351
|
+
...(exitCode !== undefined ? { exitCode } : {}),
|
|
352
|
+
...(expected.stdoutExact !== undefined && expected.stdoutExact !== null
|
|
353
|
+
? { stdoutExact: sanitizeFreeText(String(expected.stdoutExact)) }
|
|
354
|
+
: {}),
|
|
355
|
+
stdoutContains: toStringArray(expected.stdoutContains).map(sanitizeFreeText),
|
|
356
|
+
stdoutNotContains: toStringArray(expected.stdoutNotContains).map(sanitizeFreeText),
|
|
357
|
+
stdoutRegex: toStringArray(expected.stdoutRegex).map(sanitizeFreeText),
|
|
358
|
+
...(expected.stderrExact !== undefined && expected.stderrExact !== null
|
|
359
|
+
? { stderrExact: sanitizeFreeText(String(expected.stderrExact)) }
|
|
360
|
+
: {}),
|
|
361
|
+
stderrContains: toStringArray(expected.stderrContains).map(sanitizeFreeText),
|
|
362
|
+
...(expected.goldenStdout !== undefined && expected.goldenStdout !== null
|
|
363
|
+
? { goldenStdout: sanitizeFreeText(String(expected.goldenStdout)) }
|
|
364
|
+
: {}),
|
|
365
|
+
...(expected.jsonSchema ? { jsonSchema: sanitizeDeepValue(expected.jsonSchema) } : {}),
|
|
366
|
+
...(expected.jsonSubset !== undefined ? { jsonSubset: sanitizeDeepValue(expected.jsonSubset) } : {}),
|
|
367
|
+
jsonPaths
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
if (inv.type === "http") {
|
|
371
|
+
const reqHeaders = sanitizeHeaders(input.headers);
|
|
372
|
+
const expHeaders = sanitizeHeaders(expected.headers);
|
|
373
|
+
const jsonPaths = Array.isArray(expected.jsonPaths)
|
|
374
|
+
? expected.jsonPaths
|
|
375
|
+
.filter((jp) => isRecord(jp) && typeof jp.path === "string")
|
|
376
|
+
.map((jp) => ({
|
|
377
|
+
path: jp.path,
|
|
378
|
+
...(Object.prototype.hasOwnProperty.call(jp, "equals") ? { equals: sanitizeDeepValue(jp.equals) } : {}),
|
|
379
|
+
...(typeof jp.matches === "string" ? { matches: sanitizeFreeText(jp.matches) } : {})
|
|
380
|
+
}))
|
|
381
|
+
: [];
|
|
382
|
+
const status = normalizeNumericExpectation(expected.status);
|
|
383
|
+
const hasBody = input.body !== undefined && input.body !== null;
|
|
384
|
+
return {
|
|
385
|
+
id: safeId,
|
|
386
|
+
description: safeDesc,
|
|
387
|
+
type: "http",
|
|
388
|
+
defaultTarget,
|
|
389
|
+
method: typeof input.method === "string" && input.method.trim() ? input.method.trim().toUpperCase() : "GET",
|
|
390
|
+
path: sanitizePathWithQuery(typeof input.path === "string" ? input.path : "/"),
|
|
391
|
+
query: sanitizeQueryRecord(input.query),
|
|
392
|
+
headers: reqHeaders.headers,
|
|
393
|
+
hadSensitiveHeaders: reqHeaders.hadSensitiveHeaders,
|
|
394
|
+
body: hasBody ? sanitizeDeepValue(input.body) : null,
|
|
395
|
+
hasBody,
|
|
396
|
+
timeoutMs: typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
397
|
+
? input.timeoutMs
|
|
398
|
+
: 10000,
|
|
399
|
+
...(status !== undefined ? { status } : {}),
|
|
400
|
+
...(typeof expected.maxLatencyMs === "number" && Number.isFinite(expected.maxLatencyMs)
|
|
401
|
+
? { maxLatencyMs: expected.maxLatencyMs }
|
|
402
|
+
: {}),
|
|
403
|
+
expectedHeaders: expHeaders.headers,
|
|
404
|
+
...(expected.bodyExact !== undefined ? { bodyExact: sanitizeFreeText(String(expected.bodyExact)) } : {}),
|
|
405
|
+
bodyContains: toStringArray(expected.bodyContains).map(sanitizeFreeText),
|
|
406
|
+
...(expected.jsonSchema ? { jsonSchema: sanitizeDeepValue(expected.jsonSchema) } : {}),
|
|
407
|
+
...(expected.jsonSubset !== undefined ? { jsonSubset: sanitizeDeepValue(expected.jsonSubset) } : {}),
|
|
408
|
+
jsonPaths
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
if (inv.type === "web_route") {
|
|
412
|
+
const reqHeaders = sanitizeHeaders(input.headers);
|
|
413
|
+
const rawRoute = typeof input.urlPath === "string" && input.urlPath.trim()
|
|
414
|
+
? input.urlPath
|
|
415
|
+
: (typeof input.path === "string" && input.path.trim() ? input.path : "/");
|
|
416
|
+
const landmarks = Array.isArray(expected.landmarks)
|
|
417
|
+
? expected.landmarks
|
|
418
|
+
.filter((lm) => isRecord(lm) && typeof lm.tag === "string" && lm.tag.trim().length > 0)
|
|
419
|
+
.map((lm) => ({
|
|
420
|
+
tag: lm.tag.trim(),
|
|
421
|
+
...(lm.required !== undefined ? { required: Boolean(lm.required) } : {}),
|
|
422
|
+
...(typeof lm.textContains === "string" ? { textContains: sanitizeFreeText(lm.textContains) } : {})
|
|
423
|
+
}))
|
|
424
|
+
: [];
|
|
425
|
+
const status = normalizeNumericExpectation(expected.status);
|
|
426
|
+
return {
|
|
427
|
+
id: safeId,
|
|
428
|
+
description: safeDesc,
|
|
429
|
+
type: "web_route",
|
|
430
|
+
defaultTarget,
|
|
431
|
+
routePath: sanitizePathWithQuery(rawRoute),
|
|
432
|
+
headers: reqHeaders.headers,
|
|
433
|
+
hadSensitiveHeaders: reqHeaders.hadSensitiveHeaders,
|
|
434
|
+
timeoutMs: typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
435
|
+
? input.timeoutMs
|
|
436
|
+
: 15000,
|
|
437
|
+
...(status !== undefined ? { status } : {}),
|
|
438
|
+
...(typeof expected.titleContains === "string" && expected.titleContains.length > 0
|
|
439
|
+
? { titleContains: sanitizeFreeText(expected.titleContains) }
|
|
440
|
+
: {}),
|
|
441
|
+
bodyContains: toStringArray(expected.bodyContains).map(sanitizeFreeText),
|
|
442
|
+
landmarks
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
// repo_exports
|
|
446
|
+
const filesPresent = Array.isArray(expected.filesPresent)
|
|
447
|
+
? expected.filesPresent
|
|
448
|
+
.filter((f) => typeof f === "string" && f.trim().length > 0 && !/\.vibecode-vault/i.test(f))
|
|
449
|
+
.map((f) => f.trim())
|
|
450
|
+
: [];
|
|
451
|
+
const rawModulePath = typeof input.modulePath === "string" && input.modulePath.trim()
|
|
452
|
+
? input.modulePath.trim()
|
|
453
|
+
: (filesPresent[0] || null);
|
|
454
|
+
const modulePath = rawModulePath && !/\.vibecode-vault/i.test(rawModulePath) ? rawModulePath : null;
|
|
455
|
+
const exportsList = Array.isArray(expected.exports)
|
|
456
|
+
? expected.exports
|
|
457
|
+
.filter((e) => isRecord(e) && typeof e.name === "string" && e.name.trim().length > 0)
|
|
458
|
+
.map((e) => ({ name: sanitizeFreeText(e.name.trim()), kind: typeof e.kind === "string" ? e.kind : "unknown" }))
|
|
459
|
+
: [];
|
|
460
|
+
return {
|
|
461
|
+
id: safeId,
|
|
462
|
+
description: safeDesc,
|
|
463
|
+
type: "repo_exports",
|
|
464
|
+
defaultTarget,
|
|
465
|
+
filesPresent,
|
|
466
|
+
modulePath,
|
|
467
|
+
exports: exportsList
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
function buildHeaderLines(commentPrefix, contract, options, skippedIds, includeSkippedComments) {
|
|
471
|
+
const lines = [];
|
|
472
|
+
const name = sanitizeComment(contract.target?.name || "contract");
|
|
473
|
+
lines.push(`${commentPrefix} Standalone regression test suite generated from contract "${name}".`);
|
|
474
|
+
lines.push(`${commentPrefix} Zero runtime dependency on vibecode-anything.`);
|
|
475
|
+
if (typeof options.contractPath === "string" && options.contractPath.trim() && !/\.vibecode-vault/i.test(options.contractPath)) {
|
|
476
|
+
lines.push(`${commentPrefix} Source contract: ${sanitizeComment(options.contractPath)}`);
|
|
477
|
+
}
|
|
478
|
+
lines.push(`${commentPrefix} Override target via VIBECODE_TARGET (or per-domain VIBECODE_CLI_TARGET / VIBECODE_API_TARGET / VIBECODE_WEB_TARGET / VIBECODE_REPO_TARGET).`);
|
|
479
|
+
if (includeSkippedComments && skippedIds.length > 0) {
|
|
480
|
+
const safeSkipped = skippedIds.map((id) => sanitizeComment(id, 64)).join(", ");
|
|
481
|
+
lines.push(`${commentPrefix} Skipped ${skippedIds.length} unsupported invariant(s): ${safeSkipped}`);
|
|
482
|
+
lines.push(`${commentPrefix} Run "vibecode-anything verify" for visual/video/browser-flow invariants.`);
|
|
483
|
+
}
|
|
484
|
+
return lines;
|
|
485
|
+
}
|
|
486
|
+
function emitJsSharedHelpers(lines, typesUsed, anySensitiveHeaders, isTs) {
|
|
487
|
+
const t = isTs;
|
|
488
|
+
lines.push(t
|
|
489
|
+
? "function resolveTarget(kind: string, fallback: string): string {"
|
|
490
|
+
: "function resolveTarget(kind, fallback) {");
|
|
491
|
+
lines.push(" const envByKind = {");
|
|
492
|
+
lines.push(' command: process.env.VIBECODE_CLI_TARGET,');
|
|
493
|
+
lines.push(' http: process.env.VIBECODE_API_TARGET || process.env.VIBECODE_HTTP_TARGET,');
|
|
494
|
+
lines.push(' web_route: process.env.VIBECODE_WEB_TARGET || process.env.VIBECODE_API_TARGET || process.env.VIBECODE_HTTP_TARGET,');
|
|
495
|
+
lines.push(' repo_exports: process.env.VIBECODE_REPO_TARGET');
|
|
496
|
+
lines.push(" };");
|
|
497
|
+
lines.push(t ? " const specific = envByKind[kind as keyof typeof envByKind];" : " const specific = envByKind[kind];");
|
|
498
|
+
lines.push(" if (specific && specific.trim()) return specific.trim();");
|
|
499
|
+
lines.push(" const raw = process.env.VIBECODE_TARGET;");
|
|
500
|
+
lines.push(" if (raw && raw.trim()) {");
|
|
501
|
+
lines.push(' const trimmed = raw.trim();');
|
|
502
|
+
lines.push(' if (trimmed.startsWith("{")) {');
|
|
503
|
+
lines.push(" try {");
|
|
504
|
+
lines.push(t ? " const parsed = JSON.parse(trimmed) as Record<string, unknown>;" : " const parsed = JSON.parse(trimmed);");
|
|
505
|
+
lines.push(" if (parsed && typeof parsed === \"object\") {");
|
|
506
|
+
lines.push(" const aliases = {");
|
|
507
|
+
lines.push(' command: ["command", "cli", "default"],');
|
|
508
|
+
lines.push(' http: ["http", "api", "default"],');
|
|
509
|
+
lines.push(' web_route: ["web_route", "web", "http", "api", "default"],');
|
|
510
|
+
lines.push(' repo_exports: ["repo_exports", "repo", "default"]');
|
|
511
|
+
lines.push(" };");
|
|
512
|
+
lines.push(t ? " for (const key of aliases[kind as keyof typeof aliases] || []) {" : " for (const key of aliases[kind] || []) {");
|
|
513
|
+
lines.push(' const candidate = parsed[key];');
|
|
514
|
+
lines.push(' if (typeof candidate === "string" && candidate.trim()) return candidate.trim();');
|
|
515
|
+
lines.push(" }");
|
|
516
|
+
lines.push(" }");
|
|
517
|
+
lines.push(" } catch { /* treat as plain string target */ }");
|
|
518
|
+
lines.push(" }");
|
|
519
|
+
lines.push(" return trimmed;");
|
|
520
|
+
lines.push(" }");
|
|
521
|
+
lines.push(" return fallback || DEFAULT_TARGET;");
|
|
522
|
+
lines.push("}");
|
|
523
|
+
lines.push("");
|
|
524
|
+
if (anySensitiveHeaders) {
|
|
525
|
+
lines.push(t
|
|
526
|
+
? "function applyOptionalAuthHeader(headers: Record<string, string>): Record<string, string> {"
|
|
527
|
+
: "function applyOptionalAuthHeader(headers) {");
|
|
528
|
+
lines.push(" const raw = process.env.VIBECODE_AUTH_HEADER;");
|
|
529
|
+
lines.push(" if (!raw || !raw.trim()) return { ...headers };");
|
|
530
|
+
lines.push(' const idx = raw.indexOf(":");');
|
|
531
|
+
lines.push(" if (idx > 0) {");
|
|
532
|
+
lines.push(" const name = raw.slice(0, idx).trim();");
|
|
533
|
+
lines.push(" const value = raw.slice(idx + 1).trim();");
|
|
534
|
+
lines.push(" if (name) return { ...headers, [name]: value };");
|
|
535
|
+
lines.push(" }");
|
|
536
|
+
lines.push(" return { ...headers, Authorization: raw.trim() };");
|
|
537
|
+
lines.push("}");
|
|
538
|
+
lines.push("");
|
|
539
|
+
}
|
|
540
|
+
if (typesUsed.has("command")) {
|
|
541
|
+
lines.push(t ? "function splitCommand(cmdString: string): string[] {" : "function splitCommand(cmdString) {");
|
|
542
|
+
lines.push(" const s = String(cmdString ?? \"\");");
|
|
543
|
+
lines.push(t ? " const args: string[] = [];" : " const args = [];");
|
|
544
|
+
lines.push(' let cur = "";');
|
|
545
|
+
lines.push(" let hasToken = false;");
|
|
546
|
+
lines.push(" let inSingle = false;");
|
|
547
|
+
lines.push(" let inDouble = false;");
|
|
548
|
+
lines.push(" for (let i = 0; i < s.length; i++) {");
|
|
549
|
+
lines.push(" const ch = s[i];");
|
|
550
|
+
lines.push(" if (inSingle) {");
|
|
551
|
+
lines.push(' if (ch === "\'") inSingle = false;');
|
|
552
|
+
lines.push(" else cur += ch;");
|
|
553
|
+
lines.push(" } else if (inDouble) {");
|
|
554
|
+
lines.push(' if (ch === \'"\') inDouble = false;');
|
|
555
|
+
lines.push(' else if (ch === "\\\\" && i + 1 < s.length && s[i + 1] === \'"\') { cur += \'"\'; i++; }');
|
|
556
|
+
lines.push(" else cur += ch;");
|
|
557
|
+
lines.push(" } else {");
|
|
558
|
+
lines.push(' if (ch === "\'") { inSingle = true; hasToken = true; }');
|
|
559
|
+
lines.push(' else if (ch === \'"\') { inDouble = true; hasToken = true; }');
|
|
560
|
+
lines.push(" else if (/\\s/.test(ch)) {");
|
|
561
|
+
lines.push(' if (hasToken) { args.push(cur); cur = ""; hasToken = false; }');
|
|
562
|
+
lines.push(" } else {");
|
|
563
|
+
lines.push(" cur += ch;");
|
|
564
|
+
lines.push(" hasToken = true;");
|
|
565
|
+
lines.push(" }");
|
|
566
|
+
lines.push(" }");
|
|
567
|
+
lines.push(" }");
|
|
568
|
+
lines.push(" if (hasToken) args.push(cur);");
|
|
569
|
+
lines.push(" return args;");
|
|
570
|
+
lines.push("}");
|
|
571
|
+
lines.push("");
|
|
572
|
+
lines.push(t ? "function quoteWinCmdArg(arg: string): string {" : "function quoteWinCmdArg(arg) {");
|
|
573
|
+
lines.push(' if (arg.length === 0) return \'""\';');
|
|
574
|
+
lines.push(' if (!/[\\s"&|<>^(),;=%!]/.test(arg)) return arg;');
|
|
575
|
+
lines.push(' const escaped = arg.replace(/(\\\\*)\\"/g, \'$1$1\\\\"\').replace(/(\\\\+)$/, "$1$1");');
|
|
576
|
+
lines.push(' return \'"\' + escaped + \'"\';');
|
|
577
|
+
lines.push("}");
|
|
578
|
+
lines.push("");
|
|
579
|
+
lines.push(t
|
|
580
|
+
? "function runCommand(targetCmd: string, extraArgs: string[], opts: { stdin: string | null; env: Record<string, string>; cwd: string | null; timeoutMs: number }) {"
|
|
581
|
+
: "function runCommand(targetCmd, extraArgs, opts) {");
|
|
582
|
+
lines.push(" const tokens = splitCommand(targetCmd);");
|
|
583
|
+
lines.push(' if (tokens.length === 0) throw new Error("Empty command target");');
|
|
584
|
+
lines.push(" const [bin, ...baseArgs] = tokens;");
|
|
585
|
+
lines.push(" const allArgs = [...baseArgs, ...extraArgs];");
|
|
586
|
+
lines.push(' const isWinCmd = process.platform === "win32" && /\\.(cmd|bat)$/i.test(bin);');
|
|
587
|
+
lines.push(" const spawnOpts = {");
|
|
588
|
+
lines.push(' encoding: "utf8" as const,');
|
|
589
|
+
lines.push(" timeout: opts.timeoutMs,");
|
|
590
|
+
lines.push(" windowsHide: true,");
|
|
591
|
+
lines.push(" maxBuffer: 10 * 1024 * 1024,");
|
|
592
|
+
lines.push(" env: { ...process.env, ...opts.env },");
|
|
593
|
+
lines.push(" ...(opts.cwd ? { cwd: path.resolve(opts.cwd) } : {}),");
|
|
594
|
+
lines.push(" ...(opts.stdin !== null ? { input: opts.stdin } : {}),");
|
|
595
|
+
lines.push(" ...(isWinCmd ? { windowsVerbatimArguments: true } : {})");
|
|
596
|
+
lines.push(" };");
|
|
597
|
+
if (!t) {
|
|
598
|
+
// Remove `as const` for plain JS
|
|
599
|
+
lines[lines.length - 9] = ' encoding: "utf8",';
|
|
600
|
+
}
|
|
601
|
+
lines.push(" if (isWinCmd) {");
|
|
602
|
+
lines.push(' const cmdLine = [quoteWinCmdArg(bin), ...allArgs.map(quoteWinCmdArg)].join(" ");');
|
|
603
|
+
lines.push(' return spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", \'"\' + cmdLine + \'"\'], spawnOpts);');
|
|
604
|
+
lines.push(" }");
|
|
605
|
+
lines.push(" return spawnSync(bin, allArgs, spawnOpts);");
|
|
606
|
+
lines.push("}");
|
|
607
|
+
lines.push("");
|
|
608
|
+
lines.push(t ? "function normalizeText(text: string, modes: string[]): string {" : "function normalizeText(text, modes) {");
|
|
609
|
+
lines.push(' let out = text == null ? "" : String(text);');
|
|
610
|
+
lines.push(" for (const mode of modes) {");
|
|
611
|
+
lines.push(' if (mode === "crlf") out = out.replace(/\\r\\n/g, "\\n");');
|
|
612
|
+
lines.push(' else if (mode === "ansi") out = out.replace(/\\x1B\\[[0-?]*[ -/]*[@-~]/g, "");');
|
|
613
|
+
lines.push(' else if (mode === "timestamps") {');
|
|
614
|
+
lines.push(' out = out.replace(/\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?/g, "<TS>");');
|
|
615
|
+
lines.push(' out = out.replace(/\\b\\d{13}\\b/g, "<TS_MS>");');
|
|
616
|
+
lines.push(" } else if (mode === \"paths\") {");
|
|
617
|
+
lines.push(' out = out.replace(/[A-Za-z]:\\\\[^\\s"\']+/g, (m) => m.replace(/\\\\/g, "/"));');
|
|
618
|
+
lines.push(' } else if (mode === "trim") out = out.trim();');
|
|
619
|
+
lines.push(" }");
|
|
620
|
+
lines.push(" return out;");
|
|
621
|
+
lines.push("}");
|
|
622
|
+
lines.push("");
|
|
623
|
+
lines.push(t ? "function normalizeGolden(text: string): string {" : "function normalizeGolden(text) {");
|
|
624
|
+
lines.push(' return String(text ?? "").replace(/\\r\\n/g, "\\n").replace(/\\n$/, "");');
|
|
625
|
+
lines.push("}");
|
|
626
|
+
lines.push("");
|
|
627
|
+
}
|
|
628
|
+
if (typesUsed.has("command") || typesUsed.has("http")) {
|
|
629
|
+
lines.push(t
|
|
630
|
+
? "function diffJsonSubset(expected: unknown, actual: unknown, currentPath = \"$\"): string[] {"
|
|
631
|
+
: "function diffJsonSubset(expected, actual, currentPath = \"$\") {");
|
|
632
|
+
lines.push(t ? " const diffs: string[] = [];" : " const diffs = [];");
|
|
633
|
+
lines.push(" if (Array.isArray(expected)) {");
|
|
634
|
+
lines.push(" if (!Array.isArray(actual)) {");
|
|
635
|
+
lines.push(" diffs.push(currentPath + \": expected array, got \" + typeof actual);");
|
|
636
|
+
lines.push(" return diffs;");
|
|
637
|
+
lines.push(" }");
|
|
638
|
+
lines.push(" for (let i = 0; i < expected.length; i++) {");
|
|
639
|
+
lines.push(" if (i >= actual.length) diffs.push(currentPath + \"[\" + i + \"]: missing element\");");
|
|
640
|
+
lines.push(" else diffs.push(...diffJsonSubset(expected[i], actual[i], currentPath + \"[\" + i + \"]\"));");
|
|
641
|
+
lines.push(" }");
|
|
642
|
+
lines.push(" return diffs;");
|
|
643
|
+
lines.push(" }");
|
|
644
|
+
lines.push(' if (expected && typeof expected === "object") {');
|
|
645
|
+
lines.push(' if (!actual || typeof actual !== "object" || Array.isArray(actual)) {');
|
|
646
|
+
lines.push(" diffs.push(currentPath + \": expected object, got \" + JSON.stringify(actual));");
|
|
647
|
+
lines.push(" return diffs;");
|
|
648
|
+
lines.push(" }");
|
|
649
|
+
lines.push(t ? " const expObj = expected as Record<string, unknown>;" : " const expObj = expected;");
|
|
650
|
+
lines.push(t ? " const actObj = actual as Record<string, unknown>;" : " const actObj = actual;");
|
|
651
|
+
lines.push(" for (const k of Object.keys(expObj)) {");
|
|
652
|
+
lines.push(" if (!(k in actObj)) diffs.push(currentPath + \".\" + k + \": missing key\");");
|
|
653
|
+
lines.push(" else diffs.push(...diffJsonSubset(expObj[k], actObj[k], currentPath + \".\" + k));");
|
|
654
|
+
lines.push(" }");
|
|
655
|
+
lines.push(" return diffs;");
|
|
656
|
+
lines.push(" }");
|
|
657
|
+
lines.push(" if (expected !== actual) {");
|
|
658
|
+
lines.push(' diffs.push(currentPath + ": expected " + JSON.stringify(expected) + ", got " + JSON.stringify(actual));');
|
|
659
|
+
lines.push(" }");
|
|
660
|
+
lines.push(" return diffs;");
|
|
661
|
+
lines.push("}");
|
|
662
|
+
lines.push("");
|
|
663
|
+
lines.push(t
|
|
664
|
+
? "function queryJsonPath(obj: unknown, expr: string): { found: boolean; value: unknown } {"
|
|
665
|
+
: "function queryJsonPath(obj, expr) {");
|
|
666
|
+
lines.push(' if (typeof expr !== "string" || !expr.startsWith("$")) return { found: false, value: undefined };');
|
|
667
|
+
lines.push(" let cur = obj;");
|
|
668
|
+
lines.push(t ? " const tokens: Array<string | number> = [];" : " const tokens = [];");
|
|
669
|
+
lines.push(' const re = /\\.([A-Za-z_$][A-Za-z0-9_$-]*)|\\[(\\d+)\\]|\\[(?:"([^"]*)"|\'([^\']*)\')\\]/g;');
|
|
670
|
+
lines.push(" let i = 1;");
|
|
671
|
+
lines.push(" while (i < expr.length) {");
|
|
672
|
+
lines.push(" re.lastIndex = i;");
|
|
673
|
+
lines.push(" const m = re.exec(expr);");
|
|
674
|
+
lines.push(" if (!m || m.index !== i) return { found: false, value: undefined };");
|
|
675
|
+
lines.push(" if (m[1] !== undefined) tokens.push(m[1]);");
|
|
676
|
+
lines.push(" else if (m[2] !== undefined) tokens.push(Number(m[2]));");
|
|
677
|
+
lines.push(" else if (m[3] !== undefined) tokens.push(m[3]);");
|
|
678
|
+
lines.push(" else if (m[4] !== undefined) tokens.push(m[4]);");
|
|
679
|
+
lines.push(" i = re.lastIndex;");
|
|
680
|
+
lines.push(" }");
|
|
681
|
+
lines.push(" for (const tok of tokens) {");
|
|
682
|
+
lines.push(" if (cur === null || cur === undefined) return { found: false, value: undefined };");
|
|
683
|
+
lines.push(' if (typeof tok === "number") {');
|
|
684
|
+
lines.push(" if (!Array.isArray(cur) || tok < 0 || tok >= cur.length) return { found: false, value: undefined };");
|
|
685
|
+
lines.push(" cur = cur[tok];");
|
|
686
|
+
lines.push(" } else {");
|
|
687
|
+
lines.push(' if (typeof cur !== "object" || !(tok in cur)) return { found: false, value: undefined };');
|
|
688
|
+
lines.push(t ? " cur = (cur as Record<string, unknown>)[tok];" : " cur = cur[tok];");
|
|
689
|
+
lines.push(" }");
|
|
690
|
+
lines.push(" }");
|
|
691
|
+
lines.push(" return { found: true, value: cur };");
|
|
692
|
+
lines.push("}");
|
|
693
|
+
lines.push("");
|
|
694
|
+
lines.push(t
|
|
695
|
+
? "function validateJsonSchema(value: unknown, schema: Record<string, unknown>, currentPath = \"$\"): string[] {"
|
|
696
|
+
: "function validateJsonSchema(value, schema, currentPath = \"$\") {");
|
|
697
|
+
lines.push(t ? " const errors: string[] = [];" : " const errors = [];");
|
|
698
|
+
lines.push(' if (!schema || typeof schema !== "object") return errors;');
|
|
699
|
+
lines.push(" if (schema.nullable === true && value === null) return errors;");
|
|
700
|
+
lines.push(" if (schema.type !== undefined) {");
|
|
701
|
+
lines.push(" const types = Array.isArray(schema.type) ? schema.type : [schema.type];");
|
|
702
|
+
lines.push(t ? " const matches = (typ: unknown): boolean => {" : " const matches = (typ) => {");
|
|
703
|
+
lines.push(' if (typ === "null") return value === null;');
|
|
704
|
+
lines.push(' if (typ === "array") return Array.isArray(value);');
|
|
705
|
+
lines.push(' if (typ === "object") return value !== null && typeof value === "object" && !Array.isArray(value);');
|
|
706
|
+
lines.push(' if (typ === "integer") return typeof value === "number" && Number.isInteger(value);');
|
|
707
|
+
lines.push(' if (typ === "number") return typeof value === "number" && Number.isFinite(value);');
|
|
708
|
+
lines.push(' if (typ === "string") return typeof value === "string";');
|
|
709
|
+
lines.push(' if (typ === "boolean") return typeof value === "boolean";');
|
|
710
|
+
lines.push(" return true;");
|
|
711
|
+
lines.push(" };");
|
|
712
|
+
lines.push(" if (!types.some(matches)) errors.push(currentPath + \": expected type \" + JSON.stringify(schema.type));");
|
|
713
|
+
lines.push(" }");
|
|
714
|
+
lines.push(' if (Object.prototype.hasOwnProperty.call(schema, "const") && JSON.stringify(value) !== JSON.stringify(schema.const)) {');
|
|
715
|
+
lines.push(' errors.push(currentPath + ": expected const " + JSON.stringify(schema.const));');
|
|
716
|
+
lines.push(" }");
|
|
717
|
+
lines.push(" if (Array.isArray(schema.enum) && !schema.enum.some((e) => JSON.stringify(e) === JSON.stringify(value))) {");
|
|
718
|
+
lines.push(' errors.push(currentPath + ": value not in enum");');
|
|
719
|
+
lines.push(" }");
|
|
720
|
+
lines.push(' if (typeof value === "string") {');
|
|
721
|
+
lines.push(' if (typeof schema.minLength === "number" && value.length < schema.minLength) errors.push(currentPath + ": string too short");');
|
|
722
|
+
lines.push(' if (typeof schema.maxLength === "number" && value.length > schema.maxLength) errors.push(currentPath + ": string too long");');
|
|
723
|
+
lines.push(' if (typeof schema.pattern === "string" && !new RegExp(schema.pattern).test(value)) errors.push(currentPath + ": pattern mismatch");');
|
|
724
|
+
lines.push(" }");
|
|
725
|
+
lines.push(' if (typeof value === "number") {');
|
|
726
|
+
lines.push(' if (typeof schema.minimum === "number" && value < schema.minimum) errors.push(currentPath + ": below minimum");');
|
|
727
|
+
lines.push(' if (typeof schema.maximum === "number" && value > schema.maximum) errors.push(currentPath + ": above maximum");');
|
|
728
|
+
lines.push(" }");
|
|
729
|
+
lines.push(" if (Array.isArray(value)) {");
|
|
730
|
+
lines.push(' if (typeof schema.minItems === "number" && value.length < schema.minItems) errors.push(currentPath + ": too few items");');
|
|
731
|
+
lines.push(' if (typeof schema.maxItems === "number" && value.length > schema.maxItems) errors.push(currentPath + ": too many items");');
|
|
732
|
+
lines.push(' if (schema.items && typeof schema.items === "object" && !Array.isArray(schema.items)) {');
|
|
733
|
+
lines.push(" for (let i = 0; i < value.length; i++) {");
|
|
734
|
+
lines.push(t
|
|
735
|
+
? " errors.push(...validateJsonSchema(value[i], schema.items as Record<string, unknown>, currentPath + \"[\" + i + \"]\"));"
|
|
736
|
+
: " errors.push(...validateJsonSchema(value[i], schema.items, currentPath + \"[\" + i + \"]\"));");
|
|
737
|
+
lines.push(" }");
|
|
738
|
+
lines.push(" }");
|
|
739
|
+
lines.push(" }");
|
|
740
|
+
lines.push(' if (value !== null && typeof value === "object" && !Array.isArray(value)) {');
|
|
741
|
+
lines.push(t ? " const rec = value as Record<string, unknown>;" : " const rec = value;");
|
|
742
|
+
lines.push(" if (Array.isArray(schema.required)) {");
|
|
743
|
+
lines.push(" for (const reqKey of schema.required) {");
|
|
744
|
+
lines.push(' if (typeof reqKey === "string" && !(reqKey in rec)) errors.push(currentPath + "." + reqKey + ": missing required property");');
|
|
745
|
+
lines.push(" }");
|
|
746
|
+
lines.push(" }");
|
|
747
|
+
lines.push(' if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {');
|
|
748
|
+
lines.push(t
|
|
749
|
+
? " for (const [k, sub] of Object.entries(schema.properties as Record<string, unknown>)) {"
|
|
750
|
+
: " for (const [k, sub] of Object.entries(schema.properties)) {");
|
|
751
|
+
lines.push(' if (k in rec && sub && typeof sub === "object") {');
|
|
752
|
+
lines.push(t
|
|
753
|
+
? ' errors.push(...validateJsonSchema(rec[k], sub as Record<string, unknown>, currentPath + "." + k));'
|
|
754
|
+
: ' errors.push(...validateJsonSchema(rec[k], sub, currentPath + "." + k));');
|
|
755
|
+
lines.push(" }");
|
|
756
|
+
lines.push(" }");
|
|
757
|
+
lines.push(" }");
|
|
758
|
+
lines.push(" }");
|
|
759
|
+
lines.push(" return errors;");
|
|
760
|
+
lines.push("}");
|
|
761
|
+
lines.push("");
|
|
762
|
+
}
|
|
763
|
+
if (typesUsed.has("http") || typesUsed.has("web_route")) {
|
|
764
|
+
lines.push(t
|
|
765
|
+
? "function buildRequestUrl(base: string, routePath: string, query?: Record<string, string>): string {"
|
|
766
|
+
: "function buildRequestUrl(base, routePath, query) {");
|
|
767
|
+
lines.push(' const normalizedBase = /^https?:\\/\\//i.test(base) ? base : "http://" + base;');
|
|
768
|
+
lines.push(' const url = /^https?:\\/\\//i.test(routePath) ? new URL(routePath) : new URL(routePath || "/", normalizedBase);');
|
|
769
|
+
lines.push(" if (query) {");
|
|
770
|
+
lines.push(" for (const [k, v] of Object.entries(query)) {");
|
|
771
|
+
lines.push(" url.searchParams.set(k, String(v));");
|
|
772
|
+
lines.push(" }");
|
|
773
|
+
lines.push(" }");
|
|
774
|
+
lines.push(" return url.toString();");
|
|
775
|
+
lines.push("}");
|
|
776
|
+
lines.push("");
|
|
777
|
+
}
|
|
778
|
+
if (typesUsed.has("web_route")) {
|
|
779
|
+
lines.push(t ? "function stripHtml(html: string): string {" : "function stripHtml(html) {");
|
|
780
|
+
lines.push(" return String(html)");
|
|
781
|
+
lines.push(' .replace(/<script[\\s\\S]*?<\\/script>/gi, " ")');
|
|
782
|
+
lines.push(' .replace(/<style[\\s\\S]*?<\\/style>/gi, " ")');
|
|
783
|
+
lines.push(' .replace(/<[^>]+>/g, " ")');
|
|
784
|
+
lines.push(' .replace(/ /g, " ")');
|
|
785
|
+
lines.push(' .replace(/&/g, "&")');
|
|
786
|
+
lines.push(' .replace(/</g, "<")');
|
|
787
|
+
lines.push(' .replace(/>/g, ">")');
|
|
788
|
+
lines.push(' .replace(/\\s+/g, " ")');
|
|
789
|
+
lines.push(" .trim();");
|
|
790
|
+
lines.push("}");
|
|
791
|
+
lines.push("");
|
|
792
|
+
lines.push(t ? "function extractHtmlTitle(html: string): string {" : "function extractHtmlTitle(html) {");
|
|
793
|
+
lines.push(" const m = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html);");
|
|
794
|
+
lines.push(' return m ? stripHtml(m[1]) : "";');
|
|
795
|
+
lines.push("}");
|
|
796
|
+
lines.push("");
|
|
797
|
+
lines.push(t
|
|
798
|
+
? "function checkHtmlLandmark(html: string, tag: string, textContains?: string): boolean {"
|
|
799
|
+
: "function checkHtmlLandmark(html, tag, textContains) {");
|
|
800
|
+
lines.push(' const safeTag = tag.replace(/[^a-zA-Z0-9_-]/g, "");');
|
|
801
|
+
lines.push(" if (!safeTag) return false;");
|
|
802
|
+
lines.push(' const pairRe = new RegExp("<" + safeTag + "\\\\b[^>]*>([\\\\s\\\\S]*?)<\\\\/" + safeTag + ">", "gi");');
|
|
803
|
+
lines.push(" let matchedAny = false;");
|
|
804
|
+
lines.push(t ? " let m: RegExpExecArray | null;" : " let m;");
|
|
805
|
+
lines.push(" while ((m = pairRe.exec(html)) !== null) {");
|
|
806
|
+
lines.push(" matchedAny = true;");
|
|
807
|
+
lines.push(" if (!textContains) return true;");
|
|
808
|
+
lines.push(" if (stripHtml(m[1]).includes(textContains)) return true;");
|
|
809
|
+
lines.push(" }");
|
|
810
|
+
lines.push(" if (!textContains && !matchedAny) {");
|
|
811
|
+
lines.push(' return new RegExp("<" + safeTag + "\\\\b[^>]*>", "i").test(html);');
|
|
812
|
+
lines.push(" }");
|
|
813
|
+
lines.push(" return false;");
|
|
814
|
+
lines.push("}");
|
|
815
|
+
lines.push("");
|
|
816
|
+
}
|
|
817
|
+
if (typesUsed.has("repo_exports")) {
|
|
818
|
+
lines.push(t ? "function scanExportsRegex(source: string): Set<string> {" : "function scanExportsRegex(source) {");
|
|
819
|
+
lines.push(t ? " const names = new Set<string>();" : " const names = new Set();");
|
|
820
|
+
lines.push(" const declRe = /export\\s+(?:declare\\s+)?(?:async\\s+)?(?:function|class|const|let|var)\\s+([A-Za-z_$][A-Za-z0-9_$]*)/g;");
|
|
821
|
+
lines.push(t ? " let m: RegExpExecArray | null;" : " let m;");
|
|
822
|
+
lines.push(" while ((m = declRe.exec(source)) !== null) names.add(m[1]);");
|
|
823
|
+
lines.push(" const listRe = /export\\s*\\{([^}]+)\\}/g;");
|
|
824
|
+
lines.push(" while ((m = listRe.exec(source)) !== null) {");
|
|
825
|
+
lines.push(' for (const part of m[1].split(",")) {');
|
|
826
|
+
lines.push(' const cleaned = part.replace(/\\btype\\s+/g, "").trim();');
|
|
827
|
+
lines.push(" if (!cleaned) continue;");
|
|
828
|
+
lines.push(" const asMatch = /\\bas\\s+([A-Za-z_$][A-Za-z0-9_$]*)$/.exec(cleaned);");
|
|
829
|
+
lines.push(" if (asMatch) names.add(asMatch[1]);");
|
|
830
|
+
lines.push(" else {");
|
|
831
|
+
lines.push(" const idMatch = /^([A-Za-z_$][A-Za-z0-9_$]*)/.exec(cleaned);");
|
|
832
|
+
lines.push(" if (idMatch) names.add(idMatch[1]);");
|
|
833
|
+
lines.push(" }");
|
|
834
|
+
lines.push(" }");
|
|
835
|
+
lines.push(" }");
|
|
836
|
+
lines.push(' if (/export\\s+default\\b/.test(source)) names.add("default");');
|
|
837
|
+
lines.push(" const cjsRe = /(?:module\\.)?exports\\.([A-Za-z_$][A-Za-z0-9_$]*)\\s*=/g;");
|
|
838
|
+
lines.push(" while ((m = cjsRe.exec(source)) !== null) names.add(m[1]);");
|
|
839
|
+
lines.push(" return names;");
|
|
840
|
+
lines.push("}");
|
|
841
|
+
lines.push("");
|
|
842
|
+
lines.push(t
|
|
843
|
+
? "async function loadModuleExports(absPath: string): Promise<Set<string>> {"
|
|
844
|
+
: "async function loadModuleExports(absPath) {");
|
|
845
|
+
lines.push(t ? " const exported = new Set<string>();" : " const exported = new Set();");
|
|
846
|
+
lines.push(" try {");
|
|
847
|
+
lines.push(" const mod = await import(pathToFileURL(absPath).href);");
|
|
848
|
+
lines.push(" for (const key of Object.keys(mod)) exported.add(key);");
|
|
849
|
+
lines.push(" return exported;");
|
|
850
|
+
lines.push(" } catch {");
|
|
851
|
+
lines.push(' return scanExportsRegex(fs.readFileSync(absPath, "utf8"));');
|
|
852
|
+
lines.push(" }");
|
|
853
|
+
lines.push("}");
|
|
854
|
+
lines.push("");
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
function emitJsTestBody(lines, spec, style) {
|
|
858
|
+
const isVitest = style === "vitest";
|
|
859
|
+
const assertEq = (actualExpr, expectedExpr, msg) => isVitest
|
|
860
|
+
? `expect(${actualExpr}).toBe(${expectedExpr});`
|
|
861
|
+
: msg
|
|
862
|
+
? `assert.equal(${actualExpr}, ${expectedExpr}, ${safeJsonLiteral(msg)});`
|
|
863
|
+
: `assert.equal(${actualExpr}, ${expectedExpr});`;
|
|
864
|
+
const assertTrue = (condExpr, msg) => isVitest
|
|
865
|
+
? `expect(${condExpr}, ${safeJsonLiteral(msg)}).toBe(true);`
|
|
866
|
+
: `assert.ok(${condExpr}, ${safeJsonLiteral(msg)});`;
|
|
867
|
+
const assertDeepEmpty = (arrExpr, label) => isVitest
|
|
868
|
+
? `expect(${arrExpr}, ${safeJsonLiteral(label)}).toEqual([]);`
|
|
869
|
+
: `assert.deepEqual(${arrExpr}, [], ${safeJsonLiteral(label)});`;
|
|
870
|
+
if (spec.type === "command") {
|
|
871
|
+
lines.push(` const target = resolveTarget("command", ${safeJsonLiteral(spec.defaultTarget)});`);
|
|
872
|
+
lines.push(" const run = runCommand(target, " + safeJsonLiteral(spec.args) + ", {");
|
|
873
|
+
lines.push(` stdin: ${safeJsonLiteral(spec.stdin)},`);
|
|
874
|
+
lines.push(` env: ${safeJsonLiteral(spec.env)},`);
|
|
875
|
+
lines.push(` cwd: ${safeJsonLiteral(spec.cwd)},`);
|
|
876
|
+
lines.push(` timeoutMs: ${safeJsonLiteral(spec.timeoutMs)}`);
|
|
877
|
+
lines.push(" });");
|
|
878
|
+
lines.push(` ${assertTrue("!run.error || run.status !== null", `command failed to spawn: ${spec.id}`)}`);
|
|
879
|
+
lines.push(` const stdout = normalizeText(run.stdout || "", ${safeJsonLiteral(spec.normalize)});`);
|
|
880
|
+
lines.push(` const stderr = normalizeText(run.stderr || "", ${safeJsonLiteral(spec.normalize)});`);
|
|
881
|
+
if (spec.exitCode !== undefined) {
|
|
882
|
+
if (Array.isArray(spec.exitCode)) {
|
|
883
|
+
lines.push(` const acceptedCodes = ${safeJsonLiteral(spec.exitCode)};`);
|
|
884
|
+
lines.push(` ${assertTrue("run.status !== null && acceptedCodes.includes(run.status)", `unexpected exitCode for ${spec.id}`)}`);
|
|
885
|
+
}
|
|
886
|
+
else {
|
|
887
|
+
lines.push(` ${assertEq("run.status", safeJsonLiteral(spec.exitCode), `exitCode mismatch for ${spec.id}`)}`);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (spec.stdoutExact !== undefined) {
|
|
891
|
+
lines.push(` ${assertEq("stdout", `normalizeText(${safeJsonLiteral(spec.stdoutExact)}, ${safeJsonLiteral(spec.normalize)})`, "stdoutExact mismatch")}`);
|
|
892
|
+
}
|
|
893
|
+
for (const needle of spec.stdoutContains) {
|
|
894
|
+
lines.push(` ${assertTrue(`stdout.includes(${safeJsonLiteral(needle)})`, `stdout missing expected substring`)}`);
|
|
895
|
+
}
|
|
896
|
+
for (const needle of spec.stdoutNotContains) {
|
|
897
|
+
lines.push(` ${assertTrue(`!stdout.includes(${safeJsonLiteral(needle)})`, `stdout contained forbidden substring`)}`);
|
|
898
|
+
}
|
|
899
|
+
for (const pattern of spec.stdoutRegex) {
|
|
900
|
+
lines.push(` ${assertTrue(`new RegExp(${safeJsonLiteral(pattern)}).test(stdout)`, `stdout regex mismatch`)}`);
|
|
901
|
+
}
|
|
902
|
+
if (spec.stderrExact !== undefined) {
|
|
903
|
+
lines.push(` ${assertEq("stderr", `normalizeText(${safeJsonLiteral(spec.stderrExact)}, ${safeJsonLiteral(spec.normalize)})`, "stderrExact mismatch")}`);
|
|
904
|
+
}
|
|
905
|
+
for (const needle of spec.stderrContains) {
|
|
906
|
+
lines.push(` ${assertTrue(`stderr.includes(${safeJsonLiteral(needle)})`, `stderr missing expected substring`)}`);
|
|
907
|
+
}
|
|
908
|
+
if (spec.goldenStdout !== undefined) {
|
|
909
|
+
lines.push(` ${assertEq("normalizeGolden(stdout)", `normalizeGolden(normalizeText(${safeJsonLiteral(spec.goldenStdout)}, ${safeJsonLiteral(spec.normalize)}))`, "goldenStdout mismatch")}`);
|
|
910
|
+
}
|
|
911
|
+
const needsJson = spec.jsonSchema !== undefined || spec.jsonSubset !== undefined || spec.jsonPaths.length > 0;
|
|
912
|
+
if (needsJson) {
|
|
913
|
+
lines.push(' const parsedJson = JSON.parse(normalizeText(run.stdout || "", ["ansi"]).trim());');
|
|
914
|
+
if (spec.jsonSchema !== undefined) {
|
|
915
|
+
lines.push(` const schemaErrors = validateJsonSchema(parsedJson, ${safeJsonLiteral(spec.jsonSchema)});`);
|
|
916
|
+
lines.push(` ${assertDeepEmpty("schemaErrors", "stdout jsonSchema validation errors")}`);
|
|
917
|
+
}
|
|
918
|
+
if (spec.jsonSubset !== undefined) {
|
|
919
|
+
lines.push(` const subsetDiffs = diffJsonSubset(${safeJsonLiteral(spec.jsonSubset)}, parsedJson);`);
|
|
920
|
+
lines.push(` ${assertDeepEmpty("subsetDiffs", "stdout jsonSubset mismatch")}`);
|
|
921
|
+
}
|
|
922
|
+
for (const jp of spec.jsonPaths) {
|
|
923
|
+
lines.push(" {");
|
|
924
|
+
lines.push(` const q = queryJsonPath(parsedJson, ${safeJsonLiteral(jp.path)});`);
|
|
925
|
+
lines.push(` ${assertTrue("q.found", `jsonPath not found: ${jp.path}`)}`);
|
|
926
|
+
if (Object.prototype.hasOwnProperty.call(jp, "equals")) {
|
|
927
|
+
lines.push(` ${assertEq("JSON.stringify(q.value)", `JSON.stringify(${safeJsonLiteral(jp.equals)})`, `jsonPath equals mismatch: ${jp.path}`)}`);
|
|
928
|
+
}
|
|
929
|
+
else if (typeof jp.matches === "string") {
|
|
930
|
+
lines.push(` ${assertTrue(`new RegExp(${safeJsonLiteral(jp.matches)}).test(String(q.value))`, `jsonPath regex mismatch: ${jp.path}`)}`);
|
|
931
|
+
}
|
|
932
|
+
lines.push(" }");
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
if (spec.type === "http") {
|
|
938
|
+
lines.push(` const base = resolveTarget("http", ${safeJsonLiteral(spec.defaultTarget)});`);
|
|
939
|
+
lines.push(` const url = buildRequestUrl(base, ${safeJsonLiteral(spec.path)}, ${safeJsonLiteral(spec.query)});`);
|
|
940
|
+
lines.push(spec.hadSensitiveHeaders
|
|
941
|
+
? ` const headers = applyOptionalAuthHeader(${safeJsonLiteral(spec.headers)});`
|
|
942
|
+
: ` const headers = { ...${safeJsonLiteral(spec.headers)} };`);
|
|
943
|
+
const hasBody = spec.hasBody && spec.method !== "GET" && spec.method !== "HEAD";
|
|
944
|
+
if (hasBody) {
|
|
945
|
+
lines.push(` const rawBody = ${safeJsonLiteral(spec.body)};`);
|
|
946
|
+
lines.push(' const body = typeof rawBody === "string" ? rawBody : JSON.stringify(rawBody);');
|
|
947
|
+
lines.push(' if (typeof rawBody !== "string" && !Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {');
|
|
948
|
+
lines.push(' headers["content-type"] = "application/json";');
|
|
949
|
+
lines.push(" }");
|
|
950
|
+
}
|
|
951
|
+
lines.push(" const ctrl = new AbortController();");
|
|
952
|
+
lines.push(` const timer = setTimeout(() => ctrl.abort(), ${safeJsonLiteral(spec.timeoutMs)});`);
|
|
953
|
+
lines.push(" const started = Date.now();");
|
|
954
|
+
lines.push(isVitest ? " let res: Response;" : " let res;");
|
|
955
|
+
lines.push(' let text = "";');
|
|
956
|
+
lines.push(" try {");
|
|
957
|
+
lines.push(` res = await fetch(url, { method: ${safeJsonLiteral(spec.method)}, headers${hasBody ? ", body" : ""}, signal: ctrl.signal });`);
|
|
958
|
+
lines.push(" text = await res.text();");
|
|
959
|
+
lines.push(" } finally {");
|
|
960
|
+
lines.push(" clearTimeout(timer);");
|
|
961
|
+
lines.push(" }");
|
|
962
|
+
lines.push(" const durationMs = Date.now() - started;");
|
|
963
|
+
if (spec.status !== undefined) {
|
|
964
|
+
if (Array.isArray(spec.status)) {
|
|
965
|
+
lines.push(` const acceptedStatuses = ${safeJsonLiteral(spec.status)};`);
|
|
966
|
+
lines.push(` ${assertTrue("acceptedStatuses.includes(res.status)", `unexpected HTTP status for ${spec.id}`)}`);
|
|
967
|
+
}
|
|
968
|
+
else {
|
|
969
|
+
lines.push(` ${assertEq("res.status", safeJsonLiteral(spec.status), `HTTP status mismatch for ${spec.id}`)}`);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
if (spec.maxLatencyMs !== undefined) {
|
|
973
|
+
lines.push(` ${assertTrue(`durationMs <= ${safeJsonLiteral(spec.maxLatencyMs)}`, `latency exceeded maxLatencyMs (${spec.maxLatencyMs}ms)`)}`);
|
|
974
|
+
}
|
|
975
|
+
for (const [hdrKey, hdrVal] of Object.entries(spec.expectedHeaders)) {
|
|
976
|
+
lines.push(" {");
|
|
977
|
+
lines.push(` const actualHdr = res.headers.get(${safeJsonLiteral(hdrKey)});`);
|
|
978
|
+
lines.push(` ${assertTrue("actualHdr !== null", `missing response header: ${hdrKey}`)}`);
|
|
979
|
+
lines.push(` const wantHdr = ${safeJsonLiteral(hdrVal)}.toLowerCase();`);
|
|
980
|
+
lines.push(` const actualLower = (actualHdr ?? "").toLowerCase();`);
|
|
981
|
+
lines.push(` ${assertTrue("actualLower === wantHdr || actualLower.includes(wantHdr)", `header mismatch for ${hdrKey}`)}`);
|
|
982
|
+
lines.push(" }");
|
|
983
|
+
}
|
|
984
|
+
if (spec.bodyExact !== undefined) {
|
|
985
|
+
lines.push(` ${assertEq("text", safeJsonLiteral(spec.bodyExact), "bodyExact mismatch")}`);
|
|
986
|
+
}
|
|
987
|
+
for (const needle of spec.bodyContains) {
|
|
988
|
+
lines.push(` ${assertTrue(`text.includes(${safeJsonLiteral(needle)})`, "response body missing expected substring")}`);
|
|
989
|
+
}
|
|
990
|
+
const needsJson = spec.jsonSchema !== undefined || spec.jsonSubset !== undefined || spec.jsonPaths.length > 0;
|
|
991
|
+
if (needsJson) {
|
|
992
|
+
lines.push(" const parsedJson = JSON.parse(text);");
|
|
993
|
+
if (spec.jsonSchema !== undefined) {
|
|
994
|
+
lines.push(` const schemaErrors = validateJsonSchema(parsedJson, ${safeJsonLiteral(spec.jsonSchema)});`);
|
|
995
|
+
lines.push(` ${assertDeepEmpty("schemaErrors", "response jsonSchema validation errors")}`);
|
|
996
|
+
}
|
|
997
|
+
if (spec.jsonSubset !== undefined) {
|
|
998
|
+
lines.push(` const subsetDiffs = diffJsonSubset(${safeJsonLiteral(spec.jsonSubset)}, parsedJson);`);
|
|
999
|
+
lines.push(` ${assertDeepEmpty("subsetDiffs", "response jsonSubset mismatch")}`);
|
|
1000
|
+
}
|
|
1001
|
+
for (const jp of spec.jsonPaths) {
|
|
1002
|
+
lines.push(" {");
|
|
1003
|
+
lines.push(` const q = queryJsonPath(parsedJson, ${safeJsonLiteral(jp.path)});`);
|
|
1004
|
+
lines.push(` ${assertTrue("q.found", `jsonPath not found: ${jp.path}`)}`);
|
|
1005
|
+
if (Object.prototype.hasOwnProperty.call(jp, "equals")) {
|
|
1006
|
+
lines.push(` ${assertEq("JSON.stringify(q.value)", `JSON.stringify(${safeJsonLiteral(jp.equals)})`, `jsonPath equals mismatch: ${jp.path}`)}`);
|
|
1007
|
+
}
|
|
1008
|
+
else if (typeof jp.matches === "string") {
|
|
1009
|
+
lines.push(` ${assertTrue(`new RegExp(${safeJsonLiteral(jp.matches)}).test(String(q.value))`, `jsonPath regex mismatch: ${jp.path}`)}`);
|
|
1010
|
+
}
|
|
1011
|
+
lines.push(" }");
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
if (spec.type === "web_route") {
|
|
1017
|
+
lines.push(` const base = resolveTarget("web_route", ${safeJsonLiteral(spec.defaultTarget)});`);
|
|
1018
|
+
lines.push(` const url = buildRequestUrl(base, ${safeJsonLiteral(spec.routePath)});`);
|
|
1019
|
+
lines.push(spec.hadSensitiveHeaders
|
|
1020
|
+
? ` const headers = applyOptionalAuthHeader(${safeJsonLiteral(spec.headers)});`
|
|
1021
|
+
: ` const headers = { ...${safeJsonLiteral(spec.headers)} };`);
|
|
1022
|
+
lines.push(" const ctrl = new AbortController();");
|
|
1023
|
+
lines.push(` const timer = setTimeout(() => ctrl.abort(), ${safeJsonLiteral(spec.timeoutMs)});`);
|
|
1024
|
+
lines.push(isVitest ? " let res: Response;" : " let res;");
|
|
1025
|
+
lines.push(' let html = "";');
|
|
1026
|
+
lines.push(" try {");
|
|
1027
|
+
lines.push(' res = await fetch(url, { redirect: "follow", headers, signal: ctrl.signal });');
|
|
1028
|
+
lines.push(" html = await res.text();");
|
|
1029
|
+
lines.push(" } finally {");
|
|
1030
|
+
lines.push(" clearTimeout(timer);");
|
|
1031
|
+
lines.push(" }");
|
|
1032
|
+
if (spec.status !== undefined) {
|
|
1033
|
+
if (Array.isArray(spec.status)) {
|
|
1034
|
+
lines.push(` const acceptedStatuses = ${safeJsonLiteral(spec.status)};`);
|
|
1035
|
+
lines.push(` ${assertTrue("acceptedStatuses.includes(res.status)", `unexpected web_route status for ${spec.id}`)}`);
|
|
1036
|
+
}
|
|
1037
|
+
else {
|
|
1038
|
+
lines.push(` ${assertEq("res.status", safeJsonLiteral(spec.status), `web_route status mismatch for ${spec.id}`)}`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
else {
|
|
1042
|
+
lines.push(` ${assertTrue("res.status >= 200 && res.status < 400", `expected 2xx/3xx status for ${spec.id}`)}`);
|
|
1043
|
+
}
|
|
1044
|
+
if (spec.titleContains !== undefined) {
|
|
1045
|
+
lines.push(" const title = extractHtmlTitle(html);");
|
|
1046
|
+
lines.push(` ${assertTrue(`title.includes(${safeJsonLiteral(spec.titleContains)})`, `title missing expected text for ${spec.id}`)}`);
|
|
1047
|
+
}
|
|
1048
|
+
for (const needle of spec.bodyContains) {
|
|
1049
|
+
lines.push(` ${assertTrue(`html.includes(${safeJsonLiteral(needle)})`, `HTML body missing expected substring`)}`);
|
|
1050
|
+
}
|
|
1051
|
+
for (const lm of spec.landmarks) {
|
|
1052
|
+
if (lm.required === false)
|
|
1053
|
+
continue;
|
|
1054
|
+
lines.push(` ${assertTrue(`checkHtmlLandmark(html, ${safeJsonLiteral(lm.tag)}, ${safeJsonLiteral(lm.textContains ?? "")})`, `missing HTML landmark <${lm.tag}>`)}`);
|
|
1055
|
+
}
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
// repo_exports
|
|
1059
|
+
lines.push(` const root = path.resolve(resolveTarget("repo_exports", ${safeJsonLiteral(spec.defaultTarget)}));`);
|
|
1060
|
+
lines.push(` ${assertTrue("fs.existsSync(root) && fs.statSync(root).isDirectory()", `repo target directory missing for ${spec.id}`)}`);
|
|
1061
|
+
for (const rel of spec.filesPresent) {
|
|
1062
|
+
lines.push(` ${assertTrue(`fs.existsSync(path.join(root, ${safeJsonLiteral(rel)}))`, `missing expected file: ${rel}`)}`);
|
|
1063
|
+
}
|
|
1064
|
+
if (spec.exports.length > 0 && spec.modulePath) {
|
|
1065
|
+
lines.push(` const modPath = path.join(root, ${safeJsonLiteral(spec.modulePath)});`);
|
|
1066
|
+
lines.push(` ${assertTrue("fs.existsSync(modPath) && fs.statSync(modPath).isFile()", `missing module file: ${spec.modulePath}`)}`);
|
|
1067
|
+
lines.push(" const exportedNames = await loadModuleExports(modPath);");
|
|
1068
|
+
for (const exp of spec.exports) {
|
|
1069
|
+
lines.push(` ${assertTrue(`exportedNames.has(${safeJsonLiteral(exp.name)})`, `missing expected export: ${exp.name}`)}`);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
function generateNodeTestOrVitest(format, contract, specs, skippedIds, options, includeSkippedComments) {
|
|
1074
|
+
const isVitest = format === "vitest";
|
|
1075
|
+
const typesUsed = new Set(specs.map((s) => s.type));
|
|
1076
|
+
const anySensitiveHeaders = specs.some((s) => (s.type === "http" || s.type === "web_route") && s.hadSensitiveHeaders);
|
|
1077
|
+
const defaultTarget = resolveDefaultTargetForContract(contract, options.target);
|
|
1078
|
+
const lines = [];
|
|
1079
|
+
lines.push(...buildHeaderLines("//", contract, options, skippedIds, includeSkippedComments));
|
|
1080
|
+
lines.push("");
|
|
1081
|
+
if (isVitest) {
|
|
1082
|
+
lines.push('import { describe, it, expect } from "vitest";');
|
|
1083
|
+
}
|
|
1084
|
+
else {
|
|
1085
|
+
lines.push('import test, { describe } from "node:test";');
|
|
1086
|
+
lines.push('import assert from "node:assert/strict";');
|
|
1087
|
+
}
|
|
1088
|
+
if (typesUsed.has("command")) {
|
|
1089
|
+
lines.push('import { spawnSync } from "node:child_process";');
|
|
1090
|
+
}
|
|
1091
|
+
if (typesUsed.has("repo_exports")) {
|
|
1092
|
+
lines.push('import fs from "node:fs";');
|
|
1093
|
+
}
|
|
1094
|
+
if (typesUsed.has("command") || typesUsed.has("repo_exports")) {
|
|
1095
|
+
lines.push('import path from "node:path";');
|
|
1096
|
+
}
|
|
1097
|
+
if (typesUsed.has("repo_exports")) {
|
|
1098
|
+
lines.push('import { pathToFileURL } from "node:url";');
|
|
1099
|
+
}
|
|
1100
|
+
lines.push("");
|
|
1101
|
+
lines.push(`const DEFAULT_TARGET = process.env.VIBECODE_TARGET || ${safeJsonLiteral(defaultTarget)};`);
|
|
1102
|
+
lines.push("");
|
|
1103
|
+
if (specs.length > 0) {
|
|
1104
|
+
emitJsSharedHelpers(lines, typesUsed, anySensitiveHeaders, isVitest);
|
|
1105
|
+
}
|
|
1106
|
+
const suiteTitle = sanitizeFreeText(contract.target?.name || "vibecode-contract");
|
|
1107
|
+
lines.push(`describe(${safeJsonLiteral(suiteTitle)}, () => {`);
|
|
1108
|
+
const testFn = isVitest ? "it" : "test";
|
|
1109
|
+
for (const spec of specs) {
|
|
1110
|
+
const label = `${spec.id}: ${spec.description}`;
|
|
1111
|
+
const isAsync = spec.type === "http" || spec.type === "web_route" || spec.type === "repo_exports";
|
|
1112
|
+
lines.push(` ${testFn}(${safeJsonLiteral(label)}, ${isAsync ? "async " : ""}() => {`);
|
|
1113
|
+
emitJsTestBody(lines, spec, format);
|
|
1114
|
+
lines.push(" });");
|
|
1115
|
+
lines.push("");
|
|
1116
|
+
}
|
|
1117
|
+
lines.push("});");
|
|
1118
|
+
lines.push("");
|
|
1119
|
+
return lines.join("\n");
|
|
1120
|
+
}
|
|
1121
|
+
function makeUniquePyTestName(id, used) {
|
|
1122
|
+
const slug = id
|
|
1123
|
+
.toLowerCase()
|
|
1124
|
+
.replace(/[^a-z0-9]+/g, "_")
|
|
1125
|
+
.replace(/^_+|_+$/g, "")
|
|
1126
|
+
.slice(0, 64) || "invariant";
|
|
1127
|
+
let candidate = `test_${slug}`;
|
|
1128
|
+
if (!used.has(candidate)) {
|
|
1129
|
+
used.add(candidate);
|
|
1130
|
+
return candidate;
|
|
1131
|
+
}
|
|
1132
|
+
let idx = 2;
|
|
1133
|
+
while (used.has(`${candidate}_${idx}`))
|
|
1134
|
+
idx += 1;
|
|
1135
|
+
candidate = `${candidate}_${idx}`;
|
|
1136
|
+
used.add(candidate);
|
|
1137
|
+
return candidate;
|
|
1138
|
+
}
|
|
1139
|
+
function generatePytest(contract, specs, skippedIds, options, includeSkippedComments) {
|
|
1140
|
+
const typesUsed = new Set(specs.map((s) => s.type));
|
|
1141
|
+
const anySensitiveHeaders = specs.some((s) => (s.type === "http" || s.type === "web_route") && s.hadSensitiveHeaders);
|
|
1142
|
+
const defaultTarget = resolveDefaultTargetForContract(contract, options.target);
|
|
1143
|
+
const lines = [];
|
|
1144
|
+
lines.push(...buildHeaderLines("#", contract, options, skippedIds, includeSkippedComments));
|
|
1145
|
+
lines.push("");
|
|
1146
|
+
lines.push("import json");
|
|
1147
|
+
lines.push("import os");
|
|
1148
|
+
lines.push("import re");
|
|
1149
|
+
if (typesUsed.has("command")) {
|
|
1150
|
+
lines.push("import shlex");
|
|
1151
|
+
lines.push("import subprocess");
|
|
1152
|
+
}
|
|
1153
|
+
if (typesUsed.has("http") || typesUsed.has("web_route")) {
|
|
1154
|
+
lines.push("import time");
|
|
1155
|
+
lines.push("import urllib.error");
|
|
1156
|
+
lines.push("import urllib.parse");
|
|
1157
|
+
lines.push("import urllib.request");
|
|
1158
|
+
}
|
|
1159
|
+
if (typesUsed.has("repo_exports")) {
|
|
1160
|
+
lines.push("from pathlib import Path");
|
|
1161
|
+
}
|
|
1162
|
+
lines.push("");
|
|
1163
|
+
lines.push(`DEFAULT_TARGET = os.environ.get("VIBECODE_TARGET") or ${safePyLiteral(defaultTarget)}`);
|
|
1164
|
+
lines.push("");
|
|
1165
|
+
if (specs.length > 0) {
|
|
1166
|
+
lines.push("def resolve_target(kind, fallback):");
|
|
1167
|
+
lines.push(" env_by_kind = {");
|
|
1168
|
+
lines.push(' "command": os.environ.get("VIBECODE_CLI_TARGET"),');
|
|
1169
|
+
lines.push(' "http": os.environ.get("VIBECODE_API_TARGET") or os.environ.get("VIBECODE_HTTP_TARGET"),');
|
|
1170
|
+
lines.push(' "web_route": os.environ.get("VIBECODE_WEB_TARGET") or os.environ.get("VIBECODE_API_TARGET") or os.environ.get("VIBECODE_HTTP_TARGET"),');
|
|
1171
|
+
lines.push(' "repo_exports": os.environ.get("VIBECODE_REPO_TARGET"),');
|
|
1172
|
+
lines.push(" }");
|
|
1173
|
+
lines.push(" specific = env_by_kind.get(kind)");
|
|
1174
|
+
lines.push(" if specific and specific.strip():");
|
|
1175
|
+
lines.push(" return specific.strip()");
|
|
1176
|
+
lines.push(' raw = os.environ.get("VIBECODE_TARGET")');
|
|
1177
|
+
lines.push(" if raw and raw.strip():");
|
|
1178
|
+
lines.push(" trimmed = raw.strip()");
|
|
1179
|
+
lines.push(' if trimmed.startswith("{"):');
|
|
1180
|
+
lines.push(" try:");
|
|
1181
|
+
lines.push(" parsed = json.loads(trimmed)");
|
|
1182
|
+
lines.push(" if isinstance(parsed, dict):");
|
|
1183
|
+
lines.push(" aliases = {");
|
|
1184
|
+
lines.push(' "command": ("command", "cli", "default"),');
|
|
1185
|
+
lines.push(' "http": ("http", "api", "default"),');
|
|
1186
|
+
lines.push(' "web_route": ("web_route", "web", "http", "api", "default"),');
|
|
1187
|
+
lines.push(' "repo_exports": ("repo_exports", "repo", "default"),');
|
|
1188
|
+
lines.push(" }");
|
|
1189
|
+
lines.push(" for key in aliases.get(kind, ()):");
|
|
1190
|
+
lines.push(" val = parsed.get(key)");
|
|
1191
|
+
lines.push(" if isinstance(val, str) and val.strip():");
|
|
1192
|
+
lines.push(" return val.strip()");
|
|
1193
|
+
lines.push(" except Exception:");
|
|
1194
|
+
lines.push(" pass");
|
|
1195
|
+
lines.push(" return trimmed");
|
|
1196
|
+
lines.push(" return fallback or DEFAULT_TARGET");
|
|
1197
|
+
lines.push("");
|
|
1198
|
+
}
|
|
1199
|
+
if (anySensitiveHeaders) {
|
|
1200
|
+
lines.push("def apply_optional_auth_header(headers):");
|
|
1201
|
+
lines.push(" out = dict(headers)");
|
|
1202
|
+
lines.push(' raw = os.environ.get("VIBECODE_AUTH_HEADER")');
|
|
1203
|
+
lines.push(" if raw and raw.strip():");
|
|
1204
|
+
lines.push(' if ":" in raw:');
|
|
1205
|
+
lines.push(' name, val = raw.split(":", 1)');
|
|
1206
|
+
lines.push(" if name.strip():");
|
|
1207
|
+
lines.push(" out[name.strip()] = val.strip()");
|
|
1208
|
+
lines.push(" return out");
|
|
1209
|
+
lines.push(' out["Authorization"] = raw.strip()');
|
|
1210
|
+
lines.push(" return out");
|
|
1211
|
+
lines.push("");
|
|
1212
|
+
}
|
|
1213
|
+
if (typesUsed.has("command")) {
|
|
1214
|
+
lines.push("def normalize_text(text, modes):");
|
|
1215
|
+
lines.push(' out = "" if text is None else str(text)');
|
|
1216
|
+
lines.push(" for mode in modes:");
|
|
1217
|
+
lines.push(' if mode == "crlf":');
|
|
1218
|
+
lines.push(' out = out.replace("\\r\\n", "\\n")');
|
|
1219
|
+
lines.push(' elif mode == "ansi":');
|
|
1220
|
+
lines.push(' out = re.sub(r"\\x1B\\[[0-?]*[ -/]*[@-~]", "", out)');
|
|
1221
|
+
lines.push(' elif mode == "timestamps":');
|
|
1222
|
+
lines.push(' out = re.sub(r"\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?", "<TS>", out)');
|
|
1223
|
+
lines.push(' out = re.sub(r"\\b\\d{13}\\b", "<TS_MS>", out)');
|
|
1224
|
+
lines.push(' elif mode == "paths":');
|
|
1225
|
+
lines.push(' out = re.sub(r"[A-Za-z]:\\\\[^\\s\\\"\\\']+", lambda m: m.group(0).replace("\\\\", "/"), out)');
|
|
1226
|
+
lines.push(' elif mode == "trim":');
|
|
1227
|
+
lines.push(" out = out.strip()");
|
|
1228
|
+
lines.push(" return out");
|
|
1229
|
+
lines.push("");
|
|
1230
|
+
lines.push("def normalize_golden(text):");
|
|
1231
|
+
lines.push(' s = ("" if text is None else str(text)).replace("\\r\\n", "\\n")');
|
|
1232
|
+
lines.push(' return s[:-1] if s.endswith("\\n") else s');
|
|
1233
|
+
lines.push("");
|
|
1234
|
+
lines.push("def run_command(target_cmd, extra_args, stdin_text, env_extra, cwd_path, timeout_ms):");
|
|
1235
|
+
lines.push(" tokens = shlex.split(target_cmd, posix=(os.name != 'nt'))");
|
|
1236
|
+
lines.push(' assert len(tokens) > 0, "Empty command target"');
|
|
1237
|
+
lines.push(" env = dict(os.environ)");
|
|
1238
|
+
lines.push(" env.update(env_extra)");
|
|
1239
|
+
lines.push(" return subprocess.run(");
|
|
1240
|
+
lines.push(" tokens + list(extra_args),");
|
|
1241
|
+
lines.push(" input=stdin_text,");
|
|
1242
|
+
lines.push(" capture_output=True,");
|
|
1243
|
+
lines.push(" text=True,");
|
|
1244
|
+
lines.push(" env=env,");
|
|
1245
|
+
lines.push(" cwd=cwd_path or None,");
|
|
1246
|
+
lines.push(" timeout=max(0.1, timeout_ms / 1000.0),");
|
|
1247
|
+
lines.push(" shell=False,");
|
|
1248
|
+
lines.push(" )");
|
|
1249
|
+
lines.push("");
|
|
1250
|
+
}
|
|
1251
|
+
if (typesUsed.has("command") || typesUsed.has("http")) {
|
|
1252
|
+
lines.push('def diff_json_subset(expected, actual, current_path="$"):');
|
|
1253
|
+
lines.push(" diffs = []");
|
|
1254
|
+
lines.push(" if isinstance(expected, list):");
|
|
1255
|
+
lines.push(" if not isinstance(actual, list):");
|
|
1256
|
+
lines.push(' return [f"{current_path}: expected list"]');
|
|
1257
|
+
lines.push(" for idx, item in enumerate(expected):");
|
|
1258
|
+
lines.push(" if idx >= len(actual):");
|
|
1259
|
+
lines.push(' diffs.append(f"{current_path}[{idx}]: missing element")');
|
|
1260
|
+
lines.push(" else:");
|
|
1261
|
+
lines.push(' diffs.extend(diff_json_subset(item, actual[idx], f"{current_path}[{idx}]"))');
|
|
1262
|
+
lines.push(" return diffs");
|
|
1263
|
+
lines.push(" if isinstance(expected, dict):");
|
|
1264
|
+
lines.push(" if not isinstance(actual, dict):");
|
|
1265
|
+
lines.push(' return [f"{current_path}: expected dict"]');
|
|
1266
|
+
lines.push(" for k, v in expected.items():");
|
|
1267
|
+
lines.push(" if k not in actual:");
|
|
1268
|
+
lines.push(' diffs.append(f"{current_path}.{k}: missing key")');
|
|
1269
|
+
lines.push(" else:");
|
|
1270
|
+
lines.push(' diffs.extend(diff_json_subset(v, actual[k], f"{current_path}.{k}"))');
|
|
1271
|
+
lines.push(" return diffs");
|
|
1272
|
+
lines.push(" if type(expected) is bool or type(actual) is bool:");
|
|
1273
|
+
lines.push(" if expected is not actual:");
|
|
1274
|
+
lines.push(' diffs.append(f"{current_path}: expected {expected!r}, got {actual!r}")');
|
|
1275
|
+
lines.push(" elif expected != actual:");
|
|
1276
|
+
lines.push(' diffs.append(f"{current_path}: expected {expected!r}, got {actual!r}")');
|
|
1277
|
+
lines.push(" return diffs");
|
|
1278
|
+
lines.push("");
|
|
1279
|
+
lines.push("def query_json_path(obj, expr):");
|
|
1280
|
+
lines.push(' if not isinstance(expr, str) or not expr.startswith("$"):');
|
|
1281
|
+
lines.push(" return (False, None)");
|
|
1282
|
+
lines.push(" cur = obj");
|
|
1283
|
+
lines.push(" token_re = re.compile(r'''\\.([A-Za-z_$][A-Za-z0-9_$-]*)|\\[(\\d+)\\]|\\[(?:\"([^\"]*)\"|'([^']*)')\\]''')");
|
|
1284
|
+
lines.push(" pos = 1");
|
|
1285
|
+
lines.push(" tokens = []");
|
|
1286
|
+
lines.push(" while pos < len(expr):");
|
|
1287
|
+
lines.push(" m = token_re.match(expr, pos)");
|
|
1288
|
+
lines.push(" if not m:");
|
|
1289
|
+
lines.push(" return (False, None)");
|
|
1290
|
+
lines.push(" if m.group(1) is not None:");
|
|
1291
|
+
lines.push(" tokens.append(m.group(1))");
|
|
1292
|
+
lines.push(" elif m.group(2) is not None:");
|
|
1293
|
+
lines.push(" tokens.append(int(m.group(2)))");
|
|
1294
|
+
lines.push(" elif m.group(3) is not None:");
|
|
1295
|
+
lines.push(" tokens.append(m.group(3))");
|
|
1296
|
+
lines.push(" elif m.group(4) is not None:");
|
|
1297
|
+
lines.push(" tokens.append(m.group(4))");
|
|
1298
|
+
lines.push(" pos = m.end()");
|
|
1299
|
+
lines.push(" for tok in tokens:");
|
|
1300
|
+
lines.push(" if isinstance(tok, int):");
|
|
1301
|
+
lines.push(" if not isinstance(cur, list) or tok < 0 or tok >= len(cur):");
|
|
1302
|
+
lines.push(" return (False, None)");
|
|
1303
|
+
lines.push(" cur = cur[tok]");
|
|
1304
|
+
lines.push(" else:");
|
|
1305
|
+
lines.push(" if not isinstance(cur, dict) or tok not in cur:");
|
|
1306
|
+
lines.push(" return (False, None)");
|
|
1307
|
+
lines.push(" cur = cur[tok]");
|
|
1308
|
+
lines.push(" return (True, cur)");
|
|
1309
|
+
lines.push("");
|
|
1310
|
+
lines.push('def validate_json_schema(value, schema, current_path="$"):');
|
|
1311
|
+
lines.push(" errors = []");
|
|
1312
|
+
lines.push(" if not isinstance(schema, dict):");
|
|
1313
|
+
lines.push(" return errors");
|
|
1314
|
+
lines.push(' if schema.get("nullable") is True and value is None:');
|
|
1315
|
+
lines.push(" return errors");
|
|
1316
|
+
lines.push(' if "type" in schema:');
|
|
1317
|
+
lines.push(' types = schema["type"] if isinstance(schema["type"], list) else [schema["type"]]');
|
|
1318
|
+
lines.push(" def _matches(t):");
|
|
1319
|
+
lines.push(' if t == "null": return value is None');
|
|
1320
|
+
lines.push(' if t == "array": return isinstance(value, list)');
|
|
1321
|
+
lines.push(' if t == "object": return isinstance(value, dict)');
|
|
1322
|
+
lines.push(' if t == "boolean": return isinstance(value, bool)');
|
|
1323
|
+
lines.push(' if t == "integer": return isinstance(value, int) and not isinstance(value, bool)');
|
|
1324
|
+
lines.push(' if t == "number": return isinstance(value, (int, float)) and not isinstance(value, bool)');
|
|
1325
|
+
lines.push(' if t == "string": return isinstance(value, str)');
|
|
1326
|
+
lines.push(" return True");
|
|
1327
|
+
lines.push(" if not any(_matches(t) for t in types):");
|
|
1328
|
+
lines.push(' errors.append(f"{current_path}: type mismatch")');
|
|
1329
|
+
lines.push(" if isinstance(value, dict):");
|
|
1330
|
+
lines.push(' for req_key in schema.get("required", []):');
|
|
1331
|
+
lines.push(" if req_key not in value:");
|
|
1332
|
+
lines.push(' errors.append(f"{current_path}.{req_key}: missing required")');
|
|
1333
|
+
lines.push(' props = schema.get("properties")');
|
|
1334
|
+
lines.push(" if isinstance(props, dict):");
|
|
1335
|
+
lines.push(" for k, sub in props.items():");
|
|
1336
|
+
lines.push(" if k in value and isinstance(sub, dict):");
|
|
1337
|
+
lines.push(' errors.extend(validate_json_schema(value[k], sub, f"{current_path}.{k}"))');
|
|
1338
|
+
lines.push(" elif isinstance(value, list):");
|
|
1339
|
+
lines.push(' items_schema = schema.get("items")');
|
|
1340
|
+
lines.push(" if isinstance(items_schema, dict):");
|
|
1341
|
+
lines.push(" for idx, item in enumerate(value):");
|
|
1342
|
+
lines.push(' errors.extend(validate_json_schema(item, items_schema, f"{current_path}[{idx}]"))');
|
|
1343
|
+
lines.push(" return errors");
|
|
1344
|
+
lines.push("");
|
|
1345
|
+
}
|
|
1346
|
+
if (typesUsed.has("http") || typesUsed.has("web_route")) {
|
|
1347
|
+
lines.push("def build_url(base, route_path, query=None):");
|
|
1348
|
+
lines.push(' norm_base = base if re.match(r"^https?://", base, re.I) else "http://" + base');
|
|
1349
|
+
lines.push(' url = route_path if re.match(r"^https?://", route_path, re.I) else urllib.parse.urljoin(norm_base.rstrip("/") + "/", route_path.lstrip("/"))');
|
|
1350
|
+
lines.push(" if query:");
|
|
1351
|
+
lines.push(" parts = urllib.parse.urlsplit(url)");
|
|
1352
|
+
lines.push(" existing = dict(urllib.parse.parse_qsl(parts.query, keep_blank_values=True))");
|
|
1353
|
+
lines.push(" existing.update({str(k): str(v) for k, v in query.items()})");
|
|
1354
|
+
lines.push(" url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, parts.path, urllib.parse.urlencode(existing), parts.fragment))");
|
|
1355
|
+
lines.push(" return url");
|
|
1356
|
+
lines.push("");
|
|
1357
|
+
lines.push("def send_http(url, method, headers, body_bytes, timeout_ms):");
|
|
1358
|
+
lines.push(" req = urllib.request.Request(url, data=body_bytes, headers=headers, method=method)");
|
|
1359
|
+
lines.push(" started = time.monotonic()");
|
|
1360
|
+
lines.push(" try:");
|
|
1361
|
+
lines.push(" with urllib.request.urlopen(req, timeout=max(0.1, timeout_ms / 1000.0)) as resp:");
|
|
1362
|
+
lines.push(' text = resp.read().decode("utf-8", errors="replace")');
|
|
1363
|
+
lines.push(" hdrs = {k.lower(): v for k, v in resp.headers.items()}");
|
|
1364
|
+
lines.push(" return resp.status, hdrs, text, (time.monotonic() - started) * 1000.0");
|
|
1365
|
+
lines.push(" except urllib.error.HTTPError as err:");
|
|
1366
|
+
lines.push(' text = err.read().decode("utf-8", errors="replace")');
|
|
1367
|
+
lines.push(" hdrs = {k.lower(): v for k, v in err.headers.items()} if err.headers else {}");
|
|
1368
|
+
lines.push(" return err.code, hdrs, text, (time.monotonic() - started) * 1000.0");
|
|
1369
|
+
lines.push("");
|
|
1370
|
+
}
|
|
1371
|
+
if (typesUsed.has("web_route")) {
|
|
1372
|
+
lines.push("def strip_html(html):");
|
|
1373
|
+
lines.push(' s = re.sub(r"<script[\\s\\S]*?</script>", " ", html, flags=re.I)');
|
|
1374
|
+
lines.push(' s = re.sub(r"<style[\\s\\S]*?</style>", " ", s, flags=re.I)');
|
|
1375
|
+
lines.push(' s = re.sub(r"<[^>]+>", " ", s)');
|
|
1376
|
+
lines.push(' s = s.replace(" ", " ").replace("&", "&").replace("<", "<").replace(">", ">")');
|
|
1377
|
+
lines.push(' return re.sub(r"\\s+", " ", s).strip()');
|
|
1378
|
+
lines.push("");
|
|
1379
|
+
lines.push("def extract_html_title(html):");
|
|
1380
|
+
lines.push(' m = re.search(r"<title[^>]*>([\\s\\S]*?)</title>", html, flags=re.I)');
|
|
1381
|
+
lines.push(' return strip_html(m.group(1)) if m else ""');
|
|
1382
|
+
lines.push("");
|
|
1383
|
+
lines.push('def check_html_landmark(html, tag, text_contains=""):');
|
|
1384
|
+
lines.push(' safe_tag = re.sub(r"[^a-zA-Z0-9_-]", "", tag)');
|
|
1385
|
+
lines.push(" if not safe_tag:");
|
|
1386
|
+
lines.push(" return False");
|
|
1387
|
+
lines.push(' matches = list(re.finditer(rf"<{safe_tag}\\b[^>]*>([\\s\\S]*?)</{safe_tag}>", html, flags=re.I))');
|
|
1388
|
+
lines.push(" if matches:");
|
|
1389
|
+
lines.push(" if not text_contains:");
|
|
1390
|
+
lines.push(" return True");
|
|
1391
|
+
lines.push(" return any(text_contains in strip_html(m.group(1)) for m in matches)");
|
|
1392
|
+
lines.push(" if not text_contains:");
|
|
1393
|
+
lines.push(' return re.search(rf"<{safe_tag}\\b[^>]*>", html, flags=re.I) is not None');
|
|
1394
|
+
lines.push(" return False");
|
|
1395
|
+
lines.push("");
|
|
1396
|
+
}
|
|
1397
|
+
if (typesUsed.has("repo_exports")) {
|
|
1398
|
+
lines.push("def scan_exports(source_text):");
|
|
1399
|
+
lines.push(" names = set()");
|
|
1400
|
+
lines.push(' for m in re.finditer(r"export\\s+(?:declare\\s+)?(?:async\\s+)?(?:function|class|const|let|var)\\s+([A-Za-z_$][A-Za-z0-9_$]*)", source_text):');
|
|
1401
|
+
lines.push(" names.add(m.group(1))");
|
|
1402
|
+
lines.push(' for m in re.finditer(r"export\\s*\\{([^}]+)\\}", source_text):');
|
|
1403
|
+
lines.push(' for part in m.group(1).split(","):');
|
|
1404
|
+
lines.push(' cleaned = re.sub(r"\\btype\\s+", "", part).strip()');
|
|
1405
|
+
lines.push(" if not cleaned:");
|
|
1406
|
+
lines.push(" continue");
|
|
1407
|
+
lines.push(' as_m = re.search(r"\\bas\\s+([A-Za-z_$][A-Za-z0-9_$]*)$", cleaned)');
|
|
1408
|
+
lines.push(" if as_m:");
|
|
1409
|
+
lines.push(" names.add(as_m.group(1))");
|
|
1410
|
+
lines.push(" else:");
|
|
1411
|
+
lines.push(' id_m = re.match(r"^([A-Za-z_$][A-Za-z0-9_$]*)", cleaned)');
|
|
1412
|
+
lines.push(" if id_m:");
|
|
1413
|
+
lines.push(" names.add(id_m.group(1))");
|
|
1414
|
+
lines.push(' if re.search(r"export\\s+default\\b", source_text):');
|
|
1415
|
+
lines.push(' names.add("default")');
|
|
1416
|
+
lines.push(' for m in re.finditer(r"(?:module\\.)?exports\\.([A-Za-z_$][A-Za-z0-9_$]*)\\s*=", source_text):');
|
|
1417
|
+
lines.push(" names.add(m.group(1))");
|
|
1418
|
+
lines.push(' for m in re.finditer(r"^(?:async\\s+)?(?:def|class)\\s+([A-Za-z_][A-Za-z0-9_]*)", source_text, flags=re.M):');
|
|
1419
|
+
lines.push(" names.add(m.group(1))");
|
|
1420
|
+
lines.push(" return names");
|
|
1421
|
+
lines.push("");
|
|
1422
|
+
}
|
|
1423
|
+
const usedNames = new Set();
|
|
1424
|
+
for (const spec of specs) {
|
|
1425
|
+
const fnName = makeUniquePyTestName(spec.id, usedNames);
|
|
1426
|
+
lines.push(`def ${fnName}():`);
|
|
1427
|
+
lines.push(` # ${sanitizeComment(`${spec.id}: ${spec.description}`)}`);
|
|
1428
|
+
if (spec.type === "command") {
|
|
1429
|
+
lines.push(` target = resolve_target("command", ${safePyLiteral(spec.defaultTarget)})`);
|
|
1430
|
+
lines.push(` run = run_command(target, ${safePyLiteral(spec.args)}, ${safePyLiteral(spec.stdin)}, ${safePyLiteral(spec.env)}, ${safePyLiteral(spec.cwd)}, ${safePyLiteral(spec.timeoutMs)})`);
|
|
1431
|
+
lines.push(` stdout = normalize_text(run.stdout, ${safePyLiteral(spec.normalize)})`);
|
|
1432
|
+
lines.push(` stderr = normalize_text(run.stderr, ${safePyLiteral(spec.normalize)})`);
|
|
1433
|
+
if (spec.exitCode !== undefined) {
|
|
1434
|
+
if (Array.isArray(spec.exitCode)) {
|
|
1435
|
+
lines.push(` assert run.returncode in ${safePyLiteral(spec.exitCode)}, f"unexpected exitCode: {run.returncode}"`);
|
|
1436
|
+
}
|
|
1437
|
+
else {
|
|
1438
|
+
lines.push(` assert run.returncode == ${safePyLiteral(spec.exitCode)}, f"expected exitCode ${spec.exitCode}, got {run.returncode}"`);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
if (spec.stdoutExact !== undefined) {
|
|
1442
|
+
lines.push(` assert stdout == normalize_text(${safePyLiteral(spec.stdoutExact)}, ${safePyLiteral(spec.normalize)})`);
|
|
1443
|
+
}
|
|
1444
|
+
for (const needle of spec.stdoutContains) {
|
|
1445
|
+
lines.push(` assert ${safePyLiteral(needle)} in stdout`);
|
|
1446
|
+
}
|
|
1447
|
+
for (const needle of spec.stdoutNotContains) {
|
|
1448
|
+
lines.push(` assert ${safePyLiteral(needle)} not in stdout`);
|
|
1449
|
+
}
|
|
1450
|
+
for (const pattern of spec.stdoutRegex) {
|
|
1451
|
+
lines.push(` assert re.search(${safePyLiteral(pattern)}, stdout) is not None`);
|
|
1452
|
+
}
|
|
1453
|
+
if (spec.stderrExact !== undefined) {
|
|
1454
|
+
lines.push(` assert stderr == normalize_text(${safePyLiteral(spec.stderrExact)}, ${safePyLiteral(spec.normalize)})`);
|
|
1455
|
+
}
|
|
1456
|
+
for (const needle of spec.stderrContains) {
|
|
1457
|
+
lines.push(` assert ${safePyLiteral(needle)} in stderr`);
|
|
1458
|
+
}
|
|
1459
|
+
if (spec.goldenStdout !== undefined) {
|
|
1460
|
+
lines.push(` assert normalize_golden(stdout) == normalize_golden(normalize_text(${safePyLiteral(spec.goldenStdout)}, ${safePyLiteral(spec.normalize)}))`);
|
|
1461
|
+
}
|
|
1462
|
+
const needsJson = spec.jsonSchema !== undefined || spec.jsonSubset !== undefined || spec.jsonPaths.length > 0;
|
|
1463
|
+
if (needsJson) {
|
|
1464
|
+
lines.push(' parsed_json = json.loads(normalize_text(run.stdout, ["ansi"]).strip())');
|
|
1465
|
+
if (spec.jsonSchema !== undefined) {
|
|
1466
|
+
lines.push(` assert validate_json_schema(parsed_json, ${safePyLiteral(spec.jsonSchema)}) == []`);
|
|
1467
|
+
}
|
|
1468
|
+
if (spec.jsonSubset !== undefined) {
|
|
1469
|
+
lines.push(` assert diff_json_subset(${safePyLiteral(spec.jsonSubset)}, parsed_json) == []`);
|
|
1470
|
+
}
|
|
1471
|
+
for (const jp of spec.jsonPaths) {
|
|
1472
|
+
lines.push(` found, val = query_json_path(parsed_json, ${safePyLiteral(jp.path)})`);
|
|
1473
|
+
lines.push(" assert found");
|
|
1474
|
+
if (Object.prototype.hasOwnProperty.call(jp, "equals")) {
|
|
1475
|
+
lines.push(` assert val == ${safePyLiteral(jp.equals)}`);
|
|
1476
|
+
}
|
|
1477
|
+
else if (typeof jp.matches === "string") {
|
|
1478
|
+
lines.push(` assert re.search(${safePyLiteral(jp.matches)}, str(val)) is not None`);
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
else if (spec.type === "http") {
|
|
1484
|
+
lines.push(` base = resolve_target("http", ${safePyLiteral(spec.defaultTarget)})`);
|
|
1485
|
+
lines.push(` url = build_url(base, ${safePyLiteral(spec.path)}, ${safePyLiteral(spec.query)})`);
|
|
1486
|
+
lines.push(spec.hadSensitiveHeaders
|
|
1487
|
+
? ` headers = apply_optional_auth_header(${safePyLiteral(spec.headers)})`
|
|
1488
|
+
: ` headers = dict(${safePyLiteral(spec.headers)})`);
|
|
1489
|
+
const hasBody = spec.hasBody && spec.method !== "GET" && spec.method !== "HEAD";
|
|
1490
|
+
if (hasBody) {
|
|
1491
|
+
lines.push(` raw_body = ${safePyLiteral(spec.body)}`);
|
|
1492
|
+
lines.push(' body_bytes = (raw_body if isinstance(raw_body, str) else json.dumps(raw_body)).encode("utf-8")');
|
|
1493
|
+
lines.push(' if not isinstance(raw_body, str) and not any(k.lower() == "content-type" for k in headers):');
|
|
1494
|
+
lines.push(' headers["Content-Type"] = "application/json"');
|
|
1495
|
+
}
|
|
1496
|
+
else {
|
|
1497
|
+
lines.push(" body_bytes = None");
|
|
1498
|
+
}
|
|
1499
|
+
lines.push(` status, resp_headers, text, duration_ms = send_http(url, ${safePyLiteral(spec.method)}, headers, body_bytes, ${safePyLiteral(spec.timeoutMs)})`);
|
|
1500
|
+
if (spec.status !== undefined) {
|
|
1501
|
+
if (Array.isArray(spec.status)) {
|
|
1502
|
+
lines.push(` assert status in ${safePyLiteral(spec.status)}, f"unexpected status: {status}"`);
|
|
1503
|
+
}
|
|
1504
|
+
else {
|
|
1505
|
+
lines.push(` assert status == ${safePyLiteral(spec.status)}, f"expected status ${spec.status}, got {status}"`);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
if (spec.maxLatencyMs !== undefined) {
|
|
1509
|
+
lines.push(` assert duration_ms <= ${safePyLiteral(spec.maxLatencyMs)}`);
|
|
1510
|
+
}
|
|
1511
|
+
for (const [hdrKey, hdrVal] of Object.entries(spec.expectedHeaders)) {
|
|
1512
|
+
lines.push(` hdr_actual = resp_headers.get(${safePyLiteral(hdrKey.toLowerCase())})`);
|
|
1513
|
+
lines.push(" assert hdr_actual is not None");
|
|
1514
|
+
lines.push(` assert ${safePyLiteral(hdrVal.toLowerCase())} in hdr_actual.lower()`);
|
|
1515
|
+
}
|
|
1516
|
+
if (spec.bodyExact !== undefined) {
|
|
1517
|
+
lines.push(` assert text == ${safePyLiteral(spec.bodyExact)}`);
|
|
1518
|
+
}
|
|
1519
|
+
for (const needle of spec.bodyContains) {
|
|
1520
|
+
lines.push(` assert ${safePyLiteral(needle)} in text`);
|
|
1521
|
+
}
|
|
1522
|
+
const needsJson = spec.jsonSchema !== undefined || spec.jsonSubset !== undefined || spec.jsonPaths.length > 0;
|
|
1523
|
+
if (needsJson) {
|
|
1524
|
+
lines.push(" parsed_json = json.loads(text)");
|
|
1525
|
+
if (spec.jsonSchema !== undefined) {
|
|
1526
|
+
lines.push(` assert validate_json_schema(parsed_json, ${safePyLiteral(spec.jsonSchema)}) == []`);
|
|
1527
|
+
}
|
|
1528
|
+
if (spec.jsonSubset !== undefined) {
|
|
1529
|
+
lines.push(` assert diff_json_subset(${safePyLiteral(spec.jsonSubset)}, parsed_json) == []`);
|
|
1530
|
+
}
|
|
1531
|
+
for (const jp of spec.jsonPaths) {
|
|
1532
|
+
lines.push(` found, val = query_json_path(parsed_json, ${safePyLiteral(jp.path)})`);
|
|
1533
|
+
lines.push(" assert found");
|
|
1534
|
+
if (Object.prototype.hasOwnProperty.call(jp, "equals")) {
|
|
1535
|
+
lines.push(` assert val == ${safePyLiteral(jp.equals)}`);
|
|
1536
|
+
}
|
|
1537
|
+
else if (typeof jp.matches === "string") {
|
|
1538
|
+
lines.push(` assert re.search(${safePyLiteral(jp.matches)}, str(val)) is not None`);
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
else if (spec.type === "web_route") {
|
|
1544
|
+
lines.push(` base = resolve_target("web_route", ${safePyLiteral(spec.defaultTarget)})`);
|
|
1545
|
+
lines.push(` url = build_url(base, ${safePyLiteral(spec.routePath)})`);
|
|
1546
|
+
lines.push(spec.hadSensitiveHeaders
|
|
1547
|
+
? ` headers = apply_optional_auth_header(${safePyLiteral(spec.headers)})`
|
|
1548
|
+
: ` headers = dict(${safePyLiteral(spec.headers)})`);
|
|
1549
|
+
lines.push(` status, _, html, _ = send_http(url, "GET", headers, None, ${safePyLiteral(spec.timeoutMs)})`);
|
|
1550
|
+
if (spec.status !== undefined) {
|
|
1551
|
+
if (Array.isArray(spec.status)) {
|
|
1552
|
+
lines.push(` assert status in ${safePyLiteral(spec.status)}, f"unexpected status: {status}"`);
|
|
1553
|
+
}
|
|
1554
|
+
else {
|
|
1555
|
+
lines.push(` assert status == ${safePyLiteral(spec.status)}, f"expected status ${spec.status}, got {status}"`);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
else {
|
|
1559
|
+
lines.push(" assert 200 <= status < 400");
|
|
1560
|
+
}
|
|
1561
|
+
if (spec.titleContains !== undefined) {
|
|
1562
|
+
lines.push(` assert ${safePyLiteral(spec.titleContains)} in extract_html_title(html)`);
|
|
1563
|
+
}
|
|
1564
|
+
for (const needle of spec.bodyContains) {
|
|
1565
|
+
lines.push(` assert ${safePyLiteral(needle)} in html`);
|
|
1566
|
+
}
|
|
1567
|
+
for (const lm of spec.landmarks) {
|
|
1568
|
+
if (lm.required === false)
|
|
1569
|
+
continue;
|
|
1570
|
+
lines.push(` assert check_html_landmark(html, ${safePyLiteral(lm.tag)}, ${safePyLiteral(lm.textContains ?? "")})`);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
else {
|
|
1574
|
+
// repo_exports
|
|
1575
|
+
lines.push(` root = Path(resolve_target("repo_exports", ${safePyLiteral(spec.defaultTarget)})).resolve()`);
|
|
1576
|
+
lines.push(" assert root.is_dir()");
|
|
1577
|
+
for (const rel of spec.filesPresent) {
|
|
1578
|
+
lines.push(` assert (root / ${safePyLiteral(rel)}).exists()`);
|
|
1579
|
+
}
|
|
1580
|
+
if (spec.exports.length > 0 && spec.modulePath) {
|
|
1581
|
+
lines.push(` mod_file = root / ${safePyLiteral(spec.modulePath)}`);
|
|
1582
|
+
lines.push(" assert mod_file.is_file()");
|
|
1583
|
+
lines.push(' exported = scan_exports(mod_file.read_text(encoding="utf-8"))');
|
|
1584
|
+
for (const exp of spec.exports) {
|
|
1585
|
+
lines.push(` assert ${safePyLiteral(exp.name)} in exported`);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
lines.push("");
|
|
1590
|
+
}
|
|
1591
|
+
return lines.join("\n");
|
|
1592
|
+
}
|
|
1593
|
+
function generateShell(contract, specs, skippedIds, options, includeSkippedComments) {
|
|
1594
|
+
const defaultTarget = resolveDefaultTargetForContract(contract, options.target);
|
|
1595
|
+
const lines = [];
|
|
1596
|
+
lines.push("#!/usr/bin/env bash");
|
|
1597
|
+
lines.push("set -euo pipefail");
|
|
1598
|
+
lines.push("");
|
|
1599
|
+
lines.push(...buildHeaderLines("#", contract, options, skippedIds, includeSkippedComments));
|
|
1600
|
+
lines.push("");
|
|
1601
|
+
lines.push(`DEFAULT_TARGET=${safeShellSingleQuote(defaultTarget)}`);
|
|
1602
|
+
lines.push('if [ -n "${VIBECODE_TARGET:-}" ]; then');
|
|
1603
|
+
lines.push(' DEFAULT_TARGET="$VIBECODE_TARGET"');
|
|
1604
|
+
lines.push("fi");
|
|
1605
|
+
lines.push("");
|
|
1606
|
+
lines.push("PASSED=0");
|
|
1607
|
+
lines.push("FAILED=0");
|
|
1608
|
+
lines.push('TMP_DIR="$(mktemp -d)"');
|
|
1609
|
+
lines.push('trap \'rm -rf "$TMP_DIR"\' EXIT');
|
|
1610
|
+
lines.push("");
|
|
1611
|
+
lines.push("pass_case() {");
|
|
1612
|
+
lines.push(" PASSED=$((PASSED + 1))");
|
|
1613
|
+
lines.push(' printf \'PASS: %s\\n\' "$1"');
|
|
1614
|
+
lines.push("}");
|
|
1615
|
+
lines.push("");
|
|
1616
|
+
lines.push("fail_case() {");
|
|
1617
|
+
lines.push(" FAILED=$((FAILED + 1))");
|
|
1618
|
+
lines.push(' printf \'FAIL: %s (%s)\\n\' "$1" "$2" >&2');
|
|
1619
|
+
lines.push("}");
|
|
1620
|
+
lines.push("");
|
|
1621
|
+
lines.push("resolve_target() {");
|
|
1622
|
+
lines.push(' local kind="$1"');
|
|
1623
|
+
lines.push(' local fallback="$2"');
|
|
1624
|
+
lines.push(' case "$kind" in');
|
|
1625
|
+
lines.push(' command) if [ -n "${VIBECODE_CLI_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_CLI_TARGET"; return; fi ;;');
|
|
1626
|
+
lines.push(' http) if [ -n "${VIBECODE_API_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_API_TARGET"; return; fi');
|
|
1627
|
+
lines.push(' if [ -n "${VIBECODE_HTTP_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_HTTP_TARGET"; return; fi ;;');
|
|
1628
|
+
lines.push(' web_route) if [ -n "${VIBECODE_WEB_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_WEB_TARGET"; return; fi');
|
|
1629
|
+
lines.push(' if [ -n "${VIBECODE_API_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_API_TARGET"; return; fi');
|
|
1630
|
+
lines.push(' if [ -n "${VIBECODE_HTTP_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_HTTP_TARGET"; return; fi ;;');
|
|
1631
|
+
lines.push(' repo_exports) if [ -n "${VIBECODE_REPO_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_REPO_TARGET"; return; fi ;;');
|
|
1632
|
+
lines.push(" esac");
|
|
1633
|
+
lines.push(' if [ -n "${VIBECODE_TARGET:-}" ]; then printf \'%s\' "$VIBECODE_TARGET"; return; fi');
|
|
1634
|
+
lines.push(' if [ -n "$fallback" ]; then printf \'%s\' "$fallback"; return; fi');
|
|
1635
|
+
lines.push(' printf \'%s\' "$DEFAULT_TARGET"');
|
|
1636
|
+
lines.push("}");
|
|
1637
|
+
lines.push("");
|
|
1638
|
+
specs.forEach((spec, idx) => {
|
|
1639
|
+
const fnName = `run_case_${idx + 1}`;
|
|
1640
|
+
const safeLabel = safeShellSingleQuote(sanitizeComment(`${spec.id}: ${spec.description}`));
|
|
1641
|
+
lines.push(`# ${sanitizeComment(`${spec.id}: ${spec.description}`)}`);
|
|
1642
|
+
lines.push(`${fnName}() {`);
|
|
1643
|
+
lines.push(` local label=${safeLabel}`);
|
|
1644
|
+
if (spec.type === "command") {
|
|
1645
|
+
lines.push(` local target="$(resolve_target 'command' ${safeShellSingleQuote(spec.defaultTarget)})"`);
|
|
1646
|
+
lines.push(' local out_file="$TMP_DIR/stdout.txt"');
|
|
1647
|
+
lines.push(' local err_file="$TMP_DIR/stderr.txt"');
|
|
1648
|
+
lines.push(' local -a cmd_tokens=()');
|
|
1649
|
+
lines.push(' read -r -a cmd_tokens <<< "$target"');
|
|
1650
|
+
lines.push(" if [ ${#cmd_tokens[@]} -eq 0 ]; then fail_case \"$label\" 'empty command target'; return; fi");
|
|
1651
|
+
for (const arg of spec.args) {
|
|
1652
|
+
lines.push(` cmd_tokens+=(${safeShellSingleQuote(arg)})`);
|
|
1653
|
+
}
|
|
1654
|
+
lines.push(" local rc=0");
|
|
1655
|
+
lines.push(" set +e");
|
|
1656
|
+
const envPrefixParts = Object.entries(spec.env).map(([k, v]) => `${safeShellSingleQuote(`${k}=${v}`)}`);
|
|
1657
|
+
const runLine = envPrefixParts.length > 0
|
|
1658
|
+
? `env ${envPrefixParts.join(" ")} "\${cmd_tokens[@]}"`
|
|
1659
|
+
: '"${cmd_tokens[@]}"';
|
|
1660
|
+
if (spec.stdin !== null) {
|
|
1661
|
+
lines.push(` printf '%s' ${safeShellSingleQuote(spec.stdin)} | ${runLine} >"$out_file" 2>"$err_file"`);
|
|
1662
|
+
}
|
|
1663
|
+
else {
|
|
1664
|
+
lines.push(` ${runLine} >"$out_file" 2>"$err_file"`);
|
|
1665
|
+
}
|
|
1666
|
+
lines.push(" rc=$?");
|
|
1667
|
+
lines.push(" set -e");
|
|
1668
|
+
if (spec.exitCode !== undefined) {
|
|
1669
|
+
if (Array.isArray(spec.exitCode)) {
|
|
1670
|
+
const checks = spec.exitCode.map((c) => `[ "$rc" -ne ${safeShellSingleQuote(String(c))} ]`).join(" && ");
|
|
1671
|
+
lines.push(` if ${checks}; then fail_case "$label" "unexpected exit code $rc"; return; fi`);
|
|
1672
|
+
}
|
|
1673
|
+
else {
|
|
1674
|
+
lines.push(` if [ "$rc" -ne ${safeShellSingleQuote(String(spec.exitCode))} ]; then fail_case "$label" "expected exit code ${spec.exitCode}, got $rc"; return; fi`);
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
if (spec.stdoutExact !== undefined) {
|
|
1678
|
+
lines.push(' local actual_out="$(cat "$out_file")"');
|
|
1679
|
+
lines.push(` if [ "$actual_out" != ${safeShellSingleQuote(spec.stdoutExact)} ]; then fail_case "$label" 'stdoutExact mismatch'; return; fi`);
|
|
1680
|
+
}
|
|
1681
|
+
for (const needle of spec.stdoutContains) {
|
|
1682
|
+
lines.push(` if ! grep -Fq -- ${safeShellSingleQuote(needle)} "$out_file"; then fail_case "$label" 'stdout missing substring'; return; fi`);
|
|
1683
|
+
}
|
|
1684
|
+
for (const needle of spec.stdoutNotContains) {
|
|
1685
|
+
lines.push(` if grep -Fq -- ${safeShellSingleQuote(needle)} "$out_file"; then fail_case "$label" 'stdout contained forbidden substring'; return; fi`);
|
|
1686
|
+
}
|
|
1687
|
+
for (const pattern of spec.stdoutRegex) {
|
|
1688
|
+
lines.push(` if ! grep -Eq -- ${safeShellSingleQuote(pattern)} "$out_file"; then fail_case "$label" 'stdout regex mismatch'; return; fi`);
|
|
1689
|
+
}
|
|
1690
|
+
if (spec.stderrExact !== undefined) {
|
|
1691
|
+
lines.push(' local actual_err="$(cat "$err_file")"');
|
|
1692
|
+
lines.push(` if [ "$actual_err" != ${safeShellSingleQuote(spec.stderrExact)} ]; then fail_case "$label" 'stderrExact mismatch'; return; fi`);
|
|
1693
|
+
}
|
|
1694
|
+
for (const needle of spec.stderrContains) {
|
|
1695
|
+
lines.push(` if ! grep -Fq -- ${safeShellSingleQuote(needle)} "$err_file"; then fail_case "$label" 'stderr missing substring'; return; fi`);
|
|
1696
|
+
}
|
|
1697
|
+
if (spec.goldenStdout !== undefined) {
|
|
1698
|
+
lines.push(' local actual_golden="$(cat "$out_file")"');
|
|
1699
|
+
lines.push(` if [ "$actual_golden" != ${safeShellSingleQuote(spec.goldenStdout.replace(/\r\n/g, "\n").replace(/\n$/, ""))} ]; then fail_case "$label" 'goldenStdout mismatch'; return; fi`);
|
|
1700
|
+
}
|
|
1701
|
+
lines.push(' pass_case "$label"');
|
|
1702
|
+
}
|
|
1703
|
+
else if (spec.type === "http") {
|
|
1704
|
+
lines.push(` local base="$(resolve_target 'http' ${safeShellSingleQuote(spec.defaultTarget)})"`);
|
|
1705
|
+
const qs = new URLSearchParams(spec.query).toString();
|
|
1706
|
+
const relPath = qs ? (spec.path.includes("?") ? `${spec.path}&${qs}` : `${spec.path}?${qs}`) : spec.path;
|
|
1707
|
+
lines.push(` local req_path=${safeShellSingleQuote(relPath)}`);
|
|
1708
|
+
lines.push(' local url=""');
|
|
1709
|
+
lines.push(' case "$req_path" in');
|
|
1710
|
+
lines.push(' http://*|https://*) url="$req_path" ;;');
|
|
1711
|
+
lines.push(' *) url="${base%/}/${req_path#/}" ;;');
|
|
1712
|
+
lines.push(" esac");
|
|
1713
|
+
lines.push(' local body_file="$TMP_DIR/http_body.txt"');
|
|
1714
|
+
lines.push(' local hdr_file="$TMP_DIR/http_headers.txt"');
|
|
1715
|
+
lines.push(` local -a curl_args=('-sS' '-X' ${safeShellSingleQuote(spec.method)} '-D' "$hdr_file" '-o' "$body_file" '-w' '%{http_code}')`);
|
|
1716
|
+
for (const [k, v] of Object.entries(spec.headers)) {
|
|
1717
|
+
lines.push(` curl_args+=('-H' ${safeShellSingleQuote(`${k}: ${v}`)})`);
|
|
1718
|
+
}
|
|
1719
|
+
if (spec.hadSensitiveHeaders) {
|
|
1720
|
+
lines.push(' if [ -n "${VIBECODE_AUTH_HEADER:-}" ]; then');
|
|
1721
|
+
lines.push(' case "${VIBECODE_AUTH_HEADER}" in');
|
|
1722
|
+
lines.push(' *:*) curl_args+=(\'-H\' "${VIBECODE_AUTH_HEADER}") ;;');
|
|
1723
|
+
lines.push(' *) curl_args+=(\'-H\' "Authorization: ${VIBECODE_AUTH_HEADER}") ;;');
|
|
1724
|
+
lines.push(" esac");
|
|
1725
|
+
lines.push(" fi");
|
|
1726
|
+
}
|
|
1727
|
+
const hasBody = spec.hasBody && spec.method !== "GET" && spec.method !== "HEAD";
|
|
1728
|
+
if (hasBody) {
|
|
1729
|
+
const serializedBody = typeof spec.body === "string" ? spec.body : JSON.stringify(spec.body);
|
|
1730
|
+
if (typeof spec.body !== "string" && !Object.keys(spec.headers).some((k) => k.toLowerCase() === "content-type")) {
|
|
1731
|
+
lines.push(" curl_args+=('-H' 'Content-Type: application/json')");
|
|
1732
|
+
}
|
|
1733
|
+
lines.push(` curl_args+=('--data-raw' ${safeShellSingleQuote(serializedBody)})`);
|
|
1734
|
+
}
|
|
1735
|
+
lines.push(' local status=""');
|
|
1736
|
+
lines.push(' status="$(curl "${curl_args[@]}" "$url")" || { fail_case "$label" \'curl request failed\'; return; }');
|
|
1737
|
+
if (spec.status !== undefined) {
|
|
1738
|
+
if (Array.isArray(spec.status)) {
|
|
1739
|
+
const checks = spec.status.map((s) => `[ "$status" != ${safeShellSingleQuote(String(s))} ]`).join(" && ");
|
|
1740
|
+
lines.push(` if ${checks}; then fail_case "$label" "unexpected status $status"; return; fi`);
|
|
1741
|
+
}
|
|
1742
|
+
else {
|
|
1743
|
+
lines.push(` if [ "$status" != ${safeShellSingleQuote(String(spec.status))} ]; then fail_case "$label" "expected status ${spec.status}, got $status"; return; fi`);
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
for (const [hdrKey, hdrVal] of Object.entries(spec.expectedHeaders)) {
|
|
1747
|
+
lines.push(` if ! grep -Fiq -- ${safeShellSingleQuote(`${hdrKey}:`)} "$hdr_file" || ! grep -Fiq -- ${safeShellSingleQuote(hdrVal)} "$hdr_file"; then fail_case "$label" 'expected header mismatch'; return; fi`);
|
|
1748
|
+
}
|
|
1749
|
+
if (spec.bodyExact !== undefined) {
|
|
1750
|
+
lines.push(' local actual_body="$(cat "$body_file")"');
|
|
1751
|
+
lines.push(` if [ "$actual_body" != ${safeShellSingleQuote(spec.bodyExact)} ]; then fail_case "$label" 'bodyExact mismatch'; return; fi`);
|
|
1752
|
+
}
|
|
1753
|
+
for (const needle of spec.bodyContains) {
|
|
1754
|
+
lines.push(` if ! grep -Fq -- ${safeShellSingleQuote(needle)} "$body_file"; then fail_case "$label" 'body missing substring'; return; fi`);
|
|
1755
|
+
}
|
|
1756
|
+
lines.push(' pass_case "$label"');
|
|
1757
|
+
}
|
|
1758
|
+
else if (spec.type === "web_route") {
|
|
1759
|
+
lines.push(` local base="$(resolve_target 'web_route' ${safeShellSingleQuote(spec.defaultTarget)})"`);
|
|
1760
|
+
lines.push(` local req_path=${safeShellSingleQuote(spec.routePath)}`);
|
|
1761
|
+
lines.push(' local url=""');
|
|
1762
|
+
lines.push(' case "$req_path" in');
|
|
1763
|
+
lines.push(' http://*|https://*) url="$req_path" ;;');
|
|
1764
|
+
lines.push(' *) url="${base%/}/${req_path#/}" ;;');
|
|
1765
|
+
lines.push(" esac");
|
|
1766
|
+
lines.push(' local html_file="$TMP_DIR/web_body.html"');
|
|
1767
|
+
lines.push(' local -a curl_args=(\'-sSL\' \'-o\' "$html_file" \'-w\' \'%{http_code}\')');
|
|
1768
|
+
for (const [k, v] of Object.entries(spec.headers)) {
|
|
1769
|
+
lines.push(` curl_args+=('-H' ${safeShellSingleQuote(`${k}: ${v}`)})`);
|
|
1770
|
+
}
|
|
1771
|
+
if (spec.hadSensitiveHeaders) {
|
|
1772
|
+
lines.push(' if [ -n "${VIBECODE_AUTH_HEADER:-}" ]; then');
|
|
1773
|
+
lines.push(' case "${VIBECODE_AUTH_HEADER}" in');
|
|
1774
|
+
lines.push(' *:*) curl_args+=(\'-H\' "${VIBECODE_AUTH_HEADER}") ;;');
|
|
1775
|
+
lines.push(' *) curl_args+=(\'-H\' "Authorization: ${VIBECODE_AUTH_HEADER}") ;;');
|
|
1776
|
+
lines.push(" esac");
|
|
1777
|
+
lines.push(" fi");
|
|
1778
|
+
}
|
|
1779
|
+
lines.push(' local status=""');
|
|
1780
|
+
lines.push(' status="$(curl "${curl_args[@]}" "$url")" || { fail_case "$label" \'curl request failed\'; return; }');
|
|
1781
|
+
if (spec.status !== undefined) {
|
|
1782
|
+
if (Array.isArray(spec.status)) {
|
|
1783
|
+
const checks = spec.status.map((s) => `[ "$status" != ${safeShellSingleQuote(String(s))} ]`).join(" && ");
|
|
1784
|
+
lines.push(` if ${checks}; then fail_case "$label" "unexpected status $status"; return; fi`);
|
|
1785
|
+
}
|
|
1786
|
+
else {
|
|
1787
|
+
lines.push(` if [ "$status" != ${safeShellSingleQuote(String(spec.status))} ]; then fail_case "$label" "expected status ${spec.status}, got $status"; return; fi`);
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
else {
|
|
1791
|
+
lines.push(' if [ "$status" -lt 200 ] || [ "$status" -ge 400 ]; then fail_case "$label" "expected 2xx/3xx status, got $status"; return; fi');
|
|
1792
|
+
}
|
|
1793
|
+
if (spec.titleContains !== undefined) {
|
|
1794
|
+
lines.push(` if ! grep -Fiq -- ${safeShellSingleQuote(spec.titleContains)} "$html_file"; then fail_case "$label" 'title missing expected text'; return; fi`);
|
|
1795
|
+
}
|
|
1796
|
+
for (const needle of spec.bodyContains) {
|
|
1797
|
+
lines.push(` if ! grep -Fq -- ${safeShellSingleQuote(needle)} "$html_file"; then fail_case "$label" 'html missing substring'; return; fi`);
|
|
1798
|
+
}
|
|
1799
|
+
for (const lm of spec.landmarks) {
|
|
1800
|
+
if (lm.required === false)
|
|
1801
|
+
continue;
|
|
1802
|
+
const safeTag = lm.tag.replace(/[^a-zA-Z0-9_-]/g, "");
|
|
1803
|
+
if (safeTag) {
|
|
1804
|
+
lines.push(` if ! grep -Eiq -- ${safeShellSingleQuote(`<${safeTag}\\b`)} "$html_file"; then fail_case "$label" 'missing HTML landmark'; return; fi`);
|
|
1805
|
+
}
|
|
1806
|
+
if (lm.textContains) {
|
|
1807
|
+
lines.push(` if ! grep -Fq -- ${safeShellSingleQuote(lm.textContains)} "$html_file"; then fail_case "$label" 'landmark text missing'; return; fi`);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
lines.push(' pass_case "$label"');
|
|
1811
|
+
}
|
|
1812
|
+
else {
|
|
1813
|
+
// repo_exports
|
|
1814
|
+
lines.push(` local root="$(resolve_target 'repo_exports' ${safeShellSingleQuote(spec.defaultTarget)})"`);
|
|
1815
|
+
lines.push(' if [ ! -d "$root" ]; then fail_case "$label" \'repo target directory missing\'; return; fi');
|
|
1816
|
+
for (const rel of spec.filesPresent) {
|
|
1817
|
+
lines.push(` if [ ! -e "$root/"${safeShellSingleQuote(rel)} ]; then fail_case "$label" 'missing expected file'; return; fi`);
|
|
1818
|
+
}
|
|
1819
|
+
if (spec.exports.length > 0 && spec.modulePath) {
|
|
1820
|
+
lines.push(` local mod_file="$root/"${safeShellSingleQuote(spec.modulePath)}`);
|
|
1821
|
+
lines.push(' if [ ! -f "$mod_file" ]; then fail_case "$label" \'module file missing\'; return; fi');
|
|
1822
|
+
for (const exp of spec.exports) {
|
|
1823
|
+
lines.push(` if ! grep -Fq -- ${safeShellSingleQuote(exp.name)} "$mod_file"; then fail_case "$label" 'missing expected export'; return; fi`);
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
lines.push(' pass_case "$label"');
|
|
1827
|
+
}
|
|
1828
|
+
lines.push("}");
|
|
1829
|
+
lines.push("");
|
|
1830
|
+
});
|
|
1831
|
+
specs.forEach((_spec, idx) => {
|
|
1832
|
+
lines.push(`run_case_${idx + 1}`);
|
|
1833
|
+
});
|
|
1834
|
+
lines.push("");
|
|
1835
|
+
lines.push('printf \'Summary: %d passed, %d failed\\n\' "$PASSED" "$FAILED"');
|
|
1836
|
+
lines.push('if [ "$FAILED" -gt 0 ]; then exit 1; fi');
|
|
1837
|
+
lines.push("");
|
|
1838
|
+
return lines.join("\n");
|
|
1839
|
+
}
|
|
1840
|
+
export function exportContractTests(contract, options = {}) {
|
|
1841
|
+
validateContractInput(contract);
|
|
1842
|
+
const formatRaw = options.format ?? "node-test";
|
|
1843
|
+
if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
|
|
1844
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported test export format: ${String(formatRaw)}. Expected one of: node-test, vitest, pytest, shell, playwright.`);
|
|
1845
|
+
}
|
|
1846
|
+
const format = formatRaw;
|
|
1847
|
+
const includeSkippedComments = options.includeSkippedComments !== false;
|
|
1848
|
+
if (format === "playwright") {
|
|
1849
|
+
return exportPlaywrightTests(contract, {
|
|
1850
|
+
target: options.target,
|
|
1851
|
+
contractPath: options.contractPath,
|
|
1852
|
+
includeSkippedComments
|
|
1853
|
+
});
|
|
1854
|
+
}
|
|
1855
|
+
let excludedHoldoutCount = 0;
|
|
1856
|
+
const skippedIds = [];
|
|
1857
|
+
const specs = [];
|
|
1858
|
+
for (const inv of contract.invariants) {
|
|
1859
|
+
if (inv.holdout === true) {
|
|
1860
|
+
excludedHoldoutCount += 1;
|
|
1861
|
+
continue;
|
|
1862
|
+
}
|
|
1863
|
+
const prepared = prepareInvariant(contract, inv, options.target);
|
|
1864
|
+
if (!prepared) {
|
|
1865
|
+
skippedIds.push(inv.id);
|
|
1866
|
+
continue;
|
|
1867
|
+
}
|
|
1868
|
+
specs.push(prepared);
|
|
1869
|
+
}
|
|
1870
|
+
let code;
|
|
1871
|
+
if (format === "node-test" || format === "vitest") {
|
|
1872
|
+
code = generateNodeTestOrVitest(format, contract, specs, skippedIds, options, includeSkippedComments);
|
|
1873
|
+
}
|
|
1874
|
+
else if (format === "pytest") {
|
|
1875
|
+
code = generatePytest(contract, specs, skippedIds, options, includeSkippedComments);
|
|
1876
|
+
}
|
|
1877
|
+
else {
|
|
1878
|
+
code = generateShell(contract, specs, skippedIds, options, includeSkippedComments);
|
|
1879
|
+
}
|
|
1880
|
+
return {
|
|
1881
|
+
format,
|
|
1882
|
+
suggestedFilename: SUGGESTED_FILENAMES[format],
|
|
1883
|
+
code,
|
|
1884
|
+
exportedCount: specs.length,
|
|
1885
|
+
skippedCount: skippedIds.length,
|
|
1886
|
+
skippedIds,
|
|
1887
|
+
excludedHoldoutCount
|
|
1888
|
+
};
|
|
1889
|
+
}
|
|
1890
|
+
export function writeExportedTests(contract, options) {
|
|
1891
|
+
if (!isRecord(options) || typeof options.outPath !== "string" || !options.outPath.trim() || options.outPath.includes("\0")) {
|
|
1892
|
+
throw new VibecodeError("CONTRACT_INVALID", "writeExportedTests requires a valid non-empty outPath.");
|
|
1893
|
+
}
|
|
1894
|
+
const result = exportContractTests(contract, options);
|
|
1895
|
+
const resolvedOut = path.resolve(options.outPath.trim());
|
|
1896
|
+
const parentDir = path.dirname(resolvedOut);
|
|
1897
|
+
fs.mkdirSync(parentDir, { recursive: true });
|
|
1898
|
+
const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
1899
|
+
try {
|
|
1900
|
+
fs.writeFileSync(tmpPath, result.code, "utf8");
|
|
1901
|
+
fs.renameSync(tmpPath, resolvedOut);
|
|
1902
|
+
}
|
|
1903
|
+
catch (err) {
|
|
1904
|
+
try {
|
|
1905
|
+
if (fs.existsSync(tmpPath)) {
|
|
1906
|
+
fs.rmSync(tmpPath, { force: true });
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
catch {
|
|
1910
|
+
// ignore cleanup error
|
|
1911
|
+
}
|
|
1912
|
+
throw err;
|
|
1913
|
+
}
|
|
1914
|
+
return {
|
|
1915
|
+
...result,
|
|
1916
|
+
outPath: resolvedOut
|
|
1917
|
+
};
|
|
1918
|
+
}
|