diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 52a6047..5fcb705 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,8 +2,9 @@ # # Two jobs, split by cost. Roughly a third of the suite drives a real browser, # and downloading Chrome dominates that job's runtime — so the Node-only tests -# run on their own and report in a couple of minutes, which is the feedback -# that matters for almost every change. See docs/specs/CI-SPEC.md. +# (test/unit) run on their own and report in a couple of minutes, which is the +# feedback that matters for almost every change. test/browser and test/e2e run +# in the browser job. See docs/specs/CI-SPEC.md. # # No secrets are needed. The tests that would use an LLM API key skip when one # is absent, so this stays useful on pull requests from forks. @@ -43,6 +44,8 @@ jobs: # `tsc` with noEmit off is the type check — it is the same compile the # published package depends on, so a separate lint step would be noise. - run: npm run build + # tsx runs the tests without checking their types; this does. + - run: npm run typecheck:tests - run: npm run test:fast browser: diff --git a/README.md b/README.md index 611bfd7..1cb65ab 100644 --- a/README.md +++ b/README.md @@ -1404,10 +1404,11 @@ npm run build | `npm run build` | Compile TypeScript to `dist/`. Required before the installed MCP server picks up changes — it loads `dist/index.js`. | | `npm run dev` | Run the server directly via `tsx` for local iteration. Does not affect the registered MCP server. | | `npm run viewer [port]` | Start the standalone viewer (default auto-picks from 3001). | -| `npm test` | Run every test that needs only Node (~2 min). Alias for `test:fast`. | -| `npm run test:full` | The above plus the browser-driven tests. Needs Chrome — `npx puppeteer browsers install chrome`. | -| `npx tsx scripts/run-tests.ts ` | Run just the tests whose filename matches. | -| `npx tsx test-*.ts` | Run a single test script directly. | +| `npm test` | Run `test/unit`, every test that needs only Node (~2 min). Alias for `test:fast`. | +| `npm run test:full` | The above plus `test/browser` and `test/e2e` (the tests that drive the MCP server or CLI). Needs Chrome — `npx puppeteer browsers install chrome`. | +| `npm run typecheck:tests` | Type-check the tests (`tsx` runs them without checking types). | +| `npx tsx scripts/run-tests.ts ` | Run just the tests whose path matches, such as `cliche` or `unit/`. | +| `npx tsx test/unit/test-cliche.ts` | Run a single test script directly, from the repo root. | ### Env vars diff --git a/VISION.md b/VISION.md index c3325dc..1925ce0 100644 --- a/VISION.md +++ b/VISION.md @@ -430,7 +430,7 @@ framesmith catches slop but doesn't yet proactively produce taste: from a blank - [x] Pattern library — expanded `src/structures.ts` to 11 vetted page archetypes (added dashboard, auth, pricing, settings, onboarding; landing≈marquee-hero, data-screen≈split-workbench/catalogue) + elevated the existing ones to the bar - [x] Craft guidance — a "Designing with taste" section (focal point, hierarchy, type + spacing scale, restraint, pattern-first) on the agent surfaces (GUIDELINES + INSTRUCTIONS + cheatsheet), paired with the anti-slop tells - [x] Relentless loop — the core loop on every agent surface now reads generate → evaluate → fix/revise → repeat until > 95 with no cliché tells before presenting -- [x] Library quality gate — `test-patterns.ts`: every page structure regression-tested to > 95 with zero cliché tells across all 5 presets (default/dark/light/material/minimal) +- [x] Library quality gate — `test/unit/test-patterns.ts`: every page structure regression-tested to > 95 with zero cliché tells across all 5 presets (default/dark/light/material/minimal) _Full spec-driven breakdown in [`docs/specs/PHASE-20-SPEC.md`](docs/specs/PHASE-20-SPEC.md). Built across PRs; Slices A (library + gate) and B/D (guidance + loop) shipped._ @@ -551,7 +551,7 @@ The mobile attempt (2026-09-07) built one iOS screen end to end on v2.2.0 and go - [x] Slice D — vocabulary: `fixed` / `sticky` positioning with the renderer reserving room for pinned chrome, a root that grows with long content (closing slice C's long-screen gap), the `status-bar`, `home-indicator`, `nav-bar`, `tab-bar`, `button`, `list-row` and `sheet` primitives, the primitives joining the 44px target rule, `mobile-tab-bar`, and pinned bars in the safe-area rule (`safeArea` on the root landed in slice B) - [x] Slice E — starting points: anatomy and realisation on structures, resolution by canvas type, six mobile realisations, and the pattern gate extended to them - [x] Slice F — the viewer: thumbnails at the artboard's real proportions and a device frame with a safe-area overlay -- [x] Slice G — the acceptance re-run: Ridgeline Today rebuilt from `dashboard-mobile` in 33 nodes (93 by hand), 100/100 and READY in fast and detailed mode with no dark-theme finding, `canvas_stress` CLEAN, every tap target a primitive, pinned as `test-ridgeline.ts`; the re-run surfaced two render defects, fixed here: large type now scales against the artboard's own width (a phone's titles rendered at 60%, under the body), and chart tick labels no longer stretch with the plot +- [x] Slice G — the acceptance re-run: Ridgeline Today rebuilt from `dashboard-mobile` in 33 nodes (93 by hand), 100/100 and READY in fast and detailed mode with no dark-theme finding, `canvas_stress` CLEAN, every tap target a primitive, pinned as `test/e2e/test-ridgeline.ts`; the re-run surfaced two render defects, fixed here: large type now scales against the artboard's own width (a phone's titles rendered at 60%, under the body), and chart tick labels no longer stretch with the plot All seven slices are merged and the acceptance re-run passed. The phase is closed. @@ -575,7 +575,7 @@ Run on its own viewer (2026-11-08), framesmith scored every page's usability 100 - [ ] Follow-up — a disabled control inside a component instance renders undimmed, because instances render after variable resolution (`resolveInstance`); resolve instance subtrees too, so `disabled` and `state` dim inside components as they do outside - [x] Slice H — state checks: focus rings, active indicators, disabled renders and control boundaries checked analytically on every interactive primitive, without being drawn, in each theme; text inside a disabled target is exempt from text contrast on every type - [ ] Follow-up — `select` is not in the boundary check, though its `$border` is its only boundary too; and `tree-row` and the contained `tabs` draw no indicator mark when active (a tint and a heavier weight only), so the active-indicator check has nothing to measure on them -- [x] Slice I — the acceptance re-run: the viewer's gallery, detail with inspector and archive rebuilt as canvases, with the comment popover and delete-confirm states and the empty archive, all six CLEAN in fast and detailed mode in both themes with a CLEAN stress run, and the six baseline defects fixed (`test-viewer-rebuild.ts`); detailed evaluate now lays out in the design system's own fonts, and a drawer or a scrolling popover reads as scrolling under stress +- [x] Slice I — the acceptance re-run: the viewer's gallery, detail with inspector and archive rebuilt as canvases, with the comment popover and delete-confirm states and the empty archive, all six CLEAN in fast and detailed mode in both themes with a CLEAN stress run, and the six baseline defects fixed (`test/e2e/test-viewer-rebuild.ts`); detailed evaluate now lays out in the design system's own fonts, and a drawer or a scrolling popover reads as scrolling under stress - [ ] Follow-up — a misspelt `$token` in a non-colour prop (`gap: "$space-xxs"`, which does not exist) resolves to nothing and evaluate says nothing; the slice I rebuild caught one only through its own resolved-tree check. Warn on any `$ref` the merged tokens do not define - [ ] Follow-up — `nav-item.count` is not a stress slot, so a sidebar count of "999+" is never exercised; add it (and `tabs.items[].count`) to the big-numbers perturbation @@ -587,7 +587,7 @@ _Full spec-driven breakdown in [`docs/specs/PHASE-31-SPEC.md`](docs/specs/PHASE- Phases 30 and 31 closed with seven follow-ups open, and five of them are quiet false passes: evaluate says READY on a disabled button that renders undimmed inside a component, on a misspelt `$token` the renderer drops, on a `select` border at 1.46:1, and on a phone screen whose links, text inputs and dialogs are never measured. Reproducing them found more: contrast and spacing never look inside a component instance at all, and seeded dark tints and `danger` survive a light preset. This phase clears every follow-up, and first moves the 140 root-level tests into folders that set their tier, so the fixes land in the new layout. -- [ ] Slice A — tests in folders: `test/unit`, `test/browser`, `test/e2e` and `test/manual` set the tier, a Chrome guard on `test/unit` proves it at run time, tests are type-checked under `strict`, and files are named by subject, not phase or issue +- [x] Slice A — tests in folders: `test/unit`, `test/browser`, `test/e2e` and `test/manual` set the tier, a Chrome guard on `test/unit` proves it at run time, tests are type-checked under `strict`, and files are named by subject, not phase or issue - [ ] Slice B — one tree: instances expanded and resolved once, so the renderer and every rule (contrast, spacing and cliché included) see the same thing inside a component, and findings there name the instance - [ ] Slice C — tokens: an `unknown-token` warning for any `$ref` the merged tokens do not define or that is the wrong kind, with a rename autofix when only one name is close; copy props never resolve; tints and `danger` derive from the applied palette, on new stamps and on canvases holding the old seeds - [ ] Slice D — desktop-app checks: `select` gets a `$border-strong` boundary and joins the boundary check, an active `tree-row` draws a bar the indicator check measures, and stress widens `nav-item` and `tabs` counts diff --git a/package.json b/package.json index 1276461..33dc489 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,8 @@ "bench": "tsx benchmark/run.ts", "test": "npm run test:fast", "test:fast": "tsx scripts/run-tests.ts", - "test:full": "tsx scripts/run-tests.ts --full" + "test:full": "tsx scripts/run-tests.ts --full", + "typecheck:tests": "tsc -p tsconfig.test.json" }, "dependencies": { "@anthropic-ai/sdk": "^0.96.0", diff --git a/scripts/run-tests.ts b/scripts/run-tests.ts index 6cc2223..3bb2f7c 100644 --- a/scripts/run-tests.ts +++ b/scripts/run-tests.ts @@ -2,70 +2,65 @@ // // Every test in this repo is a plain script: it prints PASS/FAIL lines and // exits 0 or 1. That convention works and this runner does not change it — it -// just discovers the scripts, runs them, and reports. Before it existed the 102 +// just discovers the scripts, runs them, and reports. Before it existed the // test files could only be run one at a time by hand, which is how two of them // came to be failing at the v2.0.0 tag without anyone noticing. // -// Tiers exist so the common case is fast. Roughly a third of the suite drives a -// real browser; those tests are worth having but they should not stand between -// you and finding out that a pure-logic change broke something. +// The folder a test lives in sets its tier: // -// npm run test:fast — everything that needs nothing but Node -// npm run test:full — the above plus the browser tests +// test/unit Node only. Run with Chrome made unlaunchable, so a unit test +// that reaches for a browser fails instead of passing quietly. +// test/browser launches Chrome +// test/e2e spawns the MCP server or the CLI +// test/manual needs a human or a running viewer; never run here +// +// npm run test:fast — test/unit +// npm run test:full — test/unit, test/browser and test/e2e // npm test — test:fast // -// Pass names or substrings to run a subset: `npx tsx scripts/run-tests.ts cliche` -import { readdirSync, readFileSync } from 'node:fs'; +// Pass substrings of a test's path to run a subset: `npx tsx scripts/run-tests.ts cliche` +// or `unit/` for a folder. `--root ` reads the folders from another directory +// (the runner's own tests use it). +import { existsSync, readdirSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; import { spawn, type ChildProcess } from 'node:child_process'; -/** Tests that never terminate on their own and are not batch-runnable. */ -const INTERACTIVE = new Set([ - // Starts a viewer server and waits for a human to look at it. Running it - // here would hang the suite forever, and it also collides with a live viewer - // on the same port. - 'test-viewer.ts', - // Expects a viewer already serving on a port passed as argv (its header says - // `npx tsx test-viewer-navbar.ts `) and writes screenshots for a human - // to look at. Nothing here can supply that, so it stays a manual check. - 'test-viewer-navbar.ts', -]); - -/** Tests that need a browser but don't say so in their imports. */ -const CHROME_ANYWAY = new Set([ - // Shells out to the CLI, whose check-drift path launches Chrome. Nothing in - // this file's own imports reveals that. - 'test-cli.ts', - // Drives the MCP server over stdio, and the server renders in Chrome for - // detailed evaluate, canvas_stress and screenshots. - 'test-ridgeline.ts', - // Phase 31's acceptance re-run, the same shape as test-ridgeline.ts. - 'test-viewer-rebuild.ts', - // Drives canvas_evaluate's detailed mode over MCP (S11's font path). - 'test-evaluate-fonts.ts', -]); - -/** Direct use of the browser is the honest signal — these are the entry points - * in screenshot.ts that every browser-driven test reaches for. */ -const CHROME_MARKERS = /takeScreenshot|computeLayout|withPage|withIsolatedPage|puppeteer|from '\.\/src\/screenshot\.js'/; - -// FRAMESMITH_TEST_TIMEOUT_MS overrides it (test-runner-timeout.ts uses 3s). +const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + +// FRAMESMITH_TEST_TIMEOUT_MS overrides it (test/unit/test-runner-timeout.ts uses 3s). const TIMEOUT_MS = Number(process.env.FRAMESMITH_TEST_TIMEOUT_MS) || 180_000; +/** A Chrome path that does not exist. A unit test that launches Chrome, through + * src/screenshot.ts or puppeteer.launch directly, fails on it. */ +const NO_CHROME = join(REPO, 'no-chrome-in-unit-tests'); + +/** What a failed launch prints: src/screenshot.ts's message, then Puppeteer's own. */ +const LAUNCH_FAILURE = /Failed to launch Chrome for rendering|Tried to find the browser at the configured path/; + type Tier = 'fast' | 'full'; -const tier: Tier = process.argv.includes('--full') ? 'full' : 'fast'; -const filters = process.argv.slice(2).filter((a) => !a.startsWith('--')); +const TIER_FOLDERS: Record = { fast: ['unit'], full: ['unit', 'browser', 'e2e'] }; -const needsChrome = (file: string): boolean => - CHROME_ANYWAY.has(file) || CHROME_MARKERS.test(readFileSync(file, 'utf-8')); +const args = process.argv.slice(2); +const rootAt = args.indexOf('--root'); +const root = rootAt >= 0 ? resolve(args[rootAt + 1]) : join(REPO, 'test'); +if (rootAt >= 0) args.splice(rootAt, 2); +const tier: Tier = args.includes('--full') ? 'full' : 'fast'; +const filters = args.filter((a) => !a.startsWith('--')); -const all = readdirSync('.') - .filter((f) => f.startsWith('test-') && f.endsWith('.ts') && f !== 'test-env.ts') - .filter((f) => !INTERACTIVE.has(f)) - .sort(); +// Tests read paths relative to the repo root (`resolve('src/index.ts')`). +process.chdir(REPO); -const selected = all - .filter((f) => tier === 'full' || !needsChrome(f)) - .filter((f) => filters.length === 0 || filters.some((q) => f.includes(q))); +/** Test paths under the root, as `/`. */ +const discover = (folder: string): string[] => { + const dir = join(root, folder); + if (!existsSync(dir)) return []; + return readdirSync(dir).filter((f) => f.endsWith('.ts')).sort().map((f) => `${folder}/${f}`); +}; + +const selected = TIER_FOLDERS[tier] + .flatMap(discover) + .filter((t) => filters.length === 0 || filters.some((q) => t.includes(q))); /** The test running now. Its own process group doesn't get the terminal's * Ctrl-C, so the runner passes an interrupt on before exiting. */ @@ -77,13 +72,19 @@ for (const signal of ['SIGINT', 'SIGTERM'] as const) { }); } -function run(file: string): Promise<{ file: string; ok: boolean; why: string; ms: number }> { - return new Promise((resolve) => { +type Result = { test: string; ok: boolean; why: string; ms: number }; + +function run(test: string): Promise { + const unit = test.startsWith('unit/'); + const env = unit + ? { ...process.env, FRAMESMITH_CHROME_PATH: NO_CHROME, PUPPETEER_EXECUTABLE_PATH: NO_CHROME } + : process.env; + return new Promise((done) => { const started = Date.now(); // Its own process group, so a timeout kills npx AND the tsx under it. // Killing npx alone orphaned tsx, which kept the pipes open, and 'close' // never fired: one hung test stalled the whole run. - const child = spawn('npx', ['tsx', file], { stdio: ['ignore', 'pipe', 'pipe'], detached: true }); + const child = spawn('npx', ['tsx', join(root, test)], { stdio: ['ignore', 'pipe', 'pipe'], detached: true, env }); current = child; let out = ''; child.stdout.on('data', (d) => { out += d; }); @@ -92,33 +93,36 @@ function run(file: string): Promise<{ file: string; ok: boolean; why: string; ms child.on('close', (code, signal) => { clearTimeout(timer); const ms = Date.now() - started; - if (signal === 'SIGKILL') return resolve({ file, ok: false, why: `timed out after ${TIMEOUT_MS / 1000}s`, ms }); - if (code === 0) return resolve({ file, ok: true, why: '', ms }); + if (signal === 'SIGKILL') return done({ test, ok: false, why: `timed out after ${TIMEOUT_MS / 1000}s`, ms }); + if (code === 0) return done({ test, ok: true, why: '', ms }); + const first = out.split('\n').filter((l) => /^FAIL|Error|error TS/.test(l))[0] ?? `exit ${code}`; - resolve({ file, ok: false, why: first.trim().slice(0, 160), ms }); + const launched = unit && LAUNCH_FAILURE.test(out) + ? '\n this test launches Chrome: move it to test/browser' + : ''; + done({ test, ok: false, why: first.trim().slice(0, 160) + launched, ms }); }); }); } console.log(`${selected.length} tests (${tier} tier)${filters.length ? ` matching ${filters.join(', ')}` : ''}\n`); -const failures: { file: string; why: string }[] = []; +const failures: Result[] = []; let passed = 0; -for (const file of selected) { - const r = await run(file); - if (r.ok) { passed++; console.log(` ok ${file} ${(r.ms / 1000).toFixed(1)}s`); } - else { failures.push(r); console.log(` FAIL ${file} ${r.why}`); } +for (const test of selected) { + const r = await run(test); + if (r.ok) { passed++; console.log(` ok ${test} ${(r.ms / 1000).toFixed(1)}s`); } + else { failures.push(r); console.log(` FAIL ${test} ${r.why}`); } } console.log(`\n${passed}/${selected.length} passed`); if (tier === 'fast') { - const skipped = all.filter(needsChrome).length; - console.log(`${skipped} browser tests not run in this tier — use npm run test:full`); + const skipped = discover('browser').length + discover('e2e').length; + if (skipped) console.log(`${skipped} browser and e2e tests not run in this tier — use npm run test:full`); } -if (INTERACTIVE.size) console.log(`${[...INTERACTIVE].join(', ')} excluded (interactive)`); if (failures.length) { console.log(`\n${failures.length} failing:`); - for (const f of failures) console.log(` ${f.file} ${f.why}`); + for (const f of failures) console.log(` ${f.test} ${f.why}`); process.exit(1); } diff --git a/src/color-system.ts b/src/color-system.ts index 4187be0..1225642 100644 --- a/src/color-system.ts +++ b/src/color-system.ts @@ -2,7 +2,7 @@ // perceptual ramps, a matched neutral, status colors, and a dual-theme // semantic mapping. Hand-rolled conversions (Björn Ottosson's OKLab math, // zero dependencies — validated against Chrome's own oklch() parsing in -// test-color-system-readback.ts). Pure: token WRITING is the tool's job. +// test/browser/test-color-system-readback.ts). Pure: token WRITING is the tool's job. // // Gamut policy (spec ANALYZE): out-of-gamut colors clip toward LOWER CHROMA // at fixed lightness and hue — never hue-shift, never lightness-shift. diff --git a/src/design-language.ts b/src/design-language.ts index fb92f5e..423a6b5 100644 --- a/src/design-language.ts +++ b/src/design-language.ts @@ -9,7 +9,7 @@ // // Personalities are CURATED, not computed (the pattern-library philosophy: // taste is hand-built, gates verify it). Every choice below is a reviewed -// design decision with its intent stated; test-design-language.ts locks every +// design decision with its intent stated; test/unit/test-design-language.ts locks every // personality's output against the evaluator and the cliché tells. import { generateColorSystem } from './color-system.js'; diff --git a/src/fonts.ts b/src/fonts.ts index 01e45ad..3091bca 100644 --- a/src/fonts.ts +++ b/src/fonts.ts @@ -23,7 +23,7 @@ import { homedir } from 'node:os'; import { join } from 'node:path'; import type { Canvas, DesignVariables, FontFace, SceneNode } from './types.js'; -// Same env contract as scene-graph.ts/workspaces.ts so test-env.ts redirects +// Same env contract as scene-graph.ts/workspaces.ts so test/env.ts redirects // the font cache along with everything else. function fontsDir(): string { const home = process.env.FRAMESMITH_HOME ?? process.env.CANVAS_MCP_HOME ?? join(homedir(), '.framesmith'); diff --git a/src/state-checks.ts b/src/state-checks.ts index 98a2586..552b385 100644 --- a/src/state-checks.ts +++ b/src/state-checks.ts @@ -2,7 +2,7 @@ // checked without being drawn. The model computes, from the resolved tree with // instances expanded, the colours the renderer draws for a target's focus // ring, active indicator, disabled content and boundary (slice G P4, S9, S10, -// Q6); the four rules judge them, and test-state-model-render.ts holds the +// Q6); the four rules judge them, and test/browser/test-state-model-render.ts holds the // model to the pixels of a real render so the two cannot drift apart. import type { EvaluationIssue } from './evaluate.js'; diff --git a/test-phase2.ts b/test-phase2.ts deleted file mode 100644 index 1b52c5d..0000000 --- a/test-phase2.ts +++ /dev/null @@ -1,198 +0,0 @@ -import './test-env.js'; -/** - * Quick smoke test for Phase 2 features. - * Run with: npx tsx test-phase2.ts - */ - -import { createCanvas, getCanvas, findNode } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { resolveVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { takeScreenshot, exportToFile, shutdown } from './src/screenshot.js'; -import { listPresets, getPreset } from './src/presets.js'; -import { getIconSvg, listIconNames } from './src/icons.js'; -import { setVariables } from './src/variables.js'; - -let passed = 0; -let failed = 0; - -function assert(condition: boolean, label: string) { - if (condition) { - console.log(` ✓ ${label}`); - passed++; - } else { - console.log(` ✗ ${label}`); - failed++; - } -} - -async function testPresets() { - console.log('\n── Style Guide Presets ──'); - - const presets = listPresets(); - assert(presets.length === 4, 'Has 4 presets'); - assert(presets.some(p => p.name === 'dark'), 'Has dark preset'); - assert(presets.some(p => p.name === 'light'), 'Has light preset'); - assert(presets.some(p => p.name === 'material'), 'Has material preset'); - assert(presets.some(p => p.name === 'minimal'), 'Has minimal preset'); - - const dark = getPreset('dark')!; - assert(!!dark.variables.colors, 'Dark preset has colors'); - assert(!!dark.variables.typography, 'Dark preset has typography'); - - // Apply preset to canvas - const canvas = createCanvas('Preset Test'); - setVariables(canvas, dark.variables); - assert(canvas.variables.colors?.['bg-primary'] === '#0a0a0a', 'Preset applied to canvas'); -} - -async function testIcons() { - console.log('\n── Icon Support (Lucide) ──'); - - const names = listIconNames(); - assert(names.length > 100, `Loaded ${names.length} icons`); - assert(names.includes('search'), 'Has search icon'); - assert(names.includes('heart'), 'Has heart icon'); - assert(names.includes('home'), 'Has home icon'); - - const svg = getIconSvg('search', 24, '#ff0000'); - assert(svg !== null, 'getIconSvg returns SVG'); - assert(svg!.includes(' tag'); - assert(svg!.includes('width="24"'), 'SVG has correct size'); - assert(svg!.includes('stroke="#ff0000"'), 'SVG has custom color'); - - const missing = getIconSvg('nonexistent-icon-xyz'); - assert(missing === null, 'Returns null for unknown icon'); - - // Render icon node - const canvas = createCanvas('Icon Test'); - const results = parseAndExecute(canvas.root, ` -icon1=I("document", {type: "icon", icon: "search", iconSize: 32, iconColor: "#3b82f6"}) -icon2=I("document", {type: "icon", icon: "heart", iconSize: 24, iconColor: "#ef4444"}) - `, canvas); - assert(results.every(r => r.ok), 'Icon nodes inserted'); - - const html = renderToHtml(canvas.root, 400, 200, canvas); - assert(html.includes(' r.ok), 'Component created'); - assert(Object.keys(canvas.components).length === 1, 'Component registered in canvas'); - - const compId = results[0].nodeId!; - assert(canvas.components[compId] !== undefined, 'Component accessible by ID'); - - // Create instances with overrides - const instanceResults = parseAndExecute(canvas.root, ` -inst1=I("document", {type: "instance", componentId: "${compId}", overrides: {title: {content: "First Card"}, description: {content: "Custom description 1"}}}) -inst2=I("document", {type: "instance", componentId: "${compId}", overrides: {title: {content: "Second Card", color: "#3b82f6"}}}) - `, canvas); - assert(instanceResults.every(r => r.ok), 'Instances created'); - - // Render and verify instances are resolved - const html = renderToHtml(canvas.root, 800, 600, canvas); - assert(html.includes('First Card'), 'Instance 1 override applied'); - assert(html.includes('Second Card'), 'Instance 2 override applied'); - assert(html.includes('Custom description 1'), 'Nested override applied'); - assert(html.includes('Default description text'), 'Instance 2 keeps default description'); - - // Take screenshot to verify visual rendering - const base64 = await takeScreenshot(html, { width: 800, height: 600 }); - assert(base64.length > 100, `Screenshot captured (${Math.round(base64.length / 1024)}KB base64)`); -} - -async function testComponentBinding() { - console.log('\n── Component ID Binding ──'); - - const canvas = createCanvas('Binding Test'); - - // Use binding variable for componentId (not string literal) - const results = parseAndExecute(canvas.root, ` -btn=I("document", {type: "component", name: "Button", width: 120, height: 40, fill: "#3b82f6", cornerRadius: 8, layout: "horizontal", alignItems: "center", justifyContent: "center"}) -I(btn, {type: "text", name: "label", content: "Click me", fontSize: 14, color: "#fff"}) -inst=I("document", {type: "instance", componentId: btn, overrides: {label: {content: "Submit"}}}) - `, canvas); - assert(results.every(r => r.ok), 'Component + instance via binding'); - - const html = renderToHtml(canvas.root, 400, 200, canvas); - assert(html.includes('Submit'), 'Binding-based instance resolved'); -} - -// Run all tests -async function main() { - console.log('Framesmith — Phase 2 Smoke Tests\n================================'); - - await testPresets(); - await testIcons(); - await testExport(); - await testComponents(); - await testComponentBinding(); - - console.log(`\n================================`); - console.log(`Results: ${passed} passed, ${failed} failed`); - - await shutdown(); - process.exit(failed > 0 ? 1 : 0); -} - -main().catch((err) => { - console.error('Test error:', err); - shutdown().then(() => process.exit(1)); -}); \ No newline at end of file diff --git a/test-phase3.ts b/test-phase3.ts deleted file mode 100644 index 8611b56..0000000 --- a/test-phase3.ts +++ /dev/null @@ -1,178 +0,0 @@ -import './test-env.js'; -/** - * Smoke test for Phase 3 features. - * Run with: npx tsx test-phase3.ts - */ - -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { resolveVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { takeScreenshot, takeResponsiveScreenshots, computeDiff, shutdown } from './src/screenshot.js'; - -let passed = 0; -let failed = 0; - -function assert(condition: boolean, label: string) { - if (condition) { - console.log(` ✓ ${label}`); - passed++; - } else { - console.log(` ✗ ${label}`); - failed++; - } -} - -async function testGradients() { - console.log('\n── Gradients ──'); - - const canvas = createCanvas('Gradient Test'); - const results = parseAndExecute(canvas.root, ` -linear=I("document", {type: "frame", width: 400, height: 200, gradient: {type: "linear", angle: 135, stops: [{color: "#667eea", position: 0}, {color: "#764ba2", position: 100}]}, cornerRadius: 12}) -radial=I("document", {type: "frame", width: 400, height: 200, gradient: {type: "radial", stops: [{color: "#ffffff", position: 0}, {color: "#000000", position: 100}]}, cornerRadius: 12}) -fallback=I("document", {type: "frame", width: 400, height: 200, fill: "#ff0000"}) - `, canvas); - assert(results.every(r => r.ok), 'Gradient nodes inserted'); - - const resolved = resolveVariables(canvas.root, canvas.variables); - const html = renderToHtml(resolved, 800, 800, canvas); - - assert(html.includes('linear-gradient(135deg'), 'HTML contains linear-gradient with angle'); - assert(html.includes('#667eea 0%'), 'Linear gradient has first stop'); - assert(html.includes('#764ba2 100%'), 'Linear gradient has second stop'); - assert(html.includes('radial-gradient('), 'HTML contains radial-gradient'); - assert(html.includes('background-color: #ff0000'), 'Fallback fill still works'); - - // Gradient and fill should not both appear on the same node - // The linear gradient node should use background, not background-color - assert(html.includes('background: linear-gradient'), 'Gradient uses background property'); - - const base64 = await takeScreenshot(html, { width: 800, height: 800 }); - assert(base64.length > 100, `Screenshot captured (${Math.round(base64.length / 1024)}KB)`); -} - -async function testShadowsAndBlur() { - console.log('\n── Shadows & Blur ──'); - - const canvas = createCanvas('Shadow Test'); - const results = parseAndExecute(canvas.root, ` -box1=I("document", {type: "frame", width: 300, height: 150, fill: "#ffffff", shadows: [{x: 0, y: 4, blur: 12, spread: 0, color: "rgba(0,0,0,0.2)"}], cornerRadius: 8}) -box2=I("document", {type: "frame", width: 300, height: 150, fill: "#ffffff", shadows: [{x: 0, y: 2, blur: 4, color: "rgba(0,0,0,0.1)"}, {x: 0, y: 8, blur: 24, color: "rgba(0,0,0,0.15)"}], cornerRadius: 8}) -box3=I("document", {type: "frame", width: 300, height: 150, fill: "#ffffff", shadow: "0 4px 6px rgba(0,0,0,0.1)"}) -blurred=I("document", {type: "frame", width: 300, height: 150, fill: "#3b82f6", blur: 4}) -backdrop=I("document", {type: "frame", width: 300, height: 150, fill: "rgba(255,255,255,0.5)", backdropBlur: 8}) - `, canvas); - assert(results.every(r => r.ok), 'Shadow/blur nodes inserted'); - - const resolved = resolveVariables(canvas.root, canvas.variables); - const html = renderToHtml(resolved, 800, 1000, canvas); - - // Structured shadows - assert(html.includes('box-shadow: 0px 4px 12px 0px rgba(0,0,0,0.2)'), 'Single structured shadow rendered'); - assert(html.includes('0px 2px 4px 0px rgba(0,0,0,0.1)'), 'Multi-shadow first shadow'); - assert(html.includes('0px 8px 24px 0px rgba(0,0,0,0.15)'), 'Multi-shadow second shadow'); - - // Legacy shadow string - assert(html.includes('box-shadow: 0 4px 6px rgba(0,0,0,0.1)'), 'Legacy shadow string still works'); - - // Blur - assert(html.includes('filter: blur(4px)'), 'Blur filter rendered'); - assert(html.includes('backdrop-filter: blur(8px)'), 'Backdrop blur rendered'); -} - -async function testResponsiveBreakpoints() { - console.log('\n── Responsive Breakpoints ──'); - - const canvas = createCanvas('Responsive Test'); - parseAndExecute(canvas.root, ` -container=I("document", {type: "frame", width: "100%", height: "100%", fill: "#0a0a0a", layout: "vertical", padding: 24, gap: 16}) -I(container, {type: "text", content: "Responsive Test", fontSize: 24, color: "#ffffff"}) -row=I(container, {type: "frame", layout: "horizontal", gap: 16, wrap: true, width: "100%"}) -I(row, {type: "frame", width: 200, height: 100, fill: "#3b82f6", cornerRadius: 8}) -I(row, {type: "frame", width: 200, height: 100, fill: "#ef4444", cornerRadius: 8}) -I(row, {type: "frame", width: 200, height: 100, fill: "#22c55e", cornerRadius: 8}) - `, canvas); - - const resolved = resolveVariables(canvas.root, canvas.variables); - - const breakpoints = [ - { label: 'mobile', width: 390, height: 844 }, - { label: 'tablet', width: 768, height: 1024 }, - { label: 'desktop', width: 1440, height: 900 }, - ]; - - // Per-breakpoint render callback — matches the screenshot_responsive handler's - // signature (true reflow: the body scaffold matches each viewport). - const results = await takeResponsiveScreenshots((bp) => renderToHtml(resolved, bp.width, bp.height, canvas), breakpoints); - assert(results.length === 3, 'Got 3 responsive screenshots'); - assert(results[0].label === 'mobile', 'First is mobile'); - assert(results[0].width === 390, 'Mobile width is 390'); - assert(results[1].label === 'tablet', 'Second is tablet'); - assert(results[2].label === 'desktop', 'Third is desktop'); - assert(results.every(r => r.data.length > 100), 'All screenshots have data'); - - // Mobile screenshot should be smaller (fewer pixels) - assert(results[0].data.length < results[2].data.length, 'Mobile screenshot is smaller than desktop'); -} - -async function testDiffMode() { - console.log('\n── Diff Mode ──'); - - // Create two identical canvases - const canvas1 = createCanvas('Diff A'); - const canvas2 = createCanvas('Diff B'); - - const ops = ` -bg=I("document", {type: "frame", width: 400, height: 300, fill: "#0a0a0a", layout: "vertical", padding: 24, gap: 16}) -I(bg, {type: "text", content: "Hello World", fontSize: 24, color: "#ffffff"}) -I(bg, {type: "frame", width: 200, height: 50, fill: "#3b82f6", cornerRadius: 8}) - `; - - parseAndExecute(canvas1.root, ops, canvas1); - parseAndExecute(canvas2.root, ops, canvas2); - - const resolved1 = resolveVariables(canvas1.root, canvas1.variables); - const resolved2 = resolveVariables(canvas2.root, canvas2.variables); - - // Compare identical canvases - const html1 = renderToHtml(resolved1, 400, 300, canvas1); - const html2 = renderToHtml(resolved2, 400, 300, canvas2); - - const identicalDiff = await computeDiff(html1, html2, 400, 300, 1); - assert(identicalDiff.changePercent < 1, `Identical canvases: ${identicalDiff.changePercent}% diff (expected ~0%)`); - assert(identicalDiff.diffImage.length > 100, 'Diff image generated'); - - // Create a completely different canvas for comparison - const canvas3 = createCanvas('Diff C'); - parseAndExecute(canvas3.root, ` -bg=I("document", {type: "frame", width: 400, height: 300, fill: "#ef4444", layout: "vertical", padding: 24, gap: 16}) -I(bg, {type: "text", content: "Different!", fontSize: 48, color: "#000000"}) - `, canvas3); - - const resolved3 = resolveVariables(canvas3.root, canvas3.variables); - const html3 = renderToHtml(resolved3, 400, 300, canvas3); - - const changedDiff = await computeDiff(html1, html3, 400, 300, 1); - assert(changedDiff.changePercent > 0, `Different canvases: ${changedDiff.changePercent}% diff (expected >0%)`); - assert(changedDiff.changedPixels > 0, `Changed pixels: ${changedDiff.changedPixels}`); -} - -async function main() { - console.log('Framesmith — Phase 3 Smoke Tests\n================================'); - - await testGradients(); - await testShadowsAndBlur(); - await testResponsiveBreakpoints(); - await testDiffMode(); - - console.log(`\n================================`); - console.log(`Results: ${passed} passed, ${failed} failed`); - - await shutdown(); - process.exit(failed > 0 ? 1 : 0); -} - -main().catch((err) => { - console.error('Test error:', err); - shutdown().then(() => process.exit(1)); -}); \ No newline at end of file diff --git a/test-animations.ts b/test/browser/test-animations.ts similarity index 97% rename from test-animations.ts rename to test/browser/test-animations.ts index 270387e..672fa3c 100644 --- a/test-animations.ts +++ b/test/browser/test-animations.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 8 final item: animations + transitions. // The renderer must: // - emit a built-in @keyframes block ONLY when referenced @@ -10,11 +10,11 @@ import './test-env.js'; // - reject suspicious transition.property values (default to 'all') // - leave existing scenes unchanged when neither field is set // -// Usage: npx tsx test-animations.ts +// Usage: npx tsx test/browser/test-animations.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-auto-relative.ts b/test/browser/test-auto-relative.ts similarity index 95% rename from test-auto-relative.ts rename to test/browser/test-auto-relative.ts index c255502..4ad7e9b 100644 --- a/test-auto-relative.ts +++ b/test/browser/test-auto-relative.ts @@ -1,15 +1,15 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 8 item: auto position: relative injection. // When a descendant uses `position: absolute` without a positioned ancestor, // the renderer must inject `position: relative` on the nearest container // frame/document/component so the absolute child anchors to it instead of // escaping to body coordinates (the slice 5a mock bug). // -// Usage: npx tsx test-auto-relative.ts +// Usage: npx tsx test/browser/test-auto-relative.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; interface Case { label: string; diff --git a/test-backdrop-filter.ts b/test/browser/test-backdrop-filter.ts similarity index 93% rename from test-backdrop-filter.ts rename to test/browser/test-backdrop-filter.ts index c05c4a9..e825d77 100644 --- a/test-backdrop-filter.ts +++ b/test/browser/test-backdrop-filter.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 8 item: backdrop-filter support. // The renderer must: // - compose blur + saturate + brightness + contrast into a single @@ -9,11 +9,11 @@ import './test-env.js'; // - emit nothing when both are absent // - skip undefined sub-fields (e.g. saturate only, no blur) // -// Usage: npx tsx test-backdrop-filter.ts +// Usage: npx tsx test/browser/test-backdrop-filter.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; @@ -90,7 +90,8 @@ try { await page.setContent(html, { waitUntil: 'domcontentloaded' }); const computed = await page.evaluate(() => { const el = document.querySelector('[data-node-id="glass"]') as HTMLElement; - const cs = getComputedStyle(el); + // Chrome still exposes the prefixed property; the DOM typings do not. + const cs = getComputedStyle(el) as CSSStyleDeclaration & { webkitBackdropFilter?: string }; return { backdrop: cs.backdropFilter, webkit: cs.webkitBackdropFilter }; }); await page.close(); diff --git a/test-check-drift-url.ts b/test/browser/test-check-drift-url.ts similarity index 90% rename from test-check-drift-url.ts rename to test/browser/test-check-drift-url.ts index e832c36..8ca7615 100644 --- a/test-check-drift-url.ts +++ b/test/browser/test-check-drift-url.ts @@ -1,18 +1,18 @@ -import './test-env.js'; +import '../env.js'; // Phase 23 slice B (#148) — canvas_check_drift end-to-end: a real page served // from a local http server (no external network), imported ephemerally and // structurally compared against a canvas. Covers the in-sync path (a canvas // built to match the page) and the drifted path (the radiogroup-vs-select // incident against live HTML). // -// Usage: npx tsx test-check-drift-url.ts (needs Chrome) +// Usage: npx tsx test/browser/test-check-drift-url.ts (needs Chrome) import { createServer, type Server } from 'node:http'; -import { importUrl } from './src/import.js'; -import { shutdown } from './src/screenshot.js'; -import { computeStructuralDrift } from './src/drift.js'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; +import { importUrl } from '../../src/import.js'; +import { shutdown } from '../../src/screenshot.js'; +import { computeStructuralDrift } from '../../src/drift.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-color-system-readback.ts b/test/browser/test-color-system-readback.ts similarity index 90% rename from test-color-system-readback.ts rename to test/browser/test-color-system-readback.ts index 1c5935f..279e125 100644 --- a/test-color-system-readback.ts +++ b/test/browser/test-color-system-readback.ts @@ -3,13 +3,13 @@ // uses). For a spread of in-gamut OKLCH values, the browser's rendered RGB and // our oklchToHex must agree within 2/255 per channel. // -// Usage: npx tsx test-color-system-readback.ts (needs Chrome) +// Usage: npx tsx test/browser/test-color-system-readback.ts (needs Chrome) -import './test-env.js'; -import { oklchToHex, hexToOklch } from './src/color-system.js'; -import { withPage } from './src/screenshot.js'; -import { shutdown } from './src/screenshot.js'; -import { parseColor } from './src/evaluate.js'; +import '../env.js'; +import { oklchToHex, hexToOklch } from '../../src/color-system.js'; +import { withPage } from '../../src/screenshot.js'; +import { shutdown } from '../../src/screenshot.js'; +import { parseColor } from '../../src/evaluate.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test/browser/test-component-instances.ts b/test/browser/test-component-instances.ts new file mode 100644 index 0000000..a4f82f0 --- /dev/null +++ b/test/browser/test-component-instances.ts @@ -0,0 +1,91 @@ +import '../env.js'; +/** + * Components and their instances: overrides apply per instance, a component id + * bound by name resolves, and an instance tree renders in Chrome. + * Run with: npx tsx test/browser/test-component-instances.ts + */ + +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { takeScreenshot, shutdown } from '../../src/screenshot.js'; + +let passed = 0; +let failed = 0; + +function assert(condition: boolean, label: string) { + if (condition) { + console.log(` ✓ ${label}`); + passed++; + } else { + console.log(` ✗ ${label}`); + failed++; + } +} + +async function testComponents() { + console.log('\n── Reusable Components ──'); + + const canvas = createCanvas('Component Test'); + + // Define a component + const results = parseAndExecute(canvas.root, ` +card=I("document", {type: "component", name: "Card", width: 300, height: 150, fill: "#1a1a1a", cornerRadius: 12, layout: "vertical", padding: 16, gap: 8}) +title=I(card, {type: "text", name: "title", content: "Default Title", fontSize: 20, fontWeight: 700, color: "#ffffff"}) +desc=I(card, {type: "text", name: "description", content: "Default description text", fontSize: 14, color: "#ffffffa0"}) + `, canvas); + assert(results.every(r => r.ok), 'Component created'); + assert(Object.keys(canvas.components).length === 1, 'Component registered in canvas'); + + const compId = results[0].nodeId!; + assert(canvas.components[compId] !== undefined, 'Component accessible by ID'); + + // Create instances with overrides + const instanceResults = parseAndExecute(canvas.root, ` +inst1=I("document", {type: "instance", componentId: "${compId}", overrides: {title: {content: "First Card"}, description: {content: "Custom description 1"}}}) +inst2=I("document", {type: "instance", componentId: "${compId}", overrides: {title: {content: "Second Card", color: "#3b82f6"}}}) + `, canvas); + assert(instanceResults.every(r => r.ok), 'Instances created'); + + // Render and verify instances are resolved + const html = renderToHtml(canvas.root, 800, 600, canvas); + assert(html.includes('First Card'), 'Instance 1 override applied'); + assert(html.includes('Second Card'), 'Instance 2 override applied'); + assert(html.includes('Custom description 1'), 'Nested override applied'); + assert(html.includes('Default description text'), 'Instance 2 keeps default description'); + + // Take screenshot to verify visual rendering + const base64 = await takeScreenshot(html, { width: 800, height: 600 }); + assert(base64.length > 100, `Screenshot captured (${Math.round(base64.length / 1024)}KB base64)`); +} + +function testComponentBinding() { + console.log('\n── Component ID Binding ──'); + + const canvas = createCanvas('Binding Test'); + + // Use binding variable for componentId (not string literal) + const results = parseAndExecute(canvas.root, ` +btn=I("document", {type: "component", name: "Button", width: 120, height: 40, fill: "#3b82f6", cornerRadius: 8, layout: "horizontal", alignItems: "center", justifyContent: "center"}) +I(btn, {type: "text", name: "label", content: "Click me", fontSize: 14, color: "#fff"}) +inst=I("document", {type: "instance", componentId: btn, overrides: {label: {content: "Submit"}}}) + `, canvas); + assert(results.every(r => r.ok), 'Component + instance via binding'); + + const html = renderToHtml(canvas.root, 400, 200, canvas); + assert(html.includes('Submit'), 'Binding-based instance resolved'); +} + +async function main() { + await testComponents(); + testComponentBinding(); + + console.log(`\nResults: ${passed} passed, ${failed} failed`); + await shutdown(); + process.exit(failed > 0 ? 1 : 0); +} + +main().catch((err) => { + console.error('Test error:', err); + shutdown().then(() => process.exit(1)); +}); diff --git a/test-custom-fonts.ts b/test/browser/test-custom-fonts.ts similarity index 96% rename from test-custom-fonts.ts rename to test/browser/test-custom-fonts.ts index 8ff68fa..7843656 100644 --- a/test-custom-fonts.ts +++ b/test/browser/test-custom-fonts.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 8 item: custom font loading. // The renderer must: // - emit `@font-face` blocks in for `canvas.fonts` entries @@ -9,11 +9,11 @@ import './test-env.js'; // - declare `font-display: swap` so paint isn't blocked on slow fonts // - leave canvases with no `fonts` field unchanged (no font-face block) // -// Usage: npx tsx test-custom-fonts.ts +// Usage: npx tsx test/browser/test-custom-fonts.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; const baseRoot: SceneNode = { id: 'doc', type: 'document', fill: '#0F172A', diff --git a/test-default-font.ts b/test/browser/test-default-font.ts similarity index 90% rename from test-default-font.ts rename to test/browser/test-default-font.ts index e5279e2..9119c9f 100644 --- a/test-default-font.ts +++ b/test/browser/test-default-font.ts @@ -1,13 +1,13 @@ -import './test-env.js'; +import '../env.js'; // Smoke for the renderer default font-family. Asserts that a text node with no // `fontFamily` set inherits the sans-serif stack from the body rule (not the // browser's default serif), and that explicit per-node `fontFamily` still wins. // -// Usage: npx tsx test-default-font.ts +// Usage: npx tsx test/browser/test-default-font.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; const root: SceneNode = { id: 'doc', diff --git a/test-desktop-app-overlay-detailed.ts b/test/browser/test-desktop-app-overlay-detailed.ts similarity index 95% rename from test-desktop-app-overlay-detailed.ts rename to test/browser/test-desktop-app-overlay-detailed.ts index 8382da8..87e1890 100644 --- a/test-desktop-app-overlay-detailed.ts +++ b/test/browser/test-desktop-app-overlay-detailed.ts @@ -4,14 +4,14 @@ // two acceptance stand-ins (M7). Each detailed finding has a fast-mode twin // that stays silent, and each pass a failing twin. Needs Chrome. // -// Usage: npx tsx test-desktop-app-overlay-detailed.ts +// Usage: npx tsx test/browser/test-desktop-app-overlay-detailed.ts -import './test-env.js'; -import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; -import { createCanvas } from './src/scene-graph.js'; -import { shutdown } from './src/screenshot.js'; -import { applyStructure } from './src/structures.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import '../env.js'; +import { evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { shutdown } from '../../src/screenshot.js'; +import { applyStructure } from '../../src/structures.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -139,7 +139,7 @@ async function standIn(overlay: SceneNode[]): Promise<{ overlay: EvaluationIssue frame('comment-actions', [ { id: 'cancel', name: 'Cancel', type: 'button', label: 'Cancel', variant: 'ghost', size: 'sm' } as SceneNode, { id: 'post', name: 'Post', type: 'button', label: 'Post', variant: 'primary', size: 'sm' } as SceneNode, - ], { layout: 'horizontal', gap: 8, justifyContent: 'flex-end' }), + ], { layout: 'horizontal', gap: 8, justifyContent: 'end' }), ], } as SceneNode, ]); diff --git a/test-desktop-app-rules-detailed.ts b/test/browser/test-desktop-app-rules-detailed.ts similarity index 95% rename from test-desktop-app-rules-detailed.ts rename to test/browser/test-desktop-app-rules-detailed.ts index e7101d5..72218e6 100644 --- a/test-desktop-app-rules-detailed.ts +++ b/test/browser/test-desktop-app-rules-detailed.ts @@ -4,12 +4,12 @@ // Each detailed finding has a fast-mode twin that must stay silent, and each // pass a failing twin. Needs Chrome. // -// Usage: npx tsx test-desktop-app-rules-detailed.ts +// Usage: npx tsx test/browser/test-desktop-app-rules-detailed.ts -import './test-env.js'; -import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; -import { shutdown } from './src/screenshot.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import '../env.js'; +import { evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import { shutdown } from '../../src/screenshot.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -20,7 +20,7 @@ function check(name: string, cond: boolean, extra?: string) { function canvasOf(children: SceneNode[]): Canvas { return { id: 'c', name: 'c', projectId: 'p', components: {}, variables: {}, createdAt: '', lastModified: '', - root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 40, gap: 16, alignItems: 'flex-start', children }, + root: { id: 'document', type: 'document', name: 'Document', width: 1440, height: 900, fill: '#FFFFFF', layout: 'vertical', padding: 40, gap: 16, alignItems: 'start', children }, metadata: { surface: { type: 'desktop-app', device: 'window-1440' } }, } as Canvas; } diff --git a/test-desktop-primitives-render.ts b/test/browser/test-desktop-primitives-render.ts similarity index 93% rename from test-desktop-primitives-render.ts rename to test/browser/test-desktop-primitives-render.ts index 208eb33..b48150a 100644 --- a/test-desktop-primitives-render.ts +++ b/test/browser/test-desktop-primitives-render.ts @@ -3,15 +3,15 @@ // full-height pane divider, both themes, and long text that truncates by // design instead of clipping or overflowing. // -// Usage: npx tsx test-desktop-primitives-render.ts +// Usage: npx tsx test/browser/test-desktop-primitives-render.ts -import './test-env.js'; -import { computeLayout, shutdown, type LayoutRect } from './src/screenshot.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { applyPerturbation, compareLayouts } from './src/stress.js'; -import { generateDesignSystem } from './src/design-language.js'; -import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; +import '../env.js'; +import { computeLayout, shutdown, type LayoutRect } from '../../src/screenshot.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { applyPerturbation, compareLayouts } from '../../src/stress.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import type { Canvas, DesignVariables, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -97,7 +97,7 @@ for (const [label, vars] of themes) { { const c = canvasOf(inspector, system); const html = renderToHtml(resolveVariables(structuredClone(c.root), system), 1440, 900, c); - const { withPage } = await import('./src/screenshot.js'); + const { withPage } = await import('../../src/screenshot.js'); const rights = await withPage(async (page) => { await page.setViewport({ width: 1440, height: 900 }); await page.setContent(html, { waitUntil: 'domcontentloaded' }); diff --git a/test/browser/test-diff.ts b/test/browser/test-diff.ts new file mode 100644 index 0000000..6a68fb4 --- /dev/null +++ b/test/browser/test-diff.ts @@ -0,0 +1,80 @@ +import '../env.js'; +/** + * Diff mode: identical renders diff at about 0%, different renders report + * changed pixels and a diff image. + * Run with: npx tsx test/browser/test-diff.ts + */ + +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { resolveVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { computeDiff, shutdown } from '../../src/screenshot.js'; + +let passed = 0; +let failed = 0; + +function assert(condition: boolean, label: string) { + if (condition) { + console.log(` ✓ ${label}`); + passed++; + } else { + console.log(` ✗ ${label}`); + failed++; + } +} + +async function testDiffMode() { + console.log('\n── Diff Mode ──'); + + // Create two identical canvases + const canvas1 = createCanvas('Diff A'); + const canvas2 = createCanvas('Diff B'); + + const ops = ` +bg=I("document", {type: "frame", width: 400, height: 300, fill: "#0a0a0a", layout: "vertical", padding: 24, gap: 16}) +I(bg, {type: "text", content: "Hello World", fontSize: 24, color: "#ffffff"}) +I(bg, {type: "frame", width: 200, height: 50, fill: "#3b82f6", cornerRadius: 8}) + `; + + parseAndExecute(canvas1.root, ops, canvas1); + parseAndExecute(canvas2.root, ops, canvas2); + + const resolved1 = resolveVariables(canvas1.root, canvas1.variables); + const resolved2 = resolveVariables(canvas2.root, canvas2.variables); + + // Compare identical canvases + const html1 = renderToHtml(resolved1, 400, 300, canvas1); + const html2 = renderToHtml(resolved2, 400, 300, canvas2); + + const identicalDiff = await computeDiff(html1, html2, 400, 300, 1); + assert(identicalDiff.changePercent < 1, `Identical canvases: ${identicalDiff.changePercent}% diff (expected ~0%)`); + assert(identicalDiff.diffImage.length > 100, 'Diff image generated'); + + // Create a completely different canvas for comparison + const canvas3 = createCanvas('Diff C'); + parseAndExecute(canvas3.root, ` +bg=I("document", {type: "frame", width: 400, height: 300, fill: "#ef4444", layout: "vertical", padding: 24, gap: 16}) +I(bg, {type: "text", content: "Different!", fontSize: 48, color: "#000000"}) + `, canvas3); + + const resolved3 = resolveVariables(canvas3.root, canvas3.variables); + const html3 = renderToHtml(resolved3, 400, 300, canvas3); + + const changedDiff = await computeDiff(html1, html3, 400, 300, 1); + assert(changedDiff.changePercent > 0, `Different canvases: ${changedDiff.changePercent}% diff (expected >0%)`); + assert(changedDiff.changedPixels > 0, `Changed pixels: ${changedDiff.changedPixels}`); +} + +async function main() { + await testDiffMode(); + + console.log(`\nResults: ${passed} passed, ${failed} failed`); + await shutdown(); + process.exit(failed > 0 ? 1 : 0); +} + +main().catch((err) => { + console.error('Test error:', err); + shutdown().then(() => process.exit(1)); +}); diff --git a/test-element-states-render.ts b/test/browser/test-element-states-render.ts similarity index 87% rename from test-element-states-render.ts rename to test/browser/test-element-states-render.ts index a13d8b8..d6cdbf2 100644 --- a/test-element-states-render.ts +++ b/test/browser/test-element-states-render.ts @@ -5,14 +5,14 @@ // button, so the focus ring (outside the box, S9) is in the frame. PNG bytes // stand in for pixels: the encoder is lossless and deterministic, so equal // bytes mean equal pixels and different bytes different ones. -// Needs Chrome. Run with: npx tsx test-element-states-render.ts +// Needs Chrome. Run with: npx tsx test/browser/test-element-states-render.ts -import './test-env.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { generateDesignSystem } from './src/design-language.js'; -import { takeScreenshot, shutdown } from './src/screenshot.js'; -import type { ElementState, SceneNode } from './src/types.js'; +import '../env.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import { takeScreenshot, shutdown } from '../../src/screenshot.js'; +import type { ElementState, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test/browser/test-evaluate-detailed.ts b/test/browser/test-evaluate-detailed.ts new file mode 100644 index 0000000..2903ab5 --- /dev/null +++ b/test/browser/test-evaluate-detailed.ts @@ -0,0 +1,60 @@ +import '../env.js'; +/** + * canvas_evaluate's detailed mode, which lays the canvas out in Chrome. + * The fast-mode checks are in test/unit/test-evaluate.ts. + * Run with: npx tsx test/browser/test-evaluate-detailed.ts + */ + +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { setVariables } from '../../src/variables.js'; +import { getPreset } from '../../src/presets.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { shutdown } from '../../src/screenshot.js'; + +let passed = 0; +let failed = 0; + +function assert(condition: boolean, label: string) { + if (condition) { + console.log(` ✓ ${label}`); + passed++; + } else { + console.log(` ✗ ${label}`); + failed++; + } +} + +async function testDetailedMode() { + console.log('\n── Detailed Mode (Puppeteer) ──'); + + const canvas = createCanvas('Detailed Test'); + setVariables(canvas, getPreset('dark')!.variables); + + parseAndExecute(canvas.root, ` +page=I("document", {type: "frame", name: "page", width: 800, height: 600, fill: "$bg-primary", layout: "vertical", padding: "$lg", gap: "$md"}) +I(page, {type: "text", name: "title", content: "Detailed Test", fontSize: 24, fontWeight: 700, color: "$text-primary"}) +row=I(page, {type: "frame", name: "row", layout: "horizontal", gap: "$md"}) +I(row, {type: "frame", name: "box1", width: 200, height: 100, fill: "$bg-surface", cornerRadius: "$sm"}) +I(row, {type: "frame", name: "box2", width: 200, height: 100, fill: "$bg-surface", cornerRadius: "$sm"}) + `, canvas); + + const result = await evaluateCanvas(canvas, { mode: 'detailed' }); + assert(result.mode === 'detailed', 'Mode is detailed'); + assert(result.overallScore >= 0, `Score: ${result.overallScore}/100`); + console.log(`\n Score: ${result.overallScore}/100`); + result.categories.forEach(c => console.log(` ${c.name}: ${c.score}/100 (${c.issueCount} issues)`)); +} + +async function main() { + await testDetailedMode(); + + console.log(`\nResults: ${passed} passed, ${failed} failed`); + await shutdown(); + process.exit(failed > 0 ? 1 : 0); +} + +main().catch((err) => { + console.error('Error:', err); + shutdown().then(() => process.exit(1)); +}); diff --git a/test/browser/test-export.ts b/test/browser/test-export.ts new file mode 100644 index 0000000..cf0a8c5 --- /dev/null +++ b/test/browser/test-export.ts @@ -0,0 +1,86 @@ +import '../env.js'; +/** + * Export to PNG, PDF and JPEG through Chrome. + * Run with: npx tsx test/browser/test-export.ts + */ + +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { resolveVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { exportToFile, shutdown } from '../../src/screenshot.js'; + +const OUT = join(tmpdir(), 'framesmith-test'); + +let passed = 0; +let failed = 0; + +function assert(condition: boolean, label: string) { + if (condition) { + console.log(` ✓ ${label}`); + passed++; + } else { + console.log(` ✗ ${label}`); + failed++; + } +} + +async function testExport() { + console.log('\n── Export to PNG/PDF ──'); + + const canvas = createCanvas('Export Test'); + parseAndExecute(canvas.root, ` +box=I("document", {type: "frame", width: 200, height: 100, fill: "#3b82f6", cornerRadius: 8}) +I(box, {type: "text", content: "Export Test", fontSize: 18, color: "#ffffff"}) + `, canvas); + + const resolved = resolveVariables(canvas.root, canvas.variables); + const html = renderToHtml(resolved, 400, 200, canvas); + + // Export PNG + const pngPath = await exportToFile(html, { + format: 'png', + outputPath: OUT, + fileName: 'test-export', + width: 400, + height: 200, + }); + assert(pngPath.endsWith('.png'), `PNG exported to ${pngPath}`); + + // Export PDF + const pdfPath = await exportToFile(html, { + format: 'pdf', + outputPath: OUT, + fileName: 'test-export', + width: 400, + height: 200, + }); + assert(pdfPath.endsWith('.pdf'), `PDF exported to ${pdfPath}`); + + // Export JPEG + const jpgPath = await exportToFile(html, { + format: 'jpeg', + outputPath: OUT, + fileName: 'test-export', + width: 400, + height: 200, + }); + assert(jpgPath.endsWith('.jpeg'), `JPEG exported to ${jpgPath}`); + + console.log(` → Files written to ${OUT}/`); +} + +async function main() { + await testExport(); + + console.log(`\nResults: ${passed} passed, ${failed} failed`); + await shutdown(); + process.exit(failed > 0 ? 1 : 0); +} + +main().catch((err) => { + console.error('Test error:', err); + shutdown().then(() => process.exit(1)); +}); diff --git a/test-fluid-widths.ts b/test/browser/test-fluid-widths.ts similarity index 94% rename from test-fluid-widths.ts rename to test/browser/test-fluid-widths.ts index 533da84..ced6d1e 100644 --- a/test-fluid-widths.ts +++ b/test/browser/test-fluid-widths.ts @@ -1,13 +1,13 @@ -import './test-env.js'; +import '../env.js'; // Smoke test for Phase 5 item #3: fluid widths via minWidth / maxWidth. // Runs the renderer + puppeteer directly so it does not depend on the long- // running MCP server (which holds dist/ in Node memory until restarted). // -// Usage: npx tsx test-fluid-widths.ts +// Usage: npx tsx test/browser/test-fluid-widths.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; const root: SceneNode = { id: 'doc', diff --git a/test/browser/test-gradients-shadows.ts b/test/browser/test-gradients-shadows.ts new file mode 100644 index 0000000..ae7e9ca --- /dev/null +++ b/test/browser/test-gradients-shadows.ts @@ -0,0 +1,96 @@ +import '../env.js'; +/** + * Gradients, shadows and blur: structured and legacy forms emit the right CSS, + * and a gradient tree renders in Chrome. + * Run with: npx tsx test/browser/test-gradients-shadows.ts + */ + +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { resolveVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { takeScreenshot, shutdown } from '../../src/screenshot.js'; + +let passed = 0; +let failed = 0; + +function assert(condition: boolean, label: string) { + if (condition) { + console.log(` ✓ ${label}`); + passed++; + } else { + console.log(` ✗ ${label}`); + failed++; + } +} + +async function testGradients() { + console.log('\n── Gradients ──'); + + const canvas = createCanvas('Gradient Test'); + const results = parseAndExecute(canvas.root, ` +linear=I("document", {type: "frame", width: 400, height: 200, gradient: {type: "linear", angle: 135, stops: [{color: "#667eea", position: 0}, {color: "#764ba2", position: 100}]}, cornerRadius: 12}) +radial=I("document", {type: "frame", width: 400, height: 200, gradient: {type: "radial", stops: [{color: "#ffffff", position: 0}, {color: "#000000", position: 100}]}, cornerRadius: 12}) +fallback=I("document", {type: "frame", width: 400, height: 200, fill: "#ff0000"}) + `, canvas); + assert(results.every(r => r.ok), 'Gradient nodes inserted'); + + const resolved = resolveVariables(canvas.root, canvas.variables); + const html = renderToHtml(resolved, 800, 800, canvas); + + assert(html.includes('linear-gradient(135deg'), 'HTML contains linear-gradient with angle'); + assert(html.includes('#667eea 0%'), 'Linear gradient has first stop'); + assert(html.includes('#764ba2 100%'), 'Linear gradient has second stop'); + assert(html.includes('radial-gradient('), 'HTML contains radial-gradient'); + assert(html.includes('background-color: #ff0000'), 'Fallback fill still works'); + + // Gradient and fill should not both appear on the same node + // The linear gradient node should use background, not background-color + assert(html.includes('background: linear-gradient'), 'Gradient uses background property'); + + const base64 = await takeScreenshot(html, { width: 800, height: 800 }); + assert(base64.length > 100, `Screenshot captured (${Math.round(base64.length / 1024)}KB)`); +} + +function testShadowsAndBlur() { + console.log('\n── Shadows & Blur ──'); + + const canvas = createCanvas('Shadow Test'); + const results = parseAndExecute(canvas.root, ` +box1=I("document", {type: "frame", width: 300, height: 150, fill: "#ffffff", shadows: [{x: 0, y: 4, blur: 12, spread: 0, color: "rgba(0,0,0,0.2)"}], cornerRadius: 8}) +box2=I("document", {type: "frame", width: 300, height: 150, fill: "#ffffff", shadows: [{x: 0, y: 2, blur: 4, color: "rgba(0,0,0,0.1)"}, {x: 0, y: 8, blur: 24, color: "rgba(0,0,0,0.15)"}], cornerRadius: 8}) +box3=I("document", {type: "frame", width: 300, height: 150, fill: "#ffffff", shadow: "0 4px 6px rgba(0,0,0,0.1)"}) +blurred=I("document", {type: "frame", width: 300, height: 150, fill: "#3b82f6", blur: 4}) +backdrop=I("document", {type: "frame", width: 300, height: 150, fill: "rgba(255,255,255,0.5)", backdropBlur: 8}) + `, canvas); + assert(results.every(r => r.ok), 'Shadow/blur nodes inserted'); + + const resolved = resolveVariables(canvas.root, canvas.variables); + const html = renderToHtml(resolved, 800, 1000, canvas); + + // Structured shadows + assert(html.includes('box-shadow: 0px 4px 12px 0px rgba(0,0,0,0.2)'), 'Single structured shadow rendered'); + assert(html.includes('0px 2px 4px 0px rgba(0,0,0,0.1)'), 'Multi-shadow first shadow'); + assert(html.includes('0px 8px 24px 0px rgba(0,0,0,0.15)'), 'Multi-shadow second shadow'); + + // Legacy shadow string + assert(html.includes('box-shadow: 0 4px 6px rgba(0,0,0,0.1)'), 'Legacy shadow string still works'); + + // Blur + assert(html.includes('filter: blur(4px)'), 'Blur filter rendered'); + assert(html.includes('backdrop-filter: blur(8px)'), 'Backdrop blur rendered'); +} + +async function main() { + await testGradients(); + testShadowsAndBlur(); + + console.log(`\nResults: ${passed} passed, ${failed} failed`); + await shutdown(); + process.exit(failed > 0 ? 1 : 0); +} + +main().catch((err) => { + console.error('Test error:', err); + shutdown().then(() => process.exit(1)); +}); diff --git a/test-grid.ts b/test/browser/test-grid.ts similarity index 91% rename from test-grid.ts rename to test/browser/test-grid.ts index 39873c1..8c62821 100644 --- a/test-grid.ts +++ b/test/browser/test-grid.ts @@ -2,17 +2,17 @@ // sanitization, responsive collapse (string + real Chrome geometry), and the // table-detector guard. The bento taste gate itself lives in test-patterns. // -// Usage: npx tsx test-grid.ts (the collapse geometry checks need Chrome) +// Usage: npx tsx test/browser/test-grid.ts (the collapse geometry checks need Chrome) -import './test-env.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { computeLayout, shutdown } from './src/screenshot.js'; -import { extractInventory } from './src/drift.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import type { SceneNode } from './src/types.js'; +import '../env.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { computeLayout, shutdown } from '../../src/screenshot.js'; +import { extractInventory } from '../../src/drift.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import type { SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-import-html.ts b/test/browser/test-import-html.ts similarity index 96% rename from test-import-html.ts rename to test/browser/test-import-html.ts index e557997..43d3d9a 100644 --- a/test-import-html.ts +++ b/test/browser/test-import-html.ts @@ -1,14 +1,14 @@ -import './test-env.js'; +import '../env.js'; // Phase 17 Slice A — canvas_import_html, Chrome side. Real render → walk → // scene graph → re-render round-trip. Inline styles only (no Tailwind runtime // in a snippet — that's spec C1; class-based CSS goes through the css param). // -// Usage: npx tsx test-import-html.ts +// Usage: npx tsx test/browser/test-import-html.ts -import { importHtml } from './src/import.js'; -import { renderToHtml } from './src/renderer.js'; -import { takeScreenshot, shutdown } from './src/screenshot.js'; -import type { SceneNode } from './src/types.js'; +import { importHtml } from '../../src/import.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { takeScreenshot, shutdown } from '../../src/screenshot.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-import-url.ts b/test/browser/test-import-url.ts similarity index 96% rename from test-import-url.ts rename to test/browser/test-import-url.ts index cb7e29f..731846a 100644 --- a/test-import-url.ts +++ b/test/browser/test-import-url.ts @@ -1,16 +1,16 @@ -import './test-env.js'; +import '../env.js'; // Phase 17 Slice C — canvas_import_url. All pages served from a local // http server spun up in-test (no external network): styled page, selector // narrowing, waitFor for JS-rendered content, auth header/cookie injection // (the server echoes them into the DOM), relative-img resolution against the // page URL, and the no-auth-persistence guarantee. // -// Usage: npx tsx test-import-url.ts +// Usage: npx tsx test/browser/test-import-url.ts import { createServer, type Server } from 'node:http'; -import { importUrl } from './src/import.js'; -import { shutdown } from './src/screenshot.js'; -import type { SceneNode } from './src/types.js'; +import { importUrl } from '../../src/import.js'; +import { shutdown } from '../../src/screenshot.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-material-icons.ts b/test/browser/test-material-icons.ts similarity index 96% rename from test-material-icons.ts rename to test/browser/test-material-icons.ts index b782dca..b84dc28 100644 --- a/test-material-icons.ts +++ b/test/browser/test-material-icons.ts @@ -1,16 +1,16 @@ -import './test-env.js'; +import '../env.js'; // Phase 16 Slice B — Material Symbols icon set alongside Lucide. // Covers: ref parsing (prefix vs back-compat), per-set rendering (stroke vs // fill recolor, sizing), style variants, -fill suffix names, unknown-name // degrade, path-traversal rejection, renderer pass-through of iconStyle, and a // computed-render check in Chrome. // -// Usage: npx tsx test-material-icons.ts +// Usage: npx tsx test/browser/test-material-icons.ts import puppeteer from 'puppeteer'; -import { getIconSvg, parseIconRef } from './src/icons.js'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { getIconSvg, parseIconRef } from '../../src/icons.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-overlays-render.ts b/test/browser/test-overlays-render.ts similarity index 98% rename from test-overlays-render.ts rename to test/browser/test-overlays-render.ts index b01faac..029130d 100644 --- a/test-overlays-render.ts +++ b/test/browser/test-overlays-render.ts @@ -8,16 +8,16 @@ // check skips them; a full-page capture keeps them; long copy stays inside // the overlays; both themes. // -// Usage: npx tsx test-overlays-render.ts +// Usage: npx tsx test/browser/test-overlays-render.ts -import './test-env.js'; -import { computeLayout, withPage, takeScreenshot, shutdown, type LayoutRect } from './src/screenshot.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { applyPerturbation, compareLayouts } from './src/stress.js'; -import { generateDesignSystem } from './src/design-language.js'; -import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; +import '../env.js'; +import { computeLayout, withPage, takeScreenshot, shutdown, type LayoutRect } from '../../src/screenshot.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { applyPerturbation, compareLayouts } from '../../src/stress.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import type { Canvas, DesignVariables, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-patterns-desktop-window.ts b/test/browser/test-patterns-desktop-window.ts similarity index 89% rename from test-patterns-desktop-window.ts rename to test/browser/test-patterns-desktop-window.ts index f39da5e..72483b9 100644 --- a/test-patterns-desktop-window.ts +++ b/test/browser/test-patterns-desktop-window.ts @@ -1,8 +1,8 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 31 slice D (FR-D3, spec G3) — the desktop-app gate at the narrower * windows the viewer offers, and the documented move of stamping a table into - * a realisation's pane. test-patterns-desktop.ts covers the 1440×900 window; + * a realisation's pane. test/browser/test-patterns-desktop.ts covers the 1440×900 window; * this covers what verify round 1 found it missed: * * 1. a full stress run is CLEAN at 1024×768 (unthemed and under each @@ -15,20 +15,20 @@ import './test-env.js'; * nothing blocking in fast mode, no desktop-app finding in detailed * mode, and a CLEAN stress run. * - * Fallback fonts, as in test-patterns-desktop.ts. Needs Chrome. - * Run with: npx tsx test-patterns-desktop-window.ts + * Fallback fonts, as in test/browser/test-patterns-desktop.ts. Needs Chrome. + * Run with: npx tsx test/browser/test-patterns-desktop-window.ts */ -import { listStructures, applyStructure } from './src/structures.js'; -import { createCanvas } from './src/scene-graph.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { getVariables, resolveVariables, setVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { expandInstances } from './src/drift.js'; -import { computeLayout, shutdown } from './src/screenshot.js'; -import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from './src/stress.js'; -import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from './src/design-language.js'; -import { getCanvasTokens } from './src/workspaces.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { listStructures, applyStructure } from '../../src/structures.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { getVariables, resolveVariables, setVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { expandInstances } from '../../src/drift.js'; +import { computeLayout, shutdown } from '../../src/screenshot.js'; +import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from '../../src/stress.js'; +import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from '../../src/design-language.js'; +import { getCanvasTokens } from '../../src/workspaces.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; const CATEGORIES = ['spacing', 'color', 'typography', 'structure', 'consistency', 'cliche', 'usability']; diff --git a/test-patterns-desktop.ts b/test/browser/test-patterns-desktop.ts similarity index 92% rename from test-patterns-desktop.ts rename to test/browser/test-patterns-desktop.ts index 9ad9da2..8ff3a59 100644 --- a/test-patterns-desktop.ts +++ b/test/browser/test-patterns-desktop.ts @@ -1,7 +1,7 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 31 slice D (FR-D3, spec G3 + G4) — the pattern gate's layout half for - * the desktop-app realisations and components. test-patterns.ts holds them to + * the desktop-app realisations and components. test/unit/test-patterns.ts holds them to * > 95, zero tells and zero blocking findings in fast mode across themes and * generated systems; this runs what fast mode cannot see: * @@ -19,25 +19,25 @@ import './test-env.js'; * 4. a stamp on a 1024×768 window raises no desktop-app finding in detailed * mode and no node reaches past the artboard's right edge (stress at the * narrower windows and tables stamped into panes live in - * test-patterns-desktop-window.ts). + * test/browser/test-patterns-desktop-window.ts). * * Components marked for every type get detailed mode (no desktop-app warning * or error, spec change S7) and a CLEAN stress run on a bare desktop-app - * canvas. Renders use fallback fonts, as test-patterns-mobile.ts does: the + * canvas. Renders use fallback fonts, as test/browser/test-patterns-mobile.ts does: the * personalities' faces would need the network to reach the font cache. - * Needs Chrome. Run with: npx tsx test-patterns-desktop.ts + * Needs Chrome. Run with: npx tsx test/browser/test-patterns-desktop.ts */ -import { listStructures, applyStructure } from './src/structures.js'; -import { createCanvas } from './src/scene-graph.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { getVariables, resolveVariables, setVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { expandInstances } from './src/drift.js'; -import { computeLayout, shutdown, type LayoutRect } from './src/screenshot.js'; -import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from './src/stress.js'; -import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from './src/design-language.js'; -import { getCanvasTokens } from './src/workspaces.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { listStructures, applyStructure } from '../../src/structures.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { getVariables, resolveVariables, setVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { expandInstances } from '../../src/drift.js'; +import { computeLayout, shutdown, type LayoutRect } from '../../src/screenshot.js'; +import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from '../../src/stress.js'; +import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from '../../src/design-language.js'; +import { getCanvasTokens } from '../../src/workspaces.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; const CATEGORIES = ['spacing', 'color', 'typography', 'structure', 'consistency', 'cliche', 'usability']; diff --git a/test-patterns-mobile.ts b/test/browser/test-patterns-mobile.ts similarity index 84% rename from test-patterns-mobile.ts rename to test/browser/test-patterns-mobile.ts index 9d8d62a..ca96374 100644 --- a/test-patterns-mobile.ts +++ b/test/browser/test-patterns-mobile.ts @@ -1,7 +1,7 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 30 slice E (FR-E4) — the pattern gate's layout half for the mobile - * realisations. test-patterns.ts holds them to > 95, zero tells and zero + * realisations. test/unit/test-patterns.ts holds them to > 95, zero tells and zero * mobile findings in fast mode across the themes; this runs what fast mode * cannot see: * @@ -14,20 +14,20 @@ import './test-env.js'; * larger display face is what pushes a heading past the artboard. * * Components marked for every type get both checks on a bare phone canvas. - * Needs Chrome. Run with: npx tsx test-patterns-mobile.ts + * Needs Chrome. Run with: npx tsx test/browser/test-patterns-mobile.ts */ -import { listStructures, applyStructure } from './src/structures.js'; -import { createCanvas } from './src/scene-graph.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { getVariables, resolveVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { expandInstances } from './src/drift.js'; -import { computeLayout, shutdown } from './src/screenshot.js'; -import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from './src/stress.js'; -import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from './src/design-language.js'; -import { setVariables } from './src/variables.js'; -import { getCanvasTokens } from './src/workspaces.js'; -import type { Canvas } from './src/types.js'; +import { listStructures, applyStructure } from '../../src/structures.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { getVariables, resolveVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { expandInstances } from '../../src/drift.js'; +import { computeLayout, shutdown } from '../../src/screenshot.js'; +import { applyPerturbation, compareLayouts, PERTURBATION_NAMES } from '../../src/stress.js'; +import { generateDesignSystem, PERSONALITY_NAMES, type PersonalityName } from '../../src/design-language.js'; +import { setVariables } from '../../src/variables.js'; +import { getCanvasTokens } from '../../src/workspaces.js'; +import type { Canvas } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-pointer-targets.ts b/test/browser/test-pointer-targets.ts similarity index 96% rename from test-pointer-targets.ts rename to test/browser/test-pointer-targets.ts index e57ebb7..c6eb27e 100644 --- a/test-pointer-targets.ts +++ b/test/browser/test-pointer-targets.ts @@ -3,12 +3,12 @@ // box and no other undersized target's circle; touching passes, nested and // disabled targets never count. Needs Chrome (detailed mode lays out). // -// Usage: npx tsx test-pointer-targets.ts +// Usage: npx tsx test/browser/test-pointer-targets.ts -import './test-env.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { shutdown } from './src/screenshot.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import '../env.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { shutdown } from '../../src/screenshot.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-positioning.ts b/test/browser/test-positioning.ts similarity index 97% rename from test-positioning.ts rename to test/browser/test-positioning.ts index c34e29c..1189f8a 100644 --- a/test-positioning.ts +++ b/test/browser/test-positioning.ts @@ -1,14 +1,14 @@ -import './test-env.js'; +import '../env.js'; // Phase 30 slice D — pinned positioning, the root render, and the primitives' // rendered sizes, measured in Chrome (FR-D1, FR-D2, FR-D4, FR-D5 acceptance). // -// Usage: npx tsx test-positioning.ts +// Usage: npx tsx test/browser/test-positioning.ts -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { computeLayout, takeScreenshot, withPage, type LayoutRect } from './src/screenshot.js'; -import { createCanvas } from './src/scene-graph.js'; -import type { DesignVariables, SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { computeLayout, takeScreenshot, withPage, type LayoutRect } from '../../src/screenshot.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import type { DesignVariables, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-primitives.ts b/test/browser/test-primitives.ts similarity index 96% rename from test-primitives.ts rename to test/browser/test-primitives.ts index 33c78fb..7c939e9 100644 --- a/test-primitives.ts +++ b/test/browser/test-primitives.ts @@ -1,17 +1,17 @@ -import './test-env.js'; +import '../env.js'; // Phase 16 Slice C — input primitives (toggle / checkbox / radio / select). // Covers: token-aware defaults vs neutral fallbacks (resolveVariables), // checked/unchecked anatomy, explicit fill/stroke/color overrides, disabled // opacity, select placeholder vs value, sizing, no fake-chrome false positive // from radio groups (checkCliche), and a Chrome paint check. // -// Usage: npx tsx test-primitives.ts +// Usage: npx tsx test/browser/test-primitives.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import type { Canvas, DesignVariables, SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import type { Canvas, DesignVariables, SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-render-capture.ts b/test/browser/test-render-capture.ts similarity index 94% rename from test-render-capture.ts rename to test/browser/test-render-capture.ts index 0cd19d0..f2e1336 100644 --- a/test-render-capture.ts +++ b/test/browser/test-render-capture.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 29 slice E (#194) — renderer and capture. * @@ -15,15 +15,15 @@ import './test-env.js'; * with no way to override, so a canvas taller than its artboard could only * be seen by editing the root height by hand. * - * Needs Chrome for the capture case. Run with: npx tsx test-render-capture.ts + * Needs Chrome for the capture case. Run with: npx tsx test/browser/test-render-capture.ts */ import { readFileSync, mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { createCanvas, getCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { renderToHtml } from './src/renderer.js'; -import { takeScreenshot, exportToFile, shutdown } from './src/screenshot.js'; +import { createCanvas, getCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { takeScreenshot, exportToFile, shutdown } from '../../src/screenshot.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-responsive-reflow.ts b/test/browser/test-responsive-reflow.ts similarity index 93% rename from test-responsive-reflow.ts rename to test/browser/test-responsive-reflow.ts index fcc5746..506d890 100644 --- a/test-responsive-reflow.ts +++ b/test/browser/test-responsive-reflow.ts @@ -1,15 +1,15 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 5 item #6: screenshot_responsive renders HTML per breakpoint // so the body scaffold (max-width / min-height) matches each viewport, not the // largest breakpoint. Asserts the runtime body box at each breakpoint matches // the requested viewport dimensions and that @media reflow still fires. // -// Usage: npx tsx test-responsive-reflow.ts +// Usage: npx tsx test/browser/test-responsive-reflow.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { Breakpoint } from './src/screenshot.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { Breakpoint } from '../../src/screenshot.js'; +import type { SceneNode } from '../../src/types.js'; const root: SceneNode = { id: 'doc', type: 'document', diff --git a/test-responsive.ts b/test/browser/test-responsive.ts similarity index 55% rename from test-responsive.ts rename to test/browser/test-responsive.ts index 2f4c708..a75e45f 100644 --- a/test-responsive.ts +++ b/test/browser/test-responsive.ts @@ -1,24 +1,62 @@ -import './test-env.js'; +import '../env.js'; /** * Responsive padding + font scaling smoke test. * Builds a design with large padding (120px) and headline (64px), * captures it at mobile/tablet/desktop, and writes the rendered HTML * so you can inspect the clamp() output. * - * Run: npx tsx test-responsive.ts - * Output: /tmp/framesmith-responsive/ + * Also checks takeResponsiveScreenshots' contract on a wrapping row: one + * labelled shot per breakpoint, at the breakpoint's width. + * + * Run: npx tsx test/browser/test-responsive.ts + * Output: framesmith-responsive/ in the OS temp dir */ import { writeFile, mkdir } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { resolveVariables, setVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { takeResponsiveScreenshots, shutdown } from './src/screenshot.js'; -import { getPreset } from './src/presets.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { resolveVariables, setVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { takeResponsiveScreenshots, shutdown } from '../../src/screenshot.js'; +import { getPreset } from '../../src/presets.js'; + +const OUT = join(tmpdir(), 'framesmith-responsive'); -const OUT = '/tmp/framesmith-responsive'; +/** takeResponsiveScreenshots returns one labelled shot per breakpoint, in order. */ +async function breakpointShots(): Promise { + const canvas = createCanvas('Responsive Test'); + parseAndExecute(canvas.root, ` +container=I("document", {type: "frame", width: "100%", height: "100%", fill: "#0a0a0a", layout: "vertical", padding: 24, gap: 16}) +I(container, {type: "text", content: "Responsive Test", fontSize: 24, color: "#ffffff"}) +row=I(container, {type: "frame", layout: "horizontal", gap: 16, wrap: true, width: "100%"}) +I(row, {type: "frame", width: 200, height: 100, fill: "#3b82f6", cornerRadius: 8}) +I(row, {type: "frame", width: 200, height: 100, fill: "#ef4444", cornerRadius: 8}) +I(row, {type: "frame", width: 200, height: 100, fill: "#22c55e", cornerRadius: 8}) + `, canvas); + + const resolved = resolveVariables(canvas.root, canvas.variables); + const breakpoints = [ + { label: 'mobile', width: 390, height: 844 }, + { label: 'tablet', width: 768, height: 1024 }, + { label: 'desktop', width: 1440, height: 900 }, + ]; + const results = await takeResponsiveScreenshots((bp) => renderToHtml(resolved, bp.width, bp.height, canvas), breakpoints); + + const checks: Array<[string, boolean]> = [ + ['Got 3 responsive screenshots', results.length === 3], + ['First is mobile', results[0]?.label === 'mobile'], + ['Mobile width is 390', results[0]?.width === 390], + ['Second is tablet', results[1]?.label === 'tablet'], + ['Third is desktop', results[2]?.label === 'desktop'], + ['All screenshots have data', results.every((r) => r.data.length > 100)], + // Fewer pixels at mobile width. + ['Mobile screenshot is smaller than desktop', results[0]?.data.length < results[2]?.data.length], + ]; + for (const [name, ok] of checks) console.log(` ${ok ? '✓' : '✗'} ${name}`); + return checks.every(([, ok]) => ok); +} async function main() { await mkdir(OUT, { recursive: true }); @@ -75,8 +113,12 @@ I(card, {type: "text", content: "Inner padding shrinks on narrow viewports.", fo } console.log(`\nOpen: open ${OUT}`); + + console.log('\nBreakpoint shots'); + const shotsOk = await breakpointShots(); + await shutdown(); - if (pass !== checks.length || shots.length !== bps.length) process.exit(1); + if (pass !== checks.length || shots.length !== bps.length || !shotsOk) process.exit(1); } main().catch((err) => { diff --git a/test-root-centering.ts b/test/browser/test-root-centering.ts similarity index 94% rename from test-root-centering.ts rename to test/browser/test-root-centering.ts index 931f334..c7bd095 100644 --- a/test-root-centering.ts +++ b/test/browser/test-root-centering.ts @@ -1,13 +1,13 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 5 item #4: root document centers horizontally and the root // fill/gradient extends to the full viewport (no dead white sidebars on wide // screens). // -// Usage: npx tsx test-root-centering.ts +// Usage: npx tsx test/browser/test-root-centering.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; const SOLID: SceneNode = { id: 'doc-solid', type: 'document', fill: '#1E293B', diff --git a/test-scaffold-system.ts b/test/browser/test-scaffold-system.ts similarity index 89% rename from test-scaffold-system.ts rename to test/browser/test-scaffold-system.ts index ab6a17e..90968eb 100644 --- a/test-scaffold-system.ts +++ b/test/browser/test-scaffold-system.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 29 slice C (#194) — every scaffold belongs to the system it is stamped * into, and survives hostile content. @@ -18,17 +18,17 @@ import './test-env.js'; * monogram into a 32px box, `empty-state`'s title overflowed). * * Needs Chrome (stress measures real layout). Run with: - * npx tsx test-scaffold-system.ts + * npx tsx test/browser/test-scaffold-system.ts */ -import { listStructures, applyStructure } from './src/structures.js'; -import { createCanvas, getCanvas } from './src/scene-graph.js'; -import { generateDesignSystem } from './src/design-language.js'; -import { setVariables, resolveVariables, getVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { expandInstances } from './src/drift.js'; -import { computeLayout, takeScreenshot, shutdown } from './src/screenshot.js'; -import { applyPerturbation, compareLayouts, PERTURBATION_NAMES, type PerturbationName } from './src/stress.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { listStructures, applyStructure } from '../../src/structures.js'; +import { createCanvas, getCanvas } from '../../src/scene-graph.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import { setVariables, resolveVariables, getVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { expandInstances } from '../../src/drift.js'; +import { computeLayout, takeScreenshot, shutdown } from '../../src/screenshot.js'; +import { applyPerturbation, compareLayouts, PERTURBATION_NAMES, type PerturbationName } from '../../src/stress.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-state-model-render.ts b/test/browser/test-state-model-render.ts similarity index 96% rename from test-state-model-render.ts rename to test/browser/test-state-model-render.ts index b4082de..544437c 100644 --- a/test-state-model-render.ts +++ b/test/browser/test-state-model-render.ts @@ -7,16 +7,16 @@ // match the rendered pixel within 2/255 per channel, unthemed and under a // generated system in both themes (and the dark preset's translucent ink). // Twin: a model whose layer opacity is 0.05 off must fail the same compare. -// Needs Chrome. Run with: npx tsx test-state-model-render.ts +// Needs Chrome. Run with: npx tsx test/browser/test-state-model-render.ts -import './test-env.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { generateDesignSystem } from './src/design-language.js'; -import { withPage, shutdown } from './src/screenshot.js'; -import { boundaryPairs, disabledPairs, focusPairs, indicatorPairs, layerAlpha, paint, stateTargets } from './src/state-checks.js'; -import type { Rgb } from './src/color-math.js'; -import type { DesignVariables, ElementState, SceneNode } from './src/types.js'; +import '../env.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import { withPage, shutdown } from '../../src/screenshot.js'; +import { boundaryPairs, disabledPairs, focusPairs, indicatorPairs, layerAlpha, paint, stateTargets } from '../../src/state-checks.js'; +import type { Rgb } from '../../src/color-math.js'; +import type { DesignVariables, ElementState, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -35,7 +35,7 @@ async function sample(html: string, points: (rects: Record) => Arr return withPage(async (page) => { await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 }); await page.setContent(html, { waitUntil: 'domcontentloaded' }); - const rects: Record = await page.evaluate(`(() => { + const rects = await page.evaluate(`(() => { const out = {}; const put = (key, el) => { const r = el.getBoundingClientRect(); out[key] = { left: r.left, top: r.top, right: r.right, bottom: r.bottom }; }; document.querySelectorAll('[data-node-id]').forEach((el) => put(el.getAttribute('data-node-id'), el)); @@ -43,7 +43,7 @@ async function sample(html: string, points: (rects: Record) => Arr document.querySelectorAll('[role=textbox]').forEach((el, i) => put('field' + i, el)); document.querySelectorAll('[data-node-id="m"] [data-focusable]').forEach((el, i) => put('m' + i, el)); return out; - })()`); + })()`) as Record; const png = Buffer.from(await page.screenshot({ type: 'png' })).toString('base64'); const pts = points(rects).map(([x, y]) => [Math.round(x), Math.round(y)]); return page.evaluate(`(async () => { diff --git a/test-stress-render.ts b/test/browser/test-stress-render.ts similarity index 95% rename from test-stress-render.ts rename to test/browser/test-stress-render.ts index 4171b02..3d1a87d 100644 --- a/test-stress-render.ts +++ b/test/browser/test-stress-render.ts @@ -1,16 +1,16 @@ // Phase 24 slice D — stress through a real render: a rigid fixture must break // under perturbation, a fluid fixture must stay clean. Chrome required. // -// Usage: npx tsx test-stress-render.ts +// Usage: npx tsx test/browser/test-stress-render.ts -import './test-env.js'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { resolveVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { computeLayout, shutdown } from './src/screenshot.js'; -import { applyPerturbation, compareLayouts, type PerturbationName } from './src/stress.js'; -import type { Canvas } from './src/types.js'; +import '../env.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { resolveVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { computeLayout, shutdown } from '../../src/screenshot.js'; +import { applyPerturbation, compareLayouts, type PerturbationName } from '../../src/stress.js'; +import type { Canvas } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-style-attr-escape.ts b/test/browser/test-style-attr-escape.ts similarity index 95% rename from test-style-attr-escape.ts rename to test/browser/test-style-attr-escape.ts index 62dfcc8..1a2e0fa 100644 --- a/test-style-attr-escape.ts +++ b/test/browser/test-style-attr-escape.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Regression smoke for the inline-style attribute escape bug found while // dogfooding the Phase 8 release page. // @@ -11,11 +11,11 @@ import './test-env.js'; // the browser still parses them back to the same CSS string but the attribute // stays well-formed. // -// Usage: npx tsx test-style-attr-escape.ts +// Usage: npx tsx test/browser/test-style-attr-escape.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-svg-paths.ts b/test/browser/test-svg-paths.ts similarity index 97% rename from test-svg-paths.ts rename to test/browser/test-svg-paths.ts index 6a26268..1cbc9f6 100644 --- a/test-svg-paths.ts +++ b/test/browser/test-svg-paths.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 8 item: SVG path primitives. // The renderer must: // - emit a for type:'path' nodes @@ -10,11 +10,11 @@ import './test-env.js'; // - reject unsafe `d` strings (invalid markup characters) and emit a comment // - leave width/height/position/cornerRadius/opacity on the wrapper // -// Usage: npx tsx test-svg-paths.ts +// Usage: npx tsx test/browser/test-svg-paths.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-sync-drift.ts b/test/browser/test-sync-drift.ts similarity index 93% rename from test-sync-drift.ts rename to test/browser/test-sync-drift.ts index 47d2631..e2fd048 100644 --- a/test-sync-drift.ts +++ b/test/browser/test-sync-drift.ts @@ -1,18 +1,18 @@ -import './test-env.js'; +import '../env.js'; // Phase 17 Slice D — sync/drift core: import a local page, adopt it as the // design-of-record, then diff fresh imports against it. In-sync ≈ 0%; a // changed page (or changed canvas) reports real drift; the sync flow never // mutates the canvas. Mirrors the canvas_sync_from_url handler's pipeline // (importUrl → renderImportedTree vs canvas render → computeDiff). // -// Usage: npx tsx test-sync-drift.ts +// Usage: npx tsx test/browser/test-sync-drift.ts import { createServer, type Server } from 'node:http'; -import { importUrl, renderImportedTree } from './src/import.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { computeDiff, shutdown } from './src/screenshot.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { importUrl, renderImportedTree } from '../../src/import.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { computeDiff, shutdown } from '../../src/screenshot.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-text-props.ts b/test/browser/test-text-props.ts similarity index 94% rename from test-text-props.ts rename to test/browser/test-text-props.ts index 454c2fc..13b9815 100644 --- a/test-text-props.ts +++ b/test/browser/test-text-props.ts @@ -1,15 +1,15 @@ -import './test-env.js'; +import '../env.js'; // Smoke for text styling props the issue-#77 dogfood session needed: // - letterSpacing → letter-spacing: px // - textTransform → text-transform: // - fontVariationSettings → font-variation-settings (quotes survive the // style-attribute escape round-trip and reach the CSSOM intact) // -// Usage: npx tsx test-text-props.ts +// Usage: npx tsx test/browser/test-text-props.ts import puppeteer from 'puppeteer'; -import { renderToHtml } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-usability.ts b/test/browser/test-usability.ts similarity index 94% rename from test-usability.ts rename to test/browser/test-usability.ts index 468ce65..17fe747 100644 --- a/test-usability.ts +++ b/test/browser/test-usability.ts @@ -3,17 +3,17 @@ // rendering. The raised archetypes must produce ZERO usability findings — // the library ships the practices it preaches. // -// Usage: npx tsx test-usability.ts - -import './test-env.js'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { applyStructure } from './src/structures.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { takeScreenshot, shutdown } from './src/screenshot.js'; -import type { Canvas } from './src/types.js'; +// Usage: npx tsx test/browser/test-usability.ts + +import '../env.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { applyStructure } from '../../src/structures.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { takeScreenshot, shutdown } from '../../src/screenshot.js'; +import type { Canvas } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-viewer-compare.ts b/test/browser/test-viewer-compare.ts similarity index 94% rename from test-viewer-compare.ts rename to test/browser/test-viewer-compare.ts index 133c960..0b3b1b8 100644 --- a/test-viewer-compare.ts +++ b/test/browser/test-viewer-compare.ts @@ -1,19 +1,20 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 5 item #7: viewer detail page exposes a side-by-side // "Compare" view with three iframes (mobile / tablet / desktop) that point at // the same per-breakpoint render route added in PR #13. Renders the detail page // directly (no HTTP / no long-running viewer process — those tend to cache // stale code) and asserts the expected markup + CSS hooks are present. // -// Usage: npx tsx test-viewer-compare.ts +// Usage: npx tsx test/browser/test-viewer-compare.ts import puppeteer from 'puppeteer'; -import { renderDetailPage } from './src/viewer.js'; -import type { Canvas } from './src/types.js'; +import { renderDetailPage } from '../../src/viewer.js'; +import type { Canvas } from '../../src/types.js'; const canvas: Canvas = { id: 'test-canvas-id', name: 'compare-smoke', + projectId: 'p', root: { id: 'doc', type: 'document', width: 1440, height: 900 }, variables: {}, components: {}, @@ -58,7 +59,7 @@ try { await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 1 }); await page.setContent(html, { waitUntil: 'domcontentloaded' }); // Block child iframe loads — we're testing the parent page's toggle logic, - // not the canvas render path (covered by test-responsive-reflow.ts). + // not the canvas render path (covered by test/browser/test-responsive-reflow.ts). await page.setRequestInterception(true); page.on('request', (req) => (req.url().includes('/canvas/test-canvas-id/html') ? req.abort() : req.continue())); diff --git a/test-viewer-surface-browser.ts b/test/browser/test-viewer-surface-browser.ts similarity index 95% rename from test-viewer-surface-browser.ts rename to test/browser/test-viewer-surface-browser.ts index 130abc6..2a7d84d 100644 --- a/test-viewer-surface-browser.ts +++ b/test/browser/test-viewer-surface-browser.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Phase 30 slice F (FR-F1, FR-F2) in Chrome: serves the real viewer and checks // what the markup test can't — each thumbnail's artboard is scaled to its // card's rendered width (and refits when the window resizes), a mobile canvas @@ -6,15 +6,15 @@ import './test-env.js'; // canvas's breakpoint buttons size the frame from the profile without // clearing the rest of the toolbar's state. // -// Usage: npx tsx test-viewer-surface-browser.ts +// Usage: npx tsx test/browser/test-viewer-surface-browser.ts import puppeteer, { type Page } from 'puppeteer'; -const sg = await import('./src/scene-graph.js'); -const ws = await import('./src/workspaces.js'); -const { parseAndExecute } = await import('./src/operations.js'); -const { startViewer } = await import('./src/viewer.js'); -const { DEFAULT_PROJECT_ID } = await import('./src/types.js'); +const sg = await import('../../src/scene-graph.js'); +const ws = await import('../../src/workspaces.js'); +const { parseAndExecute } = await import('../../src/operations.js'); +const { startViewer } = await import('../../src/viewer.js'); +const { DEFAULT_PROJECT_ID } = await import('../../src/types.js'); let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-visual.ts b/test/browser/test-visual.ts similarity index 97% rename from test-visual.ts rename to test/browser/test-visual.ts index 06e35ca..1dabb4e 100644 --- a/test-visual.ts +++ b/test/browser/test-visual.ts @@ -1,20 +1,21 @@ -import './test-env.js'; +import '../env.js'; /** * Visual smoke test — generates screenshots you can actually look at. - * Run with: npx tsx test-visual.ts + * Run with: npx tsx test/browser/test-visual.ts * Then open /tmp/framesmith-visual/ to see the results. */ -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { resolveVariables, setVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { exportToFile, takeResponsiveScreenshots, computeDiff, shutdown } from './src/screenshot.js'; -import { getPreset } from './src/presets.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { resolveVariables, setVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { exportToFile, takeResponsiveScreenshots, computeDiff, shutdown } from '../../src/screenshot.js'; +import { getPreset } from '../../src/presets.js'; import { writeFile, mkdir } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; -const OUT = '/tmp/framesmith-visual'; +const OUT = join(tmpdir(), 'framesmith-visual'); async function saveBase64Png(data: string, name: string) { await writeFile(join(OUT, name), Buffer.from(data, 'base64')); diff --git a/test-cli.ts b/test/e2e/test-cli.ts similarity index 95% rename from test-cli.ts rename to test/e2e/test-cli.ts index 9ed2706..1e889b5 100644 --- a/test-cli.ts +++ b/test/e2e/test-cli.ts @@ -4,7 +4,7 @@ // regression that must never happen — NO ARGS still boots the MCP server // (a real initialize handshake over stdio, not just "didn't crash"). // -// Usage: npx tsx test-cli.ts (check-drift cases need Chrome) +// Usage: npx tsx test/e2e/test-cli.ts (check-drift cases need Chrome) import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -16,9 +16,9 @@ const tmpHome = mkdtempSync(join(tmpdir(), 'framesmith-cli-home-')); const tmpCwd = mkdtempSync(join(tmpdir(), 'framesmith-cli-cwd-')); // outside this repo: no .framesmith binding above it process.env.FRAMESMITH_HOME = tmpHome; -const { createCanvas, touchCanvas } = await import('./src/scene-graph.js'); -const { parseAndExecute } = await import('./src/operations.js'); -const { canvasVersionHash } = await import('./src/version.js'); +const { createCanvas, touchCanvas } = await import('../../src/scene-graph.js'); +const { parseAndExecute } = await import('../../src/operations.js'); +const { canvasVersionHash } = await import('../../src/version.js'); let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-evaluate-fonts.ts b/test/e2e/test-evaluate-fonts.ts similarity index 99% rename from test-evaluate-fonts.ts rename to test/e2e/test-evaluate-fonts.ts index 91d7369..0b68978 100644 --- a/test-evaluate-fonts.ts +++ b/test/e2e/test-evaluate-fonts.ts @@ -13,7 +13,7 @@ // Also: a family that cannot load comes back as a "Font warnings" item in // detailed mode, and fast mode renders nothing, so it has none. // -// Usage: npx tsx test-evaluate-fonts.ts +// Usage: npx tsx test/e2e/test-evaluate-fonts.ts import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; diff --git a/test-genre-mcp.ts b/test/e2e/test-genre-mcp.ts similarity index 99% rename from test-genre-mcp.ts rename to test/e2e/test-genre-mcp.ts index 2818baf..73c3dfe 100644 --- a/test-genre-mcp.ts +++ b/test/e2e/test-genre-mcp.ts @@ -4,7 +4,7 @@ // MCP stdio, so a handler that stopped calling stampPreset (the AC1 clobber) // or dropped a result field fails here. // -// Usage: npx tsx test-genre-mcp.ts +// Usage: npx tsx test/e2e/test-genre-mcp.ts import { mkdtempSync, readFileSync, writeFileSync, utimesSync } from 'node:fs'; import { tmpdir } from 'node:os'; diff --git a/test-mobile-rules-detailed.ts b/test/e2e/test-mobile-rules-detailed.ts similarity index 98% rename from test-mobile-rules-detailed.ts rename to test/e2e/test-mobile-rules-detailed.ts index bd16705..8fa66ce 100644 --- a/test-mobile-rules-detailed.ts +++ b/test/e2e/test-mobile-rules-detailed.ts @@ -3,19 +3,19 @@ // the canvas_stress record carrying the canvas type through the real tool // handlers. // -// Usage: npx tsx test-mobile-rules-detailed.ts +// Usage: npx tsx test/e2e/test-mobile-rules-detailed.ts -import './test-env.js'; +import '../env.js'; import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; -import { shutdown } from './src/screenshot.js'; -import type { Canvas } from './src/types.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import { shutdown } from '../../src/screenshot.js'; +import type { Canvas } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-mobile-rules.ts b/test/e2e/test-mobile-rules.ts similarity index 98% rename from test-mobile-rules.ts rename to test/e2e/test-mobile-rules.ts index 476aa71..ba7a46e 100644 --- a/test-mobile-rules.ts +++ b/test/e2e/test-mobile-rules.ts @@ -2,24 +2,24 @@ // negative fixtures from the spec's FR-C1..C8 rows and the slice C build // contract, the stress engine's mobile behaviour, the directive's type note, // and the real tool handlers over MCP stdio. Detailed mode and canvas_stress -// need Chrome and live in test-mobile-rules-detailed.ts. +// need Chrome and live in test/e2e/test-mobile-rules-detailed.ts. // -// Usage: npx tsx test-mobile-rules.ts +// Usage: npx tsx test/e2e/test-mobile-rules.ts -import './test-env.js'; +import '../env.js'; import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; -import { buildEvaluateDirective } from './src/directive.js'; -import { applyPerturbation } from './src/stress.js'; -import { fontPx, proseWords } from './src/mobile-rules.js'; -import { renderedPaddingPx, renderToHtml } from './src/renderer.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import { buildEvaluateDirective } from '../../src/directive.js'; +import { applyPerturbation } from '../../src/stress.js'; +import { fontPx, proseWords } from '../../src/mobile-rules.js'; +import { renderedPaddingPx, renderToHtml } from '../../src/renderer.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -233,7 +233,7 @@ I(o, { type: "text", content: "Welcome back" })`); const nested = await issues(phone(`${flow} w=I("document", { type: "frame", layout: "vertical" }) I(w, { type: "text", content: "Badge", position: "absolute", x: 0, y: 0 })`), 'mobile-safe-area'); - check('absolute content inside an in-flow frame → one info naming detailed mode', nested.length === 1 && nested[0].severity === 'info' && nested[0].suggestion?.includes('detailed'), show(nested)); + check('absolute content inside an in-flow frame → one info naming detailed mode', nested.length === 1 && nested[0].severity === 'info' && nested[0].suggestion?.includes('detailed') === true, show(nested)); } // ── cost: the walks stay near-linear in nesting depth ───────────────────── diff --git a/test-ridgeline.ts b/test/e2e/test-ridgeline.ts similarity index 99% rename from test-ridgeline.ts rename to test/e2e/test-ridgeline.ts index 8da5ca2..2ede549 100644 --- a/test-ridgeline.ts +++ b/test/e2e/test-ridgeline.ts @@ -7,7 +7,7 @@ // CLEAN, every tap target a primitive, no hand-built device chrome, in fewer // than 93 nodes. The numbers it prints are the ones the slice G PR quotes. // -// Usage: npx tsx test-ridgeline.ts +// Usage: npx tsx test/e2e/test-ridgeline.ts // RIDGELINE_OUT= also writes light + dark screenshots there. import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; diff --git a/test-structures-mcp.ts b/test/e2e/test-structures-mcp.ts similarity index 99% rename from test-structures-mcp.ts rename to test/e2e/test-structures-mcp.ts index fd8fa1e..abb8900 100644 --- a/test-structures-mcp.ts +++ b/test/e2e/test-structures-mcp.ts @@ -3,7 +3,7 @@ // this drives list_structures and apply_structure over MCP stdio, so a handler // that stops reading the canvas type or drops `realisation` fails here. // -// Usage: npx tsx test-structures-mcp.ts +// Usage: npx tsx test/e2e/test-structures-mcp.ts import { mkdtempSync, readFileSync, utimesSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; diff --git a/test-surface.ts b/test/e2e/test-surface.ts similarity index 98% rename from test-surface.ts rename to test/e2e/test-surface.ts index e271bd5..4e8b218 100644 --- a/test-surface.ts +++ b/test/e2e/test-surface.ts @@ -6,25 +6,25 @@ // handlers over MCP stdio: canvas_create / canvas_set_type / canvas_evaluate / // canvas_autofix / generate_design_system results and errors. // -// Usage: npx tsx test-surface.ts +// Usage: npx tsx test/e2e/test-surface.ts -import './test-env.js'; +import '../env.js'; import { mkdtempSync, readFileSync, writeFileSync, utimesSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; -import { createCanvas, setCanvasType, setCanvasGenre, addVariant, getCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { canvasVersionHash } from './src/version.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { renderToHtml } from './src/renderer.js'; -import { evalCacheKey } from './src/viewer.js'; +import { createCanvas, setCanvasType, setCanvasGenre, addVariant, getCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { canvasVersionHash } from '../../src/version.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { evalCacheKey } from '../../src/viewer.js'; import { activeRulesets, composeRulesets, resolveSurface, surfaceFor, knownGenres, relaxedByGenre, RULESETS, DEVICE_PROFILES, DEFAULT_DEVICE, MOBILE_RULES, type Ruleset, -} from './src/surfaces.js'; -import type { Canvas } from './src/types.js'; +} from '../../src/surfaces.js'; +import type { Canvas } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-verify-inherited-tokens.ts b/test/e2e/test-verify-inherited-tokens.ts similarity index 93% rename from test-verify-inherited-tokens.ts rename to test/e2e/test-verify-inherited-tokens.ts index e3b4520..8faaad7 100644 --- a/test-verify-inherited-tokens.ts +++ b/test/e2e/test-verify-inherited-tokens.ts @@ -3,9 +3,9 @@ // canvas, so `framesmith verify` must report STALE. Before #217 the hash // covered only the canvas's own tokens and verify kept printing OK. Legacy // sha256: hashes still verify, with a warning. Spawns the real CLI entry, the -// same way test-cli.ts does, but needs no Chrome (verify never touches it). +// same way test/e2e/test-cli.ts does, but needs no Chrome (verify never touches it). // -// Usage: npx tsx test-verify-inherited-tokens.ts +// Usage: npx tsx test/e2e/test-verify-inherited-tokens.ts import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -16,11 +16,11 @@ const globalHome = mkdtempSync(join(tmpdir(), 'framesmith-verify-home-')); const repoRoot = mkdtempSync(join(tmpdir(), 'framesmith-verify-repo-')); process.env.FRAMESMITH_HOME = globalHome; -const sg = await import('./src/scene-graph.js'); -const ws = await import('./src/workspaces.js'); -const { bindRepo } = await import('./src/bind.js'); -const { parseAndExecute } = await import('./src/operations.js'); -const { canvasVersionHash, legacyCanvasVersionHash } = await import('./src/version.js'); +const sg = await import('../../src/scene-graph.js'); +const ws = await import('../../src/workspaces.js'); +const { bindRepo } = await import('../../src/bind.js'); +const { parseAndExecute } = await import('../../src/operations.js'); +const { canvasVersionHash, legacyCanvasVersionHash } = await import('../../src/version.js'); let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-viewer-rebuild.ts b/test/e2e/test-viewer-rebuild.ts similarity index 99% rename from test-viewer-rebuild.ts rename to test/e2e/test-viewer-rebuild.ts index 8c42ab1..3f0e452 100644 --- a/test-viewer-rebuild.ts +++ b/test/e2e/test-viewer-rebuild.ts @@ -10,7 +10,7 @@ // prints are the ones the slice I PR quotes. Contracts: V1 to V9 in // docs/specs/PHASE-31-SPEC.md. // -// Usage: npx tsx test-viewer-rebuild.ts +// Usage: npx tsx test/e2e/test-viewer-rebuild.ts // VIEWER_OUT= also writes screenshots, crops and JSON there. import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; @@ -18,9 +18,9 @@ import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; -import { contrastRatio, parseColor } from './src/color-math.js'; -import { resolveVariables } from './src/variables.js'; -import type { DesignVariables, SceneNode } from './src/types.js'; +import { contrastRatio, parseColor } from '../../src/color-math.js'; +import { resolveVariables } from '../../src/variables.js'; +import type { DesignVariables, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-env.ts b/test/env.ts similarity index 85% rename from test-env.ts rename to test/env.ts index 3075884..866017e 100644 --- a/test-env.ts +++ b/test/env.ts @@ -1,10 +1,10 @@ // Test isolation. Redirect framesmith persistence to a throwaway tmp dir so // running any smoke test never touches the real ~/.framesmith store. // -// Import this FIRST — before any `./src/*` import — in tests that create +// Import this FIRST — before any `src/` import — in tests that create // canvases or workspaces: // -// import './test-env.js'; +// import '../env.js'; // // ES-module side effects run in import order, so a first-position import // guarantees FRAMESMITH_HOME is set before any src module evaluates. The guard diff --git a/test-fixtures/viewer-baseline/archive.json b/test/fixtures/viewer-baseline/archive.json similarity index 100% rename from test-fixtures/viewer-baseline/archive.json rename to test/fixtures/viewer-baseline/archive.json diff --git a/test-fixtures/viewer-baseline/detail-mobile-ridgeline.json b/test/fixtures/viewer-baseline/detail-mobile-ridgeline.json similarity index 100% rename from test-fixtures/viewer-baseline/detail-mobile-ridgeline.json rename to test/fixtures/viewer-baseline/detail-mobile-ridgeline.json diff --git a/test-fixtures/viewer-baseline/detail-web-dashboard.json b/test/fixtures/viewer-baseline/detail-web-dashboard.json similarity index 100% rename from test-fixtures/viewer-baseline/detail-web-dashboard.json rename to test/fixtures/viewer-baseline/detail-web-dashboard.json diff --git a/test-fixtures/viewer-baseline/gallery-pattern-library.json b/test/fixtures/viewer-baseline/gallery-pattern-library.json similarity index 100% rename from test-fixtures/viewer-baseline/gallery-pattern-library.json rename to test/fixtures/viewer-baseline/gallery-pattern-library.json diff --git a/test-viewer-navbar.ts b/test/manual/test-viewer-navbar.ts similarity index 91% rename from test-viewer-navbar.ts rename to test/manual/test-viewer-navbar.ts index 067a361..e3f11c9 100644 --- a/test-viewer-navbar.ts +++ b/test/manual/test-viewer-navbar.ts @@ -1,16 +1,17 @@ -import './test-env.js'; +import '../env.js'; /** * Visual check: detail-page toolbar wraps on narrow viewports. * Requires the standalone viewer running (npm run viewer). - * Run: npx tsx test-viewer-navbar.ts + * Run: npx tsx test/manual/test-viewer-navbar.ts * Output: /tmp/framesmith-navbar/ */ import { writeFile, mkdir } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; import puppeteer from 'puppeteer'; const PORT = process.argv[2] ?? '3002'; -const OUT = '/tmp/framesmith-navbar'; +const OUT = join(tmpdir(), 'framesmith-navbar'); async function main() { await mkdir(OUT, { recursive: true }); diff --git a/test-viewer.ts b/test/manual/test-viewer.ts similarity index 94% rename from test-viewer.ts rename to test/manual/test-viewer.ts index e25a216..ec2471d 100644 --- a/test-viewer.ts +++ b/test/manual/test-viewer.ts @@ -1,15 +1,15 @@ -import './test-env.js'; +import '../env.js'; /** * Test the web viewer HTTP server. - * Run with: npx tsx test-viewer.ts + * Run with: npx tsx test/manual/test-viewer.ts * Then open http://localhost:3001 to see the gallery. */ -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { setVariables } from './src/variables.js'; -import { getPreset } from './src/presets.js'; -import { startViewer } from './src/viewer.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { setVariables } from '../../src/variables.js'; +import { getPreset } from '../../src/presets.js'; +import { startViewer } from '../../src/viewer.js'; let PORT: number; diff --git a/test-advisory-honesty.ts b/test/unit/test-advisory-honesty.ts similarity index 95% rename from test-advisory-honesty.ts rename to test/unit/test-advisory-honesty.ts index 60ea9de..623cb86 100644 --- a/test-advisory-honesty.ts +++ b/test/unit/test-advisory-honesty.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 29 slice D (#194) — advisory honesty. * @@ -18,15 +18,15 @@ import './test-env.js'; * 4. Readiness turns on BLOCKING findings. The old rule also demanded > 95, * which stranded the attempt at "zero issues to resolve" and NOT READY. * - * Run with: npx tsx test-advisory-honesty.ts + * Run with: npx tsx test/unit/test-advisory-honesty.ts */ -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { generateDesignSystem } from './src/design-language.js'; -import type { Canvas } from './src/types.js'; -import { buildEvaluateDirective } from './src/directive.js'; -import type { EvaluationResult } from './src/evaluate.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import type { Canvas } from '../../src/types.js'; +import { buildEvaluateDirective } from '../../src/directive.js'; +import type { EvaluationResult } from '../../src/evaluate.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-apply-structure.ts b/test/unit/test-apply-structure.ts similarity index 92% rename from test-apply-structure.ts rename to test/unit/test-apply-structure.ts index d23630d..4eca613 100644 --- a/test-apply-structure.ts +++ b/test/unit/test-apply-structure.ts @@ -1,11 +1,11 @@ // T4 end-to-end smoke test: apply_structure helper + render verification. -// Run: npx tsx test-apply-structure.ts -import './test-env.js'; // isolate persistence — MUST be first -import { createCanvas } from './src/scene-graph.js'; -import { applyStructure } from './src/structures.js'; -import { getCanvasTokens } from './src/workspaces.js'; -import { resolveVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; +// Run: npx tsx test/unit/test-apply-structure.ts +import '../env.js'; // isolate persistence — MUST be first +import { createCanvas } from '../../src/scene-graph.js'; +import { applyStructure } from '../../src/structures.js'; +import { getCanvasTokens } from '../../src/workspaces.js'; +import { resolveVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; let failures = 0; const check = (cond: boolean, msg: string) => { diff --git a/test-archive-view.ts b/test/unit/test-archive-view.ts similarity index 94% rename from test-archive-view.ts rename to test/unit/test-archive-view.ts index 6c89db3..693e26c 100644 --- a/test-archive-view.ts +++ b/test/unit/test-archive-view.ts @@ -2,9 +2,9 @@ // per-card restore/delete) and detail-page lifecycle buttons. Drives the // underlying functions directly — the API endpoints are thin wrappers over // scene-graph.archiveCanvas / unarchiveCanvas / deleteCanvas, already -// covered by test-workspace-mcp-tools.ts. +// covered by test/unit/test-workspace-mcp-tools.ts. // -// Usage: npx tsx test-archive-view.ts +// Usage: npx tsx test/unit/test-archive-view.ts import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -13,10 +13,10 @@ import { join } from 'node:path'; const tmp = mkdtempSync(join(tmpdir(), 'framesmith-test-')); process.env.FRAMESMITH_HOME = tmp; -const ws = await import('./src/workspaces.js'); -const sg = await import('./src/scene-graph.js'); -const viewer = await import('./src/viewer.js'); -const { DEFAULT_PROJECT_ID } = await import('./src/types.js'); +const ws = await import('../../src/workspaces.js'); +const sg = await import('../../src/scene-graph.js'); +const viewer = await import('../../src/viewer.js'); +const { DEFAULT_PROJECT_ID } = await import('../../src/types.js'); ws.loadPersistedWorkspaces(); ws.ensureDefaultWorkspaceAndProject(); diff --git a/test-autofix.ts b/test/unit/test-autofix.ts similarity index 94% rename from test-autofix.ts rename to test/unit/test-autofix.ts index 820c5b5..0f2d0aa 100644 --- a/test-autofix.ts +++ b/test/unit/test-autofix.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Smoke for Phase 6c canvas_autofix. Asserts: // 1. Spacing off-scale values emit a fix op snapping to the nearest scale value. // 2. Padding given as an array emits ONE combined issue per node whose fix @@ -8,17 +8,18 @@ import './test-env.js'; // 5. End-to-end loop: bad-contrast canvas → evaluate → apply autofix ops via // parseAndExecute → re-evaluate → color category recovers (issueCount: 0). // -// Usage: npx tsx test-autofix.ts +// Usage: npx tsx test/unit/test-autofix.ts -import { evaluateCanvas } from './src/evaluate.js'; -import { parseAndExecute } from './src/operations.js'; -import type { Canvas, SceneNode } from './src/types.js'; -import { badContrastRoot } from './benchmark/corpus/bad-contrast.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { parseAndExecute } from '../../src/operations.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; +import { badContrastRoot } from '../../benchmark/corpus/bad-contrast.js'; function fakeCanvas(root: SceneNode): Canvas { return { id: 'test-canvas', name: 'autofix-smoke', + projectId: 'p', root, variables: {}, components: {}, diff --git a/test-batch-design-idmap.ts b/test/unit/test-batch-design-idmap.ts similarity index 94% rename from test-batch-design-idmap.ts rename to test/unit/test-batch-design-idmap.ts index d1b1b32..7f7f749 100644 --- a/test-batch-design-idmap.ts +++ b/test/unit/test-batch-design-idmap.ts @@ -3,11 +3,11 @@ // agent can target the right nodes in follow-up ops instead of counting result // positions (the issue's "mis-mapped once and edited the wrong nodes"). // -// Usage: npx tsx test-batch-design-idmap.ts +// Usage: npx tsx test/unit/test-batch-design-idmap.ts -import './test-env.js'; -import { createCanvas, findNode } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; +import '../env.js'; +import { createCanvas, findNode } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-borders-dasharray.ts b/test/unit/test-borders-dasharray.ts similarity index 93% rename from test-borders-dasharray.ts rename to test/unit/test-borders-dasharray.ts index 4d57e31..46e6d9b 100644 --- a/test-borders-dasharray.ts +++ b/test/unit/test-borders-dasharray.ts @@ -1,13 +1,13 @@ -import './test-env.js'; +import '../env.js'; // Phase 22 slice A — per-side borders (#131) + dash control (#132). // String-level assertions on renderToHtml output — no Chrome needed. // -// Usage: npx tsx test-borders-dasharray.ts +// Usage: npx tsx test/unit/test-borders-dasharray.ts -import { createCanvas, insertNode } from './src/scene-graph.js'; -import { resolveVariables } from './src/variables.js'; -import { renderToHtml, dasharrayValue } from './src/renderer.js'; -import type { SceneNode } from './src/types.js'; +import { createCanvas, insertNode } from '../../src/scene-graph.js'; +import { resolveVariables } from '../../src/variables.js'; +import { renderToHtml, dasharrayValue } from '../../src/renderer.js'; +import type { SceneNode } from '../../src/types.js'; let passed = 0; let failed = 0; diff --git a/test-build-log.ts b/test/unit/test-build-log.ts similarity index 95% rename from test-build-log.ts rename to test/unit/test-build-log.ts index ff61f18..d0ada2a 100644 --- a/test-build-log.ts +++ b/test/unit/test-build-log.ts @@ -9,7 +9,7 @@ // (and appends a minimal entry on a hand-built canvas); files serialize // deterministically (stableStringify — sorted keys + trailing newline). // -// Usage: npx tsx test-build-log.ts +// Usage: npx tsx test/unit/test-build-log.ts import { mkdtempSync, existsSync, readFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -20,12 +20,12 @@ const repoRoot = mkdtempSync(join(tmpdir(), 'framesmith-repo-')); process.env.FRAMESMITH_HOME = globalHome; // Import AFTER setting the env var so first reads see it. -const { createCanvas, getCanvas, touchCanvas, loadPersistedCanvases } = await import('./src/scene-graph.js'); -const { loadPersistedWorkspaces, ensureDefaultWorkspaceAndProject, createWorkspace, createProject, listProjects, getCanvasTokens, loadRepoWorkspace } = await import('./src/workspaces.js'); -const { applyStructure } = await import('./src/structures.js'); -const { stampPreset } = await import('./src/genre.js'); -const { bindRepo } = await import('./src/bind.js'); -const { appendBuildLog, readBuildLog, recordPresetInBuildLog, detectBinding, readWorkspaceFile, setRepoBackend, resetRepoState, stableStringify } = await import('./src/repo-store.js'); +const { createCanvas, getCanvas, touchCanvas, loadPersistedCanvases } = await import('../../src/scene-graph.js'); +const { loadPersistedWorkspaces, ensureDefaultWorkspaceAndProject, createWorkspace, createProject, listProjects, getCanvasTokens, loadRepoWorkspace } = await import('../../src/workspaces.js'); +const { applyStructure } = await import('../../src/structures.js'); +const { stampPreset } = await import('../../src/genre.js'); +const { bindRepo } = await import('../../src/bind.js'); +const { appendBuildLog, readBuildLog, recordPresetInBuildLog, detectBinding, readWorkspaceFile, setRepoBackend, resetRepoState, stableStringify } = await import('../../src/repo-store.js'); let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-calibration.ts b/test/unit/test-calibration.ts similarity index 93% rename from test-calibration.ts rename to test/unit/test-calibration.ts index 1ca05ff..5566682 100644 --- a/test-calibration.ts +++ b/test/unit/test-calibration.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Phase 22 slice C (#135) — evaluator calibration for data-dense screens: // 1. genre "dashboard" (alias "data") relaxes the honest-content tell — // explicitly and via provenance; default behavior unchanged. @@ -8,10 +8,10 @@ import './test-env.js'; // 4. End-to-end: the #135 shape (money figures + a dense app scale) reaches // zero honest-content flags and zero ratio warnings once calibrated. // -// Usage: npx tsx test-calibration.ts +// Usage: npx tsx test/unit/test-calibration.ts -import { evaluateCanvas } from './src/evaluate.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; function fakeCanvas(root: SceneNode, extras: Partial = {}): Canvas { return { @@ -29,8 +29,8 @@ function check(name: string, ok: boolean, detail?: string): void { else { failed++; console.log(`FAIL ${name}${detail ? ` — ${detail}` : ''}`); } } -const honestFlags = (issues: { tell?: string }[]) => issues.filter((i) => i.tell === 'honest-content'); -const ratioFlags = (issues: { message: string }[]) => issues.filter((i) => i.message.includes('have ratio')); +const honestFlags = (issues: EvaluationIssue[]) => issues.filter((i) => i.tell === 'honest-content'); +const ratioFlags = (issues: EvaluationIssue[]) => issues.filter((i) => i.message.includes('have ratio')); // The #135 shape: a results-and-pace screen — money figures, percentages, and // a deliberately dense 14/13/12/11 type scale matching an existing app. diff --git a/test-chart.ts b/test/unit/test-chart.ts similarity index 96% rename from test-chart.ts rename to test/unit/test-chart.ts index 2781b46..cb32f95 100644 --- a/test-chart.ts +++ b/test/unit/test-chart.ts @@ -1,16 +1,16 @@ -import './test-env.js'; +import '../env.js'; // Phase 22 slice F (#129) — the data-driven chart node. // Pure geometry via chartGeometry + SVG string assertions on renderToHtml; // ops-parser round-trip for the nested series shape. No Chrome needed. // -// Usage: npx tsx test-chart.ts - -import { createCanvas, insertNode } from './src/scene-graph.js'; -import { resolveVariables } from './src/variables.js'; -import { renderToHtml, chartGeometry } from './src/renderer.js'; -import { parseAndExecute } from './src/operations.js'; -import { applyStructure } from './src/structures.js'; -import type { SceneNode } from './src/types.js'; +// Usage: npx tsx test/unit/test-chart.ts + +import { createCanvas, insertNode } from '../../src/scene-graph.js'; +import { resolveVariables } from '../../src/variables.js'; +import { renderToHtml, chartGeometry } from '../../src/renderer.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { applyStructure } from '../../src/structures.js'; +import type { SceneNode } from '../../src/types.js'; let passed = 0; let failed = 0; diff --git a/test-charts.ts b/test/unit/test-charts.ts similarity index 95% rename from test-charts.ts rename to test/unit/test-charts.ts index 5c26e0b..515dbd4 100644 --- a/test-charts.ts +++ b/test/unit/test-charts.ts @@ -2,12 +2,12 @@ // center slots), bar emphasis + in-SVG gradients, sparkline. Pure SVG-string // assertions (no Chrome); the slice-D proof re-run covers pixels. // -// Usage: npx tsx test-charts.ts +// Usage: npx tsx test/unit/test-charts.ts -import './test-env.js'; -import { renderToHtml, chartGeometry } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import type { SceneNode } from './src/types.js'; +import '../env.js'; +import { renderToHtml, chartGeometry } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import type { SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-cliche.ts b/test/unit/test-cliche.ts similarity index 98% rename from test-cliche.ts rename to test/unit/test-cliche.ts index 312759a..a75bf67 100644 --- a/test-cliche.ts +++ b/test/unit/test-cliche.ts @@ -1,15 +1,15 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 12 — cliché & craft guardrails. Exercises the `cliche` evaluation * category: one fixture per tell, genre-relax, honest-content guard, the * mechanical autofix surfacing, and a clean design that flags nothing. - * Run with: npx tsx test-cliche.ts + * Run with: npx tsx test/unit/test-cliche.ts */ -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { evaluateCanvas, rgbToHsl, parseAlpha } from './src/evaluate.js'; -import type { Canvas } from './src/types.js'; -import { shutdown } from './src/screenshot.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { evaluateCanvas, rgbToHsl, parseAlpha, type EvaluationIssue } from '../../src/evaluate.js'; +import type { Canvas } from '../../src/types.js'; +import { shutdown } from '../../src/screenshot.js'; let passed = 0; let failed = 0; @@ -26,7 +26,7 @@ function build(name: string, ops: string): Canvas { async function cliche(canvas: Canvas, genre?: string) { return (await evaluateCanvas(canvas, { mode: 'fast', categories: ['cliche'], genre })).issues; } -const tells = (issues: { tell?: string }[], t: string) => issues.filter((i) => i.tell === t); +const tells = (issues: EvaluationIssue[], t: string) => issues.filter((i) => i.tell === t); // --- T0: color utils --- async function testColorUtils() { @@ -45,7 +45,7 @@ async function testColorUtils() { // --- Phase 28 slice C: the evaluator knows dashboard language --- async function testMicroPatternScaffolds() { console.log('\n── Phase 28: micro-pattern scaffolds ──'); - const { applyStructure } = await import('./src/structures.js'); + const { applyStructure } = await import('../../src/structures.js'); for (const name of ['kpi-card', 'status-chip', 'segmented-control', 'breadcrumb', 'initials-avatar']) { const c = createCanvas(`mp-${name}`); applyStructure(c, name, { targetId: 'document' }); diff --git a/test-color-system.ts b/test/unit/test-color-system.ts similarity index 98% rename from test-color-system.ts rename to test/unit/test-color-system.ts index 33bb1a2..4c07ee8 100644 --- a/test-color-system.ts +++ b/test/unit/test-color-system.ts @@ -3,11 +3,11 @@ // neutral, status lightness consistency, and the AA-by-construction semantic // mapping in BOTH themes. // -// Usage: npx tsx test-color-system.ts +// Usage: npx tsx test/unit/test-color-system.ts -import './test-env.js'; -import { hexToOklch, oklchToHex, generateRamp, matchedNeutral, statusColors, semanticMapping, generateColorSystem, categoricalPalette, tintLayer, RAMP_STEPS } from './src/color-system.js'; -import { contrastRatio, parseColor } from './src/evaluate.js'; +import '../env.js'; +import { hexToOklch, oklchToHex, generateRamp, matchedNeutral, statusColors, semanticMapping, generateColorSystem, categoricalPalette, tintLayer, RAMP_STEPS } from '../../src/color-system.js'; +import { contrastRatio, parseColor } from '../../src/evaluate.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-component-structures.ts b/test/unit/test-component-structures.ts similarity index 96% rename from test-component-structures.ts rename to test/unit/test-component-structures.ts index 2051671..8776910 100644 --- a/test-component-structures.ts +++ b/test/unit/test-component-structures.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Phase 16 Slice D — component-level structures. // Covers: list kinds, page-scaffold behavior unchanged (guard/provenance/ // page-bg/axes), component stamping under a target, ID re-keying + idMap, @@ -6,12 +6,12 @@ import './test-env.js'; // component stamps (spec C9), color seeding without the page background, and // a full render of the data-table (primitives + icons + tokens together). // -// Usage: npx tsx test-component-structures.ts +// Usage: npx tsx test/unit/test-component-structures.ts -import { applyStructure, listStructures } from './src/structures.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { applyStructure, listStructures } from '../../src/structures.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-components.ts b/test/unit/test-components.ts similarity index 94% rename from test-components.ts rename to test/unit/test-components.ts index 0f733db..992e748 100644 --- a/test-components.ts +++ b/test/unit/test-components.ts @@ -1,13 +1,13 @@ -import './test-env.js'; +import '../env.js'; // Phase 22 slice E (#130) — promoteToComponent + copyNodesAcross. // Render-equivalence via renderToHtml string comparison — no Chrome needed. // -// Usage: npx tsx test-components.ts +// Usage: npx tsx test/unit/test-components.ts -import { createCanvas, insertNode, findNode } from './src/scene-graph.js'; -import { promoteToComponent, copyNodesAcross } from './src/components.js'; -import { renderToHtml } from './src/renderer.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { createCanvas, insertNode, findNode } from '../../src/scene-graph.js'; +import { promoteToComponent, copyNodesAcross } from '../../src/components.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let passed = 0; let failed = 0; diff --git a/test-contrast-alpha.ts b/test/unit/test-contrast-alpha.ts similarity index 95% rename from test-contrast-alpha.ts rename to test/unit/test-contrast-alpha.ts index 1c6efc1..7b52bf8 100644 --- a/test-contrast-alpha.ts +++ b/test/unit/test-contrast-alpha.ts @@ -5,11 +5,11 @@ // of rgba(245,158,11,0.08) on a near-black panel was judged as solid amber // (1.72:1, a false error; the real pair is 13.45:1). // -// Usage: npx tsx test-contrast-alpha.ts +// Usage: npx tsx test/unit/test-contrast-alpha.ts -import './test-env.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import '../env.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-correctness-fixes.ts b/test/unit/test-contrast-rounding-preset-inherit.ts similarity index 91% rename from test-correctness-fixes.ts rename to test/unit/test-contrast-rounding-preset-inherit.ts index ef17e74..99493b0 100644 --- a/test-correctness-fixes.ts +++ b/test/unit/test-contrast-rounding-preset-inherit.ts @@ -1,4 +1,4 @@ -// Correctness fixes for issue #64 (PR 4a): +// Contrast rounding and inherited tokens under apply_preset (issue #64): // 1. canvas_evaluate flagged a contrast ratio that rounds to exactly the WCAG // threshold (a true 4.49…:1 shown as "4.5:1"). Now the ratio is rounded to // 2 decimals before comparison + display, so a value that rounds to 4.50 @@ -7,12 +7,12 @@ // workspace/project design system. Now those are preserved + reported; // new tokens and canvas-own tokens still apply. // -// Usage: npx tsx test-correctness-fixes.ts +// Usage: npx tsx test/unit/test-contrast-rounding-preset-inherit.ts -import './test-env.js'; -import { contrastRatio, parseColor, evaluateCanvas } from './src/evaluate.js'; -import { applyPresetTokens, mergeDesignTokens } from './src/variables.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import '../env.js'; +import { contrastRatio, parseColor, evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import { applyPresetTokens, mergeDesignTokens } from '../../src/variables.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -29,7 +29,7 @@ function textOnBg(textColor: string, bg: string): Canvas { } // Only WCAG failures (error severity) count here — Phase 25's APCA advisory // legitimately adds INFO issues on WCAG-passing boundary pairs. -const colorIssue = (r: { issues: Array<{ category: string; nodeId?: string; severity?: string }> }) => r.issues.find((i) => i.category === 'color' && i.nodeId === 't1' && i.severity === 'error'); +const colorIssue = (r: { issues: EvaluationIssue[] }) => r.issues.find((i) => i.category === 'color' && i.nodeId === 't1' && i.severity === 'error'); // ── 1. Contrast rounding ────────────────────────────────────────────────────── // Find a near-gray-on-white pair whose TRUE ratio sits just under 4.5 but rounds diff --git a/test-coverage.ts b/test/unit/test-coverage.ts similarity index 96% rename from test-coverage.ts rename to test/unit/test-coverage.ts index 1264013..2b29a0a 100644 --- a/test-coverage.ts +++ b/test/unit/test-coverage.ts @@ -3,13 +3,13 @@ // empty + loading; forms (3+ controls) → error. Variant canvases and // non-data screens are silent. Detection reuses the drift inventory. // -// Usage: npx tsx test-coverage.ts +// Usage: npx tsx test/unit/test-coverage.ts -import './test-env.js'; -import { createCanvas, addVariant } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { listCanvases } from './src/scene-graph.js'; +import '../env.js'; +import { createCanvas, addVariant } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { listCanvases } from '../../src/scene-graph.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -133,7 +133,7 @@ I(f, { type: "checkbox" }) // ── Phase 27 FR-B4: half-skeletoned loading variants ──────────────────────── { - const { addVariant } = await import('./src/scene-graph.js'); + const { addVariant } = await import('../../src/scene-graph.js'); const base = createCanvas('Dash'); parseAndExecute(base.root, ` main=I("document", { type: "frame", name: "Main", layout: "vertical", gap: 16 }) diff --git a/test-critique.ts b/test/unit/test-critique.ts similarity index 93% rename from test-critique.ts rename to test/unit/test-critique.ts index 7801647..2b9d37f 100644 --- a/test-critique.ts +++ b/test/unit/test-critique.ts @@ -1,15 +1,15 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 13 — structured critique closed loop. Drives runReviseLoop with STUBBED * judge + reviser (no network, no Chrome) on a real persisted canvas, asserting * the stop reasons, the no-improvement revert, verdict stamping + build log, and - * the apply-error guard. Run with: npx tsx test-critique.ts + * the apply-error guard. Run with: npx tsx test/unit/test-critique.ts */ -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { runReviseLoop, type ReviseLoopDeps } from './src/critique.js'; -import { withVerdict, RUBRIC_AXES, type LLMJudgeResult, type Rubric } from './src/llm-judge.js'; -import { readBuildLog } from './src/repo-store.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { runReviseLoop, type ReviseLoopDeps } from '../../src/critique.js'; +import { withVerdict, RUBRIC_AXES, type LLMJudgeResult, type Rubric } from '../../src/llm-judge.js'; +import { readBuildLog } from '../../src/repo-store.js'; let passed = 0, failed = 0; function assert(cond: boolean, label: string) { diff --git a/test-design-language.ts b/test/unit/test-design-language.ts similarity index 95% rename from test-design-language.ts rename to test/unit/test-design-language.ts index a25e310..b92eadf 100644 --- a/test-design-language.ts +++ b/test/unit/test-design-language.ts @@ -4,15 +4,15 @@ // distinct from the others. No Chrome, no network (fast mode; fonts are // checked as token values, not resolved binaries). // -// Usage: npx tsx test-design-language.ts +// Usage: npx tsx test/unit/test-design-language.ts -import './test-env.js'; -import { generateDesignSystem, typeBase, PERSONALITY_NAMES, type PersonalityName } from './src/design-language.js'; -import { createCanvas } from './src/scene-graph.js'; -import { applyStructure } from './src/structures.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import { resolveVariables, setVariables } from './src/variables.js'; -import type { SceneNode } from './src/types.js'; +import '../env.js'; +import { generateDesignSystem, typeBase, PERSONALITY_NAMES, type PersonalityName } from '../../src/design-language.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { applyStructure } from '../../src/structures.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { resolveVariables, setVariables } from '../../src/variables.js'; +import type { SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-design-md-tolerant.ts b/test/unit/test-design-md-tolerant.ts similarity index 97% rename from test-design-md-tolerant.ts rename to test/unit/test-design-md-tolerant.ts index 87185b2..9e866c9 100644 --- a/test-design-md-tolerant.ts +++ b/test/unit/test-design-md-tolerant.ts @@ -3,9 +3,9 @@ // radius for a `- name: value` list or a markdown table — and injected a default // spacing scale that ignored the doc's own values. These check the new formats. // -// Usage: npx tsx test-design-md-tolerant.ts +// Usage: npx tsx test/unit/test-design-md-tolerant.ts -import { parseDesignMd } from './src/design-md-parser.js'; +import { parseDesignMd } from '../../src/design-md-parser.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-design-md.ts b/test/unit/test-design-md.ts similarity index 93% rename from test-design-md.ts rename to test/unit/test-design-md.ts index d55c437..f3b7782 100644 --- a/test-design-md.ts +++ b/test/unit/test-design-md.ts @@ -1,11 +1,11 @@ -import './test-env.js'; +import '../env.js'; /** * DESIGN.md parser smoke test — colors-map filter + component extraction. - * Run: npx tsx test-design-md.ts + * Run: npx tsx test/unit/test-design-md.ts */ -import { parseDesignMd } from './src/design-md-parser.js'; -import { renderToHtml } from './src/renderer.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { parseDesignMd } from '../../src/design-md-parser.js'; +import { renderToHtml } from '../../src/renderer.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let passed = 0; let failed = 0; @@ -93,7 +93,7 @@ const root: SceneNode = { ], }; const canvas: Canvas = { - id: 'c', name: 'c', root, variables: {}, + id: 'c', name: 'c', projectId: 'p', root, variables: {}, components: { button: button!, card: card!, badge: badge! }, createdAt: '', lastModified: '', }; diff --git a/test-design-system-elevation.ts b/test/unit/test-design-system-elevation.ts similarity index 91% rename from test-design-system-elevation.ts rename to test/unit/test-design-system-elevation.ts index c55c91e..3be9d92 100644 --- a/test-design-system-elevation.ts +++ b/test/unit/test-design-system-elevation.ts @@ -6,15 +6,15 @@ // workspace or project scope lost every $elevation.* token, and screens // inheriting from that layer rendered their shadows as unresolved refs. // -// Usage: npx tsx test-design-system-elevation.ts +// Usage: npx tsx test/unit/test-design-system-elevation.ts -import './test-env.js'; -import { createCanvas } from './src/scene-graph.js'; -import { parseAndExecute } from './src/operations.js'; -import { createWorkspace, createProject, ensureDefaultWorkspaceAndProject, setWorkspaceDesignSystem, setProjectDesignSystem, getCanvasTokens } from './src/workspaces.js'; -import { generateDesignSystem } from './src/design-language.js'; -import { resolveVariables } from './src/variables.js'; -import type { SceneNode } from './src/types.js'; +import '../env.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { parseAndExecute } from '../../src/operations.js'; +import { createWorkspace, createProject, ensureDefaultWorkspaceAndProject, setWorkspaceDesignSystem, setProjectDesignSystem, getCanvasTokens } from '../../src/workspaces.js'; +import { generateDesignSystem } from '../../src/design-language.js'; +import { resolveVariables } from '../../src/variables.js'; +import type { SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-design-system-inheritance.ts b/test/unit/test-design-system-inheritance.ts similarity index 94% rename from test-design-system-inheritance.ts rename to test/unit/test-design-system-inheritance.ts index faf973f..ddf61bf 100644 --- a/test-design-system-inheritance.ts +++ b/test/unit/test-design-system-inheritance.ts @@ -11,7 +11,7 @@ // - mergeDesignTokens semantics (per-category union, rightmost wins keys) // // Usage: -// FRAMESMITH_HOME=/tmp/framesmith-test-$$ npx tsx test-design-system-inheritance.ts +// FRAMESMITH_HOME=/tmp/framesmith-test-$$ npx tsx test/unit/test-design-system-inheritance.ts // (the script sets FRAMESMITH_HOME itself so it's safe to run directly) import { mkdtempSync, rmSync } from 'node:fs'; @@ -32,9 +32,9 @@ const { getProjectDesignSystem, getWorkspace, getProject, -} = await import('./src/workspaces.js'); -const { mergeDesignTokens, resolveVariables } = await import('./src/variables.js'); -const { createCanvas, getCanvas } = await import('./src/scene-graph.js'); +} = await import('../../src/workspaces.js'); +const { mergeDesignTokens, resolveVariables } = await import('../../src/variables.js'); +const { createCanvas, getCanvas } = await import('../../src/scene-graph.js'); interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; diff --git a/test-desktop-app-overlay.ts b/test/unit/test-desktop-app-overlay.ts similarity index 98% rename from test-desktop-app-overlay.ts rename to test/unit/test-desktop-app-overlay.ts index 3e24c10..a3684c0 100644 --- a/test-desktop-app-overlay.ts +++ b/test/unit/test-desktop-app-overlay.ts @@ -2,17 +2,17 @@ // mode. Every finding has a twin, as close as possible, that must stay silent; // the rule is shown silent on web and mobile. The detailed-mode clauses // (rendered boxes, rendered modal widths, sideways scrolling) live in -// test-desktop-app-overlay-detailed.ts. +// test/browser/test-desktop-app-overlay-detailed.ts. // -// Usage: npx tsx test-desktop-app-overlay.ts +// Usage: npx tsx test/unit/test-desktop-app-overlay.ts -import './test-env.js'; -import { evaluateCanvas, type EvaluationIssue } from './src/evaluate.js'; -import { checkOverlays } from './src/desktop-app-rules.js'; -import { WINDOW_PROFILES } from './src/surfaces.js'; -import { createCanvas } from './src/scene-graph.js'; -import { applyStructure } from './src/structures.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import '../env.js'; +import { evaluateCanvas, type EvaluationIssue } from '../../src/evaluate.js'; +import { checkOverlays } from '../../src/desktop-app-rules.js'; +import { WINDOW_PROFILES } from '../../src/surfaces.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { applyStructure } from '../../src/structures.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -437,7 +437,7 @@ async function standIn(overlay: (c: Canvas) => SceneNode[]): Promise<{ overlay: id: 'comment', name: 'Comment', type: 'popover', anchor: 'comment-btn', x: 1000, y: 160, size: 'sm', gap: 8, children: [ { id: 'comment-input', name: 'Comment', type: 'text-input', label: 'Comment', placeholder: 'Add a comment' } as SceneNode, - frame('comment-actions', [btn('Cancel', { variant: 'ghost' }), btn('Post', { variant: 'primary' })], { layout: 'horizontal', gap: 8, justifyContent: 'flex-end' }), + frame('comment-actions', [btn('Cancel', { variant: 'ghost' }), btn('Post', { variant: 'primary' })], { layout: 'horizontal', gap: 8, justifyContent: 'end' }), ], } as SceneNode, ]); diff --git a/test-desktop-app-rules.ts b/test/unit/test-desktop-app-rules.ts similarity index 98% rename from test-desktop-app-rules.ts rename to test/unit/test-desktop-app-rules.ts index 6058946..d8162d8 100644 --- a/test-desktop-app-rules.ts +++ b/test/unit/test-desktop-app-rules.ts @@ -2,18 +2,18 @@ // form coverage counting text-inputs (FR-C10). Every asserted pass has a twin // that must fail, and every rule is shown silent on web. The detailed-mode // clauses (the circle test on links, rendered row heights, column edges, -// short truncations, crowded tablists) live in test-desktop-app-rules-detailed.ts. +// short truncations, crowded tablists) live in test/browser/test-desktop-app-rules-detailed.ts. // -// Usage: npx tsx test-desktop-app-rules.ts +// Usage: npx tsx test/unit/test-desktop-app-rules.ts -import './test-env.js'; +import '../env.js'; import { readFileSync } from 'node:fs'; -import { evaluateCanvas, foldIssues, type EvaluationIssue } from './src/evaluate.js'; -import { linkGlyphWidth } from './src/primitives.js'; -import { renderToHtml } from './src/renderer.js'; -import { DESKTOP_APP_RULES } from './src/surfaces.js'; -import { extractInventory } from './src/drift.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { evaluateCanvas, foldIssues, type EvaluationIssue } from '../../src/evaluate.js'; +import { linkGlyphWidth } from '../../src/primitives.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { DESKTOP_APP_RULES } from '../../src/surfaces.js'; +import { extractInventory } from '../../src/drift.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -87,7 +87,7 @@ const nav = (id: string, extra: Partial = {}): SceneNode => ({ id, na f = await findings('desktop-app-handbuilt-target', [textButton({ stroke: '#D1D5DB', padding: [10, 14] })]); check('S2: a bordered text button 36px tall is silent', f.length === 0, show(f)); - const fixture = JSON.parse(readFileSync('test-fixtures/viewer-baseline/detail-web-dashboard.json', 'utf8')) as Canvas; + const fixture = JSON.parse(readFileSync('test/fixtures/viewer-baseline/detail-web-dashboard.json', 'utf8')) as Canvas; fixture.metadata = { ...(fixture.metadata ?? {}), surface: { type: 'desktop-app', device: 'window-1440' } }; const r = await evaluateCanvas(fixture, { mode: 'fast', categories: ['usability'] }); const named = r.issues.filter((i) => i.rule === 'desktop-app-handbuilt-target'); diff --git a/test-desktop-app.ts b/test/unit/test-desktop-app.ts similarity index 95% rename from test-desktop-app.ts rename to test/unit/test-desktop-app.ts index dea479c..3b2f764 100644 --- a/test-desktop-app.ts +++ b/test/unit/test-desktop-app.ts @@ -2,25 +2,25 @@ // web/desktop-app 24px census (fast mode), navigation lists that are not // tables, folded results, the import report summary, type-aware generation // with state + control tokens, the baseline fixtures, and the viewer's window -// breakpoints. The detailed-mode circle test lives in test-pointer-targets.ts +// breakpoints. The detailed-mode circle test lives in test/browser/test-pointer-targets.ts // (it needs Chrome). // -// Usage: npx tsx test-desktop-app.ts +// Usage: npx tsx test/unit/test-desktop-app.ts -import './test-env.js'; +import '../env.js'; import { readFileSync, readdirSync } from 'node:fs'; import { createHash } from 'node:crypto'; -import { createCanvas } from './src/scene-graph.js'; -import { surfaceFor, resolveSurface, RULESETS, DESKTOP_APP_RULES } from './src/surfaces.js'; -import { evaluateCanvas, foldIssues, contrastRatio, parseColor, type EvaluationIssue } from './src/evaluate.js'; -import { extractInventory } from './src/drift.js'; -import { summarizeImportReport, type ImportReport } from './src/import.js'; -import { generateDesignSystem, typeBase, STATE_LAYERS, PERSONALITY_NAMES } from './src/design-language.js'; -import { mergeDesignTokens, setVariables } from './src/variables.js'; -import { renderToHtml } from './src/renderer.js'; -import { renderDetailPage } from './src/viewer.js'; -import { resolveStructure } from './src/structures.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { surfaceFor, resolveSurface, RULESETS, DESKTOP_APP_RULES } from '../../src/surfaces.js'; +import { evaluateCanvas, foldIssues, contrastRatio, parseColor, type EvaluationIssue } from '../../src/evaluate.js'; +import { extractInventory } from '../../src/drift.js'; +import { summarizeImportReport, type ImportReport } from '../../src/import.js'; +import { generateDesignSystem, typeBase, STATE_LAYERS, PERSONALITY_NAMES } from '../../src/design-language.js'; +import { mergeDesignTokens, setVariables } from '../../src/variables.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { renderDetailPage } from '../../src/viewer.js'; +import { resolveStructure } from '../../src/structures.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -114,7 +114,7 @@ const text = (id: string, content: string, fontSize: number): SceneNode => ({ id // ── FR-A5: lists that lead with a mark are not tables ────────────────────── { - const fixture = JSON.parse(readFileSync('test-fixtures/viewer-baseline/gallery-pattern-library.json', 'utf-8')) as Canvas; + const fixture = JSON.parse(readFileSync('test/fixtures/viewer-baseline/gallery-pattern-library.json', 'utf-8')) as Canvas; const find = (n: SceneNode, id: string): SceneNode | undefined => n.id === id ? n : n.children?.map((c) => find(c, id)).find(Boolean); const sidebar = find(fixture.root, 'imp-frame-33')!; check('the baseline sidebar subtree is present', !!sidebar && (sidebar.children?.length ?? 0) >= 6); @@ -185,7 +185,7 @@ const text = (id: string, content: string, fontSize: number): SceneNode => ({ id check('a node named by several members is listed once', JSON.stringify(dup[0].nodeIds) === '["n","m"]' && dup[0].count === 3); check('the folded entry sits where the first member was', folded.findIndex((i) => i.nodeIds?.includes('a')) === 3); - const ds = JSON.parse(readFileSync('test-fixtures/viewer-baseline/detail-web-dashboard.json', 'utf-8')) as Canvas; + const ds = JSON.parse(readFileSync('test/fixtures/viewer-baseline/detail-web-dashboard.json', 'utf-8')) as Canvas; const r = await evaluateCanvas(ds, { mode: 'fast' }); const opsBefore = r.issues.filter((i) => i.fix).map((i) => i.fix!.op).sort(); const f = foldIssues(r.issues); @@ -238,10 +238,10 @@ const text = (id: string, content: string, fontSize: number): SceneNode => ({ id // ── FR-A9: the fixtures ───────────────────────────────────────────────────── { - const files = readdirSync('test-fixtures/viewer-baseline').filter((f) => f.endsWith('.json')).sort(); + const files = readdirSync('test/fixtures/viewer-baseline').filter((f) => f.endsWith('.json')).sort(); check('four baseline fixtures are committed', JSON.stringify(files) === JSON.stringify(['archive.json', 'detail-mobile-ridgeline.json', 'detail-web-dashboard.json', 'gallery-pattern-library.json']), files.join(', ')); for (const f of files) { - const raw = readFileSync(`test-fixtures/viewer-baseline/${f}`, 'utf-8'); + const raw = readFileSync(`test/fixtures/viewer-baseline/${f}`, 'utf-8'); const c = JSON.parse(raw) as Canvas; check(`${f} loads with a root and its own design system`, c.root?.type === 'document' && !!c.variables?.colors, createHash('sha256').update(raw).digest('hex').slice(0, 12)); } diff --git a/test-desktop-primitives.ts b/test/unit/test-desktop-primitives.ts similarity index 97% rename from test-desktop-primitives.ts rename to test/unit/test-desktop-primitives.ts index ce4caff..ff65d49 100644 --- a/test-desktop-primitives.ts +++ b/test/unit/test-desktop-primitives.ts @@ -5,20 +5,20 @@ // primitive must declare its type (desktop-app-artboard), stress reaches the // new copy, repeats count as reuse, the breadcrumb is built from links, and // unthemed stamps seed $border-strong (not $accent-tint, spec change S6). Rendered geometry lives -// in test-desktop-primitives-render.ts (Chrome). +// in test/browser/test-desktop-primitives-render.ts (Chrome). // -// Usage: npx tsx test-desktop-primitives.ts +// Usage: npx tsx test/unit/test-desktop-primitives.ts -import './test-env.js'; +import '../env.js'; import { readFileSync } from 'node:fs'; -import { evaluateCanvas } from './src/evaluate.js'; -import { renderToHtml } from './src/renderer.js'; -import { resolveVariables } from './src/variables.js'; -import { applyPerturbation } from './src/stress.js'; -import { getStructure, applyStructure } from './src/structures.js'; -import { createCanvas } from './src/scene-graph.js'; -import { desktopTargets, CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES } from './src/primitives.js'; -import type { Canvas, SceneNode } from './src/types.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import { renderToHtml } from '../../src/renderer.js'; +import { resolveVariables } from '../../src/variables.js'; +import { applyPerturbation } from '../../src/stress.js'; +import { getStructure, applyStructure } from '../../src/structures.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { desktopTargets, CLICKABLE_PRIMITIVES, DESKTOP_APP_PRIMITIVES } from '../../src/primitives.js'; +import type { Canvas, SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { @@ -195,7 +195,7 @@ const html = (n: SceneNode, colors?: Record) => { const without = html({ id: 'x', name: 'x', type: t }, { border: '#EEEEEE' }); check(`an unchecked ${t} uses $border-strong only when the token exists`, /#556677/.test(withTok) && !/#556677/.test(without) && /#EEEEEE/.test(without)); } - const { registerStructure } = await import('./src/structures.js'); + const { registerStructure } = await import('../../src/structures.js'); for (const t of ['link', 'text-input', 'nav-item', 'tabs', 'tree-row', 'menu-row', 'property-row', 'divider']) { registerStructure({ name: `probe-${t}`, kind: 'component', surface: 'any', description: 'probe', nodes: [{ id: 'n', type: t as SceneNode['type'], name: 'n', label: 'L', placeholder: 'Find', value: 'v', shortcut: '⌘K', error: 'Bad', items: [{ label: 'A' }] } as SceneNode] }); const cv = createCanvas(`seed-${t}`, undefined, {}, { type: 'desktop-app', device: 'window-1440' }); @@ -284,7 +284,7 @@ const html = (n: SceneNode, colors?: Record) => { // ── Viewer baseline: the gallery rebuilt with nav-item dots (FR-A6) ───────── { - const g = JSON.parse(readFileSync('test-fixtures/viewer-baseline/gallery-pattern-library.json', 'utf-8')) as Canvas; + const g = JSON.parse(readFileSync('test/fixtures/viewer-baseline/gallery-pattern-library.json', 'utf-8')) as Canvas; const find = (n: SceneNode, id: string): SceneNode | undefined => n.id === id ? n : n.children?.map((ch) => find(ch, id)).find(Boolean); const sidebar = find(g.root, 'imp-frame-33')!; const rows = (sidebar.children ?? []).filter((r) => r.layout === 'horizontal'); diff --git a/test-desktop-structures.ts b/test/unit/test-desktop-structures.ts similarity index 95% rename from test-desktop-structures.ts rename to test/unit/test-desktop-structures.ts index 62b514f..6330494 100644 --- a/test-desktop-structures.ts +++ b/test/unit/test-desktop-structures.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; /** * Phase 31 slice D — the pieces around the desktop-app realisations, each pass * with a twin that must fail: @@ -6,13 +6,13 @@ import './test-env.js'; * on a desktop-app canvas only, and a tripled list keeps one active row; * - a property-row's label names its control (and only its own label does); * - the coverage loading hint names skeleton-table-app on desktop-app. - * No Chrome. Run with: npx tsx test-desktop-structures.ts + * No Chrome. Run with: npx tsx test/unit/test-desktop-structures.ts */ -import { applyPerturbation } from './src/stress.js'; -import { createCanvas } from './src/scene-graph.js'; -import { applyStructure } from './src/structures.js'; -import { evaluateCanvas } from './src/evaluate.js'; -import type { SceneNode } from './src/types.js'; +import { applyPerturbation } from '../../src/stress.js'; +import { createCanvas } from '../../src/scene-graph.js'; +import { applyStructure } from '../../src/structures.js'; +import { evaluateCanvas } from '../../src/evaluate.js'; +import type { SceneNode } from '../../src/types.js'; let allPass = true; function check(name: string, cond: boolean, extra?: string) { diff --git a/test-discoverability.ts b/test/unit/test-discoverability.ts similarity index 97% rename from test-discoverability.ts rename to test/unit/test-discoverability.ts index 51c6ec0..953ee4e 100644 --- a/test-discoverability.ts +++ b/test/unit/test-discoverability.ts @@ -1,4 +1,4 @@ -import './test-env.js'; +import '../env.js'; // Discoverability guard — the #77 lesson, mechanized. // // MCP agents never read the README; they learn framesmith from the server @@ -13,12 +13,12 @@ import './test-env.js'; // exactly when a NEW name (tool, report field, node type, layout source) // hasn't been surfaced anywhere agents look. // -// Usage: npx tsx test-discoverability.ts +// Usage: npx tsx test/unit/test-discoverability.ts import { readFileSync } from 'node:fs'; -import { domToSceneGraph, type RawDomNode } from './src/import.js'; -import { listStructures } from './src/structures.js'; -import { RULESETS, GENRE_ALIASES, SURFACE_TYPES, DEVICE_PROFILES, WINDOW_PROFILES } from './src/surfaces.js'; +import { domToSceneGraph, type RawDomNode } from '../../src/import.js'; +import { listStructures } from '../../src/structures.js'; +import { RULESETS, GENRE_ALIASES, SURFACE_TYPES, DEVICE_PROFILES, WINDOW_PROFILES } from '../../src/surfaces.js'; interface Check { name: string; ok: boolean; detail?: string } const checks: Check[] = []; @@ -274,7 +274,7 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); // must stay documented — a warning an agent can't interpret is noise, and an // undocumented perturbation never gets run. { - const { PERTURBATION_NAMES } = await import('./src/stress.js'); + const { PERTURBATION_NAMES } = await import('../../src/stress.js'); expect('perturbation names found', PERTURBATION_NAMES.length >= 5, PERTURBATION_NAMES.join(', ')); for (const surface of [['src/index.ts', indexSrc], ['GUIDELINES', guidelines], ['README', readme]] as const) { const missing = PERTURBATION_NAMES.filter((p: string) => !surface[1].includes(p)); @@ -300,14 +300,14 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); // theme parameter, and the motion-token prefix must stay documented — a // generated vocabulary nobody can discover is a private language. { - const { RATIO_NAMES } = await import('./src/scales.js'); + const { RATIO_NAMES } = await import('../../src/scales.js'); expect('ratio names found', RATIO_NAMES.length >= 6, RATIO_NAMES.join(', ')); for (const surface of [['src/index.ts', indexSrc], ['GUIDELINES', guidelines], ['README', readme]] as const) { const missing = RATIO_NAMES.filter((r: string) => !surface[1].includes(r)); expect(`every ratio name in ${surface[0]}`, missing.length === 0, missing.join(', ')); } - const { generateColorSystem } = await import('./src/color-system.js'); + const { generateColorSystem } = await import('../../src/color-system.js'); const semanticNames = Object.keys(generateColorSystem('#2563EB').light); expect('semantic token names found', semanticNames.length >= 7, semanticNames.join(', ')); for (const surface of [['src/index.ts', indexSrc], ['README', readme]] as const) { @@ -341,7 +341,7 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); expect(`every project finding kind in ${surface[0]}`, missing.length === 0, missing.join(', ')); } - const { FLOW_AXES } = await import('./src/llm-judge.js'); + const { FLOW_AXES } = await import('../../src/llm-judge.js'); expect('flow axes found', FLOW_AXES.length >= 4, FLOW_AXES.join(', ')); for (const surface of [['src/index.ts', indexSrc], ['GUIDELINES', guidelines], ['README', readme]] as const) { const missing = FLOW_AXES.filter((a: string) => !surface[1].includes(a)); @@ -384,7 +384,7 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); // ── Phase 27 slice A: personalities + elevation vocabulary ─────────────────── { - const { PERSONALITY_NAMES } = await import('./src/design-language.js'); + const { PERSONALITY_NAMES } = await import('../../src/design-language.js'); expect('four personalities exported', PERSONALITY_NAMES.length === 4, PERSONALITY_NAMES.join(', ')); for (const surface of [['src/index.ts', indexSrc], ['GUIDELINES', guidelines], ['README', readme]] as const) { const missing = PERSONALITY_NAMES.filter((p: string) => !surface[1].includes(p)); @@ -441,7 +441,7 @@ const guidelines = readFileSync('docs/GUIDELINES.md', 'utf-8'); // live import) appear on each surface, so a new stateful type cannot ship // undocumented. { - const { ELEMENT_STATES, STATEFUL_TYPES } = await import('./src/primitives.js'); + const { ELEMENT_STATES, STATEFUL_TYPES } = await import('../../src/primitives.js'); // Each surface's own element-states paragraph, up to its blank line. const paragraph = (src: string, marker: string) => { const at = src.indexOf(marker); diff --git a/test-diversification.ts b/test/unit/test-diversification.ts similarity index 95% rename from test-diversification.ts rename to test/unit/test-diversification.ts index d4fa63e..e01df0f 100644 --- a/test-diversification.ts +++ b/test/unit/test-diversification.ts @@ -3,11 +3,11 @@ // check of the read+slice+compute composition the canvas_create / list_structures // handlers run (last N = 5, newest first). // -// Usage: npx tsx test-diversification.ts -import './test-env.js'; // isolate persistence — MUST be first -import { computeDiversificationHint } from './src/structures.js'; -import { appendBuildLog, readBuildLog } from './src/repo-store.js'; -import type { BuildLogEntry, StructureAxes } from './src/types.js'; +// Usage: npx tsx test/unit/test-diversification.ts +import '../env.js'; // isolate persistence — MUST be first +import { computeDiversificationHint } from '../../src/structures.js'; +import { appendBuildLog, readBuildLog } from '../../src/repo-store.js'; +import type { BuildLogEntry, StructureAxes } from '../../src/types.js'; let failures = 0; const check = (cond: boolean, msg: string) => { diff --git a/test-drift.ts b/test/unit/test-drift.ts similarity index 98% rename from test-drift.ts rename to test/unit/test-drift.ts index 0cb7abe..1f7cf69 100644 --- a/test-drift.ts +++ b/test/unit/test-drift.ts @@ -3,11 +3,11 @@ // issue: a canvas showing a STATUS column / "Rename" links the page no longer // has, and a canvas radiogroup the implementation shipped as a