openpencil/tests/engine/lint/variable-binding-validation.test.ts
Danila Poyarkov aa86873dd7
test: typecheck the test suites and fix what that found (#896)
* build: typecheck the test suites

Tests were in no TypeScript program: no tsconfig included tests/** or
packages/*/tests/**, and bun strips types without checking them, so a
fixture could drop a required field and keep passing until something
read it.

@types/bun moves to the root because it was installed per package only,
and #cli-tests/* joins the paths the root config already carries.

* test: fix the type errors the test suites were hiding

Typechecking the tests turned up 1123 errors. Most were ordinary
strictness, but some were real: `NodeChange` bound to Figma's plugin
typings rather than the Kiwi codec in thirteen .fig tests,
materializeInstance was called with six arguments against five so the
blobs and source children were dropped, CanvasKit pixels were written
to a plain object that never reached WASM, and assertions were made
through accessors that do not exist, so they asserted nothing.

Fixtures that had quietly lost a required field now carry it, nullable
results are narrowed through the existing expectDefined helper rather
than assumed, and stand-ins for CanvasKit and the editor go through one
named helper instead of an unexplained cast at each site.

No test was deleted, skipped, or weakened, and no `any`, non-null
assertion, or ts-expect-error was introduced.

* docs: record what typechecking the tests established

Pins the app program's global types with an assertion rather than a
note, since an unpinned types list lets any root @types package decide
which platform src/** is judged against.

The two environment faults that look like code regressions — Vite's
dependency pre-bundle outliving a package rebuild, and heavy .fig
suites failing under load — go to the development docs, where an
explanation belongs.

* fix: align @types/bun and keep node types resolvable when extended

The root manifest declared a newer @types/bun than every package, which
check:monorepo rejects, and pinning the app program's types left them
unresolvable from a config that extends this one out of tree.

* fix: fail the test typecheck when the compiler itself fails

The gate matched diagnostics by substring, so a compiler or config
failure that named no test file printed a pass while having checked
nothing. Diagnostics are now split by whether they name a file: an
unscoped one is the run failing and stops the gate, a test file's is a
finding, and a source file's stays out by design.

Also drops the parameter planComponentConstruction never read, and
makes the inner-shadow verification script exit non-zero when it
renders no image instead of logging and succeeding.

* chore: merge master into tests-typecheck
2026-10-05 12:42:38 +00:00

251 lines
7.9 KiB
TypeScript

import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/core'
import noHardcodedColors from '@open-pencil/core/lint/rules/no-hardcoded-colors'
import { getNodeOrThrow } from '#tests/helpers/assert'
function pageId(graph: SceneGraph): string {
return graph.getPages()[0].id
}
function setupColorVars(graph: SceneGraph, ...ids: string[]): void {
graph.addCollection({
id: 'col1',
name: 'Colors',
modes: [{ modeId: 'm1', name: 'Light' }],
defaultModeId: 'm1',
variableIds: []
})
for (const id of ids) {
graph.addVariable({
id,
name: `Var ${id}`,
type: 'COLOR',
collectionId: 'col1',
valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },
description: '',
hiddenFromPublishing: false
})
}
}
// ─── bindVariable emits node:updated event ──────────────────────────────────
describe('bindVariable emits node:updated event', () => {
test('bindVariable emits node:updated event', () => {
const graph = new SceneGraph()
setupColorVars(graph, 'v1')
const node = graph.createNode('RECTANGLE', pageId(graph), {
name: 'Rect',
fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]
})
const events: Array<{ nodeId: string; changes: Record<string, unknown> }> = []
graph.onNodeEvents({
updated: (nodeId, changes) => {
events.push({ nodeId, changes })
}
})
graph.bindVariable(node.id, 'fills/0/color', 'v1')
expect(events.length).toBeGreaterThanOrEqual(1)
expect(events[0].nodeId).toBe(node.id)
expect(events[0].changes).toHaveProperty('boundVariables')
})
})
// ─── no-hardcoded-colors lint checks indexed bindings ──────────────────────
/** Variables whose only color matches the tests' 50% gray paint. */
const GRAY_VARIABLES = {
counts: { COLOR: 1, FLOAT: 0, STRING: 0, BOOLEAN: 0 },
colorsByHex: new Map([['#808080', { id: 'v1', name: 'Gray' }]])
}
describe('no-hardcoded-colors lint checks indexed bindings', () => {
test('node with fills/0/color binding passes lint (no false positive)', () => {
const node = {
id: 'n1',
name: 'Rect',
type: 'RECTANGLE',
width: 100,
height: 100,
x: 0,
y: 0,
rotation: 0,
visible: true,
locked: false,
layoutMode: 'NONE',
layoutPositioning: 'AUTO' as const,
layoutGrow: 0,
layoutAlignSelf: 'AUTO',
primaryAxisSizing: 'FIXED',
counterAxisSizing: 'FIXED',
textAutoResize: 'NONE',
itemSpacing: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
cornerRadius: 0,
childIds: [],
text: '',
fontSize: 14,
styleRunCount: 0,
boundVariables: { 'fills/0/color': 'v1' },
fills: [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0.5, g: 0.5, b: 0.5 } }],
strokes: [],
effects: []
}
const messages: Array<{ message: string }> = []
const context = {
variables: GRAY_VARIABLES,
report: (issue: { message: string }) => messages.push(issue),
getConfig: () => ({}),
getParent: () => null,
getChildren: () => []
}
noHardcodedColors.check(node, context)
// Should NOT report a violation — the color is bound to a variable
expect(messages.length).toBe(0)
})
test('node with top-level fills binding still reports violation (no false negative)', () => {
const node = {
id: 'n2',
name: 'Rect',
type: 'RECTANGLE',
width: 100,
height: 100,
x: 0,
y: 0,
rotation: 0,
visible: true,
locked: false,
layoutMode: 'NONE',
layoutPositioning: 'AUTO' as const,
layoutGrow: 0,
layoutAlignSelf: 'AUTO',
primaryAxisSizing: 'FIXED',
counterAxisSizing: 'FIXED',
textAutoResize: 'NONE',
itemSpacing: 0,
paddingTop: 0,
paddingRight: 0,
paddingBottom: 0,
paddingLeft: 0,
cornerRadius: 0,
childIds: [],
text: '',
fontSize: 14,
styleRunCount: 0,
boundVariables: { fills: 'v1' }, // top-level — renderer-ignored
fills: [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0.5, g: 0.5, b: 0.5 } }],
strokes: [],
effects: []
}
const messages: Array<{ message: string }> = []
const context = {
variables: GRAY_VARIABLES,
report: (issue: { message: string }) => messages.push(issue),
getConfig: () => ({}),
getParent: () => null,
getChildren: () => []
}
noHardcodedColors.check(node, context)
// SHOULD report a violation — top-level 'fills' binding is renderer-ignored
expect(messages.length).toBeGreaterThanOrEqual(1)
})
})
// ─── bindVariable validation ──────────────────────────────────────────────
describe('bindVariable validation', () => {
function setupGraph(): SceneGraph {
const graph = new SceneGraph()
graph.addCollection({
id: 'col1',
name: 'Colors',
modes: [{ modeId: 'm1', name: 'Light' }],
defaultModeId: 'm1',
variableIds: []
})
graph.addVariable({
id: 'v-color',
name: 'Primary',
type: 'COLOR',
collectionId: 'col1',
valuesByMode: { m1: { r: 1, g: 0, b: 0, a: 1 } },
description: '',
hiddenFromPublishing: false
})
graph.addVariable({
id: 'v-float',
name: 'Spacing',
type: 'FLOAT',
collectionId: 'col1',
valuesByMode: { m1: 16 },
description: '',
hiddenFromPublishing: false
})
return graph
}
test('bindVariable rejects nonexistent variable', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
expect(() => {
graph.bindVariable(node.id, 'fills/0/color', 'nonexistent')
}).toThrow()
expect(getNodeOrThrow(graph, node.id).boundVariables['fills/0/color']).toBeUndefined()
})
test('bindVariable rejects FLOAT variable on color field', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
expect(() => {
graph.bindVariable(node.id, 'fills/0/color', 'v-float')
}).toThrow()
expect(getNodeOrThrow(graph, node.id).boundVariables['fills/0/color']).toBeUndefined()
})
test('bindVariable rejects COLOR variable on scalar field', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
expect(() => {
graph.bindVariable(node.id, 'opacity', 'v-color')
}).toThrow()
expect(getNodeOrThrow(graph, node.id).boundVariables['opacity']).toBeUndefined()
})
test('bindVariable rejects binding to fills that do not yet exist', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })
// Rect has 0 fills — binding to fills/0/color must be rejected (index >= length)
expect(() => {
graph.bindVariable(node.id, 'fills/0/color', 'v-color')
}).toThrow(/out of range/)
})
test('bindVariable auto-removes top-level fills binding when indexed binding is set', () => {
const graph = setupGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), {
name: 'Rect',
fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]
})
const n = getNodeOrThrow(graph, node.id)
// Set top-level dead data first
n.boundVariables['fills'] = 'v-color'
// Now set a proper indexed binding — should auto-remove top-level
graph.bindVariable(node.id, 'fills/0/color', 'v-color')
expect(n.boundVariables['fills']).toBeUndefined()
expect(n.boundVariables['fills/0/color']).toBe('v-color')
})
})