Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@codama/cli

Package Overview
Dependencies
Maintainers
1
Versions
36
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@codama/cli - npm Package Compare versions

Comparing version
1.1.4
to
1.2.0
+17
-7
dist/cli.cjs

@@ -224,7 +224,9 @@ "use strict";

function setInitCommand(program2) {
program2.command("init").argument("[output]", "Optional path used to output the configuration file").option("-d, --default", "Bypass prompts and select all defaults options").option("--js", "Forces the output to be a JavaScript file").action(doInit);
program2.command("init").argument("[output]", "Optional path used to output the configuration file").option("-d, --default", "Bypass prompts and select all defaults options").option("--js", "Forces the output to be a JavaScript file").option("--gill", "Forces the output to be a gill based JavaScript file").action(doInit);
}
async function doInit(explicitOutput, options) {
const output = getOutputPath(explicitOutput, options);
const useJsFile = options.js || output.endsWith(".js");
let configFileType = output.endsWith(".js") ? "js" : "json";
if (options.gill) configFileType = "gill";
else if (options.js) configFileType = "js";
if (await canRead(output)) {

@@ -235,3 +237,3 @@ throw new Error(`Configuration file already exists at "${output}".`);

const result = await getPromptResult(options);
const content = getContentFromPromptResult(result, useJsFile);
const content = getContentFromPromptResult(result, configFileType);
await writeFile(output, content);

@@ -244,3 +246,3 @@ logSuccess(`Configuration file created at "${output}".`);

}
return resolveRelativePath(options.js ? "codama.js" : "codama.json");
return resolveRelativePath(options.js || options.gill ? "codama.js" : "codama.json");
}

