mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
perf(ci): Phase 3 PR CI under 3m — 4x Runner support, 12x E2E, incremental TS 7 cache, pure-Node postinstall, and rebalanced shards (#22804)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Pull request CI verifies every change before merge across build, typecheck, server tests, Runner tests, and Playwright E2E shards. > - After Phase 1 (#22679) and Phase 2 (#22729), full-fanout PR CI still takes 9m45s wall-clock on 4-core AWS runners because of five bottlenecks: an unsharded 7m22s `Runner support suite`, stale server/chat/Runner shard duration manifests plus newly landed SSH/soak whales, 28s of `pnpm -r run postinstall` replay on every job, cold server/UI typecheck and single-build overhead, and 3 oversized (>180s) Playwright E2E specs across 8 shards with double-start Postgres template boot. > - Docs-only prose edits under `doc/**` and `docs/**` also fanned out to 66 CI jobs because only three doc paths bypassed global dependencies. > - This pull request shards `Runner support suite` 4 ways with `pool: "threads"`, shards E2E 12 ways after splitting the 3 oversized specs and removing double-start Postgres boot, adds pure-Node workspace postinstall replay, adds read-only master-warmed incremental TS 7 and Runner dist caches, rebalances all server/chat/Runner duration manifests, demotes 48 new non-invariant soak whales to nightly, and routes audited prose docs without triggering 66-job storms. > - The benefit is driving ordinary PR CI toward under 3 minutes wall-clock while preserving every invariant check, cache boundary, and full master/nightly test coverage. ## Linked Issues or Issue Description Refs #22679 Refs #22729 **What existing behavior does this improve?** Pull request CI wall-clock latency across `.github/workflows/pr-trusted.yml`, `.github/workflows/release-verify.yml`, `.github/actions/setup-ci-dependencies/action.yml`, typecheck orchestration, Vitest/Runner lanes, and Playwright E2E shards. **Subsystem affected** Cross-cutting (multiple of the above) **Current behavior** Full-fanout PR CI takes 9m45s on 4-core runners (run `45440355579`), dominated by `Runner support suite` (7m22s), `e2e shards` (5m02s–6m24s), `General tests (server/chat)` (5m37s–6m01s), `Verify Paperclip Runner (vitest package)` (6m25s on stale manifests), `Typecheck` (4m13s–6m30s), `Build` (~4m), and 28s of `pnpm -r postinstall` per job. Prose edits under `doc/**` trigger 66 jobs. **Proposed behavior** Shard `Runner support suite` (4x) and `e2e_shards` (12x), split the 3 oversized E2E specs, boot disposable E2E Postgres in a single non-durable start, replay workspace `postinstall` in pure Node (<1s), cache prebuilt Runner dist and TS 7 `.tsbuildinfo` from canonical `master` pushes (read-only in PRs), use emit-only server compile in ordinary PR `Build`, rebalance all shard duration manifests, demote 48 new non-invariant soak whales to nightly, and route audited prose docs cleanly. ## What Changed - **Pure-Node postinstall replay (`scripts/replay-workspace-postinstall.mjs`, `.github/actions/setup-ci-dependencies/action.yml`):** Replaces the 28s `pnpm -r --if-present run postinstall && pnpm run postinstall` call on every CI job with a pure-Node parallel runner (~0.84s locally) with fallback for older checkouts. - **4-way sharded `Runner support suite` + `threads` pool (`.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`, `tests/runner-e2e/run-unit.mjs`, `tests/runner-e2e/vitest.config.ts`):** Shards Vitest and `node:test` suites 4 ways (`--shard-index 0..3 --shard-count 4`) and switches `tests/runner-e2e` to `pool: "threads"` with CPU-aware `maxWorkers` while preserving `isolate: true`. - **12-way E2E shards, single-start E2E Postgres boot, and 3 oversized spec splits (`tests/e2e/start-e2e-server.ts`, `tests/e2e/*.spec.ts`, `tests/e2e/playwright.config.ts`, `scripts/e2e-shard.mjs`, `scripts/e2e-shard-durations.json`, `.github/ci-task-matrix.json`):** Boots cold ephemeral E2E Postgres in one `initdb --no-sync` + non-durable `postgresql.conf` start overlapped with server module import; splits `agent-chat-projects`, `chat-adapters-ui-providers`, and `chat-adapters-ui-messaging` cleanly with zero tests removed; balances all 54 specs across 12 shards (6.8s spread). - **Incremental TS 7 typecheck & Runner dist caching (`server/scripts/typecheck-layers.mjs`, `scripts/ci-typecheck-lane.mjs`, `scripts/typecheck-test-programs.mjs`, `scripts/typecheck-test-projects.mjs`, `.github/workflows/pr-trusted.yml`, `.github/workflows/release-verify.yml`):** Preserves portable `.tsbuildinfo`/`.d.ts` with `layer-map.json` invalidation and stale-declaration pruning, wires read-only `runner-dist-v1` and `typecheck-incremental-v1` restores in `pr-trusted.yml` (zero `actions/cache/save`) paired with canonical-`master`-only guarded writers in `release-verify.yml`, skips redundant Runner Rust `cargo check` on TS-only shared PRs, and uses LPT scheduling with concurrency 3 (4-core) / 4 (8-core). - **Emit-only PR `Build` & audited prose doc routing (`.github/workflows/pr-trusted.yml`, `.github/scripts/ci-inputs.mjs`):** Passes `PAPERCLIP_TSC_EMIT_ONLY=1` on ordinary PR `Build` jobs (full `pnpm build` on `full-ci` / `master`), and classifies audited prose Markdown under `doc/**` and `docs/**` as `guidance` / `historical` while keeping `docs/api/**`, JSON/TS fixtures, `maps/**`, and unknown files fail-closed. - **Rebalanced shard manifests & new soak demotions (`scripts/ci/nightly-only-suites.json`, `scripts/*-shard-durations.json`, `packages/paperclip-runner/scripts/vitest-lane-durations.json`, `packages/paperclip-runner/vitest.config.ts`, `packages/paperclip-runner/scripts/vitest-sequencer.mjs`):** Demotes 48 newly landed/grown non-invariant soak suites (including 4 real-SSH integration suites) to nightly, refreshes all 4 timing manifests from live CI measurements (0.1s–0.6s LPT skew), and scales Runner package Vitest CI `maxWorkers` to 3 on 4-core / 6 on 8-core. ## Verification - `node --test .github/scripts/tests/*.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs scripts/__tests__/public-install-closure.test.mjs scripts/__tests__/merge-queue-checks-workflow.test.mjs scripts/__tests__/e2e-shard.test.mjs scripts/__tests__/ci-typecheck-lane.test.mjs scripts/__tests__/run-vitest-stable-shard.test.mjs scripts/__tests__/run-vitest-stable-pr-mode.test.mjs scripts/__tests__/runner-vitest-package-lanes.test.mjs scripts/typecheck-test-programs.test.mjs scripts/check-test-budget.test.mjs scripts/ci/test-selection-pr-timings.test.mjs scripts/ci/test-selection-timings.test.mjs` — **973/973 PASS** - `node scripts/check-test-budget.mjs --base origin/master` — **PASS** (`609` nightly suites validated, zero protected invariants demoted) - `node scripts/check-maps.mjs` — **PASS** - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/source-sdk-public-inputs.test.mjs tests/runner-e2e/unit-launcher.test.mjs` — **PASS** - `pnpm --filter @paperclipai/paperclip-runner exec vitest run scripts/vitest-sequencer.test.mjs` — **PASS** - `cd server && node ../node_modules/vitest/vitest.mjs run scripts/typecheck-layers.test.mjs scripts/typecheck-layers-incremental.test.mjs` — **56/56 PASS** (real TS 7.0.2 incremental soundness tests) - `node scripts/run-tsc.mjs -p tests/e2e/tsconfig.json --noEmit && node scripts/run-tsc.mjs -p tests/tsconfig.playwright.json --noEmit && pnpm run test:e2e:runner:typecheck` — **0 errors** - Live Playwright smoke passed across all 6 split E2E spec files on the cold non-durable Postgres boot path (`PAPERCLIP_TEST_POSTGRES_TEMPLATE=0`). - Live sharded `tests/runner-e2e` runs passed under `pool: "threads", maxWorkers: 4` (shard `1/4` 172/172 PASS; shard `2/4` all Vitest + 65/65 `node:test` PASS). ## Risks - **Cache invalidation on incremental typecheck / Runner dist:** Mitigated by exact-key hashing (including `packages/{shared,adapter-utils,plugins/sdk}/src/**` and `packages/paperclip-runner/spec/**`) with no `restore-keys:` on `runner-dist-v1`, SHA-256 self-validation inside `prepare-runner-vendor.mjs`, `layer-map.json` invalidation + stale `.d.ts` pruning in `typecheck-layers.mjs`, and read-only PR restores (only canonical `master` pushes save caches). - **Shard rebalancing & soak demotions:** All demoted suites remain in `nightly-only-suites.json` and run on `full-ci` / `master` / nightly; `check-test-budget.mjs` enforces zero protected invariants are demoted. - **Workflow security boundaries:** `ci-routing.yml`, `pr.yml`, `CODEOWNERS`, and all `runs-on:` expressions are unchanged; `pr-trusted.yml` performs zero `actions/cache/save` calls. ## Model Used - Google Gemini (Antigravity agent swarm) with extended reasoning, tool use, and local code/test execution across 6 parallel worker roles (`ci-pipeline`, `vitest-runner`, `server-prune`, `e2e-opt`, `typecheck-opt`, `verifier`). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
3ca9b6d471
commit
cffd17e78a
39 files changed
+6684
-4813
No files matched your search
@@ -0,0 +1,196 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
utimesSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { typecheckLayers } from "./typecheck-layers.mjs";
|
||||
|
||||
const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const realTsc = path.join(serverRoot, "node_modules", "typescript", "bin", "tsc");
|
||||
const outputDir = (root) => path.join(root, "node_modules", ".cache", "paperclip-typecheck");
|
||||
|
||||
describe("typecheckLayers incremental cache soundness", () => {
|
||||
const roots = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function compilerFixture() {
|
||||
const root = mkdtempSync(path.join(tmpdir(), "typecheck-layers-inc-"));
|
||||
roots.push(root);
|
||||
mkdirSync(path.join(root, "src", "__tests__"), { recursive: true });
|
||||
writeFileSync(path.join(root, "package.json"), `${JSON.stringify({ type: "module" })}\n`);
|
||||
writeFileSync(
|
||||
path.join(root, "tsconfig.json"),
|
||||
`${JSON.stringify({
|
||||
compilerOptions: {
|
||||
target: "ES2023",
|
||||
module: "NodeNext",
|
||||
moduleResolution: "NodeNext",
|
||||
strict: true,
|
||||
skipLibCheck: true,
|
||||
types: [],
|
||||
},
|
||||
include: ["src"],
|
||||
exclude: ["src/__tests__"],
|
||||
})}\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(root, "src", "__tests__", "tsconfig.json"),
|
||||
`${JSON.stringify({
|
||||
extends: "../../tsconfig.json",
|
||||
compilerOptions: { noEmit: true, rootDir: "../.." },
|
||||
include: ["."],
|
||||
})}\n`,
|
||||
);
|
||||
writeFileSync(path.join(root, "src", "leaf.ts"), `export const leaf = (): number => 1;\n`);
|
||||
writeFileSync(
|
||||
path.join(root, "src", "one.ts"),
|
||||
`import { leaf } from "./leaf.js";\nimport { two } from "./two.js";\nexport const one = (n = 0): number => (n > 0 ? two(n - 1) : leaf());\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(root, "src", "two.ts"),
|
||||
`import { one } from "./one.js";\nexport const two = (n = 0): number => (n > 0 ? one(n - 1) : 1);\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(root, "src", "route.ts"),
|
||||
`import { one } from "./one.js";\nexport const route = (): number => one();\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(root, "src", "route.test.ts"),
|
||||
`import { route } from "./route.js";\nexport const routeCheck: number = route();\n`,
|
||||
);
|
||||
writeFileSync(
|
||||
path.join(root, "src", "__tests__", "tree.test.ts"),
|
||||
`import { route } from "../route.js";\nexport const treeCheck: number = route();\n`,
|
||||
);
|
||||
return root;
|
||||
}
|
||||
|
||||
function runReal(root, options = {}) {
|
||||
const chunks = [];
|
||||
const status = typecheckLayers({
|
||||
serverRoot: root,
|
||||
log: () => {},
|
||||
logError: (msg) => chunks.push(`${msg}\n`),
|
||||
run: (args, { cwd }) => {
|
||||
const result = spawnSync(process.execPath, [realTsc, ...args, "--pretty", "false"], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
chunks.push(result.stdout, result.stderr);
|
||||
return { status: result.status ?? 1, signal: result.signal };
|
||||
},
|
||||
...options,
|
||||
});
|
||||
return { status, output: chunks.join("") };
|
||||
}
|
||||
|
||||
function backdateDirectory(dir, ageSeconds = 3600) {
|
||||
const past = new Date(Date.now() - ageSeconds * 1000);
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) backdateDirectory(fullPath, ageSeconds);
|
||||
else utimesSync(fullPath, past, past);
|
||||
}
|
||||
}
|
||||
|
||||
it("preserves tsbuildinfo across warm runs and avoids rewriting unchanged layer configs", () => {
|
||||
const root = compilerFixture();
|
||||
expect(runReal(root)).toEqual({ status: 0, output: "" });
|
||||
|
||||
const out = outputDir(root);
|
||||
const buildInfos = readdirSync(out).filter((name) => name.endsWith(".tsbuildinfo")).sort();
|
||||
expect(buildInfos).toEqual(
|
||||
expect.arrayContaining(["above.tsbuildinfo", "below.tsbuildinfo", "cycle.tsbuildinfo", "tests.tsbuildinfo"]),
|
||||
);
|
||||
expect(buildInfos.some((name) => name.startsWith("test-tree-"))).toBe(true);
|
||||
expect(existsSync(path.join(out, "layer-map.json"))).toBe(true);
|
||||
|
||||
backdateDirectory(out, 3600);
|
||||
const beforeMtime = statSync(path.join(out, "tsconfig.below.json")).mtimeMs;
|
||||
|
||||
expect(runReal(root)).toEqual({ status: 0, output: "" });
|
||||
expect(statSync(path.join(out, "tsconfig.below.json")).mtimeMs).toBe(beforeMtime);
|
||||
}, 60_000);
|
||||
|
||||
it("catches export type regressions across layers and test trees even when restored cache mtimes are older", () => {
|
||||
const root = compilerFixture();
|
||||
expect(runReal(root)).toEqual({ status: 0, output: "" });
|
||||
|
||||
// Simulate restoring a master cache onto a fresh git checkout whose source files are newer.
|
||||
backdateDirectory(outputDir(root), 3600);
|
||||
|
||||
// Change route() return type from number to string; tests + test-tree must fail.
|
||||
writeFileSync(
|
||||
path.join(root, "src", "route.ts"),
|
||||
`import { one } from "./one.js";\nexport const route = (): string => String(one());\n`,
|
||||
);
|
||||
const failed = runReal(root);
|
||||
expect(failed.status).not.toBe(0);
|
||||
expect(failed.output).toMatch(/route\.test\.ts.*TS2322/);
|
||||
expect(failed.output).toMatch(/tree\.test\.ts.*TS2322/);
|
||||
}, 60_000);
|
||||
|
||||
it("prunes stale declarations for deleted source files so dangling imports fail with TS2307", () => {
|
||||
const root = compilerFixture();
|
||||
writeFileSync(path.join(root, "src", "extra.ts"), `export const extra = 42;\n`);
|
||||
writeFileSync(
|
||||
path.join(root, "src", "route.ts"),
|
||||
`import { one } from "./one.js";\nimport { extra } from "./extra.js";\nexport const route = (): number => one() + extra;\n`,
|
||||
);
|
||||
expect(runReal(root)).toEqual({ status: 0, output: "" });
|
||||
expect(existsSync(path.join(outputDir(root), "dts", "extra.d.ts"))).toBe(true);
|
||||
|
||||
rmSync(path.join(root, "src", "extra.ts"));
|
||||
const failed = runReal(root);
|
||||
expect(failed.status).not.toBe(0);
|
||||
expect(existsSync(path.join(outputDir(root), "dts", "extra.d.ts"))).toBe(false);
|
||||
expect(failed.output).toMatch(/route\.ts.*TS2307/);
|
||||
}, 60_000);
|
||||
|
||||
it("invalidates affected layers when a file moves from below to above", () => {
|
||||
const root = compilerFixture();
|
||||
writeFileSync(path.join(root, "src", "mover.ts"), `export const moved = (): number => 1;\n`);
|
||||
expect(runReal(root)).toEqual({ status: 0, output: "" });
|
||||
|
||||
// Adding an import on `one.ts` moves `mover.ts` from `below` into `above`.
|
||||
writeFileSync(
|
||||
path.join(root, "src", "mover.ts"),
|
||||
`import { one } from "./one.js";\nexport const moved = (): number => one() + 1;\n`,
|
||||
);
|
||||
const result = runReal(root);
|
||||
expect(result).toEqual({ status: 0, output: "" });
|
||||
}, 60_000);
|
||||
|
||||
it("starts clean when dts exists without layer-map.json or when clean is requested", () => {
|
||||
const root = compilerFixture();
|
||||
expect(runReal(root)).toEqual({ status: 0, output: "" });
|
||||
|
||||
const out = outputDir(root);
|
||||
const orphanDts = path.join(out, "dts", "phantom.d.ts");
|
||||
writeFileSync(orphanDts, "export declare const phantom: number;\n");
|
||||
rmSync(path.join(out, "layer-map.json"));
|
||||
|
||||
expect(runReal(root)).toEqual({ status: 0, output: "" });
|
||||
expect(existsSync(orphanDts)).toBe(false);
|
||||
expect(existsSync(path.join(out, "layer-map.json"))).toBe(true);
|
||||
|
||||
const marker = path.join(out, "marker.txt");
|
||||
writeFileSync(marker, "stale");
|
||||
expect(runReal(root, { clean: true })).toEqual({ status: 0, output: "" });
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -25,7 +25,7 @@
|
||||
// `tsconfig.layers.json` that references tsconfig.declarations.json in the output
|
||||
// directory. --declarations-only builds those layers and skips the test layers.
|
||||
//
|
||||
// Usage: node scripts/typecheck-layers.mjs [--declarations-only | --layer <name>] [--checkers <n>]
|
||||
// Usage: node scripts/typecheck-layers.mjs [--declarations-only | --layer <name>] [--checkers <n>] [--clean]
|
||||
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
@@ -214,6 +214,10 @@ export function layerConfig(layer, { emptyLayers = new Set() } = {}) {
|
||||
if (layer.testTree) {
|
||||
return {
|
||||
extends: fromOutput("src/__tests__/tsconfig.json"),
|
||||
compilerOptions: {
|
||||
incremental: true,
|
||||
tsBuildInfoFile: `./${layer.name}.tsbuildinfo`,
|
||||
},
|
||||
files: layer.files.map(fromOutput),
|
||||
include: [],
|
||||
references,
|
||||
@@ -221,7 +225,15 @@ export function layerConfig(layer, { emptyLayers = new Set() } = {}) {
|
||||
}
|
||||
const output =
|
||||
layer.name === "tests"
|
||||
? { composite: false, declaration: false, declarationMap: false, sourceMap: false, noEmit: true }
|
||||
? {
|
||||
composite: false,
|
||||
incremental: true,
|
||||
tsBuildInfoFile: `./${layer.name}.tsbuildinfo`,
|
||||
declaration: false,
|
||||
declarationMap: false,
|
||||
sourceMap: false,
|
||||
noEmit: true,
|
||||
}
|
||||
: {
|
||||
composite: true,
|
||||
declaration: true,
|
||||
@@ -279,11 +291,124 @@ function checkOneLayer({ serverRoot, name, checkers, run, log, logError }) {
|
||||
return status;
|
||||
}
|
||||
|
||||
function writeIfChanged(filePath, content) {
|
||||
try {
|
||||
if (existsSync(filePath) && readFileSync(filePath, "utf8") === content) return false;
|
||||
} catch {}
|
||||
writeFileSync(filePath, content);
|
||||
return true;
|
||||
}
|
||||
|
||||
function sourceToDtsRelative(sourceFile) {
|
||||
return sourceFile.replace(/^src\//, "").replace(/\.tsx?$/, ".d.ts");
|
||||
}
|
||||
|
||||
function pruneStaleDeclarations(dtsRoot, expectedDts) {
|
||||
if (!existsSync(dtsRoot)) return;
|
||||
const walk = (directory, relativePrefix) => {
|
||||
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||
const fullPath = path.join(directory, entry.name);
|
||||
const relative = relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name;
|
||||
if (entry.isDirectory()) {
|
||||
walk(fullPath, relative);
|
||||
try {
|
||||
if (readdirSync(fullPath).length === 0) rmSync(fullPath, { recursive: true, force: true });
|
||||
} catch {}
|
||||
} else if (!expectedDts.has(relative)) {
|
||||
rmSync(fullPath, { force: true });
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(dtsRoot, "");
|
||||
}
|
||||
|
||||
function syncOutputDirectory({ outputRoot, layers, emptyLayers, clean }) {
|
||||
const layerMapPath = path.join(outputRoot, "layer-map.json");
|
||||
const dtsRoot = path.join(outputRoot, "dts");
|
||||
let previousLayerMap = null;
|
||||
|
||||
if (clean) {
|
||||
rmSync(outputRoot, { recursive: true, force: true });
|
||||
} else if (existsSync(outputRoot)) {
|
||||
try {
|
||||
previousLayerMap = JSON.parse(readFileSync(layerMapPath, "utf8"));
|
||||
if (!previousLayerMap || typeof previousLayerMap !== "object" || Array.isArray(previousLayerMap)) {
|
||||
previousLayerMap = null;
|
||||
}
|
||||
} catch {
|
||||
previousLayerMap = null;
|
||||
}
|
||||
// Untracked/corrupt cache without a valid layer map starts clean to prevent stale .d.ts reuse.
|
||||
if (previousLayerMap === null && existsSync(dtsRoot)) {
|
||||
rmSync(outputRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
mkdirSync(outputRoot, { recursive: true });
|
||||
|
||||
const currentLayerMap = {};
|
||||
const expectedDts = new Set();
|
||||
for (const layer of layers) {
|
||||
if (!emitsDeclarations(layer)) continue;
|
||||
for (const sourceFile of layer.sourceFiles) {
|
||||
currentLayerMap[sourceFile] = layer.name;
|
||||
expectedDts.add(sourceToDtsRelative(sourceFile));
|
||||
}
|
||||
}
|
||||
|
||||
// Invalidate any layer whose file ownership shifted, and remove stale .d.ts files for deleted/moved sources.
|
||||
if (previousLayerMap) {
|
||||
const invalidatedLayers = new Set();
|
||||
for (const [sourceFile, prevLayer] of Object.entries(previousLayerMap)) {
|
||||
const nextLayer = currentLayerMap[sourceFile];
|
||||
if (nextLayer !== prevLayer) {
|
||||
rmSync(path.join(dtsRoot, sourceToDtsRelative(sourceFile)), { force: true });
|
||||
invalidatedLayers.add(prevLayer);
|
||||
if (nextLayer) invalidatedLayers.add(nextLayer);
|
||||
}
|
||||
}
|
||||
for (const layerName of invalidatedLayers) {
|
||||
rmSync(path.join(outputRoot, `${layerName}.tsbuildinfo`), { force: true });
|
||||
}
|
||||
}
|
||||
pruneStaleDeclarations(dtsRoot, expectedDts);
|
||||
|
||||
// Remove stale configs/tsbuildinfo for layers that no longer exist.
|
||||
const planned = new Set(layers.map((layer) => layer.name));
|
||||
for (const entry of readdirSync(outputRoot, { withFileTypes: true })) {
|
||||
if (!entry.isFile()) continue;
|
||||
const configMatch = entry.name.match(/^tsconfig\.(.+)\.json$/);
|
||||
if (configMatch && configMatch[1] !== "declarations" && !planned.has(configMatch[1])) {
|
||||
rmSync(path.join(outputRoot, entry.name), { force: true });
|
||||
continue;
|
||||
}
|
||||
const buildInfoMatch = entry.name.match(/^(.+)\.tsbuildinfo$/);
|
||||
if (buildInfoMatch && !planned.has(buildInfoMatch[1])) {
|
||||
rmSync(path.join(outputRoot, entry.name), { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Without this, the path under node_modules would make the declarations CommonJS.
|
||||
writeIfChanged(path.join(outputRoot, "package.json"), `${JSON.stringify({ type: "module" })}\n`);
|
||||
for (const layer of layers) {
|
||||
writeIfChanged(
|
||||
path.join(outputRoot, `tsconfig.${layer.name}.json`),
|
||||
`${JSON.stringify(layerConfig(layer, { emptyLayers }), null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
writeIfChanged(
|
||||
path.join(outputRoot, "tsconfig.declarations.json"),
|
||||
`${JSON.stringify(declarationsConfig(layers), null, 2)}\n`,
|
||||
);
|
||||
writeIfChanged(layerMapPath, `${JSON.stringify(currentLayerMap, null, 2)}\n`);
|
||||
}
|
||||
|
||||
export function typecheckLayers({
|
||||
serverRoot,
|
||||
declarationsOnly = false,
|
||||
layer: only,
|
||||
checkers,
|
||||
clean = false,
|
||||
run = runTsc,
|
||||
log = console.log,
|
||||
logError = console.error,
|
||||
@@ -294,21 +419,7 @@ export function typecheckLayers({
|
||||
const emptyLayers = new Set(["below", "cycle", "above", "tests"].filter((name) => !planned.has(name)));
|
||||
|
||||
const outputRoot = path.join(serverRoot, OUTPUT_DIRECTORY);
|
||||
rmSync(outputRoot, { recursive: true, force: true });
|
||||
mkdirSync(outputRoot, { recursive: true });
|
||||
// Without this, the path under node_modules would make the declarations CommonJS.
|
||||
writeFileSync(path.join(outputRoot, "package.json"), `${JSON.stringify({ type: "module" })}\n`);
|
||||
for (const layer of layers) {
|
||||
writeFileSync(
|
||||
path.join(outputRoot, `tsconfig.${layer.name}.json`),
|
||||
`${JSON.stringify(layerConfig(layer, { emptyLayers }), null, 2)}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
writeFileSync(
|
||||
path.join(outputRoot, "tsconfig.declarations.json"),
|
||||
`${JSON.stringify(declarationsConfig(layers), null, 2)}\n`,
|
||||
);
|
||||
syncOutputDirectory({ outputRoot, layers, emptyLayers, clean });
|
||||
|
||||
const extraArgs = checkerTscArgs(checkers);
|
||||
let exitCode = 0;
|
||||
@@ -332,6 +443,7 @@ export function typecheckLayers({
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const args = process.argv.slice(2);
|
||||
let declarationsOnly = false;
|
||||
let clean = false;
|
||||
let layer;
|
||||
let checkers;
|
||||
let valid = true;
|
||||
@@ -339,6 +451,8 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
|
||||
const arg = args[i];
|
||||
if (arg === "--declarations-only") {
|
||||
declarationsOnly = true;
|
||||
} else if (arg === "--clean") {
|
||||
clean = true;
|
||||
} else if (arg === "--layer") {
|
||||
layer = args[++i];
|
||||
if (!layer || layer.startsWith("--")) valid = false;
|
||||
@@ -351,7 +465,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
|
||||
}
|
||||
if (declarationsOnly && layer) valid = false;
|
||||
if (!valid) {
|
||||
console.error("Usage: node scripts/typecheck-layers.mjs [--declarations-only | --layer <name>] [--checkers <n>]");
|
||||
console.error("Usage: node scripts/typecheck-layers.mjs [--declarations-only | --layer <name>] [--checkers <n>] [--clean]");
|
||||
process.exitCode = 2;
|
||||
} else {
|
||||
process.exitCode = typecheckLayers({
|
||||
@@ -359,6 +473,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
|
||||
declarationsOnly,
|
||||
layer,
|
||||
checkers,
|
||||
clean,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -180,7 +180,12 @@ describe("layerConfig", () => {
|
||||
{ emptyLayers: new Set(["cycle"]) },
|
||||
);
|
||||
|
||||
expect(config.compilerOptions).toMatchObject({ composite: false, noEmit: true });
|
||||
expect(config.compilerOptions).toMatchObject({
|
||||
composite: false,
|
||||
incremental: true,
|
||||
tsBuildInfoFile: "./tests.tsbuildinfo",
|
||||
noEmit: true,
|
||||
});
|
||||
expect(config.references).toEqual([{ path: "./tsconfig.below.json" }]);
|
||||
});
|
||||
});
|
||||
@@ -195,7 +200,10 @@ describe("layerConfig for the test tree", () => {
|
||||
});
|
||||
|
||||
expect(config.extends).toBe("../../../src/__tests__/tsconfig.json");
|
||||
expect(config.compilerOptions).toBeUndefined();
|
||||
expect(config.compilerOptions).toEqual({
|
||||
incremental: true,
|
||||
tsBuildInfoFile: "./test-tree-0.tsbuildinfo",
|
||||
});
|
||||
expect(config.files).toEqual(["../../../src/__tests__/a.test.ts"]);
|
||||
expect(config.references).toEqual([{ path: "./tsconfig.below.json" }]);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user