diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2cc2521206..554e71f6d5 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -129,7 +129,7 @@ jobs: # `index.node`, which nothing else in this job produces. # # NOT for protect-ffi's own suite, though vendoring it did add - # `@cipherstash/protect-ffi#test` to `turbo test --filter './languages/typescript/packages/*'`. + # `@cipherstash/protect-ffi#test` to `turbo test --filter './languages/typescript/packages/**' --filter './packages/**'`. # That suite must pass with no binding at all (its `build` is `tsc` and # its `test` is deliberately cargo-free), and `src/lintWiring.test.ts` # re-runs it here with the artifact hidden to keep that true — this job diff --git a/languages/typescript/packages/protect-ffi/README.md b/languages/typescript/packages/protect-ffi/README.md index ba16b3c2c9..9bf3d6d5cd 100644 --- a/languages/typescript/packages/protect-ffi/README.md +++ b/languages/typescript/packages/protect-ffi/README.md @@ -254,7 +254,9 @@ Builds the `wasm32-unknown-unknown` output into `dist/wasm/` with `wasm-pack`, t #### `pnpm test` -Typechecks the TypeScript, runs the unit tests (tsc + vitest), and lints and format-checks the TypeScript. **No cargo**, by design — see above. +Typechecks the TypeScript, runs the unit tests (vitest, against `lib/` from `build`), and lints and format-checks the TypeScript. **No cargo**, by design — see above. + +The unit tests read `lib/`, and `pnpm test` does not write it: its typecheck runs `tsc --noEmit`, because other packages' builds read `lib/` while root `pnpm test` runs. Run `pnpm run build` first. Through turbo (root `pnpm test`), `build` runs before `test` on its own. Note: this does not run the integration tests either. For those, see [below](#integration-tests). @@ -265,7 +267,7 @@ The Rust half of the test suite: `cargo test --locked` plus `cargo fmt --check`. #### `pnpm run test:typecheck:wasm` -Typechecks `type-tests/` against the wasm-bindgen-generated declarations in `dist/wasm/`. Needs `build:wasm` and `build` to have run first, which is why it is not part of `pnpm test` — that has to pass in a fresh clone with no `dist/`. +Typechecks `type-tests/` against the wasm-bindgen-generated declarations in `dist/wasm/`. Needs `build:wasm` and `build` to have run first. Root `pnpm test` has to pass in a fresh clone with no `dist/`, so `pnpm test` leaves this out. #### `mise run lint:rust` diff --git a/languages/typescript/packages/protect-ffi/package.json b/languages/typescript/packages/protect-ffi/package.json index 444ce1a491..aff3700c60 100644 --- a/languages/typescript/packages/protect-ffi/package.json +++ b/languages/typescript/packages/protect-ffi/package.json @@ -15,7 +15,7 @@ "scripts": { "test": "pnpm run test:typecheck && pnpm run test:unit && pnpm run test:lint && pnpm run test:format:ts", "test:cargo": "pnpm run test:rust && pnpm run test:format:rust", - "test:typecheck": "tsc && tsc -p tsconfig.test.json", + "test:typecheck": "tsc --noEmit && tsc -p tsconfig.test.json", "test:typecheck:wasm": "tsc -p type-tests/tsconfig.json", "test:unit": "vitest run", "test:rust": "cargo test --locked", diff --git a/languages/typescript/packages/protect-ffi/src/lintWiring.test.ts b/languages/typescript/packages/protect-ffi/src/lintWiring.test.ts index 03546ff513..d0612467a5 100644 --- a/languages/typescript/packages/protect-ffi/src/lintWiring.test.ts +++ b/languages/typescript/packages/protect-ffi/src/lintWiring.test.ts @@ -396,7 +396,7 @@ describe('lint and format wiring', () => { it('keeps cargo off the default test path', () => { // The load-bearing half of the split. Root `pnpm test` runs - // `turbo test --filter './languages/typescript/packages/*'`, which reaches this package's + // `turbo test --filter './languages/typescript/packages/**' --filter './packages/**'`, which reaches this package's // `test` — so anything cargo on that path is cargo on every PR, in a repo // where one package out of eighteen is Rust. // @@ -424,7 +424,7 @@ describe('lint and format wiring', () => { // test then requires what cargo produces: `src/nativeLoading.test.ts` // asserted `assertNativeBindingAvailable()` does not throw, which needs // an `index.node` that only `build:native` writes. Root `pnpm test` - // reaches this package through `turbo test --filter './languages/typescript/packages/*'`, so + // reaches this package through `turbo test --filter './languages/typescript/packages/**' --filter './packages/**'`, so // that made a Rust build a prerequisite of the whole repo's default test // — the exact thing the entry-point split exists to prevent, arriving // through the tests instead of through the scripts. diff --git a/languages/typescript/packages/protect-ffi/src/nativeLoading.test.ts b/languages/typescript/packages/protect-ffi/src/nativeLoading.test.ts index 08dec4e320..e03d0bc45e 100644 --- a/languages/typescript/packages/protect-ffi/src/nativeLoading.test.ts +++ b/languages/typescript/packages/protect-ffi/src/nativeLoading.test.ts @@ -14,8 +14,11 @@ * A regression here is silent for anyone with a binary installed — every * consumer who installs from npm, and every CI job that has run * `.github/actions/build-ffi-binding` — so the property is asserted against the - * EMITTED JavaScript rather than behaviour. `lib/` exists by the time this - * runs: `test:typecheck` emits it before `test:unit`. + * EMITTED JavaScript rather than behaviour. `lib/` comes from `build`, and + * turbo runs this package's `build` before its `test` (`turbo.json`, + * `@cipherstash/protect-ffi#test`). `test` itself never writes `lib/`: + * `test:typecheck` runs `tsc --noEmit`, because other packages' builds read + * `lib/` while this suite runs. * * The same blind spot is why the last block goes the other way and asserts * behaviour: what `assertNativeBindingAvailable` does with a MISSING binary @@ -24,7 +27,7 @@ * * Nothing in this file may REQUIRE a binary, though, and that is a separate * rule from the ones above. `languages/typescript/packages/protect-ffi`'s `test` is the default task - * root `pnpm test` reaches through `turbo test --filter './languages/typescript/packages/*'`, and it + * root `pnpm test` reaches through `turbo test --filter './languages/typescript/packages/**' --filter './packages/**'`, and it * is deliberately Rust-free: `index.node` stopped being tarball content when * this package was absorbed, so on a fresh checkout there is no binary * anywhere and the six `platforms/*` links are empty. `lintWiring.test.ts` @@ -32,8 +35,19 @@ * unresolvable. */ -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + utimesSync, + writeFileSync, +} from 'node:fs' import Module, { createRequire } from 'node:module' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' @@ -41,12 +55,13 @@ import { describe, expect, it } from 'vitest' const packageRoot = process.cwd() const entryPath = join(packageRoot, 'lib/index.cjs') -// `lib/` is generated, so this file carries a prerequisite the package's `test` -// chain satisfies and a bare `test:unit` does not. Without this guard the whole +// `lib/` is generated, so this file carries a prerequisite that turbo's +// `test` satisfies (it runs `build` first) and a bare `pnpm run test` or +// `test:unit` does not. Without this guard the whole // suite fails as `ENOENT: no such file or directory, open '.../lib/index.cjs'` // pointed at the readFileSync below — which names the missing file but not the -// command that produces it, and lands on whoever runs `test:unit` directly -// (every CI job that splits the chain, and anyone iterating on one test). +// command that produces it, and lands on whoever runs the package script +// directly (anyone iterating on one test). // A zero-byte entry counts as missing. An interrupted `tsc` leaves one, and it // is the state where naming the build step — the entire point of this guard — // otherwise fails to happen: `existsSync` is satisfied, and what the developer @@ -55,12 +70,36 @@ const entryPath = join(packageRoot, 'lib/index.cjs') // source` below already fails loudly on an empty read, which is why it is // there. This is so the failure names its own cure. // -// Deliberately only the empty case. A PARTIALLY written entry is not +// Only the empty case for size. A PARTIALLY written entry is not // detectable by size and needs no separate handling — the content assertions // below go red on any degraded emit; they cannot go quietly green. if (!existsSync(entryPath) || statSync(entryPath).size === 0) { throw new Error( - `${entryPath} is missing or empty. These tests assert on the EMITTED entry, and lib/ is a build output: run \`pnpm --filter @cipherstash/protect-ffi run build\` first, or \`pnpm --filter @cipherstash/protect-ffi test\`, whose test:typecheck step emits lib/ before test:unit runs.`, + `${entryPath} is missing or empty. These tests assert on the EMITTED entry, and lib/ is a build output: run \`pnpm --filter @cipherstash/protect-ffi run build\` first, or \`pnpm turbo run test --filter @cipherstash/protect-ffi\`, which runs build before test. The package's own test script does not write lib/.`, + ) +} + +/** + * The sources under `srcDir` that tsc compiles into `lib/` and that changed + * after `entry` was written, as paths relative to `srcDir`. Test files are + * left out, because the build tsconfig excludes them. + */ +function sourcesNewerThan(entry: string, srcDir: string): string[] { + const builtAt = statSync(entry).mtimeMs + return readdirSync(srcDir, { recursive: true, encoding: 'utf8' }) + .filter((file) => /\.[cm]?ts$/.test(file) && !file.endsWith('.test.ts')) + .filter((file) => statSync(join(srcDir, file)).mtimeMs > builtAt) + .sort() +} + +// A stale entry fails the same way. The package's `test` no longer writes +// lib/, so after a source edit a bare `test` would otherwise assert on the +// JavaScript the previous build emitted, and pass. CI is not affected: every +// job builds lib/ after checkout, so lib/ is newer than every source. +const staleSources = sourcesNewerThan(entryPath, join(packageRoot, 'src')) +if (staleSources.length > 0) { + throw new Error( + `${entryPath} is older than ${staleSources.join(', ')}. These tests assert on the EMITTED entry, so they would test the previous build: run \`pnpm --filter @cipherstash/protect-ffi run build\` first.`, ) } @@ -196,7 +235,7 @@ describe('assertNativeBindingAvailable', () => { // empty until someone builds one, and `languages/typescript/packages/protect-ffi`'s `test` is // deliberately Rust-free. So on every fresh checkout the assertion failed // — and it failed under root `pnpm test`, which reaches this package via - // `turbo test --filter './languages/typescript/packages/*'`. + // `turbo test --filter './languages/typescript/packages/**' --filter './packages/**'`. // // Both branches assert. A `skipIf` here would be the trade this repo keeps // refusing: it goes quiet on every contributor machine, and quiet is @@ -514,3 +553,30 @@ describe('assertNativeBindingAvailable with the platform binary missing', () => expect((caught as NodeJS.ErrnoException).code).toBe('MODULE_NOT_FOUND') }) }) + +describe('sourcesNewerThan', () => { + // The guard at the top of this file uses it to reject a stale lib/. It runs + // on a temporary tree here, because the real tree's mtimes depend on when + // build last ran. + it('lists compiled sources newer than the entry, and nothing else', () => { + const root = mkdtempSync(join(tmpdir(), 'protect-ffi-stale-')) + try { + const src = join(root, 'src') + mkdirSync(join(src, 'nested'), { recursive: true }) + const writeAt = (path: string, seconds: number) => { + writeFileSync(path, '') + utimesSync(path, seconds, seconds) + } + const entry = join(root, 'index.cjs') + writeAt(entry, 2000) + writeAt(join(src, 'old.cts'), 1000) + writeAt(join(src, 'nested', 'newer.ts'), 3000) + writeAt(join(src, 'newer.test.ts'), 3000) + writeAt(join(src, 'notes.md'), 3000) + + expect(sourcesNewerThan(entry, src)).toEqual([join('nested', 'newer.ts')]) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) diff --git a/scripts/__tests__/protect-ffi-test-no-emit.test.mjs b/scripts/__tests__/protect-ffi-test-no-emit.test.mjs new file mode 100644 index 0000000000..2e1f9b5460 --- /dev/null +++ b/scripts/__tests__/protect-ffi-test-no-emit.test.mjs @@ -0,0 +1,217 @@ +/** + * protect-ffi's `test` must not rewrite `lib/` while other packages read it. + * + * Root `pnpm test` runs `turbo test` over every package at once, in one + * checkout. `lib/` is protect-ffi's build output and its `main`: the builds of + * `@cipherstash/stack`, `stack-drizzle` and `stack-supabase` read + * `lib/*.d.*` from it. `test:typecheck` used to start with a plain `tsc`, + * which writes every file in `lib/` again. While tsc writes a file, the file + * is briefly empty. A build that read `lib/types.d.ts` at that moment saw no + * exports, and tsup failed with TS2305 ("has no exported member + * 'AuthStrategy'"). That failed Test JS on pull request #1845. + * + * Two rules close the race, and this file checks both: + * + * 1. No `tsc` reachable from protect-ffi's `test` script emits files. A + * typecheck needs no output, so `--noEmit` (or a tsconfig with + * `noEmit: true`) costs nothing. + * 2. turbo runs `@cipherstash/protect-ffi#test` after its own `build`. The + * unit tests in `nativeLoading.test.ts` read the emitted `lib/index.cjs`, + * and rule 1 means the test no longer writes it. Declaring the edge also + * puts every reader of `lib/` after the one write turbo makes to it. + * + * The failure this guards against is timing-dependent. It showed up on a + * small share of runs, so a green CI run is no evidence the race is gone. + */ + +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { describe, expect, it } from 'vitest' +import { readJsonc } from './lib/read-jsonc.mjs' +import { REPO_ROOT } from './lib/repo-root.mjs' + +const PACKAGE_DIR = join(REPO_ROOT, 'languages/typescript/packages/protect-ffi') +const PACKAGE_NAME = '@cipherstash/protect-ffi' +const manifest = JSON.parse( + readFileSync(join(PACKAGE_DIR, 'package.json'), 'utf8'), +) +const scripts = manifest.scripts + +/** + * Script names reachable from `root`, following script calls by pnpm or npm + * and the `pre` / `post` hooks pnpm runs without being asked. Based on + * `reachableFrom` in protect-ffi's `src/lintWiring.test.ts`, which follows + * only `pnpm run` and `npm run`. + */ +function reachableFrom(root, scripts = manifest.scripts) { + const seen = new Set() + const queue = [root] + while (queue.length > 0) { + const name = queue.pop() + if (seen.has(name)) continue + seen.add(name) + const body = scripts[name] + if (body === undefined) continue + queue.push(`pre${name}`, `post${name}`) + // pnpm runs a script with or without `run`, after any flags (`pnpm build`, + // `pnpm -s run build`). npm needs `run`. A name that is not a script, such + // as `exec` in `pnpm exec`, is not followed. + const calls = [ + ...body.matchAll(/\bpnpm(?:\s+-\S+)*\s+(?:run\s+)?([\w:-]+)/g), + ...body.matchAll(/\bnpm(?:\s+-\S+)*\s+run\s+([\w:-]+)/g), + ] + for (const [, called] of calls) { + if (Object.hasOwn(scripts, called)) queue.push(called) + } + } + return seen +} + +/** + * Every `tsc` command in a script body, as its argument list. A command ends + * at a shell operator or a redirect. Quotes and parentheses are stripped from + * each word, and a word counts as tsc when its last path part, without an + * `@version`, is `tsc`. So `./node_modules/.bin/tsc`, `npx tsc@5.9.3`, + * `sh -c 'tsc'` and `(tsc)` are all found. + */ +function tscCommands(body) { + const commands = [] + for (const segment of body.split(/&&|\|\||;|\||>/)) { + const words = segment + .trim() + .split(/\s+/) + .map((word) => word.replace(/["'()]/g, '')) + .filter((word) => word !== '') + const at = words.findIndex( + (word) => word.split('/').pop().replace(/@.*$/, '') === 'tsc', + ) + if (at !== -1) commands.push(words.slice(at + 1)) + } + return commands +} + +/** + * The `noEmit` a tsconfig ends up with, following `extends`. A relative + * `extends` is a path; any other is resolved like a package, from the + * directory of the config that names it. + */ +function effectiveNoEmit(configPath) { + const config = readJsonc(configPath) + const own = config.compilerOptions?.noEmit + if (own !== undefined) return own + if (typeof config.extends !== 'string') return false + const parent = config.extends.startsWith('.') + ? resolve(dirname(configPath), config.extends) + : createRequire(configPath).resolve(config.extends) + return effectiveNoEmit(parent) +} + +/** Whether a `tsc` with these arguments, run from the package, writes files. */ +function emits(args) { + if (args.includes('-b') || args.includes('--build')) return true + const noEmitAt = args.indexOf('--noEmit') + if (noEmitAt !== -1 && args[noEmitAt + 1] !== 'false') return false + const projectAt = args.findIndex((a) => a === '-p' || a === '--project') + const project = projectAt === -1 ? '.' : args[projectAt + 1] + const configPath = project.endsWith('.json') + ? join(PACKAGE_DIR, project) + : join(PACKAGE_DIR, project, 'tsconfig.json') + return !effectiveNoEmit(configPath) +} + +describe('protect-ffi test does not rewrite lib/ during turbo test', () => { + it('runs no emitting tsc from the test script', () => { + const found = [...reachableFrom('test')].flatMap((name) => + tscCommands(scripts[name] ?? '').map((args) => ({ name, args })), + ) + + // Without a tsc on the path, the assertion below checks nothing. + expect( + found.length, + 'No tsc command is reachable from protect-ffi `test`, so this check reads nothing.', + ).toBeGreaterThan(0) + + const emitting = found + .filter(({ args }) => emits(args)) + .map(({ name, args }) => `${name}: tsc ${args.join(' ')}`.trim()) + expect( + emitting, + `These tsc commands run from protect-ffi \`test\` and write files into lib/. turbo runs other packages' builds at the same time, and they read lib/*.d.* while tsc rewrites it. Add --noEmit, or use a tsconfig with "noEmit": true.`, + ).toEqual([]) + }) + + it('runs protect-ffi test after its own build in turbo', () => { + const turbo = readJsonc(join(REPO_ROOT, 'turbo.json')) + const task = turbo.tasks[`${PACKAGE_NAME}#test`] + + expect( + task, + `turbo.json has no "${PACKAGE_NAME}#test" task, so protect-ffi's test uses the generic "test" task, which does not wait for protect-ffi's own build. nativeLoading.test.ts reads lib/index.cjs, which only build writes.`, + ).toBeDefined() + expect(task.dependsOn).toEqual(expect.arrayContaining(['build', '^build'])) + }) + + it('keeps the settings of the generic test task', () => { + // The package-specific task replaces the generic one for this package. A + // setting left out here is lost for protect-ffi only, and nothing else + // would notice. + const turbo = readJsonc(join(REPO_ROOT, 'turbo.json')) + const generic = turbo.tasks.test + const specific = turbo.tasks[`${PACKAGE_NAME}#test`] + expect(specific).toBeDefined() + for (const key of Object.keys(generic)) { + if (key === 'dependsOn') continue + expect(specific[key], `"${PACKAGE_NAME}#test".${key}`).toEqual( + generic[key], + ) + } + }) +}) + +// The checks above are only as good as the helpers they use, so the helpers +// are tested on fixtures here. +describe('the helpers this guard relies on', () => { + it('follows every way pnpm can run a script', () => { + const fixture = { + test: 'pnpm build && pnpm -s run a && pnpm --silent run b && npm run c && pnpm exec d', + build: 'tsc', + a: 'true', + b: 'true', + c: 'true', + d: 'true', + } + const reached = [...reachableFrom('test', fixture)].filter( + (name) => name in fixture, + ) + expect(reached.sort()).toEqual(['a', 'b', 'build', 'c', 'test']) + }) + + it('finds tsc however the command names it', () => { + expect(tscCommands('tsc --noEmit && ./node_modules/.bin/tsc')).toEqual([ + ['--noEmit'], + [], + ]) + expect(tscCommands('npx tsc@5.9.3 -p tsconfig.json')).toEqual([ + ['-p', 'tsconfig.json'], + ]) + expect(tscCommands("sh -c 'tsc --noEmit'")).toEqual([['--noEmit']]) + expect(tscCommands('(tsc)')).toEqual([[]]) + expect(tscCommands('biome lint')).toEqual([]) + }) + + it('reads a tsconfig that has comments and trailing commas', () => { + const dir = mkdtempSync(join(tmpdir(), 'protect-ffi-no-emit-')) + try { + const configPath = join(dir, 'tsconfig.json') + writeFileSync( + configPath, + '{\n // tsc accepts comments\n "compilerOptions": { "noEmit": true, },\n}\n', + ) + expect(effectiveNoEmit(configPath)).toBe(true) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/turbo.json b/turbo.json index e49fc5ef83..a79a288637 100644 --- a/turbo.json +++ b/turbo.json @@ -49,6 +49,19 @@ "dependsOn": ["^build"], "outputs": ["lib/**"] }, + // protect-ffi's unit tests read the emitted `lib/index.cjs`, and its + // `test:typecheck` runs `tsc --noEmit`, so `build` is the only thing that + // writes `lib/`. Hence `build` here: the generic `test` task waits only + // for dependencies' builds. `test` must never write `lib/` itself — other + // packages' builds read `lib/*.d.*` while it runs, and a file tsc is + // rewriting is briefly empty. The other settings copy the generic `test` + // task. `scripts/__tests__/protect-ffi-test-no-emit.test.mjs` checks this. + "@cipherstash/protect-ffi#test": { + "dependsOn": ["^build", "build"], + "inputs": ["$TURBO_DEFAULT$", ".env*"], + "env": ["STASH_TEST_DATABASE_URL", "PG_TEST_URL"], + "cache": false + }, // These two builds `cpSync('../../../../skills', 'dist/skills')` — they consume a // directory OUTSIDE their own package, which `$TURBO_DEFAULT$` does not // cover. Without naming it here a skills-only edit does not invalidate the