@geonosis/walk 2.13.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/bin/geonosis-walk.mjs +1 -1
  3. package/dist/browser.d.ts +124 -0
  4. package/dist/browser.js +242 -0
  5. package/dist/config.d.ts +16 -0
  6. package/dist/config.js +100 -0
  7. package/dist/index.d.ts +7 -153
  8. package/dist/index.js +5 -13
  9. package/dist/options.d.ts +19 -0
  10. package/dist/options.js +64 -0
  11. package/dist/probes/buy-box-above-fold.d.ts +14 -0
  12. package/dist/probes/buy-box-above-fold.js +54 -0
  13. package/dist/probes/empty-section.d.ts +16 -0
  14. package/dist/probes/empty-section.js +29 -0
  15. package/dist/probes/error-page-status.d.ts +20 -0
  16. package/dist/probes/error-page-status.js +37 -0
  17. package/dist/probes/fabricated-claim.d.ts +14 -0
  18. package/dist/probes/fabricated-claim.js +29 -0
  19. package/dist/probes/fake-session.d.ts +14 -0
  20. package/dist/probes/fake-session.js +45 -0
  21. package/dist/probes/index.d.ts +9 -0
  22. package/dist/probes/index.js +42 -0
  23. package/dist/probes/light-on-light.d.ts +15 -0
  24. package/dist/probes/light-on-light.js +26 -0
  25. package/dist/probes/link-integrity.d.ts +14 -0
  26. package/dist/probes/link-integrity.js +69 -0
  27. package/dist/probes/money-format.d.ts +14 -0
  28. package/dist/probes/money-format.js +33 -0
  29. package/dist/probes/ops-leakage.d.ts +13 -0
  30. package/dist/probes/ops-leakage.js +29 -0
  31. package/dist/probes/orphan-url.d.ts +13 -0
  32. package/dist/probes/orphan-url.js +54 -0
  33. package/dist/probes/placeholder-asset.d.ts +14 -0
  34. package/dist/probes/placeholder-asset.js +40 -0
  35. package/dist/probes/stub-only-entity.d.ts +14 -0
  36. package/dist/probes/stub-only-entity.js +30 -0
  37. package/dist/probes/thin-page.d.ts +14 -0
  38. package/dist/probes/thin-page.js +30 -0
  39. package/dist/types.d.ts +104 -0
  40. package/dist/types.js +10 -0
  41. package/dist/walk-cli.js +41 -47
  42. package/dist/walk.d.ts +23 -0
  43. package/dist/walk.js +93 -0
  44. package/package.json +5 -4
  45. package/dist/chunk-VCGYSFL5.js +0 -956
