// Host-side package locations. Pure at import: the browser-facing kernel does not discover packages or read files // until its host asks. Architecture, "The catalog: where twins come from"; ADR 0005. import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; function packageName(dir: string): string | undefined { try { return (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { name?: string }).name; } catch { return undefined; } } /** The vendor is published data, independent of its publisher's npm name. No package code is imported. */ export function packVendor(dir: string): string | undefined { const facts = join(dir, 'generated', 'pack-facts.json'); if (existsSync(facts)) { const document = JSON.parse(readFileSync(facts, 'utf8')) as { packs?: Record }; const vendors = Object.keys(document.packs ?? {}); if (vendors.length !== 1 || !/^[a-z][a-z0-9-]*$/.test(vendors[0]!) || document.packs![vendors[0]!]!.protocol?.declared !== '3') throw new Error(`Invalid pack identity in ${facts}`); return vendors[0]; } // Source checkouts predate release facts; their conventional name remains sufficient for development. const match = /^@[^/]+\/twin-([a-z][a-z0-9-]*)$/.exec(packageName(dir) ?? ''); return match?.[1] === 'standard' || match?.[1] === 'catalog' ? undefined : match?.[1]; } /** Nearest installed package wins only over another installation of the SAME package. A World's explicit * package choice wins over a catalog recommendation; different publishers' versions never compete. */ export function installedVendorPacks(from: string, options: { sources?: Readonly>; vendors?: readonly string[] } = {}): Map { const packages = new Map(); const seen = new Set(); const pins = new Map(); const savedPins = new Set(); let at = resolve(from); for (;;) { const config = join(at, '.volter', 'world.json'); if (existsSync(config)) { const document = JSON.parse(readFileSync(config, 'utf8')) as { services?: Array<{ id: string; source?: { package?: string }; package?: string }> }; for (const service of document.services ?? []) { const name = service.source?.package ?? service.package; if (name && !pins.has(service.id)) { pins.set(service.id, name); savedPins.add(service.id); } } } const modules = join(at, 'node_modules'); if (existsSync(modules)) { const directories = readdirSync(modules, { withFileTypes: true }).filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith('.')).flatMap((e) => e.name.startsWith('@') ? readdirSync(join(modules, e.name)).map((n) => join(modules, e.name, n)) : [join(modules, e.name)]); for (const dir of directories) { const name = packageName(dir); if (!name || seen.has(name)) continue; seen.add(name); if (!existsSync(join(dir, 'generated', 'pack-facts.json')) && !/^@[^/]+\/twin-/.test(name)) continue; if (!isDerivedPack(dir)) continue; const vendor = packVendor(dir); if (vendor) packages.set(name, { dir, vendor }); } } const parent = dirname(at); if (parent === at) break; at = parent; } const index = installedPackageDir(from, '@volter/twin-catalog'); const file = index && join(index, 'recommendations.json'); const recommendations = file && existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) as Record : {}; const revokedFile = index && join(index, 'revocations.json'); const revocations = revokedFile && existsSync(revokedFile) ? JSON.parse(readFileSync(revokedFile, 'utf8')) as Array<{ package: string; version: string }> : []; for (const [id, name] of [...pins]) { const vendor = packages.get(name)?.vendor; if (vendor && vendor !== id) { if (pins.has(vendor) && pins.get(vendor) !== name) throw new Error(`${vendor}: a World must select one package implementation`); pins.set(vendor, name); savedPins.add(vendor); } } for (const [vendor, name] of Object.entries(options.sources ?? {})) { const candidate = packages.get(name); if (!candidate) throw new Error(`${vendor}: selected package ${name} is not installed; install its exact release before initializing`); if (candidate.vendor !== vendor) throw new Error(`${vendor}: selected package ${name} declares vendor ${candidate.vendor}`); if (pins.has(vendor) && pins.get(vendor) !== name) throw new Error(`${vendor}: saved World selects ${pins.get(vendor)}; trial ${name} in a separate app directory instead of replacing the saved pin`); pins.set(vendor, name); } const result = new Map(); for (const vendor of new Set([...packages.values()].map((p) => p.vendor))) { if (options.vendors && !options.vendors.includes(vendor)) continue; const candidates = [...packages.entries()].filter(([, p]) => p.vendor === vendor); const selected = pins.get(vendor) ?? recommendations[vendor]; const choice = selected ? candidates.find(([name]) => name === selected) : candidates.length === 1 ? candidates[0] : undefined; if (!choice) throw new Error(`${vendor}: ${selected ? `selected package ${selected} is not installed` : `multiple implementations installed (${candidates.map(([name]) => name).join(', ')})`}; initialize with --source ${vendor}=, or name the chosen source.package in .volter/world.json`); if (!savedPins.has(vendor)) { const version = (JSON.parse(readFileSync(join(choice[1].dir, 'package.json'), 'utf8')) as { version?: string }).version; if (revocations.some((r) => r.package === choice[0] && r.version === version)) throw new Error(`${vendor}: installed ${choice[0]}@${version} is revoked; install an approved release or retain an existing explicit World pin`); } result.set(vendor, choice[1].dir); } return result; } /** Node's nearest installed package, including linked packages and hoisted workspace dependencies. */ export function installedPackageDir(from: string, name: string): string | undefined { let dir = resolve(from); for (;;) { const candidate = join(dir, 'node_modules', ...name.split('/')); if (existsSync(join(candidate, 'package.json'))) return candidate; const up = dirname(dir); if (up === dir) return undefined; dir = up; } } /** The pack repository a World is rooted in, when it is one (ADR 0034: a platform checkout finds no pack repository * beside it; a pack reaches any other World as an installed or linked package). */ export function packRepository(from: string): string | undefined { let dir = resolve(from); for (;;) { if (packageName(dir) === 'twin-packs-p3') return dir; const up = dirname(dir); if (up === dir) return undefined; dir = up; } } /** Resolve one vendor's package directory for host-side reads (assets, infrastructure launchers). */ export function vendorPackageDir(from: string, vendor: string): string | undefined { if (!/^[a-z][a-z0-9-]*$/.test(vendor)) return undefined; const installed = installedVendorPacks(from, { vendors: [vendor] }).get(vendor); const repo = packRepository(from); const checkout = repo === undefined ? undefined : join(repo, vendor); if (!checkout || packageName(checkout) !== `@volter/twin-${vendor}` || !isDerivedPack(checkout)) return installed; if (!installed) return checkout; if (packageName(installed) !== packageName(checkout)) return installed; const major = (dir: string): number => { try { return Number(/^(\d+)/.exec((JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { version?: string }).version ?? '')?.[1] ?? 0); } catch { return 0; } }; return major(installed) > major(checkout) ? installed : checkout; } /** Whether a directory holds a derived pack: a generated surface, its own or a lane's (a vendor whose APIs are all * lanes). A catalog lists no other package as a twin. This is what it is, not its grade. */ export function isDerivedPack(dir: string): boolean { const surface = (unit: string): boolean => existsSync(join(unit, 'src', 'generated', 'surface.gen.json')) || existsSync(join(unit, 'src', 'generated', 'proto.gen.json')); if (surface(dir)) return true; return existsSync(dir) && readdirSync(dir, { withFileTypes: true }).some((entry) => entry.isDirectory() && surface(join(dir, entry.name))); } /** Package identity from a selected module, independent of the checkout's folder name and a service's alias. */ export function vendorOfPackModule(modulePath: string): string | undefined { let dir = dirname(resolve(modulePath)); for (;;) { const name = packageName(dir); if (name !== undefined) return packVendor(dir); const up = dirname(dir); if (up === dir) return undefined; dir = up; } }