Open History to see the last commit
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 }
49}
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
249const 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 pairs = beforeScreens.filter((s) => afterSet.has(`${s.platform}/${s.screen}`));
272
273 if (pairs.length === 0) {
274 return yield* new MobileAuditError({
275 operation: "compare",
276 detail: `no matching <platform>/<screen>.audit.json captures in both ${beforeDir} and ${afterDir}`,
277 });
278 }
279
280 const diffs: Array<ScreenDiff & { readonly imagePath?: string }> = [];
281 for (const pair of pairs) {
282 const [before, after] = yield* Effect.all([
283 readCaptureSet(beforeDir, pair.platform, pair.screen),
284 readCaptureSet(afterDir, pair.platform, pair.screen),
285 ]);
286 const diff = diffAuditCaptures({
287 before: before.capture,
288 after: after.capture,
289 beforeRaw: before.raw,
290 afterRaw: after.raw,
291 });
292
293 const hasDelta = diff.fixed.length > 0 || diff.regressions.length > 0;
294 const [hasBeforePng, hasAfterPng] = yield* Effect.all([
295 fs.exists(before.pngPath),
296 fs.exists(after.pngPath),
297 ]);
298 let imagePath: string | undefined;
299 if ((hasDelta || input.all) && hasBeforePng && hasAfterPng) {
300 const { beforeBoxes, afterBoxes } = buildOverlayBoxes(
301 diff,
302 after.capture.pixelDensity || 1,
303 before.capture.pixelDensity || 1,
304 );
305 const outPng = path.join(outDir, `${pair.platform}-${pair.screen}.png`);
306 yield* renderBeforeAfterComparison({
307 beforePng: before.pngPath,
308 beforeBoxes,
309 beforeTitle: `${input.beforeLabel} · ${diff.beforeCount} finding(s)`,
310 beforeViewport: resolveViewport(before.capture, before.raw),
311 afterPng: after.pngPath,
312 afterBoxes,
313 afterTitle: `${input.afterLabel} · ${diff.afterCount} finding(s) (${diff.fixed.length} fixed, ${diff.regressions.length} new)`,
314 afterBannerBg: diff.regressions.length > 0 ? "#b91c1c" : "#15803d",
315 afterViewport: resolveViewport(after.capture, after.raw),
316 outPath: outPng,
317 });
318 imagePath = outPng;
319 }
320
321 diffs.push({ ...diff, ...(imagePath === undefined ? {} : { imagePath }) });
322 }
323
324 const markdown = renderMarkdownReport(diffs);
325 const diffJson = yield* encodePrettyJson(diffs);
326 yield* fs.writeFileString(path.join(outDir, "diff.json"), `${diffJson}\n`);
327 yield* fs.writeFileString(path.join(outDir, "report.md"), markdown);
328 yield* Console.log(markdown.trimEnd());
329
330 const totalRegressions = diffs.reduce((n, d) => n + d.regressions.length, 0);
331 if (input.failOnRegression && totalRegressions > 0) {
332 return yield* new MobileAuditError({
333 operation: "compare",
334 detail: `${totalRegressions} accessibility regression(s) detected`,
335 });
336 }
337});
338
339const runReport = Effect.fn("mobileAudit.report")(function* (input: {
340 readonly dir: string;
341 readonly out: string;
342}) {
343 const fs = yield* FileSystem.FileSystem;
344 const path = yield* Path.Path;
345 const cwd = yield* HostProcess.WorkingDirectory;
346 const dir = path.resolve(cwd, input.dir);
347 const outDir = path.resolve(cwd, input.out);
348 yield* fs.makeDirectory(outDir, { recursive: true });
349
350 const screens = yield* listCapturedScreens(dir);
351 const lines: string[] = [
352 "### Mobile accessibility audit report (`agent-device audit`)",
353 "",
354 "| Platform | Screen | Findings |",
355 "| --- | --- | ---: |",
356 ];
357
358 for (const entry of screens) {
359 const { capture, raw, pngPath } = yield* readCaptureSet(dir, entry.platform, entry.screen);
360 const viewport = resolveViewport(capture, raw);
361 const findings = capture.findings.filter(
362 (f) => !isPlatformNoise(f, capture.platform, viewport),
363 );
364 lines.push(`| ${entry.platform} | \`${entry.screen}\` | ${findings.length} |`);
365
366 if (findings.length > 0 && (yield* fs.exists(pngPath))) {
367 const unit = unitForPlatform(entry.platform);
368 const boxes = findings
369 .filter((f) => f.rect !== undefined)
370 .map((f) => ({
371 ...f.rect!,
372 tag: findingTag(f, capture.pixelDensity || 1, unit),
373 color: "#ef4444",
374 }));
375 const outPng = path.join(outDir, `${entry.platform}-${entry.screen}.png`);
376 yield* renderSingleAnnotatedImage({
377 pngPath,
378 boxes,
379 bannerText: `${entry.platform} · ${entry.screen} · ${findings.length} finding(s)`,
380 bannerBg: "#b91c1c",
381 viewport,
382 outPath: outPng,
383 });
384 }
385 }
386
387 const markdown = `${lines.join("\n")}\n`;
388 yield* fs.writeFileString(path.join(outDir, "report.md"), markdown);
389 yield* Console.log(markdown.trimEnd());
390});
391
392const captureCommand = Command.make(
393 "capture",
394 {
395 platform: Flag.Literals("platform", AuditPlatformSchema.literals).pipe(
396 Flag.withDescription("Target mobile platform (ios or android)."),
397 ),
398 screen: Flag.String("screen").pipe(Flag.withDescription("Screen identifier for output files.")),
399 out: Flag.String("out").pipe(Flag.withDescription("Directory to write captured artifacts.")),
400 agentDevice: Flag.String("agent-device").pipe(
401 Flag.withDescription(
402 "Optional path to an agent-device launcher; defaults to the workspace CLI.",
403 ),
404 Flag.optional,
405 ),
406 agentDeviceArgs: Argument.String("agent-device-arg").pipe(
407 Argument.withDescription("Extra arguments forwarded to agent-device (pass after `--`)."),
408 Argument.variadic(),
409 ),
410 },
411 (input) => runCapture(input),
412).pipe(
413 Command.withDescription(
414 "Capture a screenshot, native agent-device audit JSON, and raw accessibility snapshot.",
415 ),
416);
417
418const compareCommand = Command.make(
419 "compare",
420 {
421 before: Flag.String("before").pipe(Flag.withDescription("Baseline capture directory.")),
422 after: Flag.String("after").pipe(Flag.withDescription("Candidate capture directory.")),
423 out: Flag.String("out").pipe(
424 Flag.withDescription("Output directory for diff.json, report.md, and comparison PNGs."),
425 ),
426 beforeLabel: Flag.String("before-label").pipe(
427 Flag.withDescription("Banner label for the before panel."),
428 Flag.withDefault("BEFORE (base)"),
429 ),
430 afterLabel: Flag.String("after-label").pipe(
431 Flag.withDescription("Banner label for the after panel."),
432 Flag.withDefault("AFTER (head)"),
433 ),
434 all: Flag.Boolean("all").pipe(
435 Flag.withDescription("Render comparison PNGs even for screens with no delta."),
436 Flag.withDefault(false),
437 ),
438 failOnRegression: Flag.Boolean("fail-on-regression").pipe(
439 Flag.withDescription("Exit non-zero if any screen introduces new findings."),
440 Flag.withDefault(false),
441 ),
442 },
443 (input) => runCompare(input),
444).pipe(
445 Command.withDescription(
446 "Diff two audit capture directories and render annotated side-by-side PNGs and Markdown.",
447 ),
448);
449
450const reportCommand = Command.make(
451 "report",
452 {
453 dir: Flag.String("dir").pipe(Flag.withDescription("Capture directory to annotate.")),
454 out: Flag.String("out").pipe(
455 Flag.withDescription("Output directory for report.md and annotated PNGs."),
456 ),
457 },
458 (input) => runReport(input),
459).pipe(Command.withDescription("Annotate a single audit capture directory with hit-box overlays."));
460
461const mobileAuditCommand = Command.make("mobile-audit").pipe(
462 Command.withDescription("Capture, diff, and visualize mobile accessibility audits."),
463 Command.withSubcommands([captureCommand, compareCommand, reportCommand]),
464);
465
466if (import.meta.main) {
467 Command.run(mobileAuditCommand, { version: "0.0.0" }).pipe(
468 Effect.provide(NodeServices.layer),
469 NodeRuntime.runMain,
470 );
471}