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,1722 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import { VibecodeError } from "./errors.js";
|
|
4
|
+
import { queryJsonPath, validateJsonSchema } from "./schema.js";
|
|
5
|
+
import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
|
|
6
|
+
const MAX_SYNTH_DEPTH = 16;
|
|
7
|
+
const MAX_SYNTH_NODES = 1024;
|
|
8
|
+
const MAX_ARRAY_ITEMS = 32;
|
|
9
|
+
const MAX_OBJECT_EXTRA_KEYS = 32;
|
|
10
|
+
const MAX_JSON_PATH_INDEX = 64;
|
|
11
|
+
const MAX_PRETTY_ROUTES = 20;
|
|
12
|
+
const MAX_PRETTY_SKIPPED = 12;
|
|
13
|
+
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
14
|
+
const EXTRA_SENSITIVE_HEADER_RE = /^(?:api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|x[_-]access[_-]token|x[_-]session[_-]token|x[_-]secret|x[_-](?:csrf|xsrf)[_-]token|csrf[_-]token|xsrf[_-]token|authorization|proxy[_-]authorization|cookie|set[_-]cookie)$/i;
|
|
15
|
+
const EXTRA_SENSITIVE_QUERY_RE = /^(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|x[_-]api[_-]key|x[_-]auth[_-]token|x[_-]access[_-]token|x[_-]session[_-]token|x[_-]secret|x[_-](?:csrf|xsrf)[_-]token|csrf[_-]token|xsrf[_-]token|secret|client[_-]?secret|password|passwd|passphrase|auth|jwt|session[_-]?id|sig|signature|private[_-]?key|authorization|cookie|credential|credentials)$/i;
|
|
16
|
+
const SENSITIVE_OBJECT_KEY_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credentials?|bearer)/i;
|
|
17
|
+
const HEADER_AUTH_VALUE_RE = /\b(?:bearer|basic|token|digest|apikey)\s+\S+/i;
|
|
18
|
+
const SAFE_HEADER_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
19
|
+
const TRANSPORT_SKIP_HEADERS = new Set(["content-length", "transfer-encoding", "connection"]);
|
|
20
|
+
const VAULT_PATH_RE = /(?:[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
|
|
21
|
+
const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
|
|
22
|
+
const URL_CREDENTIALS_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s@"'`<>]+)@/g;
|
|
23
|
+
const INLINE_BEARER_RE = /\b(Bearer)\s+\S+/gi;
|
|
24
|
+
const INLINE_BASIC_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{4,}/gi;
|
|
25
|
+
const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey)\s+[A-Za-z0-9._~+/=:-]{6,}/gi;
|
|
26
|
+
const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9._~+/=:-]{6,}|[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*)/gi;
|
|
27
|
+
const SAFE_HTML_TAG_RE = /^[a-z][a-z0-9-]*$/;
|
|
28
|
+
const DISALLOWED_LANDMARK_TAGS = new Set(["html", "head", "body", "title", "script", "style", "iframe", "object", "embed"]);
|
|
29
|
+
const LANDMARK_EXTRACTOR_TAGS = new Set(["header", "nav", "main", "footer", "h1", "h2", "form", "table", "ul"]);
|
|
30
|
+
const ANSI = {
|
|
31
|
+
reset: "\x1b[0m",
|
|
32
|
+
bold: "\x1b[1m",
|
|
33
|
+
dim: "\x1b[2m",
|
|
34
|
+
red: "\x1b[31m",
|
|
35
|
+
green: "\x1b[32m",
|
|
36
|
+
yellow: "\x1b[33m",
|
|
37
|
+
cyan: "\x1b[36m"
|
|
38
|
+
};
|
|
39
|
+
function isPlainObject(v) {
|
|
40
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
41
|
+
}
|
|
42
|
+
function hasOwn(obj, key) {
|
|
43
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
44
|
+
}
|
|
45
|
+
function isForbiddenKey(key) {
|
|
46
|
+
return FORBIDDEN_KEYS.has(key);
|
|
47
|
+
}
|
|
48
|
+
function isSensitiveHeaderName(name) {
|
|
49
|
+
const trimmed = String(name).trim();
|
|
50
|
+
return isSensitiveHeader(trimmed) || EXTRA_SENSITIVE_HEADER_RE.test(trimmed);
|
|
51
|
+
}
|
|
52
|
+
function isSensitiveQueryName(name) {
|
|
53
|
+
const trimmed = String(name).trim();
|
|
54
|
+
return (isSensitiveQueryParam(trimmed) ||
|
|
55
|
+
EXTRA_SENSITIVE_QUERY_RE.test(trimmed) ||
|
|
56
|
+
isSensitiveHeaderName(trimmed));
|
|
57
|
+
}
|
|
58
|
+
function sanitizeUrlInText(rawUrl) {
|
|
59
|
+
const withoutVault = rawUrl.replace(VAULT_PATH_RE, "[REDACTED_VAULT]");
|
|
60
|
+
const withoutAuth = withoutVault.replace(URL_CREDENTIALS_RE, "$1[REDACTED]@");
|
|
61
|
+
try {
|
|
62
|
+
const parsed = new URL(withoutAuth);
|
|
63
|
+
parsed.username = "";
|
|
64
|
+
parsed.password = "";
|
|
65
|
+
const safeParams = new URLSearchParams();
|
|
66
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
67
|
+
const trimmedKey = k.trim();
|
|
68
|
+
if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
|
|
69
|
+
continue;
|
|
70
|
+
if (HEADER_AUTH_VALUE_RE.test(v))
|
|
71
|
+
continue;
|
|
72
|
+
safeParams.append(k, v.replace(VAULT_PATH_RE, "[REDACTED_VAULT]"));
|
|
73
|
+
}
|
|
74
|
+
const serialized = safeParams.toString();
|
|
75
|
+
parsed.search = serialized ? `?${serialized}` : "";
|
|
76
|
+
parsed.hash = "";
|
|
77
|
+
return parsed.toString();
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return withoutAuth.replace(/#.*$/, "");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function sanitizeText(raw) {
|
|
84
|
+
return raw
|
|
85
|
+
.replace(/\0/g, "")
|
|
86
|
+
.replace(VAULT_PATH_RE, "[REDACTED_VAULT]")
|
|
87
|
+
.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match))
|
|
88
|
+
.replace(URL_CREDENTIALS_RE, "$1[REDACTED]@")
|
|
89
|
+
.replace(INLINE_BEARER_RE, "$1 [REDACTED]")
|
|
90
|
+
.replace(INLINE_BASIC_RE, "$1 [REDACTED]")
|
|
91
|
+
.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]")
|
|
92
|
+
.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
|
|
93
|
+
}
|
|
94
|
+
function sanitizeSingleLine(raw) {
|
|
95
|
+
return sanitizeText(raw)
|
|
96
|
+
.replace(/[\r\n\0\u2028\u2029]+/g, " ")
|
|
97
|
+
.trim();
|
|
98
|
+
}
|
|
99
|
+
function sanitizeHeaderValue(raw) {
|
|
100
|
+
return sanitizeSingleLine(raw)
|
|
101
|
+
.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "")
|
|
102
|
+
.replace(/[^\x09\x20-\x7e\xa0-\xff]+/g, "")
|
|
103
|
+
.replace(/\s+/g, " ")
|
|
104
|
+
.trim();
|
|
105
|
+
}
|
|
106
|
+
function sanitizeJsonValue(value, depth = 0, seen = new WeakSet()) {
|
|
107
|
+
if (depth > MAX_SYNTH_DEPTH)
|
|
108
|
+
return null;
|
|
109
|
+
if (typeof value === "string")
|
|
110
|
+
return sanitizeText(value);
|
|
111
|
+
if (value === null || typeof value === "boolean")
|
|
112
|
+
return value;
|
|
113
|
+
if (typeof value === "number")
|
|
114
|
+
return Number.isFinite(value) ? value : 0;
|
|
115
|
+
if (typeof value !== "object")
|
|
116
|
+
return null;
|
|
117
|
+
if (seen.has(value))
|
|
118
|
+
return null;
|
|
119
|
+
seen.add(value);
|
|
120
|
+
try {
|
|
121
|
+
if (Array.isArray(value)) {
|
|
122
|
+
return value.slice(0, MAX_ARRAY_ITEMS).map((item) => sanitizeJsonValue(item, depth + 1, seen));
|
|
123
|
+
}
|
|
124
|
+
const out = {};
|
|
125
|
+
for (const [k, v] of Object.entries(value)) {
|
|
126
|
+
if (isForbiddenKey(k) || v === undefined)
|
|
127
|
+
continue;
|
|
128
|
+
if (SENSITIVE_OBJECT_KEY_RE.test(k) && typeof v === "string") {
|
|
129
|
+
out[k] = "[REDACTED]";
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
out[k] = sanitizeJsonValue(v, depth + 1, seen);
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
seen.delete(value);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function escapeHtmlText(raw) {
|
|
141
|
+
return raw
|
|
142
|
+
.replace(/&/g, "&")
|
|
143
|
+
.replace(/</g, "<")
|
|
144
|
+
.replace(/>/g, ">");
|
|
145
|
+
}
|
|
146
|
+
function escapeHtmlAttr(raw) {
|
|
147
|
+
return escapeHtmlText(raw)
|
|
148
|
+
.replace(/"/g, """)
|
|
149
|
+
.replace(/'/g, "'");
|
|
150
|
+
}
|
|
151
|
+
function parsePathAndQuery(rawPath, extraQuery) {
|
|
152
|
+
let pathname = "/";
|
|
153
|
+
const query = {};
|
|
154
|
+
const trimmed = typeof rawPath === "string" ? rawPath.trim() : "";
|
|
155
|
+
if (trimmed) {
|
|
156
|
+
try {
|
|
157
|
+
let parsed;
|
|
158
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
159
|
+
parsed = new URL(trimmed);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
const cleanStart = trimmed.startsWith("/") ? trimmed.replace(/^\/+/, "/") : `/${trimmed}`;
|
|
163
|
+
parsed = new URL(cleanStart, "http://mock.local");
|
|
164
|
+
}
|
|
165
|
+
pathname = sanitizeText(parsed.pathname || "/");
|
|
166
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
167
|
+
if (!k || isForbiddenKey(k) || isSensitiveQueryName(k))
|
|
168
|
+
continue;
|
|
169
|
+
query[k] = sanitizeText(v);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
const sanitizedRaw = sanitizeText(trimmed
|
|
174
|
+
.replace(URL_CREDENTIALS_RE, "$1")
|
|
175
|
+
.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*/i, ""));
|
|
176
|
+
const noHash = sanitizedRaw.split("#")[0] || "/";
|
|
177
|
+
const qIdx = noHash.indexOf("?");
|
|
178
|
+
const pathPart = (qIdx >= 0 ? noHash.slice(0, qIdx) : noHash).replace(/[\r\n\0\x00-\x1f\x7f]+/g, "");
|
|
179
|
+
pathname = sanitizeText(pathPart.startsWith("/") ? pathPart.replace(/^\/+/, "/") : `/${pathPart || ""}`);
|
|
180
|
+
if (qIdx >= 0) {
|
|
181
|
+
const params = new URLSearchParams(noHash.slice(qIdx + 1));
|
|
182
|
+
for (const [k, v] of params.entries()) {
|
|
183
|
+
if (!k || isForbiddenKey(k) || isSensitiveQueryName(k))
|
|
184
|
+
continue;
|
|
185
|
+
query[k] = sanitizeText(v);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (isPlainObject(extraQuery)) {
|
|
191
|
+
for (const [k, v] of Object.entries(extraQuery)) {
|
|
192
|
+
if (!k || isForbiddenKey(k) || isSensitiveQueryName(k) || v === undefined || v === null)
|
|
193
|
+
continue;
|
|
194
|
+
query[k] = sanitizeText(String(v));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return { path: pathname || "/", query };
|
|
198
|
+
}
|
|
199
|
+
function resolveExpectedStatus(expectedStatus) {
|
|
200
|
+
if (typeof expectedStatus === "number" && Number.isInteger(expectedStatus) && expectedStatus >= 100 && expectedStatus <= 599) {
|
|
201
|
+
return expectedStatus;
|
|
202
|
+
}
|
|
203
|
+
if (Array.isArray(expectedStatus)) {
|
|
204
|
+
for (const candidate of expectedStatus) {
|
|
205
|
+
if (typeof candidate === "number" && Number.isInteger(candidate) && candidate >= 100 && candidate <= 599) {
|
|
206
|
+
return candidate;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return 200;
|
|
211
|
+
}
|
|
212
|
+
function sanitizeResponseHeaders(rawHeaders) {
|
|
213
|
+
const out = {};
|
|
214
|
+
if (!isPlainObject(rawHeaders))
|
|
215
|
+
return out;
|
|
216
|
+
for (const [rawKey, rawVal] of Object.entries(rawHeaders)) {
|
|
217
|
+
if (isForbiddenKey(rawKey) || rawVal === undefined || rawVal === null)
|
|
218
|
+
continue;
|
|
219
|
+
const key = rawKey.trim().toLowerCase();
|
|
220
|
+
if (!key || isForbiddenKey(key) || !SAFE_HEADER_NAME_RE.test(key))
|
|
221
|
+
continue;
|
|
222
|
+
if (TRANSPORT_SKIP_HEADERS.has(key))
|
|
223
|
+
continue;
|
|
224
|
+
if (isSensitiveHeaderName(key))
|
|
225
|
+
continue;
|
|
226
|
+
const valStr = String(rawVal);
|
|
227
|
+
if (HEADER_AUTH_VALUE_RE.test(valStr))
|
|
228
|
+
continue;
|
|
229
|
+
const cleaned = sanitizeHeaderValue(valStr);
|
|
230
|
+
if (!cleaned)
|
|
231
|
+
continue;
|
|
232
|
+
out[key] = cleaned;
|
|
233
|
+
}
|
|
234
|
+
return out;
|
|
235
|
+
}
|
|
236
|
+
function canonicalJson(v, seen = new WeakSet()) {
|
|
237
|
+
if (v === null)
|
|
238
|
+
return "null";
|
|
239
|
+
if (typeof v === "boolean" || typeof v === "string")
|
|
240
|
+
return JSON.stringify(v);
|
|
241
|
+
if (typeof v === "number")
|
|
242
|
+
return Number.isFinite(v) ? JSON.stringify(v) : "null";
|
|
243
|
+
if (typeof v === "undefined")
|
|
244
|
+
return "undefined";
|
|
245
|
+
if (Array.isArray(v)) {
|
|
246
|
+
if (seen.has(v))
|
|
247
|
+
return '"[Circular]"';
|
|
248
|
+
seen.add(v);
|
|
249
|
+
const parts = v.map((item) => (item === undefined ? "null" : canonicalJson(item, seen)));
|
|
250
|
+
seen.delete(v);
|
|
251
|
+
return `[${parts.join(",")}]`;
|
|
252
|
+
}
|
|
253
|
+
if (typeof v === "object") {
|
|
254
|
+
if (seen.has(v))
|
|
255
|
+
return '"[Circular]"';
|
|
256
|
+
seen.add(v);
|
|
257
|
+
const obj = v;
|
|
258
|
+
const keys = Object.keys(obj).sort();
|
|
259
|
+
const parts = [];
|
|
260
|
+
for (const k of keys) {
|
|
261
|
+
if (obj[k] === undefined)
|
|
262
|
+
continue;
|
|
263
|
+
parts.push(`${JSON.stringify(k)}:${canonicalJson(obj[k], seen)}`);
|
|
264
|
+
}
|
|
265
|
+
seen.delete(v);
|
|
266
|
+
return `{${parts.join(",")}}`;
|
|
267
|
+
}
|
|
268
|
+
return JSON.stringify(String(v));
|
|
269
|
+
}
|
|
270
|
+
function mergeTwoSchemas(a, b, depth = 0) {
|
|
271
|
+
if (depth > MAX_SYNTH_DEPTH)
|
|
272
|
+
return { ...a };
|
|
273
|
+
const merged = {};
|
|
274
|
+
// Merge types
|
|
275
|
+
const typesA = a.type === undefined ? null : (Array.isArray(a.type) ? a.type : [a.type]);
|
|
276
|
+
const typesB = b.type === undefined ? null : (Array.isArray(b.type) ? b.type : [b.type]);
|
|
277
|
+
if (typesA && typesB) {
|
|
278
|
+
const inter = typesA.filter((t) => typesB.includes(t));
|
|
279
|
+
if (inter.length === 1)
|
|
280
|
+
merged.type = inter[0];
|
|
281
|
+
else if (inter.length > 1)
|
|
282
|
+
merged.type = inter;
|
|
283
|
+
else if (typesA.includes("integer") && typesB.includes("number"))
|
|
284
|
+
merged.type = "integer";
|
|
285
|
+
else if (typesB.includes("integer") && typesA.includes("number"))
|
|
286
|
+
merged.type = "integer";
|
|
287
|
+
else
|
|
288
|
+
merged.type = b.type;
|
|
289
|
+
}
|
|
290
|
+
else if (typesA) {
|
|
291
|
+
merged.type = a.type;
|
|
292
|
+
}
|
|
293
|
+
else if (typesB) {
|
|
294
|
+
merged.type = b.type;
|
|
295
|
+
}
|
|
296
|
+
if (a.const !== undefined)
|
|
297
|
+
merged.const = a.const;
|
|
298
|
+
else if (b.const !== undefined)
|
|
299
|
+
merged.const = b.const;
|
|
300
|
+
if (Array.isArray(a.enum) && Array.isArray(b.enum)) {
|
|
301
|
+
const bSet = new Set(b.enum.map((item) => canonicalJson(item)));
|
|
302
|
+
const inter = a.enum.filter((item) => bSet.has(canonicalJson(item)));
|
|
303
|
+
merged.enum = inter.length > 0 ? inter : a.enum;
|
|
304
|
+
}
|
|
305
|
+
else if (Array.isArray(a.enum)) {
|
|
306
|
+
merged.enum = a.enum;
|
|
307
|
+
}
|
|
308
|
+
else if (Array.isArray(b.enum)) {
|
|
309
|
+
merged.enum = b.enum;
|
|
310
|
+
}
|
|
311
|
+
if (typeof a.format === "string")
|
|
312
|
+
merged.format = a.format;
|
|
313
|
+
if (typeof b.format === "string")
|
|
314
|
+
merged.format = b.format;
|
|
315
|
+
if (typeof a.pattern === "string")
|
|
316
|
+
merged.pattern = a.pattern;
|
|
317
|
+
if (typeof b.pattern === "string")
|
|
318
|
+
merged.pattern = b.pattern;
|
|
319
|
+
if (typeof a.minLength === "number" || typeof b.minLength === "number") {
|
|
320
|
+
merged.minLength = Math.max(a.minLength ?? 0, b.minLength ?? 0);
|
|
321
|
+
}
|
|
322
|
+
if (typeof a.maxLength === "number" || typeof b.maxLength === "number") {
|
|
323
|
+
merged.maxLength = Math.min(a.maxLength ?? Infinity, b.maxLength ?? Infinity);
|
|
324
|
+
}
|
|
325
|
+
if (typeof a.minimum === "number" || typeof b.minimum === "number") {
|
|
326
|
+
merged.minimum = Math.max(a.minimum ?? -Infinity, b.minimum ?? -Infinity);
|
|
327
|
+
}
|
|
328
|
+
if (typeof a.maximum === "number" || typeof b.maximum === "number") {
|
|
329
|
+
merged.maximum = Math.min(a.maximum ?? Infinity, b.maximum ?? Infinity);
|
|
330
|
+
}
|
|
331
|
+
if (typeof a.exclusiveMinimum === "number" || typeof b.exclusiveMinimum === "number") {
|
|
332
|
+
merged.exclusiveMinimum = Math.max(a.exclusiveMinimum ?? -Infinity, b.exclusiveMinimum ?? -Infinity);
|
|
333
|
+
}
|
|
334
|
+
if (typeof a.exclusiveMaximum === "number" || typeof b.exclusiveMaximum === "number") {
|
|
335
|
+
merged.exclusiveMaximum = Math.min(a.exclusiveMaximum ?? Infinity, b.exclusiveMaximum ?? Infinity);
|
|
336
|
+
}
|
|
337
|
+
if (typeof b.multipleOf === "number")
|
|
338
|
+
merged.multipleOf = b.multipleOf;
|
|
339
|
+
else if (typeof a.multipleOf === "number")
|
|
340
|
+
merged.multipleOf = a.multipleOf;
|
|
341
|
+
if (typeof a.minItems === "number" || typeof b.minItems === "number") {
|
|
342
|
+
merged.minItems = Math.max(a.minItems ?? 0, b.minItems ?? 0);
|
|
343
|
+
}
|
|
344
|
+
if (typeof a.maxItems === "number" || typeof b.maxItems === "number") {
|
|
345
|
+
merged.maxItems = Math.min(a.maxItems ?? Infinity, b.maxItems ?? Infinity);
|
|
346
|
+
}
|
|
347
|
+
if (a.uniqueItems === true || b.uniqueItems === true) {
|
|
348
|
+
merged.uniqueItems = true;
|
|
349
|
+
}
|
|
350
|
+
if (isPlainObject(a.items) && isPlainObject(b.items)) {
|
|
351
|
+
merged.items = mergeTwoSchemas(a.items, b.items, depth + 1);
|
|
352
|
+
}
|
|
353
|
+
else if (b.items !== undefined) {
|
|
354
|
+
merged.items = b.items;
|
|
355
|
+
}
|
|
356
|
+
else if (a.items !== undefined) {
|
|
357
|
+
merged.items = a.items;
|
|
358
|
+
}
|
|
359
|
+
if (typeof a.minProperties === "number" || typeof b.minProperties === "number") {
|
|
360
|
+
merged.minProperties = Math.max(a.minProperties ?? 0, b.minProperties ?? 0);
|
|
361
|
+
}
|
|
362
|
+
if (typeof a.maxProperties === "number" || typeof b.maxProperties === "number") {
|
|
363
|
+
merged.maxProperties = Math.min(a.maxProperties ?? Infinity, b.maxProperties ?? Infinity);
|
|
364
|
+
}
|
|
365
|
+
if (Array.isArray(a.required) || Array.isArray(b.required)) {
|
|
366
|
+
const reqSet = new Set();
|
|
367
|
+
for (const k of a.required || []) {
|
|
368
|
+
if (typeof k === "string" && !isForbiddenKey(k))
|
|
369
|
+
reqSet.add(k);
|
|
370
|
+
}
|
|
371
|
+
for (const k of b.required || []) {
|
|
372
|
+
if (typeof k === "string" && !isForbiddenKey(k))
|
|
373
|
+
reqSet.add(k);
|
|
374
|
+
}
|
|
375
|
+
merged.required = [...reqSet];
|
|
376
|
+
}
|
|
377
|
+
if (isPlainObject(a.properties) || isPlainObject(b.properties)) {
|
|
378
|
+
const props = {};
|
|
379
|
+
if (isPlainObject(a.properties)) {
|
|
380
|
+
for (const [k, sub] of Object.entries(a.properties)) {
|
|
381
|
+
if (isForbiddenKey(k))
|
|
382
|
+
continue;
|
|
383
|
+
props[k] = sub;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
if (isPlainObject(b.properties)) {
|
|
387
|
+
for (const [k, sub] of Object.entries(b.properties)) {
|
|
388
|
+
if (isForbiddenKey(k))
|
|
389
|
+
continue;
|
|
390
|
+
if (hasOwn(props, k) && isPlainObject(props[k]) && isPlainObject(sub)) {
|
|
391
|
+
props[k] = mergeTwoSchemas(props[k], sub, depth + 1);
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
props[k] = sub;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
merged.properties = props;
|
|
399
|
+
}
|
|
400
|
+
if (a.additionalProperties === false || b.additionalProperties === false) {
|
|
401
|
+
merged.additionalProperties = false;
|
|
402
|
+
}
|
|
403
|
+
else if (isPlainObject(a.additionalProperties) && isPlainObject(b.additionalProperties)) {
|
|
404
|
+
merged.additionalProperties = mergeTwoSchemas(a.additionalProperties, b.additionalProperties, depth + 1);
|
|
405
|
+
}
|
|
406
|
+
else if (b.additionalProperties !== undefined) {
|
|
407
|
+
merged.additionalProperties = b.additionalProperties;
|
|
408
|
+
}
|
|
409
|
+
else if (a.additionalProperties !== undefined) {
|
|
410
|
+
merged.additionalProperties = a.additionalProperties;
|
|
411
|
+
}
|
|
412
|
+
if (a.nullable === true && b.nullable === true)
|
|
413
|
+
merged.nullable = true;
|
|
414
|
+
if (b.example !== undefined)
|
|
415
|
+
merged.example = b.example;
|
|
416
|
+
else if (a.example !== undefined)
|
|
417
|
+
merged.example = a.example;
|
|
418
|
+
if (b.default !== undefined)
|
|
419
|
+
merged.default = b.default;
|
|
420
|
+
else if (a.default !== undefined)
|
|
421
|
+
merged.default = a.default;
|
|
422
|
+
if (Array.isArray(b.anyOf))
|
|
423
|
+
merged.anyOf = b.anyOf;
|
|
424
|
+
else if (Array.isArray(a.anyOf))
|
|
425
|
+
merged.anyOf = a.anyOf;
|
|
426
|
+
if (Array.isArray(b.oneOf))
|
|
427
|
+
merged.oneOf = b.oneOf;
|
|
428
|
+
else if (Array.isArray(a.oneOf))
|
|
429
|
+
merged.oneOf = a.oneOf;
|
|
430
|
+
if (isPlainObject(b.not))
|
|
431
|
+
merged.not = b.not;
|
|
432
|
+
else if (isPlainObject(a.not))
|
|
433
|
+
merged.not = a.not;
|
|
434
|
+
return merged;
|
|
435
|
+
}
|
|
436
|
+
function flattenAllOf(schema, depth = 0) {
|
|
437
|
+
if (depth > MAX_SYNTH_DEPTH || !Array.isArray(schema.allOf) || schema.allOf.length === 0) {
|
|
438
|
+
return schema;
|
|
439
|
+
}
|
|
440
|
+
const rest = {};
|
|
441
|
+
for (const [k, v] of Object.entries(schema)) {
|
|
442
|
+
if (k === "allOf" || isForbiddenKey(k))
|
|
443
|
+
continue;
|
|
444
|
+
rest[k] = v;
|
|
445
|
+
}
|
|
446
|
+
let acc = rest;
|
|
447
|
+
for (const sub of schema.allOf) {
|
|
448
|
+
if (!isPlainObject(sub))
|
|
449
|
+
continue;
|
|
450
|
+
const flatSub = flattenAllOf(sub, depth + 1);
|
|
451
|
+
acc = mergeTwoSchemas(acc, flatSub, depth + 1);
|
|
452
|
+
}
|
|
453
|
+
return acc;
|
|
454
|
+
}
|
|
455
|
+
function synthesizeStringForRegex(pattern) {
|
|
456
|
+
let re;
|
|
457
|
+
try {
|
|
458
|
+
re = new RegExp(pattern);
|
|
459
|
+
}
|
|
460
|
+
catch {
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
const probeCandidates = [
|
|
464
|
+
"sample",
|
|
465
|
+
"active",
|
|
466
|
+
"ok",
|
|
467
|
+
"1",
|
|
468
|
+
"0",
|
|
469
|
+
"123",
|
|
470
|
+
"abc",
|
|
471
|
+
"ABC",
|
|
472
|
+
"item-1",
|
|
473
|
+
"11111111-1111-4111-8111-111111111111",
|
|
474
|
+
"user@example.com",
|
|
475
|
+
"2026-01-15",
|
|
476
|
+
"2026-01-15T00:00:00.000Z",
|
|
477
|
+
"https://example.com/resource",
|
|
478
|
+
"127.0.0.1"
|
|
479
|
+
];
|
|
480
|
+
for (const c of probeCandidates) {
|
|
481
|
+
if (re.test(c))
|
|
482
|
+
return c;
|
|
483
|
+
}
|
|
484
|
+
// Lightweight deterministic sample generator for simple anchored regex patterns
|
|
485
|
+
let src = pattern.trim();
|
|
486
|
+
if (src.startsWith("^"))
|
|
487
|
+
src = src.slice(1);
|
|
488
|
+
if (src.endsWith("$"))
|
|
489
|
+
src = src.slice(0, -1);
|
|
490
|
+
// Pick first top-level alternation branch if simple
|
|
491
|
+
if (src.startsWith("(") && src.endsWith(")")) {
|
|
492
|
+
const inner = src.slice(1, -1);
|
|
493
|
+
if (!inner.includes("(") && !inner.includes(")")) {
|
|
494
|
+
src = inner.split("|")[0] ?? inner;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
else if (!src.includes("(") && src.includes("|")) {
|
|
498
|
+
src = src.split("|")[0] ?? src;
|
|
499
|
+
}
|
|
500
|
+
let out = "";
|
|
501
|
+
let i = 0;
|
|
502
|
+
while (i < src.length && out.length < 64) {
|
|
503
|
+
let token = "";
|
|
504
|
+
const ch = src[i];
|
|
505
|
+
if (ch === "\\" && i + 1 < src.length) {
|
|
506
|
+
const next = src[i + 1];
|
|
507
|
+
i += 2;
|
|
508
|
+
if (next === "d")
|
|
509
|
+
token = "1";
|
|
510
|
+
else if (next === "w")
|
|
511
|
+
token = "a";
|
|
512
|
+
else if (next === "s")
|
|
513
|
+
token = " ";
|
|
514
|
+
else if (next === "D")
|
|
515
|
+
token = "a";
|
|
516
|
+
else if (next === "W")
|
|
517
|
+
token = "-";
|
|
518
|
+
else if (next === "S")
|
|
519
|
+
token = "a";
|
|
520
|
+
else
|
|
521
|
+
token = next;
|
|
522
|
+
}
|
|
523
|
+
else if (ch === "[") {
|
|
524
|
+
const end = src.indexOf("]", i + 1);
|
|
525
|
+
if (end > i) {
|
|
526
|
+
const cls = src.slice(i + 1, end);
|
|
527
|
+
i = end + 1;
|
|
528
|
+
if (cls.startsWith("^"))
|
|
529
|
+
token = "a";
|
|
530
|
+
else if (cls.includes("0-9"))
|
|
531
|
+
token = "1";
|
|
532
|
+
else if (cls.includes("a-z") || cls.includes("a-f"))
|
|
533
|
+
token = "a";
|
|
534
|
+
else if (cls.includes("A-Z") || cls.includes("A-F"))
|
|
535
|
+
token = "A";
|
|
536
|
+
else
|
|
537
|
+
token = cls[0] || "a";
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
i += 1;
|
|
541
|
+
token = "a";
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
else if (ch === "(") {
|
|
545
|
+
const end = src.indexOf(")", i + 1);
|
|
546
|
+
if (end > i) {
|
|
547
|
+
const group = src.slice(i + 1, end).replace(/^\?:/, "");
|
|
548
|
+
i = end + 1;
|
|
549
|
+
token = (group.split("|")[0] || "a").replace(/\\(.)/g, "$1");
|
|
550
|
+
}
|
|
551
|
+
else {
|
|
552
|
+
i += 1;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
else if (ch === ".") {
|
|
556
|
+
i += 1;
|
|
557
|
+
token = "a";
|
|
558
|
+
}
|
|
559
|
+
else if (ch === "^" || ch === "$") {
|
|
560
|
+
i += 1;
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
else {
|
|
564
|
+
i += 1;
|
|
565
|
+
token = ch;
|
|
566
|
+
}
|
|
567
|
+
// Read optional quantifier
|
|
568
|
+
let repeat = 1;
|
|
569
|
+
if (i < src.length) {
|
|
570
|
+
const q = src[i];
|
|
571
|
+
if (q === "+") {
|
|
572
|
+
repeat = 1;
|
|
573
|
+
i += 1;
|
|
574
|
+
}
|
|
575
|
+
else if (q === "*" || q === "?") {
|
|
576
|
+
repeat = 1;
|
|
577
|
+
i += 1;
|
|
578
|
+
}
|
|
579
|
+
else if (q === "{") {
|
|
580
|
+
const closeBrace = src.indexOf("}", i + 1);
|
|
581
|
+
if (closeBrace > i) {
|
|
582
|
+
const spec = src.slice(i + 1, closeBrace);
|
|
583
|
+
const m = /^(\d+)(?:,(\d*))?$/.exec(spec);
|
|
584
|
+
if (m) {
|
|
585
|
+
repeat = Math.min(Math.max(Number(m[1]), 0), 16);
|
|
586
|
+
i = closeBrace + 1;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (i < src.length && src[i] === "?")
|
|
591
|
+
i += 1; // non-greedy modifier
|
|
592
|
+
}
|
|
593
|
+
out += token.repeat(repeat);
|
|
594
|
+
}
|
|
595
|
+
return re.test(out) ? out : null;
|
|
596
|
+
}
|
|
597
|
+
function synthesizeString(schema, variantIndex) {
|
|
598
|
+
if (typeof schema.format === "string") {
|
|
599
|
+
switch (schema.format) {
|
|
600
|
+
case "uuid": {
|
|
601
|
+
if (variantIndex === 0)
|
|
602
|
+
return "11111111-1111-4111-8111-111111111111";
|
|
603
|
+
const tail = (variantIndex + 1).toString(16).padStart(12, "0").slice(-12);
|
|
604
|
+
return `11111111-1111-4111-8111-${tail}`;
|
|
605
|
+
}
|
|
606
|
+
case "email":
|
|
607
|
+
return variantIndex === 0 ? "user@example.com" : `user${variantIndex}@example.com`;
|
|
608
|
+
case "date": {
|
|
609
|
+
if (variantIndex === 0)
|
|
610
|
+
return "2026-01-15";
|
|
611
|
+
const offset = 14 + variantIndex;
|
|
612
|
+
const day = (offset % 28) + 1;
|
|
613
|
+
const month = (Math.floor(offset / 28) % 12) + 1;
|
|
614
|
+
return `2026-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
|
|
615
|
+
}
|
|
616
|
+
case "date-time": {
|
|
617
|
+
if (variantIndex === 0)
|
|
618
|
+
return "2026-01-15T00:00:00.000Z";
|
|
619
|
+
const sec = variantIndex % 60;
|
|
620
|
+
const min = Math.floor(variantIndex / 60) % 60;
|
|
621
|
+
const hr = Math.floor(variantIndex / 3600) % 24;
|
|
622
|
+
return `2026-01-15T${String(hr).padStart(2, "0")}:${String(min).padStart(2, "0")}:${String(sec).padStart(2, "0")}.000Z`;
|
|
623
|
+
}
|
|
624
|
+
case "uri":
|
|
625
|
+
return variantIndex === 0 ? "https://example.com/resource" : `https://example.com/resource/${variantIndex}`;
|
|
626
|
+
case "ipv4":
|
|
627
|
+
return variantIndex === 0 ? "127.0.0.1" : `127.0.0.${(variantIndex % 254) + 1}`;
|
|
628
|
+
default:
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (typeof schema.pattern === "string") {
|
|
633
|
+
const matched = synthesizeStringForRegex(schema.pattern);
|
|
634
|
+
if (matched !== null) {
|
|
635
|
+
return matched;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
let value = variantIndex === 0 ? "sample" : `sample-${variantIndex}`;
|
|
639
|
+
const minLen = typeof schema.minLength === "number" && Number.isFinite(schema.minLength) && schema.minLength > 0
|
|
640
|
+
? Math.min(Math.ceil(schema.minLength), 256)
|
|
641
|
+
: 0;
|
|
642
|
+
const maxLen = typeof schema.maxLength === "number" && Number.isFinite(schema.maxLength) && schema.maxLength >= 0
|
|
643
|
+
? Math.floor(schema.maxLength)
|
|
644
|
+
: Infinity;
|
|
645
|
+
if (value.length < minLen) {
|
|
646
|
+
const padChar = String.fromCharCode(97 + (variantIndex % 26));
|
|
647
|
+
value = value + padChar.repeat(minLen - value.length);
|
|
648
|
+
}
|
|
649
|
+
if (value.length > maxLen) {
|
|
650
|
+
if (maxLen === 0) {
|
|
651
|
+
value = "";
|
|
652
|
+
}
|
|
653
|
+
else if (variantIndex > 0) {
|
|
654
|
+
const suffix = variantIndex.toString(36);
|
|
655
|
+
if (suffix.length >= maxLen) {
|
|
656
|
+
value = suffix.slice(-maxLen);
|
|
657
|
+
}
|
|
658
|
+
else {
|
|
659
|
+
value = value.slice(0, maxLen - suffix.length) + suffix;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
else {
|
|
663
|
+
value = value.slice(0, maxLen);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return value;
|
|
667
|
+
}
|
|
668
|
+
function synthesizeNumber(schema, isInt, variantIndex) {
|
|
669
|
+
const hasMin = typeof schema.minimum === "number" && Number.isFinite(schema.minimum);
|
|
670
|
+
const hasMax = typeof schema.maximum === "number" && Number.isFinite(schema.maximum);
|
|
671
|
+
const hasExMin = typeof schema.exclusiveMinimum === "number" && Number.isFinite(schema.exclusiveMinimum);
|
|
672
|
+
const hasExMax = typeof schema.exclusiveMaximum === "number" && Number.isFinite(schema.exclusiveMaximum);
|
|
673
|
+
const step = typeof schema.multipleOf === "number" && Number.isFinite(schema.multipleOf) && schema.multipleOf > 0
|
|
674
|
+
? schema.multipleOf
|
|
675
|
+
: undefined;
|
|
676
|
+
let lo = -Infinity;
|
|
677
|
+
if (hasMin)
|
|
678
|
+
lo = Math.max(lo, schema.minimum);
|
|
679
|
+
if (hasExMin)
|
|
680
|
+
lo = Math.max(lo, isInt ? Math.floor(schema.exclusiveMinimum) + 1 : schema.exclusiveMinimum);
|
|
681
|
+
let hi = Infinity;
|
|
682
|
+
if (hasMax)
|
|
683
|
+
hi = Math.min(hi, schema.maximum);
|
|
684
|
+
if (hasExMax)
|
|
685
|
+
hi = Math.min(hi, isInt ? Math.ceil(schema.exclusiveMaximum) - 1 : schema.exclusiveMaximum);
|
|
686
|
+
const isValid = (n) => {
|
|
687
|
+
if (!Number.isFinite(n))
|
|
688
|
+
return false;
|
|
689
|
+
if (isInt && !Number.isInteger(n))
|
|
690
|
+
return false;
|
|
691
|
+
if (hasMin && n < schema.minimum)
|
|
692
|
+
return false;
|
|
693
|
+
if (hasMax && n > schema.maximum)
|
|
694
|
+
return false;
|
|
695
|
+
if (hasExMin && n <= schema.exclusiveMinimum)
|
|
696
|
+
return false;
|
|
697
|
+
if (hasExMax && n >= schema.exclusiveMaximum)
|
|
698
|
+
return false;
|
|
699
|
+
if (step !== undefined) {
|
|
700
|
+
const q = n / step;
|
|
701
|
+
if (!Number.isFinite(q) || Math.abs(q - Math.round(q)) > 1e-9)
|
|
702
|
+
return false;
|
|
703
|
+
}
|
|
704
|
+
return true;
|
|
705
|
+
};
|
|
706
|
+
if (step !== undefined) {
|
|
707
|
+
const unitStep = isInt && !Number.isInteger(step) ? Math.max(1, Math.round(step)) : step;
|
|
708
|
+
let kLo = Number.isFinite(lo) ? Math.ceil((lo - 1e-9) / unitStep) : 0;
|
|
709
|
+
if (hasExMin && kLo * unitStep <= schema.exclusiveMinimum)
|
|
710
|
+
kLo += 1;
|
|
711
|
+
let kHi = Number.isFinite(hi) ? Math.floor((hi + 1e-9) / unitStep) : Infinity;
|
|
712
|
+
if (hasExMax && Number.isFinite(kHi) && kHi * unitStep >= schema.exclusiveMaximum)
|
|
713
|
+
kHi -= 1;
|
|
714
|
+
let k;
|
|
715
|
+
if (Number.isFinite(lo) && Number.isFinite(hi)) {
|
|
716
|
+
k = Math.min(kLo + variantIndex, kHi);
|
|
717
|
+
if (k < kLo)
|
|
718
|
+
k = kLo;
|
|
719
|
+
}
|
|
720
|
+
else if (Number.isFinite(lo)) {
|
|
721
|
+
k = kLo + variantIndex;
|
|
722
|
+
}
|
|
723
|
+
else if (Number.isFinite(hi)) {
|
|
724
|
+
k = kHi - variantIndex;
|
|
725
|
+
}
|
|
726
|
+
else {
|
|
727
|
+
k = variantIndex === 0 ? 1 : variantIndex + 1;
|
|
728
|
+
}
|
|
729
|
+
const candidate = isInt ? Math.round(k * unitStep) : Number((k * unitStep).toPrecision(12));
|
|
730
|
+
if (isValid(candidate))
|
|
731
|
+
return candidate;
|
|
732
|
+
}
|
|
733
|
+
let candidate;
|
|
734
|
+
if (Number.isFinite(lo) && Number.isFinite(hi)) {
|
|
735
|
+
if (isInt) {
|
|
736
|
+
const intLo = Math.ceil(lo);
|
|
737
|
+
const intHi = Math.floor(hi);
|
|
738
|
+
candidate = Math.min(intLo + variantIndex, intHi);
|
|
739
|
+
}
|
|
740
|
+
else {
|
|
741
|
+
const span = hi - lo;
|
|
742
|
+
if (hasExMin || hasExMax) {
|
|
743
|
+
const frac = (variantIndex + 1) / (variantIndex + 2);
|
|
744
|
+
candidate = lo + span * frac;
|
|
745
|
+
}
|
|
746
|
+
else {
|
|
747
|
+
candidate = variantIndex === 0 ? lo : Math.min(lo + variantIndex, hi);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
else if (Number.isFinite(lo)) {
|
|
752
|
+
const base = isInt ? Math.ceil(lo) : hasExMin ? lo + 1 : lo;
|
|
753
|
+
candidate = base + variantIndex;
|
|
754
|
+
}
|
|
755
|
+
else if (Number.isFinite(hi)) {
|
|
756
|
+
const base = isInt ? Math.floor(hi) : hasExMax ? hi - 1 : hi;
|
|
757
|
+
candidate = base - variantIndex;
|
|
758
|
+
}
|
|
759
|
+
else {
|
|
760
|
+
candidate = isInt ? variantIndex + 1 : variantIndex + 1;
|
|
761
|
+
}
|
|
762
|
+
if (isInt)
|
|
763
|
+
candidate = Math.round(candidate);
|
|
764
|
+
return candidate;
|
|
765
|
+
}
|
|
766
|
+
function inferSchemaType(schema, isRoot) {
|
|
767
|
+
if (typeof schema.type === "string")
|
|
768
|
+
return schema.type;
|
|
769
|
+
if (Array.isArray(schema.type) && schema.type.length > 0) {
|
|
770
|
+
const primary = schema.type.find((t) => t !== "null");
|
|
771
|
+
return primary || schema.type[0] || (isRoot ? "object" : "string");
|
|
772
|
+
}
|
|
773
|
+
if (isPlainObject(schema.properties) ||
|
|
774
|
+
Array.isArray(schema.required) ||
|
|
775
|
+
schema.additionalProperties !== undefined ||
|
|
776
|
+
typeof schema.minProperties === "number" ||
|
|
777
|
+
typeof schema.maxProperties === "number") {
|
|
778
|
+
return "object";
|
|
779
|
+
}
|
|
780
|
+
if (schema.items !== undefined ||
|
|
781
|
+
typeof schema.minItems === "number" ||
|
|
782
|
+
typeof schema.maxItems === "number" ||
|
|
783
|
+
schema.uniqueItems === true) {
|
|
784
|
+
return "array";
|
|
785
|
+
}
|
|
786
|
+
if (typeof schema.minimum === "number" ||
|
|
787
|
+
typeof schema.maximum === "number" ||
|
|
788
|
+
typeof schema.exclusiveMinimum === "number" ||
|
|
789
|
+
typeof schema.exclusiveMaximum === "number" ||
|
|
790
|
+
typeof schema.multipleOf === "number") {
|
|
791
|
+
return "number";
|
|
792
|
+
}
|
|
793
|
+
if (typeof schema.minLength === "number" ||
|
|
794
|
+
typeof schema.maxLength === "number" ||
|
|
795
|
+
typeof schema.pattern === "string" ||
|
|
796
|
+
typeof schema.format === "string") {
|
|
797
|
+
return "string";
|
|
798
|
+
}
|
|
799
|
+
return isRoot ? "object" : "string";
|
|
800
|
+
}
|
|
801
|
+
function cycleFallbackForSchema(rawSchema, isRoot) {
|
|
802
|
+
const primaryType = isPlainObject(rawSchema) ? inferSchemaType(rawSchema, isRoot) : isRoot ? "object" : "string";
|
|
803
|
+
if (primaryType === "object")
|
|
804
|
+
return {};
|
|
805
|
+
if (primaryType === "array")
|
|
806
|
+
return [];
|
|
807
|
+
if (primaryType === "integer" || primaryType === "number")
|
|
808
|
+
return 0;
|
|
809
|
+
if (primaryType === "boolean")
|
|
810
|
+
return false;
|
|
811
|
+
if (primaryType === "null")
|
|
812
|
+
return null;
|
|
813
|
+
return "sample";
|
|
814
|
+
}
|
|
815
|
+
function synthesizeFromJsonSchema(rawSchema, depth = 0, variantIndex = 0, isRoot = true, state = { seen: new WeakSet(), nodes: 0 }) {
|
|
816
|
+
if (depth > MAX_SYNTH_DEPTH ||
|
|
817
|
+
!isPlainObject(rawSchema) ||
|
|
818
|
+
state.nodes >= MAX_SYNTH_NODES ||
|
|
819
|
+
state.seen.has(rawSchema)) {
|
|
820
|
+
return cycleFallbackForSchema(rawSchema, isRoot);
|
|
821
|
+
}
|
|
822
|
+
state.nodes += 1;
|
|
823
|
+
state.seen.add(rawSchema);
|
|
824
|
+
try {
|
|
825
|
+
const schema = flattenAllOf(rawSchema, depth);
|
|
826
|
+
if (schema.const !== undefined) {
|
|
827
|
+
return sanitizeJsonValue(schema.const);
|
|
828
|
+
}
|
|
829
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
830
|
+
const start = variantIndex % schema.enum.length;
|
|
831
|
+
for (let offset = 0; offset < schema.enum.length; offset++) {
|
|
832
|
+
const candidate = sanitizeJsonValue(schema.enum[(start + offset) % schema.enum.length]);
|
|
833
|
+
if (validateJsonSchema(candidate, schema).length === 0) {
|
|
834
|
+
return candidate;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
return sanitizeJsonValue(schema.enum[start]);
|
|
838
|
+
}
|
|
839
|
+
if (variantIndex === 0 && schema.example !== undefined) {
|
|
840
|
+
const candidate = sanitizeJsonValue(schema.example);
|
|
841
|
+
if (validateJsonSchema(candidate, schema).length === 0) {
|
|
842
|
+
return candidate;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
if (variantIndex === 0 && schema.default !== undefined) {
|
|
846
|
+
const candidate = sanitizeJsonValue(schema.default);
|
|
847
|
+
if (validateJsonSchema(candidate, schema).length === 0) {
|
|
848
|
+
return candidate;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
852
|
+
const baseWithoutOneOf = {};
|
|
853
|
+
for (const [k, v] of Object.entries(schema)) {
|
|
854
|
+
if (k === "oneOf" || isForbiddenKey(k))
|
|
855
|
+
continue;
|
|
856
|
+
baseWithoutOneOf[k] = v;
|
|
857
|
+
}
|
|
858
|
+
for (const sub of schema.oneOf) {
|
|
859
|
+
if (!isPlainObject(sub) || state.seen.has(sub))
|
|
860
|
+
continue;
|
|
861
|
+
const combined = mergeTwoSchemas(baseWithoutOneOf, sub, depth + 1);
|
|
862
|
+
const candidate = synthesizeFromJsonSchema(combined, depth + 1, variantIndex, isRoot, state);
|
|
863
|
+
if (validateJsonSchema(candidate, schema).length === 0) {
|
|
864
|
+
return candidate;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
const firstSub = schema.oneOf.find((s) => isPlainObject(s) && !state.seen.has(s));
|
|
868
|
+
if (firstSub) {
|
|
869
|
+
return synthesizeFromJsonSchema(mergeTwoSchemas(baseWithoutOneOf, firstSub, depth + 1), depth + 1, variantIndex, isRoot, state);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
873
|
+
const baseWithoutAnyOf = {};
|
|
874
|
+
for (const [k, v] of Object.entries(schema)) {
|
|
875
|
+
if (k === "anyOf" || isForbiddenKey(k))
|
|
876
|
+
continue;
|
|
877
|
+
baseWithoutAnyOf[k] = v;
|
|
878
|
+
}
|
|
879
|
+
for (const sub of schema.anyOf) {
|
|
880
|
+
if (!isPlainObject(sub) || state.seen.has(sub))
|
|
881
|
+
continue;
|
|
882
|
+
const combined = mergeTwoSchemas(baseWithoutAnyOf, sub, depth + 1);
|
|
883
|
+
const candidate = synthesizeFromJsonSchema(combined, depth + 1, variantIndex, isRoot, state);
|
|
884
|
+
if (validateJsonSchema(candidate, schema).length === 0) {
|
|
885
|
+
return candidate;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
const firstSub = schema.anyOf.find((s) => isPlainObject(s) && !state.seen.has(s));
|
|
889
|
+
if (firstSub) {
|
|
890
|
+
return synthesizeFromJsonSchema(mergeTwoSchemas(baseWithoutAnyOf, firstSub, depth + 1), depth + 1, variantIndex, isRoot, state);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const synthForVariant = (vIdx) => {
|
|
894
|
+
const primaryType = inferSchemaType(schema, isRoot);
|
|
895
|
+
switch (primaryType) {
|
|
896
|
+
case "null":
|
|
897
|
+
return null;
|
|
898
|
+
case "boolean":
|
|
899
|
+
return vIdx % 2 === 0;
|
|
900
|
+
case "integer":
|
|
901
|
+
return synthesizeNumber(schema, true, vIdx);
|
|
902
|
+
case "number":
|
|
903
|
+
return synthesizeNumber(schema, false, vIdx);
|
|
904
|
+
case "string":
|
|
905
|
+
return synthesizeString(schema, vIdx);
|
|
906
|
+
case "array": {
|
|
907
|
+
const minItems = typeof schema.minItems === "number" && Number.isFinite(schema.minItems) && schema.minItems >= 0
|
|
908
|
+
? Math.ceil(schema.minItems)
|
|
909
|
+
: 0;
|
|
910
|
+
const maxItems = typeof schema.maxItems === "number" && Number.isFinite(schema.maxItems) && schema.maxItems >= 0
|
|
911
|
+
? Math.floor(schema.maxItems)
|
|
912
|
+
: Infinity;
|
|
913
|
+
let count = minItems;
|
|
914
|
+
if (count === 0 && maxItems > 0 && schema.items !== undefined) {
|
|
915
|
+
count = 1;
|
|
916
|
+
}
|
|
917
|
+
count = Math.min(count, maxItems, MAX_ARRAY_ITEMS);
|
|
918
|
+
const result = [];
|
|
919
|
+
const seenCanon = new Set();
|
|
920
|
+
for (let i = 0; i < count; i++) {
|
|
921
|
+
const itemSchema = Array.isArray(schema.items)
|
|
922
|
+
? (isPlainObject(schema.items[i]) ? schema.items[i] : {})
|
|
923
|
+
: isPlainObject(schema.items)
|
|
924
|
+
? schema.items
|
|
925
|
+
: { type: "string" };
|
|
926
|
+
let attemptVariant = vIdx * MAX_ARRAY_ITEMS + i;
|
|
927
|
+
let item = synthesizeFromJsonSchema(itemSchema, depth + 1, attemptVariant, false, state);
|
|
928
|
+
if (schema.uniqueItems === true) {
|
|
929
|
+
let tries = 0;
|
|
930
|
+
while (seenCanon.has(canonicalJson(item)) && tries < 16) {
|
|
931
|
+
tries += 1;
|
|
932
|
+
attemptVariant += 1;
|
|
933
|
+
item = synthesizeFromJsonSchema(itemSchema, depth + 1, attemptVariant, false, state);
|
|
934
|
+
}
|
|
935
|
+
seenCanon.add(canonicalJson(item));
|
|
936
|
+
}
|
|
937
|
+
result.push(item);
|
|
938
|
+
}
|
|
939
|
+
return result;
|
|
940
|
+
}
|
|
941
|
+
case "object":
|
|
942
|
+
default: {
|
|
943
|
+
const out = {};
|
|
944
|
+
const declaredProps = isPlainObject(schema.properties) ? schema.properties : {};
|
|
945
|
+
const requiredKeys = Array.isArray(schema.required)
|
|
946
|
+
? schema.required.filter((k) => typeof k === "string" && !isForbiddenKey(k))
|
|
947
|
+
: [];
|
|
948
|
+
const maxProps = typeof schema.maxProperties === "number" && Number.isFinite(schema.maxProperties) && schema.maxProperties >= 0
|
|
949
|
+
? Math.floor(schema.maxProperties)
|
|
950
|
+
: Infinity;
|
|
951
|
+
const minProps = typeof schema.minProperties === "number" && Number.isFinite(schema.minProperties) && schema.minProperties >= 0
|
|
952
|
+
? Math.min(Math.ceil(schema.minProperties), MAX_OBJECT_EXTRA_KEYS)
|
|
953
|
+
: 0;
|
|
954
|
+
for (const key of requiredKeys) {
|
|
955
|
+
if (Object.keys(out).length >= maxProps)
|
|
956
|
+
break;
|
|
957
|
+
if (schema.additionalProperties === false && !hasOwn(declaredProps, key))
|
|
958
|
+
continue;
|
|
959
|
+
const propSchema = hasOwn(declaredProps, key)
|
|
960
|
+
? declaredProps[key]
|
|
961
|
+
: isPlainObject(schema.additionalProperties)
|
|
962
|
+
? schema.additionalProperties
|
|
963
|
+
: { type: "string" };
|
|
964
|
+
out[key] = synthesizeFromJsonSchema(propSchema, depth + 1, vIdx, false, state);
|
|
965
|
+
}
|
|
966
|
+
for (const [key, propSchema] of Object.entries(declaredProps)) {
|
|
967
|
+
if (Object.keys(out).length >= maxProps)
|
|
968
|
+
break;
|
|
969
|
+
if (isForbiddenKey(key) || hasOwn(out, key))
|
|
970
|
+
continue;
|
|
971
|
+
out[key] = synthesizeFromJsonSchema(propSchema, depth + 1, vIdx, false, state);
|
|
972
|
+
}
|
|
973
|
+
if (schema.additionalProperties !== false && Object.keys(out).length < minProps) {
|
|
974
|
+
const extraSchema = isPlainObject(schema.additionalProperties)
|
|
975
|
+
? schema.additionalProperties
|
|
976
|
+
: { type: "string" };
|
|
977
|
+
let idx = 1;
|
|
978
|
+
while (Object.keys(out).length < minProps && Object.keys(out).length < maxProps && idx <= MAX_OBJECT_EXTRA_KEYS) {
|
|
979
|
+
const key = `field_${idx}`;
|
|
980
|
+
idx += 1;
|
|
981
|
+
if (!hasOwn(out, key)) {
|
|
982
|
+
out[key] = synthesizeFromJsonSchema(extraSchema, depth + 1, vIdx + idx, false, state);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
return out;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
let result = synthForVariant(variantIndex);
|
|
991
|
+
if (isPlainObject(schema.not)) {
|
|
992
|
+
for (let attempt = 1; attempt <= 6; attempt++) {
|
|
993
|
+
if (validateJsonSchema(result, schema.not).length > 0)
|
|
994
|
+
break;
|
|
995
|
+
result = synthForVariant(variantIndex + attempt);
|
|
996
|
+
}
|
|
997
|
+
if (validateJsonSchema(result, schema.not).length === 0 && schema.type === undefined) {
|
|
998
|
+
const fallbacks = ["other", 42, true, [], {}];
|
|
999
|
+
for (const fb of fallbacks) {
|
|
1000
|
+
if (validateJsonSchema(fb, schema).length === 0) {
|
|
1001
|
+
result = fb;
|
|
1002
|
+
break;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
return result;
|
|
1008
|
+
}
|
|
1009
|
+
finally {
|
|
1010
|
+
state.seen.delete(rawSchema);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
function deepMergeJson(base, overlay, depth = 0) {
|
|
1014
|
+
if (depth > MAX_SYNTH_DEPTH)
|
|
1015
|
+
return sanitizeJsonValue(overlay);
|
|
1016
|
+
const cleanOverlay = sanitizeJsonValue(overlay);
|
|
1017
|
+
if (Array.isArray(cleanOverlay)) {
|
|
1018
|
+
if (!Array.isArray(base))
|
|
1019
|
+
return cleanOverlay;
|
|
1020
|
+
const merged = base.slice();
|
|
1021
|
+
for (let i = 0; i < cleanOverlay.length; i++) {
|
|
1022
|
+
merged[i] = i < merged.length ? deepMergeJson(merged[i], cleanOverlay[i], depth + 1) : cleanOverlay[i];
|
|
1023
|
+
}
|
|
1024
|
+
return merged;
|
|
1025
|
+
}
|
|
1026
|
+
if (isPlainObject(cleanOverlay)) {
|
|
1027
|
+
const out = isPlainObject(base) ? { ...base } : {};
|
|
1028
|
+
for (const [k, v] of Object.entries(cleanOverlay)) {
|
|
1029
|
+
if (isForbiddenKey(k) || v === undefined)
|
|
1030
|
+
continue;
|
|
1031
|
+
out[k] = hasOwn(out, k) ? deepMergeJson(out[k], v, depth + 1) : v;
|
|
1032
|
+
}
|
|
1033
|
+
return out;
|
|
1034
|
+
}
|
|
1035
|
+
return cleanOverlay;
|
|
1036
|
+
}
|
|
1037
|
+
function tokenizeJsonPath(expr) {
|
|
1038
|
+
if (typeof expr !== "string" || !expr.startsWith("$"))
|
|
1039
|
+
return null;
|
|
1040
|
+
const tokens = [];
|
|
1041
|
+
const re = /\.([A-Za-z_$][A-Za-z0-9_$-]*)|\[(\d+)\]|\[(?:"([^"]*)"|'([^']*)')\]/g;
|
|
1042
|
+
let i = 1;
|
|
1043
|
+
while (i < expr.length) {
|
|
1044
|
+
re.lastIndex = i;
|
|
1045
|
+
const m = re.exec(expr);
|
|
1046
|
+
if (!m || m.index !== i)
|
|
1047
|
+
return null;
|
|
1048
|
+
if (m[1] !== undefined) {
|
|
1049
|
+
if (isForbiddenKey(m[1]))
|
|
1050
|
+
return null;
|
|
1051
|
+
tokens.push(m[1]);
|
|
1052
|
+
}
|
|
1053
|
+
else if (m[2] !== undefined) {
|
|
1054
|
+
const idx = Number(m[2]);
|
|
1055
|
+
if (!Number.isInteger(idx) || idx < 0 || idx > MAX_JSON_PATH_INDEX)
|
|
1056
|
+
return null;
|
|
1057
|
+
tokens.push(idx);
|
|
1058
|
+
}
|
|
1059
|
+
else if (m[3] !== undefined) {
|
|
1060
|
+
if (isForbiddenKey(m[3]))
|
|
1061
|
+
return null;
|
|
1062
|
+
tokens.push(m[3]);
|
|
1063
|
+
}
|
|
1064
|
+
else if (m[4] !== undefined) {
|
|
1065
|
+
if (isForbiddenKey(m[4]))
|
|
1066
|
+
return null;
|
|
1067
|
+
tokens.push(m[4]);
|
|
1068
|
+
}
|
|
1069
|
+
i = re.lastIndex;
|
|
1070
|
+
}
|
|
1071
|
+
return tokens;
|
|
1072
|
+
}
|
|
1073
|
+
function setJsonPathValue(root, tokens, value) {
|
|
1074
|
+
if (tokens.length === 0)
|
|
1075
|
+
return value;
|
|
1076
|
+
const first = tokens[0];
|
|
1077
|
+
let container;
|
|
1078
|
+
if (typeof first === "number") {
|
|
1079
|
+
container = Array.isArray(root) ? root : [];
|
|
1080
|
+
}
|
|
1081
|
+
else {
|
|
1082
|
+
container = isPlainObject(root) ? root : {};
|
|
1083
|
+
}
|
|
1084
|
+
let cur = container;
|
|
1085
|
+
for (let i = 0; i < tokens.length - 1; i++) {
|
|
1086
|
+
const tok = tokens[i];
|
|
1087
|
+
const nextTok = tokens[i + 1];
|
|
1088
|
+
if (typeof tok === "number") {
|
|
1089
|
+
const arr = cur;
|
|
1090
|
+
while (arr.length <= tok)
|
|
1091
|
+
arr.push(null);
|
|
1092
|
+
const existing = arr[tok];
|
|
1093
|
+
if (typeof nextTok === "number") {
|
|
1094
|
+
if (!Array.isArray(existing))
|
|
1095
|
+
arr[tok] = [];
|
|
1096
|
+
}
|
|
1097
|
+
else if (!isPlainObject(existing)) {
|
|
1098
|
+
arr[tok] = {};
|
|
1099
|
+
}
|
|
1100
|
+
cur = arr[tok];
|
|
1101
|
+
}
|
|
1102
|
+
else {
|
|
1103
|
+
const obj = cur;
|
|
1104
|
+
const existing = obj[tok];
|
|
1105
|
+
if (typeof nextTok === "number") {
|
|
1106
|
+
if (!Array.isArray(existing))
|
|
1107
|
+
obj[tok] = [];
|
|
1108
|
+
}
|
|
1109
|
+
else if (!isPlainObject(existing)) {
|
|
1110
|
+
obj[tok] = {};
|
|
1111
|
+
}
|
|
1112
|
+
cur = obj[tok];
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
const last = tokens[tokens.length - 1];
|
|
1116
|
+
if (typeof last === "number") {
|
|
1117
|
+
const arr = cur;
|
|
1118
|
+
while (arr.length <= last)
|
|
1119
|
+
arr.push(null);
|
|
1120
|
+
arr[last] = value;
|
|
1121
|
+
}
|
|
1122
|
+
else {
|
|
1123
|
+
const obj = cur;
|
|
1124
|
+
obj[last] = value;
|
|
1125
|
+
}
|
|
1126
|
+
return container;
|
|
1127
|
+
}
|
|
1128
|
+
function applyJsonPathAssertions(root, assertions) {
|
|
1129
|
+
let current = root;
|
|
1130
|
+
for (const assertion of assertions) {
|
|
1131
|
+
if (!isPlainObject(assertion) || typeof assertion.path !== "string")
|
|
1132
|
+
continue;
|
|
1133
|
+
const tokens = tokenizeJsonPath(assertion.path);
|
|
1134
|
+
if (!tokens)
|
|
1135
|
+
continue;
|
|
1136
|
+
if (hasOwn(assertion, "equals")) {
|
|
1137
|
+
const lastTok = tokens[tokens.length - 1];
|
|
1138
|
+
const rawVal = assertion.equals;
|
|
1139
|
+
const sanitizedVal = typeof lastTok === "string" && SENSITIVE_OBJECT_KEY_RE.test(lastTok) && typeof rawVal === "string"
|
|
1140
|
+
? "[REDACTED]"
|
|
1141
|
+
: sanitizeJsonValue(rawVal);
|
|
1142
|
+
current = setJsonPathValue(current, tokens, sanitizedVal);
|
|
1143
|
+
}
|
|
1144
|
+
else if (hasOwn(assertion, "matches") && typeof assertion.matches === "string") {
|
|
1145
|
+
const existing = queryJsonPath(current, assertion.path);
|
|
1146
|
+
let alreadyMatches = false;
|
|
1147
|
+
if (existing.found) {
|
|
1148
|
+
try {
|
|
1149
|
+
alreadyMatches = new RegExp(assertion.matches).test(String(existing.value));
|
|
1150
|
+
}
|
|
1151
|
+
catch {
|
|
1152
|
+
alreadyMatches = false;
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if (!alreadyMatches) {
|
|
1156
|
+
const synthesized = synthesizeStringForRegex(assertion.matches) ?? "sample";
|
|
1157
|
+
current = setJsonPathValue(current, tokens, sanitizeText(synthesized));
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
else {
|
|
1161
|
+
const existing = queryJsonPath(current, assertion.path);
|
|
1162
|
+
if (!existing.found) {
|
|
1163
|
+
current = setJsonPathValue(current, tokens, "ok");
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
return current;
|
|
1168
|
+
}
|
|
1169
|
+
function inferContentTypeForExactBody(body, headerContentType) {
|
|
1170
|
+
if (headerContentType)
|
|
1171
|
+
return headerContentType;
|
|
1172
|
+
const trimmed = body.trim();
|
|
1173
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
1174
|
+
try {
|
|
1175
|
+
JSON.parse(trimmed);
|
|
1176
|
+
return "application/json; charset=utf-8";
|
|
1177
|
+
}
|
|
1178
|
+
catch {
|
|
1179
|
+
// not valid JSON
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return "text/plain; charset=utf-8";
|
|
1183
|
+
}
|
|
1184
|
+
function synthesizeHttpResponse(invariant, status, headers) {
|
|
1185
|
+
const expected = invariant.expected || {};
|
|
1186
|
+
const headerContentType = headers["content-type"];
|
|
1187
|
+
if (typeof expected.bodyExact === "string") {
|
|
1188
|
+
const rawTrimmed = expected.bodyExact.trim();
|
|
1189
|
+
if (rawTrimmed.startsWith("{") || rawTrimmed.startsWith("[")) {
|
|
1190
|
+
try {
|
|
1191
|
+
const parsedExact = JSON.parse(rawTrimmed);
|
|
1192
|
+
const body = JSON.stringify(sanitizeJsonValue(parsedExact));
|
|
1193
|
+
return { body, contentType: headerContentType || "application/json; charset=utf-8" };
|
|
1194
|
+
}
|
|
1195
|
+
catch {
|
|
1196
|
+
// Not valid JSON; fall through to text sanitization
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
const body = sanitizeText(expected.bodyExact);
|
|
1200
|
+
return { body, contentType: inferContentTypeForExactBody(body, headerContentType) };
|
|
1201
|
+
}
|
|
1202
|
+
const hasJsonSchema = isPlainObject(expected.jsonSchema);
|
|
1203
|
+
const hasJsonSubset = expected.jsonSubset !== undefined;
|
|
1204
|
+
const hasJsonPaths = Array.isArray(expected.jsonPaths) && expected.jsonPaths.length > 0;
|
|
1205
|
+
if (hasJsonSchema || hasJsonSubset || hasJsonPaths) {
|
|
1206
|
+
let payload;
|
|
1207
|
+
if (hasJsonSchema) {
|
|
1208
|
+
payload = synthesizeFromJsonSchema(expected.jsonSchema, 0, 0, true);
|
|
1209
|
+
}
|
|
1210
|
+
else if (hasJsonSubset) {
|
|
1211
|
+
payload = sanitizeJsonValue(expected.jsonSubset);
|
|
1212
|
+
}
|
|
1213
|
+
else {
|
|
1214
|
+
const firstPath = expected.jsonPaths[0]?.path;
|
|
1215
|
+
payload = typeof firstPath === "string" && firstPath.startsWith("$[") ? [] : {};
|
|
1216
|
+
}
|
|
1217
|
+
if (hasJsonSchema && hasJsonSubset) {
|
|
1218
|
+
payload = deepMergeJson(payload, expected.jsonSubset);
|
|
1219
|
+
}
|
|
1220
|
+
if (hasJsonPaths) {
|
|
1221
|
+
payload = applyJsonPathAssertions(payload, expected.jsonPaths);
|
|
1222
|
+
}
|
|
1223
|
+
payload = sanitizeJsonValue(payload);
|
|
1224
|
+
return {
|
|
1225
|
+
body: JSON.stringify(payload),
|
|
1226
|
+
contentType: headerContentType || "application/json; charset=utf-8"
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
const containsList = typeof expected.bodyContains === "string"
|
|
1230
|
+
? (expected.bodyContains.length > 0 ? [expected.bodyContains] : [])
|
|
1231
|
+
: Array.isArray(expected.bodyContains)
|
|
1232
|
+
? expected.bodyContains.filter((s) => typeof s === "string" && s.length > 0)
|
|
1233
|
+
: [];
|
|
1234
|
+
if (containsList.length > 0) {
|
|
1235
|
+
return {
|
|
1236
|
+
body: containsList.map((snippet) => sanitizeText(snippet)).join("\n"),
|
|
1237
|
+
contentType: headerContentType || "text/plain; charset=utf-8"
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
if (status === 204 || status === 304) {
|
|
1241
|
+
return {
|
|
1242
|
+
body: "",
|
|
1243
|
+
contentType: headerContentType || "text/plain; charset=utf-8"
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
return {
|
|
1247
|
+
body: "{}",
|
|
1248
|
+
contentType: headerContentType || "application/json; charset=utf-8"
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
function renderLandmarkHtml(landmark, extraInnerHtml = "") {
|
|
1252
|
+
const rawTag = String(landmark.tag || "").trim().toLowerCase();
|
|
1253
|
+
if (!rawTag || !SAFE_HTML_TAG_RE.test(rawTag) || DISALLOWED_LANDMARK_TAGS.has(rawTag)) {
|
|
1254
|
+
return "";
|
|
1255
|
+
}
|
|
1256
|
+
const text = typeof landmark.textContains === "string" && landmark.textContains.length > 0
|
|
1257
|
+
? sanitizeText(landmark.textContains)
|
|
1258
|
+
: rawTag;
|
|
1259
|
+
const escapedText = escapeHtmlText(text);
|
|
1260
|
+
if (rawTag === "ul") {
|
|
1261
|
+
return ` <ul><li>${escapedText}</li>${extraInnerHtml}</ul>`;
|
|
1262
|
+
}
|
|
1263
|
+
if (rawTag === "table") {
|
|
1264
|
+
return ` <table><tbody><tr><td>${escapedText}</td></tr></tbody></table>`;
|
|
1265
|
+
}
|
|
1266
|
+
if (rawTag === "form") {
|
|
1267
|
+
return ` <form><span>${escapedText}</span>${extraInnerHtml}</form>`;
|
|
1268
|
+
}
|
|
1269
|
+
return ` <${rawTag}>${escapedText}${extraInnerHtml}</${rawTag}>`;
|
|
1270
|
+
}
|
|
1271
|
+
function renderInteractiveLandmarkHtml(item) {
|
|
1272
|
+
const tag = String(item.tag || "").trim().toLowerCase();
|
|
1273
|
+
const role = String(item.role || "").trim().toLowerCase();
|
|
1274
|
+
const name = typeof item.name === "string" && item.name.trim().length > 0 ? sanitizeText(item.name.trim()) : "";
|
|
1275
|
+
const ariaAttr = name ? ` aria-label="${escapeHtmlAttr(name)}"` : "";
|
|
1276
|
+
if (tag === "a" || (!tag && role === "link")) {
|
|
1277
|
+
const roleAttr = role && role !== "link" ? ` role="${escapeHtmlAttr(role)}"` : "";
|
|
1278
|
+
return ` <a href="#"${roleAttr}${ariaAttr}>${escapeHtmlText(name || "Link")}</a>`;
|
|
1279
|
+
}
|
|
1280
|
+
if (tag === "button" || (!tag && role === "button")) {
|
|
1281
|
+
const roleAttr = role && role !== "button" ? ` role="${escapeHtmlAttr(role)}"` : "";
|
|
1282
|
+
return ` <button type="button"${roleAttr}${ariaAttr}>${escapeHtmlText(name || "Action")}</button>`;
|
|
1283
|
+
}
|
|
1284
|
+
if (tag === "input" || (!tag && (role === "textbox" || role === "checkbox" || role === "radio"))) {
|
|
1285
|
+
const inputType = role === "checkbox" ? "checkbox" : role === "radio" ? "radio" : role === "button" ? "button" : "text";
|
|
1286
|
+
const placeholderAttr = name ? ` placeholder="${escapeHtmlAttr(name)}"` : "";
|
|
1287
|
+
return ` <input type="${inputType}"${ariaAttr}${placeholderAttr} />`;
|
|
1288
|
+
}
|
|
1289
|
+
if (tag === "select" || (!tag && role === "combobox")) {
|
|
1290
|
+
return ` <select${ariaAttr}><option>${escapeHtmlText(name || "Option")}</option></select>`;
|
|
1291
|
+
}
|
|
1292
|
+
if (tag === "textarea") {
|
|
1293
|
+
const placeholderAttr = name ? ` placeholder="${escapeHtmlAttr(name)}"` : "";
|
|
1294
|
+
return ` <textarea${ariaAttr}${placeholderAttr}></textarea>`;
|
|
1295
|
+
}
|
|
1296
|
+
const safeTag = tag && SAFE_HTML_TAG_RE.test(tag) && !DISALLOWED_LANDMARK_TAGS.has(tag) ? tag : "div";
|
|
1297
|
+
const roleAttr = role ? ` role="${escapeHtmlAttr(role)}"` : "";
|
|
1298
|
+
return ` <${safeTag}${roleAttr}${ariaAttr}>${escapeHtmlText(name || role || "Control")}</${safeTag}>`;
|
|
1299
|
+
}
|
|
1300
|
+
function synthesizeWebRouteHtml(contract, invariant) {
|
|
1301
|
+
const expected = invariant.expected || {};
|
|
1302
|
+
const rawTitle = (typeof expected.titleContains === "string" && expected.titleContains.length > 0
|
|
1303
|
+
? expected.titleContains
|
|
1304
|
+
: undefined) ||
|
|
1305
|
+
(typeof contract.target?.name === "string" && contract.target.name.length > 0
|
|
1306
|
+
? contract.target.name
|
|
1307
|
+
: undefined) ||
|
|
1308
|
+
"vibecode mock";
|
|
1309
|
+
const title = sanitizeText(rawTitle);
|
|
1310
|
+
const requiredLandmarks = Array.isArray(expected.landmarks)
|
|
1311
|
+
? expected.landmarks.filter((lm) => isPlainObject(lm) &&
|
|
1312
|
+
typeof lm.tag === "string" &&
|
|
1313
|
+
lm.required !== false &&
|
|
1314
|
+
SAFE_HTML_TAG_RE.test(lm.tag.trim().toLowerCase()) &&
|
|
1315
|
+
!DISALLOWED_LANDMARK_TAGS.has(lm.tag.trim().toLowerCase()))
|
|
1316
|
+
: [];
|
|
1317
|
+
const interactiveLandmarks = Array.isArray(expected.interactiveLandmarks)
|
|
1318
|
+
? expected.interactiveLandmarks.filter((il) => isPlainObject(il) && (typeof il.role === "string" || typeof il.tag === "string"))
|
|
1319
|
+
: [];
|
|
1320
|
+
const visibleSnippets = [];
|
|
1321
|
+
if (Array.isArray(expected.visibleText)) {
|
|
1322
|
+
for (const s of expected.visibleText) {
|
|
1323
|
+
if (typeof s === "string" && s.length > 0)
|
|
1324
|
+
visibleSnippets.push(sanitizeText(s));
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
if (typeof expected.bodyContains === "string" && expected.bodyContains.length > 0) {
|
|
1328
|
+
visibleSnippets.push(sanitizeText(expected.bodyContains));
|
|
1329
|
+
}
|
|
1330
|
+
else if (Array.isArray(expected.bodyContains)) {
|
|
1331
|
+
for (const s of expected.bodyContains) {
|
|
1332
|
+
if (typeof s === "string" && s.length > 0)
|
|
1333
|
+
visibleSnippets.push(sanitizeText(s));
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
const hasMainLandmark = requiredLandmarks.some((lm) => lm.tag.trim().toLowerCase() === "main");
|
|
1337
|
+
const hasOnlyParagraphLandmarks = requiredLandmarks.length > 0 &&
|
|
1338
|
+
requiredLandmarks.every((lm) => !LANDMARK_EXTRACTOR_TAGS.has(lm.tag.trim().toLowerCase()));
|
|
1339
|
+
const extraSnippetsHtml = visibleSnippets.map((s) => ` <div>${escapeHtmlText(s)}</div>`).join("\n");
|
|
1340
|
+
const interactiveHtml = interactiveLandmarks.map((il) => renderInteractiveLandmarkHtml(il)).join("\n");
|
|
1341
|
+
const bodyLines = [];
|
|
1342
|
+
let appendedMainExtras = false;
|
|
1343
|
+
for (const lm of requiredLandmarks) {
|
|
1344
|
+
const tag = lm.tag.trim().toLowerCase();
|
|
1345
|
+
if (tag === "main" && !appendedMainExtras && (extraSnippetsHtml || interactiveHtml)) {
|
|
1346
|
+
appendedMainExtras = true;
|
|
1347
|
+
const innerParts = [extraSnippetsHtml, interactiveHtml].filter(Boolean).join("\n");
|
|
1348
|
+
bodyLines.push(renderLandmarkHtml(lm, `\n${innerParts}\n `));
|
|
1349
|
+
}
|
|
1350
|
+
else {
|
|
1351
|
+
const rendered = renderLandmarkHtml(lm);
|
|
1352
|
+
if (rendered)
|
|
1353
|
+
bodyLines.push(rendered);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
if (!hasMainLandmark) {
|
|
1357
|
+
if (extraSnippetsHtml || interactiveHtml) {
|
|
1358
|
+
if (hasOnlyParagraphLandmarks && !extraSnippetsHtml) {
|
|
1359
|
+
// Preserve <p>-only landmark extraction while still exposing interactive controls
|
|
1360
|
+
bodyLines.push(` <div data-mock-controls="true">\n${interactiveHtml}\n </div>`);
|
|
1361
|
+
}
|
|
1362
|
+
else {
|
|
1363
|
+
const innerParts = [extraSnippetsHtml, interactiveHtml].filter(Boolean).join("\n");
|
|
1364
|
+
bodyLines.push(` <main>\n${innerParts}\n </main>`);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
else if (bodyLines.length === 0) {
|
|
1368
|
+
bodyLines.push(` <main>${escapeHtmlText(title)}</main>`);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
return [
|
|
1372
|
+
"<!DOCTYPE html>",
|
|
1373
|
+
'<html lang="en">',
|
|
1374
|
+
"<head>",
|
|
1375
|
+
' <meta charset="utf-8">',
|
|
1376
|
+
` <title>${escapeHtmlText(title)}</title>`,
|
|
1377
|
+
"</head>",
|
|
1378
|
+
"<body>",
|
|
1379
|
+
...bodyLines,
|
|
1380
|
+
"</body>",
|
|
1381
|
+
"</html>"
|
|
1382
|
+
].join("\n");
|
|
1383
|
+
}
|
|
1384
|
+
export function compileMockRoutes(contract) {
|
|
1385
|
+
if (!isPlainObject(contract) || !Array.isArray(contract.invariants)) {
|
|
1386
|
+
throw new VibecodeError("CONTRACT_INVALID", "Contract must be a plain object with an invariants array");
|
|
1387
|
+
}
|
|
1388
|
+
const routes = [];
|
|
1389
|
+
const skippedIds = [];
|
|
1390
|
+
let excludedHoldoutCount = 0;
|
|
1391
|
+
for (let i = 0; i < contract.invariants.length; i++) {
|
|
1392
|
+
const inv = contract.invariants[i];
|
|
1393
|
+
if (!isPlainObject(inv))
|
|
1394
|
+
continue;
|
|
1395
|
+
// Holdout zero-leakage: never compile, serve, or list in skippedIds
|
|
1396
|
+
if (inv.holdout === true) {
|
|
1397
|
+
excludedHoldoutCount += 1;
|
|
1398
|
+
continue;
|
|
1399
|
+
}
|
|
1400
|
+
const id = typeof inv.id === "string" && inv.id.length > 0 ? inv.id : `inv-${i + 1}`;
|
|
1401
|
+
const type = typeof inv.type === "string" ? inv.type : "";
|
|
1402
|
+
const input = isPlainObject(inv.input) ? inv.input : {};
|
|
1403
|
+
const expected = isPlainObject(inv.expected) ? inv.expected : {};
|
|
1404
|
+
if (type === "http") {
|
|
1405
|
+
const rawMethod = typeof input.method === "string" ? input.method.trim().toUpperCase() : "GET";
|
|
1406
|
+
const method = /^[A-Z]{2,16}$/.test(rawMethod) ? rawMethod : "GET";
|
|
1407
|
+
const rawPath = (typeof input.path === "string" && input.path.trim() ? input.path : undefined) ??
|
|
1408
|
+
(typeof input.urlPath === "string" && input.urlPath.trim() ? input.urlPath : undefined) ??
|
|
1409
|
+
"/";
|
|
1410
|
+
const { path: cleanPath, query } = parsePathAndQuery(rawPath, isPlainObject(input.query) ? input.query : undefined);
|
|
1411
|
+
const status = resolveExpectedStatus(expected.status);
|
|
1412
|
+
const headers = sanitizeResponseHeaders(isPlainObject(expected.headers) ? expected.headers : undefined);
|
|
1413
|
+
const { body, contentType } = synthesizeHttpResponse(inv, status, headers);
|
|
1414
|
+
routes.push({
|
|
1415
|
+
invariantId: id,
|
|
1416
|
+
method,
|
|
1417
|
+
path: cleanPath,
|
|
1418
|
+
query,
|
|
1419
|
+
status,
|
|
1420
|
+
headers,
|
|
1421
|
+
body,
|
|
1422
|
+
contentType
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
else if (type === "web_route") {
|
|
1426
|
+
const rawPath = (typeof input.urlPath === "string" && input.urlPath.trim() ? input.urlPath : undefined) ??
|
|
1427
|
+
(typeof input.path === "string" && input.path.trim() ? input.path : undefined) ??
|
|
1428
|
+
"/";
|
|
1429
|
+
const { path: cleanPath, query } = parsePathAndQuery(rawPath, isPlainObject(input.query) ? input.query : undefined);
|
|
1430
|
+
const status = resolveExpectedStatus(expected.status);
|
|
1431
|
+
const headers = sanitizeResponseHeaders(isPlainObject(expected.headers) ? expected.headers : undefined);
|
|
1432
|
+
const body = synthesizeWebRouteHtml(contract, inv);
|
|
1433
|
+
const contentType = headers["content-type"] || "text/html; charset=utf-8";
|
|
1434
|
+
routes.push({
|
|
1435
|
+
invariantId: id,
|
|
1436
|
+
method: "GET",
|
|
1437
|
+
path: cleanPath,
|
|
1438
|
+
query,
|
|
1439
|
+
status,
|
|
1440
|
+
headers,
|
|
1441
|
+
body,
|
|
1442
|
+
contentType
|
|
1443
|
+
});
|
|
1444
|
+
}
|
|
1445
|
+
else {
|
|
1446
|
+
skippedIds.push(id);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
return { routes, skippedIds, excludedHoldoutCount };
|
|
1450
|
+
}
|
|
1451
|
+
function scoreRouteQueryMatch(route, searchParams) {
|
|
1452
|
+
const entries = Object.entries(route.query);
|
|
1453
|
+
if (entries.length === 0)
|
|
1454
|
+
return 0;
|
|
1455
|
+
let matched = 0;
|
|
1456
|
+
for (const [key, expectedVal] of entries) {
|
|
1457
|
+
if (!searchParams.has(key)) {
|
|
1458
|
+
return -1;
|
|
1459
|
+
}
|
|
1460
|
+
const actualValues = searchParams.getAll(key);
|
|
1461
|
+
if (!actualValues.includes(expectedVal)) {
|
|
1462
|
+
return -1;
|
|
1463
|
+
}
|
|
1464
|
+
matched += 1;
|
|
1465
|
+
}
|
|
1466
|
+
return matched;
|
|
1467
|
+
}
|
|
1468
|
+
function selectRoute(routes, method, pathname, searchParams, strictQuery) {
|
|
1469
|
+
const candidates = routes.filter((r) => r.method === method && r.path === pathname);
|
|
1470
|
+
if (candidates.length === 0)
|
|
1471
|
+
return null;
|
|
1472
|
+
let best = null;
|
|
1473
|
+
let bestScore = -Infinity;
|
|
1474
|
+
for (const candidate of candidates) {
|
|
1475
|
+
const score = scoreRouteQueryMatch(candidate, searchParams);
|
|
1476
|
+
if (strictQuery && score < 0)
|
|
1477
|
+
continue;
|
|
1478
|
+
if (score > bestScore) {
|
|
1479
|
+
bestScore = score;
|
|
1480
|
+
best = candidate;
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
return best;
|
|
1484
|
+
}
|
|
1485
|
+
export function createContractMockServer(contract, options = {}) {
|
|
1486
|
+
const compiled = compileMockRoutes(contract);
|
|
1487
|
+
const strictQuery = options.strictQuery === true;
|
|
1488
|
+
const server = http.createServer((req, res) => {
|
|
1489
|
+
const reqMethod = String(req.method || "GET").trim().toUpperCase() || "GET";
|
|
1490
|
+
let reqPathname = "/";
|
|
1491
|
+
let reqSearchParams = new URLSearchParams();
|
|
1492
|
+
try {
|
|
1493
|
+
const rawUrl = typeof req.url === "string" && req.url.length > 0 ? req.url : "/";
|
|
1494
|
+
const safeRaw = rawUrl.startsWith("/") ? rawUrl.replace(/^\/+/, "/") : `/${rawUrl}`;
|
|
1495
|
+
const parsed = new URL(safeRaw, "http://mock.local");
|
|
1496
|
+
reqPathname = parsed.pathname || "/";
|
|
1497
|
+
reqSearchParams = parsed.searchParams;
|
|
1498
|
+
}
|
|
1499
|
+
catch {
|
|
1500
|
+
reqPathname = "/";
|
|
1501
|
+
}
|
|
1502
|
+
let responded = false;
|
|
1503
|
+
const respond = () => {
|
|
1504
|
+
if (responded || res.writableEnded)
|
|
1505
|
+
return;
|
|
1506
|
+
responded = true;
|
|
1507
|
+
const matched = selectRoute(compiled.routes, reqMethod, reqPathname, reqSearchParams, strictQuery);
|
|
1508
|
+
if (!matched) {
|
|
1509
|
+
const notFoundBody = JSON.stringify({
|
|
1510
|
+
error: "not_found",
|
|
1511
|
+
method: reqMethod,
|
|
1512
|
+
path: sanitizeText(reqPathname)
|
|
1513
|
+
});
|
|
1514
|
+
res.writeHead(404, {
|
|
1515
|
+
"content-type": "application/json; charset=utf-8",
|
|
1516
|
+
"content-length": String(Buffer.byteLength(notFoundBody, "utf8"))
|
|
1517
|
+
});
|
|
1518
|
+
res.end(notFoundBody);
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
const safeContentType = sanitizeHeaderValue(matched.contentType) || "text/plain; charset=utf-8";
|
|
1522
|
+
const outHeaders = {
|
|
1523
|
+
...matched.headers,
|
|
1524
|
+
"content-type": safeContentType
|
|
1525
|
+
};
|
|
1526
|
+
try {
|
|
1527
|
+
if (matched.status === 204 || matched.status === 304) {
|
|
1528
|
+
res.writeHead(matched.status, outHeaders);
|
|
1529
|
+
res.end();
|
|
1530
|
+
return;
|
|
1531
|
+
}
|
|
1532
|
+
outHeaders["content-length"] = String(Buffer.byteLength(matched.body, "utf8"));
|
|
1533
|
+
res.writeHead(matched.status, outHeaders);
|
|
1534
|
+
res.end(matched.body);
|
|
1535
|
+
}
|
|
1536
|
+
catch {
|
|
1537
|
+
if (!res.headersSent) {
|
|
1538
|
+
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
1539
|
+
}
|
|
1540
|
+
if (!res.writableEnded) {
|
|
1541
|
+
res.end("Mock response error");
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
};
|
|
1545
|
+
req.once("error", () => {
|
|
1546
|
+
if (!res.writableEnded) {
|
|
1547
|
+
try {
|
|
1548
|
+
res.end();
|
|
1549
|
+
}
|
|
1550
|
+
catch { /* ignore */ }
|
|
1551
|
+
}
|
|
1552
|
+
});
|
|
1553
|
+
if (req.complete || req.readableEnded) {
|
|
1554
|
+
respond();
|
|
1555
|
+
}
|
|
1556
|
+
else {
|
|
1557
|
+
req.on("data", () => {
|
|
1558
|
+
// Drain request body cleanly without buffering
|
|
1559
|
+
});
|
|
1560
|
+
req.once("end", respond);
|
|
1561
|
+
}
|
|
1562
|
+
});
|
|
1563
|
+
return {
|
|
1564
|
+
server,
|
|
1565
|
+
routes: compiled.routes,
|
|
1566
|
+
skippedIds: compiled.skippedIds,
|
|
1567
|
+
excludedHoldoutCount: compiled.excludedHoldoutCount
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
export async function startContractMockServer(contract, options = {}) {
|
|
1571
|
+
const host = options.host === undefined ? "127.0.0.1" : options.host;
|
|
1572
|
+
if (typeof host !== "string" || host.trim().length === 0 || /[\s\r\n\0]/.test(host)) {
|
|
1573
|
+
throw new VibecodeError("CONTRACT_INVALID", "Mock server host must be a non-empty hostname or IP address");
|
|
1574
|
+
}
|
|
1575
|
+
const port = options.port === undefined ? 0 : options.port;
|
|
1576
|
+
if (typeof port !== "number" || !Number.isInteger(port) || port < 0 || port > 65535) {
|
|
1577
|
+
throw new VibecodeError("CONTRACT_INVALID", "Mock server port must be an integer between 0 and 65535");
|
|
1578
|
+
}
|
|
1579
|
+
const created = createContractMockServer(contract, options);
|
|
1580
|
+
const { server } = created;
|
|
1581
|
+
await new Promise((resolve, reject) => {
|
|
1582
|
+
const onError = (err) => {
|
|
1583
|
+
server.off("listening", onListening);
|
|
1584
|
+
reject(err);
|
|
1585
|
+
};
|
|
1586
|
+
const onListening = () => {
|
|
1587
|
+
server.off("error", onError);
|
|
1588
|
+
resolve();
|
|
1589
|
+
};
|
|
1590
|
+
server.once("error", onError);
|
|
1591
|
+
server.once("listening", onListening);
|
|
1592
|
+
server.listen(port, host);
|
|
1593
|
+
});
|
|
1594
|
+
const addr = server.address();
|
|
1595
|
+
if (!addr || typeof addr === "string") {
|
|
1596
|
+
server.close();
|
|
1597
|
+
server.closeAllConnections?.();
|
|
1598
|
+
throw new VibecodeError("INTERNAL_ERROR", "Failed to resolve bound mock server address");
|
|
1599
|
+
}
|
|
1600
|
+
const boundPort = addr.port;
|
|
1601
|
+
const boundHost = addr.address && addr.address !== "0.0.0.0" && addr.address !== "::" ? addr.address : host;
|
|
1602
|
+
const urlHost = net.isIPv6(boundHost) ? `[${boundHost}]` : boundHost;
|
|
1603
|
+
const url = `http://${urlHost}:${boundPort}`;
|
|
1604
|
+
let closePromise = null;
|
|
1605
|
+
const close = () => {
|
|
1606
|
+
if (closePromise)
|
|
1607
|
+
return closePromise;
|
|
1608
|
+
closePromise = new Promise((resolve) => {
|
|
1609
|
+
if (!server.listening) {
|
|
1610
|
+
resolve();
|
|
1611
|
+
return;
|
|
1612
|
+
}
|
|
1613
|
+
server.close(() => resolve());
|
|
1614
|
+
try {
|
|
1615
|
+
server.closeIdleConnections?.();
|
|
1616
|
+
}
|
|
1617
|
+
catch {
|
|
1618
|
+
// ignore on older Node runtimes
|
|
1619
|
+
}
|
|
1620
|
+
try {
|
|
1621
|
+
server.closeAllConnections?.();
|
|
1622
|
+
}
|
|
1623
|
+
catch {
|
|
1624
|
+
// ignore on older Node runtimes
|
|
1625
|
+
}
|
|
1626
|
+
});
|
|
1627
|
+
return closePromise;
|
|
1628
|
+
};
|
|
1629
|
+
return {
|
|
1630
|
+
server,
|
|
1631
|
+
url,
|
|
1632
|
+
host: boundHost,
|
|
1633
|
+
port: boundPort,
|
|
1634
|
+
routes: created.routes,
|
|
1635
|
+
skippedIds: created.skippedIds,
|
|
1636
|
+
excludedHoldoutCount: created.excludedHoldoutCount,
|
|
1637
|
+
close
|
|
1638
|
+
};
|
|
1639
|
+
}
|
|
1640
|
+
function style(text, codes, useColor) {
|
|
1641
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
1642
|
+
}
|
|
1643
|
+
function methodColor(method) {
|
|
1644
|
+
switch (method.toUpperCase()) {
|
|
1645
|
+
case "GET":
|
|
1646
|
+
return ANSI.green;
|
|
1647
|
+
case "POST":
|
|
1648
|
+
case "PUT":
|
|
1649
|
+
case "PATCH":
|
|
1650
|
+
return ANSI.yellow;
|
|
1651
|
+
case "DELETE":
|
|
1652
|
+
return ANSI.red;
|
|
1653
|
+
default:
|
|
1654
|
+
return ANSI.cyan;
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
function statusColor(status) {
|
|
1658
|
+
if (status >= 500)
|
|
1659
|
+
return ANSI.red;
|
|
1660
|
+
if (status >= 400)
|
|
1661
|
+
return ANSI.yellow;
|
|
1662
|
+
if (status >= 300)
|
|
1663
|
+
return ANSI.cyan;
|
|
1664
|
+
return ANSI.green;
|
|
1665
|
+
}
|
|
1666
|
+
function formatQuerySuffix(query) {
|
|
1667
|
+
const entries = Object.entries(query);
|
|
1668
|
+
if (entries.length === 0)
|
|
1669
|
+
return "";
|
|
1670
|
+
const params = new URLSearchParams();
|
|
1671
|
+
for (const [k, v] of entries) {
|
|
1672
|
+
params.append(k, isSensitiveQueryName(k) ? "[REDACTED]" : sanitizeSingleLine(v));
|
|
1673
|
+
}
|
|
1674
|
+
const serialized = params.toString();
|
|
1675
|
+
return serialized ? `?${serialized}` : "";
|
|
1676
|
+
}
|
|
1677
|
+
export function formatPrettyMockServer(handle, options = {}) {
|
|
1678
|
+
const useColor = options.color === true;
|
|
1679
|
+
const lines = [];
|
|
1680
|
+
const banner = style("[MOCK SERVER]", `${ANSI.bold}${ANSI.cyan}`, useColor);
|
|
1681
|
+
const urlText = style(sanitizeSingleLine(handle.url), ANSI.bold, useColor);
|
|
1682
|
+
lines.push(`${banner} ${urlText}`);
|
|
1683
|
+
const routeCount = handle.routes.length;
|
|
1684
|
+
const summaryParts = [`${routeCount} ${routeCount === 1 ? "route" : "routes"}`];
|
|
1685
|
+
if (handle.skippedIds.length > 0) {
|
|
1686
|
+
summaryParts.push(`${handle.skippedIds.length} skipped`);
|
|
1687
|
+
}
|
|
1688
|
+
if (handle.excludedHoldoutCount > 0) {
|
|
1689
|
+
summaryParts.push(`${handle.excludedHoldoutCount} ${handle.excludedHoldoutCount === 1 ? "holdout" : "holdouts"} excluded`);
|
|
1690
|
+
}
|
|
1691
|
+
lines.push(`Summary: ${summaryParts.join(", ")}`);
|
|
1692
|
+
if (handle.routes.length > 0) {
|
|
1693
|
+
lines.push("Routes:");
|
|
1694
|
+
const shown = handle.routes.slice(0, MAX_PRETTY_ROUTES);
|
|
1695
|
+
for (const route of shown) {
|
|
1696
|
+
const safeMethod = sanitizeSingleLine(route.method).replace(/[^A-Z0-9-]/gi, "") || "GET";
|
|
1697
|
+
const m = style(safeMethod.padEnd(6), `${ANSI.bold}${methodColor(safeMethod)}`, useColor);
|
|
1698
|
+
const fullPath = sanitizeSingleLine(`${route.path}${formatQuerySuffix(route.query)}`);
|
|
1699
|
+
const st = style(String(route.status), statusColor(route.status), useColor);
|
|
1700
|
+
const ct = style(sanitizeSingleLine(route.contentType), ANSI.dim, useColor);
|
|
1701
|
+
const id = style(`[${sanitizeSingleLine(route.invariantId)}]`, ANSI.dim, useColor);
|
|
1702
|
+
lines.push(` - ${m} ${fullPath} -> ${st} (${ct}) ${id}`);
|
|
1703
|
+
}
|
|
1704
|
+
if (handle.routes.length > MAX_PRETTY_ROUTES) {
|
|
1705
|
+
lines.push(` ${style(`... and ${handle.routes.length - MAX_PRETTY_ROUTES} more`, ANSI.dim, useColor)}`);
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
else {
|
|
1709
|
+
lines.push(`Routes: ${style("none", ANSI.dim, useColor)}`);
|
|
1710
|
+
}
|
|
1711
|
+
if (handle.skippedIds.length > 0) {
|
|
1712
|
+
const shownSkipped = handle.skippedIds.slice(0, MAX_PRETTY_SKIPPED).map(sanitizeSingleLine);
|
|
1713
|
+
const suffix = handle.skippedIds.length > MAX_PRETTY_SKIPPED
|
|
1714
|
+
? `, ... (+${handle.skippedIds.length - MAX_PRETTY_SKIPPED} more)`
|
|
1715
|
+
: "";
|
|
1716
|
+
lines.push(`Skipped: ${shownSkipped.join(", ")}${suffix}`);
|
|
1717
|
+
}
|
|
1718
|
+
if (handle.excludedHoldoutCount > 0) {
|
|
1719
|
+
lines.push(`Holdouts: ${handle.excludedHoldoutCount} excluded (never served)`);
|
|
1720
|
+
}
|
|
1721
|
+
return lines.join("\n");
|
|
1722
|
+
}
|