@@ -307,3 +309,3 @@ async function getPromptResult(options) {

}
function getContentFromPromptResult(result, useJsFile) {
function getContentFromPromptResult(result, configFileType) {
const scripts = {};

@@ -323,4 +325,12 @@ if (result.scripts.includes("js")) {

const content = { idl: result.idlPath, before: [], scripts };
if (!useJsFile) {
if (configFileType == "json") {
return JSON.stringify(content, null, 4);
} else if (configFileType == "gill") {
return `import { createCodamaConfig } from "gill";
export default createCodamaConfig({
idl: "${result.idlPath}",
clientJs: "${result.jsPath}",
` + result.scripts.includes("rust") ? `clientRust: "${result.rustPath}",
` : `});`;
}

@@ -461,3 +471,3 @@ return "export default " + JSON.stringify(content, null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'");

function createProgram(internalOptions) {
const program2 = (0, import_commander.createCommand)().version("1.1.4").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });
const program2 = (0, import_commander.createCommand)().version("1.2.0").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });
setProgramOptions(program2);

@@ -464,0 +474,0 @@ setInitCommand(program2);

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/cli/index.ts","../src/program.ts","../src/commands/init.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/nodes.ts","../src/utils/promises.ts","../src/utils/visitors.ts","../src/commands/run.ts","../src/config.ts","../src/parsedConfig.ts","../src/programOptions.ts"],"sourcesContent":["import { createProgram } from '../program';\nimport { logDebug, logError } from '../utils';\n\nconst program = createProgram();\n\nexport async function run(argv: readonly string[]) {\n try {\n await program.parseAsync(argv);\n } catch (err) {\n if (program.opts().debug) {\n logDebug(`${(err as { stack: string }).stack}`);\n }\n logError((err as { message: string }).message);\n process.exitCode = 1;\n }\n}\n","import { Command, createCommand } from 'commander';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n await createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n }).parseAsync(args, { from: 'user' });\n}\n\nexport function createProgram(internalOptions?: { exitOverride?: boolean; suppressOutput?: boolean }): Command {\n const program = createCommand()\n .version(__VERSION__)\n .allowExcessArguments(false)\n .configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });\n\n // Set program options and commands.\n setProgramOptions(program);\n setInitCommand(program);\n setRunCommand(program);\n\n // Internal options.\n if (internalOptions?.exitOverride) {\n program.exitOverride();\n }\n if (internalOptions?.suppressOutput) {\n program.configureOutput({\n writeErr: () => {},\n writeOut: () => {},\n });\n }\n\n return program;\n}\n","import { Command } from 'commander';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport { canRead, logBanner, logSuccess, resolveRelativePath, writeFile } from '../utils';\n\nexport function setInitCommand(program: Command): void {\n program\n .command('init')\n .argument('[output]', 'Optional path used to output the configuration file')\n .option('-d, --default', 'Bypass prompts and select all defaults options')\n .option('--js', 'Forces the output to be a JavaScript file')\n .action(doInit);\n}\n\ntype InitOptions = {\n default?: boolean;\n js?: boolean;\n};\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n const useJsFile = options.js || output.endsWith('.js');\n if (await canRead(output)) {\n throw new Error(`Configuration file already exists at \"${output}\".`);\n }\n\n logBanner();\n const result = await getPromptResult(options);\n const content = getContentFromPromptResult(result, useJsFile);\n await writeFile(output, content);\n logSuccess(`Configuration file created at \"${output}\".`);\n}\n\nfunction getOutputPath(explicitOutput: string | undefined, options: Pick<InitOptions, 'js'>): string {\n if (explicitOutput) {\n return resolveRelativePath(explicitOutput);\n }\n return resolveRelativePath(options.js ? 'codama.js' : 'codama.json');\n}\n\ntype PromptResult = {\n idlPath: string;\n jsPath?: string;\n rustCrate?: string;\n rustPath?: string;\n scripts: string[];\n};\n\nasync function getPromptResult(options: Pick<InitOptions, 'default'>): Promise<PromptResult> {\n const defaults = getDefaultPromptResult();\n if (options.default) {\n return defaults;\n }\n\n const hasScript =\n (script: string, type: PromptType = 'text') =>\n (_: unknown, values: { scripts: string[] }) =>\n values.scripts.includes(script) ? type : null;\n const result: PromptResult = await prompts(\n [\n {\n initial: defaults.idlPath,\n message: 'Where is your IDL located? (Supports Codama and Anchor IDLs).',\n name: 'idlPath',\n type: 'text',\n },\n {\n choices: [\n { selected: true, title: 'Generate JavaScript client', value: 'js' },\n { selected: true, title: 'Generate Rust client', value: 'rust' },\n ],\n instructions: '[space] to toggle / [a] to toggle all / [enter] to submit',\n message: 'Which script preset would you like to use?',\n name: 'scripts',\n type: 'multiselect',\n },\n {\n initial: defaults.jsPath,\n message: '[js] Where should the JavaScript code be generated?',\n name: 'jsPath',\n type: hasScript('js'),\n },\n {\n initial: defaults.rustCrate,\n message: '[rust] Where is the Rust client crate located?',\n name: 'rustCrate',\n type: hasScript('rust'),\n },\n {\n initial: (prev: string) => `${prev}/src/generated`,\n message: '[rust] Where should the Rust code be generated?',\n name: 'rustPath',\n type: hasScript('rust'),\n },\n ],\n {\n onCancel: () => {\n throw new Error('Operation cancelled.');\n },\n },\n );\n\n return result;\n}\n\nfunction getDefaultPromptResult(): PromptResult {\n return {\n idlPath: 'program/idl.json',\n jsPath: 'clients/js/src/generated',\n rustCrate: 'clients/rust',\n rustPath: 'clients/rust/src/generated',\n scripts: ['js', 'rust'],\n };\n}\n\nfunction getContentFromPromptResult(result: PromptResult, useJsFile: boolean): string {\n const scripts: Record<ScriptName, ScriptConfig> = {};\n if (result.scripts.includes('js')) {\n scripts.js = {\n from: '@codama/renderers-js',\n args: [result.jsPath],\n };\n }\n if (result.scripts.includes('rust')) {\n scripts.rust = {\n from: '@codama/renderers-rust',\n args: [result.rustPath, { crateFolder: result.rustCrate, formatCode: true }],\n };\n }\n const content: Config = { idl: result.idlPath, before: [], scripts };\n\n if (!useJsFile) {\n return JSON.stringify(content, null, 4);\n }\n\n return (\n 'export default ' +\n JSON.stringify(content, null, 4)\n // Remove quotes around property names\n .replace(/\"([^\"]+)\":/g, '$1:')\n // Convert double-quoted strings to single quotes\n .replace(/\"([^\"]*)\"/g, \"'$1'\")\n );\n}\n","import { R_OK, W_OK } from 'node:constants';\nimport fs, { PathLike } from 'node:fs';\nimport path from 'node:path';\n\nexport function resolveRelativePath(childPath: string, relativeDirectory: string | null = null) {\n return path.resolve(relativeDirectory ?? process.cwd(), childPath);\n}\n\nexport function resolveConfigPath(childPath: string, configPath: string | null) {\n const configDir = configPath ? path.dirname(configPath) : null;\n return resolveRelativePath(childPath, configDir);\n}\n\nexport function isLocalModulePath(modulePath: string) {\n return modulePath.startsWith('.') || modulePath.startsWith('/');\n}\n\nexport async function writeFile(filePath: string, content: string) {\n const directory = path.dirname(filePath);\n if (!(await canWrite(directory))) {\n await fs.promises.mkdir(directory, { recursive: true });\n }\n await fs.promises.writeFile(filePath, content);\n}\n\nexport async function canRead(p: PathLike) {\n try {\n await fs.promises.access(p, R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function canWrite(p: PathLike) {\n try {\n await fs.promises.access(p, W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","import { createRequire } from 'node:module';\n\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\nexport async function importModuleItem<T = unknown>(\n identifier: string,\n modulePath: string,\n itemName: string = 'default',\n): Promise<T> {\n const module = await importModule(identifier, modulePath);\n const item = pickModuleItem(module, itemName) as T | undefined;\n if (item === undefined) {\n throw new Error(`Failed to import \"${itemName}\" from ${identifier} at \"${modulePath}\".`);\n }\n return item;\n}\n\ntype ModuleDefinition = Partial<Record<string, unknown>> & {\n __esModule?: boolean;\n default?: Partial<Record<string, unknown>> & { default?: Partial<Record<string, unknown>> };\n};\n\nfunction pickModuleItem(module: ModuleDefinition, itemName: string): unknown {\n if (itemName === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[itemName] ?? module.default?.[itemName] ?? module.default?.default?.[itemName];\n}\n\nasync function importModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (isLocalModulePath(modulePath)) {\n return await importLocalModule(identifier, modulePath);\n }\n\n try {\n return await importExternalUserModule(identifier, modulePath);\n } catch {\n return await importExternalModule(identifier, modulePath);\n }\n}\n\nasync function importLocalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (!(await canRead(modulePath))) {\n throw new Error(`Cannot access ${identifier} at \"${modulePath}\"`);\n }\n\n const dotIndex = modulePath.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : modulePath.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(modulePath, { with: { type: 'json' } }) : import(modulePath);\n return await handleImportPromise(modulePromise, identifier, modulePath);\n}\n\nasync function importExternalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n return await handleImportPromise(import(modulePath), identifier, modulePath);\n}\n\nasync function importExternalUserModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userModulePath = userRequire.resolve(modulePath);\n return await importExternalModule<T>(identifier, userModulePath);\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n identifier: string,\n modulePath: string,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (error) {\n let causeMessage =\n !!error && typeof error === 'object' && 'message' in error && typeof error.message === 'string'\n ? (error as { message: string }).message\n : undefined;\n causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : '';\n throw new Error(`Failed to import ${identifier} at \"${modulePath}\" as a module${causeMessage}`, {\n cause: error,\n });\n }\n}\n","import pico from 'picocolors';\n\nexport function logSuccess(...args: unknown[]): void {\n console.log(pico.green('[Success]'), ...args);\n}\n\nexport function logInfo(...args: unknown[]): void {\n console.log(pico.blueBright('[Info]'), ...args);\n}\n\nexport function logWarning(...args: unknown[]): void {\n console.log(pico.yellow('[Warning]'), ...args);\n}\n\nexport function logError(...args: unknown[]): void {\n console.log(pico.red('[Error]'), ...args);\n}\n\nexport function logDebug(...args: unknown[]): void {\n console.log(pico.magenta('[Debug]'), ...args);\n}\n\nexport function logBanner(): void {\n console.log(getBanner());\n}\n\nfunction getBanner(): string {\n const textBanner = 'Welcome to Codama!';\n const gradientBanner = pico.bold(`\\x1b[38;2;231;171;97m${textBanner}\\x1b[0m`);\n return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { type AnchorIdl, rootNodeFromAnchor } from '@codama/nodes-from-anchor';\n\nexport function getRootNodeFromIdl(idl: unknown): RootNode {\n if (typeof idl !== 'object' || idl === null) {\n throw new Error('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n return rootNodeFromAnchor(idl as AnchorIdl);\n}\n\nexport function isRootNode(value: unknown): value is RootNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { standard?: string }).standard === 'codama' &&\n (value as { kind?: string }).kind === 'rootNode'\n );\n}\n","export function promisify<T>(value: Promise<T> | T): Promise<T> {\n return Promise.resolve(value);\n}\n","import type { RootNode } from '@codama/nodes';\nimport { rootNodeVisitor, visit, type Visitor } from '@codama/visitors-core';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { importModuleItem } from './import';\nimport { isRootNode } from './nodes';\nimport { promisify } from './promises';\n\nexport async function getRootNodeVisitors(\n visitors: readonly ParsedVisitorConfig[],\n): Promise<Visitor<RootNode, 'rootNode'>[]> {\n return await Promise.all(visitors.map(getRootNodeVisitor));\n}\n\nasync function getRootNodeVisitor(visitorConfig: ParsedVisitorConfig): Promise<Visitor<RootNode, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem(identifier, path, item);\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args);\n return rootNodeVisitor(root => {\n const result = visit(root, visitor);\n return isRootNode(result) ? result : root;\n });\n}\n\ntype UnknownFunction = (...args: readonly unknown[]) => unknown;\nasync function getVisitorFromModuleItem(\n identifier: string,\n moduleItem: unknown,\n args: readonly unknown[],\n): Promise<Visitor<unknown, 'rootNode'>> {\n if (isRootNodeVisitor(moduleItem)) {\n return moduleItem;\n }\n if (typeof moduleItem === 'function') {\n const result = await promisify((moduleItem as UnknownFunction)(...args));\n if (isRootNodeVisitor(result)) {\n return result;\n }\n }\n throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`);\n}\n\nfunction isRootNodeVisitor(value: unknown): value is Visitor<unknown, 'rootNode'> {\n return !!value && typeof value === 'object' && 'visitRoot' in value;\n}\n\nfunction getVisitorIdentifier(visitorConfig: ParsedVisitorConfig): string {\n const { index, item, path, script } = visitorConfig;\n const pathWithItem = item ? `${path}#${item}` : path;\n let identifier = `visitor of index #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n identifier += ` (at path \"${pathWithItem}\")`;\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport { getRootNodeVisitors, logInfo, logSuccess, logWarning } from '../utils';\n\nexport function setRunCommand(program: Command): void {\n program\n .command('run')\n .argument('[scripts...]', 'The scripts to execute')\n .option('-a, --all', 'Run all scripts in the config file')\n .action(doRun);\n}\n\ntype RunOptions = {\n all?: boolean;\n};\n\nasync function doRun(explicitScripts: string[], { all }: RunOptions, cmd: Command) {\n if (all && explicitScripts.length > 0) {\n logWarning(`CLI arguments \"${explicitScripts.join(' ')}\" are ignored because the \"--all\" option is set.`);\n }\n const parsedConfig = await getParsedConfigFromCommand(cmd);\n const scripts = all ? Object.keys(parsedConfig.scripts) : explicitScripts;\n const plans = await getPlans(parsedConfig, scripts);\n runPlans(plans, parsedConfig.rootNode);\n}\n\ntype RunPlan = {\n script: ScriptName | null;\n visitors: Visitor<RootNode, 'rootNode'>[];\n};\n\nasync function getPlans(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n): Promise<RunPlan[]> {\n const plans: RunPlan[] = [];\n if (scripts.length === 0 && parsedConfig.before.length === 0) {\n throw new Error('There are no scripts or before visitors to run.');\n }\n\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length > 0) {\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const missingScriptsIdentifier = `${scriptPluralized} \"${missingScripts.join(', ')}\"`;\n const message = parsedConfig.configPath\n ? `${missingScriptsIdentifier} not found in config file \"${parsedConfig.configPath}\"`\n : `${missingScriptsIdentifier} not found because no config file was found`;\n throw new Error(message);\n }\n\n if (parsedConfig.before.length > 0) {\n plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) });\n }\n\n for (const script of scripts) {\n plans.push({ script, visitors: await getRootNodeVisitors(parsedConfig.scripts[script]) });\n }\n\n return plans;\n}\n\nfunction runPlans(plans: RunPlan[], rootNode: RootNode): void {\n for (const plan of plans) {\n const result = runPlan(plan, rootNode);\n if (!plan.script) {\n rootNode = result;\n }\n }\n}\n\nfunction runPlan(plan: RunPlan, rootNode: RootNode): RootNode {\n const visitorLength = plan.visitors.length;\n const visitorPluralized = visitorLength === 1 ? 'visitor' : 'visitors';\n const identifier = plan.script\n ? `script \"${plan.script}\" with ${visitorLength} ${visitorPluralized}`\n : `${visitorLength} before ${visitorPluralized}`;\n logInfo(`Running ${identifier}...`);\n const newRoot = plan.visitors.reduce(visit, rootNode);\n logSuccess(`Executed ${identifier}!`);\n return newRoot;\n}\n","import path from 'node:path';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, importModuleItem, logWarning } from './utils';\n\nexport type Config = Readonly<{\n idl?: string;\n scripts?: ScriptsConfig;\n before?: readonly VisitorConfig[];\n}>;\n\nexport type ScriptName = string;\nexport type ScriptConfig = VisitorConfig | readonly VisitorConfig[];\nexport type ScriptsConfig = Readonly<Record<ScriptName, ScriptConfig>>;\n\nexport type VisitorPath = string;\nexport type VisitorConfig<T extends readonly unknown[] = readonly unknown[]> = VisitorConfigObject<T> | VisitorPath;\nexport type VisitorConfigObject<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args?: T;\n from: VisitorPath;\n}>;\n\nexport async function getConfig(options: Pick<ProgramOptions, 'config'>): Promise<[Config, string | null]> {\n const configPath = options.config != null ? path.resolve(options.config) : await getDefaultConfigPath();\n\n if (!configPath) {\n logWarning('No config file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem('config file', configPath);\n if (!configFile || typeof configFile !== 'object') {\n throw new Error(`Invalid config file at \"${configPath}\"`);\n }\n\n return [configFile, configPath];\n}\n\nasync function getDefaultConfigPath(): Promise<string | null> {\n const candidatePaths = ['codama.js', 'codama.mjs', 'codama.cjs', 'codama.json'];\n for (const candidatePath of candidatePaths) {\n const resolvedPath = path.resolve(process.cwd(), candidatePath);\n if (await canRead(resolvedPath)) {\n return resolvedPath;\n }\n }\n return null;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { Command } from 'commander';\n\nimport { Config, getConfig, ScriptName, ScriptsConfig, VisitorConfig, VisitorPath } from './config';\nimport { ProgramOptions } from './programOptions';\nimport {\n getRootNodeFromIdl,\n importModuleItem,\n isLocalModulePath,\n resolveConfigPath,\n resolveRelativePath,\n} from './utils';\n\nexport type ParsedConfig = Readonly<{\n configPath: string | null;\n idlContent: unknown;\n idlPath: string;\n rootNode: RootNode;\n scripts: ParsedScriptsConfig;\n before: readonly ParsedVisitorConfig[];\n}>;\n\nexport type ParsedScriptsConfig = Readonly<Record<ScriptName, readonly ParsedVisitorConfig[]>>;\nexport type ParsedVisitorConfig<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args: T;\n index: number;\n item: string | undefined;\n path: VisitorPath;\n script: ScriptName | null;\n}>;\n\nexport async function getParsedConfigFromCommand(cmd: Command): Promise<ParsedConfig> {\n return await getParsedConfig(cmd.optsWithGlobals() as ProgramOptions);\n}\n\nexport async function getParsedConfig(options: Pick<ProgramOptions, 'config' | 'idl'>): Promise<ParsedConfig> {\n const [config, configPath] = await getConfig(options);\n return await parseConfig(config, configPath, options);\n}\n\nasync function parseConfig(\n config: Config,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): Promise<ParsedConfig> {\n const idlPath = parseIdlPath(config, configPath, options);\n const idlContent = await importModuleItem('IDL', idlPath);\n const rootNode = getRootNodeFromIdl(idlContent);\n const scripts = parseScripts(config.scripts ?? {}, configPath);\n const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null));\n\n return { configPath, idlContent, idlPath, rootNode, scripts, before: visitors };\n}\n\nfunction parseIdlPath(\n config: Pick<Config, 'idl'>,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): string {\n if (options.idl) {\n return resolveRelativePath(options.idl);\n }\n if (config.idl) {\n return resolveConfigPath(config.idl, configPath);\n }\n throw new Error('No IDL identified. Please provide the `--idl` option or set it in the config file.');\n}\n\nfunction parseScripts(scripts: ScriptsConfig, configPath: string | null): ParsedScriptsConfig {\n const entryPromises = Object.entries(scripts).map(([name, scriptConfig]) => {\n const visitors: readonly VisitorConfig[] = Array.isArray(scriptConfig) ? scriptConfig : [scriptConfig];\n return [name, visitors.map((v, i) => parseVisitorConfig(v, configPath, i, name))] as const;\n });\n return Object.fromEntries(entryPromises);\n}\n\nfunction parseVisitorConfig<T extends readonly unknown[]>(\n visitorConfig: VisitorConfig<T>,\n configPath: string | null,\n index: number,\n script: ScriptName | null,\n): ParsedVisitorConfig<T> {\n const emptyArgs = [] as readonly unknown[] as T;\n const visitorPath = typeof visitorConfig === 'string' ? visitorConfig : visitorConfig.from;\n const visitorArgs = typeof visitorConfig === 'string' ? emptyArgs : (visitorConfig.args ?? emptyArgs);\n const [path, item] = resolveVisitorPath(visitorPath, configPath);\n return { args: visitorArgs, index, item, path, script };\n}\n\nfunction resolveVisitorPath(visitorPath: string, configPath: string | null): readonly [string, string | undefined] {\n const [modulePath, itemName] = visitorPath.split('#') as [string, string | undefined];\n const resolveModulePath = isLocalModulePath(modulePath) ? resolveConfigPath(modulePath, configPath) : modulePath;\n return [resolveModulePath, itemName];\n}\n","import { Command } from 'commander';\n\nexport type ProgramOptions = Readonly<{\n config?: string;\n debug?: boolean;\n idl?: string;\n}>;\n\nexport function setProgramOptions(program: Command): void {\n program\n .option('--debug', 'include debugging information, such as stack dump')\n .option('-i, --idl <path>', 'The path to the IDL to use.')\n .option('-c, --config <path>', 'The path to the Codama configuration file. Defaults to `codama.(js|json)`.');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAuC;;;ACCvC,qBAAoC;;;ACDpC,4BAA2B;AAC3B,qBAA6B;AAC7B,uBAAiB;AAEV,SAAS,oBAAoB,WAAmB,oBAAmC,MAAM;AAC5F,SAAO,iBAAAA,QAAK,QAAQ,qBAAqB,QAAQ,IAAI,GAAG,SAAS;AACrE;AAEO,SAAS,kBAAkB,WAAmB,YAA2B;AAC5E,QAAM,YAAY,aAAa,iBAAAA,QAAK,QAAQ,UAAU,IAAI;AAC1D,SAAO,oBAAoB,WAAW,SAAS;AACnD;AAEO,SAAS,kBAAkB,YAAoB;AAClD,SAAO,WAAW,WAAW,GAAG,KAAK,WAAW,WAAW,GAAG;AAClE;AAEA,eAAsB,UAAU,UAAkB,SAAiB;AAC/D,QAAM,YAAY,iBAAAA,QAAK,QAAQ,QAAQ;AACvC,MAAI,CAAE,MAAM,SAAS,SAAS,GAAI;AAC9B,UAAM,eAAAC,QAAG,SAAS,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAAA,EAC1D;AACA,QAAM,eAAAA,QAAG,SAAS,UAAU,UAAU,OAAO;AACjD;AAEA,eAAsB,QAAQ,GAAa;AACvC,MAAI;AACA,UAAM,eAAAA,QAAG,SAAS,OAAO,GAAG,0BAAI;AAChC,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,eAAsB,SAAS,GAAa;AACxC,MAAI;AACA,UAAM,eAAAA,QAAG,SAAS,OAAO,GAAG,0BAAI;AAChC,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;;;ACzCA,yBAA8B;AAI9B,eAAsB,iBAClB,YACA,YACA,WAAmB,WACT;AACV,Q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U,MAAM;AAAA,MAAC;AAAA,IACrB,CAAC;AAAA,EACL;AAEA,SAAOA;AACX;;;ADhCA,IAAM,UAAU,cAAc;AAE9B,eAAsB,IAAI,MAAyB;AAC/C,MAAI;AACA,UAAM,QAAQ,WAAW,IAAI;AAAA,EACjC,SAAS,KAAK;AACV,QAAI,QAAQ,KAAK,EAAE,OAAO;AACtB,eAAS,GAAI,IAA0B,KAAK,EAAE;AAAA,IAClD;AACA,aAAU,IAA4B,OAAO;AAC7C,YAAQ,WAAW;AAAA,EACvB;AACJ;","names":["path","fs","module","pico","path","program","prompts","import_visitors_core","import_node_path","path","path","program","program","program"]}
{"version":3,"sources":["../src/cli/index.ts","../src/program.ts","../src/commands/init.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/nodes.ts","../src/utils/promises.ts","../src/utils/visitors.ts","../src/commands/run.ts","../src/config.ts","../src/parsedConfig.ts","../src/programOptions.ts"],"sourcesContent":["import { createProgram } from '../program';\nimport { logDebug, logError } from '../utils';\n\nconst program = createProgram();\n\nexport async function run(argv: readonly string[]) {\n try {\n await program.parseAsync(argv);\n } catch (err) {\n if (program.opts().debug) {\n logDebug(`${(err as { stack: string }).stack}`);\n }\n logError((err as { message: string }).message);\n process.exitCode = 1;\n }\n}\n","import { Command, createCommand } from 'commander';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n await createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n }).parseAsync(args, { from: 'user' });\n}\n\nexport function createProgram(internalOptions?: { exitOverride?: boolean; suppressOutput?: boolean }): Command {\n const program = createCommand()\n .version(__VERSION__)\n .allowExcessArguments(false)\n .configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });\n\n // Set program options and commands.\n setProgramOptions(program);\n setInitCommand(program);\n setRunCommand(program);\n\n // Internal options.\n if (internalOptions?.exitOverride) {\n program.exitOverride();\n }\n if (internalOptions?.suppressOutput) {\n program.configureOutput({\n writeErr: () => {},\n writeOut: () => {},\n });\n }\n\n return program;\n}\n","import { Command } from 'commander';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport { canRead, logBanner, logSuccess, resolveRelativePath, writeFile } from '../utils';\n\nexport function setInitCommand(program: Command): void {\n program\n .command('init')\n .argument('[output]', 'Optional path used to output the configuration file')\n .option('-d, --default', 'Bypass prompts and select all defaults options')\n .option('--js', 'Forces the output to be a JavaScript file')\n .option('--gill', 'Forces the output to be a gill based JavaScript file')\n .action(doInit);\n}\n\ntype InitOptions = {\n default?: boolean;\n js?: boolean;\n gill?: boolean;\n};\n\ntype ConfigFileType = 'gill' | 'js' | 'json';\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n let configFileType: ConfigFileType = output.endsWith('.js') ? 'js' : 'json';\n if (options.gill) configFileType = 'gill';\n else if (options.js) configFileType = 'js';\n\n if (await canRead(output)) {\n throw new Error(`Configuration file already exists at \"${output}\".`);\n }\n\n logBanner();\n const result = await getPromptResult(options);\n const content = getContentFromPromptResult(result, configFileType);\n await writeFile(output, content);\n logSuccess(`Configuration file created at \"${output}\".`);\n}\n\nfunction getOutputPath(explicitOutput: string | undefined, options: Pick<InitOptions, 'gill' | 'js'>): string {\n if (explicitOutput) {\n return resolveRelativePath(explicitOutput);\n }\n return resolveRelativePath(options.js || options.gill ? 'codama.js' : 'codama.json');\n}\n\ntype PromptResult = {\n idlPath: string;\n jsPath?: string;\n rustCrate?: string;\n rustPath?: string;\n scripts: string[];\n};\n\nasync function getPromptResult(options: Pick<InitOptions, 'default'>): Promise<PromptResult> {\n const defaults = getDefaultPromptResult();\n if (options.default) {\n return defaults;\n }\n\n const hasScript =\n (script: string, type: PromptType = 'text') =>\n (_: unknown, values: { scripts: string[] }) =>\n values.scripts.includes(script) ? type : null;\n const result: PromptResult = await prompts(\n [\n {\n initial: defaults.idlPath,\n message: 'Where is your IDL located? (Supports Codama and Anchor IDLs).',\n name: 'idlPath',\n type: 'text',\n },\n {\n choices: [\n { selected: true, title: 'Generate JavaScript client', value: 'js' },\n { selected: true, title: 'Generate Rust client', value: 'rust' },\n ],\n instructions: '[space] to toggle / [a] to toggle all / [enter] to submit',\n message: 'Which script preset would you like to use?',\n name: 'scripts',\n type: 'multiselect',\n },\n {\n initial: defaults.jsPath,\n message: '[js] Where should the JavaScript code be generated?',\n name: 'jsPath',\n type: hasScript('js'),\n },\n {\n initial: defaults.rustCrate,\n message: '[rust] Where is the Rust client crate located?',\n name: 'rustCrate',\n type: hasScript('rust'),\n },\n {\n initial: (prev: string) => `${prev}/src/generated`,\n message: '[rust] Where should the Rust code be generated?',\n name: 'rustPath',\n type: hasScript('rust'),\n },\n ],\n {\n onCancel: () => {\n throw new Error('Operation cancelled.');\n },\n },\n );\n\n return result;\n}\n\nfunction getDefaultPromptResult(): PromptResult {\n return {\n idlPath: 'program/idl.json',\n jsPath: 'clients/js/src/generated',\n rustCrate: 'clients/rust',\n rustPath: 'clients/rust/src/generated',\n scripts: ['js', 'rust'],\n };\n}\n\nfunction getContentFromPromptResult(result: PromptResult, configFileType: ConfigFileType): string {\n const scripts: Record<ScriptName, ScriptConfig> = {};\n if (result.scripts.includes('js')) {\n scripts.js = {\n from: '@codama/renderers-js',\n args: [result.jsPath],\n };\n }\n if (result.scripts.includes('rust')) {\n scripts.rust = {\n from: '@codama/renderers-rust',\n args: [result.rustPath, { crateFolder: result.rustCrate, formatCode: true }],\n };\n }\n const content: Config = { idl: result.idlPath, before: [], scripts };\n\n if (configFileType == 'json') {\n return JSON.stringify(content, null, 4);\n } else if (configFileType == 'gill') {\n return `import { createCodamaConfig } from \"gill\";\\n\\n` +\n `export default createCodamaConfig({ \\n\\t` +\n `idl: \"${result.idlPath}\", \\n\\t` +\n `clientJs: \"${result.jsPath}\", \\n` +\n result.scripts.includes('rust')\n ? `clientRust: \"${result.rustPath}\", \\n`\n : `` + `});`;\n }\n\n return (\n 'export default ' +\n JSON.stringify(content, null, 4)\n // Remove quotes around property names\n .replace(/\"([^\"]+)\":/g, '$1:')\n // Convert double-quoted strings to single quotes\n .replace(/\"([^\"]*)\"/g, \"'$1'\")\n );\n}\n","import { R_OK, W_OK } from 'node:constants';\nimport fs, { PathLike } from 'node:fs';\nimport path from 'node:path';\n\nexport function resolveRelativePath(childPath: string, relativeDirectory: string | null = null) {\n return path.resolve(relativeDirectory ?? process.cwd(), childPath);\n}\n\nexport function resolveConfigPath(childPath: string, configPath: string | null) {\n const configDir = configPath ? path.dirname(configPath) : null;\n return resolveRelativePath(childPath, configDir);\n}\n\nexport function isLocalModulePath(modulePath: string) {\n return modulePath.startsWith('.') || modulePath.startsWith('/');\n}\n\nexport async function writeFile(filePath: string, content: string) {\n const directory = path.dirname(filePath);\n if (!(await canWrite(directory))) {\n await fs.promises.mkdir(directory, { recursive: true });\n }\n await fs.promises.writeFile(filePath, content);\n}\n\nexport async function canRead(p: PathLike) {\n try {\n await fs.promises.access(p, R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function canWrite(p: PathLike) {\n try {\n await fs.promises.access(p, W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","import { createRequire } from 'node:module';\n\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\nexport async function importModuleItem<T = unknown>(\n identifier: string,\n modulePath: string,\n itemName: string = 'default',\n): Promise<T> {\n const module = await importModule(identifier, modulePath);\n const item = pickModuleItem(module, itemName) as T | undefined;\n if (item === undefined) {\n throw new Error(`Failed to import \"${itemName}\" from ${identifier} at \"${modulePath}\".`);\n }\n return item;\n}\n\ntype ModuleDefinition = Partial<Record<string, unknown>> & {\n __esModule?: boolean;\n default?: Partial<Record<string, unknown>> & { default?: Partial<Record<string, unknown>> };\n};\n\nfunction pickModuleItem(module: ModuleDefinition, itemName: string): unknown {\n if (itemName === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[itemName] ?? module.default?.[itemName] ?? module.default?.default?.[itemName];\n}\n\nasync function importModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (isLocalModulePath(modulePath)) {\n return await importLocalModule(identifier, modulePath);\n }\n\n try {\n return await importExternalUserModule(identifier, modulePath);\n } catch {\n return await importExternalModule(identifier, modulePath);\n }\n}\n\nasync function importLocalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (!(await canRead(modulePath))) {\n throw new Error(`Cannot access ${identifier} at \"${modulePath}\"`);\n }\n\n const dotIndex = modulePath.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : modulePath.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(modulePath, { with: { type: 'json' } }) : import(modulePath);\n return await handleImportPromise(modulePromise, identifier, modulePath);\n}\n\nasync function importExternalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n return await handleImportPromise(import(modulePath), identifier, modulePath);\n}\n\nasync function importExternalUserModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userModulePath = userRequire.resolve(modulePath);\n return await importExternalModule<T>(identifier, userModulePath);\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n identifier: string,\n modulePath: string,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (error) {\n let causeMessage =\n !!error && typeof error === 'object' && 'message' in error && typeof error.message === 'string'\n ? (error as { message: string }).message\n : undefined;\n causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : '';\n throw new Error(`Failed to import ${identifier} at \"${modulePath}\" as a module${causeMessage}`, {\n cause: error,\n });\n }\n}\n","import pico from 'picocolors';\n\nexport function logSuccess(...args: unknown[]): void {\n console.log(pico.green('[Success]'), ...args);\n}\n\nexport function logInfo(...args: unknown[]): void {\n console.log(pico.blueBright('[Info]'), ...args);\n}\n\nexport function logWarning(...args: unknown[]): void {\n console.log(pico.yellow('[Warning]'), ...args);\n}\n\nexport function logError(...args: unknown[]): void {\n console.log(pico.red('[Error]'), ...args);\n}\n\nexport function logDebug(...args: unknown[]): void {\n console.log(pico.magenta('[Debug]'), ...args);\n}\n\nexport function logBanner(): void {\n console.log(getBanner());\n}\n\nfunction getBanner(): string {\n const textBanner = 'Welcome to Codama!';\n const gradientBanner = pico.bold(`\\x1b[38;2;231;171;97m${textBanner}\\x1b[0m`);\n return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { type AnchorIdl, rootNodeFromAnchor } from '@codama/nodes-from-anchor';\n\nexport function getRootNodeFromIdl(idl: unknown): RootNode {\n if (typeof idl !== 'object' || idl === null) {\n throw new Error('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n return rootNodeFromAnchor(idl as AnchorIdl);\n}\n\nexport function isRootNode(value: unknown): value is RootNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { standard?: string }).standard === 'codama' &&\n (value as { kind?: string }).kind === 'rootNode'\n );\n}\n","export function promisify<T>(value: Promise<T> | T): Promise<T> {\n return Promise.resolve(value);\n}\n","import type { RootNode } from '@codama/nodes';\nimport { rootNodeVisitor, visit, type Visitor } from '@codama/visitors-core';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { importModuleItem } from './import';\nimport { isRootNode } from './nodes';\nimport { promisify } from './promises';\n\nexport async function getRootNodeVisitors(\n visitors: readonly ParsedVisitorConfig[],\n): Promise<Visitor<RootNode, 'rootNode'>[]> {\n return await Promise.all(visitors.map(getRootNodeVisitor));\n}\n\nasync function getRootNodeVisitor(visitorConfig: ParsedVisitorConfig): Promise<Visitor<RootNode, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem(identifier, path, item);\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args);\n return rootNodeVisitor(root => {\n const result = visit(root, visitor);\n return isRootNode(result) ? result : root;\n });\n}\n\ntype UnknownFunction = (...args: readonly unknown[]) => unknown;\nasync function getVisitorFromModuleItem(\n identifier: string,\n moduleItem: unknown,\n args: readonly unknown[],\n): Promise<Visitor<unknown, 'rootNode'>> {\n if (isRootNodeVisitor(moduleItem)) {\n return moduleItem;\n }\n if (typeof moduleItem === 'function') {\n const result = await promisify((moduleItem as UnknownFunction)(...args));\n if (isRootNodeVisitor(result)) {\n return result;\n }\n }\n throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`);\n}\n\nfunction isRootNodeVisitor(value: unknown): value is Visitor<unknown, 'rootNode'> {\n return !!value && typeof value === 'object' && 'visitRoot' in value;\n}\n\nfunction getVisitorIdentifier(visitorConfig: ParsedVisitorConfig): string {\n const { index, item, path, script } = visitorConfig;\n const pathWithItem = item ? `${path}#${item}` : path;\n let identifier = `visitor of index #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n identifier += ` (at path \"${pathWithItem}\")`;\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport { getRootNodeVisitors, logInfo, logSuccess, logWarning } from '../utils';\n\nexport function setRunCommand(program: Command): void {\n program\n .command('run')\n .argument('[scripts...]', 'The scripts to execute')\n .option('-a, --all', 'Run all scripts in the config file')\n .action(doRun);\n}\n\ntype RunOptions = {\n all?: boolean;\n};\n\nasync function doRun(explicitScripts: string[], { all }: RunOptions, cmd: Command) {\n if (all && explicitScripts.length > 0) {\n logWarning(`CLI arguments \"${explicitScripts.join(' ')}\" are ignored because the \"--all\" option is set.`);\n }\n const parsedConfig = await getParsedConfigFromCommand(cmd);\n const scripts = all ? Object.keys(parsedConfig.scripts) : explicitScripts;\n const plans = await getPlans(parsedConfig, scripts);\n runPlans(plans, parsedConfig.rootNode);\n}\n\ntype RunPlan = {\n script: ScriptName | null;\n visitors: Visitor<RootNode, 'rootNode'>[];\n};\n\nasync function getPlans(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n): Promise<RunPlan[]> {\n const plans: RunPlan[] = [];\n if (scripts.length === 0 && parsedConfig.before.length === 0) {\n throw new Error('There are no scripts or before visitors to run.');\n }\n\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length > 0) {\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const missingScriptsIdentifier = `${scriptPluralized} \"${missingScripts.join(', ')}\"`;\n const message = parsedConfig.configPath\n ? `${missingScriptsIdentifier} not found in config file \"${parsedConfig.configPath}\"`\n : `${missingScriptsIdentifier} not found because no config file was found`;\n throw new Error(message);\n }\n\n if (parsedConfig.before.length > 0) {\n plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) });\n }\n\n for (const script of scripts) {\n plans.push({ script, visitors: await getRootNodeVisitors(parsedConfig.scripts[script]) });\n }\n\n return plans;\n}\n\nfunction runPlans(plans: RunPlan[], rootNode: RootNode): void {\n for (const plan of plans) {\n const result = runPlan(plan, rootNode);\n if (!plan.script) {\n rootNode = result;\n }\n }\n}\n\nfunction runPlan(plan: RunPlan, rootNode: RootNode): RootNode {\n const visitorLength = plan.visitors.length;\n const visitorPluralized = visitorLength === 1 ? 'visitor' : 'visitors';\n const identifier = plan.script\n ? `script \"${plan.script}\" with ${visitorLength} ${visitorPluralized}`\n : `${visitorLength} before ${visitorPluralized}`;\n logInfo(`Running ${identifier}...`);\n const newRoot = plan.visitors.reduce(visit, rootNode);\n logSuccess(`Executed ${identifier}!`);\n return newRoot;\n}\n","import path from 'node:path';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, importModuleItem, logWarning } from './utils';\n\nexport type Config = Readonly<{\n idl?: string;\n scripts?: ScriptsConfig;\n before?: readonly VisitorConfig[];\n}>;\n\nexport type ScriptName = string;\nexport type ScriptConfig = VisitorConfig | readonly VisitorConfig[];\nexport type ScriptsConfig = Readonly<Record<ScriptName, ScriptConfig>>;\n\nexport type VisitorPath = string;\nexport type VisitorConfig<T extends readonly unknown[] = readonly unknown[]> = VisitorConfigObject<T> | VisitorPath;\nexport type VisitorConfigObject<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args?: T;\n from: VisitorPath;\n}>;\n\nexport async function getConfig(options: Pick<ProgramOptions, 'config'>): Promise<[Config, string | null]> {\n const configPath = options.config != null ? path.resolve(options.config) : await getDefaultConfigPath();\n\n if (!configPath) {\n logWarning('No config file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem('config file', configPath);\n if (!configFile || typeof configFile !== 'object') {\n throw new Error(`Invalid config file at \"${configPath}\"`);\n }\n\n return [configFile, configPath];\n}\n\nasync function getDefaultConfigPath(): Promise<string | null> {\n const candidatePaths = ['codama.js', 'codama.mjs', 'codama.cjs', 'codama.json'];\n for (const candidatePath of candidatePaths) {\n const resolvedPath = path.resolve(process.cwd(), candidatePath);\n if (await canRead(resolvedPath)) {\n return resolvedPath;\n }\n }\n return null;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { Command } from 'commander';\n\nimport { Config, getConfig, ScriptName, ScriptsConfig, VisitorConfig, VisitorPath } from './config';\nimport { ProgramOptions } from './programOptions';\nimport {\n getRootNodeFromIdl,\n importModuleItem,\n isLocalModulePath,\n resolveConfigPath,\n resolveRelativePath,\n} from './utils';\n\nexport type ParsedConfig = Readonly<{\n configPath: string | null;\n idlContent: unknown;\n idlPath: string;\n rootNode: RootNode;\n scripts: ParsedScriptsConfig;\n before: readonly ParsedVisitorConfig[];\n}>;\n\nexport type ParsedScriptsConfig = Readonly<Record<ScriptName, readonly ParsedVisitorConfig[]>>;\nexport type ParsedVisitorConfig<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args: T;\n index: number;\n item: string | undefined;\n path: VisitorPath;\n script: ScriptName | null;\n}>;\n\nexport async function getParsedConfigFromCommand(cmd: Command): Promise<ParsedConfig> {\n return await getParsedConfig(cmd.optsWithGlobals() as ProgramOptions);\n}\n\nexport async function getParsedConfig(options: Pick<ProgramOptions, 'config' | 'idl'>): Promise<ParsedConfig> {\n const [config, configPath] = await getConfig(options);\n return await parseConfig(config, configPath, options);\n}\n\nasync function parseConfig(\n config: Config,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): Promise<ParsedConfig> {\n const idlPath = parseIdlPath(config, configPath, options);\n const idlContent = await importModuleItem('IDL', idlPath);\n const rootNode = getRootNodeFromIdl(idlContent);\n const scripts = parseScripts(config.scripts ?? {}, configPath);\n const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null));\n\n return { configPath, idlContent, idlPath, rootNode, scripts, before: visitors };\n}\n\nfunction parseIdlPath(\n config: Pick<Config, 'idl'>,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): string {\n if (options.idl) {\n return resolveRelativePath(options.idl);\n }\n if (config.idl) {\n return resolveConfigPath(config.idl, configPath);\n }\n throw new Error('No IDL identified. Please provide the `--idl` option or set it in the config file.');\n}\n\nfunction parseScripts(scripts: ScriptsConfig, configPath: string | null): ParsedScriptsConfig {\n const entryPromises = Object.entries(scripts).map(([name, scriptConfig]) => {\n const visitors: readonly VisitorConfig[] = Array.isArray(scriptConfig) ? scriptConfig : [scriptConfig];\n return [name, visitors.map((v, i) => parseVisitorConfig(v, configPath, i, name))] as const;\n });\n return Object.fromEntries(entryPromises);\n}\n\nfunction parseVisitorConfig<T extends readonly unknown[]>(\n visitorConfig: VisitorConfig<T>,\n configPath: string | null,\n index: number,\n script: ScriptName | null,\n): ParsedVisitorConfig<T> {\n const emptyArgs = [] as readonly unknown[] as T;\n const visitorPath = typeof visitorConfig === 'string' ? visitorConfig : visitorConfig.from;\n const visitorArgs = typeof visitorConfig === 'string' ? emptyArgs : (visitorConfig.args ?? emptyArgs);\n const [path, item] = resolveVisitorPath(visitorPath, configPath);\n return { args: visitorArgs, index, item, path, script };\n}\n\nfunction resolveVisitorPath(visitorPath: string, configPath: string | null): readonly [string, string | undefined] {\n const [modulePath, itemName] = visitorPath.split('#') as [string, string | undefined];\n const resolveModulePath = isLocalModulePath(modulePath) ? resolveConfigPath(modulePath, configPath) : modulePath;\n return [resolveModulePath, itemName];\n}\n","import { Command } from 'commander';\n\nexport type ProgramOptions = Readonly<{\n config?: string;\n debug?: boolean;\n idl?: string;\n}>;\n\nexport function setProgramOptions(program: Command): void {\n program\n .option('--debug', 'include debugging information, such as stack dump')\n .option('-i, --idl <path>', 'The path to the IDL to use.')\n .option('-c, --config <path>', 'The path to the Codama configuration file. Defaults to `codama.(js|json)`.');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAuC;;;ACCvC,qBAAoC;;;ACDpC,4BAA2B;AAC3B,qBAA6B;AAC7B,uBAAiB;AAEV,SAAS,oBAAoB,WAAmB,oBAAmC,MAAM;AAC5F,SAAO,iBAAAA,QAAK,QAAQ,qBAAqB,QAAQ,IAAI,GAAG,SAAS;AACrE;AAEO,SAAS,kBAAkB,WAAmB,YAA2B;AAC5E,QAAM,YAAY,aAAa,iBAAAA,QAAK,QAAQ,UAAU,IAAI;AAC1D,SAAO,oBAAoB,WAAW,SAAS;AACnD;AAEO,SAAS,kBAAkB,YAAoB;AAClD,SAAO,WAAW,WAAW,GAAG,KAAK,WAAW,WAAW,GAAG;AAClE;AAEA,eAAsB,UAAU,UAAkB,SAAiB;AAC/D,QAAM,YAAY,iBAAAA,QAAK,QAAQ,QAAQ;AACvC,MAAI,CAAE,MAAM,SAAS,SAAS,GAAI;AAC9B,UAAM,eAAAC,QAAG,SAAS,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAAA,EAC1D;AACA,QAAM,eAAAA,QAAG,SAAS,UAAU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,WAAW,iBAAiB;AAClD,UAAQ,WAAW,UAAU,KAAK;AAClC,QAAM,UAAU,KAAK,SAAS,OAAO,6BAAO,QAAQ;AACpD,aAAW,YAAY,UAAU,GAAG;AACpC,SAAO;AACX;;;AG5EO,SAAS,kBAAkBC,UAAwB;AACtD,EAAAA,SACK,OAAO,WAAW,mDAAmD,EACrE,OAAO,oBAAoB,6BAA6B,EACxD,OAAO,uBAAuB,4EAA4E;AACnH;;;AXDO,SAAS,cAAc,iBAAiF;AAC3G,QAAMC,eAAU,gCAAc,EACzB,QAAQ,OAAW,EACnB,qBAAqB,KAAK,EAC1B,cAAc,EAAE,mBAAmB,MAAM,aAAa,MAAM,iBAAiB,KAAK,CAAC;AAGxF,oBAAkBA,QAAO;AACzB,iBAAeA,QAAO;AACtB,gBAAcA,QAAO;AAGrB,MAAI,iBAAiB,cAAc;AAC/B,IAAAA,SAAQ,aAAa;AAAA,EACzB;AACA,MAAI,iBAAiB,gBAAgB;AACjC,IAAAA,SAAQ,gBAAgB;AAAA,MACpB,UAAU,MAAM;AAAA,MAAC;AAAA,MACjB,UAAU,MAAM;AAAA,MAAC;AAAA,IACrB,CAAC;AAAA,EACL;AAEA,SAAOA;AACX;;;ADhCA,IAAM,UAAU,cAAc;AAE9B,eAAsB,IAAI,MAAyB;AAC/C,MAAI;AACA,UAAM,QAAQ,WAAW,IAAI;AAAA,EACjC,SAAS,KAAK;AACV,QAAI,QAAQ,KAAK,EAAE,OAAO;AACtB,eAAS,GAAI,IAA0B,KAAK,EAAE;AAAA,IAClD;AACA,aAAU,IAA4B,OAAO;AAC7C,YAAQ,WAAW;AAAA,EACvB;AACJ;","names":["path","fs","module","pico","path","program","prompts","import_visitors_core","import_node_path","path","path","program","program","program"]}

@@ -231,7 +231,9 @@ "use strict";

function setInitCommand(program) {
program.command("init").argument("[output]", "Optional path used to output the configuration file").option("-d, --default", "Bypass prompts and select all defaults options").option("--js", "Forces the output to be a JavaScript file").action(doInit);
program.command("init").argument("[output]", "Optional path used to output the configuration file").option("-d, --default", "Bypass prompts and select all defaults options").option("--js", "Forces the output to be a JavaScript file").option("--gill", "Forces the output to be a gill based JavaScript file").action(doInit);
}
async function doInit(explicitOutput, options) {
const output = getOutputPath(explicitOutput, options);
const useJsFile = options.js || output.endsWith(".js");
let configFileType = output.endsWith(".js") ? "js" : "json";
if (options.gill) configFileType = "gill";
else if (options.js) configFileType = "js";
if (await canRead(output)) {

@@ -242,3 +244,3 @@ throw new Error(`Configuration file already exists at "${output}".`);

const result = await getPromptResult(options);
const content = getContentFromPromptResult(result, useJsFile);
const content = getContentFromPromptResult(result, configFileType);
await writeFile(output, content);

@@ -251,3 +253,3 @@ logSuccess(`Configuration file created at "${output}".`);

}
return resolveRelativePath(options.js ? "codama.js" : "codama.json");
return resolveRelativePath(options.js || options.gill ? "codama.js" : "codama.json");
}

@@ -314,3 +316,3 @@ async function getPromptResult(options) {

}
function getContentFromPromptResult(result, useJsFile) {
function getContentFromPromptResult(result, configFileType) {
const scripts = {};

@@ -330,4 +332,12 @@ if (result.scripts.includes("js")) {

const content = { idl: result.idlPath, before: [], scripts };
if (!useJsFile) {
if (configFileType == "json") {
return JSON.stringify(content, null, 4);
} else if (configFileType == "gill") {
return `import { createCodamaConfig } from "gill";
export default createCodamaConfig({
idl: "${result.idlPath}",
clientJs: "${result.jsPath}",
` + result.scripts.includes("rust") ? `clientRust: "${result.rustPath}",
` : `});`;
}

@@ -474,3 +484,3 @@ return "export default " + JSON.stringify(content, null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'");

function createProgram(internalOptions) {
const program = (0, import_commander.createCommand)().version("1.1.4").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });
const program = (0, import_commander.createCommand)().version("1.2.0").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });
setProgramOptions(program);

@@ -477,0 +487,0 @@ setInitCommand(program);

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/index.ts","../src/program.ts","../src/commands/init.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/nodes.ts","../src/utils/promises.ts","../src/utils/visitors.ts","../src/commands/run.ts","../src/config.ts","../src/parsedConfig.ts","../src/programOptions.ts"],"sourcesContent":["export * from './program';\nexport * from './utils/logs';\n","import { Command, createCommand } from 'commander';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n await createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n }).parseAsync(args, { from: 'user' });\n}\n\nexport function createProgram(internalOptions?: { exitOverride?: boolean; suppressOutput?: boolean }): Command {\n const program = createCommand()\n .version(__VERSION__)\n .allowExcessArguments(false)\n .configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });\n\n // Set program options and commands.\n setProgramOptions(program);\n setInitCommand(program);\n setRunCommand(program);\n\n // Internal options.\n if (internalOptions?.exitOverride) {\n program.exitOverride();\n }\n if (internalOptions?.suppressOutput) {\n program.configureOutput({\n writeErr: () => {},\n writeOut: () => {},\n });\n }\n\n return program;\n}\n","import { Command } from 'commander';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport { canRead, logBanner, logSuccess, resolveRelativePath, writeFile } from '../utils';\n\nexport function setInitCommand(program: Command): void {\n program\n .command('init')\n .argument('[output]', 'Optional path used to output the configuration file')\n .option('-d, --default', 'Bypass prompts and select all defaults options')\n .option('--js', 'Forces the output to be a JavaScript file')\n .action(doInit);\n}\n\ntype InitOptions = {\n default?: boolean;\n js?: boolean;\n};\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n const useJsFile = options.js || output.endsWith('.js');\n if (await canRead(output)) {\n throw new Error(`Configuration file already exists at \"${output}\".`);\n }\n\n logBanner();\n const result = await getPromptResult(options);\n const content = getContentFromPromptResult(result, useJsFile);\n await writeFile(output, content);\n logSuccess(`Configuration file created at \"${output}\".`);\n}\n\nfunction getOutputPath(explicitOutput: string | undefined, options: Pick<InitOptions, 'js'>): string {\n if (explicitOutput) {\n return resolveRelativePath(explicitOutput);\n }\n return resolveRelativePath(options.js ? 'codama.js' : 'codama.json');\n}\n\ntype PromptResult = {\n idlPath: string;\n jsPath?: string;\n rustCrate?: string;\n rustPath?: string;\n scripts: string[];\n};\n\nasync function getPromptResult(options: Pick<InitOptions, 'default'>): Promise<PromptResult> {\n const defaults = getDefaultPromptResult();\n if (options.default) {\n return defaults;\n }\n\n const hasScript =\n (script: string, type: PromptType = 'text') =>\n (_: unknown, values: { scripts: string[] }) =>\n values.scripts.includes(script) ? type : null;\n const result: PromptResult = await prompts(\n [\n {\n initial: defaults.idlPath,\n message: 'Where is your IDL located? (Supports Codama and Anchor IDLs).',\n name: 'idlPath',\n type: 'text',\n },\n {\n choices: [\n { selected: true, title: 'Generate JavaScript client', value: 'js' },\n { selected: true, title: 'Generate Rust client', value: 'rust' },\n ],\n instructions: '[space] to toggle / [a] to toggle all / [enter] to submit',\n message: 'Which script preset would you like to use?',\n name: 'scripts',\n type: 'multiselect',\n },\n {\n initial: defaults.jsPath,\n message: '[js] Where should the JavaScript code be generated?',\n name: 'jsPath',\n type: hasScript('js'),\n },\n {\n initial: defaults.rustCrate,\n message: '[rust] Where is the Rust client crate located?',\n name: 'rustCrate',\n type: hasScript('rust'),\n },\n {\n initial: (prev: string) => `${prev}/src/generated`,\n message: '[rust] Where should the Rust code be generated?',\n name: 'rustPath',\n type: hasScript('rust'),\n },\n ],\n {\n onCancel: () => {\n throw new Error('Operation cancelled.');\n },\n },\n );\n\n return result;\n}\n\nfunction getDefaultPromptResult(): PromptResult {\n return {\n idlPath: 'program/idl.json',\n jsPath: 'clients/js/src/generated',\n rustCrate: 'clients/rust',\n rustPath: 'clients/rust/src/generated',\n scripts: ['js', 'rust'],\n };\n}\n\nfunction getContentFromPromptResult(result: PromptResult, useJsFile: boolean): string {\n const scripts: Record<ScriptName, ScriptConfig> = {};\n if (result.scripts.includes('js')) {\n scripts.js = {\n from: '@codama/renderers-js',\n args: [result.jsPath],\n };\n }\n if (result.scripts.includes('rust')) {\n scripts.rust = {\n from: '@codama/renderers-rust',\n args: [result.rustPath, { crateFolder: result.rustCrate, formatCode: true }],\n };\n }\n const content: Config = { idl: result.idlPath, before: [], scripts };\n\n if (!useJsFile) {\n return JSON.stringify(content, null, 4);\n }\n\n return (\n 'export default ' +\n JSON.stringify(content, null, 4)\n // Remove quotes around property names\n .replace(/\"([^\"]+)\":/g, '$1:')\n // Convert double-quoted strings to single quotes\n .replace(/\"([^\"]*)\"/g, \"'$1'\")\n );\n}\n","import { R_OK, W_OK } from 'node:constants';\nimport fs, { PathLike } from 'node:fs';\nimport path from 'node:path';\n\nexport function resolveRelativePath(childPath: string, relativeDirectory: string | null = null) {\n return path.resolve(relativeDirectory ?? process.cwd(), childPath);\n}\n\nexport function resolveConfigPath(childPath: string, configPath: string | null) {\n const configDir = configPath ? path.dirname(configPath) : null;\n return resolveRelativePath(childPath, configDir);\n}\n\nexport function isLocalModulePath(modulePath: string) {\n return modulePath.startsWith('.') || modulePath.startsWith('/');\n}\n\nexport async function writeFile(filePath: string, content: string) {\n const directory = path.dirname(filePath);\n if (!(await canWrite(directory))) {\n await fs.promises.mkdir(directory, { recursive: true });\n }\n await fs.promises.writeFile(filePath, content);\n}\n\nexport async function canRead(p: PathLike) {\n try {\n await fs.promises.access(p, R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function canWrite(p: PathLike) {\n try {\n await fs.promises.access(p, W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","import { createRequire } from 'node:module';\n\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\nexport async function importModuleItem<T = unknown>(\n identifier: string,\n modulePath: string,\n itemName: string = 'default',\n): Promise<T> {\n const module = await importModule(identifier, modulePath);\n const item = pickModuleItem(module, itemName) as T | undefined;\n if (item === undefined) {\n throw new Error(`Failed to import \"${itemName}\" from ${identifier} at \"${modulePath}\".`);\n }\n return item;\n}\n\ntype ModuleDefinition = Partial<Record<string, unknown>> & {\n __esModule?: boolean;\n default?: Partial<Record<string, unknown>> & { default?: Partial<Record<string, unknown>> };\n};\n\nfunction pickModuleItem(module: ModuleDefinition, itemName: string): unknown {\n if (itemName === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[itemName] ?? module.default?.[itemName] ?? module.default?.default?.[itemName];\n}\n\nasync function importModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (isLocalModulePath(modulePath)) {\n return await importLocalModule(identifier, modulePath);\n }\n\n try {\n return await importExternalUserModule(identifier, modulePath);\n } catch {\n return await importExternalModule(identifier, modulePath);\n }\n}\n\nasync function importLocalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (!(await canRead(modulePath))) {\n throw new Error(`Cannot access ${identifier} at \"${modulePath}\"`);\n }\n\n const dotIndex = modulePath.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : modulePath.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(modulePath, { with: { type: 'json' } }) : import(modulePath);\n return await handleImportPromise(modulePromise, identifier, modulePath);\n}\n\nasync function importExternalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n return await handleImportPromise(import(modulePath), identifier, modulePath);\n}\n\nasync function importExternalUserModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userModulePath = userRequire.resolve(modulePath);\n return await importExternalModule<T>(identifier, userModulePath);\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n identifier: string,\n modulePath: string,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (error) {\n let causeMessage =\n !!error && typeof error === 'object' && 'message' in error && typeof error.message === 'string'\n ? (error as { message: string }).message\n : undefined;\n causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : '';\n throw new Error(`Failed to import ${identifier} at \"${modulePath}\" as a module${causeMessage}`, {\n cause: error,\n });\n }\n}\n","import pico from 'picocolors';\n\nexport function logSuccess(...args: unknown[]): void {\n console.log(pico.green('[Success]'), ...args);\n}\n\nexport function logInfo(...args: unknown[]): void {\n console.log(pico.blueBright('[Info]'), ...args);\n}\n\nexport function logWarning(...args: unknown[]): void {\n console.log(pico.yellow('[Warning]'), ...args);\n}\n\nexport function logError(...args: unknown[]): void {\n console.log(pico.red('[Error]'), ...args);\n}\n\nexport function logDebug(...args: unknown[]): void {\n console.log(pico.magenta('[Debug]'), ...args);\n}\n\nexport function logBanner(): void {\n console.log(getBanner());\n}\n\nfunction getBanner(): string {\n const textBanner = 'Welcome to Codama!';\n const gradientBanner = pico.bold(`\\x1b[38;2;231;171;97m${textBanner}\\x1b[0m`);\n return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { type AnchorIdl, rootNodeFromAnchor } from '@codama/nodes-from-anchor';\n\nexport function getRootNodeFromIdl(idl: unknown): RootNode {\n if (typeof idl !== 'object' || idl === null) {\n throw new Error('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n return rootNodeFromAnchor(idl as AnchorIdl);\n}\n\nexport function isRootNode(value: unknown): value is RootNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { standard?: string }).standard === 'codama' &&\n (value as { kind?: string }).kind === 'rootNode'\n );\n}\n","export function promisify<T>(value: Promise<T> | T): Promise<T> {\n return Promise.resolve(value);\n}\n","import type { RootNode } from '@codama/nodes';\nimport { rootNodeVisitor, visit, type Visitor } from '@codama/visitors-core';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { importModuleItem } from './import';\nimport { isRootNode } from './nodes';\nimport { promisify } from './promises';\n\nexport async function getRootNodeVisitors(\n visitors: readonly ParsedVisitorConfig[],\n): Promise<Visitor<RootNode, 'rootNode'>[]> {\n return await Promise.all(visitors.map(getRootNodeVisitor));\n}\n\nasync function getRootNodeVisitor(visitorConfig: ParsedVisitorConfig): Promise<Visitor<RootNode, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem(identifier, path, item);\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args);\n return rootNodeVisitor(root => {\n const result = visit(root, visitor);\n return isRootNode(result) ? result : root;\n });\n}\n\ntype UnknownFunction = (...args: readonly unknown[]) => unknown;\nasync function getVisitorFromModuleItem(\n identifier: string,\n moduleItem: unknown,\n args: readonly unknown[],\n): Promise<Visitor<unknown, 'rootNode'>> {\n if (isRootNodeVisitor(moduleItem)) {\n return moduleItem;\n }\n if (typeof moduleItem === 'function') {\n const result = await promisify((moduleItem as UnknownFunction)(...args));\n if (isRootNodeVisitor(result)) {\n return result;\n }\n }\n throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`);\n}\n\nfunction isRootNodeVisitor(value: unknown): value is Visitor<unknown, 'rootNode'> {\n return !!value && typeof value === 'object' && 'visitRoot' in value;\n}\n\nfunction getVisitorIdentifier(visitorConfig: ParsedVisitorConfig): string {\n const { index, item, path, script } = visitorConfig;\n const pathWithItem = item ? `${path}#${item}` : path;\n let identifier = `visitor of index #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n identifier += ` (at path \"${pathWithItem}\")`;\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport { getRootNodeVisitors, logInfo, logSuccess, logWarning } from '../utils';\n\nexport function setRunCommand(program: Command): void {\n program\n .command('run')\n .argument('[scripts...]', 'The scripts to execute')\n .option('-a, --all', 'Run all scripts in the config file')\n .action(doRun);\n}\n\ntype RunOptions = {\n all?: boolean;\n};\n\nasync function doRun(explicitScripts: string[], { all }: RunOptions, cmd: Command) {\n if (all && explicitScripts.length > 0) {\n logWarning(`CLI arguments \"${explicitScripts.join(' ')}\" are ignored because the \"--all\" option is set.`);\n }\n const parsedConfig = await getParsedConfigFromCommand(cmd);\n const scripts = all ? Object.keys(parsedConfig.scripts) : explicitScripts;\n const plans = await getPlans(parsedConfig, scripts);\n runPlans(plans, parsedConfig.rootNode);\n}\n\ntype RunPlan = {\n script: ScriptName | null;\n visitors: Visitor<RootNode, 'rootNode'>[];\n};\n\nasync function getPlans(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n): Promise<RunPlan[]> {\n const plans: RunPlan[] = [];\n if (scripts.length === 0 && parsedConfig.before.length === 0) {\n throw new Error('There are no scripts or before visitors to run.');\n }\n\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length > 0) {\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const missingScriptsIdentifier = `${scriptPluralized} \"${missingScripts.join(', ')}\"`;\n const message = parsedConfig.configPath\n ? `${missingScriptsIdentifier} not found in config file \"${parsedConfig.configPath}\"`\n : `${missingScriptsIdentifier} not found because no config file was found`;\n throw new Error(message);\n }\n\n if (parsedConfig.before.length > 0) {\n plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) });\n }\n\n for (const script of scripts) {\n plans.push({ script, visitors: await getRootNodeVisitors(parsedConfig.scripts[script]) });\n }\n\n return plans;\n}\n\nfunction runPlans(plans: RunPlan[], rootNode: RootNode): void {\n for (const plan of plans) {\n const result = runPlan(plan, rootNode);\n if (!plan.script) {\n rootNode = result;\n }\n }\n}\n\nfunction runPlan(plan: RunPlan, rootNode: RootNode): RootNode {\n const visitorLength = plan.visitors.length;\n const visitorPluralized = visitorLength === 1 ? 'visitor' : 'visitors';\n const identifier = plan.script\n ? `script \"${plan.script}\" with ${visitorLength} ${visitorPluralized}`\n : `${visitorLength} before ${visitorPluralized}`;\n logInfo(`Running ${identifier}...`);\n const newRoot = plan.visitors.reduce(visit, rootNode);\n logSuccess(`Executed ${identifier}!`);\n return newRoot;\n}\n","import path from 'node:path';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, importModuleItem, logWarning } from './utils';\n\nexport type Config = Readonly<{\n idl?: string;\n scripts?: ScriptsConfig;\n before?: readonly VisitorConfig[];\n}>;\n\nexport type ScriptName = string;\nexport type ScriptConfig = VisitorConfig | readonly VisitorConfig[];\nexport type ScriptsConfig = Readonly<Record<ScriptName, ScriptConfig>>;\n\nexport type VisitorPath = string;\nexport type VisitorConfig<T extends readonly unknown[] = readonly unknown[]> = VisitorConfigObject<T> | VisitorPath;\nexport type VisitorConfigObject<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args?: T;\n from: VisitorPath;\n}>;\n\nexport async function getConfig(options: Pick<ProgramOptions, 'config'>): Promise<[Config, string | null]> {\n const configPath = options.config != null ? path.resolve(options.config) : await getDefaultConfigPath();\n\n if (!configPath) {\n logWarning('No config file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem('config file', configPath);\n if (!configFile || typeof configFile !== 'object') {\n throw new Error(`Invalid config file at \"${configPath}\"`);\n }\n\n return [configFile, configPath];\n}\n\nasync function getDefaultConfigPath(): Promise<string | null> {\n const candidatePaths = ['codama.js', 'codama.mjs', 'codama.cjs', 'codama.json'];\n for (const candidatePath of candidatePaths) {\n const resolvedPath = path.resolve(process.cwd(), candidatePath);\n if (await canRead(resolvedPath)) {\n return resolvedPath;\n }\n }\n return null;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { Command } from 'commander';\n\nimport { Config, getConfig, ScriptName, ScriptsConfig, VisitorConfig, VisitorPath } from './config';\nimport { ProgramOptions } from './programOptions';\nimport {\n getRootNodeFromIdl,\n importModuleItem,\n isLocalModulePath,\n resolveConfigPath,\n resolveRelativePath,\n} from './utils';\n\nexport type ParsedConfig = Readonly<{\n configPath: string | null;\n idlContent: unknown;\n idlPath: string;\n rootNode: RootNode;\n scripts: ParsedScriptsConfig;\n before: readonly ParsedVisitorConfig[];\n}>;\n\nexport type ParsedScriptsConfig = Readonly<Record<ScriptName, readonly ParsedVisitorConfig[]>>;\nexport type ParsedVisitorConfig<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args: T;\n index: number;\n item: string | undefined;\n path: VisitorPath;\n script: ScriptName | null;\n}>;\n\nexport async function getParsedConfigFromCommand(cmd: Command): Promise<ParsedConfig> {\n return await getParsedConfig(cmd.optsWithGlobals() as ProgramOptions);\n}\n\nexport async function getParsedConfig(options: Pick<ProgramOptions, 'config' | 'idl'>): Promise<ParsedConfig> {\n const [config, configPath] = await getConfig(options);\n return await parseConfig(config, configPath, options);\n}\n\nasync function parseConfig(\n config: Config,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): Promise<ParsedConfig> {\n const idlPath = parseIdlPath(config, configPath, options);\n const idlContent = await importModuleItem('IDL', idlPath);\n const rootNode = getRootNodeFromIdl(idlContent);\n const scripts = parseScripts(config.scripts ?? {}, configPath);\n const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null));\n\n return { configPath, idlContent, idlPath, rootNode, scripts, before: visitors };\n}\n\nfunction parseIdlPath(\n config: Pick<Config, 'idl'>,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): string {\n if (options.idl) {\n return resolveRelativePath(options.idl);\n }\n if (config.idl) {\n return resolveConfigPath(config.idl, configPath);\n }\n throw new Error('No IDL identified. Please provide the `--idl` option or set it in the config file.');\n}\n\nfunction parseScripts(scripts: ScriptsConfig, configPath: string | null): ParsedScriptsConfig {\n const entryPromises = Object.entries(scripts).map(([name, scriptConfig]) => {\n const visitors: readonly VisitorConfig[] = Array.isArray(scriptConfig) ? scriptConfig : [scriptConfig];\n return [name, visitors.map((v, i) => parseVisitorConfig(v, configPath, i, name))] as const;\n });\n return Object.fromEntries(entryPromises);\n}\n\nfunction parseVisitorConfig<T extends readonly unknown[]>(\n visitorConfig: VisitorConfig<T>,\n configPath: string | null,\n index: number,\n script: ScriptName | null,\n): ParsedVisitorConfig<T> {\n const emptyArgs = [] as readonly unknown[] as T;\n const visitorPath = typeof visitorConfig === 'string' ? visitorConfig : visitorConfig.from;\n const visitorArgs = typeof visitorConfig === 'string' ? emptyArgs : (visitorConfig.args ?? emptyArgs);\n const [path, item] = resolveVisitorPath(visitorPath, configPath);\n return { args: visitorArgs, index, item, path, script };\n}\n\nfunction resolveVisitorPath(visitorPath: string, configPath: string | null): readonly [string, string | undefined] {\n const [modulePath, itemName] = visitorPath.split('#') as [string, string | undefined];\n const resolveModulePath = isLocalModulePath(modulePath) ? resolveConfigPath(modulePath, configPath) : modulePath;\n return [resolveModulePath, itemName];\n}\n","import { Command } from 'commander';\n\nexport type ProgramOptions = Readonly<{\n config?: string;\n debug?: boolean;\n idl?: string;\n}>;\n\nexport function setProgramOptions(program: Command): void {\n program\n .option('--debug', 'include debugging information, such as stack dump')\n .option('-i, --idl <path>', 'The path to the IDL to use.')\n .option('-c, --config <path>', 'The path to the Codama configuration file. Defaults to `codama.(js|json)`.');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAuC;;;ACCvC,qBAAoC;;;ACDpC,4BAA2B;AAC3B,qBAA6B;AAC7B,uBAAiB;AAEV,SAAS,oBAAoB,WAAmB,oBAAmC,MAAM;AAC5F,SAAO,iBAAAA,QAAK,QAAQ,qBAAqB,QAAQ,IAAI,GAAG,SAAS;AACrE;AAEO,SAAS,kBAAkB,WAAmB,YAA2B;AAC5E,QAAM,YAAY,aAAa,iBAAAA,QAAK,QAAQ,UAAU,IAAI;AAC1D,SAAO,oBAAoB,WAAW,SAAS;AACnD;A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AG,aAAa,WAAW,iBAAiB;AAClD,UAAQ,WAAW,UAAU,KAAK;AAClC,QAAM,UAAU,KAAK,SAAS,OAAO,6BAAO,QAAQ;AACpD,aAAW,YAAY,UAAU,GAAG;AACpC,SAAO;AACX;;;AG5EO,SAAS,kBAAkB,SAAwB;AACtD,UACK,OAAO,WAAW,mDAAmD,EACrE,OAAO,oBAAoB,6BAA6B,EACxD,OAAO,uBAAuB,4EAA4E;AACnH;;;AXRA,eAAsB,OAAO,MAAgB,MAAoD;AAC7F,QAAM,cAAc;AAAA,IAChB,cAAc;AAAA,IACd,gBAAgB,MAAM;AAAA,EAC1B,CAAC,EAAE,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACxC;AAEO,SAAS,cAAc,iBAAiF;AAC3G,QAAM,cAAU,gCAAc,EACzB,QAAQ,OAAW,EACnB,qBAAqB,KAAK,EAC1B,cAAc,EAAE,mBAAmB,MAAM,aAAa,MAAM,iBAAiB,KAAK,CAAC;AAGxF,oBAAkB,OAAO;AACzB,iBAAe,OAAO;AACtB,gBAAc,OAAO;AAGrB,MAAI,iBAAiB,cAAc;AAC/B,YAAQ,aAAa;AAAA,EACzB;AACA,MAAI,iBAAiB,gBAAgB;AACjC,YAAQ,gBAAgB;AAAA,MACpB,UAAU,MAAM;AAAA,MAAC;AAAA,MACjB,UAAU,MAAM;AAAA,MAAC;AAAA,IACrB,CAAC;AAAA,EACL;AAEA,SAAO;AACX;","names":["path","fs","module","pico","path","prompts","import_visitors_core","import_node_path","path","path"]}
{"version":3,"sources":["../src/index.ts","../src/program.ts","../src/commands/init.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/nodes.ts","../src/utils/promises.ts","../src/utils/visitors.ts","../src/commands/run.ts","../src/config.ts","../src/parsedConfig.ts","../src/programOptions.ts"],"sourcesContent":["export * from './program';\nexport * from './utils/logs';\n","import { Command, createCommand } from 'commander';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n await createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n }).parseAsync(args, { from: 'user' });\n}\n\nexport function createProgram(internalOptions?: { exitOverride?: boolean; suppressOutput?: boolean }): Command {\n const program = createCommand()\n .version(__VERSION__)\n .allowExcessArguments(false)\n .configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });\n\n // Set program options and commands.\n setProgramOptions(program);\n setInitCommand(program);\n setRunCommand(program);\n\n // Internal options.\n if (internalOptions?.exitOverride) {\n program.exitOverride();\n }\n if (internalOptions?.suppressOutput) {\n program.configureOutput({\n writeErr: () => {},\n writeOut: () => {},\n });\n }\n\n return program;\n}\n","import { Command } from 'commander';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport { canRead, logBanner, logSuccess, resolveRelativePath, writeFile } from '../utils';\n\nexport function setInitCommand(program: Command): void {\n program\n .command('init')\n .argument('[output]', 'Optional path used to output the configuration file')\n .option('-d, --default', 'Bypass prompts and select all defaults options')\n .option('--js', 'Forces the output to be a JavaScript file')\n .option('--gill', 'Forces the output to be a gill based JavaScript file')\n .action(doInit);\n}\n\ntype InitOptions = {\n default?: boolean;\n js?: boolean;\n gill?: boolean;\n};\n\ntype ConfigFileType = 'gill' | 'js' | 'json';\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n let configFileType: ConfigFileType = output.endsWith('.js') ? 'js' : 'json';\n if (options.gill) configFileType = 'gill';\n else if (options.js) configFileType = 'js';\n\n if (await canRead(output)) {\n throw new Error(`Configuration file already exists at \"${output}\".`);\n }\n\n logBanner();\n const result = await getPromptResult(options);\n const content = getContentFromPromptResult(result, configFileType);\n await writeFile(output, content);\n logSuccess(`Configuration file created at \"${output}\".`);\n}\n\nfunction getOutputPath(explicitOutput: string | undefined, options: Pick<InitOptions, 'gill' | 'js'>): string {\n if (explicitOutput) {\n return resolveRelativePath(explicitOutput);\n }\n return resolveRelativePath(options.js || options.gill ? 'codama.js' : 'codama.json');\n}\n\ntype PromptResult = {\n idlPath: string;\n jsPath?: string;\n rustCrate?: string;\n rustPath?: string;\n scripts: string[];\n};\n\nasync function getPromptResult(options: Pick<InitOptions, 'default'>): Promise<PromptResult> {\n const defaults = getDefaultPromptResult();\n if (options.default) {\n return defaults;\n }\n\n const hasScript =\n (script: string, type: PromptType = 'text') =>\n (_: unknown, values: { scripts: string[] }) =>\n values.scripts.includes(script) ? type : null;\n const result: PromptResult = await prompts(\n [\n {\n initial: defaults.idlPath,\n message: 'Where is your IDL located? (Supports Codama and Anchor IDLs).',\n name: 'idlPath',\n type: 'text',\n },\n {\n choices: [\n { selected: true, title: 'Generate JavaScript client', value: 'js' },\n { selected: true, title: 'Generate Rust client', value: 'rust' },\n ],\n instructions: '[space] to toggle / [a] to toggle all / [enter] to submit',\n message: 'Which script preset would you like to use?',\n name: 'scripts',\n type: 'multiselect',\n },\n {\n initial: defaults.jsPath,\n message: '[js] Where should the JavaScript code be generated?',\n name: 'jsPath',\n type: hasScript('js'),\n },\n {\n initial: defaults.rustCrate,\n message: '[rust] Where is the Rust client crate located?',\n name: 'rustCrate',\n type: hasScript('rust'),\n },\n {\n initial: (prev: string) => `${prev}/src/generated`,\n message: '[rust] Where should the Rust code be generated?',\n name: 'rustPath',\n type: hasScript('rust'),\n },\n ],\n {\n onCancel: () => {\n throw new Error('Operation cancelled.');\n },\n },\n );\n\n return result;\n}\n\nfunction getDefaultPromptResult(): PromptResult {\n return {\n idlPath: 'program/idl.json',\n jsPath: 'clients/js/src/generated',\n rustCrate: 'clients/rust',\n rustPath: 'clients/rust/src/generated',\n scripts: ['js', 'rust'],\n };\n}\n\nfunction getContentFromPromptResult(result: PromptResult, configFileType: ConfigFileType): string {\n const scripts: Record<ScriptName, ScriptConfig> = {};\n if (result.scripts.includes('js')) {\n scripts.js = {\n from: '@codama/renderers-js',\n args: [result.jsPath],\n };\n }\n if (result.scripts.includes('rust')) {\n scripts.rust = {\n from: '@codama/renderers-rust',\n args: [result.rustPath, { crateFolder: result.rustCrate, formatCode: true }],\n };\n }\n const content: Config = { idl: result.idlPath, before: [], scripts };\n\n if (configFileType == 'json') {\n return JSON.stringify(content, null, 4);\n } else if (configFileType == 'gill') {\n return `import { createCodamaConfig } from \"gill\";\\n\\n` +\n `export default createCodamaConfig({ \\n\\t` +\n `idl: \"${result.idlPath}\", \\n\\t` +\n `clientJs: \"${result.jsPath}\", \\n` +\n result.scripts.includes('rust')\n ? `clientRust: \"${result.rustPath}\", \\n`\n : `` + `});`;\n }\n\n return (\n 'export default ' +\n JSON.stringify(content, null, 4)\n // Remove quotes around property names\n .replace(/\"([^\"]+)\":/g, '$1:')\n // Convert double-quoted strings to single quotes\n .replace(/\"([^\"]*)\"/g, \"'$1'\")\n );\n}\n","import { R_OK, W_OK } from 'node:constants';\nimport fs, { PathLike } from 'node:fs';\nimport path from 'node:path';\n\nexport function resolveRelativePath(childPath: string, relativeDirectory: string | null = null) {\n return path.resolve(relativeDirectory ?? process.cwd(), childPath);\n}\n\nexport function resolveConfigPath(childPath: string, configPath: string | null) {\n const configDir = configPath ? path.dirname(configPath) : null;\n return resolveRelativePath(childPath, configDir);\n}\n\nexport function isLocalModulePath(modulePath: string) {\n return modulePath.startsWith('.') || modulePath.startsWith('/');\n}\n\nexport async function writeFile(filePath: string, content: string) {\n const directory = path.dirname(filePath);\n if (!(await canWrite(directory))) {\n await fs.promises.mkdir(directory, { recursive: true });\n }\n await fs.promises.writeFile(filePath, content);\n}\n\nexport async function canRead(p: PathLike) {\n try {\n await fs.promises.access(p, R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function canWrite(p: PathLike) {\n try {\n await fs.promises.access(p, W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","import { createRequire } from 'node:module';\n\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\nexport async function importModuleItem<T = unknown>(\n identifier: string,\n modulePath: string,\n itemName: string = 'default',\n): Promise<T> {\n const module = await importModule(identifier, modulePath);\n const item = pickModuleItem(module, itemName) as T | undefined;\n if (item === undefined) {\n throw new Error(`Failed to import \"${itemName}\" from ${identifier} at \"${modulePath}\".`);\n }\n return item;\n}\n\ntype ModuleDefinition = Partial<Record<string, unknown>> & {\n __esModule?: boolean;\n default?: Partial<Record<string, unknown>> & { default?: Partial<Record<string, unknown>> };\n};\n\nfunction pickModuleItem(module: ModuleDefinition, itemName: string): unknown {\n if (itemName === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[itemName] ?? module.default?.[itemName] ?? module.default?.default?.[itemName];\n}\n\nasync function importModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (isLocalModulePath(modulePath)) {\n return await importLocalModule(identifier, modulePath);\n }\n\n try {\n return await importExternalUserModule(identifier, modulePath);\n } catch {\n return await importExternalModule(identifier, modulePath);\n }\n}\n\nasync function importLocalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (!(await canRead(modulePath))) {\n throw new Error(`Cannot access ${identifier} at \"${modulePath}\"`);\n }\n\n const dotIndex = modulePath.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : modulePath.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(modulePath, { with: { type: 'json' } }) : import(modulePath);\n return await handleImportPromise(modulePromise, identifier, modulePath);\n}\n\nasync function importExternalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n return await handleImportPromise(import(modulePath), identifier, modulePath);\n}\n\nasync function importExternalUserModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userModulePath = userRequire.resolve(modulePath);\n return await importExternalModule<T>(identifier, userModulePath);\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n identifier: string,\n modulePath: string,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (error) {\n let causeMessage =\n !!error && typeof error === 'object' && 'message' in error && typeof error.message === 'string'\n ? (error as { message: string }).message\n : undefined;\n causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : '';\n throw new Error(`Failed to import ${identifier} at \"${modulePath}\" as a module${causeMessage}`, {\n cause: error,\n });\n }\n}\n","import pico from 'picocolors';\n\nexport function logSuccess(...args: unknown[]): void {\n console.log(pico.green('[Success]'), ...args);\n}\n\nexport function logInfo(...args: unknown[]): void {\n console.log(pico.blueBright('[Info]'), ...args);\n}\n\nexport function logWarning(...args: unknown[]): void {\n console.log(pico.yellow('[Warning]'), ...args);\n}\n\nexport function logError(...args: unknown[]): void {\n console.log(pico.red('[Error]'), ...args);\n}\n\nexport function logDebug(...args: unknown[]): void {\n console.log(pico.magenta('[Debug]'), ...args);\n}\n\nexport function logBanner(): void {\n console.log(getBanner());\n}\n\nfunction getBanner(): string {\n const textBanner = 'Welcome to Codama!';\n const gradientBanner = pico.bold(`\\x1b[38;2;231;171;97m${textBanner}\\x1b[0m`);\n return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { type AnchorIdl, rootNodeFromAnchor } from '@codama/nodes-from-anchor';\n\nexport function getRootNodeFromIdl(idl: unknown): RootNode {\n if (typeof idl !== 'object' || idl === null) {\n throw new Error('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n return rootNodeFromAnchor(idl as AnchorIdl);\n}\n\nexport function isRootNode(value: unknown): value is RootNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { standard?: string }).standard === 'codama' &&\n (value as { kind?: string }).kind === 'rootNode'\n );\n}\n","export function promisify<T>(value: Promise<T> | T): Promise<T> {\n return Promise.resolve(value);\n}\n","import type { RootNode } from '@codama/nodes';\nimport { rootNodeVisitor, visit, type Visitor } from '@codama/visitors-core';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { importModuleItem } from './import';\nimport { isRootNode } from './nodes';\nimport { promisify } from './promises';\n\nexport async function getRootNodeVisitors(\n visitors: readonly ParsedVisitorConfig[],\n): Promise<Visitor<RootNode, 'rootNode'>[]> {\n return await Promise.all(visitors.map(getRootNodeVisitor));\n}\n\nasync function getRootNodeVisitor(visitorConfig: ParsedVisitorConfig): Promise<Visitor<RootNode, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem(identifier, path, item);\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args);\n return rootNodeVisitor(root => {\n const result = visit(root, visitor);\n return isRootNode(result) ? result : root;\n });\n}\n\ntype UnknownFunction = (...args: readonly unknown[]) => unknown;\nasync function getVisitorFromModuleItem(\n identifier: string,\n moduleItem: unknown,\n args: readonly unknown[],\n): Promise<Visitor<unknown, 'rootNode'>> {\n if (isRootNodeVisitor(moduleItem)) {\n return moduleItem;\n }\n if (typeof moduleItem === 'function') {\n const result = await promisify((moduleItem as UnknownFunction)(...args));\n if (isRootNodeVisitor(result)) {\n return result;\n }\n }\n throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`);\n}\n\nfunction isRootNodeVisitor(value: unknown): value is Visitor<unknown, 'rootNode'> {\n return !!value && typeof value === 'object' && 'visitRoot' in value;\n}\n\nfunction getVisitorIdentifier(visitorConfig: ParsedVisitorConfig): string {\n const { index, item, path, script } = visitorConfig;\n const pathWithItem = item ? `${path}#${item}` : path;\n let identifier = `visitor of index #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n identifier += ` (at path \"${pathWithItem}\")`;\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport { getRootNodeVisitors, logInfo, logSuccess, logWarning } from '../utils';\n\nexport function setRunCommand(program: Command): void {\n program\n .command('run')\n .argument('[scripts...]', 'The scripts to execute')\n .option('-a, --all', 'Run all scripts in the config file')\n .action(doRun);\n}\n\ntype RunOptions = {\n all?: boolean;\n};\n\nasync function doRun(explicitScripts: string[], { all }: RunOptions, cmd: Command) {\n if (all && explicitScripts.length > 0) {\n logWarning(`CLI arguments \"${explicitScripts.join(' ')}\" are ignored because the \"--all\" option is set.`);\n }\n const parsedConfig = await getParsedConfigFromCommand(cmd);\n const scripts = all ? Object.keys(parsedConfig.scripts) : explicitScripts;\n const plans = await getPlans(parsedConfig, scripts);\n runPlans(plans, parsedConfig.rootNode);\n}\n\ntype RunPlan = {\n script: ScriptName | null;\n visitors: Visitor<RootNode, 'rootNode'>[];\n};\n\nasync function getPlans(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n): Promise<RunPlan[]> {\n const plans: RunPlan[] = [];\n if (scripts.length === 0 && parsedConfig.before.length === 0) {\n throw new Error('There are no scripts or before visitors to run.');\n }\n\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length > 0) {\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const missingScriptsIdentifier = `${scriptPluralized} \"${missingScripts.join(', ')}\"`;\n const message = parsedConfig.configPath\n ? `${missingScriptsIdentifier} not found in config file \"${parsedConfig.configPath}\"`\n : `${missingScriptsIdentifier} not found because no config file was found`;\n throw new Error(message);\n }\n\n if (parsedConfig.before.length > 0) {\n plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) });\n }\n\n for (const script of scripts) {\n plans.push({ script, visitors: await getRootNodeVisitors(parsedConfig.scripts[script]) });\n }\n\n return plans;\n}\n\nfunction runPlans(plans: RunPlan[], rootNode: RootNode): void {\n for (const plan of plans) {\n const result = runPlan(plan, rootNode);\n if (!plan.script) {\n rootNode = result;\n }\n }\n}\n\nfunction runPlan(plan: RunPlan, rootNode: RootNode): RootNode {\n const visitorLength = plan.visitors.length;\n const visitorPluralized = visitorLength === 1 ? 'visitor' : 'visitors';\n const identifier = plan.script\n ? `script \"${plan.script}\" with ${visitorLength} ${visitorPluralized}`\n : `${visitorLength} before ${visitorPluralized}`;\n logInfo(`Running ${identifier}...`);\n const newRoot = plan.visitors.reduce(visit, rootNode);\n logSuccess(`Executed ${identifier}!`);\n return newRoot;\n}\n","import path from 'node:path';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, importModuleItem, logWarning } from './utils';\n\nexport type Config = Readonly<{\n idl?: string;\n scripts?: ScriptsConfig;\n before?: readonly VisitorConfig[];\n}>;\n\nexport type ScriptName = string;\nexport type ScriptConfig = VisitorConfig | readonly VisitorConfig[];\nexport type ScriptsConfig = Readonly<Record<ScriptName, ScriptConfig>>;\n\nexport type VisitorPath = string;\nexport type VisitorConfig<T extends readonly unknown[] = readonly unknown[]> = VisitorConfigObject<T> | VisitorPath;\nexport type VisitorConfigObject<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args?: T;\n from: VisitorPath;\n}>;\n\nexport async function getConfig(options: Pick<ProgramOptions, 'config'>): Promise<[Config, string | null]> {\n const configPath = options.config != null ? path.resolve(options.config) : await getDefaultConfigPath();\n\n if (!configPath) {\n logWarning('No config file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem('config file', configPath);\n if (!configFile || typeof configFile !== 'object') {\n throw new Error(`Invalid config file at \"${configPath}\"`);\n }\n\n return [configFile, configPath];\n}\n\nasync function getDefaultConfigPath(): Promise<string | null> {\n const candidatePaths = ['codama.js', 'codama.mjs', 'codama.cjs', 'codama.json'];\n for (const candidatePath of candidatePaths) {\n const resolvedPath = path.resolve(process.cwd(), candidatePath);\n if (await canRead(resolvedPath)) {\n return resolvedPath;\n }\n }\n return null;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { Command } from 'commander';\n\nimport { Config, getConfig, ScriptName, ScriptsConfig, VisitorConfig, VisitorPath } from './config';\nimport { ProgramOptions } from './programOptions';\nimport {\n getRootNodeFromIdl,\n importModuleItem,\n isLocalModulePath,\n resolveConfigPath,\n resolveRelativePath,\n} from './utils';\n\nexport type ParsedConfig = Readonly<{\n configPath: string | null;\n idlContent: unknown;\n idlPath: string;\n rootNode: RootNode;\n scripts: ParsedScriptsConfig;\n before: readonly ParsedVisitorConfig[];\n}>;\n\nexport type ParsedScriptsConfig = Readonly<Record<ScriptName, readonly ParsedVisitorConfig[]>>;\nexport type ParsedVisitorConfig<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args: T;\n index: number;\n item: string | undefined;\n path: VisitorPath;\n script: ScriptName | null;\n}>;\n\nexport async function getParsedConfigFromCommand(cmd: Command): Promise<ParsedConfig> {\n return await getParsedConfig(cmd.optsWithGlobals() as ProgramOptions);\n}\n\nexport async function getParsedConfig(options: Pick<ProgramOptions, 'config' | 'idl'>): Promise<ParsedConfig> {\n const [config, configPath] = await getConfig(options);\n return await parseConfig(config, configPath, options);\n}\n\nasync function parseConfig(\n config: Config,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): Promise<ParsedConfig> {\n const idlPath = parseIdlPath(config, configPath, options);\n const idlContent = await importModuleItem('IDL', idlPath);\n const rootNode = getRootNodeFromIdl(idlContent);\n const scripts = parseScripts(config.scripts ?? {}, configPath);\n const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null));\n\n return { configPath, idlContent, idlPath, rootNode, scripts, before: visitors };\n}\n\nfunction parseIdlPath(\n config: Pick<Config, 'idl'>,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): string {\n if (options.idl) {\n return resolveRelativePath(options.idl);\n }\n if (config.idl) {\n return resolveConfigPath(config.idl, configPath);\n }\n throw new Error('No IDL identified. Please provide the `--idl` option or set it in the config file.');\n}\n\nfunction parseScripts(scripts: ScriptsConfig, configPath: string | null): ParsedScriptsConfig {\n const entryPromises = Object.entries(scripts).map(([name, scriptConfig]) => {\n const visitors: readonly VisitorConfig[] = Array.isArray(scriptConfig) ? scriptConfig : [scriptConfig];\n return [name, visitors.map((v, i) => parseVisitorConfig(v, configPath, i, name))] as const;\n });\n return Object.fromEntries(entryPromises);\n}\n\nfunction parseVisitorConfig<T extends readonly unknown[]>(\n visitorConfig: VisitorConfig<T>,\n configPath: string | null,\n index: number,\n script: ScriptName | null,\n): ParsedVisitorConfig<T> {\n const emptyArgs = [] as readonly unknown[] as T;\n const visitorPath = typeof visitorConfig === 'string' ? visitorConfig : visitorConfig.from;\n const visitorArgs = typeof visitorConfig === 'string' ? emptyArgs : (visitorConfig.args ?? emptyArgs);\n const [path, item] = resolveVisitorPath(visitorPath, configPath);\n return { args: visitorArgs, index, item, path, script };\n}\n\nfunction resolveVisitorPath(visitorPath: string, configPath: string | null): readonly [string, string | undefined] {\n const [modulePath, itemName] = visitorPath.split('#') as [string, string | undefined];\n const resolveModulePath = isLocalModulePath(modulePath) ? resolveConfigPath(modulePath, configPath) : modulePath;\n return [resolveModulePath, itemName];\n}\n","import { Command } from 'commander';\n\nexport type ProgramOptions = Readonly<{\n config?: string;\n debug?: boolean;\n idl?: string;\n}>;\n\nexport function setProgramOptions(program: Command): void {\n program\n .option('--debug', 'include debugging information, such as stack dump')\n .option('-i, --idl <path>', 'The path to the IDL to use.')\n .option('-c, --config <path>', 'The path to the Codama configuration file. Defaults to `codama.(js|json)`.');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAuC;;;ACCvC,qBAAoC;;;ACDpC,4BAA2B;AAC3B,qBAA6B;AAC7B,uBAAiB;AAEV,SAAS,oBAAoB,WAAmB,oBAAmC,MAAM;AAC5F,SAAO,iBAAAA,QAAK,QAAQ,qBAAqB,QAAQ,IAAI,GAAG,SAAS;AACrE;AAEO,SAAS,kBAAkB,WAAmB,YAA2B;AAC5E,QAAM,YAAY,a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,IACrB,CAAC;AAAA,EACL;AAEA,SAAO;AACX;","names":["path","fs","module","pico","path","prompts","import_visitors_core","import_node_path","path","path"]}

@@ -188,7 +188,9 @@ // src/program.ts

function setInitCommand(program) {
program.command("init").argument("[output]", "Optional path used to output the configuration file").option("-d, --default", "Bypass prompts and select all defaults options").option("--js", "Forces the output to be a JavaScript file").action(doInit);
program.command("init").argument("[output]", "Optional path used to output the configuration file").option("-d, --default", "Bypass prompts and select all defaults options").option("--js", "Forces the output to be a JavaScript file").option("--gill", "Forces the output to be a gill based JavaScript file").action(doInit);
}
async function doInit(explicitOutput, options) {
const output = getOutputPath(explicitOutput, options);
const useJsFile = options.js || output.endsWith(".js");
let configFileType = output.endsWith(".js") ? "js" : "json";
if (options.gill) configFileType = "gill";
else if (options.js) configFileType = "js";
if (await canRead(output)) {

@@ -199,3 +201,3 @@ throw new Error(`Configuration file already exists at "${output}".`);

const result = await getPromptResult(options);
const content = getContentFromPromptResult(result, useJsFile);
const content = getContentFromPromptResult(result, configFileType);
await writeFile(output, content);

@@ -208,3 +210,3 @@ logSuccess(`Configuration file created at "${output}".`);

}
return resolveRelativePath(options.js ? "codama.js" : "codama.json");
return resolveRelativePath(options.js || options.gill ? "codama.js" : "codama.json");
}

@@ -271,3 +273,3 @@ async function getPromptResult(options) {

}
function getContentFromPromptResult(result, useJsFile) {
function getContentFromPromptResult(result, configFileType) {
const scripts = {};

@@ -287,4 +289,12 @@ if (result.scripts.includes("js")) {

const content = { idl: result.idlPath, before: [], scripts };
if (!useJsFile) {
if (configFileType == "json") {
return JSON.stringify(content, null, 4);
} else if (configFileType == "gill") {
return `import { createCodamaConfig } from "gill";
export default createCodamaConfig({
idl: "${result.idlPath}",
clientJs: "${result.jsPath}",
` + result.scripts.includes("rust") ? `clientRust: "${result.rustPath}",
` : `});`;
}

@@ -431,3 +441,3 @@ return "export default " + JSON.stringify(content, null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'");

function createProgram(internalOptions) {
const program = createCommand().version("1.1.4").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });
const program = createCommand().version("1.2.0").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });
setProgramOptions(program);

@@ -434,0 +444,0 @@ setInitCommand(program);

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/program.ts","../src/commands/init.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/nodes.ts","../src/utils/promises.ts","../src/utils/visitors.ts","../src/commands/run.ts","../src/config.ts","../src/parsedConfig.ts","../src/programOptions.ts"],"sourcesContent":["import { Command, createCommand } from 'commander';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n await createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n }).parseAsync(args, { from: 'user' });\n}\n\nexport function createProgram(internalOptions?: { exitOverride?: boolean; suppressOutput?: boolean }): Command {\n const program = createCommand()\n .version(__VERSION__)\n .allowExcessArguments(false)\n .configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });\n\n // Set program options and commands.\n setProgramOptions(program);\n setInitCommand(program);\n setRunCommand(program);\n\n // Internal options.\n if (internalOptions?.exitOverride) {\n program.exitOverride();\n }\n if (internalOptions?.suppressOutput) {\n program.configureOutput({\n writeErr: () => {},\n writeOut: () => {},\n });\n }\n\n return program;\n}\n","import { Command } from 'commander';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport { canRead, logBanner, logSuccess, resolveRelativePath, writeFile } from '../utils';\n\nexport function setInitCommand(program: Command): void {\n program\n .command('init')\n .argument('[output]', 'Optional path used to output the configuration file')\n .option('-d, --default', 'Bypass prompts and select all defaults options')\n .option('--js', 'Forces the output to be a JavaScript file')\n .action(doInit);\n}\n\ntype InitOptions = {\n default?: boolean;\n js?: boolean;\n};\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n const useJsFile = options.js || output.endsWith('.js');\n if (await canRead(output)) {\n throw new Error(`Configuration file already exists at \"${output}\".`);\n }\n\n logBanner();\n const result = await getPromptResult(options);\n const content = getContentFromPromptResult(result, useJsFile);\n await writeFile(output, content);\n logSuccess(`Configuration file created at \"${output}\".`);\n}\n\nfunction getOutputPath(explicitOutput: string | undefined, options: Pick<InitOptions, 'js'>): string {\n if (explicitOutput) {\n return resolveRelativePath(explicitOutput);\n }\n return resolveRelativePath(options.js ? 'codama.js' : 'codama.json');\n}\n\ntype PromptResult = {\n idlPath: string;\n jsPath?: string;\n rustCrate?: string;\n rustPath?: string;\n scripts: string[];\n};\n\nasync function getPromptResult(options: Pick<InitOptions, 'default'>): Promise<PromptResult> {\n const defaults = getDefaultPromptResult();\n if (options.default) {\n return defaults;\n }\n\n const hasScript =\n (script: string, type: PromptType = 'text') =>\n (_: unknown, values: { scripts: string[] }) =>\n values.scripts.includes(script) ? type : null;\n const result: PromptResult = await prompts(\n [\n {\n initial: defaults.idlPath,\n message: 'Where is your IDL located? (Supports Codama and Anchor IDLs).',\n name: 'idlPath',\n type: 'text',\n },\n {\n choices: [\n { selected: true, title: 'Generate JavaScript client', value: 'js' },\n { selected: true, title: 'Generate Rust client', value: 'rust' },\n ],\n instructions: '[space] to toggle / [a] to toggle all / [enter] to submit',\n message: 'Which script preset would you like to use?',\n name: 'scripts',\n type: 'multiselect',\n },\n {\n initial: defaults.jsPath,\n message: '[js] Where should the JavaScript code be generated?',\n name: 'jsPath',\n type: hasScript('js'),\n },\n {\n initial: defaults.rustCrate,\n message: '[rust] Where is the Rust client crate located?',\n name: 'rustCrate',\n type: hasScript('rust'),\n },\n {\n initial: (prev: string) => `${prev}/src/generated`,\n message: '[rust] Where should the Rust code be generated?',\n name: 'rustPath',\n type: hasScript('rust'),\n },\n ],\n {\n onCancel: () => {\n throw new Error('Operation cancelled.');\n },\n },\n );\n\n return result;\n}\n\nfunction getDefaultPromptResult(): PromptResult {\n return {\n idlPath: 'program/idl.json',\n jsPath: 'clients/js/src/generated',\n rustCrate: 'clients/rust',\n rustPath: 'clients/rust/src/generated',\n scripts: ['js', 'rust'],\n };\n}\n\nfunction getContentFromPromptResult(result: PromptResult, useJsFile: boolean): string {\n const scripts: Record<ScriptName, ScriptConfig> = {};\n if (result.scripts.includes('js')) {\n scripts.js = {\n from: '@codama/renderers-js',\n args: [result.jsPath],\n };\n }\n if (result.scripts.includes('rust')) {\n scripts.rust = {\n from: '@codama/renderers-rust',\n args: [result.rustPath, { crateFolder: result.rustCrate, formatCode: true }],\n };\n }\n const content: Config = { idl: result.idlPath, before: [], scripts };\n\n if (!useJsFile) {\n return JSON.stringify(content, null, 4);\n }\n\n return (\n 'export default ' +\n JSON.stringify(content, null, 4)\n // Remove quotes around property names\n .replace(/\"([^\"]+)\":/g, '$1:')\n // Convert double-quoted strings to single quotes\n .replace(/\"([^\"]*)\"/g, \"'$1'\")\n );\n}\n","import { R_OK, W_OK } from 'node:constants';\nimport fs, { PathLike } from 'node:fs';\nimport path from 'node:path';\n\nexport function resolveRelativePath(childPath: string, relativeDirectory: string | null = null) {\n return path.resolve(relativeDirectory ?? process.cwd(), childPath);\n}\n\nexport function resolveConfigPath(childPath: string, configPath: string | null) {\n const configDir = configPath ? path.dirname(configPath) : null;\n return resolveRelativePath(childPath, configDir);\n}\n\nexport function isLocalModulePath(modulePath: string) {\n return modulePath.startsWith('.') || modulePath.startsWith('/');\n}\n\nexport async function writeFile(filePath: string, content: string) {\n const directory = path.dirname(filePath);\n if (!(await canWrite(directory))) {\n await fs.promises.mkdir(directory, { recursive: true });\n }\n await fs.promises.writeFile(filePath, content);\n}\n\nexport async function canRead(p: PathLike) {\n try {\n await fs.promises.access(p, R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function canWrite(p: PathLike) {\n try {\n await fs.promises.access(p, W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","import { createRequire } from 'node:module';\n\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\nexport async function importModuleItem<T = unknown>(\n identifier: string,\n modulePath: string,\n itemName: string = 'default',\n): Promise<T> {\n const module = await importModule(identifier, modulePath);\n const item = pickModuleItem(module, itemName) as T | undefined;\n if (item === undefined) {\n throw new Error(`Failed to import \"${itemName}\" from ${identifier} at \"${modulePath}\".`);\n }\n return item;\n}\n\ntype ModuleDefinition = Partial<Record<string, unknown>> & {\n __esModule?: boolean;\n default?: Partial<Record<string, unknown>> & { default?: Partial<Record<string, unknown>> };\n};\n\nfunction pickModuleItem(module: ModuleDefinition, itemName: string): unknown {\n if (itemName === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[itemName] ?? module.default?.[itemName] ?? module.default?.default?.[itemName];\n}\n\nasync function importModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (isLocalModulePath(modulePath)) {\n return await importLocalModule(identifier, modulePath);\n }\n\n try {\n return await importExternalUserModule(identifier, modulePath);\n } catch {\n return await importExternalModule(identifier, modulePath);\n }\n}\n\nasync function importLocalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (!(await canRead(modulePath))) {\n throw new Error(`Cannot access ${identifier} at \"${modulePath}\"`);\n }\n\n const dotIndex = modulePath.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : modulePath.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(modulePath, { with: { type: 'json' } }) : import(modulePath);\n return await handleImportPromise(modulePromise, identifier, modulePath);\n}\n\nasync function importExternalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n return await handleImportPromise(import(modulePath), identifier, modulePath);\n}\n\nasync function importExternalUserModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userModulePath = userRequire.resolve(modulePath);\n return await importExternalModule<T>(identifier, userModulePath);\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n identifier: string,\n modulePath: string,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (error) {\n let causeMessage =\n !!error && typeof error === 'object' && 'message' in error && typeof error.message === 'string'\n ? (error as { message: string }).message\n : undefined;\n causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : '';\n throw new Error(`Failed to import ${identifier} at \"${modulePath}\" as a module${causeMessage}`, {\n cause: error,\n });\n }\n}\n","import pico from 'picocolors';\n\nexport function logSuccess(...args: unknown[]): void {\n console.log(pico.green('[Success]'), ...args);\n}\n\nexport function logInfo(...args: unknown[]): void {\n console.log(pico.blueBright('[Info]'), ...args);\n}\n\nexport function logWarning(...args: unknown[]): void {\n console.log(pico.yellow('[Warning]'), ...args);\n}\n\nexport function logError(...args: unknown[]): void {\n console.log(pico.red('[Error]'), ...args);\n}\n\nexport function logDebug(...args: unknown[]): void {\n console.log(pico.magenta('[Debug]'), ...args);\n}\n\nexport function logBanner(): void {\n console.log(getBanner());\n}\n\nfunction getBanner(): string {\n const textBanner = 'Welcome to Codama!';\n const gradientBanner = pico.bold(`\\x1b[38;2;231;171;97m${textBanner}\\x1b[0m`);\n return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { type AnchorIdl, rootNodeFromAnchor } from '@codama/nodes-from-anchor';\n\nexport function getRootNodeFromIdl(idl: unknown): RootNode {\n if (typeof idl !== 'object' || idl === null) {\n throw new Error('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n return rootNodeFromAnchor(idl as AnchorIdl);\n}\n\nexport function isRootNode(value: unknown): value is RootNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { standard?: string }).standard === 'codama' &&\n (value as { kind?: string }).kind === 'rootNode'\n );\n}\n","export function promisify<T>(value: Promise<T> | T): Promise<T> {\n return Promise.resolve(value);\n}\n","import type { RootNode } from '@codama/nodes';\nimport { rootNodeVisitor, visit, type Visitor } from '@codama/visitors-core';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { importModuleItem } from './import';\nimport { isRootNode } from './nodes';\nimport { promisify } from './promises';\n\nexport async function getRootNodeVisitors(\n visitors: readonly ParsedVisitorConfig[],\n): Promise<Visitor<RootNode, 'rootNode'>[]> {\n return await Promise.all(visitors.map(getRootNodeVisitor));\n}\n\nasync function getRootNodeVisitor(visitorConfig: ParsedVisitorConfig): Promise<Visitor<RootNode, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem(identifier, path, item);\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args);\n return rootNodeVisitor(root => {\n const result = visit(root, visitor);\n return isRootNode(result) ? result : root;\n });\n}\n\ntype UnknownFunction = (...args: readonly unknown[]) => unknown;\nasync function getVisitorFromModuleItem(\n identifier: string,\n moduleItem: unknown,\n args: readonly unknown[],\n): Promise<Visitor<unknown, 'rootNode'>> {\n if (isRootNodeVisitor(moduleItem)) {\n return moduleItem;\n }\n if (typeof moduleItem === 'function') {\n const result = await promisify((moduleItem as UnknownFunction)(...args));\n if (isRootNodeVisitor(result)) {\n return result;\n }\n }\n throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`);\n}\n\nfunction isRootNodeVisitor(value: unknown): value is Visitor<unknown, 'rootNode'> {\n return !!value && typeof value === 'object' && 'visitRoot' in value;\n}\n\nfunction getVisitorIdentifier(visitorConfig: ParsedVisitorConfig): string {\n const { index, item, path, script } = visitorConfig;\n const pathWithItem = item ? `${path}#${item}` : path;\n let identifier = `visitor of index #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n identifier += ` (at path \"${pathWithItem}\")`;\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport { getRootNodeVisitors, logInfo, logSuccess, logWarning } from '../utils';\n\nexport function setRunCommand(program: Command): void {\n program\n .command('run')\n .argument('[scripts...]', 'The scripts to execute')\n .option('-a, --all', 'Run all scripts in the config file')\n .action(doRun);\n}\n\ntype RunOptions = {\n all?: boolean;\n};\n\nasync function doRun(explicitScripts: string[], { all }: RunOptions, cmd: Command) {\n if (all && explicitScripts.length > 0) {\n logWarning(`CLI arguments \"${explicitScripts.join(' ')}\" are ignored because the \"--all\" option is set.`);\n }\n const parsedConfig = await getParsedConfigFromCommand(cmd);\n const scripts = all ? Object.keys(parsedConfig.scripts) : explicitScripts;\n const plans = await getPlans(parsedConfig, scripts);\n runPlans(plans, parsedConfig.rootNode);\n}\n\ntype RunPlan = {\n script: ScriptName | null;\n visitors: Visitor<RootNode, 'rootNode'>[];\n};\n\nasync function getPlans(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n): Promise<RunPlan[]> {\n const plans: RunPlan[] = [];\n if (scripts.length === 0 && parsedConfig.before.length === 0) {\n throw new Error('There are no scripts or before visitors to run.');\n }\n\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length > 0) {\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const missingScriptsIdentifier = `${scriptPluralized} \"${missingScripts.join(', ')}\"`;\n const message = parsedConfig.configPath\n ? `${missingScriptsIdentifier} not found in config file \"${parsedConfig.configPath}\"`\n : `${missingScriptsIdentifier} not found because no config file was found`;\n throw new Error(message);\n }\n\n if (parsedConfig.before.length > 0) {\n plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) });\n }\n\n for (const script of scripts) {\n plans.push({ script, visitors: await getRootNodeVisitors(parsedConfig.scripts[script]) });\n }\n\n return plans;\n}\n\nfunction runPlans(plans: RunPlan[], rootNode: RootNode): void {\n for (const plan of plans) {\n const result = runPlan(plan, rootNode);\n if (!plan.script) {\n rootNode = result;\n }\n }\n}\n\nfunction runPlan(plan: RunPlan, rootNode: RootNode): RootNode {\n const visitorLength = plan.visitors.length;\n const visitorPluralized = visitorLength === 1 ? 'visitor' : 'visitors';\n const identifier = plan.script\n ? `script \"${plan.script}\" with ${visitorLength} ${visitorPluralized}`\n : `${visitorLength} before ${visitorPluralized}`;\n logInfo(`Running ${identifier}...`);\n const newRoot = plan.visitors.reduce(visit, rootNode);\n logSuccess(`Executed ${identifier}!`);\n return newRoot;\n}\n","import path from 'node:path';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, importModuleItem, logWarning } from './utils';\n\nexport type Config = Readonly<{\n idl?: string;\n scripts?: ScriptsConfig;\n before?: readonly VisitorConfig[];\n}>;\n\nexport type ScriptName = string;\nexport type ScriptConfig = VisitorConfig | readonly VisitorConfig[];\nexport type ScriptsConfig = Readonly<Record<ScriptName, ScriptConfig>>;\n\nexport type VisitorPath = string;\nexport type VisitorConfig<T extends readonly unknown[] = readonly unknown[]> = VisitorConfigObject<T> | VisitorPath;\nexport type VisitorConfigObject<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args?: T;\n from: VisitorPath;\n}>;\n\nexport async function getConfig(options: Pick<ProgramOptions, 'config'>): Promise<[Config, string | null]> {\n const configPath = options.config != null ? path.resolve(options.config) : await getDefaultConfigPath();\n\n if (!configPath) {\n logWarning('No config file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem('config file', configPath);\n if (!configFile || typeof configFile !== 'object') {\n throw new Error(`Invalid config file at \"${configPath}\"`);\n }\n\n return [configFile, configPath];\n}\n\nasync function getDefaultConfigPath(): Promise<string | null> {\n const candidatePaths = ['codama.js', 'codama.mjs', 'codama.cjs', 'codama.json'];\n for (const candidatePath of candidatePaths) {\n const resolvedPath = path.resolve(process.cwd(), candidatePath);\n if (await canRead(resolvedPath)) {\n return resolvedPath;\n }\n }\n return null;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { Command } from 'commander';\n\nimport { Config, getConfig, ScriptName, ScriptsConfig, VisitorConfig, VisitorPath } from './config';\nimport { ProgramOptions } from './programOptions';\nimport {\n getRootNodeFromIdl,\n importModuleItem,\n isLocalModulePath,\n resolveConfigPath,\n resolveRelativePath,\n} from './utils';\n\nexport type ParsedConfig = Readonly<{\n configPath: string | null;\n idlContent: unknown;\n idlPath: string;\n rootNode: RootNode;\n scripts: ParsedScriptsConfig;\n before: readonly ParsedVisitorConfig[];\n}>;\n\nexport type ParsedScriptsConfig = Readonly<Record<ScriptName, readonly ParsedVisitorConfig[]>>;\nexport type ParsedVisitorConfig<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args: T;\n index: number;\n item: string | undefined;\n path: VisitorPath;\n script: ScriptName | null;\n}>;\n\nexport async function getParsedConfigFromCommand(cmd: Command): Promise<ParsedConfig> {\n return await getParsedConfig(cmd.optsWithGlobals() as ProgramOptions);\n}\n\nexport async function getParsedConfig(options: Pick<ProgramOptions, 'config' | 'idl'>): Promise<ParsedConfig> {\n const [config, configPath] = await getConfig(options);\n return await parseConfig(config, configPath, options);\n}\n\nasync function parseConfig(\n config: Config,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): Promise<ParsedConfig> {\n const idlPath = parseIdlPath(config, configPath, options);\n const idlContent = await importModuleItem('IDL', idlPath);\n const rootNode = getRootNodeFromIdl(idlContent);\n const scripts = parseScripts(config.scripts ?? {}, configPath);\n const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null));\n\n return { configPath, idlContent, idlPath, rootNode, scripts, before: visitors };\n}\n\nfunction parseIdlPath(\n config: Pick<Config, 'idl'>,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): string {\n if (options.idl) {\n return resolveRelativePath(options.idl);\n }\n if (config.idl) {\n return resolveConfigPath(config.idl, configPath);\n }\n throw new Error('No IDL identified. Please provide the `--idl` option or set it in the config file.');\n}\n\nfunction parseScripts(scripts: ScriptsConfig, configPath: string | null): ParsedScriptsConfig {\n const entryPromises = Object.entries(scripts).map(([name, scriptConfig]) => {\n const visitors: readonly VisitorConfig[] = Array.isArray(scriptConfig) ? scriptConfig : [scriptConfig];\n return [name, visitors.map((v, i) => parseVisitorConfig(v, configPath, i, name))] as const;\n });\n return Object.fromEntries(entryPromises);\n}\n\nfunction parseVisitorConfig<T extends readonly unknown[]>(\n visitorConfig: VisitorConfig<T>,\n configPath: string | null,\n index: number,\n script: ScriptName | null,\n): ParsedVisitorConfig<T> {\n const emptyArgs = [] as readonly unknown[] as T;\n const visitorPath = typeof visitorConfig === 'string' ? visitorConfig : visitorConfig.from;\n const visitorArgs = typeof visitorConfig === 'string' ? emptyArgs : (visitorConfig.args ?? emptyArgs);\n const [path, item] = resolveVisitorPath(visitorPath, configPath);\n return { args: visitorArgs, index, item, path, script };\n}\n\nfunction resolveVisitorPath(visitorPath: string, configPath: string | null): readonly [string, string | undefined] {\n const [modulePath, itemName] = visitorPath.split('#') as [string, string | undefined];\n const resolveModulePath = isLocalModulePath(modulePath) ? resolveConfigPath(modulePath, configPath) : modulePath;\n return [resolveModulePath, itemName];\n}\n","import { Command } from 'commander';\n\nexport type ProgramOptions = Readonly<{\n config?: string;\n debug?: boolean;\n idl?: string;\n}>;\n\nexport function setProgramOptions(program: Command): void {\n program\n .option('--debug', 'include debugging information, such as stack dump')\n .option('-i, --idl <path>', 'The path to the IDL to use.')\n .option('-c, --config <path>', 'The path to the Codama configuration file. Defaults to `codama.(js|json)`.');\n}\n"],"mappings":";AAAA,SAAkB,qBAAqB;;;ACCvC,OAAO,aAA6B;;;ACDpC,SAAS,MAAM,YAAY;AAC3B,OAAO,QAAsB;AAC7B,OAAO,UAAU;AAEV,SAAS,oBAAoB,WAAmB,oBAAmC,MAAM;AAC5F,SAAO,KAAK,QAAQ,qBAAqB,QAAQ,IAAI,GAAG,SAAS;AACrE;AAEO,SAAS,kBAAkB,WAAmB,YAA2B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G,aAAa,WAAW,iBAAiB;AAClD,UAAQ,WAAW,UAAU,KAAK;AAClC,QAAM,UAAU,KAAK,SAAS,OAAOC,QAAO,QAAQ;AACpD,aAAW,YAAY,UAAU,GAAG;AACpC,SAAO;AACX;;;AG5EO,SAAS,kBAAkB,SAAwB;AACtD,UACK,OAAO,WAAW,mDAAmD,EACrE,OAAO,oBAAoB,6BAA6B,EACxD,OAAO,uBAAuB,4EAA4E;AACnH;;;AXRA,eAAsB,OAAO,MAAgB,MAAoD;AAC7F,QAAM,cAAc;AAAA,IAChB,cAAc;AAAA,IACd,gBAAgB,MAAM;AAAA,EAC1B,CAAC,EAAE,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACxC;AAEO,SAAS,cAAc,iBAAiF;AAC3G,QAAM,UAAU,cAAc,EACzB,QAAQ,OAAW,EACnB,qBAAqB,KAAK,EAC1B,cAAc,EAAE,mBAAmB,MAAM,aAAa,MAAM,iBAAiB,KAAK,CAAC;AAGxF,oBAAkB,OAAO;AACzB,iBAAe,OAAO;AACtB,gBAAc,OAAO;AAGrB,MAAI,iBAAiB,cAAc;AAC/B,YAAQ,aAAa;AAAA,EACzB;AACA,MAAI,iBAAiB,gBAAgB;AACjC,YAAQ,gBAAgB;AAAA,MACpB,UAAU,MAAM;AAAA,MAAC;AAAA,MACjB,UAAU,MAAM;AAAA,MAAC;AAAA,IACrB,CAAC;AAAA,EACL;AAEA,SAAO;AACX;","names":["path","visit","path","path","path","visit"]}
{"version":3,"sources":["../src/program.ts","../src/commands/init.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/nodes.ts","../src/utils/promises.ts","../src/utils/visitors.ts","../src/commands/run.ts","../src/config.ts","../src/parsedConfig.ts","../src/programOptions.ts"],"sourcesContent":["import { Command, createCommand } from 'commander';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n await createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n }).parseAsync(args, { from: 'user' });\n}\n\nexport function createProgram(internalOptions?: { exitOverride?: boolean; suppressOutput?: boolean }): Command {\n const program = createCommand()\n .version(__VERSION__)\n .allowExcessArguments(false)\n .configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true });\n\n // Set program options and commands.\n setProgramOptions(program);\n setInitCommand(program);\n setRunCommand(program);\n\n // Internal options.\n if (internalOptions?.exitOverride) {\n program.exitOverride();\n }\n if (internalOptions?.suppressOutput) {\n program.configureOutput({\n writeErr: () => {},\n writeOut: () => {},\n });\n }\n\n return program;\n}\n","import { Command } from 'commander';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport { canRead, logBanner, logSuccess, resolveRelativePath, writeFile } from '../utils';\n\nexport function setInitCommand(program: Command): void {\n program\n .command('init')\n .argument('[output]', 'Optional path used to output the configuration file')\n .option('-d, --default', 'Bypass prompts and select all defaults options')\n .option('--js', 'Forces the output to be a JavaScript file')\n .option('--gill', 'Forces the output to be a gill based JavaScript file')\n .action(doInit);\n}\n\ntype InitOptions = {\n default?: boolean;\n js?: boolean;\n gill?: boolean;\n};\n\ntype ConfigFileType = 'gill' | 'js' | 'json';\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n let configFileType: ConfigFileType = output.endsWith('.js') ? 'js' : 'json';\n if (options.gill) configFileType = 'gill';\n else if (options.js) configFileType = 'js';\n\n if (await canRead(output)) {\n throw new Error(`Configuration file already exists at \"${output}\".`);\n }\n\n logBanner();\n const result = await getPromptResult(options);\n const content = getContentFromPromptResult(result, configFileType);\n await writeFile(output, content);\n logSuccess(`Configuration file created at \"${output}\".`);\n}\n\nfunction getOutputPath(explicitOutput: string | undefined, options: Pick<InitOptions, 'gill' | 'js'>): string {\n if (explicitOutput) {\n return resolveRelativePath(explicitOutput);\n }\n return resolveRelativePath(options.js || options.gill ? 'codama.js' : 'codama.json');\n}\n\ntype PromptResult = {\n idlPath: string;\n jsPath?: string;\n rustCrate?: string;\n rustPath?: string;\n scripts: string[];\n};\n\nasync function getPromptResult(options: Pick<InitOptions, 'default'>): Promise<PromptResult> {\n const defaults = getDefaultPromptResult();\n if (options.default) {\n return defaults;\n }\n\n const hasScript =\n (script: string, type: PromptType = 'text') =>\n (_: unknown, values: { scripts: string[] }) =>\n values.scripts.includes(script) ? type : null;\n const result: PromptResult = await prompts(\n [\n {\n initial: defaults.idlPath,\n message: 'Where is your IDL located? (Supports Codama and Anchor IDLs).',\n name: 'idlPath',\n type: 'text',\n },\n {\n choices: [\n { selected: true, title: 'Generate JavaScript client', value: 'js' },\n { selected: true, title: 'Generate Rust client', value: 'rust' },\n ],\n instructions: '[space] to toggle / [a] to toggle all / [enter] to submit',\n message: 'Which script preset would you like to use?',\n name: 'scripts',\n type: 'multiselect',\n },\n {\n initial: defaults.jsPath,\n message: '[js] Where should the JavaScript code be generated?',\n name: 'jsPath',\n type: hasScript('js'),\n },\n {\n initial: defaults.rustCrate,\n message: '[rust] Where is the Rust client crate located?',\n name: 'rustCrate',\n type: hasScript('rust'),\n },\n {\n initial: (prev: string) => `${prev}/src/generated`,\n message: '[rust] Where should the Rust code be generated?',\n name: 'rustPath',\n type: hasScript('rust'),\n },\n ],\n {\n onCancel: () => {\n throw new Error('Operation cancelled.');\n },\n },\n );\n\n return result;\n}\n\nfunction getDefaultPromptResult(): PromptResult {\n return {\n idlPath: 'program/idl.json',\n jsPath: 'clients/js/src/generated',\n rustCrate: 'clients/rust',\n rustPath: 'clients/rust/src/generated',\n scripts: ['js', 'rust'],\n };\n}\n\nfunction getContentFromPromptResult(result: PromptResult, configFileType: ConfigFileType): string {\n const scripts: Record<ScriptName, ScriptConfig> = {};\n if (result.scripts.includes('js')) {\n scripts.js = {\n from: '@codama/renderers-js',\n args: [result.jsPath],\n };\n }\n if (result.scripts.includes('rust')) {\n scripts.rust = {\n from: '@codama/renderers-rust',\n args: [result.rustPath, { crateFolder: result.rustCrate, formatCode: true }],\n };\n }\n const content: Config = { idl: result.idlPath, before: [], scripts };\n\n if (configFileType == 'json') {\n return JSON.stringify(content, null, 4);\n } else if (configFileType == 'gill') {\n return `import { createCodamaConfig } from \"gill\";\\n\\n` +\n `export default createCodamaConfig({ \\n\\t` +\n `idl: \"${result.idlPath}\", \\n\\t` +\n `clientJs: \"${result.jsPath}\", \\n` +\n result.scripts.includes('rust')\n ? `clientRust: \"${result.rustPath}\", \\n`\n : `` + `});`;\n }\n\n return (\n 'export default ' +\n JSON.stringify(content, null, 4)\n // Remove quotes around property names\n .replace(/\"([^\"]+)\":/g, '$1:')\n // Convert double-quoted strings to single quotes\n .replace(/\"([^\"]*)\"/g, \"'$1'\")\n );\n}\n","import { R_OK, W_OK } from 'node:constants';\nimport fs, { PathLike } from 'node:fs';\nimport path from 'node:path';\n\nexport function resolveRelativePath(childPath: string, relativeDirectory: string | null = null) {\n return path.resolve(relativeDirectory ?? process.cwd(), childPath);\n}\n\nexport function resolveConfigPath(childPath: string, configPath: string | null) {\n const configDir = configPath ? path.dirname(configPath) : null;\n return resolveRelativePath(childPath, configDir);\n}\n\nexport function isLocalModulePath(modulePath: string) {\n return modulePath.startsWith('.') || modulePath.startsWith('/');\n}\n\nexport async function writeFile(filePath: string, content: string) {\n const directory = path.dirname(filePath);\n if (!(await canWrite(directory))) {\n await fs.promises.mkdir(directory, { recursive: true });\n }\n await fs.promises.writeFile(filePath, content);\n}\n\nexport async function canRead(p: PathLike) {\n try {\n await fs.promises.access(p, R_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function canWrite(p: PathLike) {\n try {\n await fs.promises.access(p, W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","import { createRequire } from 'node:module';\n\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\nexport async function importModuleItem<T = unknown>(\n identifier: string,\n modulePath: string,\n itemName: string = 'default',\n): Promise<T> {\n const module = await importModule(identifier, modulePath);\n const item = pickModuleItem(module, itemName) as T | undefined;\n if (item === undefined) {\n throw new Error(`Failed to import \"${itemName}\" from ${identifier} at \"${modulePath}\".`);\n }\n return item;\n}\n\ntype ModuleDefinition = Partial<Record<string, unknown>> & {\n __esModule?: boolean;\n default?: Partial<Record<string, unknown>> & { default?: Partial<Record<string, unknown>> };\n};\n\nfunction pickModuleItem(module: ModuleDefinition, itemName: string): unknown {\n if (itemName === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[itemName] ?? module.default?.[itemName] ?? module.default?.default?.[itemName];\n}\n\nasync function importModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (isLocalModulePath(modulePath)) {\n return await importLocalModule(identifier, modulePath);\n }\n\n try {\n return await importExternalUserModule(identifier, modulePath);\n } catch {\n return await importExternalModule(identifier, modulePath);\n }\n}\n\nasync function importLocalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n if (!(await canRead(modulePath))) {\n throw new Error(`Cannot access ${identifier} at \"${modulePath}\"`);\n }\n\n const dotIndex = modulePath.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : modulePath.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(modulePath, { with: { type: 'json' } }) : import(modulePath);\n return await handleImportPromise(modulePromise, identifier, modulePath);\n}\n\nasync function importExternalModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n return await handleImportPromise(import(modulePath), identifier, modulePath);\n}\n\nasync function importExternalUserModule<T extends object>(identifier: string, modulePath: string): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userModulePath = userRequire.resolve(modulePath);\n return await importExternalModule<T>(identifier, userModulePath);\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n identifier: string,\n modulePath: string,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (error) {\n let causeMessage =\n !!error && typeof error === 'object' && 'message' in error && typeof error.message === 'string'\n ? (error as { message: string }).message\n : undefined;\n causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : '';\n throw new Error(`Failed to import ${identifier} at \"${modulePath}\" as a module${causeMessage}`, {\n cause: error,\n });\n }\n}\n","import pico from 'picocolors';\n\nexport function logSuccess(...args: unknown[]): void {\n console.log(pico.green('[Success]'), ...args);\n}\n\nexport function logInfo(...args: unknown[]): void {\n console.log(pico.blueBright('[Info]'), ...args);\n}\n\nexport function logWarning(...args: unknown[]): void {\n console.log(pico.yellow('[Warning]'), ...args);\n}\n\nexport function logError(...args: unknown[]): void {\n console.log(pico.red('[Error]'), ...args);\n}\n\nexport function logDebug(...args: unknown[]): void {\n console.log(pico.magenta('[Debug]'), ...args);\n}\n\nexport function logBanner(): void {\n console.log(getBanner());\n}\n\nfunction getBanner(): string {\n const textBanner = 'Welcome to Codama!';\n const gradientBanner = pico.bold(`\\x1b[38;2;231;171;97m${textBanner}\\x1b[0m`);\n return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { type AnchorIdl, rootNodeFromAnchor } from '@codama/nodes-from-anchor';\n\nexport function getRootNodeFromIdl(idl: unknown): RootNode {\n if (typeof idl !== 'object' || idl === null) {\n throw new Error('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n return rootNodeFromAnchor(idl as AnchorIdl);\n}\n\nexport function isRootNode(value: unknown): value is RootNode {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { standard?: string }).standard === 'codama' &&\n (value as { kind?: string }).kind === 'rootNode'\n );\n}\n","export function promisify<T>(value: Promise<T> | T): Promise<T> {\n return Promise.resolve(value);\n}\n","import type { RootNode } from '@codama/nodes';\nimport { rootNodeVisitor, visit, type Visitor } from '@codama/visitors-core';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { importModuleItem } from './import';\nimport { isRootNode } from './nodes';\nimport { promisify } from './promises';\n\nexport async function getRootNodeVisitors(\n visitors: readonly ParsedVisitorConfig[],\n): Promise<Visitor<RootNode, 'rootNode'>[]> {\n return await Promise.all(visitors.map(getRootNodeVisitor));\n}\n\nasync function getRootNodeVisitor(visitorConfig: ParsedVisitorConfig): Promise<Visitor<RootNode, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem(identifier, path, item);\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args);\n return rootNodeVisitor(root => {\n const result = visit(root, visitor);\n return isRootNode(result) ? result : root;\n });\n}\n\ntype UnknownFunction = (...args: readonly unknown[]) => unknown;\nasync function getVisitorFromModuleItem(\n identifier: string,\n moduleItem: unknown,\n args: readonly unknown[],\n): Promise<Visitor<unknown, 'rootNode'>> {\n if (isRootNodeVisitor(moduleItem)) {\n return moduleItem;\n }\n if (typeof moduleItem === 'function') {\n const result = await promisify((moduleItem as UnknownFunction)(...args));\n if (isRootNodeVisitor(result)) {\n return result;\n }\n }\n throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`);\n}\n\nfunction isRootNodeVisitor(value: unknown): value is Visitor<unknown, 'rootNode'> {\n return !!value && typeof value === 'object' && 'visitRoot' in value;\n}\n\nfunction getVisitorIdentifier(visitorConfig: ParsedVisitorConfig): string {\n const { index, item, path, script } = visitorConfig;\n const pathWithItem = item ? `${path}#${item}` : path;\n let identifier = `visitor of index #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n identifier += ` (at path \"${pathWithItem}\")`;\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport { getRootNodeVisitors, logInfo, logSuccess, logWarning } from '../utils';\n\nexport function setRunCommand(program: Command): void {\n program\n .command('run')\n .argument('[scripts...]', 'The scripts to execute')\n .option('-a, --all', 'Run all scripts in the config file')\n .action(doRun);\n}\n\ntype RunOptions = {\n all?: boolean;\n};\n\nasync function doRun(explicitScripts: string[], { all }: RunOptions, cmd: Command) {\n if (all && explicitScripts.length > 0) {\n logWarning(`CLI arguments \"${explicitScripts.join(' ')}\" are ignored because the \"--all\" option is set.`);\n }\n const parsedConfig = await getParsedConfigFromCommand(cmd);\n const scripts = all ? Object.keys(parsedConfig.scripts) : explicitScripts;\n const plans = await getPlans(parsedConfig, scripts);\n runPlans(plans, parsedConfig.rootNode);\n}\n\ntype RunPlan = {\n script: ScriptName | null;\n visitors: Visitor<RootNode, 'rootNode'>[];\n};\n\nasync function getPlans(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n): Promise<RunPlan[]> {\n const plans: RunPlan[] = [];\n if (scripts.length === 0 && parsedConfig.before.length === 0) {\n throw new Error('There are no scripts or before visitors to run.');\n }\n\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length > 0) {\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const missingScriptsIdentifier = `${scriptPluralized} \"${missingScripts.join(', ')}\"`;\n const message = parsedConfig.configPath\n ? `${missingScriptsIdentifier} not found in config file \"${parsedConfig.configPath}\"`\n : `${missingScriptsIdentifier} not found because no config file was found`;\n throw new Error(message);\n }\n\n if (parsedConfig.before.length > 0) {\n plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) });\n }\n\n for (const script of scripts) {\n plans.push({ script, visitors: await getRootNodeVisitors(parsedConfig.scripts[script]) });\n }\n\n return plans;\n}\n\nfunction runPlans(plans: RunPlan[], rootNode: RootNode): void {\n for (const plan of plans) {\n const result = runPlan(plan, rootNode);\n if (!plan.script) {\n rootNode = result;\n }\n }\n}\n\nfunction runPlan(plan: RunPlan, rootNode: RootNode): RootNode {\n const visitorLength = plan.visitors.length;\n const visitorPluralized = visitorLength === 1 ? 'visitor' : 'visitors';\n const identifier = plan.script\n ? `script \"${plan.script}\" with ${visitorLength} ${visitorPluralized}`\n : `${visitorLength} before ${visitorPluralized}`;\n logInfo(`Running ${identifier}...`);\n const newRoot = plan.visitors.reduce(visit, rootNode);\n logSuccess(`Executed ${identifier}!`);\n return newRoot;\n}\n","import path from 'node:path';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, importModuleItem, logWarning } from './utils';\n\nexport type Config = Readonly<{\n idl?: string;\n scripts?: ScriptsConfig;\n before?: readonly VisitorConfig[];\n}>;\n\nexport type ScriptName = string;\nexport type ScriptConfig = VisitorConfig | readonly VisitorConfig[];\nexport type ScriptsConfig = Readonly<Record<ScriptName, ScriptConfig>>;\n\nexport type VisitorPath = string;\nexport type VisitorConfig<T extends readonly unknown[] = readonly unknown[]> = VisitorConfigObject<T> | VisitorPath;\nexport type VisitorConfigObject<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args?: T;\n from: VisitorPath;\n}>;\n\nexport async function getConfig(options: Pick<ProgramOptions, 'config'>): Promise<[Config, string | null]> {\n const configPath = options.config != null ? path.resolve(options.config) : await getDefaultConfigPath();\n\n if (!configPath) {\n logWarning('No config file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem('config file', configPath);\n if (!configFile || typeof configFile !== 'object') {\n throw new Error(`Invalid config file at \"${configPath}\"`);\n }\n\n return [configFile, configPath];\n}\n\nasync function getDefaultConfigPath(): Promise<string | null> {\n const candidatePaths = ['codama.js', 'codama.mjs', 'codama.cjs', 'codama.json'];\n for (const candidatePath of candidatePaths) {\n const resolvedPath = path.resolve(process.cwd(), candidatePath);\n if (await canRead(resolvedPath)) {\n return resolvedPath;\n }\n }\n return null;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { Command } from 'commander';\n\nimport { Config, getConfig, ScriptName, ScriptsConfig, VisitorConfig, VisitorPath } from './config';\nimport { ProgramOptions } from './programOptions';\nimport {\n getRootNodeFromIdl,\n importModuleItem,\n isLocalModulePath,\n resolveConfigPath,\n resolveRelativePath,\n} from './utils';\n\nexport type ParsedConfig = Readonly<{\n configPath: string | null;\n idlContent: unknown;\n idlPath: string;\n rootNode: RootNode;\n scripts: ParsedScriptsConfig;\n before: readonly ParsedVisitorConfig[];\n}>;\n\nexport type ParsedScriptsConfig = Readonly<Record<ScriptName, readonly ParsedVisitorConfig[]>>;\nexport type ParsedVisitorConfig<T extends readonly unknown[] = readonly unknown[]> = Readonly<{\n args: T;\n index: number;\n item: string | undefined;\n path: VisitorPath;\n script: ScriptName | null;\n}>;\n\nexport async function getParsedConfigFromCommand(cmd: Command): Promise<ParsedConfig> {\n return await getParsedConfig(cmd.optsWithGlobals() as ProgramOptions);\n}\n\nexport async function getParsedConfig(options: Pick<ProgramOptions, 'config' | 'idl'>): Promise<ParsedConfig> {\n const [config, configPath] = await getConfig(options);\n return await parseConfig(config, configPath, options);\n}\n\nasync function parseConfig(\n config: Config,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): Promise<ParsedConfig> {\n const idlPath = parseIdlPath(config, configPath, options);\n const idlContent = await importModuleItem('IDL', idlPath);\n const rootNode = getRootNodeFromIdl(idlContent);\n const scripts = parseScripts(config.scripts ?? {}, configPath);\n const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null));\n\n return { configPath, idlContent, idlPath, rootNode, scripts, before: visitors };\n}\n\nfunction parseIdlPath(\n config: Pick<Config, 'idl'>,\n configPath: string | null,\n options: Pick<ProgramOptions, 'idl'>,\n): string {\n if (options.idl) {\n return resolveRelativePath(options.idl);\n }\n if (config.idl) {\n return resolveConfigPath(config.idl, configPath);\n }\n throw new Error('No IDL identified. Please provide the `--idl` option or set it in the config file.');\n}\n\nfunction parseScripts(scripts: ScriptsConfig, configPath: string | null): ParsedScriptsConfig {\n const entryPromises = Object.entries(scripts).map(([name, scriptConfig]) => {\n const visitors: readonly VisitorConfig[] = Array.isArray(scriptConfig) ? scriptConfig : [scriptConfig];\n return [name, visitors.map((v, i) => parseVisitorConfig(v, configPath, i, name))] as const;\n });\n return Object.fromEntries(entryPromises);\n}\n\nfunction parseVisitorConfig<T extends readonly unknown[]>(\n visitorConfig: VisitorConfig<T>,\n configPath: string | null,\n index: number,\n script: ScriptName | null,\n): ParsedVisitorConfig<T> {\n const emptyArgs = [] as readonly unknown[] as T;\n const visitorPath = typeof visitorConfig === 'string' ? visitorConfig : visitorConfig.from;\n const visitorArgs = typeof visitorConfig === 'string' ? emptyArgs : (visitorConfig.args ?? emptyArgs);\n const [path, item] = resolveVisitorPath(visitorPath, configPath);\n return { args: visitorArgs, index, item, path, script };\n}\n\nfunction resolveVisitorPath(visitorPath: string, configPath: string | null): readonly [string, string | undefined] {\n const [modulePath, itemName] = visitorPath.split('#') as [string, string | undefined];\n const resolveModulePath = isLocalModulePath(modulePath) ? resolveConfigPath(modulePath, configPath) : modulePath;\n return [resolveModulePath, itemName];\n}\n","import { Command } from 'commander';\n\nexport type ProgramOptions = Readonly<{\n config?: string;\n debug?: boolean;\n idl?: string;\n}>;\n\nexport function setProgramOptions(program: Command): void {\n program\n .option('--debug', 'include debugging information, such as stack dump')\n .option('-i, --idl <path>', 'The path to the IDL to use.')\n .option('-c, --config <path>', 'The path to the Codama configuration file. Defaults to `codama.(js|json)`.');\n}\n"],"mappings":";AAAA,SAAkB,qBAAqB;;;ACCvC,OAAO,aAA6B;;;ACDpC,SAAS,MAAM,YAAY;AAC3B,OAAO,QAAsB;AAC7B,OAAO,UAAU;AAEV,SAAS,oBAAoB,WAAmB,oBAAmC,MAAM;AAC5F,SAAO,KAAK,QAAQ,qBAAqB,QAAQ,IAAI,GAAG,SAAS;AACrE;AAEO,SAAS,kBAAkB,WAAmB,YAA2B;AAC5E,QAAM,YAAY,aAAa,KAAK,QAAQ,UAAU,IAAI;AAC1D,SAAO,oBAAoB,WAAW,SAAS;AACnD;AAEO,SAAS,kBAAkB,YAAoB;AAClD,SAAO,WAAW,WAAW,GAAG,KAAK,WAAW,WAAW,GAAG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AS;AACpC,QAAM,oBAAoB,kBAAkB,IAAI,YAAY;AAC5D,QAAM,aAAa,KAAK,SAClB,WAAW,KAAK,MAAM,UAAU,aAAa,IAAI,iBAAiB,KAClE,GAAG,aAAa,WAAW,iBAAiB;AAClD,UAAQ,WAAW,UAAU,KAAK;AAClC,QAAM,UAAU,KAAK,SAAS,OAAOC,QAAO,QAAQ;AACpD,aAAW,YAAY,UAAU,GAAG;AACpC,SAAO;AACX;;;AG5EO,SAAS,kBAAkB,SAAwB;AACtD,UACK,OAAO,WAAW,mDAAmD,EACrE,OAAO,oBAAoB,6BAA6B,EACxD,OAAO,uBAAuB,4EAA4E;AACnH;;;AXRA,eAAsB,OAAO,MAAgB,MAAoD;AAC7F,QAAM,cAAc;AAAA,IAChB,cAAc;AAAA,IACd,gBAAgB,MAAM;AAAA,EAC1B,CAAC,EAAE,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACxC;AAEO,SAAS,cAAc,iBAAiF;AAC3G,QAAM,UAAU,cAAc,EACzB,QAAQ,OAAW,EACnB,qBAAqB,KAAK,EAC1B,cAAc,EAAE,mBAAmB,MAAM,aAAa,MAAM,iBAAiB,KAAK,CAAC;AAGxF,oBAAkB,OAAO;AACzB,iBAAe,OAAO;AACtB,gBAAc,OAAO;AAGrB,MAAI,iBAAiB,cAAc;AAC/B,YAAQ,aAAa;AAAA,EACzB;AACA,MAAI,iBAAiB,gBAAgB;AACjC,YAAQ,gBAAgB;AAAA,MACpB,UAAU,MAAM;AAAA,MAAC;AAAA,MACjB,UAAU,MAAM;AAAA,MAAC;AAAA,IACrB,CAAC;AAAA,EACL;AAEA,SAAO;AACX;","names":["path","visit","path","path","path","visit"]}

@@ -1,1 +0,1 @@

{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/commands/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAOrD"}
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/commands/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAQrD"}
{
"name": "@codama/cli",
"version": "1.1.4",
"version": "1.2.0",
"description": "A CLI for setting up and managing Codama IDLs",

@@ -37,6 +37,6 @@ "exports": {

"@codama/nodes-from-anchor": "1.2.2",
"@codama/renderers": "1.0.26",
"@codama/renderers": "1.0.27",
"@codama/renderers-js": "1.3.1",
"@codama/renderers-js-umi": "1.1.16",
"@codama/renderers-rust": "1.1.1",
"@codama/renderers-rust": "1.1.2",
"@codama/visitors": "1.3.0",

@@ -43,0 +43,0 @@ "@codama/visitors-core": "1.3.0"

@@ -23,2 +23,8 @@ # Codama ➤ CLI

To initialize a [gill based Codama](https://gill.site/docs/guides/codama) configuration file, run the `init` command with the `--gill` flag like so:
```sh
pnpm codama init --gill
```
## `codama run`

@@ -25,0 +31,0 @@