// Reading the phone's Swift sources from a vitest, the way the CottonUITests// source sweeps did — ported so a guard that only reads text runs here in// seconds instead of on a Mac behind the build lock and a simulator.//// This is the TypeScript twin of `apps/cotton/Tests/CottonUITests/SourceSweep.swift`// (and of `AppSources` in `AppSources.swift`): the same roots, the same walk,// the same names, and the same comment stripping, character for character, so a// guard ported from Swift reads exactly the text it read there. The three// by-path rules SourceSweep.swift states hold here too://// (a) A read that finds nothing FAILS LOUDLY, naming the path, before any// regex runs (`mustRead`, and every walk asserts it found files).// (b) Every reader names the lane that owns the path it reads.// (c) Before any file move lands, grep the moved path repo-wide.import { existsSync, readdirSync, readFileSync } from"node:fs";import { join, relative, resolve } from"node:path";/** A source by its name relative to the root it was walked from, and its text. */exportinterfaceSource { name: string; text: string;}/** * The repo root: the checkout `COTTON_UI_TESTS_REPO_ROOT` names (the variable * SourceSweep.swift reads, so a copy of the tree can be swept — and a planted * violation in a copy proves a guard can fail), else walked up from this file: * scripts/__tests__/helpers → scripts/__tests__ → scripts → <repo>. */exportconst repoRoot = process.env.COTTON_UI_TESTS_REPO_ROOT || resolve(__dirname, "../../..");/** The app's `Sources` (`apps/cotton/Sources`). */exportconst iosSources = join(repoRoot, "apps/cotton/Sources");/** Loom's sources (`apps/loom/Sources`): CottonValues, CottonPaper, CottonFaces. */exportconst loomSources = join(repoRoot, "apps/loom/Sources");/** Every file under `root` (recursively, hidden ones included, as FileManager's enumerator walks) whose extension is `ext`. */exportfunction walk(root: string, ext: string): string[] {if (!existsSync(root)) return [];const found: string[] = [];const visit = (dir: string): void => {for (const entry of readdirSync(dir, { withFileTypes: true })) {const path = join(dir, entry.name);if (entry.isDirectory()) visit(path);elseif (entry.name.endsWith(`.${ext}`) && entry.name.length > ext.length + 1) found.push(path); } }; visit(root);return found;}const byName = (a: Source, b: Source): number => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);/** * Every `.swift` file under the app's `Sources` and Loom's, as (module-relative * path, text) — `CottonPaper/…` reads the same wherever its package is. A * DIRECTORY walk, never a file list: a two-file list is green on the day a * third file starts writing colours. */let swiftCache: Source[] | undefined;exportfunction swiftSources(): Source[] {// Read once per test file: the tree does not change under a run.if (swiftCache) return [...swiftCache];const found: Source[] = [];for (const root of [iosSources, loomSources]) {for (const path of walk(root, "swift")) found.push({ name: relative(root, path), text: readFileSync(path, "utf8") }); } swiftCache = found.sort(byName);return [...swiftCache];}/** * Every Swift source of this app — `swiftSources()` AND the Xcode project's * `App/**`, named `App/<target>/…` so two targets' files of one name stay two. * `App/` is where the `@main` struct and the extensions' principal classes live, * exactly the place a `URLSession` or a whole-body read would first be written. */exportfunction appSources(): Source[] {const found = swiftSources();const app = join(repoRoot, "apps/cotton/App");for (const path of walk(app, "swift")) found.push({ name: `App/${relative(app, path)}`, text: readFileSync(path, "utf8") });return found.sort(byName);}/** The last path component of a source's name. */exportfunction fileName(name: string): string {return name.split("/").filter(Boolean).pop() ?? name;}/** * Rule (a): a read that finds nothing fails LOUDLY, naming the path and the * lane, before anything is compared. A regex over an empty string passes, * which is how a moved file turns a guard green. */exportfunction mustRead(relativePath: string, ownedBy: string): string {const path = join(repoRoot, relativePath);let text: string | undefined;try { text = readFileSync(path, "utf8"); } catch { text = undefined; }if (text === undefined) {thrownewError(`could not read ${path} — did the file move? That path is the ${ownedBy} lane's; grep it repo-wide ` +"(__tests__ and every open worktree included) before changing this guard.", ); }if (text.length === 0) thrownewError(`${path} is empty`);return text;}/** * Comments stripped, so a guard reads the CODE — exactly SourceSweep.withoutComments: * `//` to the end of the line (the newline kept), `/* … *\/` unnested and * dropped whole, and a `"` string's contents kept with every backslash AND the * character it escapes dropped (so `"a \" b"` reads `"a b"`, and `"\(x)"` * reads `"(x)"`). A `"""` toggles the string three times, as the Swift did. */const strippedCache = newMap<string, string>();exportfunction withoutComments(text: string): string {const known = strippedCache.get(text);if (known !== undefined) return known;const out = strip(text); strippedCache.set(text, out);return out;}function strip(text: string): string {let out = "";let inLine = false;let inBlock = false;let inString = false;for (let i = 0; i < text.length; i++) {const ch = text[i];const peek = text[i + 1];if (inLine) {if (ch === "\n") { inLine = false; out += ch; } } elseif (inBlock) {if (ch === "*" && peek === "/") { inBlock = false; i++; } } elseif (inString) {if (ch === "\\") i++;elseif (ch === '"') { inString = false; out += ch; } else out += ch; } elseif (ch === "/" && peek === "/") { inLine = true; i++; } elseif (ch === "/" && peek === "*") { inBlock = true; i++; } else {if (ch === '"') inString = true; out += ch; } }return out;}/** Every match of `pattern` in `text`, as the matched text (SourceSweep.matches). */exportfunction matches(pattern: string | RegExp, text: string, flags = ""): string[] {const source = typeof pattern === "string" ? pattern : pattern.source;const all = newSet([...(typeof pattern === "string" ? "" : pattern.flags), ...flags, "g"]);return [...text.matchAll(newRegExp(source, [...all].join("")))].map((m) => m[0]);}/** A string escaped to match itself (NSRegularExpression.escapedPattern). */exportfunction escapeRegExp(text: string): string {return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}/** Spaces and tabs trimmed from both ends (`trimmingCharacters(in: .whitespaces)`). */exportfunction trimSpaces(text: string): string {return text.replace(/^[\p{Zs}\t]+|[\p{Zs}\t]+$/gu, "");}