@@ -1,956 +0,0 @@
1
- // src/types.ts
2
- var WalkError = class extends Error {
3
- constructor(message) {
4
- super(message);
5
- this.name = "WalkError";
6
- }
7
- };
8
-
9
- // src/browser.ts
10
- var inPage = (job) => {
11
- const dom = {
12
- /** The deepest element that still contains the match — the one a reader would point at. */
13
- deepest: (root, needle) => {
14
- let node = root;
15
- let moved = true;
16
- while (moved) {
17
- moved = false;
18
- for (const child of node.children) {
19
- if (dom.textOf(child).includes(needle)) {
20
- node = child;
21
- moved = true;
22
- break;
23
- }
24
- }
25
- }
26
- return node;
27
- },
28
- rectOf: (element) => {
29
- const box = element.getBoundingClientRect();
30
- return { height: box.height, left: box.left, top: box.top, width: box.width };
31
- },
32
- selectorOf: (element) => {
33
- if (element.id !== "") return `#${element.id}`;
34
- const testId = element.getAttribute("data-testid");
35
- if (testId !== null && testId !== "") return `[data-testid="${testId}"]`;
36
- const parts = [];
37
- let node = element;
38
- while (node !== null && parts.length < 5 && node.tagName !== "BODY") {
39
- const parent = node.parentElement;
40
- if (parent === null) break;
41
- const current = node;
42
- const siblings = [...parent.children].filter((one) => one.tagName === current.tagName);
43
- const nth = siblings.indexOf(current) + 1;
44
- const tag = current.tagName.toLowerCase();
45
- parts.unshift(siblings.length > 1 ? `${tag}:nth-of-type(${nth})` : tag);
46
- node = parent;
47
- }
48
- return parts.join(" > ");
49
- },
50
- shown: (element) => {
51
- const box = element.getBoundingClientRect();
52
- return box.width > 0 && box.height > 0 && getComputedStyle(element).visibility !== "hidden";
53
- },
54
- textOf: (element) => element.innerText ?? element.textContent ?? "",
55
- /** How many words a reader is shown — the count `thin-page` and `empty-section` are about. */
56
- wordsIn: (text) => text.split(/\s+/).filter((one) => one !== "").length
57
- };
58
- if (job.kind === "contrast") {
59
- const rgb = {
60
- bordered: (style) => style.borderStyle !== "none" && [
61
- style.borderTopWidth,
62
- style.borderRightWidth,
63
- style.borderBottomWidth,
64
- style.borderLeftWidth
65
- ].some((width) => Number.parseFloat(width) > 0),
66
- channel: (value) => value / 255 <= 0.03928 ? value / 255 / 12.92 : ((value / 255 + 0.055) / 1.055) ** 2.4,
67
- luminance: ({ b, g, r }) => 0.2126 * rgb.channel(r) + 0.7152 * rgb.channel(g) + 0.0722 * rgb.channel(b),
68
- parse: (value) => {
69
- const inside = /rgba?\(([^)]+)\)/.exec(value)?.[1];
70
- if (inside === void 0) return null;
71
- const numbers = inside.split(/[,\s/]+/).filter((one) => one !== "").map(Number);
72
- const [r, g, b, a] = numbers;
73
- if (r === void 0 || g === void 0 || b === void 0) return null;
74
- return { a: a ?? 1, b, g, r };
75
- },
76
- ratio: (one, other) => {
77
- const first = rgb.luminance(one);
78
- const second = rgb.luminance(other);
79
- return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
80
- }
81
- };
82
- const hits = [];
83
- const white = { a: 1, b: 255, g: 255, r: 255 };
84
- for (const element of document.querySelectorAll(job.selector)) {
85
- const tag = element.tagName;
86
- if (tag === "HTML" || tag === "BODY") continue;
87
- if (job.ignore.some((one) => element.matches(one))) continue;
88
- const style = getComputedStyle(element);
89
- const own = rgb.parse(style.backgroundColor);
90
- if (own === null || own.a !== 1) continue;
91
- if (style.backgroundImage !== "none" || style.boxShadow !== "none") continue;
92
- if (style.outlineStyle !== "none" || rgb.bordered(style)) continue;
93
- if (!dom.shown(element)) continue;
94
- const box = element.getBoundingClientRect();
95
- let node = element.parentElement;
96
- let behind = null;
97
- let fullBleed = false;
98
- let behindSelector = "the canvas";
99
- let behindValue = "rgb(255, 255, 255)";
100
- while (node !== null) {
101
- const parentStyle = getComputedStyle(node);
102
- const colour = rgb.parse(parentStyle.backgroundColor);
103
- if (colour !== null && colour.a === 1) {
104
- const parentBox = node.getBoundingClientRect();
105
- fullBleed = parentBox.width <= box.width && parentBox.height <= box.height;
106
- behind = colour;
107
- behindSelector = node.tagName === "BODY" ? "body" : dom.selectorOf(node);
108
- behindValue = parentStyle.backgroundColor;
109
- break;
110
- }
111
- node = node.parentElement;
112
- }
113
- if (fullBleed) continue;
114
- const contrast = rgb.ratio(own, behind ?? white);
115
- if (contrast >= job.minContrast) continue;
116
- hits.push({
117
- background: style.backgroundColor,
118
- container: behindValue,
119
- containerSelector: behindSelector,
120
- contrast: Math.round(contrast * 100) / 100,
121
- selector: dom.selectorOf(element)
122
- });
123
- }
124
- return hits;
125
- }
126
- if (job.kind === "assets") {
127
- const geometry = ["d", "points", "cx", "cy", "r", "x", "y", "x1", "y1", "x2", "y2", "href"];
128
- const scope = document.querySelector(job.scope) ?? document.body;
129
- const hits = [];
130
- for (const element of scope.querySelectorAll(job.assetSelector)) {
131
- if (!dom.shown(element)) continue;
132
- const tag = element.tagName.toLowerCase();
133
- const signature = tag === "img" ? `src:${element.src ?? element.getAttribute("src") ?? ""}` : `svg:${[
134
- ...element.querySelectorAll("path,circle,rect,ellipse,line,polygon,polyline,use")
135
- ].map(
136
- (shape) => `${shape.tagName.toLowerCase()}(${geometry.map((name) => shape.getAttribute(name) ?? "").join(",")})`
137
- ).join("|")}`;
138
- hits.push({
139
- label: [
140
- element.getAttribute("alt") ?? "",
141
- element.getAttribute("aria-label") ?? "",
142
- element.getAttribute("title") ?? ""
143
- ].filter((one) => one !== "").join(" "),
144
- selector: dom.selectorOf(element),
145
- signature
146
- });
147
- }
148
- return hits;
149
- }
150
- if (job.kind === "links") {
151
- return [...document.querySelectorAll(job.selector)].map((element) => ({
152
- href: element.getAttribute("href"),
153
- resolved: element.href ?? "",
154
- selector: dom.selectorOf(element),
155
- text: dom.textOf(element).trim().slice(0, 80)
156
- }));
157
- }
158
- if (job.kind === "text") {
159
- const roots = job.scope === "" ? [document.body] : [...document.querySelectorAll(job.scope)];
160
- const hits = [];
161
- for (const root of roots) {
162
- const text = dom.textOf(root);
163
- for (const pattern of job.patterns) {
164
- const matcher = new RegExp(pattern, `${job.flags}g`);
165
- let found = matcher.exec(text);
166
- while (found !== null) {
167
- const matched = found[0];
168
- if (matched === "") break;
169
- hits.push({
170
- pattern,
171
- selector: dom.selectorOf(dom.deepest(root, matched)),
172
- text: matched
173
- });
174
- found = matcher.exec(text);
175
- }
176
- }
177
- }
178
- return hits;
179
- }
180
- if (job.kind === "entities") {
181
- return [...document.querySelectorAll(job.selector)].map((element) => ({
182
- affordance: job.affordance === "" || element.querySelector(job.affordance) !== null,
183
- id: element.getAttribute(job.attribute) ?? "",
184
- selector: dom.selectorOf(element)
185
- }));
186
- }
187
- if (job.kind === "matches") {
188
- const scope = job.scope === "" ? document.body : document.querySelector(job.scope);
189
- const hits = [];
190
- if (scope === null) return hits;
191
- const walker = document.createTreeWalker(scope, 4);
192
- let node = walker.nextNode();
193
- while (node !== null) {
194
- const parent = node.parentElement;
195
- const text = node.nodeValue ?? "";
196
- if (parent !== null && text.trim() !== "" && dom.shown(parent)) {
197
- for (const pattern of job.patterns) {
198
- const matcher = new RegExp(pattern, `${job.flags}g`);
199
- let found = matcher.exec(text);
200
- while (found !== null) {
201
- const matched = found[0];
202
- if (matched === "") break;
203
- hits.push({ pattern, selector: dom.selectorOf(parent), text: matched });
204
- found = matcher.exec(text);
205
- }
206
- }
207
- }
208
- node = walker.nextNode();
209
- }
210
- return hits;
211
- }
212
- if (job.kind === "prose") {
213
- return [...document.querySelectorAll(job.selector)].filter((element) => dom.shown(element)).map((element) => ({
214
- headingWords: [...element.querySelectorAll(job.headingSelector)].filter((heading) => dom.shown(heading)).reduce((total, heading) => total + dom.wordsIn(dom.textOf(heading)), 0),
215
- media: [...element.querySelectorAll(job.mediaSelector)].filter((one) => dom.shown(one)).length,
216
- selector: dom.selectorOf(element),
217
- words: dom.wordsIn(dom.textOf(element))
218
- }));
219
- }
220
- if (job.kind === "present") {
221
- return job.selectors.map((selector) => ({
222
- present: document.querySelector(selector) !== null,
223
- selector
224
- }));
225
- }
226
- return {
227
- rects: job.selectors.map((selector) => {
228
- const element = document.querySelector(selector);
229
- return { rect: element === null ? null : dom.rectOf(element), selector };
230
- }),
231
- viewportHeight: innerHeight
232
- };
233
- };
234
- var collect = async (page, job) => await page.evaluate(inPage, job);
235
-
236
- // src/options.ts
237
- var stringOption = (probe, options, name, fallback) => {
238
- const value = options[name];
239
- if (typeof value === "string" && value !== "") return value;
240
- if (fallback !== void 0) return fallback;
241
- throw new WalkError(`${probe}: needs a "${name}" in the walk options`);
242
- };
243
- var stringsOption = (options, name, fallback) => {
244
- const value = options[name];
245
- if (!Array.isArray(value)) return fallback;
246
- return value.filter((one) => typeof one === "string");
247
- };
248
- var numberOption = (options, name, fallback) => {
249
- const value = options[name];
250
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
251
- };
252
- var flagOption = (options, name, fallback) => typeof options[name] === "boolean" ? options[name] : fallback;
253
- var requireStrings = (probe, options, name) => {
254
- const value = stringsOption(options, name, []);
255
- if (value.length === 0) {
256
- throw new WalkError(`${probe}: needs a non-empty "${name}" in the walk options`);
257
- }
258
- return value;
259
- };
260
- var requireNumber = (probe, options, name) => {
261
- const value = options[name];
262
- if (typeof value !== "number" || !Number.isFinite(value)) {
263
- throw new WalkError(`${probe}: needs a "${name}" number in the walk options`);
264
- }
265
- return value;
266
- };
267
- var ALLOWED_FLAGS = /* @__PURE__ */ new Set(["i", "m", "s", "u"]);
268
- var patternFlags = (probe, options) => {
269
- const flags = stringOption(probe, options, "flags", "");
270
- for (const flag of flags) {
271
- if (!ALLOWED_FLAGS.has(flag)) {
272
- throw new WalkError(`${probe}: "${flags}" is not a set of regex flags (i, m, s, u)`);
273
- }
274
- }
275
- return flags;
276
- };
277
- var assertPatterns = (probe, patterns, flags) => {
278
- for (const pattern of patterns) {
279
- try {
280
- RegExp(pattern, `${flags}g`);
281
- } catch {
282
- throw new WalkError(`${probe}: "${pattern}" is not a regular expression`);
283
- }
284
- }
285
- };
286
-
287
- // src/probes/buy-box-above-fold.ts
288
- var buyBoxAboveFold = {
289
- class: "buy-box-above-fold",
290
- id: "buy-box-above-fold",
291
- needs: (options) => {
292
- stringOption("buy-box-above-fold", options, "selector");
293
- },
294
- run: async (page, { options, url }) => {
295
- const selector = stringOption("buy-box-above-fold", options, "selector");
296
- const above = stringOption("buy-box-above-fold", options, "above", "");
297
- const { rects, viewportHeight } = await collect(page, {
298
- kind: "geometry",
299
- selectors: above === "" ? [selector] : [selector, above]
300
- });
301
- const buyBox = rects.find((one) => one.selector === selector)?.rect ?? null;
302
- if (buyBox === null) {
303
- return flagOption(options, "required", false) ? [
304
- {
305
- class: "buy-box-above-fold",
306
- evidence: `no element matches "${selector}" on a page the walk requires one on`,
307
- severity: "major",
308
- url
309
- }
310
- ] : [];
311
- }
312
- const fold = numberOption(options, "maxTop", viewportHeight);
313
- const other = above === "" ? null : rects.find((one) => one.selector === above)?.rect ?? null;
314
- const found = [];
315
- if (other !== null && buyBox.top > other.top) {
316
- found.push({
317
- class: "buy-box-above-fold",
318
- evidence: `the buy box starts at ${Math.round(buyBox.top)}px, below "${above}" at ${Math.round(other.top)}px`,
319
- selector,
320
- severity: "major",
321
- url
322
- });
323
- }
324
- if (buyBox.top >= fold) {
325
- found.push({
326
- class: "buy-box-above-fold",
327
- evidence: `the buy box starts at ${Math.round(buyBox.top)}px, below the fold at ${Math.round(fold)}px`,
328
- selector,
329
- severity: "major",
330
- url
331
- });
332
- }
333
- return found;
334
- }
335
- };
336
-
337
- // src/probes/empty-section.ts
338
- var emptySection = {
339
- class: "content-integrity",
340
- id: "empty-section",
341
- needs: (options) => {
342
- stringOption("empty-section", options, "selector");
343
- },
344
- run: async (page, { options, url }) => {
345
- const headingSelector = stringOption(
346
- "empty-section",
347
- options,
348
- "headingSelector",
349
- "h1,h2,h3,h4,h5,h6"
350
- );
351
- const hits = await collect(page, {
352
- headingSelector,
353
- kind: "prose",
354
- mediaSelector: stringOption(
355
- "empty-section",
356
- options,
357
- "mediaSelector",
358
- "img,svg,video,iframe,canvas"
359
- ),
360
- selector: stringOption("empty-section", options, "selector")
361
- });
362
- return hits.filter((hit) => hit.headingWords > 0 && hit.words <= hit.headingWords && hit.media === 0).map((hit) => ({
363
- class: "content-integrity",
364
- evidence: `the section renders ${hit.headingWords} heading word(s) and nothing else \u2014 no body text, no media`,
365
- selector: hit.selector,
366
- severity: "major",
367
- url
368
- }));
369
- }
370
- };
371
-
372
- // src/probes/error-page-status.ts
373
- var errorPageStatus = {
374
- class: "error-page-status",
375
- id: "error-page-status",
376
- needs: (options) => {
377
- const patterns = requireStrings("error-page-status", options, "patterns");
378
- assertPatterns("error-page-status", patterns, patternFlags("error-page-status", options));
379
- },
380
- run: async (page, { options, status, url }) => {
381
- if (status >= numberOption(options, "honestFrom", 400)) return [];
382
- const hits = await collect(page, {
383
- flags: patternFlags("error-page-status", options),
384
- kind: "text",
385
- patterns: requireStrings("error-page-status", options, "patterns"),
386
- scope: stringOption("error-page-status", options, "scope", "")
387
- });
388
- return hits.map((hit) => ({
389
- class: "error-page-status",
390
- evidence: `"${hit.text}" is on a page that answered ${status} \u2014 every health check reads that as healthy`,
391
- selector: hit.selector,
392
- severity: "blocking",
393
- url
394
- }));
395
- }
396
- };
397
-
398
- // src/probes/fabricated-claim.ts
399
- var fabricatedClaim = {
400
- class: "fabricated-claim",
401
- id: "fabricated-claim",
402
- needs: (options) => {
403
- const claims = requireStrings("fabricated-claim", options, "claims");
404
- assertPatterns("fabricated-claim", claims, patternFlags("fabricated-claim", options));
405
- },
406
- run: async (page, { options, url }) => {
407
- const hits = await collect(page, {
408
- flags: patternFlags("fabricated-claim", options),
409
- kind: "text",
410
- patterns: requireStrings("fabricated-claim", options, "claims"),
411
- scope: stringOption("fabricated-claim", options, "scope", "")
412
- });
413
- return hits.map((hit) => ({
414
- class: "fabricated-claim",
415
- evidence: `"${hit.text}" is on the page, matching /${hit.pattern}/`,
416
- selector: hit.selector,
417
- severity: "blocking",
418
- url
419
- }));
420
- }
421
- };
422
-
423
- // src/probes/fake-session.ts
424
- var escapeForRegex = (value) => value.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&");
425
- var fakeSession = {
426
- class: "fake-session",
427
- id: "fake-session",
428
- needs: (options) => {
429
- const selectors = stringsOption(options, "selectors", []);
430
- const text = stringsOption(options, "text", []);
431
- if (selectors.length === 0 && text.length === 0) {
432
- throw new WalkError(
433
- 'fake-session: needs "selectors" or "text" \u2014 what a signed-in page looks like here'
434
- );
435
- }
436
- },
437
- run: async (page, { options, url }) => {
438
- const selectors = stringsOption(options, "selectors", []);
439
- const text = stringsOption(options, "text", []);
440
- const present = selectors.length === 0 ? [] : await collect(page, { kind: "present", selectors });
441
- const said = text.length === 0 ? [] : await collect(page, {
442
- flags: "",
443
- kind: "text",
444
- patterns: text.map(escapeForRegex),
445
- scope: ""
446
- });
447
- const bySelector = present.filter((hit) => hit.present).map((hit) => ({
448
- class: "fake-session",
449
- evidence: `a context nobody signed in to renders ${hit.selector}`,
450
- selector: hit.selector,
451
- severity: "blocking",
452
- url
453
- }));
454
- const byText = said.map((hit) => ({
455
- class: "fake-session",
456
- evidence: `a context nobody signed in to reads "${hit.text}"`,
457
- selector: hit.selector,
458
- severity: "blocking",
459
- url
460
- }));
461
- return [...bySelector, ...byText];
462
- }
463
- };
464
-
465
- // src/probes/light-on-light.ts
466
- var lightOnLight = {
467
- class: "light-on-light",
468
- id: "light-on-light",
469
- run: async (page, { options, url }) => {
470
- const minContrast = numberOption(options, "minContrast", 1.05);
471
- const hits = await collect(page, {
472
- ignore: stringsOption(options, "ignore", []),
473
- kind: "contrast",
474
- minContrast,
475
- selector: stringOption("light-on-light", options, "selector", "*")
476
- });
477
- return hits.map((hit) => ({
478
- class: "light-on-light",
479
- evidence: `${hit.background} on ${hit.container} (${hit.containerSelector}) \u2014 contrast ${hit.contrast.toFixed(2)}, floor ${minContrast}`,
480
- selector: hit.selector,
481
- severity: "major",
482
- url
483
- }));
484
- }
485
- };
486
-
487
- // src/probes/link-integrity.ts
488
- var DEAD = ["", "#"];
489
- var linkIntegrity = {
490
- class: "link-integrity",
491
- id: "link-integrity",
492
- run: async (page, { memo, options, url }) => {
493
- const dead = stringsOption(options, "deadHrefs", DEAD);
494
- const ignore = stringsOption(options, "ignore", []);
495
- const checkExternal = flagOption(options, "checkExternal", false);
496
- const origin = new URL(url).origin;
497
- const hits = await collect(page, {
498
- kind: "links",
499
- selector: stringOption("link-integrity", options, "selector", 'a,[role="link"]')
500
- });
501
- const found = [];
502
- for (const hit of hits) {
503
- const href = hit.href;
504
- if (href === null || dead.includes(href.trim()) || href.trim().startsWith("javascript:")) {
505
- found.push({
506
- class: "link-integrity",
507
- evidence: `dead control: href ${href === null ? "absent" : `"${href}"`} on "${hit.text}"`,
508
- selector: hit.selector,
509
- severity: "major",
510
- url
511
- });
512
- continue;
513
- }
514
- const target = hit.resolved;
515
- if (!target.startsWith("http")) continue;
516
- if (ignore.some((pattern) => new RegExp(pattern).test(target))) continue;
517
- if (!checkExternal && new URL(target).origin !== origin) continue;
518
- const status = await statusOf(page, memo, target);
519
- if (status < 400) continue;
520
- found.push({
521
- class: "link-integrity",
522
- evidence: `${target} answered ${status}`,
523
- selector: hit.selector,
524
- severity: "blocking",
525
- url
526
- });
527
- }
528
- return found;
529
- }
530
- };
531
- var statusOf = async (page, memo, target) => {
532
- const key = `link-integrity:${target}`;
533
- const seen = memo.get(key);
534
- if (typeof seen === "number") return seen;
535
- let status;
536
- try {
537
- const head = await page.request.head(target, { failOnStatusCode: false });
538
- status = head.status() === 405 || head.status() === 501 ? (await page.request.get(target, { failOnStatusCode: false })).status() : head.status();
539
- } catch (error) {
540
- status = 599;
541
- memo.set(`${key}:why`, error.message);
542
- }
543
- memo.set(key, status);
544
- return status;
545
- };
546
-
547
- // src/probes/money-format.ts
548
- var AMOUNT = String.raw`\d{1,3}(?:[.,]\d{3})*(?:[.,]\d{1,2})?`;
549
- var MONEY = String.raw`[€$£¥₺]\s?${AMOUNT}|${AMOUNT}\s?(?:USD|EUR|GBP|TRY|JPY)\b`;
550
- var moneyFormat = {
551
- class: "content-integrity",
552
- id: "money-format",
553
- needs: (options) => {
554
- const accept = requireStrings("money-format", options, "accept");
555
- assertPatterns("money-format", accept, patternFlags("money-format", options));
556
- },
557
- run: async (page, { options, url }) => {
558
- const flags = patternFlags("money-format", options);
559
- const accept = requireStrings("money-format", options, "accept").map(
560
- (pattern) => new RegExp(`^(?:${pattern})$`, flags)
561
- );
562
- const hits = await collect(page, {
563
- flags,
564
- kind: "matches",
565
- patterns: [stringOption("money-format", options, "find", MONEY)],
566
- scope: stringOption("money-format", options, "scope", "")
567
- });
568
- return hits.filter((hit) => !accept.some((one) => one.test(hit.text.trim()))).map((hit) => ({
569
- class: "content-integrity",
570
- evidence: `"${hit.text}" is money in a shape this repo does not accept`,
571
- selector: hit.selector,
572
- severity: "major",
573
- url
574
- }));
575
- }
576
- };
577
-
578
- // src/probes/ops-leakage.ts
579
- var opsLeakage = {
580
- class: "ops-leakage",
581
- id: "ops-leakage",
582
- needs: (options) => {
583
- const patterns = requireStrings("ops-leakage", options, "patterns");
584
- assertPatterns("ops-leakage", patterns, patternFlags("ops-leakage", options));
585
- },
586
- run: async (page, { options, url }) => {
587
- const hits = await collect(page, {
588
- flags: patternFlags("ops-leakage", options),
589
- kind: "text",
590
- patterns: requireStrings("ops-leakage", options, "patterns"),
591
- scope: stringOption("ops-leakage", options, "scope", "")
592
- });
593
- return hits.map((hit) => ({
594
- class: "ops-leakage",
595
- evidence: `"${hit.text}" is offered to the customer, matching /${hit.pattern}/`,
596
- selector: hit.selector,
597
- severity: "blocking",
598
- url
599
- }));
600
- }
601
- };
602
-
603
- // src/probes/orphan-url.ts
604
- var MEMO = "orphan-url:linked";
605
- var linkedIn = (memo) => {
606
- const seen = memo.get(MEMO);
607
- if (seen instanceof Set) return seen;
608
- const fresh = /* @__PURE__ */ new Set();
609
- memo.set(MEMO, fresh);
610
- return fresh;
611
- };
612
- var bare = (url) => {
613
- try {
614
- const parsed = new URL(url);
615
- return `${parsed.origin}${parsed.pathname.replace(/\/index\.html?$/, "/")}`;
616
- } catch {
617
- return url;
618
- }
619
- };
620
- var orphanUrl = {
621
- class: "content-integrity",
622
- finish: ({ memo, options, urls }) => {
623
- if (urls.length < 2) return [];
624
- const linked = linkedIn(memo);
625
- const entry = stringsOption(options, "entry", []).map(bare);
626
- return urls.filter((url) => !linked.has(bare(url)) && !entry.includes(bare(url))).map((url) => ({
627
- class: "content-integrity",
628
- evidence: `no page in this walk links to ${bare(url)} \u2014 it is reachable only by being handed the URL`,
629
- severity: "major",
630
- url
631
- }));
632
- },
633
- id: "orphan-url",
634
- run: async (page, { memo, options, url }) => {
635
- const linked = linkedIn(memo);
636
- const here = bare(url);
637
- for (const hit of await collect(page, {
638
- kind: "links",
639
- selector: stringOption("orphan-url", options, "selector", 'a,[role="link"]')
640
- })) {
641
- if (hit.resolved === "") continue;
642
- const target = bare(hit.resolved);
643
- if (target !== here) linked.add(target);
644
- }
645
- return [];
646
- }
647
- };
648
-
649
- // src/probes/placeholder-asset.ts
650
- var placeholderAsset = {
651
- class: "placeholder-asset",
652
- id: "placeholder-asset",
653
- run: async (page, { options, url }) => {
654
- const maxRepeats = numberOption(options, "maxRepeats", 2);
655
- const signatures = stringsOption(options, "signatures", []);
656
- const flags = patternFlags("placeholder-asset", options);
657
- assertPatterns("placeholder-asset", signatures, flags);
658
- const hits = await collect(page, {
659
- assetSelector: stringOption("placeholder-asset", options, "assets", "img,svg"),
660
- kind: "assets",
661
- scope: stringOption("placeholder-asset", options, "scope", "body")
662
- });
663
- const named = hits.filter(
664
- (hit) => signatures.some(
665
- (pattern) => new RegExp(pattern, flags).test(`${hit.signature} ${hit.label}`)
666
- )
667
- ).map((hit) => ({
668
- class: "placeholder-asset",
669
- evidence: `asset matches a placeholder signature: ${hit.signature.slice(0, 120)}`,
670
- selector: hit.selector,
671
- severity: "major",
672
- url
673
- }));
674
- const bySignature = /* @__PURE__ */ new Map();
675
- for (const hit of hits) {
676
- bySignature.set(hit.signature, [...bySignature.get(hit.signature) ?? [], hit.selector]);
677
- }
678
- const repeated = [...bySignature.entries()].filter(([, selectors]) => selectors.length > maxRepeats).map(([signature, selectors]) => ({
679
- class: "placeholder-asset",
680
- evidence: `the same asset in ${selectors.length} slots, more than the ${maxRepeats} allowed \u2014 ${signature.slice(0, 120)}`,
681
- selector: selectors[0],
682
- severity: "major",
683
- url
684
- }));
685
- return [...named, ...repeated];
686
- }
687
- };
688
-
689
- // src/probes/stub-only-entity.ts
690
- var stubOnlyEntity = {
691
- class: "stub-only-entity",
692
- id: "stub-only-entity",
693
- needs: (options) => {
694
- requireStrings("stub-only-entity", options, "known");
695
- },
696
- run: async (page, { options, url }) => {
697
- const known = new Set(requireStrings("stub-only-entity", options, "known"));
698
- const attribute = stringOption("stub-only-entity", options, "attribute", "data-entity-id");
699
- const hits = await collect(page, {
700
- affordance: stringOption("stub-only-entity", options, "affordance", ""),
701
- attribute,
702
- kind: "entities",
703
- selector: stringOption("stub-only-entity", options, "selector", `[${attribute}]`)
704
- });
705
- return hits.filter((hit) => hit.id !== "" && hit.affordance && !known.has(hit.id)).map((hit) => ({
706
- class: "stub-only-entity",
707
- evidence: `"${hit.id}" can be bought here and is in no authoritative set of ${known.size} entities`,
708
- selector: hit.selector,
709
- severity: "blocking",
710
- url
711
- }));
712
- }
713
- };
714
-
715
- // src/probes/thin-page.ts
716
- var thinPage = {
717
- class: "content-integrity",
718
- id: "thin-page",
719
- needs: (options) => {
720
- requireNumber("thin-page", options, "minWords");
721
- },
722
- run: async (page, { options, url }) => {
723
- const minWords = requireNumber("thin-page", options, "minWords");
724
- const scope = stringOption("thin-page", options, "scope", "body");
725
- const hits = await collect(page, {
726
- headingSelector: stringOption("thin-page", options, "headingSelector", "h1,h2,h3,h4,h5,h6"),
727
- kind: "prose",
728
- mediaSelector: stringOption(
729
- "thin-page",
730
- options,
731
- "mediaSelector",
732
- "img,svg,video,iframe,canvas"
733
- ),
734
- selector: scope
735
- });
736
- return hits.filter((hit) => hit.words < minWords).map((hit) => ({
737
- class: "content-integrity",
738
- evidence: `${scope} renders ${hit.words} word(s), ${hit.headingWords} of them headings \u2014 the floor is ${minWords}`,
739
- ...hit.selector === "" ? {} : { selector: hit.selector },
740
- severity: "major",
741
- url
742
- }));
743
- }
744
- };
745
-
746
- // src/probes/index.ts
747
- var PROBES = [
748
- buyBoxAboveFold,
749
- emptySection,
750
- errorPageStatus,
751
- fabricatedClaim,
752
- fakeSession,
753
- lightOnLight,
754
- linkIntegrity,
755
- moneyFormat,
756
- opsLeakage,
757
- orphanUrl,
758
- placeholderAsset,
759
- stubOnlyEntity,
760
- thinPage
761
- ];
762
- var probeById = (id) => {
763
- const probe = PROBES.find((one) => one.id === id);
764
- if (probe === void 0) {
765
- throw new Error(
766
- `no probe called "${id}" \u2014 known probes: ${PROBES.map((one) => one.id).join(", ")}`
767
- );
768
- }
769
- return probe;
770
- };
771
- var DEFAULT_PROBES = PROBES.filter((one) => one.needs === void 0);
772
-
773
- // src/config.ts
774
- import { existsSync, readFileSync } from "fs";
775
- import { resolve } from "path";
776
- var VIEWPORT = { height: 900, width: 1440 };
777
- var WALK_REPORT = ".geonosis/walk-report.json";
778
- var WALK_DEFAULT = {
779
- options: {},
780
- probes: DEFAULT_PROBES.map((one) => one.id),
781
- report: WALK_REPORT,
782
- urls: [],
783
- viewport: VIEWPORT
784
- };
785
- var KNOWN = /* @__PURE__ */ new Set(["options", "probes", "report", "urls", "viewport"]);
786
- var ABOUT = {
787
- options: "object? keyed by probe id; each probe validates its own",
788
- probes: "string[]? the probe ids to run",
789
- report: "string? where the JSON report is written",
790
- urls: "string[]? the pages to walk",
791
- viewport: 'object? { "width": <number>, "height": <number> }'
792
- };
793
- var configShape = () => [
794
- "geonosis-walk reads geonosis.json",
795
- "",
796
- 'geonosis.json \u2192 "walk" every key optional, every default a contract',
797
- ...[...KNOWN].toSorted().map((key) => ` ${key.padEnd(11)}${ABOUT[key] ?? ""}`),
798
- "",
799
- "A key outside this list is REFUSED by name: a misspelling accepted in silence is a probe nobody",
800
- "is running against a page nobody is walking."
801
- ].join("\n");
802
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
803
- var readViewport = (value) => {
804
- if (value === void 0) return VIEWPORT;
805
- if (!isRecord(value) || typeof value.height !== "number" || typeof value.width !== "number") {
806
- throw new WalkError('walk.viewport must be { "width": <number>, "height": <number> }');
807
- }
808
- return { height: value.height, width: value.width };
809
- };
810
- var parseViewport = (value) => {
811
- const found = /^(\d+)x(\d+)$/.exec(value.trim());
812
- if (found?.[1] === void 0 || found[2] === void 0) {
813
- throw new WalkError(`"${value}" is not a viewport \u2014 write it as WIDTHxHEIGHT, e.g. 390x844`);
814
- }
815
- return { height: Number(found[2]), width: Number(found[1]) };
816
- };
817
- var readStrings = (value, name, fallback) => {
818
- if (value === void 0) return fallback;
819
- if (!Array.isArray(value) || value.some((one) => typeof one !== "string")) {
820
- throw new WalkError(`walk.${name} must be a list of strings`);
821
- }
822
- return value;
823
- };
824
- var loadWalkConfig = (file) => {
825
- if (!existsSync(file)) return WALK_DEFAULT;
826
- let parsed;
827
- try {
828
- parsed = JSON.parse(readFileSync(file, "utf8"));
829
- } catch (error) {
830
- throw new WalkError(`${file} is not valid JSON: ${error.message}`);
831
- }
832
- if (!isRecord(parsed)) throw new WalkError(`${file} must hold an object`);
833
- const block = parsed.walk;
834
- if (block === void 0) return WALK_DEFAULT;
835
- if (!isRecord(block)) throw new WalkError("walk must be an object");
836
- for (const key of Object.keys(block)) {
837
- if (!KNOWN.has(key)) throw new WalkError(`walk.${key} is not a key of the walk block`);
838
- }
839
- const options = block.options ?? {};
840
- if (!isRecord(options)) throw new WalkError("walk.options must be an object keyed by probe id");
841
- for (const [id, one] of Object.entries(options)) {
842
- if (!isRecord(one)) throw new WalkError(`walk.options.${id} must be an object`);
843
- }
844
- return {
845
- options,
846
- probes: readStrings(block.probes, "probes", WALK_DEFAULT.probes),
847
- report: typeof block.report === "string" ? block.report : WALK_REPORT,
848
- urls: readStrings(block.urls, "urls", []),
849
- viewport: readViewport(block.viewport)
850
- };
851
- };
852
- var configPath = (cwd, given) => resolve(cwd, given ?? "geonosis.json");
853
-
854
- // src/walk.ts
855
- var launch = async () => {
856
- let chromium;
857
- try {
858
- ;
859
- ({ chromium } = await import("playwright"));
860
- } catch (error) {
861
- throw new WalkError(
862
- `playwright is a peer dependency of @geonosis/walk and is not installed: ${error.message}`
863
- );
864
- }
865
- try {
866
- return await chromium.launch({ headless: true });
867
- } catch (error) {
868
- throw new WalkError(
869
- `chromium would not launch \u2014 \`npx playwright install chromium\`: ${error.message}`
870
- );
871
- }
872
- };
873
- var walk = async ({
874
- browser,
875
- options = {},
876
- probes,
877
- urls,
878
- viewport
879
- }) => {
880
- if (urls.length === 0) throw new WalkError("no URL to walk");
881
- for (const probe of probes) probe.needs?.(options[probe.id] ?? {});
882
- const startedAt = (/* @__PURE__ */ new Date()).toISOString();
883
- const own = browser ?? await launch();
884
- const memo = /* @__PURE__ */ new Map();
885
- const pages = [];
886
- try {
887
- for (const url of urls) {
888
- const context = await own.newContext({ viewport });
889
- try {
890
- const page = await context.newPage();
891
- const response = await page.goto(url).catch((error) => {
892
- throw new WalkError(`${url} could not be opened: ${error.message}`);
893
- });
894
- if (response === null) throw new WalkError(`${url} answered nothing`);
895
- if (response.status() >= 400) {
896
- throw new WalkError(`${url} answered ${response.status()}`);
897
- }
898
- const findings = [];
899
- for (const probe of probes) {
900
- findings.push(
901
- ...await probe.run(page, {
902
- memo,
903
- options: options[probe.id] ?? {},
904
- status: response.status(),
905
- url,
906
- viewport
907
- })
908
- );
909
- }
910
- pages.push({ findings, url });
911
- } finally {
912
- await context.close();
913
- }
914
- }
915
- } finally {
916
- if (browser === void 0) await own.close();
917
- }
918
- for (const probe of probes) {
919
- for (const finding of probe.finish?.({ memo, options: options[probe.id] ?? {}, urls }) ?? []) {
920
- const page = pages.find((one) => one.url === finding.url);
921
- if (page === void 0) pages.push({ findings: [finding], url: finding.url });
922
- else page.findings.push(finding);
923
- }
924
- }
925
- const counts = {};
926
- for (const probe of probes) counts[probe.class] = 0;
927
- for (const page of pages) {
928
- for (const finding of page.findings) {
929
- counts[finding.class] = (counts[finding.class] ?? 0) + 1;
930
- }
931
- }
932
- return {
933
- counts,
934
- finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
935
- pages,
936
- probes: probes.map((one) => one.id),
937
- startedAt,
938
- viewport
939
- };
940
- };
941
- var findingsIn = (report) => report.pages.reduce((total, page) => total + page.findings.length, 0);
942
-
943
- export {
944
- WalkError,
945
- PROBES,
946
- probeById,
947
- DEFAULT_PROBES,
948
- WALK_REPORT,
949
- WALK_DEFAULT,
950
- configShape,
951
- parseViewport,
952
- loadWalkConfig,
953
- configPath,
954
- walk,
955
- findingsIn
956
- };