Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mobile-audit.ts

483 lines16.9 KB

1#!/usr/bin/env node
2import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { Argument, Command, Flag } from "effect/cli";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15​
16import {
17 renderBeforeAfterComparison,
18 renderSingleAnnotatedImage,
19} from "./mobile-audit/annotate.ts";
20import {
21 AgentDeviceEnvelopeSchema,
22 AuditCaptureSchema,
23 AuditPayloadSchema,
24 AuditPlatformSchema,
25 RawSnapshotDataSchema,
26 buildOverlayBoxes,
27 diffAuditCaptures,
28 findingTag,
29 isPlatformNoise,
30 renderMarkdownReport,
31 resolveViewport,
32 unitForPlatform,
33 type AuditCapture,
34 type AuditPlatform,
35 type ScreenDiff,
36} from "./mobile-audit/diff.ts";
37​
38class MobileAuditError extends Schema.TaggedError<
39 MobileAuditError,
40 { readonly brand: unique symbol }
41>()("MobileAuditError", {
42 operation: Schema.String,
43 detail: Schema.String,
44 cause: Schema.optional(Schema.Defect()),
45}) {
46 override get message(): string {
47 return `${this.operation}: ${this.detail}`;
48 }
50​
51const decodeEnvelope = Schema.decodeUnknownEffect(Schema.fromJsonString(AgentDeviceEnvelopeSchema));
52const decodeAuditPayload = Schema.decodeUnknownEffect(AuditPayloadSchema);
53const decodeRawSnapshot = Schema.decodeUnknownEffect(RawSnapshotDataSchema);
54const decodeAuditCapture = Schema.decodeUnknownEffect(Schema.fromJsonString(AuditCaptureSchema));
55const encodeAuditCapture = Schema.encodeEffect(fromJsonStringPretty(AuditCaptureSchema));
56const encodePrettyJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown));
57​
58const execAgentDevice = Effect.fn("mobileAudit.execAgentDevice")(function* (
59 bin: Option.Option<string>,
60 args: ReadonlyArray<string>,
61) {
62 const path = yield* Path.Path;
63 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
64 const execPath = yield* HostProcess.ExecutablePath;
65 const defaultEntry = path.resolve(
66 import.meta.dirname,
67 "../scripts/node_modules/agent-device/bin/agent-device.mjs",
68 );
69 const program = Option.isSome(bin) ? bin.value : execPath;
70 const fullArgs = Option.isSome(bin) ? [...args] : [defaultEntry, ...args];
71​
72 const child = yield* spawner.spawn(
73 ChildProcess.make(program, fullArgs, {
74 stdin: "ignore",
75 stdout: "pipe",
76 stderr: "pipe",
77 }),
78 );
79 const [stdout, stderr, exitCode] = yield* Effect.all(
80 [
81 Stream.mkString(Stream.decodeText(child.stdout)),
82 Stream.mkString(Stream.decodeText(child.stderr)),
83 child.exitCode,
84 ],
85 { concurrency: "unbounded" },
86 );
87 if (exitCode !== 0) {
88 return yield* new MobileAuditError({
89 operation: `agent-device ${args[0] ?? ""}`.trim(),
90 detail: `exited with ${exitCode}: ${stderr.trim().slice(-600)}`,
91 });
92 }
93 return stdout;
94}, Effect.scoped);
95​
96const decodeAgentDeviceJson = <S extends Schema.Top>(
97 schema: S,
98 decodeData: (input: unknown) => Effect.Effect<S["Type"], Schema.SchemaError>,
99) =>
100 Effect.fn("mobileAudit.decodeJson")(function* (raw: string, label: string) {
101 const envelope = yield* decodeEnvelope(raw).pipe(
102 Effect.mapError(
103 (cause) =>
104 new MobileAuditError({
105 operation: label,
106 detail: "invalid JSON response",
107 cause,
108 }),
109 ),
110 );
111 if (envelope.success === false) {
112 const hint = envelope.error?.hint ? ` (${envelope.error.hint})` : "";
113 return yield* new MobileAuditError({
114 operation: label,
115 detail: `${envelope.error?.message ?? "unknown error"}${hint}`,
116 });
117 }
118 const payload = envelope.data ?? envelope;
119 return yield* decodeData(payload).pipe(
120 Effect.mapError(
121 (cause) =>
122 new MobileAuditError({
123 operation: label,
124 detail: "unexpected payload shape",
125 cause,
126 }),
127 ),
128 );
129 });
130​
131const decodeAuditJson = decodeAgentDeviceJson(AuditPayloadSchema, decodeAuditPayload);
132const decodeRawSnapshotJson = decodeAgentDeviceJson(RawSnapshotDataSchema, decodeRawSnapshot);
133​
134const runCapture = Effect.fn("mobileAudit.capture")(function* (input: {
135 readonly platform: AuditPlatform;
136 readonly screen: string;
137 readonly out: string;
138 readonly agentDevice: Option.Option<string>;
139 readonly agentDeviceArgs: ReadonlyArray<string>;
140}) {
141 const fs = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
143 const cwd = yield* HostProcess.WorkingDirectory;
144 const outRoot = path.resolve(cwd, input.out);
145 const platformDir = path.join(outRoot, input.platform);
146 yield* fs.makeDirectory(platformDir, { recursive: true });
147​
148 const pngPath = path.join(platformDir, `${input.screen}.png`);
149 const screenshotArgs =
150 input.platform === "ios"
151 ? ["screenshot", "--pixel-density", "3", pngPath, ...input.agentDeviceArgs]
152 : ["screenshot", pngPath, ...input.agentDeviceArgs];
153 yield* execAgentDevice(input.agentDevice, screenshotArgs);
154​
155 const auditRaw = yield* execAgentDevice(input.agentDevice, [
156 "audit",
157 "--json",
158 ...input.agentDeviceArgs,
159 ]);
160 const auditData = yield* decodeAuditJson(auditRaw, "agent-device audit");
161​
162 const snapRaw = yield* execAgentDevice(input.agentDevice, [
163 "snapshot",
164 "--raw",
165 "--json",
166 ...input.agentDeviceArgs,
167 ]);
168 const snapData = yield* decodeRawSnapshotJson(snapRaw, "agent-device snapshot");
169​
170 const viewport = resolveViewport({}, snapData);
171 const capture: AuditCapture = {
172 platform: input.platform,
173 screen: input.screen,
174 ...(viewport === undefined ? {} : { viewport }),
175 pixelDensity: input.platform === "android" ? (snapData.androidSnapshot?.pixelDensity ?? 1) : 1,
176 findings: auditData.findings ?? [],
177 ...(auditData.guidance === undefined ? {} : { guidance: auditData.guidance }),
178 ...(auditData.limitations === undefined ? {} : { limitations: auditData.limitations }),
179 };
180​
181 yield* fs.writeFileString(path.join(platformDir, `${input.screen}.raw.json`), snapRaw);
182 const encodedCapture = yield* encodeAuditCapture(capture);
183 yield* fs.writeFileString(
184 path.join(platformDir, `${input.screen}.audit.json`),
185 `${encodedCapture}\n`,
186 );
187​
188 const unit = unitForPlatform(input.platform);
189 yield* Console.log(
190 `[${input.platform}] ${input.screen}: ${capture.findings.length} finding(s) -> ${pngPath}`,
191 );
192 for (const finding of capture.findings) {
193 yield* Console.log(
194 ` [${finding.kind}] ${finding.role} ${findingTag(finding, capture.pixelDensity, unit)} ${finding.label ? `"${finding.label}"` : "(unnamed)"}`,
195 );
196 }
197});
198​
199const listCapturedScreens = Effect.fn("mobileAudit.listCapturedScreens")(function* (
200 rootDir: string,
201) {
202 const fs = yield* FileSystem.FileSystem;
203 const path = yield* Path.Path;
204 const results: Array<{ readonly platform: AuditPlatform; readonly screen: string }> = [];
205 for (const platform of AuditPlatformSchema.literals) {
206 const dir = path.join(rootDir, platform);
207 if (!(yield* fs.exists(dir))) continue;
208 const files = (yield* fs.readDirectory(dir)).filter((f) => f.endsWith(".audit.json")).sort();
209 for (const file of files) {
210 results.push({ platform, screen: file.replace(/\.audit\.json$/, "") });
211 }
212 }
213 return results;
214});
215​
216const readCaptureSet = Effect.fn("mobileAudit.readCaptureSet")(function* (
217 rootDir: string,
218 platform: AuditPlatform,
219 screen: string,
220) {
221 const fs = yield* FileSystem.FileSystem;
222 const path = yield* Path.Path;
223 const base = path.join(rootDir, platform, screen);
224 const auditPath = `${base}.audit.json`;
225 const capture = yield* fs.readFileString(auditPath).pipe(
226 Effect.flatMap(decodeAuditCapture),
227 Effect.mapError(
228 (cause) =>
229 new MobileAuditError({
230 operation: "readCaptureSet",
231 detail: `failed to read ${auditPath}`,
232 cause,
233 }),
234 ),
235 );
236 const rawPath = `${base}.raw.json`;
237 const raw = (yield* fs.exists(rawPath))
238 ? yield* fs
239 .readFileString(rawPath)
240 .pipe(Effect.flatMap((content) => decodeRawSnapshotJson(content, rawPath)))
241 : undefined;
242 return {
243 capture,
244 raw,
245 pngPath: `${base}.png`,
246 };
247});
248​
249export const runCompare = Effect.fn("mobileAudit.compare")(function* (input: {
250 readonly before: string;
251 readonly after: string;
252 readonly out: string;
253 readonly beforeLabel: string;
254 readonly afterLabel: string;
255 readonly all: boolean;
256 readonly failOnRegression: boolean;
257}) {
258 const fs = yield* FileSystem.FileSystem;
259 const path = yield* Path.Path;
260 const cwd = yield* HostProcess.WorkingDirectory;
261 const beforeDir = path.resolve(cwd, input.before);
262 const afterDir = path.resolve(cwd, input.after);
263 const outDir = path.resolve(cwd, input.out);
264​
265 yield* fs.makeDirectory(outDir, { recursive: true });
266 const [beforeScreens, afterScreens] = yield* Effect.all([
267 listCapturedScreens(beforeDir),
268 listCapturedScreens(afterDir),
269 ]);
270 const afterSet = new Set(afterScreens.map((s) => `${s.platform}/${s.screen}`));
271 const missingScreens = beforeScreens.filter((s) => !afterSet.has(`${s.platform}/${s.screen}`));
272 const pairs = beforeScreens.filter((s) => afterSet.has(`${s.platform}/${s.screen}`));
273​
274 if (pairs.length === 0) {
275 return yield* new MobileAuditError({
276 operation: "compare",
277 detail: `no matching <platform>/<screen>.audit.json captures in both ${beforeDir} and ${afterDir}`,
278 });
279 }
280​
281 const diffs: Array<ScreenDiff & { readonly imagePath?: string }> = [];
282 for (const pair of pairs) {
283 const [before, after] = yield* Effect.all([
284 readCaptureSet(beforeDir, pair.platform, pair.screen),
285 readCaptureSet(afterDir, pair.platform, pair.screen),
286 ]);
287 const diff = diffAuditCaptures({
288 before: before.capture,
289 after: after.capture,
290 beforeRaw: before.raw,
291 afterRaw: after.raw,
292 });
293​
294 const hasDelta = diff.fixed.length > 0 || diff.regressions.length > 0;
295 const [hasBeforePng, hasAfterPng] = yield* Effect.all([
296 fs.exists(before.pngPath),
297 fs.exists(after.pngPath),
298 ]);
299 let imagePath: string | undefined;
300 if ((hasDelta || input.all) && hasBeforePng && hasAfterPng) {
301 const { beforeBoxes, afterBoxes } = buildOverlayBoxes(
302 diff,
303 after.capture.pixelDensity || 1,
304 before.capture.pixelDensity || 1,
305 );
306 const outPng = path.join(outDir, `${pair.platform}-${pair.screen}.png`);
307 yield* renderBeforeAfterComparison({
308 beforePng: before.pngPath,
309 beforeBoxes,
310 beforeTitle: `${input.beforeLabel} · ${diff.beforeCount} finding(s)`,
311 beforeViewport: resolveViewport(before.capture, before.raw),
312 afterPng: after.pngPath,
313 afterBoxes,
314 afterTitle: `${input.afterLabel} · ${diff.afterCount} finding(s) (${diff.fixed.length} fixed, ${diff.regressions.length} new)`,
315 afterBannerBg: diff.regressions.length > 0 ? "#b91c1c" : "#15803d",
316 afterViewport: resolveViewport(after.capture, after.raw),
317 outPath: outPng,
318 });
319 imagePath = outPng;
320 }
321​
322 diffs.push({ ...diff, ...(imagePath === undefined ? {} : { imagePath }) });
323 }
324​
325 const markdown = renderMarkdownReport(diffs);
326 const diffJson = yield* encodePrettyJson(diffs);
327 yield* fs.writeFileString(path.join(outDir, "diff.json"), `${diffJson}\n`);
328 yield* fs.writeFileString(path.join(outDir, "report.md"), markdown);
329 yield* Console.log(markdown.trimEnd());
330​
331 const totalRegressions = diffs.reduce((n, d) => n + d.regressions.length, 0);
332 const failureReasons: string[] = [];
333 if (totalRegressions > 0) {
334 failureReasons.push(`${totalRegressions} accessibility regression(s) detected`);
335 }
336 if (missingScreens.length > 0) {
337 failureReasons.push(
338 `${missingScreens.length} baseline screen(s) missing from candidate captures: ${missingScreens
339 .map((s) => `${s.platform}/${s.screen}`)
340 .join(", ")}`,
341 );
342 }
343 if (input.failOnRegression && failureReasons.length > 0) {
344 return yield* new MobileAuditError({
345 operation: "compare",
346 detail: failureReasons.join("; "),
347 });
348 }
349});
350​
351const runReport = Effect.fn("mobileAudit.report")(function* (input: {
352 readonly dir: string;
353 readonly out: string;
354}) {
355 const fs = yield* FileSystem.FileSystem;
356 const path = yield* Path.Path;
357 const cwd = yield* HostProcess.WorkingDirectory;
358 const dir = path.resolve(cwd, input.dir);
359 const outDir = path.resolve(cwd, input.out);
360 yield* fs.makeDirectory(outDir, { recursive: true });
361​
362 const screens = yield* listCapturedScreens(dir);
363 const lines: string[] = [
364 "### Mobile accessibility audit report (`agent-device audit`)",
365 "",
366 "| Platform | Screen | Findings |",
367 "| --- | --- | ---: |",
368 ];
369​
370 for (const entry of screens) {
371 const { capture, raw, pngPath } = yield* readCaptureSet(dir, entry.platform, entry.screen);
372 const viewport = resolveViewport(capture, raw);
373 const findings = capture.findings.filter(
374 (f) => !isPlatformNoise(f, capture.platform, viewport),
375 );
376 lines.push(`| ${entry.platform} | \`${entry.screen}\` | ${findings.length} |`);
377​
378 if (findings.length > 0 && (yield* fs.exists(pngPath))) {
379 const unit = unitForPlatform(entry.platform);
380 const boxes = findings
381 .filter((f) => f.rect !== undefined)
382 .map((f) => ({
383 ...f.rect!,
384 tag: findingTag(f, capture.pixelDensity || 1, unit),
385 color: "#ef4444",
386 }));
387 const outPng = path.join(outDir, `${entry.platform}-${entry.screen}.png`);
388 yield* renderSingleAnnotatedImage({
389 pngPath,
390 boxes,
391 bannerText: `${entry.platform} · ${entry.screen} · ${findings.length} finding(s)`,
392 bannerBg: "#b91c1c",
393 viewport,
394 outPath: outPng,
395 });
396 }
397 }
398​
399 const markdown = `${lines.join("\n")}\n`;
400 yield* fs.writeFileString(path.join(outDir, "report.md"), markdown);
401 yield* Console.log(markdown.trimEnd());
402});
403​
404const captureCommand = Command.make(
405 "capture",
406 {
407 platform: Flag.Literals("platform", AuditPlatformSchema.literals).pipe(
408 Flag.withDescription("Target mobile platform (ios or android)."),
409 ),
410 screen: Flag.String("screen").pipe(Flag.withDescription("Screen identifier for output files.")),
411 out: Flag.String("out").pipe(Flag.withDescription("Directory to write captured artifacts.")),
412 agentDevice: Flag.String("agent-device").pipe(
413 Flag.withDescription(
414 "Optional path to an agent-device launcher; defaults to the workspace CLI.",
415 ),
416 Flag.optional,
417 ),
418 agentDeviceArgs: Argument.String("agent-device-arg").pipe(
419 Argument.withDescription("Extra arguments forwarded to agent-device (pass after `--`)."),
420 Argument.variadic(),
421 ),
422 },
423 (input) => runCapture(input),
424).pipe(
425 Command.withDescription(
426 "Capture a screenshot, native agent-device audit JSON, and raw accessibility snapshot.",
427 ),
428);
429​
430const compareCommand = Command.make(
431 "compare",
432 {
433 before: Flag.String("before").pipe(Flag.withDescription("Baseline capture directory.")),
434 after: Flag.String("after").pipe(Flag.withDescription("Candidate capture directory.")),
435 out: Flag.String("out").pipe(
436 Flag.withDescription("Output directory for diff.json, report.md, and comparison PNGs."),
437 ),
438 beforeLabel: Flag.String("before-label").pipe(
439 Flag.withDescription("Banner label for the before panel."),
440 Flag.withDefault("BEFORE (base)"),
441 ),
442 afterLabel: Flag.String("after-label").pipe(
443 Flag.withDescription("Banner label for the after panel."),
444 Flag.withDefault("AFTER (head)"),
445 ),
446 all: Flag.Boolean("all").pipe(
447 Flag.withDescription("Render comparison PNGs even for screens with no delta."),
448 Flag.withDefault(false),
449 ),
450 failOnRegression: Flag.Boolean("fail-on-regression").pipe(
451 Flag.withDescription("Exit non-zero if any screen introduces new findings."),
452 Flag.withDefault(false),
453 ),
454 },
455 (input) => runCompare(input),
456).pipe(
457 Command.withDescription(
458 "Diff two audit capture directories and render annotated side-by-side PNGs and Markdown.",
459 ),
460);
461​
462const reportCommand = Command.make(
463 "report",
464 {
465 dir: Flag.String("dir").pipe(Flag.withDescription("Capture directory to annotate.")),
466 out: Flag.String("out").pipe(
467 Flag.withDescription("Output directory for report.md and annotated PNGs."),
468 ),
469 },
470 (input) => runReport(input),
471).pipe(Command.withDescription("Annotate a single audit capture directory with hit-box overlays."));
472​
473const mobileAuditCommand = Command.make("mobile-audit").pipe(
474 Command.withDescription("Capture, diff, and visualize mobile accessibility audits."),
475 Command.withSubcommands([captureCommand, compareCommand, reportCommand]),
476);
477​
478if (import.meta.main) {
479 Command.run(mobileAuditCommand, { version: "0.0.0" }).pipe(
480 Effect.provide(NodeServices.layer),
481 NodeRuntime.runMain,
482 );