import { existsSync, statSync } from 'node:fs'; import { homedir } from 'node:os'; import { isAbsolute, join, resolve } from 'node:path'; import { getConfigPath, loadConfig, machineSettingValue, projectRootDirectories, SHIPPED_PLUGIN_PACKAGE_PREFIX, shippedPluginName, } from '@stim-cli/core/state'; import { holdsMarkers, readProjectPlugin, type ProjectPluginManifest } from '../project-plugin.ts'; import { shippedPluginDir, shippedPluginNames } from '../shipped-plugins.ts'; import { shellQuote } from '../workspace/discovery-report.ts'; import type { ProjectIntegration } from './project-registry.ts'; export const PLUGINS_SETTING = 'plugins'; export interface ProjectPluginEntry { reference: string; dir: string; package: string; version: string; kinds: Record; project: ProjectPluginManifest | null; problem: string | null; } interface Snapshot { configPath: string; configStamp: string; manifestStamps: string[]; entries: readonly ProjectPluginEntry[]; } let snapshot: Snapshot | null = null; function stamp(path: string): string { try { const stat = statSync(path, { throwIfNoEntry: false }); return stat ? `${stat.ino}:${stat.size}:${stat.mtimeMs}` : 'absent'; } catch (error) { return `error:${error instanceof Error && 'code' in error ? String(error.code) : 'unknown'}`; } } function configuredReferences(): unknown[] { try { const { value } = machineSettingValue(PLUGINS_SETTING, { config: loadConfig(), env: {}, }); return Array.isArray(value) ? value : []; } catch { return []; } } interface PluginDir { reference: string; dir: string; shipped: string | null; } function pluginDirs(references: readonly unknown[]): PluginDir[] { return references.flatMap((reference): PluginDir[] => { if (typeof reference !== 'string') return []; const shipped = shippedPluginName(reference); if (shipped !== null) return [{ reference, dir: shippedPluginDir(shipped) ?? '', shipped }]; const expanded = reference === '~' || /^~[\\/]/.test(reference) ? join(homedir(), reference.slice(2)) : reference; return isAbsolute(expanded) ? [{ reference, dir: resolve(expanded), shipped: null }] : []; }); } function shippedList(): string { const names = shippedPluginNames(); return names.length ? names.map((name) => `${SHIPPED_PLUGIN_PACKAGE_PREFIX}${name}, short name ${name}`).join('; ') : 'none'; } function readDirs(dirs: readonly PluginDir[], bundled: ReadonlyMap): ProjectPluginEntry[] { const taken = new Map(bundled); const named = new Map(); return dirs.map(({ reference, dir, shipped }) => { const rejected = (problem: string): ProjectPluginEntry => ({ reference, dir, package: shipped === null ? reference : `${SHIPPED_PLUGIN_PACKAGE_PREFIX}${shipped}`, version: '', kinds: {}, project: null, problem, }); if (shipped !== null && (dir === '' || !existsSync(join(dir, 'package.json')))) return rejected(`This Stim ships no plugin named ${reference}; the plugins it ships are ${shippedList()}`); const earlier = shipped === null ? undefined : named.get(shipped); if (earlier !== undefined) return rejected( `The earlier entry ${earlier} already turns on the plugin ${SHIPPED_PLUGIN_PACKAGE_PREFIX}${shipped}`, ); if (shipped !== null) named.set(shipped, reference); const read = readProjectPlugin(dir, taken); const expected = shipped === null ? null : `${SHIPPED_PLUGIN_PACKAGE_PREFIX}${shipped}`; if (expected !== null && read.declaredPackageName !== null && read.declaredPackageName !== expected) return rejected( `The plugin Stim ships as ${reference} has a package.json named ${read.declaredPackageName}, not ${expected}`, ); if (read.project) taken.set( read.project.id, shipped === null ? `the plugin at ${dir}` : `the plugin ${read.package} shipped with Stim`, ); return { reference, dir, package: read.package, version: read.version, kinds: read.kinds, project: read.project, problem: read.checks.find((check) => check.error !== null)?.error ?? null, }; }); } export function readProjectPlugins( references: readonly unknown[], bundled: ReadonlyMap, ): ProjectPluginEntry[] { return readDirs(pluginDirs(references), bundled); } // @ref LLP 0023#frozen-and-experimental-plugin-kinds -- reread when config.json or a named package.json changes export function projectPlugins(bundled: ReadonlyMap): readonly ProjectPluginEntry[] { const configPath = getConfigPath(); const configStamp = stamp(configPath); if ( snapshot?.configPath === configPath && snapshot.configStamp === configStamp && snapshot.entries.every((entry, index) => stamp(join(entry.dir, 'package.json')) === snapshot?.manifestStamps[index]) ) return snapshot.entries; const dirs = configStamp === 'absent' ? [] : pluginDirs(configuredReferences()); const manifestStamps = dirs.map(({ dir }) => stamp(join(dir, 'package.json'))); const entries = readDirs(dirs, bundled); snapshot = { configPath, configStamp, manifestStamps, entries }; return entries; } type ProjectPluginMatch = ProjectPluginEntry & { project: ProjectPluginManifest }; export function* matchingProjectPlugins( root: string, bundled: ReadonlyMap, fresh = false, ): Generator { const entries = fresh ? readProjectPlugins(configuredReferences(), bundled) : projectPlugins(bundled); for (const entry of entries) { const { project } = entry; if (project && holdsMarkers(root, project)) yield { ...entry, project }; } } export function pluginProjectAt( root: string, bundled: ReadonlyMap, { fresh = false, target }: { fresh?: boolean; target?: 'ios' } = {}, ): ProjectPluginMatch | null { for (const plugin of matchingProjectPlugins(root, bundled, fresh)) { if (!target || plugin.project.targets?.[target]) return plugin; } return null; } export const PLUGIN_PROJECT_ID = 'plugin-project'; /** A plugin shipped with Stim, read from its manifest whether `plugins` names it or not. */ export interface ShippedProjectPlugin { /** The short name `plugins` turns it on by. */ name: string; package: string; project: ProjectPluginManifest; } let shipped: readonly ShippedProjectPlugin[] | null = null; // @ref LLP 0023#project-plugin-manifest-data -- every shipped manifest is read as data, named or not; it reserves no id and loads no module export function shippedProjectPlugins(bundled: ReadonlyMap): readonly ShippedProjectPlugin[] { shipped ??= shippedPluginNames().flatMap((name) => { const dir = shippedPluginDir(name); const project = dir === null ? null : readProjectPlugin(dir, bundled).project; return project ? [{ name, package: `${SHIPPED_PLUGIN_PACKAGE_PREFIX}${name}`, project }] : []; }); return shipped; } /** The shipped plugin `plugins` does not name whose markers `root` holds, first in name order, or null. */ function shippedPluginOff(root: string, bundled: ReadonlyMap): ShippedProjectPlugin | null { const held = shippedProjectPlugins(bundled).filter(({ project }) => holdsMarkers(root, project)); if (!held.length) return null; const named = new Set( configuredReferences().flatMap((reference) => typeof reference === 'string' ? [shippedPluginName(reference)] : [], ), ); return held.find(({ name }) => !named.has(name)) ?? null; } // @ref LLP 0023#project-plugin-manifest-data -- a folder of a shipped plugin that is off refuses with the command that turns it on /** * Why no project was found from `startDir` when it or a folder above it holds every marker of a plugin Stim ships that * `plugins` does not name, with the command that turns it on; null when none does. It reads manifests only. */ export function shippedPluginOffRefusal( startDir: string, bundled: ReadonlyMap, ): { message: string; remedy: string } | null { for (const root of projectRootDirectories(startDir)) { const refusal = shippedPluginOffAt(root, bundled); if (refusal) return refusal; } return null; } /** `shippedPluginOffRefusal` for the folder `root` alone. */ export function shippedPluginOffAt( root: string, bundled: ReadonlyMap, ): { message: string; remedy: string } | null { const off = shippedPluginOff(root, bundled); if (!off) return null; const references = [...configuredReferences().filter((reference) => typeof reference === 'string'), off.name]; return { message: `${root} is ${/^[aeiou]/i.test(off.project.name) ? 'an' : 'a'} ${off.project.name} project, which the plugin ${off.package} shipped with Stim serves, and that plugin is not turned on.`, remedy: `Turn it on with stim settings set plugins ${shellQuote(JSON.stringify(references))} --scope machine, then run this again.`, }; } // @ref LLP 0023#frozen-and-experimental-plugin-kinds -- a match serves only a declared target and yields it to a bundled integration export function pluginProjectIntegration(bundled: () => ReadonlyMap): ProjectIntegration { return { id: PLUGIN_PROJECT_ID, inspect(root, lexicalStart = root) { let plugin: ProjectPluginMatch | undefined; const ios = pluginProjectAt(root, bundled(), { target: 'ios' }) ?? undefined; let androidMatch: ProjectPluginMatch | undefined; let recognizesWithoutModule = false; for (const match of matchingProjectPlugins(root, bundled())) { plugin ??= match; const { targets } = match.project; if (!targets?.ios || targets.android) androidMatch ??= match; if (!targets?.ios) recognizesWithoutModule = true; if (ios && recognizesWithoutModule) break; } if (!plugin) { // @ref LLP 0023#project-plugin-manifest-data -- a folder of a shipped plugin that is off refuses with the command that turns it on const off = shippedPluginOffAt(root, bundled()); return off ? { root: false, application: false, stops: true, platforms: () => [], validate: (operation) => operation === 'ios' || operation === 'android' || operation === 'dev-server' ? { kind: 'not-an-app', ...off } : undefined, } : null; } const android = androidMatch?.project.targets?.android; const served = [...(ios ? (['ios'] as const) : []), ...(android ? (['android'] as const) : [])]; const problemFor = (match: ProjectPluginMatch) => { const { name, targets } = match.project; const primary = [...(targets?.ios ? ['ios'] : []), ...(targets?.android ? ['android'] : [])]; const only = primary.map((platform) => (platform === 'ios' ? 'iOS' : 'Android')).join(' and '); return { kind: 'not-an-app' as const, ...(primary.length ? { message: `The plugin ${match.package} builds the ${name} project at ${root} for ${only} only.`, remedy: `Run ${primary.map((platform) => `stim ${platform}`).join(' or ')} to build and run it on this workspace's ${primary.map((platform) => (platform === 'ios' ? 'simulator' : 'emulator')).join(' or ')}. Use ${name}'s own tools for anything else.`, } : { message: `The plugin ${match.package} recognises ${root} as a ${name} project and adds no build or run for it.`, remedy: `Build and run the ${name} project with ${name}'s own tools. stim worktree add, list and remove manage worktrees of this folder.`, }), }; }; return { root: 'explicit', application: true, yields: true, platforms: () => [...served], validate: (operation) => (operation === 'ios' || operation === 'android') && served.includes(operation) ? null : problemFor(operation === 'android' ? (androidMatch ?? plugin) : plugin), // @ref LLP 0023#frozen-and-experimental-plugin-kinds -- the module is imported only once the registry selected this match for this root ...(ios ? { iosModulePackage: ios.package, recognizesWithoutIos: androidMatch !== undefined, recognizesWithoutModule, ios: async (_settings, scope) => { const [{ loadPluginIos }, { pluginIosProject }] = await Promise.all([ import('./plugin-module.ts'), import('./plugin-ios.ts'), ]); return pluginIosProject(root, await loadPluginIos(ios, root, scope, lexicalStart), scope); }, doctor: async (operations) => { if (!operations?.includes('ios')) return { inspect: () => [] }; return (await import('./plugin-module.ts')).pluginIosDoctorFor(ios, root, lexicalStart); }, } : {}), ...(androidMatch && android ? { android: async () => (await import('./plugin-android.ts')).pluginAndroidProject( root, { name: androidMatch.project.name, package: androidMatch.package, dir: androidMatch.dir }, android, ), } : {}), }; }, }; }