// `lecodes plugin gen`: the contracts under a path → their generated files. A plugin is a directory // with a `contract.d.ts`; the path is one plugin, or a repo that keeps them in `plugins//`. // Generated files are written beside the hand-written ones of the place they travel to // (`sdk/.gen.ts`, `ios/.gen.swift`, `android/…/.gen.kt`, `web/.gen.ts`; a host // node's native files are `Node.gen.*`, its web half is in the plugin's `web/.gen.ts`) and are // committed — `check` is what CI runs. A REPO of plugins also gets its `Package.swift` (the iOS // halves as one SwiftPM package, emitPackage.ts) from the manifests. import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs" import { createRequire } from "node:module" import { basename, join, relative, resolve, sep } from "node:path" import type tsModule from "typescript" import { CliError } from "../cli" import { ContractError, readContract, type Contract } from "./contract" import { emitKotlin } from "./emitKotlin" import { EmitError, emitSdk } from "./emitSdk" import { emitSwift } from "./emitSwift" import { emitWeb } from "./emitWeb" import { lower } from "./lower" import { CONTRACT_FILE, MANIFEST_FILE, ManifestError, readManifestIfAny, type PluginManifest } from "./manifest" import { firstPartyContractFile, firstPartyContractText } from "./firstParty" import { missingDeclarations, usesFeatures, usesPermissions, type PermissionKind } from "./permissions" import { DEFAULT_SDK_PATH, PACKAGE_FILE, PackageError, emitPackageSwift } from "./emitPackage" // A path as the report shows it: relative to `from`, with `/` on every platform (a report is // compared and pasted; `\` is Windows' own). const shown = (from: string, to: string): string => relative(from, to).split(sep).join("/") export { CONTRACT_FILE } export type PluginDir = { id: string, dir: string } /** The first-party plugin a folder's manifest says it implements (a project's half folder), or null. * Read loosely: what the manifest holds is readManifest's to say. */ const implementsOf = (dir: string): string | null => { try { const raw = JSON.parse(readFileSync(join(dir, MANIFEST_FILE), "utf8").replace(/^/, "")) as { implements?: unknown } return typeof raw.implements === "string" ? raw.implements : null } catch { return null } } /** A plugin's folder: one with its contract, or a half folder that implements a first-party one's. */ const isPluginDir = (dir: string): boolean => existsSync(join(dir, CONTRACT_FILE)) || implementsOf(dir) !== null /** The plugins under `path`: itself when it is one, else every `plugins//` that is. */ export const findPlugins = (path: string): PluginDir[] => { const root = resolve(path) if (isPluginDir(root)) return [{ id: basename(root), dir: root }] const holder = join(root, "plugins") if (!existsSync(holder)) return [] return readdirSync(holder).sort() .map(id => ({ id, dir: join(holder, id) })) .filter(p => statSync(p.dir).isDirectory() && isPluginDir(p.dir)) } /** A contract is read with the `typescript` package (5.x: 6 is ESM-only and `require` gets a stub * without `createSourceFile`): the plugin's own (looked up from its directory upwards), else the * one next to the CLI's install — a dependency of lecodes-cli after 2.4.9, so a bun / npm install * of the CLI brings it; the standalone binaries carry none and read the plugin's. */ export const loadTypescript = (dir: string): typeof tsModule => { for (const from of [join(dir, "package.json"), import.meta.url]) { try { const mod = createRequire(from)("typescript") const ts = mod?.createSourceFile ? mod : mod?.default // a runtime may hand the namespace over if (ts?.createSourceFile) return ts } catch { /* the next place */ } } throw new CliError(`Reading a contract needs the typescript package 5.x — next to the CLI (bun add -g "typescript@^5.8.3" for a bun-installed lecodes-cli) or in the plugin's repo (npm install --save-dev "typescript@^5.8.3"); TypeScript 6 is not read`) } export type Generated = { file: string, text: string } /** Everything one plugin's contract generates, as `path → text`. Throws ContractError / EmitError / * ManifestError. A half folder (`implements`) is generated from the contract of the plugin it * implements, the SDK's copy (firstParty.ts), and under that plugin's id: `web/ar.gen.ts` registers * the service "ar"; it has no sdk/ — the app's side is the SDK's wrapper. */ export const generatePlugin = (ts: typeof tsModule, plugin: PluginDir): { contract: Contract, manifest: PluginManifest | null, files: Generated[] } => { // The manifest is held to the folders the plugin has: a half the manifest does not name is built // into no host. const manifest = readManifestIfAny(plugin.dir, plugin.id) const implemented = manifest?.implements const file = implemented ? firstPartyContractFile(implemented)! : join(plugin.dir, CONTRACT_FILE) const contract = readContract(ts, file, implemented ? firstPartyContractText(file) : readFileSync(file, "utf8")) checkPermissions(plugin, contract, manifest) const id = implemented ?? plugin.id const handWritten = existsSync(join(plugin.dir, "sdk", `${id}.ts`)) const single = contract.channels.length === 1 const files: Generated[] = implemented ? [] : contract.channels.map(channel => ({ // One channel is the rule; a contract with several names each file after its channel. file: join(plugin.dir, "sdk", single ? `${id}.gen.ts` : `${id}.${channel.iface}.gen.ts`), text: emitSdk(contract, channel, { id, handWritten }), })) // A platform's file is generated where its FOLDER exists: the plugin says which platforms it has // by having them. One native file per plugin, named after its one channel (a host node's with the // `Node` its generated names carry), or after the first of several. const first = contract.channels[0]! const nativeName = single ? (first.node ? `${first.iface}Node` : first.iface) : first.iface + "Plugin" if (existsSync(join(plugin.dir, "ios"))) { files.push({ file: join(plugin.dir, "ios", `${nativeName}.gen.swift`), text: emitSwift(lower(contract), { id }) }) } if (existsSync(join(plugin.dir, "android"))) { const pkg = kotlinPackage(join(plugin.dir, "android"), manifest?.android?.register) files.push({ file: join(pkg.dir, `${nativeName}.gen.kt`), text: emitKotlin(lower(contract), { id, package: pkg.name }) }) } if (existsSync(join(plugin.dir, "web"))) { // Every channel's, host nodes included (Web Lite's `hostnode` feature holds a node's half; the // web player and headless draw a host node as an empty box: they register none). files.push({ file: join(plugin.dir, "web", `${id}.gen.ts`), text: emitWeb(lower(contract), { id }) }) const foreign = hostImports(join(plugin.dir, "web")) if (foreign.length) throw new EmitError(`web/ imports the host — a web half depends on its generated file, the document it is handed and the browser:\n${foreign.map(f => ` ${f}`).join("\n")}`) } return { contract, manifest, files } } /** The declarations the contract's `@permission` kinds need, held against the plugin's manifests: * the usage strings of ios.infoPlist (a missing one crashes the app at the prompt), the * `` elements of android/src/main/AndroidManifest.xml (a missing one is a * silent refusal) and the `` of each feature those * permissions imply (a missing one makes Play require the hardware). Checked where the plugin has * the half; a plugin without a manifest (a project's own, the shell declares for it) is not held. */ const checkPermissions = (plugin: PluginDir, contract: Contract, manifest: PluginManifest | null): void => { if (!manifest) return const kinds: PermissionKind[] = [] for (const ch of contract.channels) for (const m of ch.methods) for (const k of m.permissions) if (!kinds.includes(k)) kinds.push(k) if (kinds.length === 0) return const androidManifest = join(plugin.dir, "android", "src", "main", "AndroidManifest.xml") const androidXml = manifest.android ? (existsSync(androidManifest) ? readFileSync(androidManifest, "utf8") : "") : null const missing = missingDeclarations(kinds, manifest.ios ? manifest.ios.infoPlist ?? {} : null, androidXml === null ? null : usesPermissions(androidXml), androidXml === null ? null : usesFeatures(androidXml)) const problems: string[] = [] if (missing.infoPlist.length) problems.push(`ios.infoPlist: the contract's @permission needs ${missing.infoPlist.join(", ")} — the usage string the dialog shows`) if (missing.android.length) problems.push(`android/src/main/AndroidManifest.xml: the contract's @permission needs for ${missing.android.join(", ")}`) if (missing.androidFeatures.length) problems.push(`android/src/main/AndroidManifest.xml: the contract's @permission implies for ${missing.androidFeatures.join(", ")} — without it Play requires the hardware`) if (problems.length) throw new ManifestError(join(plugin.dir, MANIFEST_FILE), problems) } /** The imports of a web half that name a LeCodes package (`lecodes-sdk`, `lecodes-web-shared`, …), as * `file:line: the import`. A half that imports its host runs on that host only. */ export const hostImports = (web: string): string[] => { const found: string[] = [] const walk = (dir: string): void => { for (const entry of readdirSync(dir).sort()) { const path = join(dir, entry) if (statSync(path).isDirectory()) { if (entry !== "node_modules" && entry !== "dist") walk(path); continue } if (!/\.(ts|tsx|js|mjs)$/.test(entry)) continue readFileSync(path, "utf8").split("\n").forEach((line, i) => { const m = /(?:from\s+|import\s*\(\s*|import\s+)["'](lecodes-[^"']*)["']/.exec(line) if (m && !/^\s*\/\//.test(line)) found.push(`${shown(join(web, ".."), path)}:${i + 1}: ${m[1]}`) }) } } walk(web) return found } /** Where a plugin's Kotlin lives: `android/` is laid out as a Gradle module (its manifest and * resources travel with the sources), and the generated file is a file of the plugin's PACKAGE — * the package of the type that registers the half (the manifest's `android.register`, which is * also the module's namespace), when its folder is there; else the one folder under * `src/main/java` that the path narrows down to (a plugin with no manifest yet). A half may hold * other packages beside its own (a vendored library's JNI class): they do not move the file. */ export const kotlinPackage = (android: string, register?: string): { dir: string, name: string } => { const root = join(android, "src", "main", "java") if (register) { const name = register.split(".").slice(0, -1).join(".") const dir = join(root, ...name.split(".")) if (name && existsSync(dir)) return { dir, name } } let dir = root while (existsSync(dir)) { const entries = readdirSync(dir).filter(e => !e.startsWith(".")) const dirs = entries.filter(e => statSync(join(dir, e)).isDirectory()) if (dirs.length !== 1 || entries.length !== 1) break dir = join(dir, dirs[0]!) } if (dir === root) { throw new EmitError(`android/ has no package yet — make the folder of the plugin's Kotlin package (android/src/main/java/com/example/plugin), the generated file is written into it`) } return { dir, name: relative(root, dir).split(/[\\/]/).join(".") } } /** The SDK package's path the repo names for its Package.swift: `lecodes.iosSdkPath` of the repo's * package.json (the first-party repo, a submodule of core, says `../apple/lecodes`); else the default. */ export const repoSdkPath = (root: string): string => { const file = join(root, "package.json") if (!existsSync(file)) return DEFAULT_SDK_PATH try { const pkg = JSON.parse(readFileSync(file, "utf8")) as { lecodes?: { iosSdkPath?: unknown } } const path = pkg.lecodes?.iosSdkPath if (path !== undefined && typeof path !== "string") throw new PackageError(`package.json lecodes.iosSdkPath: a path, as a string`) return path ?? DEFAULT_SDK_PATH } catch (e) { if (e instanceof PackageError) throw e throw new PackageError(`package.json does not parse: ${e instanceof Error ? e.message : String(e)}`) } } export type GenReport = { /** `implements`: a half folder's first-party plugin, whose contract it was generated from. */ plugins: { id: string, implements?: string, contract: Contract, written: string[], stale: string[], fresh: string[] }[] /** The repo's own files (its Package.swift), when the path is a repo of plugins. */ repo: { written: string[], stale: string[], fresh: string[] } /** Contracts that did not read or emit, as printable text. */ failures: string[] } /** Generate (or, with `check`, compare) every plugin under `path`. Paths in the report are relative * to `path`. A failed contract does not stop the others. */ export const generate = (path: string, opts: { check?: boolean } = {}): GenReport => { const plugins = findPlugins(path) if (plugins.length === 0) throw new CliError(`No plugin under ${resolve(path)}: a plugin is a directory with a ${CONTRACT_FILE}, or a half folder whose ${MANIFEST_FILE} says what it \`implements\` (one, or plugins// of a repo or a project).`) const ts = loadTypescript(plugins[0]!.dir) const root = resolve(path) const report: GenReport = { plugins: [], repo: { written: [], stale: [], fresh: [] }, failures: [] } const place = (f: Generated, entry: { written: string[], stale: string[], fresh: string[] }): void => { const name = shown(root, f.file) || basename(f.file) const current = existsSync(f.file) ? readFileSync(f.file, "utf8") : null if (current === f.text) { entry.fresh.push(name); return } if (opts.check) { entry.stale.push(name); return } mkdirSync(join(f.file, ".."), { recursive: true }) writeFileSync(f.file, f.text) entry.written.push(name) } const manifests: { id: string, manifest: PluginManifest }[] = [] for (const plugin of plugins) { try { const { contract, manifest, files } = generatePlugin(ts, plugin) if (manifest) manifests.push({ id: plugin.id, manifest }) const entry = { id: plugin.id, implements: manifest?.implements, contract, written: [] as string[], stale: [] as string[], fresh: [] as string[] } for (const f of files) place(f, entry) report.plugins.push(entry) } catch (e) { if (e instanceof ContractError) report.failures.push(e.problems.map(p => `${shown(root, e.file) || e.file}:${p.line}: ${p.message}`).join("\n")) else if (e instanceof EmitError) report.failures.push(`${shown(root, join(plugin.dir, CONTRACT_FILE))}: ${e.message}`) else if (e instanceof ManifestError) report.failures.push(`${shown(root, e.file) || e.file}:\n${e.problems.map(p => ` ${p}`).join("\n")}`) else throw e } } // A repo of plugins (not one plugin): its Package.swift, from every manifest that read. Written // only when every contract made it — a repo with a broken plugin keeps the package it has — and // only when one has an iOS half: a project whose plugins are web halves has no package to make. const isRepo = !(plugins.length === 1 && plugins[0]!.dir === root) if (isRepo && report.failures.length === 0 && manifests.some(m => m.manifest.ios !== null)) { try { place({ file: join(root, PACKAGE_FILE), text: emitPackageSwift(manifests, repoSdkPath(root)) }, report.repo) } catch (e) { if (e instanceof PackageError) report.failures.push(`${PACKAGE_FILE}: ${e.message}`) else throw e } } return report }