Repository navigation
Expose CLI commands as a programmatic library API - #512
Conversation
🦋 Changeset detectedLatest commit: 5e073ca The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Coverage Report
📁 File Coverage (20 files)
|
33b100c to
237eb4c
Compare
00a89f2 to
6998883
Compare
|
@tuler could you rebase? |
6998883 to
6e24891
Compare
6e24891 to
cf77b41
Compare
Every command is now also a function, so applications can be built, run
and inspected from a script:
import { build, hash, run } from "@cartesi/cli";
The command actions were moved to `src/api`, and the Commander commands
became thin wrappers around them. The API functions take plain option
objects with defaults, return values instead of printing, throw instead
of exiting, and are silent unless `progress` is set to "default" or
"verbose", which reproduces the CLI output.
`src/lib.ts` is the new package entrypoint, bundled to `dist/lib.js` and
typed by `dist/types`, generated with `tsc --emitDeclarationOnly`. The
`bin` entrypoint is unchanged.
While rewiring the run command, "build and redeploy" now builds with the
configuration files given to `run`, instead of always `cartesi.toml`.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
The doctor API now runs every check in parallel and returns all results, failed and successful, instead of stopping at the first failure and reporting progress through callbacks. The command renders the results after they are gathered. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
Adds `depositEther`, `depositErc20`, `depositErc721`, `depositErc1155` and `depositErc1155Batch` to the library API, moving the deposit logic out of the commands. The commands keep the prompts, and pass everything resolved to the API. Amounts are given in the base unit of the asset as a bigint, or in its display unit as a string. Deposits that cannot be made now throw `DepositError` subclasses instead of printing and returning, which the commands render the same way as before. The connection setup shared by `send` and the deposits (client, sender and application address) moved to `resolveConnection`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
cf77b41 to
0f8ea17
Compare
|
@tuler, I built and tested this PR on 0f8ea17 locally. Build, typecheck, lint, the 548 unit tests and the integration suite (95 pass, 1 skipped) all pass. I then ran the PR build ( 1.
|
Running the checks concurrently made every check that needs docker fail on its own when docker is missing, and the RISC-V check had no mapping of the docker errors, so it printed raw execa messages. Each check now lists the checks it requires, and is reported as skipped when one of them is not satisfied; the command prints only the checks that ran. The docker errors are mapped by a single helper, so the RISC-V check also says Buildx is missing. The checks still run concurrently and every result is returned. DoctorCheck has a status instead of ok, to tell a skipped check from a failed one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
The "Build and redeploy" of cartesi run used to run the build command, which prints the accounts drive layout after building. It now calls the build API, which returns the layout without printing it, so only cartesi build printed it. The printing moves to printBuildResult, which both commands call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
run() reported the [prt] warnings before starting the environment, and the deploy at startup reported them again, so every warning was printed twice when a machine snapshot existed. The deploy at startup now uses the [prt] setup resolved and reported before the environment started. A redeploy still resolves [prt] again and reports its warnings, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
Adds foreclose, refund and withdraw to the library API. The helpers the commands kept, and their unit tests import, move to src/foreclose.ts, src/refund.ts and src/withdraw.ts, with the tests pointed there. As a library, cartesi-rollups-cli runs with --yes and --json, and its output is returned. With stream it is attached to the terminal with the transaction options as given, which the commands use. A failure the attached command printed is thrown as a NodeCommandError, which is the only error handleNodeCommandError now swallows, so an error from the steps before the node command is still printed by the commands. withdraw asks for the account only after the application is known to be foreclosed, as before. The replay and proof steps follow the caller's progress, silent by default. addRecoveryOptions moves to src/commands/recovery.ts, keeping Commander out of the modules the API uses, and getAnvilClient gets an explicit return type, as the inferred one cannot be named from outside viem. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
depositErc721 compared the token owner read from the chain, which is checksummed, with the sender as given, so a lowercase sender was told it had no balance for a token it owned. The CLI wasn't affected, as it checksums --from. resolveConnection now checksums the application and the sender it is given, which also rejects a malformed address before anything is sent, for send and every deposit. The deposits checksum their token too, and depositErc721 compares addresses whatever their case. The erc721 deposit command reads the token again before asking for the application, as it did before the deposits moved to the API, so a wrong token address fails before the prompt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
depositSpinner was exported from api/deposit/common.ts, whose
declarations are part of the public types, so they referenced
import("ora").Ora. ora is a devDependency, which a consumer of the
library doesn't install, so type-checking with skipLibCheck: false
failed with "Cannot find module 'ora'".
The spinner and the application label, both internal to the deposits,
move to api/deposit/progress.ts, which no public declaration imports.
Checked by type-checking a project that installs the packed package,
with skipLibCheck: false, under nodenext and bundler resolution.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
The library build bundled its own copies of execa, semver, smol-toml and viem, though they are installed as its dependencies. An error the library threw from viem was then an instance of its private copy, so instanceof HttpRequestError and BaseError were false with the consumer's viem, and an app also using viem shipped it twice. The library build now leaves them, and their subpaths, external. dist/lib.js drops from 1031 KiB to 489 KiB. The CLI bundle and the binaries still bundle everything, as they run without node_modules. Checked with a project that installs the packed package: a deposit against an unreachable RPC now throws an error that is an instance of the project's HttpRequestError and BaseError. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn
|
@brunomenezes thanks for the thorough review. Each item now has its own commit:
Verification: typecheck, declaration emit, lint and the 555 unit tests pass at each commit. I used your I had no Docker daemon, so I couldn't run the Docker-dependent paths: items 2 and 3 in Generated by Claude Code |
I re-ran everything on One small thing: when And you're right about erc1155. Sorry about that one. I know it is a stacked PR, but are you going to make this one ready to review so we can merge? I will look the 514 later. |
Summary
This PR refactors the Cartesi CLI to expose all commands as a programmatic library API, allowing developers to use CLI functionality directly from TypeScript/JavaScript code without invoking the command-line interface.
Key Changes
New API modules (
apps/cli/src/api/): Created modular API functions for every command but the deprecateddeploy:build.ts- Build application drives, nvrams and machine snapshotrun.ts- Start local Cartesi rollups environment, with its PRT nodessend.ts- Send inputs to deployed applicationsdeposit/- Deposit assets:depositEther,depositErc20,depositErc721,depositErc1155,depositErc1155Batchforeclose.ts,refund.ts,withdraw.ts- Recover funds from an application, sharingrecovery.tslogs.ts- Read the logs of the node and its PRT nodes, or of the services givenhash.ts- Get machine snapshot hashstatus.ts- Query environment statusshell.ts- Boot machine in interactive modedoctor.ts- Check system requirementscreate.ts- Create new applications from templatesclean.ts- Clean build artifactsaddress-book.ts- Get deployed contract addressesconnection.ts- Shared resolution of client, sender and application addresstypes.ts- Shared types and configuration resolutionCommand refactoring: Updated the command files to delegate to the new API modules, eliminating code duplication. Commands keep the interactive prompts and the terminal output, and pass resolved values to the API. Helpers that upstream unit tests import moved along with the code that uses them, and the tests import them from their new place:
selectLogServices,buildLogsArgsandlistServicestoapi/logs.ts, and the fund recovery helpers tosrc/foreclose.ts,src/refund.tsandsrc/withdraw.ts.addRecoveryOptionsmoved tocommands/recovery.ts, keeping Commander out of the modules the API uses.Library exports:
src/lib.tsas the main library entrypoint, bundled todist/lib.jsalongside the CLI bundlemain,exportsandtypestopackage.json, pointing at the library build and its declarations, whilebinkeeps pointing at the CLI build (dist/index.js). This restores the fields dropped in d78d897, now that the package does ship a library and does emit declarationstsconfig.build.json, covering the library entrypoint and what it importsviem,execa,semverandsmol-tomlback todependencies. The library build leaves them external and loads them fromnode_modules, so a consumer shares them: errors thrown from viem are instances of the consumer's viem classes, and viem isn't shipped twice. The CLI bundle and the binaries still bundle everything. Every other package stays a devDependency, inlined by the bundlerEnhanced wallet support: Added
interactiveparameter togetRpcUrl()for programmatic use cases, andDevnetClientfor the devnet client typeTest coverage: Added unit tests for
encodeInput(),resolveConfig(),parseAmount(), the deposit error hierarchy, the doctor requirements and the address normalization ofresolveConnection()Documentation: Updated README with library usage examples
Notable Implementation Details
OptionsandResulttypessilent,default,verbose) for library useConfigobjects or file pathsrun()function returns aRunResultobject with methods to deploy/undeploy applications, stop the PRT nodes and stop the environment, and it reports configuration worth saying out loud (a[prt]section with no effect, a reader-mode change on a rebuild) through anonNoticecallback instead of printing; the command prints those noticesrun()owns the PRT orchestration: it resolves[prt]before anything starts and reports its warnings once, funds the pool accounts, deploys with the sentries, starts the PRT nodes for the deployment and exposes them asprtConfigandprtServices. A redeploy resolves[prt]again and reports its warnings againprogressoption is specifieddoctor()runs every check concurrently and returns all results. Each check lists the checks it requires, and is reported asskippedwhen one of them is not satisfied, which the command doesn't print; the docker errors are mapped to what to install by a single helperbuild()resolves the accounts drive layout of the built machine and returns it with the emergency withdrawal configuration derived from it, whichcartesi buildand the "Build and redeploy" ofcartesi runthen print;run()resolves that configuration itself, before starting the environment and again on every redeployforeclose(),refund()andwithdraw()run cartesi-rollups-cli with--yesand--jsonand return its output. Withstream: trueit is attached to the terminal with the transaction options as given, which the commands use, and a failure it printed is thrown as aNodeCommandErrorsendand the deposits checksum the application, sender and token addresses they are given, which also rejects a malformed address earlybigint, or in its display unit as a string ("1.5"); the token defaults to the corresponding devnet test tokenDepositErrorsubclasses (InsufficientBalanceError,InvalidAmountError,TokenNotFoundError) instead of printing and returning; the commands render them as beforeexecaDockerFallbackreturns execa'sResult,cartesiis a viemChain,getAnvilClientreturns a viemPublicClient, andDevnetClientis spelled out from viem'sTestClient,PublicActionsandWalletActionsskipLibCheck: falseneed@types/node, as the declarations of the environment referenceNodeJS.ProcessEnvBehavior Changes
run: "Build and redeploy" now builds with the configuration files given torun -c, instead of alwayscartesi.tomldoctor: every requirement whose requirements are met is checked and reported, instead of stopping at the first failuredeposit erc721: a failed ownership check that is notERC721NonexistentTokennow stops instead of reporting the failure and continuingdeposit erc1155-batch: the token-ids/amounts length mismatch is reported after the application address prompt, rather than before itTesting
Type checking, linting, declaration emit and the 555 unit tests pass, each commit independently. The published package was checked by installing the output of
npm packinto an empty project, with TypeScript 7 and@types/node: it type-checks withskipLibCheck: falseunder bothnodenextandbundlermodule resolution, and a deposit against an unreachable RPC throws an error that is an instance of the project's ownHttpRequestErrorandBaseError. Docker was not available in the development environment, so the docker-dependent paths (build,run,logs, deposits, the PRT nodes, the fund recovery commands) were not exercised end to end and rely on CI.https://claude.ai/code/session_015SA64hXXCsNWisTYLVpEBn