@tangle-network/agent-app 0.45.22 → 0.45.23

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.
@@ -0,0 +1,1478 @@
1
+ // src/legibility/source.ts
2
+ var IDENT_START = /[A-Za-z_$]/;
3
+ var IDENT_PART = /[A-Za-z0-9_$.:-]/;
4
+ var JSX_PRECEDERS = /* @__PURE__ */ new Set(["(", "{", "}", "=", ",", ";", ":", "?", "&", "|", "!", "+", ">", "[", "\n"]);
5
+ var JSX_PRECEDING_WORDS = /* @__PURE__ */ new Set(["return", "yield", "case", "default", "in", "of", "typeof", "await"]);
6
+ function scanSource(text) {
7
+ const segments = [];
8
+ const elements = [];
9
+ const mask = new Array(text.length);
10
+ for (let i2 = 0; i2 < text.length; i2++) mask[i2] = text[i2];
11
+ const blank = (from, to) => {
12
+ for (let i2 = from; i2 < to && i2 < text.length; i2++) mask[i2] = text[i2] === "\n" ? "\n" : " ";
13
+ };
14
+ const stack = [{ kind: "code", depth: 0, element: null, containerStart: null }];
15
+ const top = () => stack[stack.length - 1];
16
+ const openElement = () => {
17
+ for (let i2 = stack.length - 1; i2 >= 0; i2--) {
18
+ const frame = stack[i2];
19
+ if (frame.kind === "jsx-children" || frame.kind === "jsx-tag") return frame.element;
20
+ }
21
+ return null;
22
+ };
23
+ const containerOf = () => {
24
+ for (let i2 = stack.length - 1; i2 >= 0; i2--) {
25
+ const frame = stack[i2];
26
+ if (frame.kind === "code") return frame.containerStart;
27
+ if (frame.kind === "jsx-children" || frame.kind === "jsx-tag") return frame.element?.containerStart ?? null;
28
+ }
29
+ return null;
30
+ };
31
+ let i = 0;
32
+ while (i < text.length) {
33
+ const frame = top();
34
+ if (frame.kind === "jsx-children") {
35
+ i = readJsxChildren(i, frame);
36
+ continue;
37
+ }
38
+ if (frame.kind === "jsx-tag") {
39
+ i = readJsxTag(i, frame);
40
+ continue;
41
+ }
42
+ if (frame.kind === "template") {
43
+ i = readTemplateChunk(i);
44
+ continue;
45
+ }
46
+ i = readCode(i, frame);
47
+ }
48
+ return { text, segments, elements, masked: mask.join("") };
49
+ function readCode(at, frame) {
50
+ const ch = text[at];
51
+ if (ch === "/" && text[at + 1] === "/") {
52
+ const end = indexOrEnd(text, "\n", at);
53
+ segments.push({ kind: "comment", start: at + 2, end, value: text.slice(at + 2, end) });
54
+ blank(at, end);
55
+ return end;
56
+ }
57
+ if (ch === "/" && text[at + 1] === "*") {
58
+ const close = text.indexOf("*/", at + 2);
59
+ const end = close === -1 ? text.length : close + 2;
60
+ segments.push({ kind: "comment", start: at + 2, end: end - 2, value: text.slice(at + 2, end - 2) });
61
+ blank(at, end);
62
+ return end;
63
+ }
64
+ if (ch === '"' || ch === "'") {
65
+ const end = readQuoted(text, at, ch);
66
+ segments.push({ kind: "string", start: at + 1, end: end - 1, value: text.slice(at + 1, end - 1) });
67
+ blank(at + 1, end - 1);
68
+ return end;
69
+ }
70
+ if (ch === "`") {
71
+ stack.push({
72
+ kind: "template",
73
+ depth: 0,
74
+ element: null,
75
+ containerStart: containerOf(),
76
+ templateAttribute: attributeOfTemplate(at + 1)
77
+ });
78
+ return at + 1;
79
+ }
80
+ if (ch === "/" && isRegexStart(text, at)) {
81
+ return skipRegex(text, at);
82
+ }
83
+ if (ch === "{") {
84
+ frame.depth++;
85
+ return at + 1;
86
+ }
87
+ if (ch === "}") {
88
+ if (frame.depth === 0 && stack.length > 1) {
89
+ stack.pop();
90
+ return at + 1;
91
+ }
92
+ frame.depth--;
93
+ return at + 1;
94
+ }
95
+ if (ch === "<" && startsJsx(text, at)) {
96
+ return openTag(at);
97
+ }
98
+ return at + 1;
99
+ }
100
+ function readTemplateChunk(at) {
101
+ let cursor = at;
102
+ while (cursor < text.length) {
103
+ const ch = text[cursor];
104
+ if (ch === "\\") {
105
+ cursor += 2;
106
+ continue;
107
+ }
108
+ if (ch === "`") {
109
+ pushTemplate(at, cursor);
110
+ stack.pop();
111
+ return cursor + 1;
112
+ }
113
+ if (ch === "$" && text[cursor + 1] === "{") {
114
+ pushTemplate(at, cursor);
115
+ stack.push({ kind: "code", depth: 0, element: null, containerStart: containerOf() });
116
+ return cursor + 2;
117
+ }
118
+ cursor++;
119
+ }
120
+ pushTemplate(at, cursor);
121
+ stack.pop();
122
+ return cursor;
123
+ }
124
+ function pushTemplate(from, to) {
125
+ if (to <= from) return;
126
+ const owner = openElement();
127
+ let attribute = null;
128
+ for (let i2 = stack.length - 1; i2 >= 0; i2--) {
129
+ const entry = stack[i2];
130
+ if (entry.kind === "template") {
131
+ attribute = entry.templateAttribute ?? null;
132
+ break;
133
+ }
134
+ }
135
+ segments.push({
136
+ kind: "template",
137
+ start: from,
138
+ end: to,
139
+ value: text.slice(from, to),
140
+ ...attribute === null ? {} : { attribute },
141
+ ...owner === null ? {} : { tag: owner.tag }
142
+ });
143
+ blank(from, to);
144
+ }
145
+ function attributeOfTemplate(from) {
146
+ let cursor = from - 1;
147
+ if (text[cursor] === "`") cursor--;
148
+ while (cursor >= 0 && /\s/.test(text[cursor])) cursor--;
149
+ if (text[cursor] === "{") cursor--;
150
+ while (cursor >= 0 && /\s/.test(text[cursor])) cursor--;
151
+ if (text[cursor] !== "=") return null;
152
+ cursor--;
153
+ const nameEnd = cursor + 1;
154
+ while (cursor >= 0 && IDENT_PART.test(text[cursor])) cursor--;
155
+ const name = text.slice(cursor + 1, nameEnd);
156
+ return name.length > 0 && IDENT_START.test(name[0]) ? name : null;
157
+ }
158
+ function openTag(at) {
159
+ let cursor = at + 1;
160
+ let tag = "";
161
+ if (text[cursor] === ">") {
162
+ const element2 = makeElement("", at);
163
+ stack.push({ kind: "jsx-children", depth: 0, element: element2, containerStart: null });
164
+ element2.openEnd = cursor + 1;
165
+ return cursor + 1;
166
+ }
167
+ while (cursor < text.length && IDENT_PART.test(text[cursor])) {
168
+ tag += text[cursor];
169
+ cursor++;
170
+ }
171
+ const element = makeElement(tag, at);
172
+ stack.push({ kind: "jsx-tag", depth: 0, element, containerStart: null });
173
+ return cursor;
174
+ }
175
+ function makeElement(tag, at) {
176
+ const parent = openElement();
177
+ const element = {
178
+ tag,
179
+ attributes: [],
180
+ children: [],
181
+ parent,
182
+ start: at,
183
+ openEnd: at,
184
+ end: at,
185
+ containerStart: containerOf()
186
+ };
187
+ if (parent) parent.children.push(element);
188
+ elements.push(element);
189
+ return element;
190
+ }
191
+ function readJsxTag(at, frame) {
192
+ const ch = text[at];
193
+ if (/\s/.test(ch)) return at + 1;
194
+ const element = frame.element;
195
+ if (element === null) {
196
+ stack.pop();
197
+ return at + 1;
198
+ }
199
+ if (ch === "/" && text[at + 1] === ">") {
200
+ element.openEnd = at + 2;
201
+ element.end = at + 2;
202
+ stack.pop();
203
+ return at + 2;
204
+ }
205
+ if (ch === ">") {
206
+ element.openEnd = at + 1;
207
+ stack.pop();
208
+ stack.push({ kind: "jsx-children", depth: 0, element, containerStart: null });
209
+ return at + 1;
210
+ }
211
+ if (ch === "{") {
212
+ stack.push({ kind: "code", depth: 0, element, containerStart: at });
213
+ return at + 1;
214
+ }
215
+ if (!IDENT_START.test(ch)) return at + 1;
216
+ let cursor = at;
217
+ let name = "";
218
+ while (cursor < text.length && IDENT_PART.test(text[cursor])) {
219
+ name += text[cursor];
220
+ cursor++;
221
+ }
222
+ let probe = cursor;
223
+ while (probe < text.length && /\s/.test(text[probe])) probe++;
224
+ if (text[probe] !== "=") {
225
+ element.attributes.push({ name, start: at, value: null, expression: false });
226
+ return cursor;
227
+ }
228
+ probe++;
229
+ while (probe < text.length && /\s/.test(text[probe])) probe++;
230
+ const valueChar = text[probe];
231
+ if (valueChar === '"' || valueChar === "'") {
232
+ const end = readQuoted(text, probe, valueChar);
233
+ const value = text.slice(probe + 1, end - 1);
234
+ element.attributes.push({ name, start: at, value, expression: false });
235
+ segments.push({
236
+ kind: "jsx-attribute",
237
+ start: probe + 1,
238
+ end: end - 1,
239
+ value,
240
+ attribute: name,
241
+ tag: element.tag
242
+ });
243
+ blank(probe + 1, end - 1);
244
+ return end;
245
+ }
246
+ element.attributes.push({ name, start: at, value: null, expression: true });
247
+ return probe;
248
+ }
249
+ function readJsxChildren(at, frame) {
250
+ let cursor = at;
251
+ while (cursor < text.length) {
252
+ const ch = text[cursor];
253
+ if (ch === "{") {
254
+ pushJsxText(at, cursor, frame.element);
255
+ stack.push({ kind: "code", depth: 0, element: frame.element, containerStart: cursor });
256
+ return cursor + 1;
257
+ }
258
+ if (ch === "<") {
259
+ pushJsxText(at, cursor, frame.element);
260
+ if (text[cursor + 1] === "/") {
261
+ const close = indexOrEnd(text, ">", cursor);
262
+ const element = frame.element;
263
+ if (element) element.end = Math.min(close + 1, text.length);
264
+ stack.pop();
265
+ return Math.min(close + 1, text.length);
266
+ }
267
+ return openTag(cursor);
268
+ }
269
+ cursor++;
270
+ }
271
+ pushJsxText(at, cursor, frame.element);
272
+ stack.pop();
273
+ return cursor;
274
+ }
275
+ function pushJsxText(from, to, owner) {
276
+ if (to <= from) return;
277
+ const value = text.slice(from, to);
278
+ if (value.trim().length === 0) return;
279
+ segments.push({
280
+ kind: "jsx-text",
281
+ start: from,
282
+ end: to,
283
+ value,
284
+ ...owner === null ? {} : { tag: owner.tag }
285
+ });
286
+ blank(from, to);
287
+ }
288
+ }
289
+ function readQuoted(text, at, quote) {
290
+ let cursor = at + 1;
291
+ while (cursor < text.length) {
292
+ const ch = text[cursor];
293
+ if (ch === "\\") {
294
+ cursor += 2;
295
+ continue;
296
+ }
297
+ if (ch === quote || ch === "\n") return cursor + 1;
298
+ cursor++;
299
+ }
300
+ return text.length;
301
+ }
302
+ function indexOrEnd(text, needle, from) {
303
+ const idx = text.indexOf(needle, from);
304
+ return idx === -1 ? text.length : idx;
305
+ }
306
+ function startsJsx(text, at) {
307
+ const next = text[at + 1];
308
+ if (next === void 0) return false;
309
+ if (next !== ">" && !IDENT_START.test(next)) return false;
310
+ let cursor = at - 1;
311
+ while (cursor >= 0 && /\s/.test(text[cursor])) cursor--;
312
+ if (cursor < 0) return true;
313
+ const prev = text[cursor];
314
+ if (JSX_PRECEDERS.has(prev)) return true;
315
+ if (!IDENT_PART.test(prev)) return false;
316
+ let wordEnd = cursor + 1;
317
+ while (cursor >= 0 && IDENT_PART.test(text[cursor])) cursor--;
318
+ return JSX_PRECEDING_WORDS.has(text.slice(cursor + 1, wordEnd));
319
+ }
320
+ function isRegexStart(text, at) {
321
+ let cursor = at - 1;
322
+ while (cursor >= 0 && /\s/.test(text[cursor])) cursor--;
323
+ if (cursor < 0) return true;
324
+ const prev = text[cursor];
325
+ return "([{=,;:?&|!+*%<>~^".includes(prev);
326
+ }
327
+ function skipRegex(text, at) {
328
+ let cursor = at + 1;
329
+ let inClass = false;
330
+ while (cursor < text.length) {
331
+ const ch = text[cursor];
332
+ if (ch === "\\") {
333
+ cursor += 2;
334
+ continue;
335
+ }
336
+ if (ch === "[") inClass = true;
337
+ else if (ch === "]") inClass = false;
338
+ else if (ch === "/" && !inClass) {
339
+ cursor++;
340
+ while (cursor < text.length && /[a-z]/.test(text[cursor])) cursor++;
341
+ return cursor;
342
+ } else if (ch === "\n") return cursor;
343
+ cursor++;
344
+ }
345
+ return cursor;
346
+ }
347
+ function lineIndex(text) {
348
+ const starts = [0];
349
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
350
+ return starts;
351
+ }
352
+ function positionAt(starts, offset) {
353
+ let lo = 0;
354
+ let hi = starts.length - 1;
355
+ while (lo < hi) {
356
+ const mid = lo + hi + 1 >> 1;
357
+ if (starts[mid] <= offset) lo = mid;
358
+ else hi = mid - 1;
359
+ }
360
+ return { line: lo + 1, column: offset - starts[lo] + 1 };
361
+ }
362
+ function elementAt(elements, offset) {
363
+ let best = null;
364
+ for (const element of elements) {
365
+ if (element.start > offset) break;
366
+ const end = element.end > element.start ? element.end : element.openEnd;
367
+ if (offset < end && (best === null || element.start >= best.start)) best = element;
368
+ }
369
+ return best;
370
+ }
371
+ function enclosingFunctionBlock(masked, offset) {
372
+ let block = enclosingBlock(masked, offset);
373
+ while (block !== null) {
374
+ const head = masked.slice(Math.max(0, block.start - 60), block.start);
375
+ if (/(=>|\)|\bfunction\b|\bdo\b)\s*$/.test(head) && !/\b(if|for|while|switch|catch|try|else)\s*\)?\s*$/.test(head)) {
376
+ return block;
377
+ }
378
+ const outer = enclosingBlock(masked, block.start);
379
+ if (outer === null || outer.start === block.start) return block;
380
+ block = outer;
381
+ }
382
+ return null;
383
+ }
384
+ function enclosingBlock(masked, offset) {
385
+ let depth = 0;
386
+ let start = -1;
387
+ for (let i = offset - 1; i >= 0; i--) {
388
+ const ch = masked[i];
389
+ if (ch === "}") depth++;
390
+ else if (ch === "{") {
391
+ if (depth === 0) {
392
+ start = i;
393
+ break;
394
+ }
395
+ depth--;
396
+ }
397
+ }
398
+ if (start === -1) return null;
399
+ depth = 0;
400
+ for (let i = start; i < masked.length; i++) {
401
+ const ch = masked[i];
402
+ if (ch === "{") depth++;
403
+ else if (ch === "}") {
404
+ depth--;
405
+ if (depth === 0) return { start, end: i + 1 };
406
+ }
407
+ }
408
+ return { start, end: masked.length };
409
+ }
410
+
411
+ // src/legibility/checks/empty-state.ts
412
+ var EMPTY_PATTERNS = [
413
+ /^no\b/i,
414
+ /^none\b/i,
415
+ /^nothing\b/i,
416
+ /^0\s+\w+\s+(found|yet)/i,
417
+ /\bnothing (here|yet|to show|to do|to review)\b/i,
418
+ /\bnot(hing)? found\b/i,
419
+ /\bis empty\b/i,
420
+ /\bno (results|items|data|matches|records|files|entries)\b/i,
421
+ /\byou (have|haven't|don't have) (no|any)\b/i
422
+ ];
423
+ var ACTION_TAGS = /* @__PURE__ */ new Set(["button", "a", "input", "select", "textarea", "form", "link", "navlink"]);
424
+ var ACTION_PROPS = /* @__PURE__ */ new Set([
425
+ "onclick",
426
+ "onsubmit",
427
+ "onchange",
428
+ "onselect",
429
+ "onpress",
430
+ "ontoggle",
431
+ "href",
432
+ "to",
433
+ "action",
434
+ "onaction",
435
+ "oncta",
436
+ "emptyaction",
437
+ "emptycta",
438
+ "onemptyaction",
439
+ "primaryaction"
440
+ ]);
441
+ var ACTION_PROP_SUFFIX = /(href|action|cta|click|submit|press|link)$/i;
442
+ var EMPTY_COPY_PROPS = /^empty[A-Z]/;
443
+ var HEADING_TAG = /^h[1-6]$/i;
444
+ var HEADING_SUFFIX = /(heading|title)$/i;
445
+ function checkEmptyStates(file, options = {}) {
446
+ const actionTags = /* @__PURE__ */ new Set([...ACTION_TAGS, ...(options.extraActionTags ?? []).map((tag) => tag.toLowerCase())]);
447
+ const actionProps = /* @__PURE__ */ new Set([...ACTION_PROPS, ...(options.extraActionProps ?? []).map((prop) => prop.toLowerCase())]);
448
+ const patterns = [...EMPTY_PATTERNS, ...(options.extraEmptyPatterns ?? []).map((source) => new RegExp(source, "i"))];
449
+ const findings = [];
450
+ const reported = /* @__PURE__ */ new Set();
451
+ const iterations = options.reportSectionZeroStates === true ? [] : listIterations(file.scan.masked);
452
+ const report = (root, offset, copy, viaProp) => {
453
+ if (reported.has(root.start)) return;
454
+ reported.add(root.start);
455
+ if (hasAction(file, root, actionTags, actionProps)) return;
456
+ if (options.reportSectionZeroStates !== true && labelsATitledSection(file, root)) return;
457
+ if (iterations.some((span) => root.start > span.start && root.start < span.end)) return;
458
+ findings.push({
459
+ check: "dead-end-empty-state",
460
+ offset,
461
+ message: `Empty state "${clip(copy)}" offers no next action${viaProp === null ? "" : ` (${viaProp})`}.`,
462
+ remedy: "Put the one thing the reader should do next inside this branch \u2014 a button, a link, or the control that creates the first item. If nothing can be done here, say why in the copy.",
463
+ evidence: clip(copy)
464
+ });
465
+ };
466
+ for (const segment of file.scan.segments) {
467
+ if (segment.kind !== "jsx-text") continue;
468
+ const text = segment.value.trim();
469
+ if (!patterns.some((pattern) => pattern.test(text))) continue;
470
+ const element = elementAt(file.scan.elements, segment.start);
471
+ if (element === null) continue;
472
+ report(branchRoot(element), segment.start, text, null);
473
+ }
474
+ for (const element of file.scan.elements) {
475
+ const copyProp = element.attributes.find(
476
+ (attribute) => EMPTY_COPY_PROPS.test(attribute.name) && attribute.value !== null
477
+ );
478
+ if (!copyProp?.value) continue;
479
+ report(element, copyProp.start, copyProp.value, `via ${copyProp.name}`);
480
+ }
481
+ return findings.sort((left, right) => left.offset - right.offset);
482
+ }
483
+ function branchRoot(element) {
484
+ let root = element;
485
+ while (root.parent !== null && root.parent.containerStart === element.containerStart) root = root.parent;
486
+ return root;
487
+ }
488
+ function listIterations(masked) {
489
+ const spans = [];
490
+ for (const match of masked.matchAll(/\.\s*map\s*\(/g)) {
491
+ const open = (match.index ?? 0) + (match[0]?.length ?? 1) - 1;
492
+ const end = matchingParen(masked, open);
493
+ if (end !== -1) spans.push({ start: open, end });
494
+ }
495
+ return spans;
496
+ }
497
+ function matchingParen(masked, open) {
498
+ let depth = 0;
499
+ for (let i = open; i < masked.length; i++) {
500
+ const ch = masked[i];
501
+ if (ch === "(") depth++;
502
+ else if (ch === ")") {
503
+ depth--;
504
+ if (depth === 0) return i + 1;
505
+ }
506
+ }
507
+ return -1;
508
+ }
509
+ function labelsATitledSection(file, root) {
510
+ let previous = null;
511
+ for (const element of file.scan.elements) {
512
+ if (element.start >= root.start) break;
513
+ if (element.parent !== root.parent) continue;
514
+ previous = element;
515
+ }
516
+ if (previous === null) return false;
517
+ const tag = previous.tag.split(".").pop() ?? previous.tag;
518
+ return HEADING_TAG.test(tag) || HEADING_SUFFIX.test(tag);
519
+ }
520
+ function hasAction(file, root, actionTags, actionProps) {
521
+ const end = root.end > root.start ? root.end : root.openEnd;
522
+ for (const element of file.scan.elements) {
523
+ if (element.start < root.start) continue;
524
+ if (element.start >= end) break;
525
+ if (isActionTag(element.tag, actionTags)) return true;
526
+ if (element.attributes.some(
527
+ (attribute) => actionProps.has(attribute.name.toLowerCase()) || ACTION_PROP_SUFFIX.test(attribute.name)
528
+ )) {
529
+ return true;
530
+ }
531
+ }
532
+ return false;
533
+ }
534
+ function isActionTag(tag, actionTags) {
535
+ const base = (tag.split(".").pop() ?? tag).toLowerCase();
536
+ if (actionTags.has(base)) return true;
537
+ return /(button|link|cta|anchor|action)$/.test(base);
538
+ }
539
+ function clip(value, max = 72) {
540
+ const flat = value.replace(/\s+/g, " ").trim();
541
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
542
+ }
543
+
544
+ // src/legibility/scan.ts
545
+ import { readFileSync, readdirSync } from "fs";
546
+ import { join, relative } from "path";
547
+ var SOURCE_RE = /\.(tsx?|jsx?|mjs|cjs)$/;
548
+ var SKIP_DIRS = /* @__PURE__ */ new Set([
549
+ "node_modules",
550
+ ".git",
551
+ "dist",
552
+ "build",
553
+ ".next",
554
+ ".react-router",
555
+ "coverage",
556
+ ".wrangler",
557
+ ".turbo"
558
+ ]);
559
+ var DEFAULT_IGNORE = [
560
+ ".test.",
561
+ ".spec.",
562
+ "__tests__",
563
+ "__fixtures__",
564
+ "/fixtures/",
565
+ "/tests/",
566
+ "/test/",
567
+ ".d.ts",
568
+ ".stories.",
569
+ "/+types/"
570
+ ];
571
+ function walkSources(dir, ignore = []) {
572
+ let entries;
573
+ try {
574
+ entries = readdirSync(dir, { withFileTypes: true });
575
+ } catch {
576
+ return [];
577
+ }
578
+ const skip = [...DEFAULT_IGNORE, ...ignore];
579
+ return entries.flatMap((entry) => {
580
+ const full = join(dir, entry.name);
581
+ if (entry.isDirectory()) return SKIP_DIRS.has(entry.name) ? [] : walkSources(full, ignore);
582
+ return SOURCE_RE.test(entry.name) ? [full] : [];
583
+ }).filter((file) => !skip.some((needle) => file.includes(needle)));
584
+ }
585
+ function scanFile(path) {
586
+ let text;
587
+ try {
588
+ text = readFileSync(path, "utf8");
589
+ } catch {
590
+ return null;
591
+ }
592
+ return buildScannedFile(path, text);
593
+ }
594
+ function buildScannedFile(path, text) {
595
+ const scan = scanSource(text);
596
+ const lineStarts = lineIndex(text);
597
+ return {
598
+ path,
599
+ display: displayPath(path),
600
+ text,
601
+ scan,
602
+ lineStarts,
603
+ positionAt: (offset) => positionAt(lineStarts, offset)
604
+ };
605
+ }
606
+ function scanSources(srcDirs, ignore = []) {
607
+ const files = srcDirs.flatMap((dir) => walkSources(dir, ignore));
608
+ const unique = [...new Set(files)].sort();
609
+ return unique.flatMap((path) => {
610
+ const scanned = scanFile(path);
611
+ return scanned ? [scanned] : [];
612
+ });
613
+ }
614
+ function displayPath(file) {
615
+ const rel = relative(process.cwd(), file);
616
+ return rel && !rel.startsWith("..") ? rel : file;
617
+ }
618
+ function evidenceOf(text, start, end, max = 100) {
619
+ const raw = text.slice(start, Math.min(end, start + max * 3)).replace(/\s+/g, " ").trim();
620
+ return raw.length > max ? `${raw.slice(0, max - 1)}\u2026` : raw;
621
+ }
622
+
623
+ // src/legibility/checks/reachability.ts
624
+ import { readFileSync as readFileSync2 } from "fs";
625
+ var ROUTE_CALL_RE = /(?<![\w$.])(route|index|layout|prefix)\s*\(/g;
626
+ var MODULE_LITERAL = /\.(tsx?|jsx?)$/;
627
+ var LINK_ATTRIBUTES = /* @__PURE__ */ new Set(["to", "href", "action", "redirect"]);
628
+ var LINK_ATTRIBUTE_SUFFIX = /(href|url|link|route|path)$/i;
629
+ var LINK_CALLS = /* @__PURE__ */ new Set(["navigate", "redirect", "redirectdocument"]);
630
+ var LINK_CALL_TAIL = /* @__PURE__ */ new Set(["push", "replace", "assign", "navigate", "redirect"]);
631
+ var LOCATION_ASSIGN_RE = /\blocation\s*\.\s*href\s*=\s*/g;
632
+ function parseRouteConfig(file) {
633
+ const masked = file.scan.masked;
634
+ const calls = [];
635
+ ROUTE_CALL_RE.lastIndex = 0;
636
+ for (const match of masked.matchAll(ROUTE_CALL_RE)) {
637
+ const parenStart = (match.index ?? 0) + (match[0]?.length ?? 1) - 1;
638
+ const end = matchingParen2(masked, parenStart);
639
+ if (end === -1) continue;
640
+ const args = file.scan.segments.filter((segment) => segment.kind === "string" && segment.start > parenStart && segment.end < end).filter((segment) => topLevelArgument(masked, parenStart, segment.start)).map((segment) => ({ value: segment.value, start: segment.start }));
641
+ calls.push({ kind: match[1] ?? "", start: match.index ?? 0, end, args });
642
+ }
643
+ const ancestorsOf = (call) => calls.filter((other) => other !== call && other.start < call.start && other.end > call.end);
644
+ const entries = [];
645
+ for (const call of calls) {
646
+ if (call.kind !== "route" && call.kind !== "prefix") continue;
647
+ const own = call.args[0];
648
+ if (own === void 0) continue;
649
+ if (MODULE_LITERAL.test(own.value)) continue;
650
+ const prefixParts = ancestorsOf(call).filter((ancestor) => ancestor.kind === "route" || ancestor.kind === "prefix").sort((left, right) => left.start - right.start).map((ancestor) => ancestor.args[0]?.value ?? "");
651
+ if (call.kind === "prefix") continue;
652
+ entries.push({
653
+ path: joinPath([...prefixParts, own.value]),
654
+ module: call.args[1]?.value ?? null,
655
+ offset: own.start,
656
+ isLayout: calls.some((other) => other !== call && other.start > call.start && other.end < call.end)
657
+ });
658
+ }
659
+ return entries;
660
+ }
661
+ function topLevelArgument(masked, parenStart, at) {
662
+ let depth = 0;
663
+ for (let i = parenStart; i < at; i++) {
664
+ const ch = masked[i];
665
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
666
+ else if (ch === ")" || ch === "]" || ch === "}") depth--;
667
+ }
668
+ return depth === 1;
669
+ }
670
+ function endOfStatement(masked, from) {
671
+ for (let i = from; i < masked.length; i++) {
672
+ const ch = masked[i];
673
+ if (ch === ";" || ch === "\n") return i;
674
+ }
675
+ return masked.length;
676
+ }
677
+ function matchingParen2(masked, open) {
678
+ let depth = 0;
679
+ for (let i = open; i < masked.length; i++) {
680
+ const ch = masked[i];
681
+ if (ch === "(") depth++;
682
+ else if (ch === ")") {
683
+ depth--;
684
+ if (depth === 0) return i + 1;
685
+ }
686
+ }
687
+ return -1;
688
+ }
689
+ function joinPath(parts) {
690
+ return parts.flatMap((part) => part.split("/")).map((part) => part.trim()).filter((part) => part.length > 0).join("/");
691
+ }
692
+ function staticSegments(path) {
693
+ return path.replace(/\$\{[^}]*\}/g, "/*/").split(/[/?#]/).map((segment) => segment.trim()).filter((segment) => segment.length > 0 && !segment.startsWith(":") && segment !== "*" && !segment.startsWith("$"));
694
+ }
695
+ function pathLike(value) {
696
+ const trimmed = value.trim();
697
+ return trimmed.length > 1 && trimmed.startsWith("/") && /^\/[\w:$@.{}\-/[\]]+$/.test(trimmed);
698
+ }
699
+ function linkTargets(file) {
700
+ const targets = [];
701
+ const push = (raw) => {
702
+ const segments = staticSegments(raw);
703
+ if (segments.length > 0) targets.push({ raw, segments });
704
+ };
705
+ for (const segment of file.scan.segments) {
706
+ if (segment.kind !== "jsx-attribute" && segment.kind !== "template") continue;
707
+ const attribute = segment.attribute;
708
+ if (attribute === void 0) continue;
709
+ if (LINK_ATTRIBUTES.has(attribute.toLowerCase()) || LINK_ATTRIBUTE_SUFFIX.test(attribute)) push(segment.value);
710
+ }
711
+ const masked = file.scan.masked;
712
+ const callRe = /(?<![\w$.])([A-Za-z_$][\w$.]*)\s*\(/g;
713
+ for (const match of masked.matchAll(callRe)) {
714
+ const name = (match[1] ?? "").toLowerCase();
715
+ const tail = name.split(".").pop() ?? name;
716
+ if (!LINK_CALLS.has(name) && !LINK_CALL_TAIL.has(tail)) continue;
717
+ const parenStart = (match.index ?? 0) + (match[0]?.length ?? 1) - 1;
718
+ const end = matchingParen2(masked, parenStart);
719
+ for (const segment of file.scan.segments) {
720
+ if (segment.kind !== "string" && segment.kind !== "template") continue;
721
+ if (segment.start < parenStart || end !== -1 && segment.end > end) continue;
722
+ push(segment.value);
723
+ }
724
+ }
725
+ LOCATION_ASSIGN_RE.lastIndex = 0;
726
+ for (const match of masked.matchAll(LOCATION_ASSIGN_RE)) {
727
+ const after = (match.index ?? 0) + (match[0]?.length ?? 0);
728
+ const statementEnd = endOfStatement(masked, after);
729
+ for (const segment of file.scan.segments) {
730
+ if (segment.kind !== "string" && segment.kind !== "template") continue;
731
+ if (segment.start < after || segment.start >= statementEnd) continue;
732
+ push(segment.value);
733
+ }
734
+ }
735
+ for (const segment of file.scan.segments) {
736
+ if (segment.kind === "comment") continue;
737
+ if (pathLike(segment.value)) push(segment.value);
738
+ }
739
+ return targets;
740
+ }
741
+ function navTargets(file) {
742
+ const targets = [...linkTargets(file)];
743
+ for (const segment of file.scan.segments) {
744
+ if (segment.kind !== "string" && segment.kind !== "template") continue;
745
+ const value = segment.value.trim();
746
+ if (value.length === 0 || /\s/.test(value)) continue;
747
+ if (!/^[/$]/.test(value) && !value.includes("/")) continue;
748
+ const segments = staticSegments(value);
749
+ if (segments.length > 0) targets.push({ raw: value, segments });
750
+ }
751
+ return targets;
752
+ }
753
+ function checkReachability({ files, options }) {
754
+ const routeFile = options.routeConfigFile ? readScanned(options.routeConfigFile) : null;
755
+ const declared = routeFile ? parseRouteConfig(routeFile) : (options.routePaths ?? []).map((path) => ({ path, module: null, offset: 0, isLayout: false }));
756
+ if (declared.length === 0) return { findings: [], routeFile, routeCount: 0 };
757
+ const navFiles = (options.navFiles ?? []).map((path) => readScanned(path)).filter(isScanned);
758
+ const navPaths = navFiles.flatMap((file) => navTargets(file));
759
+ const navSet = new Set(navFiles.map((file) => file.path));
760
+ const product = files.filter((file) => !navSet.has(file.path) && file.path !== routeFile?.path);
761
+ const routeModules = indexRouteModules(declared, product);
762
+ const freeDoors = product.filter((file) => !routeModules.has(file.path)).flatMap((file) => linkTargets(file));
763
+ const doors = reachableDoors({ files: product, navPaths, freeDoors, routeModules });
764
+ const ignore = options.ignore ?? ["api/*"];
765
+ const ignoreNonTsx = options.ignoreNonTsxRoutes ?? true;
766
+ const findings = [];
767
+ for (const entry of declared) {
768
+ if (entry.path.length === 0) continue;
769
+ if (entry.isLayout) continue;
770
+ if (ignore.some((pattern) => matchesIgnore(entry.path, pattern))) continue;
771
+ if (ignoreNonTsx && entry.module !== null && !entry.module.endsWith(".tsx")) continue;
772
+ const target = staticSegments(entry.path);
773
+ if (target.length === 0) continue;
774
+ if (doors.some((door) => isSuffix(target, door.segments))) continue;
775
+ findings.push({
776
+ check: "unreachable-capability",
777
+ offset: entry.offset,
778
+ message: `Route "${entry.path}" is reachable by neither the navigation nor any link in the source \u2014 only by typing the URL.`,
779
+ remedy: "Add it to the navigation, or link it from the screen a reader would look for it on. If it is deliberately unlisted (an internal tool, a deep link sent by email), suppress it with that reason.",
780
+ evidence: routeFile ? evidenceOf(routeFile.text, entry.offset - 1, entry.offset + entry.path.length + 60, 90) : entry.path
781
+ });
782
+ }
783
+ return { findings, routeFile, routeCount: declared.length };
784
+ }
785
+ function isScanned(file) {
786
+ return file !== null;
787
+ }
788
+ function indexRouteModules(declared, files) {
789
+ const byFile = /* @__PURE__ */ new Map();
790
+ for (const entry of declared) {
791
+ const module = entry.module;
792
+ if (module === null) continue;
793
+ const owner = files.find((file) => file.path === module || file.path.endsWith(`/${module}`));
794
+ if (owner === void 0) continue;
795
+ const existing = byFile.get(owner.path);
796
+ if (existing) existing.push(entry);
797
+ else byFile.set(owner.path, [entry]);
798
+ }
799
+ return byFile;
800
+ }
801
+ function reachableDoors({ files, navPaths, freeDoors, routeModules }) {
802
+ const doors = [...navPaths, ...freeDoors];
803
+ const pending = files.filter((file) => routeModules.has(file.path)).map((file) => ({
804
+ file,
805
+ // A layout adds no path of its own and renders around every child, so it
806
+ // opens as soon as anything is open at all.
807
+ targets: (routeModules.get(file.path) ?? []).filter((entry) => !entry.isLayout).map((entry) => staticSegments(entry.path)).filter((parts) => parts.length > 0)
808
+ }));
809
+ let open = true;
810
+ while (open) {
811
+ open = false;
812
+ for (let i = pending.length - 1; i >= 0; i--) {
813
+ const candidate = pending[i];
814
+ if (candidate === void 0) continue;
815
+ const reached = candidate.targets.length === 0 || candidate.targets.some((target) => doors.some((door) => isSuffix(target, door.segments)));
816
+ if (!reached) continue;
817
+ pending.splice(i, 1);
818
+ doors.push(...linkTargets(candidate.file));
819
+ open = true;
820
+ }
821
+ }
822
+ return doors;
823
+ }
824
+ function readScanned(path) {
825
+ try {
826
+ return buildScannedFile(path, readFileSync2(path, "utf8"));
827
+ } catch {
828
+ return null;
829
+ }
830
+ }
831
+ function isSuffix(route, door) {
832
+ if (door.length === 0 || door.length > route.length) return false;
833
+ const offset = route.length - door.length;
834
+ return door.every((segment, index) => segment.toLowerCase() === (route[offset + index] ?? "").toLowerCase());
835
+ }
836
+ function matchesIgnore(path, pattern) {
837
+ if (pattern.endsWith("/*")) return path === pattern.slice(0, -2) || path.startsWith(pattern.slice(0, -1));
838
+ return path === pattern;
839
+ }
840
+
841
+ // src/legibility/checks/silent-failure.ts
842
+ var ERROR_SINK = /\bthrow\b|\breject\s*\(|\btoast\b|\bfail[A-Za-z]*\s*\(|\b(set|show|render|display|report|surface|push|add|emit|on)[A-Za-z]*(error|failure|failed|problem|issue|notice|warning|message|banner|alert|toast)\s*\(|\b(error|failure|message|notice)\s*[:=][^=]/i;
843
+ var CONSOLE_CALL = /\bconsole\s*\.\s*[a-z]+\s*\([^()]*(\([^()]*\)[^()]*)*\)/g;
844
+ var RESTORES_STATE = /\b(set|restore|revert|roll)[A-Za-z]*\s*\(\s*(prev|previous|original|before|last|old)[A-Za-z]*\s*[,)]/i;
845
+ function returnsWords(bodyWithoutConsole) {
846
+ const at = bodyWithoutConsole.search(/\breturn\b/);
847
+ return at !== -1 && /['"`]/.test(bodyWithoutConsole.slice(at));
848
+ }
849
+ var IO_IN_TRY = /\bawait\b|\.\s*then\s*\(|\bfetch\s*\(|\bXMLHttpRequest\b/;
850
+ var BODY_READ_AFTER_AWAIT = /^[\s(]*[\w$.\s()]*?\.\s*(json|text|formData|arrayBuffer|blob)\s*\(\s*\)/;
851
+ function parseOnlyTry(tryBody) {
852
+ if (/\bfetch\s*\(|\.\s*then\s*\(|\bXMLHttpRequest\b/.test(tryBody)) return false;
853
+ const awaits = [...tryBody.matchAll(/\bawait\b/g)];
854
+ if (awaits.length === 0) return false;
855
+ return awaits.every((match) => BODY_READ_AFTER_AWAIT.test(tryBody.slice((match.index ?? 0) + "await".length)));
856
+ }
857
+ var READERLESS_PATHS = ["/.server/", "/routes/api."];
858
+ var CATCH_RE = /\bcatch\s*(?:\(([^)]*)\)\s*)?\{/g;
859
+ var PROMISE_CATCH_RE = /\.\s*catch\s*\(/g;
860
+ function checkSilentFailure(file, options = {}) {
861
+ const extraSinks = (options.extraErrorSinks ?? []).map((sink) => sink.toLowerCase());
862
+ const readerless = options.readerlessPaths ?? READERLESS_PATHS;
863
+ if (readerless.some((marker) => file.path.includes(marker))) return [];
864
+ const masked = file.scan.masked;
865
+ const findings = [];
866
+ const surfaced = (body) => {
867
+ if (ERROR_SINK.test(body) || RESTORES_STATE.test(body)) return true;
868
+ if (returnsWords(body.replace(CONSOLE_CALL, " "))) return true;
869
+ return extraSinks.some((sink) => body.toLowerCase().includes(sink));
870
+ };
871
+ CATCH_RE.lastIndex = 0;
872
+ for (const match of masked.matchAll(CATCH_RE)) {
873
+ const braceAt = (match.index ?? 0) + (match[0]?.length ?? 1) - 1;
874
+ const block = blockFrom(masked, braceAt);
875
+ if (block === null) continue;
876
+ const body = masked.slice(block.start + 1, block.end - 1);
877
+ if (surfaced(body)) continue;
878
+ if (carriesError(body, match[1])) continue;
879
+ const guarded = tryBlockBefore(masked, match.index ?? 0);
880
+ if (guarded === null || !IO_IN_TRY.test(guarded)) continue;
881
+ if (parseOnlyTry(guarded)) continue;
882
+ findings.push({
883
+ check: "silent-failure",
884
+ offset: match.index ?? 0,
885
+ message: body.trim().length === 0 ? "This catch swallows the failure entirely \u2014 the request failed and the screen will render as if it returned nothing." : "This catch never surfaces the failure \u2014 the reader sees an empty result, not a problem they can act on.",
886
+ remedy: "Set an error state this screen renders (with a retry), or rethrow so a boundary above can. A console line is not a sink \u2014 the reader has no console.",
887
+ evidence: evidenceOf(file.text, match.index ?? 0, block.end, 80)
888
+ });
889
+ }
890
+ PROMISE_CATCH_RE.lastIndex = 0;
891
+ for (const match of masked.matchAll(PROMISE_CATCH_RE)) {
892
+ const parenAt = (match.index ?? 0) + (match[0]?.length ?? 1) - 1;
893
+ const end = matchingParen3(masked, parenAt);
894
+ if (end === -1) continue;
895
+ const body = masked.slice(parenAt + 1, end - 1);
896
+ if (body.trim().length === 0) continue;
897
+ if (surfaced(body)) continue;
898
+ if (!isRequestChain(masked, match.index ?? 0)) continue;
899
+ if (!/=>|\bfunction\b/.test(body)) continue;
900
+ findings.push({
901
+ check: "silent-failure",
902
+ offset: match.index ?? 0,
903
+ message: "This .catch() handler discards the failure \u2014 the promise rejects and nothing on screen changes.",
904
+ remedy: "Surface it: set the error state this view renders, or rethrow. If the failure is genuinely ignorable, suppress with a reason saying why.",
905
+ evidence: evidenceOf(file.text, match.index ?? 0, end, 80)
906
+ });
907
+ }
908
+ return findings.sort((left, right) => left.offset - right.offset);
909
+ }
910
+ function isRequestChain(masked, catchAt) {
911
+ const chain = masked.slice(chainStart(masked, catchAt), catchAt);
912
+ if (!/\bfetch\s*\(/.test(chain)) return false;
913
+ return !/\.\s*(json|text|blob|arrayBuffer|formData)\s*\(\s*\)\s*$/.test(chain);
914
+ }
915
+ function chainStart(masked, from) {
916
+ let at = from;
917
+ for (; ; ) {
918
+ at = trimmedEnd(masked, at);
919
+ if (at <= 0) return 0;
920
+ const ch = masked[at - 1];
921
+ if (ch === ")" || ch === "]") {
922
+ const open = matchingOpenBefore(masked, at - 1);
923
+ if (open === -1) return at;
924
+ at = trimmedEnd(masked, open);
925
+ continue;
926
+ }
927
+ if (ch !== void 0 && /[\w$]/.test(ch)) {
928
+ let start = at - 1;
929
+ while (start > 0 && /[\w$]/.test(masked[start - 1] ?? "")) start--;
930
+ const beforeIdent = trimmedEnd(masked, start);
931
+ if (beforeIdent > 0 && masked[beforeIdent - 1] === ".") {
932
+ at = beforeIdent - 1;
933
+ continue;
934
+ }
935
+ return start;
936
+ }
937
+ return at;
938
+ }
939
+ }
940
+ function trimmedEnd(masked, from) {
941
+ let at = from;
942
+ while (at > 0 && /\s/.test(masked[at - 1] ?? "")) at--;
943
+ return at;
944
+ }
945
+ function matchingOpenBefore(masked, close) {
946
+ const closer = masked[close];
947
+ const opener = closer === ")" ? "(" : "[";
948
+ let depth = 0;
949
+ for (let i = close; i >= 0; i--) {
950
+ const ch = masked[i];
951
+ if (ch === closer) depth++;
952
+ else if (ch === opener) {
953
+ depth--;
954
+ if (depth === 0) return i;
955
+ }
956
+ }
957
+ return -1;
958
+ }
959
+ function carriesError(body, binding) {
960
+ const name = /^[A-Za-z_$][\w$]*/.exec((binding ?? "").trim())?.[0];
961
+ if (name === void 0) return false;
962
+ const withoutConsole = body.replace(CONSOLE_CALL, " ");
963
+ return new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(withoutConsole);
964
+ }
965
+ function blockFrom(masked, braceAt) {
966
+ let depth = 0;
967
+ for (let i = braceAt; i < masked.length; i++) {
968
+ const ch = masked[i];
969
+ if (ch === "{") depth++;
970
+ else if (ch === "}") {
971
+ depth--;
972
+ if (depth === 0) return { start: braceAt, end: i + 1 };
973
+ }
974
+ }
975
+ return null;
976
+ }
977
+ function matchingParen3(masked, open) {
978
+ let depth = 0;
979
+ for (let i = open; i < masked.length; i++) {
980
+ const ch = masked[i];
981
+ if (ch === "(") depth++;
982
+ else if (ch === ")") {
983
+ depth--;
984
+ if (depth === 0) return i + 1;
985
+ }
986
+ }
987
+ return -1;
988
+ }
989
+ function tryBlockBefore(masked, catchAt) {
990
+ const before = masked.slice(0, catchAt).trimEnd();
991
+ if (!before.endsWith("}")) return null;
992
+ const block = enclosingBlock(masked, before.length - 1);
993
+ if (block === null) return null;
994
+ const head = masked.slice(Math.max(0, block.start - 8), block.start);
995
+ if (!/\btry\s*$/.test(head)) return null;
996
+ return masked.slice(block.start, block.end);
997
+ }
998
+
999
+ // src/legibility/checks/success.ts
1000
+ var DEFAULT_HTTP_CALLS = ["fetch"];
1001
+ var SUCCESS_CALLS = /* @__PURE__ */ new Set(["toast.success", "toast.ok", "notifySuccess"]);
1002
+ var SUCCESS_SETTER = /^set[A-Za-z]*(saved|success|succeeded|done|complete|completed|sent|submitted|confirmed)$/i;
1003
+ var STATUS_SETTER = /^set[A-Za-z]*(status|state|phase|stage|message|notice)$/i;
1004
+ var SUCCESS_WORD = /^(saved|success|succeeded|done|sent|complete|completed|updated|created|ok)\b/i;
1005
+ var INSPECTS_RESPONSE = /\.\s*(ok|status|statusText)\b|\{[^}\n]*\b(ok|status)\b[^}\n]*\}\s*=/;
1006
+ var CALL_RE = /(?<![\w$.])((?:new\s+)?[A-Za-z_$][\w$.]*)\s*\(/g;
1007
+ function callSites(masked) {
1008
+ const sites = [];
1009
+ CALL_RE.lastIndex = 0;
1010
+ for (const match of masked.matchAll(CALL_RE)) {
1011
+ const name = (match[1] ?? "").replace(/^new\s+/, "");
1012
+ const start = match.index ?? 0;
1013
+ const parenStart = start + (match[0]?.length ?? 1) - 1;
1014
+ sites.push({ name, start, parenStart, parenEnd: matchingParen4(masked, parenStart) });
1015
+ }
1016
+ return sites;
1017
+ }
1018
+ function matchingParen4(masked, open) {
1019
+ let depth = 0;
1020
+ for (let i = open; i < masked.length; i++) {
1021
+ const ch = masked[i];
1022
+ if (ch === "(") depth++;
1023
+ else if (ch === ")") {
1024
+ depth--;
1025
+ if (depth === 0) return i + 1;
1026
+ }
1027
+ }
1028
+ return -1;
1029
+ }
1030
+ function checkUncheckedSuccess(file, options = {}) {
1031
+ const httpCalls = new Set([...DEFAULT_HTTP_CALLS, ...options.httpCalls ?? []].map((call) => call.toLowerCase()));
1032
+ const okGuards = new Set((options.okGuards ?? []).map((guard) => guard.toLowerCase()));
1033
+ const extraSignals = new Set((options.extraSuccessSignals ?? []).map((signal) => signal.toLowerCase()));
1034
+ const masked = file.scan.masked;
1035
+ const sites = callSites(masked);
1036
+ const requests = sites.filter((site) => httpCalls.has(site.name.toLowerCase()));
1037
+ if (requests.length === 0) return [];
1038
+ const findings = [];
1039
+ const reported = /* @__PURE__ */ new Set();
1040
+ for (const request of requests) {
1041
+ const scope = enclosingFunctionBlock(masked, request.start) ?? { start: 0, end: masked.length };
1042
+ if (reported.has(scope.start)) continue;
1043
+ const body = masked.slice(scope.start, scope.end);
1044
+ if (INSPECTS_RESPONSE.test(body)) continue;
1045
+ if (sites.some((site) => okGuards.has(site.name.toLowerCase()) && within(site.start, scope))) continue;
1046
+ const signal = sites.find((site) => within(site.start, scope) && isSuccessSignal(file, site, extraSignals));
1047
+ if (!signal) continue;
1048
+ reported.add(scope.start);
1049
+ const awaited = isAwaited(masked, request.start) || isChained(masked, request.parenEnd);
1050
+ findings.push({
1051
+ check: "unchecked-success",
1052
+ offset: signal.start,
1053
+ message: awaited ? `"${signal.name}(\u2026)" reports success, but nothing in this function reads the response's ok/status \u2014 ${request.name} resolves on a 404 as happily as on a 200.` : `"${signal.name}(\u2026)" reports success before ${request.name}(\u2026) has settled \u2014 the request is not awaited, so the outcome cannot be known yet.`,
1054
+ remedy: awaited ? `Check the response first: const res = await ${request.name}(\u2026); if (!res.ok) { show the failure } else { ${signal.name}(\u2026) }.` : `Await the request, then branch on res.ok. If it is deliberately fire-and-forget, say "sending" rather than "sent".`,
1055
+ evidence: evidenceOf(file.text, lineStart(file, signal.start), signal.parenEnd > 0 ? signal.parenEnd : signal.start)
1056
+ });
1057
+ }
1058
+ return findings;
1059
+ }
1060
+ function within(offset, scope) {
1061
+ return offset >= scope.start && offset < scope.end;
1062
+ }
1063
+ function lineStart(file, offset) {
1064
+ const { line } = file.positionAt(offset);
1065
+ return file.lineStarts[line - 1] ?? offset;
1066
+ }
1067
+ function isSuccessSignal(file, site, extraSignals) {
1068
+ const name = site.name;
1069
+ if (SUCCESS_CALLS.has(name) || extraSignals.has(name.toLowerCase())) return true;
1070
+ const argument = firstArgument(file, site);
1071
+ if (SUCCESS_SETTER.test(name)) return argument.literal === null ? argument.code === "true" : true;
1072
+ if (STATUS_SETTER.test(name)) return argument.literal !== null && SUCCESS_WORD.test(argument.literal.trim());
1073
+ return false;
1074
+ }
1075
+ function firstArgument(file, site) {
1076
+ const literal = file.scan.segments.find(
1077
+ (segment) => (segment.kind === "string" || segment.kind === "template") && segment.start > site.parenStart && (site.parenEnd === -1 || segment.end <= site.parenEnd)
1078
+ );
1079
+ const code = file.scan.masked.slice(site.parenStart + 1, site.parenEnd > 0 ? site.parenEnd - 1 : site.parenStart + 40).trim();
1080
+ const literalIsFirst = literal !== void 0 && file.scan.masked.slice(site.parenStart + 1, literal.start).replace(/['"`]/g, "").trim() === "";
1081
+ return { literal: literalIsFirst && literal ? literal.value : null, code };
1082
+ }
1083
+ function isAwaited(masked, callStart) {
1084
+ return /\bawait\s*$/.test(masked.slice(Math.max(0, callStart - 12), callStart));
1085
+ }
1086
+ function isChained(masked, parenEnd) {
1087
+ if (parenEnd <= 0) return false;
1088
+ return /^\s*\.\s*(then|catch|finally)\b/.test(masked.slice(parenEnd, parenEnd + 24));
1089
+ }
1090
+
1091
+ // src/legibility/checks/vocabulary.ts
1092
+ var DEFAULT_BANNED_TERMS = [
1093
+ { term: "materialize", instead: 'say what the reader gets: "your documents are ready"' },
1094
+ { term: "materialized", instead: 'say what the reader gets: "your documents are ready"' },
1095
+ { term: "materializing", instead: 'say what is happening: "getting your documents ready"' },
1096
+ { term: "materialization", instead: 'say what is happening: "getting your documents ready"' },
1097
+ { term: "fact", instead: 'name the thing: "the figure we found", "the wage entry"' },
1098
+ { term: "facts", instead: 'name the things: "the figures we found", "wage entries"' },
1099
+ { term: "conflict", instead: 'say what disagrees: "two documents report different wages"' },
1100
+ { term: "conflicts", instead: 'say what disagrees: "two documents report different wages"' },
1101
+ { term: "proposed", instead: 'say who acts next: "needs your approval"' },
1102
+ { term: "workspace", instead: 'name the container the reader recognises: "account", "client", "matter"' },
1103
+ { term: "record", instead: 'name the domain object: "return", "matter", "contact"' },
1104
+ { term: "records", instead: 'name the domain objects: "returns", "matters", "contacts"' },
1105
+ { term: "artifact", instead: 'name the deliverable: "return", "redline", "brief"' },
1106
+ { term: "artifacts", instead: 'name the deliverables: "returns", "redlines", "briefs"' },
1107
+ { term: "work product", instead: "name the deliverable the reader asked for" },
1108
+ { term: "OCR", instead: 'say what happened: "we read your scan"' },
1109
+ { term: "extraction", instead: 'say what happened: "what we found in your documents"' },
1110
+ { term: "superseded", instead: '"replaced by a newer version"' },
1111
+ { term: "sourceKind", instead: "an internal field name \u2014 write the label the reader reads" },
1112
+ { term: "itemKey", instead: "an internal field name \u2014 write the label the reader reads" },
1113
+ { term: "payload", instead: 'name what was sent: "your answers", "the document"' },
1114
+ { term: "null", instead: "a value the code failed to fill \u2014 render the real value or written fallback copy" },
1115
+ { term: "undefined", instead: "a value the code failed to fill \u2014 render the real value or written fallback copy" }
1116
+ ];
1117
+ var COPY_KEYS = [
1118
+ "title",
1119
+ "label",
1120
+ "placeholder",
1121
+ "alt",
1122
+ "description",
1123
+ "heading",
1124
+ "subheading",
1125
+ "subtitle",
1126
+ "message",
1127
+ "tooltip",
1128
+ "caption",
1129
+ "summary",
1130
+ "hint",
1131
+ "helper",
1132
+ "helperText",
1133
+ "error",
1134
+ "errorMessage",
1135
+ "emptyTitle",
1136
+ "emptyDescription",
1137
+ "emptyLabel",
1138
+ "emptyMessage",
1139
+ "emptyText",
1140
+ "cta",
1141
+ "ctaLabel",
1142
+ "confirmLabel",
1143
+ "cancelLabel",
1144
+ "submitLabel",
1145
+ "actionLabel",
1146
+ "buttonLabel",
1147
+ "headline",
1148
+ "copy",
1149
+ "note",
1150
+ "notice",
1151
+ "warning",
1152
+ "question"
1153
+ ];
1154
+ var COPY_CALLS = [
1155
+ "toast",
1156
+ "toast.success",
1157
+ "toast.error",
1158
+ "toast.info",
1159
+ "toast.warning",
1160
+ "toast.message",
1161
+ "alert",
1162
+ "confirm",
1163
+ "notify",
1164
+ "Error",
1165
+ "setError",
1166
+ "setErrorMessage",
1167
+ "setMessage",
1168
+ "setNotice",
1169
+ "setWarning"
1170
+ ];
1171
+ function compile(terms) {
1172
+ return terms.map((term) => ({
1173
+ term,
1174
+ // Whitespace in a term matches any run of whitespace, so "work product"
1175
+ // still matches across a wrapped line of JSX text.
1176
+ re: new RegExp(`(?<![\\w-])${escape(term.term).replace(/\\?\s+/g, "\\s+")}(?![\\w-])`, "gi")
1177
+ }));
1178
+ }
1179
+ function escape(value) {
1180
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1181
+ }
1182
+ function checkVocabulary(file, options = {}) {
1183
+ const allow = new Set((options.allowTerms ?? []).map((term) => term.toLowerCase()));
1184
+ const base = options.terms ?? DEFAULT_BANNED_TERMS;
1185
+ const terms = compile(
1186
+ [...base, ...options.extraTerms ?? []].filter((entry) => !allow.has(entry.term.toLowerCase()))
1187
+ );
1188
+ const copyKeys = new Set([...COPY_KEYS, ...options.extraCopyKeys ?? []].map((key) => key.toLowerCase()));
1189
+ const copyCalls = new Set([...COPY_CALLS, ...options.extraCopyCalls ?? []].map((call) => call.toLowerCase()));
1190
+ const findings = [];
1191
+ for (const segment of file.scan.segments) {
1192
+ const visible = visibleCopy(file, segment, {
1193
+ copyKeys,
1194
+ copyCalls,
1195
+ includeObjectCopy: options.includeObjectCopy === true
1196
+ });
1197
+ if (visible === null) continue;
1198
+ for (const { term, re } of terms) {
1199
+ re.lastIndex = 0;
1200
+ for (const match of segment.value.matchAll(re)) {
1201
+ const offset = segment.start + (match.index ?? 0);
1202
+ findings.push({
1203
+ check: "engineering-vocabulary",
1204
+ offset,
1205
+ message: `"${match[0]}" is a word from the codebase, on screen in ${visible}.`,
1206
+ remedy: `Write what the reader needs: ${term.instead}.`,
1207
+ evidence: segment.value.replace(/\s+/g, " ").trim().slice(0, 100)
1208
+ });
1209
+ }
1210
+ }
1211
+ }
1212
+ return findings;
1213
+ }
1214
+ function visibleCopy(file, segment, context) {
1215
+ const { kind, attribute, start } = segment;
1216
+ if (kind === "comment") return null;
1217
+ if (kind === "jsx-text") return "rendered text";
1218
+ const named = attribute !== void 0 && context.copyKeys.has(attribute.toLowerCase());
1219
+ if (kind === "jsx-attribute") return named ? `the ${attribute} attribute` : null;
1220
+ if (named && segment.tag !== void 0) return `the ${attribute} attribute`;
1221
+ return codeContext(file, start, context);
1222
+ }
1223
+ function codeContext(file, start, context) {
1224
+ const from = Math.max(0, start - 90);
1225
+ const before = file.scan.masked.slice(from, Math.max(from, start - 1));
1226
+ const call = /(?:new\s+)?([A-Za-z_$][\w$.]*)\s*\(\s*$/.exec(before);
1227
+ if (call?.[1] && context.copyCalls.has(call[1].toLowerCase())) return `${call[1]}(\u2026)`;
1228
+ if (!context.includeObjectCopy) return null;
1229
+ const key = /([A-Za-z_$][\w$]*)\s*[:=]\s*$/.exec(before);
1230
+ if (key?.[1] && context.copyKeys.has(key[1].toLowerCase())) return `the ${key[1]} value`;
1231
+ return null;
1232
+ }
1233
+
1234
+ // src/legibility/types.ts
1235
+ var LEGIBILITY_CHECKS = [
1236
+ "engineering-vocabulary",
1237
+ "dead-end-empty-state",
1238
+ "unchecked-success",
1239
+ "silent-failure",
1240
+ "unreachable-capability",
1241
+ "suppression-without-reason"
1242
+ ];
1243
+
1244
+ // src/legibility/suppress.ts
1245
+ var MIN_REASON = 12;
1246
+ var DIRECTIVE_RE = /legibility-ignore(-file)?\s+([^\n]*)/;
1247
+ var KNOWN = new Set(LEGIBILITY_CHECKS);
1248
+ function buildSuppressionIndex(file) {
1249
+ const directives = [];
1250
+ const selfFindings = [];
1251
+ for (const segment of file.scan.segments) {
1252
+ if (segment.kind !== "comment") continue;
1253
+ const match = DIRECTIVE_RE.exec(segment.value);
1254
+ if (!match) continue;
1255
+ const wholeFile = match[1] === "-file";
1256
+ const rest = (match[2] ?? "").trim();
1257
+ const { names, reason } = splitDirective(rest);
1258
+ const known = names.filter((name) => KNOWN.has(name));
1259
+ const unknownChecks = names.filter((name) => !KNOWN.has(name));
1260
+ const directiveLine = file.positionAt(segment.start + match.index).line;
1261
+ const hasReason = reason.length >= MIN_REASON;
1262
+ const offset = segment.start + match.index;
1263
+ if (names.length === 0) {
1264
+ selfFindings.push({
1265
+ check: "suppression-without-reason",
1266
+ offset,
1267
+ message: "legibility-ignore names no check, so it is unclear what it excuses.",
1268
+ remedy: `Name the check and give a reason: legibility-ignore <${LEGIBILITY_CHECKS.slice(0, 2).join("|")}|\u2026> \u2014 why this one is right.`,
1269
+ evidence: `legibility-ignore ${rest}`.trim()
1270
+ });
1271
+ continue;
1272
+ }
1273
+ for (const unknown of unknownChecks) {
1274
+ selfFindings.push({
1275
+ check: "suppression-without-reason",
1276
+ offset,
1277
+ message: `legibility-ignore names "${unknown}", which is not a check \u2014 it suppresses nothing.`,
1278
+ remedy: `Use one of: ${LEGIBILITY_CHECKS.join(", ")}.`,
1279
+ evidence: `legibility-ignore ${rest}`.trim()
1280
+ });
1281
+ }
1282
+ if (!hasReason && known.length > 0) {
1283
+ selfFindings.push({
1284
+ check: "suppression-without-reason",
1285
+ offset,
1286
+ message: `legibility-ignore ${known.join(", ")} gives no reason, so it does not suppress anything.`,
1287
+ remedy: `Write why this instance is right after a dash: legibility-ignore ${known[0]} \u2014 <reason, ${MIN_REASON}+ characters>.`,
1288
+ evidence: `legibility-ignore ${rest}`.trim()
1289
+ });
1290
+ }
1291
+ if (known.length === 0) continue;
1292
+ directives.push({
1293
+ checks: known,
1294
+ reason,
1295
+ hasReason,
1296
+ unknownChecks,
1297
+ line: directiveLine,
1298
+ appliesToLine: wholeFile ? null : targetLine(file, segment.start, directiveLine)
1299
+ });
1300
+ }
1301
+ const honoured = directives.filter((directive) => directive.hasReason);
1302
+ return {
1303
+ selfFindings,
1304
+ reasonFor(check, line) {
1305
+ for (const directive of honoured) {
1306
+ if (!directive.checks.includes(check)) continue;
1307
+ if (directive.appliesToLine === null || directive.appliesToLine === line) return directive.reason;
1308
+ }
1309
+ return null;
1310
+ }
1311
+ };
1312
+ }
1313
+ function splitDirective(rest) {
1314
+ const separator = /(?:^|\s)(?:—|–|--|-|:)\s|:\s/.exec(rest);
1315
+ const head = separator ? rest.slice(0, separator.index) : rest;
1316
+ const reason = separator ? rest.slice(separator.index + separator[0].length).trim() : "";
1317
+ const names = head.split(/[,\s]+/).map((name) => name.trim()).filter((name) => name.length > 0);
1318
+ return { names, reason };
1319
+ }
1320
+ function targetLine(file, commentStart, commentLine) {
1321
+ const lineStart2 = file.lineStarts[commentLine - 1] ?? 0;
1322
+ const before = file.text.slice(lineStart2, commentStart).replace(/[{/*]/g, "").trim();
1323
+ if (before.length > 0) return commentLine;
1324
+ for (let line = commentLine + 1; line <= file.lineStarts.length; line++) {
1325
+ const start = file.lineStarts[line - 1];
1326
+ if (start === void 0) break;
1327
+ const end = file.lineStarts[line] ?? file.text.length;
1328
+ const content = file.text.slice(start, end).trim();
1329
+ if (content.length === 0) continue;
1330
+ if (/^(\/\/|\*|\{?\/\*)/.test(content) && !/legibility-ignore/.test(content)) continue;
1331
+ if (/legibility-ignore/.test(content)) continue;
1332
+ return line;
1333
+ }
1334
+ return commentLine + 1;
1335
+ }
1336
+
1337
+ // src/legibility/report.ts
1338
+ var CHECK_TITLES = {
1339
+ "engineering-vocabulary": "Engineering vocabulary on screen",
1340
+ "dead-end-empty-state": "Empty states with no next action",
1341
+ "unchecked-success": "Success reported without reading the response",
1342
+ "silent-failure": "Failures the reader never learns about",
1343
+ "unreachable-capability": "Capabilities with no door",
1344
+ "suppression-without-reason": "Suppressions that suppress nothing"
1345
+ };
1346
+ function formatLegibilityReport(report, options = {}) {
1347
+ const lines = [];
1348
+ const bold = (text) => options.colour ? `\x1B[1m${text}\x1B[0m` : text;
1349
+ if (report.ok) {
1350
+ lines.push(
1351
+ `legibility OK \u2014 ${report.filesScanned} file(s), ${report.checksRun.length} check(s), no findings` + (report.suppressed.length > 0 ? ` (${report.suppressed.length} suppressed with a reason)` : "")
1352
+ );
1353
+ if (options.listSuppressions) lines.push("", ...suppressionLines(report));
1354
+ return lines.join("\n");
1355
+ }
1356
+ lines.push(
1357
+ `legibility FAILED \u2014 ${report.findings.length} finding(s) across ${report.filesScanned} file(s).`,
1358
+ "Each one is a place a reader is left guessing. Fix it, or suppress that line with a written reason.",
1359
+ ""
1360
+ );
1361
+ for (const check of LEGIBILITY_CHECKS) {
1362
+ const findings = report.findings.filter((finding) => finding.check === check);
1363
+ if (findings.length === 0) continue;
1364
+ lines.push(`${bold(CHECK_TITLES[check])} [${check}] ${findings.length}`);
1365
+ for (const finding of findings) lines.push(...findingLines(finding));
1366
+ lines.push("");
1367
+ }
1368
+ if (report.suppressed.length > 0) {
1369
+ lines.push(
1370
+ `${report.suppressed.length} finding(s) suppressed with a written reason` + (options.listSuppressions ? ":" : " \u2014 run with --list-suppressions to read them.")
1371
+ );
1372
+ if (options.listSuppressions) lines.push(...suppressionLines(report));
1373
+ lines.push("");
1374
+ }
1375
+ lines.push("Suppress one deliberate instance with a reason on the line above it:");
1376
+ lines.push(" // legibility-ignore <check> \u2014 why this instance is right");
1377
+ return lines.join("\n");
1378
+ }
1379
+ function findingLines(finding) {
1380
+ return [
1381
+ ` ${finding.file}:${finding.line}:${finding.column}`,
1382
+ ` ${finding.message}`,
1383
+ ` \u2192 ${finding.remedy}`,
1384
+ ...finding.evidence ? [` ${finding.evidence}`] : []
1385
+ ];
1386
+ }
1387
+ function suppressionLines(report) {
1388
+ return report.suppressed.map(
1389
+ (suppression) => ` ${suppression.file}:${suppression.line} ${suppression.check} \u2014 ${suppression.reason}`
1390
+ );
1391
+ }
1392
+ function legibilityReportToJson(report) {
1393
+ return JSON.stringify(report, null, 2);
1394
+ }
1395
+
1396
+ // src/legibility/index.ts
1397
+ function enabled(config, check) {
1398
+ return config.checks?.[check] !== false;
1399
+ }
1400
+ function checkLegibility(config) {
1401
+ if (config.srcDirs.length === 0) throw new Error("checkLegibility: srcDirs must name at least one directory");
1402
+ const files = scanSources(config.srcDirs, config.ignorePaths ?? []);
1403
+ const findings = [];
1404
+ const suppressed = [];
1405
+ const collect = (file, raw) => {
1406
+ const index = buildSuppressionIndex(file);
1407
+ for (const finding of [...raw, ...index.selfFindings]) {
1408
+ if (!enabled(config, finding.check)) continue;
1409
+ const { line, column } = file.positionAt(finding.offset);
1410
+ const reason = finding.check === "suppression-without-reason" ? null : index.reasonFor(finding.check, line);
1411
+ if (reason !== null) {
1412
+ suppressed.push({ check: finding.check, reason, file: file.display, line });
1413
+ continue;
1414
+ }
1415
+ findings.push({
1416
+ check: finding.check,
1417
+ file: file.display,
1418
+ line,
1419
+ column,
1420
+ message: finding.message,
1421
+ remedy: finding.remedy,
1422
+ evidence: finding.evidence
1423
+ });
1424
+ }
1425
+ };
1426
+ for (const file of files) {
1427
+ const raw = [];
1428
+ if (enabled(config, "engineering-vocabulary")) raw.push(...checkVocabulary(file, config.vocabulary));
1429
+ if (enabled(config, "dead-end-empty-state")) raw.push(...checkEmptyStates(file, config.emptyState));
1430
+ if (enabled(config, "unchecked-success")) raw.push(...checkUncheckedSuccess(file, config.success));
1431
+ if (enabled(config, "silent-failure")) raw.push(...checkSilentFailure(file, config.silentFailure));
1432
+ collect(file, raw);
1433
+ }
1434
+ if (enabled(config, "unreachable-capability") && config.reachability) {
1435
+ const result = checkReachability({ files, options: config.reachability });
1436
+ if (result.routeFile) collect(result.routeFile, result.findings);
1437
+ else for (const finding of result.findings) findings.push(withoutFile(finding));
1438
+ }
1439
+ findings.sort(
1440
+ (left, right) => left.file.localeCompare(right.file) || left.line - right.line || left.column - right.column
1441
+ );
1442
+ return {
1443
+ ok: findings.length === 0,
1444
+ findings,
1445
+ suppressed,
1446
+ filesScanned: files.length,
1447
+ checksRun: LEGIBILITY_CHECKS.filter((check) => enabled(config, check))
1448
+ };
1449
+ }
1450
+ function withoutFile(finding) {
1451
+ return {
1452
+ check: finding.check,
1453
+ file: "(routePaths)",
1454
+ line: 0,
1455
+ column: 0,
1456
+ message: finding.message,
1457
+ remedy: finding.remedy,
1458
+ evidence: finding.evidence
1459
+ };
1460
+ }
1461
+
1462
+ export {
1463
+ scanSource,
1464
+ scanFile,
1465
+ buildScannedFile,
1466
+ scanSources,
1467
+ parseRouteConfig,
1468
+ staticSegments,
1469
+ READERLESS_PATHS,
1470
+ DEFAULT_BANNED_TERMS,
1471
+ COPY_KEYS,
1472
+ COPY_CALLS,
1473
+ LEGIBILITY_CHECKS,
1474
+ formatLegibilityReport,
1475
+ legibilityReportToJson,
1476
+ checkLegibility
1477
+ };
1478
+ //# sourceMappingURL=chunk-XEA5EG6P.js.map