// A public type nobody else names is an internal one wearing the wrong word.// PublicSurfaceSweepTests.swift (CottonUITests), ported to vitest: it only ever// read Swift as text. The describe keeps the Swift suite's name.//// The rule is by NAME across the whole tree (`Sources/**`, `App/**`, the Swift// `Tests/**`, Loom's tests and app): a type named in any other file may stay// public, because a test in another module or the App target may be that// reader; a type named in a PUBLIC SIGNATURE of its own file (or a `case` of a// public enum, or a requirement of a public protocol) is API without a name and// stays public too; a type named in neither is lowered. A signature is read TO// ITS CLOSING PARENTHESIS, not one line at a time. Whole-word, comments// stripped from the declaring side only — a name mentioned in another file's// prose still counts as a reader, which errs towards leaving a type alone.import { readFileSync } from"node:fs";import { basename, join } from"node:path";import { describe, expect, it } from"vitest";import { appSources, escapeRegExp, matches, repoRoot, typeSource, trimSpaces, walk, withoutComments } from"./helpers/swift-source-sweep";/** A file may keep an own-file-only public type ONLY with a sentence saying which lane owns the exception; a row the file no longer earns fails. */const allowed: Record<string, string> = {// Generated from the Rust definition types: the generator, not a lane, sets visibility."CottonUI/Definitions/GeneratedDefinitionTypes.swift": "gen-swift-definition-types.py",// Generated by cotton-gen from the core's design modules (`pnpm gen:design`): the generator sets visibility."CottonPaper/Generated/Palette.swift": "cotton-gen design/palette.rs",};/** Every `.swift` file under the package's `Tests`, Loom's tests and its app, named by prefix and file name — the readers `appSources()` does not walk. */function swiftTests(): Source[] {const found: Source[] = [];for (const [path, prefix] of [ ["apps/cotton/Tests", "Tests/"], ["apps/loom/Tests", "LoomTests/"], ]) {for (const file of walk(join(repoRoot, path), "swift")) found.push({ name: prefix + basename(file), text: readFileSync(file, "utf8") }); } expect(found.length, "the sweep found no tests under apps/cotton/Tests").toBeGreaterThan(0);return found;}/** How many `(` a line leaves open (negative when it closes more than it opens). */function unclosedParentheses(line: string): number {let depth = 0;for (const character of line) {if (character === "(") depth += 1;elseif (character === ")") depth -= 1; }return depth;}const declaration = String.raw`^\s*(?:@\w+(?:\([^)]*\))?\s+)*public\s+(?:final\s+)?(?:struct|class|enum|actor|protocol)\s+([A-Z]\w*)`;describe("PublicSurfaceSweepTests", () => {// RULE: a type is `public` only when another file names it or a public signature of its own file does — a public word nobody reads hides the real API, so a type neither names is internal; the sweep must find public types to prove it, so a walk that reads nothing never passes. it("every public type is named in another file", () => {const sources = appSources(); expect(sources.length, "the sweep read no sources").toBeGreaterThan(0);// `\bName\b` for a name made only of word characters matches exactly when some// maximal run of word characters IS the name, so each reader's runs are read once.const everything = [...sources, ...swiftTests()].map((source) => ({ name: source.name, words: newSet(source.text.match(/\w+/g) ?? []) }));let declared = 0;const lonely: string[] = [];const exceptionsSeen = newSet<string>();for (const { name, text } of sources) {const code = withoutComments(text);const names = matches(declaration, code, "m").map((m) => m.split(" ").filter(Boolean).pop() ?? "");for (const typeName of names) { declared += 1;const word = newRegExp(String.raw`\b${escapeRegExp(typeName)}\b`);// The sweep's own file is never a reader (an `allowed` row's key spells the file name, which spells the type).const namedElsewhere = everything.some( (other) => other.name !== name && !other.name.endsWith("PublicSurfaceSweepTests.swift") && other.words.has(typeName), );if (namedElsewhere) continue;// Named in a public signature of its own file: API through the member.let inPublicProtocol = false;let namedInOwnPublicSignature = false;const lines = code.split("\n").filter(Boolean);let next = 0;while (next < lines.length) {let line = lines[next]; next += 1;if (/^\s*public\s+protocol\b/.test(line)) inPublicProtocol = true;elseif (/^}/.test(line)) inPublicProtocol = false;const isSignature = /^\s*(?:@\w+(?:\([^)]*\))?\s+)*(?:public|case)\b/.test(line) || (inPublicProtocol && /^\s*(?:static\s+|mutating\s+)*(?:func|var|init|subscript)\b/.test(line));if (!isSignature) continue;// The rest of a signature that runs over several lines: up to the line that closes its parentheses, never past the brace that opens a body.let depth = unclosedParentheses(line);while (depth > 0 && !trimSpaces(line).endsWith("{") && next < lines.length) { depth += unclosedParentheses(lines[next]); line += `\n${lines[next]}`; next += 1; }if (newRegExp(String.raw`\b(?:struct|class|enum|actor|protocol)\s+${escapeRegExp(typeName)}\b`).test(line)) continue;if (word.test(line)) { namedInOwnPublicSignature = true;break; } }if (namedInOwnPublicSignature) continue;if (allowed[name] !== undefined) { exceptionsSeen.add(name);continue; } lonely.push(`${name}: ${typeName}`); } } expect(declared, "the sweep found no public types, so it proved nothing").toBeGreaterThan(0); expect( lonely,`${lonely.length} public type(s) are named in no other file and should be internal (or the file needs an \`allowed\` row with the lane that owns the exception)`, ).toEqual([]);for (const [file, reason] ofObject.entries(allowed)) { expect(exceptionsSeen.has(file), `\`allowed\` names ${file} (${reason}) but it declares no own-file-only public type any more — drop the row`).toBe(true); } });});