logigate/tests/library.test.ts

336 lines
17 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { nandCounts, truthTable } from '../app/lib/logic/analyze'
import { cleanBundle, closure, describeBundle, importBundle, kindsIn, libraryBundle, lockedKinds, publishProblem, type LibraryMeta } from '../app/lib/logic/library'
import { createProject, duplicateComponent, lookup, startChallenge } from '../app/lib/logic/ops'
import { parseProject, toProject } from '../app/lib/logic/project'
import { libraryKeys, setLibraryKey } from '../app/lib/logic/storage'
import { CHALLENGES } from '../app/lib/logic/challenges'
import type { ComponentDef, LibraryOrigin, Project, Wire } from '../app/lib/logic/types'
import { publicMeta, searchLibrary, type LibraryItem } from '../server/utils/library'
const w = (id: string, from: [string, string], to: [string, string]): Wire => ({ id, from: { node: from[0], pin: from[1] }, to: { node: to[0], pin: to[1] } })
const origin: LibraryOrigin = { id: 'Lib12345', version: 1, author: 'Ada' }
/** The rows of a component's truth table, as text. */
function rows(p: Project, id: string) {
const t = truthTable(lookup(p), id)
return 'error' in t ? t.error : t.rows.map(r => `${r.ins.join('')}|${r.outs.join('')}`)
}
/** Ada's project: the examples, a link of her own and a part that sends two lines over it. */
function adasProject(): Project {
const p = createProject({ examples: true })
p.connectors = [{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }]
const sender: ComponentDef = {
id: 'csend',
name: 'Sender',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'b', kind: 'input', x: 0, y: 2, label: 'B' },
{ id: 'x', kind: 'chip', chip: 'ex-xor', x: 6, y: 0 },
{ id: 'tx', kind: 'portout', conn: 'k1', x: 20, y: 0 },
],
wires: [w('w1', ['a', 'q'], ['x', 'a']), w('w2', ['b', 'q'], ['x', 'b']), w('w3', ['x', 'q'], ['tx', 'l0']), w('w4', ['a', 'q'], ['tx', 'l1'])],
}
p.components.push(sender)
return p
}
/** What a library entry hands out: the bundle, cleaned as the server does. */
const published = (p: Project, id: string) => cleanBundle(JSON.parse(JSON.stringify(libraryBundle(p, id))))
describe('library: what goes along', () => {
it('lists a component after everything it uses, each once, itself last', () => {
const p = createProject({ examples: true })
const order = closure(lookup(p), 'ex-add4').map(d => d.id)
expect(order.at(-1)).toBe('ex-add4')
expect(new Set(order).size).toBe(order.length)
expect([...order].sort()).toEqual(['ex-add4', 'ex-and', 'ex-fa', 'ex-ha', 'ex-not', 'ex-or', 'ex-xor'])
const get = lookup(p)
for (const [i, id] of order.entries()) {
for (const n of get(id)!.nodes) if (n.kind === 'chip') expect(order.indexOf(n.chip!), `${id} uses ${n.chip}`).toBeLessThan(i)
}
})
it('carries the connector types its ports use, without challenge marks', () => {
const p = adasProject()
p.connectors!.push({ id: 'k2', name: 'Unused', lines: [{ name: 'X' }] })
p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
const b = libraryBundle(p, 'csend')
expect(b.root).toBe('csend')
expect(b.components.map(d => d.id)).toEqual(['ex-xor', 'csend'])
expect(b.connectors?.map(c => c.id)).toEqual(['k1'])
expect(b.components.some(d => d.challenge)).toBe(false)
// The project itself keeps its marks.
expect(p.components.find(d => d.id === 'ex-xor')!.challenge).toBe('xor')
})
it('keeps challenges and puzzle solutions private', () => {
const p = createProject({ examples: true })
const not = startChallenge(p, CHALLENGES.find(c => c.id === 'not')!)
expect(publishProblem(p, not.id)).toMatch(/private/)
expect(publishProblem(p, 'ex-add4')).toBeNull()
// A solved built-in challenge may be used inside; a puzzle solution may not.
p.components.find(d => d.id === 'ex-xor')!.challenge = 'xor'
expect(publishProblem(p, 'ex-add4')).toBeNull()
p.components.find(d => d.id === 'ex-xor')!.challenge = 'pz:abc123'
expect(publishProblem(p, 'ex-add4')).toMatch(/puzzle "XOR"/)
p.components.push({ id: 'empty', name: 'Empty', symbol: 'box', nodes: [], wires: [] })
expect(publishProblem(p, 'empty')).toMatch(/nothing/)
})
})
describe('library: checks on the server', () => {
it('keeps only what the component uses and counts it honestly', () => {
const p = adasProject()
const raw = { ...libraryBundle(p, 'csend'), components: p.components }
const b = cleanBundle(JSON.parse(JSON.stringify(raw)))
expect(b.components.map(d => d.id)).toEqual(closure(lookup(p), 'csend').map(d => d.id))
const meta = describeBundle(b)
expect(meta.transistors).toBe(nandCounts(p.components).get('csend')! * 4)
expect(meta).toMatchObject({ name: 'Sender', inputs: ['A', 'B'], outputs: [], uses: 1, connectors: 1 })
expect(meta.kinds).toEqual(['input', 'nand', 'output', 'portout'])
})
it('refuses missing parts, parts that contain themselves and broken nodes', () => {
const p = createProject({ examples: true })
const b = libraryBundle(p, 'ex-ha')
expect(() => cleanBundle({ ...b, components: b.components.filter(d => d.id !== 'ex-xor') })).toThrow(/Missing component/)
const loop = JSON.parse(JSON.stringify(b))
loop.components.find((d: ComponentDef) => d.id === 'ex-xor').nodes.push({ id: 'me', kind: 'chip', chip: 'ex-ha', x: 0, y: 9 })
expect(() => cleanBundle(loop)).toThrow(/contains itself/)
const broken = JSON.parse(JSON.stringify(b))
broken.components[0].nodes[0].x = 'left'
expect(() => cleanBundle(broken)).toThrow(/broken/)
expect(() => cleanBundle({ root: 'nope', components: b.components })).toThrow(/missing/)
expect(() => cleanBundle('hello')).toThrow()
})
/** Components l0 … l<depth>, each holding `n` of the one below; l0 is one NAND. */
function tower(depth: number, n: number) {
const components: ComponentDef[] = [{ id: 'l0', name: 'L0', symbol: 'box', nodes: [{ id: 'g', kind: 'nand', x: 0, y: 0 }], wires: [] }]
for (let i = 1; i <= depth; i++) {
const nodes = Array.from({ length: n }, (_, k) => ({ id: `c${k}`, kind: 'chip' as const, chip: `l${i - 1}`, x: 0, y: 4 * k }))
components.push({ id: `l${i}`, name: `L${i}`, symbol: 'box', nodes, wires: [] })
}
return { root: `l${depth}`, components }
}
it('refuses nesting deeper than the simulator goes, and parts too huge to run, without building them', () => {
expect(() => cleanBundle(tower(63, 1))).not.toThrow()
expect(() => cleanBundle(tower(64, 1))).toThrow(/Nesting deeper than 64/)
// 10^12 NANDs once opened up: refused at once.
const t = performance.now()
expect(() => cleanBundle(tower(12, 10))).toThrow(/Too large to run/)
expect(performance.now() - t).toBeLessThan(1000)
expect(describeBundle(cleanBundle(tower(6, 10))).transistors).toBe(4_000_000)
})
})
describe('library: adding an entry to a project', () => {
it('brings everything with new ids, wired to each other, computing the same', () => {
const ada = adasProject()
const bob = createProject({ examples: false })
const res = importBundle(bob, published(ada, 'csend'), origin)
expect(res.added).toBe(closure(lookup(ada), 'csend').length)
const root = bob.components.find(d => d.id === res.root)!
expect(root.name).toBe('Sender')
expect(root.id).not.toBe('csend')
// Every component it uses is here, under its new id.
const get = lookup(bob)
for (const d of closure(get, root.id)) for (const n of d.nodes) if (n.kind === 'chip') expect(get(n.chip!), n.chip).toBeTruthy()
expect(closure(get, root.id)).toHaveLength(res.added)
expect(nandCounts(bob.components).get(root.id)).toBe(nandCounts(ada.components).get('csend'))
const xor = closure(get, root.id).find(d => d.name === 'XOR')!
expect(rows(bob, xor.id)).toEqual(rows(ada, 'ex-xor'))
// The connector type came along and the port uses it.
expect(bob.connectors).toEqual([{ id: 'k1', name: 'Link', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }] }])
expect(root.nodes.find(n => n.kind === 'portout')!.conn).toBe('k1')
})
it('marks the entry, and what came along with it', () => {
const bob = createProject({ examples: false })
const res = importBundle(bob, published(createProject({ examples: true }), 'ex-ha'), origin)
const added = bob.components.slice(-res.added)
expect(added.find(d => d.id === res.root)!.from).toEqual(origin)
for (const d of added.filter(d => d.id !== res.root)) expect(d.from).toEqual({ ...origin, inside: true })
})
it('makes a copy of an added component your own, without the mark', () => {
const bob = createProject({ examples: false })
const res = importBundle(bob, published(createProject({ examples: true }), 'ex-xor'), origin)
expect(duplicateComponent(bob, res.root)!.from).toBeUndefined()
})
it('keeps the marks of library components used inside, so their authors stay named', () => {
const ada = createProject({ examples: true })
ada.components.find(d => d.id === 'ex-xor')!.from = { id: 'Xor00001', version: 3, author: 'Cy' }
const bob = createProject({ examples: false })
importBundle(bob, published(ada, 'ex-ha'), origin)
expect(bob.components.find(d => d.name === 'XOR')!.from).toEqual({ id: 'Xor00001', version: 3, author: 'Cy' })
})
it('uses what is here in the same form, and adds nothing for the same entry twice', () => {
const ada = createProject({ examples: true })
const bob = createProject({ examples: true })
const before = bob.components.length
// Bob has the examples: the half adder and all it uses are his already.
const first = importBundle(bob, published(ada, 'ex-ha'), origin)
expect(first).toEqual({ root: 'ex-ha', added: 0 })
expect(bob.components).toHaveLength(before)
const carl = createProject({ examples: false })
const a = importBundle(carl, published(ada, 'ex-fa'), origin)
const again = importBundle(carl, published(ada, 'ex-fa'), { ...origin, version: 2 })
expect(again).toEqual({ root: a.root, added: 0 })
expect(carl.components.find(d => d.id === a.root)!.from).toEqual({ ...origin, version: 2 })
})
it('gives a name that is taken by something else a number', () => {
const ada = createProject({ examples: true })
const bob = createProject({ examples: true })
// Bob's NOT differs from Ada's: hers comes in as "NOT 2", with what uses it pointing at hers.
ada.components.find(d => d.id === 'ex-not')!.nodes[0]!.x += 1
const res = importBundle(bob, published(ada, 'ex-and'), origin)
expect(res.added).toBe(2)
const and = bob.components.find(d => d.id === res.root)!
expect(and.name).toBe('AND 2')
const not = bob.components.find(d => d.id === and.nodes.find(n => n.kind === 'chip')!.chip)!
expect(not.name).toBe('NOT 2')
expect(not.id).not.toBe('ex-not')
expect(rows(bob, and.id)).toEqual(rows(ada, 'ex-and'))
})
it('joins connector types with the same lines, and keeps different ones apart', () => {
const ada = adasProject()
const same = createProject({ examples: true })
same.connectors = [{ id: 'mine', name: 'link', lines: [{ name: 'D0' }, { name: 'D1' }] }]
const a = importBundle(same, published(ada, 'csend'), origin)
expect(same.connectors).toHaveLength(1)
expect(same.components.find(d => d.id === a.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe('mine')
const other = createProject({ examples: true })
other.connectors = [{ id: 'k1', name: 'Link', lines: [{ name: 'TX' }, { name: 'RX', back: true }] }]
const b = importBundle(other, published(ada, 'csend'), origin)
expect(other.connectors).toHaveLength(2)
const added = other.connectors[1]!
expect(added.id).not.toBe('k1')
expect(added.name).toBe('Link 2')
expect(other.components.find(d => d.id === b.root)!.nodes.find(n => n.kind === 'portout')!.conn).toBe(added.id)
})
it('updates a component in place to a newer version, where it is used too', () => {
const ada = createProject({ examples: true })
const bob = createProject({ examples: false })
const v1 = importBundle(bob, published(ada, 'ex-and'), origin)
const main = bob.components.find(d => d.id === 'main')!
main.nodes.push({ id: 'u', kind: 'chip', chip: v1.root, x: 10, y: 10 })
// Version 2: AND became OR (same pins), now built from Ada's OR.
const and = ada.components.find(d => d.id === 'ex-and')!
const or = ada.components.find(d => d.id === 'ex-or')!
and.nodes = structuredClone(or.nodes)
and.wires = structuredClone(or.wires)
const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, v1.root)
expect(v2.root).toBe(v1.root)
const updated = bob.components.find(d => d.id === v1.root)!
expect(updated.name).toBe('AND')
expect(updated.from).toEqual({ ...origin, version: 2 })
expect(rows(bob, v1.root)).toEqual(rows(ada, 'ex-or'))
expect(main.nodes.find(n => n.id === 'u')!.chip).toBe(v1.root)
})
it('never reuses the component being updated inside its own new version', () => {
const bob = createProject({ examples: false })
const ada = createProject({ examples: true })
// The entry was Ada's NOT; its next version is her AND, which uses a NOT exactly like the one Bob has.
const res = importBundle(bob, published(ada, 'ex-not'), origin)
const v2 = importBundle(bob, published(ada, 'ex-and'), { ...origin, version: 2 }, res.root)
const get = lookup(bob)
expect(closure(get, v2.root).filter(d => d.id === v2.root)).toHaveLength(1)
expect(get(v2.root)!.nodes.some(n => n.chip === v2.root)).toBe(false)
expect(rows(bob, v2.root)).toEqual(rows(ada, 'ex-and'))
})
})
describe('library: campaign and old projects', () => {
it('names the parts a campaign has not earned yet', () => {
const p = createProject({ examples: false, campaign: true })
const b = published(createProject({ examples: true }), 'ex-cnt4')
// The counter's display and the constant 1 in its incrementer.
expect(lockedKinds(p, kindsIn(b.components))).toEqual(['hex', 'high'])
p.solved.push('not')
expect(lockedKinds(p, kindsIn(b.components))).toEqual(['hex'])
p.solved.push('dec2')
expect(lockedKinds(p, kindsIn(b.components))).toEqual([])
expect(lockedKinds(createProject({ examples: false }), ['clock', 'portin'])).toEqual([])
})
it('loads projects without library marks as before, and drops broken marks', () => {
const p = createProject({ examples: true })
const plain = toProject(JSON.parse(JSON.stringify(p)))
expect(plain.components.some(d => 'from' in d)).toBe(false)
expect(plain).toEqual(JSON.parse(JSON.stringify(p)))
const marked = JSON.parse(JSON.stringify(p))
marked.components[1].from = { id: 'Lib12345', version: 2, author: 'Ada', inside: true, extra: 1 }
marked.components[2].from = { id: '../etc', version: 1, author: 'x' }
marked.components[3].from = { id: 'Lib12345', version: 0 }
const q = parseProject(JSON.stringify(marked))
expect(q.components[1]!.from).toEqual({ id: 'Lib12345', version: 2, author: 'Ada', inside: true })
expect(q.components[2]!.from).toBeUndefined()
expect(q.components[3]!.from).toBeUndefined()
})
})
describe('library keys in the browser', () => {
it('keeps what was published from here, and reads anything broken as nothing', () => {
const map = new Map<string, string>()
globalThis.localStorage = { getItem: k => map.get(k) ?? null, setItem: (k, v) => void map.set(k, v), removeItem: k => void map.delete(k) } as Storage
expect(libraryKeys()).toEqual({})
setLibraryKey('Lib12345', { key: 'secret', project: 'p1', def: 'c1' })
setLibraryKey('Lib67890', { key: 'other', project: 'p1', def: 'c2' })
setLibraryKey('Lib67890', null)
expect(libraryKeys()).toEqual({ Lib12345: { key: 'secret', project: 'p1', def: 'c1' } })
map.set('logigate:library-keys', '[1, 2]')
expect(libraryKeys()).toEqual({})
map.set('logigate:library-keys', 'not json')
expect(libraryKeys()).toEqual({})
})
})
describe('library listing', () => {
const item = (id: string, name: string, updated: number, player: string, description = ''): LibraryItem => ({
id,
name,
description,
group: '',
version: 1,
created: 0,
updated,
transistors: 8,
inputs: ['A'],
outputs: ['Q'],
uses: 0,
connectors: 0,
kinds: ['nand'],
player,
})
const names = { 'player-ada-0001': 'Ada' }
const list = [item('a1', 'Adder 8', 10, 'player-ada-0001', 'ripple carry'), item('a2', 'ALU', 30, 'player-bob-0002'), item('a3', 'Shifter', 20, 'player-ada-0001')].map(m =>
publicMeta(m, names),
)
it('shows authors by their name, never their player id', () => {
expect(list[0]!.author).toBe('Ada')
expect(list[1]!.author).toBe('')
expect(JSON.stringify(list)).not.toContain('player-')
})
it('finds every word in name, description or author, newest first', () => {
expect(searchLibrary(list, '').map((m: LibraryMeta) => m.id)).toEqual(['a2', 'a3', 'a1'])
expect(searchLibrary(list, 'ada').map(m => m.id)).toEqual(['a3', 'a1'])
expect(searchLibrary(list, 'Carry ADA').map(m => m.id)).toEqual(['a1'])
expect(searchLibrary(list, 'nothing')).toEqual([])
})
})