/** * NO PERSON-READ WORDS IN KOTLIN: every string a person reads in Cotton's apps on * Android comes from the core (`shell.lines`, the kit's lines, an answer's * own words), never a Kotlin literal — the Android twin of iOS's * `swift_literals` guard (crates/cotton-core/tests/swift_literals.rs). * * It tokenizes every `.kt` file under apps/android (the shared shell and every * app) as text, skipping * comments and the tests' own sources (`src/test`, `src/test<App>`, `src/androidTest`: synthetic trees, * fixtures and the walker, nothing a person is shown), and flags a string literal that is English (two letters in a row * once `$name` and `${…}` templates are taken out) when it is * - the first argument of a call that draws words (`Text`, `FitText`, * `WayOut`, `ItemTile`, `ViewTile`, …), or * - assigned to a property a screen reader says (`contentDescription = "…"`, * as a named argument or inside `semantics { }`), even one word, or * - sentence-shaped anywhere: two or more words of two or more letters, or * ending in `.`, `?` or `…`. * Inside a developer-only call (`error`, `check`, `require`, `Log.*`, an * exception, `Regex`) a literal is never a person's. * * The allow-list is EMPTY and stays so: a word a person reads that the core * does not answer is a core gap, said in the lane's notes, not a literal here. * The scan must also SEE literals: a sweep over a moved folder that reads * nothing passes over nothing. */import { existsSync, readdirSync, readFileSync, statSync } from"node:fs";import { dirname, join, relative, resolve, sep } from"node:path";import { fileURLToPath } from"node:url";import { describe, expect, it } from"vitest";const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");const APP = join(REPO_ROOT, "apps", "android");/** Calls whose first argument is drawn for a person. */const DRAWN = newSet(["Text", "FitText", "WayOut", "ItemTile", "ViewTile", "FaceSwatch", "Toast", "makeText", "setTitle", "setText"]);/** Calls whose literals are the developer's: never a person's words. */const DEVELOPER_ONLY = newSet(["error", "check", "require", "checkNotNull", "requireNotNull", "TODO", "println", "print","d", "e", "w", "i", "v", "wtf", "Regex", "toRegex","IllegalStateException", "IllegalArgumentException", "RuntimeException", "Exception", "CoreException", "NativeOpenException",]);/** The allow-list: empty, and a test below keeps it so. */const ALLOWED: ReadonlyArray<string> = [];exporttypeLiteral = { file: string; line: number; text: string; call: string | null; argument: number; inside: string[]; assignedTo: string | null };/** Properties a screen reader says aloud: a literal assigned to one is a person's words, even a single word. */const SPOKEN = newSet(["contentDescription"]);typeFrame = { open: string; name: string | null; argument: number };/** Every string literal in Kotlin source, with the call it is an argument of and every call around it. */exportfunction literals(source: string, file = "<source>"): Literal[] {const found: Literal[] = [];const stack: Frame[] = [];let closed: string | null = null;let i = 0;let line = 1;const n = source.length;const identBefore = (at: number): string | null => {let j = at - 1;while (j >= 0 && /\s/.test(source[j])) j--;let end = j + 1;while (j >= 0 && /[A-Za-z0-9_]/.test(source[j])) j--;const name = source.slice(j + 1, end);return name && /^[A-Za-z_]/.test(name) ? name : null; };/** The property a literal starting at `at` is assigned to (`name = "…"`), not compared with (`==`). */const assignedBefore = (at: number): string | null => {let j = at - 1;while (j >= 0 && /\s/.test(source[j])) j--;if (source[j] !== "=" || /[=!<>+\-*/]/.test(source[j - 1] ?? "")) returnnull;return identBefore(j); };while (i < n) {const c = source[i];if (c === "\n") { line++; i++; continue; }if (c === "/" && source[i + 1] === "/") { while (i < n && source[i] !== "\n") i++; continue; }if (c === "/" && source[i + 1] === "*") { i += 2;while (i < n && !(source[i] === "*" && source[i + 1] === "/")) { if (source[i] === "\n") line++; i++; } i += 2;continue; }if (c === "'") { i++;while (i < n && source[i] !== "'") { if (source[i] === "\\") i++; i++; } i++;continue; }if (c === '"') {const triple = source.startsWith('"""', i);const startLine = line;const assignedTo = assignedBefore(i); i += triple ? 3 : 1;let text = "";let depth = 0;while (i < n) {if (triple && depth === 0 && source.startsWith('"""', i)) { i += 3; break; }if (!triple && depth === 0 && source[i] === '"') { i++; break; }if (!triple && source[i] === "\\") { text += source.slice(i, i + 2); i += 2; continue; }if (source[i] === "$" && source[i + 1] === "{") { depth++; text += "\u0000"; i += 2; continue; }if (depth > 0) { if (source[i] === "{") depth++; if (source[i] === "}") depth--; if (source[i] === "\n") line++; i++; continue; }if (source[i] === "$" && /[A-Za-z_]/.test(source[i + 1] ?? "")) { i++;while (i < n && /[A-Za-z0-9_]/.test(source[i])) i++; text += "\u0000";continue; }if (source[i] === "\n") line++; text += source[i]; i++; }const top = stack[stack.length - 1]; found.push({ file, line: startLine, text, call: top?.open === "(" ? top.name : null, argument: top?.open === "(" ? top.argument : 0, inside: stack.map((frame) => frame.name).filter((name): name is string => name !== null), assignedTo, });continue; }// A `{` straight after a call's `)` is that call's trailing lambda (`require(ok) { "…" }`): it carries the call's name.if (c === "(" || c === "{" || c === "[") {const name = c === "(" ? identBefore(i) : c === "{" && /\)\s*$/.test(source.slice(Math.max(0, i - 80), i)) ? closed : null; stack.push({ open: c, name, argument: 0 }); i++;continue; }if (c === ")" || c === "}" || c === "]") { const frame = stack.pop(); closed = frame?.open === "(" ? frame.name : null; i++; continue; }if (c === "," && stack.length) { stack[stack.length - 1].argument++; i++; continue; } i++; }return found;}const english = (text: string) => /[A-Za-z]{2}/.test(text.replace(/\\u[0-9a-fA-F]{4}/g, ""));const sentenceShaped = (text: string) => {const plain = text.replace(/\u0000/g, " ").trim();const words = plain.split(/\s+/).filter((word) => /^[A-Za-z][A-Za-z'’,;:]*[.?…!]?$/.test(word) && word.replace(/[^A-Za-z]/g, "").length >= 2);return words.length >= 2 || (/\s/.test(plain) && /[.?…]$/.test(plain) && /[A-Za-z]{2}/.test(plain));};/** One token naming a thing (`personal-session`, `paper/x.png`, `customer.send`): an identifier, never words. */const identifier = (text: string) => !/\s/.test(text.replace(/\u0000/g, "")) && /[-_./@:]/.test(text);/** The literals a person would read. */exportfunction personRead(found: Literal[]): Literal[] {return found.filter((literal) => {if (!english(literal.text)) returnfalse;if (literal.inside.some((call) => DEVELOPER_ONLY.has(call))) returnfalse;if (identifier(literal.text)) returnfalse;if (literal.assignedTo && SPOKEN.has(literal.assignedTo)) returntrue;if (literal.call && DRAWN.has(literal.call) && literal.argument === 0) returntrue;return sentenceShaped(literal.text); });}function kotlinFiles(folder: string): string[] {return readdirSync(folder).flatMap((name) => {const path = join(folder, name);if (name === "build" || name.startsWith(".")) return [];// `src/test`, a flavour's own unit tests (`src/testBooks`, `src/testCinemas`) and instrumented tests// (`src/androidTest`: the walker, a test APK no person installs).if (/^(android)?[tT]est([A-Z]\w*)?$/.test(name) && folder.endsWith(`${sep}src`)) return [];if (statSync(path).isDirectory()) return kotlinFiles(path);return name.endsWith(".kt") ? [path] : []; });}describe("Kotlin literals (apps/android)", () => { it("finds the app's sources", () => { expect(existsSync(APP), `${APP} is gone: this guard reads nothing`).toBe(true); });const files = existsSync(APP) ? kotlinFiles(APP) : [];const all = files.flatMap((path) => literals(readFileSync(path, "utf8"), relative(REPO_ROOT, path))); it("sees the app's literals", () => { expect(files.length).toBeGreaterThan(0); expect(all.length).toBeGreaterThan(0); }); it("draws no word a person reads from a Kotlin literal", () => {const hits = personRead(all).map((literal) => `${literal.file}:${literal.line} "${literal.text.replace(/\u0000/g, "…").slice(0, 60)}"`); expect(hits.filter((hit) => !ALLOWED.some((allowed) => hit.startsWith(allowed)))).toEqual([]); }); it("keeps its allow-list empty", () => { expect(ALLOWED).toEqual([]); });});describe("the Kotlin literal reader", () => { it("flags drawn words and sentences, and nothing a developer reads", () => {const source = ['Text("Hello")','val a = "Your books are here."','FitText(label, 12.sp, family, ink)','Log.d("books", "the core said no thing")','error("no Materials")','val key = "personal-session"','put("phone", phone)','val line = "$set.$key"','// Text("in a comment")','/* "a block comment sentence." */',"val c = '\"'",'val r = Regex("""\\bCotton(DB for Mac)?\\b""")','lines.line("board", "customer.send")','Text("${count}")','Text("$at of $total")','WayOut(label, "ink") { go() }','ItemTile(words, icon?.let { "act-$it" })','image("paper/$name.$it")','Icon(painter, contentDescription = "Close")','Modifier.semantics { contentDescription = "Play" }','Icon(painter, contentDescription = null)','if (contentDescription == "Nope") go()','Modifier.semantics { contentDescription = words }','require(text.isNotEmpty()) { "the build wrote no signer list" }','check(ready) {\n "the core is not open yet"\n}','if (ready) { Text("Your books are here.") }', ].join("\n");const hits = personRead(literals(source)).map((literal) => literal.text.replace(/\u0000/g, "$")); expect(hits).toEqual(["Hello", "Your books are here.", "$ of $", "Close", "Play", "Your books are here."]); });});