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,2482 @@
|
|
|
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 VALID_FORMATS = new Set(["sdl", "introspection"]);
|
|
7
|
+
const MAX_SCHEMA_DEPTH = 12;
|
|
8
|
+
const MAX_OBJECT_FIELDS = 100;
|
|
9
|
+
const MAX_ENUM_VALUES = 100;
|
|
10
|
+
const MAX_PRETTY_ITEMS = 20;
|
|
11
|
+
const MAX_PRETTY_WARNINGS = 10;
|
|
12
|
+
const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
13
|
+
const BUILTIN_SCALARS = new Set(["String", "Int", "Float", "Boolean", "ID"]);
|
|
14
|
+
const BUILTIN_SCALAR_ORDER = ["String", "Int", "Float", "Boolean", "ID"];
|
|
15
|
+
const GRAPHQL_RESERVED_TYPE_NAMES = new Set([
|
|
16
|
+
"Query",
|
|
17
|
+
"Mutation",
|
|
18
|
+
"Subscription",
|
|
19
|
+
"String",
|
|
20
|
+
"Int",
|
|
21
|
+
"Float",
|
|
22
|
+
"Boolean",
|
|
23
|
+
"ID",
|
|
24
|
+
"schema",
|
|
25
|
+
"type",
|
|
26
|
+
"interface",
|
|
27
|
+
"union",
|
|
28
|
+
"enum",
|
|
29
|
+
"input",
|
|
30
|
+
"scalar",
|
|
31
|
+
"directive",
|
|
32
|
+
"extend",
|
|
33
|
+
"implements",
|
|
34
|
+
"repeatable",
|
|
35
|
+
"on",
|
|
36
|
+
"true",
|
|
37
|
+
"false",
|
|
38
|
+
"null"
|
|
39
|
+
]);
|
|
40
|
+
const GRAPHQL_FORBIDDEN_ENUM_VALUES = new Set(["true", "false", "null"]);
|
|
41
|
+
const SUPPORTED_HTTP_METHODS = new Set([
|
|
42
|
+
"GET",
|
|
43
|
+
"POST",
|
|
44
|
+
"PUT",
|
|
45
|
+
"PATCH",
|
|
46
|
+
"DELETE",
|
|
47
|
+
"HEAD",
|
|
48
|
+
"OPTIONS"
|
|
49
|
+
]);
|
|
50
|
+
const MUTATING_HTTP_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
51
|
+
const EXTRA_SENSITIVE_HEADER_RE = /(?:authorization|proxy[-_]?authorization|cookie|set[-_]?cookie|api[-_]?key|apikey|token|secret|bearer|csrf|xsrf|password|passwd|passphrase|credential|private[-_]?key|session[-_]?id|jwt|(?:^|[-_])auth(?:$|[-_]))/i;
|
|
52
|
+
const EXTRA_SENSITIVE_QUERY_RE = /(?:token|api[-_]?key|apikey|secret|password|passwd|passphrase|jwt|session[-_]?id|private[-_]?key|authorization|cookie|csrf|xsrf|bearer|credential|(?:^|[-_])(?:auth|sig|signature)(?:$|[-_]))/i;
|
|
53
|
+
// Careful not to false-positive on normal domain words like `author` or `authors`.
|
|
54
|
+
const SECRET_FIELD_NAME_RE = /(?:password|passwd|passphrase|secret|token|apikey|api[_-]?key|private[_-]?key|authorization|proxy[_-]?authorization|cookie|set[_-]?cookie|session[_-]?id|jwt|credentials?|bearer|csrf|xsrf|auth(?:orization|entication|[_-]?(?:token|header|key|secret|code|pass))|(?:^|[_-])auth(?:$|[_-]))/i;
|
|
55
|
+
const AUTH_SCHEME_VALUE_RE = /^(?:\s*(?:bearer|basic|token|digest|apikey)\s+\S+)|\bbearer\s+\S+/i;
|
|
56
|
+
const VAULT_PATH_RE = /(?:~|[A-Za-z]:)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
|
|
57
|
+
const URL_IN_TEXT_RE = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'`<>()[\]{}]+/g;
|
|
58
|
+
const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/\s"'`<>]+)@/g;
|
|
59
|
+
const INLINE_BEARER_TOKEN_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
|
|
60
|
+
const INLINE_BASIC_TOKEN_RE = /\b([bB][aA][sS][iI][cC])\s+(?=[A-Za-z0-9._~+/=-]*(?:[0-9._~+/=-]|[A-Z]))[A-Za-z0-9._~+/=-]{6,}/g;
|
|
61
|
+
const INLINE_SCHEME_TOKEN_RE = /\b([tT][oO][kK][eE][nN]|[aA][pP][iI][kK][eE][yY])\s+(?=[A-Za-z0-9._~+/=:-]*(?:[0-9._~+/=:-]|[A-Z]))[A-Za-z0-9._~+/=:-]{6,}/g;
|
|
62
|
+
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,})/gi;
|
|
63
|
+
const INLINE_SENSITIVE_HEADER_RE = /\b(?:(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;]+(?:\s*;\s*[A-Za-z0-9_.-]+=[^\s,\r\n;]+)*|(Authorization|Proxy-Authorization|X-API-Key|X-Auth-Token|X-Access-Token|X-Session-Token|X-Secret|X-CSRF-Token|X-XSRF-Token|CSRF-Token|XSRF-Token)\s*[:=]\s*(?:(?:Bearer|Basic|Token|ApiKey|Digest)\s+(?:\[REDACTED\]|[^\s,;]+)|[^\s,;]+))/gi;
|
|
64
|
+
const INLINE_SENSITIVE_QUERY_RE = /([?&])([^=&\s#]+)=([^&\s#]+)/g;
|
|
65
|
+
const INLINE_SENSITIVE_ENV_RE = /\b([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;`"']+)/g;
|
|
66
|
+
const GRAPHQL_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
67
|
+
const ANSI = {
|
|
68
|
+
reset: "\x1b[0m",
|
|
69
|
+
bold: "\x1b[1m",
|
|
70
|
+
dim: "\x1b[2m",
|
|
71
|
+
red: "\x1b[31m",
|
|
72
|
+
green: "\x1b[32m",
|
|
73
|
+
yellow: "\x1b[33m",
|
|
74
|
+
cyan: "\x1b[36m"
|
|
75
|
+
};
|
|
76
|
+
function isRecord(value) {
|
|
77
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
78
|
+
}
|
|
79
|
+
function hasOwn(obj, key) {
|
|
80
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
81
|
+
}
|
|
82
|
+
function isForbiddenKey(key) {
|
|
83
|
+
return FORBIDDEN_KEYS.has(key);
|
|
84
|
+
}
|
|
85
|
+
function isSensitiveHeaderName(name) {
|
|
86
|
+
const trimmed = String(name).trim();
|
|
87
|
+
return isSensitiveHeader(trimmed) || EXTRA_SENSITIVE_HEADER_RE.test(trimmed);
|
|
88
|
+
}
|
|
89
|
+
function isSensitiveQueryName(name) {
|
|
90
|
+
const trimmed = String(name).trim();
|
|
91
|
+
return (isSensitiveQueryParam(trimmed) ||
|
|
92
|
+
EXTRA_SENSITIVE_QUERY_RE.test(trimmed) ||
|
|
93
|
+
isSensitiveHeaderName(trimmed));
|
|
94
|
+
}
|
|
95
|
+
function isSecretFieldName(name) {
|
|
96
|
+
const trimmed = String(name).trim();
|
|
97
|
+
if (!trimmed)
|
|
98
|
+
return false;
|
|
99
|
+
return (SECRET_FIELD_NAME_RE.test(trimmed) ||
|
|
100
|
+
isSensitiveHeaderName(trimmed) ||
|
|
101
|
+
isSensitiveQueryName(trimmed));
|
|
102
|
+
}
|
|
103
|
+
function hasAuthSchemeValue(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
|
+
const safeParams = new URLSearchParams();
|
|
117
|
+
for (const [k, v] of parsed.searchParams.entries()) {
|
|
118
|
+
const trimmedKey = k.trim();
|
|
119
|
+
if (!trimmedKey || isForbiddenKey(trimmedKey) || isSensitiveQueryName(trimmedKey))
|
|
120
|
+
continue;
|
|
121
|
+
if (hasAuthSchemeValue(v))
|
|
122
|
+
continue;
|
|
123
|
+
safeParams.append(k, redactVaultPaths(v));
|
|
124
|
+
}
|
|
125
|
+
const serialized = safeParams.toString();
|
|
126
|
+
parsed.search = serialized ? `?${serialized}` : "";
|
|
127
|
+
parsed.hash = "";
|
|
128
|
+
return parsed.toString();
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return withoutAuth
|
|
132
|
+
.replace(/#.*$/, "")
|
|
133
|
+
.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key) => isSensitiveQueryName(key) ? `${sep}${key}=[REDACTED]` : match);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
function sanitizeText(raw) {
|
|
137
|
+
const noNul = raw.replace(/\0/g, "");
|
|
138
|
+
const noVault = redactVaultPaths(noNul);
|
|
139
|
+
const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
|
|
140
|
+
const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
|
|
141
|
+
const noSensQuery = noBasicAuth.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key) => isSensitiveQueryName(key) ? `${sep}${key}=[REDACTED]` : match);
|
|
142
|
+
const noBearer = noSensQuery.replace(INLINE_BEARER_TOKEN_RE, "$1 [REDACTED]");
|
|
143
|
+
const noBasic = noBearer.replace(INLINE_BASIC_TOKEN_RE, "$1 [REDACTED]");
|
|
144
|
+
const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
|
|
145
|
+
const noDigest = noScheme.replace(INLINE_DIGEST_TOKEN_RE, "$1 [REDACTED]");
|
|
146
|
+
const noSensHeader = noDigest.replace(INLINE_SENSITIVE_HEADER_RE, (_m, cookieHdr, otherHdr) => `${cookieHdr || otherHdr}: [REDACTED]`);
|
|
147
|
+
return noSensHeader.replace(INLINE_SENSITIVE_ENV_RE, (match, key) => isSecretFieldName(key) ? `${key}=[REDACTED]` : match);
|
|
148
|
+
}
|
|
149
|
+
function sanitizeSingleLineText(raw) {
|
|
150
|
+
return sanitizeText(raw)
|
|
151
|
+
.replace(/[\r\n\u2028\u2029\x00-\x1f\x7f]+/g, " ")
|
|
152
|
+
.replace(/\s+/g, " ")
|
|
153
|
+
.trim();
|
|
154
|
+
}
|
|
155
|
+
function sanitizeDescription(raw) {
|
|
156
|
+
if (typeof raw !== "string")
|
|
157
|
+
return undefined;
|
|
158
|
+
const cleaned = sanitizeSingleLineText(raw);
|
|
159
|
+
if (!cleaned)
|
|
160
|
+
return undefined;
|
|
161
|
+
return cleaned.length > 240 ? `${cleaned.slice(0, 237)}...` : cleaned;
|
|
162
|
+
}
|
|
163
|
+
function formatSdlString(text) {
|
|
164
|
+
const clean = sanitizeSingleLineText(text);
|
|
165
|
+
// Single-line double-quoted GraphQL string; JSON.stringify escapes every `"` and `\`
|
|
166
|
+
// so neither `"` nor `"""` can ever break out of the string literal.
|
|
167
|
+
return JSON.stringify(clean).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
168
|
+
}
|
|
169
|
+
function splitIdentifierWords(raw) {
|
|
170
|
+
const cleaned = sanitizeSingleLineText(raw);
|
|
171
|
+
if (!cleaned)
|
|
172
|
+
return [];
|
|
173
|
+
return cleaned
|
|
174
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
175
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
|
|
176
|
+
.replace(/[^A-Za-z0-9]+/g, " ")
|
|
177
|
+
.trim()
|
|
178
|
+
.split(/\s+/)
|
|
179
|
+
.filter((w) => w.length > 0);
|
|
180
|
+
}
|
|
181
|
+
function toCamelCase(raw, fallback = "field") {
|
|
182
|
+
const words = splitIdentifierWords(raw);
|
|
183
|
+
if (words.length === 0)
|
|
184
|
+
return fallback;
|
|
185
|
+
const joined = words
|
|
186
|
+
.map((w, idx) => {
|
|
187
|
+
const lower = w.toLowerCase();
|
|
188
|
+
if (idx === 0)
|
|
189
|
+
return lower;
|
|
190
|
+
return lower.charAt(0).toUpperCase() + lower.slice(1);
|
|
191
|
+
})
|
|
192
|
+
.join("");
|
|
193
|
+
return sanitizeFieldIdentifier(joined, fallback);
|
|
194
|
+
}
|
|
195
|
+
function toPascalCase(raw, fallback = "Payload") {
|
|
196
|
+
const words = splitIdentifierWords(raw);
|
|
197
|
+
if (words.length === 0)
|
|
198
|
+
return fallback;
|
|
199
|
+
const joined = words
|
|
200
|
+
.map((w) => {
|
|
201
|
+
const lower = w.toLowerCase();
|
|
202
|
+
return lower.charAt(0).toUpperCase() + lower.slice(1);
|
|
203
|
+
})
|
|
204
|
+
.join("");
|
|
205
|
+
return sanitizeTypeIdentifier(joined, fallback);
|
|
206
|
+
}
|
|
207
|
+
function sanitizeFieldIdentifier(raw, fallback = "field") {
|
|
208
|
+
const cleaned = sanitizeSingleLineText(raw);
|
|
209
|
+
if (!cleaned || isForbiddenKey(cleaned))
|
|
210
|
+
return fallback;
|
|
211
|
+
let ident = cleaned.replace(/[^A-Za-z0-9_]+/g, "_");
|
|
212
|
+
// GraphQL forbids `__` prefix (introspection reserved)
|
|
213
|
+
ident = ident.replace(/^_+/, (m) => (m.length >= 2 ? "_" : m));
|
|
214
|
+
if (!ident || ident === "_")
|
|
215
|
+
return fallback;
|
|
216
|
+
if (/^[0-9]/.test(ident)) {
|
|
217
|
+
ident = `f_${ident}`;
|
|
218
|
+
}
|
|
219
|
+
if (ident.startsWith("__")) {
|
|
220
|
+
ident = `f_${ident.replace(/^_+/, "") || "field"}`;
|
|
221
|
+
}
|
|
222
|
+
if (isForbiddenKey(ident) || !GRAPHQL_IDENTIFIER_RE.test(ident)) {
|
|
223
|
+
return fallback;
|
|
224
|
+
}
|
|
225
|
+
return ident;
|
|
226
|
+
}
|
|
227
|
+
function sanitizeTypeIdentifier(raw, fallback = "Payload") {
|
|
228
|
+
const cleaned = sanitizeSingleLineText(raw);
|
|
229
|
+
if (!cleaned || isForbiddenKey(cleaned))
|
|
230
|
+
return fallback;
|
|
231
|
+
let ident = cleaned.replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+/, "");
|
|
232
|
+
if (!ident)
|
|
233
|
+
return fallback;
|
|
234
|
+
if (/^[0-9]/.test(ident)) {
|
|
235
|
+
ident = `T_${ident}`;
|
|
236
|
+
}
|
|
237
|
+
ident = ident.charAt(0).toUpperCase() + ident.slice(1);
|
|
238
|
+
if (ident.startsWith("__")) {
|
|
239
|
+
ident = `T_${ident.replace(/^_+/, "") || "Type"}`;
|
|
240
|
+
}
|
|
241
|
+
if (isForbiddenKey(ident) || !GRAPHQL_IDENTIFIER_RE.test(ident)) {
|
|
242
|
+
return fallback;
|
|
243
|
+
}
|
|
244
|
+
if (GRAPHQL_RESERVED_TYPE_NAMES.has(ident)) {
|
|
245
|
+
ident = `${ident}Payload`;
|
|
246
|
+
}
|
|
247
|
+
return ident;
|
|
248
|
+
}
|
|
249
|
+
function containsEmbeddedJsonOrSecretKv(raw) {
|
|
250
|
+
const trimmed = raw.trim();
|
|
251
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
252
|
+
try {
|
|
253
|
+
const parsed = JSON.parse(trimmed);
|
|
254
|
+
if (parsed !== null && typeof parsed === "object")
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
// fall through to key=value / secret checks
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const hasSecretKv = (s) => {
|
|
262
|
+
let found = false;
|
|
263
|
+
s.replace(INLINE_SENSITIVE_ENV_RE, (match, key) => {
|
|
264
|
+
if (isSecretFieldName(key))
|
|
265
|
+
found = true;
|
|
266
|
+
return match;
|
|
267
|
+
});
|
|
268
|
+
return found;
|
|
269
|
+
};
|
|
270
|
+
return hasSecretKv(raw);
|
|
271
|
+
}
|
|
272
|
+
function sanitizeEnumValueIdentifier(raw) {
|
|
273
|
+
if (containsEmbeddedJsonOrSecretKv(raw))
|
|
274
|
+
return null;
|
|
275
|
+
const cleaned = sanitizeSingleLineText(raw);
|
|
276
|
+
if (!cleaned || isForbiddenKey(cleaned))
|
|
277
|
+
return null;
|
|
278
|
+
if (GRAPHQL_FORBIDDEN_ENUM_VALUES.has(cleaned))
|
|
279
|
+
return null;
|
|
280
|
+
if (GRAPHQL_IDENTIFIER_RE.test(cleaned) && !cleaned.startsWith("__")) {
|
|
281
|
+
return cleaned;
|
|
282
|
+
}
|
|
283
|
+
let ident = cleaned
|
|
284
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
|
285
|
+
.replace(/[^A-Za-z0-9_]+/g, "_")
|
|
286
|
+
.replace(/^_+|_+$/g, "")
|
|
287
|
+
.toUpperCase();
|
|
288
|
+
if (!ident)
|
|
289
|
+
return null;
|
|
290
|
+
if (/^[0-9]/.test(ident)) {
|
|
291
|
+
ident = `V_${ident}`;
|
|
292
|
+
}
|
|
293
|
+
if (ident.startsWith("__")) {
|
|
294
|
+
ident = `V_${ident.replace(/^_+/, "")}`;
|
|
295
|
+
}
|
|
296
|
+
if (!ident ||
|
|
297
|
+
isForbiddenKey(ident) ||
|
|
298
|
+
GRAPHQL_FORBIDDEN_ENUM_VALUES.has(ident) ||
|
|
299
|
+
!GRAPHQL_IDENTIFIER_RE.test(ident)) {
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
return ident;
|
|
303
|
+
}
|
|
304
|
+
function isIdLikeFieldName(name) {
|
|
305
|
+
return name === "id" || name.endsWith("Id") || name.endsWith("_id");
|
|
306
|
+
}
|
|
307
|
+
function nonNull(ref) {
|
|
308
|
+
return ref.kind === "NON_NULL" ? ref : { kind: "NON_NULL", ofType: ref };
|
|
309
|
+
}
|
|
310
|
+
function listOf(ref) {
|
|
311
|
+
return { kind: "LIST", ofType: ref };
|
|
312
|
+
}
|
|
313
|
+
function namedType(name) {
|
|
314
|
+
return { kind: "NAMED", name };
|
|
315
|
+
}
|
|
316
|
+
function unwrapNullable(ref) {
|
|
317
|
+
return ref.kind === "NON_NULL" && ref.ofType ? ref.ofType : ref;
|
|
318
|
+
}
|
|
319
|
+
function unwrapNamedTypeName(ref) {
|
|
320
|
+
let cur = ref;
|
|
321
|
+
let guard = 0;
|
|
322
|
+
while (cur && guard < 32) {
|
|
323
|
+
if (cur.kind === "NAMED")
|
|
324
|
+
return cur.name || "String";
|
|
325
|
+
cur = cur.ofType;
|
|
326
|
+
guard += 1;
|
|
327
|
+
}
|
|
328
|
+
return "String";
|
|
329
|
+
}
|
|
330
|
+
function renderTypeRefSdl(ref, depth = 0) {
|
|
331
|
+
if (depth > 32)
|
|
332
|
+
return "String";
|
|
333
|
+
if (ref.kind === "NON_NULL" && ref.ofType) {
|
|
334
|
+
return `${renderTypeRefSdl(ref.ofType, depth + 1)}!`;
|
|
335
|
+
}
|
|
336
|
+
if (ref.kind === "LIST" && ref.ofType) {
|
|
337
|
+
return `[${renderTypeRefSdl(ref.ofType, depth + 1)}]`;
|
|
338
|
+
}
|
|
339
|
+
return ref.name || "String";
|
|
340
|
+
}
|
|
341
|
+
function typeSignature(def) {
|
|
342
|
+
if (def.kind === "SCALAR")
|
|
343
|
+
return `SCALAR:${def.name}`;
|
|
344
|
+
if (def.kind === "ENUM") {
|
|
345
|
+
return `ENUM:${(def.enumValues || []).join(",")}`;
|
|
346
|
+
}
|
|
347
|
+
if (def.kind === "INPUT_OBJECT") {
|
|
348
|
+
const parts = (def.inputFields || [])
|
|
349
|
+
.map((f) => `${f.name}:${renderTypeRefSdl(f.type)}`)
|
|
350
|
+
.sort();
|
|
351
|
+
return `INPUT:${parts.join(";")}`;
|
|
352
|
+
}
|
|
353
|
+
const parts = (def.fields || [])
|
|
354
|
+
.map((f) => {
|
|
355
|
+
const argSig = f.args.map((a) => `${a.name}:${renderTypeRefSdl(a.type)}`).join(",");
|
|
356
|
+
return `${f.name}(${argSig}):${renderTypeRefSdl(f.type)}`;
|
|
357
|
+
})
|
|
358
|
+
.sort();
|
|
359
|
+
return `OBJECT:${parts.join(";")}`;
|
|
360
|
+
}
|
|
361
|
+
class SchemaBuilder {
|
|
362
|
+
types = new Map();
|
|
363
|
+
queryFields = new Map();
|
|
364
|
+
mutationFields = new Map();
|
|
365
|
+
warnings = [];
|
|
366
|
+
warningSet = new Set();
|
|
367
|
+
signatureToName = new Map();
|
|
368
|
+
usedJsonScalar = false;
|
|
369
|
+
addWarning(message) {
|
|
370
|
+
const clean = sanitizeSingleLineText(message);
|
|
371
|
+
if (!clean || this.warningSet.has(clean))
|
|
372
|
+
return;
|
|
373
|
+
this.warningSet.add(clean);
|
|
374
|
+
this.warnings.push(clean);
|
|
375
|
+
}
|
|
376
|
+
ensureJsonScalar() {
|
|
377
|
+
if (!this.usedJsonScalar) {
|
|
378
|
+
this.usedJsonScalar = true;
|
|
379
|
+
if (!this.types.has("JSON")) {
|
|
380
|
+
this.types.set("JSON", {
|
|
381
|
+
kind: "SCALAR",
|
|
382
|
+
name: "JSON",
|
|
383
|
+
description: "Arbitrary JSON scalar value"
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return namedType("JSON");
|
|
388
|
+
}
|
|
389
|
+
registerNamedType(preferredName, defWithoutName) {
|
|
390
|
+
const baseName = sanitizeTypeIdentifier(preferredName, "Payload");
|
|
391
|
+
const tempDef = { ...defWithoutName, name: baseName };
|
|
392
|
+
const sig = typeSignature(tempDef);
|
|
393
|
+
// Reuse existing identical non-scalar type when structurally identical.
|
|
394
|
+
if (defWithoutName.kind !== "SCALAR") {
|
|
395
|
+
const exactSame = this.types.get(baseName);
|
|
396
|
+
if (exactSame && typeSignature(exactSame) === sig) {
|
|
397
|
+
return baseName;
|
|
398
|
+
}
|
|
399
|
+
const existingBySig = this.signatureToName.get(sig);
|
|
400
|
+
if (existingBySig && this.types.has(existingBySig)) {
|
|
401
|
+
return existingBySig;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
else if (this.types.has(baseName)) {
|
|
405
|
+
return baseName;
|
|
406
|
+
}
|
|
407
|
+
let candidate = baseName;
|
|
408
|
+
let suffix = 2;
|
|
409
|
+
while (this.types.has(candidate) || GRAPHQL_RESERVED_TYPE_NAMES.has(candidate)) {
|
|
410
|
+
candidate = `${baseName}${suffix}`;
|
|
411
|
+
suffix += 1;
|
|
412
|
+
}
|
|
413
|
+
const finalDef = { ...defWithoutName, name: candidate };
|
|
414
|
+
this.types.set(candidate, finalDef);
|
|
415
|
+
if (defWithoutName.kind !== "SCALAR") {
|
|
416
|
+
this.signatureToName.set(sig, candidate);
|
|
417
|
+
}
|
|
418
|
+
return candidate;
|
|
419
|
+
}
|
|
420
|
+
registerExplicitType(name, def) {
|
|
421
|
+
const safeName = sanitizeTypeIdentifier(name, "Payload");
|
|
422
|
+
const existing = this.types.get(safeName);
|
|
423
|
+
if (existing) {
|
|
424
|
+
if (existing.kind === def.kind) {
|
|
425
|
+
if (def.kind === "INPUT_OBJECT" && def.inputFields && existing.inputFields) {
|
|
426
|
+
const seen = new Set(existing.inputFields.map((f) => f.name));
|
|
427
|
+
for (const field of def.inputFields) {
|
|
428
|
+
if (!seen.has(field.name)) {
|
|
429
|
+
existing.inputFields.push(field);
|
|
430
|
+
seen.add(field.name);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return safeName;
|
|
435
|
+
}
|
|
436
|
+
return this.registerNamedType(`${safeName}Type`, {
|
|
437
|
+
kind: def.kind,
|
|
438
|
+
...(def.description ? { description: def.description } : {}),
|
|
439
|
+
...(def.fields ? { fields: def.fields } : {}),
|
|
440
|
+
...(def.inputFields ? { inputFields: def.inputFields } : {}),
|
|
441
|
+
...(def.enumValues ? { enumValues: def.enumValues } : {})
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
const finalDef = { ...def, name: safeName };
|
|
445
|
+
this.types.set(safeName, finalDef);
|
|
446
|
+
if (def.kind !== "SCALAR") {
|
|
447
|
+
this.signatureToName.set(typeSignature(finalDef), safeName);
|
|
448
|
+
}
|
|
449
|
+
return safeName;
|
|
450
|
+
}
|
|
451
|
+
addRootField(root, field, mergeIfExists) {
|
|
452
|
+
const map = root === "query" ? this.queryFields : this.mutationFields;
|
|
453
|
+
const baseName = sanitizeFieldIdentifier(field.name, root === "query" ? "queryField" : "mutationField");
|
|
454
|
+
if (mergeIfExists && map.has(baseName)) {
|
|
455
|
+
const existing = map.get(baseName);
|
|
456
|
+
const existingArgNames = new Set(existing.args.map((a) => a.name));
|
|
457
|
+
for (const arg of field.args) {
|
|
458
|
+
if (!existingArgNames.has(arg.name)) {
|
|
459
|
+
existing.args.push(arg);
|
|
460
|
+
existingArgNames.add(arg.name);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
// Prefer a structured object return type over a generic scalar fallback.
|
|
464
|
+
const existingNamed = unwrapNamedTypeName(existing.type);
|
|
465
|
+
const incomingNamed = unwrapNamedTypeName(field.type);
|
|
466
|
+
if (BUILTIN_SCALARS.has(existingNamed) && !BUILTIN_SCALARS.has(incomingNamed)) {
|
|
467
|
+
existing.type = field.type;
|
|
468
|
+
}
|
|
469
|
+
return baseName;
|
|
470
|
+
}
|
|
471
|
+
let candidate = baseName;
|
|
472
|
+
let suffix = 2;
|
|
473
|
+
while (map.has(candidate)) {
|
|
474
|
+
candidate = `${baseName}${suffix}`;
|
|
475
|
+
suffix += 1;
|
|
476
|
+
}
|
|
477
|
+
map.set(candidate, { ...field, name: candidate });
|
|
478
|
+
return candidate;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function tokenizeOperation(rawText) {
|
|
482
|
+
const text = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
483
|
+
const tokens = [];
|
|
484
|
+
const len = text.length;
|
|
485
|
+
let i = 0;
|
|
486
|
+
while (i < len) {
|
|
487
|
+
const ch = text[i];
|
|
488
|
+
const code = text.charCodeAt(i);
|
|
489
|
+
if (ch === " " || ch === "\t" || ch === "," || ch === "\n" || ch === "\r") {
|
|
490
|
+
i += 1;
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
if (ch === "#") {
|
|
494
|
+
while (i < len && text[i] !== "\n" && text[i] !== "\r")
|
|
495
|
+
i += 1;
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (ch === "." && text[i + 1] === "." && text[i + 2] === ".") {
|
|
499
|
+
tokens.push({ kind: "PUNCT", value: "..." });
|
|
500
|
+
i += 3;
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
if ("!$():=@[{}]|&".includes(ch) || ch === "]") {
|
|
504
|
+
tokens.push({ kind: "PUNCT", value: ch });
|
|
505
|
+
i += 1;
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
// Block string """..."""
|
|
509
|
+
if (ch === '"' && text[i + 1] === '"' && text[i + 2] === '"') {
|
|
510
|
+
i += 3;
|
|
511
|
+
let val = "";
|
|
512
|
+
while (i < len) {
|
|
513
|
+
if (text[i] === "\\" && text[i + 1] === '"' && text[i + 2] === '"' && text[i + 3] === '"') {
|
|
514
|
+
val += '"""';
|
|
515
|
+
i += 4;
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (text[i] === '"' && text[i + 1] === '"' && text[i + 2] === '"') {
|
|
519
|
+
i += 3;
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
val += text[i];
|
|
523
|
+
i += 1;
|
|
524
|
+
}
|
|
525
|
+
tokens.push({ kind: "STRING", value: val });
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
// Quoted string "..."
|
|
529
|
+
if (ch === '"') {
|
|
530
|
+
i += 1;
|
|
531
|
+
let val = "";
|
|
532
|
+
while (i < len) {
|
|
533
|
+
const c = text[i];
|
|
534
|
+
if (c === "\n" || c === "\r")
|
|
535
|
+
break;
|
|
536
|
+
if (c === '"') {
|
|
537
|
+
i += 1;
|
|
538
|
+
break;
|
|
539
|
+
}
|
|
540
|
+
if (c === "\\" && i + 1 < len) {
|
|
541
|
+
const esc = text[i + 1];
|
|
542
|
+
if (esc === "n")
|
|
543
|
+
val += "\n";
|
|
544
|
+
else if (esc === "r")
|
|
545
|
+
val += "\r";
|
|
546
|
+
else if (esc === "t")
|
|
547
|
+
val += "\t";
|
|
548
|
+
else
|
|
549
|
+
val += esc;
|
|
550
|
+
i += 2;
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
val += c;
|
|
554
|
+
i += 1;
|
|
555
|
+
}
|
|
556
|
+
tokens.push({ kind: "STRING", value: val });
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
// Number
|
|
560
|
+
if (ch === "-" || (code >= 48 && code <= 57)) {
|
|
561
|
+
const start = i;
|
|
562
|
+
if (text[i] === "-")
|
|
563
|
+
i += 1;
|
|
564
|
+
while (i < len && text.charCodeAt(i) >= 48 && text.charCodeAt(i) <= 57)
|
|
565
|
+
i += 1;
|
|
566
|
+
let isFloat = false;
|
|
567
|
+
if (text[i] === ".") {
|
|
568
|
+
isFloat = true;
|
|
569
|
+
i += 1;
|
|
570
|
+
while (i < len && text.charCodeAt(i) >= 48 && text.charCodeAt(i) <= 57)
|
|
571
|
+
i += 1;
|
|
572
|
+
}
|
|
573
|
+
if (text[i] === "e" || text[i] === "E") {
|
|
574
|
+
isFloat = true;
|
|
575
|
+
i += 1;
|
|
576
|
+
if (text[i] === "+" || text[i] === "-")
|
|
577
|
+
i += 1;
|
|
578
|
+
while (i < len && text.charCodeAt(i) >= 48 && text.charCodeAt(i) <= 57)
|
|
579
|
+
i += 1;
|
|
580
|
+
}
|
|
581
|
+
const numStr = text.slice(start, i);
|
|
582
|
+
if (numStr === "-") {
|
|
583
|
+
i = start + 1;
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
tokens.push({ kind: isFloat ? "FLOAT" : "INT", value: numStr });
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
// Identifier
|
|
590
|
+
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95) {
|
|
591
|
+
const start = i;
|
|
592
|
+
i += 1;
|
|
593
|
+
while (i < len) {
|
|
594
|
+
const cc = text.charCodeAt(i);
|
|
595
|
+
if ((cc >= 65 && cc <= 90) ||
|
|
596
|
+
(cc >= 97 && cc <= 122) ||
|
|
597
|
+
(cc >= 48 && cc <= 57) ||
|
|
598
|
+
cc === 95) {
|
|
599
|
+
i += 1;
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
break;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
tokens.push({ kind: "NAME", value: text.slice(start, i) });
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
// Unexpected char — skip safely to avoid infinite loop
|
|
609
|
+
i += 1;
|
|
610
|
+
}
|
|
611
|
+
tokens.push({ kind: "EOF", value: "" });
|
|
612
|
+
return tokens;
|
|
613
|
+
}
|
|
614
|
+
function parseGraphqlOperationDocument(rawQuery, targetOperationName) {
|
|
615
|
+
const tokens = tokenizeOperation(rawQuery);
|
|
616
|
+
let pos = 0;
|
|
617
|
+
const peek = (offset = 0) => tokens[Math.min(pos + offset, tokens.length - 1)];
|
|
618
|
+
const next = () => {
|
|
619
|
+
const tok = peek();
|
|
620
|
+
if (pos < tokens.length - 1)
|
|
621
|
+
pos += 1;
|
|
622
|
+
return tok;
|
|
623
|
+
};
|
|
624
|
+
const matchPunct = (val) => {
|
|
625
|
+
const tok = peek();
|
|
626
|
+
if (tok.kind === "PUNCT" && tok.value === val) {
|
|
627
|
+
next();
|
|
628
|
+
return true;
|
|
629
|
+
}
|
|
630
|
+
return false;
|
|
631
|
+
};
|
|
632
|
+
const parseTypeRef = (depth = 0) => {
|
|
633
|
+
if (depth > MAX_SCHEMA_DEPTH)
|
|
634
|
+
return namedType("String");
|
|
635
|
+
let ref = null;
|
|
636
|
+
if (matchPunct("[")) {
|
|
637
|
+
const inner = parseTypeRef(depth + 1);
|
|
638
|
+
if (!inner)
|
|
639
|
+
return null;
|
|
640
|
+
if (!matchPunct("]"))
|
|
641
|
+
return null;
|
|
642
|
+
ref = listOf(inner);
|
|
643
|
+
}
|
|
644
|
+
else if (peek().kind === "NAME") {
|
|
645
|
+
const rawName = next().value;
|
|
646
|
+
const safeName = BUILTIN_SCALARS.has(rawName)
|
|
647
|
+
? rawName
|
|
648
|
+
: sanitizeTypeIdentifier(rawName, "Payload");
|
|
649
|
+
ref = namedType(safeName);
|
|
650
|
+
}
|
|
651
|
+
else {
|
|
652
|
+
return null;
|
|
653
|
+
}
|
|
654
|
+
if (matchPunct("!")) {
|
|
655
|
+
ref = nonNull(ref);
|
|
656
|
+
}
|
|
657
|
+
return ref;
|
|
658
|
+
};
|
|
659
|
+
const parseValue = (depth = 0) => {
|
|
660
|
+
if (depth > MAX_SCHEMA_DEPTH)
|
|
661
|
+
return { kind: "STRING", value: "" };
|
|
662
|
+
const tok = peek();
|
|
663
|
+
if (tok.kind === "PUNCT" && tok.value === "$") {
|
|
664
|
+
next();
|
|
665
|
+
if (peek().kind !== "NAME")
|
|
666
|
+
return null;
|
|
667
|
+
return { kind: "VARIABLE", name: next().value };
|
|
668
|
+
}
|
|
669
|
+
if (tok.kind === "INT") {
|
|
670
|
+
next();
|
|
671
|
+
return { kind: "INT", value: Number.parseInt(tok.value, 10) };
|
|
672
|
+
}
|
|
673
|
+
if (tok.kind === "FLOAT") {
|
|
674
|
+
next();
|
|
675
|
+
return { kind: "FLOAT", value: Number.parseFloat(tok.value) };
|
|
676
|
+
}
|
|
677
|
+
if (tok.kind === "STRING") {
|
|
678
|
+
next();
|
|
679
|
+
return { kind: "STRING", value: tok.value };
|
|
680
|
+
}
|
|
681
|
+
if (tok.kind === "NAME") {
|
|
682
|
+
next();
|
|
683
|
+
if (tok.value === "true")
|
|
684
|
+
return { kind: "BOOLEAN", value: true };
|
|
685
|
+
if (tok.value === "false")
|
|
686
|
+
return { kind: "BOOLEAN", value: false };
|
|
687
|
+
if (tok.value === "null")
|
|
688
|
+
return { kind: "NULL" };
|
|
689
|
+
return { kind: "ENUM", value: tok.value };
|
|
690
|
+
}
|
|
691
|
+
if (matchPunct("[")) {
|
|
692
|
+
const values = [];
|
|
693
|
+
let guard = 0;
|
|
694
|
+
while (!(peek().kind === "PUNCT" && peek().value === "]") && peek().kind !== "EOF" && guard < 200) {
|
|
695
|
+
guard += 1;
|
|
696
|
+
const val = parseValue(depth + 1);
|
|
697
|
+
if (!val)
|
|
698
|
+
break;
|
|
699
|
+
values.push(val);
|
|
700
|
+
}
|
|
701
|
+
matchPunct("]");
|
|
702
|
+
return { kind: "LIST", values };
|
|
703
|
+
}
|
|
704
|
+
if (matchPunct("{")) {
|
|
705
|
+
const fields = [];
|
|
706
|
+
let guard = 0;
|
|
707
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}") && peek().kind !== "EOF" && guard < 200) {
|
|
708
|
+
guard += 1;
|
|
709
|
+
if (peek().kind !== "NAME")
|
|
710
|
+
break;
|
|
711
|
+
const fieldName = next().value;
|
|
712
|
+
if (!matchPunct(":"))
|
|
713
|
+
break;
|
|
714
|
+
const fieldVal = parseValue(depth + 1);
|
|
715
|
+
if (!fieldVal)
|
|
716
|
+
break;
|
|
717
|
+
if (!isForbiddenKey(fieldName)) {
|
|
718
|
+
fields.push({ name: fieldName, value: fieldVal });
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
matchPunct("}");
|
|
722
|
+
return { kind: "OBJECT", fields };
|
|
723
|
+
}
|
|
724
|
+
return null;
|
|
725
|
+
};
|
|
726
|
+
const skipDirectives = () => {
|
|
727
|
+
let guard = 0;
|
|
728
|
+
while (peek().kind === "PUNCT" && peek().value === "@" && guard < 32) {
|
|
729
|
+
guard += 1;
|
|
730
|
+
next();
|
|
731
|
+
if (peek().kind === "NAME")
|
|
732
|
+
next();
|
|
733
|
+
if (matchPunct("(")) {
|
|
734
|
+
let argGuard = 0;
|
|
735
|
+
while (!(peek().kind === "PUNCT" && peek().value === ")") && peek().kind !== "EOF" && argGuard < 64) {
|
|
736
|
+
argGuard += 1;
|
|
737
|
+
if (peek().kind === "NAME")
|
|
738
|
+
next();
|
|
739
|
+
if (matchPunct(":")) {
|
|
740
|
+
parseValue(0);
|
|
741
|
+
}
|
|
742
|
+
else {
|
|
743
|
+
next();
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
matchPunct(")");
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
const fragments = new Map();
|
|
751
|
+
const skipSelectionSet = () => {
|
|
752
|
+
if (!matchPunct("{"))
|
|
753
|
+
return;
|
|
754
|
+
let braceDepth = 1;
|
|
755
|
+
let guard = 0;
|
|
756
|
+
while (braceDepth > 0 && peek().kind !== "EOF" && guard < 10000) {
|
|
757
|
+
guard += 1;
|
|
758
|
+
const tok = next();
|
|
759
|
+
if (tok.kind === "PUNCT" && tok.value === "{")
|
|
760
|
+
braceDepth += 1;
|
|
761
|
+
else if (tok.kind === "PUNCT" && tok.value === "}")
|
|
762
|
+
braceDepth -= 1;
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
const parseSelectionSet = (depth = 0) => {
|
|
766
|
+
if (!matchPunct("{"))
|
|
767
|
+
return [];
|
|
768
|
+
const selections = [];
|
|
769
|
+
let guard = 0;
|
|
770
|
+
while (!(peek().kind === "PUNCT" && peek().value === "}") && peek().kind !== "EOF" && guard < 500) {
|
|
771
|
+
guard += 1;
|
|
772
|
+
if (matchPunct("...")) {
|
|
773
|
+
if (peek().kind === "NAME" && peek().value === "on") {
|
|
774
|
+
next();
|
|
775
|
+
if (peek().kind === "NAME")
|
|
776
|
+
next(); // type condition
|
|
777
|
+
skipDirectives();
|
|
778
|
+
if (depth < MAX_SCHEMA_DEPTH) {
|
|
779
|
+
selections.push(...parseSelectionSet(depth + 1));
|
|
780
|
+
}
|
|
781
|
+
else {
|
|
782
|
+
skipSelectionSet();
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
else if (peek().kind === "NAME") {
|
|
786
|
+
const fragName = next().value;
|
|
787
|
+
skipDirectives();
|
|
788
|
+
selections.push({
|
|
789
|
+
name: `...${fragName}`,
|
|
790
|
+
args: [],
|
|
791
|
+
children: []
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
else {
|
|
795
|
+
skipDirectives();
|
|
796
|
+
if (peek().kind === "PUNCT" && peek().value === "{") {
|
|
797
|
+
if (depth < MAX_SCHEMA_DEPTH) {
|
|
798
|
+
selections.push(...parseSelectionSet(depth + 1));
|
|
799
|
+
}
|
|
800
|
+
else {
|
|
801
|
+
skipSelectionSet();
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
if (peek().kind !== "NAME") {
|
|
808
|
+
next();
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
const firstName = next().value;
|
|
812
|
+
let alias;
|
|
813
|
+
let fieldName = firstName;
|
|
814
|
+
if (matchPunct(":")) {
|
|
815
|
+
if (peek().kind !== "NAME")
|
|
816
|
+
continue;
|
|
817
|
+
alias = firstName;
|
|
818
|
+
fieldName = next().value;
|
|
819
|
+
}
|
|
820
|
+
const args = [];
|
|
821
|
+
if (matchPunct("(")) {
|
|
822
|
+
let argGuard = 0;
|
|
823
|
+
while (!(peek().kind === "PUNCT" && peek().value === ")") && peek().kind !== "EOF" && argGuard < 100) {
|
|
824
|
+
argGuard += 1;
|
|
825
|
+
if (peek().kind !== "NAME") {
|
|
826
|
+
next();
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
const argName = next().value;
|
|
830
|
+
if (!matchPunct(":"))
|
|
831
|
+
continue;
|
|
832
|
+
const argVal = parseValue(0);
|
|
833
|
+
if (argVal && !isForbiddenKey(argName)) {
|
|
834
|
+
args.push({ name: argName, value: argVal });
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
matchPunct(")");
|
|
838
|
+
}
|
|
839
|
+
skipDirectives();
|
|
840
|
+
let children = [];
|
|
841
|
+
if (peek().kind === "PUNCT" && peek().value === "{") {
|
|
842
|
+
if (depth < MAX_SCHEMA_DEPTH) {
|
|
843
|
+
children = parseSelectionSet(depth + 1);
|
|
844
|
+
}
|
|
845
|
+
else {
|
|
846
|
+
skipSelectionSet();
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
selections.push({
|
|
850
|
+
name: fieldName,
|
|
851
|
+
...(alias ? { alias } : {}),
|
|
852
|
+
args,
|
|
853
|
+
children
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
matchPunct("}");
|
|
857
|
+
return selections;
|
|
858
|
+
};
|
|
859
|
+
const expandFragments = (nodes, seen, depth = 0) => {
|
|
860
|
+
if (depth > MAX_SCHEMA_DEPTH)
|
|
861
|
+
return [];
|
|
862
|
+
const out = [];
|
|
863
|
+
for (const node of nodes) {
|
|
864
|
+
if (node.name.startsWith("...")) {
|
|
865
|
+
const fragName = node.name.slice(3);
|
|
866
|
+
if (seen.has(fragName))
|
|
867
|
+
continue;
|
|
868
|
+
const fragSelections = fragments.get(fragName);
|
|
869
|
+
if (!fragSelections)
|
|
870
|
+
continue;
|
|
871
|
+
const nextSeen = new Set(seen);
|
|
872
|
+
nextSeen.add(fragName);
|
|
873
|
+
out.push(...expandFragments(fragSelections, nextSeen, depth + 1));
|
|
874
|
+
}
|
|
875
|
+
else {
|
|
876
|
+
out.push({
|
|
877
|
+
...node,
|
|
878
|
+
children: expandFragments(node.children, seen, depth + 1)
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
return out;
|
|
883
|
+
};
|
|
884
|
+
const operations = [];
|
|
885
|
+
let topGuard = 0;
|
|
886
|
+
while (peek().kind !== "EOF" && topGuard < 100) {
|
|
887
|
+
topGuard += 1;
|
|
888
|
+
const tok = peek();
|
|
889
|
+
if (tok.kind === "PUNCT" && tok.value === "{") {
|
|
890
|
+
const selections = parseSelectionSet(0);
|
|
891
|
+
if (selections.length > 0) {
|
|
892
|
+
operations.push({
|
|
893
|
+
operationKind: "query",
|
|
894
|
+
variables: new Map(),
|
|
895
|
+
selections
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
continue;
|
|
899
|
+
}
|
|
900
|
+
if (tok.kind === "NAME" && tok.value === "fragment") {
|
|
901
|
+
next();
|
|
902
|
+
if (peek().kind !== "NAME")
|
|
903
|
+
break;
|
|
904
|
+
const fragName = next().value;
|
|
905
|
+
if (peek().kind === "NAME" && peek().value === "on") {
|
|
906
|
+
next();
|
|
907
|
+
if (peek().kind === "NAME")
|
|
908
|
+
next();
|
|
909
|
+
}
|
|
910
|
+
skipDirectives();
|
|
911
|
+
const fragSelections = parseSelectionSet(0);
|
|
912
|
+
if (!isForbiddenKey(fragName)) {
|
|
913
|
+
fragments.set(fragName, fragSelections);
|
|
914
|
+
}
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
if (tok.kind === "NAME" &&
|
|
918
|
+
(tok.value === "query" || tok.value === "mutation" || tok.value === "subscription")) {
|
|
919
|
+
const opKind = next().value;
|
|
920
|
+
let opName;
|
|
921
|
+
if (peek().kind === "NAME") {
|
|
922
|
+
opName = next().value;
|
|
923
|
+
}
|
|
924
|
+
const variables = new Map();
|
|
925
|
+
if (matchPunct("(")) {
|
|
926
|
+
let varGuard = 0;
|
|
927
|
+
while (!(peek().kind === "PUNCT" && peek().value === ")") && peek().kind !== "EOF" && varGuard < 100) {
|
|
928
|
+
varGuard += 1;
|
|
929
|
+
if (!matchPunct("$")) {
|
|
930
|
+
next();
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
if (peek().kind !== "NAME")
|
|
934
|
+
continue;
|
|
935
|
+
const varName = next().value;
|
|
936
|
+
if (!matchPunct(":"))
|
|
937
|
+
continue;
|
|
938
|
+
const varType = parseTypeRef(0);
|
|
939
|
+
if (matchPunct("=")) {
|
|
940
|
+
parseValue(0);
|
|
941
|
+
}
|
|
942
|
+
skipDirectives();
|
|
943
|
+
if (varType && !isForbiddenKey(varName)) {
|
|
944
|
+
variables.set(varName, varType);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
matchPunct(")");
|
|
948
|
+
}
|
|
949
|
+
skipDirectives();
|
|
950
|
+
const selections = parseSelectionSet(0);
|
|
951
|
+
if (selections.length > 0) {
|
|
952
|
+
operations.push({
|
|
953
|
+
operationKind: opKind,
|
|
954
|
+
...(opName ? { operationName: opName } : {}),
|
|
955
|
+
variables,
|
|
956
|
+
selections
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
// Not a recognized GraphQL operation token
|
|
962
|
+
return null;
|
|
963
|
+
}
|
|
964
|
+
if (operations.length === 0)
|
|
965
|
+
return null;
|
|
966
|
+
let chosen = operations[0];
|
|
967
|
+
if (targetOperationName) {
|
|
968
|
+
const match = operations.find((op) => op.operationName === targetOperationName);
|
|
969
|
+
if (match)
|
|
970
|
+
chosen = match;
|
|
971
|
+
}
|
|
972
|
+
return {
|
|
973
|
+
...chosen,
|
|
974
|
+
selections: expandFragments(chosen.selections, new Set(), 0)
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
function parseJsonBody(rawBody) {
|
|
978
|
+
if (typeof rawBody === "string") {
|
|
979
|
+
const trimmed = rawBody.trim();
|
|
980
|
+
if (!trimmed)
|
|
981
|
+
return undefined;
|
|
982
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
983
|
+
try {
|
|
984
|
+
return JSON.parse(trimmed);
|
|
985
|
+
}
|
|
986
|
+
catch {
|
|
987
|
+
return rawBody;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
return rawBody;
|
|
991
|
+
}
|
|
992
|
+
return rawBody;
|
|
993
|
+
}
|
|
994
|
+
function looksLikeGraphqlOperationText(text) {
|
|
995
|
+
const cleaned = text.replace(/^\uFEFF/, "").replace(/(?:^|\n)\s*#[^\n]*/g, "").trim();
|
|
996
|
+
if (!cleaned)
|
|
997
|
+
return false;
|
|
998
|
+
return /^(?:query|mutation|subscription|fragment)\b/i.test(cleaned) || cleaned.startsWith("{");
|
|
999
|
+
}
|
|
1000
|
+
function detectNativeGraphqlPayload(inv) {
|
|
1001
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
1002
|
+
const rawBody = parseJsonBody(input.body);
|
|
1003
|
+
if (isRecord(rawBody) && typeof rawBody.query === "string" && rawBody.query.trim()) {
|
|
1004
|
+
const query = rawBody.query.trim();
|
|
1005
|
+
if (looksLikeGraphqlOperationText(query)) {
|
|
1006
|
+
const operationName = typeof rawBody.operationName === "string" && rawBody.operationName.trim()
|
|
1007
|
+
? rawBody.operationName.trim()
|
|
1008
|
+
: undefined;
|
|
1009
|
+
const variables = isRecord(rawBody.variables) ? rawBody.variables : undefined;
|
|
1010
|
+
return {
|
|
1011
|
+
query,
|
|
1012
|
+
...(operationName ? { operationName } : {}),
|
|
1013
|
+
...(variables ? { variables } : {})
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
// Also check GET /graphql?query=...
|
|
1018
|
+
const rawPath = typeof input.path === "string" ? input.path : typeof input.urlPath === "string" ? input.urlPath : "";
|
|
1019
|
+
const hasGraphqlHint = /\/(?:graphql|gql)(?:$|[/?#])/i.test(rawPath) ||
|
|
1020
|
+
(Array.isArray(inv.tags) && inv.tags.some((t) => typeof t === "string" && t.toLowerCase() === "graphql"));
|
|
1021
|
+
if (hasGraphqlHint) {
|
|
1022
|
+
if (isRecord(input.query) && typeof input.query.query === "string" && looksLikeGraphqlOperationText(input.query.query)) {
|
|
1023
|
+
let variables;
|
|
1024
|
+
if (typeof input.query.variables === "string") {
|
|
1025
|
+
try {
|
|
1026
|
+
const parsedVars = JSON.parse(input.query.variables);
|
|
1027
|
+
if (isRecord(parsedVars))
|
|
1028
|
+
variables = parsedVars;
|
|
1029
|
+
}
|
|
1030
|
+
catch {
|
|
1031
|
+
// ignore malformed variables
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
return {
|
|
1035
|
+
query: input.query.query.trim(),
|
|
1036
|
+
...(typeof input.query.operationName === "string" && input.query.operationName.trim()
|
|
1037
|
+
? { operationName: input.query.operationName.trim() }
|
|
1038
|
+
: {}),
|
|
1039
|
+
...(variables ? { variables } : {})
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
if (rawPath.includes("?")) {
|
|
1043
|
+
try {
|
|
1044
|
+
const parsedUrl = new URL(rawPath.startsWith("http") ? rawPath : `http://local.invalid${rawPath.startsWith("/") ? "" : "/"}${rawPath}`);
|
|
1045
|
+
const q = parsedUrl.searchParams.get("query");
|
|
1046
|
+
if (q && looksLikeGraphqlOperationText(q)) {
|
|
1047
|
+
const opName = parsedUrl.searchParams.get("operationName") || undefined;
|
|
1048
|
+
let variables;
|
|
1049
|
+
const rawVars = parsedUrl.searchParams.get("variables");
|
|
1050
|
+
if (rawVars) {
|
|
1051
|
+
try {
|
|
1052
|
+
const parsedVars = JSON.parse(rawVars);
|
|
1053
|
+
if (isRecord(parsedVars))
|
|
1054
|
+
variables = parsedVars;
|
|
1055
|
+
}
|
|
1056
|
+
catch {
|
|
1057
|
+
// ignore
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
return {
|
|
1061
|
+
query: q.trim(),
|
|
1062
|
+
...(opName ? { operationName: opName } : {}),
|
|
1063
|
+
...(variables ? { variables } : {})
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
catch {
|
|
1068
|
+
// ignore URL parse error
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
return null;
|
|
1073
|
+
}
|
|
1074
|
+
function inferTypeFromConcreteValue(value, builder, contextName, mode, depth, activeObjects, fieldNameHint) {
|
|
1075
|
+
if (depth > MAX_SCHEMA_DEPTH) {
|
|
1076
|
+
builder.addWarning(`Schema exceeded maximum nesting depth (${MAX_SCHEMA_DEPTH}); deeper nodes were flattened to String.`);
|
|
1077
|
+
return namedType("String");
|
|
1078
|
+
}
|
|
1079
|
+
if (value === null || value === undefined) {
|
|
1080
|
+
return namedType("String");
|
|
1081
|
+
}
|
|
1082
|
+
if (typeof value === "boolean") {
|
|
1083
|
+
return namedType("Boolean");
|
|
1084
|
+
}
|
|
1085
|
+
if (typeof value === "number") {
|
|
1086
|
+
return namedType(Number.isInteger(value) ? "Int" : "Float");
|
|
1087
|
+
}
|
|
1088
|
+
if (typeof value === "string") {
|
|
1089
|
+
if (fieldNameHint && isIdLikeFieldName(fieldNameHint) && !isSecretFieldName(fieldNameHint)) {
|
|
1090
|
+
return namedType("ID");
|
|
1091
|
+
}
|
|
1092
|
+
return namedType("String");
|
|
1093
|
+
}
|
|
1094
|
+
if (Array.isArray(value)) {
|
|
1095
|
+
if (activeObjects.has(value)) {
|
|
1096
|
+
builder.addWarning("Circular schema reference detected; cycle was broken safely.");
|
|
1097
|
+
return listOf(namedType("String"));
|
|
1098
|
+
}
|
|
1099
|
+
activeObjects.add(value);
|
|
1100
|
+
try {
|
|
1101
|
+
const firstNonNull = value.find((item) => item !== null && item !== undefined);
|
|
1102
|
+
if (firstNonNull === undefined) {
|
|
1103
|
+
return listOf(namedType("String"));
|
|
1104
|
+
}
|
|
1105
|
+
const elemType = inferTypeFromConcreteValue(firstNonNull, builder, `${contextName}Item`, mode, depth + 1, activeObjects);
|
|
1106
|
+
const hasNull = value.some((item) => item === null);
|
|
1107
|
+
return listOf(hasNull ? elemType : nonNull(elemType));
|
|
1108
|
+
}
|
|
1109
|
+
finally {
|
|
1110
|
+
activeObjects.delete(value);
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
if (isRecord(value)) {
|
|
1114
|
+
if (activeObjects.has(value)) {
|
|
1115
|
+
builder.addWarning("Circular schema reference detected; cycle was broken safely.");
|
|
1116
|
+
return namedType("String");
|
|
1117
|
+
}
|
|
1118
|
+
activeObjects.add(value);
|
|
1119
|
+
try {
|
|
1120
|
+
const entries = Object.entries(value).filter(([k]) => !isForbiddenKey(k) && !k.startsWith("__"));
|
|
1121
|
+
if (entries.length === 0) {
|
|
1122
|
+
return mode === "output" ? builder.ensureJsonScalar() : namedType("String");
|
|
1123
|
+
}
|
|
1124
|
+
const usedFieldNames = new Set();
|
|
1125
|
+
const makeUniqueFieldName = (rawKey) => {
|
|
1126
|
+
const base = sanitizeFieldIdentifier(rawKey, "field");
|
|
1127
|
+
let name = base;
|
|
1128
|
+
let n = 2;
|
|
1129
|
+
while (usedFieldNames.has(name)) {
|
|
1130
|
+
name = `${base}${n}`;
|
|
1131
|
+
n += 1;
|
|
1132
|
+
}
|
|
1133
|
+
usedFieldNames.add(name);
|
|
1134
|
+
return name;
|
|
1135
|
+
};
|
|
1136
|
+
if (mode === "input") {
|
|
1137
|
+
const inputFields = [];
|
|
1138
|
+
for (const [rawKey, rawVal] of entries.slice(0, MAX_OBJECT_FIELDS)) {
|
|
1139
|
+
const fieldName = makeUniqueFieldName(rawKey);
|
|
1140
|
+
const secret = isSecretFieldName(rawKey) || isSecretFieldName(fieldName);
|
|
1141
|
+
const fieldType = secret
|
|
1142
|
+
? namedType("String")
|
|
1143
|
+
: inferTypeFromConcreteValue(rawVal, builder, `${contextName}${toPascalCase(fieldName, "Field")}`, "input", depth + 1, activeObjects, fieldName);
|
|
1144
|
+
inputFields.push({
|
|
1145
|
+
name: fieldName,
|
|
1146
|
+
type: rawVal === null || rawVal === undefined ? fieldType : nonNull(fieldType)
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
const typeName = builder.registerNamedType(contextName.endsWith("Input") ? contextName : `${contextName}Input`, { kind: "INPUT_OBJECT", inputFields });
|
|
1150
|
+
return namedType(typeName);
|
|
1151
|
+
}
|
|
1152
|
+
const fields = [];
|
|
1153
|
+
for (const [rawKey, rawVal] of entries.slice(0, MAX_OBJECT_FIELDS)) {
|
|
1154
|
+
const fieldName = makeUniqueFieldName(rawKey);
|
|
1155
|
+
const secret = isSecretFieldName(rawKey) || isSecretFieldName(fieldName);
|
|
1156
|
+
const fieldType = secret
|
|
1157
|
+
? namedType("String")
|
|
1158
|
+
: inferTypeFromConcreteValue(rawVal, builder, `${contextName}${toPascalCase(fieldName, "Field")}`, "output", depth + 1, activeObjects, fieldName);
|
|
1159
|
+
fields.push({
|
|
1160
|
+
name: fieldName,
|
|
1161
|
+
args: [],
|
|
1162
|
+
type: rawVal === null || rawVal === undefined ? fieldType : nonNull(fieldType)
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
const typeName = builder.registerNamedType(contextName, {
|
|
1166
|
+
kind: "OBJECT",
|
|
1167
|
+
fields
|
|
1168
|
+
});
|
|
1169
|
+
return namedType(typeName);
|
|
1170
|
+
}
|
|
1171
|
+
finally {
|
|
1172
|
+
activeObjects.delete(value);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
return namedType("String");
|
|
1176
|
+
}
|
|
1177
|
+
function inferTypeFromLiteralAst(ast, builder, contextName, variables, runtimeVariables, depth, fieldNameHint) {
|
|
1178
|
+
if (depth > MAX_SCHEMA_DEPTH) {
|
|
1179
|
+
builder.addWarning(`Schema exceeded maximum nesting depth (${MAX_SCHEMA_DEPTH}); deeper nodes were flattened to String.`);
|
|
1180
|
+
return namedType("String");
|
|
1181
|
+
}
|
|
1182
|
+
switch (ast.kind) {
|
|
1183
|
+
case "VARIABLE": {
|
|
1184
|
+
const declared = variables.get(ast.name);
|
|
1185
|
+
if (declared) {
|
|
1186
|
+
return ensureReferencedInputTypeDefined(declared, ast.name, runtimeVariables, builder);
|
|
1187
|
+
}
|
|
1188
|
+
if (runtimeVariables && !isForbiddenKey(ast.name) && hasOwn(runtimeVariables, ast.name)) {
|
|
1189
|
+
const inferred = inferTypeFromConcreteValue(runtimeVariables[ast.name], builder, `${contextName}${toPascalCase(ast.name, "Input")}`, "input", depth + 1, new Set(), ast.name);
|
|
1190
|
+
return nonNull(inferred);
|
|
1191
|
+
}
|
|
1192
|
+
return nonNull(namedType(fieldNameHint && isIdLikeFieldName(fieldNameHint) ? "ID" : "String"));
|
|
1193
|
+
}
|
|
1194
|
+
case "INT":
|
|
1195
|
+
return nonNull(namedType("Int"));
|
|
1196
|
+
case "FLOAT":
|
|
1197
|
+
return nonNull(namedType("Float"));
|
|
1198
|
+
case "BOOLEAN":
|
|
1199
|
+
return nonNull(namedType("Boolean"));
|
|
1200
|
+
case "STRING":
|
|
1201
|
+
return nonNull(namedType(fieldNameHint && isIdLikeFieldName(fieldNameHint) && !isSecretFieldName(fieldNameHint)
|
|
1202
|
+
? "ID"
|
|
1203
|
+
: "String"));
|
|
1204
|
+
case "ENUM": {
|
|
1205
|
+
if (fieldNameHint && isSecretFieldName(fieldNameHint)) {
|
|
1206
|
+
return nonNull(namedType("String"));
|
|
1207
|
+
}
|
|
1208
|
+
const validVal = sanitizeEnumValueIdentifier(ast.value);
|
|
1209
|
+
if (validVal) {
|
|
1210
|
+
const enumName = builder.registerNamedType(`${contextName}Enum`, {
|
|
1211
|
+
kind: "ENUM",
|
|
1212
|
+
enumValues: [validVal]
|
|
1213
|
+
});
|
|
1214
|
+
return nonNull(namedType(enumName));
|
|
1215
|
+
}
|
|
1216
|
+
return nonNull(namedType("String"));
|
|
1217
|
+
}
|
|
1218
|
+
case "NULL":
|
|
1219
|
+
return namedType("String");
|
|
1220
|
+
case "LIST": {
|
|
1221
|
+
const first = ast.values.find((v) => v.kind !== "NULL");
|
|
1222
|
+
if (!first)
|
|
1223
|
+
return nonNull(listOf(namedType("String")));
|
|
1224
|
+
const elem = inferTypeFromLiteralAst(first, builder, `${contextName}Item`, variables, runtimeVariables, depth + 1);
|
|
1225
|
+
return nonNull(listOf(elem));
|
|
1226
|
+
}
|
|
1227
|
+
case "OBJECT": {
|
|
1228
|
+
if (ast.fields.length === 0) {
|
|
1229
|
+
return nonNull(namedType("String"));
|
|
1230
|
+
}
|
|
1231
|
+
const usedFieldNames = new Set();
|
|
1232
|
+
const inputFields = [];
|
|
1233
|
+
for (const f of ast.fields.slice(0, MAX_OBJECT_FIELDS)) {
|
|
1234
|
+
if (isForbiddenKey(f.name) || f.name.startsWith("__"))
|
|
1235
|
+
continue;
|
|
1236
|
+
const base = sanitizeFieldIdentifier(f.name, "field");
|
|
1237
|
+
let name = base;
|
|
1238
|
+
let n = 2;
|
|
1239
|
+
while (usedFieldNames.has(name)) {
|
|
1240
|
+
name = `${base}${n}`;
|
|
1241
|
+
n += 1;
|
|
1242
|
+
}
|
|
1243
|
+
usedFieldNames.add(name);
|
|
1244
|
+
const secret = isSecretFieldName(f.name) || isSecretFieldName(name);
|
|
1245
|
+
const fieldType = secret
|
|
1246
|
+
? nonNull(namedType("String"))
|
|
1247
|
+
: inferTypeFromLiteralAst(f.value, builder, `${contextName}${toPascalCase(name, "Field")}`, variables, runtimeVariables, depth + 1, name);
|
|
1248
|
+
inputFields.push({ name, type: fieldType });
|
|
1249
|
+
}
|
|
1250
|
+
if (inputFields.length === 0) {
|
|
1251
|
+
return nonNull(namedType("String"));
|
|
1252
|
+
}
|
|
1253
|
+
const inputName = builder.registerNamedType(contextName.endsWith("Input") ? contextName : `${contextName}Input`, { kind: "INPUT_OBJECT", inputFields });
|
|
1254
|
+
return nonNull(namedType(inputName));
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
function replaceNamedTypeName(ref, nextName) {
|
|
1259
|
+
if (ref.kind === "NAMED")
|
|
1260
|
+
return { kind: "NAMED", name: nextName };
|
|
1261
|
+
return {
|
|
1262
|
+
kind: ref.kind,
|
|
1263
|
+
...(ref.ofType ? { ofType: replaceNamedTypeName(ref.ofType, nextName) } : {})
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
function ensureReferencedInputTypeDefined(ref, varName, runtimeVariables, builder) {
|
|
1267
|
+
const typeName = unwrapNamedTypeName(ref);
|
|
1268
|
+
if (BUILTIN_SCALARS.has(typeName))
|
|
1269
|
+
return ref;
|
|
1270
|
+
const existingType = builder.types.get(typeName);
|
|
1271
|
+
if (existingType && existingType.kind !== "OBJECT")
|
|
1272
|
+
return ref;
|
|
1273
|
+
let targetTypeName = typeName;
|
|
1274
|
+
if (existingType?.kind === "OBJECT") {
|
|
1275
|
+
const candidateInput = `${typeName}Input`;
|
|
1276
|
+
const existingInput = builder.types.get(candidateInput);
|
|
1277
|
+
if (existingInput && existingInput.kind !== "OBJECT") {
|
|
1278
|
+
return replaceNamedTypeName(ref, candidateInput);
|
|
1279
|
+
}
|
|
1280
|
+
targetTypeName = candidateInput;
|
|
1281
|
+
}
|
|
1282
|
+
let sampleVal;
|
|
1283
|
+
if (runtimeVariables && !isForbiddenKey(varName) && hasOwn(runtimeVariables, varName)) {
|
|
1284
|
+
sampleVal = runtimeVariables[varName];
|
|
1285
|
+
if (Array.isArray(sampleVal)) {
|
|
1286
|
+
sampleVal = sampleVal.find((item) => item !== null && item !== undefined);
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
if (isRecord(sampleVal)) {
|
|
1290
|
+
const entries = Object.entries(sampleVal).filter(([k]) => !isForbiddenKey(k) && !k.startsWith("__"));
|
|
1291
|
+
const inputFields = [];
|
|
1292
|
+
const used = new Set();
|
|
1293
|
+
for (const [k, v] of entries.slice(0, MAX_OBJECT_FIELDS)) {
|
|
1294
|
+
const base = sanitizeFieldIdentifier(k, "field");
|
|
1295
|
+
let fieldName = base;
|
|
1296
|
+
let n = 2;
|
|
1297
|
+
while (used.has(fieldName)) {
|
|
1298
|
+
fieldName = `${base}${n}`;
|
|
1299
|
+
n += 1;
|
|
1300
|
+
}
|
|
1301
|
+
used.add(fieldName);
|
|
1302
|
+
const secret = isSecretFieldName(k) || isSecretFieldName(fieldName);
|
|
1303
|
+
const ft = secret
|
|
1304
|
+
? namedType("String")
|
|
1305
|
+
: inferTypeFromConcreteValue(v, builder, `${targetTypeName}${toPascalCase(fieldName, "Field")}`, "input", 1, new Set([sampleVal]), fieldName);
|
|
1306
|
+
inputFields.push({
|
|
1307
|
+
name: fieldName,
|
|
1308
|
+
type: v === null || v === undefined ? ft : nonNull(ft)
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
if (inputFields.length > 0) {
|
|
1312
|
+
const registeredName = builder.registerExplicitType(targetTypeName, {
|
|
1313
|
+
kind: "INPUT_OBJECT",
|
|
1314
|
+
name: targetTypeName,
|
|
1315
|
+
inputFields
|
|
1316
|
+
});
|
|
1317
|
+
return registeredName === typeName ? ref : replaceNamedTypeName(ref, registeredName);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
// Fallback definition so SDL & Introspection never reference an undefined type.
|
|
1321
|
+
if (existingType?.kind === "OBJECT" || /(?:Input|Filter|Params|Args|Payload)$/i.test(targetTypeName)) {
|
|
1322
|
+
const registeredName = builder.registerExplicitType(targetTypeName, {
|
|
1323
|
+
kind: "INPUT_OBJECT",
|
|
1324
|
+
name: targetTypeName,
|
|
1325
|
+
inputFields: [{ name: "value", type: namedType("String") }]
|
|
1326
|
+
});
|
|
1327
|
+
return registeredName === typeName ? ref : replaceNamedTypeName(ref, registeredName);
|
|
1328
|
+
}
|
|
1329
|
+
const registeredName = builder.registerExplicitType(targetTypeName, {
|
|
1330
|
+
kind: "SCALAR",
|
|
1331
|
+
name: targetTypeName
|
|
1332
|
+
});
|
|
1333
|
+
return registeredName === typeName ? ref : replaceNamedTypeName(ref, registeredName);
|
|
1334
|
+
}
|
|
1335
|
+
function mergeAllOfSchemas(schemas, activeSchemas, depth, builder) {
|
|
1336
|
+
const properties = Object.create(null);
|
|
1337
|
+
const required = new Set();
|
|
1338
|
+
let nullable = false;
|
|
1339
|
+
for (const sub of schemas) {
|
|
1340
|
+
if (!isRecord(sub))
|
|
1341
|
+
continue;
|
|
1342
|
+
if (activeSchemas.has(sub)) {
|
|
1343
|
+
builder.addWarning("Circular schema reference detected; cycle was broken safely.");
|
|
1344
|
+
continue;
|
|
1345
|
+
}
|
|
1346
|
+
if (depth > MAX_SCHEMA_DEPTH) {
|
|
1347
|
+
builder.addWarning(`Schema exceeded maximum nesting depth (${MAX_SCHEMA_DEPTH}); deeper nodes were flattened to String.`);
|
|
1348
|
+
break;
|
|
1349
|
+
}
|
|
1350
|
+
if (sub.nullable === true)
|
|
1351
|
+
nullable = true;
|
|
1352
|
+
if (Array.isArray(sub.type) && sub.type.includes("null"))
|
|
1353
|
+
nullable = true;
|
|
1354
|
+
if (isRecord(sub.properties)) {
|
|
1355
|
+
for (const [k, v] of Object.entries(sub.properties)) {
|
|
1356
|
+
if (isForbiddenKey(k) || k.startsWith("__") || !isRecord(v))
|
|
1357
|
+
continue;
|
|
1358
|
+
properties[k] = v;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
if (Array.isArray(sub.required)) {
|
|
1362
|
+
for (const r of sub.required) {
|
|
1363
|
+
if (typeof r === "string" && !isForbiddenKey(r) && !r.startsWith("__")) {
|
|
1364
|
+
required.add(r);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
return {
|
|
1370
|
+
type: nullable ? ["object", "null"] : "object",
|
|
1371
|
+
properties,
|
|
1372
|
+
...(required.size > 0 ? { required: [...required] } : {})
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
function extractSchemaTypes(schema) {
|
|
1376
|
+
let isNullable = schema.nullable === true;
|
|
1377
|
+
const primaryTypes = [];
|
|
1378
|
+
if (typeof schema.type === "string") {
|
|
1379
|
+
if (schema.type === "null")
|
|
1380
|
+
isNullable = true;
|
|
1381
|
+
else
|
|
1382
|
+
primaryTypes.push(schema.type);
|
|
1383
|
+
}
|
|
1384
|
+
else if (Array.isArray(schema.type)) {
|
|
1385
|
+
for (const t of schema.type) {
|
|
1386
|
+
if (t === "null")
|
|
1387
|
+
isNullable = true;
|
|
1388
|
+
else if (typeof t === "string")
|
|
1389
|
+
primaryTypes.push(t);
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
if (Array.isArray(schema.enum) && schema.enum.includes(null)) {
|
|
1393
|
+
isNullable = true;
|
|
1394
|
+
}
|
|
1395
|
+
return { primaryTypes, isNullable };
|
|
1396
|
+
}
|
|
1397
|
+
function convertJsonSchemaToTypeRef(rawSchema, builder, contextName, mode, depth, activeSchemas, options = {}) {
|
|
1398
|
+
if (!isRecord(rawSchema)) {
|
|
1399
|
+
const base = namedType("String");
|
|
1400
|
+
return options.requireNonNull ? nonNull(base) : base;
|
|
1401
|
+
}
|
|
1402
|
+
if (activeSchemas.has(rawSchema)) {
|
|
1403
|
+
builder.addWarning("Circular schema reference detected; cycle was broken safely.");
|
|
1404
|
+
const base = namedType("String");
|
|
1405
|
+
return options.requireNonNull ? nonNull(base) : base;
|
|
1406
|
+
}
|
|
1407
|
+
if (depth > MAX_SCHEMA_DEPTH) {
|
|
1408
|
+
builder.addWarning(`Schema exceeded maximum nesting depth (${MAX_SCHEMA_DEPTH}); deeper nodes were flattened to String.`);
|
|
1409
|
+
const base = namedType("String");
|
|
1410
|
+
return options.requireNonNull ? nonNull(base) : base;
|
|
1411
|
+
}
|
|
1412
|
+
const schema = rawSchema;
|
|
1413
|
+
const isSecret = options.isSecretField === true;
|
|
1414
|
+
activeSchemas.add(rawSchema);
|
|
1415
|
+
try {
|
|
1416
|
+
// Handle anyOf / oneOf with nullability unwrapping
|
|
1417
|
+
const unionBranches = Array.isArray(schema.anyOf)
|
|
1418
|
+
? schema.anyOf
|
|
1419
|
+
: Array.isArray(schema.oneOf)
|
|
1420
|
+
? schema.oneOf
|
|
1421
|
+
: null;
|
|
1422
|
+
if (unionBranches && unionBranches.length > 0) {
|
|
1423
|
+
let hasNullBranch = schema.nullable === true;
|
|
1424
|
+
const nonNullBranches = [];
|
|
1425
|
+
for (const branch of unionBranches) {
|
|
1426
|
+
if (!isRecord(branch))
|
|
1427
|
+
continue;
|
|
1428
|
+
if (branch.type === "null") {
|
|
1429
|
+
hasNullBranch = true;
|
|
1430
|
+
}
|
|
1431
|
+
else {
|
|
1432
|
+
nonNullBranches.push(branch);
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
if (nonNullBranches.length === 1) {
|
|
1436
|
+
const inner = convertJsonSchemaToTypeRef(nonNullBranches[0], builder, contextName, mode, depth + 1, activeSchemas, {
|
|
1437
|
+
...options,
|
|
1438
|
+
requireNonNull: options.requireNonNull === true && !hasNullBranch
|
|
1439
|
+
});
|
|
1440
|
+
return hasNullBranch ? unwrapNullable(inner) : inner;
|
|
1441
|
+
}
|
|
1442
|
+
if (nonNullBranches.length > 1) {
|
|
1443
|
+
const preferred = nonNullBranches.find((b) => b.type === "object" || isRecord(b.properties)) ||
|
|
1444
|
+
nonNullBranches[0];
|
|
1445
|
+
const inner = convertJsonSchemaToTypeRef(preferred, builder, contextName, mode, depth + 1, activeSchemas, {
|
|
1446
|
+
...options,
|
|
1447
|
+
requireNonNull: options.requireNonNull === true && !hasNullBranch
|
|
1448
|
+
});
|
|
1449
|
+
return hasNullBranch ? unwrapNullable(inner) : inner;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
// Handle allOf object composition
|
|
1453
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
|
|
1454
|
+
const merged = mergeAllOfSchemas(schema.allOf, activeSchemas, depth + 1, builder);
|
|
1455
|
+
return convertJsonSchemaToTypeRef(merged, builder, contextName, mode, depth + 1, activeSchemas, options);
|
|
1456
|
+
}
|
|
1457
|
+
const { primaryTypes, isNullable } = extractSchemaTypes(schema);
|
|
1458
|
+
const shouldBeNonNull = options.requireNonNull === true && !isNullable;
|
|
1459
|
+
// Secret fields: never emit enum values, defaults, examples, or descriptions
|
|
1460
|
+
if (isSecret) {
|
|
1461
|
+
const scalar = primaryTypes[0] === "integer"
|
|
1462
|
+
? "Int"
|
|
1463
|
+
: primaryTypes[0] === "number"
|
|
1464
|
+
? "Float"
|
|
1465
|
+
: primaryTypes[0] === "boolean"
|
|
1466
|
+
? "Boolean"
|
|
1467
|
+
: "String";
|
|
1468
|
+
const ref = namedType(scalar);
|
|
1469
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1470
|
+
}
|
|
1471
|
+
// Determine effective primary type
|
|
1472
|
+
let primaryType = primaryTypes[0];
|
|
1473
|
+
if (!primaryType) {
|
|
1474
|
+
if (isRecord(schema.properties))
|
|
1475
|
+
primaryType = "object";
|
|
1476
|
+
else if (schema.items !== undefined)
|
|
1477
|
+
primaryType = "array";
|
|
1478
|
+
else if (Array.isArray(schema.enum)) {
|
|
1479
|
+
const firstVal = schema.enum.find((v) => v !== null && v !== undefined);
|
|
1480
|
+
if (typeof firstVal === "string")
|
|
1481
|
+
primaryType = "string";
|
|
1482
|
+
else if (typeof firstVal === "number")
|
|
1483
|
+
primaryType = Number.isInteger(firstVal) ? "integer" : "number";
|
|
1484
|
+
else if (typeof firstVal === "boolean")
|
|
1485
|
+
primaryType = "boolean";
|
|
1486
|
+
}
|
|
1487
|
+
else if (schema.const !== undefined && schema.const !== null) {
|
|
1488
|
+
if (typeof schema.const === "string")
|
|
1489
|
+
primaryType = "string";
|
|
1490
|
+
else if (typeof schema.const === "number")
|
|
1491
|
+
primaryType = Number.isInteger(schema.const) ? "integer" : "number";
|
|
1492
|
+
else if (typeof schema.const === "boolean")
|
|
1493
|
+
primaryType = "boolean";
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
// Enum on string schema
|
|
1497
|
+
if (primaryType === "string" && Array.isArray(schema.enum)) {
|
|
1498
|
+
const rawNonNull = schema.enum.filter((v) => typeof v === "string");
|
|
1499
|
+
if (rawNonNull.length > 0 && rawNonNull.length <= MAX_ENUM_VALUES) {
|
|
1500
|
+
const enumValues = [];
|
|
1501
|
+
const seen = new Set();
|
|
1502
|
+
let allValid = true;
|
|
1503
|
+
for (const item of rawNonNull) {
|
|
1504
|
+
const validIdent = sanitizeEnumValueIdentifier(item);
|
|
1505
|
+
if (!validIdent) {
|
|
1506
|
+
allValid = false;
|
|
1507
|
+
break;
|
|
1508
|
+
}
|
|
1509
|
+
if (!seen.has(validIdent)) {
|
|
1510
|
+
seen.add(validIdent);
|
|
1511
|
+
enumValues.push(validIdent);
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
if (allValid && enumValues.length > 0) {
|
|
1515
|
+
const preferredEnumName = typeof schema.title === "string" && schema.title.trim()
|
|
1516
|
+
? schema.title.trim()
|
|
1517
|
+
: contextName;
|
|
1518
|
+
const enumName = builder.registerNamedType(preferredEnumName, {
|
|
1519
|
+
kind: "ENUM",
|
|
1520
|
+
enumValues,
|
|
1521
|
+
...(sanitizeDescription(schema.description)
|
|
1522
|
+
? { description: sanitizeDescription(schema.description) }
|
|
1523
|
+
: {})
|
|
1524
|
+
});
|
|
1525
|
+
const ref = namedType(enumName);
|
|
1526
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
if (primaryType === "integer") {
|
|
1531
|
+
const ref = namedType("Int");
|
|
1532
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1533
|
+
}
|
|
1534
|
+
if (primaryType === "number") {
|
|
1535
|
+
const ref = namedType("Float");
|
|
1536
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1537
|
+
}
|
|
1538
|
+
if (primaryType === "boolean") {
|
|
1539
|
+
const ref = namedType("Boolean");
|
|
1540
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1541
|
+
}
|
|
1542
|
+
if (primaryType === "string") {
|
|
1543
|
+
const isId = schema.format === "uuid" ||
|
|
1544
|
+
(options.fieldNameHint !== undefined && isIdLikeFieldName(options.fieldNameHint));
|
|
1545
|
+
const ref = namedType(isId ? "ID" : "String");
|
|
1546
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1547
|
+
}
|
|
1548
|
+
if (primaryType === "array") {
|
|
1549
|
+
const itemSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;
|
|
1550
|
+
const itemRef = itemSchema
|
|
1551
|
+
? convertJsonSchemaToTypeRef(itemSchema, builder, `${contextName}Item`, mode, depth + 1, activeSchemas, {
|
|
1552
|
+
selectionChildren: options.selectionChildren,
|
|
1553
|
+
requireNonNull: true
|
|
1554
|
+
})
|
|
1555
|
+
: nonNull(namedType("String"));
|
|
1556
|
+
const listRef = listOf(itemRef);
|
|
1557
|
+
return shouldBeNonNull ? nonNull(listRef) : listRef;
|
|
1558
|
+
}
|
|
1559
|
+
if (primaryType === "object") {
|
|
1560
|
+
const rawProps = isRecord(schema.properties) ? schema.properties : {};
|
|
1561
|
+
const requiredSet = new Set(Array.isArray(schema.required)
|
|
1562
|
+
? schema.required.filter((r) => typeof r === "string")
|
|
1563
|
+
: []);
|
|
1564
|
+
const propEntries = Object.entries(rawProps).filter(([k]) => !isForbiddenKey(k) && !k.startsWith("__"));
|
|
1565
|
+
// Build selection lookup if we also have GraphQL selection children
|
|
1566
|
+
const selectionByName = new Map();
|
|
1567
|
+
if (options.selectionChildren) {
|
|
1568
|
+
for (const child of options.selectionChildren) {
|
|
1569
|
+
if (!isForbiddenKey(child.name) && !child.name.startsWith("__")) {
|
|
1570
|
+
selectionByName.set(child.alias || child.name, child);
|
|
1571
|
+
selectionByName.set(child.name, child);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
if (propEntries.length === 0) {
|
|
1576
|
+
// Fallback to selection children if present
|
|
1577
|
+
if (options.selectionChildren && options.selectionChildren.length > 0 && mode === "output") {
|
|
1578
|
+
const selRef = inferObjectFromSelections(options.selectionChildren, builder, contextName, depth + 1);
|
|
1579
|
+
if (selRef) {
|
|
1580
|
+
return shouldBeNonNull ? nonNull(selRef) : selRef;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
const scalarFallback = mode === "output" ? builder.ensureJsonScalar() : namedType("String");
|
|
1584
|
+
return shouldBeNonNull ? nonNull(scalarFallback) : scalarFallback;
|
|
1585
|
+
}
|
|
1586
|
+
const preferredTypeName = typeof schema.title === "string" && schema.title.trim()
|
|
1587
|
+
? schema.title.trim()
|
|
1588
|
+
: contextName;
|
|
1589
|
+
const typeDesc = sanitizeDescription(schema.description);
|
|
1590
|
+
const usedFieldNames = new Set();
|
|
1591
|
+
const makeUniqueFieldName = (rawKey) => {
|
|
1592
|
+
const base = sanitizeFieldIdentifier(rawKey, "field");
|
|
1593
|
+
let name = base;
|
|
1594
|
+
let n = 2;
|
|
1595
|
+
while (usedFieldNames.has(name)) {
|
|
1596
|
+
name = `${base}${n}`;
|
|
1597
|
+
n += 1;
|
|
1598
|
+
}
|
|
1599
|
+
usedFieldNames.add(name);
|
|
1600
|
+
return name;
|
|
1601
|
+
};
|
|
1602
|
+
if (mode === "input") {
|
|
1603
|
+
const inputFields = [];
|
|
1604
|
+
for (const [rawKey, propSchema] of propEntries.slice(0, MAX_OBJECT_FIELDS)) {
|
|
1605
|
+
const fieldName = makeUniqueFieldName(rawKey);
|
|
1606
|
+
const secretField = isSecretFieldName(rawKey) || isSecretFieldName(fieldName);
|
|
1607
|
+
const isReq = requiredSet.has(rawKey);
|
|
1608
|
+
const fieldType = convertJsonSchemaToTypeRef(propSchema, builder, `${toPascalCase(preferredTypeName, "Input")}${toPascalCase(fieldName, "Field")}`, "input", depth + 1, activeSchemas, {
|
|
1609
|
+
fieldNameHint: fieldName,
|
|
1610
|
+
isSecretField: secretField,
|
|
1611
|
+
requireNonNull: isReq
|
|
1612
|
+
});
|
|
1613
|
+
const fieldDesc = !secretField && isRecord(propSchema)
|
|
1614
|
+
? sanitizeDescription(propSchema.description)
|
|
1615
|
+
: undefined;
|
|
1616
|
+
inputFields.push({
|
|
1617
|
+
name: fieldName,
|
|
1618
|
+
type: fieldType,
|
|
1619
|
+
...(fieldDesc ? { description: fieldDesc } : {})
|
|
1620
|
+
});
|
|
1621
|
+
}
|
|
1622
|
+
const typeName = builder.registerNamedType(preferredTypeName.endsWith("Input") ? preferredTypeName : `${preferredTypeName}Input`, {
|
|
1623
|
+
kind: "INPUT_OBJECT",
|
|
1624
|
+
inputFields,
|
|
1625
|
+
...(typeDesc ? { description: typeDesc } : {})
|
|
1626
|
+
});
|
|
1627
|
+
const ref = namedType(typeName);
|
|
1628
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1629
|
+
}
|
|
1630
|
+
const fields = [];
|
|
1631
|
+
for (const [rawKey, propSchema] of propEntries.slice(0, MAX_OBJECT_FIELDS)) {
|
|
1632
|
+
const fieldName = makeUniqueFieldName(rawKey);
|
|
1633
|
+
const secretField = isSecretFieldName(rawKey) || isSecretFieldName(fieldName);
|
|
1634
|
+
const isReq = requiredSet.has(rawKey);
|
|
1635
|
+
const matchingSel = selectionByName.get(rawKey) || selectionByName.get(fieldName);
|
|
1636
|
+
const fieldType = convertJsonSchemaToTypeRef(propSchema, builder, `${toPascalCase(preferredTypeName, "Type")}${toPascalCase(fieldName, "Field")}`, "output", depth + 1, activeSchemas, {
|
|
1637
|
+
fieldNameHint: fieldName,
|
|
1638
|
+
isSecretField: secretField,
|
|
1639
|
+
selectionChildren: matchingSel?.children,
|
|
1640
|
+
requireNonNull: isReq
|
|
1641
|
+
});
|
|
1642
|
+
const fieldDesc = !secretField && isRecord(propSchema)
|
|
1643
|
+
? sanitizeDescription(propSchema.description)
|
|
1644
|
+
: undefined;
|
|
1645
|
+
fields.push({
|
|
1646
|
+
name: fieldName,
|
|
1647
|
+
args: [],
|
|
1648
|
+
type: fieldType,
|
|
1649
|
+
...(fieldDesc ? { description: fieldDesc } : {})
|
|
1650
|
+
});
|
|
1651
|
+
}
|
|
1652
|
+
const typeName = builder.registerNamedType(preferredTypeName, {
|
|
1653
|
+
kind: "OBJECT",
|
|
1654
|
+
fields,
|
|
1655
|
+
...(typeDesc ? { description: typeDesc } : {})
|
|
1656
|
+
});
|
|
1657
|
+
const ref = namedType(typeName);
|
|
1658
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1659
|
+
}
|
|
1660
|
+
// Multiple non-null scalar types (e.g., custom scalar from ingestGraphql) or unconstrained `{}`
|
|
1661
|
+
if (primaryTypes.length >= 4 || primaryTypes.length === 0) {
|
|
1662
|
+
const ref = mode === "output" ? builder.ensureJsonScalar() : namedType("String");
|
|
1663
|
+
return shouldBeNonNull ? nonNull(ref) : ref;
|
|
1664
|
+
}
|
|
1665
|
+
const fallback = namedType("String");
|
|
1666
|
+
return shouldBeNonNull ? nonNull(fallback) : fallback;
|
|
1667
|
+
}
|
|
1668
|
+
finally {
|
|
1669
|
+
activeSchemas.delete(rawSchema);
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
function inferObjectFromSelections(selections, builder, contextName, depth) {
|
|
1673
|
+
if (depth > MAX_SCHEMA_DEPTH) {
|
|
1674
|
+
builder.addWarning(`Schema exceeded maximum nesting depth (${MAX_SCHEMA_DEPTH}); deeper nodes were flattened to String.`);
|
|
1675
|
+
return namedType("String");
|
|
1676
|
+
}
|
|
1677
|
+
const usable = selections.filter((s) => !isForbiddenKey(s.name) && !s.name.startsWith("__"));
|
|
1678
|
+
if (usable.length === 0)
|
|
1679
|
+
return null;
|
|
1680
|
+
const fields = [];
|
|
1681
|
+
const used = new Set();
|
|
1682
|
+
for (const child of usable.slice(0, MAX_OBJECT_FIELDS)) {
|
|
1683
|
+
const base = sanitizeFieldIdentifier(child.name, "field");
|
|
1684
|
+
let fieldName = base;
|
|
1685
|
+
let n = 2;
|
|
1686
|
+
while (used.has(fieldName)) {
|
|
1687
|
+
fieldName = `${base}${n}`;
|
|
1688
|
+
n += 1;
|
|
1689
|
+
}
|
|
1690
|
+
used.add(fieldName);
|
|
1691
|
+
let fieldType;
|
|
1692
|
+
if (child.children.length > 0) {
|
|
1693
|
+
fieldType =
|
|
1694
|
+
inferObjectFromSelections(child.children, builder, `${contextName}${toPascalCase(fieldName, "Field")}`, depth + 1) || namedType("String");
|
|
1695
|
+
}
|
|
1696
|
+
else if (isIdLikeFieldName(fieldName) && !isSecretFieldName(fieldName)) {
|
|
1697
|
+
fieldType = namedType("ID");
|
|
1698
|
+
}
|
|
1699
|
+
else {
|
|
1700
|
+
fieldType = namedType("String");
|
|
1701
|
+
}
|
|
1702
|
+
fields.push({ name: fieldName, args: [], type: fieldType });
|
|
1703
|
+
}
|
|
1704
|
+
if (fields.length === 0)
|
|
1705
|
+
return null;
|
|
1706
|
+
const typeName = builder.registerNamedType(contextName, {
|
|
1707
|
+
kind: "OBJECT",
|
|
1708
|
+
fields
|
|
1709
|
+
});
|
|
1710
|
+
return namedType(typeName);
|
|
1711
|
+
}
|
|
1712
|
+
function extractGraphqlFieldResponseSchema(inv, responseKey, fieldName) {
|
|
1713
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
1714
|
+
const rootSchema = isRecord(expected.jsonSchema) ? expected.jsonSchema : undefined;
|
|
1715
|
+
if (!rootSchema || !isRecord(rootSchema.properties))
|
|
1716
|
+
return undefined;
|
|
1717
|
+
if (hasOwn(rootSchema.properties, "data") && isRecord(rootSchema.properties.data)) {
|
|
1718
|
+
const dataSchema = rootSchema.properties.data;
|
|
1719
|
+
if (isRecord(dataSchema.properties)) {
|
|
1720
|
+
if (!isForbiddenKey(responseKey) && hasOwn(dataSchema.properties, responseKey)) {
|
|
1721
|
+
return dataSchema.properties[responseKey];
|
|
1722
|
+
}
|
|
1723
|
+
if (!isForbiddenKey(fieldName) && hasOwn(dataSchema.properties, fieldName)) {
|
|
1724
|
+
return dataSchema.properties[fieldName];
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
if (!isForbiddenKey(responseKey) && hasOwn(rootSchema.properties, responseKey)) {
|
|
1729
|
+
return rootSchema.properties[responseKey];
|
|
1730
|
+
}
|
|
1731
|
+
return undefined;
|
|
1732
|
+
}
|
|
1733
|
+
function extractGraphqlFieldResponseSubset(inv, responseKey, fieldName) {
|
|
1734
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
1735
|
+
const subset = expected.jsonSubset;
|
|
1736
|
+
if (!isRecord(subset))
|
|
1737
|
+
return undefined;
|
|
1738
|
+
if (hasOwn(subset, "data") && isRecord(subset.data)) {
|
|
1739
|
+
const dataObj = subset.data;
|
|
1740
|
+
if (!isForbiddenKey(responseKey) && hasOwn(dataObj, responseKey)) {
|
|
1741
|
+
return dataObj[responseKey];
|
|
1742
|
+
}
|
|
1743
|
+
if (!isForbiddenKey(fieldName) && hasOwn(dataObj, fieldName)) {
|
|
1744
|
+
return dataObj[fieldName];
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
return undefined;
|
|
1748
|
+
}
|
|
1749
|
+
function processNativeGraphqlInvariant(inv, payload, builder) {
|
|
1750
|
+
const parsedOp = parseGraphqlOperationDocument(payload.query, payload.operationName);
|
|
1751
|
+
if (!parsedOp) {
|
|
1752
|
+
builder.addWarning(`Skipped malformed GraphQL operation in invariant ${sanitizeSingleLineText(inv.id || "unknown")}.`);
|
|
1753
|
+
return false;
|
|
1754
|
+
}
|
|
1755
|
+
if (parsedOp.operationKind === "subscription") {
|
|
1756
|
+
builder.addWarning(`Skipped GraphQL subscription invariant ${sanitizeSingleLineText(inv.id || "unknown")} (subscriptions are not exported).`);
|
|
1757
|
+
return false;
|
|
1758
|
+
}
|
|
1759
|
+
const rootKind = parsedOp.operationKind;
|
|
1760
|
+
let extractedAny = false;
|
|
1761
|
+
const invDesc = sanitizeDescription(inv.description);
|
|
1762
|
+
for (const sel of parsedOp.selections) {
|
|
1763
|
+
if (isForbiddenKey(sel.name) || sel.name.startsWith("__"))
|
|
1764
|
+
continue;
|
|
1765
|
+
const fieldName = sanitizeFieldIdentifier(sel.name, rootKind === "query" ? "queryField" : "mutationField");
|
|
1766
|
+
const responseKey = sel.alias || sel.name;
|
|
1767
|
+
const typeContext = toPascalCase(fieldName, "Payload");
|
|
1768
|
+
// Extract field arguments (stripping secret defaults/examples/descriptions)
|
|
1769
|
+
const args = [];
|
|
1770
|
+
const seenArgs = new Set();
|
|
1771
|
+
for (const arg of sel.args) {
|
|
1772
|
+
if (isForbiddenKey(arg.name) || arg.name.startsWith("__"))
|
|
1773
|
+
continue;
|
|
1774
|
+
const argName = sanitizeFieldIdentifier(arg.name, "arg");
|
|
1775
|
+
if (seenArgs.has(argName))
|
|
1776
|
+
continue;
|
|
1777
|
+
seenArgs.add(argName);
|
|
1778
|
+
const secretArg = isSecretFieldName(arg.name) || isSecretFieldName(argName);
|
|
1779
|
+
let argType;
|
|
1780
|
+
if (secretArg) {
|
|
1781
|
+
// Preserve variable nullability if declared, otherwise String!
|
|
1782
|
+
const varDecl = arg.value.kind === "VARIABLE" ? parsedOp.variables.get(arg.value.name) : undefined;
|
|
1783
|
+
argType = varDecl && varDecl.kind === "NON_NULL" ? nonNull(namedType("String")) : namedType("String");
|
|
1784
|
+
}
|
|
1785
|
+
else {
|
|
1786
|
+
argType = inferTypeFromLiteralAst(arg.value, builder, `${typeContext}${toPascalCase(argName, "Arg")}`, parsedOp.variables, payload.variables, 0, argName);
|
|
1787
|
+
}
|
|
1788
|
+
args.push({ name: argName, type: argType });
|
|
1789
|
+
}
|
|
1790
|
+
// Extract return type from expected.jsonSchema -> expected.jsonSubset -> query selection set
|
|
1791
|
+
const fieldJsonSchema = extractGraphqlFieldResponseSchema(inv, responseKey, sel.name);
|
|
1792
|
+
const fieldJsonSubset = extractGraphqlFieldResponseSubset(inv, responseKey, sel.name);
|
|
1793
|
+
const secretRoot = isSecretFieldName(sel.name) || isSecretFieldName(fieldName);
|
|
1794
|
+
let returnType;
|
|
1795
|
+
if (fieldJsonSchema) {
|
|
1796
|
+
returnType = convertJsonSchemaToTypeRef(fieldJsonSchema, builder, typeContext, "output", 0, new Set(), {
|
|
1797
|
+
fieldNameHint: fieldName,
|
|
1798
|
+
isSecretField: secretRoot,
|
|
1799
|
+
selectionChildren: sel.children,
|
|
1800
|
+
requireNonNull: true
|
|
1801
|
+
});
|
|
1802
|
+
}
|
|
1803
|
+
else if (fieldJsonSubset !== undefined) {
|
|
1804
|
+
const inferred = inferTypeFromConcreteValue(fieldJsonSubset, builder, typeContext, "output", 0, new Set(), fieldName);
|
|
1805
|
+
returnType = fieldJsonSubset === null ? inferred : nonNull(inferred);
|
|
1806
|
+
}
|
|
1807
|
+
else if (sel.children.length > 0) {
|
|
1808
|
+
returnType =
|
|
1809
|
+
inferObjectFromSelections(sel.children, builder, typeContext, 0) || namedType("String");
|
|
1810
|
+
}
|
|
1811
|
+
else {
|
|
1812
|
+
returnType = namedType(isIdLikeFieldName(fieldName) ? "ID" : "String");
|
|
1813
|
+
}
|
|
1814
|
+
builder.addRootField(rootKind, {
|
|
1815
|
+
name: fieldName,
|
|
1816
|
+
args,
|
|
1817
|
+
type: returnType,
|
|
1818
|
+
...(!secretRoot && invDesc ? { description: invDesc } : {})
|
|
1819
|
+
}, true);
|
|
1820
|
+
extractedAny = true;
|
|
1821
|
+
}
|
|
1822
|
+
return extractedAny;
|
|
1823
|
+
}
|
|
1824
|
+
function parseAndSanitizeRestPath(inv) {
|
|
1825
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
1826
|
+
const rawPath = typeof input.path === "string"
|
|
1827
|
+
? input.path.trim()
|
|
1828
|
+
: typeof input.urlPath === "string"
|
|
1829
|
+
? input.urlPath.trim()
|
|
1830
|
+
: "";
|
|
1831
|
+
if (!rawPath)
|
|
1832
|
+
return null;
|
|
1833
|
+
const cleanedRaw = redactVaultPaths(rawPath.replace(/\0/g, ""))
|
|
1834
|
+
.replace(URL_BASIC_AUTH_RE, "$1")
|
|
1835
|
+
.replace(/#.*$/, "");
|
|
1836
|
+
let pathname = "/";
|
|
1837
|
+
const queryEntries = [];
|
|
1838
|
+
const seenQueryKeys = new Set();
|
|
1839
|
+
try {
|
|
1840
|
+
const fakeUrl = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(cleanedRaw)
|
|
1841
|
+
? new URL(cleanedRaw)
|
|
1842
|
+
: new URL(cleanedRaw.startsWith("/") ? `http://local.invalid${cleanedRaw}` : `http://local.invalid/${cleanedRaw}`);
|
|
1843
|
+
pathname = (fakeUrl.pathname || "/")
|
|
1844
|
+
.replace(/%7b/gi, "{")
|
|
1845
|
+
.replace(/%7d/gi, "}")
|
|
1846
|
+
.replace(/%3c/gi, "<")
|
|
1847
|
+
.replace(/%3e/gi, ">");
|
|
1848
|
+
for (const [k, v] of fakeUrl.searchParams.entries()) {
|
|
1849
|
+
const key = k.trim();
|
|
1850
|
+
if (!key || isForbiddenKey(key) || isSensitiveQueryName(key) || hasAuthSchemeValue(v))
|
|
1851
|
+
continue;
|
|
1852
|
+
if (seenQueryKeys.has(key))
|
|
1853
|
+
continue;
|
|
1854
|
+
seenQueryKeys.add(key);
|
|
1855
|
+
queryEntries.push([key, sanitizeSingleLineText(v)]);
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
catch {
|
|
1859
|
+
const stripped = cleanedRaw.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*/, "") || "/";
|
|
1860
|
+
const qIdx = stripped.indexOf("?");
|
|
1861
|
+
pathname = qIdx >= 0 ? stripped.slice(0, qIdx) : stripped;
|
|
1862
|
+
if (!pathname.startsWith("/"))
|
|
1863
|
+
pathname = `/${pathname}`;
|
|
1864
|
+
}
|
|
1865
|
+
// Merge explicit `input.query` parameters (skipping sensitive & forbidden keys)
|
|
1866
|
+
if (isRecord(input.query)) {
|
|
1867
|
+
for (const [rawKey, rawVal] of Object.entries(input.query)) {
|
|
1868
|
+
const key = rawKey.trim();
|
|
1869
|
+
if (!key || isForbiddenKey(key) || isSensitiveQueryName(key))
|
|
1870
|
+
continue;
|
|
1871
|
+
if (rawVal === undefined || rawVal === null)
|
|
1872
|
+
continue;
|
|
1873
|
+
const valStr = String(rawVal);
|
|
1874
|
+
if (hasAuthSchemeValue(valStr))
|
|
1875
|
+
continue;
|
|
1876
|
+
if (seenQueryKeys.has(key))
|
|
1877
|
+
continue;
|
|
1878
|
+
seenQueryKeys.add(key);
|
|
1879
|
+
queryEntries.push([key, valStr]);
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
// Extract path params like `:id`, `{userId}`, `<slug>`
|
|
1883
|
+
const pathParams = [];
|
|
1884
|
+
const segments = pathname.split("/").filter((seg) => seg.length > 0);
|
|
1885
|
+
for (const seg of segments) {
|
|
1886
|
+
let paramName = null;
|
|
1887
|
+
if (seg.startsWith(":") && seg.length > 1) {
|
|
1888
|
+
paramName = seg.slice(1);
|
|
1889
|
+
}
|
|
1890
|
+
else if (seg.startsWith("{") && seg.endsWith("}") && seg.length > 2) {
|
|
1891
|
+
paramName = seg.slice(1, -1);
|
|
1892
|
+
}
|
|
1893
|
+
else if (seg.startsWith("<") && seg.endsWith(">") && seg.length > 2) {
|
|
1894
|
+
paramName = seg.slice(1, -1);
|
|
1895
|
+
}
|
|
1896
|
+
if (paramName && !isForbiddenKey(paramName) && !isSensitiveQueryName(paramName)) {
|
|
1897
|
+
pathParams.push(paramName);
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
return { pathname, pathParams, queryEntries };
|
|
1901
|
+
}
|
|
1902
|
+
function deriveRestFieldName(method, pathname) {
|
|
1903
|
+
const rawSegments = pathname.split("/").filter((s) => s.length > 0);
|
|
1904
|
+
const staticSegments = [];
|
|
1905
|
+
let trailingParam = null;
|
|
1906
|
+
for (let i = 0; i < rawSegments.length; i += 1) {
|
|
1907
|
+
const seg = rawSegments[i];
|
|
1908
|
+
const isParam = (seg.startsWith(":") && seg.length > 1) ||
|
|
1909
|
+
(seg.startsWith("{") && seg.endsWith("}") && seg.length > 2) ||
|
|
1910
|
+
(seg.startsWith("<") && seg.endsWith(">") && seg.length > 2);
|
|
1911
|
+
if (isParam) {
|
|
1912
|
+
if (i === rawSegments.length - 1) {
|
|
1913
|
+
trailingParam = seg.replace(/^[:{<]+|[}>]+$/g, "");
|
|
1914
|
+
}
|
|
1915
|
+
continue;
|
|
1916
|
+
}
|
|
1917
|
+
staticSegments.push(seg);
|
|
1918
|
+
}
|
|
1919
|
+
// Strip leading `/api` / `/v1` prefixes only if descriptive segments follow
|
|
1920
|
+
const trimmedStatic = staticSegments.slice();
|
|
1921
|
+
while (trimmedStatic.length > 1 &&
|
|
1922
|
+
(/^(?:api|v\d+)$/i.test(trimmedStatic[0]))) {
|
|
1923
|
+
trimmedStatic.shift();
|
|
1924
|
+
}
|
|
1925
|
+
const baseWords = trimmedStatic.length > 0 ? trimmedStatic.join(" ") : "root";
|
|
1926
|
+
const suffix = trailingParam ? ` by ${trailingParam}` : "";
|
|
1927
|
+
const fullPhrase = `${baseWords}${suffix}`;
|
|
1928
|
+
if (method === "GET") {
|
|
1929
|
+
return toCamelCase(fullPhrase, "queryRoot");
|
|
1930
|
+
}
|
|
1931
|
+
if (method === "HEAD") {
|
|
1932
|
+
return toCamelCase(`head ${fullPhrase}`, "headRoot");
|
|
1933
|
+
}
|
|
1934
|
+
if (method === "OPTIONS") {
|
|
1935
|
+
return toCamelCase(`options ${fullPhrase}`, "optionsRoot");
|
|
1936
|
+
}
|
|
1937
|
+
if (method === "POST") {
|
|
1938
|
+
return toCamelCase(`create ${fullPhrase}`, "createRoot");
|
|
1939
|
+
}
|
|
1940
|
+
if (method === "PUT") {
|
|
1941
|
+
return toCamelCase(`update ${fullPhrase}`, "updateRoot");
|
|
1942
|
+
}
|
|
1943
|
+
if (method === "PATCH") {
|
|
1944
|
+
return toCamelCase(`patch ${fullPhrase}`, "patchRoot");
|
|
1945
|
+
}
|
|
1946
|
+
if (method === "DELETE") {
|
|
1947
|
+
return toCamelCase(`delete ${fullPhrase}`, "deleteRoot");
|
|
1948
|
+
}
|
|
1949
|
+
return toCamelCase(`${method.toLowerCase()} ${fullPhrase}`, "operation");
|
|
1950
|
+
}
|
|
1951
|
+
function inferQueryArgType(key, value) {
|
|
1952
|
+
if (typeof value === "boolean")
|
|
1953
|
+
return namedType("Boolean");
|
|
1954
|
+
if (typeof value === "number")
|
|
1955
|
+
return namedType(Number.isInteger(value) ? "Int" : "Float");
|
|
1956
|
+
if (typeof value === "string") {
|
|
1957
|
+
if (value === "true" || value === "false")
|
|
1958
|
+
return namedType("Boolean");
|
|
1959
|
+
if (/^-?\d+$/.test(value) && !isIdLikeFieldName(key))
|
|
1960
|
+
return namedType("Int");
|
|
1961
|
+
if (/^-?\d+\.\d+$/.test(value))
|
|
1962
|
+
return namedType("Float");
|
|
1963
|
+
}
|
|
1964
|
+
return namedType(isIdLikeFieldName(key) ? "ID" : "String");
|
|
1965
|
+
}
|
|
1966
|
+
function processRestFallbackInvariant(inv, builder) {
|
|
1967
|
+
const input = isRecord(inv.input) ? inv.input : {};
|
|
1968
|
+
const method = (typeof input.method === "string" ? input.method : "GET").trim().toUpperCase();
|
|
1969
|
+
if (!SUPPORTED_HTTP_METHODS.has(method)) {
|
|
1970
|
+
return false;
|
|
1971
|
+
}
|
|
1972
|
+
const parsedPath = parseAndSanitizeRestPath(inv);
|
|
1973
|
+
if (!parsedPath)
|
|
1974
|
+
return false;
|
|
1975
|
+
const rootKind = MUTATING_HTTP_METHODS.has(method) ? "mutation" : "query";
|
|
1976
|
+
const fieldName = deriveRestFieldName(method, parsedPath.pathname);
|
|
1977
|
+
const typeContext = toPascalCase(fieldName, "Payload");
|
|
1978
|
+
const args = [];
|
|
1979
|
+
const seenArgs = new Set();
|
|
1980
|
+
// 1. Path parameters -> required scalar args
|
|
1981
|
+
for (const rawParam of parsedPath.pathParams) {
|
|
1982
|
+
const argName = sanitizeFieldIdentifier(toCamelCase(rawParam, "id"), "id");
|
|
1983
|
+
if (seenArgs.has(argName) || isSecretFieldName(rawParam) || isSecretFieldName(argName))
|
|
1984
|
+
continue;
|
|
1985
|
+
seenArgs.add(argName);
|
|
1986
|
+
args.push({
|
|
1987
|
+
name: argName,
|
|
1988
|
+
type: nonNull(namedType(isIdLikeFieldName(argName) ? "ID" : "String"))
|
|
1989
|
+
});
|
|
1990
|
+
}
|
|
1991
|
+
// 2. Query parameters -> nullable scalar args (sensitive keys already stripped)
|
|
1992
|
+
const rawInputQuery = isRecord(input.query) ? input.query : undefined;
|
|
1993
|
+
for (const [rawKey, valStr] of parsedPath.queryEntries) {
|
|
1994
|
+
const argName = sanitizeFieldIdentifier(toCamelCase(rawKey, "param"), "param");
|
|
1995
|
+
if (seenArgs.has(argName) || isSecretFieldName(rawKey) || isSecretFieldName(argName))
|
|
1996
|
+
continue;
|
|
1997
|
+
seenArgs.add(argName);
|
|
1998
|
+
const typedVal = rawInputQuery && !isForbiddenKey(rawKey) && hasOwn(rawInputQuery, rawKey)
|
|
1999
|
+
? rawInputQuery[rawKey]
|
|
2000
|
+
: valStr;
|
|
2001
|
+
args.push({
|
|
2002
|
+
name: argName,
|
|
2003
|
+
type: inferQueryArgType(argName, typedVal)
|
|
2004
|
+
});
|
|
2005
|
+
}
|
|
2006
|
+
// 3. Request body (for mutating methods) -> `input: <OpPascal>Input!`
|
|
2007
|
+
if (MUTATING_HTTP_METHODS.has(method) && input.body !== undefined && input.body !== null) {
|
|
2008
|
+
const parsedBody = parseJsonBody(input.body);
|
|
2009
|
+
if (parsedBody !== undefined && parsedBody !== null) {
|
|
2010
|
+
const bodyType = inferTypeFromConcreteValue(parsedBody, builder, `${typeContext}Input`, "input", 0, new Set());
|
|
2011
|
+
let argName = "input";
|
|
2012
|
+
let n = 2;
|
|
2013
|
+
while (seenArgs.has(argName)) {
|
|
2014
|
+
argName = `input${n}`;
|
|
2015
|
+
n += 1;
|
|
2016
|
+
}
|
|
2017
|
+
seenArgs.add(argName);
|
|
2018
|
+
args.push({
|
|
2019
|
+
name: argName,
|
|
2020
|
+
type: nonNull(bodyType)
|
|
2021
|
+
});
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
// 4. Response return type from expected.jsonSchema -> expected.jsonSubset -> expected.bodyExact
|
|
2025
|
+
const expected = isRecord(inv.expected) ? inv.expected : {};
|
|
2026
|
+
let returnType;
|
|
2027
|
+
if (isRecord(expected.jsonSchema)) {
|
|
2028
|
+
returnType = convertJsonSchemaToTypeRef(expected.jsonSchema, builder, `${typeContext}Response`, "output", 0, new Set(), { requireNonNull: true });
|
|
2029
|
+
}
|
|
2030
|
+
else if (expected.jsonSubset !== undefined) {
|
|
2031
|
+
const inferred = inferTypeFromConcreteValue(expected.jsonSubset, builder, `${typeContext}Response`, "output", 0, new Set());
|
|
2032
|
+
returnType = expected.jsonSubset === null ? inferred : nonNull(inferred);
|
|
2033
|
+
}
|
|
2034
|
+
else if (typeof expected.bodyExact === "string" && expected.bodyExact.trim()) {
|
|
2035
|
+
const parsedExact = parseJsonBody(expected.bodyExact);
|
|
2036
|
+
if (typeof parsedExact === "string") {
|
|
2037
|
+
returnType = nonNull(namedType("String"));
|
|
2038
|
+
}
|
|
2039
|
+
else {
|
|
2040
|
+
const inferred = inferTypeFromConcreteValue(parsedExact, builder, `${typeContext}Response`, "output", 0, new Set());
|
|
2041
|
+
returnType = parsedExact === null ? inferred : nonNull(inferred);
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
else {
|
|
2045
|
+
const status = Array.isArray(expected.status) ? expected.status[0] : expected.status;
|
|
2046
|
+
returnType = status === 204 ? nonNull(namedType("Boolean")) : namedType("String");
|
|
2047
|
+
}
|
|
2048
|
+
const invDesc = sanitizeDescription(inv.description);
|
|
2049
|
+
builder.addRootField(rootKind, {
|
|
2050
|
+
name: fieldName,
|
|
2051
|
+
args,
|
|
2052
|
+
type: returnType,
|
|
2053
|
+
...(invDesc ? { description: invDesc } : {})
|
|
2054
|
+
}, false);
|
|
2055
|
+
return true;
|
|
2056
|
+
}
|
|
2057
|
+
function renderSdl(builder, title, skippedIds, includeSkippedComments, hasPlaceholderQuery) {
|
|
2058
|
+
const blocks = [];
|
|
2059
|
+
const headerLines = [
|
|
2060
|
+
"# GraphQL SDL exported by vibecode-anything",
|
|
2061
|
+
`# Title: ${sanitizeSingleLineText(title)}`
|
|
2062
|
+
];
|
|
2063
|
+
if (includeSkippedComments && skippedIds.length > 0) {
|
|
2064
|
+
const safeIds = skippedIds.map((id) => sanitizeSingleLineText(id)).filter(Boolean);
|
|
2065
|
+
headerLines.push(`# Skipped ${skippedIds.length} non-exported ${skippedIds.length === 1 ? "invariant" : "invariants"}: ${safeIds.join(", ")}`);
|
|
2066
|
+
}
|
|
2067
|
+
blocks.push(headerLines.join("\n"));
|
|
2068
|
+
const scalars = [];
|
|
2069
|
+
const enums = [];
|
|
2070
|
+
const inputs = [];
|
|
2071
|
+
const objects = [];
|
|
2072
|
+
for (const def of builder.types.values()) {
|
|
2073
|
+
if (def.kind === "SCALAR")
|
|
2074
|
+
scalars.push(def);
|
|
2075
|
+
else if (def.kind === "ENUM")
|
|
2076
|
+
enums.push(def);
|
|
2077
|
+
else if (def.kind === "INPUT_OBJECT")
|
|
2078
|
+
inputs.push(def);
|
|
2079
|
+
else if (def.kind === "OBJECT")
|
|
2080
|
+
objects.push(def);
|
|
2081
|
+
}
|
|
2082
|
+
for (const s of scalars) {
|
|
2083
|
+
const lines = [];
|
|
2084
|
+
if (s.description)
|
|
2085
|
+
lines.push(formatSdlString(s.description));
|
|
2086
|
+
lines.push(`scalar ${s.name}`);
|
|
2087
|
+
blocks.push(lines.join("\n"));
|
|
2088
|
+
}
|
|
2089
|
+
for (const e of enums) {
|
|
2090
|
+
const lines = [];
|
|
2091
|
+
if (e.description)
|
|
2092
|
+
lines.push(formatSdlString(e.description));
|
|
2093
|
+
lines.push(`enum ${e.name} {`);
|
|
2094
|
+
for (const val of e.enumValues || []) {
|
|
2095
|
+
lines.push(` ${val}`);
|
|
2096
|
+
}
|
|
2097
|
+
lines.push("}");
|
|
2098
|
+
blocks.push(lines.join("\n"));
|
|
2099
|
+
}
|
|
2100
|
+
for (const inp of inputs) {
|
|
2101
|
+
const lines = [];
|
|
2102
|
+
if (inp.description)
|
|
2103
|
+
lines.push(formatSdlString(inp.description));
|
|
2104
|
+
lines.push(`input ${inp.name} {`);
|
|
2105
|
+
const fields = inp.inputFields && inp.inputFields.length > 0
|
|
2106
|
+
? inp.inputFields
|
|
2107
|
+
: [{ name: "value", type: namedType("String") }];
|
|
2108
|
+
for (const f of fields) {
|
|
2109
|
+
if (f.description)
|
|
2110
|
+
lines.push(` ${formatSdlString(f.description)}`);
|
|
2111
|
+
lines.push(` ${f.name}: ${renderTypeRefSdl(f.type)}`);
|
|
2112
|
+
}
|
|
2113
|
+
lines.push("}");
|
|
2114
|
+
blocks.push(lines.join("\n"));
|
|
2115
|
+
}
|
|
2116
|
+
const renderObjectBlock = (typeName, fields, description) => {
|
|
2117
|
+
const lines = [];
|
|
2118
|
+
if (description)
|
|
2119
|
+
lines.push(formatSdlString(description));
|
|
2120
|
+
lines.push(`type ${typeName} {`);
|
|
2121
|
+
for (const f of fields) {
|
|
2122
|
+
if (f.description)
|
|
2123
|
+
lines.push(` ${formatSdlString(f.description)}`);
|
|
2124
|
+
const argsPart = f.args.length > 0
|
|
2125
|
+
? `(${f.args.map((a) => `${a.name}: ${renderTypeRefSdl(a.type)}`).join(", ")})`
|
|
2126
|
+
: "";
|
|
2127
|
+
lines.push(` ${f.name}${argsPart}: ${renderTypeRefSdl(f.type)}`);
|
|
2128
|
+
}
|
|
2129
|
+
lines.push("}");
|
|
2130
|
+
return lines.join("\n");
|
|
2131
|
+
};
|
|
2132
|
+
for (const obj of objects) {
|
|
2133
|
+
const fields = obj.fields && obj.fields.length > 0
|
|
2134
|
+
? obj.fields
|
|
2135
|
+
: [{ name: "id", args: [], type: namedType("ID") }];
|
|
2136
|
+
blocks.push(renderObjectBlock(obj.name, fields, obj.description));
|
|
2137
|
+
}
|
|
2138
|
+
const queryFields = hasPlaceholderQuery
|
|
2139
|
+
? [{ name: "_empty", args: [], type: namedType("Boolean") }]
|
|
2140
|
+
: [...builder.queryFields.values()];
|
|
2141
|
+
blocks.push(renderObjectBlock("Query", queryFields));
|
|
2142
|
+
if (builder.mutationFields.size > 0) {
|
|
2143
|
+
blocks.push(renderObjectBlock("Mutation", [...builder.mutationFields.values()]));
|
|
2144
|
+
}
|
|
2145
|
+
return `${blocks.join("\n\n")}\n`;
|
|
2146
|
+
}
|
|
2147
|
+
function buildIntrospectionTypeRef(ref, builder, depth = 0) {
|
|
2148
|
+
if (depth > 32) {
|
|
2149
|
+
return { kind: "SCALAR", name: "String", ofType: null };
|
|
2150
|
+
}
|
|
2151
|
+
if (ref.kind === "NON_NULL" && ref.ofType) {
|
|
2152
|
+
return {
|
|
2153
|
+
kind: "NON_NULL",
|
|
2154
|
+
name: null,
|
|
2155
|
+
ofType: buildIntrospectionTypeRef(ref.ofType, builder, depth + 1)
|
|
2156
|
+
};
|
|
2157
|
+
}
|
|
2158
|
+
if (ref.kind === "LIST" && ref.ofType) {
|
|
2159
|
+
return {
|
|
2160
|
+
kind: "LIST",
|
|
2161
|
+
name: null,
|
|
2162
|
+
ofType: buildIntrospectionTypeRef(ref.ofType, builder, depth + 1)
|
|
2163
|
+
};
|
|
2164
|
+
}
|
|
2165
|
+
const name = ref.name || "String";
|
|
2166
|
+
let kind = "SCALAR";
|
|
2167
|
+
if (BUILTIN_SCALARS.has(name)) {
|
|
2168
|
+
kind = "SCALAR";
|
|
2169
|
+
}
|
|
2170
|
+
else if (name === "Query" || name === "Mutation") {
|
|
2171
|
+
kind = "OBJECT";
|
|
2172
|
+
}
|
|
2173
|
+
else {
|
|
2174
|
+
const def = builder.types.get(name);
|
|
2175
|
+
kind = def ? def.kind : "SCALAR";
|
|
2176
|
+
}
|
|
2177
|
+
return { kind, name, ofType: null };
|
|
2178
|
+
}
|
|
2179
|
+
function buildIntrospectionField(field, builder) {
|
|
2180
|
+
return {
|
|
2181
|
+
name: field.name,
|
|
2182
|
+
description: field.description ?? null,
|
|
2183
|
+
args: field.args.map((arg) => ({
|
|
2184
|
+
name: arg.name,
|
|
2185
|
+
description: arg.description ?? null,
|
|
2186
|
+
type: buildIntrospectionTypeRef(arg.type, builder),
|
|
2187
|
+
defaultValue: null
|
|
2188
|
+
})),
|
|
2189
|
+
type: buildIntrospectionTypeRef(field.type, builder),
|
|
2190
|
+
isDeprecated: false,
|
|
2191
|
+
deprecationReason: null
|
|
2192
|
+
};
|
|
2193
|
+
}
|
|
2194
|
+
function renderIntrospectionJson(builder, hasPlaceholderQuery) {
|
|
2195
|
+
const types = [];
|
|
2196
|
+
const queryFields = hasPlaceholderQuery
|
|
2197
|
+
? [{ name: "_empty", args: [], type: namedType("Boolean") }]
|
|
2198
|
+
: [...builder.queryFields.values()];
|
|
2199
|
+
types.push({
|
|
2200
|
+
kind: "OBJECT",
|
|
2201
|
+
name: "Query",
|
|
2202
|
+
description: null,
|
|
2203
|
+
fields: queryFields.map((f) => buildIntrospectionField(f, builder)),
|
|
2204
|
+
inputFields: null,
|
|
2205
|
+
interfaces: [],
|
|
2206
|
+
enumValues: null,
|
|
2207
|
+
possibleTypes: null
|
|
2208
|
+
});
|
|
2209
|
+
const hasMutations = builder.mutationFields.size > 0;
|
|
2210
|
+
if (hasMutations) {
|
|
2211
|
+
types.push({
|
|
2212
|
+
kind: "OBJECT",
|
|
2213
|
+
name: "Mutation",
|
|
2214
|
+
description: null,
|
|
2215
|
+
fields: [...builder.mutationFields.values()].map((f) => buildIntrospectionField(f, builder)),
|
|
2216
|
+
inputFields: null,
|
|
2217
|
+
interfaces: [],
|
|
2218
|
+
enumValues: null,
|
|
2219
|
+
possibleTypes: null
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
for (const def of builder.types.values()) {
|
|
2223
|
+
if (def.kind === "OBJECT") {
|
|
2224
|
+
const fields = def.fields && def.fields.length > 0
|
|
2225
|
+
? def.fields
|
|
2226
|
+
: [{ name: "id", args: [], type: namedType("ID") }];
|
|
2227
|
+
types.push({
|
|
2228
|
+
kind: "OBJECT",
|
|
2229
|
+
name: def.name,
|
|
2230
|
+
description: def.description ?? null,
|
|
2231
|
+
fields: fields.map((f) => buildIntrospectionField(f, builder)),
|
|
2232
|
+
inputFields: null,
|
|
2233
|
+
interfaces: [],
|
|
2234
|
+
enumValues: null,
|
|
2235
|
+
possibleTypes: null
|
|
2236
|
+
});
|
|
2237
|
+
}
|
|
2238
|
+
else if (def.kind === "INPUT_OBJECT") {
|
|
2239
|
+
const inputFields = def.inputFields && def.inputFields.length > 0
|
|
2240
|
+
? def.inputFields
|
|
2241
|
+
: [{ name: "value", type: namedType("String") }];
|
|
2242
|
+
types.push({
|
|
2243
|
+
kind: "INPUT_OBJECT",
|
|
2244
|
+
name: def.name,
|
|
2245
|
+
description: def.description ?? null,
|
|
2246
|
+
fields: null,
|
|
2247
|
+
inputFields: inputFields.map((f) => ({
|
|
2248
|
+
name: f.name,
|
|
2249
|
+
description: f.description ?? null,
|
|
2250
|
+
type: buildIntrospectionTypeRef(f.type, builder),
|
|
2251
|
+
defaultValue: null
|
|
2252
|
+
})),
|
|
2253
|
+
interfaces: null,
|
|
2254
|
+
enumValues: null,
|
|
2255
|
+
possibleTypes: null
|
|
2256
|
+
});
|
|
2257
|
+
}
|
|
2258
|
+
else if (def.kind === "ENUM") {
|
|
2259
|
+
types.push({
|
|
2260
|
+
kind: "ENUM",
|
|
2261
|
+
name: def.name,
|
|
2262
|
+
description: def.description ?? null,
|
|
2263
|
+
fields: null,
|
|
2264
|
+
inputFields: null,
|
|
2265
|
+
interfaces: null,
|
|
2266
|
+
enumValues: (def.enumValues || []).map((val) => ({
|
|
2267
|
+
name: val,
|
|
2268
|
+
description: null,
|
|
2269
|
+
isDeprecated: false,
|
|
2270
|
+
deprecationReason: null
|
|
2271
|
+
})),
|
|
2272
|
+
possibleTypes: null
|
|
2273
|
+
});
|
|
2274
|
+
}
|
|
2275
|
+
else if (def.kind === "SCALAR") {
|
|
2276
|
+
types.push({
|
|
2277
|
+
kind: "SCALAR",
|
|
2278
|
+
name: def.name,
|
|
2279
|
+
description: def.description ?? null,
|
|
2280
|
+
fields: null,
|
|
2281
|
+
inputFields: null,
|
|
2282
|
+
interfaces: null,
|
|
2283
|
+
enumValues: null,
|
|
2284
|
+
possibleTypes: null
|
|
2285
|
+
});
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
for (const scalarName of BUILTIN_SCALAR_ORDER) {
|
|
2289
|
+
types.push({
|
|
2290
|
+
kind: "SCALAR",
|
|
2291
|
+
name: scalarName,
|
|
2292
|
+
description: null,
|
|
2293
|
+
fields: null,
|
|
2294
|
+
inputFields: null,
|
|
2295
|
+
interfaces: null,
|
|
2296
|
+
enumValues: null,
|
|
2297
|
+
possibleTypes: null
|
|
2298
|
+
});
|
|
2299
|
+
}
|
|
2300
|
+
const doc = {
|
|
2301
|
+
__schema: {
|
|
2302
|
+
queryType: { name: "Query" },
|
|
2303
|
+
mutationType: hasMutations ? { name: "Mutation" } : null,
|
|
2304
|
+
subscriptionType: null,
|
|
2305
|
+
types,
|
|
2306
|
+
directives: []
|
|
2307
|
+
}
|
|
2308
|
+
};
|
|
2309
|
+
return `${JSON.stringify(doc, null, 2)}\n`;
|
|
2310
|
+
}
|
|
2311
|
+
function suggestedFilenameFor(format) {
|
|
2312
|
+
return format === "introspection" ? "vibecode-introspection.json" : "vibecode-schema.graphql";
|
|
2313
|
+
}
|
|
2314
|
+
/**
|
|
2315
|
+
* Compile visible HTTP invariants from a ContractV02 into a valid GraphQL SDL (`.graphql`)
|
|
2316
|
+
* or W3C GraphQL Introspection JSON (`{ __schema: ... }`) schema.
|
|
2317
|
+
*/
|
|
2318
|
+
export function exportGraphqlSchema(contract, options = {}) {
|
|
2319
|
+
if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
|
|
2320
|
+
throw new VibecodeError("CONTRACT_INVALID", "exportGraphqlSchema requires a valid contract object with an invariants array.");
|
|
2321
|
+
}
|
|
2322
|
+
const formatRaw = options.format ?? "sdl";
|
|
2323
|
+
if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
|
|
2324
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported GraphQL export format "${String(formatRaw)}". Supported formats: sdl, introspection.`);
|
|
2325
|
+
}
|
|
2326
|
+
const format = formatRaw;
|
|
2327
|
+
const includeRestFallback = options.includeRestFallback !== false;
|
|
2328
|
+
const includeSkippedComments = options.includeSkippedComments !== false;
|
|
2329
|
+
const builder = new SchemaBuilder();
|
|
2330
|
+
const skippedIds = [];
|
|
2331
|
+
let exportedCount = 0;
|
|
2332
|
+
for (const inv of contract.invariants) {
|
|
2333
|
+
if (!isRecord(inv))
|
|
2334
|
+
continue;
|
|
2335
|
+
// Holdouts are excluded completely: never in SDL, JSON, warnings, skippedCount, or comments.
|
|
2336
|
+
if (inv.holdout === true) {
|
|
2337
|
+
continue;
|
|
2338
|
+
}
|
|
2339
|
+
const invId = typeof inv.id === "string" && inv.id.trim() ? inv.id.trim() : "unknown";
|
|
2340
|
+
if (inv.type !== "http") {
|
|
2341
|
+
skippedIds.push(invId);
|
|
2342
|
+
continue;
|
|
2343
|
+
}
|
|
2344
|
+
const nativePayload = detectNativeGraphqlPayload(inv);
|
|
2345
|
+
if (nativePayload) {
|
|
2346
|
+
const ok = processNativeGraphqlInvariant(inv, nativePayload, builder);
|
|
2347
|
+
if (ok) {
|
|
2348
|
+
exportedCount += 1;
|
|
2349
|
+
}
|
|
2350
|
+
else {
|
|
2351
|
+
skippedIds.push(invId);
|
|
2352
|
+
}
|
|
2353
|
+
continue;
|
|
2354
|
+
}
|
|
2355
|
+
if (!includeRestFallback) {
|
|
2356
|
+
skippedIds.push(invId);
|
|
2357
|
+
continue;
|
|
2358
|
+
}
|
|
2359
|
+
const ok = processRestFallbackInvariant(inv, builder);
|
|
2360
|
+
if (ok) {
|
|
2361
|
+
exportedCount += 1;
|
|
2362
|
+
}
|
|
2363
|
+
else {
|
|
2364
|
+
skippedIds.push(invId);
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
const rawTitle = (typeof options.title === "string" && options.title.trim()) ||
|
|
2368
|
+
(isRecord(contract.target) && typeof contract.target.name === "string" && contract.target.name.trim()) ||
|
|
2369
|
+
"vibecode-graphql-schema";
|
|
2370
|
+
const title = sanitizeSingleLineText(rawTitle) || "vibecode-graphql-schema";
|
|
2371
|
+
const hasPlaceholderQuery = builder.queryFields.size === 0;
|
|
2372
|
+
if (hasPlaceholderQuery) {
|
|
2373
|
+
builder.addWarning("No query operations were found; emitted placeholder Query._empty field to keep the GraphQL schema valid.");
|
|
2374
|
+
}
|
|
2375
|
+
const content = format === "introspection"
|
|
2376
|
+
? renderIntrospectionJson(builder, hasPlaceholderQuery)
|
|
2377
|
+
: renderSdl(builder, title, skippedIds, includeSkippedComments, hasPlaceholderQuery);
|
|
2378
|
+
return {
|
|
2379
|
+
format,
|
|
2380
|
+
suggestedFilename: suggestedFilenameFor(format),
|
|
2381
|
+
content,
|
|
2382
|
+
exportedCount,
|
|
2383
|
+
skippedCount: skippedIds.length,
|
|
2384
|
+
warnings: builder.warnings,
|
|
2385
|
+
queryFields: [...builder.queryFields.keys()],
|
|
2386
|
+
mutationFields: [...builder.mutationFields.keys()],
|
|
2387
|
+
typeNames: [...builder.types.keys()]
|
|
2388
|
+
};
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* Export and atomically write a GraphQL SDL or Introspection JSON schema to disk
|
|
2392
|
+
* (temp file + rename in target parent directory).
|
|
2393
|
+
*/
|
|
2394
|
+
export function writeGraphqlSchema(contract, outPath, options = {}) {
|
|
2395
|
+
if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
|
|
2396
|
+
throw new VibecodeError("CONTRACT_INVALID", "writeGraphqlSchema requires a valid non-empty outPath without NUL bytes.");
|
|
2397
|
+
}
|
|
2398
|
+
const resolvedOut = path.resolve(outPath.trim());
|
|
2399
|
+
if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
|
|
2400
|
+
throw new VibecodeError("CONTRACT_INVALID", `Cannot write GraphQL schema: "${resolvedOut}" is a directory.`, { fallbackHint: "Pass a file path (for example `.vibecode/schema.graphql`), not a directory." });
|
|
2401
|
+
}
|
|
2402
|
+
const result = exportGraphqlSchema(contract, options);
|
|
2403
|
+
const parentDir = path.dirname(resolvedOut);
|
|
2404
|
+
fs.mkdirSync(parentDir, { recursive: true });
|
|
2405
|
+
const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
2406
|
+
try {
|
|
2407
|
+
fs.writeFileSync(tmpPath, result.content, "utf8");
|
|
2408
|
+
fs.renameSync(tmpPath, resolvedOut);
|
|
2409
|
+
}
|
|
2410
|
+
catch (err) {
|
|
2411
|
+
try {
|
|
2412
|
+
if (fs.existsSync(tmpPath)) {
|
|
2413
|
+
fs.rmSync(tmpPath, { force: true });
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
catch {
|
|
2417
|
+
// ignore cleanup error
|
|
2418
|
+
}
|
|
2419
|
+
throw err;
|
|
2420
|
+
}
|
|
2421
|
+
return {
|
|
2422
|
+
...result,
|
|
2423
|
+
outPath: resolvedOut
|
|
2424
|
+
};
|
|
2425
|
+
}
|
|
2426
|
+
function style(text, codes, useColor) {
|
|
2427
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
2428
|
+
}
|
|
2429
|
+
function formatNameList(items, useColor, colorCode) {
|
|
2430
|
+
if (items.length === 0)
|
|
2431
|
+
return style("none", ANSI.dim, useColor);
|
|
2432
|
+
const shown = items.slice(0, MAX_PRETTY_ITEMS).map((item) => sanitizeSingleLineText(item)).filter(Boolean);
|
|
2433
|
+
const rendered = shown.map((name) => style(name, colorCode, useColor)).join(", ");
|
|
2434
|
+
if (items.length > MAX_PRETTY_ITEMS) {
|
|
2435
|
+
return `${rendered} ${style(`(+${items.length - MAX_PRETTY_ITEMS} more)`, ANSI.dim, useColor)}`;
|
|
2436
|
+
}
|
|
2437
|
+
return rendered;
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* Format a concise, sanitized terminal summary for a GraphQL schema export result.
|
|
2441
|
+
*/
|
|
2442
|
+
export function formatPrettyGraphqlExport(result, outPath, color) {
|
|
2443
|
+
const useColor = color === true;
|
|
2444
|
+
const lines = [];
|
|
2445
|
+
const banner = style("[GRAPHQL EXPORT]", `${ANSI.bold}${ANSI.cyan}`, useColor);
|
|
2446
|
+
const formatLabel = result.format === "introspection"
|
|
2447
|
+
? style("GraphQL Introspection JSON", ANSI.bold, useColor)
|
|
2448
|
+
: style("GraphQL SDL", ANSI.bold, useColor);
|
|
2449
|
+
lines.push(`${banner} ${formatLabel}`);
|
|
2450
|
+
const effectiveOut = (typeof outPath === "string" && outPath.trim()) ||
|
|
2451
|
+
(typeof result.outPath === "string" && result.outPath.trim()) ||
|
|
2452
|
+
"";
|
|
2453
|
+
if (effectiveOut) {
|
|
2454
|
+
lines.push(`Output: ${sanitizeSingleLineText(effectiveOut)}`);
|
|
2455
|
+
}
|
|
2456
|
+
const totalBytes = Buffer.byteLength(result.content || "", "utf8");
|
|
2457
|
+
const opLabel = result.exportedCount === 1 ? "operation" : "operations";
|
|
2458
|
+
const summaryParts = [
|
|
2459
|
+
`${result.exportedCount} ${opLabel}`,
|
|
2460
|
+
`${result.queryFields.length} ${result.queryFields.length === 1 ? "query" : "queries"}`,
|
|
2461
|
+
`${result.mutationFields.length} ${result.mutationFields.length === 1 ? "mutation" : "mutations"}`,
|
|
2462
|
+
`${result.typeNames.length} ${result.typeNames.length === 1 ? "type" : "types"}`
|
|
2463
|
+
];
|
|
2464
|
+
if (result.skippedCount > 0) {
|
|
2465
|
+
summaryParts.push(`${result.skippedCount} skipped`);
|
|
2466
|
+
}
|
|
2467
|
+
summaryParts.push(`${totalBytes} bytes`);
|
|
2468
|
+
lines.push(`Summary: ${summaryParts.join(", ")}`);
|
|
2469
|
+
lines.push(`Queries: ${formatNameList(result.queryFields, useColor, ANSI.green)}`);
|
|
2470
|
+
lines.push(`Mutations: ${formatNameList(result.mutationFields, useColor, ANSI.yellow)}`);
|
|
2471
|
+
lines.push(`Types: ${formatNameList(result.typeNames, useColor, ANSI.cyan)}`);
|
|
2472
|
+
if (Array.isArray(result.warnings) && result.warnings.length > 0) {
|
|
2473
|
+
lines.push("Warnings:");
|
|
2474
|
+
for (const warning of result.warnings.slice(0, MAX_PRETTY_WARNINGS)) {
|
|
2475
|
+
lines.push(` - ${style(sanitizeSingleLineText(warning), ANSI.yellow, useColor)}`);
|
|
2476
|
+
}
|
|
2477
|
+
if (result.warnings.length > MAX_PRETTY_WARNINGS) {
|
|
2478
|
+
lines.push(` ${style(`... and ${result.warnings.length - MAX_PRETTY_WARNINGS} more`, ANSI.dim, useColor)}`);
|
|
2479
|
+
}
|
|
2480
|
+
}
|
|
2481
|
+
return lines.join("\n");
|
|
2482
|
+
}
|