vibecode-anything 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,1852 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { VibecodeError, errorMessage } from "../core/errors.js";
4
+ import { validateContract, validateJsonSchema } from "../core/schema.js";
5
+ import { isSensitiveHeader, isSensitiveQueryParam, mergeHeaders, redactHeaders } from "./trace.js";
6
+ const GRAPHQL_MAX_INVARIANTS = 50;
7
+ const MAX_SOURCE_BYTES = 5 * 1024 * 1024;
8
+ const MAX_SELECTION_DEPTH = 2;
9
+ const MAX_SELECTED_FIELDS_PER_TYPE = 25;
10
+ const MAX_TYPE_REF_DEPTH = 32;
11
+ const MAX_SUBSET_BYTES = 64 * 1024;
12
+ const DEFAULT_PROBE_TIMEOUT_MS = 10000;
13
+ const BUILTIN_SCALARS = new Set(["String", "Int", "Float", "Boolean", "ID"]);
14
+ const EXTRA_SENSITIVE_HEADERS = new Set([
15
+ "x-csrf-token",
16
+ "x-xsrf-token",
17
+ "csrf-token"
18
+ ]);
19
+ const TOP_LEVEL_SDL_KEYWORDS = new Set([
20
+ "schema",
21
+ "type",
22
+ "interface",
23
+ "union",
24
+ "enum",
25
+ "input",
26
+ "scalar",
27
+ "directive",
28
+ "extend"
29
+ ]);
30
+ function isObject(v) {
31
+ return v !== null && typeof v === "object" && !Array.isArray(v);
32
+ }
33
+ function isGraphqlSensitiveHeader(name) {
34
+ const lower = name.trim().toLowerCase();
35
+ return isSensitiveHeader(lower) || EXTRA_SENSITIVE_HEADERS.has(lower);
36
+ }
37
+ function stripSensitiveHeaders(headers) {
38
+ if (!isObject(headers))
39
+ return { safe: {}, redacted: false, secretValues: [] };
40
+ const candidate = {};
41
+ const secretValues = [];
42
+ let redacted = false;
43
+ for (const [rawKey, rawVal] of Object.entries(headers)) {
44
+ const key = rawKey.trim();
45
+ if (!key || rawVal === undefined || rawVal === null)
46
+ continue;
47
+ const valStr = String(rawVal);
48
+ if (isGraphqlSensitiveHeader(key)) {
49
+ redacted = true;
50
+ const trimmedVal = valStr.trim();
51
+ if (trimmedVal) {
52
+ secretValues.push(trimmedVal);
53
+ const bare = trimmedVal.replace(/^(?:bearer|basic|token|digest|apikey)\s+/i, "").trim();
54
+ if (bare && bare !== trimmedVal)
55
+ secretValues.push(bare);
56
+ }
57
+ continue;
58
+ }
59
+ candidate[key] = valStr;
60
+ }
61
+ const safe = redactHeaders(candidate, "strip");
62
+ if (Object.keys(safe).length < Object.keys(candidate).length) {
63
+ redacted = true;
64
+ }
65
+ return { safe, redacted, secretValues };
66
+ }
67
+ function hasHeaderCaseInsensitive(headers, name) {
68
+ const lower = name.toLowerCase();
69
+ return Object.keys(headers).some((k) => k.toLowerCase() === lower);
70
+ }
71
+ function setHeaderCaseInsensitive(headers, name, value) {
72
+ const lower = name.toLowerCase();
73
+ for (const existingKey of Object.keys(headers)) {
74
+ if (existingKey.toLowerCase() === lower && existingKey !== name) {
75
+ delete headers[existingKey];
76
+ }
77
+ }
78
+ headers[name] = value;
79
+ }
80
+ function isNameStart(code) {
81
+ return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95;
82
+ }
83
+ function isNameContinue(code) {
84
+ return isNameStart(code) || (code >= 48 && code <= 57);
85
+ }
86
+ function isDigit(code) {
87
+ return code >= 48 && code <= 57;
88
+ }
89
+ function tokenizeGraphql(rawText) {
90
+ const text = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
91
+ const tokens = [];
92
+ const len = text.length;
93
+ let i = 0;
94
+ let line = 1;
95
+ let col = 1;
96
+ const advanceLine = () => {
97
+ line += 1;
98
+ col = 1;
99
+ };
100
+ while (i < len) {
101
+ const ch = text[i];
102
+ const code = text.charCodeAt(i);
103
+ // Ignored horizontal whitespace & commas (insignificant in GraphQL)
104
+ if (ch === " " || ch === "\t" || ch === ",") {
105
+ i += 1;
106
+ col += 1;
107
+ continue;
108
+ }
109
+ // Line terminators
110
+ if (ch === "\n") {
111
+ i += 1;
112
+ advanceLine();
113
+ continue;
114
+ }
115
+ if (ch === "\r") {
116
+ i += text[i + 1] === "\n" ? 2 : 1;
117
+ advanceLine();
118
+ continue;
119
+ }
120
+ // Line comments `# ...`
121
+ if (ch === "#") {
122
+ i += 1;
123
+ col += 1;
124
+ while (i < len && text[i] !== "\n" && text[i] !== "\r") {
125
+ i += 1;
126
+ col += 1;
127
+ }
128
+ continue;
129
+ }
130
+ const startLine = line;
131
+ const startCol = col;
132
+ // Spread punctuator `...`
133
+ if (ch === "." && text[i + 1] === "." && text[i + 2] === ".") {
134
+ tokens.push({ kind: "PUNCT", value: "...", line: startLine, col: startCol });
135
+ i += 3;
136
+ col += 3;
137
+ continue;
138
+ }
139
+ // Single-character punctuators
140
+ if (ch === "!" ||
141
+ ch === "$" ||
142
+ ch === "&" ||
143
+ ch === "(" ||
144
+ ch === ")" ||
145
+ ch === ":" ||
146
+ ch === "=" ||
147
+ ch === "@" ||
148
+ ch === "[" ||
149
+ ch === "]" ||
150
+ ch === "{" ||
151
+ ch === "|" ||
152
+ ch === "}") {
153
+ tokens.push({ kind: "PUNCT", value: ch, line: startLine, col: startCol });
154
+ i += 1;
155
+ col += 1;
156
+ continue;
157
+ }
158
+ // Block string `"""..."""`
159
+ if (ch === '"' && text[i + 1] === '"' && text[i + 2] === '"') {
160
+ i += 3;
161
+ col += 3;
162
+ let val = "";
163
+ let closed = false;
164
+ while (i < len) {
165
+ if (text[i] === "\\" && text[i + 1] === '"' && text[i + 2] === '"' && text[i + 3] === '"') {
166
+ val += '"""';
167
+ i += 4;
168
+ col += 4;
169
+ continue;
170
+ }
171
+ if (text[i] === '"' && text[i + 1] === '"' && text[i + 2] === '"') {
172
+ i += 3;
173
+ col += 3;
174
+ closed = true;
175
+ break;
176
+ }
177
+ if (text[i] === "\n") {
178
+ val += "\n";
179
+ i += 1;
180
+ advanceLine();
181
+ continue;
182
+ }
183
+ if (text[i] === "\r") {
184
+ val += "\n";
185
+ i += text[i + 1] === "\n" ? 2 : 1;
186
+ advanceLine();
187
+ continue;
188
+ }
189
+ val += text[i];
190
+ i += 1;
191
+ col += 1;
192
+ }
193
+ if (!closed) {
194
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Unterminated GraphQL block string at line ${startLine}, column ${startCol}`);
195
+ }
196
+ tokens.push({ kind: "STRING", value: val.trim(), line: startLine, col: startCol });
197
+ continue;
198
+ }
199
+ // Single-line string `"..."`
200
+ if (ch === '"') {
201
+ i += 1;
202
+ col += 1;
203
+ let val = "";
204
+ let closed = false;
205
+ while (i < len) {
206
+ const c = text[i];
207
+ if (c === "\n" || c === "\r") {
208
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Unterminated GraphQL string literal at line ${startLine}, column ${startCol}`);
209
+ }
210
+ if (c === '"') {
211
+ i += 1;
212
+ col += 1;
213
+ closed = true;
214
+ break;
215
+ }
216
+ if (c === "\\") {
217
+ i += 1;
218
+ col += 1;
219
+ if (i >= len) {
220
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Unterminated escape in GraphQL string at line ${startLine}, column ${startCol}`);
221
+ }
222
+ const esc = text[i];
223
+ if (esc === '"') {
224
+ val += '"';
225
+ i += 1;
226
+ col += 1;
227
+ }
228
+ else if (esc === "\\") {
229
+ val += "\\";
230
+ i += 1;
231
+ col += 1;
232
+ }
233
+ else if (esc === "/") {
234
+ val += "/";
235
+ i += 1;
236
+ col += 1;
237
+ }
238
+ else if (esc === "b") {
239
+ val += "\b";
240
+ i += 1;
241
+ col += 1;
242
+ }
243
+ else if (esc === "f") {
244
+ val += "\f";
245
+ i += 1;
246
+ col += 1;
247
+ }
248
+ else if (esc === "n") {
249
+ val += "\n";
250
+ i += 1;
251
+ col += 1;
252
+ }
253
+ else if (esc === "r") {
254
+ val += "\r";
255
+ i += 1;
256
+ col += 1;
257
+ }
258
+ else if (esc === "t") {
259
+ val += "\t";
260
+ i += 1;
261
+ col += 1;
262
+ }
263
+ else if (esc === "u") {
264
+ if (text[i + 1] === "{") {
265
+ const endBrace = text.indexOf("}", i + 2);
266
+ const hex = endBrace > i + 2 ? text.slice(i + 2, endBrace) : "";
267
+ if (!hex || !/^[0-9a-fA-F]{1,6}$/.test(hex)) {
268
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid unicode escape in GraphQL string at line ${line}, column ${col}`);
269
+ }
270
+ const cp = parseInt(hex, 16);
271
+ if (cp > 0x10ffff) {
272
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Unicode escape out of range at line ${line}, column ${col}`);
273
+ }
274
+ val += String.fromCodePoint(cp);
275
+ const consumed = endBrace - i + 1;
276
+ i = endBrace + 1;
277
+ col += consumed;
278
+ }
279
+ else {
280
+ const hex = text.slice(i + 1, i + 5);
281
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
282
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid unicode escape in GraphQL string at line ${line}, column ${col}`);
283
+ }
284
+ val += String.fromCharCode(parseInt(hex, 16));
285
+ i += 5;
286
+ col += 5;
287
+ }
288
+ }
289
+ else {
290
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid escape sequence \\${esc} in GraphQL string at line ${line}, column ${col}`);
291
+ }
292
+ continue;
293
+ }
294
+ val += c;
295
+ i += 1;
296
+ col += 1;
297
+ }
298
+ if (!closed) {
299
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Unterminated GraphQL string literal at line ${startLine}, column ${startCol}`);
300
+ }
301
+ tokens.push({ kind: "STRING", value: val, line: startLine, col: startCol });
302
+ continue;
303
+ }
304
+ // Names
305
+ if (isNameStart(code)) {
306
+ const start = i;
307
+ i += 1;
308
+ col += 1;
309
+ while (i < len && isNameContinue(text.charCodeAt(i))) {
310
+ i += 1;
311
+ col += 1;
312
+ }
313
+ tokens.push({ kind: "NAME", value: text.slice(start, i), line: startLine, col: startCol });
314
+ continue;
315
+ }
316
+ // Int or Float literal
317
+ if (ch === "-" || isDigit(code)) {
318
+ const start = i;
319
+ let isFloat = false;
320
+ if (ch === "-") {
321
+ i += 1;
322
+ col += 1;
323
+ if (i >= len || !isDigit(text.charCodeAt(i))) {
324
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid number token at line ${startLine}, column ${startCol}`);
325
+ }
326
+ }
327
+ if (text[i] === "0") {
328
+ i += 1;
329
+ col += 1;
330
+ if (i < len && isDigit(text.charCodeAt(i))) {
331
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid leading zero in number at line ${startLine}, column ${startCol}`);
332
+ }
333
+ }
334
+ else {
335
+ while (i < len && isDigit(text.charCodeAt(i))) {
336
+ i += 1;
337
+ col += 1;
338
+ }
339
+ }
340
+ if (i < len && text[i] === ".") {
341
+ isFloat = true;
342
+ i += 1;
343
+ col += 1;
344
+ if (i >= len || !isDigit(text.charCodeAt(i))) {
345
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid fractional number at line ${startLine}, column ${startCol}`);
346
+ }
347
+ while (i < len && isDigit(text.charCodeAt(i))) {
348
+ i += 1;
349
+ col += 1;
350
+ }
351
+ }
352
+ if (i < len && (text[i] === "e" || text[i] === "E")) {
353
+ isFloat = true;
354
+ i += 1;
355
+ col += 1;
356
+ if (i < len && (text[i] === "+" || text[i] === "-")) {
357
+ i += 1;
358
+ col += 1;
359
+ }
360
+ if (i >= len || !isDigit(text.charCodeAt(i))) {
361
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Invalid exponent in number at line ${startLine}, column ${startCol}`);
362
+ }
363
+ while (i < len && isDigit(text.charCodeAt(i))) {
364
+ i += 1;
365
+ col += 1;
366
+ }
367
+ }
368
+ if (i < len && (isNameStart(text.charCodeAt(i)) || text[i] === ".")) {
369
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Unexpected character '${text[i]}' after number at line ${line}, column ${col}`);
370
+ }
371
+ tokens.push({
372
+ kind: isFloat ? "FLOAT" : "INT",
373
+ value: text.slice(start, i),
374
+ line: startLine,
375
+ col: startCol
376
+ });
377
+ continue;
378
+ }
379
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Unexpected character ${JSON.stringify(ch)} in GraphQL SDL at line ${startLine}, column ${startCol}`);
380
+ }
381
+ tokens.push({ kind: "EOF", value: "", line, col });
382
+ return tokens;
383
+ }
384
+ function mergeFields(existing, incoming) {
385
+ const result = existing ? existing.slice() : [];
386
+ const indexByName = new Map();
387
+ for (let i = 0; i < result.length; i += 1) {
388
+ indexByName.set(result[i].name, i);
389
+ }
390
+ for (const field of incoming) {
391
+ const idx = indexByName.get(field.name);
392
+ if (idx !== undefined) {
393
+ result[idx] = field;
394
+ }
395
+ else {
396
+ indexByName.set(field.name, result.length);
397
+ result.push(field);
398
+ }
399
+ }
400
+ return result;
401
+ }
402
+ function mergeInputFields(existing, incoming) {
403
+ const result = existing ? existing.slice() : [];
404
+ const indexByName = new Map();
405
+ for (let i = 0; i < result.length; i += 1) {
406
+ indexByName.set(result[i].name, i);
407
+ }
408
+ for (const field of incoming) {
409
+ const idx = indexByName.get(field.name);
410
+ if (idx !== undefined) {
411
+ result[idx] = field;
412
+ }
413
+ else {
414
+ indexByName.set(field.name, result.length);
415
+ result.push(field);
416
+ }
417
+ }
418
+ return result;
419
+ }
420
+ function mergeUniqueStrings(existing, incoming) {
421
+ const out = existing ? existing.slice() : [];
422
+ const seen = new Set(out);
423
+ for (const item of incoming) {
424
+ if (!seen.has(item)) {
425
+ seen.add(item);
426
+ out.push(item);
427
+ }
428
+ }
429
+ return out;
430
+ }
431
+ function parseSdlDefinitions(text) {
432
+ const tokens = tokenizeGraphql(text);
433
+ let pos = 0;
434
+ const peek = (offset = 0) => tokens[Math.min(pos + offset, tokens.length - 1)];
435
+ const next = () => {
436
+ const tok = peek();
437
+ if (pos < tokens.length - 1)
438
+ pos += 1;
439
+ return tok;
440
+ };
441
+ const fail = (message, tok = peek()) => {
442
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `GraphQL SDL syntax error at line ${tok.line}, column ${tok.col}: ${message}`);
443
+ };
444
+ const expectPunct = (val) => {
445
+ const tok = peek();
446
+ if (tok.kind !== "PUNCT" || tok.value !== val) {
447
+ fail(`expected '${val}', got ${tok.kind === "EOF" ? "EOF" : `'${tok.value}'`}`, tok);
448
+ }
449
+ next();
450
+ };
451
+ const expectName = (context = "identifier") => {
452
+ const tok = peek();
453
+ if (tok.kind !== "NAME") {
454
+ fail(`expected ${context}, got ${tok.kind === "EOF" ? "EOF" : `'${tok.value}'`}`, tok);
455
+ }
456
+ next();
457
+ return tok.value;
458
+ };
459
+ const expectKeyword = (kw) => {
460
+ const tok = peek();
461
+ if (tok.kind !== "NAME" || tok.value !== kw) {
462
+ fail(`expected '${kw}', got ${tok.kind === "EOF" ? "EOF" : `'${tok.value}'`}`, tok);
463
+ }
464
+ next();
465
+ };
466
+ const matchPunct = (val) => {
467
+ const tok = peek();
468
+ if (tok.kind === "PUNCT" && tok.value === val) {
469
+ next();
470
+ return true;
471
+ }
472
+ return false;
473
+ };
474
+ const parseOptionalDescription = () => {
475
+ if (peek().kind === "STRING") {
476
+ return next().value;
477
+ }
478
+ return undefined;
479
+ };
480
+ const parseTypeRef = (depth = 0) => {
481
+ if (depth > MAX_TYPE_REF_DEPTH) {
482
+ fail("type nesting depth exceeded");
483
+ }
484
+ let ref;
485
+ if (matchPunct("[")) {
486
+ const inner = parseTypeRef(depth + 1);
487
+ expectPunct("]");
488
+ ref = { kind: "LIST", ofType: inner };
489
+ }
490
+ else {
491
+ const name = expectName("type name");
492
+ ref = { kind: "NAMED", name };
493
+ }
494
+ if (matchPunct("!")) {
495
+ ref = { kind: "NON_NULL", ofType: ref };
496
+ }
497
+ return ref;
498
+ };
499
+ const parseConstValue = (depth = 0) => {
500
+ if (depth > MAX_TYPE_REF_DEPTH) {
501
+ fail("value nesting depth exceeded");
502
+ }
503
+ const tok = peek();
504
+ if (tok.kind === "INT" || tok.kind === "FLOAT") {
505
+ next();
506
+ return tok.value;
507
+ }
508
+ if (tok.kind === "STRING") {
509
+ next();
510
+ return JSON.stringify(tok.value);
511
+ }
512
+ if (tok.kind === "NAME") {
513
+ next();
514
+ return tok.value;
515
+ }
516
+ if (tok.kind === "PUNCT" && tok.value === "[") {
517
+ next();
518
+ const parts = [];
519
+ while (!(peek().kind === "PUNCT" && peek().value === "]")) {
520
+ if (peek().kind === "EOF")
521
+ fail("unterminated list value");
522
+ parts.push(parseConstValue(depth + 1));
523
+ }
524
+ expectPunct("]");
525
+ return `[${parts.join(", ")}]`;
526
+ }
527
+ if (tok.kind === "PUNCT" && tok.value === "{") {
528
+ next();
529
+ const parts = [];
530
+ while (!(peek().kind === "PUNCT" && peek().value === "}")) {
531
+ if (peek().kind === "EOF")
532
+ fail("unterminated input object value");
533
+ const fieldName = expectName("object field name");
534
+ expectPunct(":");
535
+ const fieldVal = parseConstValue(depth + 1);
536
+ parts.push(`${fieldName}: ${fieldVal}`);
537
+ }
538
+ expectPunct("}");
539
+ return `{ ${parts.join(", ")} }`;
540
+ }
541
+ return fail(`expected constant value, got ${tok.kind === "EOF" ? "EOF" : `'${tok.value}'`}`, tok);
542
+ };
543
+ const parseDirectives = () => {
544
+ let count = 0;
545
+ while (peek().kind === "PUNCT" && peek().value === "@") {
546
+ count += 1;
547
+ next();
548
+ expectName("directive name");
549
+ if (matchPunct("(")) {
550
+ if (peek().kind === "PUNCT" && peek().value === ")") {
551
+ fail("directive argument list cannot be empty");
552
+ }
553
+ while (!(peek().kind === "PUNCT" && peek().value === ")")) {
554
+ if (peek().kind === "EOF")
555
+ fail("unterminated directive arguments");
556
+ expectName("directive argument name");
557
+ expectPunct(":");
558
+ parseConstValue();
559
+ }
560
+ expectPunct(")");
561
+ }
562
+ }
563
+ return count;
564
+ };
565
+ const parseInputValueDef = () => {
566
+ const description = parseOptionalDescription();
567
+ const name = expectName("input value name");
568
+ expectPunct(":");
569
+ const type = parseTypeRef();
570
+ let defaultValue;
571
+ if (matchPunct("=")) {
572
+ defaultValue = parseConstValue();
573
+ }
574
+ parseDirectives();
575
+ return {
576
+ name,
577
+ type,
578
+ required: type.kind === "NON_NULL" && defaultValue === undefined,
579
+ ...(defaultValue !== undefined ? { defaultValue } : {}),
580
+ ...(description !== undefined ? { description } : {})
581
+ };
582
+ };
583
+ const parseArgumentsDef = () => {
584
+ if (!matchPunct("("))
585
+ return [];
586
+ const args = [];
587
+ while (!(peek().kind === "PUNCT" && peek().value === ")")) {
588
+ if (peek().kind === "EOF")
589
+ fail("unterminated argument list");
590
+ args.push(parseInputValueDef());
591
+ }
592
+ expectPunct(")");
593
+ return args;
594
+ };
595
+ const parseImplements = () => {
596
+ const tok = peek();
597
+ if (tok.kind !== "NAME" || tok.value !== "implements")
598
+ return [];
599
+ next();
600
+ matchPunct("&");
601
+ const list = [expectName("interface name")];
602
+ while (true) {
603
+ if (matchPunct("&")) {
604
+ list.push(expectName("interface name"));
605
+ continue;
606
+ }
607
+ // Legacy GraphQL 2016 comma-separated implements (`implements A, B {`)
608
+ const upcoming = peek();
609
+ if (upcoming.kind === "NAME" && !TOP_LEVEL_SDL_KEYWORDS.has(upcoming.value)) {
610
+ list.push(expectName("interface name"));
611
+ continue;
612
+ }
613
+ break;
614
+ }
615
+ return list;
616
+ };
617
+ const parseFieldsBlock = () => {
618
+ expectPunct("{");
619
+ const fields = [];
620
+ while (!(peek().kind === "PUNCT" && peek().value === "}")) {
621
+ if (peek().kind === "EOF")
622
+ fail("unterminated field block");
623
+ const description = parseOptionalDescription();
624
+ const name = expectName("field name");
625
+ const args = parseArgumentsDef();
626
+ expectPunct(":");
627
+ const type = parseTypeRef();
628
+ parseDirectives();
629
+ fields.push({
630
+ name,
631
+ args,
632
+ type,
633
+ ...(description !== undefined ? { description } : {})
634
+ });
635
+ }
636
+ expectPunct("}");
637
+ return fields;
638
+ };
639
+ const parseInputFieldsBlock = () => {
640
+ expectPunct("{");
641
+ const fields = [];
642
+ while (!(peek().kind === "PUNCT" && peek().value === "}")) {
643
+ if (peek().kind === "EOF")
644
+ fail("unterminated input block");
645
+ fields.push(parseInputValueDef());
646
+ }
647
+ expectPunct("}");
648
+ return fields;
649
+ };
650
+ const parseEnumValuesBlock = () => {
651
+ expectPunct("{");
652
+ const values = [];
653
+ while (!(peek().kind === "PUNCT" && peek().value === "}")) {
654
+ if (peek().kind === "EOF")
655
+ fail("unterminated enum block");
656
+ parseOptionalDescription();
657
+ const valName = expectName("enum value");
658
+ if (valName === "true" || valName === "false" || valName === "null") {
659
+ fail(`invalid enum value '${valName}'`);
660
+ }
661
+ parseDirectives();
662
+ values.push(valName);
663
+ }
664
+ expectPunct("}");
665
+ return values;
666
+ };
667
+ const types = {};
668
+ let defsCount = 0;
669
+ let hasStructuralDef = false;
670
+ let hasExplicitSchema = false;
671
+ let queryRoot = null;
672
+ let mutationRoot = null;
673
+ let subscriptionRoot = null;
674
+ while (peek().kind !== "EOF") {
675
+ const description = parseOptionalDescription();
676
+ const isExtend = peek().kind === "NAME" && peek().value === "extend";
677
+ if (isExtend) {
678
+ next();
679
+ }
680
+ const kwTok = peek();
681
+ if (kwTok.kind !== "NAME") {
682
+ fail(`expected GraphQL definition keyword, got '${kwTok.value || "EOF"}'`, kwTok);
683
+ }
684
+ const kw = kwTok.value;
685
+ next();
686
+ defsCount += 1;
687
+ if (kw === "schema") {
688
+ if (!isExtend)
689
+ hasExplicitSchema = true;
690
+ const dirCount = parseDirectives();
691
+ if (peek().kind === "PUNCT" && peek().value === "{") {
692
+ hasStructuralDef = true;
693
+ expectPunct("{");
694
+ while (!(peek().kind === "PUNCT" && peek().value === "}")) {
695
+ if (peek().kind === "EOF")
696
+ fail("unterminated schema block");
697
+ const opType = expectName("operation type");
698
+ expectPunct(":");
699
+ const rootName = expectName("root type name");
700
+ if (opType === "query")
701
+ queryRoot = rootName;
702
+ else if (opType === "mutation")
703
+ mutationRoot = rootName;
704
+ else if (opType === "subscription")
705
+ subscriptionRoot = rootName;
706
+ else
707
+ fail(`unknown schema operation type '${opType}'`);
708
+ }
709
+ expectPunct("}");
710
+ }
711
+ else if (!isExtend) {
712
+ fail("schema definition must have a '{ ... }' block");
713
+ }
714
+ else if (dirCount > 0) {
715
+ hasStructuralDef = true;
716
+ }
717
+ continue;
718
+ }
719
+ if (kw === "scalar") {
720
+ const name = expectName("scalar name");
721
+ const dirCount = parseDirectives();
722
+ if (dirCount > 0 || /^[A-Z]/.test(name)) {
723
+ hasStructuralDef = true;
724
+ }
725
+ const existing = types[name];
726
+ if (!existing) {
727
+ types[name] = {
728
+ kind: "SCALAR",
729
+ name,
730
+ ...(description !== undefined ? { description } : {})
731
+ };
732
+ }
733
+ continue;
734
+ }
735
+ if (kw === "type") {
736
+ const name = expectName("object type name");
737
+ const interfaces = parseImplements();
738
+ const dirCount = parseDirectives();
739
+ const hasBrace = peek().kind === "PUNCT" && peek().value === "{";
740
+ const fields = hasBrace ? parseFieldsBlock() : [];
741
+ if (hasBrace || interfaces.length > 0 || dirCount > 0) {
742
+ hasStructuralDef = true;
743
+ }
744
+ const existing = types[name];
745
+ if (existing && existing.kind !== "OBJECT") {
746
+ fail(`cannot redefine ${existing.kind} '${name}' as OBJECT`);
747
+ }
748
+ types[name] = {
749
+ kind: "OBJECT",
750
+ name,
751
+ ...(description !== undefined ? { description } : existing?.description ? { description: existing.description } : {}),
752
+ fields: mergeFields(existing?.fields, fields),
753
+ ...(interfaces.length > 0 || existing?.interfaces?.length
754
+ ? { interfaces: mergeUniqueStrings(existing?.interfaces, interfaces) }
755
+ : {})
756
+ };
757
+ continue;
758
+ }
759
+ if (kw === "interface") {
760
+ const name = expectName("interface name");
761
+ const interfaces = parseImplements();
762
+ const dirCount = parseDirectives();
763
+ const hasBrace = peek().kind === "PUNCT" && peek().value === "{";
764
+ const fields = hasBrace ? parseFieldsBlock() : [];
765
+ if (hasBrace || interfaces.length > 0 || dirCount > 0) {
766
+ hasStructuralDef = true;
767
+ }
768
+ const existing = types[name];
769
+ if (existing && existing.kind !== "INTERFACE") {
770
+ fail(`cannot redefine ${existing.kind} '${name}' as INTERFACE`);
771
+ }
772
+ types[name] = {
773
+ kind: "INTERFACE",
774
+ name,
775
+ ...(description !== undefined ? { description } : existing?.description ? { description: existing.description } : {}),
776
+ fields: mergeFields(existing?.fields, fields),
777
+ ...(interfaces.length > 0 || existing?.interfaces?.length
778
+ ? { interfaces: mergeUniqueStrings(existing?.interfaces, interfaces) }
779
+ : {})
780
+ };
781
+ continue;
782
+ }
783
+ if (kw === "input") {
784
+ const name = expectName("input type name");
785
+ const dirCount = parseDirectives();
786
+ const hasBrace = peek().kind === "PUNCT" && peek().value === "{";
787
+ const inputFields = hasBrace ? parseInputFieldsBlock() : [];
788
+ if (hasBrace || dirCount > 0) {
789
+ hasStructuralDef = true;
790
+ }
791
+ const existing = types[name];
792
+ if (existing && existing.kind !== "INPUT_OBJECT") {
793
+ fail(`cannot redefine ${existing.kind} '${name}' as INPUT_OBJECT`);
794
+ }
795
+ types[name] = {
796
+ kind: "INPUT_OBJECT",
797
+ name,
798
+ ...(description !== undefined ? { description } : existing?.description ? { description: existing.description } : {}),
799
+ inputFields: mergeInputFields(existing?.inputFields, inputFields)
800
+ };
801
+ continue;
802
+ }
803
+ if (kw === "enum") {
804
+ const name = expectName("enum name");
805
+ const dirCount = parseDirectives();
806
+ const hasBrace = peek().kind === "PUNCT" && peek().value === "{";
807
+ const enumValues = hasBrace ? parseEnumValuesBlock() : [];
808
+ if (hasBrace || dirCount > 0) {
809
+ hasStructuralDef = true;
810
+ }
811
+ const existing = types[name];
812
+ if (existing && existing.kind !== "ENUM") {
813
+ fail(`cannot redefine ${existing.kind} '${name}' as ENUM`);
814
+ }
815
+ types[name] = {
816
+ kind: "ENUM",
817
+ name,
818
+ ...(description !== undefined ? { description } : existing?.description ? { description: existing.description } : {}),
819
+ enumValues: mergeUniqueStrings(existing?.enumValues, enumValues)
820
+ };
821
+ continue;
822
+ }
823
+ if (kw === "union") {
824
+ const name = expectName("union name");
825
+ const dirCount = parseDirectives();
826
+ const members = [];
827
+ const hasEq = matchPunct("=");
828
+ if (hasEq) {
829
+ matchPunct("|");
830
+ members.push(expectName("union member type"));
831
+ while (matchPunct("|")) {
832
+ members.push(expectName("union member type"));
833
+ }
834
+ }
835
+ if (hasEq || dirCount > 0) {
836
+ hasStructuralDef = true;
837
+ }
838
+ const existing = types[name];
839
+ if (existing && existing.kind !== "UNION") {
840
+ fail(`cannot redefine ${existing.kind} '${name}' as UNION`);
841
+ }
842
+ types[name] = {
843
+ kind: "UNION",
844
+ name,
845
+ ...(description !== undefined ? { description } : existing?.description ? { description: existing.description } : {}),
846
+ possibleTypes: mergeUniqueStrings(existing?.possibleTypes, members)
847
+ };
848
+ continue;
849
+ }
850
+ if (kw === "directive" && !isExtend) {
851
+ hasStructuralDef = true;
852
+ expectPunct("@");
853
+ expectName("directive name");
854
+ parseArgumentsDef();
855
+ if (peek().kind === "NAME" && peek().value === "repeatable") {
856
+ next();
857
+ }
858
+ expectKeyword("on");
859
+ matchPunct("|");
860
+ expectName("directive location");
861
+ while (matchPunct("|")) {
862
+ expectName("directive location");
863
+ }
864
+ continue;
865
+ }
866
+ fail(`unexpected GraphQL top-level keyword '${kw}'`, kwTok);
867
+ }
868
+ return {
869
+ defsCount,
870
+ hasStructuralDef,
871
+ hasExplicitSchema,
872
+ queryRoot,
873
+ mutationRoot,
874
+ subscriptionRoot,
875
+ types
876
+ };
877
+ }
878
+ function extractIntrospectionSchemaObj(doc) {
879
+ if (!isObject(doc))
880
+ return null;
881
+ if (isObject(doc.__schema))
882
+ return doc.__schema;
883
+ if (isObject(doc.data) && isObject(doc.data.__schema))
884
+ return doc.data.__schema;
885
+ return null;
886
+ }
887
+ export function isGraphqlIntrospectionDoc(doc) {
888
+ const schemaObj = extractIntrospectionSchemaObj(doc);
889
+ if (!schemaObj || !Array.isArray(schemaObj.types))
890
+ return false;
891
+ if (schemaObj.types.length === 0)
892
+ return true;
893
+ return schemaObj.types.every((entry) => isObject(entry) && (typeof entry.name === "string" || typeof entry.kind === "string"));
894
+ }
895
+ export function isGraphqlSchemaText(text) {
896
+ if (typeof text !== "string")
897
+ return false;
898
+ const cleaned = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
899
+ const trimmed = cleaned.trim();
900
+ if (!trimmed)
901
+ return false;
902
+ // Reject JSON objects/arrays and HTML/XML documents immediately
903
+ const first = trimmed[0];
904
+ if (first === "{" || first === "[" || first === "<")
905
+ return false;
906
+ try {
907
+ const parsed = parseSdlDefinitions(trimmed);
908
+ return parsed.defsCount > 0 && parsed.hasStructuralDef;
909
+ }
910
+ catch {
911
+ return false;
912
+ }
913
+ }
914
+ function convertIntrospectionTypeRef(raw, depth = 0) {
915
+ if (depth > MAX_TYPE_REF_DEPTH || !isObject(raw)) {
916
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "Malformed GraphQL introspection type reference");
917
+ }
918
+ const kind = typeof raw.kind === "string" ? raw.kind : "";
919
+ if (kind === "NON_NULL") {
920
+ return { kind: "NON_NULL", ofType: convertIntrospectionTypeRef(raw.ofType, depth + 1) };
921
+ }
922
+ if (kind === "LIST") {
923
+ return { kind: "LIST", ofType: convertIntrospectionTypeRef(raw.ofType, depth + 1) };
924
+ }
925
+ if (typeof raw.name !== "string" || !raw.name) {
926
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Malformed GraphQL introspection named type (kind=${kind || "unknown"})`);
927
+ }
928
+ return { kind: "NAMED", name: raw.name };
929
+ }
930
+ function parseIntrospectionInputValue(raw) {
931
+ if (!isObject(raw) || typeof raw.name !== "string" || !raw.name)
932
+ return null;
933
+ const type = convertIntrospectionTypeRef(raw.type);
934
+ const defaultValue = typeof raw.defaultValue === "string" ? raw.defaultValue : undefined;
935
+ const description = typeof raw.description === "string" ? raw.description : undefined;
936
+ return {
937
+ name: raw.name,
938
+ type,
939
+ required: type.kind === "NON_NULL" && defaultValue === undefined,
940
+ ...(defaultValue !== undefined ? { defaultValue } : {}),
941
+ ...(description !== undefined ? { description } : {})
942
+ };
943
+ }
944
+ function parseIntrospectionField(raw) {
945
+ if (!isObject(raw) || typeof raw.name !== "string" || !raw.name)
946
+ return null;
947
+ const type = convertIntrospectionTypeRef(raw.type);
948
+ const rawArgs = Array.isArray(raw.args) ? raw.args : [];
949
+ const args = [];
950
+ for (const rawArg of rawArgs) {
951
+ const parsedArg = parseIntrospectionInputValue(rawArg);
952
+ if (parsedArg)
953
+ args.push(parsedArg);
954
+ }
955
+ const description = typeof raw.description === "string" ? raw.description : undefined;
956
+ return {
957
+ name: raw.name,
958
+ args,
959
+ type,
960
+ ...(description !== undefined ? { description } : {})
961
+ };
962
+ }
963
+ function finalizeParsedSchema(types, roots) {
964
+ const queryRootName = roots.queryRoot ?? (!roots.hasExplicitSchema ? "Query" : null);
965
+ const mutationRootName = roots.mutationRoot ?? (!roots.hasExplicitSchema && types["Mutation"]?.kind === "OBJECT" ? "Mutation" : null);
966
+ const subscriptionRootName = roots.subscriptionRoot ??
967
+ (!roots.hasExplicitSchema && types["Subscription"]?.kind === "OBJECT" ? "Subscription" : null);
968
+ if (!queryRootName) {
969
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "GraphQL schema does not define a Query root type");
970
+ }
971
+ const queryType = types[queryRootName];
972
+ if (!queryType || queryType.kind !== "OBJECT") {
973
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `GraphQL Query root type '${queryRootName}' was not found as an OBJECT type`);
974
+ }
975
+ const queries = (queryType.fields || []).filter((f) => !f.name.startsWith("__"));
976
+ if (queries.length === 0) {
977
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `GraphQL Query root '${queryRootName}' contains no queryable fields`);
978
+ }
979
+ const mutationType = mutationRootName ? types[mutationRootName] : undefined;
980
+ const mutations = mutationType && mutationType.kind === "OBJECT"
981
+ ? (mutationType.fields || []).filter((f) => !f.name.startsWith("__"))
982
+ : [];
983
+ const subscriptionType = subscriptionRootName ? types[subscriptionRootName] : undefined;
984
+ const subscriptions = subscriptionType && subscriptionType.kind === "OBJECT"
985
+ ? (subscriptionType.fields || []).filter((f) => !f.name.startsWith("__"))
986
+ : [];
987
+ const scalars = [];
988
+ const enums = {};
989
+ const inputs = {};
990
+ const unions = {};
991
+ const interfaces = {};
992
+ for (const [name, def] of Object.entries(types)) {
993
+ if (name.startsWith("__"))
994
+ continue;
995
+ if (def.kind === "SCALAR") {
996
+ scalars.push(name);
997
+ }
998
+ else if (def.kind === "ENUM") {
999
+ enums[name] = (def.enumValues || []).slice();
1000
+ }
1001
+ else if (def.kind === "INPUT_OBJECT") {
1002
+ inputs[name] = (def.inputFields || []).slice();
1003
+ }
1004
+ else if (def.kind === "UNION") {
1005
+ unions[name] = (def.possibleTypes || []).slice();
1006
+ }
1007
+ else if (def.kind === "INTERFACE") {
1008
+ interfaces[name] = (def.fields || []).filter((f) => !f.name.startsWith("__"));
1009
+ }
1010
+ }
1011
+ return {
1012
+ queryRoot: queryRootName,
1013
+ mutationRoot: mutationType && mutationType.kind === "OBJECT" ? mutationRootName : null,
1014
+ subscriptionRoot: subscriptionType && subscriptionType.kind === "OBJECT" ? subscriptionRootName : null,
1015
+ queries,
1016
+ mutations,
1017
+ subscriptions,
1018
+ skippedMutationCount: mutations.length,
1019
+ skippedSubscriptionCount: subscriptions.length,
1020
+ types,
1021
+ scalars,
1022
+ enums,
1023
+ inputs,
1024
+ unions,
1025
+ interfaces
1026
+ };
1027
+ }
1028
+ function parseIntrospectionSchema(doc) {
1029
+ if (!isGraphqlIntrospectionDoc(doc)) {
1030
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "Object is not a valid GraphQL introspection document");
1031
+ }
1032
+ const schemaObj = extractIntrospectionSchemaObj(doc);
1033
+ const rawTypes = schemaObj.types;
1034
+ const types = {};
1035
+ for (const rawType of rawTypes) {
1036
+ if (!isObject(rawType))
1037
+ continue;
1038
+ const name = typeof rawType.name === "string" ? rawType.name : "";
1039
+ const kind = typeof rawType.kind === "string" ? rawType.kind : "";
1040
+ if (!name || name.startsWith("__"))
1041
+ continue;
1042
+ const description = typeof rawType.description === "string" ? rawType.description : undefined;
1043
+ if (kind === "OBJECT" || kind === "INTERFACE") {
1044
+ const rawFields = Array.isArray(rawType.fields) ? rawType.fields : [];
1045
+ const fields = [];
1046
+ for (const rf of rawFields) {
1047
+ const parsedField = parseIntrospectionField(rf);
1048
+ if (parsedField)
1049
+ fields.push(parsedField);
1050
+ }
1051
+ const rawIfaces = Array.isArray(rawType.interfaces) ? rawType.interfaces : [];
1052
+ const ifaceNames = rawIfaces
1053
+ .filter((x) => isObject(x) && typeof x.name === "string" && x.name.length > 0)
1054
+ .map((x) => x.name);
1055
+ types[name] = {
1056
+ kind,
1057
+ name,
1058
+ ...(description !== undefined ? { description } : {}),
1059
+ fields,
1060
+ ...(ifaceNames.length > 0 ? { interfaces: ifaceNames } : {})
1061
+ };
1062
+ }
1063
+ else if (kind === "INPUT_OBJECT") {
1064
+ const rawInputFields = Array.isArray(rawType.inputFields) ? rawType.inputFields : [];
1065
+ const inputFields = [];
1066
+ for (const rif of rawInputFields) {
1067
+ const parsedField = parseIntrospectionInputValue(rif);
1068
+ if (parsedField)
1069
+ inputFields.push(parsedField);
1070
+ }
1071
+ types[name] = {
1072
+ kind: "INPUT_OBJECT",
1073
+ name,
1074
+ ...(description !== undefined ? { description } : {}),
1075
+ inputFields
1076
+ };
1077
+ }
1078
+ else if (kind === "ENUM") {
1079
+ const rawVals = Array.isArray(rawType.enumValues) ? rawType.enumValues : [];
1080
+ const enumValues = rawVals
1081
+ .filter((v) => isObject(v) && typeof v.name === "string" && v.name.length > 0)
1082
+ .map((v) => v.name);
1083
+ types[name] = {
1084
+ kind: "ENUM",
1085
+ name,
1086
+ ...(description !== undefined ? { description } : {}),
1087
+ enumValues
1088
+ };
1089
+ }
1090
+ else if (kind === "UNION") {
1091
+ const rawPossible = Array.isArray(rawType.possibleTypes) ? rawType.possibleTypes : [];
1092
+ const possibleTypes = rawPossible
1093
+ .filter((v) => isObject(v) && typeof v.name === "string" && v.name.length > 0)
1094
+ .map((v) => v.name);
1095
+ types[name] = {
1096
+ kind: "UNION",
1097
+ name,
1098
+ ...(description !== undefined ? { description } : {}),
1099
+ possibleTypes
1100
+ };
1101
+ }
1102
+ else if (kind === "SCALAR") {
1103
+ types[name] = {
1104
+ kind: "SCALAR",
1105
+ name,
1106
+ ...(description !== undefined ? { description } : {})
1107
+ };
1108
+ }
1109
+ }
1110
+ const hasQueryTypeKey = Object.prototype.hasOwnProperty.call(schemaObj, "queryType");
1111
+ const queryRoot = isObject(schemaObj.queryType) && typeof schemaObj.queryType.name === "string" && schemaObj.queryType.name
1112
+ ? schemaObj.queryType.name
1113
+ : hasQueryTypeKey
1114
+ ? null
1115
+ : "Query";
1116
+ const mutationRoot = isObject(schemaObj.mutationType) && typeof schemaObj.mutationType.name === "string" && schemaObj.mutationType.name
1117
+ ? schemaObj.mutationType.name
1118
+ : null;
1119
+ const subscriptionRoot = isObject(schemaObj.subscriptionType) &&
1120
+ typeof schemaObj.subscriptionType.name === "string" &&
1121
+ schemaObj.subscriptionType.name
1122
+ ? schemaObj.subscriptionType.name
1123
+ : null;
1124
+ return finalizeParsedSchema(types, {
1125
+ hasExplicitSchema: hasQueryTypeKey,
1126
+ queryRoot,
1127
+ mutationRoot,
1128
+ subscriptionRoot
1129
+ });
1130
+ }
1131
+ export function parseGraphqlSchema(input) {
1132
+ if (isObject(input)) {
1133
+ return parseIntrospectionSchema(input);
1134
+ }
1135
+ if (typeof input !== "string") {
1136
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "GraphQL schema input must be an SDL string or introspection JSON object");
1137
+ }
1138
+ const cleaned = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input;
1139
+ const trimmed = cleaned.trim();
1140
+ if (!trimmed) {
1141
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "GraphQL schema input is empty");
1142
+ }
1143
+ if (trimmed.startsWith("{")) {
1144
+ let parsedJson;
1145
+ try {
1146
+ parsedJson = JSON.parse(trimmed);
1147
+ }
1148
+ catch (err) {
1149
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Malformed JSON in GraphQL input: ${errorMessage(err)}`);
1150
+ }
1151
+ if (!isObject(parsedJson) || !isGraphqlIntrospectionDoc(parsedJson)) {
1152
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "JSON input is not a valid GraphQL introspection document");
1153
+ }
1154
+ return parseIntrospectionSchema(parsedJson);
1155
+ }
1156
+ const sdl = parseSdlDefinitions(trimmed);
1157
+ if (sdl.defsCount === 0) {
1158
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", "No GraphQL SDL definitions found");
1159
+ }
1160
+ return finalizeParsedSchema(sdl.types, {
1161
+ hasExplicitSchema: sdl.hasExplicitSchema,
1162
+ queryRoot: sdl.queryRoot,
1163
+ mutationRoot: sdl.mutationRoot,
1164
+ subscriptionRoot: sdl.subscriptionRoot
1165
+ });
1166
+ }
1167
+ function unwrapNamedType(ref) {
1168
+ let cur = ref;
1169
+ let guard = 0;
1170
+ while (cur && guard < MAX_TYPE_REF_DEPTH) {
1171
+ if (cur.kind === "NAMED")
1172
+ return cur.name || "String";
1173
+ cur = cur.ofType;
1174
+ guard += 1;
1175
+ }
1176
+ return "String";
1177
+ }
1178
+ function isLeafTypeName(typeName, schema) {
1179
+ if (BUILTIN_SCALARS.has(typeName))
1180
+ return true;
1181
+ const def = schema.types[typeName];
1182
+ if (!def)
1183
+ return true;
1184
+ return def.kind === "SCALAR" || def.kind === "ENUM";
1185
+ }
1186
+ function synthesizeGraphqlValue(typeRef, schema, visitedInputs = new Set()) {
1187
+ if (typeRef.kind === "NON_NULL" && typeRef.ofType) {
1188
+ return synthesizeGraphqlValue(typeRef.ofType, schema, visitedInputs);
1189
+ }
1190
+ if (typeRef.kind === "LIST" && typeRef.ofType) {
1191
+ return `[${synthesizeGraphqlValue(typeRef.ofType, schema, visitedInputs)}]`;
1192
+ }
1193
+ const name = typeRef.name || "String";
1194
+ if (name === "ID" || name === "String")
1195
+ return '"sample"';
1196
+ if (name === "Int")
1197
+ return "1";
1198
+ if (name === "Float")
1199
+ return "1.5";
1200
+ if (name === "Boolean")
1201
+ return "true";
1202
+ const def = schema.types[name];
1203
+ if (!def)
1204
+ return '"sample"';
1205
+ if (def.kind === "ENUM") {
1206
+ const firstVal = def.enumValues?.[0];
1207
+ return firstVal || "SAMPLE";
1208
+ }
1209
+ if (def.kind === "INPUT_OBJECT") {
1210
+ if (visitedInputs.has(name))
1211
+ return "{}";
1212
+ const nextVisited = new Set(visitedInputs);
1213
+ nextVisited.add(name);
1214
+ const parts = [];
1215
+ for (const field of def.inputFields || []) {
1216
+ if (!field.required)
1217
+ continue;
1218
+ const val = synthesizeGraphqlValue(field.type, schema, nextVisited);
1219
+ parts.push(`${field.name}: ${val}`);
1220
+ }
1221
+ return parts.length > 0 ? `{ ${parts.join(", ")} }` : "{}";
1222
+ }
1223
+ return '"sample"';
1224
+ }
1225
+ function formatRequiredFieldArgs(args, schema) {
1226
+ const requiredArgs = args.filter((a) => a.required);
1227
+ if (requiredArgs.length === 0)
1228
+ return "";
1229
+ const rendered = requiredArgs.map((arg) => `${arg.name}: ${synthesizeGraphqlValue(arg.type, schema)}`);
1230
+ return `(${rendered.join(", ")})`;
1231
+ }
1232
+ const TYPENAME_NODE = {
1233
+ name: "__typename",
1234
+ argsText: "",
1235
+ type: { kind: "NON_NULL", ofType: { kind: "NAMED", name: "String" } }
1236
+ };
1237
+ function buildSelectionNodes(typeRef, schema, depth, visitedTypes) {
1238
+ const typeName = unwrapNamedType(typeRef);
1239
+ if (isLeafTypeName(typeName, schema)) {
1240
+ return undefined;
1241
+ }
1242
+ const def = schema.types[typeName];
1243
+ if (!def)
1244
+ return undefined;
1245
+ if (def.kind === "UNION") {
1246
+ return [TYPENAME_NODE];
1247
+ }
1248
+ if (def.kind !== "OBJECT" && def.kind !== "INTERFACE") {
1249
+ return undefined;
1250
+ }
1251
+ if (visitedTypes.has(typeName) || depth > MAX_SELECTION_DEPTH) {
1252
+ return [TYPENAME_NODE];
1253
+ }
1254
+ const nextVisited = new Set(visitedTypes);
1255
+ nextVisited.add(typeName);
1256
+ const fields = (def.fields || []).filter((f) => !f.name.startsWith("__"));
1257
+ const selected = [];
1258
+ // Pass 1: scalar and enum leaf fields
1259
+ for (const field of fields) {
1260
+ if (selected.length >= MAX_SELECTED_FIELDS_PER_TYPE)
1261
+ break;
1262
+ const targetName = unwrapNamedType(field.type);
1263
+ if (!isLeafTypeName(targetName, schema))
1264
+ continue;
1265
+ selected.push({
1266
+ name: field.name,
1267
+ argsText: formatRequiredFieldArgs(field.args, schema),
1268
+ type: field.type
1269
+ });
1270
+ }
1271
+ // Pass 2: nested object / interface / union fields up to MAX_SELECTION_DEPTH
1272
+ if (depth < MAX_SELECTION_DEPTH) {
1273
+ for (const field of fields) {
1274
+ if (selected.length >= MAX_SELECTED_FIELDS_PER_TYPE)
1275
+ break;
1276
+ const targetName = unwrapNamedType(field.type);
1277
+ if (isLeafTypeName(targetName, schema))
1278
+ continue;
1279
+ if (nextVisited.has(targetName))
1280
+ continue;
1281
+ const subChildren = buildSelectionNodes(field.type, schema, depth + 1, nextVisited);
1282
+ if (!subChildren || subChildren.length === 0)
1283
+ continue;
1284
+ selected.push({
1285
+ name: field.name,
1286
+ argsText: formatRequiredFieldArgs(field.args, schema),
1287
+ type: field.type,
1288
+ children: subChildren
1289
+ });
1290
+ }
1291
+ }
1292
+ // Fallback for interfaces / pure-cycle objects / objects with no selectable scalar leaves
1293
+ if (selected.length === 0) {
1294
+ return [TYPENAME_NODE];
1295
+ }
1296
+ return selected;
1297
+ }
1298
+ function renderSelectionNode(node) {
1299
+ if (!node.children || node.children.length === 0) {
1300
+ return `${node.name}${node.argsText}`;
1301
+ }
1302
+ return `${node.name}${node.argsText} { ${node.children.map(renderSelectionNode).join(" ")} }`;
1303
+ }
1304
+ function synthesizeOperationDocument(operationKind, field, schema) {
1305
+ const children = buildSelectionNodes(field.type, schema, 1, new Set());
1306
+ const rootNode = {
1307
+ name: field.name,
1308
+ argsText: formatRequiredFieldArgs(field.args, schema),
1309
+ type: field.type,
1310
+ ...(children ? { children } : {})
1311
+ };
1312
+ const query = `${operationKind} { ${renderSelectionNode(rootNode)} }`;
1313
+ return { query, rootNode };
1314
+ }
1315
+ function buildFieldJsonSchema(typeRef, children, schema, depth = 0) {
1316
+ if (depth >= MAX_TYPE_REF_DEPTH)
1317
+ return {};
1318
+ const isNonNull = typeRef.kind === "NON_NULL";
1319
+ const inner = isNonNull && typeRef.ofType ? typeRef.ofType : typeRef;
1320
+ if (inner.kind === "LIST" && inner.ofType) {
1321
+ return {
1322
+ type: isNonNull ? "array" : ["array", "null"],
1323
+ items: buildFieldJsonSchema(inner.ofType, children, schema, depth + 1)
1324
+ };
1325
+ }
1326
+ const name = inner.name || "String";
1327
+ if (name === "String" || name === "ID") {
1328
+ return { type: isNonNull ? "string" : ["string", "null"] };
1329
+ }
1330
+ if (name === "Int") {
1331
+ return { type: isNonNull ? "integer" : ["integer", "null"] };
1332
+ }
1333
+ if (name === "Float") {
1334
+ return { type: isNonNull ? "number" : ["number", "null"] };
1335
+ }
1336
+ if (name === "Boolean") {
1337
+ return { type: isNonNull ? "boolean" : ["boolean", "null"] };
1338
+ }
1339
+ const def = schema.types[name];
1340
+ if (def?.kind === "ENUM") {
1341
+ const vals = def.enumValues || [];
1342
+ if (vals.length > 0) {
1343
+ return isNonNull
1344
+ ? { type: "string", enum: [...vals] }
1345
+ : { type: ["string", "null"], enum: [...vals, null] };
1346
+ }
1347
+ return { type: isNonNull ? "string" : ["string", "null"] };
1348
+ }
1349
+ if (children && children.length > 0) {
1350
+ const properties = {};
1351
+ const required = [];
1352
+ for (const child of children) {
1353
+ properties[child.name] = buildFieldJsonSchema(child.type, child.children, schema, depth + 1);
1354
+ if (child.type.kind === "NON_NULL") {
1355
+ required.push(child.name);
1356
+ }
1357
+ }
1358
+ return {
1359
+ type: isNonNull ? "object" : ["object", "null"],
1360
+ ...(required.length > 0 ? { required } : {}),
1361
+ properties
1362
+ };
1363
+ }
1364
+ if (def?.kind === "OBJECT" || def?.kind === "INTERFACE" || def?.kind === "UNION") {
1365
+ return { type: isNonNull ? "object" : ["object", "null"] };
1366
+ }
1367
+ // Custom scalar
1368
+ return isNonNull ? { type: ["string", "number", "boolean", "object", "array"] } : {};
1369
+ }
1370
+ function buildResponseJsonSchema(rootNode, schema) {
1371
+ return {
1372
+ type: "object",
1373
+ required: ["data"],
1374
+ properties: {
1375
+ data: {
1376
+ type: "object",
1377
+ required: [rootNode.name],
1378
+ properties: {
1379
+ [rootNode.name]: buildFieldJsonSchema(rootNode.type, rootNode.children, schema)
1380
+ }
1381
+ },
1382
+ // Reject non-null `errors` payloads via validateJsonSchema's property check when present
1383
+ errors: { type: "null" }
1384
+ }
1385
+ };
1386
+ }
1387
+ function observedJsonType(value) {
1388
+ if (value === null)
1389
+ return "null";
1390
+ if (Array.isArray(value))
1391
+ return "array";
1392
+ if (isObject(value))
1393
+ return "object";
1394
+ if (typeof value === "number")
1395
+ return Number.isInteger(value) ? "integer" : "number";
1396
+ if (typeof value === "string" || typeof value === "boolean")
1397
+ return typeof value;
1398
+ return null;
1399
+ }
1400
+ function refineJsonSchemaWithObserved(schema, observed, depth = 0) {
1401
+ if (depth >= 16 || observed === undefined)
1402
+ return schema;
1403
+ // Tighten unconstrained custom scalar schemas using the observed non-null type
1404
+ const isCustomNonNullScalar = Array.isArray(schema.type) &&
1405
+ schema.type.length >= 4 &&
1406
+ !schema.properties &&
1407
+ !schema.items &&
1408
+ !schema.enum;
1409
+ const isUnconstrainedScalar = schema.type === undefined && !schema.properties && !schema.items && !schema.enum;
1410
+ if (isCustomNonNullScalar || isUnconstrainedScalar) {
1411
+ const obsType = observedJsonType(observed);
1412
+ if (obsType && obsType !== "null") {
1413
+ return isCustomNonNullScalar ? { type: obsType } : { type: [obsType, "null"] };
1414
+ }
1415
+ return schema;
1416
+ }
1417
+ if (Array.isArray(observed) && isObject(schema.items) && observed.length > 0) {
1418
+ const firstNonNull = observed.find((item) => item !== null && item !== undefined);
1419
+ if (firstNonNull !== undefined) {
1420
+ return {
1421
+ ...schema,
1422
+ items: refineJsonSchemaWithObserved(schema.items, firstNonNull, depth + 1)
1423
+ };
1424
+ }
1425
+ return schema;
1426
+ }
1427
+ if (isObject(observed) && isObject(schema.properties)) {
1428
+ const refinedProps = {};
1429
+ for (const [k, propSchema] of Object.entries(schema.properties)) {
1430
+ if (k in observed) {
1431
+ refinedProps[k] = refineJsonSchemaWithObserved(propSchema, observed[k], depth + 1);
1432
+ }
1433
+ else {
1434
+ refinedProps[k] = propSchema;
1435
+ }
1436
+ }
1437
+ return { ...schema, properties: refinedProps };
1438
+ }
1439
+ return schema;
1440
+ }
1441
+ function parseAndSanitizeBaseUrl(rawBase) {
1442
+ const trimmed = rawBase.trim();
1443
+ if (!trimmed)
1444
+ return null;
1445
+ let u;
1446
+ try {
1447
+ const normalized = /^https?:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
1448
+ u = new URL(normalized);
1449
+ }
1450
+ catch {
1451
+ return null;
1452
+ }
1453
+ if (u.protocol !== "http:" && u.protocol !== "https:")
1454
+ return null;
1455
+ let redactedSecrets = false;
1456
+ let ephemeralBasicAuth = null;
1457
+ const secretValues = [];
1458
+ if (u.username || u.password) {
1459
+ redactedSecrets = true;
1460
+ if (u.username)
1461
+ secretValues.push(u.username);
1462
+ if (u.password)
1463
+ secretValues.push(u.password);
1464
+ try {
1465
+ const decUser = decodeURIComponent(u.username);
1466
+ const decPass = decodeURIComponent(u.password);
1467
+ if (decUser)
1468
+ secretValues.push(decUser);
1469
+ if (decPass)
1470
+ secretValues.push(decPass);
1471
+ ephemeralBasicAuth = `${decUser}:${decPass}`;
1472
+ }
1473
+ catch {
1474
+ ephemeralBasicAuth = `${u.username}:${u.password}`;
1475
+ }
1476
+ u.username = "";
1477
+ u.password = "";
1478
+ }
1479
+ const safeParams = new URLSearchParams();
1480
+ for (const [k, v] of u.searchParams.entries()) {
1481
+ if (isSensitiveQueryParam(k)) {
1482
+ redactedSecrets = true;
1483
+ if (v)
1484
+ secretValues.push(v);
1485
+ continue;
1486
+ }
1487
+ safeParams.append(k, v);
1488
+ }
1489
+ const rawPathname = u.pathname || "/";
1490
+ const trimmedPath = rawPathname.length > 1 ? rawPathname.replace(/\/+$/, "") : rawPathname;
1491
+ const endpointPath = trimmedPath && trimmedPath !== "/" ? trimmedPath : "/graphql";
1492
+ const safeQuery = safeParams.toString();
1493
+ const safeBaseUrl = `${u.origin}${trimmedPath === "/" ? "" : trimmedPath}${safeQuery ? `?${safeQuery}` : ""}`;
1494
+ const probeUrl = `${u.origin}${endpointPath}${safeQuery ? `?${safeQuery}` : ""}`;
1495
+ return {
1496
+ safeBaseUrl,
1497
+ endpointPath,
1498
+ probeUrl,
1499
+ ephemeralBasicAuth,
1500
+ redactedSecrets,
1501
+ secretValues
1502
+ };
1503
+ }
1504
+ function scrubSecretsFromText(text, rawBaseUrl, safeBaseUrl, secretValues = []) {
1505
+ let out = text;
1506
+ if (rawBaseUrl && safeBaseUrl && rawBaseUrl !== safeBaseUrl) {
1507
+ out = out.split(rawBaseUrl).join(safeBaseUrl);
1508
+ }
1509
+ // Redact any `scheme://user:pass@host` credentials
1510
+ out = out.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1[REDACTED]@");
1511
+ // Redact sensitive URL query params (`?api_key=...`, `&token=...`)
1512
+ out = out.replace(/([?&])([^=&\s#]+)=([^&\s#]+)/g, (match, sep, key) => isSensitiveQueryParam(key) ? `${sep}${key}=[REDACTED]` : match);
1513
+ // Redact any known secret values from baseUrl or sensitive headers
1514
+ for (const secret of secretValues) {
1515
+ if (secret && secret.length >= 3) {
1516
+ out = out.split(secret).join("[REDACTED]");
1517
+ }
1518
+ }
1519
+ return out;
1520
+ }
1521
+ async function fetchJson(url, { method = "POST", headers = {}, body, timeoutMs = DEFAULT_PROBE_TIMEOUT_MS } = {}) {
1522
+ const ctrl = new AbortController();
1523
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
1524
+ const serializedBody = body === undefined || body === null
1525
+ ? undefined
1526
+ : typeof body === "string"
1527
+ ? body
1528
+ : JSON.stringify(body);
1529
+ try {
1530
+ const res = await fetch(url, {
1531
+ method: method.toUpperCase(),
1532
+ headers,
1533
+ body: serializedBody,
1534
+ signal: ctrl.signal
1535
+ });
1536
+ const text = await res.text();
1537
+ let json = null;
1538
+ try {
1539
+ json = text ? JSON.parse(text) : null;
1540
+ }
1541
+ catch {
1542
+ // ignore non-JSON body
1543
+ }
1544
+ const headersObj = {};
1545
+ for (const [k, v] of res.headers.entries())
1546
+ headersObj[k.toLowerCase()] = v;
1547
+ return { status: res.status, headers: headersObj, text, json };
1548
+ }
1549
+ finally {
1550
+ clearTimeout(t);
1551
+ }
1552
+ }
1553
+ function slugify(text, fallback = "op") {
1554
+ const s = String(text || "")
1555
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
1556
+ .toLowerCase()
1557
+ .replace(/[^a-z0-9]+/g, "-")
1558
+ .replace(/^-+|-+$/g, "")
1559
+ .slice(0, 64);
1560
+ return s || fallback;
1561
+ }
1562
+ function uniqueId(base, used) {
1563
+ let id = slugify(base, "inv");
1564
+ if (!id.startsWith("inv-"))
1565
+ id = `inv-${id}`;
1566
+ if (!used.has(id)) {
1567
+ used.add(id);
1568
+ return id;
1569
+ }
1570
+ let n = 2;
1571
+ while (used.has(`${id}-${n}`))
1572
+ n += 1;
1573
+ const out = `${id}-${n}`;
1574
+ used.add(out);
1575
+ return out;
1576
+ }
1577
+ function validateInvariantsOrThrow(invariants) {
1578
+ const contract = {
1579
+ schemaVersion: "0.2.0",
1580
+ target: { name: "graphql", domains: ["api"], sources: [{ id: "src-1", kind: "graphql", ref: "inline", meta: {} }] },
1581
+ artifacts: { root: ".vibecode/artifacts", files: {} },
1582
+ thresholds: { hardBehavioralParity: 1, softPerceptualParity: 0.85, softGateMode: "warn", defaults: {} },
1583
+ invariants
1584
+ };
1585
+ const res = validateContract(contract);
1586
+ if (!res.ok) {
1587
+ const err = res.errors[0];
1588
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `GraphQL ingestor produced invalid invariant: ${err.path} ${err.message}`, { details: res.errors });
1589
+ }
1590
+ }
1591
+ function looksLikeGraphqlFilePath(trimmed) {
1592
+ if (/[\r\n{}]/.test(trimmed) || /\s/.test(trimmed))
1593
+ return false;
1594
+ const ext = path.extname(trimmed).toLowerCase();
1595
+ return ext === ".graphql" || ext === ".gql" || ext === ".json";
1596
+ }
1597
+ export async function ingestGraphql(options = {}, deps = {}) {
1598
+ if (typeof options.source !== "string" || !options.source.trim()) {
1599
+ throw new VibecodeError("TARGET_MISSING", "GraphQL ingestor requires --source <schema.graphql|introspection.json|sdl>");
1600
+ }
1601
+ const cwd = options.cwd || process.cwd();
1602
+ const rawSource = options.source;
1603
+ const trimmedSource = rawSource.trim();
1604
+ let rawText = "";
1605
+ let isFileSource = false;
1606
+ if (!/[\r\n]/.test(trimmedSource)) {
1607
+ const candidatePath = path.resolve(cwd, trimmedSource);
1608
+ let exists = false;
1609
+ try {
1610
+ exists = fs.existsSync(candidatePath);
1611
+ }
1612
+ catch {
1613
+ exists = false;
1614
+ }
1615
+ if (exists) {
1616
+ let stat;
1617
+ try {
1618
+ stat = fs.statSync(candidatePath);
1619
+ }
1620
+ catch (err) {
1621
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Failed to stat GraphQL source ${trimmedSource}: ${errorMessage(err)}`);
1622
+ }
1623
+ if (!stat.isFile()) {
1624
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `GraphQL source path is not a file: ${trimmedSource}`);
1625
+ }
1626
+ if (stat.size === 0) {
1627
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `GraphQL source file is empty: ${trimmedSource}`);
1628
+ }
1629
+ if (stat.size > MAX_SOURCE_BYTES) {
1630
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `GraphQL source file exceeds maximum size of ${MAX_SOURCE_BYTES} bytes: ${trimmedSource}`);
1631
+ }
1632
+ try {
1633
+ rawText = fs.readFileSync(candidatePath, "utf8");
1634
+ }
1635
+ catch (err) {
1636
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Failed to read GraphQL source ${trimmedSource}: ${errorMessage(err)}`);
1637
+ }
1638
+ isFileSource = true;
1639
+ }
1640
+ else if (looksLikeGraphqlFilePath(trimmedSource)) {
1641
+ throw new VibecodeError("TARGET_MISSING", `GraphQL schema file not found: ${trimmedSource}`);
1642
+ }
1643
+ }
1644
+ if (!isFileSource) {
1645
+ if (Buffer.byteLength(rawSource, "utf8") > MAX_SOURCE_BYTES) {
1646
+ throw new VibecodeError("BRIDGE_FORMAT_ERROR", `Inline GraphQL schema exceeds maximum size of ${MAX_SOURCE_BYTES} bytes`);
1647
+ }
1648
+ rawText = rawSource;
1649
+ }
1650
+ const parsed = parseGraphqlSchema(rawText);
1651
+ const includeMutating = options.includeMutating === true;
1652
+ const offline = options.offline === true;
1653
+ const rawBaseUrl = typeof options.baseUrl === "string" ? options.baseUrl.trim() : "";
1654
+ const parsedBase = rawBaseUrl ? parseAndSanitizeBaseUrl(rawBaseUrl) : null;
1655
+ const warnings = [];
1656
+ if (rawBaseUrl && !parsedBase) {
1657
+ warnings.push({
1658
+ code: "ADAPTER_DEGRADED",
1659
+ message: "Invalid GraphQL baseUrl provided; falling back to offline schema-derived expectations."
1660
+ });
1661
+ }
1662
+ const endpointPath = parsedBase?.endpointPath || "/graphql";
1663
+ const safeBaseUrl = parsedBase?.safeBaseUrl || "";
1664
+ let redactedSecrets = parsedBase?.redactedSecrets === true;
1665
+ const globalHeaders = isObject(options.headers) ? options.headers : undefined;
1666
+ const { safe: safeOptionHeaders, redacted: headersRedacted, secretValues: headerSecrets } = stripSensitiveHeaders(globalHeaders);
1667
+ if (headersRedacted)
1668
+ redactedSecrets = true;
1669
+ const allSecretValues = [...(parsedBase?.secretValues || []), ...headerSecrets];
1670
+ const persistedHeaders = { ...safeOptionHeaders };
1671
+ if (!hasHeaderCaseInsensitive(persistedHeaders, "content-type")) {
1672
+ setHeaderCaseInsensitive(persistedHeaders, "content-type", "application/json");
1673
+ }
1674
+ // Ephemeral runtime probe headers (NEVER persisted in invariants, sources, or warnings)
1675
+ const probeHeaders = mergeHeaders({ "content-type": "application/json" }, globalHeaders);
1676
+ if (parsedBase?.ephemeralBasicAuth && !hasHeaderCaseInsensitive(probeHeaders, "authorization")) {
1677
+ const encoded = Buffer.from(parsedBase.ephemeralBasicAuth, "utf8").toString("base64");
1678
+ setHeaderCaseInsensitive(probeHeaders, "Authorization", `Basic ${encoded}`);
1679
+ }
1680
+ // Build operation list and emit a single summary BRIDGE_FORMAT_WARNING for skipped Mutation/Subscription operations
1681
+ const operations = parsed.queries.map((field) => ({
1682
+ kind: "query",
1683
+ field
1684
+ }));
1685
+ if (includeMutating) {
1686
+ for (const field of parsed.mutations) {
1687
+ operations.push({ kind: "mutation", field });
1688
+ }
1689
+ if (parsed.skippedSubscriptionCount > 0) {
1690
+ warnings.push({
1691
+ code: "BRIDGE_FORMAT_WARNING",
1692
+ message: `Skipped ${parsed.skippedSubscriptionCount} GraphQL Subscription operation(s) (HTTP POST ingest does not probe streaming subscriptions).`,
1693
+ details: {
1694
+ skippedMutationCount: 0,
1695
+ skippedSubscriptionCount: parsed.skippedSubscriptionCount
1696
+ }
1697
+ });
1698
+ }
1699
+ }
1700
+ else if (parsed.skippedMutationCount > 0 || parsed.skippedSubscriptionCount > 0) {
1701
+ const parts = [];
1702
+ if (parsed.skippedMutationCount > 0)
1703
+ parts.push(`${parsed.skippedMutationCount} Mutation`);
1704
+ if (parsed.skippedSubscriptionCount > 0)
1705
+ parts.push(`${parsed.skippedSubscriptionCount} Subscription`);
1706
+ warnings.push({
1707
+ code: "BRIDGE_FORMAT_WARNING",
1708
+ message: `Skipped ${parts.join(" and ")} GraphQL operation(s); pass includeMutating: true to include mutations.`,
1709
+ details: {
1710
+ skippedMutationCount: parsed.skippedMutationCount,
1711
+ skippedSubscriptionCount: parsed.skippedSubscriptionCount
1712
+ }
1713
+ });
1714
+ }
1715
+ let selectedOps = operations;
1716
+ if (operations.length > GRAPHQL_MAX_INVARIANTS) {
1717
+ selectedOps = operations.slice(0, GRAPHQL_MAX_INVARIANTS);
1718
+ warnings.push({
1719
+ code: "BRIDGE_FORMAT_WARNING",
1720
+ message: `GraphQL schema exceeded maximum of ${GRAPHQL_MAX_INVARIANTS} emitted invariants; remaining operations were skipped.`
1721
+ });
1722
+ }
1723
+ const canProbe = !offline && parsedBase !== null;
1724
+ if (!canProbe && !(rawBaseUrl && !parsedBase)) {
1725
+ warnings.push({
1726
+ code: "ADAPTER_DEGRADED",
1727
+ message: offline
1728
+ ? "Offline mode: emitted schema-derived GraphQL invariants without live HTTP probing."
1729
+ : "No baseUrl provided: emitted schema-derived GraphQL invariants without live HTTP probing."
1730
+ });
1731
+ }
1732
+ const timeoutMs = typeof deps.timeoutMs === "number" && deps.timeoutMs > 0 ? deps.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS;
1733
+ const doFetch = deps.fetchJson || fetchJson;
1734
+ const usedIds = new Set();
1735
+ const invariants = [];
1736
+ for (const op of selectedOps) {
1737
+ const { query, rootNode } = synthesizeOperationDocument(op.kind, op.field, parsed);
1738
+ const schemaDerivedJsonSchema = buildResponseJsonSchema(rootNode, parsed);
1739
+ let observedValid = false;
1740
+ let finalJsonSchema = schemaDerivedJsonSchema;
1741
+ let observedSubset;
1742
+ if (canProbe && parsedBase) {
1743
+ let observed = null;
1744
+ let probeErr = null;
1745
+ try {
1746
+ observed = await doFetch(parsedBase.probeUrl, {
1747
+ method: "POST",
1748
+ headers: probeHeaders,
1749
+ body: { query },
1750
+ timeoutMs
1751
+ });
1752
+ }
1753
+ catch (err) {
1754
+ probeErr = err;
1755
+ }
1756
+ if (probeErr !== null || !observed) {
1757
+ const safeErr = scrubSecretsFromText(probeErr ? errorMessage(probeErr) : "unknown error", rawBaseUrl, safeBaseUrl, allSecretValues);
1758
+ warnings.push({
1759
+ code: "ADAPTER_DEGRADED",
1760
+ message: `Live GraphQL probe failed for ${op.kind} ${op.field.name}; fell back to schema-derived contract: ${safeErr}`
1761
+ });
1762
+ }
1763
+ else if (observed.status !== 200) {
1764
+ warnings.push({
1765
+ code: "ADAPTER_DEGRADED",
1766
+ message: `Live GraphQL probe returned HTTP ${observed.status} for ${op.kind} ${op.field.name}; keeping schema-derived status 200 contract.`
1767
+ });
1768
+ }
1769
+ else if (!isObject(observed.json)) {
1770
+ warnings.push({
1771
+ code: "ADAPTER_DEGRADED",
1772
+ message: `Live GraphQL probe returned non-JSON payload for ${op.kind} ${op.field.name}; keeping schema-derived contract.`
1773
+ });
1774
+ }
1775
+ else if (Array.isArray(observed.json.errors) && observed.json.errors.length > 0) {
1776
+ warnings.push({
1777
+ code: "ADAPTER_DEGRADED",
1778
+ message: `Live GraphQL probe returned ${observed.json.errors.length} GraphQL error(s) for ${op.kind} ${op.field.name}; keeping strict schema-derived contract.`
1779
+ });
1780
+ }
1781
+ else if (isObject(observed.json.data) && op.field.name in observed.json.data) {
1782
+ const schemaErrors = validateJsonSchema(observed.json, schemaDerivedJsonSchema, "$");
1783
+ if (schemaErrors.length === 0) {
1784
+ observedValid = true;
1785
+ finalJsonSchema = refineJsonSchemaWithObserved(schemaDerivedJsonSchema, observed.json);
1786
+ if (observed.text.length <= MAX_SUBSET_BYTES) {
1787
+ observedSubset = { data: observed.json.data };
1788
+ }
1789
+ }
1790
+ else {
1791
+ warnings.push({
1792
+ code: "ADAPTER_DEGRADED",
1793
+ message: `Live GraphQL probe response for ${op.kind} ${op.field.name} violated schema (${schemaErrors[0].path}: ${schemaErrors[0].message}); keeping strict schema-derived contract.`
1794
+ });
1795
+ }
1796
+ }
1797
+ else {
1798
+ warnings.push({
1799
+ code: "ADAPTER_DEGRADED",
1800
+ message: `Live GraphQL probe response for ${op.kind} ${op.field.name} missing data.${op.field.name}; keeping schema-derived contract.`
1801
+ });
1802
+ }
1803
+ }
1804
+ const expected = {
1805
+ status: 200,
1806
+ jsonSchema: finalJsonSchema,
1807
+ ...(observedSubset !== undefined ? { jsonSubset: observedSubset } : {})
1808
+ };
1809
+ const input = {
1810
+ method: "POST",
1811
+ path: endpointPath,
1812
+ headers: { ...persistedHeaders },
1813
+ body: { query }
1814
+ };
1815
+ const tags = ["api", "graphql", op.kind, observedValid ? "observed" : "schema-only"];
1816
+ invariants.push({
1817
+ id: uniqueId(`inv-graphql-${op.kind}-${slugify(op.field.name)}`, usedIds),
1818
+ domain: "api",
1819
+ type: "http",
1820
+ severity: "hard",
1821
+ description: `GraphQL ${op.kind} ${op.field.name} matches ${observedValid ? "observed" : "schema-derived"} contract`,
1822
+ tags,
1823
+ sourceId: "src-1",
1824
+ input,
1825
+ expected,
1826
+ tolerance: {}
1827
+ });
1828
+ }
1829
+ validateInvariantsOrThrow(invariants);
1830
+ return {
1831
+ domain: "api",
1832
+ sources: [
1833
+ {
1834
+ id: "src-1",
1835
+ kind: "graphql",
1836
+ ref: isFileSource ? trimmedSource : (safeBaseUrl || "inline"),
1837
+ meta: {
1838
+ ...(safeBaseUrl ? { baseUrl: safeBaseUrl } : {}),
1839
+ endpointPath,
1840
+ queryRoot: parsed.queryRoot,
1841
+ queryCount: parsed.queries.length,
1842
+ ...(parsed.skippedMutationCount > 0 ? { skippedMutationCount: parsed.skippedMutationCount } : {}),
1843
+ ...(parsed.skippedSubscriptionCount > 0 ? { skippedSubscriptionCount: parsed.skippedSubscriptionCount } : {}),
1844
+ ...(redactedSecrets ? { redactedSecrets: true } : {})
1845
+ }
1846
+ }
1847
+ ],
1848
+ artifacts: { root: ".vibecode/artifacts", files: {} },
1849
+ invariants,
1850
+ warnings
1851
+ };
1852
+ }