Skip to content
Myr

weak-shapes.ts

This file

Path

packages/checks/src/weak-shapes.ts

307 lines · 8.5 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

lines 1–2why, one step back
1// Reads expect-style checks (vitest, jest, bun) only: a file with no
2// `expect(` call flags nothing, and the twice-red run still guards it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 3–43why, one step back
3import { Array, Option, pipe } from "effect";
45export type Weakness =6 | "self-referential"7 | "constant pin"8 | "absence-only"9 | "mock-only"10 | "fixture-asserts-fixture";1112export interface CheckFile {13 readonly path: string;14 readonly content: string;15}1617interface Expectation {18 readonly subject: string;19 readonly negated: boolean;20 readonly matcher: string;21 readonly expected: string;22}2324interface Source {25 readonly text: string;26 readonly masked: string;27}2829const QUOTES = new Set(['"', "'", "`"]);3031const stringEnd = (source: string, start: number) => {32 const quote = source[start];33 let at = start + 1;3435 while (at < source.length && source[at] !== quote) {36 at += source[at] === "\\" ? 2 : 1;37 }3839 return Math.min(at + 1, source.length);40};4142const blank = (text: string) => text.replaceAll(/[^\n]/gu, " ");43

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

lines 44–45why, one step back
44// Both copies keep every index, so a position found in `masked` reads the
45// same span of `text`.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 46–149why, one step back
46const read = (source: string): Source => {
47 const text: string[] = [];48 const masked: string[] = [];49 let at = 0;5051 while (at < source.length) {52 const pair = source.slice(at, at + 2);53 const char = source[at] ?? "";5455 if (pair === "//" || pair === "/*") {56 const close = pair === "//" ? "\n" : "*/";57 const found = source.indexOf(close, at + 2);58 const end = found === -1 ? source.length : found + close.length;59 const span = blank(source.slice(at, end));6061 text.push(span);62 masked.push(span);63 at = end;64 } else if (QUOTES.has(char)) {65 const end = stringEnd(source, at);66 const literal = source.slice(at, end);6768 text.push(literal);69 masked.push(`${char}${blank(literal.slice(1, -1))}${literal.slice(-1)}`);70 at = end;71 } else {72 text.push(char);73 masked.push(char);74 at += 1;75 }76 }7778 return { masked: masked.join(""), text: text.join("") };79};8081const closing = (masked: string, open: number) => {82 let depth = 0;8384 for (let at = open; at < masked.length; at += 1) {85 if (masked[at] === "(") {86 depth += 1;87 } else if (masked[at] === ")") {88 depth -= 1;8990 if (depth === 0) {91 return Option.some(at);92 }93 }94 }9596 return Option.none();97};9899const expectationAt = (100 { masked, text }: Source,101 start: number102): Option.Option<Expectation> =>103 Option.gen(function* () {104 const open = masked.indexOf("(", start);105 const close = yield* closing(masked, open);106107 const chain =108 /\s*(?<modifiers>(?:\.\s*(?:not|resolves|rejects)\s*)*)\.\s*(?<matcher>[A-Za-z_$][\w$]*)\s*\(/uy;109110 chain.lastIndex = close + 1;111 const found = yield* Option.fromNullishOr(chain.exec(masked));112 const matcherOpen = found.index + found[0].length - 1;113 const matcherClose = yield* closing(masked, matcherOpen);114115 return {116 expected: text.slice(matcherOpen + 1, matcherClose).trim(),117 matcher: found.groups?.matcher ?? "",118 negated: /\bnot\b/u.test(found.groups?.modifiers ?? ""),119 subject: text.slice(open + 1, close).trim(),120 };121 });122123const expectationsOf = (source: Source) =>124 Array.getSomes(125 Array.map(126 [...source.masked.matchAll(/(?<![\w$.])expect\s*\(/gu)],127 (match) => expectationAt(source, match.index)128 )129 );130131const importsOf = ({ masked, text }: Source) =>132 pipe(133 [134 ...text.matchAll(135 /(?<keyword>\bfrom|\bimport\s*\(?|\brequire\s*\()\s*["'](?<specifier>[^"'\n]+)["']/gu136 ),137 ],138 // A keyword inside a string is blanked in `masked`.139 Array.filter((match) => masked[match.index] !== " "),140 Array.map((match) => match.groups?.specifier ?? "")141 );142143const EXTENSION = /\.(?:[cm]?[jt]sx?|json)$/u;144145const GLOB = /[*?[{]/u;146147const segmentsOf = (path: string) =>148 path.split("/").filter((segment) => segment !== "" && segment !== ".");149

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

lines 150–151why, one step back
150// A glob naming one file covers its folder, since a check reaches a file
151// through its folder's index too.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 152–272why, one step back
152const baseOf = (glob: string) => {
153 const segments = segmentsOf(glob);154 const fixed = Array.takeWhile(segments, (segment) => !GLOB.test(segment));155156 const isFile =157 fixed.length === segments.length && EXTENSION.test(fixed.at(-1) ?? "");158159 return isFile ? fixed.slice(0, -1) : fixed;160};161162const resolve = (checkPath: string, specifier: string) => {163 const resolved = segmentsOf(checkPath).slice(0, -1);164165 for (const segment of segmentsOf(specifier)) {166 if (segment === "..") {167 resolved.pop();168 } else {169 resolved.push(segment);170 }171 }172173 return resolved;174};175176const startsWith = (path: readonly string[], head: readonly string[]) =>177 head.every((segment, index) => path[index] === segment);178179const reaches =180 (checkPath: string) => (specifier: string, base: readonly string[]) => {181 if (!specifier.startsWith(".")) {182 const parts = specifier.split("/");183 const name = specifier.startsWith("@") ? parts[1] : parts[0];184185 return name !== undefined && base.includes(name);186 }187188 const path = resolve(checkPath, specifier);189190 return startsWith(path, base) || startsWith(base, path);191 };192193// After strings, numbers and the literal keywords go, a literal has no194// identifier left but its object keys, and no call or arrow.195const isLiteral = (text: string) =>196 text !== "" &&197 !/[(=]/u.test(text) &&198 !/[A-Za-z_$]/u.test(199 text200 .replaceAll(201 /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\$]|\\.)*`/gu,202 "0"203 )204 .replaceAll(205 /\b(?:0[box][\da-f_]+|\d[\d_]*(?:\.\d+)?(?:e[+-]?\d+)?n?)\b/giu,206 "0"207 )208 .replaceAll(/\b(?:true|false|null|undefined|NaN|Infinity)\b/gu, "0")209 .replaceAll(/[A-Za-z_$][\w$]*\s*:/gu, "")210 );211212const isAbsence = ({ matcher, negated }: Expectation) =>213 negated214 ? ["toThrow", "toThrowError", "toBeDefined", "toBeTruthy"].includes(matcher)215 : ["toBeUndefined", "toBeFalsy"].includes(matcher);216217const MOCK_MATCHER =218 /^to(?:HaveBeen(?:Last|Nth)?Called|BeCalled|Have(?:Last|Nth)?Returned)/u;219220const rootOf = (text: string) =>221 /^(?:await\s+)?(?<root>[A-Za-z_$][\w$]*)/u.exec(text)?.groups?.root;222223const mocksOf = ({ text }: Source) =>224 new Set(225 Array.map(226 [227 ...text.matchAll(228 /\b(?:const|let|var)\s+(?<name>[A-Za-z_$][\w$]*)\s*=\s*(?:(?:vi|jest)\.(?:fn|spyOn)|mock)\s*\(/gu229 ),230 ],231 (match) => match.groups?.name ?? ""232 )233 );234235const isOnMock = (mocks: ReadonlySet<string>) => (each: Expectation) =>236 MOCK_MATCHER.test(each.matcher) ||237 each.subject.includes(".mock.") ||238 /\b(?:vi|jest)\.fn\s*\(/u.test(each.subject) ||239 mocks.has(rootOf(each.subject) ?? "");240241const resultsOf = ({ text }: Source) =>242 new Set(243 Array.map(244 [245 ...text.matchAll(246 /\b(?:const|let|var)\s+(?<name>[A-Za-z_$][\w$]*)\s*=\s*(?:await\s+)?[A-Za-z_$][\w$.]*\s*\(/gu247 ),248 ],249 (match) => match.groups?.name ?? ""250 )251 );252253const squash = (text: string) => text.replaceAll(/\s+/gu, "");254255const isFromOneFixture =256 (results: ReadonlySet<string>) =>257 ({ expected, subject }: Expectation) => {258 const root = rootOf(subject);259260 return (261 !isLiteral(subject) &&262 (squash(subject) === squash(expected) ||263 (!subject.includes("(") &&264 root !== undefined &&265 !results.has(root) &&266 root === rootOf(expected)))267 );268 };269270const isConstantPin = ({ expected, subject }: Expectation) =>271 isLiteral(subject) && (expected === "" || isLiteral(expected));272

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

lines 273–274why, one step back
273// A shape over expectations holds only when every expectation has it, so one
274// real assertion among weak ones keeps the check.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 275–307why, one step back
275export const weaknessesOf = (
276 checkFile: CheckFile,277 territoryPaths: readonly string[]278): readonly Weakness[] => {279 const source = read(checkFile.content);280 const expectations = expectationsOf(source);281282 if (!Array.isReadonlyArrayNonEmpty(expectations)) {283 return [];284 }285286 const bases = territoryPaths.map(baseOf);287 const intoTerritory = reaches(checkFile.path);288 const mocks = mocksOf(source);289290 const every = (holds: (each: Expectation) => boolean) =>291 expectations.every(holds);292293 const found: readonly [Weakness, boolean][] = [294 [295 "self-referential",296 !importsOf(source).some((specifier) =>297 bases.some((base) => intoTerritory(specifier, base))298 ),299 ],300 ["constant pin", every(isConstantPin)],301 ["absence-only", every(isAbsence)],302 ["mock-only", every(isOnMock(mocks))],303 ["fixture-asserts-fixture", every(isFromOneFixture(resultsOf(source)))],304 ];305306 return found.flatMap(([weakness, holds]) => (holds ? [weakness] : []));307};