From a096bac5648fd29b5dd60357b32a9d24744ae80c Mon Sep 17 00:00:00 2001 From: alowpoly Date: Thu, 3 Dec 2026 17:41:46 -0300 Subject: [PATCH] chore(infra): centralize workspace source aliases and add CI-checked repo map --- .github/architecture/repo-map.md | 110 +++ .github/scripts/generate-repo-map.mjs | 639 ++++++++++++++++++ .github/scripts/generate-repo-map.test.mjs | 93 +++ AGENTS.md | 2 +- bench/build.mjs | 10 +- package.json | 4 +- packages/fonts/vitest.config.ts | 5 +- packages/morph/vitest.config.ts | 6 +- packages/polycss/vitest.config.ts | 6 +- packages/react/vitest.config.ts | 7 +- packages/vitest.base.mjs | 11 +- packages/vue/vitest.config.ts | 7 +- packages/workspace-aliases.mjs | 78 +++ website/astro.config.mjs | 28 +- .../generate-builder-shape-thumbnails.mjs | 7 +- .../scripts/generate-gallery-domformat.mjs | 10 +- website/scripts/prove-gallery-domformat.mjs | 11 +- website/tsconfig.json | 14 +- 18 files changed, 959 insertions(+), 89 deletions(-) create mode 100644 .github/architecture/repo-map.md create mode 100644 .github/scripts/generate-repo-map.mjs create mode 100644 .github/scripts/generate-repo-map.test.mjs create mode 100644 packages/workspace-aliases.mjs diff --git a/.github/architecture/repo-map.md b/.github/architecture/repo-map.md new file mode 100644 index 00000000..a1369ff6 --- /dev/null +++ b/.github/architecture/repo-map.md @@ -0,0 +1,110 @@ + +# PolyCSS Repository Map + +Tracked production code scanned across `packages/*/src`, `bench/`, and `website/src`: **421 files**, **101,578 lines**. Regenerate with `pnpm map`; verified in CI by `pnpm check:map`. + +## 1. Packages & Entry Points + +| Package | Visibility | Exports | Workspace deps | Src files | Src lines | Test files | +|---|---|---|---|---:|---:|---:| +| `packages/core` (`@layoutit/polycss-core`) | npm | `., ./three` | — | 75 | 27,024 | 58 | +| `packages/domformat` (`@layoutit/polycss-domformat`) | private | `., ./browser` | — | 36 | 13,165 | 0 | +| `packages/fonts` (`@layoutit/polycss-fonts`) | npm | `.` | `@layoutit/polycss-core` | 7 | 1,661 | 4 | +| `packages/morph` (`@layoutit/polycss-morph`) | npm | `., ./prepare` | `@layoutit/polycss`, `@layoutit/polycss-core` | 49 | 7,633 | 14 | +| `packages/polycss` (`@layoutit/polycss`) | npm | `., ./runtime, ./elements, ./three` | `@layoutit/polycss-core` | 62 | 16,582 | 40 | +| `packages/react` (`@layoutit/polycss-react`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 44 | 6,398 | 31 | +| `packages/skills` (`@layoutit/polycss-skills`) | npm | `.` | — | 1 | 415 | 1 | +| `packages/vue` (`@layoutit/polycss-vue`) | npm | `., ./three` | `@layoutit/polycss`, `@layoutit/polycss-core` | 42 | 5,560 | 29 | + +## 2. Canonical Workspace Source Aliases + +Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/workspace-aliases.mjs) (validated against every `package.json#exports` and `website/tsconfig.json`). + +| Specifier | Source entry | +|---|---| +| `@layoutit/polycss-core/three` | `packages/core/src/three/index.ts` | +| `@layoutit/polycss-core` | `packages/core/src/index.ts` | +| `@layoutit/polycss/runtime` | `packages/polycss/src/runtime.ts` | +| `@layoutit/polycss/elements` | `packages/polycss/src/elements/index.ts` | +| `@layoutit/polycss/three` | `packages/polycss/src/three.ts` | +| `@layoutit/polycss` | `packages/polycss/src/index.ts` | +| `@layoutit/polycss-react/three` | `packages/react/src/three/index.ts` | +| `@layoutit/polycss-react` | `packages/react/src/index.ts` | +| `@layoutit/polycss-vue/three` | `packages/vue/src/three/index.ts` | +| `@layoutit/polycss-vue` | `packages/vue/src/index.ts` | +| `@layoutit/polycss-fonts` | `packages/fonts/src/index.ts` | +| `@layoutit/polycss-morph/prepare` | `packages/morph/src/prepare.ts` | +| `@layoutit/polycss-morph` | `packages/morph/src/index.ts` | + +**Consumers (12):** `bench/build.mjs`, `packages/fonts/vitest.config.ts`, `packages/morph/vitest.config.ts`, `packages/polycss/vitest.config.ts`, `packages/react/vitest.config.ts`, `packages/vitest.base.mjs`, `packages/vue/vitest.config.ts`, `website/astro.config.mjs`, `website/scripts/generate-builder-shape-thumbnails.mjs`, `website/scripts/generate-gallery-domformat.mjs`, `website/scripts/prove-gallery-domformat.mjs`, `website/tsconfig.json` + +## 3. Top Import Hubs (`fanIn`) & Largest Source Files + +### Highest `fanIn` (production files importing this file) + +| Fan-in | Lines | File | +|---:|---:|---| +| 108 | 642 | `packages/core/src/index.ts` | +| 65 | 248 | `packages/core/src/types.ts` | +| 32 | 301 | `packages/react/src/index.ts` | +| 31 | 119 | `website/src/components/types.ts` | +| 24 | 147 | `packages/polycss/src/runtime.ts` | +| 18 | 218 | `packages/polycss/src/index.ts` | +| 18 | 88 | `website/src/components/GalleryWorkbench/types.ts` | +| 13 | 283 | `packages/polycss/src/elements/PolySceneElement.ts` | +| 13 | 45 | `packages/polycss/src/render/textureAtlas.ts` | +| 13 | 41 | `packages/react/src/camera/context.ts` | +| 12 | 1,396 | `packages/polycss/src/api/createPolyScene.ts` | +| 11 | 101 | `packages/core/src/atlas/constants.ts` | + +### Largest production source files + +| Lines | File | +|---:|---| +| 3,578 | `packages/domformat/src/schema.ts` | +| 2,746 | `packages/core/src/merge/optimizePolygons.ts` | +| 2,185 | `packages/core/src/shadow/computeReceiverShadows.ts` | +| 2,017 | `packages/core/src/parser/parseGltf.ts` | +| 1,935 | `packages/domformat/src/state/polycss.ts` | +| 1,592 | `packages/core/src/merge/seamRepair.ts` | +| 1,527 | `website/src/components/GalleryWorkbench/GalleryWorkbench.tsx` | +| 1,396 | `packages/polycss/src/api/createPolyScene.ts` | +| 1,283 | `website/src/components/VanillaScene/VanillaScene.tsx` | +| 1,227 | `packages/react/src/controls/TransformControls.tsx` | +| 1,214 | `website/src/components/WordArtWorkbench/WordArtWorkbench.tsx` | +| 1,198 | `bench/visual-gate.mjs` | + +## 4. Core Render & Control Pipelines + +| Pipeline | Entry chain (`file:symbol`) | Notes | +|---|---|---| +| **Parse & Optimize** | `packages/core/src/parser/loadMesh.ts` (`loadMesh`) → `packages/core/src/parser/parseGltf.ts` (`parseGltf`) → `packages/core/src/merge/optimizePolygons.ts` (`optimizeMeshPolygons`) | OBJ/GLB/glTF/VOX/STL -> `Polygon[]` (+ optional `voxelSource`). Pure ES2020 in `core`. | +| **Atlas Plan & Leaf Emit** | `packages/core/src/atlas/plan.ts` (`computeTextureAtlasPlan`) → `packages/polycss/src/render/atlas/packing.ts` (`packTextureAtlasPlansWithScale`) → `packages/polycss/src/render/atlas/renderPolygons.ts` (`renderPolygonsWithTextureAtlas`) → `packages/polycss/src/render/voxelRenderer.ts` (`createPolyVoxelRenderer`) | Cheapest strategy per polygon (`` -> `` -> `` -> ``); direct voxel fast path for baked `.vox`. | +| **Scene Runtime & Rebake** | `packages/polycss/src/api/createPolyScene.ts` (`createPolyScene`) → `packages/polycss/src/api/scene/mountSync.ts` (`syncMountedRendered`) → `packages/polycss/src/api/scene/rebake.ts` (`requestRebakeAtlas`) → `packages/polycss/src/api/scene/lightingVars.ts` (`applyDynamicLightVars`) | Single DOM renderer exposed via `@layoutit/polycss/runtime`; no per-frame rAF leaf writes. | +| **Cast & Receiver Shadows** | `packages/core/src/shadow/computeReceiverShadows.ts` (`computeMergedReceiverShadows`) → `packages/polycss/src/api/scene/shadowOrchestrator.ts` (`emitSceneShadows`) → `packages/polycss/src/api/scene/shadowSvg.ts` (`ensureGroundShadow`) → `packages/polycss/src/api/scene/shadowCache.ts` (`clearAllSceneShadows`) | CPU-projected SVG overlays under `.polycss-shadows`; cached by quantized light + camera facing. | +| **React & Vue Adopt-DOM** | `packages/react/src/scene/PolyScene.tsx` (`PolyScene`) → `packages/react/src/scene/PolyMesh.tsx` (`PolyMesh`) → `packages/vue/src/scene/PolyScene.ts` (`PolyScene`) → `packages/vue/src/scene/PolyMesh.ts` (`PolyMesh`) | Framework owns outer `
` refs; runtime adopts elements (`elements`, `wrapper`) with `bakedLightPolicy: "auto"`. | +| **Morph & Domformat** | `packages/morph/src/prepare/prepare.ts` (`preparePolyMorphModel`) → `packages/morph/src/render/mount.ts` (`mountPolyMorphModel`) → `packages/domformat/src/schema.ts` (`validatePolycssChannelInvariants`) | Prepared runtime & closed `domformat@0` wire contract (private, producer-neutral). | + +## 5. Mutable Runtime State Containers & Invariants + +| Container | Owner (`file:symbol`) | Key mutable fields | Primary writers | Invariant | +|---|---|---|---|---| +| **SceneContext** | `packages/polycss/src/api/scene/sceneContext.ts` (`SceneContext`) | `options.current`, `meshes`, `shadowSvgState`, `lastEmittedShadowLightKey` | `packages/polycss/src/api/createPolyScene.ts` (`setOptions`), `packages/polycss/src/api/scene/shadowOrchestrator.ts` (`emitSceneShadows`) | `setOptions` checks `hasOwnProperty` for every optional prop (including `textureQuality`, `directionalLight`, `strategies`, `shadow`) so clearing to `undefined` updates leaves and shadows. | +| **MeshEntry** | `packages/polycss/src/api/scene/internalTypes.ts` (`MeshEntry`) | `rebakeInFlight`, `rebakeQueued`, `stableDom`, `adoptedWrapper`, `ownedNodes`, `atomicSwapVersion`, `disposed`, `renderOverrides` | `packages/polycss/src/api/createPolyScene.ts` (`renderEntry`), `packages/polycss/src/api/scene/rebake.ts` (`rebakeRenderEntryInPlace`), `packages/polycss/src/api/scene/mountLifecycle.ts` (`clearMountedRendered`) | Every path in `rebakeRenderEntryInPlace` must run `finish()` to clear `rebakeInFlight` and drain `rebakeQueued`. `stableDom` resets to `false` when polygons are not stable-triangle eligible. `adoptedWrapper` is never removed from DOM on dispose. | +| **ShadowSvgState** | `packages/polycss/src/api/scene/shadowSvg.ts` (`ShadowSvgState`) | `shadowRoot`, `groundSvg`, `groundVisible`, `currentGroundCssZ` | `packages/polycss/src/api/scene/shadowSvg.ts` (`disposeShadowRoot`), `packages/polycss/src/api/scene/shadowCache.ts` (`clearAllSceneShadows`) | `clearAllSceneShadows` (called on `scene.destroy()`) detaches `shadowRoot` so adopted `` elements never accumulate orphan `.polycss-shadows` wrappers across StrictMode remounts. | +| **CameraHandle** | `packages/polycss/src/api/createPolyCamera.ts` (`createPolyCamera`) | `state` (`rotX`, `rotY`, `zoom`, `distance`, `target`) | `packages/polycss/src/api/createPolyOrbitControls.ts` (`createPolyOrbitControls`), `packages/react/src/camera/useCamera.ts` (`usePolyCamera`), `packages/vue/src/camera/useCamera.ts` (`usePolyCamera`) | Mutating camera state requires `scene.applyCamera()` to flush DOM transforms, voxel face culling, and receiver-shadow visibility boundaries. | +| **React runtimeSceneSlot** | `packages/react/src/scene/sceneContext.ts` (`RuntimeSceneSlot`) | `current`, `subscribe`, `set` | `packages/react/src/scene/PolyScene.tsx` (`PolyScene`), `packages/react/src/scene/PolyMesh.tsx` (`PolyMesh`) | Synchronous commit-1 handoff from `` to child `` without triggering extra React re-renders; `` preserves `.polycss-voxel-mesh` across `className` updates and skips redundant `setTransform` on dynamic mount. | +| **Vue sceneCtx** | `packages/vue/src/scene/sceneContext.ts` (`PolySceneContextKey`) | `runtimeScene` ref, `isLoadingSlot`, `activeVoxelSource` | `packages/vue/src/scene/PolyScene.ts` (`PolyScene`), `packages/vue/src/scene/PolyMesh.ts` (`PolyMesh`) | `PolyMesh` watches `isLoadingSlot`/`activeVoxelSource` with `flush: "post"` and `polygons` with `flush: "pre"` so async `src` transitions mount once and `props.class` updates preserve `.polycss-voxel-mesh`. | + +## 6. Verification Gate Coverage Matrix + +| Gate | Command | What it proves | Explicit blind spots | +|---|---|---|---| +| **Static guards & script tests** | `pnpm check:guards` | Package dependency + `/runtime`-only subpath boundaries, React↔Vue mirror/export parity, `AGENTS.md` size & links, README/skill sync, alias & repo-map freshness, gate unit tests. | Runtime browser behavior, CSS rendering, pixel output, timing. | +| **Unit & coverage suite** | `pnpm test:coverage` | Math, parsers, shadow geometry, runtime seams, and React/Vue component logic under `happy-dom` + v8 coverage thresholds across all 8 packages. | Real browser layout/compositing, WebKit/Firefox quirks, real Canvas/Blob image decoding. | +| **3-way DOM/CSS IR conformance** | `pnpm check:ir` | Compiled `polycss`, `react`, and `vue` `dist/index.js` emit matching DOM tags, lighting vars, transforms, and shadows in `happy-dom`. | Post-mount mutations, real browser pixel rasterization. | +| **Tarball pack check** | `pnpm check:packs` | All 7 publishable tarballs contain declared entries + `typesVersions` + `README.md`, zero `workspace:` leaks, zero test files. | Runtime execution inside consumer apps. | +| **Visual pixelmatch gate** | `pnpm bench:gate:ci -- --base-ref origin/main --browsers chromium,firefox` | 0-px (`threshold: 0`, `includeAA: true`) base-vs-candidate static equivalence and 4-way Vanilla/HTML/React/Vue pixel + leaf-tag parity on real Chromium and Firefox. | Post-mount state transitions, StrictMode, async `src` loading, animation frame times (only captures 1 static frame at mount). | +| **A/B performance gate** | `pnpm bench:gate:perf -- --base-ref origin/main` | Active camera/light motion (`sceneAttrMutations > 0`), 0 per-frame childList and descendant attribute mutations, exact leaf counts, no DOM/style/``/layout regressions, paired p50/p95/JS/bimodal budgets on Chromium. | Firefox/WebKit perf, visual correctness, non-motion UI transitions. | +| **Lifecycle & SSR gate** | `pnpm bench:gate:lifecycle` | Pure Node SSR (zero DOM globals) for React + Vue `renderToString`, dev-mode React `` remounts + live decoded blob ``, 3× rebake + `undefined` prop clears, real `.vox` class updates, stable-topology overrides, dynamic shadows, real `.obj` Vue async `src` single-mount, and controls interaction in real Chromium. | Pixel accuracy (covered by `visual-gate`) and frame timing (covered by `perf-gate`). | +| **Domformat browser & Gallery corpus** | `pnpm --filter @layoutit/polycss-website verify:domformat:fresh` | `domformat@0` runtime conformance in Chromium and byte-exact 304-model Gallery corpus regeneration on macOS. | React/Vue adapters and dynamic CSS lighting paths. | diff --git a/.github/scripts/generate-repo-map.mjs b/.github/scripts/generate-repo-map.mjs new file mode 100644 index 00000000..cbd3f902 --- /dev/null +++ b/.github/scripts/generate-repo-map.mjs @@ -0,0 +1,639 @@ +#!/usr/bin/env node +/** + * Generates and fail-closed verifies `.github/architecture/repo-map.md`. + * + * Keeps a single compact (~150–200 line) structural, state-container, alias, + * and verification-gate map synchronized with the real repository tree: + * + * 1. Validates `packages/workspace-aliases.mjs` covers every publishable + * JS export subpath, points to existing source files, orders subpaths + * before root package names, and matches `website/tsconfig.json#paths`. + * 2. Verifies every file + symbol anchor referenced in the pipeline and + * mutable-state tables actually exists in the codebase (fails closed on + * stale anchors). + * 3. Computes deterministic package metrics, top import hubs (`fanIn`), + * and largest source files using the lexical scanner from + * `check-boundaries.mjs`. + * 4. In `--check` mode, fails closed if `.github/architecture/repo-map.md` + * drifts from the generated output, or if alias / anchor invariants fail. + * + * Usage: + * node .github/scripts/generate-repo-map.mjs # regenerate map + * node .github/scripts/generate-repo-map.mjs --check # CI fail-closed check + */ +import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { dirname, extname, posix, relative, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import { extractSpecifiers } from "./check-boundaries.mjs"; +import { isDirectRun } from "./is-direct-run.mjs"; +import { WORKSPACE_SOURCE_ENTRIES } from "../../packages/workspace-aliases.mjs"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repoRoot = resolve(__dirname, "..", ".."); + +export const MAP_RELATIVE_PATH = ".github/architecture/repo-map.md"; + +const SKIPPED_DIRS = new Set([ + "node_modules", + "dist", + ".generated", + "coverage", + "build", + "vendor", + ".astro", + "gallery-domformat-corpus", +]); + +const CODE_EXTS = new Set([".ts", ".tsx", ".mts", ".cts", ".mjs", ".cjs", ".js"]); +const TEST_RE = /\.(test|spec)\.[^.]+$/; + +const PIPELINES = [ + { + name: "Parse & Optimize", + chain: [ + { file: "packages/core/src/parser/loadMesh.ts", symbol: "loadMesh" }, + { file: "packages/core/src/parser/parseGltf.ts", symbol: "parseGltf" }, + { file: "packages/core/src/merge/optimizePolygons.ts", symbol: "optimizeMeshPolygons" }, + ], + notes: "OBJ/GLB/glTF/VOX/STL -> `Polygon[]` (+ optional `voxelSource`). Pure ES2020 in `core`.", + }, + { + name: "Atlas Plan & Leaf Emit", + chain: [ + { file: "packages/core/src/atlas/plan.ts", symbol: "computeTextureAtlasPlan" }, + { file: "packages/polycss/src/render/atlas/packing.ts", symbol: "packTextureAtlasPlansWithScale" }, + { file: "packages/polycss/src/render/atlas/renderPolygons.ts", symbol: "renderPolygonsWithTextureAtlas" }, + { file: "packages/polycss/src/render/voxelRenderer.ts", symbol: "createPolyVoxelRenderer" }, + ], + notes: "Cheapest strategy per polygon (`` -> `` -> `` -> ``); direct voxel fast path for baked `.vox`.", + }, + { + name: "Scene Runtime & Rebake", + chain: [ + { file: "packages/polycss/src/api/createPolyScene.ts", symbol: "createPolyScene" }, + { file: "packages/polycss/src/api/scene/mountSync.ts", symbol: "syncMountedRendered" }, + { file: "packages/polycss/src/api/scene/rebake.ts", symbol: "requestRebakeAtlas" }, + { file: "packages/polycss/src/api/scene/lightingVars.ts", symbol: "applyDynamicLightVars" }, + ], + notes: "Single DOM renderer exposed via `@layoutit/polycss/runtime`; no per-frame rAF leaf writes.", + }, + { + name: "Cast & Receiver Shadows", + chain: [ + { file: "packages/core/src/shadow/computeReceiverShadows.ts", symbol: "computeMergedReceiverShadows" }, + { file: "packages/polycss/src/api/scene/shadowOrchestrator.ts", symbol: "emitSceneShadows" }, + { file: "packages/polycss/src/api/scene/shadowSvg.ts", symbol: "ensureGroundShadow" }, + { file: "packages/polycss/src/api/scene/shadowCache.ts", symbol: "clearAllSceneShadows" }, + ], + notes: "CPU-projected SVG overlays under `.polycss-shadows`; cached by quantized light + camera facing.", + }, + { + name: "React & Vue Adopt-DOM", + chain: [ + { file: "packages/react/src/scene/PolyScene.tsx", symbol: "PolyScene" }, + { file: "packages/react/src/scene/PolyMesh.tsx", symbol: "PolyMesh" }, + { file: "packages/vue/src/scene/PolyScene.ts", symbol: "PolyScene" }, + { file: "packages/vue/src/scene/PolyMesh.ts", symbol: "PolyMesh" }, + ], + notes: "Framework owns outer `
` refs; runtime adopts elements (`elements`, `wrapper`) with `bakedLightPolicy: \"auto\"`.", + }, + { + name: "Morph & Domformat", + chain: [ + { file: "packages/morph/src/prepare/prepare.ts", symbol: "preparePolyMorphModel" }, + { file: "packages/morph/src/render/mount.ts", symbol: "mountPolyMorphModel" }, + { file: "packages/domformat/src/schema.ts", symbol: "validatePolycssChannelInvariants" }, + ], + notes: "Prepared runtime & closed `domformat@0` wire contract (private, producer-neutral).", + }, +]; + +const STATE_CONTAINERS = [ + { + container: "SceneContext", + file: "packages/polycss/src/api/scene/sceneContext.ts", + symbol: "SceneContext", + flags: "`options.current`, `meshes`, `shadowSvgState`, `lastEmittedShadowLightKey`", + writers: [ + { file: "packages/polycss/src/api/createPolyScene.ts", symbol: "setOptions" }, + { file: "packages/polycss/src/api/scene/shadowOrchestrator.ts", symbol: "emitSceneShadows" }, + ], + invariant: "`setOptions` checks `hasOwnProperty` for every optional prop (including `textureQuality`, `directionalLight`, `strategies`, `shadow`) so clearing to `undefined` updates leaves and shadows.", + }, + { + container: "MeshEntry", + file: "packages/polycss/src/api/scene/internalTypes.ts", + symbol: "MeshEntry", + flags: "`rebakeInFlight`, `rebakeQueued`, `stableDom`, `adoptedWrapper`, `ownedNodes`, `atomicSwapVersion`, `disposed`, `renderOverrides`", + writers: [ + { file: "packages/polycss/src/api/createPolyScene.ts", symbol: "renderEntry" }, + { file: "packages/polycss/src/api/scene/rebake.ts", symbol: "rebakeRenderEntryInPlace" }, + { file: "packages/polycss/src/api/scene/mountLifecycle.ts", symbol: "clearMountedRendered" }, + ], + invariant: "Every path in `rebakeRenderEntryInPlace` must run `finish()` to clear `rebakeInFlight` and drain `rebakeQueued`. `stableDom` resets to `false` when polygons are not stable-triangle eligible. `adoptedWrapper` is never removed from DOM on dispose.", + }, + { + container: "ShadowSvgState", + file: "packages/polycss/src/api/scene/shadowSvg.ts", + symbol: "ShadowSvgState", + flags: "`shadowRoot`, `groundSvg`, `groundVisible`, `currentGroundCssZ`", + writers: [ + { file: "packages/polycss/src/api/scene/shadowSvg.ts", symbol: "disposeShadowRoot" }, + { file: "packages/polycss/src/api/scene/shadowCache.ts", symbol: "clearAllSceneShadows" }, + ], + invariant: "`clearAllSceneShadows` (called on `scene.destroy()`) detaches `shadowRoot` so adopted `` elements never accumulate orphan `.polycss-shadows` wrappers across StrictMode remounts.", + }, + { + container: "CameraHandle", + file: "packages/polycss/src/api/createPolyCamera.ts", + symbol: "createPolyCamera", + flags: "`state` (`rotX`, `rotY`, `zoom`, `distance`, `target`)", + writers: [ + { file: "packages/polycss/src/api/createPolyOrbitControls.ts", symbol: "createPolyOrbitControls" }, + { file: "packages/react/src/camera/useCamera.ts", symbol: "usePolyCamera" }, + { file: "packages/vue/src/camera/useCamera.ts", symbol: "usePolyCamera" }, + ], + invariant: "Mutating camera state requires `scene.applyCamera()` to flush DOM transforms, voxel face culling, and receiver-shadow visibility boundaries.", + }, + { + container: "React runtimeSceneSlot", + file: "packages/react/src/scene/sceneContext.ts", + symbol: "RuntimeSceneSlot", + flags: "`current`, `subscribe`, `set`", + writers: [ + { file: "packages/react/src/scene/PolyScene.tsx", symbol: "PolyScene" }, + { file: "packages/react/src/scene/PolyMesh.tsx", symbol: "PolyMesh" }, + ], + invariant: "Synchronous commit-1 handoff from `` to child `` without triggering extra React re-renders; `` preserves `.polycss-voxel-mesh` across `className` updates and skips redundant `setTransform` on dynamic mount.", + }, + { + container: "Vue sceneCtx", + file: "packages/vue/src/scene/sceneContext.ts", + symbol: "PolySceneContextKey", + flags: "`runtimeScene` ref, `isLoadingSlot`, `activeVoxelSource`", + writers: [ + { file: "packages/vue/src/scene/PolyScene.ts", symbol: "PolyScene" }, + { file: "packages/vue/src/scene/PolyMesh.ts", symbol: "PolyMesh" }, + ], + invariant: "`PolyMesh` watches `isLoadingSlot`/`activeVoxelSource` with `flush: \"post\"` and `polygons` with `flush: \"pre\"` so async `src` transitions mount once and `props.class` updates preserve `.polycss-voxel-mesh`.", + }, +]; + +const GATE_MATRIX = [ + { + gate: "Static guards & script tests", + command: "`pnpm check:guards`", + proves: "Package dependency + `/runtime`-only subpath boundaries, React↔Vue mirror/export parity, `AGENTS.md` size & links, README/skill sync, alias & repo-map freshness, gate unit tests.", + blindSpots: "Runtime browser behavior, CSS rendering, pixel output, timing.", + }, + { + gate: "Unit & coverage suite", + command: "`pnpm test:coverage`", + proves: "Math, parsers, shadow geometry, runtime seams, and React/Vue component logic under `happy-dom` + v8 coverage thresholds across all 8 packages.", + blindSpots: "Real browser layout/compositing, WebKit/Firefox quirks, real Canvas/Blob image decoding.", + }, + { + gate: "3-way DOM/CSS IR conformance", + command: "`pnpm check:ir`", + proves: "Compiled `polycss`, `react`, and `vue` `dist/index.js` emit matching DOM tags, lighting vars, transforms, and shadows in `happy-dom`.", + blindSpots: "Post-mount mutations, real browser pixel rasterization.", + }, + { + gate: "Tarball pack check", + command: "`pnpm check:packs`", + proves: "All 7 publishable tarballs contain declared entries + `typesVersions` + `README.md`, zero `workspace:` leaks, zero test files.", + blindSpots: "Runtime execution inside consumer apps.", + }, + { + gate: "Visual pixelmatch gate", + command: "`pnpm bench:gate:ci -- --base-ref origin/main --browsers chromium,firefox`", + proves: "0-px (`threshold: 0`, `includeAA: true`) base-vs-candidate static equivalence and 4-way Vanilla/HTML/React/Vue pixel + leaf-tag parity on real Chromium and Firefox.", + blindSpots: "Post-mount state transitions, StrictMode, async `src` loading, animation frame times (only captures 1 static frame at mount).", + }, + { + gate: "A/B performance gate", + command: "`pnpm bench:gate:perf -- --base-ref origin/main`", + proves: "Active camera/light motion (`sceneAttrMutations > 0`), 0 per-frame childList and descendant attribute mutations, exact leaf counts, no DOM/style/``/layout regressions, paired p50/p95/JS/bimodal budgets on Chromium.", + blindSpots: "Firefox/WebKit perf, visual correctness, non-motion UI transitions.", + }, + { + gate: "Lifecycle & SSR gate", + command: "`pnpm bench:gate:lifecycle`", + proves: "Pure Node SSR (zero DOM globals) for React + Vue `renderToString`, dev-mode React `` remounts + live decoded blob ``, 3× rebake + `undefined` prop clears, real `.vox` class updates, stable-topology overrides, dynamic shadows, real `.obj` Vue async `src` single-mount, and controls interaction in real Chromium.", + blindSpots: "Pixel accuracy (covered by `visual-gate`) and frame timing (covered by `perf-gate`).", + }, + { + gate: "Domformat browser & Gallery corpus", + command: "`pnpm --filter @layoutit/polycss-website verify:domformat:fresh`", + proves: "`domformat@0` runtime conformance in Chromium and byte-exact 304-model Gallery corpus regeneration on macOS.", + blindSpots: "React/Vue adapters and dynamic CSS lighting paths.", + }, +]; + +function toPosix(p) { + return p.split(sep).join("/"); +} + +function walkFiles(dir, predicate) { + const out = []; + if (!existsSync(dir)) return out; + for (const name of readdirSync(dir).sort()) { + if (SKIPPED_DIRS.has(name)) continue; + const abs = resolve(dir, name); + const st = statSync(abs); + if (st.isDirectory()) out.push(...walkFiles(abs, predicate)); + else if (predicate(abs, name)) out.push(abs); + } + return out; +} + +function countLines(text) { + if (!text) return 0; + return text.split("\n").length - (text.endsWith("\n") ? 1 : 0); +} + +/** + * Validates `packages/workspace-aliases.mjs` against all workspace manifests + * and `website/tsconfig.json`. Returns an array of violation strings (empty = valid). + */ +export function validateWorkspaceAliases(root, entries = WORKSPACE_SOURCE_ENTRIES) { + const violations = []; + const packagesDir = resolve(root, "packages"); + const keys = Object.keys(entries); + + // 1. Subpath ordering: every `@scope/pkg/subpath` must precede `@scope/pkg`. + const seenRoots = new Set(); + for (const key of keys) { + const parts = key.split("/"); + const rootPkg = key.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const isSubpath = key !== rootPkg; + if (isSubpath && seenRoots.has(rootPkg)) { + violations.push( + `packages/workspace-aliases.mjs: subpath "${key}" must be listed before root "${rootPkg}"`, + ); + } + if (!isSubpath) seenRoots.add(rootPkg); + } + + // 2. Every alias target exists on disk. + for (const [spec, rel] of Object.entries(entries)) { + const abs = resolve(packagesDir, rel); + if (!existsSync(abs)) { + violations.push( + `packages/workspace-aliases.mjs: "${spec}" points to missing source "packages/${rel}"`, + ); + } + } + + // 3. Every publishable package JS export subpath is covered by WORKSPACE_SOURCE_ENTRIES. + if (existsSync(packagesDir)) { + for (const dir of readdirSync(packagesDir).sort()) { + const pkgJsonPath = resolve(packagesDir, dir, "package.json"); + if (!existsSync(pkgJsonPath)) continue; + const manifest = JSON.parse(readFileSync(pkgJsonPath, "utf8")); + if (manifest.private || dir === "skills") continue; + const exportsField = manifest.exports; + if (!exportsField || typeof exportsField !== "object") continue; + for (const [subpath, target] of Object.entries(exportsField)) { + if (subpath === "./package.json") continue; + const importTarget = typeof target === "string" ? target : target?.import; + if (typeof importTarget !== "string" || !importTarget.endsWith(".js")) continue; + const spec = subpath === "." ? manifest.name : `${manifest.name}/${subpath.replace(/^\.\//, "")}`; + if (!Object.prototype.hasOwnProperty.call(entries, spec)) { + violations.push( + `packages/workspace-aliases.mjs: missing exported subpath "${spec}" declared in packages/${dir}/package.json`, + ); + } + } + } + } + + // 4. `website/tsconfig.json#compilerOptions.paths` matches every alias entry. + const websiteTsconfigPath = resolve(root, "website/tsconfig.json"); + if (existsSync(websiteTsconfigPath)) { + const tsconfig = JSON.parse(readFileSync(websiteTsconfigPath, "utf8")); + const paths = tsconfig?.compilerOptions?.paths ?? {}; + for (const [spec, rel] of Object.entries(entries)) { + const expected = `packages/${rel}`; + const actual = paths[spec]?.[0]; + if (actual !== expected) { + violations.push( + `website/tsconfig.json: paths["${spec}"] is ${JSON.stringify(actual)} (expected ${JSON.stringify(expected)})`, + ); + } + } + } + + return violations; +} + +/** + * Verifies every `{ file, symbol }` anchor referenced in PIPELINES and + * STATE_CONTAINERS actually exists in the repository. + */ +export function validateCodeAnchors(root) { + const violations = []; + const anchors = []; + for (const p of PIPELINES) anchors.push(...p.chain); + for (const s of STATE_CONTAINERS) { + anchors.push({ file: s.file, symbol: s.symbol }); + anchors.push(...s.writers); + } + const seen = new Set(); + for (const { file, symbol } of anchors) { + const key = `${file}#${symbol}`; + if (seen.has(key)) continue; + seen.add(key); + const abs = resolve(root, file); + if (!existsSync(abs)) { + violations.push(`repo-map anchor missing file: ${file}`); + continue; + } + const content = readFileSync(abs, "utf8"); + const symRe = new RegExp(`\\b${symbol.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`); + if (!symRe.test(content)) { + violations.push(`repo-map anchor missing symbol "${symbol}" in ${file}`); + } + } + return violations; +} + +function collectPackageStats(root) { + const packagesDir = resolve(root, "packages"); + const rows = []; + for (const dir of readdirSync(packagesDir).sort()) { + const pkgDir = resolve(packagesDir, dir); + const manifestPath = resolve(pkgDir, "package.json"); + if (!existsSync(manifestPath)) continue; + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + const exportsList = + manifest.exports && typeof manifest.exports === "object" + ? Object.keys(manifest.exports).filter((k) => k !== "./package.json") + : ["."]; + const wsDeps = []; + for (const field of ["dependencies", "peerDependencies"]) { + for (const name of Object.keys(manifest[field] ?? {})) { + if (name.startsWith("@layoutit/")) wsDeps.push(name); + } + } + const srcFiles = walkFiles(resolve(pkgDir, "src"), (abs) => CODE_EXTS.has(extname(abs))); + const prodFiles = srcFiles.filter((f) => !TEST_RE.test(f)); + const testFiles = srcFiles.filter((f) => TEST_RE.test(f)); + const prodLines = prodFiles.reduce((sum, f) => sum + countLines(readFileSync(f, "utf8")), 0); + rows.push({ + dir, + name: manifest.name, + visibility: manifest.private ? "private" : "npm", + exports: exportsList.join(", "), + wsDeps: wsDeps.length > 0 ? wsDeps.sort().join(", ") : "—", + prodFiles: prodFiles.length, + prodLines, + testFiles: testFiles.length, + }); + } + return rows; +} + +function findAliasConsumers(root) { + const roots = ["packages", "bench", "website"]; + const consumers = []; + for (const sub of roots) { + const files = walkFiles(resolve(root, sub), (abs, name) => { + if (!CODE_EXTS.has(extname(name))) return false; + if (TEST_RE.test(name)) return false; + if (toPosix(relative(root, abs)) === "packages/workspace-aliases.mjs") return false; + return true; + }); + for (const abs of files) { + const content = readFileSync(abs, "utf8"); + if (content.includes("workspace-aliases.mjs") || content.includes("workspaceAliases: true")) { + consumers.push(toPosix(relative(root, abs))); + } + } + } + if (existsSync(resolve(root, "website/tsconfig.json"))) { + consumers.push("website/tsconfig.json"); + } + return consumers.sort(); +} + +function resolveRelativeTarget(fromAbs, spec) { + const base = resolve(dirname(fromAbs), spec); + const candidates = [ + base, + `${base}.ts`, + `${base}.tsx`, + `${base}.mjs`, + `${base}.js`, + resolve(base, "index.ts"), + resolve(base, "index.tsx"), + resolve(base, "index.mjs"), + resolve(base, "index.js"), + ]; + for (const c of candidates) { + if (existsSync(c) && statSync(c).isFile()) return c; + } + return null; +} + +function collectImportHubsAndLargest(root) { + const scanRoots = [ + ...readdirSync(resolve(root, "packages")) + .sort() + .map((d) => resolve(root, "packages", d, "src")), + resolve(root, "bench"), + resolve(root, "website/src"), + ].filter((d) => existsSync(d)); + + const prodFiles = []; + for (const dir of scanRoots) { + prodFiles.push( + ...walkFiles(dir, (abs) => CODE_EXTS.has(extname(abs)) && !TEST_RE.test(abs)), + ); + } + + const aliasAbsMap = new Map( + Object.entries(WORKSPACE_SOURCE_ENTRIES).map(([k, rel]) => [k, resolve(root, "packages", rel)]), + ); + const fanIn = new Map(); + const sizes = []; + + for (const abs of prodFiles) { + const content = readFileSync(abs, "utf8"); + const rel = toPosix(relative(root, abs)); + const lines = countLines(content); + sizes.push({ path: rel, lines }); + + const seenTargets = new Set(); + for (const spec of extractSpecifiers(content)) { + let targetAbs = null; + if (spec.startsWith("./") || spec.startsWith("../")) { + targetAbs = resolveRelativeTarget(abs, spec); + } else if (aliasAbsMap.has(spec)) { + targetAbs = aliasAbsMap.get(spec); + } + if (!targetAbs || targetAbs === abs) continue; + const targetRel = toPosix(relative(root, targetAbs)); + if (seenTargets.has(targetRel)) continue; + seenTargets.add(targetRel); + fanIn.set(targetRel, (fanIn.get(targetRel) ?? 0) + 1); + } + } + + const sizeMap = new Map(sizes.map((s) => [s.path, s.lines])); + const topHubs = Array.from(fanIn.entries()) + .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) + .slice(0, 12) + .map(([path, count]) => ({ path, fanIn: count, lines: sizeMap.get(path) ?? 0 })); + + const largest = sizes + .sort((a, b) => b.lines - a.lines || a.path.localeCompare(b.path)) + .slice(0, 12); + + return { + totalProdFiles: prodFiles.length, + totalProdLines: sizes.reduce((sum, s) => sum + s.lines, 0), + topHubs, + largest, + }; +} + +export function generateRepoMapMarkdown(root) { + const pkgRows = collectPackageStats(root); + const aliasConsumers = findAliasConsumers(root); + const { totalProdFiles, totalProdLines, topHubs, largest } = collectImportHubsAndLargest(root); + + const lines = []; + lines.push(""); + lines.push("# PolyCSS Repository Map"); + lines.push(""); + lines.push( + `Tracked production code scanned across \`packages/*/src\`, \`bench/\`, and \`website/src\`: **${totalProdFiles.toLocaleString("en-US")} files**, **${totalProdLines.toLocaleString("en-US")} lines**. Regenerate with \`pnpm map\`; verified in CI by \`pnpm check:map\`.`, + ); + lines.push(""); + + lines.push("## 1. Packages & Entry Points"); + lines.push(""); + lines.push("| Package | Visibility | Exports | Workspace deps | Src files | Src lines | Test files |"); + lines.push("|---|---|---|---|---:|---:|---:|"); + for (const r of pkgRows) { + lines.push( + `| \`packages/${r.dir}\` (\`${r.name}\`) | ${r.visibility} | \`${r.exports}\` | ${r.wsDeps === "—" ? "—" : r.wsDeps.split(", ").map((d) => `\`${d}\``).join(", ")} | ${r.prodFiles} | ${r.prodLines.toLocaleString("en-US")} | ${r.testFiles} |`, + ); + } + lines.push(""); + + lines.push("## 2. Canonical Workspace Source Aliases"); + lines.push(""); + lines.push( + "Single source of truth: [`packages/workspace-aliases.mjs`](../../packages/workspace-aliases.mjs) (validated against every `package.json#exports` and `website/tsconfig.json`).", + ); + lines.push(""); + lines.push("| Specifier | Source entry |"); + lines.push("|---|---|"); + for (const [spec, rel] of Object.entries(WORKSPACE_SOURCE_ENTRIES)) { + lines.push(`| \`${spec}\` | \`packages/${rel}\` |`); + } + lines.push(""); + lines.push(`**Consumers (${aliasConsumers.length}):** ${aliasConsumers.map((c) => `\`${c}\``).join(", ")}`); + lines.push(""); + + lines.push("## 3. Top Import Hubs (`fanIn`) & Largest Source Files"); + lines.push(""); + lines.push("### Highest `fanIn` (production files importing this file)"); + lines.push(""); + lines.push("| Fan-in | Lines | File |"); + lines.push("|---:|---:|---|"); + for (const h of topHubs) { + lines.push(`| ${h.fanIn} | ${h.lines.toLocaleString("en-US")} | \`${h.path}\` |`); + } + lines.push(""); + + lines.push("### Largest production source files"); + lines.push(""); + lines.push("| Lines | File |"); + lines.push("|---:|---|"); + for (const f of largest) { + lines.push(`| ${f.lines.toLocaleString("en-US")} | \`${f.path}\` |`); + } + lines.push(""); + + lines.push("## 4. Core Render & Control Pipelines"); + lines.push(""); + lines.push("| Pipeline | Entry chain (`file:symbol`) | Notes |"); + lines.push("|---|---|---|"); + for (const p of PIPELINES) { + const chain = p.chain.map((a) => `\`${a.file}\` (\`${a.symbol}\`)`).join(" → "); + lines.push(`| **${p.name}** | ${chain} | ${p.notes} |`); + } + lines.push(""); + + lines.push("## 5. Mutable Runtime State Containers & Invariants"); + lines.push(""); + lines.push("| Container | Owner (`file:symbol`) | Key mutable fields | Primary writers | Invariant |"); + lines.push("|---|---|---|---|---|"); + for (const s of STATE_CONTAINERS) { + const writers = s.writers.map((w) => `\`${w.file}\` (\`${w.symbol}\`)`).join(", "); + lines.push(`| **${s.container}** | \`${s.file}\` (\`${s.symbol}\`) | ${s.flags} | ${writers} | ${s.invariant} |`); + } + lines.push(""); + + lines.push("## 6. Verification Gate Coverage Matrix"); + lines.push(""); + lines.push("| Gate | Command | What it proves | Explicit blind spots |"); + lines.push("|---|---|---|---|"); + for (const g of GATE_MATRIX) { + lines.push(`| **${g.gate}** | ${g.command} | ${g.proves} | ${g.blindSpots} |`); + } + lines.push(""); + + return lines.join("\n"); +} + +export function runRepoMap({ root = repoRoot, check = false } = {}) { + const violations = [ + ...validateWorkspaceAliases(root), + ...validateCodeAnchors(root), + ]; + const expected = generateRepoMapMarkdown(root); + const targetPath = resolve(root, MAP_RELATIVE_PATH); + + if (check) { + if (!existsSync(targetPath)) { + violations.push(`${MAP_RELATIVE_PATH} is missing — run "pnpm map" to generate it`); + } else { + const actual = readFileSync(targetPath, "utf8"); + if (actual !== expected) { + violations.push(`${MAP_RELATIVE_PATH} is out of date — run "pnpm map" to regenerate it`); + } + } + return { ok: violations.length === 0, violations, path: targetPath }; + } + + if (violations.length > 0) { + return { ok: false, violations, path: targetPath }; + } + writeFileSync(targetPath, expected, "utf8"); + return { ok: true, violations: [], path: targetPath, bytes: Buffer.byteLength(expected) }; +} + +if (isDirectRun(import.meta.url)) { + const args = process.argv.slice(2); + const check = args.includes("--check"); + const unknown = args.filter((a) => a !== "--check"); + if (unknown.length > 0) { + console.error(`[repo-map] Unknown argument(s): ${unknown.join(", ")}`); + process.exit(1); + } + const result = runRepoMap({ root: repoRoot, check }); + if (!result.ok) { + console.error("[repo-map] Check failed:\n"); + for (const v of result.violations) console.error(` - ${v}`); + process.exit(1); + } + if (check) { + console.log(`[repo-map] ${MAP_RELATIVE_PATH} and workspace aliases are up to date.`); + } else { + console.log(`[repo-map] wrote ${MAP_RELATIVE_PATH} (${result.bytes} bytes).`); + } +} diff --git a/.github/scripts/generate-repo-map.test.mjs b/.github/scripts/generate-repo-map.test.mjs new file mode 100644 index 00000000..4062451e --- /dev/null +++ b/.github/scripts/generate-repo-map.test.mjs @@ -0,0 +1,93 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +import { + generateRepoMapMarkdown, + runRepoMap, + validateCodeAnchors, + validateWorkspaceAliases, +} from "./generate-repo-map.mjs"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const repoRoot = resolve(__dirname, "..", ".."); + +function makeFakeRepo(files) { + const root = mkdtempSync(resolve(tmpdir(), "polycss-repo-map-test-")); + for (const [rel, content] of Object.entries(files)) { + const abs = resolve(root, rel); + mkdirSync(dirname(abs), { recursive: true }); + writeFileSync(abs, content, "utf8"); + } + return root; +} + +test("validateWorkspaceAliases passes on the real repository", () => { + assert.deepEqual(validateWorkspaceAliases(repoRoot), []); +}); + +test("validateWorkspaceAliases fails closed on missing export, missing file, bad order, and tsconfig drift", () => { + const root = makeFakeRepo({ + "packages/core/package.json": JSON.stringify({ + name: "@layoutit/polycss-core", + exports: { + ".": { import: "./dist/index.js" }, + "./three": { import: "./dist/three.js" }, + }, + }), + "packages/core/src/index.ts": "export const a = 1;\n", + "website/tsconfig.json": JSON.stringify({ + compilerOptions: { + paths: { + "@layoutit/polycss-core": ["packages/core/src/wrong.ts"], + }, + }, + }), + }); + + try { + // 1. Missing subpath export + tsconfig drift + const missing = validateWorkspaceAliases(root, { + "@layoutit/polycss-core": "core/src/index.ts", + }); + assert.ok(missing.some((v) => v.includes('missing exported subpath "@layoutit/polycss-core/three"'))); + assert.ok(missing.some((v) => v.includes('website/tsconfig.json: paths["@layoutit/polycss-core"]'))); + + // 2. Bad ordering (root before subpath) + missing source file + const badOrder = validateWorkspaceAliases(root, { + "@layoutit/polycss-core": "core/src/index.ts", + "@layoutit/polycss-core/three": "core/src/three/index.ts", + }); + assert.ok(badOrder.some((v) => v.includes("must be listed before root"))); + assert.ok(badOrder.some((v) => v.includes("points to missing source"))); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +test("validateCodeAnchors passes on the real repository and catches missing files/symbols", () => { + assert.deepEqual(validateCodeAnchors(repoRoot), []); + + const emptyRoot = makeFakeRepo({}); + try { + const missing = validateCodeAnchors(emptyRoot); + assert.ok(missing.length > 0); + assert.ok(missing.every((v) => v.includes("repo-map anchor missing file"))); + } finally { + rmSync(emptyRoot, { recursive: true, force: true }); + } +}); + +test("generateRepoMapMarkdown is deterministic and check mode passes when in sync", () => { + const first = generateRepoMapMarkdown(repoRoot); + const second = generateRepoMapMarkdown(repoRoot); + assert.equal(first, second); + assert.ok(first.includes("## 1. Packages & Entry Points")); + assert.ok(first.includes("## 5. Mutable Runtime State Containers & Invariants")); + assert.ok(first.includes("## 6. Verification Gate Coverage Matrix")); + + const check = runRepoMap({ root: repoRoot, check: true }); + assert.equal(check.ok, true, check.violations.join("\n")); +}); diff --git a/AGENTS.md b/AGENTS.md index 0fa10e51..22e598ea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # PolyCSS — agent guide -This file is the single source of truth for AI coding agents (Claude Code, Cursor, etc.). `CLAUDE.md` is a symlink to this file — **always edit `AGENTS.md`, never `CLAUDE.md`**. Keep this file under 20 KB (enforced by `.github/scripts/check-agents-doc.test.mjs`) so agent rule loaders never truncate operational rules; deep subsystem references live in `.github/architecture/*.md`. +This file is the single source of truth for AI coding agents (Claude Code, Cursor, etc.). `CLAUDE.md` is a symlink to this file — **always edit `AGENTS.md`, never `CLAUDE.md`**. Keep this file under 20 KB (enforced by `.github/scripts/check-agents-doc.test.mjs`) so agent rule loaders never truncate operational rules; deep subsystem references live in `.github/architecture/*.md`. **Start with [.github/architecture/repo-map.md](.github/architecture/repo-map.md)** (auto-generated via `pnpm map`, enforced by `pnpm check:map`) for package exports, shared workspace aliases (`packages/workspace-aliases.mjs`), import hubs, core pipelines, mutable runtime state invariants, and the verification gate coverage matrix. ## What this repo is diff --git a/bench/build.mjs b/bench/build.mjs index 3a727726..c643e85e 100644 --- a/bench/build.mjs +++ b/bench/build.mjs @@ -29,6 +29,7 @@ import { build } from "esbuild"; import { mkdir } from "node:fs/promises"; import { resolve, dirname } from "node:path"; import { fileURLToPath } from "node:url"; +import { createWorkspaceSourceAliases } from "../packages/workspace-aliases.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); const repoRoot = resolve(__dirname, ".."); @@ -44,14 +45,7 @@ const bundleDir = resolve(optStr("out-dir", resolve(__dirname, ".generated"))); const group = optStr("group", "all"); const ALIASES = { - "@layoutit/polycss-core": resolve(packagesRoot, "core/src/index.ts"), - "@layoutit/polycss-core/three": resolve(packagesRoot, "core/src/three/index.ts"), - "@layoutit/polycss": resolve(packagesRoot, "polycss/src/index.ts"), - "@layoutit/polycss/runtime": resolve(packagesRoot, "polycss/src/runtime.ts"), - "@layoutit/polycss/elements": resolve(packagesRoot, "polycss/src/elements/index.ts"), - "@layoutit/polycss/three": resolve(packagesRoot, "polycss/src/three.ts"), - "@layoutit/polycss-react": resolve(packagesRoot, "react/src/index.ts"), - "@layoutit/polycss-vue": resolve(packagesRoot, "vue/src/index.ts"), + ...createWorkspaceSourceAliases(packagesRoot), "three": resolve(repoRoot, "node_modules/three/build/three.module.js"), // Pin React + ReactDOM to the workspace-root copies so the alias-resolved // @layoutit/polycss-react source AND the bench entry import the SAME instance. diff --git a/package.json b/package.json index cbe29302..100592b7 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,8 @@ "sync:skill": "node .github/scripts/sync-skill-docs.mjs", "check:readmes": "node .github/scripts/sync-package-readmes.mjs --check", "check:skill": "node .github/scripts/sync-skill-docs.mjs --check", + "map": "node .github/scripts/generate-repo-map.mjs", + "check:map": "node .github/scripts/generate-repo-map.mjs --check", "eval:skill": "node eval/skill/run.mjs", "eval:selftest": "node eval/skill/selftest.mjs", "check:boundaries": "node .github/scripts/check-boundaries.mjs", @@ -35,7 +37,7 @@ "check:ir": "node --test bench/renderer-ir-conformance.test.mjs", "typecheck": "pnpm --filter './packages/*' -r --if-present typecheck", "test:scripts": "node --test .github/scripts/*.test.mjs bench/visual-gate.test.mjs bench/perf-gate.test.mjs bench/lifecycle-gate.test.mjs", - "check:guards": "pnpm test:scripts && pnpm check:readmes && pnpm check:skill && pnpm check:boundaries && pnpm check:mirrors --require-base && pnpm check:exports", + "check:guards": "pnpm test:scripts && pnpm check:readmes && pnpm check:skill && pnpm check:map && pnpm check:boundaries && pnpm check:mirrors --require-base && pnpm check:exports", "verify": "pnpm check:guards && pnpm test && pnpm build:packages && pnpm typecheck && pnpm check:ir && pnpm check:packs && pnpm bench:build && pnpm --filter './examples/*' -r build", "publish:all": "pnpm sync:readmes && pnpm --filter './packages/*' --filter '!@layoutit/polycss-domformat' -r publish --access public", "dev:website": "pnpm --filter @layoutit/polycss-website dev", diff --git a/packages/fonts/vitest.config.ts b/packages/fonts/vitest.config.ts index 621715eb..690083c6 100644 --- a/packages/fonts/vitest.config.ts +++ b/packages/fonts/vitest.config.ts @@ -1,9 +1,6 @@ -import { resolve } from "node:path"; import { createVitestConfig } from "../vitest.base.mjs"; export default createVitestConfig({ environment: "node", - alias: { - "@layoutit/polycss-core": resolve(__dirname, "../core/src/index.ts"), - }, + workspaceAliases: true, }); diff --git a/packages/morph/vitest.config.ts b/packages/morph/vitest.config.ts index 4fbae3a4..209ed181 100644 --- a/packages/morph/vitest.config.ts +++ b/packages/morph/vitest.config.ts @@ -1,12 +1,8 @@ -import { resolve } from "node:path"; import { createVitestConfig } from "../vitest.base.mjs"; export default createVitestConfig({ environment: "happy-dom", coverageExclude: ["src/**/*.test.ts", "src/**/index.ts", "src/**/types.ts", "src/testing/**"], thresholds: { statements: 90, branches: 80, functions: 95, lines: 90 }, - alias: { - "@layoutit/polycss": resolve(__dirname, "../polycss/src/index.ts"), - "@layoutit/polycss-core": resolve(__dirname, "../core/src/index.ts"), - }, + workspaceAliases: true, }); diff --git a/packages/polycss/vitest.config.ts b/packages/polycss/vitest.config.ts index 671a10d5..c4b0e1f4 100644 --- a/packages/polycss/vitest.config.ts +++ b/packages/polycss/vitest.config.ts @@ -1,10 +1,6 @@ -import { resolve } from "node:path"; import { createVitestConfig } from "../vitest.base.mjs"; export default createVitestConfig({ environment: "happy-dom", - alias: { - "@layoutit/polycss-core/three": resolve(__dirname, "../core/src/three/index.ts"), - "@layoutit/polycss-core": resolve(__dirname, "../core/src/index.ts"), - }, + workspaceAliases: true, }); diff --git a/packages/react/vitest.config.ts b/packages/react/vitest.config.ts index 179af7f9..32f42626 100644 --- a/packages/react/vitest.config.ts +++ b/packages/react/vitest.config.ts @@ -1,4 +1,3 @@ -import { resolve } from "node:path"; import { createVitestConfig } from "../vitest.base.mjs"; export default createVitestConfig({ @@ -7,9 +6,5 @@ export default createVitestConfig({ setupFiles: ["./vitest.setup.ts"], coverageInclude: ["src/**/*.{ts,tsx}"], coverageExclude: ["src/**/*.test.ts", "src/**/*.test.tsx", "src/**/index.ts", "src/**/*.d.ts"], - alias: { - "@layoutit/polycss-core/three": resolve(__dirname, "../core/src/three/index.ts"), - "@layoutit/polycss-core": resolve(__dirname, "../core/src/index.ts"), - "@layoutit/polycss/runtime": resolve(__dirname, "../polycss/src/runtime.ts"), - }, + workspaceAliases: true, }); diff --git a/packages/vitest.base.mjs b/packages/vitest.base.mjs index d0843171..8d3af76e 100644 --- a/packages/vitest.base.mjs +++ b/packages/vitest.base.mjs @@ -1,4 +1,5 @@ import { defineConfig } from "vitest/config"; +import { createWorkspaceSourceAliases } from "./workspace-aliases.mjs"; export function createVitestConfig({ environment, @@ -7,8 +8,16 @@ export function createVitestConfig({ coverageInclude = ["src/**/*.ts"], coverageExclude = ["src/**/*.test.ts", "src/**/index.ts", "src/**/*.d.ts"], thresholds = { statements: 80, branches: 75, functions: 80, lines: 80 }, + workspaceAliases = false, alias, } = {}) { + const resolvedAlias = + workspaceAliases || alias + ? { + ...(workspaceAliases ? createWorkspaceSourceAliases() : {}), + ...(alias ?? {}), + } + : undefined; return defineConfig({ test: { // Bound the worker pool: vitest defaults to one worker per CPU core, @@ -26,6 +35,6 @@ export function createVitestConfig({ thresholds, }, }, - ...(alias ? { resolve: { alias } } : {}), + ...(resolvedAlias ? { resolve: { alias: resolvedAlias } } : {}), }); } diff --git a/packages/vue/vitest.config.ts b/packages/vue/vitest.config.ts index 970fb291..c4b0e1f4 100644 --- a/packages/vue/vitest.config.ts +++ b/packages/vue/vitest.config.ts @@ -1,11 +1,6 @@ -import { resolve } from "node:path"; import { createVitestConfig } from "../vitest.base.mjs"; export default createVitestConfig({ environment: "happy-dom", - alias: { - "@layoutit/polycss-core/three": resolve(__dirname, "../core/src/three/index.ts"), - "@layoutit/polycss-core": resolve(__dirname, "../core/src/index.ts"), - "@layoutit/polycss/runtime": resolve(__dirname, "../polycss/src/runtime.ts"), - }, + workspaceAliases: true, }); diff --git a/packages/workspace-aliases.mjs b/packages/workspace-aliases.mjs new file mode 100644 index 00000000..c929213e --- /dev/null +++ b/packages/workspace-aliases.mjs @@ -0,0 +1,78 @@ +/** + * Single source of truth for workspace package -> TypeScript source entry aliases. + * + * Consumed by: + * - packages/vitest.base.mjs (all package Vitest configs) + * - bench/build.mjs (visual, perf, and lifecycle gate bundles, including base worktrees) + * - website/astro.config.mjs (Vite/Astro website build) + * - website/scripts/{generate,prove}-gallery-domformat.mjs & generate-builder-shape-thumbnails.mjs + * + * Validated in CI by `.github/scripts/generate-repo-map.mjs --check` against + * every package's `package.json#exports` and `website/tsconfig.json#compilerOptions.paths`. + * + * Subpaths MUST stay listed before their root package name so prefix-matching + * bundlers (Vite/Rollup/esbuild) never shadow a subpath with the root entry. + */ +import { existsSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const defaultPackagesRoot = dirname(fileURLToPath(import.meta.url)); + +/** Ordered map of workspace specifier -> path relative to `packages/`. */ +export const WORKSPACE_SOURCE_ENTRIES = Object.freeze({ + "@layoutit/polycss-core/three": "core/src/three/index.ts", + "@layoutit/polycss-core": "core/src/index.ts", + "@layoutit/polycss/runtime": "polycss/src/runtime.ts", + "@layoutit/polycss/elements": "polycss/src/elements/index.ts", + "@layoutit/polycss/three": "polycss/src/three.ts", + "@layoutit/polycss": "polycss/src/index.ts", + "@layoutit/polycss-react/three": "react/src/three/index.ts", + "@layoutit/polycss-react": "react/src/index.ts", + "@layoutit/polycss-vue/three": "vue/src/three/index.ts", + "@layoutit/polycss-vue": "vue/src/index.ts", + "@layoutit/polycss-fonts": "fonts/src/index.ts", + "@layoutit/polycss-morph/prepare": "morph/src/prepare.ts", + "@layoutit/polycss-morph": "morph/src/index.ts", +}); + +/** + * Resolve workspace source aliases as a plain `{ [specifier]: absolutePath }` map + * for esbuild and Vitest. When `packagesRoot` differs from this checkout's + * `packages/` (e.g. an older git worktree in base-vs-candidate gates), entries + * whose file does not exist in that worktree are omitted gracefully. + */ +export function createWorkspaceSourceAliases( + packagesRoot = defaultPackagesRoot, + keys = Object.keys(WORKSPACE_SOURCE_ENTRIES), +) { + const isExternalRoot = resolve(packagesRoot) !== resolve(defaultPackagesRoot); + const out = {}; + for (const key of keys) { + const rel = WORKSPACE_SOURCE_ENTRIES[key]; + if (!rel) throw new Error(`Unknown workspace source alias key: ${key}`); + const abs = resolve(packagesRoot, rel); + if (isExternalRoot && !existsSync(abs)) continue; + out[key] = abs; + } + return out; +} + +function escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +/** + * Resolve workspace source aliases as exact-match Vite/Rollup `{ find: RegExp, replacement }` + * rules so subpaths and root entries never collide. + */ +export function createViteWorkspaceSourceAliases( + packagesRoot = defaultPackagesRoot, + keys = Object.keys(WORKSPACE_SOURCE_ENTRIES), +) { + const map = createWorkspaceSourceAliases(packagesRoot, keys); + return Object.entries(map).map(([spec, replacement]) => ({ + find: new RegExp(`^${escapeRegExp(spec)}$`), + replacement, + })); +} diff --git a/website/astro.config.mjs b/website/astro.config.mjs index e31602a8..0a71df46 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -1,12 +1,9 @@ // @ts-check -import { fileURLToPath } from 'node:url'; import { defineConfig } from 'astro/config'; import starlight from '@astrojs/starlight'; import sitemap from '@astrojs/sitemap'; import react from '@astrojs/react'; - -/** @param {string} path */ -const repoPath = (path) => fileURLToPath(new URL(path, import.meta.url)); +import { createViteWorkspaceSourceAliases } from '../packages/workspace-aliases.mjs'; export default defineConfig({ site: 'https://polycss.com', @@ -14,28 +11,7 @@ export default defineConfig({ vite: { resolve: { dedupe: ['react', 'react-dom'], - alias: [ - { - find: /^@layoutit\/polycss\/runtime$/, - replacement: repoPath('../packages/polycss/src/runtime.ts'), - }, - { - find: /^@layoutit\/polycss\/elements$/, - replacement: repoPath('../packages/polycss/src/elements/index.ts'), - }, - { - find: /^@layoutit\/polycss-fonts$/, - replacement: repoPath('../packages/fonts/src/index.ts'), - }, - { - find: /^@layoutit\/polycss-morph$/, - replacement: repoPath('../packages/morph/src/index.ts'), - }, - { - find: /^@layoutit\/polycss$/, - replacement: repoPath('../packages/polycss/src/index.ts'), - }, - ], + alias: createViteWorkspaceSourceAliases(), }, }, integrations: [ diff --git a/website/scripts/generate-builder-shape-thumbnails.mjs b/website/scripts/generate-builder-shape-thumbnails.mjs index d7553f90..4dec96f1 100644 --- a/website/scripts/generate-builder-shape-thumbnails.mjs +++ b/website/scripts/generate-builder-shape-thumbnails.mjs @@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url"; import * as esbuild from "esbuild"; import { launchBrowser } from "../../bench/browser-discovery.mjs"; import { startStaticServer } from "../../bench/http-server.mjs"; +import { createWorkspaceSourceAliases } from "../../packages/workspace-aliases.mjs"; const scriptDir = dirname(fileURLToPath(import.meta.url)); const websiteRoot = resolve(scriptDir, ".."); @@ -114,11 +115,7 @@ await esbuild.build({ platform: "browser", jsx: "automatic", absWorkingDir: websiteRoot, - alias: { - "@layoutit/polycss-core": join(websiteRoot, "../packages/core/src/index.ts"), - "@layoutit/polycss/runtime": join(websiteRoot, "../packages/polycss/src/runtime.ts"), - "@layoutit/polycss": join(websiteRoot, "../packages/polycss/src/index.ts"), - }, + alias: createWorkspaceSourceAliases(), sourcemap: false, logLevel: "silent", }); diff --git a/website/scripts/generate-gallery-domformat.mjs b/website/scripts/generate-gallery-domformat.mjs index 1f4241b8..7fc790c4 100644 --- a/website/scripts/generate-gallery-domformat.mjs +++ b/website/scripts/generate-gallery-domformat.mjs @@ -35,12 +35,10 @@ import { sha256, sourceArtifactRole, } from "./gallery-domformat-shared.mjs"; +import { createWorkspaceSourceAliases } from "../../packages/workspace-aliases.mjs"; const scriptRoot = dirname(fileURLToPath(import.meta.url)); const websiteRoot = resolve(scriptRoot, ".."); -const coreSourceEntry = join(websiteRoot, "../packages/core/src/index.ts"); -const polycssSourceEntry = join(websiteRoot, "../packages/polycss/src/index.ts"); -const polycssRuntimeEntry = join(websiteRoot, "../packages/polycss/src/runtime.ts"); const galleryRoot = join(websiteRoot, "public/gallery"); const defaultOutputRoot = join(websiteRoot, "gallery-domformat-corpus"); const browserEntry = join(scriptRoot, "gallery-domformat-browser.ts"); @@ -698,11 +696,7 @@ async function main() { try { await build({ entryPoints: [browserEntry], - alias: { - "@layoutit/polycss-core": coreSourceEntry, - "@layoutit/polycss/runtime": polycssRuntimeEntry, - "@layoutit/polycss": polycssSourceEntry, - }, + alias: createWorkspaceSourceAliases(), bundle: true, format: "esm", platform: "browser", diff --git a/website/scripts/prove-gallery-domformat.mjs b/website/scripts/prove-gallery-domformat.mjs index e4f01769..1126e404 100644 --- a/website/scripts/prove-gallery-domformat.mjs +++ b/website/scripts/prove-gallery-domformat.mjs @@ -11,13 +11,10 @@ import { isWithin, requireCondition, } from "./gallery-domformat-shared.mjs"; +import { createWorkspaceSourceAliases } from "../../packages/workspace-aliases.mjs"; const scriptRoot = dirname(fileURLToPath(import.meta.url)); const websiteRoot = resolve(scriptRoot, ".."); -const repositoryRoot = resolve(websiteRoot, ".."); -const coreSourceEntry = join(repositoryRoot, "packages/core/src/index.ts"); -const polycssSourceEntry = join(repositoryRoot, "packages/polycss/src/index.ts"); -const polycssRuntimeEntry = join(repositoryRoot, "packages/polycss/src/runtime.ts"); const galleryRoot = join(websiteRoot, "public/gallery"); const defaultCorpusRoot = join(websiteRoot, "gallery-domformat-corpus"); const directEntry = join(scriptRoot, "gallery-domformat-browser.ts"); @@ -79,11 +76,7 @@ async function bundles(directory) { await Promise.all([ build({ entryPoints: [directEntry], - alias: { - "@layoutit/polycss-core": coreSourceEntry, - "@layoutit/polycss/runtime": polycssRuntimeEntry, - "@layoutit/polycss": polycssSourceEntry, - }, + alias: createWorkspaceSourceAliases(), bundle: true, format: "esm", platform: "browser", diff --git a/website/tsconfig.json b/website/tsconfig.json index 23514b6d..32fac8ea 100644 --- a/website/tsconfig.json +++ b/website/tsconfig.json @@ -3,14 +3,20 @@ "compilerOptions": { "baseUrl": "..", "paths": { + "@layoutit/polycss-core/three": ["packages/core/src/three/index.ts"], "@layoutit/polycss-core": ["packages/core/src/index.ts"], + "@layoutit/polycss/runtime": ["packages/polycss/src/runtime.ts"], + "@layoutit/polycss/elements": ["packages/polycss/src/elements/index.ts"], + "@layoutit/polycss/three": ["packages/polycss/src/three.ts"], + "@layoutit/polycss": ["packages/polycss/src/index.ts"], + "@layoutit/polycss-react/three": ["packages/react/src/three/index.ts"], "@layoutit/polycss-react": ["packages/react/src/index.ts"], + "@layoutit/polycss-vue/three": ["packages/vue/src/three/index.ts"], + "@layoutit/polycss-vue": ["packages/vue/src/index.ts"], "@layoutit/polycss-fonts": ["packages/fonts/src/index.ts"], + "@layoutit/polycss-morph/prepare": ["packages/morph/src/prepare.ts"], "@layoutit/polycss-morph": ["packages/morph/src/index.ts"], - "@layoutit/polycss-domformat": ["packages/domformat/src/index.ts"], - "@layoutit/polycss": ["packages/polycss/src/index.ts"], - "@layoutit/polycss/runtime": ["packages/polycss/src/runtime.ts"], - "@layoutit/polycss/elements": ["packages/polycss/src/elements/index.ts"] + "@layoutit/polycss-domformat": ["packages/domformat/src/index.ts"] } }, "include": [".astro/types.d.ts", "**/*"],