import { existsSync } from 'node:fs'; import { join } from 'node:path'; import { installedPackageDir } from './installed-package'; import { declaredContributions, type ProductDeclaration, readVolterManifest } from './volter-manifest'; export const PRODUCT_DECLARATION_KEY = 'contributes.volter.product'; /** Light or dark — the two the workbench's own `ColorScheme` has plain names * for, and the only two a product needs to state (a high-contrast scheme is a * person's accessibility choice, never a product's declaration). */ export type ProductColorTheme = 'dark' | 'light'; export interface ProductWorkbench { /** The GitHub Release tag on `volter-ai/code-oss`. */ readonly release: string; /** The sha256 of that release's tarball asset, hex. */ readonly tarballSha256: string; } /** A product package, as everything outside it needs to know it. */ export interface ProductIdentity { readonly name: string; /** Its version, reported beside the workbench by the editor's `status` command. */ readonly version: string; readonly command: string; /** The name a person sees — `contributes.volter.product.displayName`. */ readonly displayName: string; /** * `contributes.volter.product.upgrade: true` — its command has `upgrade [version]` * (the product CLI's own), so a pinned-engine refusal * may tell a person to run it. Optional: a product that says nothing has none. */ readonly upgrade?: boolean; /** * `contributes.volter.product.adapterRequired: true` — a project this product opens must have its own * adapter module (`editor/volter.adapter.ts`), because the product's layout and document * finders are declared there and the native default shows none of them. Such a product refuses * a project without one. Optional: a product that says nothing opens it on the native default. */ readonly adapterRequired?: boolean; /** Its package root, absolute. */ readonly dir: string; /** * Its ONE source entry, package-relative and POSIX (`./src/index.ts`). That * entry IS the product's frame entry: it composes and re-exports `mountVolter`, * which is the name the fork's contribution reads off the served module. */ readonly entry: string; /** * The packages this product mounts, in order — `contributes.volter.product.composes`. The ONE statement of * the composition: the session reads it here for the packages it installs and serves, the catalog and the * serving doors. */ readonly composes: readonly string[]; readonly colorTheme: ProductColorTheme; /** WHICH WORKBENCH THIS PRODUCT IS — see {@link ProductWorkbench}. */ readonly workbench: ProductWorkbench | null; /** * The ONE LINE that installs this product and starts a project in it — * `contributes.volter.product.install` (`npx create my-project`). A limited view quotes * it wherever it cannot do what the local editor does (its agent answers with it, and every * route it does not carry names it), so it is a declaration read without running the product. * An undeclared one is `npx create my-project`, which is what every product's `create` * verb accepts. */ readonly install: string; } /** What a project without a product is told to add: the declaration this module reads, naming no package. */ export const PRODUCT_DECLARATION_HINT = `a product package as a dev dependency: one whose package.json declares \`${PRODUCT_DECLARATION_KEY}\``; const PRODUCT_COLOR_THEMES: readonly ProductColorTheme[] = ['dark', 'light']; /** * Read one product package's declaration, or `null` when the manifest is not a * product's. Throws when it declares `contributes.volter.product` and the declaration is * unusable — a half-written product must be named, never skipped. */ export function readProductManifest(packageDir: string): ProductIdentity | null { const manifestPath = join(packageDir, 'package.json'); const manifest = readVolterManifest(manifestPath); const declared = manifest?.product; if (manifest === null || declared === undefined) return null; const entry = declared.entry; if (typeof entry !== 'string' || !entry.startsWith('./')) throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY} but its "entry" is ` + `${JSON.stringify(entry)}. It must be a ./-relative module — the product's ONE source ` + 'entry, which is also its frame entry (e.g. "./src/index.ts").', ); const resolved = join(packageDir, entry); if (!existsSync(resolved)) throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY}.entry ${JSON.stringify(entry)}, ` + `which does not exist (${resolved}).`, ); const colorTheme = declared.colorTheme; // REQUIRED, like `entry`, and for the same reason: a product that does not // say which way round it paints gets the workbench's web default, which is // LIGHT, and its cover is white until its real theme loads. There is no // defensible default to invent here — a dark product and a light product are // both ordinary — so an unstated one is named rather than guessed. if (typeof colorTheme !== 'string' || !PRODUCT_COLOR_THEMES.includes(colorTheme as never)) throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY} but its "colorTheme" is ` + `${JSON.stringify(colorTheme)}. It must be ${PRODUCT_COLOR_THEMES.map((one) => JSON.stringify(one), ).join(' or ')} — which way round this product paints, read before any of its code ` + "runs so the workbench's first frame is already the product's own background.", ); // REQUIRED, for the same reason as `entry`: the kit names verbs in every // message it writes, and there is no command to name but the product's own. const composes = productComposes(manifestPath, declared); const bin = manifest.bin; const commands = bin !== null && typeof bin === 'object' ? Object.keys(bin) : []; if (commands.length !== 1) throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY} but its "bin" names ` + `${commands.length === 0 ? 'no command' : `${commands.length} commands`}. A product has ` + 'exactly one command — the one every session message tells a person to run.', ); const displayName = declared.displayName; if (typeof displayName !== 'string' || displayName.trim() === '') throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY} but its "displayName" is ` + `${JSON.stringify(displayName)}. It must be the name a person sees (e.g. "Volter Editor").`, ); const name = manifest.name ?? packageDir; const install = declared.install; if (install !== undefined && (typeof install !== 'string' || install.trim() === '')) throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY} but its "install" is ` + `${JSON.stringify(install)}. It is the one line that installs this product and starts a ` + `project (e.g. "npx ${name} create my-project"), or absent.`, ); return { name, version: manifest.version ?? 'unknown', command: commands[0]!, displayName, upgrade: declared.upgrade === true, adapterRequired: declared.adapterRequired === true, dir: packageDir, entry, composes, colorTheme: colorTheme as ProductColorTheme, // A private source product may use an explicitly selected matching checkout. // Public packages must always carry a downloadable, checksummed workbench. workbench: manifest.private && declared.workbench === undefined ? null : readProductWorkbench(manifestPath, declared.workbench), install: typeof install === 'string' ? install.trim() : `npx ${name} create my-project`, }; } /** A product declaration's `composes`, checked: the packages it mounts, by name, in order. The * build's composition module and the session read it through this one check. */ export function productComposes(manifestPath: string, declared: ProductDeclaration): string[] { const composes = declared.composes; if (!Array.isArray(composes) || composes.some((name) => typeof name !== 'string' || name === '')) throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY} but its "composes" is ` + `${JSON.stringify(composes)}. It must list the packages this product mounts, by name ` + '(e.g. [""]); each is a dependency of the product package.', ); return composes as string[]; } /** The sha256 a release pins its tarball with, as `BUILD.json` writes it. */ const SHA256_HEX = /^[0-9a-f]{64}$/; /** * REQUIRED, like `entry` and `colorTheme`, and for the sharpest reason of all * three of them: a product that does not say which workbench it is cannot be INSTALLED * — `npx @volter/ create ` on a machine with nothing else on it * has no other way to find the bytes it runs in, and the person is left writing * a path to a directory they would have to build first. There is no default to * invent (the tag names a fork commit nobody can guess), so an unstated one is * named rather than guessed. */ function readProductWorkbench(manifestPath: string, declared: unknown): ProductWorkbench { const example = ' "contributes": { "volter": { "product": { "workbench": { "release": "--", ' + '"tarballSha256": "<64 hex>" } } } }\n' + '`node scripts/workbench/build-release.mjs --publish --out ` cuts the release ' + 'and prints exactly that block.'; if (typeof declared !== 'object' || declared === null || Array.isArray(declared)) throw new Error( `${manifestPath} declares ${PRODUCT_DECLARATION_KEY} but its "workbench" is ` + `${JSON.stringify(declared)}. A product IS the Code-OSS workbench it was compiled into, ` + `so it names the published release those bytes are:\n${example}`, ); const platforms = declared as Record; if (!('release' in platforms) && !('tarballSha256' in platforms)) { const machine = `${process.platform}-${process.arch}`; const declaredHere = platforms[machine]; if (declaredHere === undefined) throw new Error( `${manifestPath}'s ${PRODUCT_DECLARATION_KEY}.workbench declares releases for ` + `${Object.keys(platforms).join(', ') || 'no platform'} and this machine is ${machine}. A ` + "Code-OSS server package carries its own platform's node binary and native modules, so " + `there is nothing this product can run in here until a ${machine} release is cut:\n` + ` node scripts/workbench/build-release.mjs --product --platform ${machine} --checkout --publish`, ); return readPlatformWorkbench(manifestPath, declaredHere, example); } return readPlatformWorkbench(manifestPath, declared, example); } function readPlatformWorkbench(manifestPath: string, declared: unknown, example: string): ProductWorkbench { if (typeof declared !== 'object' || declared === null || Array.isArray(declared)) throw new Error( `${manifestPath}'s ${PRODUCT_DECLARATION_KEY}.workbench names ${JSON.stringify(declared)} ` + `for this platform, which is not a release:\n${example}`, ); const record = declared as Record; const extra = Object.keys(record).filter((key) => key !== 'release' && key !== 'tarballSha256'); if (extra.length > 0) throw new Error( `${manifestPath}'s ${PRODUCT_DECLARATION_KEY}.workbench carries ` + `${extra.map((key) => `"${key}"`).join(', ')}, which this declaration has no meaning for. ` + `It names the release and the pin, and nothing else:\n${example}`, ); const release = record['release']; if (typeof release !== 'string' || release.trim() === '') throw new Error( `${manifestPath}'s ${PRODUCT_DECLARATION_KEY}.workbench names no "release" — the GitHub ` + `Release tag its workbench was published under:\n${example}`, ); const tarballSha256 = record['tarballSha256']; if (typeof tarballSha256 !== 'string' || !SHA256_HEX.test(tarballSha256)) throw new Error( `${manifestPath}'s ${PRODUCT_DECLARATION_KEY}.workbench has tarballSha256 ` + `${JSON.stringify(tarballSha256)}, which is not 64 hex characters. It is the PIN — the ` + 'hash the downloaded tarball is checked against before a byte of it is extracted, so it ' + `is never approximate:\n${example}`, ); return { release, tarballSha256 }; } /** * A product's SHORT id — `@/` → ``. * * It is the product's own `product({ id })`, the directory its workbench half * lives in (`packages//workbench`), the `--product` flag the overlay and the * release build take, and what a release records in `BUILD.json`. One derivation * rather than four literals: the package name is the only place the product is * NAMED, and everything else is that name's last segment. */ export function workbenchProductId(packageName: string): string { return packageName.split('/').pop() ?? packageName; } /** A product's entry as a path relative to `fromDir`, POSIX — the spelling a * Vite manifest key and a dev-server URL both use. */ export function productEntryPath(product: ProductIdentity, fromDir: string): string { const absolute = join(product.dir, product.entry); const prefix = fromDir.endsWith('/') ? fromDir : `${fromDir}/`; const relative = absolute.startsWith(prefix) ? absolute.slice(prefix.length) : absolute; return relative.split('\\').join('/'); } /** Every `@volter/*` this project declares, in either section, sorted. */ function declaredVolterPackages(projectRoot: string): string[] { const manifest = readVolterManifest(join(projectRoot, 'package.json')); return (manifest?.dependencyNames ?? []).filter((name) => name.startsWith('@volter/')).sort(); } /** * The packages `product` mounts that are installed and contribute: its `contributes.volter.product.composes`, * each resolved from the product's own directory and kept when its manifest declares * a `contributes.volter` object (its serving half, `contributes.volter.serving`, may be all a package contributes). */ export function productComposedPackages(product: ProductIdentity): string[] { return product.composes.filter((name) => { const dir = installedPackageDir(product.dir, name); if (dir === null) return false; const manifest = readVolterManifest(join(dir, 'package.json')); return declaredContributions(manifest) !== null; }); } /** The products this project declares AND resolves, in declaration order. */ export function declaredProducts(projectRoot: string): ProductIdentity[] { const found: ProductIdentity[] = []; for (const name of declaredVolterPackages(projectRoot)) { const dir = installedPackageDir(projectRoot, name); if (dir === null) continue; const product = readProductManifest(dir); if (product !== null) found.push(product); } return found; } /** * THE product this project opens in, or a throw naming what is wrong. * * The refusals are the whole point: a project with none and a project with two * are both states a person can be in, and neither has an answer this code may * invent. */ export function resolveProductForProject(projectRoot: string): ProductIdentity { const products = declaredProducts(projectRoot); if (products.length === 1) return products[0] as ProductIdentity; if (products.length === 0) throw new Error( `${projectRoot} declares no editor product, so there is no editor to open it in.\n` + 'The installed product supplies the editor,\n' + 'and which one runs is what the project installed, never a flag.\n' + `For THIS folder, install ${PRODUCT_DECLARATION_HINT},\n` + "then run that product's `edit` command again. For a NEW project, the product's own `create` verb makes it.", ); throw new Error( `${projectRoot} declares ${products.length} editor products — ` + `${products.map((product) => product.name).join(' and ')}.\n` + 'One page runs one product, and nothing here may choose between them. Remove the one you\n' + 'are not building with:\n' + products.map((product) => ` npm uninstall ${product.name}`).join('\n'), ); }