@codama/cli
Advanced tools
| import { ChildProcess, SpawnOptions } from 'child_process'; | ||
| export type ChildCommand = { | ||
| command: string; | ||
| args: string[]; | ||
| }; | ||
| export declare function createChildCommand(command: string, args?: string[]): ChildCommand; | ||
| export declare function formatChildCommand(childCommand: ChildCommand): string; | ||
| export type ChildProcessResult = ChildProcess & { | ||
| stdoutString: string; | ||
| stderrString: string; | ||
| }; | ||
| export type ChildProcessError = Error & { | ||
| childProcess: ChildProcessResult; | ||
| }; | ||
| export declare function spawnChildCommand(childCommand: ChildCommand, options?: SpawnOptions & { | ||
| quiet: boolean; | ||
| }): Promise<ChildProcess & { | ||
| stdoutString: string; | ||
| stderrString: string; | ||
| }>; | ||
| //# sourceMappingURL=childCommands.d.ts.map |
| {"version":3,"file":"childCommands.d.ts","sourceRoot":"","sources":["../../../src/utils/childCommands.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAS,YAAY,EAAE,MAAM,eAAe,CAAC;AAElE,MAAM,MAAM,YAAY,GAAG;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;CAClB,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,GAAE,MAAM,EAAO,GAAG,YAAY,CAErF;AAED,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,YAAY,GAAG,MAAM,CAGrE;AAED,MAAM,MAAM,kBAAkB,GAAG,YAAY,GAAG;IAC5C,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,KAAK,GAAG;IACpC,YAAY,EAAE,kBAAkB,CAAC;CACpC,CAAC;AAEF,wBAAsB,iBAAiB,CACnC,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE,YAAY,GAAG;IAAE,KAAK,EAAE,OAAO,CAAA;CAAqB,GAC9D,OAAO,CAAC,YAAY,GAAG;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CA4BxE"} |
| export declare class CliError extends Error { | ||
| items: string[]; | ||
| constructor(message: string, items?: string[], options?: ErrorOptions); | ||
| } | ||
| //# sourceMappingURL=errors.d.ts.map |
| {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/utils/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,QAAS,SAAQ,KAAK;IAGpB,KAAK,EAAE,MAAM,EAAE;gBADtB,OAAO,EAAE,MAAM,EACR,KAAK,GAAE,MAAM,EAAO,EAC3B,OAAO,CAAC,EAAE,YAAY;CAK7B"} |
| import { ChildCommand } from './childCommands'; | ||
| export declare function getPackageManagerInstallCommand(packages: string[], options?: string[]): Promise<ChildCommand>; | ||
| export declare function installMissingDependencies(message: string, requiredDependencies: string[]): Promise<boolean>; | ||
| export declare function installDependencies(message: string, dependencies: string[]): Promise<boolean>; | ||
| //# sourceMappingURL=packageInstall.d.ts.map |
| {"version":3,"file":"packageInstall.d.ts","sourceRoot":"","sources":["../../../src/utils/packageInstall.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAA6D,MAAM,iBAAiB,CAAC;AAM1G,wBAAsB,+BAA+B,CACjD,QAAQ,EAAE,MAAM,EAAE,EAClB,OAAO,GAAE,MAAM,EAAO,GACvB,OAAO,CAAC,YAAY,CAAC,CAIvB;AAED,wBAAsB,0BAA0B,CAAC,OAAO,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAQlH;AAED,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAkCnG"} |
| type PackageJson = { | ||
| name: string; | ||
| dependencies?: Record<string, string>; | ||
| devDependencies?: Record<string, string>; | ||
| scripts?: Record<string, string>; | ||
| packageManager?: string; | ||
| [key: string]: unknown; | ||
| }; | ||
| export declare function getPackageJson(): Promise<PackageJson>; | ||
| export declare function getPackageJsonDependencies(options?: { | ||
| includeDev?: boolean; | ||
| }): Promise<string[]>; | ||
| export {}; | ||
| //# sourceMappingURL=packageJson.d.ts.map |
| {"version":3,"file":"packageJson.d.ts","sourceRoot":"","sources":["../../../src/utils/packageJson.ts"],"names":[],"mappings":"AAKA,KAAK,WAAW,GAAG;IACf,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B,CAAC;AAGF,wBAAsB,cAAc,IAAI,OAAO,CAAC,WAAW,CAAC,CAS3D;AAED,wBAAsB,0BAA0B,CAAC,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAM1G"} |
| type PackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn'; | ||
| export declare function getPackageManager(): Promise<PackageManager>; | ||
| export {}; | ||
| //# sourceMappingURL=packageManager.d.ts.map |
| {"version":3,"file":"packageManager.d.ts","sourceRoot":"","sources":["../../../src/utils/packageManager.ts"],"names":[],"mappings":"AAIA,KAAK,cAAc,GAAG,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;AAKtD,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,cAAc,CAAC,CAKjE"} |
| import prompts from 'prompts'; | ||
| export declare const PROMPT_OPTIONS: prompts.Options; | ||
| //# sourceMappingURL=prompts.d.ts.map |
| {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../../../src/utils/prompts.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAI9B,eAAO,MAAM,cAAc,EAAE,OAAO,CAAC,OAIpC,CAAC"} |
+414
-114
@@ -39,6 +39,58 @@ "use strict"; | ||
| var import_commander = require("commander"); | ||
| var import_picocolors9 = __toESM(require("picocolors")); | ||
| // src/commands/init.ts | ||
| var import_prompts = __toESM(require("prompts")); | ||
| var import_picocolors6 = __toESM(require("picocolors")); | ||
| var import_prompts3 = __toESM(require("prompts")); | ||
| // src/utils/childCommands.ts | ||
| var import_child_process = require("child_process"); | ||
| function createChildCommand(command, args = []) { | ||
| return { command, args }; | ||
| } | ||
| function formatChildCommand(childCommand) { | ||
| const { command, args } = childCommand; | ||
| return [command, ...args].join(" "); | ||
| } | ||
| async function spawnChildCommand(childCommand, options = { quiet: false }) { | ||
| const { command, args } = childCommand; | ||
| const childProcess = (0, import_child_process.spawn)(command, args, options); | ||
| childProcess.stdoutString = ""; | ||
| childProcess.stderrString = ""; | ||
| childProcess.stdout?.on("data", (chunk) => { | ||
| childProcess.stdoutString += chunk.toString(); | ||
| if (!options.quiet) { | ||
| process.stdout.write(chunk); | ||
| } | ||
| }); | ||
| childProcess.stderr?.on("data", (chunk) => { | ||
| childProcess.stderrString += chunk.toString(); | ||
| if (!options.quiet) { | ||
| process.stderr.write(chunk); | ||
| } | ||
| }); | ||
| const exitCode = await new Promise((resolve, reject) => { | ||
| childProcess.on("error", () => reject(createChildProcessResultError(childCommand, childProcess))); | ||
| childProcess.on("close", resolve); | ||
| }); | ||
| if (exitCode) { | ||
| throw createChildProcessResultError(childCommand, childProcess); | ||
| } | ||
| return childProcess; | ||
| } | ||
| function createChildProcessResultError(childCommand, childProcess) { | ||
| const error = new Error(`Command [${formatChildCommand(childCommand)}] failed`); | ||
| error.childProcess = childProcess; | ||
| return error; | ||
| } | ||
| // src/utils/errors.ts | ||
| var CliError = class extends Error { | ||
| constructor(message, items = [], options) { | ||
| super(message, options); | ||
| this.items = items; | ||
| this.name = "CliError"; | ||
| } | ||
| }; | ||
| // src/utils/fs.ts | ||
@@ -58,2 +110,8 @@ var import_node_constants = require("constants"); | ||
| } | ||
| async function readJson(filePath) { | ||
| return JSON.parse(await readFile(filePath)); | ||
| } | ||
| async function readFile(filePath) { | ||
| return await import_node_fs.default.promises.readFile(filePath, "utf8"); | ||
| } | ||
| async function writeFile(filePath, content) { | ||
@@ -85,73 +143,106 @@ const directory = import_node_path.default.dirname(filePath); | ||
| var import_node_module = require("module"); | ||
| async function importModuleItem(identifier, modulePath, itemName = "default") { | ||
| const module2 = await importModule(identifier, modulePath); | ||
| const item = pickModuleItem(module2, itemName); | ||
| if (item === void 0) { | ||
| throw new Error(`Failed to import "${itemName}" from ${identifier} at "${modulePath}".`); | ||
| var import_picocolors = __toESM(require("picocolors")); | ||
| async function importModuleItem(options) { | ||
| const module2 = await importModule(options); | ||
| const moduleItem = pickModuleItem(module2, options.item); | ||
| if (moduleItem === void 0) { | ||
| const items = getErrorItems(options); | ||
| throw new CliError(`Failed to load ${options.identifier ?? "module"}.`, items); | ||
| } | ||
| return item; | ||
| return moduleItem; | ||
| } | ||
| function pickModuleItem(module2, itemName) { | ||
| if (itemName === "default") { | ||
| function pickModuleItem(module2, item = "default") { | ||
| if (item === "default") { | ||
| return module2.default?.default ?? module2.default ?? module2; | ||
| } | ||
| return module2[itemName] ?? module2.default?.[itemName] ?? module2.default?.default?.[itemName]; | ||
| return module2[item] ?? module2.default?.[item] ?? module2.default?.default?.[item]; | ||
| } | ||
| async function importModule(identifier, modulePath) { | ||
| if (isLocalModulePath(modulePath)) { | ||
| return await importLocalModule(identifier, modulePath); | ||
| async function importModule(options) { | ||
| if (isLocalModulePath(options.from)) { | ||
| return await importLocalModule(options); | ||
| } | ||
| try { | ||
| return await importExternalUserModule(identifier, modulePath); | ||
| return await importExternalUserModule(options); | ||
| } catch { | ||
| return await importExternalModule(identifier, modulePath); | ||
| return await importExternalModule(options); | ||
| } | ||
| } | ||
| async function importLocalModule(identifier, modulePath) { | ||
| if (!await canRead(modulePath)) { | ||
| throw new Error(`Cannot access ${identifier} at "${modulePath}"`); | ||
| async function importLocalModule(options) { | ||
| const { from, identifier } = options; | ||
| if (!await canRead(from)) { | ||
| const items = getErrorItems(options); | ||
| throw new CliError(`Cannot access ${identifier ?? "module"}.`, items); | ||
| } | ||
| const dotIndex = modulePath.lastIndexOf("."); | ||
| const extension = dotIndex === -1 ? void 0 : modulePath.slice(dotIndex); | ||
| const modulePromise = extension === ".json" ? import(modulePath, { with: { type: "json" } }) : import(modulePath); | ||
| return await handleImportPromise(modulePromise, identifier, modulePath); | ||
| const dotIndex = from.lastIndexOf("."); | ||
| const extension = dotIndex === -1 ? void 0 : from.slice(dotIndex); | ||
| const modulePromise = extension === ".json" ? import(from, { with: { type: "json" } }) : import(from); | ||
| return await handleImportPromise(modulePromise, options); | ||
| } | ||
| async function importExternalModule(identifier, modulePath) { | ||
| return await handleImportPromise(import(modulePath), identifier, modulePath); | ||
| async function importExternalModule(options) { | ||
| return await handleImportPromise(import(options.from), options); | ||
| } | ||
| async function importExternalUserModule(identifier, modulePath) { | ||
| async function importExternalUserModule(options) { | ||
| const userPackageJsonPath = resolveRelativePath("package.json"); | ||
| const userRequire = (0, import_node_module.createRequire)(userPackageJsonPath); | ||
| const userModulePath = userRequire.resolve(modulePath); | ||
| return await importExternalModule(identifier, userModulePath); | ||
| const userFrom = userRequire.resolve(options.from); | ||
| return await importExternalModule({ ...options, from: userFrom }); | ||
| } | ||
| async function handleImportPromise(importPromise, identifier, modulePath) { | ||
| async function handleImportPromise(importPromise, options) { | ||
| try { | ||
| return await importPromise; | ||
| } catch (error) { | ||
| let causeMessage = !!error && typeof error === "object" && "message" in error && typeof error.message === "string" ? error.message : void 0; | ||
| causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : ""; | ||
| throw new Error(`Failed to import ${identifier} at "${modulePath}" as a module${causeMessage}`, { | ||
| cause: error | ||
| }); | ||
| } catch (cause) { | ||
| const items = getErrorItems(options, cause); | ||
| throw new CliError(`Failed to load ${options.identifier ?? "module"}.`, items, { cause }); | ||
| } | ||
| } | ||
| function getErrorItems(options, cause) { | ||
| const { from, item } = options; | ||
| const items = [`${import_picocolors.default.bold("Module")}: ${from}`]; | ||
| if (item) { | ||
| items.push(`${import_picocolors.default.bold("Item")}: ${item}`); | ||
| } | ||
| const hasCause = !!cause && typeof cause === "object" && "message" in cause && typeof cause.message === "string"; | ||
| if (hasCause) { | ||
| items.push(`${import_picocolors.default.bold("Caused by")}: ${cause.message}`); | ||
| } | ||
| return items; | ||
| } | ||
| // src/utils/logs.ts | ||
| var import_picocolors = __toESM(require("picocolors")); | ||
| function logSuccess(...args) { | ||
| console.log(import_picocolors.default.green("[Success]"), ...args); | ||
| var import_picocolors2 = __toESM(require("picocolors")); | ||
| function getLogLevelInfo(logLevel) { | ||
| const identity = (text) => text; | ||
| const infos = { | ||
| success: ["\u2714", import_picocolors2.default.green, import_picocolors2.default.green], | ||
| info: ["\u2192", import_picocolors2.default.blueBright, identity], | ||
| warning: ["\u25B2", import_picocolors2.default.yellow, import_picocolors2.default.yellow], | ||
| error: ["\u2716", import_picocolors2.default.red, import_picocolors2.default.red], | ||
| debug: ["\u2731", import_picocolors2.default.magenta, import_picocolors2.default.magenta] | ||
| }; | ||
| return { | ||
| icon: infos[logLevel][0], | ||
| color: infos[logLevel][1], | ||
| messageColor: infos[logLevel][2] | ||
| }; | ||
| } | ||
| function logInfo(...args) { | ||
| console.log(import_picocolors.default.blueBright("[Info]"), ...args); | ||
| var logWrapper = (level) => (message, items) => log({ level, message, items }); | ||
| var logSuccess = logWrapper("success"); | ||
| var logError = logWrapper("error"); | ||
| var logInfo = logWrapper("info"); | ||
| var logWarning = logWrapper("warning"); | ||
| var logDebug = logWrapper("debug"); | ||
| function log({ level, message, items }) { | ||
| const { icon, color, messageColor } = getLogLevelInfo(level); | ||
| console.log(color(icon), messageColor(message)); | ||
| if (items) { | ||
| logItems(items, color); | ||
| } | ||
| } | ||
| function logWarning(...args) { | ||
| console.log(import_picocolors.default.yellow("[Warning]"), ...args); | ||
| function logItems(items, color) { | ||
| const colorFn = color ?? ((text) => text); | ||
| items.forEach((item, index) => { | ||
| const prefix = index === items.length - 1 ? "\u2514\u2500" : "\u251C\u2500"; | ||
| console.log(" " + colorFn(prefix), item); | ||
| }); | ||
| } | ||
| function logError(...args) { | ||
| console.log(import_picocolors.default.red("[Error]"), ...args); | ||
| } | ||
| function logDebug(...args) { | ||
| console.log(import_picocolors.default.magenta("[Debug]"), ...args); | ||
| } | ||
| function logBanner() { | ||
@@ -162,11 +253,142 @@ console.log(getBanner()); | ||
| const textBanner = "Welcome to Codama!"; | ||
| const gradientBanner = import_picocolors.default.bold(`\x1B[38;2;231;171;97m${textBanner}\x1B[0m`); | ||
| const gradientBanner = import_picocolors2.default.bold(`\x1B[38;2;231;171;97m${textBanner}\x1B[0m`); | ||
| return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner; | ||
| } | ||
| // src/utils/packageInstall.ts | ||
| var import_picocolors4 = __toESM(require("picocolors")); | ||
| var import_prompts = __toESM(require("prompts")); | ||
| // src/utils/packageJson.ts | ||
| var import_picocolors3 = __toESM(require("picocolors")); | ||
| var packageJson; | ||
| async function getPackageJson() { | ||
| if (!packageJson) { | ||
| const packageJsonPath = resolveRelativePath("package.json"); | ||
| if (!await canRead(packageJsonPath)) { | ||
| throw new CliError("Cannot read package.json.", [`${import_picocolors3.default.bold("Path")}: ${packageJsonPath}`]); | ||
| } | ||
| packageJson = await readJson(packageJsonPath); | ||
| } | ||
| return packageJson; | ||
| } | ||
| async function getPackageJsonDependencies(options = {}) { | ||
| const packageJson2 = await getPackageJson(); | ||
| return [ | ||
| ...packageJson2.dependencies ? Object.keys(packageJson2.dependencies) : [], | ||
| ...options.includeDev && packageJson2.devDependencies ? Object.keys(packageJson2.devDependencies) : [] | ||
| ]; | ||
| } | ||
| // src/utils/packageManager.ts | ||
| var FALLBACK_PACKAGE_MANAGER = "npm"; | ||
| var packageManager; | ||
| async function getPackageManager() { | ||
| if (!packageManager) { | ||
| packageManager = await detectPackageManager(); | ||
| } | ||
| return packageManager; | ||
| } | ||
| async function detectPackageManager() { | ||
| const fromPackageJson = await detectPackageManagerFromPackageJson(); | ||
| if (fromPackageJson) return fromPackageJson; | ||
| const fromLockfile = await detectPackageManagerFromLockfile(); | ||
| if (fromLockfile) return fromLockfile; | ||
| const fromInstalledCli = await detectPackageManagerFromInstalledCli(); | ||
| if (fromInstalledCli) return fromInstalledCli; | ||
| return FALLBACK_PACKAGE_MANAGER; | ||
| } | ||
| async function detectPackageManagerFromPackageJson() { | ||
| const packageJson2 = await getPackageJson(); | ||
| if (!packageJson2.packageManager) return void 0; | ||
| if (packageJson2.packageManager.startsWith("npm@")) return "npm"; | ||
| if (packageJson2.packageManager.startsWith("pnpm@")) return "pnpm"; | ||
| if (packageJson2.packageManager.startsWith("yarn@")) return "yarn"; | ||
| if (packageJson2.packageManager.startsWith("bun@")) return "bun"; | ||
| return void 0; | ||
| } | ||
| async function detectPackageManagerFromLockfile() { | ||
| const [isYarn, isPnpm, isBun, isNpm] = await Promise.all([ | ||
| canRead(resolveRelativePath("yarn.lock")), | ||
| canRead(resolveRelativePath("pnpm-lock.yaml")), | ||
| canRead(resolveRelativePath("bun.lockb")), | ||
| canRead(resolveRelativePath("package-lock.json")) | ||
| ]); | ||
| if (isYarn) return "yarn"; | ||
| if (isPnpm) return "pnpm"; | ||
| if (isBun) return "bun"; | ||
| if (isNpm) return "npm"; | ||
| return void 0; | ||
| } | ||
| async function detectPackageManagerFromInstalledCli() { | ||
| const [isPnpm, isYarn, isBun] = await Promise.all([ | ||
| hasPackageManagerCli("pnpm"), | ||
| hasPackageManagerCli("yarn"), | ||
| hasPackageManagerCli("bun") | ||
| ]); | ||
| if (isPnpm) return "pnpm"; | ||
| if (isYarn) return "yarn"; | ||
| if (isBun) return "bun"; | ||
| return void 0; | ||
| } | ||
| async function hasPackageManagerCli(packageManager2) { | ||
| return await spawnChildCommand(createChildCommand(packageManager2, ["--version"]), { quiet: true }).then(() => true).catch(() => false); | ||
| } | ||
| // src/utils/prompts.ts | ||
| var PROMPT_OPTIONS = { | ||
| onCancel: () => { | ||
| throw new CliError("Operation cancelled."); | ||
| } | ||
| }; | ||
| // src/utils/packageInstall.ts | ||
| async function getPackageManagerInstallCommand(packages, options = []) { | ||
| const packageManager2 = await getPackageManager(); | ||
| const args = [packageManager2 === "yarn" ? "add" : "install", ...packages, ...options]; | ||
| return createChildCommand(packageManager2, args); | ||
| } | ||
| async function installMissingDependencies(message, requiredDependencies) { | ||
| if (requiredDependencies.length === 0) return true; | ||
| const installedDependencies = await getPackageJsonDependencies({ includeDev: true }); | ||
| const missingDependencies = requiredDependencies.filter((dep) => !installedDependencies.includes(dep)); | ||
| if (missingDependencies.length === 0) return true; | ||
| return await installDependencies(message, missingDependencies); | ||
| } | ||
| async function installDependencies(message, dependencies) { | ||
| if (dependencies.length === 0) return true; | ||
| const installCommand = await getPackageManagerInstallCommand(dependencies); | ||
| const formattedInstallCommand = import_picocolors4.default.yellow(formatChildCommand(installCommand)); | ||
| if (process.env.CI) { | ||
| logWarning(message); | ||
| logWarning(`Skipping installation in CI environment. Please install manually:`); | ||
| logWarning(formattedInstallCommand); | ||
| return false; | ||
| } | ||
| logWarning(message); | ||
| logWarning(`Install command: ${formattedInstallCommand}`); | ||
| const dependencyResult = await (0, import_prompts.default)( | ||
| { initial: true, message: "Install dependencies?", name: "installDependencies", type: "confirm" }, | ||
| PROMPT_OPTIONS | ||
| ); | ||
| if (!dependencyResult.installDependencies) { | ||
| logWarning("Skipping installation."); | ||
| return false; | ||
| } | ||
| try { | ||
| logInfo(`Installing`, dependencies); | ||
| await spawnChildCommand(installCommand, { quiet: true }); | ||
| logSuccess(`Dependencies installed successfully.`); | ||
| return true; | ||
| } catch { | ||
| logError(`Failed to install dependencies. Please try manually:`); | ||
| logError(formattedInstallCommand); | ||
| return false; | ||
| } | ||
| } | ||
| // src/utils/nodes.ts | ||
| var import_nodes_from_anchor = require("@codama/nodes-from-anchor"); | ||
| function getRootNodeFromIdl(idl) { | ||
| async function getRootNodeFromIdl(idl) { | ||
| if (typeof idl !== "object" || idl === null) { | ||
| throw new Error("Unexpected IDL content. Expected an object, got " + typeof idl); | ||
| throw new CliError("Unexpected IDL content. Expected an object, got " + typeof idl); | ||
| } | ||
@@ -176,3 +398,14 @@ if (isRootNode(idl)) { | ||
| } | ||
| return (0, import_nodes_from_anchor.rootNodeFromAnchor)(idl); | ||
| const hasNodesFromAnchor = await installMissingDependencies( | ||
| "Anchor IDL detected. Additional dependencies are required to process Anchor IDLs.", | ||
| ["@codama/nodes-from-anchor"] | ||
| ); | ||
| if (!hasNodesFromAnchor) { | ||
| throw new CliError("Cannot proceed without Anchor IDL support."); | ||
| } | ||
| const rootNodeFromAnchor = await importModuleItem({ | ||
| from: "@codama/nodes-from-anchor", | ||
| item: "rootNodeFromAnchor" | ||
| }); | ||
| return rootNodeFromAnchor(idl); | ||
| } | ||
@@ -190,2 +423,3 @@ function isRootNode(value) { | ||
| var import_visitors_core = require("@codama/visitors-core"); | ||
| var import_picocolors5 = __toESM(require("picocolors")); | ||
| async function getRootNodeVisitors(visitors) { | ||
@@ -195,6 +429,6 @@ return await Promise.all(visitors.map(getRootNodeVisitor)); | ||
| async function getRootNodeVisitor(visitorConfig) { | ||
| const { args, item, path: path3 } = visitorConfig; | ||
| const { item, path: path3 } = visitorConfig; | ||
| const identifier = getVisitorIdentifier(visitorConfig); | ||
| const moduleItem = await importModuleItem(identifier, path3, item); | ||
| const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args); | ||
| const moduleItem = await importModuleItem({ identifier, from: path3, item }); | ||
| const visitor = await getVisitorFromModuleItem(identifier, moduleItem, visitorConfig); | ||
| return (0, import_visitors_core.rootNodeVisitor)((root) => { | ||
@@ -205,3 +439,4 @@ const result = (0, import_visitors_core.visit)(root, visitor); | ||
| } | ||
| async function getVisitorFromModuleItem(identifier, moduleItem, args) { | ||
| async function getVisitorFromModuleItem(identifier, moduleItem, visitorConfig) { | ||
| const { args, item, path: path3 } = visitorConfig; | ||
| if (isRootNodeVisitor(moduleItem)) { | ||
@@ -216,3 +451,7 @@ return moduleItem; | ||
| } | ||
| throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`); | ||
| throw new CliError(`Invalid visitor. Expected a visitor or a function returning a visitor.`, [ | ||
| `${import_picocolors5.default.bold("Visitor")}: ${identifier}`, | ||
| `${import_picocolors5.default.bold("Path")}: ${path3}`, | ||
| ...item ? [`${import_picocolors5.default.bold("Item")}: ${item}`] : [] | ||
| ]); | ||
| } | ||
@@ -223,7 +462,5 @@ function isRootNodeVisitor(value) { | ||
| function getVisitorIdentifier(visitorConfig) { | ||
| const { index, item, path: path3, script } = visitorConfig; | ||
| const pathWithItem = item ? `${path3}#${item}` : path3; | ||
| let identifier = `visitor of index #${index}`; | ||
| const { index, script } = visitorConfig; | ||
| let identifier = `visitor #${index}`; | ||
| identifier += script ? ` in script "${script}"` : ""; | ||
| identifier += ` (at path "${pathWithItem}")`; | ||
| return identifier; | ||
@@ -234,17 +471,22 @@ } | ||
| 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").option("--gill", "Forces the output to be a gill based 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("--force", "Overwrite existing configuration file, if any").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); | ||
| let configFileType = output.endsWith(".js") ? "js" : "json"; | ||
| if (options.gill) configFileType = "gill"; | ||
| else if (options.js) configFileType = "js"; | ||
| if (await canRead(output)) { | ||
| throw new Error(`Configuration file already exists at "${output}".`); | ||
| const configFileType = getConfigFileType(output, options); | ||
| if (!options.force && await canRead(output)) { | ||
| throw new CliError(`Configuration file already exists.`, [`${import_picocolors6.default.bold("Path")}: ${output}`]); | ||
| } | ||
| logBanner(); | ||
| const result = await getPromptResult(options); | ||
| const result = await getPromptResult(options, configFileType); | ||
| const isAnchor = await isAnchorIdl(result.idlPath); | ||
| await installMissingDependencies(`Your configuration requires additional dependencies.`, [ | ||
| ...isAnchor ? ["@codama/nodes-from-anchor"] : [], | ||
| ...result.scripts.includes("js") ? ["@codama/renderers-js"] : [], | ||
| ...result.scripts.includes("rust") ? ["@codama/renderers-rust"] : [] | ||
| ]); | ||
| const content = getContentFromPromptResult(result, configFileType); | ||
| await writeFile(output, content); | ||
| logSuccess(`Configuration file created at "${output}".`); | ||
| console.log(); | ||
| logSuccess(import_picocolors6.default.bold("Configuration file created."), [`${import_picocolors6.default.bold("Path")}: ${output}`]); | ||
| } | ||
@@ -257,3 +499,3 @@ function getOutputPath(explicitOutput, options) { | ||
| } | ||
| async function getPromptResult(options) { | ||
| async function getPromptResult(options, configFileType) { | ||
| const defaults = getDefaultPromptResult(); | ||
@@ -264,3 +506,3 @@ if (options.default) { | ||
| const hasScript = (script, type = "text") => (_, values) => values.scripts.includes(script) ? type : null; | ||
| const result = await (0, import_prompts.default)( | ||
| return await (0, import_prompts3.default)( | ||
| [ | ||
@@ -281,3 +523,11 @@ { | ||
| name: "scripts", | ||
| type: "multiselect" | ||
| type: "multiselect", | ||
| onRender() { | ||
| if (configFileType === "gill") { | ||
| const value = this.value; | ||
| const jsChoice = value.find((choice) => choice.value === "js"); | ||
| jsChoice.description = import_picocolors6.default.yellow("Required with --gill option."); | ||
| jsChoice.selected = true; | ||
| } | ||
| } | ||
| }, | ||
@@ -303,9 +553,4 @@ { | ||
| ], | ||
| { | ||
| onCancel: () => { | ||
| throw new Error("Operation cancelled."); | ||
| } | ||
| } | ||
| PROMPT_OPTIONS | ||
| ); | ||
| return result; | ||
| } | ||
@@ -321,3 +566,19 @@ function getDefaultPromptResult() { | ||
| } | ||
| function getConfigFileType(output, options) { | ||
| if (options.gill) return "gill"; | ||
| else if (options.js) return "js"; | ||
| return output.endsWith(".js") ? "js" : "json"; | ||
| } | ||
| function getContentFromPromptResult(result, configFileType) { | ||
| switch (configFileType) { | ||
| case "gill": | ||
| return getContentForGill(result); | ||
| case "js": | ||
| return `export default ` + JSON.stringify(getConfigFromPromptResult(result), null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'"); | ||
| case "json": | ||
| default: | ||
| return JSON.stringify(getConfigFromPromptResult(result), null, 4); | ||
| } | ||
| } | ||
| function getConfigFromPromptResult(result) { | ||
| const scripts = {}; | ||
@@ -336,15 +597,27 @@ if (result.scripts.includes("js")) { | ||
| } | ||
| const content = { idl: result.idlPath, before: [], scripts }; | ||
| if (configFileType == "json") { | ||
| return JSON.stringify(content, null, 4); | ||
| } else if (configFileType == "gill") { | ||
| return `import { createCodamaConfig } from "gill"; | ||
| return { idl: result.idlPath, before: [], scripts }; | ||
| } | ||
| function getContentForGill(result) { | ||
| const attributes = [ | ||
| `idl: "${result.idlPath}"`, | ||
| `clientJs: "${result.jsPath}"`, | ||
| ...result.scripts.includes("rust") ? [`clientRust: "${result.rustPath}"`] : [] | ||
| ]; | ||
| const attributesString = attributes.map((attr) => ` ${attr}, | ||
| `).join(""); | ||
| return `import { createCodamaConfig } from "gill"; | ||
| export default createCodamaConfig({ | ||
| idl: "${result.idlPath}", | ||
| clientJs: "${result.jsPath}", | ||
| ` + result.scripts.includes("rust") ? `clientRust: "${result.rustPath}", | ||
| ` : `});`; | ||
| export default createCodamaConfig({ | ||
| ${attributesString}}); | ||
| `; | ||
| } | ||
| async function isAnchorIdl(idlPath) { | ||
| const resolvedIdlPath = resolveRelativePath(idlPath); | ||
| if (!await canRead(resolvedIdlPath)) return false; | ||
| try { | ||
| const idlContent = await importModuleItem({ identifier: "IDL", from: resolvedIdlPath }); | ||
| return !isRootNode(idlContent); | ||
| } catch { | ||
| return false; | ||
| } | ||
| return "export default " + JSON.stringify(content, null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'"); | ||
| } | ||
@@ -354,14 +627,16 @@ | ||
| var import_visitors_core2 = require("@codama/visitors-core"); | ||
| var import_picocolors8 = __toESM(require("picocolors")); | ||
| // src/config.ts | ||
| var import_node_path2 = __toESM(require("path")); | ||
| var import_picocolors7 = __toESM(require("picocolors")); | ||
| async function getConfig(options) { | ||
| const configPath = options.config != null ? import_node_path2.default.resolve(options.config) : await getDefaultConfigPath(); | ||
| if (!configPath) { | ||
| logWarning("No config file found. Using empty configs. Make sure you provide the `--idl` option."); | ||
| logWarning("No configuration file found. Using empty configs. Make sure you provide the `--idl` option."); | ||
| return [{}, configPath]; | ||
| } | ||
| const configFile = await importModuleItem("config file", configPath); | ||
| const configFile = await importModuleItem({ identifier: "configuration file", from: configPath }); | ||
| if (!configFile || typeof configFile !== "object") { | ||
| throw new Error(`Invalid config file at "${configPath}"`); | ||
| throw new CliError(`Invalid configuration file.`, [`${import_picocolors7.default.bold("Path")}: ${configPath}`]); | ||
| } | ||
@@ -391,4 +666,4 @@ return [configFile, configPath]; | ||
| const idlPath = parseIdlPath(config, configPath, options); | ||
| const idlContent = await importModuleItem("IDL", idlPath); | ||
| const rootNode = getRootNodeFromIdl(idlContent); | ||
| const idlContent = await importModuleItem({ identifier: "IDL", from: idlPath }); | ||
| const rootNode = await getRootNodeFromIdl(idlContent); | ||
| const scripts = parseScripts(config.scripts ?? {}, configPath); | ||
@@ -405,3 +680,3 @@ const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null)); | ||
| } | ||
| throw new Error("No IDL identified. Please provide the `--idl` option or set it in the config file."); | ||
| throw new CliError("No IDL identified. Please provide the `--idl` option or set it in the configuration file."); | ||
| } | ||
@@ -430,3 +705,3 @@ function parseScripts(scripts, configPath) { | ||
| function setRunCommand(program2) { | ||
| program2.command("run").argument("[scripts...]", "The scripts to execute").option("-a, --all", "Run all scripts in the config file").action(doRun); | ||
| program2.command("run").argument("[scripts...]", "The scripts to execute").option("-a, --all", "Run all scripts in the configuration file").action(doRun); | ||
| } | ||
@@ -445,11 +720,6 @@ async function doRun(explicitScripts, { all }, cmd) { | ||
| if (scripts.length === 0 && parsedConfig.before.length === 0) { | ||
| throw new Error("There are no scripts or before visitors to run."); | ||
| throw new CliError("There are no scripts or before visitors to run."); | ||
| } | ||
| const missingScripts = scripts.filter((script) => !parsedConfig.scripts[script]); | ||
| if (missingScripts.length > 0) { | ||
| const scriptPluralized = missingScripts.length === 1 ? "Script" : "Scripts"; | ||
| const missingScriptsIdentifier = `${scriptPluralized} "${missingScripts.join(", ")}"`; | ||
| const message = parsedConfig.configPath ? `${missingScriptsIdentifier} not found in config file "${parsedConfig.configPath}"` : `${missingScriptsIdentifier} not found because no config file was found`; | ||
| throw new Error(message); | ||
| } | ||
| checkMissingScripts(parsedConfig, scripts); | ||
| await checkMissingDependencies(parsedConfig, scripts); | ||
| if (parsedConfig.before.length > 0) { | ||
@@ -480,2 +750,28 @@ plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) }); | ||
| } | ||
| function checkMissingScripts(parsedConfig, scripts) { | ||
| const missingScripts = scripts.filter((script) => !parsedConfig.scripts[script]); | ||
| if (missingScripts.length === 0) return; | ||
| const scriptPluralized = missingScripts.length === 1 ? "Script" : "Scripts"; | ||
| const message = parsedConfig.configPath ? `${scriptPluralized} not found in configuration file.` : `${scriptPluralized} not found because no configuration file was found.`; | ||
| const items = [ | ||
| `${import_picocolors8.default.bold(scriptPluralized)}: ${missingScripts.join(", ")}`, | ||
| ...parsedConfig.configPath ? [`${import_picocolors8.default.bold("Path")}: ${parsedConfig.configPath}`] : [] | ||
| ]; | ||
| throw new CliError(message, items); | ||
| } | ||
| async function checkMissingDependencies(parsedConfig, scripts) { | ||
| const dependencies = /* @__PURE__ */ new Set([ | ||
| ...parsedConfig.before.map((v) => v.path), | ||
| ...scripts.flatMap((script) => parsedConfig.scripts[script]?.map((v) => v.path) ?? []) | ||
| ]); | ||
| const externalDependencies = [...dependencies].filter((dep) => !isLocalModulePath(dep)); | ||
| const scriptsRequirePluralized = scripts.length === 1 ? "script requires" : "scripts require"; | ||
| const installed = await installMissingDependencies( | ||
| `Your ${scriptsRequirePluralized} additional dependencies.`, | ||
| externalDependencies | ||
| ); | ||
| if (!installed) { | ||
| throw new CliError("Cannot proceed without missing dependencies."); | ||
| } | ||
| } | ||
@@ -488,4 +784,16 @@ // src/programOptions.ts | ||
| // src/program.ts | ||
| async function runProgram(program2, argv, parseOptions) { | ||
| try { | ||
| await program2.parseAsync(argv, parseOptions); | ||
| } catch (err) { | ||
| const error = err; | ||
| if (program2.opts().debug) { | ||
| logDebug(`${error.stack}`); | ||
| } | ||
| logError(import_picocolors9.default.bold(error.message), error.items ?? []); | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| function createProgram(internalOptions) { | ||
| const program2 = (0, import_commander.createCommand)().version("1.2.2").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true }); | ||
| const program2 = (0, import_commander.createCommand)().version("1.3.0").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true }); | ||
| setProgramOptions(program2); | ||
@@ -511,11 +819,3 @@ setInitCommand(program2); | ||
| async function run(argv) { | ||
| try { | ||
| await program.parseAsync(argv); | ||
| } catch (err) { | ||
| if (program.opts().debug) { | ||
| logDebug(`${err.stack}`); | ||
| } | ||
| logError(err.message); | ||
| process.exitCode = 1; | ||
| } | ||
| await runProgram(program, argv); | ||
| } | ||
@@ -522,0 +822,0 @@ // Annotate the CommonJS export names for ESM import in node: |
+1
-1
@@ -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 .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":";;;;;;;;;;;;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,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"]} | ||
| {"version":3,"sources":["../src/cli/index.ts","../src/program.ts","../src/commands/init.ts","../src/utils/childCommands.ts","../src/utils/errors.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/packageInstall.ts","../src/utils/packageJson.ts","../src/utils/packageManager.ts","../src/utils/prompts.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, runProgram } from '../program';\n\nconst program = createProgram();\n\nexport async function run(argv: readonly string[]) {\n await runProgram(program, argv);\n}\n","import { Command, createCommand, ParseOptions } from 'commander';\nimport pico from 'picocolors';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\nimport { logDebug, logError } from './utils';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n const program = createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n });\n await runProgram(program, args, { from: 'user' });\n}\n\nexport async function runProgram(program: Command, argv: readonly string[], parseOptions?: ParseOptions) {\n try {\n await program.parseAsync(argv, parseOptions);\n } catch (err) {\n const error = err as { message: string; stack?: string; items?: string[] };\n if (program.opts().debug) {\n logDebug(`${error.stack}`);\n }\n logError(pico.bold(error.message), error.items ?? []);\n process.exitCode = 1;\n }\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 pico from 'picocolors';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport {\n canRead,\n CliError,\n importModuleItem,\n installMissingDependencies,\n isRootNode,\n logBanner,\n logSuccess,\n PROMPT_OPTIONS,\n resolveRelativePath,\n writeFile,\n} 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('--force', 'Overwrite existing configuration file, if any')\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 force?: boolean;\n gill?: boolean;\n js?: boolean;\n};\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n const configFileType = getConfigFileType(output, options);\n\n if (!options.force && (await canRead(output))) {\n throw new CliError(`Configuration file already exists.`, [`${pico.bold('Path')}: ${output}`]);\n }\n\n // Start prompts.\n logBanner();\n const result = await getPromptResult(options, configFileType);\n\n // Check dependencies.\n const isAnchor = await isAnchorIdl(result.idlPath);\n await installMissingDependencies(`Your configuration requires additional dependencies.`, [\n ...(isAnchor ? ['@codama/nodes-from-anchor'] : []),\n ...(result.scripts.includes('js') ? ['@codama/renderers-js'] : []),\n ...(result.scripts.includes('rust') ? ['@codama/renderers-rust'] : []),\n ]);\n\n // Write configuration file.\n const content = getContentFromPromptResult(result, configFileType);\n await writeFile(output, content);\n console.log();\n logSuccess(pico.bold('Configuration file created.'), [`${pico.bold('Path')}: ${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(\n options: Pick<InitOptions, 'default'>,\n configFileType: ConfigFileType,\n): 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 return 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 onRender() {\n if (configFileType === 'gill') {\n const value = (this as unknown as { value: prompts.Choice[] }).value;\n const jsChoice = value.find(choice => choice.value === 'js')!;\n jsChoice.description = pico.yellow('Required with --gill option.');\n jsChoice.selected = true;\n }\n },\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 PROMPT_OPTIONS,\n );\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\ntype ConfigFileType = 'gill' | 'js' | 'json';\nfunction getConfigFileType(output: string, options: Pick<InitOptions, 'gill' | 'js'>): ConfigFileType {\n if (options.gill) return 'gill';\n else if (options.js) return 'js';\n return output.endsWith('.js') ? 'js' : 'json';\n}\n\nfunction getContentFromPromptResult(result: PromptResult, configFileType: ConfigFileType): string {\n switch (configFileType) {\n case 'gill':\n return getContentForGill(result);\n case 'js':\n return (\n `export default ` +\n JSON.stringify(getConfigFromPromptResult(result), 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 case 'json':\n default:\n return JSON.stringify(getConfigFromPromptResult(result), null, 4);\n }\n}\n\nfunction getConfigFromPromptResult(result: PromptResult): Config {\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 return { idl: result.idlPath, before: [], scripts };\n}\n\nfunction getContentForGill(result: PromptResult): string {\n const attributes: string[] = [\n `idl: \"${result.idlPath}\"`,\n `clientJs: \"${result.jsPath}\"`,\n ...(result.scripts.includes('rust') ? [`clientRust: \"${result.rustPath}\"`] : []),\n ];\n const attributesString = attributes.map(attr => ` ${attr},\\n`).join('');\n\n return (\n `import { createCodamaConfig } from \"gill\";\\n\\n` +\n `export default createCodamaConfig({\\n${attributesString}});\\n`\n );\n}\n\nasync function isAnchorIdl(idlPath: string): Promise<boolean> {\n const resolvedIdlPath = resolveRelativePath(idlPath);\n if (!(await canRead(resolvedIdlPath))) return false;\n try {\n const idlContent = await importModuleItem({ identifier: 'IDL', from: resolvedIdlPath });\n return !isRootNode(idlContent);\n } catch {\n return false;\n }\n}\n","import { ChildProcess, spawn, SpawnOptions } from 'child_process';\n\nexport type ChildCommand = {\n command: string;\n args: string[];\n};\n\nexport function createChildCommand(command: string, args: string[] = []): ChildCommand {\n return { command, args };\n}\n\nexport function formatChildCommand(childCommand: ChildCommand): string {\n const { command, args } = childCommand;\n return [command, ...args].join(' ');\n}\n\nexport type ChildProcessResult = ChildProcess & {\n stdoutString: string;\n stderrString: string;\n};\n\nexport type ChildProcessError = Error & {\n childProcess: ChildProcessResult;\n};\n\nexport async function spawnChildCommand(\n childCommand: ChildCommand,\n options: SpawnOptions & { quiet: boolean } = { quiet: false },\n): Promise<ChildProcess & { stdoutString: string; stderrString: string }> {\n const { command, args } = childCommand;\n const childProcess = spawn(command, args, options) as ChildProcessResult;\n childProcess.stdoutString = '';\n childProcess.stderrString = '';\n\n childProcess.stdout?.on('data', (chunk: Uint8Array) => {\n childProcess.stdoutString += chunk.toString();\n if (!options.quiet) {\n process.stdout.write(chunk);\n }\n });\n childProcess.stderr?.on('data', (chunk: Uint8Array) => {\n childProcess.stderrString += chunk.toString();\n if (!options.quiet) {\n process.stderr.write(chunk);\n }\n });\n\n const exitCode: number = await new Promise((resolve, reject) => {\n childProcess.on('error', () => reject(createChildProcessResultError(childCommand, childProcess)));\n childProcess.on('close', resolve);\n });\n if (exitCode) {\n throw createChildProcessResultError(childCommand, childProcess);\n }\n\n return childProcess;\n}\n\nfunction createChildProcessResultError(\n childCommand: ChildCommand,\n childProcess: ChildProcessResult,\n): ChildProcessError {\n const error = new Error(`Command [${formatChildCommand(childCommand)}] failed`) as ChildProcessError;\n error.childProcess = childProcess;\n return error;\n}\n","export class CliError extends Error {\n constructor(\n message: string,\n public items: string[] = [],\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'CliError';\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 readJson<T>(filePath: string): Promise<T> {\n return JSON.parse(await readFile(filePath)) as T;\n}\n\nexport async function readFile(filePath: string): Promise<string> {\n return await fs.promises.readFile(filePath, 'utf8');\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 pico from 'picocolors';\n\nimport { CliError } from './errors';\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\ntype ImportModuleItemOptions = {\n from: string;\n identifier?: string;\n item?: string;\n};\n\nexport async function importModuleItem<T = unknown>(options: ImportModuleItemOptions): Promise<T> {\n const module = await importModule(options);\n const moduleItem = pickModuleItem(module, options.item) as T | undefined;\n if (moduleItem === undefined) {\n const items = getErrorItems(options);\n throw new CliError(`Failed to load ${options.identifier ?? 'module'}.`, items);\n }\n return moduleItem;\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, item: string = 'default'): unknown {\n if (item === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[item] ?? module.default?.[item] ?? module.default?.default?.[item];\n}\n\nasync function importModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n if (isLocalModulePath(options.from)) {\n return await importLocalModule(options);\n }\n\n try {\n return await importExternalUserModule(options);\n } catch {\n return await importExternalModule(options);\n }\n}\n\nasync function importLocalModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n const { from, identifier } = options;\n if (!(await canRead(from))) {\n const items = getErrorItems(options);\n throw new CliError(`Cannot access ${identifier ?? 'module'}.`, items);\n }\n\n const dotIndex = from.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : from.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(from, { with: { type: 'json' } }) : import(from);\n return await handleImportPromise(modulePromise, options);\n}\n\nasync function importExternalModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n return await handleImportPromise(import(options.from), options);\n}\n\nasync function importExternalUserModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userFrom = userRequire.resolve(options.from);\n return await importExternalModule<T>({ ...options, from: userFrom });\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n options: ImportModuleItemOptions,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (cause) {\n const items = getErrorItems(options, cause);\n throw new CliError(`Failed to load ${options.identifier ?? 'module'}.`, items, { cause });\n }\n}\n\nfunction getErrorItems(options: ImportModuleItemOptions, cause?: unknown): string[] {\n const { from, item } = options;\n const items = [`${pico.bold('Module')}: ${from}`];\n if (item) {\n items.push(`${pico.bold('Item')}: ${item}`);\n }\n\n const hasCause = !!cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string';\n if (hasCause) {\n items.push(`${pico.bold('Caused by')}: ${(cause as { message: string }).message}`);\n }\n\n return items;\n}\n","import pico from 'picocolors';\n\ntype LogLevel = 'debug' | 'error' | 'info' | 'success' | 'warning';\n\ntype LogOptions = {\n level: LogLevel;\n message: string;\n items?: string[];\n};\n\nfunction getLogLevelInfo(logLevel: LogLevel) {\n const identity = (text: string) => text;\n const infos: Record<LogLevel, [string, (text: string) => string, (text: string) => string]> = {\n success: ['✔', pico.green, pico.green],\n info: ['→', pico.blueBright, identity],\n warning: ['▲', pico.yellow, pico.yellow],\n error: ['✖', pico.red, pico.red],\n debug: ['✱', pico.magenta, pico.magenta],\n };\n\n return {\n icon: infos[logLevel][0],\n color: infos[logLevel][1],\n messageColor: infos[logLevel][2],\n };\n}\n\nconst logWrapper = (level: LogLevel) => (message: string, items?: string[]) => log({ level, message, items });\nexport const logSuccess = logWrapper('success');\nexport const logError = logWrapper('error');\nexport const logInfo = logWrapper('info');\nexport const logWarning = logWrapper('warning');\nexport const logDebug = logWrapper('debug');\n\nfunction log({ level, message, items }: LogOptions): void {\n const { icon, color, messageColor } = getLogLevelInfo(level);\n console.log(color(icon), messageColor(message));\n if (items) {\n logItems(items, color);\n }\n}\n\nfunction logItems(items: string[], color?: (text: string) => string): void {\n const colorFn = color ?? (text => text);\n items.forEach((item, index) => {\n const prefix = index === items.length - 1 ? '└─' : '├─';\n console.log(' ' + colorFn(prefix), item);\n });\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 pico from 'picocolors';\nimport prompts from 'prompts';\n\nimport { ChildCommand, createChildCommand, formatChildCommand, spawnChildCommand } from './childCommands';\nimport { logError, logInfo, logSuccess, logWarning } from './logs';\nimport { getPackageJsonDependencies } from './packageJson';\nimport { getPackageManager } from './packageManager';\nimport { PROMPT_OPTIONS } from './prompts';\n\nexport async function getPackageManagerInstallCommand(\n packages: string[],\n options: string[] = [],\n): Promise<ChildCommand> {\n const packageManager = await getPackageManager();\n const args = [packageManager === 'yarn' ? 'add' : 'install', ...packages, ...options];\n return createChildCommand(packageManager, args);\n}\n\nexport async function installMissingDependencies(message: string, requiredDependencies: string[]): Promise<boolean> {\n if (requiredDependencies.length === 0) return true;\n\n const installedDependencies = await getPackageJsonDependencies({ includeDev: true });\n const missingDependencies = requiredDependencies.filter(dep => !installedDependencies.includes(dep));\n if (missingDependencies.length === 0) return true;\n\n return await installDependencies(message, missingDependencies);\n}\n\nexport async function installDependencies(message: string, dependencies: string[]): Promise<boolean> {\n if (dependencies.length === 0) return true;\n const installCommand = await getPackageManagerInstallCommand(dependencies);\n const formattedInstallCommand = pico.yellow(formatChildCommand(installCommand));\n\n if (process.env.CI) {\n logWarning(message);\n logWarning(`Skipping installation in CI environment. Please install manually:`);\n logWarning(formattedInstallCommand);\n return false;\n }\n\n logWarning(message);\n logWarning(`Install command: ${formattedInstallCommand}`);\n\n const dependencyResult: { installDependencies: boolean } = await prompts(\n { initial: true, message: 'Install dependencies?', name: 'installDependencies', type: 'confirm' },\n PROMPT_OPTIONS,\n );\n if (!dependencyResult.installDependencies) {\n logWarning('Skipping installation.');\n return false;\n }\n\n try {\n logInfo(`Installing`, dependencies);\n await spawnChildCommand(installCommand, { quiet: true });\n logSuccess(`Dependencies installed successfully.`);\n return true;\n } catch {\n logError(`Failed to install dependencies. Please try manually:`);\n logError(formattedInstallCommand);\n return false;\n }\n}\n","import pico from 'picocolors';\n\nimport { CliError } from './errors';\nimport { canRead, readJson, resolveRelativePath } from './fs';\n\ntype PackageJson = {\n name: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n scripts?: Record<string, string>;\n packageManager?: string;\n [key: string]: unknown;\n};\n\nlet packageJson: PackageJson | undefined;\nexport async function getPackageJson(): Promise<PackageJson> {\n if (!packageJson) {\n const packageJsonPath = resolveRelativePath('package.json');\n if (!(await canRead(packageJsonPath))) {\n throw new CliError('Cannot read package.json.', [`${pico.bold('Path')}: ${packageJsonPath}`]);\n }\n packageJson = await readJson<PackageJson>(packageJsonPath);\n }\n return packageJson;\n}\n\nexport async function getPackageJsonDependencies(options: { includeDev?: boolean } = {}): Promise<string[]> {\n const packageJson = await getPackageJson();\n return [\n ...(packageJson.dependencies ? Object.keys(packageJson.dependencies) : []),\n ...(options.includeDev && packageJson.devDependencies ? Object.keys(packageJson.devDependencies) : []),\n ];\n}\n","import { createChildCommand, spawnChildCommand } from './childCommands';\nimport { canRead, resolveRelativePath } from './fs';\nimport { getPackageJson } from './packageJson';\n\ntype PackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn';\n\nconst FALLBACK_PACKAGE_MANAGER: PackageManager = 'npm';\n\nlet packageManager: PackageManager | undefined;\nexport async function getPackageManager(): Promise<PackageManager> {\n if (!packageManager) {\n packageManager = await detectPackageManager();\n }\n return packageManager;\n}\n\nasync function detectPackageManager(): Promise<PackageManager> {\n const fromPackageJson = await detectPackageManagerFromPackageJson();\n if (fromPackageJson) return fromPackageJson;\n\n const fromLockfile = await detectPackageManagerFromLockfile();\n if (fromLockfile) return fromLockfile;\n\n const fromInstalledCli = await detectPackageManagerFromInstalledCli();\n if (fromInstalledCli) return fromInstalledCli;\n\n return FALLBACK_PACKAGE_MANAGER;\n}\n\nasync function detectPackageManagerFromPackageJson(): Promise<PackageManager | undefined> {\n const packageJson = await getPackageJson();\n if (!packageJson.packageManager) return undefined;\n if (packageJson.packageManager.startsWith('npm@')) return 'npm';\n if (packageJson.packageManager.startsWith('pnpm@')) return 'pnpm';\n if (packageJson.packageManager.startsWith('yarn@')) return 'yarn';\n if (packageJson.packageManager.startsWith('bun@')) return 'bun';\n return undefined;\n}\n\nasync function detectPackageManagerFromLockfile(): Promise<PackageManager | undefined> {\n const [isYarn, isPnpm, isBun, isNpm] = await Promise.all([\n canRead(resolveRelativePath('yarn.lock')),\n canRead(resolveRelativePath('pnpm-lock.yaml')),\n canRead(resolveRelativePath('bun.lockb')),\n canRead(resolveRelativePath('package-lock.json')),\n ]);\n\n if (isYarn) return 'yarn';\n if (isPnpm) return 'pnpm';\n if (isBun) return 'bun';\n if (isNpm) return 'npm';\n return undefined;\n}\n\nasync function detectPackageManagerFromInstalledCli(): Promise<PackageManager | undefined> {\n const [isPnpm, isYarn, isBun] = await Promise.all([\n hasPackageManagerCli('pnpm'),\n hasPackageManagerCli('yarn'),\n hasPackageManagerCli('bun'),\n ]);\n\n if (isPnpm) return 'pnpm';\n if (isYarn) return 'yarn';\n if (isBun) return 'bun';\n return undefined;\n}\n\nasync function hasPackageManagerCli(packageManager: PackageManager): Promise<boolean> {\n return await spawnChildCommand(createChildCommand(packageManager, ['--version']), { quiet: true })\n .then(() => true)\n .catch(() => false);\n}\n","import prompts from 'prompts';\n\nimport { CliError } from './errors';\n\nexport const PROMPT_OPTIONS: prompts.Options = {\n onCancel: () => {\n throw new CliError('Operation cancelled.');\n },\n};\n","import type { RootNode } from '@codama/nodes';\n\nimport { CliError } from './errors';\nimport { importModuleItem } from './import';\nimport { installMissingDependencies } from './packageInstall';\n\nexport async function getRootNodeFromIdl(idl: unknown): Promise<RootNode> {\n if (typeof idl !== 'object' || idl === null) {\n throw new CliError('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n\n const hasNodesFromAnchor = await installMissingDependencies(\n 'Anchor IDL detected. Additional dependencies are required to process Anchor IDLs.',\n ['@codama/nodes-from-anchor'],\n );\n if (!hasNodesFromAnchor) {\n throw new CliError('Cannot proceed without Anchor IDL support.');\n }\n\n const rootNodeFromAnchor = await importModuleItem<(idl: unknown) => RootNode>({\n from: '@codama/nodes-from-anchor',\n item: 'rootNodeFromAnchor',\n });\n return rootNodeFromAnchor(idl);\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';\nimport pico from 'picocolors';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { CliError } from './errors';\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 { item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem({ identifier, from: path, item });\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, visitorConfig);\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 visitorConfig: ParsedVisitorConfig,\n): Promise<Visitor<unknown, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\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 CliError(`Invalid visitor. Expected a visitor or a function returning a visitor.`, [\n `${pico.bold('Visitor')}: ${identifier}`,\n `${pico.bold('Path')}: ${path}`,\n ...(item ? [`${pico.bold('Item')}: ${item}`] : []),\n ]);\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, script } = visitorConfig;\n let identifier = `visitor #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\nimport pico from 'picocolors';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport {\n CliError,\n getRootNodeVisitors,\n installMissingDependencies,\n isLocalModulePath,\n logInfo,\n logSuccess,\n logWarning,\n} 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 configuration 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 CliError('There are no scripts or before visitors to run.');\n }\n\n checkMissingScripts(parsedConfig, scripts);\n await checkMissingDependencies(parsedConfig, scripts);\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\nfunction checkMissingScripts(parsedConfig: Pick<ParsedConfig, 'configPath' | 'scripts'>, scripts: ScriptName[]) {\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length === 0) return;\n\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const message = parsedConfig.configPath\n ? `${scriptPluralized} not found in configuration file.`\n : `${scriptPluralized} not found because no configuration file was found.`;\n const items = [\n `${pico.bold(scriptPluralized)}: ${missingScripts.join(', ')}`,\n ...(parsedConfig.configPath ? [`${pico.bold('Path')}: ${parsedConfig.configPath}`] : []),\n ];\n throw new CliError(message, items);\n}\n\nasync function checkMissingDependencies(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n) {\n const dependencies = new Set<string>([\n ...parsedConfig.before.map(v => v.path),\n ...scripts.flatMap(script => parsedConfig.scripts[script]?.map(v => v.path) ?? []),\n ]);\n const externalDependencies = [...dependencies].filter(dep => !isLocalModulePath(dep));\n const scriptsRequirePluralized = scripts.length === 1 ? 'script requires' : 'scripts require';\n const installed = await installMissingDependencies(\n `Your ${scriptsRequirePluralized} additional dependencies.`,\n externalDependencies,\n );\n if (!installed) {\n throw new CliError('Cannot proceed without missing dependencies.');\n }\n}\n","import path from 'node:path';\n\nimport pico from 'picocolors';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, CliError, 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 configuration file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem({ identifier: 'configuration file', from: configPath });\n if (!configFile || typeof configFile !== 'object') {\n throw new CliError(`Invalid configuration file.`, [`${pico.bold('Path')}: ${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 CliError,\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());\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({ identifier: 'IDL', from: idlPath });\n const rootNode = await 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 CliError('No IDL identified. Please provide the `--idl` option or set it in the configuration 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,uBAAqD;AACrD,IAAAA,qBAAiB;;;ACAjB,IAAAC,qBAAiB;AACjB,IAAAC,kBAAoC;;;ACFpC,2BAAkD;AAO3C,SAAS,mBAAmB,SAAiB,OAAiB,CAAC,GAAiB;AACnF,SAAO,EAAE,SAAS,KAAK;AAC3B;AAEO,SAAS,mBAAmB,cAAoC;AACnE,QAAM,EAAE,SAAS,KAAK,IAAI;AAC1B,SAAO,CAAC,SAAS,GAAG,IAAI,EAAE,KAAK,GAAG;AACtC;AAWA,eAAsB,kBAClB,cACA,UAA6C,EAAE,OAAO,MAAM,GACU;AACtE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AAE,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;;;ADjDA,IAAM,UAAU,cAAc;AAE9B,eAAsB,IAAI,MAAyB;AAC/C,QAAM,WAAW,SAAS,IAAI;AAClC;","names":["import_picocolors","import_picocolors","import_prompts","path","fs","module","pico","import_picocolors","pico","import_picocolors","import_picocolors","pico","packageJson","packageJson","packageManager","packageManager","pico","prompts","import_picocolors","path","pico","program","pico","prompts","import_visitors_core","import_picocolors","import_node_path","import_picocolors","path","pico","path","program","pico","program","program","pico"]} |
+418
-119
@@ -35,8 +35,3 @@ "use strict"; | ||
| createProgram: () => createProgram, | ||
| logBanner: () => logBanner, | ||
| logDebug: () => logDebug, | ||
| logError: () => logError, | ||
| logInfo: () => logInfo, | ||
| logSuccess: () => logSuccess, | ||
| logWarning: () => logWarning | ||
| runProgram: () => runProgram | ||
| }); | ||
@@ -47,6 +42,58 @@ module.exports = __toCommonJS(index_exports); | ||
| var import_commander = require("commander"); | ||
| var import_picocolors9 = __toESM(require("picocolors")); | ||
| // src/commands/init.ts | ||
| var import_prompts = __toESM(require("prompts")); | ||
| var import_picocolors6 = __toESM(require("picocolors")); | ||
| var import_prompts3 = __toESM(require("prompts")); | ||
| // src/utils/childCommands.ts | ||
| var import_child_process = require("child_process"); | ||
| function createChildCommand(command, args = []) { | ||
| return { command, args }; | ||
| } | ||
| function formatChildCommand(childCommand) { | ||
| const { command, args } = childCommand; | ||
| return [command, ...args].join(" "); | ||
| } | ||
| async function spawnChildCommand(childCommand, options = { quiet: false }) { | ||
| const { command, args } = childCommand; | ||
| const childProcess = (0, import_child_process.spawn)(command, args, options); | ||
| childProcess.stdoutString = ""; | ||
| childProcess.stderrString = ""; | ||
| childProcess.stdout?.on("data", (chunk) => { | ||
| childProcess.stdoutString += chunk.toString(); | ||
| if (!options.quiet) { | ||
| process.stdout.write(chunk); | ||
| } | ||
| }); | ||
| childProcess.stderr?.on("data", (chunk) => { | ||
| childProcess.stderrString += chunk.toString(); | ||
| if (!options.quiet) { | ||
| process.stderr.write(chunk); | ||
| } | ||
| }); | ||
| const exitCode = await new Promise((resolve, reject) => { | ||
| childProcess.on("error", () => reject(createChildProcessResultError(childCommand, childProcess))); | ||
| childProcess.on("close", resolve); | ||
| }); | ||
| if (exitCode) { | ||
| throw createChildProcessResultError(childCommand, childProcess); | ||
| } | ||
| return childProcess; | ||
| } | ||
| function createChildProcessResultError(childCommand, childProcess) { | ||
| const error = new Error(`Command [${formatChildCommand(childCommand)}] failed`); | ||
| error.childProcess = childProcess; | ||
| return error; | ||
| } | ||
| // src/utils/errors.ts | ||
| var CliError = class extends Error { | ||
| constructor(message, items = [], options) { | ||
| super(message, options); | ||
| this.items = items; | ||
| this.name = "CliError"; | ||
| } | ||
| }; | ||
| // src/utils/fs.ts | ||
@@ -66,2 +113,8 @@ var import_node_constants = require("constants"); | ||
| } | ||
| async function readJson(filePath) { | ||
| return JSON.parse(await readFile(filePath)); | ||
| } | ||
| async function readFile(filePath) { | ||
| return await import_node_fs.default.promises.readFile(filePath, "utf8"); | ||
| } | ||
| async function writeFile(filePath, content) { | ||
@@ -93,73 +146,106 @@ const directory = import_node_path.default.dirname(filePath); | ||
| var import_node_module = require("module"); | ||
| async function importModuleItem(identifier, modulePath, itemName = "default") { | ||
| const module2 = await importModule(identifier, modulePath); | ||
| const item = pickModuleItem(module2, itemName); | ||
| if (item === void 0) { | ||
| throw new Error(`Failed to import "${itemName}" from ${identifier} at "${modulePath}".`); | ||
| var import_picocolors = __toESM(require("picocolors")); | ||
| async function importModuleItem(options) { | ||
| const module2 = await importModule(options); | ||
| const moduleItem = pickModuleItem(module2, options.item); | ||
| if (moduleItem === void 0) { | ||
| const items = getErrorItems(options); | ||
| throw new CliError(`Failed to load ${options.identifier ?? "module"}.`, items); | ||
| } | ||
| return item; | ||
| return moduleItem; | ||
| } | ||
| function pickModuleItem(module2, itemName) { | ||
| if (itemName === "default") { | ||
| function pickModuleItem(module2, item = "default") { | ||
| if (item === "default") { | ||
| return module2.default?.default ?? module2.default ?? module2; | ||
| } | ||
| return module2[itemName] ?? module2.default?.[itemName] ?? module2.default?.default?.[itemName]; | ||
| return module2[item] ?? module2.default?.[item] ?? module2.default?.default?.[item]; | ||
| } | ||
| async function importModule(identifier, modulePath) { | ||
| if (isLocalModulePath(modulePath)) { | ||
| return await importLocalModule(identifier, modulePath); | ||
| async function importModule(options) { | ||
| if (isLocalModulePath(options.from)) { | ||
| return await importLocalModule(options); | ||
| } | ||
| try { | ||
| return await importExternalUserModule(identifier, modulePath); | ||
| return await importExternalUserModule(options); | ||
| } catch { | ||
| return await importExternalModule(identifier, modulePath); | ||
| return await importExternalModule(options); | ||
| } | ||
| } | ||
| async function importLocalModule(identifier, modulePath) { | ||
| if (!await canRead(modulePath)) { | ||
| throw new Error(`Cannot access ${identifier} at "${modulePath}"`); | ||
| async function importLocalModule(options) { | ||
| const { from, identifier } = options; | ||
| if (!await canRead(from)) { | ||
| const items = getErrorItems(options); | ||
| throw new CliError(`Cannot access ${identifier ?? "module"}.`, items); | ||
| } | ||
| const dotIndex = modulePath.lastIndexOf("."); | ||
| const extension = dotIndex === -1 ? void 0 : modulePath.slice(dotIndex); | ||
| const modulePromise = extension === ".json" ? import(modulePath, { with: { type: "json" } }) : import(modulePath); | ||
| return await handleImportPromise(modulePromise, identifier, modulePath); | ||
| const dotIndex = from.lastIndexOf("."); | ||
| const extension = dotIndex === -1 ? void 0 : from.slice(dotIndex); | ||
| const modulePromise = extension === ".json" ? import(from, { with: { type: "json" } }) : import(from); | ||
| return await handleImportPromise(modulePromise, options); | ||
| } | ||
| async function importExternalModule(identifier, modulePath) { | ||
| return await handleImportPromise(import(modulePath), identifier, modulePath); | ||
| async function importExternalModule(options) { | ||
| return await handleImportPromise(import(options.from), options); | ||
| } | ||
| async function importExternalUserModule(identifier, modulePath) { | ||
| async function importExternalUserModule(options) { | ||
| const userPackageJsonPath = resolveRelativePath("package.json"); | ||
| const userRequire = (0, import_node_module.createRequire)(userPackageJsonPath); | ||
| const userModulePath = userRequire.resolve(modulePath); | ||
| return await importExternalModule(identifier, userModulePath); | ||
| const userFrom = userRequire.resolve(options.from); | ||
| return await importExternalModule({ ...options, from: userFrom }); | ||
| } | ||
| async function handleImportPromise(importPromise, identifier, modulePath) { | ||
| async function handleImportPromise(importPromise, options) { | ||
| try { | ||
| return await importPromise; | ||
| } catch (error) { | ||
| let causeMessage = !!error && typeof error === "object" && "message" in error && typeof error.message === "string" ? error.message : void 0; | ||
| causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : ""; | ||
| throw new Error(`Failed to import ${identifier} at "${modulePath}" as a module${causeMessage}`, { | ||
| cause: error | ||
| }); | ||
| } catch (cause) { | ||
| const items = getErrorItems(options, cause); | ||
| throw new CliError(`Failed to load ${options.identifier ?? "module"}.`, items, { cause }); | ||
| } | ||
| } | ||
| function getErrorItems(options, cause) { | ||
| const { from, item } = options; | ||
| const items = [`${import_picocolors.default.bold("Module")}: ${from}`]; | ||
| if (item) { | ||
| items.push(`${import_picocolors.default.bold("Item")}: ${item}`); | ||
| } | ||
| const hasCause = !!cause && typeof cause === "object" && "message" in cause && typeof cause.message === "string"; | ||
| if (hasCause) { | ||
| items.push(`${import_picocolors.default.bold("Caused by")}: ${cause.message}`); | ||
| } | ||
| return items; | ||
| } | ||
| // src/utils/logs.ts | ||
| var import_picocolors = __toESM(require("picocolors")); | ||
| function logSuccess(...args) { | ||
| console.log(import_picocolors.default.green("[Success]"), ...args); | ||
| var import_picocolors2 = __toESM(require("picocolors")); | ||
| function getLogLevelInfo(logLevel) { | ||
| const identity = (text) => text; | ||
| const infos = { | ||
| success: ["\u2714", import_picocolors2.default.green, import_picocolors2.default.green], | ||
| info: ["\u2192", import_picocolors2.default.blueBright, identity], | ||
| warning: ["\u25B2", import_picocolors2.default.yellow, import_picocolors2.default.yellow], | ||
| error: ["\u2716", import_picocolors2.default.red, import_picocolors2.default.red], | ||
| debug: ["\u2731", import_picocolors2.default.magenta, import_picocolors2.default.magenta] | ||
| }; | ||
| return { | ||
| icon: infos[logLevel][0], | ||
| color: infos[logLevel][1], | ||
| messageColor: infos[logLevel][2] | ||
| }; | ||
| } | ||
| function logInfo(...args) { | ||
| console.log(import_picocolors.default.blueBright("[Info]"), ...args); | ||
| var logWrapper = (level) => (message, items) => log({ level, message, items }); | ||
| var logSuccess = logWrapper("success"); | ||
| var logError = logWrapper("error"); | ||
| var logInfo = logWrapper("info"); | ||
| var logWarning = logWrapper("warning"); | ||
| var logDebug = logWrapper("debug"); | ||
| function log({ level, message, items }) { | ||
| const { icon, color, messageColor } = getLogLevelInfo(level); | ||
| console.log(color(icon), messageColor(message)); | ||
| if (items) { | ||
| logItems(items, color); | ||
| } | ||
| } | ||
| function logWarning(...args) { | ||
| console.log(import_picocolors.default.yellow("[Warning]"), ...args); | ||
| function logItems(items, color) { | ||
| const colorFn = color ?? ((text) => text); | ||
| items.forEach((item, index) => { | ||
| const prefix = index === items.length - 1 ? "\u2514\u2500" : "\u251C\u2500"; | ||
| console.log(" " + colorFn(prefix), item); | ||
| }); | ||
| } | ||
| function logError(...args) { | ||
| console.log(import_picocolors.default.red("[Error]"), ...args); | ||
| } | ||
| function logDebug(...args) { | ||
| console.log(import_picocolors.default.magenta("[Debug]"), ...args); | ||
| } | ||
| function logBanner() { | ||
@@ -170,11 +256,142 @@ console.log(getBanner()); | ||
| const textBanner = "Welcome to Codama!"; | ||
| const gradientBanner = import_picocolors.default.bold(`\x1B[38;2;231;171;97m${textBanner}\x1B[0m`); | ||
| const gradientBanner = import_picocolors2.default.bold(`\x1B[38;2;231;171;97m${textBanner}\x1B[0m`); | ||
| return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner; | ||
| } | ||
| // src/utils/packageInstall.ts | ||
| var import_picocolors4 = __toESM(require("picocolors")); | ||
| var import_prompts = __toESM(require("prompts")); | ||
| // src/utils/packageJson.ts | ||
| var import_picocolors3 = __toESM(require("picocolors")); | ||
| var packageJson; | ||
| async function getPackageJson() { | ||
| if (!packageJson) { | ||
| const packageJsonPath = resolveRelativePath("package.json"); | ||
| if (!await canRead(packageJsonPath)) { | ||
| throw new CliError("Cannot read package.json.", [`${import_picocolors3.default.bold("Path")}: ${packageJsonPath}`]); | ||
| } | ||
| packageJson = await readJson(packageJsonPath); | ||
| } | ||
| return packageJson; | ||
| } | ||
| async function getPackageJsonDependencies(options = {}) { | ||
| const packageJson2 = await getPackageJson(); | ||
| return [ | ||
| ...packageJson2.dependencies ? Object.keys(packageJson2.dependencies) : [], | ||
| ...options.includeDev && packageJson2.devDependencies ? Object.keys(packageJson2.devDependencies) : [] | ||
| ]; | ||
| } | ||
| // src/utils/packageManager.ts | ||
| var FALLBACK_PACKAGE_MANAGER = "npm"; | ||
| var packageManager; | ||
| async function getPackageManager() { | ||
| if (!packageManager) { | ||
| packageManager = await detectPackageManager(); | ||
| } | ||
| return packageManager; | ||
| } | ||
| async function detectPackageManager() { | ||
| const fromPackageJson = await detectPackageManagerFromPackageJson(); | ||
| if (fromPackageJson) return fromPackageJson; | ||
| const fromLockfile = await detectPackageManagerFromLockfile(); | ||
| if (fromLockfile) return fromLockfile; | ||
| const fromInstalledCli = await detectPackageManagerFromInstalledCli(); | ||
| if (fromInstalledCli) return fromInstalledCli; | ||
| return FALLBACK_PACKAGE_MANAGER; | ||
| } | ||
| async function detectPackageManagerFromPackageJson() { | ||
| const packageJson2 = await getPackageJson(); | ||
| if (!packageJson2.packageManager) return void 0; | ||
| if (packageJson2.packageManager.startsWith("npm@")) return "npm"; | ||
| if (packageJson2.packageManager.startsWith("pnpm@")) return "pnpm"; | ||
| if (packageJson2.packageManager.startsWith("yarn@")) return "yarn"; | ||
| if (packageJson2.packageManager.startsWith("bun@")) return "bun"; | ||
| return void 0; | ||
| } | ||
| async function detectPackageManagerFromLockfile() { | ||
| const [isYarn, isPnpm, isBun, isNpm] = await Promise.all([ | ||
| canRead(resolveRelativePath("yarn.lock")), | ||
| canRead(resolveRelativePath("pnpm-lock.yaml")), | ||
| canRead(resolveRelativePath("bun.lockb")), | ||
| canRead(resolveRelativePath("package-lock.json")) | ||
| ]); | ||
| if (isYarn) return "yarn"; | ||
| if (isPnpm) return "pnpm"; | ||
| if (isBun) return "bun"; | ||
| if (isNpm) return "npm"; | ||
| return void 0; | ||
| } | ||
| async function detectPackageManagerFromInstalledCli() { | ||
| const [isPnpm, isYarn, isBun] = await Promise.all([ | ||
| hasPackageManagerCli("pnpm"), | ||
| hasPackageManagerCli("yarn"), | ||
| hasPackageManagerCli("bun") | ||
| ]); | ||
| if (isPnpm) return "pnpm"; | ||
| if (isYarn) return "yarn"; | ||
| if (isBun) return "bun"; | ||
| return void 0; | ||
| } | ||
| async function hasPackageManagerCli(packageManager2) { | ||
| return await spawnChildCommand(createChildCommand(packageManager2, ["--version"]), { quiet: true }).then(() => true).catch(() => false); | ||
| } | ||
| // src/utils/prompts.ts | ||
| var PROMPT_OPTIONS = { | ||
| onCancel: () => { | ||
| throw new CliError("Operation cancelled."); | ||
| } | ||
| }; | ||
| // src/utils/packageInstall.ts | ||
| async function getPackageManagerInstallCommand(packages, options = []) { | ||
| const packageManager2 = await getPackageManager(); | ||
| const args = [packageManager2 === "yarn" ? "add" : "install", ...packages, ...options]; | ||
| return createChildCommand(packageManager2, args); | ||
| } | ||
| async function installMissingDependencies(message, requiredDependencies) { | ||
| if (requiredDependencies.length === 0) return true; | ||
| const installedDependencies = await getPackageJsonDependencies({ includeDev: true }); | ||
| const missingDependencies = requiredDependencies.filter((dep) => !installedDependencies.includes(dep)); | ||
| if (missingDependencies.length === 0) return true; | ||
| return await installDependencies(message, missingDependencies); | ||
| } | ||
| async function installDependencies(message, dependencies) { | ||
| if (dependencies.length === 0) return true; | ||
| const installCommand = await getPackageManagerInstallCommand(dependencies); | ||
| const formattedInstallCommand = import_picocolors4.default.yellow(formatChildCommand(installCommand)); | ||
| if (process.env.CI) { | ||
| logWarning(message); | ||
| logWarning(`Skipping installation in CI environment. Please install manually:`); | ||
| logWarning(formattedInstallCommand); | ||
| return false; | ||
| } | ||
| logWarning(message); | ||
| logWarning(`Install command: ${formattedInstallCommand}`); | ||
| const dependencyResult = await (0, import_prompts.default)( | ||
| { initial: true, message: "Install dependencies?", name: "installDependencies", type: "confirm" }, | ||
| PROMPT_OPTIONS | ||
| ); | ||
| if (!dependencyResult.installDependencies) { | ||
| logWarning("Skipping installation."); | ||
| return false; | ||
| } | ||
| try { | ||
| logInfo(`Installing`, dependencies); | ||
| await spawnChildCommand(installCommand, { quiet: true }); | ||
| logSuccess(`Dependencies installed successfully.`); | ||
| return true; | ||
| } catch { | ||
| logError(`Failed to install dependencies. Please try manually:`); | ||
| logError(formattedInstallCommand); | ||
| return false; | ||
| } | ||
| } | ||
| // src/utils/nodes.ts | ||
| var import_nodes_from_anchor = require("@codama/nodes-from-anchor"); | ||
| function getRootNodeFromIdl(idl) { | ||
| async function getRootNodeFromIdl(idl) { | ||
| if (typeof idl !== "object" || idl === null) { | ||
| throw new Error("Unexpected IDL content. Expected an object, got " + typeof idl); | ||
| throw new CliError("Unexpected IDL content. Expected an object, got " + typeof idl); | ||
| } | ||
@@ -184,3 +401,14 @@ if (isRootNode(idl)) { | ||
| } | ||
| return (0, import_nodes_from_anchor.rootNodeFromAnchor)(idl); | ||
| const hasNodesFromAnchor = await installMissingDependencies( | ||
| "Anchor IDL detected. Additional dependencies are required to process Anchor IDLs.", | ||
| ["@codama/nodes-from-anchor"] | ||
| ); | ||
| if (!hasNodesFromAnchor) { | ||
| throw new CliError("Cannot proceed without Anchor IDL support."); | ||
| } | ||
| const rootNodeFromAnchor = await importModuleItem({ | ||
| from: "@codama/nodes-from-anchor", | ||
| item: "rootNodeFromAnchor" | ||
| }); | ||
| return rootNodeFromAnchor(idl); | ||
| } | ||
@@ -198,2 +426,3 @@ function isRootNode(value) { | ||
| var import_visitors_core = require("@codama/visitors-core"); | ||
| var import_picocolors5 = __toESM(require("picocolors")); | ||
| async function getRootNodeVisitors(visitors) { | ||
@@ -203,6 +432,6 @@ return await Promise.all(visitors.map(getRootNodeVisitor)); | ||
| async function getRootNodeVisitor(visitorConfig) { | ||
| const { args, item, path: path3 } = visitorConfig; | ||
| const { item, path: path3 } = visitorConfig; | ||
| const identifier = getVisitorIdentifier(visitorConfig); | ||
| const moduleItem = await importModuleItem(identifier, path3, item); | ||
| const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args); | ||
| const moduleItem = await importModuleItem({ identifier, from: path3, item }); | ||
| const visitor = await getVisitorFromModuleItem(identifier, moduleItem, visitorConfig); | ||
| return (0, import_visitors_core.rootNodeVisitor)((root) => { | ||
@@ -213,3 +442,4 @@ const result = (0, import_visitors_core.visit)(root, visitor); | ||
| } | ||
| async function getVisitorFromModuleItem(identifier, moduleItem, args) { | ||
| async function getVisitorFromModuleItem(identifier, moduleItem, visitorConfig) { | ||
| const { args, item, path: path3 } = visitorConfig; | ||
| if (isRootNodeVisitor(moduleItem)) { | ||
@@ -224,3 +454,7 @@ return moduleItem; | ||
| } | ||
| throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`); | ||
| throw new CliError(`Invalid visitor. Expected a visitor or a function returning a visitor.`, [ | ||
| `${import_picocolors5.default.bold("Visitor")}: ${identifier}`, | ||
| `${import_picocolors5.default.bold("Path")}: ${path3}`, | ||
| ...item ? [`${import_picocolors5.default.bold("Item")}: ${item}`] : [] | ||
| ]); | ||
| } | ||
@@ -231,7 +465,5 @@ function isRootNodeVisitor(value) { | ||
| function getVisitorIdentifier(visitorConfig) { | ||
| const { index, item, path: path3, script } = visitorConfig; | ||
| const pathWithItem = item ? `${path3}#${item}` : path3; | ||
| let identifier = `visitor of index #${index}`; | ||
| const { index, script } = visitorConfig; | ||
| let identifier = `visitor #${index}`; | ||
| identifier += script ? ` in script "${script}"` : ""; | ||
| identifier += ` (at path "${pathWithItem}")`; | ||
| return identifier; | ||
@@ -242,17 +474,22 @@ } | ||
| 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").option("--gill", "Forces the output to be a gill based 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("--force", "Overwrite existing configuration file, if any").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); | ||
| let configFileType = output.endsWith(".js") ? "js" : "json"; | ||
| if (options.gill) configFileType = "gill"; | ||
| else if (options.js) configFileType = "js"; | ||
| if (await canRead(output)) { | ||
| throw new Error(`Configuration file already exists at "${output}".`); | ||
| const configFileType = getConfigFileType(output, options); | ||
| if (!options.force && await canRead(output)) { | ||
| throw new CliError(`Configuration file already exists.`, [`${import_picocolors6.default.bold("Path")}: ${output}`]); | ||
| } | ||
| logBanner(); | ||
| const result = await getPromptResult(options); | ||
| const result = await getPromptResult(options, configFileType); | ||
| const isAnchor = await isAnchorIdl(result.idlPath); | ||
| await installMissingDependencies(`Your configuration requires additional dependencies.`, [ | ||
| ...isAnchor ? ["@codama/nodes-from-anchor"] : [], | ||
| ...result.scripts.includes("js") ? ["@codama/renderers-js"] : [], | ||
| ...result.scripts.includes("rust") ? ["@codama/renderers-rust"] : [] | ||
| ]); | ||
| const content = getContentFromPromptResult(result, configFileType); | ||
| await writeFile(output, content); | ||
| logSuccess(`Configuration file created at "${output}".`); | ||
| console.log(); | ||
| logSuccess(import_picocolors6.default.bold("Configuration file created."), [`${import_picocolors6.default.bold("Path")}: ${output}`]); | ||
| } | ||
@@ -265,3 +502,3 @@ function getOutputPath(explicitOutput, options) { | ||
| } | ||
| async function getPromptResult(options) { | ||
| async function getPromptResult(options, configFileType) { | ||
| const defaults = getDefaultPromptResult(); | ||
@@ -272,3 +509,3 @@ if (options.default) { | ||
| const hasScript = (script, type = "text") => (_, values) => values.scripts.includes(script) ? type : null; | ||
| const result = await (0, import_prompts.default)( | ||
| return await (0, import_prompts3.default)( | ||
| [ | ||
@@ -289,3 +526,11 @@ { | ||
| name: "scripts", | ||
| type: "multiselect" | ||
| type: "multiselect", | ||
| onRender() { | ||
| if (configFileType === "gill") { | ||
| const value = this.value; | ||
| const jsChoice = value.find((choice) => choice.value === "js"); | ||
| jsChoice.description = import_picocolors6.default.yellow("Required with --gill option."); | ||
| jsChoice.selected = true; | ||
| } | ||
| } | ||
| }, | ||
@@ -311,9 +556,4 @@ { | ||
| ], | ||
| { | ||
| onCancel: () => { | ||
| throw new Error("Operation cancelled."); | ||
| } | ||
| } | ||
| PROMPT_OPTIONS | ||
| ); | ||
| return result; | ||
| } | ||
@@ -329,3 +569,19 @@ function getDefaultPromptResult() { | ||
| } | ||
| function getConfigFileType(output, options) { | ||
| if (options.gill) return "gill"; | ||
| else if (options.js) return "js"; | ||
| return output.endsWith(".js") ? "js" : "json"; | ||
| } | ||
| function getContentFromPromptResult(result, configFileType) { | ||
| switch (configFileType) { | ||
| case "gill": | ||
| return getContentForGill(result); | ||
| case "js": | ||
| return `export default ` + JSON.stringify(getConfigFromPromptResult(result), null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'"); | ||
| case "json": | ||
| default: | ||
| return JSON.stringify(getConfigFromPromptResult(result), null, 4); | ||
| } | ||
| } | ||
| function getConfigFromPromptResult(result) { | ||
| const scripts = {}; | ||
@@ -344,15 +600,27 @@ if (result.scripts.includes("js")) { | ||
| } | ||
| const content = { idl: result.idlPath, before: [], scripts }; | ||
| if (configFileType == "json") { | ||
| return JSON.stringify(content, null, 4); | ||
| } else if (configFileType == "gill") { | ||
| return `import { createCodamaConfig } from "gill"; | ||
| return { idl: result.idlPath, before: [], scripts }; | ||
| } | ||
| function getContentForGill(result) { | ||
| const attributes = [ | ||
| `idl: "${result.idlPath}"`, | ||
| `clientJs: "${result.jsPath}"`, | ||
| ...result.scripts.includes("rust") ? [`clientRust: "${result.rustPath}"`] : [] | ||
| ]; | ||
| const attributesString = attributes.map((attr) => ` ${attr}, | ||
| `).join(""); | ||
| return `import { createCodamaConfig } from "gill"; | ||
| export default createCodamaConfig({ | ||
| idl: "${result.idlPath}", | ||
| clientJs: "${result.jsPath}", | ||
| ` + result.scripts.includes("rust") ? `clientRust: "${result.rustPath}", | ||
| ` : `});`; | ||
| export default createCodamaConfig({ | ||
| ${attributesString}}); | ||
| `; | ||
| } | ||
| async function isAnchorIdl(idlPath) { | ||
| const resolvedIdlPath = resolveRelativePath(idlPath); | ||
| if (!await canRead(resolvedIdlPath)) return false; | ||
| try { | ||
| const idlContent = await importModuleItem({ identifier: "IDL", from: resolvedIdlPath }); | ||
| return !isRootNode(idlContent); | ||
| } catch { | ||
| return false; | ||
| } | ||
| return "export default " + JSON.stringify(content, null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'"); | ||
| } | ||
@@ -362,14 +630,16 @@ | ||
| var import_visitors_core2 = require("@codama/visitors-core"); | ||
| var import_picocolors8 = __toESM(require("picocolors")); | ||
| // src/config.ts | ||
| var import_node_path2 = __toESM(require("path")); | ||
| var import_picocolors7 = __toESM(require("picocolors")); | ||
| async function getConfig(options) { | ||
| const configPath = options.config != null ? import_node_path2.default.resolve(options.config) : await getDefaultConfigPath(); | ||
| if (!configPath) { | ||
| logWarning("No config file found. Using empty configs. Make sure you provide the `--idl` option."); | ||
| logWarning("No configuration file found. Using empty configs. Make sure you provide the `--idl` option."); | ||
| return [{}, configPath]; | ||
| } | ||
| const configFile = await importModuleItem("config file", configPath); | ||
| const configFile = await importModuleItem({ identifier: "configuration file", from: configPath }); | ||
| if (!configFile || typeof configFile !== "object") { | ||
| throw new Error(`Invalid config file at "${configPath}"`); | ||
| throw new CliError(`Invalid configuration file.`, [`${import_picocolors7.default.bold("Path")}: ${configPath}`]); | ||
| } | ||
@@ -399,4 +669,4 @@ return [configFile, configPath]; | ||
| const idlPath = parseIdlPath(config, configPath, options); | ||
| const idlContent = await importModuleItem("IDL", idlPath); | ||
| const rootNode = getRootNodeFromIdl(idlContent); | ||
| const idlContent = await importModuleItem({ identifier: "IDL", from: idlPath }); | ||
| const rootNode = await getRootNodeFromIdl(idlContent); | ||
| const scripts = parseScripts(config.scripts ?? {}, configPath); | ||
@@ -413,3 +683,3 @@ const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null)); | ||
| } | ||
| throw new Error("No IDL identified. Please provide the `--idl` option or set it in the config file."); | ||
| throw new CliError("No IDL identified. Please provide the `--idl` option or set it in the configuration file."); | ||
| } | ||
@@ -438,3 +708,3 @@ function parseScripts(scripts, configPath) { | ||
| function setRunCommand(program) { | ||
| program.command("run").argument("[scripts...]", "The scripts to execute").option("-a, --all", "Run all scripts in the config file").action(doRun); | ||
| program.command("run").argument("[scripts...]", "The scripts to execute").option("-a, --all", "Run all scripts in the configuration file").action(doRun); | ||
| } | ||
@@ -453,11 +723,6 @@ async function doRun(explicitScripts, { all }, cmd) { | ||
| if (scripts.length === 0 && parsedConfig.before.length === 0) { | ||
| throw new Error("There are no scripts or before visitors to run."); | ||
| throw new CliError("There are no scripts or before visitors to run."); | ||
| } | ||
| const missingScripts = scripts.filter((script) => !parsedConfig.scripts[script]); | ||
| if (missingScripts.length > 0) { | ||
| const scriptPluralized = missingScripts.length === 1 ? "Script" : "Scripts"; | ||
| const missingScriptsIdentifier = `${scriptPluralized} "${missingScripts.join(", ")}"`; | ||
| const message = parsedConfig.configPath ? `${missingScriptsIdentifier} not found in config file "${parsedConfig.configPath}"` : `${missingScriptsIdentifier} not found because no config file was found`; | ||
| throw new Error(message); | ||
| } | ||
| checkMissingScripts(parsedConfig, scripts); | ||
| await checkMissingDependencies(parsedConfig, scripts); | ||
| if (parsedConfig.before.length > 0) { | ||
@@ -488,2 +753,28 @@ plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) }); | ||
| } | ||
| function checkMissingScripts(parsedConfig, scripts) { | ||
| const missingScripts = scripts.filter((script) => !parsedConfig.scripts[script]); | ||
| if (missingScripts.length === 0) return; | ||
| const scriptPluralized = missingScripts.length === 1 ? "Script" : "Scripts"; | ||
| const message = parsedConfig.configPath ? `${scriptPluralized} not found in configuration file.` : `${scriptPluralized} not found because no configuration file was found.`; | ||
| const items = [ | ||
| `${import_picocolors8.default.bold(scriptPluralized)}: ${missingScripts.join(", ")}`, | ||
| ...parsedConfig.configPath ? [`${import_picocolors8.default.bold("Path")}: ${parsedConfig.configPath}`] : [] | ||
| ]; | ||
| throw new CliError(message, items); | ||
| } | ||
| async function checkMissingDependencies(parsedConfig, scripts) { | ||
| const dependencies = /* @__PURE__ */ new Set([ | ||
| ...parsedConfig.before.map((v) => v.path), | ||
| ...scripts.flatMap((script) => parsedConfig.scripts[script]?.map((v) => v.path) ?? []) | ||
| ]); | ||
| const externalDependencies = [...dependencies].filter((dep) => !isLocalModulePath(dep)); | ||
| const scriptsRequirePluralized = scripts.length === 1 ? "script requires" : "scripts require"; | ||
| const installed = await installMissingDependencies( | ||
| `Your ${scriptsRequirePluralized} additional dependencies.`, | ||
| externalDependencies | ||
| ); | ||
| if (!installed) { | ||
| throw new CliError("Cannot proceed without missing dependencies."); | ||
| } | ||
| } | ||
@@ -497,9 +788,22 @@ // src/programOptions.ts | ||
| async function codama(args, opts) { | ||
| await createProgram({ | ||
| const program = createProgram({ | ||
| exitOverride: true, | ||
| suppressOutput: opts?.suppressOutput | ||
| }).parseAsync(args, { from: "user" }); | ||
| }); | ||
| await runProgram(program, args, { from: "user" }); | ||
| } | ||
| async function runProgram(program, argv, parseOptions) { | ||
| try { | ||
| await program.parseAsync(argv, parseOptions); | ||
| } catch (err) { | ||
| const error = err; | ||
| if (program.opts().debug) { | ||
| logDebug(`${error.stack}`); | ||
| } | ||
| logError(import_picocolors9.default.bold(error.message), error.items ?? []); | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| function createProgram(internalOptions) { | ||
| const program = (0, import_commander.createCommand)().version("1.2.2").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true }); | ||
| const program = (0, import_commander.createCommand)().version("1.3.0").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true }); | ||
| setProgramOptions(program); | ||
@@ -525,9 +829,4 @@ setInitCommand(program); | ||
| createProgram, | ||
| logBanner, | ||
| logDebug, | ||
| logError, | ||
| logInfo, | ||
| logSuccess, | ||
| logWarning | ||
| runProgram | ||
| }); | ||
| //# sourceMappingURL=index.node.cjs.map |
@@ -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 .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,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,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,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,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/childCommands.ts","../src/utils/errors.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/packageInstall.ts","../src/utils/packageJson.ts","../src/utils/packageManager.ts","../src/utils/prompts.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';\n","import { Command, createCommand, ParseOptions } from 'commander';\nimport pico from 'picocolors';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\nimport { logDebug, logError } from './utils';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n const program = createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n });\n await runProgram(program, args, { from: 'user' });\n}\n\nexport async function runProgram(program: Command, argv: readonly string[], parseOptions?: ParseOptions) {\n try {\n await program.parseAsync(argv, parseOptions);\n } catch (err) {\n const error = err as { message: string; stack?: string; items?: string[] };\n if (program.opts().debug) {\n logDebug(`${error.stack}`);\n }\n logError(pico.bold(error.message), error.items ?? []);\n process.exitCode = 1;\n }\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 pico from 'picocolors';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport {\n canRead,\n CliError,\n importModuleItem,\n installMissingDependencies,\n isRootNode,\n logBanner,\n logSuccess,\n PROMPT_OPTIONS,\n resolveRelativePath,\n writeFile,\n} 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('--force', 'Overwrite existing configuration file, if any')\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 force?: boolean;\n gill?: boolean;\n js?: boolean;\n};\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n const configFileType = getConfigFileType(output, options);\n\n if (!options.force && (await canRead(output))) {\n throw new CliError(`Configuration file already exists.`, [`${pico.bold('Path')}: ${output}`]);\n }\n\n // Start prompts.\n logBanner();\n const result = await getPromptResult(options, configFileType);\n\n // Check dependencies.\n const isAnchor = await isAnchorIdl(result.idlPath);\n await installMissingDependencies(`Your configuration requires additional dependencies.`, [\n ...(isAnchor ? ['@codama/nodes-from-anchor'] : []),\n ...(result.scripts.includes('js') ? ['@codama/renderers-js'] : []),\n ...(result.scripts.includes('rust') ? ['@codama/renderers-rust'] : []),\n ]);\n\n // Write configuration file.\n const content = getContentFromPromptResult(result, configFileType);\n await writeFile(output, content);\n console.log();\n logSuccess(pico.bold('Configuration file created.'), [`${pico.bold('Path')}: ${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(\n options: Pick<InitOptions, 'default'>,\n configFileType: ConfigFileType,\n): 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 return 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 onRender() {\n if (configFileType === 'gill') {\n const value = (this as unknown as { value: prompts.Choice[] }).value;\n const jsChoice = value.find(choice => choice.value === 'js')!;\n jsChoice.description = pico.yellow('Required with --gill option.');\n jsChoice.selected = true;\n }\n },\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 PROMPT_OPTIONS,\n );\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\ntype ConfigFileType = 'gill' | 'js' | 'json';\nfunction getConfigFileType(output: string, options: Pick<InitOptions, 'gill' | 'js'>): ConfigFileType {\n if (options.gill) return 'gill';\n else if (options.js) return 'js';\n return output.endsWith('.js') ? 'js' : 'json';\n}\n\nfunction getContentFromPromptResult(result: PromptResult, configFileType: ConfigFileType): string {\n switch (configFileType) {\n case 'gill':\n return getContentForGill(result);\n case 'js':\n return (\n `export default ` +\n JSON.stringify(getConfigFromPromptResult(result), 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 case 'json':\n default:\n return JSON.stringify(getConfigFromPromptResult(result), null, 4);\n }\n}\n\nfunction getConfigFromPromptResult(result: PromptResult): Config {\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 return { idl: result.idlPath, before: [], scripts };\n}\n\nfunction getContentForGill(result: PromptResult): string {\n const attributes: string[] = [\n `idl: \"${result.idlPath}\"`,\n `clientJs: \"${result.jsPath}\"`,\n ...(result.scripts.includes('rust') ? [`clientRust: \"${result.rustPath}\"`] : []),\n ];\n const attributesString = attributes.map(attr => ` ${attr},\\n`).join('');\n\n return (\n `import { createCodamaConfig } from \"gill\";\\n\\n` +\n `export default createCodamaConfig({\\n${attributesString}});\\n`\n );\n}\n\nasync function isAnchorIdl(idlPath: string): Promise<boolean> {\n const resolvedIdlPath = resolveRelativePath(idlPath);\n if (!(await canRead(resolvedIdlPath))) return false;\n try {\n const idlContent = await importModuleItem({ identifier: 'IDL', from: resolvedIdlPath });\n return !isRootNode(idlContent);\n } catch {\n return false;\n }\n}\n","import { ChildProcess, spawn, SpawnOptions } from 'child_process';\n\nexport type ChildCommand = {\n command: string;\n args: string[];\n};\n\nexport function createChildCommand(command: string, args: string[] = []): ChildCommand {\n return { command, args };\n}\n\nexport function formatChildCommand(childCommand: ChildCommand): string {\n const { command, args } = childCommand;\n return [command, ...args].join(' ');\n}\n\nexport type ChildProcessResult = ChildProcess & {\n stdoutString: string;\n stderrString: string;\n};\n\nexport type ChildProcessError = Error & {\n childProcess: ChildProcessResult;\n};\n\nexport async function spawnChildCommand(\n childCommand: ChildCommand,\n options: SpawnOptions & { quiet: boolean } = { quiet: false },\n): Promise<ChildProcess & { stdoutString: string; stderrString: string }> {\n const { command, args } = childCommand;\n const childProcess = spawn(command, args, options) as ChildProcessResult;\n childProcess.stdoutString = '';\n childProcess.stderrString = '';\n\n childProcess.stdout?.on('data', (chunk: Uint8Array) => {\n childProcess.stdoutString += chunk.toString();\n if (!options.quiet) {\n process.stdout.write(chunk);\n }\n });\n childProcess.stderr?.on('data', (chunk: Uint8Array) => {\n childProcess.stderrString += chunk.toString();\n if (!options.quiet) {\n process.stderr.write(chunk);\n }\n });\n\n const exitCode: number = await new Promise((resolve, reject) => {\n childProcess.on('error', () => reject(createChildProcessResultError(childCommand, childProcess)));\n childProcess.on('close', resolve);\n });\n if (exitCode) {\n throw createChildProcessResultError(childCommand, childProcess);\n }\n\n return childProcess;\n}\n\nfunction createChildProcessResultError(\n childCommand: ChildCommand,\n childProcess: ChildProcessResult,\n): ChildProcessError {\n const error = new Error(`Command [${formatChildCommand(childCommand)}] failed`) as ChildProcessError;\n error.childProcess = childProcess;\n return error;\n}\n","export class CliError extends Error {\n constructor(\n message: string,\n public items: string[] = [],\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'CliError';\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 readJson<T>(filePath: string): Promise<T> {\n return JSON.parse(await readFile(filePath)) as T;\n}\n\nexport async function readFile(filePath: string): Promise<string> {\n return await fs.promises.readFile(filePath, 'utf8');\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 pico from 'picocolors';\n\nimport { CliError } from './errors';\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\ntype ImportModuleItemOptions = {\n from: string;\n identifier?: string;\n item?: string;\n};\n\nexport async function importModuleItem<T = unknown>(options: ImportModuleItemOptions): Promise<T> {\n const module = await importModule(options);\n const moduleItem = pickModuleItem(module, options.item) as T | undefined;\n if (moduleItem === undefined) {\n const items = getErrorItems(options);\n throw new CliError(`Failed to load ${options.identifier ?? 'module'}.`, items);\n }\n return moduleItem;\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, item: string = 'default'): unknown {\n if (item === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[item] ?? module.default?.[item] ?? module.default?.default?.[item];\n}\n\nasync function importModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n if (isLocalModulePath(options.from)) {\n return await importLocalModule(options);\n }\n\n try {\n return await importExternalUserModule(options);\n } catch {\n return await importExternalModule(options);\n }\n}\n\nasync function importLocalModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n const { from, identifier } = options;\n if (!(await canRead(from))) {\n const items = getErrorItems(options);\n throw new CliError(`Cannot access ${identifier ?? 'module'}.`, items);\n }\n\n const dotIndex = from.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : from.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(from, { with: { type: 'json' } }) : import(from);\n return await handleImportPromise(modulePromise, options);\n}\n\nasync function importExternalModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n return await handleImportPromise(import(options.from), options);\n}\n\nasync function importExternalUserModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userFrom = userRequire.resolve(options.from);\n return await importExternalModule<T>({ ...options, from: userFrom });\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n options: ImportModuleItemOptions,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (cause) {\n const items = getErrorItems(options, cause);\n throw new CliError(`Failed to load ${options.identifier ?? 'module'}.`, items, { cause });\n }\n}\n\nfunction getErrorItems(options: ImportModuleItemOptions, cause?: unknown): string[] {\n const { from, item } = options;\n const items = [`${pico.bold('Module')}: ${from}`];\n if (item) {\n items.push(`${pico.bold('Item')}: ${item}`);\n }\n\n const hasCause = !!cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string';\n if (hasCause) {\n items.push(`${pico.bold('Caused by')}: ${(cause as { message: string }).message}`);\n }\n\n return items;\n}\n","import pico from 'picocolors';\n\ntype LogLevel = 'debug' | 'error' | 'info' | 'success' | 'warning';\n\ntype LogOptions = {\n level: LogLevel;\n message: string;\n items?: string[];\n};\n\nfunction getLogLevelInfo(logLevel: LogLevel) {\n const identity = (text: string) => text;\n const infos: Record<LogLevel, [string, (text: string) => string, (text: string) => string]> = {\n success: ['✔', pico.green, pico.green],\n info: ['→', pico.blueBright, identity],\n warning: ['▲', pico.yellow, pico.yellow],\n error: ['✖', pico.red, pico.red],\n debug: ['✱', pico.magenta, pico.magenta],\n };\n\n return {\n icon: infos[logLevel][0],\n color: infos[logLevel][1],\n messageColor: infos[logLevel][2],\n };\n}\n\nconst logWrapper = (level: LogLevel) => (message: string, items?: string[]) => log({ level, message, items });\nexport const logSuccess = logWrapper('success');\nexport const logError = logWrapper('error');\nexport const logInfo = logWrapper('info');\nexport const logWarning = logWrapper('warning');\nexport const logDebug = logWrapper('debug');\n\nfunction log({ level, message, items }: LogOptions): void {\n const { icon, color, messageColor } = getLogLevelInfo(level);\n console.log(color(icon), messageColor(message));\n if (items) {\n logItems(items, color);\n }\n}\n\nfunction logItems(items: string[], color?: (text: string) => string): void {\n const colorFn = color ?? (text => text);\n items.forEach((item, index) => {\n const prefix = index === items.length - 1 ? '└─' : '├─';\n console.log(' ' + colorFn(prefix), item);\n });\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 pico from 'picocolors';\nimport prompts from 'prompts';\n\nimport { ChildCommand, createChildCommand, formatChildCommand, spawnChildCommand } from './childCommands';\nimport { logError, logInfo, logSuccess, logWarning } from './logs';\nimport { getPackageJsonDependencies } from './packageJson';\nimport { getPackageManager } from './packageManager';\nimport { PROMPT_OPTIONS } from './prompts';\n\nexport async function getPackageManagerInstallCommand(\n packages: string[],\n options: string[] = [],\n): Promise<ChildCommand> {\n const packageManager = await getPackageManager();\n const args = [packageManager === 'yarn' ? 'add' : 'install', ...packages, ...options];\n return createChildCommand(packageManager, args);\n}\n\nexport async function installMissingDependencies(message: string, requiredDependencies: string[]): Promise<boolean> {\n if (requiredDependencies.length === 0) return true;\n\n const installedDependencies = await getPackageJsonDependencies({ includeDev: true });\n const missingDependencies = requiredDependencies.filter(dep => !installedDependencies.includes(dep));\n if (missingDependencies.length === 0) return true;\n\n return await installDependencies(message, missingDependencies);\n}\n\nexport async function installDependencies(message: string, dependencies: string[]): Promise<boolean> {\n if (dependencies.length === 0) return true;\n const installCommand = await getPackageManagerInstallCommand(dependencies);\n const formattedInstallCommand = pico.yellow(formatChildCommand(installCommand));\n\n if (process.env.CI) {\n logWarning(message);\n logWarning(`Skipping installation in CI environment. Please install manually:`);\n logWarning(formattedInstallCommand);\n return false;\n }\n\n logWarning(message);\n logWarning(`Install command: ${formattedInstallCommand}`);\n\n const dependencyResult: { installDependencies: boolean } = await prompts(\n { initial: true, message: 'Install dependencies?', name: 'installDependencies', type: 'confirm' },\n PROMPT_OPTIONS,\n );\n if (!dependencyResult.installDependencies) {\n logWarning('Skipping installation.');\n return false;\n }\n\n try {\n logInfo(`Installing`, dependencies);\n await spawnChildCommand(installCommand, { quiet: true });\n logSuccess(`Dependencies installed successfully.`);\n return true;\n } catch {\n logError(`Failed to install dependencies. Please try manually:`);\n logError(formattedInstallCommand);\n return false;\n }\n}\n","import pico from 'picocolors';\n\nimport { CliError } from './errors';\nimport { canRead, readJson, resolveRelativePath } from './fs';\n\ntype PackageJson = {\n name: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n scripts?: Record<string, string>;\n packageManager?: string;\n [key: string]: unknown;\n};\n\nlet packageJson: PackageJson | undefined;\nexport async function getPackageJson(): Promise<PackageJson> {\n if (!packageJson) {\n const packageJsonPath = resolveRelativePath('package.json');\n if (!(await canRead(packageJsonPath))) {\n throw new CliError('Cannot read package.json.', [`${pico.bold('Path')}: ${packageJsonPath}`]);\n }\n packageJson = await readJson<PackageJson>(packageJsonPath);\n }\n return packageJson;\n}\n\nexport async function getPackageJsonDependencies(options: { includeDev?: boolean } = {}): Promise<string[]> {\n const packageJson = await getPackageJson();\n return [\n ...(packageJson.dependencies ? Object.keys(packageJson.dependencies) : []),\n ...(options.includeDev && packageJson.devDependencies ? Object.keys(packageJson.devDependencies) : []),\n ];\n}\n","import { createChildCommand, spawnChildCommand } from './childCommands';\nimport { canRead, resolveRelativePath } from './fs';\nimport { getPackageJson } from './packageJson';\n\ntype PackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn';\n\nconst FALLBACK_PACKAGE_MANAGER: PackageManager = 'npm';\n\nlet packageManager: PackageManager | undefined;\nexport async function getPackageManager(): Promise<PackageManager> {\n if (!packageManager) {\n packageManager = await detectPackageManager();\n }\n return packageManager;\n}\n\nasync function detectPackageManager(): Promise<PackageManager> {\n const fromPackageJson = await detectPackageManagerFromPackageJson();\n if (fromPackageJson) return fromPackageJson;\n\n const fromLockfile = await detectPackageManagerFromLockfile();\n if (fromLockfile) return fromLockfile;\n\n const fromInstalledCli = await detectPackageManagerFromInstalledCli();\n if (fromInstalledCli) return fromInstalledCli;\n\n return FALLBACK_PACKAGE_MANAGER;\n}\n\nasync function detectPackageManagerFromPackageJson(): Promise<PackageManager | undefined> {\n const packageJson = await getPackageJson();\n if (!packageJson.packageManager) return undefined;\n if (packageJson.packageManager.startsWith('npm@')) return 'npm';\n if (packageJson.packageManager.startsWith('pnpm@')) return 'pnpm';\n if (packageJson.packageManager.startsWith('yarn@')) return 'yarn';\n if (packageJson.packageManager.startsWith('bun@')) return 'bun';\n return undefined;\n}\n\nasync function detectPackageManagerFromLockfile(): Promise<PackageManager | undefined> {\n const [isYarn, isPnpm, isBun, isNpm] = await Promise.all([\n canRead(resolveRelativePath('yarn.lock')),\n canRead(resolveRelativePath('pnpm-lock.yaml')),\n canRead(resolveRelativePath('bun.lockb')),\n canRead(resolveRelativePath('package-lock.json')),\n ]);\n\n if (isYarn) return 'yarn';\n if (isPnpm) return 'pnpm';\n if (isBun) return 'bun';\n if (isNpm) return 'npm';\n return undefined;\n}\n\nasync function detectPackageManagerFromInstalledCli(): Promise<PackageManager | undefined> {\n const [isPnpm, isYarn, isBun] = await Promise.all([\n hasPackageManagerCli('pnpm'),\n hasPackageManagerCli('yarn'),\n hasPackageManagerCli('bun'),\n ]);\n\n if (isPnpm) return 'pnpm';\n if (isYarn) return 'yarn';\n if (isBun) return 'bun';\n return undefined;\n}\n\nasync function hasPackageManagerCli(packageManager: PackageManager): Promise<boolean> {\n return await spawnChildCommand(createChildCommand(packageManager, ['--version']), { quiet: true })\n .then(() => true)\n .catch(() => false);\n}\n","import prompts from 'prompts';\n\nimport { CliError } from './errors';\n\nexport const PROMPT_OPTIONS: prompts.Options = {\n onCancel: () => {\n throw new CliError('Operation cancelled.');\n },\n};\n","import type { RootNode } from '@codama/nodes';\n\nimport { CliError } from './errors';\nimport { importModuleItem } from './import';\nimport { installMissingDependencies } from './packageInstall';\n\nexport async function getRootNodeFromIdl(idl: unknown): Promise<RootNode> {\n if (typeof idl !== 'object' || idl === null) {\n throw new CliError('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n\n const hasNodesFromAnchor = await installMissingDependencies(\n 'Anchor IDL detected. Additional dependencies are required to process Anchor IDLs.',\n ['@codama/nodes-from-anchor'],\n );\n if (!hasNodesFromAnchor) {\n throw new CliError('Cannot proceed without Anchor IDL support.');\n }\n\n const rootNodeFromAnchor = await importModuleItem<(idl: unknown) => RootNode>({\n from: '@codama/nodes-from-anchor',\n item: 'rootNodeFromAnchor',\n });\n return rootNodeFromAnchor(idl);\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';\nimport pico from 'picocolors';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { CliError } from './errors';\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 { item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem({ identifier, from: path, item });\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, visitorConfig);\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 visitorConfig: ParsedVisitorConfig,\n): Promise<Visitor<unknown, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\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 CliError(`Invalid visitor. Expected a visitor or a function returning a visitor.`, [\n `${pico.bold('Visitor')}: ${identifier}`,\n `${pico.bold('Path')}: ${path}`,\n ...(item ? [`${pico.bold('Item')}: ${item}`] : []),\n ]);\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, script } = visitorConfig;\n let identifier = `visitor #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\nimport pico from 'picocolors';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport {\n CliError,\n getRootNodeVisitors,\n installMissingDependencies,\n isLocalModulePath,\n logInfo,\n logSuccess,\n logWarning,\n} 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 configuration 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 CliError('There are no scripts or before visitors to run.');\n }\n\n checkMissingScripts(parsedConfig, scripts);\n await checkMissingDependencies(parsedConfig, scripts);\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\nfunction checkMissingScripts(parsedConfig: Pick<ParsedConfig, 'configPath' | 'scripts'>, scripts: ScriptName[]) {\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length === 0) return;\n\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const message = parsedConfig.configPath\n ? `${scriptPluralized} not found in configuration file.`\n : `${scriptPluralized} not found because no configuration file was found.`;\n const items = [\n `${pico.bold(scriptPluralized)}: ${missingScripts.join(', ')}`,\n ...(parsedConfig.configPath ? [`${pico.bold('Path')}: ${parsedConfig.configPath}`] : []),\n ];\n throw new CliError(message, items);\n}\n\nasync function checkMissingDependencies(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n) {\n const dependencies = new Set<string>([\n ...parsedConfig.before.map(v => v.path),\n ...scripts.flatMap(script => parsedConfig.scripts[script]?.map(v => v.path) ?? []),\n ]);\n const externalDependencies = [...dependencies].filter(dep => !isLocalModulePath(dep));\n const scriptsRequirePluralized = scripts.length === 1 ? 'script requires' : 'scripts require';\n const installed = await installMissingDependencies(\n `Your ${scriptsRequirePluralized} additional dependencies.`,\n externalDependencies,\n );\n if (!installed) {\n throw new CliError('Cannot proceed without missing dependencies.');\n }\n}\n","import path from 'node:path';\n\nimport pico from 'picocolors';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, CliError, 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 configuration file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem({ identifier: 'configuration file', from: configPath });\n if (!configFile || typeof configFile !== 'object') {\n throw new CliError(`Invalid configuration file.`, [`${pico.bold('Path')}: ${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 CliError,\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());\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({ identifier: 'IDL', from: idlPath });\n const rootNode = await 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 CliError('No IDL identified. Please provide the `--idl` option or set it in the configuration 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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cAAc;AAAA,IAC1B,cAAc;AAAA,IACd,gBAAgB,MAAM;AAAA,EAC1B,CAAC;AACD,QAAM,WAAW,SAAS,MAAM,EAAE,MAAM,OAAO,CAAC;AACpD;AAEA,eAAsB,WAAW,SAAkB,MAAyB,cAA6B;AACrG,MAAI;AACA,UAAM,QAAQ,WAAW,MAAM,YAAY;AAAA,EAC/C,SAAS,KAAK;AACV,UAAM,QAAQ;AACd,QAAI,QAAQ,KAAK,EAAE,OAAO;AACtB,eAAS,GAAG,MAAM,KAAK,EAAE;AAAA,IAC7B;AACA,aAAS,mBAAAC,QAAK,KAAK,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,CAAC;AACpD,YAAQ,WAAW;AAAA,EACvB;AACJ;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":["import_picocolors","import_picocolors","import_prompts","path","fs","module","pico","import_picocolors","pico","import_picocolors","import_picocolors","pico","packageJson","packageJson","packageManager","packageManager","pico","prompts","import_picocolors","path","pico","pico","prompts","import_visitors_core","import_picocolors","import_node_path","import_picocolors","path","pico","path","pico","pico"]} |
+416
-112
| // src/program.ts | ||
| import { createCommand } from "commander"; | ||
| import pico9 from "picocolors"; | ||
| // src/commands/init.ts | ||
| import prompts from "prompts"; | ||
| import pico6 from "picocolors"; | ||
| import prompts2 from "prompts"; | ||
| // src/utils/childCommands.ts | ||
| import { spawn } from "child_process"; | ||
| function createChildCommand(command, args = []) { | ||
| return { command, args }; | ||
| } | ||
| function formatChildCommand(childCommand) { | ||
| const { command, args } = childCommand; | ||
| return [command, ...args].join(" "); | ||
| } | ||
| async function spawnChildCommand(childCommand, options = { quiet: false }) { | ||
| const { command, args } = childCommand; | ||
| const childProcess = spawn(command, args, options); | ||
| childProcess.stdoutString = ""; | ||
| childProcess.stderrString = ""; | ||
| childProcess.stdout?.on("data", (chunk) => { | ||
| childProcess.stdoutString += chunk.toString(); | ||
| if (!options.quiet) { | ||
| process.stdout.write(chunk); | ||
| } | ||
| }); | ||
| childProcess.stderr?.on("data", (chunk) => { | ||
| childProcess.stderrString += chunk.toString(); | ||
| if (!options.quiet) { | ||
| process.stderr.write(chunk); | ||
| } | ||
| }); | ||
| const exitCode = await new Promise((resolve, reject) => { | ||
| childProcess.on("error", () => reject(createChildProcessResultError(childCommand, childProcess))); | ||
| childProcess.on("close", resolve); | ||
| }); | ||
| if (exitCode) { | ||
| throw createChildProcessResultError(childCommand, childProcess); | ||
| } | ||
| return childProcess; | ||
| } | ||
| function createChildProcessResultError(childCommand, childProcess) { | ||
| const error = new Error(`Command [${formatChildCommand(childCommand)}] failed`); | ||
| error.childProcess = childProcess; | ||
| return error; | ||
| } | ||
| // src/utils/errors.ts | ||
| var CliError = class extends Error { | ||
| constructor(message, items = [], options) { | ||
| super(message, options); | ||
| this.items = items; | ||
| this.name = "CliError"; | ||
| } | ||
| }; | ||
| // src/utils/fs.ts | ||
@@ -21,2 +73,8 @@ import { R_OK, W_OK } from "constants"; | ||
| } | ||
| async function readJson(filePath) { | ||
| return JSON.parse(await readFile(filePath)); | ||
| } | ||
| async function readFile(filePath) { | ||
| return await fs.promises.readFile(filePath, "utf8"); | ||
| } | ||
| async function writeFile(filePath, content) { | ||
@@ -48,73 +106,106 @@ const directory = path.dirname(filePath); | ||
| import { createRequire } from "module"; | ||
| async function importModuleItem(identifier, modulePath, itemName = "default") { | ||
| const module = await importModule(identifier, modulePath); | ||
| const item = pickModuleItem(module, itemName); | ||
| if (item === void 0) { | ||
| throw new Error(`Failed to import "${itemName}" from ${identifier} at "${modulePath}".`); | ||
| import pico from "picocolors"; | ||
| async function importModuleItem(options) { | ||
| const module = await importModule(options); | ||
| const moduleItem = pickModuleItem(module, options.item); | ||
| if (moduleItem === void 0) { | ||
| const items = getErrorItems(options); | ||
| throw new CliError(`Failed to load ${options.identifier ?? "module"}.`, items); | ||
| } | ||
| return item; | ||
| return moduleItem; | ||
| } | ||
| function pickModuleItem(module, itemName) { | ||
| if (itemName === "default") { | ||
| function pickModuleItem(module, item = "default") { | ||
| if (item === "default") { | ||
| return module.default?.default ?? module.default ?? module; | ||
| } | ||
| return module[itemName] ?? module.default?.[itemName] ?? module.default?.default?.[itemName]; | ||
| return module[item] ?? module.default?.[item] ?? module.default?.default?.[item]; | ||
| } | ||
| async function importModule(identifier, modulePath) { | ||
| if (isLocalModulePath(modulePath)) { | ||
| return await importLocalModule(identifier, modulePath); | ||
| async function importModule(options) { | ||
| if (isLocalModulePath(options.from)) { | ||
| return await importLocalModule(options); | ||
| } | ||
| try { | ||
| return await importExternalUserModule(identifier, modulePath); | ||
| return await importExternalUserModule(options); | ||
| } catch { | ||
| return await importExternalModule(identifier, modulePath); | ||
| return await importExternalModule(options); | ||
| } | ||
| } | ||
| async function importLocalModule(identifier, modulePath) { | ||
| if (!await canRead(modulePath)) { | ||
| throw new Error(`Cannot access ${identifier} at "${modulePath}"`); | ||
| async function importLocalModule(options) { | ||
| const { from, identifier } = options; | ||
| if (!await canRead(from)) { | ||
| const items = getErrorItems(options); | ||
| throw new CliError(`Cannot access ${identifier ?? "module"}.`, items); | ||
| } | ||
| const dotIndex = modulePath.lastIndexOf("."); | ||
| const extension = dotIndex === -1 ? void 0 : modulePath.slice(dotIndex); | ||
| const modulePromise = extension === ".json" ? import(modulePath, { with: { type: "json" } }) : import(modulePath); | ||
| return await handleImportPromise(modulePromise, identifier, modulePath); | ||
| const dotIndex = from.lastIndexOf("."); | ||
| const extension = dotIndex === -1 ? void 0 : from.slice(dotIndex); | ||
| const modulePromise = extension === ".json" ? import(from, { with: { type: "json" } }) : import(from); | ||
| return await handleImportPromise(modulePromise, options); | ||
| } | ||
| async function importExternalModule(identifier, modulePath) { | ||
| return await handleImportPromise(import(modulePath), identifier, modulePath); | ||
| async function importExternalModule(options) { | ||
| return await handleImportPromise(import(options.from), options); | ||
| } | ||
| async function importExternalUserModule(identifier, modulePath) { | ||
| async function importExternalUserModule(options) { | ||
| const userPackageJsonPath = resolveRelativePath("package.json"); | ||
| const userRequire = createRequire(userPackageJsonPath); | ||
| const userModulePath = userRequire.resolve(modulePath); | ||
| return await importExternalModule(identifier, userModulePath); | ||
| const userFrom = userRequire.resolve(options.from); | ||
| return await importExternalModule({ ...options, from: userFrom }); | ||
| } | ||
| async function handleImportPromise(importPromise, identifier, modulePath) { | ||
| async function handleImportPromise(importPromise, options) { | ||
| try { | ||
| return await importPromise; | ||
| } catch (error) { | ||
| let causeMessage = !!error && typeof error === "object" && "message" in error && typeof error.message === "string" ? error.message : void 0; | ||
| causeMessage = causeMessage ? ` (caused by: ${causeMessage})` : ""; | ||
| throw new Error(`Failed to import ${identifier} at "${modulePath}" as a module${causeMessage}`, { | ||
| cause: error | ||
| }); | ||
| } catch (cause) { | ||
| const items = getErrorItems(options, cause); | ||
| throw new CliError(`Failed to load ${options.identifier ?? "module"}.`, items, { cause }); | ||
| } | ||
| } | ||
| function getErrorItems(options, cause) { | ||
| const { from, item } = options; | ||
| const items = [`${pico.bold("Module")}: ${from}`]; | ||
| if (item) { | ||
| items.push(`${pico.bold("Item")}: ${item}`); | ||
| } | ||
| const hasCause = !!cause && typeof cause === "object" && "message" in cause && typeof cause.message === "string"; | ||
| if (hasCause) { | ||
| items.push(`${pico.bold("Caused by")}: ${cause.message}`); | ||
| } | ||
| return items; | ||
| } | ||
| // src/utils/logs.ts | ||
| import pico from "picocolors"; | ||
| function logSuccess(...args) { | ||
| console.log(pico.green("[Success]"), ...args); | ||
| import pico2 from "picocolors"; | ||
| function getLogLevelInfo(logLevel) { | ||
| const identity = (text) => text; | ||
| const infos = { | ||
| success: ["\u2714", pico2.green, pico2.green], | ||
| info: ["\u2192", pico2.blueBright, identity], | ||
| warning: ["\u25B2", pico2.yellow, pico2.yellow], | ||
| error: ["\u2716", pico2.red, pico2.red], | ||
| debug: ["\u2731", pico2.magenta, pico2.magenta] | ||
| }; | ||
| return { | ||
| icon: infos[logLevel][0], | ||
| color: infos[logLevel][1], | ||
| messageColor: infos[logLevel][2] | ||
| }; | ||
| } | ||
| function logInfo(...args) { | ||
| console.log(pico.blueBright("[Info]"), ...args); | ||
| var logWrapper = (level) => (message, items) => log({ level, message, items }); | ||
| var logSuccess = logWrapper("success"); | ||
| var logError = logWrapper("error"); | ||
| var logInfo = logWrapper("info"); | ||
| var logWarning = logWrapper("warning"); | ||
| var logDebug = logWrapper("debug"); | ||
| function log({ level, message, items }) { | ||
| const { icon, color, messageColor } = getLogLevelInfo(level); | ||
| console.log(color(icon), messageColor(message)); | ||
| if (items) { | ||
| logItems(items, color); | ||
| } | ||
| } | ||
| function logWarning(...args) { | ||
| console.log(pico.yellow("[Warning]"), ...args); | ||
| function logItems(items, color) { | ||
| const colorFn = color ?? ((text) => text); | ||
| items.forEach((item, index) => { | ||
| const prefix = index === items.length - 1 ? "\u2514\u2500" : "\u251C\u2500"; | ||
| console.log(" " + colorFn(prefix), item); | ||
| }); | ||
| } | ||
| function logError(...args) { | ||
| console.log(pico.red("[Error]"), ...args); | ||
| } | ||
| function logDebug(...args) { | ||
| console.log(pico.magenta("[Debug]"), ...args); | ||
| } | ||
| function logBanner() { | ||
@@ -125,11 +216,142 @@ console.log(getBanner()); | ||
| const textBanner = "Welcome to Codama!"; | ||
| const gradientBanner = pico.bold(`\x1B[38;2;231;171;97m${textBanner}\x1B[0m`); | ||
| const gradientBanner = pico2.bold(`\x1B[38;2;231;171;97m${textBanner}\x1B[0m`); | ||
| return process.stdout.isTTY && process.stdout.getColorDepth() > 8 ? gradientBanner : textBanner; | ||
| } | ||
| // src/utils/packageInstall.ts | ||
| import pico4 from "picocolors"; | ||
| import prompts from "prompts"; | ||
| // src/utils/packageJson.ts | ||
| import pico3 from "picocolors"; | ||
| var packageJson; | ||
| async function getPackageJson() { | ||
| if (!packageJson) { | ||
| const packageJsonPath = resolveRelativePath("package.json"); | ||
| if (!await canRead(packageJsonPath)) { | ||
| throw new CliError("Cannot read package.json.", [`${pico3.bold("Path")}: ${packageJsonPath}`]); | ||
| } | ||
| packageJson = await readJson(packageJsonPath); | ||
| } | ||
| return packageJson; | ||
| } | ||
| async function getPackageJsonDependencies(options = {}) { | ||
| const packageJson2 = await getPackageJson(); | ||
| return [ | ||
| ...packageJson2.dependencies ? Object.keys(packageJson2.dependencies) : [], | ||
| ...options.includeDev && packageJson2.devDependencies ? Object.keys(packageJson2.devDependencies) : [] | ||
| ]; | ||
| } | ||
| // src/utils/packageManager.ts | ||
| var FALLBACK_PACKAGE_MANAGER = "npm"; | ||
| var packageManager; | ||
| async function getPackageManager() { | ||
| if (!packageManager) { | ||
| packageManager = await detectPackageManager(); | ||
| } | ||
| return packageManager; | ||
| } | ||
| async function detectPackageManager() { | ||
| const fromPackageJson = await detectPackageManagerFromPackageJson(); | ||
| if (fromPackageJson) return fromPackageJson; | ||
| const fromLockfile = await detectPackageManagerFromLockfile(); | ||
| if (fromLockfile) return fromLockfile; | ||
| const fromInstalledCli = await detectPackageManagerFromInstalledCli(); | ||
| if (fromInstalledCli) return fromInstalledCli; | ||
| return FALLBACK_PACKAGE_MANAGER; | ||
| } | ||
| async function detectPackageManagerFromPackageJson() { | ||
| const packageJson2 = await getPackageJson(); | ||
| if (!packageJson2.packageManager) return void 0; | ||
| if (packageJson2.packageManager.startsWith("npm@")) return "npm"; | ||
| if (packageJson2.packageManager.startsWith("pnpm@")) return "pnpm"; | ||
| if (packageJson2.packageManager.startsWith("yarn@")) return "yarn"; | ||
| if (packageJson2.packageManager.startsWith("bun@")) return "bun"; | ||
| return void 0; | ||
| } | ||
| async function detectPackageManagerFromLockfile() { | ||
| const [isYarn, isPnpm, isBun, isNpm] = await Promise.all([ | ||
| canRead(resolveRelativePath("yarn.lock")), | ||
| canRead(resolveRelativePath("pnpm-lock.yaml")), | ||
| canRead(resolveRelativePath("bun.lockb")), | ||
| canRead(resolveRelativePath("package-lock.json")) | ||
| ]); | ||
| if (isYarn) return "yarn"; | ||
| if (isPnpm) return "pnpm"; | ||
| if (isBun) return "bun"; | ||
| if (isNpm) return "npm"; | ||
| return void 0; | ||
| } | ||
| async function detectPackageManagerFromInstalledCli() { | ||
| const [isPnpm, isYarn, isBun] = await Promise.all([ | ||
| hasPackageManagerCli("pnpm"), | ||
| hasPackageManagerCli("yarn"), | ||
| hasPackageManagerCli("bun") | ||
| ]); | ||
| if (isPnpm) return "pnpm"; | ||
| if (isYarn) return "yarn"; | ||
| if (isBun) return "bun"; | ||
| return void 0; | ||
| } | ||
| async function hasPackageManagerCli(packageManager2) { | ||
| return await spawnChildCommand(createChildCommand(packageManager2, ["--version"]), { quiet: true }).then(() => true).catch(() => false); | ||
| } | ||
| // src/utils/prompts.ts | ||
| var PROMPT_OPTIONS = { | ||
| onCancel: () => { | ||
| throw new CliError("Operation cancelled."); | ||
| } | ||
| }; | ||
| // src/utils/packageInstall.ts | ||
| async function getPackageManagerInstallCommand(packages, options = []) { | ||
| const packageManager2 = await getPackageManager(); | ||
| const args = [packageManager2 === "yarn" ? "add" : "install", ...packages, ...options]; | ||
| return createChildCommand(packageManager2, args); | ||
| } | ||
| async function installMissingDependencies(message, requiredDependencies) { | ||
| if (requiredDependencies.length === 0) return true; | ||
| const installedDependencies = await getPackageJsonDependencies({ includeDev: true }); | ||
| const missingDependencies = requiredDependencies.filter((dep) => !installedDependencies.includes(dep)); | ||
| if (missingDependencies.length === 0) return true; | ||
| return await installDependencies(message, missingDependencies); | ||
| } | ||
| async function installDependencies(message, dependencies) { | ||
| if (dependencies.length === 0) return true; | ||
| const installCommand = await getPackageManagerInstallCommand(dependencies); | ||
| const formattedInstallCommand = pico4.yellow(formatChildCommand(installCommand)); | ||
| if (process.env.CI) { | ||
| logWarning(message); | ||
| logWarning(`Skipping installation in CI environment. Please install manually:`); | ||
| logWarning(formattedInstallCommand); | ||
| return false; | ||
| } | ||
| logWarning(message); | ||
| logWarning(`Install command: ${formattedInstallCommand}`); | ||
| const dependencyResult = await prompts( | ||
| { initial: true, message: "Install dependencies?", name: "installDependencies", type: "confirm" }, | ||
| PROMPT_OPTIONS | ||
| ); | ||
| if (!dependencyResult.installDependencies) { | ||
| logWarning("Skipping installation."); | ||
| return false; | ||
| } | ||
| try { | ||
| logInfo(`Installing`, dependencies); | ||
| await spawnChildCommand(installCommand, { quiet: true }); | ||
| logSuccess(`Dependencies installed successfully.`); | ||
| return true; | ||
| } catch { | ||
| logError(`Failed to install dependencies. Please try manually:`); | ||
| logError(formattedInstallCommand); | ||
| return false; | ||
| } | ||
| } | ||
| // src/utils/nodes.ts | ||
| import { rootNodeFromAnchor } from "@codama/nodes-from-anchor"; | ||
| function getRootNodeFromIdl(idl) { | ||
| async function getRootNodeFromIdl(idl) { | ||
| if (typeof idl !== "object" || idl === null) { | ||
| throw new Error("Unexpected IDL content. Expected an object, got " + typeof idl); | ||
| throw new CliError("Unexpected IDL content. Expected an object, got " + typeof idl); | ||
| } | ||
@@ -139,2 +361,13 @@ if (isRootNode(idl)) { | ||
| } | ||
| const hasNodesFromAnchor = await installMissingDependencies( | ||
| "Anchor IDL detected. Additional dependencies are required to process Anchor IDLs.", | ||
| ["@codama/nodes-from-anchor"] | ||
| ); | ||
| if (!hasNodesFromAnchor) { | ||
| throw new CliError("Cannot proceed without Anchor IDL support."); | ||
| } | ||
| const rootNodeFromAnchor = await importModuleItem({ | ||
| from: "@codama/nodes-from-anchor", | ||
| item: "rootNodeFromAnchor" | ||
| }); | ||
| return rootNodeFromAnchor(idl); | ||
@@ -153,2 +386,3 @@ } | ||
| import { rootNodeVisitor, visit } from "@codama/visitors-core"; | ||
| import pico5 from "picocolors"; | ||
| async function getRootNodeVisitors(visitors) { | ||
@@ -158,6 +392,6 @@ return await Promise.all(visitors.map(getRootNodeVisitor)); | ||
| async function getRootNodeVisitor(visitorConfig) { | ||
| const { args, item, path: path3 } = visitorConfig; | ||
| const { item, path: path3 } = visitorConfig; | ||
| const identifier = getVisitorIdentifier(visitorConfig); | ||
| const moduleItem = await importModuleItem(identifier, path3, item); | ||
| const visitor = await getVisitorFromModuleItem(identifier, moduleItem, args); | ||
| const moduleItem = await importModuleItem({ identifier, from: path3, item }); | ||
| const visitor = await getVisitorFromModuleItem(identifier, moduleItem, visitorConfig); | ||
| return rootNodeVisitor((root) => { | ||
@@ -168,3 +402,4 @@ const result = visit(root, visitor); | ||
| } | ||
| async function getVisitorFromModuleItem(identifier, moduleItem, args) { | ||
| async function getVisitorFromModuleItem(identifier, moduleItem, visitorConfig) { | ||
| const { args, item, path: path3 } = visitorConfig; | ||
| if (isRootNodeVisitor(moduleItem)) { | ||
@@ -179,3 +414,7 @@ return moduleItem; | ||
| } | ||
| throw new Error(`Invalid ${identifier}. Expected a visitor or a function returning a visitor.`); | ||
| throw new CliError(`Invalid visitor. Expected a visitor or a function returning a visitor.`, [ | ||
| `${pico5.bold("Visitor")}: ${identifier}`, | ||
| `${pico5.bold("Path")}: ${path3}`, | ||
| ...item ? [`${pico5.bold("Item")}: ${item}`] : [] | ||
| ]); | ||
| } | ||
@@ -186,7 +425,5 @@ function isRootNodeVisitor(value) { | ||
| function getVisitorIdentifier(visitorConfig) { | ||
| const { index, item, path: path3, script } = visitorConfig; | ||
| const pathWithItem = item ? `${path3}#${item}` : path3; | ||
| let identifier = `visitor of index #${index}`; | ||
| const { index, script } = visitorConfig; | ||
| let identifier = `visitor #${index}`; | ||
| identifier += script ? ` in script "${script}"` : ""; | ||
| identifier += ` (at path "${pathWithItem}")`; | ||
| return identifier; | ||
@@ -197,17 +434,22 @@ } | ||
| 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").option("--gill", "Forces the output to be a gill based 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("--force", "Overwrite existing configuration file, if any").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); | ||
| let configFileType = output.endsWith(".js") ? "js" : "json"; | ||
| if (options.gill) configFileType = "gill"; | ||
| else if (options.js) configFileType = "js"; | ||
| if (await canRead(output)) { | ||
| throw new Error(`Configuration file already exists at "${output}".`); | ||
| const configFileType = getConfigFileType(output, options); | ||
| if (!options.force && await canRead(output)) { | ||
| throw new CliError(`Configuration file already exists.`, [`${pico6.bold("Path")}: ${output}`]); | ||
| } | ||
| logBanner(); | ||
| const result = await getPromptResult(options); | ||
| const result = await getPromptResult(options, configFileType); | ||
| const isAnchor = await isAnchorIdl(result.idlPath); | ||
| await installMissingDependencies(`Your configuration requires additional dependencies.`, [ | ||
| ...isAnchor ? ["@codama/nodes-from-anchor"] : [], | ||
| ...result.scripts.includes("js") ? ["@codama/renderers-js"] : [], | ||
| ...result.scripts.includes("rust") ? ["@codama/renderers-rust"] : [] | ||
| ]); | ||
| const content = getContentFromPromptResult(result, configFileType); | ||
| await writeFile(output, content); | ||
| logSuccess(`Configuration file created at "${output}".`); | ||
| console.log(); | ||
| logSuccess(pico6.bold("Configuration file created."), [`${pico6.bold("Path")}: ${output}`]); | ||
| } | ||
@@ -220,3 +462,3 @@ function getOutputPath(explicitOutput, options) { | ||
| } | ||
| async function getPromptResult(options) { | ||
| async function getPromptResult(options, configFileType) { | ||
| const defaults = getDefaultPromptResult(); | ||
@@ -227,3 +469,3 @@ if (options.default) { | ||
| const hasScript = (script, type = "text") => (_, values) => values.scripts.includes(script) ? type : null; | ||
| const result = await prompts( | ||
| return await prompts2( | ||
| [ | ||
@@ -244,3 +486,11 @@ { | ||
| name: "scripts", | ||
| type: "multiselect" | ||
| type: "multiselect", | ||
| onRender() { | ||
| if (configFileType === "gill") { | ||
| const value = this.value; | ||
| const jsChoice = value.find((choice) => choice.value === "js"); | ||
| jsChoice.description = pico6.yellow("Required with --gill option."); | ||
| jsChoice.selected = true; | ||
| } | ||
| } | ||
| }, | ||
@@ -266,9 +516,4 @@ { | ||
| ], | ||
| { | ||
| onCancel: () => { | ||
| throw new Error("Operation cancelled."); | ||
| } | ||
| } | ||
| PROMPT_OPTIONS | ||
| ); | ||
| return result; | ||
| } | ||
@@ -284,3 +529,19 @@ function getDefaultPromptResult() { | ||
| } | ||
| function getConfigFileType(output, options) { | ||
| if (options.gill) return "gill"; | ||
| else if (options.js) return "js"; | ||
| return output.endsWith(".js") ? "js" : "json"; | ||
| } | ||
| function getContentFromPromptResult(result, configFileType) { | ||
| switch (configFileType) { | ||
| case "gill": | ||
| return getContentForGill(result); | ||
| case "js": | ||
| return `export default ` + JSON.stringify(getConfigFromPromptResult(result), null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'"); | ||
| case "json": | ||
| default: | ||
| return JSON.stringify(getConfigFromPromptResult(result), null, 4); | ||
| } | ||
| } | ||
| function getConfigFromPromptResult(result) { | ||
| const scripts = {}; | ||
@@ -299,15 +560,27 @@ if (result.scripts.includes("js")) { | ||
| } | ||
| const content = { idl: result.idlPath, before: [], scripts }; | ||
| if (configFileType == "json") { | ||
| return JSON.stringify(content, null, 4); | ||
| } else if (configFileType == "gill") { | ||
| return `import { createCodamaConfig } from "gill"; | ||
| return { idl: result.idlPath, before: [], scripts }; | ||
| } | ||
| function getContentForGill(result) { | ||
| const attributes = [ | ||
| `idl: "${result.idlPath}"`, | ||
| `clientJs: "${result.jsPath}"`, | ||
| ...result.scripts.includes("rust") ? [`clientRust: "${result.rustPath}"`] : [] | ||
| ]; | ||
| const attributesString = attributes.map((attr) => ` ${attr}, | ||
| `).join(""); | ||
| return `import { createCodamaConfig } from "gill"; | ||
| export default createCodamaConfig({ | ||
| idl: "${result.idlPath}", | ||
| clientJs: "${result.jsPath}", | ||
| ` + result.scripts.includes("rust") ? `clientRust: "${result.rustPath}", | ||
| ` : `});`; | ||
| export default createCodamaConfig({ | ||
| ${attributesString}}); | ||
| `; | ||
| } | ||
| async function isAnchorIdl(idlPath) { | ||
| const resolvedIdlPath = resolveRelativePath(idlPath); | ||
| if (!await canRead(resolvedIdlPath)) return false; | ||
| try { | ||
| const idlContent = await importModuleItem({ identifier: "IDL", from: resolvedIdlPath }); | ||
| return !isRootNode(idlContent); | ||
| } catch { | ||
| return false; | ||
| } | ||
| return "export default " + JSON.stringify(content, null, 4).replace(/"([^"]+)":/g, "$1:").replace(/"([^"]*)"/g, "'$1'"); | ||
| } | ||
@@ -317,14 +590,16 @@ | ||
| import { visit as visit2 } from "@codama/visitors-core"; | ||
| import pico8 from "picocolors"; | ||
| // src/config.ts | ||
| import path2 from "path"; | ||
| import pico7 from "picocolors"; | ||
| async function getConfig(options) { | ||
| const configPath = options.config != null ? path2.resolve(options.config) : await getDefaultConfigPath(); | ||
| if (!configPath) { | ||
| logWarning("No config file found. Using empty configs. Make sure you provide the `--idl` option."); | ||
| logWarning("No configuration file found. Using empty configs. Make sure you provide the `--idl` option."); | ||
| return [{}, configPath]; | ||
| } | ||
| const configFile = await importModuleItem("config file", configPath); | ||
| const configFile = await importModuleItem({ identifier: "configuration file", from: configPath }); | ||
| if (!configFile || typeof configFile !== "object") { | ||
| throw new Error(`Invalid config file at "${configPath}"`); | ||
| throw new CliError(`Invalid configuration file.`, [`${pico7.bold("Path")}: ${configPath}`]); | ||
| } | ||
@@ -354,4 +629,4 @@ return [configFile, configPath]; | ||
| const idlPath = parseIdlPath(config, configPath, options); | ||
| const idlContent = await importModuleItem("IDL", idlPath); | ||
| const rootNode = getRootNodeFromIdl(idlContent); | ||
| const idlContent = await importModuleItem({ identifier: "IDL", from: idlPath }); | ||
| const rootNode = await getRootNodeFromIdl(idlContent); | ||
| const scripts = parseScripts(config.scripts ?? {}, configPath); | ||
@@ -368,3 +643,3 @@ const visitors = (config.before ?? []).map((v, i) => parseVisitorConfig(v, configPath, i, null)); | ||
| } | ||
| throw new Error("No IDL identified. Please provide the `--idl` option or set it in the config file."); | ||
| throw new CliError("No IDL identified. Please provide the `--idl` option or set it in the configuration file."); | ||
| } | ||
@@ -393,3 +668,3 @@ function parseScripts(scripts, configPath) { | ||
| function setRunCommand(program) { | ||
| program.command("run").argument("[scripts...]", "The scripts to execute").option("-a, --all", "Run all scripts in the config file").action(doRun); | ||
| program.command("run").argument("[scripts...]", "The scripts to execute").option("-a, --all", "Run all scripts in the configuration file").action(doRun); | ||
| } | ||
@@ -408,11 +683,6 @@ async function doRun(explicitScripts, { all }, cmd) { | ||
| if (scripts.length === 0 && parsedConfig.before.length === 0) { | ||
| throw new Error("There are no scripts or before visitors to run."); | ||
| throw new CliError("There are no scripts or before visitors to run."); | ||
| } | ||
| const missingScripts = scripts.filter((script) => !parsedConfig.scripts[script]); | ||
| if (missingScripts.length > 0) { | ||
| const scriptPluralized = missingScripts.length === 1 ? "Script" : "Scripts"; | ||
| const missingScriptsIdentifier = `${scriptPluralized} "${missingScripts.join(", ")}"`; | ||
| const message = parsedConfig.configPath ? `${missingScriptsIdentifier} not found in config file "${parsedConfig.configPath}"` : `${missingScriptsIdentifier} not found because no config file was found`; | ||
| throw new Error(message); | ||
| } | ||
| checkMissingScripts(parsedConfig, scripts); | ||
| await checkMissingDependencies(parsedConfig, scripts); | ||
| if (parsedConfig.before.length > 0) { | ||
@@ -443,2 +713,28 @@ plans.push({ script: null, visitors: await getRootNodeVisitors(parsedConfig.before) }); | ||
| } | ||
| function checkMissingScripts(parsedConfig, scripts) { | ||
| const missingScripts = scripts.filter((script) => !parsedConfig.scripts[script]); | ||
| if (missingScripts.length === 0) return; | ||
| const scriptPluralized = missingScripts.length === 1 ? "Script" : "Scripts"; | ||
| const message = parsedConfig.configPath ? `${scriptPluralized} not found in configuration file.` : `${scriptPluralized} not found because no configuration file was found.`; | ||
| const items = [ | ||
| `${pico8.bold(scriptPluralized)}: ${missingScripts.join(", ")}`, | ||
| ...parsedConfig.configPath ? [`${pico8.bold("Path")}: ${parsedConfig.configPath}`] : [] | ||
| ]; | ||
| throw new CliError(message, items); | ||
| } | ||
| async function checkMissingDependencies(parsedConfig, scripts) { | ||
| const dependencies = /* @__PURE__ */ new Set([ | ||
| ...parsedConfig.before.map((v) => v.path), | ||
| ...scripts.flatMap((script) => parsedConfig.scripts[script]?.map((v) => v.path) ?? []) | ||
| ]); | ||
| const externalDependencies = [...dependencies].filter((dep) => !isLocalModulePath(dep)); | ||
| const scriptsRequirePluralized = scripts.length === 1 ? "script requires" : "scripts require"; | ||
| const installed = await installMissingDependencies( | ||
| `Your ${scriptsRequirePluralized} additional dependencies.`, | ||
| externalDependencies | ||
| ); | ||
| if (!installed) { | ||
| throw new CliError("Cannot proceed without missing dependencies."); | ||
| } | ||
| } | ||
@@ -452,9 +748,22 @@ // src/programOptions.ts | ||
| async function codama(args, opts) { | ||
| await createProgram({ | ||
| const program = createProgram({ | ||
| exitOverride: true, | ||
| suppressOutput: opts?.suppressOutput | ||
| }).parseAsync(args, { from: "user" }); | ||
| }); | ||
| await runProgram(program, args, { from: "user" }); | ||
| } | ||
| async function runProgram(program, argv, parseOptions) { | ||
| try { | ||
| await program.parseAsync(argv, parseOptions); | ||
| } catch (err) { | ||
| const error = err; | ||
| if (program.opts().debug) { | ||
| logDebug(`${error.stack}`); | ||
| } | ||
| logError(pico9.bold(error.message), error.items ?? []); | ||
| process.exitCode = 1; | ||
| } | ||
| } | ||
| function createProgram(internalOptions) { | ||
| const program = createCommand().version("1.2.2").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true }); | ||
| const program = createCommand().version("1.3.0").allowExcessArguments(false).configureHelp({ showGlobalOptions: true, sortOptions: true, sortSubcommands: true }); | ||
| setProgramOptions(program); | ||
@@ -479,9 +788,4 @@ setInitCommand(program); | ||
| createProgram, | ||
| logBanner, | ||
| logDebug, | ||
| logError, | ||
| logInfo, | ||
| logSuccess, | ||
| logWarning | ||
| runProgram | ||
| }; | ||
| //# sourceMappingURL=index.node.mjs.map |
@@ -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 .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;AAClE;AAEA,eAAsB,UAAU,UAAkB,SAAiB;AAC/D,QAAM,YAAY,KAAK,QAAQ,QAAQ;AACvC,MAAI,CAAE,MAAM,SAAS,SAAS,GAAI;AAC9B,UAAM,GAAG,SAAS,MAAM,WAAW,EAAE,WAAW,KAAK,CAAC;AAAA,EAC1D;AACA,QAAM,GAAG,SAAS,UAAU,UAAU,OAAO;AACjD;AAEA,eAAsB,QAAQ,GAAa;AACvC,MAAI;AACA,UAAM,GAAG,SAAS,OAAO,GAAG,IAAI;AAChC,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;AAEA,eAAsB,SAAS,GAAa;AACxC,MAAI;AACA,UAAM,GAAG,SAAS,OAAO,GAAG,IAAI;AAChC,WAAO;AAAA,EACX,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;;;ACzCA,SAAS,qBAAqB;AAI9B,eAAsB,iBAClB,YACA,YACA,WAAmB,WACT;AACV,QAAM,SAAS,MAAM,aAAa,YAAY,UAAU;AACxD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AAQ,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/childCommands.ts","../src/utils/errors.ts","../src/utils/fs.ts","../src/utils/import.ts","../src/utils/logs.ts","../src/utils/packageInstall.ts","../src/utils/packageJson.ts","../src/utils/packageManager.ts","../src/utils/prompts.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, ParseOptions } from 'commander';\nimport pico from 'picocolors';\n\nimport { setInitCommand, setRunCommand } from './commands';\nimport { setProgramOptions } from './programOptions';\nimport { logDebug, logError } from './utils';\n\nexport async function codama(args: string[], opts?: { suppressOutput?: boolean }): Promise<void> {\n const program = createProgram({\n exitOverride: true,\n suppressOutput: opts?.suppressOutput,\n });\n await runProgram(program, args, { from: 'user' });\n}\n\nexport async function runProgram(program: Command, argv: readonly string[], parseOptions?: ParseOptions) {\n try {\n await program.parseAsync(argv, parseOptions);\n } catch (err) {\n const error = err as { message: string; stack?: string; items?: string[] };\n if (program.opts().debug) {\n logDebug(`${error.stack}`);\n }\n logError(pico.bold(error.message), error.items ?? []);\n process.exitCode = 1;\n }\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 pico from 'picocolors';\nimport prompts, { PromptType } from 'prompts';\n\nimport { Config, ScriptConfig, ScriptName } from '../config';\nimport {\n canRead,\n CliError,\n importModuleItem,\n installMissingDependencies,\n isRootNode,\n logBanner,\n logSuccess,\n PROMPT_OPTIONS,\n resolveRelativePath,\n writeFile,\n} 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('--force', 'Overwrite existing configuration file, if any')\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 force?: boolean;\n gill?: boolean;\n js?: boolean;\n};\n\nasync function doInit(explicitOutput: string | undefined, options: InitOptions) {\n const output = getOutputPath(explicitOutput, options);\n const configFileType = getConfigFileType(output, options);\n\n if (!options.force && (await canRead(output))) {\n throw new CliError(`Configuration file already exists.`, [`${pico.bold('Path')}: ${output}`]);\n }\n\n // Start prompts.\n logBanner();\n const result = await getPromptResult(options, configFileType);\n\n // Check dependencies.\n const isAnchor = await isAnchorIdl(result.idlPath);\n await installMissingDependencies(`Your configuration requires additional dependencies.`, [\n ...(isAnchor ? ['@codama/nodes-from-anchor'] : []),\n ...(result.scripts.includes('js') ? ['@codama/renderers-js'] : []),\n ...(result.scripts.includes('rust') ? ['@codama/renderers-rust'] : []),\n ]);\n\n // Write configuration file.\n const content = getContentFromPromptResult(result, configFileType);\n await writeFile(output, content);\n console.log();\n logSuccess(pico.bold('Configuration file created.'), [`${pico.bold('Path')}: ${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(\n options: Pick<InitOptions, 'default'>,\n configFileType: ConfigFileType,\n): 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 return 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 onRender() {\n if (configFileType === 'gill') {\n const value = (this as unknown as { value: prompts.Choice[] }).value;\n const jsChoice = value.find(choice => choice.value === 'js')!;\n jsChoice.description = pico.yellow('Required with --gill option.');\n jsChoice.selected = true;\n }\n },\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 PROMPT_OPTIONS,\n );\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\ntype ConfigFileType = 'gill' | 'js' | 'json';\nfunction getConfigFileType(output: string, options: Pick<InitOptions, 'gill' | 'js'>): ConfigFileType {\n if (options.gill) return 'gill';\n else if (options.js) return 'js';\n return output.endsWith('.js') ? 'js' : 'json';\n}\n\nfunction getContentFromPromptResult(result: PromptResult, configFileType: ConfigFileType): string {\n switch (configFileType) {\n case 'gill':\n return getContentForGill(result);\n case 'js':\n return (\n `export default ` +\n JSON.stringify(getConfigFromPromptResult(result), 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 case 'json':\n default:\n return JSON.stringify(getConfigFromPromptResult(result), null, 4);\n }\n}\n\nfunction getConfigFromPromptResult(result: PromptResult): Config {\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 return { idl: result.idlPath, before: [], scripts };\n}\n\nfunction getContentForGill(result: PromptResult): string {\n const attributes: string[] = [\n `idl: \"${result.idlPath}\"`,\n `clientJs: \"${result.jsPath}\"`,\n ...(result.scripts.includes('rust') ? [`clientRust: \"${result.rustPath}\"`] : []),\n ];\n const attributesString = attributes.map(attr => ` ${attr},\\n`).join('');\n\n return (\n `import { createCodamaConfig } from \"gill\";\\n\\n` +\n `export default createCodamaConfig({\\n${attributesString}});\\n`\n );\n}\n\nasync function isAnchorIdl(idlPath: string): Promise<boolean> {\n const resolvedIdlPath = resolveRelativePath(idlPath);\n if (!(await canRead(resolvedIdlPath))) return false;\n try {\n const idlContent = await importModuleItem({ identifier: 'IDL', from: resolvedIdlPath });\n return !isRootNode(idlContent);\n } catch {\n return false;\n }\n}\n","import { ChildProcess, spawn, SpawnOptions } from 'child_process';\n\nexport type ChildCommand = {\n command: string;\n args: string[];\n};\n\nexport function createChildCommand(command: string, args: string[] = []): ChildCommand {\n return { command, args };\n}\n\nexport function formatChildCommand(childCommand: ChildCommand): string {\n const { command, args } = childCommand;\n return [command, ...args].join(' ');\n}\n\nexport type ChildProcessResult = ChildProcess & {\n stdoutString: string;\n stderrString: string;\n};\n\nexport type ChildProcessError = Error & {\n childProcess: ChildProcessResult;\n};\n\nexport async function spawnChildCommand(\n childCommand: ChildCommand,\n options: SpawnOptions & { quiet: boolean } = { quiet: false },\n): Promise<ChildProcess & { stdoutString: string; stderrString: string }> {\n const { command, args } = childCommand;\n const childProcess = spawn(command, args, options) as ChildProcessResult;\n childProcess.stdoutString = '';\n childProcess.stderrString = '';\n\n childProcess.stdout?.on('data', (chunk: Uint8Array) => {\n childProcess.stdoutString += chunk.toString();\n if (!options.quiet) {\n process.stdout.write(chunk);\n }\n });\n childProcess.stderr?.on('data', (chunk: Uint8Array) => {\n childProcess.stderrString += chunk.toString();\n if (!options.quiet) {\n process.stderr.write(chunk);\n }\n });\n\n const exitCode: number = await new Promise((resolve, reject) => {\n childProcess.on('error', () => reject(createChildProcessResultError(childCommand, childProcess)));\n childProcess.on('close', resolve);\n });\n if (exitCode) {\n throw createChildProcessResultError(childCommand, childProcess);\n }\n\n return childProcess;\n}\n\nfunction createChildProcessResultError(\n childCommand: ChildCommand,\n childProcess: ChildProcessResult,\n): ChildProcessError {\n const error = new Error(`Command [${formatChildCommand(childCommand)}] failed`) as ChildProcessError;\n error.childProcess = childProcess;\n return error;\n}\n","export class CliError extends Error {\n constructor(\n message: string,\n public items: string[] = [],\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'CliError';\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 readJson<T>(filePath: string): Promise<T> {\n return JSON.parse(await readFile(filePath)) as T;\n}\n\nexport async function readFile(filePath: string): Promise<string> {\n return await fs.promises.readFile(filePath, 'utf8');\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 pico from 'picocolors';\n\nimport { CliError } from './errors';\nimport { canRead, isLocalModulePath, resolveRelativePath } from './fs';\n\ntype ImportModuleItemOptions = {\n from: string;\n identifier?: string;\n item?: string;\n};\n\nexport async function importModuleItem<T = unknown>(options: ImportModuleItemOptions): Promise<T> {\n const module = await importModule(options);\n const moduleItem = pickModuleItem(module, options.item) as T | undefined;\n if (moduleItem === undefined) {\n const items = getErrorItems(options);\n throw new CliError(`Failed to load ${options.identifier ?? 'module'}.`, items);\n }\n return moduleItem;\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, item: string = 'default'): unknown {\n if (item === 'default') {\n return module.default?.default ?? module.default ?? module;\n }\n return module[item] ?? module.default?.[item] ?? module.default?.default?.[item];\n}\n\nasync function importModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n if (isLocalModulePath(options.from)) {\n return await importLocalModule(options);\n }\n\n try {\n return await importExternalUserModule(options);\n } catch {\n return await importExternalModule(options);\n }\n}\n\nasync function importLocalModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n const { from, identifier } = options;\n if (!(await canRead(from))) {\n const items = getErrorItems(options);\n throw new CliError(`Cannot access ${identifier ?? 'module'}.`, items);\n }\n\n const dotIndex = from.lastIndexOf('.');\n const extension = dotIndex === -1 ? undefined : from.slice(dotIndex);\n const modulePromise = extension === '.json' ? import(from, { with: { type: 'json' } }) : import(from);\n return await handleImportPromise(modulePromise, options);\n}\n\nasync function importExternalModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n return await handleImportPromise(import(options.from), options);\n}\n\nasync function importExternalUserModule<T extends object>(options: ImportModuleItemOptions): Promise<T> {\n const userPackageJsonPath = resolveRelativePath('package.json');\n const userRequire = createRequire(userPackageJsonPath);\n const userFrom = userRequire.resolve(options.from);\n return await importExternalModule<T>({ ...options, from: userFrom });\n}\n\nasync function handleImportPromise<T extends object>(\n importPromise: Promise<unknown>,\n options: ImportModuleItemOptions,\n): Promise<T> {\n try {\n return (await importPromise) as T;\n } catch (cause) {\n const items = getErrorItems(options, cause);\n throw new CliError(`Failed to load ${options.identifier ?? 'module'}.`, items, { cause });\n }\n}\n\nfunction getErrorItems(options: ImportModuleItemOptions, cause?: unknown): string[] {\n const { from, item } = options;\n const items = [`${pico.bold('Module')}: ${from}`];\n if (item) {\n items.push(`${pico.bold('Item')}: ${item}`);\n }\n\n const hasCause = !!cause && typeof cause === 'object' && 'message' in cause && typeof cause.message === 'string';\n if (hasCause) {\n items.push(`${pico.bold('Caused by')}: ${(cause as { message: string }).message}`);\n }\n\n return items;\n}\n","import pico from 'picocolors';\n\ntype LogLevel = 'debug' | 'error' | 'info' | 'success' | 'warning';\n\ntype LogOptions = {\n level: LogLevel;\n message: string;\n items?: string[];\n};\n\nfunction getLogLevelInfo(logLevel: LogLevel) {\n const identity = (text: string) => text;\n const infos: Record<LogLevel, [string, (text: string) => string, (text: string) => string]> = {\n success: ['✔', pico.green, pico.green],\n info: ['→', pico.blueBright, identity],\n warning: ['▲', pico.yellow, pico.yellow],\n error: ['✖', pico.red, pico.red],\n debug: ['✱', pico.magenta, pico.magenta],\n };\n\n return {\n icon: infos[logLevel][0],\n color: infos[logLevel][1],\n messageColor: infos[logLevel][2],\n };\n}\n\nconst logWrapper = (level: LogLevel) => (message: string, items?: string[]) => log({ level, message, items });\nexport const logSuccess = logWrapper('success');\nexport const logError = logWrapper('error');\nexport const logInfo = logWrapper('info');\nexport const logWarning = logWrapper('warning');\nexport const logDebug = logWrapper('debug');\n\nfunction log({ level, message, items }: LogOptions): void {\n const { icon, color, messageColor } = getLogLevelInfo(level);\n console.log(color(icon), messageColor(message));\n if (items) {\n logItems(items, color);\n }\n}\n\nfunction logItems(items: string[], color?: (text: string) => string): void {\n const colorFn = color ?? (text => text);\n items.forEach((item, index) => {\n const prefix = index === items.length - 1 ? '└─' : '├─';\n console.log(' ' + colorFn(prefix), item);\n });\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 pico from 'picocolors';\nimport prompts from 'prompts';\n\nimport { ChildCommand, createChildCommand, formatChildCommand, spawnChildCommand } from './childCommands';\nimport { logError, logInfo, logSuccess, logWarning } from './logs';\nimport { getPackageJsonDependencies } from './packageJson';\nimport { getPackageManager } from './packageManager';\nimport { PROMPT_OPTIONS } from './prompts';\n\nexport async function getPackageManagerInstallCommand(\n packages: string[],\n options: string[] = [],\n): Promise<ChildCommand> {\n const packageManager = await getPackageManager();\n const args = [packageManager === 'yarn' ? 'add' : 'install', ...packages, ...options];\n return createChildCommand(packageManager, args);\n}\n\nexport async function installMissingDependencies(message: string, requiredDependencies: string[]): Promise<boolean> {\n if (requiredDependencies.length === 0) return true;\n\n const installedDependencies = await getPackageJsonDependencies({ includeDev: true });\n const missingDependencies = requiredDependencies.filter(dep => !installedDependencies.includes(dep));\n if (missingDependencies.length === 0) return true;\n\n return await installDependencies(message, missingDependencies);\n}\n\nexport async function installDependencies(message: string, dependencies: string[]): Promise<boolean> {\n if (dependencies.length === 0) return true;\n const installCommand = await getPackageManagerInstallCommand(dependencies);\n const formattedInstallCommand = pico.yellow(formatChildCommand(installCommand));\n\n if (process.env.CI) {\n logWarning(message);\n logWarning(`Skipping installation in CI environment. Please install manually:`);\n logWarning(formattedInstallCommand);\n return false;\n }\n\n logWarning(message);\n logWarning(`Install command: ${formattedInstallCommand}`);\n\n const dependencyResult: { installDependencies: boolean } = await prompts(\n { initial: true, message: 'Install dependencies?', name: 'installDependencies', type: 'confirm' },\n PROMPT_OPTIONS,\n );\n if (!dependencyResult.installDependencies) {\n logWarning('Skipping installation.');\n return false;\n }\n\n try {\n logInfo(`Installing`, dependencies);\n await spawnChildCommand(installCommand, { quiet: true });\n logSuccess(`Dependencies installed successfully.`);\n return true;\n } catch {\n logError(`Failed to install dependencies. Please try manually:`);\n logError(formattedInstallCommand);\n return false;\n }\n}\n","import pico from 'picocolors';\n\nimport { CliError } from './errors';\nimport { canRead, readJson, resolveRelativePath } from './fs';\n\ntype PackageJson = {\n name: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n scripts?: Record<string, string>;\n packageManager?: string;\n [key: string]: unknown;\n};\n\nlet packageJson: PackageJson | undefined;\nexport async function getPackageJson(): Promise<PackageJson> {\n if (!packageJson) {\n const packageJsonPath = resolveRelativePath('package.json');\n if (!(await canRead(packageJsonPath))) {\n throw new CliError('Cannot read package.json.', [`${pico.bold('Path')}: ${packageJsonPath}`]);\n }\n packageJson = await readJson<PackageJson>(packageJsonPath);\n }\n return packageJson;\n}\n\nexport async function getPackageJsonDependencies(options: { includeDev?: boolean } = {}): Promise<string[]> {\n const packageJson = await getPackageJson();\n return [\n ...(packageJson.dependencies ? Object.keys(packageJson.dependencies) : []),\n ...(options.includeDev && packageJson.devDependencies ? Object.keys(packageJson.devDependencies) : []),\n ];\n}\n","import { createChildCommand, spawnChildCommand } from './childCommands';\nimport { canRead, resolveRelativePath } from './fs';\nimport { getPackageJson } from './packageJson';\n\ntype PackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn';\n\nconst FALLBACK_PACKAGE_MANAGER: PackageManager = 'npm';\n\nlet packageManager: PackageManager | undefined;\nexport async function getPackageManager(): Promise<PackageManager> {\n if (!packageManager) {\n packageManager = await detectPackageManager();\n }\n return packageManager;\n}\n\nasync function detectPackageManager(): Promise<PackageManager> {\n const fromPackageJson = await detectPackageManagerFromPackageJson();\n if (fromPackageJson) return fromPackageJson;\n\n const fromLockfile = await detectPackageManagerFromLockfile();\n if (fromLockfile) return fromLockfile;\n\n const fromInstalledCli = await detectPackageManagerFromInstalledCli();\n if (fromInstalledCli) return fromInstalledCli;\n\n return FALLBACK_PACKAGE_MANAGER;\n}\n\nasync function detectPackageManagerFromPackageJson(): Promise<PackageManager | undefined> {\n const packageJson = await getPackageJson();\n if (!packageJson.packageManager) return undefined;\n if (packageJson.packageManager.startsWith('npm@')) return 'npm';\n if (packageJson.packageManager.startsWith('pnpm@')) return 'pnpm';\n if (packageJson.packageManager.startsWith('yarn@')) return 'yarn';\n if (packageJson.packageManager.startsWith('bun@')) return 'bun';\n return undefined;\n}\n\nasync function detectPackageManagerFromLockfile(): Promise<PackageManager | undefined> {\n const [isYarn, isPnpm, isBun, isNpm] = await Promise.all([\n canRead(resolveRelativePath('yarn.lock')),\n canRead(resolveRelativePath('pnpm-lock.yaml')),\n canRead(resolveRelativePath('bun.lockb')),\n canRead(resolveRelativePath('package-lock.json')),\n ]);\n\n if (isYarn) return 'yarn';\n if (isPnpm) return 'pnpm';\n if (isBun) return 'bun';\n if (isNpm) return 'npm';\n return undefined;\n}\n\nasync function detectPackageManagerFromInstalledCli(): Promise<PackageManager | undefined> {\n const [isPnpm, isYarn, isBun] = await Promise.all([\n hasPackageManagerCli('pnpm'),\n hasPackageManagerCli('yarn'),\n hasPackageManagerCli('bun'),\n ]);\n\n if (isPnpm) return 'pnpm';\n if (isYarn) return 'yarn';\n if (isBun) return 'bun';\n return undefined;\n}\n\nasync function hasPackageManagerCli(packageManager: PackageManager): Promise<boolean> {\n return await spawnChildCommand(createChildCommand(packageManager, ['--version']), { quiet: true })\n .then(() => true)\n .catch(() => false);\n}\n","import prompts from 'prompts';\n\nimport { CliError } from './errors';\n\nexport const PROMPT_OPTIONS: prompts.Options = {\n onCancel: () => {\n throw new CliError('Operation cancelled.');\n },\n};\n","import type { RootNode } from '@codama/nodes';\n\nimport { CliError } from './errors';\nimport { importModuleItem } from './import';\nimport { installMissingDependencies } from './packageInstall';\n\nexport async function getRootNodeFromIdl(idl: unknown): Promise<RootNode> {\n if (typeof idl !== 'object' || idl === null) {\n throw new CliError('Unexpected IDL content. Expected an object, got ' + typeof idl);\n }\n if (isRootNode(idl)) {\n return idl;\n }\n\n const hasNodesFromAnchor = await installMissingDependencies(\n 'Anchor IDL detected. Additional dependencies are required to process Anchor IDLs.',\n ['@codama/nodes-from-anchor'],\n );\n if (!hasNodesFromAnchor) {\n throw new CliError('Cannot proceed without Anchor IDL support.');\n }\n\n const rootNodeFromAnchor = await importModuleItem<(idl: unknown) => RootNode>({\n from: '@codama/nodes-from-anchor',\n item: 'rootNodeFromAnchor',\n });\n return rootNodeFromAnchor(idl);\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';\nimport pico from 'picocolors';\n\nimport { ParsedVisitorConfig } from '../parsedConfig';\nimport { CliError } from './errors';\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 { item, path } = visitorConfig;\n const identifier = getVisitorIdentifier(visitorConfig);\n const moduleItem = await importModuleItem({ identifier, from: path, item });\n const visitor = await getVisitorFromModuleItem(identifier, moduleItem, visitorConfig);\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 visitorConfig: ParsedVisitorConfig,\n): Promise<Visitor<unknown, 'rootNode'>> {\n const { args, item, path } = visitorConfig;\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 CliError(`Invalid visitor. Expected a visitor or a function returning a visitor.`, [\n `${pico.bold('Visitor')}: ${identifier}`,\n `${pico.bold('Path')}: ${path}`,\n ...(item ? [`${pico.bold('Item')}: ${item}`] : []),\n ]);\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, script } = visitorConfig;\n let identifier = `visitor #${index}`;\n identifier += script ? ` in script \"${script}\"` : '';\n return identifier;\n}\n","import type { RootNode } from '@codama/nodes';\nimport { visit, type Visitor } from '@codama/visitors-core';\nimport { Command } from 'commander';\nimport pico from 'picocolors';\n\nimport { ScriptName } from '../config';\nimport { getParsedConfigFromCommand, ParsedConfig } from '../parsedConfig';\nimport {\n CliError,\n getRootNodeVisitors,\n installMissingDependencies,\n isLocalModulePath,\n logInfo,\n logSuccess,\n logWarning,\n} 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 configuration 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 CliError('There are no scripts or before visitors to run.');\n }\n\n checkMissingScripts(parsedConfig, scripts);\n await checkMissingDependencies(parsedConfig, scripts);\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\nfunction checkMissingScripts(parsedConfig: Pick<ParsedConfig, 'configPath' | 'scripts'>, scripts: ScriptName[]) {\n const missingScripts = scripts.filter(script => !parsedConfig.scripts[script]);\n if (missingScripts.length === 0) return;\n\n const scriptPluralized = missingScripts.length === 1 ? 'Script' : 'Scripts';\n const message = parsedConfig.configPath\n ? `${scriptPluralized} not found in configuration file.`\n : `${scriptPluralized} not found because no configuration file was found.`;\n const items = [\n `${pico.bold(scriptPluralized)}: ${missingScripts.join(', ')}`,\n ...(parsedConfig.configPath ? [`${pico.bold('Path')}: ${parsedConfig.configPath}`] : []),\n ];\n throw new CliError(message, items);\n}\n\nasync function checkMissingDependencies(\n parsedConfig: Pick<ParsedConfig, 'before' | 'configPath' | 'scripts'>,\n scripts: ScriptName[],\n) {\n const dependencies = new Set<string>([\n ...parsedConfig.before.map(v => v.path),\n ...scripts.flatMap(script => parsedConfig.scripts[script]?.map(v => v.path) ?? []),\n ]);\n const externalDependencies = [...dependencies].filter(dep => !isLocalModulePath(dep));\n const scriptsRequirePluralized = scripts.length === 1 ? 'script requires' : 'scripts require';\n const installed = await installMissingDependencies(\n `Your ${scriptsRequirePluralized} additional dependencies.`,\n externalDependencies,\n );\n if (!installed) {\n throw new CliError('Cannot proceed without missing dependencies.');\n }\n}\n","import path from 'node:path';\n\nimport pico from 'picocolors';\n\nimport { ProgramOptions } from './programOptions';\nimport { canRead, CliError, 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 configuration file found. Using empty configs. Make sure you provide the `--idl` option.');\n return [{}, configPath];\n }\n\n const configFile = await importModuleItem({ identifier: 'configuration file', from: configPath });\n if (!configFile || typeof configFile !== 'object') {\n throw new CliError(`Invalid configuration file.`, [`${pico.bold('Path')}: ${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 CliError,\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());\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({ identifier: 'IDL', from: idlPath });\n const rootNode = await 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 CliError('No IDL identified. Please provide the `--idl` option or set it in the configuration 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,qBAAmC;AACrD,OAAOA,WAAU;;;ACAjB,OAAOC,WAAU;AACjB,OAAOC,cAA6B;;;ACFpC,SAAuB,aAA2B;AAO3C,SAAS,mBAAmB,SAAiB,OAAiB,CAAC,GAAiB;AACnF,SAAO,EAAE,SAAS,KAAK;AAC3B;AAEO,SAAS,mBAAmB,cAAoC;AACnE,QAAM,EAAE,SAAS,KAAK,IAAI;AAC1B,SAAO,CAAC,SAAS,GAAG,IAAI,EAAE,KAAK,GAAG;AACtC;AAWA,eAAsB,kBAClB,cACA,UAA6C,EAAE,OAAO,MAAM,GACU;AACtE,QAAM,EAAE,SAAS,KAAK,IAAI;AAC1B,QAAM,eAAe,MAAM,SAAS,MAAM,OAAO;AACjD,eAAa,eAAe;AAC5B,eAAa,eAAe;AAE5B,eAAa,QAAQ,GAAG,QAAQ,CAAC,UAAsB;AACnD,iBAAa,gBAAgB,MAAM,SAAS;AAC5C,QAAI,CAAC,QAAQ,OAAO;AAChB,cAAQ,OAAO,MAAM,KAAK;AAAA,IAC9B;AAAA,EACJ,CAAC;AACD,eAAa,QAAQ,G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AI,CAAC,WAAW;AACZ,UAAM,IAAI,SAAS,8CAA8C;AAAA,EACrE;AACJ;;;AGhHO,SAAS,kBAAkB,SAAwB;AACtD,UACK,OAAO,WAAW,mDAAmD,EACrE,OAAO,oBAAoB,6BAA6B,EACxD,OAAO,uBAAuB,4EAA4E;AACnH;;;AjBNA,eAAsB,OAAO,MAAgB,MAAoD;AAC7F,QAAM,UAAU,cAAc;AAAA,IAC1B,cAAc;AAAA,IACd,gBAAgB,MAAM;AAAA,EAC1B,CAAC;AACD,QAAM,WAAW,SAAS,MAAM,EAAE,MAAM,OAAO,CAAC;AACpD;AAEA,eAAsB,WAAW,SAAkB,MAAyB,cAA6B;AACrG,MAAI;AACA,UAAM,QAAQ,WAAW,MAAM,YAAY;AAAA,EAC/C,SAAS,KAAK;AACV,UAAM,QAAQ;AACd,QAAI,QAAQ,KAAK,EAAE,OAAO;AACtB,eAAS,GAAG,MAAM,KAAK,EAAE;AAAA,IAC7B;AACA,aAASC,MAAK,KAAK,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,CAAC;AACpD,YAAQ,WAAW;AAAA,EACvB;AACJ;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":["pico","pico","prompts","pico","pico","pico","pico","packageJson","packageJson","packageManager","packageManager","pico","pico","path","pico","pico","prompts","visit","pico","path","pico","path","pico","path","visit","pico","pico"]} |
@@ -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,CAQrD"} | ||
| {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../src/commands/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAkBpC,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CASrD"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../src/commands/run.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAMpC,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAMpD"} | ||
| {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../src/commands/run.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAepC,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAMpD"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAGlD,MAAM,MAAM,MAAM,GAAG,QAAQ,CAAC;IAC1B,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,aAAa,CAAC;IACxB,MAAM,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;CACrC,CAAC,CAAC;AAEH,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC;AAChC,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,SAAS,aAAa,EA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S,OAAO,EAAE,IAAI,mBAAmB,CAAC,CAAC,CAAC,GAAG,WAAW,CAAC;AACpH,MAAM,MAAM,mBAAmB,CAAC,CAAC,SAAS,SAAS,OAAO,EAAE,GAAG,SAAS,OAAO,EAAE,IAAI,QAAQ,CAAC;IAC1F,IAAI,CAAC,EAAE,CAAC,CAAC;IACT,IAAI,EAAE,WAAW,CAAC;CACrB,CAAC,CAAC;AAEH,wBAAsB,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,QAAQ,CAAC,GAAG,OAAO,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAczG"} |
| export * from './program'; | ||
| export * from './utils/logs'; | ||
| //# sourceMappingURL=index.d.ts.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,cAAc,CAAC"} | ||
| {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"parsedConfig.d.ts","sourceRoot":"","sources":["../../src/parsedConfig.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAqB,UAAU,EAAgC,WAAW,EAAE,MAAM,UAAU,CAAC;AACpG,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AASlD,MAAM,MAAM,YAAY,GAAG,QAAQ,CAAC;IAChC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,UAAU,EAAE,OAAO,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,QAAQ,CAAC;IACnB,OAAO,EAAE,mBAAmB,CAAC;IAC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AC;CAC1C,CAAC,CAAC;AAEH,MAAM,MAAM,mBAAmB,GAAG,QAAQ,CAAC,MAAM,CAAC,UAAU,EAAE,SAAS,mBAAmB,EAAE,CAAC,CAAC,CAAC;AAC/F,MAAM,MAAM,mBAAmB,CAAC,CAAC,SAAS,SAAS,OAAO,EAAE,GAAG,SAAS,OAAO,EAAE,IAAI,QAAQ,CAAC;IAC1F,IAAI,EAAE,CAAC,CAAC;IACR,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,IAAI,EAAE,WAAW,CAAC;IAClB,MAAM,EAAE,UAAU,GAAG,IAAI,CAAC;CAC7B,CAAC,CAAC;AAEH,wBAAsB,0BAA0B,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,CAEpF;AAED,wBAAsB,eAAe,CAAC,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,QAAQ,GAAG,KAAK,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC,CAG5G"} |
@@ -1,5 +0,6 @@ | ||
| import { Command } from 'commander'; | ||
| import { Command, ParseOptions } from 'commander'; | ||
| export declare function codama(args: string[], opts?: { | ||
| suppressOutput?: boolean; | ||
| }): Promise<void>; | ||
| export declare function runProgram(program: Command, argv: readonly string[], parseOptions?: ParseOptions): Promise<void>; | ||
| export declare function createProgram(internalOptions?: { | ||
@@ -6,0 +7,0 @@ exitOverride?: boolean; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"program.d.ts","sourceRoot":"","sources":["../../src/program.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAiB,MAAM,WAAW,CAAC;AAKnD,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,CAAC,EAAE;IAAE,cAAc,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAK/F;AAED,wBAAgB,aAAa,CAAC,eAAe,CAAC,EAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAC;IAAC,cAAc,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAuB7G"} | ||
| {"version":3,"file":"program.d.ts","sourceRoot":"","sources":["../../src/program.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAiB,YAAY,EAAE,MAAM,WAAW,CAAC;AAOjE,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,CAAC,EAAE;IAAE,cAAc,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAM/F;AAED,wBAAsB,UAAU,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,YAAY,CAAC,EAAE,YAAY,iBAWtG;AAED,wBAAgB,aAAa,CAAC,eAAe,CAAC,EAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAC;IAAC,cAAc,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,OAAO,CAuB7G"} |
@@ -5,2 +5,4 @@ import { PathLike } from 'node:fs'; | ||
| export declare function isLocalModulePath(modulePath: string): boolean; | ||
| export declare function readJson<T>(filePath: string): Promise<T>; | ||
| export declare function readFile(filePath: string): Promise<string>; | ||
| export declare function writeFile(filePath: string, content: string): Promise<void>; | ||
@@ -7,0 +9,0 @@ export declare function canRead(p: PathLike): Promise<boolean>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../../src/utils/fs.ts"],"names":[],"mappings":"AACA,OAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAGvC,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,iBAAiB,GAAE,MAAM,GAAG,IAAW,UAE7F;AAED,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,UAG7E;AAED,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,WAEnD;AAED,wBAAsB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,iBAMhE;AAED,wBAAsB,OAAO,CAAC,CAAC,EAAE,QAAQ,oBAOxC;AAED,wBAAsB,QAAQ,CAAC,CAAC,EAAE,QAAQ,oBAOzC"} | ||
| {"version":3,"file":"fs.d.ts","sourceRoot":"","sources":["../../../src/utils/fs.ts"],"names":[],"mappings":"AACA,OAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAGvC,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,iBAAiB,GAAE,MAAM,GAAG,IAAW,UAE7F;AAED,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,UAG7E;AAED,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,WAEnD;AAED,wBAAsB,QAAQ,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,CAE9D;AAED,wBAAsB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEhE;AAED,wBAAsB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,iBAMhE;AAED,wBAAsB,OAAO,CAAC,CAAC,EAAE,QAAQ,oBAOxC;AAED,wBAAsB,QAAQ,CAAC,CAAC,EAAE,QAAQ,oBAOzC"} |
@@ -1,2 +0,8 @@ | ||
| export declare function importModuleItem<T = unknown>(identifier: string, modulePath: string, itemName?: string): Promise<T>; | ||
| type ImportModuleItemOptions = { | ||
| from: string; | ||
| identifier?: string; | ||
| item?: string; | ||
| }; | ||
| export declare function importModuleItem<T = unknown>(options: ImportModuleItemOptions): Promise<T>; | ||
| export {}; | ||
| //# sourceMappingURL=import.d.ts.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"import.d.ts","sourceRoot":"","sources":["../../../src/utils/import.ts"],"names":[],"mappings":"AAIA,wBAAsB,gBAAgB,CAAC,CAAC,GAAG,OAAO,EAC9C,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,EAClB,QAAQ,GAAE,MAAkB,GAC7B,OAAO,CAAC,CAAC,CAAC,CAOZ"} | ||
| {"version":3,"file":"import.d.ts","sourceRoot":"","sources":["../../../src/utils/import.ts"],"names":[],"mappings":"AAOA,KAAK,uBAAuB,GAAG;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,wBAAsB,gBAAgB,CAAC,CAAC,GAAG,OAAO,EAAE,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,CAAC,CAAC,CAQhG"} |
@@ -0,1 +1,3 @@ | ||
| export * from './childCommands'; | ||
| export * from './errors'; | ||
| export * from './fs'; | ||
@@ -5,4 +7,8 @@ export * from './import'; | ||
| export * from './nodes'; | ||
| export * from './packageInstall'; | ||
| export * from './packageJson'; | ||
| export * from './packageManager'; | ||
| export * from './promises'; | ||
| export * from './prompts'; | ||
| export * from './visitors'; | ||
| //# sourceMappingURL=index.d.ts.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,MAAM,CAAC;AACrB,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC"} | ||
| {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,MAAM,CAAC;AACrB,cAAc,UAAU,CAAC;AACzB,cAAc,QAAQ,CAAC;AACvB,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC"} |
@@ -1,7 +0,7 @@ | ||
| export declare function logSuccess(...args: unknown[]): void; | ||
| export declare function logInfo(...args: unknown[]): void; | ||
| export declare function logWarning(...args: unknown[]): void; | ||
| export declare function logError(...args: unknown[]): void; | ||
| export declare function logDebug(...args: unknown[]): void; | ||
| export declare const logSuccess: (message: string, items?: string[]) => void; | ||
| export declare const logError: (message: string, items?: string[]) => void; | ||
| export declare const logInfo: (message: string, items?: string[]) => void; | ||
| export declare const logWarning: (message: string, items?: string[]) => void; | ||
| export declare const logDebug: (message: string, items?: string[]) => void; | ||
| export declare function logBanner(): void; | ||
| //# sourceMappingURL=logs.d.ts.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"logs.d.ts","sourceRoot":"","sources":["../../../src/utils/logs.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAEnD;AAED,wBAAgB,OAAO,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAEhD;AAED,wBAAgB,UAAU,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAEnD;AAED,wBAAgB,QAAQ,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAEjD;AAED,wBAAgB,QAAQ,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAEjD;AAED,wBAAgB,SAAS,IAAI,IAAI,CAEhC"} | ||
| {"version":3,"file":"logs.d.ts","sourceRoot":"","sources":["../../../src/utils/logs.ts"],"names":[],"mappings":"AA4BA,eAAO,MAAM,UAAU,YAD2B,MAAM,UAAU,MAAM,EAAE,SAC3B,CAAC;AAChD,eAAO,MAAM,QAAQ,YAF6B,MAAM,UAAU,MAAM,EAAE,SAE/B,CAAC;AAC5C,eAAO,MAAM,OAAO,YAH8B,MAAM,UAAU,MAAM,EAAE,SAGjC,CAAC;AAC1C,eAAO,MAAM,UAAU,YAJ2B,MAAM,UAAU,MAAM,EAAE,SAI3B,CAAC;AAChD,eAAO,MAAM,QAAQ,YAL6B,MAAM,UAAU,MAAM,EAAE,SAK/B,CAAC;AAkB5C,wBAAgB,SAAS,IAAI,IAAI,CAEhC"} |
| import type { RootNode } from '@codama/nodes'; | ||
| export declare function getRootNodeFromIdl(idl: unknown): RootNode; | ||
| export declare function getRootNodeFromIdl(idl: unknown): Promise<RootNode>; | ||
| export declare function isRootNode(value: unknown): value is RootNode; | ||
| //# sourceMappingURL=nodes.d.ts.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"nodes.d.ts","sourceRoot":"","sources":["../../../src/utils/nodes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAG9C,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,QAAQ,CAQzD;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAO5D"} | ||
| {"version":3,"file":"nodes.d.ts","sourceRoot":"","sources":["../../../src/utils/nodes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAM9C,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqBxE;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAO5D"} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"visitors.d.ts","sourceRoot":"","sources":["../../../src/utils/visitors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAA0B,KAAK,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAE7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAKtD,wBAAsB,mBAAmB,CACrC,QAAQ,EAAE,SAAS,mBAAmB,EAAE,GACzC,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE,CAAC,CAE1C"} | ||
| {"version":3,"file":"visitors.d.ts","sourceRoot":"","sources":["../../../src/utils/visitors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EAA0B,KAAK,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAG7E,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAMtD,wBAAsB,mBAAmB,CACrC,QAAQ,EAAE,SAAS,mBAAmB,EAAE,GACzC,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,EAAE,CAAC,CAE1C"} |
+4
-9
| { | ||
| "name": "@codama/cli", | ||
| "version": "1.2.2", | ||
| "version": "1.3.0", | ||
| "description": "A CLI for setting up and managing Codama IDLs", | ||
@@ -35,10 +35,5 @@ "exports": { | ||
| "prompts": "^2.4.2", | ||
| "@codama/renderers": "1.0.29", | ||
| "@codama/nodes-from-anchor": "1.2.3", | ||
| "@codama/renderers-js": "1.3.2", | ||
| "@codama/nodes": "1.3.1", | ||
| "@codama/renderers-js-umi": "1.1.17", | ||
| "@codama/renderers-rust": "1.2.0", | ||
| "@codama/visitors": "1.3.1", | ||
| "@codama/visitors-core": "1.3.1" | ||
| "@codama/nodes": "1.3.2", | ||
| "@codama/visitors": "1.3.2", | ||
| "@codama/visitors-core": "1.3.2" | ||
| }, | ||
@@ -45,0 +40,0 @@ "devDependencies": { |
+6
-4
@@ -12,8 +12,10 @@ # Codama ➤ CLI | ||
| Note that, whilst the CLI code is located in the `@codama/cli` package, the CLI binary is also included in the main `codama` library. | ||
| ## Getting started | ||
| To get started with Codama, simply install `@codama/cli` which provides the `codama` binary. Then, run the `init` command like so: | ||
| To get started with Codama, simply install `codama` to your project and run the `init` command like so: | ||
| ```sh | ||
| pnpm install @codama/cli | ||
| pnpm install codama | ||
| pnpm codama init | ||
@@ -32,3 +34,3 @@ ``` | ||
| Once you have your codama config file, you can run your Codama scripts using the `codama run` command as follows: | ||
| Once you have your codama configuration file, you can run your Codama scripts using the `codama run` command as follows: | ||
@@ -43,3 +45,3 @@ ```sh | ||
| The codama config file defines an object containing the following fields: | ||
| The codama configuration file defines an object containing the following fields: | ||
@@ -46,0 +48,0 @@ - `idl` (string): The path to the IDL file. This can be a Codama IDL or an Anchor IDL which will be automatically converted to a Codama IDL. |
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
293460
60.97%6
-45.45%52
30%2455
62.26%88
2.33%9
50%4
Infinity%+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated
Updated
Updated