@riddledc/riddle-proof 0.8.85 → 0.8.87

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 (58) hide show
  1. package/dist/advanced/index.d.cts +1 -1
  2. package/dist/advanced/index.d.ts +1 -1
  3. package/dist/advanced/proof-run-engine.d.cts +1 -1
  4. package/dist/advanced/proof-run-engine.d.ts +1 -1
  5. package/dist/change-proof.cjs +2 -9
  6. package/dist/change-proof.d.cts +1 -1
  7. package/dist/change-proof.d.ts +1 -1
  8. package/dist/change-proof.js +2 -2
  9. package/dist/{chunk-AFARUBE4.js → chunk-3W4NGKZ6.js} +11 -11
  10. package/dist/chunk-6S33FQL7.js +14 -0
  11. package/dist/{chunk-FW7CKARF.js → chunk-7W6ZJPHJ.js} +1 -1
  12. package/dist/{chunk-JZKLCY5G.js → chunk-BVYM4WJ5.js} +1 -1
  13. package/dist/chunk-GQOE5Q7C.js +32 -0
  14. package/dist/chunk-H5AALGSA.js +32 -0
  15. package/dist/{chunk-2K3DIK7A.js → chunk-KF6F2RMQ.js} +301 -3979
  16. package/dist/{chunk-O2AO726C.js → chunk-NR2XQXIC.js} +3 -3
  17. package/dist/cli/index.js +5 -5
  18. package/dist/cli.cjs +285 -3999
  19. package/dist/cli.js +5 -5
  20. package/dist/evidence-trust-root.cjs +54 -0
  21. package/dist/evidence-trust-root.d.cts +2 -0
  22. package/dist/evidence-trust-root.d.ts +2 -0
  23. package/dist/evidence-trust-root.js +31 -0
  24. package/dist/index.cjs +346 -3991
  25. package/dist/index.d.cts +8 -1
  26. package/dist/index.d.ts +8 -1
  27. package/dist/index.js +80 -14
  28. package/dist/packet.cjs +54 -0
  29. package/dist/packet.d.cts +2 -0
  30. package/dist/packet.d.ts +2 -0
  31. package/dist/packet.js +31 -0
  32. package/dist/pr-comment.cjs +2 -9
  33. package/dist/pr-comment.d.cts +2 -2
  34. package/dist/pr-comment.d.ts +2 -2
  35. package/dist/pr-comment.js +3 -3
  36. package/dist/profile/index.cjs +277 -3991
  37. package/dist/profile/index.d.cts +2 -3
  38. package/dist/profile/index.d.ts +2 -3
  39. package/dist/profile/index.js +1 -1
  40. package/dist/profile-suggestions.cjs +2 -2
  41. package/dist/profile-suggestions.d.cts +1 -3
  42. package/dist/profile-suggestions.d.ts +1 -3
  43. package/dist/profile-suggestions.js +2 -2
  44. package/dist/profile.cjs +277 -3991
  45. package/dist/profile.d.cts +3 -550
  46. package/dist/profile.d.ts +3 -550
  47. package/dist/profile.js +1 -1
  48. package/dist/{proof-run-engine-DpChFR5H.d.cts → proof-run-engine-Baiv6l3A.d.cts} +3 -3
  49. package/dist/{proof-run-engine-BqRoA3Do.d.ts → proof-run-engine-MiKZt9oY.d.ts} +3 -3
  50. package/dist/proof-run-engine.d.cts +1 -1
  51. package/dist/proof-run-engine.d.ts +1 -1
  52. package/dist/receipts.d.cts +3 -0
  53. package/dist/receipts.d.ts +3 -0
  54. package/dist/rule-trust-root.cjs +36 -0
  55. package/dist/rule-trust-root.d.cts +2 -0
  56. package/dist/rule-trust-root.d.ts +2 -0
  57. package/dist/rule-trust-root.js +13 -0
  58. package/package.json +20 -5
@@ -20,180 +20,45 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/profile/index.ts
21
21
  var profile_exports = {};
22
22
  __export(profile_exports, {
23
- RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS: () => RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS,
24
- RIDDLE_PROOF_ORDERED_TRACE_OPERATORS: () => RIDDLE_PROOF_ORDERED_TRACE_OPERATORS,
25
- RIDDLE_PROOF_PROFILE_CHECK_TYPES: () => RIDDLE_PROOF_PROFILE_CHECK_TYPES,
26
- RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION: () => RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION,
27
- RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES: () => RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES,
28
- RIDDLE_PROOF_PROFILE_RESULT_VERSION: () => RIDDLE_PROOF_PROFILE_RESULT_VERSION,
29
- RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES: () => RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES,
30
- RIDDLE_PROOF_PROFILE_STATUSES: () => RIDDLE_PROOF_PROFILE_STATUSES,
31
- RIDDLE_PROOF_PROFILE_VERSION: () => RIDDLE_PROOF_PROFILE_VERSION,
32
- applyRiddleProofProfileArtifactCompleteness: () => applyRiddleProofProfileArtifactCompleteness,
33
- assessRiddleProofOrderedTrace: () => assessRiddleProofOrderedTrace,
34
- assessRiddleProofOrderedTraceSetupResults: () => assessRiddleProofOrderedTraceSetupResults,
35
- assessRiddleProofProfileArtifactCompleteness: () => assessRiddleProofProfileArtifactCompleteness,
36
- assessRiddleProofProfileEvidence: () => assessRiddleProofProfileEvidence,
23
+ RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS: () => import_profile2.RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS,
24
+ RIDDLE_PROOF_ORDERED_TRACE_OPERATORS: () => import_profile2.RIDDLE_PROOF_ORDERED_TRACE_OPERATORS,
25
+ RIDDLE_PROOF_PROFILE_CHECK_TYPES: () => import_profile2.RIDDLE_PROOF_PROFILE_CHECK_TYPES,
26
+ RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION: () => import_profile2.RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION,
27
+ RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES: () => import_profile2.RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES,
28
+ RIDDLE_PROOF_PROFILE_RESULT_VERSION: () => import_profile2.RIDDLE_PROOF_PROFILE_RESULT_VERSION,
29
+ RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES: () => import_profile2.RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES,
30
+ RIDDLE_PROOF_PROFILE_STATUSES: () => import_profile2.RIDDLE_PROOF_PROFILE_STATUSES,
31
+ RIDDLE_PROOF_PROFILE_VERSION: () => import_profile2.RIDDLE_PROOF_PROFILE_VERSION,
32
+ applyRiddleProofProfileArtifactCompleteness: () => import_profile2.applyRiddleProofProfileArtifactCompleteness,
33
+ assessRiddleProofOrderedTrace: () => import_profile2.assessRiddleProofOrderedTrace,
34
+ assessRiddleProofOrderedTraceSetupResults: () => import_profile2.assessRiddleProofOrderedTraceSetupResults,
35
+ assessRiddleProofProfileArtifactCompleteness: () => import_profile2.assessRiddleProofProfileArtifactCompleteness,
36
+ assessRiddleProofProfileEvidence: () => import_profile2.assessRiddleProofProfileEvidence,
37
37
  buildRiddleProofProfileScript: () => buildRiddleProofProfileScript,
38
- collectRiddleProfileArtifactRefs: () => collectRiddleProfileArtifactRefs,
39
- collectRiddleProofProfileWarnings: () => collectRiddleProofProfileWarnings,
40
- createRiddleProofProfileConfigurationError: () => createRiddleProofProfileConfigurationError,
41
- createRiddleProofProfileEnvironmentBlockedResult: () => createRiddleProofProfileEnvironmentBlockedResult,
42
- createRiddleProofProfileInsufficientResult: () => createRiddleProofProfileInsufficientResult,
43
- deriveRiddleProofArtifactBodyAssertions: () => deriveRiddleProofArtifactBodyAssertions,
44
- extractRiddleProofProfileResult: () => extractRiddleProofProfileResult,
45
- normalizeRiddleProofProfile: () => normalizeRiddleProofProfile,
38
+ collectRiddleProfileArtifactRefs: () => import_profile2.collectRiddleProfileArtifactRefs,
39
+ collectRiddleProofProfileWarnings: () => import_profile2.collectRiddleProofProfileWarnings,
40
+ createRiddleProofProfileConfigurationError: () => import_profile2.createRiddleProofProfileConfigurationError,
41
+ createRiddleProofProfileEnvironmentBlockedResult: () => import_profile2.createRiddleProofProfileEnvironmentBlockedResult,
42
+ createRiddleProofProfileInsufficientResult: () => import_profile2.createRiddleProofProfileInsufficientResult,
43
+ deriveRiddleProofArtifactBodyAssertions: () => import_profile2.deriveRiddleProofArtifactBodyAssertions,
44
+ extractRiddleProofProfileResult: () => import_profile2.extractRiddleProofProfileResult,
45
+ normalizeRiddleProofProfile: () => import_profile2.normalizeRiddleProofProfile,
46
46
  preflightRiddleProofProfileHttpStatusChecks: () => preflightRiddleProofProfileHttpStatusChecks,
47
- preflightRiddleProofProfileRunnerArtifacts: () => preflightRiddleProofProfileRunnerArtifacts,
48
- profileStatusExitCode: () => profileStatusExitCode,
49
- resolveRiddleProofProfileRouteUrl: () => resolveRiddleProofProfileRouteUrl,
50
- resolveRiddleProofProfileTargetUrl: () => resolveRiddleProofProfileTargetUrl,
51
- resolveRiddleProofProfileTimeoutSec: () => resolveRiddleProofProfileTimeoutSec,
52
- slugifyRiddleProofProfileName: () => slugifyRiddleProofProfileName,
53
- summarizeRiddleProofProfileResult: () => summarizeRiddleProofProfileResult
47
+ preflightRiddleProofProfileRunnerArtifacts: () => import_profile2.preflightRiddleProofProfileRunnerArtifacts,
48
+ profileStatusExitCode: () => import_profile2.profileStatusExitCode,
49
+ resolveRiddleProofProfileRouteUrl: () => import_profile2.resolveRiddleProofProfileRouteUrl,
50
+ resolveRiddleProofProfileTargetUrl: () => import_profile2.resolveRiddleProofProfileTargetUrl,
51
+ resolveRiddleProofProfileTimeoutSec: () => import_profile2.resolveRiddleProofProfileTimeoutSec,
52
+ slugifyRiddleProofProfileName: () => import_profile2.slugifyRiddleProofProfileName,
53
+ summarizeRiddleProofProfileResult: () => import_profile2.summarizeRiddleProofProfileResult
54
54
  });
55
55
  module.exports = __toCommonJS(profile_exports);
56
56
 
57
57
  // src/profile.ts
58
- var RIDDLE_PROOF_PROFILE_VERSION = "riddle-proof.profile.v1";
59
- var RIDDLE_PROOF_PROFILE_EVIDENCE_VERSION = "riddle-proof.profile-evidence.v1";
60
- var RIDDLE_PROOF_PROFILE_RESULT_VERSION = "riddle-proof.profile-result.v1";
61
- var RIDDLE_PROOF_PROFILE_STATUSES = [
62
- "passed",
63
- "product_regression",
64
- "proof_insufficient",
65
- "environment_blocked",
66
- "configuration_error",
67
- "needs_human_review"
68
- ];
69
- var RIDDLE_PROOF_PROFILE_CHECK_TYPES = [
70
- "route_loaded",
71
- "url_search_param_equals",
72
- "url_search_param_absent",
73
- "selector_visible",
74
- "selector_absent",
75
- "selector_count_at_least",
76
- "selector_count_equals",
77
- "selector_count_equal",
78
- "selector_count_eq",
79
- "dialog_count_equals",
80
- "dialog_accept_count_equals",
81
- "dialog_dismiss_count_equals",
82
- "selector_text_visible",
83
- "selector_text_absent",
84
- "selector_text_order",
85
- "ordered_trace",
86
- "observe_within",
87
- "frame_text_visible",
88
- "frame_url_equals",
89
- "frame_url_matches",
90
- "frame_no_horizontal_overflow",
91
- "text_visible",
92
- "text_absent",
93
- "http_status",
94
- "link_status",
95
- "artifact_link_status",
96
- "route_inventory",
97
- "no_horizontal_overflow",
98
- "no_mobile_horizontal_overflow",
99
- "no_fatal_console_errors",
100
- "no_console_warnings"
101
- ];
102
- var RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES = [
103
- "click",
104
- "tap",
105
- "tap_until",
106
- "drag",
107
- "press",
108
- "key_down",
109
- "key_up",
110
- "fill",
111
- "set_input_value",
112
- "set_range_value",
113
- "deterministic_runtime",
114
- "canvas_signature",
115
- "assert_text_visible",
116
- "assert_text_absent",
117
- "assert_selector_count",
118
- "assert_window_value",
119
- "assert_window_number",
120
- "local_storage",
121
- "session_storage",
122
- "clear_storage",
123
- "clear_console",
124
- "dialog_response",
125
- "screenshot",
126
- "wait",
127
- "wait_for_selector",
128
- "wait_for_text",
129
- "window_eval",
130
- "window_call",
131
- "window_call_until"
132
- ];
133
- var RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES = [
134
- "aborted",
135
- "accessdenied",
136
- "addressunreachable",
137
- "blockedbyclient",
138
- "blockedbyresponse",
139
- "connectionaborted",
140
- "connectionclosed",
141
- "connectionfailed",
142
- "connectionrefused",
143
- "connectionreset",
144
- "internetdisconnected",
145
- "namenotresolved",
146
- "timedout",
147
- "failed"
148
- ];
149
- var RIDDLE_PROOF_ORDERED_TRACE_OPERATORS = [
150
- "exists",
151
- "equals",
152
- "not_equals",
153
- "truthy",
154
- "falsy",
155
- "gt",
156
- "gte",
157
- "lt",
158
- "lte",
159
- "abs_gt",
160
- "abs_gte",
161
- "abs_lt",
162
- "abs_lte"
163
- ];
164
- function uniqueNonEmptyStrings(values) {
165
- const seen = /* @__PURE__ */ new Set();
166
- const result = [];
167
- for (const value of values ?? []) {
168
- const normalized = typeof value === "string" ? value.trim() : "";
169
- if (!normalized || seen.has(normalized)) continue;
170
- seen.add(normalized);
171
- result.push(normalized);
172
- }
173
- return result;
174
- }
175
- function deriveRiddleProofArtifactBodyAssertions(input) {
176
- const artifactText = typeof input.artifact_text === "string" ? input.artifact_text : "";
177
- const candidates = uniqueNonEmptyStrings(input.candidates);
178
- const required = uniqueNonEmptyStrings(input.required);
179
- const mergedCandidates = uniqueNonEmptyStrings([...required, ...candidates]);
180
- const presentCandidates = mergedCandidates.filter((snippet) => artifactText.includes(snippet));
181
- const missingCandidates = mergedCandidates.filter((snippet) => !artifactText.includes(snippet));
182
- const missingRequired = required.filter((snippet) => !artifactText.includes(snippet));
183
- const warnings = missingCandidates.map((snippet) => `candidate snippet is not present in artifact body: ${snippet}`);
184
- return {
185
- version: "riddle-proof.artifact-body-assertions.v1",
186
- ok: missingRequired.length === 0,
187
- body_contains: presentCandidates,
188
- present_candidates: presentCandidates,
189
- missing_candidates: missingCandidates,
190
- missing_required: missingRequired,
191
- warnings
192
- };
193
- }
194
- var DEFAULT_VIEWPORTS = [
195
- { name: "desktop", width: 1280, height: 800 }
196
- ];
58
+ var import_profile2 = require("@riddledc/riddle-proof-core/profile");
59
+
60
+ // src/profile-capabilities.ts
61
+ var import_profile = require("@riddledc/riddle-proof-core/profile");
197
62
  function isRecord(value) {
198
63
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
199
64
  }
@@ -203,113 +68,12 @@ function stringValue(value) {
203
68
  function hasOwn(value, key) {
204
69
  return Object.prototype.hasOwnProperty.call(value, key);
205
70
  }
206
- function stringFromOwn(input, ...keys) {
207
- for (const key of keys) {
208
- if (hasOwn(input, key)) {
209
- const value = input[key];
210
- if (value !== void 0 && value !== null) return String(value);
211
- }
212
- }
213
- return void 0;
214
- }
215
- function valueFromOwn(input, ...keys) {
216
- for (const key of keys) {
217
- if (hasOwn(input, key)) return input[key];
218
- }
219
- return void 0;
220
- }
221
71
  function numberValue(value) {
222
72
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
223
73
  }
224
74
  function booleanValue(value) {
225
75
  return typeof value === "boolean" ? value : void 0;
226
76
  }
227
- function horizontalBoundsOverflowPx(value) {
228
- if (!isRecord(value)) return 0;
229
- let max = maxPositiveNumber(
230
- value.overflow_px,
231
- value.overflow,
232
- value.bounds_overflow_px,
233
- value.horizontal_overflow_px,
234
- value.left_overflow_px,
235
- value.right_overflow_px
236
- );
237
- for (const offender of boundsOffendersForEvidence(value)) {
238
- max = Math.max(max, horizontalOffenderOverflowPx(offender));
239
- }
240
- return roundPixels(max);
241
- }
242
- function horizontalOffenderOverflowPx(value) {
243
- if (!isRecord(value)) return 0;
244
- let max = maxPositiveNumber(
245
- value.overflow,
246
- value.overflow_px,
247
- value.bounds_overflow_px,
248
- value.horizontal_overflow_px,
249
- value.left_overflow_px,
250
- value.right_overflow_px,
251
- value.leftOverflowPx,
252
- value.rightOverflowPx
253
- );
254
- const clipped = isRecord(value.clipped || value.clip || value.clipping) ? value.clipped || value.clip || value.clipping : void 0;
255
- if (isRecord(clipped)) {
256
- max = Math.max(max, maxPositiveNumber(
257
- clipped.left,
258
- clipped.right,
259
- clipped.left_px,
260
- clipped.right_px,
261
- clipped.leftPx,
262
- clipped.rightPx
263
- ));
264
- }
265
- const rect = isRecord(value.rect || value.bounds || value.bounding_rect || value.boundingRect) ? value.rect || value.bounds || value.bounding_rect || value.boundingRect : void 0;
266
- const viewportWidth = numberValue(value.viewport_width ?? value.viewportWidth);
267
- if (isRecord(rect) && viewportWidth !== void 0) {
268
- const left = numberValue(rect.left);
269
- const right = numberValue(rect.right);
270
- if (left !== void 0 && left < 0) max = Math.max(max, Math.abs(left));
271
- if (right !== void 0 && right > viewportWidth) max = Math.max(max, right - viewportWidth);
272
- }
273
- return roundPixels(max);
274
- }
275
- function boundsOffendersForEvidence(value) {
276
- if (!isRecord(value)) return [];
277
- const offenders = [
278
- ...Array.isArray(value.overflow_offenders) ? value.overflow_offenders : [],
279
- ...Array.isArray(value.overflowOffenders) ? value.overflowOffenders : [],
280
- ...Array.isArray(value.bounds_offenders) ? value.bounds_offenders : [],
281
- ...Array.isArray(value.boundsOffenders) ? value.boundsOffenders : [],
282
- ...Array.isArray(value.clipped_elements) ? value.clipped_elements : [],
283
- ...Array.isArray(value.clippedElements) ? value.clippedElements : [],
284
- ...Array.isArray(value.clipping_offenders) ? value.clipping_offenders : [],
285
- ...Array.isArray(value.clippingOffenders) ? value.clippingOffenders : []
286
- ];
287
- return offenders.filter((item) => isRecord(item)).sort((a, b) => horizontalOffenderOverflowPx(b) - horizontalOffenderOverflowPx(a));
288
- }
289
- function maxPositiveNumber(...values) {
290
- let max = 0;
291
- for (const value of values) {
292
- const number = numberValue(value);
293
- if (number !== void 0 && number > max) max = number;
294
- }
295
- return max;
296
- }
297
- function roundPixels(value) {
298
- return Math.round(value * 100) / 100;
299
- }
300
- function timeoutSecValue(value) {
301
- const number = numberValue(value);
302
- return number && number > 0 ? Math.ceil(number) : void 0;
303
- }
304
- function jsonRecord(value) {
305
- if (!isRecord(value)) return void 0;
306
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, toJsonValue(child)]));
307
- }
308
- function stringRecord(value) {
309
- if (!isRecord(value)) return void 0;
310
- const entries = Object.entries(value).map(([key, child]) => [key, String(child)]).filter(([key]) => key.trim());
311
- return entries.length ? Object.fromEntries(entries) : void 0;
312
- }
313
77
  function toJsonValue(value) {
314
78
  if (value === null || value === void 0) return null;
315
79
  if (typeof value === "string" || typeof value === "boolean") return value;
@@ -452,185 +216,6 @@ function resolveJsonPath(root, path) {
452
216
  }
453
217
  return { exists: true, value: current };
454
218
  }
