// The public component library: components people published for everyone, // each with every component it uses and the connector types those need. // Publishing sends one component and what it uses (a bundle); adding an // entry to a project brings the bundle in with new ids, and uses what the // project has in exactly that form already. Shared by the browser and the // library server, so it must stay free of browser APIs. import { nandCounts, TRANSISTORS_PER_NAND } from './analyze' import { CHALLENGES } from './challenges' import { MAX_DEPTH } from './compile' import { chipPins, type DefLookup } from './geometry' import { containsDef, lookup, uid, uniqueName } from './ops' import { KIND_NAMES, kindUnlocked } from './progress' import { toProject } from './project' import type { ComponentDef, ConnectorType, LibraryOrigin, NodeKind, Project } from './types' import { NAND_BASE } from './wide' /** Upper bounds for a published component: the request, its name and description. */ export const LIBRARY_LIMITS = { bytes: 1_000_000, name: 60, description: 400 } /** What gets published: a component (`root`) and everything it uses, used ones first, with their connector types. */ export interface LibraryBundle { root: string components: ComponentDef[] connectors?: ConnectorType[] } /** A library entry as it is listed: what it is, who published it, what it takes. */ export interface LibraryMeta { id: string name: string description: string group: string /** The publisher's leaderboard name; empty for anonymous. */ author: string version: number created: number updated: number /** Transistors at every depth, 4 per NAND. */ transistors: number /** Pin names, top to bottom. */ inputs: string[] outputs: string[] /** Components it uses, at every depth; they come along. */ uses: number /** Connector types that come along. */ connectors: number /** Built-in parts used anywhere inside (a campaign has to have earned them). */ kinds: NodeKind[] } /** Deep copy that also works on Vue reactive proxies (structuredClone does not). */ function clone(value: T): T { return JSON.parse(JSON.stringify(value)) as T } /** * A component and every component it uses, at every depth, each once: the * used ones before the ones that use them, the component itself last. A * component that contains itself is not followed round again. */ export function closure(get: DefLookup, defId: string): ComponentDef[] { const out: ComponentDef[] = [] const seen = new Set() const visit = (id: string) => { if (seen.has(id)) return seen.add(id) const def = get(id) if (!def) return for (const n of def.nodes) if (n.kind === 'chip' && n.chip) visit(n.chip) if (def.wide && def.wide.base !== NAND_BASE) visit(def.wide.base) out.push(def) } visit(defId) return out } /** Connector types the ports of these components use, in the project's order. */ function connectorsUsed(connectors: ConnectorType[] | undefined, defs: ComponentDef[]): ConnectorType[] { const used = new Set(defs.flatMap(d => d.nodes.filter(n => (n.kind === 'portin' || n.kind === 'portout') && n.conn).map(n => n.conn!))) return (connectors ?? []).filter(c => used.has(c.id)) } /** Built-in parts used anywhere in these components, in a fixed order. */ export function kindsIn(defs: ComponentDef[]): NodeKind[] { return [...new Set(defs.flatMap(d => d.nodes.map(n => n.kind)))].filter(k => k !== 'chip').sort() } /** Built-in parts a project has not earned yet (in a campaign), out of these. */ export function lockedKinds(project: Project, kinds: NodeKind[]): NodeKind[] { return kinds.filter(k => !kindUnlocked(project, k)) } /** * Why a component can't go to the library, in words; null when it can. * Challenges and puzzles stay private, so nobody gets the answer: neither * a challenge circuit itself nor a puzzle solution used inside. */ export function publishProblem(project: Project, defId: string): string | null { const get = lookup(project) const def = get(defId) if (!def) return 'Circuit not found' if (def.challenge) return 'Challenges and puzzles stay private, so nobody gets the answer' if (!def.nodes.length) return 'There is nothing in it yet' const puzzle = closure(get, defId).find(d => d.challenge && !CHALLENGES.some(c => c.id === d.challenge)) if (puzzle) return `It uses your solution to the puzzle "${puzzle.name}", which stays private` return null } /** * What publishing a component sends: copies of it and of what it uses, * without challenge marks, and their connector types. Components it uses * keep their own library marks, so their authors stay named. */ export function libraryBundle(project: Project, defId: string): LibraryBundle { const components = clone(closure(lookup(project), defId)) for (const d of components) delete d.challenge const root = components.find(d => d.id === defId) if (root) delete root.from const connectors = clone(connectorsUsed(project.connectors, components)) return { root: defId, components, ...(connectors.length ? { connectors } : {}) } } /** Parts a published component may have at every depth, so whoever adds it can still run it. */ export const MAX_FLAT_PARTS = 10_000_000 /** * What the simulator would refuse in a component, or choke on: a component * inside that is missing, one that contains itself, nesting too deep, or * too many parts once every component inside is opened up. Found by looking * at each component once, never by building the whole circuit, so a part * made to be huge costs no more to check than a small one. */ function nestingProblem(get: DefLookup, rootId: string): string | null { const seen = new Map() const busy = new Set() let problem: string | null = null const visit = (def: ComponentDef): { depth: number; parts: number } => { const known = seen.get(def.id) if (known) return known busy.add(def.id) const size = { depth: 1, parts: 0 } for (const n of def.nodes) { const child = n.kind === 'chip' && n.chip ? get(n.chip) : undefined if (n.kind !== 'chip') size.parts++ else if (!child) problem ??= `Missing component in "${def.name}"` else if (busy.has(child.id)) problem ??= `"${child.name}" contains itself` else { const inner = visit(child) size.depth = Math.max(size.depth, 1 + inner.depth) size.parts += inner.parts } } busy.delete(def.id) seen.set(def.id, size) return size } const size = visit(get(rootId)!) if (size.depth > MAX_DEPTH) problem ??= `Nesting deeper than ${MAX_DEPTH} levels` if (size.parts > MAX_FLAT_PARTS) problem ??= `Too large to run: over ${MAX_FLAT_PARTS.toLocaleString('en')} parts with everything inside opened up` return problem } /** Every kind of node there is: the built-in parts and components. */ const KINDS = new Set([...Object.keys(KIND_NAMES), 'chip']) /** * Checks a bundle from outside with the same checks as any project, plus * the ones a part from a stranger needs: every node and wire well formed, * nothing missing, nothing inside itself, nothing too big to run. Keeps only * the component and what it uses, and drops challenge marks. Throws with a * readable message. */ export function cleanBundle(raw: unknown): LibraryBundle { const b = raw as Partial if (!b || typeof b !== 'object' || typeof b.root !== 'string') throw new Error('Not a component for the library') const p = toProject({ name: 'Library', components: b.components, connectors: b.connectors, openId: b.root }) for (const d of p.components) { const broken = () => new Error(`"${d.name}" is broken`) for (const n of d.nodes) { if (!n || typeof n.id !== 'string' || !KINDS.has(n.kind) || !Number.isFinite(n.x) || !Number.isFinite(n.y)) throw broken() if (n.label !== undefined && typeof n.label !== 'string') delete n.label } for (const w of d.wires) { if (!w || typeof w.id !== 'string' || [w.from, w.to].some(r => !r || typeof r.node !== 'string' || typeof r.pin !== 'string')) throw broken() } for (const k of ['description', 'group'] as const) if (d[k] !== undefined && typeof d[k] !== 'string') delete d[k] } const get = lookup(p) const root = get(b.root) if (!root) throw new Error('The component itself is missing') const problem = nestingProblem(get, root.id) if (problem) throw new Error(problem) const components = closure(get, root.id) for (const d of components) delete d.challenge delete root.from root.name = root.name.trim().slice(0, LIBRARY_LIMITS.name) || 'Component' if (root.description !== undefined) root.description = root.description.trim().slice(0, LIBRARY_LIMITS.description) const connectors = connectorsUsed(p.connectors, components) return { root: root.id, components, ...(connectors.length ? { connectors } : {}) } } /** What the listing says about a bundle, counted from the circuit itself so it can be trusted. */ export function describeBundle(b: LibraryBundle): Pick { const root = b.components.find(d => d.id === b.root) if (!root) throw new Error('The component itself is missing') const pins = chipPins(root) return { name: root.name, description: root.description ?? '', group: root.group?.trim() ?? '', transistors: (nandCounts(b.components).get(root.id) ?? 0) * TRANSISTORS_PER_NAND, inputs: pins.inputs.map(p => p.label), outputs: pins.outputs.map(p => p.label), uses: b.components.length - 1, connectors: b.connectors?.length ?? 0, kinds: kindsIn(b.components), } } /** JSON with object keys sorted, so the same data always gives the same text. */ function canon(value: unknown): string { return JSON.stringify(value, (_, v) => v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) : v, ) } /** What a component is, apart from its id, name, texts and marks: the same for two copies of one thing. */ const form = (d: ComponentDef) => canon({ symbol: d.symbol, face: d.face, wide: d.wide, design: d.design, nodes: d.nodes, wires: d.wires }) const sameLines = (a: ConnectorType, b: ConnectorType) => canon(a.lines.map(l => [l.name, !!l.back])) === canon(b.lines.map(l => [l.name, !!l.back])) /** Parts of a component that an update replaces; its name and group stay as they are here. */ const CONTENT = ['symbol', 'description', 'face', 'wide', 'design', 'nodes', 'wires'] as const /** * Adds a library entry to a project. What the project has in exactly this * form already (an earlier import, the examples) is used as it is; the rest * comes in with new ids, and with a number after its name when the name is * taken. A connector type joins the project's type of the same id or name * when their lines match, and comes in as a new type otherwise. The entry's * component is marked with where it came from; the ones it uses are marked * as having come along, unless they carry a mark of their own. * * With `replace` (a component here from the same entry), that component * takes the entry's new version instead, so every place it is used follows. * Returns the id of the entry's component here and how many were added. */ export function importBundle(project: Project, bundle: LibraryBundle, origin: LibraryOrigin, replace?: string): { root: string; added: number } { const conns = new Map() for (const c of bundle.connectors ?? []) { const have = project.connectors ?? [] const same = have.find(h => (h.id === c.id || h.name.toLowerCase() === c.name.toLowerCase()) && sameLines(h, c)) if (same) { conns.set(c.id, same.id) continue } const copy = clone(c) if (have.some(h => h.id === copy.id)) copy.id = uid('k') const names = new Set(have.map(h => h.name.toLowerCase())) for (let i = 2; names.has(copy.name.toLowerCase()); i++) copy.name = `${c.name} ${i}` project.connectors = [...have, copy] conns.set(c.id, copy.id) } // Components already here, by form. Not challenge attempts, which are // still being worked on, nor anything that contains the one being // replaced, or it would end up inside itself. const forms = new Map() for (const d of project.components) { if (d.challenge || (replace && containsDef(project, d.id, replace))) continue const k = form(d) if (!forms.has(k)) forms.set(k, d.id) } const target = replace ? project.components.find(d => d.id === replace) : undefined const byId = new Map(bundle.components.map(d => [d.id, d])) const ids = new Map() let root = '' let added = 0 for (const d of closure(id => byId.get(id), bundle.root)) { const copy = clone(d) for (const n of copy.nodes) { if (n.kind === 'chip' && n.chip) n.chip = ids.get(n.chip) ?? n.chip if (n.conn) n.conn = conns.get(n.conn) ?? n.conn } if (copy.wide && copy.wide.base !== NAND_BASE) copy.wide.base = ids.get(copy.wide.base) ?? copy.wide.base delete copy.challenge const isRoot = d.id === bundle.root if (isRoot) copy.from = { ...origin } else copy.from ??= { ...origin, inside: true } if (isRoot && target) { const t = target as unknown as Record for (const k of CONTENT) { if (copy[k] === undefined) delete t[k] else t[k] = copy[k] } target.from = copy.from delete target.challenge ids.set(d.id, target.id) root = target.id continue } const same = forms.get(form(copy)) if (same) { ids.set(d.id, same) // The same entry again, unchanged: it now counts as the newer version. const have = project.components.find(x => x.id === same)! if (have.from?.id === copy.from.id && (isRoot ? !have.from.inside : have.from.inside)) have.from = copy.from if (isRoot) root = same continue } copy.id = uid('c') while (project.components.some(x => x.id === copy.id)) copy.id = uid('c') copy.name = uniqueName(project, copy.name) project.components.push(copy) forms.set(form(copy), copy.id) ids.set(d.id, copy.id) added++ if (isRoot) root = copy.id } return { root, added } }