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,2538 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { VibecodeError } from "./errors.js";
|
|
5
|
+
import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
|
|
6
|
+
const DEFAULT_BASE_URL = "http://127.0.0.1:8080";
|
|
7
|
+
const MAX_SCHEMA_DEPTH = 12;
|
|
8
|
+
const MAX_BODY_DEPTH = 16;
|
|
9
|
+
const MAX_SCHEMA_PROPERTIES = 128;
|
|
10
|
+
const VALID_FORMATS = new Set(["ts-fetch", "python", "go"]);
|
|
11
|
+
const SUPPORTED_HTTP_METHODS = new Set([
|
|
12
|
+
"GET",
|
|
13
|
+
"POST",
|
|
14
|
+
"PUT",
|
|
15
|
+
"PATCH",
|
|
16
|
+
"DELETE",
|
|
17
|
+
"HEAD",
|
|
18
|
+
"OPTIONS"
|
|
19
|
+
]);
|
|
20
|
+
const BODY_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
21
|
+
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
22
|
+
const HEADER_NAME_TOKEN_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
23
|
+
const SENSITIVE_HEADER_RE = /(?:authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|api[_-]?key|apikey|auth[_-]?token|access[_-]?token|session[_-]?token|csrf|xsrf|secret|token|passwd|password|passphrase|credential|bearer)/i;
|
|
24
|
+
const SENSITIVE_QUERY_RE = /(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|secret|client[_-]?secret|password|passwd|passphrase|auth|jwt|session[_-]?id|session|sig|signature|private[_-]?key|authorization|cookie|csrf|xsrf|credential|credentials|bearer)/i;
|
|
25
|
+
const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|cookie|session[_-]?id|jwt|credentials?|bearer|csrf|xsrf)/i;
|
|
26
|
+
const AUTH_SCHEME_VALUE_RE = /^\s*(?:bearer|basic|token|digest|apikey)\s+\S+/i;
|
|
27
|
+
const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
|
|
28
|
+
const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>]+/g;
|
|
29
|
+
const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
|
|
30
|
+
const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
|
|
31
|
+
const INLINE_BASIC_TOKEN_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{4,}/gi;
|
|
32
|
+
const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey)\s+[A-Za-z0-9._~+/=:-]{4,}/gi;
|
|
33
|
+
const INLINE_DIGEST_TOKEN_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"[^"]*"))*|[A-Za-z0-9._~+/:-]{6,}={0,2})/gi;
|
|
34
|
+
const TS_RESERVED_WORDS = new Set([
|
|
35
|
+
"abstract", "any", "as", "asserts", "async", "await", "bigint", "boolean",
|
|
36
|
+
"break", "case", "catch", "class", "const", "constructor", "continue",
|
|
37
|
+
"debugger", "declare", "default", "delete", "do", "else", "enum", "export",
|
|
38
|
+
"extends", "false", "finally", "for", "from", "function", "get", "if",
|
|
39
|
+
"implements", "import", "in", "infer", "instanceof", "interface", "is",
|
|
40
|
+
"keyof", "let", "module", "namespace", "never", "new", "null", "number",
|
|
41
|
+
"object", "of", "package", "private", "protected", "public", "readonly",
|
|
42
|
+
"require", "return", "set", "static", "string", "super", "switch", "symbol",
|
|
43
|
+
"this", "throw", "true", "try", "type", "typeof", "undefined", "unique",
|
|
44
|
+
"unknown", "var", "void", "while", "with", "yield",
|
|
45
|
+
"__proto__", "prototype", "toString", "valueOf", "hasOwnProperty",
|
|
46
|
+
"request", "baseUrl", "defaultHeaders", "fetchImpl", "ClientOptions",
|
|
47
|
+
"RequestOptions", "ApiClientError", "createClient", "Object", "Error", "Function",
|
|
48
|
+
"Promise", "Record", "Omit", "URL", "Map", "Set", "Array", "RequestInit", "Response", "Headers", "ReadableStream"
|
|
49
|
+
]);
|
|
50
|
+
const PYTHON_RESERVED_WORDS = new Set([
|
|
51
|
+
"False", "None", "True", "and", "as", "assert", "async", "await", "break",
|
|
52
|
+
"case", "class", "continue", "def", "del", "elif", "else", "except",
|
|
53
|
+
"finally", "for", "from", "global", "if", "import", "in", "is", "lambda",
|
|
54
|
+
"match", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
|
|
55
|
+
"with", "yield", "self", "cls", "object", "dict", "list", "str", "int",
|
|
56
|
+
"float", "bool", "type", "Any", "Dict", "List", "Optional", "Sequence",
|
|
57
|
+
"TypedDict", "Union", "Literal", "ApiClientError", "ClientConfig",
|
|
58
|
+
"create_client", "__init__", "__proto__", "constructor", "prototype"
|
|
59
|
+
]);
|
|
60
|
+
const GO_RESERVED_WORDS = new Set([
|
|
61
|
+
"break", "case", "chan", "const", "continue", "default", "defer", "else",
|
|
62
|
+
"fallthrough", "for", "func", "go", "goto", "if", "import", "interface",
|
|
63
|
+
"map", "package", "range", "return", "select", "struct", "switch", "type",
|
|
64
|
+
"var", "main", "init", "any", "bool", "byte", "comparable", "complex64",
|
|
65
|
+
"complex128", "error", "float32", "float64", "int", "int8", "int16", "int32",
|
|
66
|
+
"int64", "rune", "string", "uint", "uint8", "uint16", "uint32", "uint64",
|
|
67
|
+
"uintptr", "true", "false", "iota", "nil", "RequestOptions", "ApiError",
|
|
68
|
+
"Error", "String"
|
|
69
|
+
]);
|
|
70
|
+
const ANSI = {
|
|
71
|
+
reset: "\x1b[0m",
|
|
72
|
+
bold: "\x1b[1m",
|
|
73
|
+
dim: "\x1b[2m",
|
|
74
|
+
green: "\x1b[32m",
|
|
75
|
+
yellow: "\x1b[33m",
|
|
76
|
+
cyan: "\x1b[36m"
|
|
77
|
+
};
|
|
78
|
+
function isRecord(value) {
|
|
79
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
80
|
+
}
|
|
81
|
+
function hasOwn(obj, key) {
|
|
82
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
83
|
+
}
|
|
84
|
+
function isForbiddenKey(key) {
|
|
85
|
+
return FORBIDDEN_KEYS.has(key);
|
|
86
|
+
}
|
|
87
|
+
function isSensitiveHeaderName(name) {
|
|
88
|
+
const trimmed = String(name).trim();
|
|
89
|
+
return isSensitiveHeader(trimmed) || SENSITIVE_HEADER_RE.test(trimmed);
|
|
90
|
+
}
|
|
91
|
+
function isSensitiveQueryName(name) {
|
|
92
|
+
const trimmed = String(name).trim();
|
|
93
|
+
return (isSensitiveQueryParam(trimmed) ||
|
|
94
|
+
SENSITIVE_QUERY_RE.test(trimmed) ||
|
|
95
|
+
isSensitiveHeaderName(trimmed));
|
|
96
|
+
}
|
|
97
|
+
function isSecretFieldName(name) {
|
|
98
|
+
const trimmed = String(name).trim();
|
|
99
|
+
return (SECRET_FIELD_NAME_RE.test(trimmed) ||
|
|
100
|
+
isSensitiveHeaderName(trimmed) ||
|
|
101
|
+
isSensitiveQueryName(trimmed));
|
|
102
|
+
}
|
|
103
|
+
function isAuthSchemeValue(value) {
|
|
104
|
+
return AUTH_SCHEME_VALUE_RE.test(value);
|
|
105
|
+
}
|
|
106
|
+
function redactVaultPaths(text) {
|
|
107
|
+
return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT_PATH]");
|
|
108
|
+
}
|
|
109
|
+
function sanitizeUrlInText(rawUrl) {
|
|
110
|
+
const withoutVault = redactVaultPaths(rawUrl);
|
|
111
|
+
const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
|
|
112
|
+
try {
|
|
113
|
+
const parsed = new URL(withoutAuth);
|
|
114
|
+
parsed.username = "";
|
|
115
|
+
parsed.password = "";
|
|
116
|
+
parsed.hash = "";
|
|
117
|
+
const safeParams = new URLSearchParams();
|
|
118
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
119
|
+
const trimmedKey = k.trim();
|
|
120
|
+
if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
|
|
121
|
+
continue;
|
|
122
|
+
if (isAuthSchemeValue(v) || /\.vibecode-vault/i.test(v))
|
|
123
|
+
continue;
|
|
124
|
+
safeParams.append(k, redactVaultPaths(v));
|
|
125
|
+
}
|
|
126
|
+
const serialized = safeParams.toString();
|
|
127
|
+
parsed.search = serialized ? `?${serialized}` : "";
|
|
128
|
+
return parsed.toString();
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
const hashIdx = withoutAuth.indexOf("#");
|
|
132
|
+
const noHash = hashIdx >= 0 ? withoutAuth.slice(0, hashIdx) : withoutAuth;
|
|
133
|
+
const qIdx = noHash.indexOf("?");
|
|
134
|
+
if (qIdx < 0)
|
|
135
|
+
return noHash;
|
|
136
|
+
const basePart = noHash.slice(0, qIdx);
|
|
137
|
+
const params = new URLSearchParams(noHash.slice(qIdx + 1));
|
|
138
|
+
const safeParams = new URLSearchParams();
|
|
139
|
+
for (const [k, v] of params.entries()) {
|
|
140
|
+
const trimmedKey = k.trim();
|
|
141
|
+
if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
|
|
142
|
+
continue;
|
|
143
|
+
if (isAuthSchemeValue(v) || /\.vibecode-vault/i.test(v))
|
|
144
|
+
continue;
|
|
145
|
+
safeParams.append(k, redactVaultPaths(v));
|
|
146
|
+
}
|
|
147
|
+
const serialized = safeParams.toString();
|
|
148
|
+
return serialized ? `${basePart}?${serialized}` : basePart;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function sanitizeText(raw) {
|
|
152
|
+
const noNul = raw.replace(/\0/g, "");
|
|
153
|
+
const noVault = redactVaultPaths(noNul);
|
|
154
|
+
const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
|
|
155
|
+
const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
|
|
156
|
+
const noBearer = noBasicAuth.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
|
|
157
|
+
const noBasic = noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
|
|
158
|
+
const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
|
|
159
|
+
return noScheme.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
|
|
160
|
+
}
|
|
161
|
+
function sanitizeSingleLineText(raw, maxLen = 200) {
|
|
162
|
+
const cleaned = sanitizeText(raw)
|
|
163
|
+
.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
|
|
164
|
+
.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
|
|
165
|
+
.replace(/\*\//g, "* /")
|
|
166
|
+
.replace(/\s+/g, " ")
|
|
167
|
+
.trim();
|
|
168
|
+
if (cleaned.length <= maxLen)
|
|
169
|
+
return cleaned;
|
|
170
|
+
return `${cleaned.slice(0, maxLen - 3)}...`;
|
|
171
|
+
}
|
|
172
|
+
function sanitizeBaseUrl(raw) {
|
|
173
|
+
const cleaned = raw.replace(/[\r\n\0\x00-\x1f\x7f]+/g, "").trim();
|
|
174
|
+
if (!cleaned || /\.vibecode-vault/i.test(cleaned))
|
|
175
|
+
return null;
|
|
176
|
+
const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
|
|
177
|
+
try {
|
|
178
|
+
const parsed = new URL(withoutAuth);
|
|
179
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
180
|
+
return null;
|
|
181
|
+
parsed.username = "";
|
|
182
|
+
parsed.password = "";
|
|
183
|
+
parsed.search = "";
|
|
184
|
+
parsed.hash = "";
|
|
185
|
+
const cleanPath = parsed.pathname === "/" ? "" : parsed.pathname.replace(/\/+$/, "");
|
|
186
|
+
return `${parsed.origin}${cleanPath}`;
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function resolveBaseUrl(contract, options) {
|
|
193
|
+
if (typeof options.baseUrl === "string" && options.baseUrl.trim()) {
|
|
194
|
+
const sanitized = sanitizeBaseUrl(options.baseUrl);
|
|
195
|
+
if (sanitized)
|
|
196
|
+
return sanitized;
|
|
197
|
+
}
|
|
198
|
+
if (isRecord(contract.target) && Array.isArray(contract.target.sources) && contract.target.sources.length > 0) {
|
|
199
|
+
const firstSource = contract.target.sources[0];
|
|
200
|
+
if (isRecord(firstSource)) {
|
|
201
|
+
if (typeof firstSource.ref === "string" && /^https?:\/\//i.test(firstSource.ref.trim())) {
|
|
202
|
+
const sanitized = sanitizeBaseUrl(firstSource.ref);
|
|
203
|
+
if (sanitized)
|
|
204
|
+
return sanitized;
|
|
205
|
+
}
|
|
206
|
+
if (isRecord(firstSource.meta) &&
|
|
207
|
+
typeof firstSource.meta.baseUrl === "string" &&
|
|
208
|
+
/^https?:\/\//i.test(firstSource.meta.baseUrl.trim())) {
|
|
209
|
+
const sanitized = sanitizeBaseUrl(firstSource.meta.baseUrl);
|
|
210
|
+
if (sanitized)
|
|
211
|
+
return sanitized;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return DEFAULT_BASE_URL;
|
|
216
|
+
}
|
|
217
|
+
function sanitizePathname(rawPathname) {
|
|
218
|
+
const noHash = rawPathname.split("#")[0] ?? "";
|
|
219
|
+
const noControl = sanitizeText(noHash)
|
|
220
|
+
.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "")
|
|
221
|
+
.trim();
|
|
222
|
+
if (!noControl)
|
|
223
|
+
return "/";
|
|
224
|
+
const encodedSpaces = noControl.replace(/\s+/g, "%20");
|
|
225
|
+
return encodedSpaces.startsWith("/") ? encodedSpaces : `/${encodedSpaces}`;
|
|
226
|
+
}
|
|
227
|
+
function splitRelativePathAndQuery(raw) {
|
|
228
|
+
const hashIdx = raw.indexOf("#");
|
|
229
|
+
const withoutHash = hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
|
|
230
|
+
const qIdx = withoutHash.indexOf("?");
|
|
231
|
+
const rawPathPart = qIdx >= 0 ? withoutHash.slice(0, qIdx) : withoutHash;
|
|
232
|
+
const rawQueryPart = qIdx >= 0 ? withoutHash.slice(qIdx + 1) : "";
|
|
233
|
+
const inlineQuery = [];
|
|
234
|
+
if (rawQueryPart) {
|
|
235
|
+
const params = new URLSearchParams(rawQueryPart);
|
|
236
|
+
for (const [k, v] of params.entries()) {
|
|
237
|
+
inlineQuery.push([k, v]);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
pathname: sanitizePathname(rawPathPart),
|
|
242
|
+
inlineQuery
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
function parsePathAndInlineQuery(rawPath) {
|
|
246
|
+
if (typeof rawPath !== "string") {
|
|
247
|
+
return { pathname: "/", inlineQuery: [] };
|
|
248
|
+
}
|
|
249
|
+
const cleaned = rawPath.replace(/[\r\n\0\x00-\x1f\x7f]+/g, "").trim();
|
|
250
|
+
if (!cleaned) {
|
|
251
|
+
return { pathname: "/", inlineQuery: [] };
|
|
252
|
+
}
|
|
253
|
+
if (/^https?:\/\//i.test(cleaned)) {
|
|
254
|
+
const withoutAuth = redactVaultPaths(cleaned).replace(URL_BASIC_AUTH_RE, "$1");
|
|
255
|
+
try {
|
|
256
|
+
const parsed = new URL(withoutAuth);
|
|
257
|
+
const inlineQuery = [];
|
|
258
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
259
|
+
inlineQuery.push([k, v]);
|
|
260
|
+
}
|
|
261
|
+
return {
|
|
262
|
+
pathname: sanitizePathname(parsed.pathname || "/"),
|
|
263
|
+
inlineQuery
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
const stripped = withoutAuth.replace(/^https?:\/\/[^/?#]*/i, "") || "/";
|
|
268
|
+
return splitRelativePathAndQuery(stripped);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return splitRelativePathAndQuery(cleaned);
|
|
272
|
+
}
|
|
273
|
+
function sanitizeQueryEntries(inlineQuery, structuredQuery) {
|
|
274
|
+
const merged = new Map();
|
|
275
|
+
const consider = (rawKey, rawVal) => {
|
|
276
|
+
const cleanKey = rawKey.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
|
|
277
|
+
if (!cleanKey || isForbiddenKey(cleanKey))
|
|
278
|
+
return;
|
|
279
|
+
if (isSensitiveQueryName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
|
|
280
|
+
return;
|
|
281
|
+
if (/\.vibecode-vault/i.test(rawVal) || isAuthSchemeValue(rawVal))
|
|
282
|
+
return;
|
|
283
|
+
const cleanVal = sanitizeText(rawVal).replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, "");
|
|
284
|
+
if (isAuthSchemeValue(cleanVal))
|
|
285
|
+
return;
|
|
286
|
+
merged.set(cleanKey, cleanVal);
|
|
287
|
+
};
|
|
288
|
+
for (const [k, v] of inlineQuery) {
|
|
289
|
+
consider(k, v);
|
|
290
|
+
}
|
|
291
|
+
if (isRecord(structuredQuery)) {
|
|
292
|
+
for (const key of Object.keys(structuredQuery)) {
|
|
293
|
+
if (isForbiddenKey(key))
|
|
294
|
+
continue;
|
|
295
|
+
const val = structuredQuery[key];
|
|
296
|
+
if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
|
|
297
|
+
if (typeof val === "number" && !Number.isFinite(val))
|
|
298
|
+
continue;
|
|
299
|
+
consider(key, String(val));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return [...merged.entries()];
|
|
304
|
+
}
|
|
305
|
+
function sanitizeHeaders(rawHeaders) {
|
|
306
|
+
if (!isRecord(rawHeaders))
|
|
307
|
+
return [];
|
|
308
|
+
const byLower = new Map();
|
|
309
|
+
for (const rawKey of Object.keys(rawHeaders)) {
|
|
310
|
+
const cleanKey = rawKey.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, "").trim();
|
|
311
|
+
if (!cleanKey || isForbiddenKey(cleanKey) || isForbiddenKey(cleanKey.toLowerCase()))
|
|
312
|
+
continue;
|
|
313
|
+
if (!HEADER_NAME_TOKEN_RE.test(cleanKey))
|
|
314
|
+
continue;
|
|
315
|
+
if (isSensitiveHeaderName(cleanKey) || /\.vibecode-vault/i.test(cleanKey))
|
|
316
|
+
continue;
|
|
317
|
+
const rawVal = rawHeaders[rawKey];
|
|
318
|
+
if (rawVal === undefined || rawVal === null)
|
|
319
|
+
continue;
|
|
320
|
+
const singleLineVal = String(rawVal)
|
|
321
|
+
.replace(/\0/g, "")
|
|
322
|
+
.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
|
|
323
|
+
.trim();
|
|
324
|
+
if (!singleLineVal || singleLineVal === "[REDACTED]")
|
|
325
|
+
continue;
|
|
326
|
+
if (isAuthSchemeValue(singleLineVal) || /\.vibecode-vault/i.test(singleLineVal))
|
|
327
|
+
continue;
|
|
328
|
+
const cleanVal = sanitizeText(singleLineVal)
|
|
329
|
+
.replace(/[\r\n\0\u2028\u2029\x00-\x1f\x7f]+/g, " ")
|
|
330
|
+
.trim();
|
|
331
|
+
if (!cleanVal)
|
|
332
|
+
continue;
|
|
333
|
+
byLower.set(cleanKey.toLowerCase(), [cleanKey, cleanVal]);
|
|
334
|
+
}
|
|
335
|
+
return [...byLower.values()];
|
|
336
|
+
}
|
|
337
|
+
function extractExpectedStatuses(rawStatus) {
|
|
338
|
+
const valid = new Set();
|
|
339
|
+
const isValid = (n) => typeof n === "number" && Number.isInteger(n) && n >= 100 && n <= 599;
|
|
340
|
+
if (isValid(rawStatus)) {
|
|
341
|
+
valid.add(rawStatus);
|
|
342
|
+
}
|
|
343
|
+
else if (Array.isArray(rawStatus)) {
|
|
344
|
+
for (const item of rawStatus) {
|
|
345
|
+
if (isValid(item))
|
|
346
|
+
valid.add(item);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return [...valid];
|
|
350
|
+
}
|
|
351
|
+
function extractMediaType(rawContentType) {
|
|
352
|
+
if (typeof rawContentType !== "string")
|
|
353
|
+
return undefined;
|
|
354
|
+
const base = rawContentType
|
|
355
|
+
.replace(/[\r\n\0]+/g, "")
|
|
356
|
+
.split(";")[0]
|
|
357
|
+
?.trim()
|
|
358
|
+
.toLowerCase();
|
|
359
|
+
if (!base || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(base)) {
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
return base;
|
|
363
|
+
}
|
|
364
|
+
function sanitizeJsonValue(value, depth = 0, seen = new Set()) {
|
|
365
|
+
if (value === null || value === undefined)
|
|
366
|
+
return value;
|
|
367
|
+
if (typeof value === "boolean")
|
|
368
|
+
return value;
|
|
369
|
+
if (typeof value === "number")
|
|
370
|
+
return Number.isFinite(value) ? value : null;
|
|
371
|
+
if (typeof value === "string") {
|
|
372
|
+
const trimmed = value.trim();
|
|
373
|
+
if (depth < MAX_BODY_DEPTH &&
|
|
374
|
+
((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
|
|
375
|
+
(trimmed.startsWith("[") && trimmed.endsWith("]")))) {
|
|
376
|
+
try {
|
|
377
|
+
const parsed = JSON.parse(trimmed);
|
|
378
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
379
|
+
return JSON.stringify(sanitizeJsonValue(parsed, depth + 1, seen));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
// Fall through to plain text sanitization
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return sanitizeText(value);
|
|
387
|
+
}
|
|
388
|
+
if (depth >= MAX_BODY_DEPTH)
|
|
389
|
+
return null;
|
|
390
|
+
if (typeof value !== "object")
|
|
391
|
+
return undefined;
|
|
392
|
+
if (seen.has(value))
|
|
393
|
+
return null;
|
|
394
|
+
seen.add(value);
|
|
395
|
+
try {
|
|
396
|
+
if (Array.isArray(value)) {
|
|
397
|
+
return value.map((item) => sanitizeJsonValue(item, depth + 1, seen));
|
|
398
|
+
}
|
|
399
|
+
const out = Object.create(null);
|
|
400
|
+
for (const key of Object.keys(value)) {
|
|
401
|
+
if (isForbiddenKey(key))
|
|
402
|
+
continue;
|
|
403
|
+
const cleanKey = sanitizeText(key).replace(/\0/g, "");
|
|
404
|
+
if (!cleanKey || isForbiddenKey(cleanKey))
|
|
405
|
+
continue;
|
|
406
|
+
const rawVal = value[key];
|
|
407
|
+
if (rawVal === undefined || typeof rawVal === "function" || typeof rawVal === "symbol") {
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
if (isSecretFieldName(key) || isSecretFieldName(cleanKey)) {
|
|
411
|
+
out[cleanKey] = typeof rawVal === "object" && rawVal !== null
|
|
412
|
+
? sanitizeJsonValue(rawVal, depth + 1, seen)
|
|
413
|
+
: "[REDACTED]";
|
|
414
|
+
}
|
|
415
|
+
else {
|
|
416
|
+
out[cleanKey] = sanitizeJsonValue(rawVal, depth + 1, seen);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return out;
|
|
420
|
+
}
|
|
421
|
+
finally {
|
|
422
|
+
seen.delete(value);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function sanitizeSchemaNode(schema, inSecretField = false, depth = 0, seen = new Set()) {
|
|
426
|
+
if (!isRecord(schema))
|
|
427
|
+
return undefined;
|
|
428
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
429
|
+
return {};
|
|
430
|
+
if (seen.has(schema))
|
|
431
|
+
return {};
|
|
432
|
+
seen.add(schema);
|
|
433
|
+
try {
|
|
434
|
+
const out = {};
|
|
435
|
+
let propCount = 0;
|
|
436
|
+
for (const key of Object.keys(schema)) {
|
|
437
|
+
if (isForbiddenKey(key))
|
|
438
|
+
continue;
|
|
439
|
+
// Never retain example/examples/default values in generated client schemas.
|
|
440
|
+
if (key === "example" || key === "examples" || key === "default")
|
|
441
|
+
continue;
|
|
442
|
+
if (inSecretField && (key === "const" || key === "enum" || key === "$ref"))
|
|
443
|
+
continue;
|
|
444
|
+
const val = schema[key];
|
|
445
|
+
if (val === undefined)
|
|
446
|
+
continue;
|
|
447
|
+
if (key === "type") {
|
|
448
|
+
if (typeof val === "string") {
|
|
449
|
+
out.type = val;
|
|
450
|
+
}
|
|
451
|
+
else if (Array.isArray(val)) {
|
|
452
|
+
const types = val.filter((t) => typeof t === "string");
|
|
453
|
+
if (types.length > 0)
|
|
454
|
+
out.type = types;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
else if (key === "nullable" && typeof val === "boolean") {
|
|
458
|
+
out.nullable = val;
|
|
459
|
+
}
|
|
460
|
+
else if (key === "format" && typeof val === "string") {
|
|
461
|
+
out.format = sanitizeSingleLineText(val, 64);
|
|
462
|
+
}
|
|
463
|
+
else if (key === "$ref" && typeof val === "string") {
|
|
464
|
+
out.$ref = sanitizeSingleLineText(val, 200);
|
|
465
|
+
}
|
|
466
|
+
else if (key === "required" && Array.isArray(val)) {
|
|
467
|
+
const reqs = val.filter((item) => typeof item === "string" && !isForbiddenKey(item));
|
|
468
|
+
if (reqs.length > 0)
|
|
469
|
+
out.required = [...new Set(reqs)];
|
|
470
|
+
}
|
|
471
|
+
else if (key === "properties" && isRecord(val)) {
|
|
472
|
+
const props = Object.create(null);
|
|
473
|
+
for (const propKey of Object.keys(val)) {
|
|
474
|
+
if (isForbiddenKey(propKey))
|
|
475
|
+
continue;
|
|
476
|
+
if (propCount >= MAX_SCHEMA_PROPERTIES)
|
|
477
|
+
break;
|
|
478
|
+
const cleanPropKey = sanitizeText(propKey).replace(/\0/g, "");
|
|
479
|
+
if (!cleanPropKey || isForbiddenKey(cleanPropKey))
|
|
480
|
+
continue;
|
|
481
|
+
propCount += 1;
|
|
482
|
+
const sanitizedProp = sanitizeSchemaNode(val[propKey], inSecretField || isSecretFieldName(propKey) || isSecretFieldName(cleanPropKey), depth + 1, seen);
|
|
483
|
+
props[cleanPropKey] = sanitizedProp ?? {};
|
|
484
|
+
}
|
|
485
|
+
out.properties = props;
|
|
486
|
+
}
|
|
487
|
+
else if (key === "additionalProperties") {
|
|
488
|
+
if (typeof val === "boolean") {
|
|
489
|
+
out.additionalProperties = val;
|
|
490
|
+
}
|
|
491
|
+
else if (isRecord(val)) {
|
|
492
|
+
out.additionalProperties = sanitizeSchemaNode(val, inSecretField, depth + 1, seen) ?? {};
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
else if (key === "items") {
|
|
496
|
+
if (Array.isArray(val)) {
|
|
497
|
+
const tuple = val
|
|
498
|
+
.map((item) => sanitizeSchemaNode(item, inSecretField, depth + 1, seen) ?? {})
|
|
499
|
+
.slice(0, 32);
|
|
500
|
+
out.items = tuple;
|
|
501
|
+
}
|
|
502
|
+
else if (isRecord(val)) {
|
|
503
|
+
out.items = sanitizeSchemaNode(val, inSecretField, depth + 1, seen) ?? {};
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
else if (key === "prefixItems" && Array.isArray(val)) {
|
|
507
|
+
out.prefixItems = val
|
|
508
|
+
.map((item) => sanitizeSchemaNode(item, inSecretField, depth + 1, seen) ?? {})
|
|
509
|
+
.slice(0, 32);
|
|
510
|
+
}
|
|
511
|
+
else if (key === "allOf" || key === "anyOf" || key === "oneOf") {
|
|
512
|
+
if (Array.isArray(val)) {
|
|
513
|
+
const branches = val
|
|
514
|
+
.map((item) => sanitizeSchemaNode(item, inSecretField, depth + 1, seen))
|
|
515
|
+
.filter((item) => item !== undefined);
|
|
516
|
+
if (branches.length > 0)
|
|
517
|
+
out[key] = branches;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
else if (key === "const") {
|
|
521
|
+
out.const = sanitizeJsonValue(val, depth + 1, seen);
|
|
522
|
+
}
|
|
523
|
+
else if (key === "enum" && Array.isArray(val)) {
|
|
524
|
+
out.enum = val.map((item) => sanitizeJsonValue(item, depth + 1, seen));
|
|
525
|
+
}
|
|
526
|
+
else if ((key === "$defs" || key === "definitions") && isRecord(val)) {
|
|
527
|
+
const defs = Object.create(null);
|
|
528
|
+
for (const defKey of Object.keys(val)) {
|
|
529
|
+
if (isForbiddenKey(defKey))
|
|
530
|
+
continue;
|
|
531
|
+
const cleanDefKey = sanitizeText(defKey).replace(/\0/g, "");
|
|
532
|
+
if (!cleanDefKey || isForbiddenKey(cleanDefKey))
|
|
533
|
+
continue;
|
|
534
|
+
const defSchema = sanitizeSchemaNode(val[defKey], inSecretField || isSecretFieldName(defKey) || isSecretFieldName(cleanDefKey), depth + 1, seen);
|
|
535
|
+
if (defSchema)
|
|
536
|
+
defs[cleanDefKey] = defSchema;
|
|
537
|
+
}
|
|
538
|
+
out[key] = defs;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return out;
|
|
542
|
+
}
|
|
543
|
+
finally {
|
|
544
|
+
seen.delete(schema);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
function inferSchemaFromValue(value, depth = 0, seen = new Set()) {
|
|
548
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
549
|
+
return {};
|
|
550
|
+
if (value === null)
|
|
551
|
+
return { type: "null" };
|
|
552
|
+
if (typeof value === "boolean")
|
|
553
|
+
return { type: "boolean" };
|
|
554
|
+
if (typeof value === "number") {
|
|
555
|
+
return { type: Number.isInteger(value) ? "integer" : "number" };
|
|
556
|
+
}
|
|
557
|
+
if (typeof value === "string")
|
|
558
|
+
return { type: "string" };
|
|
559
|
+
if (typeof value !== "object")
|
|
560
|
+
return {};
|
|
561
|
+
if (seen.has(value))
|
|
562
|
+
return {};
|
|
563
|
+
seen.add(value);
|
|
564
|
+
try {
|
|
565
|
+
if (Array.isArray(value)) {
|
|
566
|
+
if (value.length === 0)
|
|
567
|
+
return { type: "array", items: {} };
|
|
568
|
+
const firstSchema = inferSchemaFromValue(value[0], depth + 1, seen);
|
|
569
|
+
return { type: "array", items: firstSchema };
|
|
570
|
+
}
|
|
571
|
+
const obj = value;
|
|
572
|
+
const properties = Object.create(null);
|
|
573
|
+
const required = [];
|
|
574
|
+
for (const key of Object.keys(obj)) {
|
|
575
|
+
if (isForbiddenKey(key))
|
|
576
|
+
continue;
|
|
577
|
+
const cleanKey = sanitizeText(key).replace(/\0/g, "");
|
|
578
|
+
if (!cleanKey || isForbiddenKey(cleanKey))
|
|
579
|
+
continue;
|
|
580
|
+
const val = obj[key];
|
|
581
|
+
if (val === undefined)
|
|
582
|
+
continue;
|
|
583
|
+
required.push(cleanKey);
|
|
584
|
+
if ((isSecretFieldName(key) || isSecretFieldName(cleanKey)) && typeof val === "string") {
|
|
585
|
+
properties[cleanKey] = { type: "string" };
|
|
586
|
+
}
|
|
587
|
+
else {
|
|
588
|
+
properties[cleanKey] = inferSchemaFromValue(val, depth + 1, seen);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return {
|
|
592
|
+
type: "object",
|
|
593
|
+
properties,
|
|
594
|
+
...(required.length > 0 ? { required } : {})
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
finally {
|
|
598
|
+
seen.delete(value);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
function resolveLocalRef(rootSchema, ref) {
|
|
602
|
+
if (!rootSchema || !ref.startsWith("#/"))
|
|
603
|
+
return undefined;
|
|
604
|
+
const parts = ref
|
|
605
|
+
.slice(2)
|
|
606
|
+
.split("/")
|
|
607
|
+
.map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
608
|
+
let current = rootSchema;
|
|
609
|
+
for (const part of parts) {
|
|
610
|
+
if (!part || isForbiddenKey(part) || !isRecord(current) || !hasOwn(current, part)) {
|
|
611
|
+
return undefined;
|
|
612
|
+
}
|
|
613
|
+
current = current[part];
|
|
614
|
+
}
|
|
615
|
+
return isRecord(current) ? current : undefined;
|
|
616
|
+
}
|
|
617
|
+
// ============================================================================
|
|
618
|
+
// Identifier & Escaping Utilities (TS, Python, Go)
|
|
619
|
+
// ============================================================================
|
|
620
|
+
function splitToAsciiWords(raw) {
|
|
621
|
+
const cleaned = sanitizeSingleLineText(raw, 160);
|
|
622
|
+
if (!cleaned)
|
|
623
|
+
return [];
|
|
624
|
+
const withSpaces = cleaned
|
|
625
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
626
|
+
.replace(/[^A-Za-z0-9]+/g, " ")
|
|
627
|
+
.trim();
|
|
628
|
+
if (!withSpaces)
|
|
629
|
+
return [];
|
|
630
|
+
return withSpaces
|
|
631
|
+
.split(/\s+/)
|
|
632
|
+
.map((w) => w.toLowerCase())
|
|
633
|
+
.filter((w) => w.length > 0)
|
|
634
|
+
.slice(0, 12);
|
|
635
|
+
}
|
|
636
|
+
function capitalizeWord(word) {
|
|
637
|
+
if (!word)
|
|
638
|
+
return "";
|
|
639
|
+
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
|
|
640
|
+
}
|
|
641
|
+
function toPascalCase(words, fallback) {
|
|
642
|
+
const clean = words
|
|
643
|
+
.map((w) => w.replace(/[^A-Za-z0-9]/g, ""))
|
|
644
|
+
.filter((w) => w.length > 0);
|
|
645
|
+
if (clean.length === 0)
|
|
646
|
+
return fallback;
|
|
647
|
+
let joined = clean.map(capitalizeWord).join("");
|
|
648
|
+
if (/^[0-9]/.test(joined)) {
|
|
649
|
+
joined = `Api${joined}`;
|
|
650
|
+
}
|
|
651
|
+
return joined || fallback;
|
|
652
|
+
}
|
|
653
|
+
function toCamelCase(words, fallback) {
|
|
654
|
+
const clean = words
|
|
655
|
+
.map((w) => w.replace(/[^A-Za-z0-9]/g, ""))
|
|
656
|
+
.filter((w) => w.length > 0);
|
|
657
|
+
if (clean.length === 0)
|
|
658
|
+
return fallback;
|
|
659
|
+
let joined = clean[0].toLowerCase() + clean.slice(1).map(capitalizeWord).join("");
|
|
660
|
+
if (/^[0-9]/.test(joined)) {
|
|
661
|
+
joined = `op${capitalizeWord(joined)}`;
|
|
662
|
+
}
|
|
663
|
+
return joined || fallback;
|
|
664
|
+
}
|
|
665
|
+
function toSnakeCase(words, fallback) {
|
|
666
|
+
const clean = words
|
|
667
|
+
.map((w) => w.replace(/[^A-Za-z0-9]/g, "").toLowerCase())
|
|
668
|
+
.filter((w) => w.length > 0);
|
|
669
|
+
if (clean.length === 0)
|
|
670
|
+
return fallback;
|
|
671
|
+
let joined = clean.join("_");
|
|
672
|
+
if (/^[0-9]/.test(joined)) {
|
|
673
|
+
joined = `op_${joined}`;
|
|
674
|
+
}
|
|
675
|
+
return joined || fallback;
|
|
676
|
+
}
|
|
677
|
+
function sanitizeClassName(raw, fallbackTitle) {
|
|
678
|
+
const source = typeof raw === "string" && raw.trim() ? raw : fallbackTitle;
|
|
679
|
+
const words = splitToAsciiWords(source);
|
|
680
|
+
let name = toPascalCase(words, "ApiClient");
|
|
681
|
+
if (!raw && !name.endsWith("Client")) {
|
|
682
|
+
name = `${name}Client`;
|
|
683
|
+
}
|
|
684
|
+
if (TS_RESERVED_WORDS.has(name) ||
|
|
685
|
+
PYTHON_RESERVED_WORDS.has(name) ||
|
|
686
|
+
GO_RESERVED_WORDS.has(name)) {
|
|
687
|
+
name = `${name}Client`;
|
|
688
|
+
}
|
|
689
|
+
return name;
|
|
690
|
+
}
|
|
691
|
+
function sanitizeGoPackageName(raw, fallbackTitle) {
|
|
692
|
+
const source = typeof raw === "string" && raw.trim() ? raw : fallbackTitle;
|
|
693
|
+
const words = splitToAsciiWords(source);
|
|
694
|
+
let pkg = words.join("").replace(/[^a-z0-9]/g, "");
|
|
695
|
+
if (!pkg || /^[0-9]/.test(pkg)) {
|
|
696
|
+
pkg = pkg ? `pkg${pkg}` : "apiclient";
|
|
697
|
+
}
|
|
698
|
+
if (GO_RESERVED_WORDS.has(pkg)) {
|
|
699
|
+
pkg = `${pkg}client`;
|
|
700
|
+
}
|
|
701
|
+
return pkg.slice(0, 48);
|
|
702
|
+
}
|
|
703
|
+
function safeTsIdentifier(candidate, fallback, used) {
|
|
704
|
+
let name = candidate.replace(/[^A-Za-z0-9_$]/g, "");
|
|
705
|
+
if (!name || /^[0-9]/.test(name)) {
|
|
706
|
+
name = `${fallback}${name}`;
|
|
707
|
+
}
|
|
708
|
+
if (TS_RESERVED_WORDS.has(name) || isForbiddenKey(name)) {
|
|
709
|
+
name = `${name}Endpoint`;
|
|
710
|
+
}
|
|
711
|
+
let unique = name;
|
|
712
|
+
let seq = 2;
|
|
713
|
+
while (used.has(unique) || TS_RESERVED_WORDS.has(unique)) {
|
|
714
|
+
unique = `${name}${seq}`;
|
|
715
|
+
seq += 1;
|
|
716
|
+
}
|
|
717
|
+
used.add(unique);
|
|
718
|
+
return unique;
|
|
719
|
+
}
|
|
720
|
+
function safePyIdentifier(candidate, fallback, used) {
|
|
721
|
+
let name = candidate.replace(/[^A-Za-z0-9_]/g, "").toLowerCase();
|
|
722
|
+
if (!name || /^[0-9]/.test(name) || name.startsWith("_")) {
|
|
723
|
+
name = `${fallback}_${name.replace(/^_+/, "")}`.replace(/_+$/, "") || fallback;
|
|
724
|
+
}
|
|
725
|
+
if (PYTHON_RESERVED_WORDS.has(name) || isForbiddenKey(name)) {
|
|
726
|
+
name = `${name}_endpoint`;
|
|
727
|
+
}
|
|
728
|
+
let unique = name;
|
|
729
|
+
let seq = 2;
|
|
730
|
+
while (used.has(unique) || PYTHON_RESERVED_WORDS.has(unique)) {
|
|
731
|
+
unique = `${name}_${seq}`;
|
|
732
|
+
seq += 1;
|
|
733
|
+
}
|
|
734
|
+
used.add(unique);
|
|
735
|
+
return unique;
|
|
736
|
+
}
|
|
737
|
+
function safeGoExportedIdentifier(candidate, fallback, used) {
|
|
738
|
+
let name = candidate.replace(/[^A-Za-z0-9]/g, "");
|
|
739
|
+
if (!name || !/^[A-Za-z]/.test(name)) {
|
|
740
|
+
name = `${fallback}${name}`;
|
|
741
|
+
}
|
|
742
|
+
name = name.charAt(0).toUpperCase() + name.slice(1);
|
|
743
|
+
if (GO_RESERVED_WORDS.has(name) || isForbiddenKey(name)) {
|
|
744
|
+
name = `${name}Endpoint`;
|
|
745
|
+
}
|
|
746
|
+
let unique = name;
|
|
747
|
+
let seq = 2;
|
|
748
|
+
while (used.has(unique) || GO_RESERVED_WORDS.has(unique)) {
|
|
749
|
+
unique = `${name}${seq}`;
|
|
750
|
+
seq += 1;
|
|
751
|
+
}
|
|
752
|
+
used.add(unique);
|
|
753
|
+
return unique;
|
|
754
|
+
}
|
|
755
|
+
function safePyTypeName(candidate, fallback, used) {
|
|
756
|
+
let name = candidate.replace(/[^A-Za-z0-9]/g, "");
|
|
757
|
+
if (!name || !/^[A-Za-z]/.test(name)) {
|
|
758
|
+
name = `${fallback}${name}`;
|
|
759
|
+
}
|
|
760
|
+
name = name.charAt(0).toUpperCase() + name.slice(1);
|
|
761
|
+
if (PYTHON_RESERVED_WORDS.has(name) || isForbiddenKey(name)) {
|
|
762
|
+
name = `${name}Model`;
|
|
763
|
+
}
|
|
764
|
+
let unique = name;
|
|
765
|
+
let seq = 2;
|
|
766
|
+
while (used.has(unique) || PYTHON_RESERVED_WORDS.has(unique)) {
|
|
767
|
+
unique = `${name}${seq}`;
|
|
768
|
+
seq += 1;
|
|
769
|
+
}
|
|
770
|
+
used.add(unique);
|
|
771
|
+
return unique;
|
|
772
|
+
}
|
|
773
|
+
function tsString(raw) {
|
|
774
|
+
return JSON.stringify(raw)
|
|
775
|
+
.replace(/\u2028/g, "\\u2028")
|
|
776
|
+
.replace(/\u2029/g, "\\u2029");
|
|
777
|
+
}
|
|
778
|
+
function pyString(raw) {
|
|
779
|
+
let out = "\"";
|
|
780
|
+
for (let i = 0; i < raw.length; i++) {
|
|
781
|
+
const ch = raw[i];
|
|
782
|
+
const code = raw.charCodeAt(i);
|
|
783
|
+
if (ch === "\\")
|
|
784
|
+
out += "\\\\";
|
|
785
|
+
else if (ch === "\"")
|
|
786
|
+
out += "\\\"";
|
|
787
|
+
else if (ch === "\n")
|
|
788
|
+
out += "\\n";
|
|
789
|
+
else if (ch === "\r")
|
|
790
|
+
out += "\\r";
|
|
791
|
+
else if (ch === "\t")
|
|
792
|
+
out += "\\t";
|
|
793
|
+
else if (code < 0x20 || code === 0x7f)
|
|
794
|
+
out += `\\x${code.toString(16).padStart(2, "0")}`;
|
|
795
|
+
else if (code === 0x2028 || code === 0x2029)
|
|
796
|
+
out += `\\u${code.toString(16).padStart(4, "0")}`;
|
|
797
|
+
else
|
|
798
|
+
out += ch;
|
|
799
|
+
}
|
|
800
|
+
out += "\"";
|
|
801
|
+
return out;
|
|
802
|
+
}
|
|
803
|
+
function goString(raw) {
|
|
804
|
+
let out = "\"";
|
|
805
|
+
for (let i = 0; i < raw.length; i++) {
|
|
806
|
+
const ch = raw[i];
|
|
807
|
+
const code = raw.charCodeAt(i);
|
|
808
|
+
if (ch === "\\")
|
|
809
|
+
out += "\\\\";
|
|
810
|
+
else if (ch === "\"")
|
|
811
|
+
out += "\\\"";
|
|
812
|
+
else if (ch === "\n")
|
|
813
|
+
out += "\\n";
|
|
814
|
+
else if (ch === "\r")
|
|
815
|
+
out += "\\r";
|
|
816
|
+
else if (ch === "\t")
|
|
817
|
+
out += "\\t";
|
|
818
|
+
else if (code < 0x20 || code === 0x7f)
|
|
819
|
+
out += `\\x${code.toString(16).padStart(2, "0")}`;
|
|
820
|
+
else if (code === 0x2028 || code === 0x2029)
|
|
821
|
+
out += `\\u${code.toString(16).padStart(4, "0")}`;
|
|
822
|
+
else
|
|
823
|
+
out += ch;
|
|
824
|
+
}
|
|
825
|
+
out += "\"";
|
|
826
|
+
return out;
|
|
827
|
+
}
|
|
828
|
+
function safeCommentLine(raw, maxLen = 180) {
|
|
829
|
+
return sanitizeSingleLineText(raw, maxLen);
|
|
830
|
+
}
|
|
831
|
+
function isSimpleTsPropKey(key) {
|
|
832
|
+
return (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) &&
|
|
833
|
+
!isForbiddenKey(key));
|
|
834
|
+
}
|
|
835
|
+
function formatTsPropKey(key) {
|
|
836
|
+
return isSimpleTsPropKey(key) ? key : tsString(key);
|
|
837
|
+
}
|
|
838
|
+
// ============================================================================
|
|
839
|
+
// Endpoint Normalization
|
|
840
|
+
// ============================================================================
|
|
841
|
+
function deriveRouteTokens(method, pathname, id) {
|
|
842
|
+
const methodWord = method.toLowerCase();
|
|
843
|
+
const pathWords = splitToAsciiWords(pathname);
|
|
844
|
+
if (pathWords.length > 0) {
|
|
845
|
+
return [methodWord, ...pathWords];
|
|
846
|
+
}
|
|
847
|
+
const idWords = splitToAsciiWords(id).filter((w) => w !== "inv" && w !== "http");
|
|
848
|
+
if (idWords.length > 0) {
|
|
849
|
+
if (idWords[0] === methodWord)
|
|
850
|
+
return idWords;
|
|
851
|
+
return [methodWord, ...idWords];
|
|
852
|
+
}
|
|
853
|
+
return [methodWord, "root"];
|
|
854
|
+
}
|
|
855
|
+
function normalizeHttpInvariant(inv, usedTsMethods, usedPyMethods, usedGoMethods, usedPascalBases) {
|
|
856
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
857
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
858
|
+
const methodRaw = typeof input.method === "string" && input.method.replace(/[\r\n\0]+/g, "").trim()
|
|
859
|
+
? input.method.replace(/[\r\n\0]+/g, "").trim().toUpperCase()
|
|
860
|
+
: "GET";
|
|
861
|
+
if (!SUPPORTED_HTTP_METHODS.has(methodRaw)) {
|
|
862
|
+
return null;
|
|
863
|
+
}
|
|
864
|
+
const rawPath = typeof input.path === "string"
|
|
865
|
+
? input.path
|
|
866
|
+
: typeof input.urlPath === "string"
|
|
867
|
+
? input.urlPath
|
|
868
|
+
: undefined;
|
|
869
|
+
const { pathname, inlineQuery } = parsePathAndInlineQuery(rawPath);
|
|
870
|
+
const query = sanitizeQueryEntries(inlineQuery, input.query);
|
|
871
|
+
const headers = sanitizeHeaders(input.headers);
|
|
872
|
+
let hasBody = false;
|
|
873
|
+
let requestSchema;
|
|
874
|
+
if (BODY_HTTP_METHODS.has(methodRaw)) {
|
|
875
|
+
if (input.body !== undefined && input.body !== null) {
|
|
876
|
+
hasBody = true;
|
|
877
|
+
if (typeof input.body === "string") {
|
|
878
|
+
const trimmed = input.body.trim();
|
|
879
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
880
|
+
try {
|
|
881
|
+
const parsed = JSON.parse(trimmed);
|
|
882
|
+
requestSchema = inferSchemaFromValue(sanitizeJsonValue(parsed));
|
|
883
|
+
}
|
|
884
|
+
catch {
|
|
885
|
+
requestSchema = { type: "string" };
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
else {
|
|
889
|
+
requestSchema = { type: "string" };
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
else {
|
|
893
|
+
requestSchema = inferSchemaFromValue(sanitizeJsonValue(input.body));
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
else if (methodRaw === "POST" || methodRaw === "PUT" || methodRaw === "PATCH") {
|
|
897
|
+
hasBody = true;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
const expectedStatuses = extractExpectedStatuses(expected.status);
|
|
901
|
+
let expectedContentType;
|
|
902
|
+
if (isRecord(expected.headers)) {
|
|
903
|
+
for (const key of Object.keys(expected.headers)) {
|
|
904
|
+
if (isForbiddenKey(key))
|
|
905
|
+
continue;
|
|
906
|
+
if (key.trim().toLowerCase() === "content-type") {
|
|
907
|
+
const val = expected.headers[key];
|
|
908
|
+
if (typeof val === "string") {
|
|
909
|
+
expectedContentType = extractMediaType(val);
|
|
910
|
+
break;
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
let responseSchema;
|
|
916
|
+
let responseKind = "json";
|
|
917
|
+
if (expected.jsonSchema !== undefined && isRecord(expected.jsonSchema)) {
|
|
918
|
+
responseSchema = sanitizeSchemaNode(expected.jsonSchema);
|
|
919
|
+
responseKind = "json";
|
|
920
|
+
}
|
|
921
|
+
else if (expected.jsonSubset !== undefined) {
|
|
922
|
+
responseSchema = inferSchemaFromValue(sanitizeJsonValue(expected.jsonSubset));
|
|
923
|
+
responseKind = "json";
|
|
924
|
+
}
|
|
925
|
+
else if (typeof expected.bodyExact === "string" && expected.bodyExact.length > 0) {
|
|
926
|
+
const trimmed = expected.bodyExact.trim();
|
|
927
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
928
|
+
try {
|
|
929
|
+
const parsed = JSON.parse(trimmed);
|
|
930
|
+
responseSchema = inferSchemaFromValue(sanitizeJsonValue(parsed));
|
|
931
|
+
responseKind = "json";
|
|
932
|
+
}
|
|
933
|
+
catch {
|
|
934
|
+
responseSchema = { type: "string" };
|
|
935
|
+
responseKind = "text";
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
else {
|
|
939
|
+
responseSchema = { type: "string" };
|
|
940
|
+
responseKind = "text";
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
else if (methodRaw === "HEAD" ||
|
|
944
|
+
(expectedStatuses.length > 0 && expectedStatuses.every((s) => s === 204 || s === 205))) {
|
|
945
|
+
responseKind = "void";
|
|
946
|
+
}
|
|
947
|
+
else if (expectedContentType &&
|
|
948
|
+
!expectedContentType.includes("json") &&
|
|
949
|
+
(expectedContentType.startsWith("text/") || expectedContentType.includes("xml"))) {
|
|
950
|
+
responseKind = "text";
|
|
951
|
+
responseSchema = { type: "string" };
|
|
952
|
+
}
|
|
953
|
+
else if ((typeof expected.bodyContains === "string" && expected.bodyContains.length > 0) ||
|
|
954
|
+
(Array.isArray(expected.bodyContains) && expected.bodyContains.length > 0)) {
|
|
955
|
+
responseKind = "text";
|
|
956
|
+
responseSchema = { type: "string" };
|
|
957
|
+
}
|
|
958
|
+
else {
|
|
959
|
+
responseKind = "json";
|
|
960
|
+
}
|
|
961
|
+
const id = typeof inv.id === "string" && inv.id.trim()
|
|
962
|
+
? sanitizeSingleLineText(inv.id.trim(), 80)
|
|
963
|
+
: "unknown";
|
|
964
|
+
const rawSummary = typeof inv.description === "string" && inv.description.trim()
|
|
965
|
+
? sanitizeSingleLineText(inv.description, 160)
|
|
966
|
+
: "";
|
|
967
|
+
const summary = rawSummary || `${methodRaw} ${pathname}`;
|
|
968
|
+
const baseNameTokens = deriveRouteTokens(methodRaw, pathname, id);
|
|
969
|
+
const tsMethodName = safeTsIdentifier(toCamelCase(baseNameTokens, "requestEndpoint"), "call", usedTsMethods);
|
|
970
|
+
const pyMethodName = safePyIdentifier(toSnakeCase(baseNameTokens, "request_endpoint"), "call", usedPyMethods);
|
|
971
|
+
const goMethodName = safeGoExportedIdentifier(toPascalCase(baseNameTokens, "RequestEndpoint"), "Call", usedGoMethods);
|
|
972
|
+
let pascalBaseName = safeGoExportedIdentifier(toPascalCase(baseNameTokens, "Endpoint"), "Op", usedPascalBases);
|
|
973
|
+
while (usedPascalBases.has(`${pascalBaseName}Query`) ||
|
|
974
|
+
usedPascalBases.has(`${pascalBaseName}Request`) ||
|
|
975
|
+
usedPascalBases.has(`${pascalBaseName}Response`)) {
|
|
976
|
+
pascalBaseName = safeGoExportedIdentifier(`${pascalBaseName}Op`, "Op", usedPascalBases);
|
|
977
|
+
}
|
|
978
|
+
return {
|
|
979
|
+
id,
|
|
980
|
+
summary,
|
|
981
|
+
method: methodRaw,
|
|
982
|
+
pathname,
|
|
983
|
+
query,
|
|
984
|
+
headers,
|
|
985
|
+
hasBody,
|
|
986
|
+
...(requestSchema ? { requestSchema } : {}),
|
|
987
|
+
expectedStatuses,
|
|
988
|
+
responseKind,
|
|
989
|
+
...(responseSchema ? { responseSchema } : {}),
|
|
990
|
+
baseNameTokens,
|
|
991
|
+
tsMethodName,
|
|
992
|
+
pyMethodName,
|
|
993
|
+
goMethodName,
|
|
994
|
+
pascalBaseName
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
// ============================================================================
|
|
998
|
+
// Shared Schema Merging Helper (for Draft 2020-12 allOf)
|
|
999
|
+
// ============================================================================
|
|
1000
|
+
function mergeAllOfObjectBranches(branches, rootSchema) {
|
|
1001
|
+
const properties = Object.create(null);
|
|
1002
|
+
const required = new Set();
|
|
1003
|
+
let allObjects = branches.length > 0;
|
|
1004
|
+
let hasAnyProps = false;
|
|
1005
|
+
for (const rawBranch of branches) {
|
|
1006
|
+
const branch = typeof rawBranch.$ref === "string"
|
|
1007
|
+
? (resolveLocalRef(rootSchema, rawBranch.$ref) ?? rawBranch)
|
|
1008
|
+
: rawBranch;
|
|
1009
|
+
const isObjLike = branch.type === "object" ||
|
|
1010
|
+
isRecord(branch.properties) ||
|
|
1011
|
+
Array.isArray(branch.required);
|
|
1012
|
+
if (!isObjLike) {
|
|
1013
|
+
allObjects = false;
|
|
1014
|
+
break;
|
|
1015
|
+
}
|
|
1016
|
+
if (isRecord(branch.properties)) {
|
|
1017
|
+
for (const k of Object.keys(branch.properties)) {
|
|
1018
|
+
if (isForbiddenKey(k))
|
|
1019
|
+
continue;
|
|
1020
|
+
properties[k] = branch.properties[k];
|
|
1021
|
+
hasAnyProps = true;
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
if (Array.isArray(branch.required)) {
|
|
1025
|
+
for (const reqKey of branch.required) {
|
|
1026
|
+
if (typeof reqKey === "string" && !isForbiddenKey(reqKey)) {
|
|
1027
|
+
required.add(reqKey);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
return {
|
|
1033
|
+
allObjects: allObjects && hasAnyProps,
|
|
1034
|
+
merged: {
|
|
1035
|
+
type: "object",
|
|
1036
|
+
properties,
|
|
1037
|
+
...(required.size > 0 ? { required: [...required] } : {})
|
|
1038
|
+
}
|
|
1039
|
+
};
|
|
1040
|
+
}
|
|
1041
|
+
// ============================================================================
|
|
1042
|
+
// 1. TypeScript (`ts-fetch`) Codegen
|
|
1043
|
+
// ============================================================================
|
|
1044
|
+
function renderTsLiteral(value) {
|
|
1045
|
+
if (value === null)
|
|
1046
|
+
return "null";
|
|
1047
|
+
if (typeof value === "boolean")
|
|
1048
|
+
return value ? "true" : "false";
|
|
1049
|
+
if (typeof value === "number")
|
|
1050
|
+
return Number.isFinite(value) ? String(value) : null;
|
|
1051
|
+
if (typeof value === "string")
|
|
1052
|
+
return tsString(value);
|
|
1053
|
+
return null;
|
|
1054
|
+
}
|
|
1055
|
+
function schemaToTsType(schema, rootSchema, depth = 0, seen = new Set(), indent = 0) {
|
|
1056
|
+
if (!schema || !isRecord(schema))
|
|
1057
|
+
return "unknown";
|
|
1058
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1059
|
+
return "unknown";
|
|
1060
|
+
if (seen.has(schema))
|
|
1061
|
+
return "unknown";
|
|
1062
|
+
seen.add(schema);
|
|
1063
|
+
try {
|
|
1064
|
+
if (typeof schema.$ref === "string") {
|
|
1065
|
+
const target = resolveLocalRef(rootSchema, schema.$ref);
|
|
1066
|
+
if (target) {
|
|
1067
|
+
return schemaToTsType(target, rootSchema, depth + 1, seen, indent);
|
|
1068
|
+
}
|
|
1069
|
+
return "unknown";
|
|
1070
|
+
}
|
|
1071
|
+
if (schema.const !== undefined) {
|
|
1072
|
+
const lit = renderTsLiteral(schema.const);
|
|
1073
|
+
return lit ?? "unknown";
|
|
1074
|
+
}
|
|
1075
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
1076
|
+
const lits = [
|
|
1077
|
+
...new Set(schema.enum
|
|
1078
|
+
.map((item) => renderTsLiteral(item))
|
|
1079
|
+
.filter((item) => item !== null))
|
|
1080
|
+
];
|
|
1081
|
+
if (lits.length > 0) {
|
|
1082
|
+
const union = lits.join(" | ");
|
|
1083
|
+
return schema.nullable && !lits.includes("null") ? `${union} | null` : union;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
1087
|
+
const parts = [
|
|
1088
|
+
...new Set(schema.oneOf.map((branch) => {
|
|
1089
|
+
const t = schemaToTsType(branch, rootSchema, depth + 1, seen, indent);
|
|
1090
|
+
return t.includes(" & ") ? `(${t})` : t;
|
|
1091
|
+
}))
|
|
1092
|
+
];
|
|
1093
|
+
const joined = parts.join(" | ");
|
|
1094
|
+
return schema.nullable && !parts.includes("null") ? `(${joined}) | null` : joined;
|
|
1095
|
+
}
|
|
1096
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
1097
|
+
const parts = [
|
|
1098
|
+
...new Set(schema.anyOf.map((branch) => {
|
|
1099
|
+
const t = schemaToTsType(branch, rootSchema, depth + 1, seen, indent);
|
|
1100
|
+
return t.includes(" & ") ? `(${t})` : t;
|
|
1101
|
+
}))
|
|
1102
|
+
];
|
|
1103
|
+
const joined = parts.join(" | ");
|
|
1104
|
+
return schema.nullable && !parts.includes("null") ? `(${joined}) | null` : joined;
|
|
1105
|
+
}
|
|
1106
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1107
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema);
|
|
1108
|
+
if (allObjects) {
|
|
1109
|
+
const mergedType = schemaToTsType(merged, rootSchema, depth + 1, seen, indent);
|
|
1110
|
+
return schema.nullable ? `(${mergedType}) | null` : mergedType;
|
|
1111
|
+
}
|
|
1112
|
+
const parts = [
|
|
1113
|
+
...new Set(schema.allOf.map((branch) => {
|
|
1114
|
+
const t = schemaToTsType(branch, rootSchema, depth + 1, seen, indent);
|
|
1115
|
+
return t.includes(" | ") ? `(${t})` : t;
|
|
1116
|
+
}))
|
|
1117
|
+
];
|
|
1118
|
+
const joined = parts.join(" & ");
|
|
1119
|
+
return schema.nullable ? `(${joined}) | null` : joined;
|
|
1120
|
+
}
|
|
1121
|
+
const rawType = schema.type;
|
|
1122
|
+
if (Array.isArray(rawType) && rawType.length > 0) {
|
|
1123
|
+
const parts = [
|
|
1124
|
+
...new Set(rawType.map((singleType) => schemaToTsType({ ...schema, type: singleType, nullable: false }, rootSchema, depth + 1, seen, indent)))
|
|
1125
|
+
];
|
|
1126
|
+
const joined = parts.join(" | ");
|
|
1127
|
+
return schema.nullable && !parts.includes("null") ? `${joined} | null` : joined;
|
|
1128
|
+
}
|
|
1129
|
+
const effectiveType = typeof rawType === "string"
|
|
1130
|
+
? rawType
|
|
1131
|
+
: isRecord(schema.properties) || schema.additionalProperties !== undefined
|
|
1132
|
+
? "object"
|
|
1133
|
+
: schema.items !== undefined || Array.isArray(schema.prefixItems)
|
|
1134
|
+
? "array"
|
|
1135
|
+
: undefined;
|
|
1136
|
+
let result;
|
|
1137
|
+
if (effectiveType === "string") {
|
|
1138
|
+
result = "string";
|
|
1139
|
+
}
|
|
1140
|
+
else if (effectiveType === "number" || effectiveType === "integer") {
|
|
1141
|
+
result = "number";
|
|
1142
|
+
}
|
|
1143
|
+
else if (effectiveType === "boolean") {
|
|
1144
|
+
result = "boolean";
|
|
1145
|
+
}
|
|
1146
|
+
else if (effectiveType === "null") {
|
|
1147
|
+
return "null";
|
|
1148
|
+
}
|
|
1149
|
+
else if (effectiveType === "array") {
|
|
1150
|
+
const tupleItems = Array.isArray(schema.prefixItems)
|
|
1151
|
+
? schema.prefixItems
|
|
1152
|
+
: Array.isArray(schema.items)
|
|
1153
|
+
? schema.items
|
|
1154
|
+
: undefined;
|
|
1155
|
+
if (tupleItems && tupleItems.length > 0) {
|
|
1156
|
+
const elems = tupleItems.map((item) => schemaToTsType(item, rootSchema, depth + 1, seen, indent));
|
|
1157
|
+
result = `[${elems.join(", ")}]`;
|
|
1158
|
+
}
|
|
1159
|
+
else if (isRecord(schema.items)) {
|
|
1160
|
+
const elemType = schemaToTsType(schema.items, rootSchema, depth + 1, seen, indent);
|
|
1161
|
+
result = elemType.includes(" | ") || elemType.includes(" & ") || elemType.includes("\n")
|
|
1162
|
+
? `Array<${elemType}>`
|
|
1163
|
+
: `${elemType}[]`;
|
|
1164
|
+
}
|
|
1165
|
+
else {
|
|
1166
|
+
result = "unknown[]";
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
else if (effectiveType === "object") {
|
|
1170
|
+
const props = isRecord(schema.properties) ? schema.properties : undefined;
|
|
1171
|
+
const propKeys = props ? Object.keys(props).filter((k) => !isForbiddenKey(k)) : [];
|
|
1172
|
+
if (propKeys.length === 0) {
|
|
1173
|
+
if (isRecord(schema.additionalProperties)) {
|
|
1174
|
+
const valType = schemaToTsType(schema.additionalProperties, rootSchema, depth + 1, seen, indent);
|
|
1175
|
+
result = `Record<string, ${valType}>`;
|
|
1176
|
+
}
|
|
1177
|
+
else if (schema.additionalProperties === false) {
|
|
1178
|
+
result = "Record<string, never>";
|
|
1179
|
+
}
|
|
1180
|
+
else {
|
|
1181
|
+
result = "Record<string, unknown>";
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
else {
|
|
1185
|
+
const reqSet = new Set(Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === "string") : []);
|
|
1186
|
+
const pad = " ".repeat(indent + 2);
|
|
1187
|
+
const closePad = " ".repeat(indent);
|
|
1188
|
+
const lines = ["{"];
|
|
1189
|
+
for (const key of propKeys) {
|
|
1190
|
+
const optionalMark = reqSet.has(key) ? "" : "?";
|
|
1191
|
+
const fieldType = schemaToTsType(props[key], rootSchema, depth + 1, seen, indent + 2);
|
|
1192
|
+
lines.push(`${pad}${formatTsPropKey(key)}${optionalMark}: ${fieldType};`);
|
|
1193
|
+
}
|
|
1194
|
+
lines.push(`${closePad}}`);
|
|
1195
|
+
result = lines.join("\n");
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
else {
|
|
1199
|
+
result = "unknown";
|
|
1200
|
+
}
|
|
1201
|
+
if (schema.nullable && result !== "null" && result !== "unknown") {
|
|
1202
|
+
return result.includes("\n") || result.includes(" & ") ? `(${result}) | null` : `${result} | null`;
|
|
1203
|
+
}
|
|
1204
|
+
return result;
|
|
1205
|
+
}
|
|
1206
|
+
finally {
|
|
1207
|
+
seen.delete(schema);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
function emitTsObjectInterfaceBody(schema, rootSchema) {
|
|
1211
|
+
let target = schema;
|
|
1212
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1213
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema);
|
|
1214
|
+
if (!allObjects)
|
|
1215
|
+
return null;
|
|
1216
|
+
target = merged;
|
|
1217
|
+
}
|
|
1218
|
+
if (target.nullable ||
|
|
1219
|
+
Array.isArray(target.oneOf) ||
|
|
1220
|
+
Array.isArray(target.anyOf) ||
|
|
1221
|
+
Array.isArray(target.enum) ||
|
|
1222
|
+
target.const !== undefined) {
|
|
1223
|
+
return null;
|
|
1224
|
+
}
|
|
1225
|
+
const effectiveType = typeof target.type === "string"
|
|
1226
|
+
? target.type
|
|
1227
|
+
: isRecord(target.properties)
|
|
1228
|
+
? "object"
|
|
1229
|
+
: undefined;
|
|
1230
|
+
if (effectiveType !== "object" || !isRecord(target.properties))
|
|
1231
|
+
return null;
|
|
1232
|
+
const propKeys = Object.keys(target.properties).filter((k) => !isForbiddenKey(k));
|
|
1233
|
+
if (propKeys.length === 0)
|
|
1234
|
+
return null;
|
|
1235
|
+
const reqSet = new Set(Array.isArray(target.required) ? target.required.filter((r) => typeof r === "string") : []);
|
|
1236
|
+
const lines = [];
|
|
1237
|
+
for (const key of propKeys) {
|
|
1238
|
+
const optionalMark = reqSet.has(key) ? "" : "?";
|
|
1239
|
+
const fieldType = schemaToTsType(target.properties[key], rootSchema, 1, new Set(), 2);
|
|
1240
|
+
lines.push(` ${formatTsPropKey(key)}${optionalMark}: ${fieldType};`);
|
|
1241
|
+
}
|
|
1242
|
+
return lines;
|
|
1243
|
+
}
|
|
1244
|
+
function emitTypeScriptClient(endpoints, baseUrl, title, className, skippedIds, includeSkippedComments) {
|
|
1245
|
+
const lines = [
|
|
1246
|
+
"// Generated by vibecode-anything -- Typed Fetch API Client",
|
|
1247
|
+
`// Title: ${safeCommentLine(title)}`,
|
|
1248
|
+
`// Default base URL: ${safeCommentLine(baseUrl)}`,
|
|
1249
|
+
"// Zero external dependencies -- compatible with Node 24 native TypeScript and strict tsc.",
|
|
1250
|
+
"",
|
|
1251
|
+
"export interface ClientOptions {",
|
|
1252
|
+
" baseUrl?: string;",
|
|
1253
|
+
" headers?: Record<string, string>;",
|
|
1254
|
+
" fetch?: typeof fetch;",
|
|
1255
|
+
"}",
|
|
1256
|
+
"",
|
|
1257
|
+
"export interface RequestOptions<TQuery = Record<string, string | number | boolean | undefined>> {",
|
|
1258
|
+
" query?: TQuery;",
|
|
1259
|
+
" headers?: Record<string, string>;",
|
|
1260
|
+
" init?: Omit<RequestInit, \"method\" | \"headers\" | \"body\">;",
|
|
1261
|
+
"}",
|
|
1262
|
+
"",
|
|
1263
|
+
"export class ApiClientError extends Error {",
|
|
1264
|
+
" readonly status: number;",
|
|
1265
|
+
" readonly expectedStatuses: readonly number[];",
|
|
1266
|
+
" readonly method: string;",
|
|
1267
|
+
" readonly url: string;",
|
|
1268
|
+
" readonly responseBody: string;",
|
|
1269
|
+
"",
|
|
1270
|
+
" constructor(",
|
|
1271
|
+
" message: string,",
|
|
1272
|
+
" details: {",
|
|
1273
|
+
" status: number;",
|
|
1274
|
+
" expectedStatuses: readonly number[];",
|
|
1275
|
+
" method: string;",
|
|
1276
|
+
" url: string;",
|
|
1277
|
+
" responseBody: string;",
|
|
1278
|
+
" }",
|
|
1279
|
+
" ) {",
|
|
1280
|
+
" super(message);",
|
|
1281
|
+
" this.name = \"ApiClientError\";",
|
|
1282
|
+
" this.status = details.status;",
|
|
1283
|
+
" this.expectedStatuses = details.expectedStatuses;",
|
|
1284
|
+
" this.method = details.method;",
|
|
1285
|
+
" this.url = details.url;",
|
|
1286
|
+
" this.responseBody = details.responseBody;",
|
|
1287
|
+
" }",
|
|
1288
|
+
"}",
|
|
1289
|
+
""
|
|
1290
|
+
];
|
|
1291
|
+
// Emit per-endpoint types
|
|
1292
|
+
for (const ep of endpoints) {
|
|
1293
|
+
if (ep.query.length > 0) {
|
|
1294
|
+
lines.push(`export interface ${ep.pascalBaseName}Query {`);
|
|
1295
|
+
for (const [qKey] of ep.query) {
|
|
1296
|
+
lines.push(` ${formatTsPropKey(qKey)}?: string | number | boolean;`);
|
|
1297
|
+
}
|
|
1298
|
+
lines.push(" [key: string]: string | number | boolean | undefined;");
|
|
1299
|
+
lines.push("}");
|
|
1300
|
+
lines.push("");
|
|
1301
|
+
}
|
|
1302
|
+
if (ep.hasBody) {
|
|
1303
|
+
const reqTypeName = `${ep.pascalBaseName}Request`;
|
|
1304
|
+
if (ep.requestSchema) {
|
|
1305
|
+
const bodyLines = emitTsObjectInterfaceBody(ep.requestSchema, ep.requestSchema);
|
|
1306
|
+
if (bodyLines) {
|
|
1307
|
+
lines.push(`export interface ${reqTypeName} {`);
|
|
1308
|
+
lines.push(...bodyLines);
|
|
1309
|
+
lines.push("}");
|
|
1310
|
+
}
|
|
1311
|
+
else {
|
|
1312
|
+
const rendered = schemaToTsType(ep.requestSchema, ep.requestSchema, 0, new Set(), 0);
|
|
1313
|
+
lines.push(`export type ${reqTypeName} = ${rendered};`);
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
else {
|
|
1317
|
+
lines.push(`export type ${reqTypeName} = unknown;`);
|
|
1318
|
+
}
|
|
1319
|
+
lines.push("");
|
|
1320
|
+
}
|
|
1321
|
+
const resTypeName = `${ep.pascalBaseName}Response`;
|
|
1322
|
+
if (ep.responseKind === "void") {
|
|
1323
|
+
lines.push(`export type ${resTypeName} = void;`);
|
|
1324
|
+
}
|
|
1325
|
+
else if (ep.responseKind === "text") {
|
|
1326
|
+
lines.push(`export type ${resTypeName} = string;`);
|
|
1327
|
+
}
|
|
1328
|
+
else if (ep.responseSchema) {
|
|
1329
|
+
const resLines = emitTsObjectInterfaceBody(ep.responseSchema, ep.responseSchema);
|
|
1330
|
+
if (resLines) {
|
|
1331
|
+
lines.push(`export interface ${resTypeName} {`);
|
|
1332
|
+
lines.push(...resLines);
|
|
1333
|
+
lines.push("}");
|
|
1334
|
+
}
|
|
1335
|
+
else {
|
|
1336
|
+
const rendered = schemaToTsType(ep.responseSchema, ep.responseSchema, 0, new Set(), 0);
|
|
1337
|
+
lines.push(`export type ${resTypeName} = ${rendered};`);
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
else {
|
|
1341
|
+
lines.push(`export type ${resTypeName} = unknown;`);
|
|
1342
|
+
}
|
|
1343
|
+
lines.push("");
|
|
1344
|
+
}
|
|
1345
|
+
// Emit client class
|
|
1346
|
+
lines.push(`export class ${className} {`);
|
|
1347
|
+
lines.push(" readonly baseUrl: string;");
|
|
1348
|
+
lines.push(" readonly defaultHeaders: Record<string, string>;");
|
|
1349
|
+
lines.push(" private readonly fetchImpl: typeof fetch;");
|
|
1350
|
+
lines.push("");
|
|
1351
|
+
lines.push(" constructor(options: ClientOptions = {}) {");
|
|
1352
|
+
lines.push(` const rawBase = options.baseUrl ?? ${tsString(baseUrl)};`);
|
|
1353
|
+
lines.push(" this.baseUrl = rawBase.replace(/\\/+$/, \"\");");
|
|
1354
|
+
lines.push(" this.defaultHeaders = {};");
|
|
1355
|
+
lines.push(" if (options.headers) {");
|
|
1356
|
+
lines.push(" for (const [k, v] of Object.entries(options.headers)) {");
|
|
1357
|
+
lines.push(" if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") continue;");
|
|
1358
|
+
lines.push(" this.defaultHeaders[k] = v;");
|
|
1359
|
+
lines.push(" }");
|
|
1360
|
+
lines.push(" }");
|
|
1361
|
+
lines.push(" this.fetchImpl = options.fetch ?? globalThis.fetch;");
|
|
1362
|
+
lines.push(" }");
|
|
1363
|
+
lines.push("");
|
|
1364
|
+
lines.push(" private async request<T>(");
|
|
1365
|
+
lines.push(" method: string,");
|
|
1366
|
+
lines.push(" routePath: string,");
|
|
1367
|
+
lines.push(" expectedStatuses: readonly number[],");
|
|
1368
|
+
lines.push(" responseKind: \"json\" | \"text\" | \"void\",");
|
|
1369
|
+
lines.push(" defaultQuery: Record<string, string>,");
|
|
1370
|
+
lines.push(" defaultHeaders: Record<string, string>,");
|
|
1371
|
+
lines.push(" body?: unknown,");
|
|
1372
|
+
lines.push(" options?: {");
|
|
1373
|
+
lines.push(" query?: object;");
|
|
1374
|
+
lines.push(" headers?: Record<string, string>;");
|
|
1375
|
+
lines.push(" init?: Omit<RequestInit, \"method\" | \"headers\" | \"body\">;");
|
|
1376
|
+
lines.push(" }");
|
|
1377
|
+
lines.push(" ): Promise<T> {");
|
|
1378
|
+
lines.push(" const url = new URL(`${this.baseUrl}${routePath}`);");
|
|
1379
|
+
lines.push(" const mergedQuery = new Map<string, string>();");
|
|
1380
|
+
lines.push(" for (const [k, v] of Object.entries(defaultQuery)) {");
|
|
1381
|
+
lines.push(" mergedQuery.set(k, v);");
|
|
1382
|
+
lines.push(" }");
|
|
1383
|
+
lines.push(" if (options?.query) {");
|
|
1384
|
+
lines.push(" for (const [k, v] of Object.entries(options.query as Record<string, unknown>)) {");
|
|
1385
|
+
lines.push(" if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") continue;");
|
|
1386
|
+
lines.push(" if (v === undefined) {");
|
|
1387
|
+
lines.push(" mergedQuery.delete(k);");
|
|
1388
|
+
lines.push(" } else {");
|
|
1389
|
+
lines.push(" mergedQuery.set(k, String(v));");
|
|
1390
|
+
lines.push(" }");
|
|
1391
|
+
lines.push(" }");
|
|
1392
|
+
lines.push(" }");
|
|
1393
|
+
lines.push(" for (const [k, v] of mergedQuery.entries()) {");
|
|
1394
|
+
lines.push(" url.searchParams.set(k, v);");
|
|
1395
|
+
lines.push(" }");
|
|
1396
|
+
lines.push("");
|
|
1397
|
+
lines.push(" const headers: Record<string, string> = {};");
|
|
1398
|
+
lines.push(" const applyHeaders = (src?: Record<string, string>): void => {");
|
|
1399
|
+
lines.push(" if (!src) return;");
|
|
1400
|
+
lines.push(" for (const [k, v] of Object.entries(src)) {");
|
|
1401
|
+
lines.push(" if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") continue;");
|
|
1402
|
+
lines.push(" headers[k] = v;");
|
|
1403
|
+
lines.push(" }");
|
|
1404
|
+
lines.push(" };");
|
|
1405
|
+
lines.push(" applyHeaders(defaultHeaders);");
|
|
1406
|
+
lines.push(" applyHeaders(this.defaultHeaders);");
|
|
1407
|
+
lines.push(" applyHeaders(options?.headers);");
|
|
1408
|
+
lines.push("");
|
|
1409
|
+
lines.push(" let serializedBody: string | undefined;");
|
|
1410
|
+
lines.push(" if (body !== undefined) {");
|
|
1411
|
+
lines.push(" if (typeof body === \"string\") {");
|
|
1412
|
+
lines.push(" serializedBody = body;");
|
|
1413
|
+
lines.push(" } else {");
|
|
1414
|
+
lines.push(" serializedBody = JSON.stringify(body);");
|
|
1415
|
+
lines.push(" const hasContentType = Object.keys(headers).some((k) => k.toLowerCase() === \"content-type\");");
|
|
1416
|
+
lines.push(" if (!hasContentType) {");
|
|
1417
|
+
lines.push(" headers[\"Content-Type\"] = \"application/json\";");
|
|
1418
|
+
lines.push(" }");
|
|
1419
|
+
lines.push(" }");
|
|
1420
|
+
lines.push(" }");
|
|
1421
|
+
lines.push("");
|
|
1422
|
+
lines.push(" const response = await this.fetchImpl(url.toString(), {");
|
|
1423
|
+
lines.push(" ...(options?.init ?? {}),");
|
|
1424
|
+
lines.push(" method,");
|
|
1425
|
+
lines.push(" headers,");
|
|
1426
|
+
lines.push(" ...(serializedBody !== undefined ? { body: serializedBody } : {})");
|
|
1427
|
+
lines.push(" });");
|
|
1428
|
+
lines.push("");
|
|
1429
|
+
lines.push(" const statusOk =");
|
|
1430
|
+
lines.push(" expectedStatuses.length > 0");
|
|
1431
|
+
lines.push(" ? expectedStatuses.includes(response.status)");
|
|
1432
|
+
lines.push(" : response.ok;");
|
|
1433
|
+
lines.push("");
|
|
1434
|
+
lines.push(" if (!statusOk) {");
|
|
1435
|
+
lines.push(" const text = await response.text().catch(() => \"\");");
|
|
1436
|
+
lines.push(" const snippet = text.length > 300 ? `${text.slice(0, 300)}...` : text;");
|
|
1437
|
+
lines.push(" const expectedDesc = expectedStatuses.length > 0 ? expectedStatuses.join(\", \") : \"2xx\";");
|
|
1438
|
+
lines.push(" throw new ApiClientError(");
|
|
1439
|
+
lines.push(" `${method} ${routePath} failed: expected status ${expectedDesc}, got ${response.status}${snippet ? ` (${snippet})` : \"\"}`,");
|
|
1440
|
+
lines.push(" {");
|
|
1441
|
+
lines.push(" status: response.status,");
|
|
1442
|
+
lines.push(" expectedStatuses,");
|
|
1443
|
+
lines.push(" method,");
|
|
1444
|
+
lines.push(" url: url.toString(),");
|
|
1445
|
+
lines.push(" responseBody: snippet");
|
|
1446
|
+
lines.push(" }");
|
|
1447
|
+
lines.push(" );");
|
|
1448
|
+
lines.push(" }");
|
|
1449
|
+
lines.push("");
|
|
1450
|
+
lines.push(" if (responseKind === \"void\" || response.status === 204 || response.status === 205) {");
|
|
1451
|
+
lines.push(" return undefined as T;");
|
|
1452
|
+
lines.push(" }");
|
|
1453
|
+
lines.push("");
|
|
1454
|
+
lines.push(" const rawText = await response.text();");
|
|
1455
|
+
lines.push(" if (responseKind === \"text\") {");
|
|
1456
|
+
lines.push(" return rawText as T;");
|
|
1457
|
+
lines.push(" }");
|
|
1458
|
+
lines.push(" if (!rawText) {");
|
|
1459
|
+
lines.push(" return undefined as T;");
|
|
1460
|
+
lines.push(" }");
|
|
1461
|
+
lines.push(" return JSON.parse(rawText) as T;");
|
|
1462
|
+
lines.push(" }");
|
|
1463
|
+
for (const ep of endpoints) {
|
|
1464
|
+
const queryType = ep.query.length > 0
|
|
1465
|
+
? `${ep.pascalBaseName}Query`
|
|
1466
|
+
: "Record<string, string | number | boolean | undefined>";
|
|
1467
|
+
const resType = `${ep.pascalBaseName}Response`;
|
|
1468
|
+
const defaultQueryObj = ep.query.length > 0
|
|
1469
|
+
? `{ ${ep.query.map(([k, v]) => `${tsString(k)}: ${tsString(v)}`).join(", ")} }`
|
|
1470
|
+
: "{}";
|
|
1471
|
+
const defaultHeadersObj = ep.headers.length > 0
|
|
1472
|
+
? `{ ${ep.headers.map(([k, v]) => `${tsString(k)}: ${tsString(v)}`).join(", ")} }`
|
|
1473
|
+
: "{}";
|
|
1474
|
+
const statusesArr = `[${ep.expectedStatuses.join(", ")}]`;
|
|
1475
|
+
lines.push("");
|
|
1476
|
+
lines.push(` /** ${safeCommentLine(ep.summary)} (${ep.method} ${safeCommentLine(ep.pathname)}) */`);
|
|
1477
|
+
if (ep.hasBody) {
|
|
1478
|
+
const reqType = `${ep.pascalBaseName}Request`;
|
|
1479
|
+
lines.push(` async ${ep.tsMethodName}(body?: ${reqType}, options?: RequestOptions<${queryType}>): Promise<${resType}> {`);
|
|
1480
|
+
lines.push(` return this.request<${resType}>(`);
|
|
1481
|
+
lines.push(` ${tsString(ep.method)},`);
|
|
1482
|
+
lines.push(` ${tsString(ep.pathname)},`);
|
|
1483
|
+
lines.push(` ${statusesArr},`);
|
|
1484
|
+
lines.push(` ${tsString(ep.responseKind)},`);
|
|
1485
|
+
lines.push(` ${defaultQueryObj},`);
|
|
1486
|
+
lines.push(` ${defaultHeadersObj},`);
|
|
1487
|
+
lines.push(" body,");
|
|
1488
|
+
lines.push(" options");
|
|
1489
|
+
lines.push(" );");
|
|
1490
|
+
lines.push(" }");
|
|
1491
|
+
}
|
|
1492
|
+
else {
|
|
1493
|
+
lines.push(` async ${ep.tsMethodName}(options?: RequestOptions<${queryType}>): Promise<${resType}> {`);
|
|
1494
|
+
lines.push(` return this.request<${resType}>(`);
|
|
1495
|
+
lines.push(` ${tsString(ep.method)},`);
|
|
1496
|
+
lines.push(` ${tsString(ep.pathname)},`);
|
|
1497
|
+
lines.push(` ${statusesArr},`);
|
|
1498
|
+
lines.push(` ${tsString(ep.responseKind)},`);
|
|
1499
|
+
lines.push(` ${defaultQueryObj},`);
|
|
1500
|
+
lines.push(` ${defaultHeadersObj},`);
|
|
1501
|
+
lines.push(" undefined,");
|
|
1502
|
+
lines.push(" options");
|
|
1503
|
+
lines.push(" );");
|
|
1504
|
+
lines.push(" }");
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
lines.push("}");
|
|
1508
|
+
lines.push("");
|
|
1509
|
+
lines.push(`export function createClient(options: ClientOptions = {}): ${className} {`);
|
|
1510
|
+
lines.push(` return new ${className}(options);`);
|
|
1511
|
+
lines.push("}");
|
|
1512
|
+
if (includeSkippedComments && skippedIds.length > 0) {
|
|
1513
|
+
lines.push("");
|
|
1514
|
+
lines.push(`// Skipped non-HTTP invariants (${skippedIds.length}): ${skippedIds.map((s) => safeCommentLine(s, 60)).join(", ")}`);
|
|
1515
|
+
}
|
|
1516
|
+
lines.push("");
|
|
1517
|
+
return lines.join("\n");
|
|
1518
|
+
}
|
|
1519
|
+
function renderPyLiteral(value) {
|
|
1520
|
+
if (value === null)
|
|
1521
|
+
return "None";
|
|
1522
|
+
if (typeof value === "boolean")
|
|
1523
|
+
return value ? "True" : "False";
|
|
1524
|
+
if (typeof value === "number")
|
|
1525
|
+
return Number.isFinite(value) && Number.isInteger(value) ? String(value) : null;
|
|
1526
|
+
if (typeof value === "string")
|
|
1527
|
+
return pyString(value);
|
|
1528
|
+
return null;
|
|
1529
|
+
}
|
|
1530
|
+
function schemaToPyType(schema, rootSchema, hintName, ctx, depth = 0, seen = new Set()) {
|
|
1531
|
+
if (!schema || !isRecord(schema))
|
|
1532
|
+
return "Any";
|
|
1533
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1534
|
+
return "Any";
|
|
1535
|
+
if (seen.has(schema))
|
|
1536
|
+
return "Any";
|
|
1537
|
+
seen.add(schema);
|
|
1538
|
+
try {
|
|
1539
|
+
if (typeof schema.$ref === "string") {
|
|
1540
|
+
const target = resolveLocalRef(rootSchema, schema.$ref);
|
|
1541
|
+
if (target) {
|
|
1542
|
+
return schemaToPyType(target, rootSchema, hintName, ctx, depth + 1, seen);
|
|
1543
|
+
}
|
|
1544
|
+
return "Any";
|
|
1545
|
+
}
|
|
1546
|
+
if (schema.const !== undefined) {
|
|
1547
|
+
const lit = renderPyLiteral(schema.const);
|
|
1548
|
+
if (lit === "None")
|
|
1549
|
+
return "None";
|
|
1550
|
+
return lit ? `Literal[${lit}]` : "Any";
|
|
1551
|
+
}
|
|
1552
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
1553
|
+
const nonNullLits = [];
|
|
1554
|
+
let hasNull = Boolean(schema.nullable);
|
|
1555
|
+
let allRepresentable = true;
|
|
1556
|
+
for (const item of schema.enum) {
|
|
1557
|
+
if (item === null) {
|
|
1558
|
+
hasNull = true;
|
|
1559
|
+
continue;
|
|
1560
|
+
}
|
|
1561
|
+
const lit = renderPyLiteral(item);
|
|
1562
|
+
if (!lit) {
|
|
1563
|
+
allRepresentable = false;
|
|
1564
|
+
break;
|
|
1565
|
+
}
|
|
1566
|
+
if (!nonNullLits.includes(lit))
|
|
1567
|
+
nonNullLits.push(lit);
|
|
1568
|
+
}
|
|
1569
|
+
if (allRepresentable && nonNullLits.length > 0) {
|
|
1570
|
+
const base = `Literal[${nonNullLits.join(", ")}]`;
|
|
1571
|
+
return hasNull ? `Optional[${base}]` : base;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
1575
|
+
const parts = [
|
|
1576
|
+
...new Set(schema.oneOf.map((branch, idx) => schemaToPyType(branch, rootSchema, `${hintName}Option${idx + 1}`, ctx, depth + 1, seen)))
|
|
1577
|
+
];
|
|
1578
|
+
if (schema.nullable && !parts.includes("None"))
|
|
1579
|
+
parts.push("None");
|
|
1580
|
+
return parts.length === 1 ? parts[0] : `Union[${parts.join(", ")}]`;
|
|
1581
|
+
}
|
|
1582
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
1583
|
+
const parts = [
|
|
1584
|
+
...new Set(schema.anyOf.map((branch, idx) => schemaToPyType(branch, rootSchema, `${hintName}Variant${idx + 1}`, ctx, depth + 1, seen)))
|
|
1585
|
+
];
|
|
1586
|
+
if (schema.nullable && !parts.includes("None"))
|
|
1587
|
+
parts.push("None");
|
|
1588
|
+
return parts.length === 1 ? parts[0] : `Union[${parts.join(", ")}]`;
|
|
1589
|
+
}
|
|
1590
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1591
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema);
|
|
1592
|
+
if (allObjects) {
|
|
1593
|
+
const mergedType = schemaToPyType(merged, rootSchema, hintName, ctx, depth + 1, seen);
|
|
1594
|
+
return schema.nullable ? `Optional[${mergedType}]` : mergedType;
|
|
1595
|
+
}
|
|
1596
|
+
return "Any";
|
|
1597
|
+
}
|
|
1598
|
+
const rawType = schema.type;
|
|
1599
|
+
if (Array.isArray(rawType) && rawType.length > 0) {
|
|
1600
|
+
const parts = [
|
|
1601
|
+
...new Set(rawType.map((singleType) => schemaToPyType({ ...schema, type: singleType, nullable: false }, rootSchema, hintName, ctx, depth + 1, seen)))
|
|
1602
|
+
];
|
|
1603
|
+
if (schema.nullable && !parts.includes("None"))
|
|
1604
|
+
parts.push("None");
|
|
1605
|
+
return parts.length === 1 ? parts[0] : `Union[${parts.join(", ")}]`;
|
|
1606
|
+
}
|
|
1607
|
+
const effectiveType = typeof rawType === "string"
|
|
1608
|
+
? rawType
|
|
1609
|
+
: isRecord(schema.properties) || schema.additionalProperties !== undefined
|
|
1610
|
+
? "object"
|
|
1611
|
+
: schema.items !== undefined || Array.isArray(schema.prefixItems)
|
|
1612
|
+
? "array"
|
|
1613
|
+
: undefined;
|
|
1614
|
+
let result;
|
|
1615
|
+
if (effectiveType === "string") {
|
|
1616
|
+
result = "str";
|
|
1617
|
+
}
|
|
1618
|
+
else if (effectiveType === "integer") {
|
|
1619
|
+
result = "int";
|
|
1620
|
+
}
|
|
1621
|
+
else if (effectiveType === "number") {
|
|
1622
|
+
result = "float";
|
|
1623
|
+
}
|
|
1624
|
+
else if (effectiveType === "boolean") {
|
|
1625
|
+
result = "bool";
|
|
1626
|
+
}
|
|
1627
|
+
else if (effectiveType === "null") {
|
|
1628
|
+
return "None";
|
|
1629
|
+
}
|
|
1630
|
+
else if (effectiveType === "array") {
|
|
1631
|
+
if (isRecord(schema.items)) {
|
|
1632
|
+
const itemType = schemaToPyType(schema.items, rootSchema, `${hintName}Item`, ctx, depth + 1, seen);
|
|
1633
|
+
result = `List[${itemType}]`;
|
|
1634
|
+
}
|
|
1635
|
+
else {
|
|
1636
|
+
result = "List[Any]";
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
else if (effectiveType === "object") {
|
|
1640
|
+
const props = isRecord(schema.properties) ? schema.properties : undefined;
|
|
1641
|
+
const propKeys = props ? Object.keys(props).filter((k) => !isForbiddenKey(k)) : [];
|
|
1642
|
+
if (propKeys.length === 0) {
|
|
1643
|
+
if (isRecord(schema.additionalProperties)) {
|
|
1644
|
+
const valType = schemaToPyType(schema.additionalProperties, rootSchema, `${hintName}Value`, ctx, depth + 1, seen);
|
|
1645
|
+
result = `Dict[str, ${valType}]`;
|
|
1646
|
+
}
|
|
1647
|
+
else {
|
|
1648
|
+
result = "Dict[str, Any]";
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
else {
|
|
1652
|
+
const typeName = safePyTypeName(hintName, "Model", ctx.usedNames);
|
|
1653
|
+
const reqSet = new Set(Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === "string") : []);
|
|
1654
|
+
const fieldLines = [];
|
|
1655
|
+
for (const propKey of propKeys) {
|
|
1656
|
+
const fieldHint = `${typeName}${toPascalCase(splitToAsciiWords(propKey), "Field")}`;
|
|
1657
|
+
const baseFieldType = schemaToPyType(props[propKey], rootSchema, fieldHint, ctx, depth + 1, seen);
|
|
1658
|
+
const fieldType = reqSet.has(propKey) || baseFieldType === "Any" || baseFieldType.startsWith("Optional[")
|
|
1659
|
+
? baseFieldType
|
|
1660
|
+
: `Optional[${baseFieldType}]`;
|
|
1661
|
+
fieldLines.push(` ${pyString(propKey)}: ${fieldType},`);
|
|
1662
|
+
}
|
|
1663
|
+
const totalFlag = propKeys.every((k) => reqSet.has(k)) ? "True" : "False";
|
|
1664
|
+
ctx.definitions.push(`${typeName} = TypedDict(${pyString(typeName)}, {\n${fieldLines.join("\n")}\n}, total=${totalFlag})`);
|
|
1665
|
+
result = typeName;
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
else {
|
|
1669
|
+
result = "Any";
|
|
1670
|
+
}
|
|
1671
|
+
if (schema.nullable && result !== "None" && result !== "Any" && !result.startsWith("Optional[")) {
|
|
1672
|
+
return `Optional[${result}]`;
|
|
1673
|
+
}
|
|
1674
|
+
return result;
|
|
1675
|
+
}
|
|
1676
|
+
finally {
|
|
1677
|
+
seen.delete(schema);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
function emitPythonClient(endpoints, baseUrl, title, className, skippedIds, includeSkippedComments) {
|
|
1681
|
+
const ctx = {
|
|
1682
|
+
definitions: [],
|
|
1683
|
+
usedNames: new Set([className, "ApiClientError", "ClientConfig"])
|
|
1684
|
+
};
|
|
1685
|
+
const methodMeta = [];
|
|
1686
|
+
for (const ep of endpoints) {
|
|
1687
|
+
let reqType;
|
|
1688
|
+
if (ep.hasBody) {
|
|
1689
|
+
reqType = ep.requestSchema
|
|
1690
|
+
? schemaToPyType(ep.requestSchema, ep.requestSchema, `${ep.pascalBaseName}Request`, ctx)
|
|
1691
|
+
: "Any";
|
|
1692
|
+
}
|
|
1693
|
+
let resType;
|
|
1694
|
+
if (ep.responseKind === "void") {
|
|
1695
|
+
resType = "None";
|
|
1696
|
+
}
|
|
1697
|
+
else if (ep.responseKind === "text") {
|
|
1698
|
+
resType = "str";
|
|
1699
|
+
}
|
|
1700
|
+
else if (ep.responseSchema) {
|
|
1701
|
+
resType = schemaToPyType(ep.responseSchema, ep.responseSchema, `${ep.pascalBaseName}Response`, ctx);
|
|
1702
|
+
}
|
|
1703
|
+
else {
|
|
1704
|
+
resType = "Any";
|
|
1705
|
+
}
|
|
1706
|
+
methodMeta.push({ ep, ...(reqType ? { reqType } : {}), resType });
|
|
1707
|
+
}
|
|
1708
|
+
const lines = [
|
|
1709
|
+
"# Generated by vibecode-anything -- Typed Python API Client",
|
|
1710
|
+
`# Title: ${safeCommentLine(title)}`,
|
|
1711
|
+
`# Default base URL: ${safeCommentLine(baseUrl)}`,
|
|
1712
|
+
"# Zero external dependencies -- uses Python 3 standard library only.",
|
|
1713
|
+
"",
|
|
1714
|
+
"from __future__ import annotations",
|
|
1715
|
+
"",
|
|
1716
|
+
"from dataclasses import dataclass, field",
|
|
1717
|
+
"import json",
|
|
1718
|
+
"from typing import Any, Dict, List, Literal, Optional, Sequence, TypedDict, Union",
|
|
1719
|
+
"import urllib.error",
|
|
1720
|
+
"import urllib.parse",
|
|
1721
|
+
"import urllib.request",
|
|
1722
|
+
"",
|
|
1723
|
+
"_FORBIDDEN_KEYS = {\"__proto__\", \"constructor\", \"prototype\"}",
|
|
1724
|
+
"",
|
|
1725
|
+
"",
|
|
1726
|
+
"@dataclass",
|
|
1727
|
+
"class ApiClientError(Exception):",
|
|
1728
|
+
" message: str",
|
|
1729
|
+
" status: int",
|
|
1730
|
+
" expected_statuses: Sequence[int]",
|
|
1731
|
+
" method: str",
|
|
1732
|
+
" url: str",
|
|
1733
|
+
" response_body: str = \"\"",
|
|
1734
|
+
"",
|
|
1735
|
+
" def __post_init__(self) -> None:",
|
|
1736
|
+
" super().__init__(self.message)",
|
|
1737
|
+
"",
|
|
1738
|
+
"",
|
|
1739
|
+
"@dataclass",
|
|
1740
|
+
"class ClientConfig:",
|
|
1741
|
+
` base_url: str = ${pyString(baseUrl)}`,
|
|
1742
|
+
" headers: Dict[str, str] = field(default_factory=dict)",
|
|
1743
|
+
" timeout: float = 30.0",
|
|
1744
|
+
""
|
|
1745
|
+
];
|
|
1746
|
+
if (ctx.definitions.length > 0) {
|
|
1747
|
+
lines.push("");
|
|
1748
|
+
for (const def of ctx.definitions) {
|
|
1749
|
+
lines.push(def);
|
|
1750
|
+
lines.push("");
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
lines.push("");
|
|
1754
|
+
lines.push(`class ${className}:`);
|
|
1755
|
+
lines.push(` ${pyString(`Typed HTTP client for ${safeCommentLine(title)}.`)}`);
|
|
1756
|
+
lines.push("");
|
|
1757
|
+
lines.push(" def __init__(");
|
|
1758
|
+
lines.push(" self,");
|
|
1759
|
+
lines.push(` base_url: str = ${pyString(baseUrl)},`);
|
|
1760
|
+
lines.push(" headers: Optional[Dict[str, str]] = None,");
|
|
1761
|
+
lines.push(" timeout: float = 30.0,");
|
|
1762
|
+
lines.push(" ) -> None:");
|
|
1763
|
+
lines.push(" safe_headers: Dict[str, str] = {}");
|
|
1764
|
+
lines.push(" if headers:");
|
|
1765
|
+
lines.push(" for k, v in headers.items():");
|
|
1766
|
+
lines.push(" if k in _FORBIDDEN_KEYS:");
|
|
1767
|
+
lines.push(" continue");
|
|
1768
|
+
lines.push(" safe_headers[str(k)] = str(v)");
|
|
1769
|
+
lines.push(" self.config = ClientConfig(");
|
|
1770
|
+
lines.push(" base_url=base_url.rstrip(\"/\"),");
|
|
1771
|
+
lines.push(" headers=safe_headers,");
|
|
1772
|
+
lines.push(" timeout=timeout,");
|
|
1773
|
+
lines.push(" )");
|
|
1774
|
+
lines.push("");
|
|
1775
|
+
lines.push(" def _request(");
|
|
1776
|
+
lines.push(" self,");
|
|
1777
|
+
lines.push(" method: str,");
|
|
1778
|
+
lines.push(" route_path: str,");
|
|
1779
|
+
lines.push(" expected_statuses: Sequence[int],");
|
|
1780
|
+
lines.push(" response_kind: str,");
|
|
1781
|
+
lines.push(" default_query: Dict[str, str],");
|
|
1782
|
+
lines.push(" default_headers: Dict[str, str],");
|
|
1783
|
+
lines.push(" body: Any = None,");
|
|
1784
|
+
lines.push(" query: Optional[Dict[str, Any]] = None,");
|
|
1785
|
+
lines.push(" headers: Optional[Dict[str, str]] = None,");
|
|
1786
|
+
lines.push(" timeout: Optional[float] = None,");
|
|
1787
|
+
lines.push(" ) -> Any:");
|
|
1788
|
+
lines.push(" merged_query: Dict[str, str] = dict(default_query)");
|
|
1789
|
+
lines.push(" if query:");
|
|
1790
|
+
lines.push(" for k, v in query.items():");
|
|
1791
|
+
lines.push(" if k in _FORBIDDEN_KEYS:");
|
|
1792
|
+
lines.push(" continue");
|
|
1793
|
+
lines.push(" if v is None:");
|
|
1794
|
+
lines.push(" merged_query.pop(k, None)");
|
|
1795
|
+
lines.push(" else:");
|
|
1796
|
+
lines.push(" merged_query[str(k)] = str(v)");
|
|
1797
|
+
lines.push(" query_string = urllib.parse.urlencode(merged_query) if merged_query else \"\"");
|
|
1798
|
+
lines.push(" full_url = f\"{self.config.base_url}{route_path}\"");
|
|
1799
|
+
lines.push(" if query_string:");
|
|
1800
|
+
lines.push(" full_url = f\"{full_url}?{query_string}\"");
|
|
1801
|
+
lines.push("");
|
|
1802
|
+
lines.push(" merged_headers: Dict[str, str] = {}");
|
|
1803
|
+
lines.push(" for src in (default_headers, self.config.headers, headers or {}):");
|
|
1804
|
+
lines.push(" for k, v in src.items():");
|
|
1805
|
+
lines.push(" if k in _FORBIDDEN_KEYS:");
|
|
1806
|
+
lines.push(" continue");
|
|
1807
|
+
lines.push(" merged_headers[str(k)] = str(v)");
|
|
1808
|
+
lines.push("");
|
|
1809
|
+
lines.push(" payload: Optional[bytes] = None");
|
|
1810
|
+
lines.push(" if body is not None:");
|
|
1811
|
+
lines.push(" if isinstance(body, (bytes, bytearray)):");
|
|
1812
|
+
lines.push(" payload = bytes(body)");
|
|
1813
|
+
lines.push(" elif isinstance(body, str):");
|
|
1814
|
+
lines.push(" payload = body.encode(\"utf-8\")");
|
|
1815
|
+
lines.push(" else:");
|
|
1816
|
+
lines.push(" payload = json.dumps(body).encode(\"utf-8\")");
|
|
1817
|
+
lines.push(" if not any(k.lower() == \"content-type\" for k in merged_headers):");
|
|
1818
|
+
lines.push(" merged_headers[\"Content-Type\"] = \"application/json\"");
|
|
1819
|
+
lines.push("");
|
|
1820
|
+
lines.push(" req = urllib.request.Request(full_url, data=payload, headers=merged_headers, method=method)");
|
|
1821
|
+
lines.push(" effective_timeout = self.config.timeout if timeout is None else timeout");
|
|
1822
|
+
lines.push(" status_code = 0");
|
|
1823
|
+
lines.push(" raw_bytes = b\"\"");
|
|
1824
|
+
lines.push(" try:");
|
|
1825
|
+
lines.push(" with urllib.request.urlopen(req, timeout=effective_timeout) as resp:");
|
|
1826
|
+
lines.push(" status_code = int(resp.status)");
|
|
1827
|
+
lines.push(" raw_bytes = resp.read()");
|
|
1828
|
+
lines.push(" except urllib.error.HTTPError as exc:");
|
|
1829
|
+
lines.push(" status_code = int(exc.code)");
|
|
1830
|
+
lines.push(" raw_bytes = exc.read() if exc.fp is not None else b\"\"");
|
|
1831
|
+
lines.push("");
|
|
1832
|
+
lines.push(" status_ok = (");
|
|
1833
|
+
lines.push(" status_code in expected_statuses");
|
|
1834
|
+
lines.push(" if expected_statuses");
|
|
1835
|
+
lines.push(" else 200 <= status_code < 300");
|
|
1836
|
+
lines.push(" )");
|
|
1837
|
+
lines.push(" raw_text = raw_bytes.decode(\"utf-8\", errors=\"replace\")");
|
|
1838
|
+
lines.push(" if not status_ok:");
|
|
1839
|
+
lines.push(" snippet = f\"{raw_text[:300]}...\" if len(raw_text) > 300 else raw_text");
|
|
1840
|
+
lines.push(" expected_desc = \", \".join(str(s) for s in expected_statuses) if expected_statuses else \"2xx\"");
|
|
1841
|
+
lines.push(" raise ApiClientError(");
|
|
1842
|
+
lines.push(" message=f\"{method} {route_path} failed: expected status {expected_desc}, got {status_code}\",");
|
|
1843
|
+
lines.push(" status=status_code,");
|
|
1844
|
+
lines.push(" expected_statuses=tuple(expected_statuses),");
|
|
1845
|
+
lines.push(" method=method,");
|
|
1846
|
+
lines.push(" url=full_url,");
|
|
1847
|
+
lines.push(" response_body=snippet,");
|
|
1848
|
+
lines.push(" )");
|
|
1849
|
+
lines.push("");
|
|
1850
|
+
lines.push(" if response_kind == \"void\" or status_code in (204, 205):");
|
|
1851
|
+
lines.push(" return None");
|
|
1852
|
+
lines.push(" if response_kind == \"text\":");
|
|
1853
|
+
lines.push(" return raw_text");
|
|
1854
|
+
lines.push(" if not raw_text:");
|
|
1855
|
+
lines.push(" return None");
|
|
1856
|
+
lines.push(" return json.loads(raw_text)");
|
|
1857
|
+
for (const { ep, reqType, resType } of methodMeta) {
|
|
1858
|
+
const queryDict = ep.query.length > 0
|
|
1859
|
+
? `{${ep.query.map(([k, v]) => `${pyString(k)}: ${pyString(v)}`).join(", ")}}`
|
|
1860
|
+
: "{}";
|
|
1861
|
+
const headersDict = ep.headers.length > 0
|
|
1862
|
+
? `{${ep.headers.map(([k, v]) => `${pyString(k)}: ${pyString(v)}`).join(", ")}}`
|
|
1863
|
+
: "{}";
|
|
1864
|
+
const statusesTuple = ep.expectedStatuses.length === 1
|
|
1865
|
+
? `(${ep.expectedStatuses[0]},)`
|
|
1866
|
+
: `(${ep.expectedStatuses.join(", ")})`;
|
|
1867
|
+
lines.push("");
|
|
1868
|
+
if (ep.hasBody) {
|
|
1869
|
+
lines.push(` def ${ep.pyMethodName}(`);
|
|
1870
|
+
lines.push(" self,");
|
|
1871
|
+
lines.push(` body: Optional[${reqType ?? "Any"}] = None,`);
|
|
1872
|
+
lines.push(" *,");
|
|
1873
|
+
lines.push(" query: Optional[Dict[str, Any]] = None,");
|
|
1874
|
+
lines.push(" headers: Optional[Dict[str, str]] = None,");
|
|
1875
|
+
lines.push(" timeout: Optional[float] = None,");
|
|
1876
|
+
lines.push(` ) -> ${resType}:`);
|
|
1877
|
+
}
|
|
1878
|
+
else {
|
|
1879
|
+
lines.push(` def ${ep.pyMethodName}(`);
|
|
1880
|
+
lines.push(" self,");
|
|
1881
|
+
lines.push(" *,");
|
|
1882
|
+
lines.push(" query: Optional[Dict[str, Any]] = None,");
|
|
1883
|
+
lines.push(" headers: Optional[Dict[str, str]] = None,");
|
|
1884
|
+
lines.push(" timeout: Optional[float] = None,");
|
|
1885
|
+
lines.push(` ) -> ${resType}:`);
|
|
1886
|
+
}
|
|
1887
|
+
lines.push(` ${pyString(`${safeCommentLine(ep.summary)} (${ep.method} ${safeCommentLine(ep.pathname)})`)}`);
|
|
1888
|
+
lines.push(" return self._request(");
|
|
1889
|
+
lines.push(` method=${pyString(ep.method)},`);
|
|
1890
|
+
lines.push(` route_path=${pyString(ep.pathname)},`);
|
|
1891
|
+
lines.push(` expected_statuses=${statusesTuple},`);
|
|
1892
|
+
lines.push(` response_kind=${pyString(ep.responseKind)},`);
|
|
1893
|
+
lines.push(` default_query=${queryDict},`);
|
|
1894
|
+
lines.push(` default_headers=${headersDict},`);
|
|
1895
|
+
lines.push(ep.hasBody ? " body=body," : " body=None,");
|
|
1896
|
+
lines.push(" query=query,");
|
|
1897
|
+
lines.push(" headers=headers,");
|
|
1898
|
+
lines.push(" timeout=timeout,");
|
|
1899
|
+
lines.push(" )");
|
|
1900
|
+
}
|
|
1901
|
+
lines.push("");
|
|
1902
|
+
lines.push("");
|
|
1903
|
+
lines.push("def create_client(");
|
|
1904
|
+
lines.push(` base_url: str = ${pyString(baseUrl)},`);
|
|
1905
|
+
lines.push(" headers: Optional[Dict[str, str]] = None,");
|
|
1906
|
+
lines.push(" timeout: float = 30.0,");
|
|
1907
|
+
lines.push(`) -> ${className}:`);
|
|
1908
|
+
lines.push(` return ${className}(base_url=base_url, headers=headers, timeout=timeout)`);
|
|
1909
|
+
if (includeSkippedComments && skippedIds.length > 0) {
|
|
1910
|
+
lines.push("");
|
|
1911
|
+
lines.push(`# Skipped non-HTTP invariants (${skippedIds.length}): ${skippedIds.map((s) => safeCommentLine(s, 60)).join(", ")}`);
|
|
1912
|
+
}
|
|
1913
|
+
lines.push("");
|
|
1914
|
+
return lines.join("\n");
|
|
1915
|
+
}
|
|
1916
|
+
function formatGoJsonTag(rawKey, isOptional) {
|
|
1917
|
+
// Strip characters that can break Go struct tags or encoding/json tag grammar.
|
|
1918
|
+
const safeKey = sanitizeText(rawKey)
|
|
1919
|
+
.replace(/[\r\n\0\x00-\x1f\x7f\u2028\u2029`\\,"]/g, "")
|
|
1920
|
+
.trim();
|
|
1921
|
+
const keyPart = safeKey || "field";
|
|
1922
|
+
const tagValue = isOptional ? `${keyPart},omitempty` : keyPart;
|
|
1923
|
+
return `\`json:"${tagValue}"\``;
|
|
1924
|
+
}
|
|
1925
|
+
function schemaToGoType(schema, rootSchema, hintName, ctx, depth = 0, seen = new Set()) {
|
|
1926
|
+
if (!schema || !isRecord(schema))
|
|
1927
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1928
|
+
if (depth >= MAX_SCHEMA_DEPTH)
|
|
1929
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1930
|
+
if (seen.has(schema))
|
|
1931
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1932
|
+
seen.add(schema);
|
|
1933
|
+
try {
|
|
1934
|
+
if (typeof schema.$ref === "string") {
|
|
1935
|
+
const target = resolveLocalRef(rootSchema, schema.$ref);
|
|
1936
|
+
if (target) {
|
|
1937
|
+
return schemaToGoType(target, rootSchema, hintName, ctx, depth + 1, seen);
|
|
1938
|
+
}
|
|
1939
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1940
|
+
}
|
|
1941
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
|
|
1942
|
+
if (schema.oneOf.length === 1) {
|
|
1943
|
+
return schemaToGoType(schema.oneOf[0], rootSchema, hintName, ctx, depth + 1, seen);
|
|
1944
|
+
}
|
|
1945
|
+
const nonNull = schema.oneOf.filter((b) => b.type !== "null");
|
|
1946
|
+
if (nonNull.length === 1 && schema.oneOf.length === 2) {
|
|
1947
|
+
const inner = schemaToGoType(nonNull[0], rootSchema, hintName, ctx, depth + 1, seen);
|
|
1948
|
+
return {
|
|
1949
|
+
typeName: inner.typeName === "any" || inner.typeName.startsWith("*") ? inner.typeName : `*${inner.typeName}`,
|
|
1950
|
+
isNamedStruct: false
|
|
1951
|
+
};
|
|
1952
|
+
}
|
|
1953
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1954
|
+
}
|
|
1955
|
+
if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
|
|
1956
|
+
if (schema.anyOf.length === 1) {
|
|
1957
|
+
return schemaToGoType(schema.anyOf[0], rootSchema, hintName, ctx, depth + 1, seen);
|
|
1958
|
+
}
|
|
1959
|
+
const nonNull = schema.anyOf.filter((b) => b.type !== "null");
|
|
1960
|
+
if (nonNull.length === 1 && schema.anyOf.length === 2) {
|
|
1961
|
+
const inner = schemaToGoType(nonNull[0], rootSchema, hintName, ctx, depth + 1, seen);
|
|
1962
|
+
return {
|
|
1963
|
+
typeName: inner.typeName === "any" || inner.typeName.startsWith("*") ? inner.typeName : `*${inner.typeName}`,
|
|
1964
|
+
isNamedStruct: false
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1968
|
+
}
|
|
1969
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1970
|
+
const { allObjects, merged } = mergeAllOfObjectBranches(schema.allOf, rootSchema);
|
|
1971
|
+
if (allObjects) {
|
|
1972
|
+
return schemaToGoType(merged, rootSchema, hintName, ctx, depth + 1, seen);
|
|
1973
|
+
}
|
|
1974
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1975
|
+
}
|
|
1976
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) {
|
|
1977
|
+
const nonNull = schema.enum.filter((v) => v !== null);
|
|
1978
|
+
if (nonNull.length > 0) {
|
|
1979
|
+
if (nonNull.every((v) => typeof v === "string")) {
|
|
1980
|
+
return { typeName: schema.nullable ? "*string" : "string", isNamedStruct: false };
|
|
1981
|
+
}
|
|
1982
|
+
if (nonNull.every((v) => typeof v === "number" && Number.isInteger(v))) {
|
|
1983
|
+
return { typeName: schema.nullable ? "*int64" : "int64", isNamedStruct: false };
|
|
1984
|
+
}
|
|
1985
|
+
if (nonNull.every((v) => typeof v === "number")) {
|
|
1986
|
+
return { typeName: schema.nullable ? "*float64" : "float64", isNamedStruct: false };
|
|
1987
|
+
}
|
|
1988
|
+
if (nonNull.every((v) => typeof v === "boolean")) {
|
|
1989
|
+
return { typeName: schema.nullable ? "*bool" : "bool", isNamedStruct: false };
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
return { typeName: "any", isNamedStruct: false };
|
|
1993
|
+
}
|
|
1994
|
+
if (schema.const !== undefined) {
|
|
1995
|
+
if (typeof schema.const === "string")
|
|
1996
|
+
return { typeName: "string", isNamedStruct: false };
|
|
1997
|
+
if (typeof schema.const === "boolean")
|
|
1998
|
+
return { typeName: "bool", isNamedStruct: false };
|
|
1999
|
+
if (typeof schema.const === "number") {
|
|
2000
|
+
return { typeName: Number.isInteger(schema.const) ? "int64" : "float64", isNamedStruct: false };
|
|
2001
|
+
}
|
|
2002
|
+
return { typeName: "any", isNamedStruct: false };
|
|
2003
|
+
}
|
|
2004
|
+
const rawType = schema.type;
|
|
2005
|
+
if (Array.isArray(rawType) && rawType.length > 0) {
|
|
2006
|
+
const nonNull = rawType.filter((t) => t !== "null");
|
|
2007
|
+
const hasNull = rawType.includes("null") || Boolean(schema.nullable);
|
|
2008
|
+
if (nonNull.length === 1) {
|
|
2009
|
+
const inner = schemaToGoType({ ...schema, type: nonNull[0], nullable: false }, rootSchema, hintName, ctx, depth + 1, seen);
|
|
2010
|
+
if (hasNull && inner.typeName !== "any" && !inner.typeName.startsWith("*") && !inner.typeName.startsWith("[]") && !inner.typeName.startsWith("map[")) {
|
|
2011
|
+
return { typeName: `*${inner.typeName}`, isNamedStruct: false };
|
|
2012
|
+
}
|
|
2013
|
+
return inner;
|
|
2014
|
+
}
|
|
2015
|
+
return { typeName: "any", isNamedStruct: false };
|
|
2016
|
+
}
|
|
2017
|
+
const effectiveType = typeof rawType === "string"
|
|
2018
|
+
? rawType
|
|
2019
|
+
: isRecord(schema.properties) || schema.additionalProperties !== undefined
|
|
2020
|
+
? "object"
|
|
2021
|
+
: schema.items !== undefined || Array.isArray(schema.prefixItems)
|
|
2022
|
+
? "array"
|
|
2023
|
+
: undefined;
|
|
2024
|
+
if (effectiveType === "string") {
|
|
2025
|
+
return { typeName: schema.nullable ? "*string" : "string", isNamedStruct: false };
|
|
2026
|
+
}
|
|
2027
|
+
if (effectiveType === "integer") {
|
|
2028
|
+
return { typeName: schema.nullable ? "*int64" : "int64", isNamedStruct: false };
|
|
2029
|
+
}
|
|
2030
|
+
if (effectiveType === "number") {
|
|
2031
|
+
return { typeName: schema.nullable ? "*float64" : "float64", isNamedStruct: false };
|
|
2032
|
+
}
|
|
2033
|
+
if (effectiveType === "boolean") {
|
|
2034
|
+
return { typeName: schema.nullable ? "*bool" : "bool", isNamedStruct: false };
|
|
2035
|
+
}
|
|
2036
|
+
if (effectiveType === "null") {
|
|
2037
|
+
return { typeName: "any", isNamedStruct: false };
|
|
2038
|
+
}
|
|
2039
|
+
if (effectiveType === "array") {
|
|
2040
|
+
if (isRecord(schema.items)) {
|
|
2041
|
+
const elem = schemaToGoType(schema.items, rootSchema, `${hintName}Item`, ctx, depth + 1, seen);
|
|
2042
|
+
return { typeName: `[]${elem.typeName}`, isNamedStruct: false };
|
|
2043
|
+
}
|
|
2044
|
+
return { typeName: "[]any", isNamedStruct: false };
|
|
2045
|
+
}
|
|
2046
|
+
if (effectiveType === "object") {
|
|
2047
|
+
const props = isRecord(schema.properties) ? schema.properties : undefined;
|
|
2048
|
+
const propKeys = props ? Object.keys(props).filter((k) => !isForbiddenKey(k)) : [];
|
|
2049
|
+
if (propKeys.length === 0) {
|
|
2050
|
+
if (isRecord(schema.additionalProperties)) {
|
|
2051
|
+
const valType = schemaToGoType(schema.additionalProperties, rootSchema, `${hintName}Value`, ctx, depth + 1, seen);
|
|
2052
|
+
return { typeName: `map[string]${valType.typeName}`, isNamedStruct: false };
|
|
2053
|
+
}
|
|
2054
|
+
return { typeName: "map[string]any", isNamedStruct: false };
|
|
2055
|
+
}
|
|
2056
|
+
const structName = safeGoExportedIdentifier(hintName, "Model", ctx.usedNames);
|
|
2057
|
+
const reqSet = new Set(Array.isArray(schema.required) ? schema.required.filter((r) => typeof r === "string") : []);
|
|
2058
|
+
const usedFields = new Set();
|
|
2059
|
+
const fieldLines = [];
|
|
2060
|
+
for (const propKey of propKeys) {
|
|
2061
|
+
const fieldWords = splitToAsciiWords(propKey);
|
|
2062
|
+
const fieldName = safeGoExportedIdentifier(toPascalCase(fieldWords, "Field"), "Field", usedFields);
|
|
2063
|
+
const isOptional = !reqSet.has(propKey);
|
|
2064
|
+
const fieldTypeInfo = schemaToGoType(props[propKey], rootSchema, `${structName}${fieldName}`, ctx, depth + 1, seen);
|
|
2065
|
+
let goFieldType = fieldTypeInfo.typeName;
|
|
2066
|
+
if (isOptional &&
|
|
2067
|
+
goFieldType !== "any" &&
|
|
2068
|
+
!goFieldType.startsWith("*") &&
|
|
2069
|
+
!goFieldType.startsWith("[]") &&
|
|
2070
|
+
!goFieldType.startsWith("map[")) {
|
|
2071
|
+
goFieldType = `*${goFieldType}`;
|
|
2072
|
+
}
|
|
2073
|
+
fieldLines.push(`\t${fieldName} ${goFieldType} ${formatGoJsonTag(propKey, isOptional)}`);
|
|
2074
|
+
}
|
|
2075
|
+
ctx.definitions.push(`type ${structName} struct {\n${fieldLines.join("\n")}\n}`);
|
|
2076
|
+
return {
|
|
2077
|
+
typeName: schema.nullable ? `*${structName}` : structName,
|
|
2078
|
+
isNamedStruct: !schema.nullable
|
|
2079
|
+
};
|
|
2080
|
+
}
|
|
2081
|
+
return { typeName: "any", isNamedStruct: false };
|
|
2082
|
+
}
|
|
2083
|
+
finally {
|
|
2084
|
+
seen.delete(schema);
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
function emitGoClient(endpoints, baseUrl, title, className, packageName, skippedIds, includeSkippedComments) {
|
|
2088
|
+
const goStructName = className.endsWith("Client") ? className : `${className}Client`;
|
|
2089
|
+
const ctx = {
|
|
2090
|
+
definitions: [],
|
|
2091
|
+
usedNames: new Set([goStructName, "RequestOptions", "ApiError"])
|
|
2092
|
+
};
|
|
2093
|
+
const methodMeta = [];
|
|
2094
|
+
for (const ep of endpoints) {
|
|
2095
|
+
let reqType;
|
|
2096
|
+
if (ep.hasBody) {
|
|
2097
|
+
if (ep.requestSchema) {
|
|
2098
|
+
const info = schemaToGoType(ep.requestSchema, ep.requestSchema, `${ep.pascalBaseName}Request`, ctx);
|
|
2099
|
+
reqType = info.isNamedStruct ? `*${info.typeName}` : info.typeName;
|
|
2100
|
+
}
|
|
2101
|
+
else {
|
|
2102
|
+
reqType = "any";
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
let resType;
|
|
2106
|
+
let resIsStruct = false;
|
|
2107
|
+
if (ep.responseKind === "void") {
|
|
2108
|
+
resType = "";
|
|
2109
|
+
}
|
|
2110
|
+
else if (ep.responseKind === "text") {
|
|
2111
|
+
resType = "string";
|
|
2112
|
+
}
|
|
2113
|
+
else if (ep.responseSchema) {
|
|
2114
|
+
const info = schemaToGoType(ep.responseSchema, ep.responseSchema, `${ep.pascalBaseName}Response`, ctx);
|
|
2115
|
+
resType = info.typeName;
|
|
2116
|
+
resIsStruct = info.isNamedStruct;
|
|
2117
|
+
}
|
|
2118
|
+
else {
|
|
2119
|
+
resType = "any";
|
|
2120
|
+
}
|
|
2121
|
+
methodMeta.push({ ep, ...(reqType ? { reqType } : {}), resType, resIsStruct });
|
|
2122
|
+
}
|
|
2123
|
+
const lines = [
|
|
2124
|
+
"// Generated by vibecode-anything -- Typed Go API Client",
|
|
2125
|
+
`// Title: ${safeCommentLine(title)}`,
|
|
2126
|
+
`// Default base URL: ${safeCommentLine(baseUrl)}`,
|
|
2127
|
+
"// Zero external dependencies -- uses Go standard library only.",
|
|
2128
|
+
"",
|
|
2129
|
+
`package ${packageName}`,
|
|
2130
|
+
"",
|
|
2131
|
+
"import (",
|
|
2132
|
+
"\t\"bytes\"",
|
|
2133
|
+
"\t\"context\"",
|
|
2134
|
+
"\t\"encoding/json\"",
|
|
2135
|
+
"\t\"fmt\"",
|
|
2136
|
+
"\t\"io\"",
|
|
2137
|
+
"\t\"net/http\"",
|
|
2138
|
+
"\t\"net/url\"",
|
|
2139
|
+
"\t\"strings\"",
|
|
2140
|
+
")",
|
|
2141
|
+
"",
|
|
2142
|
+
"type RequestOptions struct {",
|
|
2143
|
+
"\tQuery map[string]string",
|
|
2144
|
+
"\tHeaders map[string]string",
|
|
2145
|
+
"}",
|
|
2146
|
+
"",
|
|
2147
|
+
"type ApiError struct {",
|
|
2148
|
+
"\tStatus int",
|
|
2149
|
+
"\tExpectedStatuses []int",
|
|
2150
|
+
"\tMethod string",
|
|
2151
|
+
"\tURL string",
|
|
2152
|
+
"\tBody string",
|
|
2153
|
+
"}",
|
|
2154
|
+
"",
|
|
2155
|
+
"func (e *ApiError) Error() string {",
|
|
2156
|
+
"\tif e.Body != \"\" {",
|
|
2157
|
+
"\t\treturn fmt.Sprintf(\"%s %s failed: unexpected status %d (%s)\", e.Method, e.URL, e.Status, e.Body)",
|
|
2158
|
+
"\t}",
|
|
2159
|
+
"\treturn fmt.Sprintf(\"%s %s failed: unexpected status %d\", e.Method, e.URL, e.Status)",
|
|
2160
|
+
"}",
|
|
2161
|
+
""
|
|
2162
|
+
];
|
|
2163
|
+
for (const def of ctx.definitions) {
|
|
2164
|
+
lines.push(def);
|
|
2165
|
+
lines.push("");
|
|
2166
|
+
}
|
|
2167
|
+
lines.push(`type ${goStructName} struct {`);
|
|
2168
|
+
lines.push("\tBaseURL string");
|
|
2169
|
+
lines.push("\tDefaultHeaders map[string]string");
|
|
2170
|
+
lines.push("\tHTTPClient *http.Client");
|
|
2171
|
+
lines.push("}");
|
|
2172
|
+
lines.push("");
|
|
2173
|
+
lines.push(`func New${goStructName}(baseUrl string, headers map[string]string) *${goStructName} {`);
|
|
2174
|
+
lines.push("\tif strings.TrimSpace(baseUrl) == \"\" {");
|
|
2175
|
+
lines.push(`\t\tbaseUrl = ${goString(baseUrl)}`);
|
|
2176
|
+
lines.push("\t}");
|
|
2177
|
+
lines.push("\tcopied := make(map[string]string, len(headers))");
|
|
2178
|
+
lines.push("\tfor k, v := range headers {");
|
|
2179
|
+
lines.push("\t\tif k == \"__proto__\" || k == \"constructor\" || k == \"prototype\" {");
|
|
2180
|
+
lines.push("\t\t\tcontinue");
|
|
2181
|
+
lines.push("\t\t}");
|
|
2182
|
+
lines.push("\t\tcopied[k] = v");
|
|
2183
|
+
lines.push("\t}");
|
|
2184
|
+
lines.push(`\treturn &${goStructName}{`);
|
|
2185
|
+
lines.push("\t\tBaseURL: strings.TrimRight(baseUrl, \"/\"),");
|
|
2186
|
+
lines.push("\t\tDefaultHeaders: copied,");
|
|
2187
|
+
lines.push("\t\tHTTPClient: http.DefaultClient,");
|
|
2188
|
+
lines.push("\t}");
|
|
2189
|
+
lines.push("}");
|
|
2190
|
+
lines.push("");
|
|
2191
|
+
lines.push(`func (c *${goStructName}) doRequest(`);
|
|
2192
|
+
lines.push("\tctx context.Context,");
|
|
2193
|
+
lines.push("\tmethod string,");
|
|
2194
|
+
lines.push("\troutePath string,");
|
|
2195
|
+
lines.push("\texpectedStatuses []int,");
|
|
2196
|
+
lines.push("\tdefaultQuery map[string]string,");
|
|
2197
|
+
lines.push("\tdefaultHeaders map[string]string,");
|
|
2198
|
+
lines.push("\tbody any,");
|
|
2199
|
+
lines.push("\topts *RequestOptions,");
|
|
2200
|
+
lines.push(") ([]byte, int, error) {");
|
|
2201
|
+
lines.push("\tparsedURL, err := url.Parse(c.BaseURL + routePath)");
|
|
2202
|
+
lines.push("\tif err != nil {");
|
|
2203
|
+
lines.push("\t\treturn nil, 0, err");
|
|
2204
|
+
lines.push("\t}");
|
|
2205
|
+
lines.push("\tquery := parsedURL.Query()");
|
|
2206
|
+
lines.push("\tfor k, v := range defaultQuery {");
|
|
2207
|
+
lines.push("\t\tquery.Set(k, v)");
|
|
2208
|
+
lines.push("\t}");
|
|
2209
|
+
lines.push("\tif opts != nil {");
|
|
2210
|
+
lines.push("\t\tfor k, v := range opts.Query {");
|
|
2211
|
+
lines.push("\t\t\tif k == \"__proto__\" || k == \"constructor\" || k == \"prototype\" {");
|
|
2212
|
+
lines.push("\t\t\t\tcontinue");
|
|
2213
|
+
lines.push("\t\t\t}");
|
|
2214
|
+
lines.push("\t\t\tquery.Set(k, v)");
|
|
2215
|
+
lines.push("\t\t}");
|
|
2216
|
+
lines.push("\t}");
|
|
2217
|
+
lines.push("\tparsedURL.RawQuery = query.Encode()");
|
|
2218
|
+
lines.push("");
|
|
2219
|
+
lines.push("\tvar bodyReader io.Reader");
|
|
2220
|
+
lines.push("\thasJSONBody := false");
|
|
2221
|
+
lines.push("\tif body != nil {");
|
|
2222
|
+
lines.push("\t\tif strBody, ok := body.(string); ok {");
|
|
2223
|
+
lines.push("\t\t\tbodyReader = strings.NewReader(strBody)");
|
|
2224
|
+
lines.push("\t\t} else {");
|
|
2225
|
+
lines.push("\t\t\tencoded, marshalErr := json.Marshal(body)");
|
|
2226
|
+
lines.push("\t\t\tif marshalErr != nil {");
|
|
2227
|
+
lines.push("\t\t\t\treturn nil, 0, marshalErr");
|
|
2228
|
+
lines.push("\t\t\t}");
|
|
2229
|
+
lines.push("\t\t\tbodyReader = bytes.NewReader(encoded)");
|
|
2230
|
+
lines.push("\t\t\thasJSONBody = true");
|
|
2231
|
+
lines.push("\t\t}");
|
|
2232
|
+
lines.push("\t}");
|
|
2233
|
+
lines.push("");
|
|
2234
|
+
lines.push("\treq, err := http.NewRequestWithContext(ctx, method, parsedURL.String(), bodyReader)");
|
|
2235
|
+
lines.push("\tif err != nil {");
|
|
2236
|
+
lines.push("\t\treturn nil, 0, err");
|
|
2237
|
+
lines.push("\t}");
|
|
2238
|
+
lines.push("\tfor k, v := range defaultHeaders {");
|
|
2239
|
+
lines.push("\t\treq.Header.Set(k, v)");
|
|
2240
|
+
lines.push("\t}");
|
|
2241
|
+
lines.push("\tfor k, v := range c.DefaultHeaders {");
|
|
2242
|
+
lines.push("\t\treq.Header.Set(k, v)");
|
|
2243
|
+
lines.push("\t}");
|
|
2244
|
+
lines.push("\tif opts != nil {");
|
|
2245
|
+
lines.push("\t\tfor k, v := range opts.Headers {");
|
|
2246
|
+
lines.push("\t\t\tif k == \"__proto__\" || k == \"constructor\" || k == \"prototype\" {");
|
|
2247
|
+
lines.push("\t\t\t\tcontinue");
|
|
2248
|
+
lines.push("\t\t\t}");
|
|
2249
|
+
lines.push("\t\t\treq.Header.Set(k, v)");
|
|
2250
|
+
lines.push("\t\t}");
|
|
2251
|
+
lines.push("\t}");
|
|
2252
|
+
lines.push("\tif hasJSONBody && req.Header.Get(\"Content-Type\") == \"\" {");
|
|
2253
|
+
lines.push("\t\treq.Header.Set(\"Content-Type\", \"application/json\")");
|
|
2254
|
+
lines.push("\t}");
|
|
2255
|
+
lines.push("");
|
|
2256
|
+
lines.push("\thttpClient := c.HTTPClient");
|
|
2257
|
+
lines.push("\tif httpClient == nil {");
|
|
2258
|
+
lines.push("\t\thttpClient = http.DefaultClient");
|
|
2259
|
+
lines.push("\t}");
|
|
2260
|
+
lines.push("\tresp, err := httpClient.Do(req)");
|
|
2261
|
+
lines.push("\tif err != nil {");
|
|
2262
|
+
lines.push("\t\treturn nil, 0, err");
|
|
2263
|
+
lines.push("\t}");
|
|
2264
|
+
lines.push("\tdefer resp.Body.Close()");
|
|
2265
|
+
lines.push("");
|
|
2266
|
+
lines.push("\trawBody, err := io.ReadAll(resp.Body)");
|
|
2267
|
+
lines.push("\tif err != nil {");
|
|
2268
|
+
lines.push("\t\treturn nil, resp.StatusCode, err");
|
|
2269
|
+
lines.push("\t}");
|
|
2270
|
+
lines.push("");
|
|
2271
|
+
lines.push("\tstatusOK := false");
|
|
2272
|
+
lines.push("\tif len(expectedStatuses) > 0 {");
|
|
2273
|
+
lines.push("\t\tfor _, code := range expectedStatuses {");
|
|
2274
|
+
lines.push("\t\t\tif resp.StatusCode == code {");
|
|
2275
|
+
lines.push("\t\t\t\tstatusOK = true");
|
|
2276
|
+
lines.push("\t\t\t\tbreak");
|
|
2277
|
+
lines.push("\t\t\t}");
|
|
2278
|
+
lines.push("\t\t}");
|
|
2279
|
+
lines.push("\t} else {");
|
|
2280
|
+
lines.push("\t\tstatusOK = resp.StatusCode >= 200 && resp.StatusCode < 300");
|
|
2281
|
+
lines.push("\t}");
|
|
2282
|
+
lines.push("\tif !statusOK {");
|
|
2283
|
+
lines.push("\t\tsnippet := string(rawBody)");
|
|
2284
|
+
lines.push("\t\tif len(snippet) > 300 {");
|
|
2285
|
+
lines.push("\t\t\tsnippet = snippet[:300] + \"...\"");
|
|
2286
|
+
lines.push("\t\t}");
|
|
2287
|
+
lines.push("\t\treturn nil, resp.StatusCode, &ApiError{");
|
|
2288
|
+
lines.push("\t\t\tStatus: resp.StatusCode,");
|
|
2289
|
+
lines.push("\t\t\tExpectedStatuses: expectedStatuses,");
|
|
2290
|
+
lines.push("\t\t\tMethod: method,");
|
|
2291
|
+
lines.push("\t\t\tURL: parsedURL.String(),");
|
|
2292
|
+
lines.push("\t\t\tBody: snippet,");
|
|
2293
|
+
lines.push("\t\t}");
|
|
2294
|
+
lines.push("\t}");
|
|
2295
|
+
lines.push("");
|
|
2296
|
+
lines.push("\treturn rawBody, resp.StatusCode, nil");
|
|
2297
|
+
lines.push("}");
|
|
2298
|
+
for (const { ep, reqType, resType, resIsStruct } of methodMeta) {
|
|
2299
|
+
const queryMapLit = ep.query.length > 0
|
|
2300
|
+
? `map[string]string{${ep.query.map(([k, v]) => `${goString(k)}: ${goString(v)}`).join(", ")}}`
|
|
2301
|
+
: "nil";
|
|
2302
|
+
const headersMapLit = ep.headers.length > 0
|
|
2303
|
+
? `map[string]string{${ep.headers.map(([k, v]) => `${goString(k)}: ${goString(v)}`).join(", ")}}`
|
|
2304
|
+
: "nil";
|
|
2305
|
+
const statusesLit = ep.expectedStatuses.length > 0
|
|
2306
|
+
? `[]int{${ep.expectedStatuses.join(", ")}}`
|
|
2307
|
+
: "nil";
|
|
2308
|
+
lines.push("");
|
|
2309
|
+
lines.push(`// ${ep.goMethodName}: ${safeCommentLine(ep.summary)} (${ep.method} ${safeCommentLine(ep.pathname)})`);
|
|
2310
|
+
const sigParams = ep.hasBody
|
|
2311
|
+
? `ctx context.Context, body ${reqType ?? "any"}, opts *RequestOptions`
|
|
2312
|
+
: "ctx context.Context, opts *RequestOptions";
|
|
2313
|
+
if (ep.responseKind === "void") {
|
|
2314
|
+
lines.push(`func (c *${goStructName}) ${ep.goMethodName}(${sigParams}) error {`);
|
|
2315
|
+
lines.push(`\t_, _, err := c.doRequest(ctx, ${goString(ep.method)}, ${goString(ep.pathname)}, ${statusesLit}, ${queryMapLit}, ${headersMapLit}, ${ep.hasBody ? "body" : "nil"}, opts)`);
|
|
2316
|
+
lines.push("\treturn err");
|
|
2317
|
+
lines.push("}");
|
|
2318
|
+
}
|
|
2319
|
+
else if (ep.responseKind === "text") {
|
|
2320
|
+
lines.push(`func (c *${goStructName}) ${ep.goMethodName}(${sigParams}) (string, error) {`);
|
|
2321
|
+
lines.push(`\traw, _, err := c.doRequest(ctx, ${goString(ep.method)}, ${goString(ep.pathname)}, ${statusesLit}, ${queryMapLit}, ${headersMapLit}, ${ep.hasBody ? "body" : "nil"}, opts)`);
|
|
2322
|
+
lines.push("\tif err != nil {");
|
|
2323
|
+
lines.push("\t\treturn \"\", err");
|
|
2324
|
+
lines.push("\t}");
|
|
2325
|
+
lines.push("\treturn string(raw), nil");
|
|
2326
|
+
lines.push("}");
|
|
2327
|
+
}
|
|
2328
|
+
else if (resIsStruct) {
|
|
2329
|
+
lines.push(`func (c *${goStructName}) ${ep.goMethodName}(${sigParams}) (*${resType}, error) {`);
|
|
2330
|
+
lines.push(`\traw, status, err := c.doRequest(ctx, ${goString(ep.method)}, ${goString(ep.pathname)}, ${statusesLit}, ${queryMapLit}, ${headersMapLit}, ${ep.hasBody ? "body" : "nil"}, opts)`);
|
|
2331
|
+
lines.push("\tif err != nil {");
|
|
2332
|
+
lines.push("\t\treturn nil, err");
|
|
2333
|
+
lines.push("\t}");
|
|
2334
|
+
lines.push("\tif status == http.StatusNoContent || len(raw) == 0 {");
|
|
2335
|
+
lines.push("\t\treturn nil, nil");
|
|
2336
|
+
lines.push("\t}");
|
|
2337
|
+
lines.push(`\tvar out ${resType}`);
|
|
2338
|
+
lines.push("\tif err := json.Unmarshal(raw, &out); err != nil {");
|
|
2339
|
+
lines.push("\t\treturn nil, err");
|
|
2340
|
+
lines.push("\t}");
|
|
2341
|
+
lines.push("\treturn &out, nil");
|
|
2342
|
+
lines.push("}");
|
|
2343
|
+
}
|
|
2344
|
+
else {
|
|
2345
|
+
lines.push(`func (c *${goStructName}) ${ep.goMethodName}(${sigParams}) (${resType}, error) {`);
|
|
2346
|
+
lines.push(`\tvar zero ${resType}`);
|
|
2347
|
+
lines.push(`\traw, status, err := c.doRequest(ctx, ${goString(ep.method)}, ${goString(ep.pathname)}, ${statusesLit}, ${queryMapLit}, ${headersMapLit}, ${ep.hasBody ? "body" : "nil"}, opts)`);
|
|
2348
|
+
lines.push("\tif err != nil {");
|
|
2349
|
+
lines.push("\t\treturn zero, err");
|
|
2350
|
+
lines.push("\t}");
|
|
2351
|
+
lines.push("\tif status == http.StatusNoContent || len(raw) == 0 {");
|
|
2352
|
+
lines.push("\t\treturn zero, nil");
|
|
2353
|
+
lines.push("\t}");
|
|
2354
|
+
lines.push(`\tvar out ${resType}`);
|
|
2355
|
+
lines.push("\tif err := json.Unmarshal(raw, &out); err != nil {");
|
|
2356
|
+
lines.push("\t\treturn zero, err");
|
|
2357
|
+
lines.push("\t}");
|
|
2358
|
+
lines.push("\treturn out, nil");
|
|
2359
|
+
lines.push("}");
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
if (includeSkippedComments && skippedIds.length > 0) {
|
|
2363
|
+
lines.push("");
|
|
2364
|
+
lines.push(`// Skipped non-HTTP invariants (${skippedIds.length}): ${skippedIds.map((s) => safeCommentLine(s, 60)).join(", ")}`);
|
|
2365
|
+
}
|
|
2366
|
+
lines.push("");
|
|
2367
|
+
return lines.join("\n");
|
|
2368
|
+
}
|
|
2369
|
+
// ============================================================================
|
|
2370
|
+
// Public API
|
|
2371
|
+
// ============================================================================
|
|
2372
|
+
function suggestedFilenameFor(format) {
|
|
2373
|
+
if (format === "ts-fetch")
|
|
2374
|
+
return "vibecode-client.ts";
|
|
2375
|
+
if (format === "python")
|
|
2376
|
+
return "vibecode_client.py";
|
|
2377
|
+
return "vibecode_client.go";
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* Compile visible HTTP invariants from a ContractV02 into a zero-dependency typed API client SDK
|
|
2381
|
+
* (`ts-fetch`, `python`, or `go`). Holdout invariants are completely excluded and never disclosed.
|
|
2382
|
+
*/
|
|
2383
|
+
export function exportClientCode(contract, options = {}) {
|
|
2384
|
+
if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
|
|
2385
|
+
throw new VibecodeError("CONTRACT_INVALID", "exportClientCode requires a valid contract object with an invariants array.");
|
|
2386
|
+
}
|
|
2387
|
+
const formatRaw = options.format ?? "ts-fetch";
|
|
2388
|
+
if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
|
|
2389
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported client export format "${String(formatRaw)}". Supported formats: ts-fetch, python, go.`);
|
|
2390
|
+
}
|
|
2391
|
+
const format = formatRaw;
|
|
2392
|
+
const includeSkippedComments = options.includeSkippedComments === true;
|
|
2393
|
+
const rawTitle = (typeof options.title === "string" && options.title.trim()) ||
|
|
2394
|
+
(isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()) ||
|
|
2395
|
+
"vibecode-api";
|
|
2396
|
+
const title = sanitizeSingleLineText(rawTitle, 120) || "vibecode-api";
|
|
2397
|
+
const baseUrl = resolveBaseUrl(contract, options);
|
|
2398
|
+
const className = sanitizeClassName(options.className, title);
|
|
2399
|
+
const packageName = format === "go" ? sanitizeGoPackageName(options.packageName, title) : undefined;
|
|
2400
|
+
const endpoints = [];
|
|
2401
|
+
const skippedIds = [];
|
|
2402
|
+
const warnings = [];
|
|
2403
|
+
const usedTsMethods = new Set();
|
|
2404
|
+
const usedPyMethods = new Set();
|
|
2405
|
+
const usedGoMethods = new Set();
|
|
2406
|
+
const usedPascalBases = new Set([className]);
|
|
2407
|
+
for (const inv of contract.invariants) {
|
|
2408
|
+
if (!isRecord(inv))
|
|
2409
|
+
continue;
|
|
2410
|
+
// Holdout invariants MUST remain completely invisible: no code, comments, counts, or warnings.
|
|
2411
|
+
if (inv.holdout === true) {
|
|
2412
|
+
continue;
|
|
2413
|
+
}
|
|
2414
|
+
const invId = typeof inv.id === "string" && inv.id.trim()
|
|
2415
|
+
? sanitizeSingleLineText(inv.id.trim(), 80)
|
|
2416
|
+
: "unknown";
|
|
2417
|
+
if (inv.type !== "http") {
|
|
2418
|
+
skippedIds.push(invId);
|
|
2419
|
+
continue;
|
|
2420
|
+
}
|
|
2421
|
+
const normalized = normalizeHttpInvariant(inv, usedTsMethods, usedPyMethods, usedGoMethods, usedPascalBases);
|
|
2422
|
+
if (!normalized) {
|
|
2423
|
+
skippedIds.push(invId);
|
|
2424
|
+
warnings.push(`Skipped HTTP invariant "${invId}" due to unsupported HTTP method.`);
|
|
2425
|
+
continue;
|
|
2426
|
+
}
|
|
2427
|
+
endpoints.push(normalized);
|
|
2428
|
+
}
|
|
2429
|
+
if (endpoints.length === 0) {
|
|
2430
|
+
warnings.push("No visible HTTP invariants found; generated empty client scaffold.");
|
|
2431
|
+
}
|
|
2432
|
+
let content;
|
|
2433
|
+
let methodNames;
|
|
2434
|
+
if (format === "ts-fetch") {
|
|
2435
|
+
content = emitTypeScriptClient(endpoints, baseUrl, title, className, skippedIds, includeSkippedComments);
|
|
2436
|
+
methodNames = endpoints.map((ep) => ep.tsMethodName);
|
|
2437
|
+
}
|
|
2438
|
+
else if (format === "python") {
|
|
2439
|
+
content = emitPythonClient(endpoints, baseUrl, title, className, skippedIds, includeSkippedComments);
|
|
2440
|
+
methodNames = endpoints.map((ep) => ep.pyMethodName);
|
|
2441
|
+
}
|
|
2442
|
+
else {
|
|
2443
|
+
content = emitGoClient(endpoints, baseUrl, title, className, packageName ?? "apiclient", skippedIds, includeSkippedComments);
|
|
2444
|
+
methodNames = endpoints.map((ep) => ep.goMethodName);
|
|
2445
|
+
}
|
|
2446
|
+
return {
|
|
2447
|
+
format,
|
|
2448
|
+
suggestedFilename: suggestedFilenameFor(format),
|
|
2449
|
+
content,
|
|
2450
|
+
exportedCount: endpoints.length,
|
|
2451
|
+
skippedCount: skippedIds.length,
|
|
2452
|
+
warnings,
|
|
2453
|
+
baseUrl,
|
|
2454
|
+
className,
|
|
2455
|
+
...(packageName ? { packageName } : {}),
|
|
2456
|
+
methodNames
|
|
2457
|
+
};
|
|
2458
|
+
}
|
|
2459
|
+
/**
|
|
2460
|
+
* Generate and atomically write a typed API client SDK file to disk via temp file + rename.
|
|
2461
|
+
*/
|
|
2462
|
+
export function writeClientCode(contract, outPath, options = {}) {
|
|
2463
|
+
if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
|
|
2464
|
+
throw new VibecodeError("CONTRACT_INVALID", "writeClientCode requires a valid non-empty outPath without NUL bytes.");
|
|
2465
|
+
}
|
|
2466
|
+
const trimmedPath = outPath.trim();
|
|
2467
|
+
const resolvedOut = path.resolve(trimmedPath);
|
|
2468
|
+
if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
|
|
2469
|
+
throw new VibecodeError("CONTRACT_INVALID", "writeClientCode outPath must point to a file, not a directory.");
|
|
2470
|
+
}
|
|
2471
|
+
const result = exportClientCode(contract, options);
|
|
2472
|
+
const parentDir = path.dirname(resolvedOut);
|
|
2473
|
+
fs.mkdirSync(parentDir, { recursive: true });
|
|
2474
|
+
const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
2475
|
+
try {
|
|
2476
|
+
fs.writeFileSync(tmpPath, result.content, "utf8");
|
|
2477
|
+
fs.renameSync(tmpPath, resolvedOut);
|
|
2478
|
+
}
|
|
2479
|
+
catch (err) {
|
|
2480
|
+
try {
|
|
2481
|
+
if (fs.existsSync(tmpPath)) {
|
|
2482
|
+
fs.rmSync(tmpPath, { force: true });
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
catch {
|
|
2486
|
+
// ignore cleanup error
|
|
2487
|
+
}
|
|
2488
|
+
throw err;
|
|
2489
|
+
}
|
|
2490
|
+
return {
|
|
2491
|
+
...result,
|
|
2492
|
+
outPath: resolvedOut
|
|
2493
|
+
};
|
|
2494
|
+
}
|
|
2495
|
+
function style(text, codes, useColor) {
|
|
2496
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
2497
|
+
}
|
|
2498
|
+
/**
|
|
2499
|
+
* Render a pure ASCII/ANSI terminal summary for a client SDK export with zero raw secrets or vault paths.
|
|
2500
|
+
*/
|
|
2501
|
+
export function formatPrettyClientExport(result, outPath, color = false) {
|
|
2502
|
+
const useColor = color === true;
|
|
2503
|
+
const lines = [];
|
|
2504
|
+
const banner = style("[CLIENT SDK]", `${ANSI.bold}${ANSI.cyan}`, useColor);
|
|
2505
|
+
const fmt = style(sanitizeSingleLineText(result.format, 32), ANSI.bold, useColor);
|
|
2506
|
+
lines.push(`${banner} ${fmt} (${sanitizeSingleLineText(result.className, 64)})`);
|
|
2507
|
+
const safeBaseUrl = sanitizeBaseUrl(result.baseUrl) ?? sanitizeSingleLineText(result.baseUrl, 160);
|
|
2508
|
+
lines.push(`Base URL: ${safeBaseUrl}`);
|
|
2509
|
+
if (result.packageName) {
|
|
2510
|
+
lines.push(`Package: ${sanitizeSingleLineText(result.packageName, 64)}`);
|
|
2511
|
+
}
|
|
2512
|
+
const effectiveOutPath = outPath ?? result.outPath;
|
|
2513
|
+
if (typeof effectiveOutPath === "string" && effectiveOutPath.trim()) {
|
|
2514
|
+
lines.push(`Output: ${sanitizeSingleLineText(effectiveOutPath, 240)}`);
|
|
2515
|
+
}
|
|
2516
|
+
const countText = style(`${result.exportedCount} ${result.exportedCount === 1 ? "endpoint" : "endpoints"}`, result.exportedCount > 0 ? ANSI.green : ANSI.yellow, useColor);
|
|
2517
|
+
const summaryParts = [countText];
|
|
2518
|
+
if (result.skippedCount > 0) {
|
|
2519
|
+
summaryParts.push(`${result.skippedCount} skipped`);
|
|
2520
|
+
}
|
|
2521
|
+
lines.push(`Summary: ${summaryParts.join(", ")}`);
|
|
2522
|
+
if (Array.isArray(result.methodNames) && result.methodNames.length > 0) {
|
|
2523
|
+
const maxShown = 16;
|
|
2524
|
+
const shown = result.methodNames.slice(0, maxShown).map((m) => sanitizeSingleLineText(m, 64));
|
|
2525
|
+
const suffix = result.methodNames.length > maxShown
|
|
2526
|
+
? `, ... (+${result.methodNames.length - maxShown} more)`
|
|
2527
|
+
: "";
|
|
2528
|
+
lines.push(`Methods: ${shown.join(", ")}${suffix}`);
|
|
2529
|
+
}
|
|
2530
|
+
if (Array.isArray(result.warnings) && result.warnings.length > 0) {
|
|
2531
|
+
lines.push("Warnings:");
|
|
2532
|
+
for (const warning of result.warnings.slice(0, 10)) {
|
|
2533
|
+
const cleanWarning = sanitizeSingleLineText(warning, 200);
|
|
2534
|
+
lines.push(` - ${style(cleanWarning, ANSI.yellow, useColor)}`);
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
return lines.join("\n");
|
|
2538
|
+
}
|