455
- function assessRiddleProofOrderedTrace(trace, events) {
456
- const insufficient = (reason, traceLength = Array.isArray(trace) ? trace.length : 0, witnesses2 = [], missingEvent, missingPaths) => ({
457
- version: "riddle-proof.ordered-trace-assessment.v1",
458
- status: "proof_insufficient",
459
- trace_length: traceLength,
460
- witnesses: witnesses2,
461
- missing_event: missingEvent,
462
- missing_paths: missingPaths,
463
- reason
464
- });
465
- const parsePath = (path) => {
466
- const segments = [];
467
- let token = "";
468
- const pushToken = () => {
469
- const value = token.trim();
470
- if (value) segments.push(value);
471
- token = "";
472
- };
473
- for (let index = 0; index < path.length; index += 1) {
474
- const char = path[index];
475
- if (char === ".") {
476
- pushToken();
477
- continue;
478
- }
479
- if (char !== "[") {
480
- token += char;
481
- continue;
482
- }
483
- pushToken();
484
- const closeIndex = path.indexOf("]", index + 1);
485
- if (closeIndex === -1) throw new Error(`unterminated bracket at ${index}`);
486
- const bracket = path.slice(index + 1, closeIndex).trim();
487
- if (!bracket) throw new Error(`empty bracket at ${index}`);
488
- if (/^\d+$/.test(bracket)) {
489
- segments.push(Number(bracket));
490
- } else {
491
- segments.push(bracket.replace(/^['"]|['"]$/g, ""));
492
- }
493
- index = closeIndex;
494
- }
495
- pushToken();
496
- return segments;
497
- };
498
- const resolve = (root, path) => {
499
- let segments;
500
- try {
501
- segments = parsePath(path);
502
- } catch {
503
- return { exists: false };
504
- }
505
- let current = root;
506
- for (const segment of segments) {
507
- if (Array.isArray(current)) {
508
- const index = typeof segment === "number" ? segment : /^\d+$/.test(segment) ? Number(segment) : -1;
509
- if (index < 0 || index >= current.length) return { exists: false };
510
- current = current[index];
511
- continue;
512
- }
513
- if (typeof segment !== "string" || current === null || typeof current !== "object") return { exists: false };
514
- if (!Object.hasOwn(current, segment)) return { exists: false };
515
- current = current[segment];
516
- }
517
- return { exists: true, value: current };
518
- };
519
- const valuesEqual = (left, right) => {
520
- if (Object.is(left, right)) return true;
521
- if (Array.isArray(left) || Array.isArray(right)) {
522
- return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => valuesEqual(value, right[index]));
523
- }
524
- if (left === null || right === null || typeof left !== "object" || typeof right !== "object") return false;
525
- const leftRecord = left;
526
- const rightRecord = right;
527
- const leftKeys = Object.keys(leftRecord).sort();
528
- const rightKeys = Object.keys(rightRecord).sort();
529
- return leftKeys.length === rightKeys.length && leftKeys.every((key, index) => key === rightKeys[index] && valuesEqual(leftRecord[key], rightRecord[key]));
530
- };
531
- const numericOperator = (op) => [
532
- "gt",
533
- "gte",
534
- "lt",
535
- "lte",
536
- "abs_gt",
537
- "abs_gte",
538
- "abs_lt",
539
- "abs_lte"
540
- ].includes(op);
541
- const matches = (value, predicate) => {
542
- if (predicate.op === "exists") return true;
543
- if (predicate.op === "equals") return valuesEqual(value, predicate.value);
544
- if (predicate.op === "not_equals") return !valuesEqual(value, predicate.value);
545
- if (predicate.op === "truthy") return Boolean(value);
546
- if (predicate.op === "falsy") return !value;
547
- const observed = typeof value === "number" ? value : Number.NaN;
548
- const expected = typeof predicate.value === "number" ? predicate.value : Number.NaN;
549
- if (!Number.isFinite(observed) || !Number.isFinite(expected)) return false;
550
- const candidate = predicate.op.startsWith("abs_") ? Math.abs(observed) : observed;
551
- if (predicate.op === "gt" || predicate.op === "abs_gt") return candidate > expected;
552
- if (predicate.op === "gte" || predicate.op === "abs_gte") return candidate >= expected;
553
- if (predicate.op === "lt" || predicate.op === "abs_lt") return candidate < expected;
554
- return candidate <= expected;
555
- };
556
- if (!Array.isArray(trace) || trace.length === 0) return insufficient("trace_missing_or_empty");
557
- if (!Array.isArray(events) || events.length === 0) return insufficient("events_missing", trace.length);
558
- for (const event of events) {
559
- const missingPaths = event.predicates.filter((predicate) => !trace.some((sample) => {
560
- const resolved = resolve(sample, predicate.path);
561
- return resolved.exists && (!numericOperator(predicate.op) || typeof resolved.value === "number" && Number.isFinite(resolved.value));
562
- })).map((predicate) => predicate.path);
563
- if (missingPaths.length) {
564
- return insufficient("required_trace_field_missing", trace.length, [], event.label, Array.from(new Set(missingPaths)));
565
- }
566
- }
567
- const witnesses = [];
568
- let cursor = 0;
569
- for (const event of events) {
570
- let witnessIndex = -1;
571
- for (let index = cursor; index < trace.length; index += 1) {
572
- if (event.predicates.every((predicate) => {
573
- const resolved = resolve(trace[index], predicate.path);
574
- return resolved.exists && matches(resolved.value, predicate);
575
- })) {
576
- witnessIndex = index;
577
- break;
578
- }
579
- }
580
- if (witnessIndex < 0) {
581
- return {
582
- version: "riddle-proof.ordered-trace-assessment.v1",
583
- status: "failed",
584
- trace_length: trace.length,
585
- witnesses,
586
- missing_event: event.label,
587
- reason: "ordered_event_not_observed"
588
- };
589
- }
590
- witnesses.push({
591
- label: event.label,
592
- index: witnessIndex,
593
- observations: event.predicates.map((predicate) => {
594
- const observed = resolve(trace[witnessIndex], predicate.path).value;
595
- return {
596
- path: predicate.path,
597
- op: predicate.op,
598
- expected: predicate.value,
599
- observed
600
- };
601
- })
602
- });
603
- cursor = witnessIndex + 1;
604
- }
605
- return {
606
- version: "riddle-proof.ordered-trace-assessment.v1",
607
- status: "passed",
608
- trace_length: trace.length,
609
- witnesses
610
- };
611
- }
612
- function assessRiddleProofOrderedTraceSetupResults(results, setupActionLabel, tracePath, events) {
613
- const insufficient = (reason) => ({
614
- version: "riddle-proof.ordered-trace-assessment.v1",
615
- status: "proof_insufficient",
616
- trace_length: 0,
617
- witnesses: [],
618
- reason
619
- });
620
- if (!Array.isArray(results)) return insufficient("setup_results_missing");
621
- const source = results.find((item) => item && typeof item === "object" && !Array.isArray(item) && item.label === setupActionLabel);
622
- if (!source) return insufficient("setup_action_result_missing");
623
- if (!Object.hasOwn(source, "returned")) return insufficient("setup_action_return_missing");
624
- const segments = tracePath.split(".").map((segment) => segment.trim()).filter(Boolean);
625
- let trace = source.returned;
626
- for (const segment of segments) {
627
- if (trace === null || typeof trace !== "object" || Array.isArray(trace) || !Object.hasOwn(trace, segment)) {
628
- return insufficient("trace_path_missing");
629
- }
630
- trace = trace[segment];
631
- }
632
- return assessRiddleProofOrderedTrace(trace, events);
633
- }
634
219
  function evaluateHttpStatusBodyJsonAssertion(root, assertion) {
635
220
  const resolved = resolveJsonPath(root, assertion.path);
636
221
  const errors = [];
@@ -686,3498 +271,290 @@ function evaluateHttpStatusBodyJsonAssertions(bodyText, assertions) {
686
271
  }
687
272
  return expected.map((assertion) => evaluateHttpStatusBodyJsonAssertion(parsed, assertion));
688
273
  }
689
- function compactProfileSetupSummaryText(value, limit = 160) {
690
- const text = typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
691
- if (!text) return void 0;
692
- if (text.length <= limit) return text;
693
- return `${text.slice(0, Math.max(0, limit - 15)).trimEnd()}... (${text.length} chars)`;
694
- }
695
- function profileSetupResultAction(value) {
696
- const action = value.action ?? value.type;
697
- return typeof action === "string" && action ? action : "unknown";
274
+ function checkLabel(check) {
275
+ return check.label || check.type;
698
276
  }
699
- function profileSetupFrameUrls(viewport) {
700
- const urls = [];
701
- const frames = viewport.frames || {};
702
- for (const container of Object.values(frames)) {
703
- if (!isRecord(container) || !Array.isArray(container.frames)) continue;
704
- for (const frame of container.frames) {
705
- if (!isRecord(frame)) continue;
706
- const url = typeof frame.url === "string" ? frame.url : void 0;
707
- if (url && !urls.includes(url)) urls.push(url);
277
+ function httpStatusRequestUrl(check, baseUrl) {
278
+ const rawUrl = check.url || "";
279
+ if (!rawUrl) return "";
280
+ try {
281
+ if (baseUrl && rawUrl.startsWith("/") && !rawUrl.startsWith("//")) {
282
+ const base = new URL(baseUrl);
283
+ const mountPrefix = previewMountPrefix(base.pathname);
284
+ if (mountPrefix) {
285
+ const requested = new URL(rawUrl, base.origin);
286
+ base.pathname = joinMountedRoutePath(mountPrefix, requested.pathname);
287
+ base.search = requested.search;
288
+ base.hash = requested.hash;
289
+ return base.href;
290
+ }
708
291
  }
292
+ return baseUrl ? new URL(rawUrl, baseUrl).href : new URL(rawUrl).href;
293
+ } catch {
294
+ return rawUrl;
709
295
  }
710
- return urls.slice(0, 10);
711
- }
712
- function profileSetupActionCounts(results) {
713
- const counts = {};
714
- for (const result of results) {
715
- const action = profileSetupResultAction(result);
716
- counts[action] = (counts[action] || 0) + 1;
717
- }
718
- return toJsonValue(counts);
719
296
  }
720
- function profileSetupScreenshotLabels(results) {
721
- return results.filter((result) => profileSetupResultAction(result) === "screenshot" && result.ok !== false && typeof result.screenshot_label === "string").map((result) => result.screenshot_label).filter(Boolean);
297
+ function httpStatusMethod(check) {
298
+ return (check.method || "GET").toUpperCase();
722
299
  }
723
- function profileSetupWindowCallUntilReceipts(results) {
724
- return results.filter((result) => profileSetupResultAction(result) === "window_call_until").map((result) => ({
725
- ordinal: result.ordinal ?? null,
726
- ok: result.ok !== false,
727
- path: result.path ?? null,
728
- until_path: result.until_path ?? null,
729
- until_value: result.until_value ?? null,
730
- until_expected_value: result.until_expected_value ?? null,
731
- call_count: result.call_count ?? null,
732
- max_calls: result.max_calls ?? null,
733
- reason: result.reason ?? result.error ?? null
734
- }));
300
+ function httpStatusAllowedStatuses(check) {
301
+ if (check.allowed_statuses?.length) return check.allowed_statuses;
302
+ if (check.expected_status !== void 0) return [check.expected_status];
303
+ return void 0;
735
304
  }
736
- function profileSetupWindowCallReceipts(results) {
737
- return results.filter((result) => profileSetupResultAction(result) === "window_call").map((result) => {
738
- const receipt = {
739
- ordinal: result.ordinal ?? null,
740
- label: result.label ?? null,
741
- ok: result.ok !== false,
742
- path: result.path ?? null,
743
- return_captured: result.return_captured ?? null,
744
- return_stored_to: result.return_stored_to ?? null,
745
- reason: result.reason ?? result.store_reason ?? null
746
- };
747
- if (result.error !== void 0) receipt.error = result.error;
748
- if (result.returned !== void 0) receipt.returned = result.returned;
749
- if (result.expected_return !== void 0) receipt.expected_return = result.expected_return;
750
- const returnSummary = profileSetupReturnSummary(result);
751
- if (returnSummary.length) receipt.return_summary = returnSummary;
752
- return receipt;
753
- });
305
+ function httpStatusIsAllowed(status, check) {
306
+ if (status === void 0) return false;
307
+ const allowed = httpStatusAllowedStatuses(check);
308
+ return allowed?.length ? allowed.includes(status) : status >= 200 && status < 400;
754
309
  }
755
- function profileSetupWindowEvalReceipts(results) {
756
- return results.filter((result) => profileSetupResultAction(result) === "window_eval").map((result) => {
757
- const receipt = {
758
- ordinal: result.ordinal ?? null,
759
- label: result.label ?? null,
760
- ok: result.ok !== false,
761
- script_length: result.script_length ?? null,
762
- return_captured: result.return_captured ?? null,
763
- return_stored_to: result.return_stored_to ?? null,
764
- reason: result.reason ?? result.store_reason ?? null
765
- };
766
- if (result.error !== void 0) receipt.error = result.error;
767
- if (result.returned !== void 0) receipt.returned = result.returned;
768
- if (result.expected_return !== void 0) receipt.expected_return = result.expected_return;
769
- const returnSummary = profileSetupReturnSummary(result);
770
- if (returnSummary.length) receipt.return_summary = returnSummary;
771
- return receipt;
772
- });
310
+ function linkStatusObservedBytes(result) {
311
+ const bytes = numberValue(result.bytes);
312
+ const contentLength = numberValue(result.content_length);
313
+ return Math.max(bytes ?? 0, contentLength ?? 0) || void 0;
773
314
  }
774
- function profileSetupDeterministicRuntimeReceipts(results) {
775
- return results.filter((result) => profileSetupResultAction(result) === "deterministic_runtime").map((result) => ({
776
- ordinal: result.ordinal ?? null,
777
- ok: result.ok !== false,
778
- random_enabled: result.random_enabled ?? null,
779
- random_queue_added: result.random_queue_added ?? null,
780
- random_queue_length: result.random_queue_length ?? null,
781
- random_queue_mode: result.random_queue_mode ?? null,
782
- random_underflow_count: result.random_underflow_count ?? null,
783
- clock_enabled: result.clock_enabled ?? null,
784
- previous_now: result.previous_now ?? null,
785
- now: result.now ?? null,
786
- advance_ms: result.advance_ms ?? null,
787
- restored: result.restored ?? null,
788
- reason: result.reason ?? result.error ?? null
789
- }));
315
+ function normalizeLinkStatusContentType(value) {
316
+ const normalized = value?.split(";")[0]?.trim().toLowerCase();
317
+ return normalized || void 0;
790
318
  }
791
- function profileSetupReturnSummaryFields(result) {
792
- const input = result.return_summary_fields;
793
- if (!Array.isArray(input)) return [];
794
- const fields = [];
795
- for (const item of input) {
796
- if (typeof item === "string") {
797
- const path2 = item.trim();
798
- if (path2) fields.push({ path: path2 });
799
- continue;
800
- }
801
- if (!isRecord(item)) continue;
802
- const path = stringValue(item.path) ?? stringValue(item.key) ?? stringValue(item.json_path) ?? stringValue(item.jsonPath);
803
- if (!path) continue;
804
- const label = stringValue(item.label) ?? stringValue(item.name) ?? stringValue(item.title);
805
- fields.push(label ? { path, label } : { path });
806
- }
807
- return fields;
319
+ function linkStatusContentTypesMatch(actual, expected) {
320
+ if (!actual || !expected) return false;
321
+ if (expected.endsWith("/*")) return actual.startsWith(expected.slice(0, -1));
322
+ if (actual === expected) return true;
323
+ const yamlTypes = /* @__PURE__ */ new Set(["application/yaml", "application/x-yaml", "text/yaml", "text/x-yaml"]);
324
+ return yamlTypes.has(actual) && yamlTypes.has(expected);
808
325
  }
809
- function profileSetupReturnSummary(result) {
810
- if (result.returned === void 0) return [];
811
- return profileSetupReturnSummaryFields(result).map((field) => {
812
- const resolved = resolveJsonPath(result.returned, field.path);
813
- const receipt = {
814
- label: field.label || field.path,
815
- path: field.path,
816
- exists: resolved.exists
817
- };
818
- if (resolved.exists) receipt.value = toJsonValue(resolved.value);
819
- if (resolved.error) receipt.reason = resolved.error;
820
- return receipt;
326
+ function linkStatusContentTypeOk(result, check) {
327
+ const expected = check.allowed_content_types;
328
+ if (!expected?.length) return true;
329
+ const actual = normalizeLinkStatusContentType(stringValue(result.content_type));
330
+ if (!actual) return false;
331
+ return expected.some((contentType) => {
332
+ const normalized = normalizeLinkStatusContentType(contentType);
333
+ if (!normalized) return false;
334
+ return linkStatusContentTypesMatch(actual, normalized);
821
335
  });
822
336
  }
823
- function profileSetupRangeValueReceipts(results) {
824
- return results.filter((result) => profileSetupResultAction(result) === "set_range_value").map((result) => ({
825
- ordinal: result.ordinal ?? null,
826
- ok: result.ok !== false,
827
- selector: result.selector ?? null,
828
- frame_selector: result.frame_selector ?? null,
829
- requested_value: result.requested_value ?? null,
830
- actual_value: result.actual_value ?? null,
831
- before_value: result.before_value ?? null,
832
- value_as_number: result.value_as_number ?? null,
833
- min: result.min ?? null,
834
- max: result.max ?? null,
835
- step: result.step ?? null,
836
- reason: result.reason ?? result.error ?? null
837
- }));
838
- }
839
- function profileSetupDragReceipts(results) {
840
- return results.filter((result) => profileSetupResultAction(result) === "drag").map((result) => ({
841
- ordinal: result.ordinal ?? null,
842
- ok: result.ok !== false,
843
- selector: result.selector ?? null,
844
- frame_selector: result.frame_selector ?? null,
845
- pointer_type: result.pointer_type ?? null,
846
- input_dispatch: result.input_dispatch ?? null,
847
- coordinate_mode: result.coordinate_mode ?? null,
848
- from_x: result.from_x ?? null,
849
- from_y: result.from_y ?? null,
850
- to_x: result.to_x ?? null,
851
- to_y: result.to_y ?? null,
852
- steps: result.steps ?? null,
853
- duration_ms: result.duration_ms ?? null,
854
- reason: result.reason ?? result.error ?? null
855
- }));
856
- }
857
- function profileSetupTapReceipts(results) {
858
- return results.filter((result) => profileSetupResultAction(result) === "tap").map((result) => ({
859
- ordinal: result.ordinal ?? null,
860
- ok: result.ok !== false,
861
- selector: result.selector ?? null,
862
- frame_selector: result.frame_selector ?? null,
863
- pointer_type: result.pointer_type ?? null,
864
- input_dispatch: result.input_dispatch ?? null,
865
- coordinate_mode: result.coordinate_mode ?? null,
866
- x: result.x ?? null,
867
- y: result.y ?? null,
868
- duration_ms: result.duration_ms ?? null,
869
- reason: result.reason ?? result.error ?? null
870
- }));
871
- }
872
- function profileSetupTapUntilReceipts(results) {
873
- return results.filter((result) => profileSetupResultAction(result) === "tap_until").map((result) => ({
874
- ordinal: result.ordinal ?? null,
875
- ok: result.ok !== false,
876
- selector: result.selector ?? null,
877
- frame_selector: result.frame_selector ?? null,
878
- pointer_type: result.pointer_type ?? null,
879
- input_dispatch: result.input_dispatch ?? null,
880
- coordinate_mode: result.coordinate_mode ?? null,
881
- x: result.x ?? null,
882
- y: result.y ?? null,
883
- duration_ms: result.duration_ms ?? null,
884
- until_path: result.until_path ?? null,
885
- until_value: result.until_value ?? null,
886
- until_expected_value: result.until_expected_value ?? null,
887
- tap_count: result.tap_count ?? null,
888
- max_taps: result.max_taps ?? result.max_calls ?? null,
889
- tap_burst_size: result.tap_burst_size ?? null,
890
- condition_check_count: result.condition_check_count ?? null,
891
- settle_ms: result.settle_ms ?? null,
892
- elapsed_ms: result.elapsed_ms ?? null,
893
- interval_ms: result.interval_ms ?? null,
894
- timeout_ms: result.timeout_ms ?? null,
895
- reason: result.reason ?? result.error ?? null
896
- }));
897
- }
898
- function profileSetupKeyboardReceipts(results) {
899
- return results.filter((result) => ["press", "key_down", "key_up"].includes(profileSetupResultAction(result))).map((result) => ({
900
- action: profileSetupResultAction(result),
901
- ordinal: result.ordinal ?? null,
902
- ok: result.ok !== false,
903
- selector: result.selector ?? null,
904
- frame_selector: result.frame_selector ?? null,
905
- key: result.key ?? null,
906
- hold_ms: result.hold_ms ?? null,
907
- reason: result.reason ?? result.error ?? null
908
- }));
337
+ function httpStatusBodyContainsFailures(result, check) {
338
+ const expected = check.body_contains?.filter(Boolean) ?? [];
339
+ if (!expected.length) return [];
340
+ const observed = isRecord(result.body_contains) ? result.body_contains : {};
341
+ return expected.filter((text) => observed[text] !== true);
909
342
  }
910
- function profileSetupCanvasSignatureReceipts(results) {
911
- return results.filter((result) => profileSetupResultAction(result) === "canvas_signature").map((result) => ({
912
- ordinal: result.ordinal ?? null,
913
- ok: result.ok !== false,
914
- selector: result.selector ?? null,
915
- frame_selector: result.frame_selector ?? null,
916
- label: result.label ?? null,
917
- hash: result.hash ?? null,
918
- data_length: result.data_length ?? null,
919
- width: result.width ?? null,
920
- height: result.height ?? null,
921
- css_width: result.css_width ?? null,
922
- css_height: result.css_height ?? null,
923
- compare_to: result.compare_to ?? null,
924
- previous_hash: result.previous_hash ?? null,
925
- changed: result.changed ?? null,
926
- return_stored_to: result.return_stored_to ?? null,
927
- reason: result.reason ?? result.error ?? null
928
- }));
343
+ function httpStatusBodyNotContainsFailures(result, check) {
344
+ const forbidden = check.body_not_contains?.filter(Boolean) ?? [];
345
+ if (!forbidden.length) return [];
346
+ const observed = isRecord(result.body_not_contains) ? result.body_not_contains : {};
347
+ return forbidden.filter((text) => observed[text] !== false);
929
348
  }
930
- function profileSetupCanvasSignatureStableHashGroups(results) {
931
- const groups = /* @__PURE__ */ new Map();
932
- for (const receipt of profileSetupCanvasSignatureReceipts(results)) {
933
- if (receipt.ok === false) continue;
934
- const hash = stringValue(receipt.hash);
935
- if (!hash) continue;
936
- const selector = stringValue(receipt.selector) || "canvas";
937
- const frameSelector = stringValue(receipt.frame_selector);
938
- const key = String(frameSelector || "") + "\n" + selector;
939
- const group = groups.get(key) || { selector, frame_selector: frameSelector, receipts: [] };
940
- const ordinal = numberValue(receipt.ordinal);
941
- const label = stringValue(receipt.label) || (ordinal === void 0 ? `capture-${group.receipts.length + 1}` : `#${ordinal}`);
942
- group.receipts.push({ hash, label, ordinal });
943
- groups.set(key, group);
944
- }
945
- const warnings = [];
946
- for (const group of groups.values()) {
947
- const receiptsByHash = /* @__PURE__ */ new Map();
948
- for (const receipt of group.receipts) {
949
- const hashReceipts = receiptsByHash.get(receipt.hash) || [];
950
- hashReceipts.push(receipt);
951
- receiptsByHash.set(receipt.hash, hashReceipts);
952
- }
953
- for (const [hash, receipts] of receiptsByHash.entries()) {
954
- const labels = [...new Set(receipts.map((receipt) => receipt.label))];
955
- if (receipts.length < 2 || labels.length < 2) continue;
956
- const visibleLabels = labels.slice(0, 8);
957
- warnings.push({
958
- selector: group.selector,
959
- frame_selector: group.frame_selector ?? null,
960
- hash,
961
- count: receipts.length,
962
- label_count: labels.length,
963
- labels: visibleLabels,
964
- omitted_label_count: Math.max(0, labels.length - visibleLabels.length),
965
- ordinals: receipts.map((receipt) => receipt.ordinal).filter((value) => value !== void 0).slice(0, 12),
966
- reason: "stable_canvas_signature_hash"
967
- });
968
- }
969
- }
970
- return warnings;
971
- }
972
- function profileSetupClickSequenceReceipts(clickedItems) {
973
- const nthChildPattern = /:nth-child\((\d+)\)/;
974
- const nthChildTemplatePattern = /:nth-child\(\d+\)/g;
975
- const groups = /* @__PURE__ */ new Map();
976
- for (const item of clickedItems) {
977
- const selector = stringValue(item.selector);
978
- if (!selector) continue;
979
- const frameSelector = stringValue(item.frame_selector);
980
- const clickCountValue = numberValue(item.click_count);
981
- const clickCount = clickCountValue === void 0 ? 1 : Math.max(1, Math.min(100, Math.floor(clickCountValue)));
982
- const ordinal = numberValue(item.ordinal);
983
- const match = nthChildPattern.exec(selector);
984
- const selectorTemplate = match ? selector.replace(nthChildTemplatePattern, ":nth-child(*)") : selector;
985
- const valueSource = match ? "nth-child" : "same-selector";
986
- const key = `${valueSource}
987
- ${frameSelector || ""}
988
- ${selectorTemplate}`;
989
- const group = groups.get(key) || {
990
- selector_template: selectorTemplate,
991
- frame_selector: frameSelector,
992
- value_source: valueSource,
993
- sequence: [],
994
- ordinals: [],
995
- result_count: 0,
996
- click_total: 0
997
- };
998
- if (match) {
999
- const value = Number(match[1]);
1000
- for (let index = 0; index < clickCount; index += 1) group.sequence.push(value);
1001
- }
1002
- if (ordinal !== void 0) group.ordinals.push(ordinal);
1003
- group.result_count += 1;
1004
- group.click_total += clickCount;
1005
- groups.set(key, group);
1006
- }
1007
- return [...groups.values()].filter((group) => group.result_count >= 4).map((group) => {
1008
- const sequence = group.sequence.slice(0, 32);
1009
- const ordinals = group.ordinals.slice(0, 16);
1010
- return {
1011
- selector_template: group.selector_template,
1012
- frame_selector: group.frame_selector ?? null,
1013
- value_source: group.value_source,
1014
- result_count: group.result_count,
1015
- click_total: group.click_total,
1016
- sequence,
1017
- omitted_sequence_count: Math.max(0, group.sequence.length - sequence.length),
1018
- ordinals,
1019
- omitted_ordinal_count: Math.max(0, group.ordinals.length - ordinals.length)
1020
- };
1021
- });
1022
- }
1023
- function sampleProfileSetupSummaryItems(items, limit) {
1024
- if (items.length <= limit) return items;
1025
- const firstCount = Math.floor(limit / 2);
1026
- const lastCount = limit - firstCount;
1027
- return [...items.slice(0, firstCount), ...items.slice(-lastCount)];
1028
- }
1029
- function profileScreenshotLabels(viewports) {
1030
- const labels = [];
1031
- for (const viewport of viewports || []) {
1032
- if (viewport.screenshot_label) labels.push(viewport.screenshot_label);
1033
- labels.push(...profileSetupScreenshotLabels(viewport.setup_action_results || []));
1034
- }
1035
- return labels;
1036
- }
1037
- function profileFinalScreenshotLabels(viewports) {
1038
- return (viewports || []).map((viewport) => viewport.screenshot_label).filter((label) => typeof label === "string" && Boolean(label.trim()));
1039
- }
1040
- function profileAllSetupScreenshotLabels(viewports) {
1041
- return (viewports || []).flatMap((viewport) => profileSetupScreenshotLabels(viewport.setup_action_results || []));
1042
- }
1043
- function profileSetupSummary(viewports, actionCount, expectedActionCountByViewport, finalScreenshotFullPage) {
1044
- const normalizedFinalScreenshotFullPage = finalScreenshotFullPage === void 0 ? void 0 : finalScreenshotFullPage !== false;
1045
- const finalScreenshotCount = viewports.filter((viewport) => typeof viewport.screenshot_label === "string" && viewport.screenshot_label.trim()).length;
1046
- return toJsonValue({
1047
- viewport_count: viewports.length,
1048
- action_count: actionCount ?? null,
1049
- final_screenshot_count: finalScreenshotCount,
1050
- final_screenshot_full_page: normalizedFinalScreenshotFullPage ?? null,
1051
- final_screenshot_mode: normalizedFinalScreenshotFullPage === void 0 ? null : normalizedFinalScreenshotFullPage ? "full_page" : "viewport",
1052
- viewports: viewports.map((viewport) => {
1053
- const expectedActionCount = expectedActionCountByViewport?.get(viewport.name) ?? actionCount;
1054
- const viewportFinalScreenshotFullPage = typeof viewport.screenshot_full_page === "boolean" ? viewport.screenshot_full_page : normalizedFinalScreenshotFullPage;
1055
- const results = viewport.setup_action_results || [];
1056
- const failed = results.filter((result) => result.ok === false && result.optional !== true);
1057
- const optionalFailed = results.filter((result) => result.ok === false && result.optional === true);
1058
- const successfulClicks = results.filter((result) => profileSetupResultAction(result) === "click" && result.ok !== false);
1059
- const clickCountValues = successfulClicks.map((result) => typeof result.click_count === "number" && Number.isFinite(result.click_count) && result.click_count > 1 ? result.click_count : void 0).filter((value) => value !== void 0);
1060
- const windowCallUntilReceipts = profileSetupWindowCallUntilReceipts(results);
1061
- const windowCallUntilCallCounts = windowCallUntilReceipts.map((result) => typeof result.call_count === "number" && Number.isFinite(result.call_count) ? result.call_count : void 0).filter((value) => value !== void 0);
1062
- const sampledWindowCallUntilReceipts = sampleProfileSetupSummaryItems(windowCallUntilReceipts, 8);
1063
- const windowCallReceipts = profileSetupWindowCallReceipts(results);
1064
- const windowCallStoredTotal = windowCallReceipts.filter((result) => typeof result.return_stored_to === "string" && result.return_stored_to.trim()).length;
1065
- const windowCallCapturedTotal = windowCallReceipts.filter((result) => result.return_captured === true).length;
1066
- const sampledWindowCallReceipts = sampleProfileSetupSummaryItems(windowCallReceipts, 8);
1067
- const windowEvalReceipts = profileSetupWindowEvalReceipts(results);
1068
- const windowEvalStoredTotal = windowEvalReceipts.filter((result) => typeof result.return_stored_to === "string" && result.return_stored_to.trim()).length;
1069
- const windowEvalCapturedTotal = windowEvalReceipts.filter((result) => result.return_captured === true).length;
1070
- const sampledWindowEvalReceipts = sampleProfileSetupSummaryItems(windowEvalReceipts, 8);
1071
- const deterministicRuntimeReceipts = profileSetupDeterministicRuntimeReceipts(results);
1072
- const sampledDeterministicRuntimeReceipts = sampleProfileSetupSummaryItems(deterministicRuntimeReceipts, 8);
1073
- const rangeValueReceipts = profileSetupRangeValueReceipts(results);
1074
- const sampledRangeValueReceipts = sampleProfileSetupSummaryItems(rangeValueReceipts, 8);
1075
- const dragReceipts = profileSetupDragReceipts(results);
1076
- const sampledDragReceipts = sampleProfileSetupSummaryItems(dragReceipts, 8);
1077
- const tapReceipts = profileSetupTapReceipts(results);
1078
- const sampledTapReceipts = sampleProfileSetupSummaryItems(tapReceipts, 8);
1079
- const tapUntilReceipts = profileSetupTapUntilReceipts(results);
1080
- const tapUntilTapCounts = tapUntilReceipts.map((result) => typeof result.tap_count === "number" && Number.isFinite(result.tap_count) ? result.tap_count : void 0).filter((value) => value !== void 0);
1081
- const sampledTapUntilReceipts = sampleProfileSetupSummaryItems(tapUntilReceipts, 8);
1082
- const keyboardReceipts = profileSetupKeyboardReceipts(results);
1083
- const sampledKeyboardReceipts = sampleProfileSetupSummaryItems(keyboardReceipts, 8);
1084
- const canvasSignatureReceipts = profileSetupCanvasSignatureReceipts(results);
1085
- const sampledCanvasSignatureReceipts = sampleProfileSetupSummaryItems(canvasSignatureReceipts, 8);
1086
- const clickedItems = results.filter((result) => profileSetupResultAction(result) === "click" && result.ok !== false).map((result) => {
1087
- const clickCount = typeof result.click_count === "number" && Number.isFinite(result.click_count) && result.click_count > 1 ? result.click_count : void 0;
1088
- return {
1089
- ordinal: result.ordinal ?? null,
1090
- selector: result.selector ?? null,
1091
- frame_selector: result.frame_selector ?? null,
1092
- text: compactProfileSetupSummaryText(result.text),
1093
- ...result.fallback_to_tap === true ? { fallback_to_tap: true } : {},
1094
- ...result.input_dispatch ? { input_dispatch: result.input_dispatch } : {},
1095
- ...result.click_error ? { click_error: compactProfileSetupSummaryText(result.click_error) } : {},
1096
- ...clickCount ? { click_count: clickCount } : {}
1097
- };
1098
- });
1099
- const clicked = sampleProfileSetupSummaryItems(clickedItems, 8);
1100
- const clickSequences = profileSetupClickSequenceReceipts(clickedItems);
1101
- const sampledClickSequences = sampleProfileSetupSummaryItems(clickSequences, 6);
1102
- const text_samples = results.filter((result) => result.ok !== false && typeof result.text === "string" && (profileSetupResultAction(result) === "assert_text_visible" || profileSetupResultAction(result) === "assert_text_absent" || profileSetupResultAction(result) === "wait_for_text")).map((result) => ({
1103
- ordinal: result.ordinal ?? null,
1104
- action: profileSetupResultAction(result),
1105
- frame_selector: result.frame_selector ?? null,
1106
- text: compactProfileSetupSummaryText(result.text)
1107
- })).filter((item) => item.text).slice(-6);
1108
- return {
1109
- name: viewport.name,
1110
- expected_action_count: expectedActionCount ?? null,
1111
- ok: (expectedActionCount === void 0 ? results.length > 0 : results.length >= expectedActionCount) && failed.length === 0,
1112
- result_count: results.length,
1113
- observed_path: viewport.route?.observed ?? null,
1114
- final_url: viewport.url ?? null,
1115
- action_counts: profileSetupActionCounts(results),
1116
- frame_action_count: results.filter((result) => result.frame_selector).length,
1117
- frame_urls: profileSetupFrameUrls(viewport),
1118
- final_screenshot: viewport.screenshot_label ?? null,
1119
- final_screenshot_full_page: viewportFinalScreenshotFullPage ?? null,
1120
- setup_screenshots: profileSetupScreenshotLabels(results),
1121
- clicked_total: clickedItems.length,
1122
- clicked_truncated: clickedItems.length > clicked.length,
1123
- click_sequence_total: clickSequences.length,
1124
- click_sequence_truncated: clickSequences.length > sampledClickSequences.length,
1125
- click_sequences: sampledClickSequences,
1126
- click_count_action_total: clickCountValues.length,
1127
- click_count_value_total: clickCountValues.reduce((sum, value) => sum + value, 0),
1128
- window_call_until_total: windowCallUntilReceipts.length,
1129
- window_call_until_call_total: windowCallUntilCallCounts.reduce((sum, value) => sum + value, 0),
1130
- window_call_until_truncated: windowCallUntilReceipts.length > sampledWindowCallUntilReceipts.length,
1131
- window_call_until: sampledWindowCallUntilReceipts,
1132
- window_call_total: windowCallReceipts.length,
1133
- window_call_stored_total: windowCallStoredTotal,
1134
- window_call_captured_total: windowCallCapturedTotal,
1135
- window_call_truncated: windowCallReceipts.length > sampledWindowCallReceipts.length,
1136
- window_call: sampledWindowCallReceipts,
1137
- window_eval_total: windowEvalReceipts.length,
1138
- window_eval_stored_total: windowEvalStoredTotal,
1139
- window_eval_captured_total: windowEvalCapturedTotal,
1140
- window_eval_truncated: windowEvalReceipts.length > sampledWindowEvalReceipts.length,
1141
- window_eval: sampledWindowEvalReceipts,
1142
- deterministic_runtime_total: deterministicRuntimeReceipts.length,
1143
- deterministic_runtime_truncated: deterministicRuntimeReceipts.length > sampledDeterministicRuntimeReceipts.length,
1144
- deterministic_runtime: sampledDeterministicRuntimeReceipts,
1145
- set_range_value_total: rangeValueReceipts.length,
1146
- set_range_value_truncated: rangeValueReceipts.length > sampledRangeValueReceipts.length,
1147
- set_range_value: sampledRangeValueReceipts,
1148
- drag_total: dragReceipts.length,
1149
- drag_truncated: dragReceipts.length > sampledDragReceipts.length,
1150
- drag: sampledDragReceipts,
1151
- tap_total: tapReceipts.length,
1152
- tap_truncated: tapReceipts.length > sampledTapReceipts.length,
1153
- tap: sampledTapReceipts,
1154
- tap_until_total: tapUntilReceipts.length,
1155
- tap_until_tap_total: tapUntilTapCounts.reduce((sum, value) => sum + value, 0),
1156
- tap_until_truncated: tapUntilReceipts.length > sampledTapUntilReceipts.length,
1157
- tap_until: sampledTapUntilReceipts,
1158
- keyboard_total: keyboardReceipts.length,
1159
- keyboard_truncated: keyboardReceipts.length > sampledKeyboardReceipts.length,
1160
- keyboard: sampledKeyboardReceipts,
1161
- canvas_signature_total: canvasSignatureReceipts.length,
1162
- canvas_signature_truncated: canvasSignatureReceipts.length > sampledCanvasSignatureReceipts.length,
1163
- canvas_signature: sampledCanvasSignatureReceipts,
1164
- canvas_signature_stable_hash_groups: profileSetupCanvasSignatureStableHashGroups(results),
1165
- clicked,
1166
- text_samples,
1167
- failed: failed.map((result) => ({
1168
- ordinal: result.ordinal ?? null,
1169
- action: profileSetupResultAction(result),
1170
- selector: result.selector ?? null,
1171
- frame_selector: result.frame_selector ?? null,
1172
- reason: result.reason ?? result.error ?? null,
1173
- error: result.error ?? null,
1174
- case_insensitive_text: compactProfileSetupSummaryText(result.case_insensitive_text)
1175
- })),
1176
- optional_failed: optionalFailed.map((result) => ({
1177
- ordinal: result.ordinal ?? null,
1178
- action: profileSetupResultAction(result),
1179
- selector: result.selector ?? null,
1180
- frame_selector: result.frame_selector ?? null,
1181
- reason: result.reason ?? result.error ?? null,
1182
- error: result.error ?? null,
1183
- case_insensitive_text: compactProfileSetupSummaryText(result.case_insensitive_text)
1184
- }))
1185
- };
1186
- })
1187
- });
1188
- }
1189
- function normalizeName(value, fallback) {
1190
- const name = stringValue(value) || fallback;
1191
- return name.replace(/\s+/g, " ").trim();
1192
- }
1193
- function slugifyRiddleProofProfileName(value) {
1194
- return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "profile";
1195
- }
1196
- function normalizeViewport(input, index) {
1197
- if (!isRecord(input)) throw new Error(`target.viewports[${index}] must be an object.`);
1198
- const width = numberValue(input.width);
1199
- const height = numberValue(input.height);
1200
- if (!width || !height || width < 100 || height < 100) {
1201
- throw new Error(`target.viewports[${index}] requires numeric width and height >= 100.`);
1202
- }
1203
- const hasTouch = booleanValue(valueFromOwn(input, "hasTouch", "has_touch"));
1204
- const isMobile = booleanValue(valueFromOwn(input, "isMobile", "is_mobile"));
1205
- return {
1206
- name: normalizeName(input.name || input.label, `viewport-${index + 1}`),
1207
- width: Math.round(width),
1208
- height: Math.round(height),
1209
- ...hasTouch === void 0 ? {} : { hasTouch },
1210
- ...isMobile === void 0 ? {} : { isMobile }
1211
- };
1212
- }
1213
- function normalizeViewports(value) {
1214
- if (value === void 0) return [...DEFAULT_VIEWPORTS];
1215
- if (!Array.isArray(value) || value.length === 0) throw new Error("target.viewports must be a non-empty array.");
1216
- return value.map(normalizeViewport);
1217
- }
1218
- function isSupportedCheckType(value) {
1219
- return RIDDLE_PROOF_PROFILE_CHECK_TYPES.includes(value);
1220
- }
1221
- function normalizeSetupActionType(value, index) {
1222
- const normalizedInput = String(value || "").trim().replace(/-/g, "_");
1223
- const normalized = normalizedInput === "clear_browser_storage" ? "clear_storage" : normalizedInput === "reset_console" || normalizedInput === "clear_browser_console" || normalizedInput === "reset_browser_console" ? "clear_console" : normalizedInput === "pointer_drag" || normalizedInput === "mouse_drag" || normalizedInput === "drag_to" ? "drag" : normalizedInput === "pointer_tap" || normalizedInput === "touch_tap" || normalizedInput === "canvas_tap" ? "tap" : normalizedInput === "tap_until" || normalizedInput === "pointer_tap_until" || normalizedInput === "touch_tap_until" || normalizedInput === "canvas_tap_until" || normalizedInput === "tap_repeat_until" || normalizedInput === "repeat_tap_until" ? "tap_until" : normalizedInput === "keyboard_press" || normalizedInput === "key_press" ? "press" : normalizedInput === "keyboard_down" || normalizedInput === "key_down" || normalizedInput === "keydown" || normalizedInput === "press_down" ? "key_down" : normalizedInput === "keyboard_up" || normalizedInput === "key_up" || normalizedInput === "keyup" || normalizedInput === "press_up" || normalizedInput === "release_key" || normalizedInput === "key_release" ? "key_up" : normalizedInput === "set_slider_value" || normalizedInput === "slider_value" || normalizedInput === "set_slider" || normalizedInput === "set_range" || normalizedInput === "range_value" || normalizedInput === "range_input" || normalizedInput === "set_range_input" ? "set_range_value" : normalizedInput === "deterministic_runtime" || normalizedInput === "mock_runtime" || normalizedInput === "mock_random" || normalizedInput === "mock_random_queue" || normalizedInput === "seed_random_queue" || normalizedInput === "set_random_queue" || normalizedInput === "mock_clock" || normalizedInput === "set_mock_clock" || normalizedInput === "set_runtime_determinism" || normalizedInput === "runtime_determinism" ? "deterministic_runtime" : normalizedInput === "canvas_hash" || normalizedInput === "capture_canvas_hash" || normalizedInput === "capture_canvas_signature" || normalizedInput === "canvas_state_signature" ? "canvas_signature" : normalizedInput === "capture_screenshot" || normalizedInput === "save_screenshot" || normalizedInput === "setup_screenshot" ? "screenshot" : normalizedInput === "accept_dialog" || normalizedInput === "accept_dialogs" || normalizedInput === "confirm_dialog" || normalizedInput === "set_dialog_response" ? "dialog_response" : normalizedInput === "dismiss_dialog" || normalizedInput === "dismiss_dialogs" || normalizedInput === "cancel_dialog" ? "dialog_response" : normalizedInput === "window_call_until" || normalizedInput === "call_until" || normalizedInput === "window_call_repeat_until" || normalizedInput === "repeat_window_call_until" ? "window_call_until" : normalizedInput === "window_evaluate" || normalizedInput === "browser_eval" || normalizedInput === "browser_evaluate" || normalizedInput === "evaluate_script" || normalizedInput === "profile_script" ? "window_eval" : normalizedInput;
1224
- if (RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES.includes(normalized)) {
1225
- return normalized;
1226
- }
1227
- throw new Error(`target.setup_actions[${index}].type ${value || "(missing)"} is not supported. Supported actions: ${RIDDLE_PROOF_PROFILE_SETUP_ACTION_TYPES.join(", ")}`);
1228
- }
1229
- function normalizeSetupActionStorage(value, index) {
1230
- if (value === void 0 || value === null || value === "") return void 0;
1231
- const normalized = String(value).trim().replace(/-/g, "_");
1232
- if (normalized === "local" || normalized === "local_storage") return "local";
1233
- if (normalized === "session" || normalized === "session_storage") return "session";
1234
- if (normalized === "both" || normalized === "all") return "both";
1235
- throw new Error(`target.setup_actions[${index}].storage ${String(value)} is not supported. Supported storage values: local, session, both.`);
1236
- }
1237
- function normalizeSetupActionArgs(input, index) {
1238
- const argsInput = valueFromOwn(input, "args", "arguments", "args_json", "argsJson");
1239
- if (argsInput === void 0) return void 0;
1240
- if (!Array.isArray(argsInput)) {
1241
- throw new Error(`target.setup_actions[${index}] window_call/window_eval args must be an array.`);
1242
- }
1243
- return argsInput.map(toJsonValue);
1244
- }
1245
- function normalizeReturnSummaryFields(input, index) {
1246
- const fieldsInput = valueFromOwn(
1247
- input,
1248
- "return_summary_fields",
1249
- "returnSummaryFields",
1250
- "summary_fields",
1251
- "summaryFields",
1252
- "receipt_fields",
1253
- "receiptFields",
1254
- "return_receipt_fields",
1255
- "returnReceiptFields"
1256
- );
1257
- if (fieldsInput === void 0) return void 0;
1258
- if (!Array.isArray(fieldsInput)) {
1259
- throw new Error(`target.setup_actions[${index}].return_summary_fields must be an array.`);
1260
- }
1261
- return fieldsInput.map((field, fieldIndex) => {
1262
- if (typeof field === "string") {
1263
- const path2 = field.trim();
1264
- if (!path2) throw new Error(`target.setup_actions[${index}].return_summary_fields[${fieldIndex}] requires path.`);
1265
- return { path: path2 };
1266
- }
1267
- if (!isRecord(field)) {
1268
- throw new Error(`target.setup_actions[${index}].return_summary_fields[${fieldIndex}] must be a string path or object.`);
1269
- }
1270
- const path = stringFromOwn(field, "path", "key", "json_path", "jsonPath");
1271
- if (!path) throw new Error(`target.setup_actions[${index}].return_summary_fields[${fieldIndex}] requires path.`);
1272
- const label = stringFromOwn(field, "label", "name", "title");
1273
- return label ? { path, label } : { path };
1274
- });
1275
- }
1276
- function normalizeSetupActionRepeat(input, index) {
1277
- const repeat = numberValue(valueFromOwn(input, "repeat", "repeat_count", "repeatCount", "times"));
1278
- if (repeat === void 0) return void 0;
1279
- if (!Number.isInteger(repeat) || repeat < 1 || repeat > 100) {
1280
- throw new Error(`target.setup_actions[${index}].repeat must be an integer from 1 to 100.`);
1281
- }
1282
- return repeat;
1283
- }
1284
- function normalizeSetupActionClickCount(input, type, index) {
1285
- const clickCountInput = valueFromOwn(input, "click_count", "clickCount", "clicks");
1286
- if (clickCountInput === void 0) return void 0;
1287
- if (type !== "click") {
1288
- throw new Error(`target.setup_actions[${index}].click_count is only supported for click actions.`);
1289
- }
1290
- const clickCount = numberValue(clickCountInput);
1291
- if (clickCount === void 0 || !Number.isInteger(clickCount) || clickCount < 1 || clickCount > 10) {
1292
- throw new Error(`target.setup_actions[${index}].click_count must be an integer from 1 to 10.`);
1293
- }
1294
- return clickCount;
1295
- }
1296
- function normalizeSetupActionCoordinateMode(value, index) {
1297
- if (value === void 0 || value === null || value === "") return void 0;
1298
- const normalized = String(value).trim().replace(/-/g, "_").toLowerCase();
1299
- if (normalized === "pixels" || normalized === "pixel" || normalized === "px") return "pixels";
1300
- if (normalized === "ratio" || normalized === "relative" || normalized === "fraction") return "ratio";
1301
- throw new Error(`target.setup_actions[${index}].coordinate_mode ${String(value)} is not supported. Supported coordinate modes: pixels, ratio.`);
1302
- }
1303
- function normalizeSetupActionPointerType(value, type, index) {
1304
- if (value === void 0 || value === null || value === "") return void 0;
1305
- if (type !== "drag" && type !== "tap" && type !== "tap_until") {
1306
- throw new Error(`target.setup_actions[${index}].pointer_type is only supported for drag/tap/tap_until actions.`);
1307
- }
1308
- const normalized = String(value).trim().replace(/-/g, "_").toLowerCase();
1309
- if (normalized === "mouse") return "mouse";
1310
- if (normalized === "touch" || normalized === "finger") return "touch";
1311
- if (normalized === "pen" || normalized === "stylus") return "pen";
1312
- throw new Error(`target.setup_actions[${index}].pointer_type ${String(value)} is not supported. Supported pointer types: mouse, touch, pen.`);
1313
- }
1314
- function normalizeSetupActionScreenshotFullPage(input, type, index) {
1315
- const directFullPage = booleanValue(valueFromOwn(input, "full_page", "fullPage"));
1316
- const viewportOnly = booleanValue(valueFromOwn(input, "viewport_only", "viewportOnly", "viewport_screenshot", "viewportScreenshot"));
1317
- if (type !== "screenshot") {
1318
- if (directFullPage !== void 0 || viewportOnly !== void 0 || valueFromOwn(input, "screenshot_mode", "screenshotMode", "capture_mode", "captureMode") !== void 0) {
1319
- throw new Error(`target.setup_actions[${index}].full_page is only supported for screenshot actions.`);
1320
- }
1321
- return void 0;
1322
- }
1323
- const modeInput = stringFromOwn(input, "mode", "screenshot_mode", "screenshotMode", "capture_mode", "captureMode");
1324
- let modeFullPage;
1325
- if (modeInput) {
1326
- const mode = modeInput.trim().toLowerCase().replace(/[-\s]+/g, "_");
1327
- if (mode === "full_page" || mode === "fullpage" || mode === "page" || mode === "document") {
1328
- modeFullPage = true;
1329
- } else if (mode === "viewport" || mode === "view") {
1330
- modeFullPage = false;
1331
- } else {
1332
- throw new Error(`target.setup_actions[${index}].mode ${modeInput} is not supported for screenshot actions. Supported modes: full_page, viewport.`);
1333
- }
1334
- }
1335
- const values = [directFullPage, viewportOnly === void 0 ? void 0 : !viewportOnly, modeFullPage].filter((value) => value !== void 0);
1336
- if (!values.length) return void 0;
1337
- if (values.some((value) => value !== values[0])) {
1338
- throw new Error(`target.setup_actions[${index}] has conflicting screenshot full_page / viewport mode options.`);
1339
- }
1340
- return values[0];
1341
- }
1342
- function normalizeSetupActionRandomQueue(input, index) {
1343
- const rawQueue = valueFromOwn(
1344
- input,
1345
- "random_queue",
1346
- "randomQueue",
1347
- "random_values",
1348
- "randomValues",
1349
- "random_sequence",
1350
- "randomSequence",
1351
- "math_random",
1352
- "mathRandom"
1353
- );
1354
- if (rawQueue === void 0) return void 0;
1355
- if (!Array.isArray(rawQueue) || rawQueue.length === 0) {
1356
- throw new Error(`target.setup_actions[${index}].random_queue must be a non-empty array of numbers from 0 inclusive to 1 exclusive.`);
1357
- }
1358
- return rawQueue.map((item, queueIndex) => {
1359
- const value = numberValue(item);
1360
- if (value === void 0 || value < 0 || value >= 1) {
1361
- throw new Error(`target.setup_actions[${index}].random_queue[${queueIndex}] must be a finite number from 0 inclusive to 1 exclusive.`);
1362
- }
1363
- return value;
1364
- });
1365
- }
1366
- function normalizeSetupActionNonNegativeNumber(input, index, outputKey, ...keys) {
1367
- const rawValue = valueFromOwn(input, ...keys);
1368
- if (rawValue === void 0) return void 0;
1369
- const value = numberValue(rawValue);
1370
- if (value === void 0 || value < 0) {
1371
- throw new Error(`target.setup_actions[${index}].${outputKey} must be a finite non-negative number.`);
1372
- }
1373
- return value;
1374
- }
1375
- function normalizeSetupAction(input, index) {
1376
- if (!isRecord(input)) throw new Error(`target.setup_actions[${index}] must be an object.`);
1377
- const type = normalizeSetupActionType(stringValue(input.type), index);
1378
- const rawType = String(input.type || "").trim().replace(/-/g, "_").toLowerCase();
1379
- const selector = stringValue(input.selector);
1380
- const frameSelector = stringFromOwn(input, "frame_selector", "frameSelector", "iframe_selector", "iframeSelector");
1381
- const frameIndex = numberValue(valueFromOwn(input, "frame_index", "frameIndex", "iframe_index", "iframeIndex"));
1382
- if (frameIndex !== void 0 && (!Number.isInteger(frameIndex) || frameIndex < 0)) {
1383
- throw new Error(`target.setup_actions[${index}].frame_index must be a non-negative integer.`);
1384
- }
1385
- if ((type === "click" || type === "tap" || type === "tap_until" || type === "drag" || type === "fill" || type === "set_input_value" || type === "set_range_value" || type === "canvas_signature" || type === "wait_for_selector" || type === "wait_for_text" || type === "assert_text_visible" || type === "assert_text_absent" || type === "assert_selector_count") && !selector) {
1386
- throw new Error(`target.setup_actions[${index}] ${type} requires selector.`);
1387
- }
1388
- const fromX = type === "click" || type === "tap" || type === "tap_until" ? numberValue(valueFromOwn(input, "from_x", "fromX", "x", "click_x", "clickX", "start_x", "startX", "x1")) : numberValue(valueFromOwn(input, "from_x", "fromX", "start_x", "startX", "x1"));
1389
- const fromY = type === "click" || type === "tap" || type === "tap_until" ? numberValue(valueFromOwn(input, "from_y", "fromY", "y", "click_y", "clickY", "start_y", "startY", "y1")) : numberValue(valueFromOwn(input, "from_y", "fromY", "start_y", "startY", "y1"));
1390
- const toX = numberValue(valueFromOwn(input, "to_x", "toX", "end_x", "endX", "x2"));
1391
- const toY = numberValue(valueFromOwn(input, "to_y", "toY", "end_y", "endY", "y2"));
1392
- const coordinateMode = normalizeSetupActionCoordinateMode(valueFromOwn(input, "coordinate_mode", "coordinateMode", "coords", "units"), index);
1393
- const pointerType = normalizeSetupActionPointerType(valueFromOwn(input, "pointer_type", "pointerType", "input_type", "inputType"), type, index);
1394
- const durationMs = numberValue(input.duration_ms) ?? numberValue(input.durationMs);
1395
- const holdMs = type === "press" ? normalizeSetupActionNonNegativeNumber(input, index, "hold_ms", "hold_ms", "holdMs", "key_down_ms", "keyDownMs", "down_ms", "downMs") ?? durationMs : void 0;
1396
- if (type === "press" && holdMs !== void 0 && (holdMs < 0 || holdMs > 3e4)) {
1397
- throw new Error(`target.setup_actions[${index}].hold_ms must be a finite number from 0 to 30000.`);
1398
- }
1399
- if (type === "click") {
1400
- const hasClickCoordinate = fromX !== void 0 || fromY !== void 0;
1401
- if (hasClickCoordinate && (fromX === void 0 || fromY === void 0)) {
1402
- throw new Error(`target.setup_actions[${index}] click coordinates require both x and y.`);
1403
- }
1404
- if (hasClickCoordinate && fromX !== void 0 && fromY !== void 0) {
1405
- const clickCoordinates = [fromX, fromY];
1406
- if (coordinateMode === "ratio" && clickCoordinates.some((value2) => value2 < 0 || value2 > 1)) {
1407
- throw new Error(`target.setup_actions[${index}] click ratio coordinates must be between 0 and 1.`);
1408
- }
1409
- if ((coordinateMode === void 0 || coordinateMode === "pixels") && clickCoordinates.some((value2) => value2 < 0)) {
1410
- throw new Error(`target.setup_actions[${index}] click pixel coordinates must be non-negative.`);
1411
- }
1412
- }
1413
- }
1414
- if (type === "tap" || type === "tap_until") {
1415
- const hasTapCoordinate = fromX !== void 0 || fromY !== void 0;
1416
- if (hasTapCoordinate && (fromX === void 0 || fromY === void 0)) {
1417
- throw new Error(`target.setup_actions[${index}] ${type} coordinates require both x and y.`);
1418
- }
1419
- if (hasTapCoordinate && fromX !== void 0 && fromY !== void 0) {
1420
- const tapCoordinates = [fromX, fromY];
1421
- if (coordinateMode === "ratio" && tapCoordinates.some((value2) => value2 < 0 || value2 > 1)) {
1422
- throw new Error(`target.setup_actions[${index}] ${type} ratio coordinates must be between 0 and 1.`);
1423
- }
1424
- if ((coordinateMode === void 0 || coordinateMode === "pixels") && tapCoordinates.some((value2) => value2 < 0)) {
1425
- throw new Error(`target.setup_actions[${index}] ${type} pixel coordinates must be non-negative.`);
1426
- }
1427
- }
1428
- }
1429
- if (type === "drag") {
1430
- if (fromX === void 0 || fromY === void 0 || toX === void 0 || toY === void 0) {
1431
- throw new Error(`target.setup_actions[${index}] drag requires from_x, from_y, to_x, and to_y.`);
1432
- }
1433
- if (coordinateMode === "ratio" && [fromX, fromY, toX, toY].some((value2) => value2 < 0 || value2 > 1)) {
1434
- throw new Error(`target.setup_actions[${index}] drag ratio coordinates must be between 0 and 1.`);
1435
- }
1436
- if ((coordinateMode === void 0 || coordinateMode === "pixels") && [fromX, fromY, toX, toY].some((value2) => value2 < 0)) {
1437
- throw new Error(`target.setup_actions[${index}] drag pixel coordinates must be non-negative.`);
1438
- }
1439
- }
1440
- if (type === "wait_for_text" && !stringValue(input.text) && !stringValue(input.pattern)) {
1441
- throw new Error(`target.setup_actions[${index}] wait_for_text requires text or pattern.`);
1442
- }
1443
- if ((type === "assert_text_visible" || type === "assert_text_absent") && !stringValue(input.text) && !stringValue(input.pattern)) {
1444
- throw new Error(`target.setup_actions[${index}] ${type} requires text or pattern.`);
1445
- }
1446
- const expectedCount = numberValue(input.expected_count ?? input.expectedCount ?? input.count);
1447
- if (type === "assert_selector_count" && (expectedCount === void 0 || !Number.isInteger(expectedCount) || expectedCount < 0)) {
1448
- throw new Error(`target.setup_actions[${index}] ${type} requires non-negative integer expected_count.`);
1449
- }
1450
- const value = stringFromOwn(input, "value", "input_value", "inputValue");
1451
- const hasJsonValue = hasOwn(input, "value_json") || hasOwn(input, "valueJson") || hasOwn(input, "json");
1452
- if ((type === "fill" || type === "set_input_value" || type === "set_range_value") && value === void 0 && !hasJsonValue) {
1453
- throw new Error(`target.setup_actions[${index}] ${type} requires value.`);
1454
- }
1455
- const randomQueue = type === "deterministic_runtime" ? normalizeSetupActionRandomQueue(input, index) : void 0;
1456
- const deterministicNow = type === "deterministic_runtime" ? normalizeSetupActionNonNegativeNumber(input, index, "now", "now", "date_now", "dateNow", "mock_now", "mockNow", "clock", "timestamp", "time_ms", "timeMs") : void 0;
1457
- const deterministicAdvanceMs = type === "deterministic_runtime" ? normalizeSetupActionNonNegativeNumber(input, index, "advance_ms", "advance_ms", "advanceMs", "tick_ms", "tickMs", "add_ms", "addMs") : void 0;
1458
- const deterministicAppend = type === "deterministic_runtime" && booleanValue(valueFromOwn(input, "append", "append_random", "appendRandom")) === true;
1459
- const deterministicRestore = type === "deterministic_runtime" && booleanValue(valueFromOwn(input, "restore", "reset", "restore_originals", "restoreOriginals")) === true;
1460
- if (type === "deterministic_runtime" && randomQueue === void 0 && deterministicNow === void 0 && deterministicAdvanceMs === void 0 && !deterministicRestore) {
1461
- throw new Error(`target.setup_actions[${index}] deterministic_runtime requires random_queue, now, advance_ms, or restore.`);
1462
- }
1463
- const key = stringValue(input.key);
1464
- let dialogAccept;
1465
- if (type === "dialog_response") {
1466
- const acceptInput = valueFromOwn(input, "accept", "accepted", "should_accept", "shouldAccept");
1467
- const responseInput = stringFromOwn(input, "response", "dialog_response", "dialogResponse", "mode");
1468
- const response = String(responseInput || "").trim().toLowerCase().replace(/-/g, "_");
1469
- if (acceptInput !== void 0) {
1470
- dialogAccept = acceptInput !== false && String(acceptInput).toLowerCase() !== "false";
1471
- } else if (rawType === "dismiss_dialog" || rawType === "dismiss_dialogs" || rawType === "cancel_dialog") {
1472
- dialogAccept = false;
1473
- } else if (response === "dismiss" || response === "cancel" || response === "reject" || response === "no" || response === "false") {
1474
- dialogAccept = false;
1475
- } else {
1476
- dialogAccept = true;
1477
- }
1478
- }
1479
- if ((type === "press" || type === "key_down" || type === "key_up") && !key) {
1480
- throw new Error(`target.setup_actions[${index}] ${type} requires key.`);
1481
- }
1482
- if ((type === "local_storage" || type === "session_storage") && !key) {
1483
- throw new Error(`target.setup_actions[${index}] ${type} requires key.`);
1484
- }
1485
- if ((type === "local_storage" || type === "session_storage") && value === void 0 && !hasJsonValue) {
1486
- throw new Error(`target.setup_actions[${index}] ${type} requires value.`);
1487
- }
1488
- const path = stringFromOwn(input, "path", "function_path", "functionPath", "window_path", "windowPath", "state_path", "statePath");
1489
- if ((type === "window_call" || type === "window_call_until" || type === "assert_window_value" || type === "assert_window_number") && !path) {
1490
- throw new Error(`target.setup_actions[${index}] ${type} requires path.`);
1491
- }
1492
- const script = stringFromOwn(input, "script", "code", "source", "body");
1493
- if (type === "window_eval" && !script) {
1494
- throw new Error(`target.setup_actions[${index}] window_eval requires script.`);
1495
- }
1496
- const args = type === "window_call" || type === "window_call_until" || type === "window_eval" ? normalizeSetupActionArgs(input, index) : void 0;
1497
- const hasExpectedValue = hasOwn(input, "expected_value") || hasOwn(input, "expectedValue") || hasOwn(input, "expected") || hasOwn(input, "expect_value") || hasOwn(input, "expectValue") || hasOwn(input, "expect");
1498
- if (type === "assert_window_value" && !hasExpectedValue) {
1499
- throw new Error(`target.setup_actions[${index}] ${type} requires expected_value.`);
1500
- }
1501
- const rawExpectedValue = valueFromOwn(input, "expected_value", "expectedValue", "expected", "expect_value", "expectValue", "expect");
1502
- const minValue = numberValue(valueFromOwn(input, "min_value", "minValue", "minimum", "min", "at_least", "atLeast", "gte"));
1503
- const maxValue = numberValue(valueFromOwn(input, "max_value", "maxValue", "maximum", "max", "at_most", "atMost", "lte"));
1504
- if (type === "assert_window_number") {
1505
- if (!hasExpectedValue && minValue === void 0 && maxValue === void 0) {
1506
- throw new Error(`target.setup_actions[${index}] ${type} requires expected_value, min_value, or max_value.`);
1507
- }
1508
- if (hasExpectedValue && numberValue(rawExpectedValue) === void 0) {
1509
- throw new Error(`target.setup_actions[${index}] ${type} expected_value must be a finite number.`);
1510
- }
1511
- }
1512
- const hasExpectedReturn = hasOwn(input, "expect_return") || hasOwn(input, "expectReturn") || hasOwn(input, "expected_return") || hasOwn(input, "expectedReturn");
1513
- const storeReturnTo = stringFromOwn(
1514
- input,
1515
- "store_return_to",
1516
- "storeReturnTo",
1517
- "save_return_to",
1518
- "saveReturnTo",
1519
- "assign_return_to",
1520
- "assignReturnTo",
1521
- "return_state_path",
1522
- "returnStatePath",
1523
- "store_signature_to",
1524
- "storeSignatureTo",
1525
- "signature_path",
1526
- "signaturePath"
1527
- );
1528
- const captureReturn = input.capture_return === false || input.captureReturn === false || input.include_return === false || input.includeReturn === false || input.omit_return === true || input.omitReturn === true ? false : void 0;
1529
- const untilPath = stringFromOwn(input, "until_path", "untilPath", "until_state_path", "untilStatePath", "until_window_path", "untilWindowPath", "until");
1530
- const hasUntilExpectedValue = hasOwn(input, "until_expected_value") || hasOwn(input, "untilExpectedValue") || hasOwn(input, "until_expected") || hasOwn(input, "untilExpected") || hasOwn(input, "until_value") || hasOwn(input, "untilValue") || hasOwn(input, "expected_value") || hasOwn(input, "expectedValue") || hasOwn(input, "expected");
1531
- if (type === "window_call_until" || type === "tap_until") {
1532
- if (!untilPath) {
1533
- throw new Error(`target.setup_actions[${index}] ${type} requires until_path.`);
1534
- }
1535
- if (!hasUntilExpectedValue) {
1536
- throw new Error(`target.setup_actions[${index}] ${type} requires until_expected_value.`);
1537
- }
1538
- }
1539
- const maxCalls = numberValue(valueFromOwn(input, "max_calls", "maxCalls", "max_attempts", "maxAttempts", "attempts", "max_taps", "maxTaps", "tap_limit", "tapLimit"));
1540
- if ((type === "window_call_until" || type === "tap_until") && (maxCalls === void 0 || !Number.isInteger(maxCalls) || maxCalls < 1 || maxCalls > 100)) {
1541
- throw new Error(`target.setup_actions[${index}].max_calls must be an integer from 1 to 100.`);
1542
- }
1543
- const tapBurstSize = type === "tap_until" ? numberValue(valueFromOwn(input, "tap_burst_size", "tapBurstSize", "burst_size", "burstSize", "check_every_taps", "checkEveryTaps", "predicate_interval_taps", "predicateIntervalTaps")) : void 0;
1544
- if (type === "tap_until" && tapBurstSize !== void 0 && (!Number.isInteger(tapBurstSize) || tapBurstSize < 1 || tapBurstSize > 100)) {
1545
- throw new Error(`target.setup_actions[${index}].tap_burst_size must be an integer from 1 to 100.`);
1546
- }
1547
- const settleMs = type === "tap_until" ? numberValue(valueFromOwn(input, "settle_ms", "settleMs", "predicate_settle_ms", "predicateSettleMs", "post_burst_wait_ms", "postBurstWaitMs", "after_burst_ms", "afterBurstMs", "settle_after_tap_ms", "settleAfterTapMs")) : void 0;
1548
- if (type === "tap_until" && settleMs !== void 0 && (!Number.isInteger(settleMs) || settleMs < 0 || settleMs > 1e4)) {
1549
- throw new Error(`target.setup_actions[${index}].settle_ms must be an integer from 0 to 10000.`);
1550
- }
1551
- const intervalMs = numberValue(valueFromOwn(input, "interval_ms", "intervalMs", "poll_ms", "pollMs", "call_interval_ms", "callIntervalMs"));
1552
- if ((type === "window_call_until" || type === "tap_until") && intervalMs !== void 0 && (!Number.isInteger(intervalMs) || intervalMs < 0 || intervalMs > 5e3)) {
1553
- throw new Error(`target.setup_actions[${index}].interval_ms must be an integer from 0 to 5000.`);
1554
- }
1555
- const steps = numberValue(input.steps);
1556
- if (type === "drag" && steps !== void 0 && (!Number.isInteger(steps) || steps < 1 || steps > 100)) {
1557
- throw new Error(`target.setup_actions[${index}].steps must be an integer from 1 to 100.`);
1558
- }
1559
- return {
1560
- type,
1561
- selector,
1562
- frame_selector: frameSelector,
1563
- frame_index: frameIndex,
1564
- full_page: normalizeSetupActionScreenshotFullPage(input, type, index),
1565
- force: type === "click" && (input.force === true || input.force_click === true || input.forceClick === true),
1566
- fallback_to_tap: type === "click" && (input.fallback_to_tap === true || input.fallbackToTap === true || input.fallback_to_pointer_tap === true || input.fallbackToPointerTap === true || input.pointer_fallback === true || input.pointerFallback === true) || void 0,
1567
- click_count: normalizeSetupActionClickCount(input, type, index),
1568
- coordinate_mode: coordinateMode,
1569
- pointer_type: pointerType,
1570
- from_x: fromX,
1571
- from_y: fromY,
1572
- to_x: toX,
1573
- to_y: toY,
1574
- duration_ms: durationMs,
1575
- steps,
1576
- key,
1577
- hold_ms: holdMs,
1578
- value,
1579
- value_json: hasJsonValue ? toJsonValue(input.value_json ?? input.valueJson ?? input.json) : void 0,
1580
- random_queue: randomQueue,
1581
- now: deterministicNow,
1582
- advance_ms: deterministicAdvanceMs,
1583
- append: deterministicAppend || void 0,
1584
- restore: deterministicRestore || void 0,
1585
- label: stringFromOwn(input, "label", "name", "screenshot_label", "screenshotLabel"),
1586
- script,
1587
- path,
1588
- args,
1589
- expect_return: hasExpectedReturn ? toJsonValue(valueFromOwn(input, "expect_return", "expectReturn", "expected_return", "expectedReturn")) : void 0,
1590
- store_return_to: storeReturnTo,
1591
- capture_return: captureReturn,
1592
- return_summary_fields: normalizeReturnSummaryFields(input, index),
1593
- compare_to: stringFromOwn(input, "compare_to", "compareTo", "previous_signature_path", "previousSignaturePath", "previous_path", "previousPath", "changed_from", "changedFrom"),
1594
- expect_changed: booleanValue(valueFromOwn(input, "expect_changed", "expectChanged", "should_change", "shouldChange", "changed")),
1595
- until_path: untilPath,
1596
- until_expected_value: hasUntilExpectedValue ? toJsonValue(valueFromOwn(input, "until_expected_value", "untilExpectedValue", "until_expected", "untilExpected", "until_value", "untilValue", "expected_value", "expectedValue", "expected")) : void 0,
1597
- expected_path: stringFromOwn(input, "expected_path", "expectedPath", "expected_terminal_path", "expectedTerminalPath"),
1598
- expected_url: stringFromOwn(input, "expected_url", "expectedUrl", "expected_terminal_url", "expectedTerminalUrl"),
1599
- max_calls: maxCalls,
1600
- tap_burst_size: tapBurstSize,
1601
- settle_ms: settleMs,
1602
- interval_ms: intervalMs,
1603
- expected_value: hasExpectedValue ? toJsonValue(rawExpectedValue) : void 0,
1604
- min_value: minValue,
1605
- max_value: maxValue,
1606
- text: stringValue(input.text),
1607
- pattern: stringValue(input.pattern),
1608
- flags: stringValue(input.flags),
1609
- accept: dialogAccept,
1610
- prompt_text: stringFromOwn(input, "prompt_text", "promptText", "prompt_value", "promptValue"),
1611
- message_text: stringFromOwn(input, "message_text", "messageText", "dialog_text", "dialogText"),
1612
- message_pattern: stringFromOwn(input, "message_pattern", "messagePattern", "dialog_pattern", "dialogPattern"),
1613
- index: numberValue(valueFromOwn(input, "index", "target_index", "targetIndex")),
1614
- expected_count: expectedCount,
1615
- ms: numberValue(input.ms) ?? numberValue(input.wait_ms) ?? numberValue(input.waitMs),
1616
- timeout_ms: numberValue(input.timeout_ms) ?? numberValue(input.timeoutMs),
1617
- after_ms: numberValue(input.after_ms) ?? numberValue(input.afterMs),
1618
- repeat: normalizeSetupActionRepeat(input, index),
1619
- reload: input.reload === true,
1620
- storage: normalizeSetupActionStorage(input.storage, index),
1621
- viewports: normalizeStringList(input.viewports ?? input.viewport_names ?? input.viewportNames, `target.setup_actions[${index}] viewports`),
1622
- optional: input.optional === true || input.required === false,
1623
- continue_on_failure: input.continue_on_failure === true || input.continueOnFailure === true
1624
- };
1625
- }
1626
- function normalizeSetupActions(value) {
1627
- if (value === void 0) return void 0;
1628
- if (!Array.isArray(value)) throw new Error("target.setup_actions must be an array.");
1629
- return value.map(normalizeSetupAction);
1630
- }
1631
- function normalizeTargetScreenshotFullPage(input) {
1632
- const directFullPage = booleanValue(valueFromOwn(
1633
- input,
1634
- "screenshot_full_page",
1635
- "screenshotFullPage",
1636
- "final_screenshot_full_page",
1637
- "finalScreenshotFullPage",
1638
- "full_page_screenshots",
1639
- "fullPageScreenshots"
1640
- ));
1641
- const viewportOnly = booleanValue(valueFromOwn(
1642
- input,
1643
- "viewport_screenshots",
1644
- "viewportScreenshots",
1645
- "viewport_only_screenshots",
1646
- "viewportOnlyScreenshots"
1647
- ));
1648
- const modeInput = stringFromOwn(input, "screenshot_mode", "screenshotMode", "final_screenshot_mode", "finalScreenshotMode");
1649
- let modeFullPage;
1650
- if (modeInput) {
1651
- const mode = modeInput.trim().toLowerCase().replace(/[-\s]+/g, "_");
1652
- if (mode === "full_page" || mode === "fullpage" || mode === "page" || mode === "document") {
1653
- modeFullPage = true;
1654
- } else if (mode === "viewport" || mode === "view") {
1655
- modeFullPage = false;
1656
- } else {
1657
- throw new Error(`target.screenshot_mode ${modeInput} is not supported. Supported modes: full_page, viewport.`);
1658
- }
1659
- }
1660
- const values = [directFullPage, viewportOnly === void 0 ? void 0 : !viewportOnly, modeFullPage].filter((value) => value !== void 0);
1661
- if (!values.length) return void 0;
1662
- if (values.some((value) => value !== values[0])) {
1663
- throw new Error("target has conflicting screenshot full_page / viewport mode options.");
1664
- }
1665
- return values[0];
1666
- }
1667
- function normalizeNetworkMock(input, index) {
1668
- if (!isRecord(input)) throw new Error(`target.network_mocks[${index}] must be an object.`);
1669
- const url = stringValue(input.url) || stringValue(input.glob) || stringValue(input.pattern);
1670
- if (!url) throw new Error(`target.network_mocks[${index}] requires url.`);
1671
- const payload = normalizeNetworkMockResponsePayload(input, `target.network_mocks[${index}]`);
1672
- const responsesInput = input.responses ?? input.sequence;
1673
- const responses = normalizeNetworkMockResponses(responsesInput, index, payload);
1674
- const requestBody = normalizeNetworkMockRequestBodyConstraints(input, `target.network_mocks[${index}]`);
1675
- const requiredHitCount = numberValue(
1676
- input.required_hit_count ?? input.requiredHitCount ?? input.required_hits ?? input.requiredHits ?? input.min_hits ?? input.minHits
1677
- );
1678
- if (requiredHitCount !== void 0 && (!Number.isInteger(requiredHitCount) || requiredHitCount < 1)) {
1679
- throw new Error(`target.network_mocks[${index}].required_hit_count must be a positive integer.`);
1680
- }
1681
- const forbidden = input.forbidden === true || input.must_not_hit === true || input.mustNotHit === true || input.should_not_run === true || input.shouldNotRun === true;
1682
- const configuredMaxHitCount = numberValue(
1683
- input.max_hit_count ?? input.maxHitCount ?? input.max_hits ?? input.maxHits
1684
- );
1685
- if (configuredMaxHitCount !== void 0 && (!Number.isInteger(configuredMaxHitCount) || configuredMaxHitCount < 0)) {
1686
- throw new Error(`target.network_mocks[${index}].max_hit_count must be a non-negative integer.`);
1687
- }
1688
- if (forbidden && configuredMaxHitCount !== void 0 && configuredMaxHitCount !== 0) {
1689
- throw new Error(`target.network_mocks[${index}].forbidden cannot be combined with max_hit_count greater than 0.`);
1690
- }
1691
- const maxHitCount = forbidden ? 0 : configuredMaxHitCount;
1692
- const required = input.required === false || maxHitCount === 0 && input.required !== true ? false : true;
1693
- const effectiveRequiredHitCount = required ? requiredHitCount ?? (Array.isArray(responses) && responses.length ? responses.length : 1) : 0;
1694
- if (maxHitCount !== void 0 && effectiveRequiredHitCount > maxHitCount) {
1695
- throw new Error(`target.network_mocks[${index}].max_hit_count cannot be less than its required hit count.`);
1696
- }
1697
- const sequenceScopeInput = stringValue(
1698
- input.sequence_scope ?? input.sequenceScope ?? input.response_sequence_scope ?? input.responseSequenceScope
1699
- );
1700
- let sequenceScope;
1701
- if (sequenceScopeInput) {
1702
- const normalizedScope = sequenceScopeInput.toLowerCase().replace(/[-\s]+/g, "_");
1703
- if (normalizedScope === "global" || normalizedScope === "profile" || normalizedScope === "run") {
1704
- sequenceScope = "global";
1705
- } else if (normalizedScope === "viewport" || normalizedScope === "per_viewport" || normalizedScope === "viewport_scoped") {
1706
- sequenceScope = "viewport";
1707
- } else {
1708
- throw new Error(`target.network_mocks[${index}].sequence_scope must be "global" or "viewport".`);
1709
- }
1710
- }
1711
- return {
1712
- ...payload,
1713
- label: normalizeName(input.label || input.name, `network-mock-${index + 1}`),
1714
- url,
1715
- method: stringValue(input.method)?.toUpperCase(),
1716
- responses,
1717
- repeat_responses: input.repeat_responses === true || input.repeatResponses === true || input.cycle_responses === true || input.cycleResponses === true,
1718
- sequence_scope: sequenceScope,
1719
- required_hit_count: requiredHitCount,
1720
- max_hit_count: maxHitCount,
1721
- forbidden,
1722
- required,
1723
- capture_request_body: requestBody.capture_request_body,
1724
- request_body_contains: requestBody.request_body_contains,
1725
- request_body_patterns: requestBody.request_body_patterns,
1726
- request_body_not_contains: requestBody.request_body_not_contains,
1727
- request_body_not_patterns: requestBody.request_body_not_patterns
1728
- };
1729
- }
1730
- function normalizeNetworkMockRequestBodyConstraints(input, label) {
1731
- const requestBodyContains = normalizeStringList(
1732
- input.request_body_contains ?? input.requestBodyContains ?? input.body_contains ?? input.bodyContains,
1733
- `${label}.request_body_contains`
1734
- );
1735
- const requestBodyPatterns = normalizeStringList(
1736
- input.request_body_patterns ?? input.requestBodyPatterns ?? input.body_patterns ?? input.bodyPatterns,
1737
- `${label}.request_body_patterns`
1738
- );
1739
- validateRegexPatterns(requestBodyPatterns, `${label}.request_body_patterns`);
1740
- const requestBodyNotContains = normalizeStringList(
1741
- input.request_body_not_contains ?? input.requestBodyNotContains ?? input.request_body_absent ?? input.requestBodyAbsent ?? input.body_not_contains ?? input.bodyNotContains ?? input.body_absent ?? input.bodyAbsent,
1742
- `${label}.request_body_not_contains`
1743
- );
1744
- const requestBodyNotPatterns = normalizeStringList(
1745
- input.request_body_not_patterns ?? input.requestBodyNotPatterns ?? input.request_body_forbidden_patterns ?? input.requestBodyForbiddenPatterns ?? input.body_not_patterns ?? input.bodyNotPatterns ?? input.body_forbidden_patterns ?? input.bodyForbiddenPatterns,
1746
- `${label}.request_body_not_patterns`
1747
- );
1748
- validateRegexPatterns(requestBodyNotPatterns, `${label}.request_body_not_patterns`);
1749
- return {
1750
- capture_request_body: input.capture_request_body === true || input.captureRequestBody === true || Boolean(requestBodyContains?.length) || Boolean(requestBodyPatterns?.length) || Boolean(requestBodyNotContains?.length) || Boolean(requestBodyNotPatterns?.length),
1751
- request_body_contains: requestBodyContains,
1752
- request_body_patterns: requestBodyPatterns,
1753
- request_body_not_contains: requestBodyNotContains,
1754
- request_body_not_patterns: requestBodyNotPatterns
1755
- };
1756
- }
1757
- function normalizeNetworkMockResponsePayload(input, label, defaults = {}) {
1758
- const status = numberValue(input.status) ?? defaults.status ?? 200;
1759
- if (!Number.isInteger(status) || status < 100 || status > 599) {
1760
- throw new Error(`${label}.status must be an HTTP status code.`);
1761
- }
1762
- const body = stringValue(input.body) ?? stringValue(input.body_text) ?? stringValue(input.bodyText) ?? defaults.body;
1763
- const hasJsonBody = Object.prototype.hasOwnProperty.call(input, "body_json") || Object.prototype.hasOwnProperty.call(input, "bodyJson") || Object.prototype.hasOwnProperty.call(input, "json");
1764
- const requestBody = normalizeNetworkMockRequestBodyConstraints(input, label);
1765
- const abort = normalizeNetworkMockAbort(input, label, defaults.abort, defaults.abort_error_code);
1766
- return {
1767
- label: stringValue(input.label) || stringValue(input.name) || defaults.label,
1768
- status,
1769
- content_type: stringValue(input.content_type) || stringValue(input.contentType) || defaults.content_type,
1770
- headers: stringRecord(input.headers) || defaults.headers,
1771
- body,
1772
- body_json: hasJsonBody ? toJsonValue(input.body_json ?? input.bodyJson ?? input.json) : defaults.body_json,
1773
- delay_ms: normalizeNetworkMockDelay(input, label, defaults.delay_ms),
1774
- abort: abort.abort,
1775
- abort_error_code: abort.abort_error_code,
1776
- capture_request_body: requestBody.capture_request_body,
1777
- request_body_contains: requestBody.request_body_contains,
1778
- request_body_patterns: requestBody.request_body_patterns,
1779
- request_body_not_contains: requestBody.request_body_not_contains,
1780
- request_body_not_patterns: requestBody.request_body_not_patterns
1781
- };
1782
- }
1783
- function normalizeNetworkMockAbort(input, label, defaultAbort, defaultErrorCode) {
1784
- const abortInput = input.abort ?? input.route_abort ?? input.routeAbort;
1785
- const explicitAbort = typeof abortInput === "string" ? abortInput.trim().length > 0 : abortInput === true;
1786
- const abort = explicitAbort || defaultAbort === true;
1787
- if (!abort) return {};
1788
- const codeInput = stringValue(
1789
- typeof abortInput === "string" ? abortInput : input.abort_error_code ?? input.abortErrorCode ?? input.abort_error ?? input.abortError ?? input.network_error ?? input.networkError
1790
- ) || defaultErrorCode || "failed";
1791
- const abort_error_code = codeInput.toLowerCase();
1792
- if (!RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES.includes(abort_error_code)) {
1793
- throw new Error(`${label}.abort_error_code must be one of ${RIDDLE_PROOF_PROFILE_NETWORK_ABORT_ERROR_CODES.join(", ")}.`);
1794
- }
1795
- return { abort: true, abort_error_code };
1796
- }
1797
- function normalizeNetworkMockDelay(input, label, defaultValue) {
1798
- const value = numberValue(
1799
- input.delay_ms ?? input.delayMs ?? input.wait_ms ?? input.waitMs ?? input.latency_ms ?? input.latencyMs
1800
- ) ?? defaultValue;
1801
- if (value === void 0) return void 0;
1802
- if (!Number.isInteger(value) || value < 0 || value > 6e4) {
1803
- throw new Error(`${label}.delay_ms must be an integer from 0 to 60000.`);
1804
- }
1805
- return value;
1806
- }
1807
- function normalizeNetworkMockResponses(value, mockIndex, defaults) {
1808
- if (value === void 0) return void 0;
1809
- if (!Array.isArray(value)) throw new Error(`target.network_mocks[${mockIndex}].responses must be an array.`);
1810
- if (!value.length) throw new Error(`target.network_mocks[${mockIndex}].responses must not be empty.`);
1811
- const responseDefaults = {
1812
- label: void 0,
1813
- status: defaults.status,
1814
- content_type: defaults.content_type,
1815
- headers: defaults.headers,
1816
- body: defaults.body,
1817
- body_json: defaults.body_json,
1818
- delay_ms: defaults.delay_ms,
1819
- abort: defaults.abort,
1820
- abort_error_code: defaults.abort_error_code
1821
- };
1822
- return value.map((response, responseIndex) => {
1823
- if (!isRecord(response)) {
1824
- throw new Error(`target.network_mocks[${mockIndex}].responses[${responseIndex}] must be an object.`);
1825
- }
1826
- return normalizeNetworkMockResponsePayload(
1827
- response,
1828
- `target.network_mocks[${mockIndex}].responses[${responseIndex}]`,
1829
- responseDefaults
1830
- );
1831
- });
1832
- }
1833
- function normalizeNetworkMocks(value) {
1834
- if (value === void 0) return void 0;
1835
- if (!Array.isArray(value)) throw new Error("target.network_mocks must be an array.");
1836
- return value.map(normalizeNetworkMock);
1837
- }
1838
- function profileStringList(value) {
1839
- return Array.isArray(value) ? value.map((item) => String(item)).filter(Boolean) : [];
1840
- }
1841
- function responseHasRequestBodyContract(response) {
1842
- if (!response) return false;
1843
- return profileStringList(response.request_body_contains).length > 0 || profileStringList(response.request_body_patterns).length > 0 || profileStringList(response.request_body_not_contains).length > 0 || profileStringList(response.request_body_not_patterns).length > 0;
1844
- }
1845
- function responseHasOnlyPositiveTextSelector(response) {
1846
- if (!response) return false;
1847
- return profileStringList(response.request_body_contains).length > 0 && profileStringList(response.request_body_patterns).length === 0 && profileStringList(response.request_body_not_contains).length === 0 && profileStringList(response.request_body_not_patterns).length === 0;
1848
- }
1849
- function responseMayShadowLaterRequestBodyMatch(earlier, later) {
1850
- if (!responseHasOnlyPositiveTextSelector(earlier) || !responseHasRequestBodyContract(later)) return false;
1851
- const earlierContains = profileStringList(earlier.request_body_contains);
1852
- const laterContains = profileStringList(later.request_body_contains);
1853
- if (!laterContains.length) return false;
1854
- return earlierContains.every((fragment) => laterContains.includes(fragment));
1855
- }
1856
- function responseLabel(response, index) {
1857
- return response.label ? `"${response.label}"` : `responses[${index}]`;
1858
- }
1859
- function collectRiddleProofProfileWarnings(profile) {
1860
- const warnings = [];
1861
- for (const [mockIndex, mock] of (profile.target.network_mocks || []).entries()) {
1862
- const responses = Array.isArray(mock.responses) ? mock.responses : [];
1863
- if (responses.length < 2) continue;
1864
- for (let laterIndex = 1; laterIndex < responses.length; laterIndex += 1) {
1865
- const later = responses[laterIndex];
1866
- if (!responseHasRequestBodyContract(later)) continue;
1867
- for (let earlierIndex = 0; earlierIndex < laterIndex; earlierIndex += 1) {
1868
- const earlier = responses[earlierIndex];
1869
- if (!responseMayShadowLaterRequestBodyMatch(earlier, later)) continue;
1870
- const mockLabel = mock.label ? ` (${mock.label})` : "";
1871
- warnings.push(
1872
- `target.network_mocks[${mockIndex}]${mockLabel} ${responseLabel(earlier, earlierIndex)} can shadow ${responseLabel(later, laterIndex)} because the earlier request_body_contains fragments are a subset of the later response and have no negative or pattern disambiguator. First matching request-body response wins.`
1873
- );
1874
- break;
1875
- }
1876
- }
1877
- }
1878
- return warnings;
1879
- }
1880
- function profileStatusProbeCounts(profile) {
1881
- let httpStatus = 0;
1882
- let linkStatus = 0;
1883
- for (const check of profile.checks || []) {
1884
- if (check.type === "http_status") httpStatus += 1;
1885
- if (check.type === "link_status" || check.type === "artifact_link_status") linkStatus += 1;
1886
- }
1887
- return { httpStatus, linkStatus };
1888
- }
1889
- function riddleApiStrictSafetyWarnings(blocker) {
1890
- const rawWarnings = Array.isArray(blocker?.warnings) ? blocker.warnings.filter((warning) => typeof warning === "string") : [];
1891
- const errorText = typeof blocker?.error === "string" ? blocker.error.toLowerCase() : "";
1892
- const hasSafetyError = errorText.includes("potentially unsafe operations");
1893
- const hasDirectNetworkWarning = rawWarnings.some((warning) => warning.toLowerCase().includes("direct network operations"));
1894
- return hasSafetyError || hasDirectNetworkWarning ? rawWarnings : [];
1895
- }
1896
- function collectRiddleProofProfileEnvironmentBlockedWarnings(profile, blocker) {
1897
- const warnings = collectRiddleProofProfileWarnings(profile);
1898
- const safetyWarnings = riddleApiStrictSafetyWarnings(blocker);
1899
- if (!safetyWarnings.length) return warnings;
1900
- const counts = profileStatusProbeCounts(profile);
1901
- const statusProbeCount = counts.httpStatus + counts.linkStatus;
1902
- if (!statusProbeCount) return warnings;
1903
- const parts = [
1904
- counts.httpStatus ? `${counts.httpStatus} http_status` : "",
1905
- counts.linkStatus ? `${counts.linkStatus} link_status/artifact_link_status` : ""
1906
- ].filter(Boolean);
1907
- warnings.push(
1908
- `Riddle API strict script validation blocked a hosted profile runner with ${parts.join(" and ")} check(s). These checks intentionally collect endpoint/link evidence from inside the generated browser runner; hosted run-profile defaults to --strict=false, so omit --strict=true or rerun with --strict=false for trusted generated profile runs.`
1909
- );
1910
- return warnings;
1911
- }
1912
- function normalizeRouteInventoryPath(value, label) {
1913
- const path = stringValue(value);
1914
- if (!path) throw new Error(`${label} requires path.`);
1915
- if (!path.startsWith("/")) throw new Error(`${label}.path must start with /.`);
1916
- return normalizeRoutePath(path);
1917
- }
1918
- function normalizeRouteInventoryRoute(input, index) {
1919
- if (typeof input === "string") return { path: normalizeRouteInventoryPath(input, `checks route_inventory expected_routes[${index}]`) };
1920
- if (!isRecord(input)) throw new Error(`checks route_inventory expected_routes[${index}] must be a string or object.`);
1921
- return {
1922
- name: stringValue(input.name),
1923
- path: normalizeRouteInventoryPath(input.path, `checks route_inventory expected_routes[${index}]`)
1924
- };
1925
- }
1926
- function normalizeRouteInventoryRoutes(value, index) {
1927
- if (value === void 0) return void 0;
1928
- if (!Array.isArray(value) || value.length === 0) {
1929
- throw new Error(`checks[${index}] route_inventory expected_routes must be a non-empty array.`);
1930
- }
1931
- const routes = value.map(normalizeRouteInventoryRoute);
1932
- const seen = /* @__PURE__ */ new Set();
1933
- for (const route of routes) {
1934
- if (seen.has(route.path)) throw new Error(`checks[${index}] route_inventory expected_routes contains duplicate path ${route.path}.`);
1935
- seen.add(route.path);
1936
- }
1937
- return routes;
1938
- }
1939
- function normalizeExpectedTexts(value, index) {
1940
- if (value === void 0) return void 0;
1941
- if (!Array.isArray(value) || value.length === 0) {
1942
- throw new Error(`checks[${index}] selector_text_order expected_texts must be a non-empty array.`);
1943
- }
1944
- const texts = value.map((item) => String(item).replace(/\s+/g, " ").trim()).filter(Boolean);
1945
- if (!texts.length) throw new Error(`checks[${index}] selector_text_order expected_texts must contain non-empty strings.`);
1946
- return texts;
1947
- }
1948
- function normalizeStringList(value, label) {
1949
- if (value === void 0) return void 0;
1950
- if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);
1951
- const values = value.map((item) => String(item).replace(/\s+/g, " ").trim()).filter(Boolean);
1952
- if (!values.length) throw new Error(`${label} must contain non-empty strings.`);
1953
- return values;
1954
- }
1955
- function normalizeHttpStatus(value, label) {
1956
- if (value === void 0) return void 0;
1957
- const status = numberValue(value);
1958
- if (status === void 0 || !Number.isInteger(status) || status < 100 || status > 599) {
1959
- throw new Error(`${label} must be an HTTP status code.`);
1960
- }
1961
- return status;
1962
- }
1963
- function normalizeHttpStatuses(value, label) {
1964
- if (value === void 0) return void 0;
1965
- if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);
1966
- if (!value.length) throw new Error(`${label} must not be empty.`);
1967
- const statuses = value.map((item, index) => normalizeHttpStatus(item, `${label}[${index}]`));
1968
- return Array.from(new Set(statuses));
1969
- }
1970
- function normalizePositiveInteger(value, label, max) {
1971
- if (value === void 0) return void 0;
1972
- const number = numberValue(value);
1973
- if (number === void 0 || !Number.isInteger(number) || number < 1 || max !== void 0 && number > max) {
1974
- throw new Error(`${label} must be an integer from 1 to ${max ?? "unbounded"}.`);
1975
- }
1976
- return number;
1977
- }
1978
- function validateRegexPatterns(patterns, label) {
1979
- for (const pattern of patterns || []) {
1980
- try {
1981
- new RegExp(pattern);
1982
- } catch (error) {
1983
- const message = error instanceof Error ? error.message : String(error);
1984
- throw new Error(`${label} contains invalid regex ${JSON.stringify(pattern)}: ${message}`);
1985
- }
1986
- }
1987
- }
1988
- function normalizeHttpStatusBodyJsonAssertions(value, label) {
1989
- if (value === void 0) return void 0;
1990
- if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);
1991
- if (!value.length) throw new Error(`${label} must not be empty.`);
1992
- return value.map((item, index) => {
1993
- const itemLabel = `${label}[${index}]`;
1994
- if (typeof item === "string") {
1995
- const path2 = stringValue(item);
1996
- if (!path2) throw new Error(`${itemLabel} path must not be empty.`);
1997
- return { path: path2, exists: true };
1998
- }
1999
- if (!isRecord(item)) throw new Error(`${itemLabel} must be an object or JSON path string.`);
2000
- const path = stringFromOwn(item, "path", "json_path", "jsonPath", "key");
2001
- if (!path) throw new Error(`${itemLabel}.path is required.`);
2002
- const assertion = {
2003
- label: stringValue(item.label),
2004
- path
2005
- };
2006
- const exists = booleanValue(valueFromOwn(item, "exists", "present"));
2007
- if (exists !== void 0) assertion.exists = exists;
2008
- const type = stringValue(valueFromOwn(item, "type", "value_type", "valueType"));
2009
- if (type !== void 0) {
2010
- const allowedTypes = ["array", "boolean", "null", "number", "object", "string"];
2011
- if (!allowedTypes.includes(type)) {
2012
- throw new Error(`${itemLabel}.type must be one of ${allowedTypes.join(", ")}.`);
2013
- }
2014
- assertion.type = type;
2015
- }
2016
- const equalsValue = valueFromOwn(item, "equals", "expected", "expected_value", "expectedValue", "value");
2017
- if (equalsValue !== void 0) assertion.equals = toJsonValue(equalsValue);
2018
- const notEqualsValue = valueFromOwn(item, "not_equals", "notEquals", "forbidden", "forbidden_value", "forbiddenValue");
2019
- if (notEqualsValue !== void 0) assertion.not_equals = toJsonValue(notEqualsValue);
2020
- const containsValue = valueFromOwn(item, "contains", "includes", "contains_value", "containsValue", "include");
2021
- if (containsValue !== void 0) assertion.contains = toJsonValue(containsValue);
2022
- if (assertion.exists === void 0 && assertion.type === void 0 && !hasOwn(assertion, "equals") && !hasOwn(assertion, "not_equals") && !hasOwn(assertion, "contains")) {
2023
- assertion.exists = true;
2024
- }
2025
- return assertion;
2026
- });
2027
- }
2028
- function isDialogCountCheckType(type) {
2029
- return type === "dialog_count_equals" || type === "dialog_accept_count_equals" || type === "dialog_dismiss_count_equals";
2030
- }
2031
- function dialogCountFieldForCheckType(type) {
2032
- if (type === "dialog_accept_count_equals") return "dialog_accept_count";
2033
- if (type === "dialog_dismiss_count_equals") return "dialog_dismiss_count";
2034
- return "dialog_count";
2035
- }
2036
- function normalizeOrderedTraceEvents(value, label) {
2037
- if (value === void 0) return void 0;
2038
- if (!Array.isArray(value) || !value.length) throw new Error(`${label} must be a non-empty array.`);
2039
- const seenLabels = /* @__PURE__ */ new Set();
2040
- return value.map((item, eventIndex) => {
2041
- const eventLabel = `${label}[${eventIndex}]`;
2042
- if (!isRecord(item)) throw new Error(`${eventLabel} must be an object.`);
2043
- const name = stringFromOwn(item, "label", "name", "event");
2044
- if (!name) throw new Error(`${eventLabel}.label is required.`);
2045
- if (seenLabels.has(name)) throw new Error(`${eventLabel}.label must be unique.`);
2046
- seenLabels.add(name);
2047
- const predicatesInput = item.predicates ?? item.all ?? item.where;
2048
- if (!Array.isArray(predicatesInput) || !predicatesInput.length) {
2049
- throw new Error(`${eventLabel}.predicates must be a non-empty array.`);
2050
- }
2051
- const predicates = predicatesInput.map((predicateInput, predicateIndex) => {
2052
- const predicateLabel = `${eventLabel}.predicates[${predicateIndex}]`;
2053
- if (!isRecord(predicateInput)) throw new Error(`${predicateLabel} must be an object.`);
2054
- const path = stringFromOwn(predicateInput, "path", "field", "key");
2055
- if (!path) throw new Error(`${predicateLabel}.path is required.`);
2056
- const op = stringFromOwn(predicateInput, "op", "operator");
2057
- if (!op || !RIDDLE_PROOF_ORDERED_TRACE_OPERATORS.includes(op)) {
2058
- throw new Error(`${predicateLabel}.op must be one of ${RIDDLE_PROOF_ORDERED_TRACE_OPERATORS.join(", ")}.`);
2059
- }
2060
- const requiresValue = !["exists", "truthy", "falsy"].includes(op);
2061
- const hasValue = hasOwn(predicateInput, "value") || hasOwn(predicateInput, "expected");
2062
- if (requiresValue && !hasValue) throw new Error(`${predicateLabel}.value is required for ${op}.`);
2063
- const value2 = hasOwn(predicateInput, "value") ? predicateInput.value : predicateInput.expected;
2064
- if (["gt", "gte", "lt", "lte", "abs_gt", "abs_gte", "abs_lt", "abs_lte"].includes(op)) {
2065
- if (typeof value2 !== "number" || !Number.isFinite(value2)) {
2066
- throw new Error(`${predicateLabel}.value must be a finite number for ${op}.`);
2067
- }
2068
- if (op.startsWith("abs_") && value2 < 0) {
2069
- throw new Error(`${predicateLabel}.value must be non-negative for ${op}.`);
2070
- }
2071
- }
2072
- return {
2073
- path,
2074
- op,
2075
- value: requiresValue ? toJsonValue(value2) : void 0
2076
- };
2077
- });
2078
- return { label: name, predicates };
2079
- });
2080
- }
2081
- function normalizeCheck(input, index) {
2082
- if (!isRecord(input)) throw new Error(`checks[${index}] must be an object.`);
2083
- const type = stringValue(input.type);
2084
- if (!type) throw new Error(`checks[${index}].type is required.`);
2085
- if (!isSupportedCheckType(type)) {
2086
- throw new Error(`checks[${index}].type ${type} is not supported. Supported checks: ${RIDDLE_PROOF_PROFILE_CHECK_TYPES.join(", ")}`);
2087
- }
2088
- const isDialogCountCheck = isDialogCountCheckType(type);
2089
- if ((type === "selector_visible" || type === "selector_absent" || type === "selector_count_at_least" || type === "selector_count_equals" || type === "selector_count_equal" || type === "selector_count_eq" || type === "selector_text_visible" || type === "selector_text_absent" || type === "observe_within" && !stringValue(input.text) && !stringValue(input.pattern)) && !stringValue(input.selector)) {
2090
- throw new Error(`checks[${index}] ${type} requires selector.`);
2091
- }
2092
- if ((type === "frame_text_visible" || type === "frame_url_equals" || type === "frame_url_matches" || type === "frame_no_horizontal_overflow") && !stringValue(input.selector)) {
2093
- throw new Error(`checks[${index}] ${type} requires selector.`);
2094
- }
2095
- if (type === "frame_text_visible" && !stringValue(input.text) && !stringValue(input.pattern)) {
2096
- throw new Error(`checks[${index}] frame_text_visible requires text or pattern.`);
2097
- }
2098
- const expectedUrl = stringFromOwn(input, "expected_url", "expectedUrl", "url", "expected_value", "expectedValue", "value");
2099
- if (type === "frame_url_equals" && expectedUrl === void 0) {
2100
- throw new Error(`checks[${index}] frame_url_equals requires expected_url.`);
2101
- }
2102
- if (type === "frame_url_matches" && !stringValue(input.pattern)) {
2103
- throw new Error(`checks[${index}] frame_url_matches requires pattern.`);
2104
- }
2105
- if ((type === "text_visible" || type === "text_absent" || type === "selector_text_visible" || type === "selector_text_absent") && !stringValue(input.text) && !stringValue(input.pattern)) {
2106
- throw new Error(`checks[${index}] ${type} requires text or pattern.`);
2107
- }
2108
- if ((type === "url_search_param_equals" || type === "url_search_param_absent") && !stringValue(input.param) && !stringValue(input.search_param) && !stringValue(input.searchParam) && !stringValue(input.key)) {
2109
- throw new Error(`checks[${index}] ${type} requires param.`);
2110
- }
2111
- const expectedValue = stringFromOwn(input, "expected_value", "expectedValue", "value");
2112
- if (type === "url_search_param_equals" && expectedValue === void 0) {
2113
- throw new Error(`checks[${index}] url_search_param_equals requires expected_value.`);
2114
- }
2115
- const minCount = numberValue(input.min_count) ?? numberValue(input.minCount);
2116
- if (type === "selector_count_at_least" && minCount === void 0) {
2117
- throw new Error(`checks[${index}] selector_count_at_least requires min_count.`);
2118
- }
2119
- const expectedCount = numberValue(input.expected_count) ?? numberValue(input.expectedCount) ?? numberValue(input.count);
2120
- if ((type === "selector_count_equals" || type === "selector_count_equal" || type === "selector_count_eq" || isDialogCountCheck) && expectedCount === void 0) {
2121
- throw new Error(`checks[${index}] ${type} requires expected_count.`);
2122
- }
2123
- if (isDialogCountCheck && (expectedCount === void 0 || !Number.isInteger(expectedCount) || expectedCount < 0)) {
2124
- throw new Error(`checks[${index}] ${type} expected_count must be a non-negative integer.`);
2125
- }
2126
- const expectedTexts = normalizeExpectedTexts(input.expected_texts ?? input.expectedTexts, index);
2127
- if (type === "selector_text_order") {
2128
- if (!stringValue(input.selector)) throw new Error(`checks[${index}] selector_text_order requires selector.`);
2129
- if (!expectedTexts?.length) throw new Error(`checks[${index}] selector_text_order requires expected_texts.`);
2130
- }
2131
- const setupActionLabel = stringFromOwn(input, "setup_action_label", "setupActionLabel", "source_action_label", "sourceActionLabel");
2132
- const tracePath = stringFromOwn(input, "trace_path", "tracePath", "path");
2133
- const orderedTraceEvents = normalizeOrderedTraceEvents(
2134
- input.events ?? input.sequence ?? input.ordered_events ?? input.orderedEvents,
2135
- `checks[${index}].events`
2136
- );
2137
- if (type === "ordered_trace") {
2138
- if (!setupActionLabel) throw new Error(`checks[${index}] ordered_trace requires setup_action_label.`);
2139
- if (!tracePath) throw new Error(`checks[${index}] ordered_trace requires trace_path.`);
2140
- if (!orderedTraceEvents?.length) throw new Error(`checks[${index}] ordered_trace requires events.`);
2141
- }
2142
- const expectedRoutes = normalizeRouteInventoryRoutes(input.expected_routes ?? input.expectedRoutes, index);
2143
- if (type === "route_inventory" && !expectedRoutes?.length) {
2144
- throw new Error(`checks[${index}] route_inventory requires expected_routes.`);
2145
- }
2146
- const isHttpStatusCheck = type === "http_status";
2147
- const isLinkStatusCheck = type === "link_status" || type === "artifact_link_status";
2148
- const isStatusCheck = isHttpStatusCheck || isLinkStatusCheck;
2149
- const requestUrl = stringFromOwn(input, "url", "endpoint_url", "endpointUrl", "endpoint", "request_url", "requestUrl", "path");
2150
- if (isHttpStatusCheck && !requestUrl) {
2151
- throw new Error(`checks[${index}] http_status requires url.`);
2152
- }
2153
- const method = stringFromOwn(input, "method", "http_method", "httpMethod")?.toUpperCase();
2154
- if (isHttpStatusCheck && method && !/^[A-Z]+$/.test(method)) {
2155
- throw new Error(`checks[${index}] http_status method must contain only letters.`);
2156
- }
2157
- const hasBodyJson = hasOwn(input, "body_json") || hasOwn(input, "bodyJson") || hasOwn(input, "json");
2158
- const expectedStatus = isStatusCheck ? normalizeHttpStatus(input.expected_status ?? input.expectedStatus ?? input.status, `checks[${index}] expected_status`) : void 0;
2159
- const allowedStatuses = isStatusCheck ? normalizeHttpStatuses(
2160
- input.allowed_statuses ?? input.allowedStatuses ?? input.expected_statuses ?? input.expectedStatuses,
2161
- `checks[${index}] allowed_statuses`
2162
- ) : void 0;
2163
- const maxLinks = isLinkStatusCheck ? normalizePositiveInteger(input.max_links ?? input.maxLinks ?? input.limit, `checks[${index}] max_links`, 500) : void 0;
2164
- const minBytes = isStatusCheck ? normalizePositiveInteger(input.min_bytes ?? input.minBytes ?? input.min_response_bytes ?? input.minResponseBytes, `checks[${index}] min_bytes`) : void 0;
2165
- const expectedContentType = isStatusCheck ? stringValue(input.expected_content_type) || stringValue(input.expectedContentType) || stringValue(input.content_type) || stringValue(input.contentType) : void 0;
2166
- const allowedContentTypes = isStatusCheck ? normalizeStringList(
2167
- input.allowed_content_types ?? input.allowedContentTypes ?? input.expected_content_types ?? input.expectedContentTypes,
2168
- `checks[${index}] allowed_content_types`
2169
- ) ?? (expectedContentType ? [expectedContentType] : void 0) : void 0;
2170
- const bodyContains = isHttpStatusCheck ? normalizeStringList(
2171
- input.body_contains ?? input.bodyContains ?? input.expected_body_contains ?? input.expectedBodyContains ?? input.response_body_contains ?? input.responseBodyContains ?? input.body_includes ?? input.bodyIncludes,
2172
- `checks[${index}] body_contains`
2173
- ) : void 0;
2174
- const bodyNotContains = isHttpStatusCheck ? normalizeStringList(
2175
- input.body_not_contains ?? input.bodyNotContains ?? input.expected_body_not_contains ?? input.expectedBodyNotContains ?? input.response_body_not_contains ?? input.responseBodyNotContains ?? input.body_absent ?? input.bodyAbsent,
2176
- `checks[${index}] body_not_contains`
2177
- ) : void 0;
2178
- const bodyNotPatterns = isHttpStatusCheck ? normalizeStringList(
2179
- input.body_not_patterns ?? input.bodyNotPatterns ?? input.expected_body_not_patterns ?? input.expectedBodyNotPatterns ?? input.response_body_not_patterns ?? input.responseBodyNotPatterns ?? input.body_forbidden_patterns ?? input.bodyForbiddenPatterns,
2180
- `checks[${index}] body_not_patterns`
2181
- ) : void 0;
2182
- if (bodyNotPatterns?.length) validateRegexPatterns(bodyNotPatterns, `checks[${index}] body_not_patterns`);
2183
- const bodyJsonAssertions = isHttpStatusCheck ? normalizeHttpStatusBodyJsonAssertions(
2184
- input.body_json_assertions ?? input.bodyJsonAssertions ?? input.json_body_assertions ?? input.jsonBodyAssertions ?? input.json_assertions ?? input.jsonAssertions ?? input.response_json_assertions ?? input.responseJsonAssertions,
2185
- `checks[${index}] body_json_assertions`
2186
- ) : void 0;
2187
- if (isLinkStatusCheck) {
2188
- if (minCount !== void 0 && (!Number.isInteger(minCount) || minCount < 0)) {
2189
- throw new Error(`checks[${index}] ${type} min_count must be a non-negative integer.`);
2190
- }
2191
- if (expectedCount !== void 0 && (!Number.isInteger(expectedCount) || expectedCount < 0)) {
2192
- throw new Error(`checks[${index}] ${type} expected_count must be a non-negative integer.`);
2193
- }
2194
- }
2195
- return {
2196
- type,
2197
- label: stringValue(input.label),
2198
- expected_path: stringValue(input.expected_path),
2199
- param: stringValue(input.param) || stringValue(input.search_param) || stringValue(input.searchParam) || stringValue(input.key),
2200
- expected_value: expectedValue,
2201
- expected_url: expectedUrl,
2202
- expected_routes: expectedRoutes,
2203
- selector: stringValue(input.selector),
2204
- url: isHttpStatusCheck ? requestUrl : void 0,
2205
- method: isHttpStatusCheck ? method || "GET" : void 0,
2206
- headers: isHttpStatusCheck ? stringRecord(input.headers) : void 0,
2207
- body: isHttpStatusCheck ? stringValue(input.body) : void 0,
2208
- body_json: isHttpStatusCheck && hasBodyJson ? toJsonValue(input.body_json ?? input.bodyJson ?? input.json) : void 0,
2209
- body_contains: bodyContains,
2210
- body_not_contains: bodyNotContains,
2211
- body_not_patterns: bodyNotPatterns,
2212
- body_json_assertions: bodyJsonAssertions,
2213
- expected_texts: expectedTexts,
2214
- setup_action_label: type === "ordered_trace" ? setupActionLabel : void 0,
2215
- trace_path: type === "ordered_trace" ? tracePath : void 0,
2216
- events: type === "ordered_trace" ? orderedTraceEvents : void 0,
2217
- link_selector: stringValue(input.link_selector) || stringValue(input.linkSelector),
2218
- source_selector: stringValue(input.source_selector) || stringValue(input.sourceSelector),
2219
- route_path_prefix: stringValue(input.route_path_prefix) || stringValue(input.routePathPrefix),
2220
- route_ready_selector: stringValue(input.route_ready_selector) || stringValue(input.routeReadySelector),
2221
- route_ready_text: stringValue(input.route_ready_text) || stringValue(input.routeReadyText),
2222
- route_ready_pattern: stringValue(input.route_ready_pattern) || stringValue(input.routeReadyPattern),
2223
- route_ready_flags: stringValue(input.route_ready_flags) || stringValue(input.routeReadyFlags),
2224
- text: stringValue(input.text),
2225
- pattern: stringValue(input.pattern),
2226
- flags: stringValue(input.flags),
2227
- viewports: normalizeStringList(input.viewports ?? input.viewport_names ?? input.viewportNames, `checks[${index}] viewports`),
2228
- allowed_console_texts: normalizeStringList(input.allowed_console_texts ?? input.allowedConsoleTexts ?? input.allow_console_texts ?? input.allowConsoleTexts, `checks[${index}] allowed_console_texts`),
2229
- allowed_console_patterns: normalizeStringList(input.allowed_console_patterns ?? input.allowedConsolePatterns ?? input.allow_console_patterns ?? input.allowConsolePatterns, `checks[${index}] allowed_console_patterns`),
2230
- allowed_page_error_texts: normalizeStringList(input.allowed_page_error_texts ?? input.allowedPageErrorTexts ?? input.allow_page_error_texts ?? input.allowPageErrorTexts, `checks[${index}] allowed_page_error_texts`),
2231
- allowed_page_error_patterns: normalizeStringList(input.allowed_page_error_patterns ?? input.allowedPageErrorPatterns ?? input.allow_page_error_patterns ?? input.allowPageErrorPatterns, `checks[${index}] allowed_page_error_patterns`),
2232
- min_count: minCount,
2233
- expected_count: expectedCount,
2234
- expected_status: expectedStatus,
2235
- allowed_statuses: allowedStatuses,
2236
- max_links: maxLinks,
2237
- same_origin_only: isLinkStatusCheck ? input.same_origin_only === true || input.sameOriginOnly === true : void 0,
2238
- dedupe: isLinkStatusCheck ? input.dedupe === false ? false : true : void 0,
2239
- require_nonzero_bytes: isStatusCheck ? input.require_nonzero_bytes === true || input.requireNonzeroBytes === true : void 0,
2240
- min_bytes: minBytes,
2241
- allowed_content_types: allowedContentTypes,
2242
- allow_get_fallback: isLinkStatusCheck ? input.allow_get_fallback === false || input.allowGetFallback === false ? false : true : void 0,
2243
- max_overflow_px: numberValue(input.max_overflow_px),
2244
- timeout_ms: numberValue(input.timeout_ms) ?? numberValue(input.timeoutMs) ?? numberValue(input.within_ms) ?? numberValue(input.withinMs),
2245
- run_direct_routes: input.run_direct_routes === false || input.runDirectRoutes === false ? false : true,
2246
- run_clickthroughs: input.run_clickthroughs === false || input.runClickthroughs === false ? false : true,
2247
- run_all_viewports: input.run_all_viewports === true || input.runAllViewports === true,
2248
- require_unique_routes: input.require_unique_routes === false || input.requireUniqueRoutes === false ? false : true,
2249
- allow_unexpected_routes: input.allow_unexpected_routes === true || input.allowUnexpectedRoutes === true,
2250
- save_route_screenshots: input.save_route_screenshots === true || input.saveRouteScreenshots === true
2251
- };
2252
- }
2253
- function normalizeFailurePolicy(input) {
2254
- const defaults = {
2255
- product_regression: "fail",
2256
- proof_insufficient: "fail",
2257
- environment_blocked: "neutral",
2258
- configuration_error: "fail",
2259
- needs_human_review: "fail"
2260
- };
2261
- if (!isRecord(input)) return defaults;
2262
- const next = { ...defaults };
2263
- for (const [key, value] of Object.entries(input)) {
2264
- if (!RIDDLE_PROOF_PROFILE_STATUSES.includes(key)) continue;
2265
- if (value === "fail" || value === "neutral" || value === "review") {
2266
- next[key] = value;
2267
- }
2268
- }
2269
- return next;
2270
- }
2271
- function normalizeRiddleProofProfile(input, options = {}) {
2272
- if (!isRecord(input)) throw new Error("profile must be a JSON object.");
2273
- const version = stringValue(input.version) || RIDDLE_PROOF_PROFILE_VERSION;
2274
- if (version !== RIDDLE_PROOF_PROFILE_VERSION) {
2275
- throw new Error(`Unsupported profile version ${version}. Expected ${RIDDLE_PROOF_PROFILE_VERSION}.`);
2276
- }
2277
- const targetInput = isRecord(input.target) ? input.target : {};
2278
- const checks = Array.isArray(input.checks) ? input.checks.map(normalizeCheck) : [];
2279
- if (!checks.length) throw new Error("profile.checks must contain at least one check.");
2280
- const targetUrl = stringValue(options.url) || stringValue(targetInput.url);
2281
- const route = stringValue(options.route) || stringValue(targetInput.route);
2282
- if (!targetUrl && !route) throw new Error("profile.target requires url or route, or pass --url.");
2283
- const setupActions = normalizeSetupActions(targetInput.setup_actions ?? targetInput.setupActions);
2284
- for (const [index, check] of checks.entries()) {
2285
- if (check.type !== "ordered_trace") continue;
2286
- const matches = (setupActions || []).filter((action) => action.label === check.setup_action_label);
2287
- if (matches.length !== 1) {
2288
- throw new Error(`checks[${index}] ordered_trace setup_action_label must match exactly one target.setup_actions label.`);
2289
- }
2290
- if (!["window_eval", "window_call", "window_call_until"].includes(matches[0].type)) {
2291
- throw new Error(`checks[${index}] ordered_trace source action must capture a window_eval, window_call, or window_call_until return.`);
2292
- }
2293
- if (matches[0].capture_return === false) {
2294
- throw new Error(`checks[${index}] ordered_trace source action must not set capture_return to false.`);
2295
- }
2296
- }
2297
- return {
2298
- version: RIDDLE_PROOF_PROFILE_VERSION,
2299
- name: normalizeName(input.name, "riddle-proof-profile"),
2300
- target: {
2301
- url: targetUrl,
2302
- route,
2303
- viewports: options.viewports?.length ? options.viewports : normalizeViewports(targetInput.viewports),
2304
- auth: stringValue(targetInput.auth) || "none",
2305
- timeout_sec: timeoutSecValue(targetInput.timeout_sec) ?? timeoutSecValue(targetInput.timeoutSec) ?? timeoutSecValue(targetInput.riddle_timeout_sec) ?? timeoutSecValue(targetInput.riddleTimeoutSec),
2306
- wait_for_selector: stringValue(targetInput.wait_for_selector) || stringValue(targetInput.waitForSelector),
2307
- wait_ms: numberValue(targetInput.wait_ms) ?? numberValue(targetInput.waitMs),
2308
- screenshot_full_page: normalizeTargetScreenshotFullPage(targetInput),
2309
- setup_actions: setupActions,
2310
- network_mocks: normalizeNetworkMocks(targetInput.network_mocks ?? targetInput.networkMocks)
2311
- },
2312
- checks,
2313
- artifacts: Array.isArray(input.artifacts) ? input.artifacts.map((item) => String(item)).filter(Boolean) : ["screenshot", "console", "dom_summary", "proof_json"],
2314
- baseline_policy: stringValue(input.baseline_policy) || stringValue(input.baselinePolicy) || "invariant_only",
2315
- failure_policy: normalizeFailurePolicy(input.failure_policy || input.failurePolicy),
2316
- metadata: jsonRecord(input.metadata)
2317
- };
2318
- }
2319
- function resolveRiddleProofProfileTargetUrl(profile) {
2320
- const route = profile.target.route || "";
2321
- const targetUrl = profile.target.url || "";
2322
- if (targetUrl && route) return resolveRiddleProofProfileRouteUrl(targetUrl, route);
2323
- if (/^https?:\/\//i.test(route)) return route;
2324
- if (targetUrl) return targetUrl;
2325
- throw new Error("profile target URL could not be resolved.");
2326
- }
2327
- function resolveRiddleProofProfileTimeoutSec(profile, requestedTimeoutSec) {
2328
- return timeoutSecValue(requestedTimeoutSec) ?? timeoutSecValue(profile.target.timeout_sec);
2329
- }
2330
- function routeForViewport(viewport, targetUrl) {
2331
- if (viewport?.route) {
2332
- return {
2333
- ...viewport.route,
2334
- matched: viewport.route.matched || routePathMatches(viewport.route.observed, viewport.route.expected_path, targetUrl)
2335
- };
2336
- }
2337
- return {
2338
- requested: "",
2339
- observed: "",
2340
- matched: false,
2341
- error: "missing viewport evidence"
2342
- };
2343
- }
2344
- function checkLabel(check) {
2345
- return check.label || check.type;
2346
- }
2347
- function selectorKey(check) {
2348
- return check.selector || "";
2349
- }
2350
- function linkStatusSelector(check) {
2351
- return check.selector || check.link_selector || "a[href]";
2352
- }
2353
- function httpStatusRequestUrl(check, baseUrl) {
2354
- const rawUrl = check.url || "";
2355
- if (!rawUrl) return "";
2356
- try {
2357
- if (baseUrl && rawUrl.startsWith("/") && !rawUrl.startsWith("//")) {
2358
- const base = new URL(baseUrl);
2359
- const mountPrefix = previewMountPrefix(base.pathname);
2360
- if (mountPrefix) {
2361
- const requested = new URL(rawUrl, base.origin);
2362
- base.pathname = joinMountedRoutePath(mountPrefix, requested.pathname);
2363
- base.search = requested.search;
2364
- base.hash = requested.hash;
2365
- return base.href;
2366
- }
2367
- }
2368
- return baseUrl ? new URL(rawUrl, baseUrl).href : new URL(rawUrl).href;
2369
- } catch {
2370
- return rawUrl;
2371
- }
2372
- }
2373
- function httpStatusMethod(check) {
2374
- return (check.method || "GET").toUpperCase();
2375
- }
2376
- function httpStatusKey(check, baseUrl) {
2377
- return `${httpStatusMethod(check)} ${httpStatusRequestUrl(check, baseUrl)}`;
2378
- }
2379
- function httpStatusAllowedStatuses(check) {
2380
- if (check.allowed_statuses?.length) return check.allowed_statuses;
2381
- if (check.expected_status !== void 0) return [check.expected_status];
2382
- return void 0;
2383
- }
2384
- function linkStatusAllowedStatuses(check) {
2385
- return httpStatusAllowedStatuses(check);
2386
- }
2387
- function httpStatusIsAllowed(status, check) {
2388
- if (status === void 0) return false;
2389
- const allowed = httpStatusAllowedStatuses(check);
2390
- return allowed?.length ? allowed.includes(status) : status >= 200 && status < 400;
2391
- }
2392
- function linkStatusObservedBytes(result) {
2393
- const bytes = numberValue(result.bytes);
2394
- const contentLength = numberValue(result.content_length);
2395
- return Math.max(bytes ?? 0, contentLength ?? 0) || void 0;
2396
- }
2397
- function normalizeLinkStatusContentType(value) {
2398
- const normalized = value?.split(";")[0]?.trim().toLowerCase();
2399
- return normalized || void 0;
2400
- }
2401
- function linkStatusContentTypesMatch(actual, expected) {
2402
- if (!actual || !expected) return false;
2403
- if (expected.endsWith("/*")) return actual.startsWith(expected.slice(0, -1));
2404
- if (actual === expected) return true;
2405
- const yamlTypes = /* @__PURE__ */ new Set(["application/yaml", "application/x-yaml", "text/yaml", "text/x-yaml"]);
2406
- return yamlTypes.has(actual) && yamlTypes.has(expected);
2407
- }
2408
- function linkStatusContentTypeOk(result, check) {
2409
- const expected = check.allowed_content_types;
2410
- if (!expected?.length) return true;
2411
- const actual = normalizeLinkStatusContentType(stringValue(result.content_type));
2412
- if (!actual) return false;
2413
- return expected.some((contentType) => {
2414
- const normalized = normalizeLinkStatusContentType(contentType);
2415
- if (!normalized) return false;
2416
- return linkStatusContentTypesMatch(actual, normalized);
2417
- });
2418
- }
2419
- function httpStatusBodyContainsFailures(result, check) {
2420
- const expected = check.body_contains?.filter(Boolean) ?? [];
2421
- if (!expected.length) return [];
2422
- const observed = isRecord(result.body_contains) ? result.body_contains : {};
2423
- return expected.filter((text) => observed[text] !== true);
2424
- }
2425
- function httpStatusBodyNotContainsFailures(result, check) {
2426
- const forbidden = check.body_not_contains?.filter(Boolean) ?? [];
2427
- if (!forbidden.length) return [];
2428
- const observed = isRecord(result.body_not_contains) ? result.body_not_contains : {};
2429
- return forbidden.filter((text) => observed[text] !== false);
2430
- }
2431
- function httpStatusBodyNotPatternFailures(result, check) {
2432
- const forbidden = check.body_not_patterns?.filter(Boolean) ?? [];
2433
- if (!forbidden.length) return [];
2434
- const observed = isRecord(result.body_not_patterns) ? result.body_not_patterns : {};
2435
- return forbidden.filter((pattern) => observed[pattern] !== false);
2436
- }
2437
- function httpStatusBodyJsonAssertionFailures(result, check) {
2438
- const expected = check.body_json_assertions?.filter((assertion) => assertion.path) ?? [];
2439
- if (!expected.length) return [];
2440
- if (!Array.isArray(result.body_json_assertions)) {
2441
- return expected.map((assertion) => ({
2442
- label: assertion.label || assertion.path,
2443
- path: assertion.path,
2444
- ok: false,
2445
- exists: false,
2446
- observed_type: "missing",
2447
- errors: ["body_json_assertions evidence missing"]
2448
- }));
2449
- }
2450
- return result.body_json_assertions.filter((assertion) => isRecord(assertion) && assertion.ok !== true).map((assertion) => ({
2451
- label: stringValue(assertion.label) || stringValue(assertion.path) || "json assertion",
2452
- path: stringValue(assertion.path) || "",
2453
- ok: false,
2454
- exists: assertion.exists === true,
2455
- observed: hasOwn(assertion, "observed") ? toJsonValue(assertion.observed) : void 0,
2456
- observed_sample: hasOwn(assertion, "observed_sample") ? toJsonValue(assertion.observed_sample) : void 0,
2457
- observed_length: numberValue(assertion.observed_length),
2458
- observed_key_count: numberValue(assertion.observed_key_count),
2459
- observed_omitted_count: numberValue(assertion.observed_omitted_count),
2460
- observed_type: stringValue(assertion.observed_type) || "missing",
2461
- expected_exists: booleanValue(assertion.expected_exists),
2462
- equals: hasOwn(assertion, "equals") ? toJsonValue(assertion.equals) : void 0,
2463
- not_equals: hasOwn(assertion, "not_equals") ? toJsonValue(assertion.not_equals) : void 0,
2464
- contains: hasOwn(assertion, "contains") ? toJsonValue(assertion.contains) : void 0,
2465
- type: stringValue(assertion.type),
2466
- errors: Array.isArray(assertion.errors) ? assertion.errors.map(String) : void 0
2467
- }));
2468
- }
2469
- function linkStatusResultOk(result, check) {
2470
- const status = numberValue(result.status);
2471
- if (!httpStatusIsAllowed(status, check)) return false;
2472
- if (stringValue(result.error)) return false;
2473
- if (result.ok === false) return false;
2474
- if (!linkStatusContentTypeOk(result, check)) return false;
2475
- if (check.require_nonzero_bytes) {
2476
- const observedBytes = linkStatusObservedBytes(result);
2477
- if (observedBytes === void 0 || observedBytes <= 0) return false;
2478
- }
2479
- if (check.min_bytes !== void 0) {
2480
- const observedBytes = linkStatusObservedBytes(result);
2481
- if (observedBytes === void 0 || observedBytes < check.min_bytes) return false;
2482
- }
2483
- if (httpStatusBodyContainsFailures(result, check).length) return false;
2484
- if (httpStatusBodyNotContainsFailures(result, check).length) return false;
2485
- if (httpStatusBodyNotPatternFailures(result, check).length) return false;
2486
- if (httpStatusBodyJsonAssertionFailures(result, check).length) return false;
2487
- return true;
2488
- }
2489
- function responseHeader(response, name) {
2490
- const getter = response.headers?.get;
2491
- if (typeof getter !== "function") return null;
2492
- return getter.call(response.headers, name);
2493
- }
2494
- function responseContentLength(response) {
2495
- const value = responseHeader(response, "content-length");
2496
- return value && /^\d+$/.test(value) ? Number(value) : null;
2497
- }
2498
- async function responseBodyText(response) {
2499
- if (typeof response.arrayBuffer === "function") {
2500
- const buffer = await response.arrayBuffer();
2501
- return {
2502
- text: new TextDecoder().decode(buffer),
2503
- bytes: buffer.byteLength
2504
- };
2505
- }
2506
- if (typeof response.text === "function") {
2507
- const text = await response.text();
2508
- return {
2509
- text,
2510
- bytes: new TextEncoder().encode(text).byteLength
2511
- };
2512
- }
2513
- return { text: "", bytes: null };
2514
- }
2515
- function httpStatusRequestBody(check) {
2516
- const headers = isRecord(check.headers) ? Object.fromEntries(Object.entries(check.headers).map(([key, value]) => [key, String(value)]).filter(([key]) => key.trim())) : {};
2517
- if (check.body_json !== void 0) {
2518
- if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
2519
- headers["content-type"] = "application/json";
2520
- }
2521
- return { headers, body: JSON.stringify(check.body_json) };
2522
- }
2523
- if (typeof check.body === "string") {
2524
- return { headers, body: check.body };
2525
- }
2526
- return { headers };
2527
- }
2528
- async function preflightHttpStatusCheck(check, index, targetUrl, fetchImpl) {
2529
- const url = httpStatusRequestUrl(check, targetUrl);
2530
- const method = httpStatusMethod(check);
2531
- const request = httpStatusRequestBody(check);
2532
- const init = {
2533
- method,
2534
- redirect: "follow",
2535
- cache: "no-store",
2536
- headers: request.headers
2537
- };
2538
- if (request.body !== void 0 && method !== "GET" && method !== "HEAD") {
2539
- init.body = request.body;
2540
- }
2541
- const result = {
2542
- status: null,
2543
- content_type: null,
2544
- content_length: null,
2545
- bytes: null
2546
- };
2547
- let error = null;
2548
- let statusText = "";
2549
- try {
2550
- const response = await fetchImpl(url, init);
2551
- result.status = typeof response.status === "number" && Number.isFinite(response.status) ? response.status : null;
2552
- statusText = typeof response.statusText === "string" ? response.statusText : "";
2553
- result.content_type = responseHeader(response, "content-type");
2554
- result.content_length = responseContentLength(response);
2555
- const shouldReadBody = check.require_nonzero_bytes === true || typeof check.min_bytes === "number" || Boolean(check.body_contains?.length) || Boolean(check.body_not_contains?.length) || Boolean(check.body_not_patterns?.length) || Boolean(check.body_json_assertions?.length);
2556
- if (shouldReadBody && method !== "HEAD") {
2557
- const body = await responseBodyText(response);
2558
- result.bytes = body.bytes;
2559
- if (check.body_contains?.length) {
2560
- result.body_contains = Object.fromEntries(check.body_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
2561
- }
2562
- if (check.body_not_contains?.length) {
2563
- result.body_not_contains = Object.fromEntries(check.body_not_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
2564
- }
2565
- if (check.body_not_patterns?.length) {
2566
- result.body_not_patterns = Object.fromEntries(check.body_not_patterns.filter(Boolean).map((pattern) => [pattern, new RegExp(pattern).test(body.text)]));
2567
- }
2568
- if (check.body_json_assertions?.length) {
2569
- result.body_json_assertions = evaluateHttpStatusBodyJsonAssertions(body.text, check.body_json_assertions);
2570
- }
2571
- }
2572
- } catch (caught) {
2573
- error = String(caught instanceof Error ? caught.message : caught).slice(0, 500);
2574
- result.error = error;
2575
- }
2576
- const bodyContainsMissing = httpStatusBodyContainsFailures(result, check);
2577
- const bodyNotContainsFound = httpStatusBodyNotContainsFailures(result, check);
2578
- const bodyNotPatternsFound = httpStatusBodyNotPatternFailures(result, check);
2579
- const bodyJsonAssertionsFailed = httpStatusBodyJsonAssertionFailures(result, check);
2580
- const ok = !error && linkStatusResultOk(result, check);
2581
- return {
2582
- index,
2583
- label: checkLabel(check) || `checks[${index}]`,
2584
- url,
2585
- method,
2586
- ok,
2587
- status: numberValue(result.status) ?? null,
2588
- status_text: statusText,
2589
- error,
2590
- content_type: stringValue(result.content_type) ?? null,
2591
- content_length: numberValue(result.content_length) ?? null,
2592
- bytes: numberValue(result.bytes) ?? null,
2593
- body_contains: isRecord(result.body_contains) ? Object.fromEntries(Object.entries(result.body_contains).map(([key, value]) => [key, value === true])) : null,
2594
- body_contains_missing: bodyContainsMissing,
2595
- body_not_contains: isRecord(result.body_not_contains) ? Object.fromEntries(Object.entries(result.body_not_contains).map(([key, value]) => [key, value === true])) : null,
2596
- body_not_contains_found: bodyNotContainsFound,
2597
- body_not_patterns: isRecord(result.body_not_patterns) ? Object.fromEntries(Object.entries(result.body_not_patterns).map(([key, value]) => [key, value === true])) : null,
2598
- body_not_patterns_found: bodyNotPatternsFound,
2599
- body_json_assertions: Array.isArray(result.body_json_assertions) ? result.body_json_assertions : null,
2600
- body_json_assertions_failed: bodyJsonAssertionsFailed
2601
- };
2602
- }
2603
- async function preflightRiddleProofProfileHttpStatusChecks(profile, options = {}) {
2604
- const targetUrl = options.target_url || resolveRiddleProofProfileTargetUrl(profile);
2605
- const fetchImpl = options.fetchImpl ?? globalThis.fetch;
2606
- if (typeof fetchImpl !== "function") {
2607
- throw new Error("profile http_status preflight requires fetch support or options.fetchImpl.");
2608
- }
2609
- const httpStatusChecks = profile.checks.map((check, index) => ({ check, index })).filter((item) => item.check.type === "http_status");
2610
- const checks = await Promise.all(httpStatusChecks.map((item) => preflightHttpStatusCheck(item.check, item.index, targetUrl, fetchImpl)));
2611
- const failed = checks.filter((check) => !check.ok).length;
2612
- return {
2613
- version: "riddle-proof.profile-http-status-preflight.v1",
2614
- ok: failed === 0,
2615
- profile_name: profile.name,
2616
- target_url: targetUrl,
2617
- checked: checks.length,
2618
- failed,
2619
- checks,
2620
- summary: failed === 0 ? `${profile.name} http_status preflight passed ${checks.length} check(s).` : `${profile.name} http_status preflight failed ${failed} of ${checks.length} check(s).`
2621
- };
2622
- }
2623
- function httpStatusEvidenceForCheck(viewport, check) {
2624
- const evidence = viewport.http_statuses?.[httpStatusKey(check, viewport.url)];
2625
- return isRecord(evidence) ? evidence : void 0;
2626
- }
2627
- function summarizeHttpStatusEvidence(viewport, check) {
2628
- const key = httpStatusKey(check, viewport.url);
2629
- const statusEvidence = httpStatusEvidenceForCheck(viewport, check);
2630
- if (!statusEvidence) {
2631
- return {
2632
- viewport: viewport.name,
2633
- key,
2634
- url: httpStatusRequestUrl(check, viewport.url),
2635
- method: httpStatusMethod(check),
2636
- ok: false,
2637
- status: null,
2638
- failures: [{ code: "http_status_evidence_missing" }]
2639
- };
2640
- }
2641
- const failures = [];
2642
- const bodyContainsMissing = httpStatusBodyContainsFailures(statusEvidence, check);
2643
- const bodyNotContainsFound = httpStatusBodyNotContainsFailures(statusEvidence, check);
2644
- const bodyNotPatternsFound = httpStatusBodyNotPatternFailures(statusEvidence, check);
2645
- const bodyJsonAssertionsFailed = httpStatusBodyJsonAssertionFailures(statusEvidence, check);
2646
- if (!linkStatusResultOk(statusEvidence, check)) {
2647
- failures.push({
2648
- code: "http_status_failed",
2649
- url: stringValue(statusEvidence.url) ?? httpStatusRequestUrl(check, viewport.url),
2650
- status: numberValue(statusEvidence.status) ?? null,
2651
- method: stringValue(statusEvidence.method) ?? httpStatusMethod(check),
2652
- error: stringValue(statusEvidence.error) ?? null,
2653
- content_type: stringValue(statusEvidence.content_type) ?? null,
2654
- bytes: linkStatusObservedBytes(statusEvidence) ?? null,
2655
- allowed_statuses: httpStatusAllowedStatuses(check) ?? ["2xx", "3xx"],
2656
- min_bytes: check.min_bytes ?? null,
2657
- allowed_content_types: check.allowed_content_types ?? null,
2658
- body_contains: check.body_contains ?? null,
2659
- body_contains_missing: bodyContainsMissing,
2660
- body_not_contains: check.body_not_contains ?? null,
2661
- body_not_contains_found: bodyNotContainsFound,
2662
- body_not_patterns: check.body_not_patterns ?? null,
2663
- body_not_patterns_found: bodyNotPatternsFound,
2664
- body_json_assertions: check.body_json_assertions ?? null,
2665
- body_json_assertions_failed: bodyJsonAssertionsFailed.map((assertion) => toJsonValue(assertion)),
2666
- body_sample: stringValue(statusEvidence.body_sample) ?? null
2667
- });
2668
- }
2669
- return {
2670
- viewport: viewport.name,
2671
- key,
2672
- url: stringValue(statusEvidence.url) ?? httpStatusRequestUrl(check, viewport.url),
2673
- method: stringValue(statusEvidence.method) ?? httpStatusMethod(check),
2674
- status: numberValue(statusEvidence.status) ?? null,
2675
- status_text: stringValue(statusEvidence.status_text) ?? null,
2676
- ok: failures.length === 0,
2677
- error: stringValue(statusEvidence.error) ?? null,
2678
- content_type: stringValue(statusEvidence.content_type) ?? null,
2679
- content_length: numberValue(statusEvidence.content_length) ?? null,
2680
- bytes: linkStatusObservedBytes(statusEvidence) ?? null,
2681
- body_contains: isRecord(statusEvidence.body_contains) ? toJsonValue(statusEvidence.body_contains) : null,
2682
- body_contains_missing: bodyContainsMissing,
2683
- body_not_contains: isRecord(statusEvidence.body_not_contains) ? toJsonValue(statusEvidence.body_not_contains) : null,
2684
- body_not_contains_found: bodyNotContainsFound,
2685
- body_not_patterns: isRecord(statusEvidence.body_not_patterns) ? toJsonValue(statusEvidence.body_not_patterns) : null,
2686
- body_not_patterns_found: bodyNotPatternsFound,
2687
- body_json_assertions: Array.isArray(statusEvidence.body_json_assertions) ? toJsonValue(statusEvidence.body_json_assertions) : null,
2688
- body_json_assertions_failed: bodyJsonAssertionsFailed.map((assertion) => toJsonValue(assertion)),
2689
- body_sample: stringValue(statusEvidence.body_sample) ?? null,
2690
- failures
2691
- };
2692
- }
2693
- function linkStatusEvidenceForCheck(viewport, check) {
2694
- const evidence = viewport.link_statuses?.[linkStatusSelector(check)];
2695
- return isRecord(evidence) ? evidence : void 0;
2696
- }
2697
- function summarizeLinkStatusEvidence(viewport, check) {
2698
- const linkEvidence = linkStatusEvidenceForCheck(viewport, check);
2699
- if (!linkEvidence) {
2700
- return {
2701
- viewport: viewport.name,
2702
- selector: linkStatusSelector(check),
2703
- total_count: 0,
2704
- ok_count: 0,
2705
- failed_count: 1,
2706
- failures: [{ code: "link_status_evidence_missing" }]
2707
- };
2708
- }
2709
- const results = Array.isArray(linkEvidence.results) ? linkEvidence.results.filter(isRecord) : [];
2710
- const totalCount = numberValue(linkEvidence.total_count) ?? results.length;
2711
- const resultCount = numberValue(linkEvidence.result_count) ?? totalCount;
2712
- const storedResultCount = numberValue(linkEvidence.stored_result_count) ?? results.length;
2713
- const omittedResultCount = numberValue(linkEvidence.omitted_result_count) ?? Math.max(0, resultCount - storedResultCount);
2714
- const omittedSuccessCount = numberValue(linkEvidence.omitted_success_count) ?? 0;
2715
- const okCount = results.filter((result) => linkStatusResultOk(result, check)).length;
2716
- const failures = results.filter((result) => !linkStatusResultOk(result, check)).map((result) => ({
2717
- code: "link_status_failed",
2718
- url: stringValue(result.url) ?? null,
2719
- status: numberValue(result.status) ?? null,
2720
- method: stringValue(result.method) ?? null,
2721
- error: stringValue(result.error) ?? null,
2722
- content_type: stringValue(result.content_type) ?? null,
2723
- bytes: linkStatusObservedBytes(result) ?? null,
2724
- min_bytes: check.min_bytes ?? null,
2725
- allowed_content_types: check.allowed_content_types ?? null
2726
- }));
2727
- if (stringValue(linkEvidence.error)) {
2728
- failures.push({ code: "link_status_capture_failed", error: stringValue(linkEvidence.error) ?? "" });
2729
- }
2730
- const recordedFailedCount = numberValue(linkEvidence.failed_count) ?? 0;
2731
- if (!failures.length && recordedFailedCount > 0) {
2732
- const recordedFailures = Array.isArray(linkEvidence.failures) ? linkEvidence.failures.slice(0, 20) : [];
2733
- failures.push({
2734
- code: "link_status_recorded_failures",
2735
- failed_count: recordedFailedCount,
2736
- failures: toJsonValue(recordedFailures)
2737
- });
2738
- }
2739
- if (linkEvidence.truncated === true) {
2740
- failures.push({
2741
- code: "link_status_probe_truncated",
2742
- discovered_count: numberValue(linkEvidence.discovered_count) ?? totalCount,
2743
- max_links: numberValue(linkEvidence.max_links) ?? check.max_links ?? 100
2744
- });
2745
- }
2746
- if (check.expected_count !== void 0 && totalCount !== check.expected_count) {
2747
- failures.push({ code: "link_status_count_mismatch", expected: check.expected_count, actual: totalCount });
2748
- }
2749
- if (check.min_count !== void 0 && totalCount < check.min_count) {
2750
- failures.push({ code: "link_status_count_below_minimum", min_count: check.min_count, actual: totalCount });
2751
- }
2752
- const statusCounts = isRecord(linkEvidence.status_counts) ? linkEvidence.status_counts : {};
2753
- return {
2754
- viewport: viewport.name,
2755
- selector: linkStatusSelector(check),
2756
- total_count: totalCount,
2757
- discovered_count: numberValue(linkEvidence.discovered_count) ?? totalCount,
2758
- ok_count: numberValue(linkEvidence.ok_count) ?? okCount,
2759
- failed_count: failures.length,
2760
- truncated: linkEvidence.truncated === true,
2761
- max_links: numberValue(linkEvidence.max_links) ?? check.max_links ?? 100,
2762
- result_count: resultCount,
2763
- stored_result_count: storedResultCount,
2764
- omitted_result_count: omittedResultCount,
2765
- omitted_success_count: omittedSuccessCount,
2766
- results_compacted: linkEvidence.results_compacted === true || omittedResultCount > 0,
2767
- min_bytes: check.min_bytes ?? null,
2768
- allowed_content_types: check.allowed_content_types ?? null,
2769
- status_counts: statusCounts,
2770
- failures: failures.slice(0, 20)
2771
- };
2772
- }
2773
- function textKey(check) {
2774
- return check.pattern ? `pattern:${check.pattern}/${check.flags || ""}` : `text:${check.text || ""}`;
2775
- }
2776
- function observeWithinTimeoutMs(check) {
2777
- const raw = check.timeout_ms;
2778
- if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) return Math.min(Math.round(raw), 6e4);
2779
- return 2e3;
2780
- }
2781
- function observeWithinKey(check) {
2782
- const target = check.selector ? `selector:${check.selector}` : "page";
2783
- const expectation = check.pattern ? `pattern:${check.pattern}/${check.flags || ""}` : check.text ? `text:${check.text}` : "visible";
2784
- return `${target}|${expectation}|within:${observeWithinTimeoutMs(check)}`;
2785
- }
2786
- function textSequenceForCheck(viewport, check) {
2787
- const key = selectorKey(check);
2788
- const sequence = viewport.text_sequences?.[key];
2789
- if (isRecord(sequence)) {
2790
- const visibleMatchTexts = Array.isArray(sequence.visible_match_texts) ? sequence.visible_match_texts : [];
2791
- const matchTexts = Array.isArray(sequence.match_texts) ? sequence.match_texts : [];
2792
- const visibleTexts = Array.isArray(sequence.visible_texts) ? sequence.visible_texts : [];
2793
- const texts = Array.isArray(sequence.texts) ? sequence.texts : [];
2794
- let candidates;
2795
- if (check.type === "selector_text_visible") {
2796
- candidates = visibleMatchTexts.length ? visibleMatchTexts : visibleTexts;
2797
- } else if (check.type === "selector_text_absent") {
2798
- candidates = matchTexts.length ? matchTexts : texts;
2799
- } else {
2800
- candidates = visibleMatchTexts.length ? visibleMatchTexts : matchTexts.length ? matchTexts : visibleTexts.length ? visibleTexts : texts;
2801
- }
2802
- return candidates.map((text) => String(text).replace(/\s+/g, " ").trim()).filter(Boolean);
2803
- }
2804
- return [];
2805
- }
2806
- function textOrderMatch(texts, expectedTexts) {
2807
- const positions = [];
2808
- let startAt = 0;
2809
- for (const expected of expectedTexts) {
2810
- const index = texts.findIndex((text, offset) => offset >= startAt && text.includes(expected));
2811
- if (index < 0) return { matched: false, positions };
2812
- positions.push(index);
2813
- startAt = index + 1;
2814
- }
2815
- return { matched: true, positions };
2816
- }
2817
- function frameEvidenceForSelector(viewport, selector) {
2818
- const container = viewport.frames?.[selector];
2819
- if (!isRecord(container)) return [];
2820
- const frames = Array.isArray(container.frames) ? container.frames : [];
2821
- return frames.filter((frame) => isRecord(frame));
2822
- }
2823
- function frameTextSample(frame) {
2824
- const parts = [
2825
- frame.title,
2826
- frame.text_sample,
2827
- frame.body_text_sample,
2828
- frame.body_text,
2829
- frame.text
2830
- ];
2831
- return parts.map((part) => String(part || "")).filter(Boolean).join(" ");
2832
- }
2833
- function summarizeRouteInventory(viewport, inventory) {
2834
- const directRoutes = Array.isArray(inventory.direct_routes) ? inventory.direct_routes : [];
2835
- const clickthroughs = Array.isArray(inventory.clickthroughs) ? inventory.clickthroughs : [];
2836
- const sourceLinkCount = numberValue(inventory.source_link_count) ?? numberValue(inventory.home_game_link_count) ?? null;
2837
- const sourceUniqueLinkCount = numberValue(inventory.source_unique_link_count) ?? numberValue(inventory.home_unique_game_link_count) ?? null;
2838
- const sourceCandidateCount = numberValue(inventory.source_candidate_count);
2839
- const sourceCandidateUniqueLinkCount = numberValue(inventory.source_candidate_unique_link_count);
2840
- const sourceLinkScope = stringValue(inventory.source_link_scope);
2841
- const duplicateSourceLinks = Array.isArray(inventory.duplicate_source_link_paths) ? inventory.duplicate_source_link_paths.map((path) => String(path)) : [];
2842
- const duplicateSourceLinkCount = numberValue(inventory.duplicate_source_link_count) ?? (sourceLinkCount !== null && sourceUniqueLinkCount !== null ? Math.max(0, sourceLinkCount - sourceUniqueLinkCount) : null);
2843
- const failures = Array.isArray(inventory.failures) ? inventory.failures : [];
2844
- return {
2845
- viewport,
2846
- source_link_scope: sourceLinkScope ?? null,
2847
- source_candidate_count: sourceCandidateCount ?? sourceLinkCount,
2848
- source_candidate_unique_link_count: sourceCandidateUniqueLinkCount ?? sourceUniqueLinkCount,
2849
- source_link_count: sourceLinkCount,
2850
- source_unique_link_count: sourceUniqueLinkCount,
2851
- duplicate_source_link_count: duplicateSourceLinkCount,
2852
- duplicate_source_links: duplicateSourceLinks,
2853
- direct_route_count: directRoutes.length,
2854
- clickthrough_count: clickthroughs.length,
2855
- failure_count: failures.length
2856
- };
2857
- }
2858
- function routeInventoryExpectedRouteSummaries(value, fallback) {
2859
- const rawRoutes = Array.isArray(value) ? value : Array.isArray(fallback) ? fallback : [];
2860
- return rawRoutes.map((route) => {
2861
- if (typeof route === "string") {
2862
- const path2 = route.trim();
2863
- return path2 ? { path: path2 } : void 0;
2864
- }
2865
- if (!isRecord(route)) return void 0;
2866
- const path = stringValue(route.path);
2867
- if (!path) return void 0;
2868
- const name = stringValue(route.name);
2869
- return name ? { name, path } : { path };
2870
- }).filter((route) => Boolean(route));
2871
- }
2872
- function matchText(sample, check) {
2873
- if (check.pattern) {
2874
- try {
2875
- return new RegExp(check.pattern, check.flags || "").test(sample);
2876
- } catch {
2877
- return false;
2878
- }
2879
- }
2880
- return sample.includes(check.text || "");
2881
- }
2882
- function compactTextEvidenceSample(value) {
2883
- return String(value || "").replace(/\s+/g, " ").trim();
2884
- }
2885
- function textSampleAroundMatch(sample, index, length) {
2886
- if (index < 0) return void 0;
2887
- const source = String(sample || "");
2888
- const context = 120;
2889
- const start = Math.max(0, index - context);
2890
- const end = Math.min(source.length, index + Math.max(length, 1) + context);
2891
- const prefix = start > 0 ? "..." : "";
2892
- const suffix = end < source.length ? "..." : "";
2893
- const compacted = compactTextEvidenceSample(`${prefix}${source.slice(start, end)}${suffix}`);
2894
- return compacted ? compacted.slice(0, 240) : void 0;
2895
- }
2896
- function textMatchSamples(sample, check) {
2897
- const source = String(sample || "");
2898
- if (!source) return [];
2899
- if (check.pattern) {
2900
- try {
2901
- const flags = Array.from(new Set(String(check.flags || "").replace(/[gy]/g, "").split(""))).join("");
2902
- const match = new RegExp(check.pattern, flags).exec(source);
2903
- const sampleText2 = match ? textSampleAroundMatch(source, match.index, match[0]?.length || 1) : void 0;
2904
- return sampleText2 ? [sampleText2] : [];
2905
- } catch {
2906
- return [];
2907
- }
2908
- }
2909
- const text = check.text || "";
2910
- if (!text) return [];
2911
- const index = source.indexOf(text);
2912
- const sampleText = textSampleAroundMatch(source, index, text.length);
2913
- return sampleText ? [sampleText] : [];
2914
- }
2915
- function textCaseInsensitiveSamples(sample, check) {
2916
- const source = String(sample || "");
2917
- const text = check.pattern ? "" : check.text || "";
2918
- if (!source || !text) return [];
2919
- const index = source.toLowerCase().indexOf(text.toLowerCase());
2920
- const sampleText = textSampleAroundMatch(source, index, text.length);
2921
- return sampleText ? [sampleText] : [];
2922
- }
2923
- function textCaseInsensitiveSequenceSamples(texts, check) {
2924
- const text = check.pattern ? "" : compactTextEvidenceSample(check.text || "");
2925
- if (!text) return [];
2926
- const expected = text.toLowerCase();
2927
- return texts.map((candidate) => compactTextEvidenceSample(candidate)).filter((candidate) => candidate && candidate.toLowerCase().includes(expected)).slice(0, 3).map((candidate) => candidate.slice(0, 240));
2928
- }
2929
- function textCaseInsensitiveFailureSamples(viewport, check) {
2930
- const key = textKey(check);
2931
- const captured = viewport.text_case_insensitive_samples?.[key] || [];
2932
- const capturedSamples = captured.map((sample) => compactTextEvidenceSample(sample).slice(0, 240)).filter(Boolean);
2933
- if (capturedSamples.length) return capturedSamples.slice(0, 3);
2934
- return textCaseInsensitiveSamples(viewport.body_text_sample || "", check).slice(0, 3);
2935
- }
2936
- function textCheckFailureSamples(viewport, check) {
2937
- const key = textKey(check);
2938
- const captured = viewport.text_match_samples?.[key] || [];
2939
- const capturedSamples = captured.map((sample) => compactTextEvidenceSample(sample).slice(0, 240)).filter(Boolean);
2940
- if (capturedSamples.length) return capturedSamples.slice(0, 3);
2941
- const matchedSamples = textMatchSamples(viewport.body_text_sample || "", check);
2942
- if (matchedSamples.length) return matchedSamples.slice(0, 3);
2943
- const fallback = compactTextEvidenceSample(viewport.body_text_sample || "").slice(0, 240);
2944
- return fallback ? [fallback] : [];
2945
- }
2946
- function allowedMessageSample(input) {
2947
- if (!isRecord(input)) return String(input || "");
2948
- const parts = [
2949
- input.text,
2950
- input.message,
2951
- isRecord(input.location) ? input.location.url : void 0
2952
- ];
2953
- return parts.map((part) => String(part || "")).filter(Boolean).join(" ");
2954
- }
2955
- function matchesAllowedMessage(input, texts, patterns) {
2956
- const sample = allowedMessageSample(input);
2957
- if (texts?.some((text) => sample.includes(text))) return true;
2958
- for (const pattern of patterns || []) {
2959
- try {
2960
- if (new RegExp(pattern).test(sample)) return true;
2961
- } catch {
2962
- continue;
2963
- }
2964
- }
2965
- return false;
2966
- }
2967
- function consoleEventLocationUrl(input) {
2968
- if (!isRecord(input) || !isRecord(input.location)) return void 0;
2969
- return stringValue(input.location.url);
2970
- }
2971
- function expectedFailedNetworkMockEvents(evidence) {
2972
- return (evidence.network_mocks || []).filter((event) => {
2973
- if (!isRecord(event) || event.ok === false) return false;
2974
- const status = numberValue(event.status);
2975
- const isHttpFailure = status !== void 0 && status >= 400;
2976
- const isAbortedMock = event.abort === true && Boolean(stringValue(event.abort_error_code));
2977
- return (isHttpFailure || isAbortedMock) && Boolean(stringValue(event.url));
2978
- });
2979
- }
2980
- function matchingExpectedFailedNetworkMockConsoleEvent(event, evidence) {
2981
- const sample = allowedMessageSample(event);
2982
- if (!/Failed to load resource/i.test(sample)) return void 0;
2983
- const eventUrl = consoleEventLocationUrl(event);
2984
- if (!eventUrl) return void 0;
2985
- return expectedFailedNetworkMockEvents(evidence).find((mockEvent) => {
2986
- const status = numberValue(mockEvent.status);
2987
- const abortErrorCode = stringValue(mockEvent.abort_error_code);
2988
- return stringValue(mockEvent.url) === eventUrl && (status !== void 0 && sample.includes(String(status)) || Boolean(abortErrorCode) && /Failed to load resource/i.test(sample));
2989
- });
2990
- }
2991
- function isExpectedFailedNetworkMockConsoleEvent(event, evidence) {
2992
- return Boolean(matchingExpectedFailedNetworkMockConsoleEvent(event, evidence));
2993
- }
2994
- function expectedFailedNetworkMockConsoleEventSummary(event, evidence) {
2995
- const match = matchingExpectedFailedNetworkMockConsoleEvent(event, evidence);
2996
- const sample = allowedMessageSample(event);
2997
- return {
2998
- url: consoleEventLocationUrl(event) ?? null,
2999
- status: match ? numberValue(match.status) ?? null : null,
3000
- abort_error_code: match ? stringValue(match.abort_error_code) ?? null : null,
3001
- label: match ? stringValue(match.label) ?? null : null,
3002
- response_label: match ? stringValue(match.response_label) ?? null : null,
3003
- text: isRecord(event) && typeof event.text === "string" ? event.text.slice(0, 300) : sample.slice(0, 300)
3004
- };
3005
- }
3006
- function normalizeRoutePath(path) {
3007
- const value = path || "/";
3008
- if (value === "/") return "/";
3009
- return value.replace(/\/+$/, "") || "/";
3010
- }
3011
- function previewMountPrefix(pathname) {
3012
- const value = pathname || "/";
3013
- const apiPreview = value.match(/^(\/s\/[^/]+)(?:\/|$)/);
3014
- if (apiPreview) return apiPreview[1];
3015
- const internalPreview = value.match(/^(\/preview\/[^/]+\/[^/]+)(?:\/|$)/);
3016
- return internalPreview ? internalPreview[1] : "";
3017
- }
3018
- function joinMountedRoutePath(mountPrefix, routePath) {
3019
- const route = routePath.startsWith("/") ? routePath : `/${routePath}`;
3020
- if (!mountPrefix) return route;
3021
- if (route === mountPrefix || route.startsWith(`${mountPrefix}/`)) return route;
3022
- return `${mountPrefix}${route}`;
3023
- }
3024
- function resolveRiddleProofProfileRouteUrl(targetUrl, route) {
3025
- if (/^https?:\/\//i.test(route)) return route;
3026
- if (!targetUrl) return route;
3027
- if (route.startsWith("/")) {
3028
- const base = new URL(targetUrl);
3029
- const mountPrefix = previewMountPrefix(base.pathname);
3030
- if (mountPrefix) {
3031
- const routeParts = new URL(route, base.origin);
3032
- base.pathname = joinMountedRoutePath(mountPrefix, routeParts.pathname);
3033
- base.search = routeParts.search;
3034
- base.hash = routeParts.hash;
3035
- return base.href;
3036
- }
3037
- }
3038
- return new URL(route, targetUrl).href;
3039
- }
3040
- function mountedExpectedRoutePath(targetUrl, expected) {
3041
- if (!targetUrl || !expected || !expected.startsWith("/")) return expected;
3042
- const mountPrefix = previewMountPrefix(new URL(targetUrl).pathname);
3043
- return mountPrefix ? joinMountedRoutePath(mountPrefix, expected) : expected;
3044
- }
3045
- function routePathMatches(observed, expected, targetUrl) {
3046
- const normalizedObserved = normalizeRoutePath(observed);
3047
- const normalizedExpected = normalizeRoutePath(expected);
3048
- if (normalizedObserved === normalizedExpected) return true;
3049
- return normalizedObserved === normalizeRoutePath(mountedExpectedRoutePath(targetUrl, expected));
3050
- }
3051
- function successfulRoute(route, targetUrl) {
3052
- const matched = route.matched || routePathMatches(route.observed, route.expected_path, targetUrl);
3053
- return matched && !route.error && (route.http_status === null || route.http_status === void 0 || route.http_status < 400);
3054
- }
3055
- function routeReadinessFailed(route, targetUrl) {
3056
- const matched = route.matched || routePathMatches(route.observed, route.expected_path, targetUrl);
3057
- const httpOk = route.http_status === null || route.http_status === void 0 || route.http_status < 400;
3058
- return matched && httpOk && Boolean(route.error);
3059
- }
3060
- function compactRouteError(error) {
3061
- const text = typeof error === "string" ? error.replace(/\s+/g, " ").trim() : "";
3062
- return text ? text.slice(0, 240) : void 0;
3063
- }
3064
- function routeLoadedFailureMessage(failedRoutes, expectedPath, targetUrl) {
3065
- const readinessFailures = failedRoutes.filter((route) => routeReadinessFailed(route, targetUrl));
3066
- if (readinessFailures.length === failedRoutes.length && readinessFailures.length) {
3067
- const sample = compactRouteError(readinessFailures.find((route) => route.error)?.error);
3068
- return `Route matched ${expectedPath}, but readiness failed in ${readinessFailures.length} viewport(s)${sample ? `: ${sample}` : "."}`;
3069
- }
3070
- if (readinessFailures.length) {
3071
- const sample = compactRouteError(readinessFailures.find((route) => route.error)?.error);
3072
- return `Route did not become ready as ${expectedPath} in ${failedRoutes.length} viewport(s); ${readinessFailures.length} matched path and HTTP but failed readiness${sample ? `: ${sample}` : "."}`;
3073
- }
3074
- return `Route did not load as ${expectedPath} in ${failedRoutes.length} viewport(s).`;
3075
- }
3076
- function parseEvidenceUrl(value, targetUrl) {
3077
- if (!value) return void 0;
3078
- try {
3079
- return targetUrl ? new URL(value, targetUrl) : new URL(value);
3080
- } catch {
3081
- try {
3082
- return new URL(value);
3083
- } catch {
3084
- return void 0;
3085
- }
3086
- }
3087
- }
3088
- function observedUrlForViewport(viewport, targetUrl) {
3089
- return parseEvidenceUrl(viewport.url, targetUrl) || parseEvidenceUrl(viewport.route?.observed, targetUrl) || parseEvidenceUrl(viewport.route?.requested, targetUrl) || parseEvidenceUrl(targetUrl, void 0);
3090
- }
3091
- function searchParamObservation(viewport, targetUrl, param) {
3092
- const url = observedUrlForViewport(viewport, targetUrl);
3093
- const values = url ? url.searchParams.getAll(param) : [];
3094
- return {
3095
- viewport: viewport.name,
3096
- url: url?.href || null,
3097
- value: values.length ? values[0] : null,
3098
- values,
3099
- present: values.length > 0
3100
- };
3101
- }
3102
- function viewportsForCheck(check, viewports) {
3103
- if (!check.viewports?.length) return viewports;
3104
- const names = new Set(check.viewports);
3105
- return viewports.filter((viewport) => names.has(viewport.name));
3106
- }
3107
- function setupActionAppliesToViewport(action, viewportName) {
3108
- if (!action.viewports?.length) return true;
3109
- return Boolean(viewportName && action.viewports.includes(viewportName));
3110
- }
3111
- function setupActionsForViewport(actions, viewportName) {
3112
- return (actions || []).filter((action) => setupActionAppliesToViewport(action, viewportName));
3113
- }
3114
- function assessCheckFromEvidence(check, evidence) {
3115
- const viewports = viewportsForCheck(check, evidence.viewports || []);
3116
- if (!viewports.length) {
3117
- return {
3118
- type: check.type,
3119
- label: checkLabel(check),
3120
- status: "failed",
3121
- evidence: {
3122
- expected_viewports: check.viewports || []
3123
- },
3124
- message: check.viewports?.length ? `No matching viewport evidence was captured for ${check.viewports.join(", ")}.` : "No viewport evidence was captured."
3125
- };
3126
- }
3127
- if (isDialogCountCheckType(check.type)) {
3128
- const field = dialogCountFieldForCheckType(check.type);
3129
- const expectedCount = check.expected_count ?? 0;
3130
- const actualCount = numberValue(evidence.dom_summary?.[field]) ?? 0;
3131
- return {
3132
- type: check.type,
3133
- label: checkLabel(check),
3134
- status: actualCount === expectedCount ? "passed" : "failed",
3135
- evidence: {
3136
- field,
3137
- expected_count: expectedCount,
3138
- count: actualCount
3139
- },
3140
- message: actualCount === expectedCount ? void 0 : `${field} did not equal ${expectedCount}; observed ${actualCount}.`
3141
- };
3142
- }
3143
- if (check.type === "route_loaded") {
3144
- const expectedPath = check.expected_path || new URL(evidence.target_url).pathname || "/";
3145
- const routes = viewports.map((viewport) => ({
3146
- ...viewport.route,
3147
- expected_path: expectedPath,
3148
- matched: routePathMatches(viewport.route.observed, expectedPath, evidence.target_url) || viewport.route.matched
3149
- }));
3150
- const failed = routes.filter((route) => !successfulRoute(route, evidence.target_url));
3151
- return {
3152
- type: check.type,
3153
- label: checkLabel(check),
3154
- status: failed.length ? "failed" : "passed",
3155
- evidence: {
3156
- expected_path: expectedPath,
3157
- observed_paths: viewports.map((viewport) => viewport.route.observed),
3158
- http_statuses: viewports.map((viewport) => viewport.route.http_status ?? null),
3159
- route_errors: viewports.map((viewport) => viewport.route.error ?? null)
3160
- },
3161
- message: failed.length ? routeLoadedFailureMessage(failed, expectedPath, evidence.target_url) : void 0
3162
- };
3163
- }
3164
- if (check.type === "url_search_param_equals") {
3165
- const param = check.param || "";
3166
- const expectedValue = check.expected_value ?? "";
3167
- const observations = viewports.map((viewport) => searchParamObservation(viewport, evidence.target_url, param));
3168
- const failed = observations.filter((observation) => observation.value !== expectedValue);
3169
- return {
3170
- type: check.type,
3171
- label: checkLabel(check),
3172
- status: failed.length ? "failed" : "passed",
3173
- evidence: {
3174
- param,
3175
- expected_value: expectedValue,
3176
- observed_values: observations.map((observation) => observation.value),
3177
- observed_all_values: observations.map((observation) => observation.values),
3178
- observed_urls: observations.map((observation) => observation.url),
3179
- viewports: observations.map((observation) => toJsonValue(observation))
3180
- },
3181
- message: failed.length ? `URL search param ${param} did not equal ${JSON.stringify(expectedValue)} in ${failed.length} viewport(s).` : void 0
3182
- };
3183
- }
3184
- if (check.type === "url_search_param_absent") {
3185
- const param = check.param || "";
3186
- const observations = viewports.map((viewport) => searchParamObservation(viewport, evidence.target_url, param));
3187
- const failed = observations.filter((observation) => observation.present);
3188
- return {
3189
- type: check.type,
3190
- label: checkLabel(check),
3191
- status: failed.length ? "failed" : "passed",
3192
- evidence: {
3193
- param,
3194
- observed_values: observations.map((observation) => observation.value),
3195
- observed_all_values: observations.map((observation) => observation.values),
3196
- observed_urls: observations.map((observation) => observation.url),
3197
- viewports: observations.map((observation) => toJsonValue(observation))
3198
- },
3199
- message: failed.length ? `URL search param ${param} was present in ${failed.length} viewport(s).` : void 0
3200
- };
3201
- }
3202
- if (check.type === "selector_visible") {
3203
- const key = selectorKey(check);
3204
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.visible_count || 0) < 1);
3205
- return {
3206
- type: check.type,
3207
- label: checkLabel(check),
3208
- status: failed.length ? "failed" : "passed",
3209
- evidence: {
3210
- selector: key,
3211
- visible_counts: viewports.map((viewport) => viewport.selectors?.[key]?.visible_count || 0)
3212
- },
3213
- message: failed.length ? `Selector ${key} was not visible in ${failed.length} viewport(s).` : void 0
3214
- };
3215
- }
3216
- if (check.type === "selector_absent") {
3217
- const key = selectorKey(check);
3218
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.count || 0) > 0);
3219
- return {
3220
- type: check.type,
3221
- label: checkLabel(check),
3222
- status: failed.length ? "failed" : "passed",
3223
- evidence: {
3224
- selector: key,
3225
- counts: viewports.map((viewport) => viewport.selectors?.[key]?.count || 0)
3226
- },
3227
- message: failed.length ? `Selector ${key} was present in ${failed.length} viewport(s).` : void 0
3228
- };
3229
- }
3230
- if (check.type === "selector_count_at_least") {
3231
- const key = selectorKey(check);
3232
- const minCount = check.min_count ?? 1;
3233
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.count || 0) < minCount);
3234
- return {
3235
- type: check.type,
3236
- label: checkLabel(check),
3237
- status: failed.length ? "failed" : "passed",
3238
- evidence: {
3239
- selector: key,
3240
- min_count: minCount,
3241
- counts: viewports.map((viewport) => viewport.selectors?.[key]?.count || 0)
3242
- },
3243
- message: failed.length ? `Selector ${key} count was below ${minCount} in ${failed.length} viewport(s).` : void 0
3244
- };
3245
- }
3246
- if (check.type === "selector_count_equals" || check.type === "selector_count_equal" || check.type === "selector_count_eq") {
3247
- const key = selectorKey(check);
3248
- const expectedCount = check.expected_count ?? 0;
3249
- const failed = viewports.filter((viewport) => (viewport.selectors?.[key]?.count || 0) !== expectedCount);
3250
- return {
3251
- type: check.type,
3252
- label: checkLabel(check),
3253
- status: failed.length ? "failed" : "passed",
3254
- evidence: {
3255
- selector: key,
3256
- expected_count: expectedCount,
3257
- counts: viewports.map((viewport) => viewport.selectors?.[key]?.count || 0)
3258
- },
3259
- message: failed.length ? `Selector ${key} count did not equal ${expectedCount} in ${failed.length} viewport(s).` : void 0
3260
- };
3261
- }
3262
- if (check.type === "selector_text_visible" || check.type === "selector_text_absent") {
3263
- const key = selectorKey(check);
3264
- const expectedVisible = check.type === "selector_text_visible";
3265
- const results = viewports.map((viewport) => {
3266
- const texts = textSequenceForCheck(viewport, check);
3267
- const matches = texts.filter((text) => matchText(text, check));
3268
- const matched = matches.length > 0;
3269
- const failedAgainstExpectation = matched !== expectedVisible;
3270
- const sampleTexts = matches.length ? matches : failedAgainstExpectation ? texts : [];
3271
- const caseInsensitiveSamples = failedAgainstExpectation && expectedVisible && !matched ? textCaseInsensitiveSequenceSamples(texts, check) : [];
3272
- return {
3273
- viewport: viewport.name,
3274
- selector_count: viewport.selectors?.[key]?.count || 0,
3275
- visible_count: viewport.selectors?.[key]?.visible_count || 0,
3276
- matched_count: matches.length,
3277
- matched,
3278
- samples: sampleTexts.slice(0, 3).map((text) => text.slice(0, 240)),
3279
- case_insensitive_samples: caseInsensitiveSamples
3280
- };
3281
- });
3282
- const failed = results.filter((result) => result.matched !== expectedVisible).length;
3283
- return {
3284
- type: check.type,
3285
- label: checkLabel(check),
3286
- status: failed ? "failed" : "passed",
3287
- evidence: {
3288
- selector: key,
3289
- text: check.text || null,
3290
- pattern: check.pattern || null,
3291
- viewports: results.map((result) => toJsonValue(result))
3292
- },
3293
- message: failed ? `Selector ${key} text assertion failed in ${failed} viewport(s).` : void 0
3294
- };
3295
- }
3296
- if (check.type === "selector_text_order") {
3297
- const key = selectorKey(check);
3298
- const expectedTexts = check.expected_texts || [];
3299
- const results = viewports.map((viewport) => {
3300
- const texts = textSequenceForCheck(viewport, check);
3301
- const match = textOrderMatch(texts, expectedTexts);
3302
- return {
3303
- viewport: viewport.name,
3304
- matched: match.matched,
3305
- matched_positions: match.positions,
3306
- visible_texts: texts.slice(0, 20).map((text) => text.slice(0, 240))
3307
- };
3308
- });
3309
- const failed = results.filter((result) => !result.matched).length;
3310
- return {
3311
- type: check.type,
3312
- label: checkLabel(check),
3313
- status: failed ? "failed" : "passed",
3314
- evidence: {
3315
- selector: key,
3316
- expected_texts: expectedTexts,
3317
- viewports: results.map((result) => toJsonValue(result))
3318
- },
3319
- message: failed ? `Selector ${key} text order failed in ${failed} viewport(s).` : void 0
3320
- };
3321
- }
3322
- if (check.type === "ordered_trace") {
3323
- const assessments = viewports.map((viewport) => ({
3324
- viewport: viewport.name,
3325
- assessment: assessRiddleProofOrderedTraceSetupResults(
3326
- viewport.setup_action_results,
3327
- check.setup_action_label || "",
3328
- check.trace_path || "",
3329
- check.events || []
3330
- )
3331
- }));
3332
- const insufficient = assessments.filter((item) => item.assessment.status === "proof_insufficient");
3333
- const failed = assessments.filter((item) => item.assessment.status === "failed");
3334
- const status = insufficient.length ? "proof_insufficient" : failed.length ? "failed" : "passed";
3335
- return {
3336
- type: check.type,
3337
- label: checkLabel(check),
3338
- status,
3339
- evidence: {
3340
- setup_action_label: check.setup_action_label || "",
3341
- trace_path: check.trace_path || "",
3342
- events: toJsonValue((check.events || []).map((event) => event.label)),
3343
- viewports: toJsonValue(assessments)
3344
- },
3345
- message: insufficient.length ? `Ordered trace evidence was insufficient in ${insufficient.length} viewport(s).` : failed.length ? `Ordered trace did not contain the required event sequence in ${failed.length} viewport(s).` : void 0
3346
- };
3347
- }
3348
- if (check.type === "observe_within") {
3349
- const key = observeWithinKey(check);
3350
- const timeoutMs = observeWithinTimeoutMs(check);
3351
- const results = viewports.map((viewport) => {
3352
- const observation = viewport.observations?.[key];
3353
- const matched = observation?.matched === true;
3354
- return {
3355
- viewport: viewport.name,
3356
- matched,
3357
- elapsed_ms: numberValue(observation?.elapsed_ms) ?? null,
3358
- timeout_ms: numberValue(observation?.timeout_ms) ?? timeoutMs,
3359
- attempts: numberValue(observation?.attempts) ?? null,
3360
- selector_count: numberValue(observation?.selector_count) ?? null,
3361
- visible_count: numberValue(observation?.visible_count) ?? null,
3362
- matched_count: numberValue(observation?.matched_count) ?? null,
3363
- sample: stringValue(observation?.sample) ?? null,
3364
- error: stringValue(observation?.error) ?? null
3365
- };
3366
- });
3367
- const failed = results.filter((result) => !result.matched).length;
3368
- return {
3369
- type: check.type,
3370
- label: checkLabel(check),
3371
- status: failed ? "failed" : "passed",
3372
- evidence: {
3373
- selector: check.selector || null,
3374
- text: check.text || null,
3375
- pattern: check.pattern || null,
3376
- timeout_ms: timeoutMs,
3377
- viewports: results.map((result) => toJsonValue(result))
3378
- },
3379
- message: failed ? `Observation did not match within ${timeoutMs}ms in ${failed} viewport(s).` : void 0
3380
- };
3381
- }
3382
- if (check.type === "frame_text_visible") {
3383
- const key = selectorKey(check);
3384
- const results = viewports.map((viewport) => {
3385
- const frames = frameEvidenceForSelector(viewport, key);
3386
- const matches = frames.map((frame, index) => ({ index, frame, matched: matchText(frameTextSample(frame), check) })).filter((item) => item.matched);
3387
- return {
3388
- viewport: viewport.name,
3389
- frame_count: frames.length,
3390
- matched_count: matches.length,
3391
- matched: matches.length > 0,
3392
- urls: frames.map((frame) => String(frame.url || "")).filter(Boolean).slice(0, 10),
3393
- samples: matches.map((item) => frameTextSample(item.frame).replace(/\s+/g, " ").trim().slice(0, 240)).slice(0, 3)
3394
- };
3395
- });
3396
- const failed = results.filter((result) => !result.matched).length;
3397
- return {
3398
- type: check.type,
3399
- label: checkLabel(check),
3400
- status: failed ? "failed" : "passed",
3401
- evidence: {
3402
- selector: key,
3403
- text: check.text || null,
3404
- pattern: check.pattern || null,
3405
- viewports: results.map((result) => toJsonValue(result))
3406
- },
3407
- message: failed ? `Frame selector ${key} did not contain expected text in ${failed} viewport(s).` : void 0
3408
- };
3409
- }
3410
- if (check.type === "frame_url_equals" || check.type === "frame_url_matches") {
3411
- const key = selectorKey(check);
3412
- const expectedUrl = check.expected_url || check.expected_value || "";
3413
- const results = viewports.map((viewport) => {
3414
- const frames = frameEvidenceForSelector(viewport, key);
3415
- const urls = frames.map((frame) => String(frame.url || "")).filter(Boolean);
3416
- const matches = urls.filter((url) => check.type === "frame_url_equals" ? url === expectedUrl : matchText(url, check));
3417
- return {
3418
- viewport: viewport.name,
3419
- frame_count: frames.length,
3420
- matched_count: matches.length,
3421
- matched: matches.length > 0,
3422
- urls: urls.slice(0, 10)
3423
- };
3424
- });
3425
- const failed = results.filter((result) => !result.matched).length;
3426
- return {
3427
- type: check.type,
3428
- label: checkLabel(check),
3429
- status: failed ? "failed" : "passed",
3430
- evidence: {
3431
- selector: key,
3432
- expected_url: check.type === "frame_url_equals" ? expectedUrl : null,
3433
- pattern: check.type === "frame_url_matches" ? check.pattern || null : null,
3434
- viewports: results.map((result) => toJsonValue(result))
3435
- },
3436
- message: failed ? `Frame selector ${key} URL assertion failed in ${failed} viewport(s).` : void 0
3437
- };
3438
- }
3439
- if (check.type === "frame_no_horizontal_overflow") {
3440
- const key = selectorKey(check);
3441
- const maxOverflow = check.max_overflow_px ?? 4;
3442
- const results = viewports.map((viewport) => {
3443
- const frames = frameEvidenceForSelector(viewport, key);
3444
- const frameOverflows = frames.map((frame, index) => ({
3445
- index,
3446
- url: String(frame.url || ""),
3447
- overflow_px: horizontalBoundsOverflowPx(frame),
3448
- offender_count: boundsOffendersForEvidence(frame).length
3449
- }));
3450
- const maxFrameOverflow = frameOverflows.reduce((max, frame) => Math.max(max, frame.overflow_px), 0);
3451
- return {
3452
- viewport: viewport.name,
3453
- frame_count: frames.length,
3454
- max_overflow_px: roundPixels(maxFrameOverflow),
3455
- failed_frame_count: frameOverflows.filter((frame) => frame.overflow_px > maxOverflow).length,
3456
- frames: frameOverflows.map((frame) => toJsonValue(frame))
3457
- };
3458
- });
3459
- const failed = results.filter((result) => result.frame_count < 1 || result.failed_frame_count > 0).length;
3460
- return {
3461
- type: check.type,
3462
- label: checkLabel(check),
3463
- status: failed ? "failed" : "passed",
3464
- evidence: {
3465
- selector: key,
3466
- max_overflow_px: maxOverflow,
3467
- viewports: results.map((result) => toJsonValue(result))
3468
- },
3469
- message: failed ? `Frame selector ${key} overflow exceeded ${maxOverflow}px or was missing in ${failed} viewport(s).` : void 0
3470
- };
3471
- }
3472
- if (check.type === "text_visible" || check.type === "text_absent") {
3473
- const key = textKey(check);
3474
- const expectedVisible = check.type === "text_visible";
3475
- const results = viewports.map((viewport) => {
3476
- const fromEvidence = viewport.text_matches?.[key];
3477
- const matched = typeof fromEvidence === "boolean" ? fromEvidence : matchText(viewport.body_text_sample || "", check);
3478
- const failedAgainstExpectation = matched !== expectedVisible;
3479
- return {
3480
- viewport: viewport.name,
3481
- matched,
3482
- samples: failedAgainstExpectation ? textCheckFailureSamples(viewport, check) : [],
3483
- case_insensitive_samples: failedAgainstExpectation && expectedVisible && !matched ? textCaseInsensitiveFailureSamples(viewport, check) : []
3484
- };
3485
- });
3486
- const matches = results.map((result) => result.matched);
3487
- const failed = matches.filter((matched) => matched !== expectedVisible).length;
3488
- return {
3489
- type: check.type,
3490
- label: checkLabel(check),
3491
- status: failed ? "failed" : "passed",
3492
- evidence: {
3493
- text: check.text || null,
3494
- pattern: check.pattern || null,
3495
- matches,
3496
- viewports: results.map((result) => toJsonValue(result))
3497
- },
3498
- message: failed ? `Text assertion failed in ${failed} viewport(s).` : void 0
3499
- };
3500
- }
3501
- if (check.type === "http_status") {
3502
- const url = httpStatusRequestUrl(check, evidence.target_url);
3503
- const method = httpStatusMethod(check);
3504
- const summaries = viewports.map((viewport) => summarizeHttpStatusEvidence(viewport, check));
3505
- const failed = summaries.filter((summary) => Array.isArray(summary.failures) && summary.failures.length > 0);
3506
- return {
3507
- type: check.type,
3508
- label: checkLabel(check),
3509
- status: failed.length ? "failed" : "passed",
3510
- evidence: {
3511
- url,
3512
- method,
3513
- allowed_statuses: httpStatusAllowedStatuses(check) || ["2xx", "3xx"],
3514
- require_nonzero_bytes: check.require_nonzero_bytes === true,
3515
- min_bytes: check.min_bytes ?? null,
3516
- allowed_content_types: check.allowed_content_types ?? null,
3517
- body_contains: check.body_contains ?? [],
3518
- body_not_contains: check.body_not_contains ?? [],
3519
- body_not_patterns: check.body_not_patterns ?? [],
3520
- body_json_assertions: toJsonValue(check.body_json_assertions ?? []),
3521
- viewports: summaries.map((summary) => toJsonValue(summary)),
3522
- failures: failed.flatMap((summary) => Array.isArray(summary.failures) ? summary.failures.map((failure) => toJsonValue({ viewport: stringValue(summary.viewport) ?? null, failure })) : [])
3523
- },
3524
- message: failed.length ? `HTTP status failed in ${failed.length} viewport(s).` : void 0
3525
- };
3526
- }
3527
- if (check.type === "link_status" || check.type === "artifact_link_status") {
3528
- const selector = linkStatusSelector(check);
3529
- const summaries = viewports.map((viewport) => summarizeLinkStatusEvidence(viewport, check));
3530
- const failed = summaries.filter((summary) => (numberValue(summary.failed_count) ?? 0) > 0);
3531
- return {
3532
- type: check.type,
3533
- label: checkLabel(check),
3534
- status: failed.length ? "failed" : "passed",
3535
- evidence: {
3536
- selector,
3537
- expected_count: check.expected_count ?? null,
3538
- min_count: check.min_count ?? null,
3539
- allowed_statuses: linkStatusAllowedStatuses(check) || ["2xx", "3xx"],
3540
- require_nonzero_bytes: check.require_nonzero_bytes === true,
3541
- min_bytes: check.min_bytes ?? null,
3542
- allowed_content_types: check.allowed_content_types ?? null,
3543
- viewports: summaries.map((summary) => toJsonValue(summary)),
3544
- failures: failed.flatMap((summary) => Array.isArray(summary.failures) ? summary.failures.map((failure) => toJsonValue({ viewport: stringValue(summary.viewport) ?? null, failure })) : [])
3545
- },
3546
- message: failed.length ? `Link status failed in ${failed.length} viewport(s).` : void 0
3547
- };
3548
- }
3549
- if (check.type === "route_inventory") {
3550
- const inventories = viewports.map((viewport) => ({ viewport: viewport.name, inventory: viewport.route_inventory })).filter((item) => isRecord(item.inventory));
3551
- if (!inventories.length) {
3552
- return {
3553
- type: check.type,
3554
- label: checkLabel(check),
3555
- status: "failed",
3556
- evidence: {
3557
- expected_count: check.expected_routes?.length || 0,
3558
- expected_routes: routeInventoryExpectedRouteSummaries(void 0, check.expected_routes)
3559
- },
3560
- message: "No route inventory evidence was captured."
3561
- };
3562
- }
3563
- const viewportSummaries = inventories.map((item) => summarizeRouteInventory(item.viewport, item.inventory));
3564
- const failures = inventories.flatMap((item) => Array.isArray(item.inventory?.failures) ? item.inventory.failures.map((failure) => toJsonValue({ viewport: item.viewport, failure })) : []);
3565
- const first = inventories[0]?.inventory;
3566
- const directRoutes = Array.isArray(first?.direct_routes) ? first.direct_routes : [];
3567
- const clickthroughs = Array.isArray(first?.clickthroughs) ? first.clickthroughs : [];
3568
- const sourceLinkCount = numberValue(first?.source_link_count) ?? numberValue(first?.home_game_link_count) ?? null;
3569
- const sourceUniqueLinkCount = numberValue(first?.source_unique_link_count) ?? numberValue(first?.home_unique_game_link_count) ?? null;
3570
- const sourceCandidateCount = numberValue(first?.source_candidate_count);
3571
- const sourceCandidateUniqueLinkCount = numberValue(first?.source_candidate_unique_link_count);
3572
- const sourceLinkScope = stringValue(first?.source_link_scope);
3573
- const duplicateSourceLinks = Array.isArray(first?.duplicate_source_link_paths) ? first.duplicate_source_link_paths.map((path) => String(path)) : [];
3574
- const duplicateSourceLinkCount = numberValue(first?.duplicate_source_link_count) ?? (sourceLinkCount !== null && sourceUniqueLinkCount !== null ? Math.max(0, sourceLinkCount - sourceUniqueLinkCount) : null);
3575
- const expectedRoutes = routeInventoryExpectedRouteSummaries(first?.expected_routes, check.expected_routes);
3576
- return {
3577
- type: check.type,
3578
- label: checkLabel(check),
3579
- status: failures.length ? "failed" : "passed",
3580
- evidence: {
3581
- expected_count: check.expected_routes?.length || 0,
3582
- expected_routes: expectedRoutes,
3583
- source_link_scope: sourceLinkScope ?? null,
3584
- source_candidate_count: sourceCandidateCount ?? sourceLinkCount,
3585
- source_candidate_unique_link_count: sourceCandidateUniqueLinkCount ?? sourceUniqueLinkCount,
3586
- source_link_count: sourceLinkCount,
3587
- source_unique_link_count: sourceUniqueLinkCount,
3588
- duplicate_source_link_count: duplicateSourceLinkCount,
3589
- duplicate_source_links: duplicateSourceLinks,
3590
- duplicates_allowed: check.require_unique_routes === false,
3591
- homepage_link_count: numberValue(first?.home_game_link_count) ?? sourceLinkCount,
3592
- homepage_unique_link_count: numberValue(first?.home_unique_game_link_count) ?? sourceUniqueLinkCount,
3593
- direct_route_count: directRoutes.length,
3594
- clickthrough_count: clickthroughs.length,
3595
- viewport_count: inventories.length,
3596
- viewports: viewportSummaries.map((summary) => toJsonValue(summary)),
3597
- failures
3598
- },
3599
- message: failures.length ? `Route inventory failed with ${failures.length} issue(s).` : void 0
3600
- };
3601
- }
3602
- if (check.type === "no_horizontal_overflow" || check.type === "no_mobile_horizontal_overflow") {
3603
- const maxOverflow = check.max_overflow_px ?? 4;
3604
- const applicable = check.type === "no_mobile_horizontal_overflow" ? viewports.filter((viewport) => viewport.width <= 820) : viewports;
3605
- if (!applicable.length) {
3606
- const mobileOnly = check.type === "no_mobile_horizontal_overflow";
3607
- return {
3608
- type: check.type,
3609
- label: checkLabel(check),
3610
- status: mobileOnly ? "skipped" : "failed",
3611
- evidence: { max_overflow_px: maxOverflow, viewports: [] },
3612
- message: mobileOnly ? "No mobile viewport evidence was captured; mobile overflow check skipped." : "No applicable viewport evidence was captured for overflow check."
3613
- };
3614
- }
3615
- const failed = applicable.filter((viewport) => horizontalBoundsOverflowPx(viewport) > maxOverflow);
3616
- return {
3617
- type: check.type,
3618
- label: checkLabel(check),
3619
- status: failed.length ? "failed" : "passed",
3620
- evidence: {
3621
- max_overflow_px: maxOverflow,
3622
- overflow_px: applicable.map((viewport) => viewport.overflow_px ?? null),
3623
- bounds_overflow_px: applicable.map((viewport) => horizontalBoundsOverflowPx(viewport)),
3624
- overflow_offender_counts: applicable.map((viewport) => boundsOffendersForEvidence(viewport).length),
3625
- viewports: applicable.map((viewport) => viewport.name)
3626
- },
3627
- message: failed.length ? `Horizontal bounds overflow exceeded ${maxOverflow}px in ${failed.length} viewport(s).` : void 0
3628
- };
3629
- }
3630
- if (check.type === "no_fatal_console_errors") {
3631
- const fatalConsoleEvents = (evidence.console?.events || []).filter((event) => event.type === "error" || event.type === "assert");
3632
- const explicitlyAllowedConsoleEvents = fatalConsoleEvents.filter((event) => matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns));
3633
- const expectedNetworkMockConsoleEvents = fatalConsoleEvents.filter((event) => !matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns) && isExpectedFailedNetworkMockConsoleEvent(event, evidence));
3634
- const allowedConsoleEvents = fatalConsoleEvents.filter((event) => matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns) || isExpectedFailedNetworkMockConsoleEvent(event, evidence));
3635
- const unallowedConsoleEvents = fatalConsoleEvents.filter((event) => !matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns) && !isExpectedFailedNetworkMockConsoleEvent(event, evidence));
3636
- const pageErrors = evidence.page_errors || [];
3637
- const allowedPageErrors = pageErrors.filter((error) => matchesAllowedMessage(error, check.allowed_page_error_texts, check.allowed_page_error_patterns));
3638
- const unallowedPageErrors = pageErrors.filter((error) => !matchesAllowedMessage(error, check.allowed_page_error_texts, check.allowed_page_error_patterns));
3639
- const fatalCount = unallowedConsoleEvents.length + unallowedPageErrors.length;
3640
- return {
3641
- type: check.type,
3642
- label: checkLabel(check),
3643
- status: fatalCount ? "failed" : "passed",
3644
- evidence: {
3645
- console_fatal_count: unallowedConsoleEvents.length,
3646
- page_error_count: unallowedPageErrors.length,
3647
- total_console_fatal_count: fatalConsoleEvents.length,
3648
- total_page_error_count: pageErrors.length,
3649
- allowed_console_fatal_count: allowedConsoleEvents.length,
3650
- explicitly_allowed_console_fatal_count: explicitlyAllowedConsoleEvents.length,
3651
- allowed_expected_network_mock_console_count: expectedNetworkMockConsoleEvents.length,
3652
- allowed_expected_network_mock_console_events: expectedNetworkMockConsoleEvents.slice(0, 5).map((event) => expectedFailedNetworkMockConsoleEventSummary(event, evidence)),
3653
- allowed_page_error_count: allowedPageErrors.length,
3654
- allowed_console_texts: check.allowed_console_texts || [],
3655
- allowed_console_patterns: check.allowed_console_patterns || [],
3656
- allowed_page_error_texts: check.allowed_page_error_texts || [],
3657
- allowed_page_error_patterns: check.allowed_page_error_patterns || []
3658
- },
3659
- message: fatalCount ? `${fatalCount} fatal browser error(s) were captured.` : void 0
3660
- };
3661
- }
3662
- if (check.type === "no_console_warnings") {
3663
- const warningConsoleEvents = (evidence.console?.events || []).filter((event) => event.type === "warning" || event.type === "warn");
3664
- const allowedConsoleEvents = warningConsoleEvents.filter((event) => matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns));
3665
- const unallowedConsoleEvents = warningConsoleEvents.filter((event) => !matchesAllowedMessage(event, check.allowed_console_texts, check.allowed_console_patterns));
3666
- return {
3667
- type: check.type,
3668
- label: checkLabel(check),
3669
- status: unallowedConsoleEvents.length ? "failed" : "passed",
3670
- evidence: {
3671
- console_warning_count: unallowedConsoleEvents.length,
3672
- total_console_warning_count: warningConsoleEvents.length,
3673
- allowed_console_warning_count: allowedConsoleEvents.length,
3674
- allowed_console_texts: check.allowed_console_texts || [],
3675
- allowed_console_patterns: check.allowed_console_patterns || [],
3676
- unallowed_console_warning_samples: unallowedConsoleEvents.slice(0, 5).map((event) => allowedMessageSample(event)),
3677
- allowed_console_warning_samples: allowedConsoleEvents.slice(0, 5).map((event) => allowedMessageSample(event))
3678
- },
3679
- message: unallowedConsoleEvents.length ? `${unallowedConsoleEvents.length} console warning(s) were captured.` : void 0
3680
- };
3681
- }
3682
- return {
3683
- type: check.type,
3684
- label: checkLabel(check),
3685
- status: "needs_human_review",
3686
- evidence: {},
3687
- message: "Unsupported check type."
3688
- };
3689
- }
3690
- function assessSetupActionsFromEvidence(profile, evidence) {
3691
- if (!profile.target.setup_actions?.length) return void 0;
3692
- const actionCount = profile.target.setup_actions.length;
3693
- const failed = [];
3694
- const viewports = evidence.viewports || [];
3695
- const expectedActionCountByViewport = /* @__PURE__ */ new Map();
3696
- for (const viewport of viewports) {
3697
- const expectedActionCount = setupActionsForViewport(profile.target.setup_actions, viewport.name).length;
3698
- expectedActionCountByViewport.set(viewport.name, expectedActionCount);
3699
- const results = viewport.setup_action_results || [];
3700
- for (const result of results) {
3701
- if (result.ok === false && result.optional !== true) {
3702
- failed.push({
3703
- viewport: viewport.name,
3704
- action: result.action ?? result.type ?? null,
3705
- selector: result.selector ?? null,
3706
- frame_selector: result.frame_selector ?? null,
3707
- frame_index: result.frame_index ?? null,
3708
- reason: result.reason ?? result.error ?? null
3709
- });
3710
- }
3711
- }
3712
- if (results.length < expectedActionCount && results.every((result) => result.ok !== false || result.optional === true)) {
3713
- failed.push({
3714
- viewport: viewport.name,
3715
- action: "setup_actions",
3716
- selector: null,
3717
- reason: `missing setup action results: ${results.length}/${expectedActionCount}`
3718
- });
3719
- }
3720
- }
3721
- return {
3722
- type: "setup_actions_succeeded",
3723
- label: "setup actions succeeded",
3724
- status: failed.length ? "failed" : "passed",
3725
- evidence: {
3726
- action_count: actionCount,
3727
- viewports: viewports.map((viewport) => ({
3728
- name: viewport.name,
3729
- expected_action_count: expectedActionCountByViewport.get(viewport.name) ?? actionCount,
3730
- ok: (viewport.setup_action_results || []).length >= (expectedActionCountByViewport.get(viewport.name) ?? actionCount) && (viewport.setup_action_results || []).every((result) => result.ok !== false || result.optional === true),
3731
- result_count: (viewport.setup_action_results || []).length
3732
- })),
3733
- setup_summary: profileSetupSummary(viewports, actionCount, expectedActionCountByViewport, profile.target.screenshot_full_page),
3734
- failed
3735
- },
3736
- message: failed.length ? `Setup actions failed in ${failed.length} viewport action(s).` : void 0
3737
- };
349
+ function httpStatusBodyNotPatternFailures(result, check) {
350
+ const forbidden = check.body_not_patterns?.filter(Boolean) ?? [];
351
+ if (!forbidden.length) return [];
352
+ const observed = isRecord(result.body_not_patterns) ? result.body_not_patterns : {};
353
+ return forbidden.filter((pattern) => observed[pattern] !== false);
3738
354
  }
3739
- function assessNetworkMocksFromEvidence(profile, evidence) {
3740
- const mocks = profile.target.network_mocks || [];
3741
- if (!mocks.length) return void 0;
3742
- const events = evidence.network_mocks || [];
3743
- const failed = [];
3744
- const requiredMocks = mocks.filter((mock) => mock.required !== false);
3745
- const hitCountForMock = (mock) => events.filter((event) => event.label === mock.label && event.ok !== false).length;
3746
- for (const mock of requiredMocks) {
3747
- const hits = hitCountForMock(mock);
3748
- const requiredHitCount = requiredNetworkMockHitCount(mock);
3749
- if (hits < requiredHitCount) {
3750
- failed.push({
3751
- label: mock.label,
3752
- url: mock.url,
3753
- method: mock.method || null,
3754
- reason: hits < 1 ? "required_mock_not_hit" : "required_mock_hit_count_not_met",
3755
- required_hit_count: requiredHitCount,
3756
- hit_count: hits
3757
- });
3758
- }
355
+ function httpStatusBodyJsonAssertionFailures(result, check) {
356
+ const expected = check.body_json_assertions?.filter((assertion) => assertion.path) ?? [];
357
+ if (!expected.length) return [];
358
+ if (!Array.isArray(result.body_json_assertions)) {
359
+ return expected.map((assertion) => ({
360
+ label: assertion.label || assertion.path,
361
+ path: assertion.path,
362
+ ok: false,
363
+ exists: false,
364
+ observed_type: "missing",
365
+ errors: ["body_json_assertions evidence missing"]
366
+ }));
3759
367
  }
3760
- for (const mock of mocks) {
3761
- if (mock.max_hit_count === void 0) continue;
3762
- const hits = hitCountForMock(mock);
3763
- if (hits > mock.max_hit_count) {
3764
- failed.push({
3765
- label: mock.label,
3766
- url: mock.url,
3767
- method: mock.method || null,
3768
- reason: mock.max_hit_count === 0 ? "forbidden_mock_hit" : "mock_hit_count_exceeded",
3769
- max_hit_count: mock.max_hit_count,
3770
- hit_count: hits
3771
- });
3772
- }
368
+ return result.body_json_assertions.filter((assertion) => isRecord(assertion) && assertion.ok !== true).map((assertion) => ({
369
+ label: stringValue(assertion.label) || stringValue(assertion.path) || "json assertion",
370
+ path: stringValue(assertion.path) || "",
371
+ ok: false,
372
+ exists: assertion.exists === true,
373
+ observed: hasOwn(assertion, "observed") ? toJsonValue(assertion.observed) : void 0,
374
+ observed_sample: hasOwn(assertion, "observed_sample") ? toJsonValue(assertion.observed_sample) : void 0,
375
+ observed_length: numberValue(assertion.observed_length),
376
+ observed_key_count: numberValue(assertion.observed_key_count),
377
+ observed_omitted_count: numberValue(assertion.observed_omitted_count),
378
+ observed_type: stringValue(assertion.observed_type) || "missing",
379
+ expected_exists: booleanValue(assertion.expected_exists),
380
+ equals: hasOwn(assertion, "equals") ? toJsonValue(assertion.equals) : void 0,
381
+ not_equals: hasOwn(assertion, "not_equals") ? toJsonValue(assertion.not_equals) : void 0,
382
+ contains: hasOwn(assertion, "contains") ? toJsonValue(assertion.contains) : void 0,
383
+ type: stringValue(assertion.type),
384
+ errors: Array.isArray(assertion.errors) ? assertion.errors.map(String) : void 0
385
+ }));
386
+ }
387
+ function linkStatusResultOk(result, check) {
388
+ const status = numberValue(result.status);
389
+ if (!httpStatusIsAllowed(status, check)) return false;
390
+ if (stringValue(result.error)) return false;
391
+ if (result.ok === false) return false;
392
+ if (!linkStatusContentTypeOk(result, check)) return false;
393
+ if (check.require_nonzero_bytes) {
394
+ const observedBytes = linkStatusObservedBytes(result);
395
+ if (observedBytes === void 0 || observedBytes <= 0) return false;
3773
396
  }
3774
- for (const event of events) {
3775
- if (event.ok === false) {
3776
- failed.push({
3777
- label: event.label ?? null,
3778
- url: event.url ?? null,
3779
- method: event.method ?? null,
3780
- reason: event.reason ?? event.error ?? "mock_failed"
3781
- });
3782
- }
3783
- if (event.request_body_matches === false) {
3784
- failed.push({
3785
- label: event.label ?? null,
3786
- response_label: event.response_label ?? null,
3787
- hit_index: event.hit_index ?? null,
3788
- response_index: event.response_index ?? null,
3789
- url: event.url ?? null,
3790
- method: event.method ?? null,
3791
- reason: "request_body_mismatch",
3792
- request_body_failures: event.request_body_failures ?? [],
3793
- request_body_length: event.request_body_length ?? null,
3794
- request_body_sample: event.request_body_sample ?? null
3795
- });
3796
- }
397
+ if (check.min_bytes !== void 0) {
398
+ const observedBytes = linkStatusObservedBytes(result);
399
+ if (observedBytes === void 0 || observedBytes < check.min_bytes) return false;
3797
400
  }
3798
- return {
3799
- type: "network_mocks_succeeded",
3800
- label: "network mocks succeeded",
3801
- status: failed.length ? "failed" : "passed",
3802
- evidence: {
3803
- mock_count: mocks.length,
3804
- required_count: requiredMocks.length,
3805
- hit_count: events.filter((event) => event.ok !== false).length,
3806
- hits_by_label: Object.fromEntries(mocks.map((mock) => [
3807
- mock.label,
3808
- hitCountForMock(mock)
3809
- ])),
3810
- required_hits_by_label: Object.fromEntries(requiredMocks.map((mock) => [
3811
- mock.label,
3812
- requiredNetworkMockHitCount(mock)
3813
- ])),
3814
- max_hits_by_label: Object.fromEntries(mocks.filter((mock) => mock.max_hit_count !== void 0).map((mock) => [mock.label, mock.max_hit_count ?? null])),
3815
- response_hits_by_label: networkMockResponseHitsByLabel(events),
3816
- failed
3817
- },
3818
- message: failed.length ? `Network mocks failed or hit-count contracts failed for ${failed.length} mock(s).` : void 0
3819
- };
401
+ if (httpStatusBodyContainsFailures(result, check).length) return false;
402
+ if (httpStatusBodyNotContainsFailures(result, check).length) return false;
403
+ if (httpStatusBodyNotPatternFailures(result, check).length) return false;
404
+ if (httpStatusBodyJsonAssertionFailures(result, check).length) return false;
405
+ return true;
3820
406
  }
3821
- function networkMockResponseHitsByLabel(events) {
3822
- const responseHits = {};
3823
- for (const event of events) {
3824
- if (!event || event.ok === false) continue;
3825
- const label = typeof event.label === "string" ? event.label : "";
3826
- const responseLabel2 = typeof event.response_label === "string" ? event.response_label : "";
3827
- const hasSequenceResponse = typeof event.response_index === "number" || event.sequence_cycle === true || Boolean(responseLabel2 && responseLabel2 !== label);
3828
- if (!label || !responseLabel2 || !hasSequenceResponse) continue;
3829
- responseHits[label] || (responseHits[label] = {});
3830
- responseHits[label][responseLabel2] = (responseHits[label][responseLabel2] || 0) + 1;
3831
- }
3832
- return responseHits;
407
+ function responseHeader(response, name) {
408
+ const getter = response.headers?.get;
409
+ if (typeof getter !== "function") return null;
410
+ return getter.call(response.headers, name);
3833
411
  }
3834
- function requiredNetworkMockHitCount(mock) {
3835
- if (mock.required === false) return 0;
3836
- if (mock.required_hit_count !== void 0) return mock.required_hit_count;
3837
- if (Array.isArray(mock.responses) && mock.responses.length) return mock.responses.length;
3838
- return 1;
412
+ function responseContentLength(response) {
413
+ const value = responseHeader(response, "content-length");
414
+ return value && /^\d+$/.test(value) ? Number(value) : null;
3839
415
  }
3840
- function profileStatusFromEvidence(profile, evidence, checks) {
3841
- if (!evidence) return "proof_insufficient";
3842
- const viewports = evidence.viewports || [];
3843
- const expectedViewportCount = profile.target.viewports?.length || 0;
3844
- if (!viewports.length || !checks.length) return "proof_insufficient";
3845
- if (viewports.some((viewport) => viewport.navigation_error)) return "environment_blocked";
3846
- if (expectedViewportCount && viewports.length < expectedViewportCount) return "proof_insufficient";
3847
- if (checks.some((check) => check.status === "proof_insufficient")) return "proof_insufficient";
3848
- if (checks.some((check) => check.status === "needs_human_review")) return "needs_human_review";
3849
- if (checks.some((check) => check.status === "failed")) return "product_regression";
3850
- return "passed";
3851
- }
3852
- var RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS = [
3853
- "screenshot",
3854
- "console",
3855
- "dom_summary",
3856
- "proof_json"
3857
- ];
3858
- function preflightRiddleProofProfileRunnerArtifacts(profile, runner) {
3859
- const requested = uniqueNonEmptyStrings(profile.artifacts || []);
3860
- if (runner !== "riddle") {
416
+ async function responseBodyText(response) {
417
+ if (typeof response.arrayBuffer === "function") {
418
+ const buffer = await response.arrayBuffer();
3861
419
  return {
3862
- ok: true,
3863
- runner,
3864
- requested,
3865
- local_only: [],
3866
- hosted_artifacts: [...RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS]
420
+ text: new TextDecoder().decode(buffer),
421
+ bytes: buffer.byteLength
3867
422
  };
3868
423
  }
3869
- const localOnly = requested.filter(profileArtifactIsHostedLocalOnly);
3870
- const subject = localOnly.join(", ");
3871
- const message = localOnly.length ? `${subject} ${localOnly.length === 1 ? "is" : "are"} local-runner output; hosted runs produce proof_json, console, dom_summary, and screenshots. Remove ${localOnly.length === 1 ? "it" : "them"} from profile.artifacts for --runner riddle.` : void 0;
3872
- return {
3873
- ok: localOnly.length === 0,
3874
- runner,
3875
- requested,
3876
- local_only: localOnly,
3877
- hosted_artifacts: [...RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS],
3878
- message
3879
- };
3880
- }
3881
- function assessRiddleProofProfileArtifactCompleteness(profile, result, artifacts) {
3882
- const required = profileRequiredArtifactKeys(profile, result);
3883
- const missing = required.filter((key) => !profileArtifactKeyPresent(key, artifacts));
3884
- return {
3885
- ok: missing.length === 0,
3886
- required,
3887
- observed: artifacts.map((artifact) => profileArtifactObservedLabel(artifact)).filter(Boolean),
3888
- missing
3889
- };
3890
- }
3891
- function applyRiddleProofProfileArtifactCompleteness(profile, result, artifacts) {
3892
- if (artifacts === void 0) return result;
3893
- const completeness = assessRiddleProofProfileArtifactCompleteness(profile, result, artifacts);
3894
- if (result.status !== "passed" || completeness.ok) {
424
+ if (typeof response.text === "function") {
425
+ const text = await response.text();
3895
426
  return {
3896
- ...result,
3897
- artifacts: {
3898
- ...result.artifacts,
3899
- riddle_artifacts: artifacts
3900
- }
427
+ text,
428
+ bytes: new TextEncoder().encode(text).byteLength
3901
429
  };
3902
430
  }
3903
- const missing = completeness.missing.join(", ");
3904
- const message = `Missing required profile artifact(s): ${missing}`;
3905
- const warnings = [...result.warnings || [], message];
3906
- return {
3907
- ...result,
3908
- status: "proof_insufficient",
3909
- artifacts: {
3910
- ...result.artifacts,
3911
- riddle_artifacts: artifacts
3912
- },
3913
- summary: `${profile.name} did not produce required profile artifact(s): ${missing}.`,
3914
- warnings,
3915
- error: message
3916
- };
431
+ return { text: "", bytes: null };
3917
432
  }
3918
- function profileRequiredArtifactKeys(profile, result) {
3919
- const keys = [];
3920
- for (const artifact of profile.artifacts || []) {
3921
- const role = normalizeProfileArtifactRole(artifact);
3922
- if (!role) continue;
3923
- if (role === "screenshot") {
3924
- const screenshots = result.artifacts.screenshots || [];
3925
- if (screenshots.length) {
3926
- keys.push(...screenshots.map((label) => `screenshot:${label}`));
3927
- } else {
3928
- keys.push("screenshot");
3929
- }
3930
- continue;
433
+ function httpStatusRequestBody(check) {
434
+ const headers = isRecord(check.headers) ? Object.fromEntries(Object.entries(check.headers).map(([key, value]) => [key, String(value)]).filter(([key]) => key.trim())) : {};
435
+ if (check.body_json !== void 0) {
436
+ if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) {
437
+ headers["content-type"] = "application/json";
3931
438
  }
3932
- keys.push(role);
3933
- }
3934
- return uniqueNonEmptyStrings(keys);
3935
- }
3936
- function normalizeProfileArtifactRole(input) {
3937
- const normalized = input.trim().toLowerCase().replace(/[\s-]+/g, "_");
3938
- if (!normalized) return "";
3939
- if (normalized === "screenshots") return "screenshot";
3940
- if (normalized === "console" || normalized === "console_json" || normalized === "console.json") return "console.json";
3941
- if (normalized === "dom_summary" || normalized === "dom_summary_json" || normalized === "dom-summary.json") return "dom-summary.json";
3942
- if (normalized === "proof" || normalized === "proof_json" || normalized === "proof.json") return "proof.json";
3943
- return normalizeRiddleProfileArtifactName(input.trim()).toLowerCase();
3944
- }
3945
- function profileArtifactIsHostedLocalOnly(input) {
3946
- const raw = input.trim().toLowerCase();
3947
- const normalized = raw.replace(/[\s-]+/g, "_");
3948
- const role = normalizeProfileArtifactRole(input);
3949
- return [
3950
- raw,
3951
- normalized,
3952
- role
3953
- ].some((value) => value === "artifact_manifest" || value === "artifact_manifest.json" || value === "artifact-manifest" || value === "artifact-manifest.json");
3954
- }
3955
- function profileArtifactKeyPresent(key, artifacts) {
3956
- if (key.startsWith("screenshot:")) {
3957
- const label = key.slice("screenshot:".length);
3958
- return artifacts.some((artifact) => profileArtifactRefIsScreenshot(artifact) && profileArtifactRefText(artifact).includes(label.toLowerCase()));
3959
- }
3960
- if (key === "screenshot") {
3961
- return artifacts.some((artifact) => profileArtifactRefIsScreenshot(artifact));
3962
- }
3963
- return artifacts.some((artifact) => {
3964
- const name = normalizeRiddleProfileArtifactName(artifact.name || artifactNameFromPath(artifact.url || artifact.path) || "").toLowerCase();
3965
- return name === key || profileArtifactRefText(artifact).includes(key);
3966
- });
3967
- }
3968
- function profileArtifactRefIsScreenshot(artifact) {
3969
- const kind = (artifact.kind || "").toLowerCase();
3970
- const contentType = (artifact.content_type || "").toLowerCase();
3971
- const text = profileArtifactRefText(artifact);
3972
- return kind === "screenshot" || contentType.startsWith("image/") || /\.(png|jpe?g|webp)(?:$|[?#])/i.test(text) || /\.(png|jpe?g|webp)$/i.test(text);
3973
- }
3974
- function profileArtifactRefText(artifact) {
3975
- return [
3976
- artifact.name,
3977
- artifact.url,
3978
- artifact.path,
3979
- artifact.kind,
3980
- artifact.content_type
3981
- ].filter(Boolean).join(" ").toLowerCase();
3982
- }
3983
- function profileArtifactObservedLabel(artifact) {
3984
- return artifact.name || artifact.url || artifact.path || artifact.kind || "";
3985
- }
3986
- function assessRiddleProofProfileEvidence(profile, evidence, options = {}) {
3987
- const capturedAt = evidence?.captured_at || (/* @__PURE__ */ new Date()).toISOString();
3988
- const warnings = collectRiddleProofProfileWarnings(profile);
3989
- const checks = evidence ? [
3990
- assessNetworkMocksFromEvidence(profile, evidence),
3991
- assessSetupActionsFromEvidence(profile, evidence),
3992
- ...profile.checks.map((check) => assessCheckFromEvidence(check, evidence))
3993
- ].filter((check) => Boolean(check)) : [];
3994
- const status = profileStatusFromEvidence(profile, evidence, checks);
3995
- const firstViewport = evidence?.viewports?.[0];
3996
- const screenshots = profileScreenshotLabels(evidence?.viewports);
3997
- const canonicalScreenshots = profileFinalScreenshotLabels(evidence?.viewports);
3998
- const setupScreenshots = profileAllSetupScreenshotLabels(evidence?.viewports);
3999
- const result = {
4000
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
4001
- profile_name: profile.name,
4002
- runner: options.runner || "riddle",
4003
- status,
4004
- baseline_policy: profile.baseline_policy,
4005
- route: routeForViewport(firstViewport, evidence?.target_url),
4006
- artifacts: {
4007
- screenshots,
4008
- canonical_screenshots: canonicalScreenshots,
4009
- setup_screenshots: setupScreenshots,
4010
- console: "console.json",
4011
- proof_json: "proof.json",
4012
- dom_summary: "dom-summary.json",
4013
- riddle_artifacts: options.artifacts
4014
- },
4015
- checks,
4016
- summary: summarizeRiddleProofProfileResult({ profile_name: profile.name, status, checks, viewports: evidence?.viewports || [] }),
4017
- captured_at: capturedAt,
4018
- metadata: profile.metadata,
4019
- warnings: warnings.length ? warnings : void 0,
4020
- evidence,
4021
- riddle: options.riddle
4022
- };
4023
- return applyRiddleProofProfileArtifactCompleteness(profile, result, options.artifacts);
4024
- }
4025
- function summarizeRiddleProofProfileResult(input) {
4026
- const passedChecks = input.checks.filter((check) => check.status === "passed").length;
4027
- const failedChecks = input.checks.filter((check) => check.status === "failed").length;
4028
- const viewportNames = input.viewports.map((viewport) => viewport.name).join(", ");
4029
- if (input.status === "passed") {
4030
- return `${input.profile_name} passed ${passedChecks} check(s) across ${input.viewports.length} viewport(s)${viewportNames ? ` (${viewportNames})` : ""}.`;
4031
- }
4032
- if (input.status === "product_regression") {
4033
- return `${input.profile_name} failed ${failedChecks} product invariant(s) across ${input.viewports.length} viewport(s).`;
4034
- }
4035
- if (input.status === "environment_blocked") {
4036
- return `${input.profile_name} could not collect reliable evidence because navigation or the browser environment was blocked.`;
4037
- }
4038
- if (input.status === "proof_insufficient") {
4039
- return `${input.profile_name} did not produce enough evidence for a profile judgment.`;
4040
- }
4041
- if (input.status === "configuration_error") {
4042
- return `${input.profile_name} has a profile configuration error.`;
439
+ return { headers, body: JSON.stringify(check.body_json) };
4043
440
  }
4044
- return `${input.profile_name} collected artifacts but needs human review.`;
4045
- }
4046
- function profileStatusExitCode(profile, status) {
4047
- if (status === "passed") return 0;
4048
- return profile.failure_policy[status] === "neutral" ? 0 : 1;
4049
- }
4050
- function createRiddleProofProfileConfigurationError(profileOrName, error, runner = "riddle", options = {}) {
4051
- const profile = typeof profileOrName === "string" ? void 0 : profileOrName;
4052
- const name = profile ? profile.name : String(profileOrName);
4053
- const message = error instanceof Error ? error.message : String(error);
4054
- let requested = "";
4055
- if (profile) {
4056
- try {
4057
- requested = resolveRiddleProofProfileTargetUrl(profile);
4058
- } catch {
4059
- requested = "";
4060
- }
441
+ if (typeof check.body === "string") {
442
+ return { headers, body: check.body };
4061
443
  }
4062
- return {
4063
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
4064
- profile_name: name,
4065
- runner,
4066
- status: "configuration_error",
4067
- baseline_policy: profile?.baseline_policy || "invariant_only",
4068
- route: { requested, observed: "", matched: false, error: message },
4069
- artifacts: { screenshots: [], proof_json: "proof.json" },
4070
- checks: [],
4071
- summary: `${name} has a profile configuration error.`,
4072
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
4073
- metadata: profile?.metadata,
4074
- warnings: options.warnings?.length ? options.warnings : void 0,
4075
- configuration_blocker: options.configurationBlocker,
4076
- error: message
4077
- };
444
+ return { headers };
4078
445
  }
4079
- function createRiddleProofProfileEnvironmentBlockedResult(input) {
4080
- const message = input.error instanceof Error ? input.error.message : input.error ? String(input.error) : "Riddle runner did not complete successfully.";
4081
- const environmentBlocker = input.environmentBlocker || extractRiddleRunnerBlocker(message);
4082
- const warnings = collectRiddleProofProfileEnvironmentBlockedWarnings(input.profile, environmentBlocker);
4083
- return {
4084
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
4085
- profile_name: input.profile.name,
4086
- runner: input.runner || "riddle",
4087
- status: "environment_blocked",
4088
- baseline_policy: input.profile.baseline_policy,
4089
- route: { requested: resolveRiddleProofProfileTargetUrl(input.profile), observed: "", matched: false, error: message },
4090
- artifacts: { screenshots: [], proof_json: "proof.json", riddle_artifacts: input.artifacts },
4091
- checks: [],
4092
- summary: summarizeEnvironmentBlockedRunner(input.profile.name, environmentBlocker),
4093
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
4094
- metadata: input.profile.metadata,
4095
- warnings: warnings.length ? warnings : void 0,
4096
- riddle: input.riddle,
4097
- environment_blocker: environmentBlocker,
4098
- error: message
446
+ async function preflightHttpStatusCheck(check, index, targetUrl, fetchImpl) {
447
+ const url = httpStatusRequestUrl(check, targetUrl);
448
+ const method = httpStatusMethod(check);
449
+ const request = httpStatusRequestBody(check);
450
+ const init = {
451
+ method,
452
+ redirect: "follow",
453
+ cache: "no-store",
454
+ headers: request.headers
4099
455
  };
4100
- }
4101
- function extractRiddleRunnerBlocker(message) {
4102
- const apiError = message.match(/^Riddle API\s+(\S+)\s+failed HTTP\s+(\d+):\s+(\{[\s\S]*\})$/);
4103
- if (!apiError) return void 0;
4104
- const details = {
4105
- source: "riddle_api",
4106
- endpoint: apiError[1],
4107
- http_status: Number(apiError[2])
456
+ if (request.body !== void 0 && method !== "GET" && method !== "HEAD") {
457
+ init.body = request.body;
458
+ }
459
+ const result = {
460
+ status: null,
461
+ content_type: null,
462
+ content_length: null,
463
+ bytes: null
4108
464
  };
4109
- let payload;
465
+ let error = null;
466
+ let statusText = "";
4110
467
  try {
4111
- const parsed = JSON.parse(apiError[3]);
4112
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4113
- payload = parsed;
468
+ const response = await fetchImpl(url, init);
469
+ result.status = typeof response.status === "number" && Number.isFinite(response.status) ? response.status : null;
470
+ statusText = typeof response.statusText === "string" ? response.statusText : "";
471
+ result.content_type = responseHeader(response, "content-type");
472
+ result.content_length = responseContentLength(response);
473
+ const shouldReadBody = check.require_nonzero_bytes === true || typeof check.min_bytes === "number" || Boolean(check.body_contains?.length) || Boolean(check.body_not_contains?.length) || Boolean(check.body_not_patterns?.length) || Boolean(check.body_json_assertions?.length);
474
+ if (shouldReadBody && method !== "HEAD") {
475
+ const body = await responseBodyText(response);
476
+ result.bytes = body.bytes;
477
+ if (check.body_contains?.length) {
478
+ result.body_contains = Object.fromEntries(check.body_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
479
+ }
480
+ if (check.body_not_contains?.length) {
481
+ result.body_not_contains = Object.fromEntries(check.body_not_contains.filter(Boolean).map((snippet) => [snippet, body.text.includes(snippet)]));
482
+ }
483
+ if (check.body_not_patterns?.length) {
484
+ result.body_not_patterns = Object.fromEntries(check.body_not_patterns.filter(Boolean).map((pattern) => [pattern, new RegExp(pattern).test(body.text)]));
485
+ }
486
+ if (check.body_json_assertions?.length) {
487
+ result.body_json_assertions = evaluateHttpStatusBodyJsonAssertions(body.text, check.body_json_assertions);
488
+ }
4114
489
  }
4115
- } catch {
4116
- payload = void 0;
490
+ } catch (caught) {
491
+ error = String(caught instanceof Error ? caught.message : caught).slice(0, 500);
492
+ result.error = error;
4117
493
  }
4118
- const copyScalar = (key) => {
4119
- const value = payload?.[key];
4120
- if (typeof value === "string" || typeof value === "boolean") details[key] = value;
4121
- if (typeof value === "number" && Number.isFinite(value)) details[key] = value;
494
+ const bodyContainsMissing = httpStatusBodyContainsFailures(result, check);
495
+ const bodyNotContainsFound = httpStatusBodyNotContainsFailures(result, check);
496
+ const bodyNotPatternsFound = httpStatusBodyNotPatternFailures(result, check);
497
+ const bodyJsonAssertionsFailed = httpStatusBodyJsonAssertionFailures(result, check);
498
+ const ok = !error && linkStatusResultOk(result, check);
499
+ return {
500
+ index,
501
+ label: checkLabel(check) || `checks[${index}]`,
502
+ url,
503
+ method,
504
+ ok,
505
+ status: numberValue(result.status) ?? null,
506
+ status_text: statusText,
507
+ error,
508
+ content_type: stringValue(result.content_type) ?? null,
509
+ content_length: numberValue(result.content_length) ?? null,
510
+ bytes: numberValue(result.bytes) ?? null,
511
+ body_contains: isRecord(result.body_contains) ? Object.fromEntries(Object.entries(result.body_contains).map(([key, value]) => [key, value === true])) : null,
512
+ body_contains_missing: bodyContainsMissing,
513
+ body_not_contains: isRecord(result.body_not_contains) ? Object.fromEntries(Object.entries(result.body_not_contains).map(([key, value]) => [key, value === true])) : null,
514
+ body_not_contains_found: bodyNotContainsFound,
515
+ body_not_patterns: isRecord(result.body_not_patterns) ? Object.fromEntries(Object.entries(result.body_not_patterns).map(([key, value]) => [key, value === true])) : null,
516
+ body_not_patterns_found: bodyNotPatternsFound,
517
+ body_json_assertions: Array.isArray(result.body_json_assertions) ? result.body_json_assertions : null,
518
+ body_json_assertions_failed: bodyJsonAssertionsFailed
4122
519
  };
4123
- for (const key of ["error", "required_seconds", "available_seconds", "deficit_seconds", "minimum_purchase_dollars"]) {
4124
- copyScalar(key);
4125
- }
4126
- const warnings = payload?.warnings;
4127
- if (Array.isArray(warnings)) {
4128
- const warningStrings = warnings.filter((warning) => typeof warning === "string");
4129
- if (warningStrings.length) details.warnings = warningStrings;
4130
- }
4131
- const httpStatus = typeof details.http_status === "number" ? details.http_status : void 0;
4132
- const errorText = typeof details.error === "string" ? details.error.toLowerCase() : "";
4133
- if (httpStatus === 402 && errorText.includes("balance")) {
4134
- details.reason = "insufficient_balance";
4135
- }
4136
- return details;
4137
- }
4138
- function summarizeEnvironmentBlockedRunner(profileName, blocker) {
4139
- if (blocker?.reason === "insufficient_balance") {
4140
- const required = typeof blocker.required_seconds === "number" ? blocker.required_seconds : void 0;
4141
- const available = typeof blocker.available_seconds === "number" ? blocker.available_seconds : void 0;
4142
- const deficit = typeof blocker.deficit_seconds === "number" ? blocker.deficit_seconds : void 0;
4143
- const parts = [
4144
- required === void 0 ? "" : `required ${required}s`,
4145
- available === void 0 ? "" : `available ${available}s`,
4146
- deficit === void 0 ? "" : `deficit ${deficit}s`
4147
- ].filter(Boolean);
4148
- return `${profileName} could not start because Riddle balance was insufficient${parts.length ? ` (${parts.join(", ")})` : ""}.`;
4149
- }
4150
- if (blocker?.source === "riddle_api") {
4151
- const endpoint = typeof blocker.endpoint === "string" ? blocker.endpoint : "Riddle API";
4152
- const status = typeof blocker.http_status === "number" ? blocker.http_status : void 0;
4153
- return `${profileName} could not start because ${endpoint} returned${status === void 0 ? "" : ` HTTP ${status}`}.`;
4154
- }
4155
- return `${profileName} could not collect reliable evidence because the runner was blocked.`;
4156
- }
4157
- function createRiddleProofProfileInsufficientResult(input) {
4158
- const message = input.error instanceof Error ? input.error.message : input.error ? String(input.error) : "No proof.json profile result artifact was found.";
4159
- const warnings = collectRiddleProofProfileWarnings(input.profile);
520
+ }
521
+ async function preflightRiddleProofProfileHttpStatusChecks(profile, options = {}) {
522
+ const targetUrl = options.target_url || (0, import_profile.resolveRiddleProofProfileTargetUrl)(profile);
523
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
524
+ if (typeof fetchImpl !== "function") {
525
+ throw new Error("profile http_status preflight requires fetch support or options.fetchImpl.");
526
+ }
527
+ const httpStatusChecks = profile.checks.map((check, index) => ({ check, index })).filter((item) => item.check.type === "http_status");
528
+ const checks = await Promise.all(httpStatusChecks.map((item) => preflightHttpStatusCheck(item.check, item.index, targetUrl, fetchImpl)));
529
+ const failed = checks.filter((check) => !check.ok).length;
4160
530
  return {
4161
- version: RIDDLE_PROOF_PROFILE_RESULT_VERSION,
4162
- profile_name: input.profile.name,
4163
- runner: input.runner || "riddle",
4164
- status: "proof_insufficient",
4165
- baseline_policy: input.profile.baseline_policy,
4166
- route: { requested: resolveRiddleProofProfileTargetUrl(input.profile), observed: "", matched: false, error: message },
4167
- artifacts: { screenshots: [], proof_json: "proof.json", riddle_artifacts: input.artifacts },
4168
- checks: [],
4169
- summary: `${input.profile.name} did not produce enough evidence for a profile judgment.`,
4170
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
4171
- metadata: input.profile.metadata,
4172
- warnings: warnings.length ? warnings : void 0,
4173
- riddle: input.riddle,
4174
- error: message
531
+ version: "riddle-proof.profile-http-status-preflight.v1",
532
+ ok: failed === 0,
533
+ profile_name: profile.name,
534
+ target_url: targetUrl,
535
+ checked: checks.length,
536
+ failed,
537
+ checks,
538
+ summary: failed === 0 ? `${profile.name} http_status preflight passed ${checks.length} check(s).` : `${profile.name} http_status preflight failed ${failed} of ${checks.length} check(s).`
4175
539
  };
4176
540
  }
541
+ function previewMountPrefix(pathname) {
542
+ const value = pathname || "/";
543
+ const apiPreview = value.match(/^(\/s\/[^/]+)(?:\/|$)/);
544
+ if (apiPreview) return apiPreview[1];
545
+ const internalPreview = value.match(/^(\/preview\/[^/]+\/[^/]+)(?:\/|$)/);
546
+ return internalPreview ? internalPreview[1] : "";
547
+ }
548
+ function joinMountedRoutePath(mountPrefix, routePath) {
549
+ const route = routePath.startsWith("/") ? routePath : `/${routePath}`;
550
+ if (!mountPrefix) return route;
551
+ if (route === mountPrefix || route.startsWith(`${mountPrefix}/`)) return route;
552
+ return `${mountPrefix}${route}`;
553
+ }
4177
554
  function runtimeScriptAssessmentSource(includeOrderedTrace = false) {
4178
555
  const orderedTraceSource = includeOrderedTrace ? String.raw`
4179
- const assessRiddleProofOrderedTrace = ${assessRiddleProofOrderedTrace.toString()};
4180
- const assessRiddleProofOrderedTraceSetupResults = ${assessRiddleProofOrderedTraceSetupResults.toString()};` : "";
556
+ const assessRiddleProofOrderedTrace = ${import_profile.assessRiddleProofOrderedTrace.toString()};
557
+ const assessRiddleProofOrderedTraceSetupResults = ${import_profile.assessRiddleProofOrderedTraceSetupResults.toString()};` : "";
4181
558
  return String.raw`
4182
559
  ${orderedTraceSource}
4183
560
  function normalizeRoutePath(path) {
@@ -6273,9 +2650,9 @@ function assessProfile(profile, evidence) {
6273
2650
  `;
6274
2651
  }
6275
2652
  function buildRiddleProofProfileScript(profile) {
6276
- const targetUrl = resolveRiddleProofProfileTargetUrl(profile);
6277
- const slug = slugifyRiddleProofProfileName(profile.name);
6278
- const profileWarnings = collectRiddleProofProfileWarnings(profile);
2653
+ const targetUrl = (0, import_profile.resolveRiddleProofProfileTargetUrl)(profile);
2654
+ const slug = (0, import_profile.slugifyRiddleProofProfileName)(profile.name);
2655
+ const profileWarnings = (0, import_profile.collectRiddleProofProfileWarnings)(profile);
6279
2656
  const serializableProfile = JSON.stringify(profile);
6280
2657
  const serializableProfileWarnings = JSON.stringify(profileWarnings);
6281
2658
  const serializableTargetUrl = JSON.stringify(targetUrl);
@@ -9927,97 +6304,6 @@ for (const viewport of profile.target.viewports || []) {
9927
6304
  return result;
9928
6305
  `.trim();
9929
6306
  }
9930
- function collectRiddleProfileArtifactRefs(input) {
9931
- const refs = [];
9932
- const indexes = /* @__PURE__ */ new Map();
9933
- const priorities = /* @__PURE__ */ new Map();
9934
- function add(item, source) {
9935
- if (!isRecord(item)) return;
9936
- const url = stringValue(item.url);
9937
- const path = stringValue(item.path);
9938
- const rawName = stringValue(item.name) || stringValue(item.filename) || artifactNameFromPath(url || path) || "";
9939
- const name = normalizeRiddleProfileArtifactName(rawName);
9940
- if (!name && !url && !path) return;
9941
- const key = profileArtifactDedupeKey(name, url || path || "");
9942
- const priority = profileArtifactPriority(rawName, name);
9943
- const ref = {
9944
- name,
9945
- url,
9946
- path,
9947
- kind: stringValue(item.kind) || stringValue(item.type),
9948
- content_type: stringValue(item.content_type) || stringValue(item.contentType),
9949
- source
9950
- };
9951
- const existingIndex = indexes.get(key);
9952
- if (existingIndex !== void 0) {
9953
- if (priority > (priorities.get(key) || 0)) {
9954
- refs[existingIndex] = ref;
9955
- priorities.set(key, priority);
9956
- }
9957
- return;
9958
- }
9959
- indexes.set(key, refs.length);
9960
- priorities.set(key, priority);
9961
- refs.push(ref);
9962
- }
9963
- function visit(value, source) {
9964
- if (Array.isArray(value)) {
9965
- for (const item of value) add(item, source);
9966
- return;
9967
- }
9968
- if (!isRecord(value)) return;
9969
- for (const key of ["artifacts", "outputs", "screenshots", "files"]) {
9970
- if (Array.isArray(value[key])) visit(value[key], key);
9971
- }
9972
- }
9973
- visit(input, "artifacts");
9974
- return refs;
9975
- }
9976
- function normalizeRiddleProfileArtifactName(name) {
9977
- return name.replace(/\.json\.json$/i, ".json");
9978
- }
9979
- function profileArtifactDedupeKey(name, location) {
9980
- if (PROFILE_SINGLETON_ARTIFACT_NAMES.has(name.toLowerCase())) return name.toLowerCase();
9981
- return `${name}:${location}`;
9982
- }
9983
- function profileArtifactPriority(rawName, normalizedName) {
9984
- const lower = normalizedName.toLowerCase();
9985
- if (!PROFILE_SINGLETON_ARTIFACT_NAMES.has(lower)) return 1;
9986
- return /\.json\.json$/i.test(rawName) ? 2 : 1;
9987
- }
9988
- function artifactNameFromPath(value) {
9989
- if (!value) return "";
9990
- try {
9991
- return new URL(value).pathname.split("/").filter(Boolean).pop() || "";
9992
- } catch {
9993
- return value.split(/[\\/]/).filter(Boolean).pop() || "";
9994
- }
9995
- }
9996
- var PROFILE_SINGLETON_ARTIFACT_NAMES = /* @__PURE__ */ new Set([
9997
- "proof.json",
9998
- "console.json",
9999
- "dom-summary.json"
10000
- ]);
10001
- function extractRiddleProofProfileResult(input) {
10002
- if (!isRecord(input)) return void 0;
10003
- if (input.version === RIDDLE_PROOF_PROFILE_RESULT_VERSION) return input;
10004
- const candidates = [
10005
- input.result,
10006
- input.return_value,
10007
- input.value,
10008
- input.profile_result,
10009
- isRecord(input["proof.json"]) ? input["proof.json"] : void 0,
10010
- isRecord(input._proof_json) ? input._proof_json : void 0
10011
- ];
10012
- for (const candidate of candidates) {
10013
- const result = extractRiddleProofProfileResult(candidate);
10014
- if (result) return result;
10015
- }
10016
- if (isRecord(input._artifact_json)) {
10017
- return extractRiddleProofProfileResult(input._artifact_json["proof.json"]);
10018
- }
10019
- return void 0;
10020
- }
10021
6307
  // Annotate the CommonJS export names for ESM import in node:
10022
6308
  0 && (module.exports = {
10023
6309
  RIDDLE_PROOF_HOSTED_PROFILE_ARTIFACTS,