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,1268 @@
1
+ import crypto from "node:crypto";
2
+ import net from "node:net";
3
+ import tls from "node:tls";
4
+ import { diffJsonSubset } from "../core/diff.js";
5
+ import { VibecodeError, errorMessage } from "../core/errors.js";
6
+ import { queryJsonPath, validateJsonSchema } from "../core/schema.js";
7
+ import { HTTP_HEADER_NAME_RE, STRICT_CONTROL_CHARS_RE, collectHeaderSecrets, collectJsonSecrets, collectSecretValue, collectUrlSecrets, isForbiddenObjectKey, isRecordSafe, isSensitiveHeaderName, isSensitiveKeyName, isSensitiveQueryParamName, redactDeepValue, redactSecretSpans, redactSensitiveText, resolveSafeTargetUrl, sanitizeSingleLine } from "../core/security.js";
8
+ import { redactRuntimeVars } from "../core/target-map.js";
9
+ import { mergeHeaders } from "../ingestors/trace.js";
10
+ const DEFAULT_TIMEOUT_MS = 10_000;
11
+ const DEFAULT_MAX_BYTES = 4 * 1024 * 1024;
12
+ const DEFAULT_MAX_EVENTS = 1000;
13
+ const DEFAULT_WS_MAX_BYTES = 2 * 1024 * 1024;
14
+ const MAX_HANDSHAKE_BYTES = 64 * 1024;
15
+ const MAX_NDJSON_STORED_ERRORS = 100;
16
+ const MAX_WS_FRAGMENTS = 4096;
17
+ const MAX_WS_QUEUE_LEN = 1024;
18
+ const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
19
+ const HTTP_METHOD_RE = /^[A-Z!#$%&'*+\-.^_`|~0-9]+$/;
20
+ const FORBIDDEN_PATH_RE = /(?:^|[.[\]"'\s])(?:__proto__|constructor|prototype)(?:$|[.[\]"'\s])/;
21
+ const WS_OP = { CONT: 0x0, TEXT: 0x1, BIN: 0x2, CLOSE: 0x8, PING: 0x9, PONG: 0xa };
22
+ const VALID_WS_OPCODES = new Set([0x0, 0x1, 0x2, 0x8, 0x9, 0xa]);
23
+ const RESERVED_WS_HDRS = new Set(["host", "upgrade", "connection", "sec-websocket-key", "sec-websocket-version"]);
24
+ const STREAM_SECRET_OPTS = {};
25
+ const PRESERVE_HASH_KEYS = new Set(["candidateOutputHash"]);
26
+ const isObj = isRecordSafe;
27
+ const posInt = (v, fb) => typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : fb;
28
+ const tryJson = (raw) => {
29
+ if (!raw.trim())
30
+ return { ok: false, value: undefined };
31
+ try {
32
+ return { ok: true, value: JSON.parse(raw) };
33
+ }
34
+ catch {
35
+ return { ok: false, value: undefined };
36
+ }
37
+ };
38
+ const isSensKey = (k) => isSensitiveHeaderName(k) || isSensitiveKeyName(k);
39
+ const isSensPath = (p) => {
40
+ const leaf = p.replace(/\[[^\]]*\]/g, "").split(".").pop() ?? "";
41
+ return isSensitiveKeyName(leaf) || isSensitiveKeyName(p);
42
+ };
43
+ function redactText(text, secrets) {
44
+ const raw = String(text ?? "");
45
+ if (!raw)
46
+ return "";
47
+ return redactSensitiveText(secrets && secrets.size > 0 ? redactSecretSpans(raw, secrets) : raw);
48
+ }
49
+ const fmtSafe = (v, sens = false, secrets) => sens ? '"[REDACTED]"' : redactText(sanitizeSingleLine(JSON.stringify(redactDeep(v, secrets)) ?? "undefined", 180), secrets);
50
+ function redactDeep(val, secrets) {
51
+ return redactDeepValue(val, {
52
+ maxDepth: 24,
53
+ redactText: (s) => redactText(s, secrets),
54
+ sensitiveKeyMode: "value",
55
+ sensitivePathAware: true
56
+ });
57
+ }
58
+ function safeQueryJsonPath(obj, expr) {
59
+ if (FORBIDDEN_PATH_RE.test(expr))
60
+ return { found: false, value: undefined, blocked: true };
61
+ return queryJsonPath(obj, expr);
62
+ }
63
+ function validateHeaderMap(raw, kind, secrets) {
64
+ if (!isObj(raw))
65
+ return null;
66
+ for (const [rawK, rawV] of Object.entries(raw)) {
67
+ if (rawV === undefined || rawV === null)
68
+ continue;
69
+ const k = rawK.trim();
70
+ const v = String(rawV);
71
+ if (STRICT_CONTROL_CHARS_RE.test(rawK) || !k || !HTTP_HEADER_NAME_RE.test(k) || STRICT_CONTROL_CHARS_RE.test(v)) {
72
+ return `Invalid ${kind} header: ${redactText(rawK, secrets)}`;
73
+ }
74
+ }
75
+ return null;
76
+ }
77
+ function buildUrl(base, reqPath, query, ws) {
78
+ if (!ws) {
79
+ return resolveSafeTargetUrl(reqPath || "/", base, { query });
80
+ }
81
+ const normBase = base.trim().replace(/^http:/i, "ws:").replace(/^https:/i, "wss:");
82
+ return resolveSafeTargetUrl(reqPath || "/", normBase, {
83
+ allowWs: true,
84
+ defaultProtocol: "ws",
85
+ normalizeWsProtocol: true,
86
+ query
87
+ });
88
+ }
89
+ function checkHeaders(expected, actual, failures, secrets) {
90
+ if (!isObj(expected))
91
+ return;
92
+ for (const [k, v] of Object.entries(expected)) {
93
+ const got = actual[k.toLowerCase()];
94
+ const sens = isSensKey(k);
95
+ if (got === undefined)
96
+ failures.push(redactText(`missing header ${k}`, secrets));
97
+ else if (got.toLowerCase() !== String(v).toLowerCase() && !got.toLowerCase().includes(String(v).toLowerCase())) {
98
+ failures.push(redactText(`header ${k} expected ${fmtSafe(String(v), sens, secrets)}, got ${fmtSafe(got, sens, secrets)}`, secrets));
99
+ }
100
+ }
101
+ }
102
+ function checkPayload(prefix, text, hasJson, json, rule, failures, diffs, secrets) {
103
+ if (rule.textExact !== undefined && text !== rule.textExact) {
104
+ failures.push(redactText(`${prefix}: exact text mismatch (expected ${fmtSafe(rule.textExact, false, secrets)}, got ${fmtSafe(text, false, secrets)})`, secrets));
105
+ diffs.textExact = redactDeep({ expected: rule.textExact, actual: text }, secrets);
106
+ }
107
+ if (rule.textContains !== undefined && !text.includes(rule.textContains)) {
108
+ failures.push(redactText(`${prefix}: text missing ${fmtSafe(rule.textContains, false, secrets)}`, secrets));
109
+ diffs.textContains = redactDeep({ expected: rule.textContains, actual: sanitizeSingleLine(text, 180) }, secrets);
110
+ }
111
+ if (rule.jsonSchema) {
112
+ if (!hasJson)
113
+ failures.push(`${prefix}: payload is not valid JSON (required by jsonSchema assertion)`);
114
+ else {
115
+ const errs = validateJsonSchema(json, rule.jsonSchema, "$");
116
+ if (errs.length) {
117
+ for (const e of errs.slice(0, 10))
118
+ failures.push(redactText(`${prefix}.jsonSchema ${e.path}: ${e.message}`, secrets));
119
+ diffs.jsonSchema = redactDeep(errs, secrets);
120
+ }
121
+ }
122
+ }
123
+ if (rule.jsonSubset !== undefined) {
124
+ if (!hasJson)
125
+ failures.push(`${prefix}: payload is not valid JSON (required by jsonSubset assertion)`);
126
+ else {
127
+ const sub = diffJsonSubset(rule.jsonSubset, json, "$");
128
+ if (sub.length) {
129
+ for (const e of sub.slice(0, 10)) {
130
+ const sens = isSensPath(e.path);
131
+ failures.push(redactText(`${prefix}.jsonSubset ${e.path}: expected ${fmtSafe(e.expected, sens, secrets)}, got ${fmtSafe(e.actual, sens, secrets)}`, secrets));
132
+ }
133
+ diffs.jsonSubset = redactDeep(sub, secrets);
134
+ }
135
+ }
136
+ }
137
+ const pathDiffs = [];
138
+ for (const a of rule.jsonPaths || []) {
139
+ const sens = isSensPath(a.path);
140
+ if (FORBIDDEN_PATH_RE.test(a.path)) {
141
+ failures.push(redactText(`${prefix}.jsonPath ${a.path}: blocked prototype key`, secrets));
142
+ pathDiffs.push({ path: a.path, error: "blocked prototype key" });
143
+ continue;
144
+ }
145
+ if (!hasJson) {
146
+ failures.push(redactText(`${prefix}.jsonPath ${a.path}: payload is not valid JSON`, secrets));
147
+ pathDiffs.push(redactDeep({ path: a.path, expected: sens ? "[REDACTED]" : a.equals, actual: undefined }, secrets));
148
+ continue;
149
+ }
150
+ const q = safeQueryJsonPath(json, a.path);
151
+ if (q.blocked) {
152
+ failures.push(redactText(`${prefix}.jsonPath ${a.path}: blocked prototype key`, secrets));
153
+ pathDiffs.push({ path: a.path, error: "blocked prototype key" });
154
+ continue;
155
+ }
156
+ if (!q.found) {
157
+ failures.push(redactText(`${prefix}.jsonPath ${a.path}: not found`, secrets));
158
+ pathDiffs.push(redactDeep({ path: a.path, expected: sens ? "[REDACTED]" : a.equals, actual: undefined }, secrets));
159
+ continue;
160
+ }
161
+ let ok = true;
162
+ const hasEq = Object.prototype.hasOwnProperty.call(a, "equals");
163
+ if (hasEq)
164
+ ok = JSON.stringify(q.value) === JSON.stringify(a.equals);
165
+ else if (Object.prototype.hasOwnProperty.call(a, "matches")) {
166
+ if (typeof a.matches !== "string") {
167
+ failures.push(redactText(`${prefix}.jsonPath ${a.path}: invalid regex pattern`, secrets));
168
+ pathDiffs.push(redactDeep({ path: a.path, expected: a.matches, actual: q.value, error: "invalid regex pattern" }, secrets));
169
+ continue;
170
+ }
171
+ try {
172
+ ok = new RegExp(a.matches).test(String(q.value));
173
+ }
174
+ catch (err) {
175
+ const msg = redactText(errorMessage(err), secrets);
176
+ failures.push(redactText(`${prefix}.jsonPath ${a.path}: invalid regex: ${msg}`, secrets));
177
+ pathDiffs.push(redactDeep({ path: a.path, expected: a.matches, actual: q.value, error: msg }, secrets));
178
+ continue;
179
+ }
180
+ }
181
+ if (!ok) {
182
+ const exp = hasEq ? a.equals : a.matches;
183
+ failures.push(redactText(`${prefix}.jsonPath ${a.path}: expected ${fmtSafe(exp, sens, secrets)}, got ${fmtSafe(q.value, sens, secrets)}`, secrets));
184
+ pathDiffs.push(redactDeep({ path: a.path, expected: exp, actual: q.value }, secrets));
185
+ }
186
+ }
187
+ if (pathDiffs.length)
188
+ diffs.jsonPaths = pathDiffs;
189
+ }
190
+ function createSseRawParser(maxEvents = Number.POSITIVE_INFINITY) {
191
+ const events = [];
192
+ let bom = false, pendingCr = false, lineBuf = "", hasData = false, hasEvent = false;
193
+ let eventName, eventId, eventRetry;
194
+ let dataLines = [];
195
+ const flush = (truncated) => {
196
+ if (hasData || (truncated && hasEvent)) {
197
+ const data = dataLines.join("\n");
198
+ const parsed = tryJson(data);
199
+ events.push({
200
+ event: eventName || "message",
201
+ data,
202
+ ...(eventId !== undefined ? { id: eventId } : {}),
203
+ ...(eventRetry !== undefined ? { retry: eventRetry } : {}),
204
+ ...(parsed.ok ? { json: parsed.value } : {}),
205
+ ...(truncated ? { truncated: true } : {})
206
+ });
207
+ }
208
+ eventName = eventId = eventRetry = undefined;
209
+ dataLines = [];
210
+ hasData = hasEvent = false;
211
+ };
212
+ const handleLine = (line) => {
213
+ if (line === "") {
214
+ flush(false);
215
+ return;
216
+ }
217
+ if (line.startsWith(":"))
218
+ return;
219
+ const colon = line.indexOf(":");
220
+ const field = colon === -1 ? line : line.slice(0, colon);
221
+ let val = colon === -1 ? "" : line.slice(colon + 1);
222
+ if (val.startsWith(" "))
223
+ val = val.slice(1);
224
+ if (field === "data") {
225
+ dataLines.push(val);
226
+ hasData = true;
227
+ }
228
+ else if (field === "event") {
229
+ eventName = val;
230
+ hasEvent = true;
231
+ }
232
+ else if (field === "id" && !val.includes("\0"))
233
+ eventId = val;
234
+ else if (field === "retry" && /^\d+$/.test(val)) {
235
+ const n = Number(val);
236
+ if (Number.isSafeInteger(n))
237
+ eventRetry = n;
238
+ }
239
+ };
240
+ return {
241
+ feed(rawChunk) {
242
+ let chunk = rawChunk;
243
+ if (!bom && chunk.length) {
244
+ bom = true;
245
+ if (chunk.startsWith("\uFEFF"))
246
+ chunk = chunk.slice(1);
247
+ }
248
+ let start = 0;
249
+ for (let i = 0; i < chunk.length; i++) {
250
+ const ch = chunk.charCodeAt(i);
251
+ if (pendingCr) {
252
+ pendingCr = false;
253
+ if (ch === 10) {
254
+ start = i + 1;
255
+ continue;
256
+ }
257
+ }
258
+ if (ch === 13 || ch === 10) {
259
+ handleLine(lineBuf + chunk.slice(start, i));
260
+ lineBuf = "";
261
+ if (ch === 13) {
262
+ if (i + 1 < chunk.length && chunk.charCodeAt(i + 1) === 10)
263
+ i++;
264
+ else if (i + 1 === chunk.length)
265
+ pendingCr = true;
266
+ }
267
+ start = i + 1;
268
+ if (events.length >= maxEvents)
269
+ return true;
270
+ }
271
+ }
272
+ if (start < chunk.length)
273
+ lineBuf += chunk.slice(start);
274
+ return events.length >= maxEvents;
275
+ },
276
+ finish() {
277
+ if (events.length < maxEvents) {
278
+ if (lineBuf.length) {
279
+ handleLine(lineBuf);
280
+ lineBuf = "";
281
+ }
282
+ if (hasData || hasEvent)
283
+ flush(true);
284
+ }
285
+ return events;
286
+ }
287
+ };
288
+ }
289
+ function createNdjsonRawParser(maxEvents = Number.POSITIVE_INFINITY, maxErrors = Number.POSITIVE_INFINITY) {
290
+ const items = [];
291
+ const errors = [];
292
+ let bom = false, lineBuf = "", lineNo = 0, totalErrors = 0;
293
+ const handleLine = (rawLine) => {
294
+ lineNo++;
295
+ const trimmed = (rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine).trim();
296
+ if (!trimmed)
297
+ return;
298
+ try {
299
+ items.push(JSON.parse(trimmed));
300
+ }
301
+ catch (err) {
302
+ totalErrors++;
303
+ if (errors.length < MAX_NDJSON_STORED_ERRORS) {
304
+ errors.push({ line: lineNo, message: redactSensitiveText(errorMessage(err)) });
305
+ }
306
+ }
307
+ };
308
+ return {
309
+ feed(rawChunk) {
310
+ let chunk = rawChunk;
311
+ if (!bom && chunk.length) {
312
+ bom = true;
313
+ if (chunk.startsWith("\uFEFF"))
314
+ chunk = chunk.slice(1);
315
+ }
316
+ let start = 0;
317
+ for (let i = 0; i < chunk.length; i++) {
318
+ if (chunk.charCodeAt(i) === 10) {
319
+ handleLine(lineBuf + chunk.slice(start, i));
320
+ lineBuf = "";
321
+ start = i + 1;
322
+ if (items.length >= maxEvents || totalErrors >= maxErrors)
323
+ return true;
324
+ }
325
+ }
326
+ if (start < chunk.length)
327
+ lineBuf += chunk.slice(start);
328
+ return items.length >= maxEvents || totalErrors >= maxErrors;
329
+ },
330
+ finish() {
331
+ if (items.length < maxEvents && totalErrors < maxErrors && lineBuf.length) {
332
+ handleLine(lineBuf);
333
+ lineBuf = "";
334
+ }
335
+ return { items, errors, totalErrors };
336
+ }
337
+ };
338
+ }
339
+ function createUnifiedStreamParser(format, cap, maxErrors) {
340
+ if (format === "sse") {
341
+ const sse = createSseRawParser(cap);
342
+ return {
343
+ feed: (c) => sse.feed(c),
344
+ finish: () => {
345
+ const evs = sse.finish();
346
+ const truncatedCount = evs.filter((e) => e.truncated).length;
347
+ return {
348
+ items: evs.map((e) => ({
349
+ event: e.event, data: e.data, hasJson: Object.prototype.hasOwnProperty.call(e, "json"), json: e.json,
350
+ ...(e.truncated ? { truncated: true } : {})
351
+ })),
352
+ errors: [],
353
+ malformedCount: truncatedCount,
354
+ truncatedCount
355
+ };
356
+ }
357
+ };
358
+ }
359
+ const nd = createNdjsonRawParser(cap, maxErrors);
360
+ return {
361
+ feed: (c) => nd.feed(c),
362
+ finish: () => {
363
+ const res = nd.finish();
364
+ return {
365
+ items: res.items.map((x) => ({ event: "message", data: JSON.stringify(x), hasJson: true, json: x })),
366
+ errors: res.errors,
367
+ malformedCount: res.totalErrors,
368
+ truncatedCount: 0
369
+ };
370
+ }
371
+ };
372
+ }
373
+ /** Spec-accurate Server-Sent Events (SSE) parser with EOF truncation awareness. */
374
+ export function parseSseText(raw) {
375
+ const p = createSseRawParser();
376
+ p.feed(raw);
377
+ return p.finish();
378
+ }
379
+ /** Line-delimited JSON (NDJSON) parser tracking 1-based malformed line numbers. */
380
+ export function parseNdjsonText(raw) {
381
+ const p = createNdjsonRawParser();
382
+ p.feed(raw);
383
+ const { items, errors } = p.finish();
384
+ return { items, errors };
385
+ }
386
+ function resolveFormat(req, ct, sample) {
387
+ if (req === "sse" || req === "ndjson")
388
+ return req;
389
+ if (ct.toLowerCase().includes("text/event-stream"))
390
+ return "sse";
391
+ if (/ndjson|jsonl|json-seq/i.test(ct))
392
+ return "ndjson";
393
+ let i = sample.startsWith("\uFEFF") ? 1 : 0;
394
+ const len = sample.length;
395
+ while (i < len) {
396
+ let lineEnd = i;
397
+ while (lineEnd < len && sample.charCodeAt(lineEnd) !== 10 && sample.charCodeAt(lineEnd) !== 13)
398
+ lineEnd++;
399
+ let firstNonWs = i;
400
+ while (firstNonWs < lineEnd && (sample.charCodeAt(firstNonWs) === 32 || sample.charCodeAt(firstNonWs) === 9))
401
+ firstNonWs++;
402
+ if (firstNonWs < lineEnd) {
403
+ const prefix = sample.slice(i, Math.min(lineEnd, i + 16));
404
+ return /^(?:data|event|id|retry)?:/.test(prefix) ? "sse" : "ndjson";
405
+ }
406
+ i = lineEnd + 1;
407
+ }
408
+ return "ndjson";
409
+ }
410
+ function matchStreamEvent(prefix, actual, rule, failures, diffs, secrets) {
411
+ if (rule.event !== undefined && actual.event !== rule.event) {
412
+ failures.push(redactText(`${prefix}.event: expected ${JSON.stringify(rule.event)}, got ${JSON.stringify(actual.event)}`, secrets));
413
+ diffs.event = redactDeep({ expected: rule.event, actual: actual.event }, secrets);
414
+ }
415
+ checkPayload(prefix, actual.data, actual.hasJson, actual.json, {
416
+ textExact: rule.dataExact, textContains: rule.dataContains,
417
+ jsonSchema: rule.jsonSchema, jsonSubset: rule.jsonSubset, jsonPaths: rule.jsonPaths
418
+ }, failures, diffs, secrets);
419
+ }
420
+ const RUNTIME_VARS_TEMPLATE_RE = /\{\{\s*vars\.([A-Za-z_][A-Za-z0-9_.-]{0,63})\s*\}\}/g;
421
+ const MAX_RUNTIME_DEPTH = 32;
422
+ function hasRuntimeVars(ctx) {
423
+ return Boolean(ctx.vars && typeof ctx.vars === "object" && Object.keys(ctx.vars).length > 0);
424
+ }
425
+ /** Replace `{{vars.NAME}}` with runtime var values (deep, cycle-safe); unknown names are left untouched. */
426
+ function interpolateRuntimeVars(value, vars, encode = false, depth = 0, seen = new WeakSet()) {
427
+ if (typeof value === "string") {
428
+ return value.replace(RUNTIME_VARS_TEMPLATE_RE, (match, name) => Object.prototype.hasOwnProperty.call(vars, name) && !isForbiddenObjectKey(name) ? (encode ? encodeURIComponent(vars[name]) : vars[name]) : match);
429
+ }
430
+ if (value === null || typeof value !== "object" || depth >= MAX_RUNTIME_DEPTH || seen.has(value))
431
+ return value;
432
+ seen.add(value);
433
+ try {
434
+ if (Array.isArray(value))
435
+ return value.map((v) => interpolateRuntimeVars(v, vars, encode, depth + 1, seen));
436
+ const out = {};
437
+ for (const [k, v] of Object.entries(value)) {
438
+ if (isForbiddenObjectKey(k))
439
+ continue;
440
+ out[k] = interpolateRuntimeVars(v, vars, encode, depth + 1, seen);
441
+ }
442
+ return out;
443
+ }
444
+ finally {
445
+ seen.delete(value);
446
+ }
447
+ }
448
+ /** In-memory copy of a stream/ws invariant with `{{vars.*}}` resolved in path, headers, body and ws send steps. */
449
+ function withRuntimeVars(invariant, vars) {
450
+ const input = (invariant.input || {});
451
+ const next = { ...input };
452
+ if (typeof input.path === "string")
453
+ next.path = interpolateRuntimeVars(input.path, vars, true);
454
+ if (isObj(input.headers))
455
+ next.headers = interpolateRuntimeVars(input.headers, vars);
456
+ if (input.body !== undefined)
457
+ next.body = interpolateRuntimeVars(input.body, vars);
458
+ if (Array.isArray(input.steps)) {
459
+ next.steps = input.steps.map((step) => {
460
+ if (!isObj(step) || step.action !== "send")
461
+ return step;
462
+ return {
463
+ ...step,
464
+ ...(step.text !== undefined ? { text: interpolateRuntimeVars(step.text, vars) } : {}),
465
+ ...(step.json !== undefined ? { json: interpolateRuntimeVars(step.json, vars) } : {})
466
+ };
467
+ });
468
+ }
469
+ return { ...invariant, input: next };
470
+ }
471
+ function scrubRuntimeDeep(value, vars) {
472
+ return redactDeepValue(value, {
473
+ maxDepth: MAX_RUNTIME_DEPTH,
474
+ redactText: (s) => redactRuntimeVars(s, vars),
475
+ preserveKeys: PRESERVE_HASH_KEYS
476
+ });
477
+ }
478
+ function scrubRuntimeOutcome(outcome, vars) {
479
+ const out = { ...outcome };
480
+ for (const key of ["failures", "reason", "diagnostic", "diff", "metrics"]) {
481
+ if (out[key] !== undefined)
482
+ out[key] = scrubRuntimeDeep(out[key], vars);
483
+ }
484
+ return out;
485
+ }
486
+ /** Verifies SSE or NDJSON HTTP streaming endpoints incrementally with strict bounds. */
487
+ export async function verifyHttpStream(invariant, ctx, deps = {}) {
488
+ if (!hasRuntimeVars(ctx))
489
+ return verifyHttpStreamImpl(invariant, ctx, deps);
490
+ return scrubRuntimeOutcome(await verifyHttpStreamImpl(withRuntimeVars(invariant, ctx.vars), ctx, deps), ctx.vars);
491
+ }
492
+ async function verifyHttpStreamImpl(invariant, ctx, _deps = {}) {
493
+ if (!ctx.target)
494
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <base-url> for HTTP stream verification.");
495
+ const input = (invariant.input || {});
496
+ const expected = (invariant.expected || {});
497
+ const secrets = new Set();
498
+ collectUrlSecrets(secrets, ctx.target, STREAM_SECRET_OPTS);
499
+ if (typeof input.path === "string")
500
+ collectUrlSecrets(secrets, input.path, STREAM_SECRET_OPTS);
501
+ if (isObj(input.query)) {
502
+ for (const [qk, qv] of Object.entries(input.query)) {
503
+ if (qv !== undefined && qv !== null && (isSensitiveQueryParamName(qk) || isSensitiveKeyName(qk)))
504
+ collectSecretValue(secrets, String(qv), STREAM_SECRET_OPTS);
505
+ }
506
+ }
507
+ collectHeaderSecrets(secrets, isObj(input.headers) ? input.headers : undefined, STREAM_SECRET_OPTS);
508
+ collectHeaderSecrets(secrets, ctx.headers, STREAM_SECRET_OPTS);
509
+ collectJsonSecrets(secrets, input.body, { maxDepth: 24, ...STREAM_SECRET_OPTS });
510
+ const method = String(input.method || "GET").trim().toUpperCase();
511
+ const started = Date.now();
512
+ let parsedUrl;
513
+ try {
514
+ parsedUrl = buildUrl(ctx.target, input.path || "/", input.query, false);
515
+ }
516
+ catch (err) {
517
+ return {
518
+ status: "fail", score: 0,
519
+ failures: [redactText(`invalid stream URL: ${errorMessage(err)}`, secrets)],
520
+ metrics: { url: redactText(String(input.path || ctx.target), secrets), method: redactText(method, secrets), durationMs: Date.now() - started }
521
+ };
522
+ }
523
+ const url = parsedUrl.toString();
524
+ collectUrlSecrets(secrets, url, STREAM_SECRET_OPTS);
525
+ const safeUrl = redactText(url, secrets);
526
+ if (!HTTP_METHOD_RE.test(method)) {
527
+ return { status: "fail", score: 0, failures: [redactText(`invalid HTTP method: ${JSON.stringify(method)}`, secrets)], metrics: { url: safeUrl, method: redactText(method, secrets), durationMs: Date.now() - started } };
528
+ }
529
+ const headerErr = validateHeaderMap(isObj(input.headers) ? input.headers : undefined, "HTTP", secrets) ?? validateHeaderMap(ctx.headers, "HTTP", secrets);
530
+ if (headerErr) {
531
+ return { status: "fail", score: 0, failures: [redactText(headerErr, secrets)], metrics: { url: safeUrl, method, durationMs: Date.now() - started } };
532
+ }
533
+ const headers = mergeHeaders(isObj(input.headers) ? input.headers : undefined, ctx.headers);
534
+ const timeoutMs = posInt(input.timeoutMs, DEFAULT_TIMEOUT_MS);
535
+ const maxBytes = posInt(input.maxBytes, DEFAULT_MAX_BYTES);
536
+ const hasExplicitInputMaxEvents = input.maxEvents !== undefined;
537
+ const hasExpectedMaxEvents = typeof expected.maxEvents === "number" && Number.isFinite(expected.maxEvents) && expected.maxEvents >= 0;
538
+ const capEvents = hasExplicitInputMaxEvents
539
+ ? posInt(input.maxEvents, DEFAULT_MAX_EVENTS)
540
+ : hasExpectedMaxEvents
541
+ ? Math.max(1, Math.floor(expected.maxEvents) + 1)
542
+ : DEFAULT_MAX_EVENTS + 1;
543
+ const forbidMalformed = expected.forbidMalformedEvents !== false;
544
+ const maxErrors = forbidMalformed ? Math.min(capEvents, MAX_NDJSON_STORED_ERRORS) : Math.max(capEvents * 10, DEFAULT_MAX_EVENTS);
545
+ const ctrl = new AbortController();
546
+ let timedOut = false;
547
+ const timer = setTimeout(() => { timedOut = true; ctrl.abort(); }, timeoutMs);
548
+ let status = 0, totalBytes = 0, exceededMaxBytes = false, hitEventCap = false;
549
+ const resHeaders = {};
550
+ let reader = null;
551
+ let format = null;
552
+ let parser = null;
553
+ let sniffBuf = "";
554
+ let sniffHasNonWs = false;
555
+ const abortEarly = async () => {
556
+ ctrl.abort();
557
+ if (reader)
558
+ await reader.cancel().catch(() => { });
559
+ };
560
+ try {
561
+ const res = await fetch(url, {
562
+ method,
563
+ headers,
564
+ body: input.body === undefined || input.body === null ? undefined : typeof input.body === "string" ? input.body : JSON.stringify(input.body),
565
+ signal: ctrl.signal
566
+ });
567
+ status = res.status;
568
+ for (const [k, v] of res.headers.entries()) {
569
+ const lk = k.toLowerCase();
570
+ resHeaders[lk] = v;
571
+ if (isSensKey(lk) || redactSensitiveText(v) !== v)
572
+ collectSecretValue(secrets, v, STREAM_SECRET_OPTS);
573
+ }
574
+ const ct = resHeaders["content-type"] || "";
575
+ if (input.format === "sse" || input.format === "ndjson")
576
+ format = input.format;
577
+ else if (ct.toLowerCase().includes("text/event-stream"))
578
+ format = "sse";
579
+ else if (/ndjson|jsonl|json-seq/i.test(ct))
580
+ format = "ndjson";
581
+ if (format)
582
+ parser = createUnifiedStreamParser(format, capEvents, maxErrors);
583
+ if (res.body) {
584
+ reader = res.body.getReader();
585
+ const decoder = new TextDecoder("utf-8");
586
+ let stoppedEarly = false;
587
+ while (true) {
588
+ const chunk = await reader.read();
589
+ if (chunk.done)
590
+ break;
591
+ totalBytes += chunk.value.byteLength;
592
+ if (totalBytes > maxBytes) {
593
+ exceededMaxBytes = stoppedEarly = true;
594
+ await abortEarly();
595
+ break;
596
+ }
597
+ const text = decoder.decode(chunk.value, { stream: true });
598
+ if (!parser) {
599
+ if (!sniffHasNonWs && /[^\s\uFEFF]/.test(text))
600
+ sniffHasNonWs = true;
601
+ sniffBuf += text;
602
+ if (!sniffHasNonWs)
603
+ continue;
604
+ if (!/[\r\n]/.test(sniffBuf) && sniffBuf.length < 32)
605
+ continue;
606
+ format = resolveFormat(input.format, ct, sniffBuf);
607
+ parser = createUnifiedStreamParser(format, capEvents, maxErrors);
608
+ const hit = parser.feed(sniffBuf);
609
+ sniffBuf = "";
610
+ if (hit) {
611
+ hitEventCap = stoppedEarly = true;
612
+ await abortEarly();
613
+ break;
614
+ }
615
+ }
616
+ else if (parser.feed(text)) {
617
+ hitEventCap = stoppedEarly = true;
618
+ await abortEarly();
619
+ break;
620
+ }
621
+ }
622
+ if (!stoppedEarly) {
623
+ const tail = decoder.decode();
624
+ if (!parser) {
625
+ sniffBuf += tail;
626
+ format = resolveFormat(input.format, ct, sniffBuf);
627
+ parser = createUnifiedStreamParser(format, capEvents, maxErrors);
628
+ if (sniffBuf)
629
+ parser.feed(sniffBuf);
630
+ }
631
+ else if (tail) {
632
+ parser.feed(tail);
633
+ }
634
+ }
635
+ }
636
+ }
637
+ catch (err) {
638
+ const durationMs = Date.now() - started;
639
+ const msg = timedOut ? `stream timed out after ${timeoutMs}ms` : `stream request failed: ${redactText(errorMessage(err), secrets)}`;
640
+ return { status: "fail", score: 0, failures: [redactText(msg, secrets)], metrics: { url: safeUrl, method, durationMs } };
641
+ }
642
+ finally {
643
+ clearTimeout(timer);
644
+ if (reader) {
645
+ await reader.cancel().catch(() => { });
646
+ try {
647
+ reader.releaseLock();
648
+ }
649
+ catch { /* ignore */ }
650
+ }
651
+ }
652
+ const durationMs = Date.now() - started;
653
+ const resolvedFmt = format ?? resolveFormat(input.format, resHeaders["content-type"] || "", sniffBuf);
654
+ const parsed = parser ? parser.finish() : { items: [], errors: [], malformedCount: 0, truncatedCount: 0 };
655
+ const items = parsed.items;
656
+ for (const item of items)
657
+ if (item.hasJson)
658
+ collectJsonSecrets(secrets, item.json, { maxDepth: 24, ...STREAM_SECRET_OPTS });
659
+ const failures = [];
660
+ const diff = {};
661
+ if (exceededMaxBytes)
662
+ failures.push(`stream exceeded maxBytes limit (${maxBytes} bytes)`);
663
+ if (hitEventCap && !hasExplicitInputMaxEvents && !hasExpectedMaxEvents && items.length >= capEvents) {
664
+ failures.push(`stream exceeded maxEvents limit (${DEFAULT_MAX_EVENTS} events)`);
665
+ }
666
+ if (expected.status !== undefined) {
667
+ const acc = Array.isArray(expected.status) ? expected.status : [expected.status];
668
+ if (!acc.includes(status))
669
+ failures.push(`status expected ${JSON.stringify(acc)}, got ${status}`);
670
+ }
671
+ checkHeaders(expected.headers, resHeaders, failures, secrets);
672
+ if (typeof expected.maxDurationMs === "number" && durationMs > expected.maxDurationMs) {
673
+ failures.push(`stream duration ${durationMs}ms > maxDurationMs ${expected.maxDurationMs}ms`);
674
+ }
675
+ const malformedCount = resolvedFmt === "sse" ? parsed.truncatedCount : parsed.malformedCount;
676
+ if (forbidMalformed && resolvedFmt === "sse" && parsed.truncatedCount > 0) {
677
+ failures.push("stream truncated: incomplete final SSE event without terminating blank line");
678
+ }
679
+ if (forbidMalformed && resolvedFmt === "ndjson" && parsed.errors.length > 0) {
680
+ for (const e of parsed.errors.slice(0, 10))
681
+ failures.push(redactText(`malformed ndjson line ${e.line}: ${e.message}`, secrets));
682
+ diff.malformedEvents = redactDeep(parsed.errors, secrets);
683
+ }
684
+ if (typeof expected.minEvents === "number" && items.length < expected.minEvents) {
685
+ failures.push(`event count ${items.length} < minEvents ${expected.minEvents}`);
686
+ }
687
+ if (typeof expected.maxEvents === "number" && items.length > expected.maxEvents) {
688
+ failures.push(`event count ${items.length} > maxEvents ${expected.maxEvents}`);
689
+ }
690
+ if (Array.isArray(expected.orderedEvents)) {
691
+ const orderedDiffs = [];
692
+ for (let i = 0; i < expected.orderedEvents.length; i++) {
693
+ const rule = expected.orderedEvents[i];
694
+ if (i >= items.length) {
695
+ failures.push(`stream truncated: expected event[${i}] (${rule.event ? `event=${JSON.stringify(rule.event)}` : "item"}), got only ${items.length} events`);
696
+ orderedDiffs.push({ index: i, reason: "stream truncated" });
697
+ continue;
698
+ }
699
+ const evDiff = {};
700
+ matchStreamEvent(`event[${i}]`, items[i], rule, failures, evDiff, secrets);
701
+ if (Object.keys(evDiff).length)
702
+ orderedDiffs.push({ index: i, ...evDiff });
703
+ }
704
+ if (orderedDiffs.length)
705
+ diff.orderedEvents = orderedDiffs;
706
+ }
707
+ if (expected.terminalEvent) {
708
+ const last = items[items.length - 1];
709
+ if (!last) {
710
+ failures.push("stream truncated: missing expected terminal event (received 0 events)");
711
+ diff.terminalEvent = { reason: "stream truncated", receivedEvents: 0 };
712
+ }
713
+ else {
714
+ const tf = [];
715
+ const td = {};
716
+ matchStreamEvent("terminalEvent", last, expected.terminalEvent, tf, td, secrets);
717
+ if (tf.length || last.truncated) {
718
+ failures.push(redactText(`stream truncated: missing expected terminal event (${tf.length ? tf.join("; ") : "incomplete trailing frame"})`, secrets));
719
+ diff.terminalEvent = Object.keys(td).length ? td : { reason: "incomplete trailing frame" };
720
+ }
721
+ }
722
+ }
723
+ const seed = items.length ? redactText(items.map((e) => `${e.event}:${e.data}`).join("\n"), secrets) : "";
724
+ const candidateOutputHash = seed ? crypto.createHash("sha256").update(seed, "utf8").digest("hex") : undefined;
725
+ return {
726
+ status: failures.length ? "fail" : "pass",
727
+ score: failures.length ? 0 : 1,
728
+ failures: failures.map((f) => redactText(f, secrets)),
729
+ ...(Object.keys(diff).length ? { diff: redactDeep(diff, secrets) } : {}),
730
+ metrics: {
731
+ url: redactText(url, secrets), method, format: resolvedFmt, status, bytes: totalBytes,
732
+ eventCount: items.length, malformedCount, durationMs,
733
+ ...(candidateOutputHash ? { candidateOutputHash } : {})
734
+ }
735
+ };
736
+ }
737
+ /** Encodes a masked RFC 6455 client-to-server WebSocket frame. */
738
+ export function encodeWsClientFrame(opcode, payload = Buffer.alloc(0), maskKey) {
739
+ const data = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
740
+ const mask = maskKey && maskKey.length === 4 ? maskKey : crypto.randomBytes(4);
741
+ const len = data.length;
742
+ const b0 = 0x80 | (opcode & 0x0f);
743
+ const hdr = len < 126
744
+ ? Buffer.from([b0, 0x80 | len])
745
+ : len <= 0xffff
746
+ ? Buffer.from([b0, 0x80 | 126, (len >> 8) & 0xff, len & 0xff])
747
+ : (() => { const b = Buffer.alloc(10); b[0] = b0; b[1] = 0x80 | 127; b.writeBigUInt64BE(BigInt(len), 2); return b; })();
748
+ const masked = Buffer.allocUnsafe(len);
749
+ for (let i = 0; i < len; i++)
750
+ masked[i] = data[i] ^ mask[i & 3];
751
+ return Buffer.concat([hdr, mask, masked]);
752
+ }
753
+ /** Decodes RFC 6455 frames from a TCP byte stream with strict payload bounds. */
754
+ export function decodeWsFrames(buffer, maxMessageBytes = DEFAULT_WS_MAX_BYTES) {
755
+ const limit = Number.isFinite(maxMessageBytes) && maxMessageBytes >= 0 ? Math.floor(maxMessageBytes) : DEFAULT_WS_MAX_BYTES;
756
+ const frames = [];
757
+ let off = 0;
758
+ while (off + 2 <= buffer.length) {
759
+ const b0 = buffer[off], b1 = buffer[off + 1];
760
+ if ((b0 & 0x70) !== 0)
761
+ throw new Error("WebSocket protocol error: non-zero RSV bits");
762
+ const fin = (b0 & 0x80) !== 0, opcode = b0 & 0x0f, masked = (b1 & 0x80) !== 0, lenByte = b1 & 0x7f;
763
+ if (!VALID_WS_OPCODES.has(opcode))
764
+ throw new Error(`WebSocket protocol error: reserved opcode 0x${opcode.toString(16)}`);
765
+ if (opcode >= 0x8 && (!fin || lenByte >= 126))
766
+ throw new Error("WebSocket protocol error: invalid control frame");
767
+ let hdrLen = 2, payloadLen = lenByte;
768
+ if (lenByte === 126) {
769
+ if (off + 4 > buffer.length)
770
+ break;
771
+ payloadLen = buffer.readUInt16BE(off + 2);
772
+ hdrLen = 4;
773
+ }
774
+ else if (lenByte === 127) {
775
+ if (off + 10 > buffer.length)
776
+ break;
777
+ const bigLen = buffer.readBigUInt64BE(off + 2);
778
+ if (bigLen > 0x7fffffffffffffffn || bigLen > BigInt(limit)) {
779
+ throw new Error(`WebSocket frame length (${bigLen.toString()} bytes) exceeds maxMessageBytes (${limit})`);
780
+ }
781
+ payloadLen = Number(bigLen);
782
+ hdrLen = 10;
783
+ }
784
+ if (payloadLen > limit)
785
+ throw new Error(`WebSocket frame length (${payloadLen} bytes) exceeds maxMessageBytes (${limit})`);
786
+ const maskOff = off + hdrLen, dataOff = maskOff + (masked ? 4 : 0);
787
+ if (dataOff + payloadLen > buffer.length)
788
+ break;
789
+ const payload = masked ? Buffer.allocUnsafe(payloadLen) : Buffer.from(buffer.subarray(dataOff, dataOff + payloadLen));
790
+ if (masked)
791
+ for (let i = 0; i < payloadLen; i++)
792
+ payload[i] = buffer[dataOff + i] ^ buffer[maskOff + (i & 3)];
793
+ frames.push({ fin, opcode, masked, payload });
794
+ off = dataOff + payloadLen;
795
+ }
796
+ return { frames, remainder: off < buffer.length ? Buffer.from(buffer.subarray(off)) : Buffer.alloc(0) };
797
+ }
798
+ function validateWsHandshake(headerText, expectedAccept) {
799
+ const lines = headerText.split("\r\n");
800
+ const statusMatch = /^HTTP\/1\.1\s+(\d{3})(?:\s|$)/.exec(lines[0] || "");
801
+ const code = statusMatch ? Number(statusMatch[1]) : 0;
802
+ if (code !== 101)
803
+ return `WebSocket handshake failed: expected HTTP/1.1 101, got ${code || "invalid response"}`;
804
+ const hdrs = Object.create(null);
805
+ let acceptCount = 0;
806
+ for (let i = 1; i < lines.length; i++) {
807
+ const idx = lines[i].indexOf(":");
808
+ if (idx <= 0)
809
+ continue;
810
+ const name = lines[i].slice(0, idx).trim().toLowerCase();
811
+ const val = lines[i].slice(idx + 1).trim();
812
+ if (!name || isForbiddenObjectKey(name))
813
+ continue;
814
+ if (name === "sec-websocket-accept")
815
+ acceptCount++;
816
+ hdrs[name] = hdrs[name] ? `${hdrs[name]}, ${val}` : val;
817
+ }
818
+ const hasUpgrade = (hdrs.connection || "").toLowerCase().split(",").some((t) => t.trim() === "upgrade");
819
+ const hasWebSocket = (hdrs.upgrade || "").toLowerCase().split(",").some((t) => t.trim() === "websocket");
820
+ if (!hasWebSocket || !hasUpgrade)
821
+ return "WebSocket handshake failed: missing Upgrade/Connection headers";
822
+ if (acceptCount !== 1 || hdrs["sec-websocket-accept"] !== expectedAccept) {
823
+ return "WebSocket handshake failed: Sec-WebSocket-Accept mismatch";
824
+ }
825
+ return null;
826
+ }
827
+ function connectWsClient(url, headers, timeoutMs, maxMsgBytes, secrets) {
828
+ return new Promise((resolve, reject) => {
829
+ const isTls = url.protocol === "wss:";
830
+ const host = url.hostname.startsWith("[") && url.hostname.endsWith("]") ? url.hostname.slice(1, -1) : url.hostname;
831
+ const port = url.port ? Number(url.port) : isTls ? 443 : 80;
832
+ const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname;
833
+ const reqTarget = `${url.pathname || "/"}${url.search}`;
834
+ if (STRICT_CONTROL_CHARS_RE.test(reqTarget) || /\s/.test(reqTarget) || STRICT_CONTROL_CHARS_RE.test(hostHeader) || /\s/.test(hostHeader)) {
835
+ reject(new Error("Invalid WebSocket request target or host header"));
836
+ return;
837
+ }
838
+ const key = crypto.randomBytes(16).toString("base64");
839
+ const expectedAccept = crypto.createHash("sha1").update(key + WS_GUID, "ascii").digest("base64");
840
+ const reqLines = [
841
+ `GET ${reqTarget} HTTP/1.1`, `Host: ${hostHeader}`, "Upgrade: websocket",
842
+ "Connection: Upgrade", `Sec-WebSocket-Key: ${key}`, "Sec-WebSocket-Version: 13"
843
+ ];
844
+ for (const [rawK, rawV] of Object.entries(headers)) {
845
+ const k = rawK.trim(), v = String(rawV);
846
+ if (STRICT_CONTROL_CHARS_RE.test(rawK) || !k || !HTTP_HEADER_NAME_RE.test(k) || STRICT_CONTROL_CHARS_RE.test(v)) {
847
+ reject(new Error(`Invalid WebSocket header: ${redactText(rawK, secrets)}`));
848
+ return;
849
+ }
850
+ if (RESERVED_WS_HDRS.has(k.toLowerCase()))
851
+ continue;
852
+ reqLines.push(`${k}: ${v}`);
853
+ }
854
+ const handshakeReq = `${reqLines.join("\r\n")}\r\n\r\n`;
855
+ const socket = isTls
856
+ ? tls.connect({ host, port, servername: net.isIP(host) ? undefined : host })
857
+ : net.connect({ host, port });
858
+ let handshakeDone = false, closeSent = false, closed = false, pongsSent = 0, fragBytes = 0, fragCount = 0, queuedBytes = 0;
859
+ const maxQueueBytes = Math.max(maxMsgBytes * 4, 4 * 1024 * 1024);
860
+ let hsBuf = Buffer.alloc(0), rawBuf = Buffer.alloc(0);
861
+ let fragOp = null, fragChunks = [];
862
+ let closeCode, fatalError = null;
863
+ const queue = [];
864
+ let msgWaiter = null;
865
+ const closeWaiters = [];
866
+ const settleWaiters = (err) => {
867
+ if (msgWaiter) {
868
+ const w = msgWaiter;
869
+ msgWaiter = null;
870
+ clearTimeout(w.timer);
871
+ if (err)
872
+ w.reject(err);
873
+ }
874
+ while (closeWaiters.length) {
875
+ const cw = closeWaiters.pop();
876
+ clearTimeout(cw.timer);
877
+ cw.resolve(closeCode);
878
+ }
879
+ };
880
+ const fail = (err) => {
881
+ if (!fatalError)
882
+ fatalError = err;
883
+ closed = true;
884
+ clearTimeout(hsTimer);
885
+ hsBuf = Buffer.alloc(0);
886
+ rawBuf = Buffer.alloc(0);
887
+ fragChunks = [];
888
+ if (!handshakeDone) {
889
+ socket.destroy();
890
+ reject(err);
891
+ return;
892
+ }
893
+ settleWaiters(err);
894
+ socket.destroy();
895
+ };
896
+ const deliver = (msg) => {
897
+ if (msgWaiter) {
898
+ const w = msgWaiter;
899
+ msgWaiter = null;
900
+ clearTimeout(w.timer);
901
+ w.resolve(msg);
902
+ return;
903
+ }
904
+ queuedBytes += msg.bytes;
905
+ if (queue.length >= MAX_WS_QUEUE_LEN || queuedBytes > maxQueueBytes) {
906
+ fail(new Error(`WebSocket receive queue exceeded bounds (${queue.length} messages, ${queuedBytes} bytes)`));
907
+ return;
908
+ }
909
+ queue.push(msg);
910
+ };
911
+ const consume = (chunk) => {
912
+ if (closed)
913
+ return;
914
+ rawBuf = rawBuf.length ? Buffer.concat([rawBuf, chunk]) : chunk;
915
+ let dec;
916
+ try {
917
+ dec = decodeWsFrames(rawBuf, maxMsgBytes);
918
+ }
919
+ catch (err) {
920
+ fail(err instanceof Error ? err : new Error(errorMessage(err)));
921
+ return;
922
+ }
923
+ rawBuf = dec.remainder;
924
+ for (const f of dec.frames) {
925
+ if (f.masked) {
926
+ fail(new Error("WebSocket protocol error: server sent masked frame"));
927
+ return;
928
+ }
929
+ if (f.opcode === WS_OP.PING) {
930
+ if (!closed && socket.writable && !socket.destroyed) {
931
+ socket.write(encodeWsClientFrame(WS_OP.PONG, f.payload));
932
+ pongsSent++;
933
+ }
934
+ }
935
+ else if (f.opcode === WS_OP.PONG) {
936
+ continue;
937
+ }
938
+ else if (f.opcode === WS_OP.CLOSE) {
939
+ if (f.payload.length === 1) {
940
+ fail(new Error("WebSocket protocol error: invalid 1-byte close frame"));
941
+ return;
942
+ }
943
+ if (fragOp !== null) {
944
+ fail(new Error("WebSocket stream truncated: unclosed fragmented message before close"));
945
+ return;
946
+ }
947
+ closeCode = f.payload.length >= 2 ? f.payload.readUInt16BE(0) : 1005;
948
+ if (!closeSent && socket.writable && !socket.destroyed) {
949
+ closeSent = true;
950
+ socket.write(encodeWsClientFrame(WS_OP.CLOSE, f.payload.length >= 2 ? f.payload.subarray(0, 2) : Buffer.alloc(0)));
951
+ }
952
+ closed = true;
953
+ socket.end();
954
+ settleWaiters(new Error(`WebSocket closed before expected message (code ${closeCode})`));
955
+ return;
956
+ }
957
+ else if (f.opcode === WS_OP.TEXT || f.opcode === WS_OP.BIN) {
958
+ if (fragOp !== null) {
959
+ fail(new Error("WebSocket protocol error: overlapping fragmented message"));
960
+ return;
961
+ }
962
+ if (f.fin)
963
+ deliver({ opcode: f.opcode, text: f.payload.toString("utf8"), bytes: f.payload.length });
964
+ else {
965
+ fragOp = f.opcode;
966
+ fragChunks = f.payload.length ? [f.payload] : [];
967
+ fragBytes = f.payload.length;
968
+ fragCount = 1;
969
+ }
970
+ }
971
+ else if (f.opcode === WS_OP.CONT) {
972
+ if (fragOp === null) {
973
+ fail(new Error("WebSocket protocol error: unexpected continuation frame"));
974
+ return;
975
+ }
976
+ fragCount++;
977
+ if (fragCount > MAX_WS_FRAGMENTS) {
978
+ fail(new Error(`WebSocket fragmented message exceeds max fragment count (${MAX_WS_FRAGMENTS})`));
979
+ return;
980
+ }
981
+ fragBytes += f.payload.length;
982
+ if (fragBytes > maxMsgBytes) {
983
+ fail(new Error(`WebSocket fragmented message exceeds maxMessageBytes (${maxMsgBytes})`));
984
+ return;
985
+ }
986
+ if (f.payload.length)
987
+ fragChunks.push(f.payload);
988
+ if (f.fin) {
989
+ const full = Buffer.concat(fragChunks), op = fragOp;
990
+ fragOp = null;
991
+ fragChunks = [];
992
+ fragBytes = 0;
993
+ fragCount = 0;
994
+ deliver({ opcode: op, text: full.toString("utf8"), bytes: full.length });
995
+ }
996
+ }
997
+ else {
998
+ fail(new Error(`WebSocket protocol error: reserved opcode 0x${f.opcode.toString(16)}`));
999
+ return;
1000
+ }
1001
+ }
1002
+ };
1003
+ const session = {
1004
+ sendText(text) {
1005
+ if (fatalError)
1006
+ throw fatalError;
1007
+ if (closed || !socket.writable || socket.destroyed)
1008
+ throw new Error("Cannot send on closed WebSocket");
1009
+ socket.write(encodeWsClientFrame(WS_OP.TEXT, text));
1010
+ },
1011
+ nextMessage(stepTimeoutMs) {
1012
+ if (queue.length) {
1013
+ const next = queue.shift();
1014
+ queuedBytes = Math.max(0, queuedBytes - next.bytes);
1015
+ return Promise.resolve(next);
1016
+ }
1017
+ if (fatalError)
1018
+ return Promise.reject(fatalError);
1019
+ if (closed)
1020
+ return Promise.reject(new Error(`WebSocket stream truncated: closed before expected message (code ${closeCode ?? "none"})`));
1021
+ return new Promise((resM, rejM) => {
1022
+ const t = setTimeout(() => { if (msgWaiter?.timer === t)
1023
+ msgWaiter = null; rejM(new Error(`WebSocket expect timed out after ${stepTimeoutMs}ms`)); }, stepTimeoutMs);
1024
+ msgWaiter = { resolve: resM, reject: rejM, timer: t };
1025
+ });
1026
+ },
1027
+ close(code, waitMs) {
1028
+ if (closed)
1029
+ return Promise.resolve(closeCode);
1030
+ if (!closeSent && socket.writable && !socket.destroyed) {
1031
+ closeSent = true;
1032
+ const p = Buffer.alloc(2);
1033
+ p.writeUInt16BE(code & 0xffff, 0);
1034
+ socket.write(encodeWsClientFrame(WS_OP.CLOSE, p));
1035
+ }
1036
+ return new Promise((resC) => {
1037
+ const t = setTimeout(() => {
1038
+ const idx = closeWaiters.findIndex((w) => w.timer === t);
1039
+ if (idx >= 0)
1040
+ closeWaiters.splice(idx, 1);
1041
+ resC(closeCode);
1042
+ }, waitMs);
1043
+ closeWaiters.push({ resolve: resC, timer: t });
1044
+ });
1045
+ },
1046
+ getCloseCode: () => closeCode,
1047
+ getPongsSent: () => pongsSent,
1048
+ getFatalError: () => fatalError,
1049
+ destroy() {
1050
+ closed = true;
1051
+ clearTimeout(hsTimer);
1052
+ hsBuf = Buffer.alloc(0);
1053
+ rawBuf = Buffer.alloc(0);
1054
+ fragChunks = [];
1055
+ settleWaiters(new Error("WebSocket connection destroyed"));
1056
+ socket.removeAllListeners();
1057
+ socket.on("error", () => { });
1058
+ socket.destroy();
1059
+ }
1060
+ };
1061
+ const hsTimer = setTimeout(() => fail(new Error(`WebSocket handshake timed out after ${timeoutMs}ms`)), timeoutMs);
1062
+ socket.once(isTls ? "secureConnect" : "connect", () => {
1063
+ if (!closed && socket.writable && !socket.destroyed)
1064
+ socket.write(handshakeReq);
1065
+ });
1066
+ socket.on("data", (chunk) => {
1067
+ if (handshakeDone) {
1068
+ consume(chunk);
1069
+ return;
1070
+ }
1071
+ hsBuf = Buffer.concat([hsBuf, chunk]);
1072
+ const end = hsBuf.indexOf("\r\n\r\n");
1073
+ if (end === -1) {
1074
+ if (hsBuf.length > MAX_HANDSHAKE_BYTES)
1075
+ fail(new Error("WebSocket handshake headers exceed 64 KiB"));
1076
+ return;
1077
+ }
1078
+ clearTimeout(hsTimer);
1079
+ if (end > MAX_HANDSHAKE_BYTES) {
1080
+ fail(new Error("WebSocket handshake headers exceed 64 KiB"));
1081
+ return;
1082
+ }
1083
+ const errMsg = validateWsHandshake(hsBuf.subarray(0, end).toString("latin1"), expectedAccept);
1084
+ const trailing = Buffer.from(hsBuf.subarray(end + 4));
1085
+ hsBuf = Buffer.alloc(0);
1086
+ if (errMsg) {
1087
+ fail(new Error(errMsg));
1088
+ return;
1089
+ }
1090
+ handshakeDone = true;
1091
+ resolve(session);
1092
+ if (trailing.length)
1093
+ consume(trailing);
1094
+ });
1095
+ socket.on("error", (err) => fail(err));
1096
+ socket.on("close", () => {
1097
+ closed = true;
1098
+ clearTimeout(hsTimer);
1099
+ if (!handshakeDone) {
1100
+ fail(new Error("WebSocket stream truncated: socket closed before handshake completed"));
1101
+ return;
1102
+ }
1103
+ if (!fatalError) {
1104
+ if (rawBuf.length > 0) {
1105
+ fatalError = new Error(`WebSocket stream truncated: connection closed mid-frame (${rawBuf.length} trailing bytes)`);
1106
+ }
1107
+ else if (fragOp !== null) {
1108
+ fatalError = new Error("WebSocket stream truncated: unclosed fragmented message before disconnect");
1109
+ }
1110
+ }
1111
+ rawBuf = Buffer.alloc(0);
1112
+ fragChunks = [];
1113
+ settleWaiters(fatalError ?? new Error(`WebSocket stream truncated: closed before expected message (code ${closeCode ?? "none"})`));
1114
+ });
1115
+ });
1116
+ }
1117
+ /** Verifies RFC 6455 WebSocket exchanges, auto-pong, and close codes. */
1118
+ export async function verifyWsProtocol(invariant, ctx, deps = {}) {
1119
+ if (!hasRuntimeVars(ctx))
1120
+ return verifyWsProtocolImpl(invariant, ctx, deps);
1121
+ return scrubRuntimeOutcome(await verifyWsProtocolImpl(withRuntimeVars(invariant, ctx.vars), ctx, deps), ctx.vars);
1122
+ }
1123
+ async function verifyWsProtocolImpl(invariant, ctx, _deps = {}) {
1124
+ if (!ctx.target)
1125
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <ws-url> for WebSocket verification.");
1126
+ const input = (invariant.input || {});
1127
+ const expected = (invariant.expected || {});
1128
+ const secrets = new Set();
1129
+ collectUrlSecrets(secrets, ctx.target, STREAM_SECRET_OPTS);
1130
+ if (typeof input.path === "string")
1131
+ collectUrlSecrets(secrets, input.path, STREAM_SECRET_OPTS);
1132
+ if (isObj(input.query)) {
1133
+ for (const [qk, qv] of Object.entries(input.query)) {
1134
+ if (qv !== undefined && qv !== null && (isSensitiveQueryParamName(qk) || isSensitiveKeyName(qk)))
1135
+ collectSecretValue(secrets, String(qv), STREAM_SECRET_OPTS);
1136
+ }
1137
+ }
1138
+ collectHeaderSecrets(secrets, isObj(input.headers) ? input.headers : undefined, STREAM_SECRET_OPTS);
1139
+ collectHeaderSecrets(secrets, ctx.headers, STREAM_SECRET_OPTS);
1140
+ const started = Date.now();
1141
+ let url;
1142
+ try {
1143
+ url = buildUrl(ctx.target, input.path || "/", input.query, true);
1144
+ }
1145
+ catch (err) {
1146
+ return {
1147
+ status: "fail", score: 0,
1148
+ failures: [redactText(`invalid WebSocket URL: ${errorMessage(err)}`, secrets)],
1149
+ metrics: { url: redactText(String(input.path || ctx.target), secrets), durationMs: Date.now() - started, messagesSent: 0, messagesReceived: 0, pongsSent: 0 }
1150
+ };
1151
+ }
1152
+ collectUrlSecrets(secrets, url.toString(), STREAM_SECRET_OPTS);
1153
+ const safeUrl = redactText(url.toString(), secrets);
1154
+ const headerErr = validateHeaderMap(isObj(input.headers) ? input.headers : undefined, "WebSocket", secrets) ?? validateHeaderMap(ctx.headers, "WebSocket", secrets);
1155
+ if (headerErr) {
1156
+ return {
1157
+ status: "fail", score: 0,
1158
+ failures: [redactText(`ws_protocol error: ${headerErr}`, secrets)],
1159
+ metrics: { url: safeUrl, durationMs: Date.now() - started, messagesSent: 0, messagesReceived: 0, pongsSent: 0 }
1160
+ };
1161
+ }
1162
+ const headers = mergeHeaders(isObj(input.headers) ? input.headers : undefined, ctx.headers);
1163
+ const timeoutMs = posInt(input.timeoutMs, DEFAULT_TIMEOUT_MS);
1164
+ const maxMsgBytes = posInt(input.maxMessageBytes, DEFAULT_WS_MAX_BYTES);
1165
+ const steps = Array.isArray(input.steps) ? input.steps : [];
1166
+ const failures = [];
1167
+ const diff = {};
1168
+ const stepDiffs = [];
1169
+ const receivedTexts = [];
1170
+ let messagesSent = 0, messagesReceived = 0;
1171
+ let reportedFatal = false;
1172
+ let session = null;
1173
+ try {
1174
+ session = await connectWsClient(url, headers, timeoutMs, maxMsgBytes, secrets);
1175
+ for (let i = 0; i < steps.length; i++) {
1176
+ const step = steps[i];
1177
+ if (!isObj(step)) {
1178
+ failures.push(`step[${i}]: invalid step object`);
1179
+ break;
1180
+ }
1181
+ if (step.action === "send") {
1182
+ if (step.json !== undefined)
1183
+ collectJsonSecrets(secrets, step.json, { maxDepth: 24, ...STREAM_SECRET_OPTS });
1184
+ session.sendText(step.text !== undefined ? String(step.text) : step.json !== undefined ? JSON.stringify(step.json) : "");
1185
+ messagesSent++;
1186
+ }
1187
+ else if (step.action === "expect") {
1188
+ let msg;
1189
+ try {
1190
+ msg = await session.nextMessage(posInt(step.timeoutMs, timeoutMs));
1191
+ }
1192
+ catch (err) {
1193
+ if (session.getFatalError())
1194
+ reportedFatal = true;
1195
+ failures.push(redactText(`step[${i}] expect failed: ${errorMessage(err)}`, secrets));
1196
+ break;
1197
+ }
1198
+ messagesReceived++;
1199
+ receivedTexts.push(msg.text);
1200
+ const parsed = tryJson(msg.text);
1201
+ if (parsed.ok)
1202
+ collectJsonSecrets(secrets, parsed.value, { maxDepth: 24, ...STREAM_SECRET_OPTS });
1203
+ const sDiff = {};
1204
+ checkPayload(`step[${i}]`, msg.text, parsed.ok, parsed.value, {
1205
+ textExact: step.textExact, textContains: step.textContains,
1206
+ jsonSchema: step.jsonSchema, jsonSubset: step.jsonSubset, jsonPaths: step.jsonPaths
1207
+ }, failures, sDiff, secrets);
1208
+ if (Object.keys(sDiff).length)
1209
+ stepDiffs.push({ step: i, ...sDiff });
1210
+ }
1211
+ else if (step.action === "close") {
1212
+ await session.close(typeof step.code === "number" ? step.code : 1000, posInt(step.timeoutMs, Math.min(timeoutMs, 2000)));
1213
+ }
1214
+ else {
1215
+ failures.push(redactText(`step[${i}]: unsupported ws_protocol action ${JSON.stringify(step.action)}`, secrets));
1216
+ break;
1217
+ }
1218
+ }
1219
+ if (expected.closeCode !== undefined && session.getCloseCode() === undefined && !session.getFatalError()) {
1220
+ await session.close(1000, Math.min(timeoutMs, 1500));
1221
+ }
1222
+ const fatal = session.getFatalError();
1223
+ if (fatal && !reportedFatal) {
1224
+ failures.push(redactText(`ws_protocol error: ${errorMessage(fatal)}`, secrets));
1225
+ }
1226
+ const observedCode = session.getCloseCode();
1227
+ if (expected.closeCode !== undefined && observedCode !== expected.closeCode) {
1228
+ failures.push(`closeCode expected ${expected.closeCode}, got ${observedCode ?? "none"}`);
1229
+ diff.closeCode = { expected: expected.closeCode, actual: observedCode };
1230
+ }
1231
+ }
1232
+ catch (err) {
1233
+ failures.push(redactText(`ws_protocol error: ${errorMessage(err)}`, secrets));
1234
+ }
1235
+ finally {
1236
+ session?.destroy();
1237
+ }
1238
+ const durationMs = Date.now() - started;
1239
+ if (typeof expected.maxDurationMs === "number" && durationMs > expected.maxDurationMs) {
1240
+ failures.push(`ws duration ${durationMs}ms > maxDurationMs ${expected.maxDurationMs}ms`);
1241
+ }
1242
+ if (stepDiffs.length)
1243
+ diff.steps = stepDiffs;
1244
+ const seed = receivedTexts.length ? redactText(receivedTexts.join("\n"), secrets) : "";
1245
+ const candidateOutputHash = seed ? crypto.createHash("sha256").update(seed, "utf8").digest("hex") : undefined;
1246
+ const finalCloseCode = session?.getCloseCode();
1247
+ return {
1248
+ status: failures.length ? "fail" : "pass",
1249
+ score: failures.length ? 0 : 1,
1250
+ failures: failures.map((f) => redactText(f, secrets)),
1251
+ ...(Object.keys(diff).length ? { diff: redactDeep(diff, secrets) } : {}),
1252
+ metrics: {
1253
+ url: redactText(url.toString(), secrets), durationMs, messagesSent, messagesReceived,
1254
+ pongsSent: session?.getPongsSent() ?? 0,
1255
+ ...(finalCloseCode !== undefined ? { closeCode: finalCloseCode } : {}),
1256
+ ...(candidateOutputHash ? { candidateOutputHash } : {})
1257
+ }
1258
+ };
1259
+ }
1260
+ /** Unified oracle dispatcher for http_stream and ws_protocol invariants. */
1261
+ export async function verifyInvariant(invariant, ctx, deps = {}) {
1262
+ const kind = invariant.type;
1263
+ if (kind === "http_stream")
1264
+ return verifyHttpStream(invariant, ctx, deps);
1265
+ if (kind === "ws_protocol")
1266
+ return verifyWsProtocol(invariant, ctx, deps);
1267
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported stream invariant type: ${kind}`);
1268
+ }