@typesol/cli 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +250 -0
  2. package/README.md +63 -17
  3. package/SECURITY.md +9 -7
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +9 -0
  6. package/dist/cli.js +33 -15
  7. package/dist/compiler/analyze.js +57 -6
  8. package/dist/compiler/diagnostics.d.ts +4 -3
  9. package/dist/compiler/diagnostics.js +10 -6
  10. package/dist/compiler/emit/base.d.ts +1 -1
  11. package/dist/compiler/emit/calls.js +18 -5
  12. package/dist/compiler/emit/cpi-core.d.ts +3 -1
  13. package/dist/compiler/emit/cpi-core.js +8 -4
  14. package/dist/compiler/emit/expressions.d.ts +14 -0
  15. package/dist/compiler/emit/expressions.js +52 -4
  16. package/dist/compiler/emit/shared.d.ts +8 -1
  17. package/dist/compiler/emit/shared.js +8 -1
  18. package/dist/compiler/emit/statements.d.ts +8 -3
  19. package/dist/compiler/emit/statements.js +68 -3
  20. package/dist/compiler/emit/storage.js +5 -1
  21. package/dist/compiler/hints.d.ts +7 -0
  22. package/dist/compiler/hints.js +58 -9
  23. package/dist/compiler/index.d.ts +5 -0
  24. package/dist/compiler/index.js +10 -1
  25. package/dist/compiler/model.js +3 -2
  26. package/dist/compiler/toolchain.d.ts +50 -2
  27. package/dist/compiler/toolchain.js +96 -11
  28. package/dist/idl-coder.d.ts +110 -0
  29. package/dist/idl-coder.js +529 -0
  30. package/dist/node-version.d.ts +4 -0
  31. package/dist/node-version.js +12 -0
  32. package/dist/testing.d.ts +44 -7
  33. package/dist/testing.js +30 -19
  34. package/dist/tools/doctor.d.ts +41 -0
  35. package/dist/tools/doctor.js +96 -14
  36. package/dist/workspace.d.ts +9 -2
  37. package/dist/workspace.js +13 -4
  38. package/docker/deps/0.46.0.lock.json +1206 -0
  39. package/docker/deps/0.47.0.lock.json +1206 -0
  40. package/docs/ai.md +2 -1
  41. package/docs/architecture.md +7 -3
  42. package/docs/audit.md +6 -6
  43. package/docs/case-study-phoenix.md +1 -1
  44. package/docs/case-study-raydium-amm.md +1 -1
  45. package/docs/case-study-spl-stake-pool.md +1 -1
  46. package/docs/cli.md +42 -4
  47. package/docs/errors.md +22 -8
  48. package/docs/glossary.md +210 -0
  49. package/docs/language-accounts.md +499 -0
  50. package/docs/language-basics.md +389 -0
  51. package/docs/language-builtins.md +411 -0
  52. package/docs/language-chain.md +198 -0
  53. package/docs/language-cpi.md +470 -0
  54. package/docs/language-errors-events.md +184 -0
  55. package/docs/language-native.md +493 -0
  56. package/docs/language-pdas.md +198 -0
  57. package/docs/language-statements.md +620 -0
  58. package/docs/language-types.md +601 -0
  59. package/docs/language.md +190 -467
  60. package/docs/mainnet.md +18 -3
  61. package/docs/migrate-from-anchor.md +7 -6
  62. package/docs/security-model.md +3 -3
  63. package/docs/stability.md +3 -1
  64. package/docs/test-your-program.md +54 -15
  65. package/docs/troubleshooting.md +222 -100
  66. package/lib/typesol.d.ts +67 -22
  67. package/llms-full.txt +4920 -638
  68. package/llms.txt +12 -1
  69. package/package.json +2 -6
  70. package/releases/0.45.0.json +732 -0
  71. package/releases/0.46.0.json +817 -0
  72. package/ts-plugin/index.js +16 -5
package/dist/testing.d.ts CHANGED
@@ -14,9 +14,9 @@
14
14
  * integers, address strings for Pubkeys, null for an empty Option. Decoded accounts and return data come back the
15
15
  * same way (bigints, address strings).
16
16
  *
17
- * Needs `litesvm` and `@anchor-lang/core`, which `typesol init` projects have.
17
+ * Needs `litesvm`, which `typesol init` projects have. Instruction data, accounts and return data are encoded and
18
+ * decoded from the IDL by TypeSOL's own Borsh coder (src/idl-coder.ts).
18
19
  */
19
- import anchor, { type Idl } from "@anchor-lang/core";
20
20
  import { type Address, type Instruction, type KeyPairSigner } from "@solana/kit";
21
21
  import { FailedTransactionMetadata, LiteSVM, TransactionMetadata } from "litesvm";
22
22
  import { loadClonedAccounts } from "./tools/clone.js";
@@ -25,8 +25,44 @@ export { type SvmConnection, svmConnection };
25
25
  export * from "./testing-stake.js";
26
26
  /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
27
27
  export { loadClonedAccounts };
28
- declare const BorshCoder: typeof anchor.BorshCoder;
29
- type BorshCoder = InstanceType<typeof BorshCoder>;
28
+ /** An Anchor IDL (spec 0.1.0), as `typesol build` writes it and Anchor's `Idl` type describes it. */
29
+ export interface TestIdl {
30
+ address: string;
31
+ metadata?: unknown;
32
+ instructions: readonly {
33
+ name: string;
34
+ discriminator: readonly number[];
35
+ accounts: readonly unknown[];
36
+ args: readonly {
37
+ name: string;
38
+ type: unknown;
39
+ }[];
40
+ returns?: unknown;
41
+ }[];
42
+ accounts?: readonly {
43
+ name: string;
44
+ discriminator: readonly number[];
45
+ }[];
46
+ events?: readonly unknown[];
47
+ errors?: readonly {
48
+ code: number;
49
+ name: string;
50
+ msg?: string;
51
+ }[];
52
+ types?: readonly unknown[];
53
+ constants?: readonly unknown[];
54
+ }
55
+ /**
56
+ * Anchor's `BorshCoder` for the program's IDL (`instruction`, `accounts`, `events`, `types`), which works with BN and
57
+ * PublicKey values. `@anchor-lang/core` is loaded the first time `t.coder` is read: install it to use `t.coder`.
58
+ * The other helpers do not need it.
59
+ */
60
+ export interface AnchorBorshCoder {
61
+ instruction: any;
62
+ accounts: any;
63
+ events: any;
64
+ types: any;
65
+ }
30
66
  export type Result = TransactionMetadata | FailedTransactionMetadata;
31
67
  /** An account for an instruction: an address, a keypair (which then signs), or null to leave an optional one out. */
32
68
  export type AccountInput = Address | KeyPairSigner | null;
@@ -38,8 +74,9 @@ export type SeedInput = string | Address | KeyPairSigner | Uint8Array | bigint;
38
74
  export interface TestProgram {
39
75
  svm: LiteSVM;
40
76
  programId: Address;
41
- idl: Idl;
42
- coder: BorshCoder;
77
+ idl: TestIdl;
78
+ /** Anchor's BorshCoder for this IDL; needs `@anchor-lang/core` installed (loaded on first use). */
79
+ readonly coder: AnchorBorshCoder;
43
80
  /** A new keypair funded with `sol` SOL (default 10). */
44
81
  wallet(sol?: number): Promise<KeyPairSigner>;
45
82
  /** The program's PDA for these seeds. */
@@ -100,4 +137,4 @@ export interface TestProgram {
100
137
  /** Build `program` of the project around `from` (a file URL such as import.meta.url, or a directory) and load it. */
101
138
  export declare function testProgram(program: string, from: string | URL): Promise<TestProgram>;
102
139
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
103
- export declare function programHarness(svm: LiteSVM, programId: Address, idl: Idl): TestProgram;
140
+ export declare function programHarness(svm: LiteSVM, programId: Address, idl: TestIdl): TestProgram;
package/dist/testing.js CHANGED
@@ -14,14 +14,16 @@
14
14
  * integers, address strings for Pubkeys, null for an empty Option. Decoded accounts and return data come back the
15
15
  * same way (bigints, address strings).
16
16
  *
17
- * Needs `litesvm` and `@anchor-lang/core`, which `typesol init` projects have.
17
+ * Needs `litesvm`, which `typesol init` projects have. Instruction data, accounts and return data are encoded and
18
+ * decoded from the IDL by TypeSOL's own Borsh coder (src/idl-coder.ts).
18
19
  */
19
- import anchor from "@anchor-lang/core";
20
20
  import { AccountRole, appendTransactionMessageInstructions, createTransactionMessage, generateKeyPairSigner, getAddressDecoder, getAddressEncoder, getProgramDerivedAddress, isAddress, isOffCurveAddress, lamports, pipe, setTransactionMessageFeePayerSigner, signTransactionMessageWithSigners, } from "@solana/kit";
21
21
  import { FailedTransactionMetadata, LiteSVM } from "litesvm";
22
22
  import { createHash } from "node:crypto";
23
+ import { createRequire } from "node:module";
23
24
  import path from "node:path";
24
25
  import { fileURLToPath } from "node:url";
26
+ import { IdlCoder } from "./idl-coder.js";
25
27
  import { TYPESOL_ERRORS } from "./tools/clientgen.js";
26
28
  import { loadClonedAccounts } from "./tools/clone.js";
27
29
  import { svmConnection } from "./tools/svmrpc.js";
@@ -30,8 +32,21 @@ export { svmConnection };
30
32
  export * from "./testing-stake.js";
31
33
  /** Load what `typesol clone` wrote (a directory of `<address>.json` accounts and `<address>.so` programs) into a LiteSVM. */
32
34
  export { loadClonedAccounts };
33
- // @anchor-lang/core is CommonJS: Node 22 cannot import its classes by name from an installed ES module.
34
- const { BN, BorshCoder } = anchor;
35
+ /** `new BorshCoder(idl)` from `@anchor-lang/core`, found next to typesol or in the project being tested. */
36
+ function anchorCoder(idl) {
37
+ for (const from of [import.meta.url, path.join(process.cwd(), "package.json")]) {
38
+ let anchor;
39
+ try {
40
+ // CommonJS: loaded with require, as Node cannot import its classes by name from an ES module.
41
+ anchor = createRequire(from)("@anchor-lang/core");
42
+ }
43
+ catch {
44
+ continue;
45
+ }
46
+ return new anchor.BorshCoder(idl);
47
+ }
48
+ throw new Error("t.coder is Anchor's BorshCoder: install @anchor-lang/core (npm install -D @anchor-lang/core) to use it");
49
+ }
35
50
  /**
36
51
  * An instruction's accounts with groups flattened as the generated client does: `pool.vault` becomes `pool_vault`
37
52
  * (`poolVault` in `t.ix`), and a seed naming a field of the same group names its flattened account.
@@ -51,7 +66,6 @@ function flattenAccounts(items, prefix = "") {
51
66
  }
52
67
  return out;
53
68
  }
54
- const BIG = new Set(["u64", "i64", "u128", "i128"]);
55
69
  const snake = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
56
70
  const camel = (s) => s.replace(/_([a-z0-9])/g, (_, c) => c.toUpperCase());
57
71
  const isSigner = (v) => typeof v === "object" && v !== null && "address" in v && "signTransactions" in v;
@@ -76,23 +90,22 @@ export async function testProgram(program, from) {
76
90
  }
77
91
  /** The same helpers for a program already loaded into `svm` at `programId` with this IDL. */
78
92
  export function programHarness(svm, programId, idl) {
79
- const coder = new BorshCoder(idl);
93
+ const coder = new IdlCoder(idl);
94
+ let anchor;
80
95
  const source = idl;
81
96
  const pidl = { ...source, instructions: source.instructions.map((ix) => ({ ...ix, accounts: flattenAccounts(ix.accounts) })) };
82
97
  const types = new Map((pidl.types ?? []).map((t) => [t.name, t]));
83
98
  const enc = getAddressEncoder();
84
- /** A plain value → what the Anchor coder expects for `type`. */
99
+ /** A plain value → what the coder expects for `type` (integers of 64 bits and more it parses itself). */
85
100
  const toCoder = (v, type, where) => {
86
101
  if (typeof type === "string") {
87
- if (BIG.has(type))
88
- return new BN(String(v));
89
102
  if (/^[ui](8|16|32)$/.test(type))
90
103
  return Number(v);
91
104
  if (type === "pubkey") {
92
105
  const a = isSigner(v) ? v.address : v;
93
106
  if (typeof a !== "string" || !isAddress(a))
94
107
  throw new Error(`${where}: expected an address`);
95
- return { toBuffer: () => Buffer.from(enc.encode(a)) };
108
+ return a;
96
109
  }
97
110
  return v;
98
111
  }
@@ -136,14 +149,10 @@ export function programHarness(svm, programId, idl) {
136
149
  }
137
150
  return v;
138
151
  };
139
- /** What the coder decodes → plain values (bigints, address strings), recursively. */
152
+ /** What the coder decodes (bigints, address strings) with TypeSOL's fixed-layout Options and strings unwrapped. */
140
153
  const plain = (v) => {
141
154
  if (v === null || v === undefined)
142
155
  return v;
143
- if (BN.isBN(v))
144
- return BigInt(v.toString());
145
- if (typeof v === "object" && typeof v.toBase58 === "function")
146
- return v.toBase58();
147
156
  if (Array.isArray(v))
148
157
  return v.map(plain);
149
158
  if (v instanceof Uint8Array)
@@ -228,7 +237,9 @@ export function programHarness(svm, programId, idl) {
228
237
  svm,
229
238
  programId,
230
239
  idl,
231
- coder,
240
+ get coder() {
241
+ return (anchor ??= anchorCoder(idl));
242
+ },
232
243
  async wallet(sol = 10) {
233
244
  const k = await generateKeyPairSigner();
234
245
  svm.airdrop(k.address, lamports(BigInt(Math.round(sol * 1e9))));
@@ -318,7 +329,7 @@ export function programHarness(svm, programId, idl) {
318
329
  });
319
330
  const a = args;
320
331
  const encoded = Object.fromEntries(def.args.map((x) => [x.name, toCoder(a[x.name] ?? a[camel(x.name)], x.type, `${def.name}(${camel(x.name)})`)]));
321
- return { programAddress: programId, accounts: metas, data: new Uint8Array(coder.instruction.encode(def.name, encoded)) };
332
+ return { programAddress: programId, accounts: metas, data: new Uint8Array(coder.encodeInstruction(def.name, encoded)) };
322
333
  },
323
334
  async send(payer, ...ixs) {
324
335
  const tx = await pipe(createTransactionMessage({ version: 0 }), (t) => setTransactionMessageFeePayerSigner(payer, t), (t) => svm.setTransactionMessageLifetimeUsingLatestBlockhash(t), (t) => appendTransactionMessageInstructions(ixs, t), (t) => signTransactionMessageWithSigners(t));
@@ -403,7 +414,7 @@ export function programHarness(svm, programId, idl) {
403
414
  const a = svm.getAccount(address);
404
415
  if (!a.exists)
405
416
  return null;
406
- return plain(coder.accounts.decode(type, Buffer.from(a.data)));
417
+ return plain(coder.decodeAccount(type, Buffer.from(a.data)));
407
418
  },
408
419
  returned(instruction, res) {
409
420
  const def = pidl.instructions.find((i) => i.name === instruction || i.name === snake(instruction));
@@ -446,7 +457,7 @@ export function programHarness(svm, programId, idl) {
446
457
  return (bytes <= 4 ? Number(n) : n);
447
458
  }
448
459
  if ("defined" in t)
449
- return plain(coder.types.decode(t.defined.name, data));
460
+ return plain(coder.decodeType(t.defined.name, data));
450
461
  throw new Error(`decode ${instruction}'s return data yourself (${JSON.stringify(t)})`);
451
462
  },
452
463
  balance(address) {
@@ -12,6 +12,16 @@ export interface Check {
12
12
  }
13
13
  /** The platform-tools the compiler needs: found, or what to run. */
14
14
  export declare function toolchainCheck(): Check;
15
+ /** The install commands for this host, each with its note on the line above when what it does is not obvious. */
16
+ export declare function installSteps(from: "agave" | "platform-tools", host?: {
17
+ platform: string;
18
+ arch: string;
19
+ }): string[];
20
+ /** The Solana CLI (deploying only): the Agave installer, or on Linux arm64, where there is none, what to do instead. */
21
+ export declare function solanaCliFix(host?: {
22
+ platform: string;
23
+ arch: string;
24
+ }): string;
15
25
  /**
16
26
  * Whether the active platform-tools are the ones TypeSOL is tested with. An untested one is a warning, or an error
17
27
  * under TYPESOL_TOOLCHAIN=strict (as it is for a build then). Undefined when there are no platform-tools at all.
@@ -41,6 +51,35 @@ export declare function rpcTimeoutSeconds(): number;
41
51
  * `deploy` do (the URL can carry an API key).
42
52
  */
43
53
  export declare function cliRpc(url: string): Promise<Rpc<SolanaRpcApi>>;
54
+ /**
55
+ * Whether a `--keypair` / `keypair_path` value is a signer the Solana CLI resolves itself rather than a file: `ASK`,
56
+ * `-` (stdin) or a `usb:`, `prompt:` or `stdin:` URI (`usb://ledger?key=0`, `prompt://`, `stdin://`; the scheme in any
57
+ * case, as the Solana CLI reads it). Anything else is a file: `file:` through keypairFile.
58
+ */
59
+ export declare function isSignerUri(source: string): boolean;
60
+ /** The file a `--keypair` / `keypair_path` value names: the path of a `file:` URI (`file:id.json`, `file:///abs/id.json`), as the Solana CLI reads it, else the value. */
61
+ export declare function keypairFile(source: string): string;
62
+ /** Where a deploy's payer comes from, for the message when its file is missing. */
63
+ export type PayerSource = {
64
+ from: "flag";
65
+ } | {
66
+ from: "config";
67
+ config: string;
68
+ } | {
69
+ from: "default";
70
+ };
71
+ /**
72
+ * A deploy's payer keypair file must exist: without it `solana program deploy` refuses only after the build, mid-way.
73
+ * A signer URI (a Ledger, a prompt, stdin) is the Solana CLI's to resolve, so it is passed through unchecked.
74
+ */
75
+ export declare function requirePayer(url: string, payer: string, source?: PayerSource): void;
76
+ /** `deploy` runs `solana program deploy`: without the Solana CLI on PATH it stops before building. */
77
+ export declare function requireSolanaCli(): void;
78
+ /** The error for a missing `solana`, with how to get it on this host. */
79
+ export declare function solanaNotFound(host?: {
80
+ platform: string;
81
+ arch: string;
82
+ }): string;
44
83
  /**
45
84
  * Before `solana program deploy`: the RPC answers, and the payer holds enough for the program's rent (a first deploy
46
85
  * holds about twice the binary's rent while the buffer exists; an upgrade, the buffer's). Throws with what to do.
@@ -60,4 +99,6 @@ export declare function doctorChecks(opts: {
60
99
  url?: string;
61
100
  config?: string;
62
101
  }): Promise<Check[]>;
102
+ /** The last line of `doctor`: what is ready, and what the warnings are about. */
103
+ export declare function doctorSummary(checks: Check[]): string;
63
104
  export declare function formatChecks(checks: Check[]): string;
@@ -5,13 +5,13 @@ import { execFileSync } from "node:child_process";
5
5
  import { existsSync, readFileSync, statSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
- import { findToolchain, INSTALL_TESTED_TOOLCHAIN, shortClang, TESTED_TOOLCHAIN, toolchainInfo, toolchainStrict } from "../compiler/toolchain.js";
8
+ import { findToolchain, INSTALL_TESTED_TOOLCHAIN, installLines, linuxArm64, shortClang, TESTED_TOOLCHAIN, ToolchainMissing, toolchainInfo, toolchainStrict, } from "../compiler/toolchain.js";
9
9
  import { base58, readKeypair } from "../keys.js";
10
10
  import { DOCKER_PLATFORM, dockerStatus } from "./docker.js";
11
11
  import { findWorkspace } from "../workspace.js";
12
+ import { MIN_NODE } from "../node-version.js";
12
13
  /** The Agave CLI release TypeSOL is tested with (its platform-tools are the tested ones). */
13
14
  export const INSTALL_AGAVE = INSTALL_TESTED_TOOLCHAIN[0];
14
- const MIN_NODE = [22, 12];
15
15
  /** The platform-tools the compiler needs: found, or what to run. */
16
16
  export function toolchainCheck() {
17
17
  try {
@@ -28,14 +28,21 @@ export function toolchainCheck() {
28
28
  return { ok: true, what: "platform-tools", detail: version || tc.sdk };
29
29
  }
30
30
  catch (e) {
31
- return {
32
- ok: false,
33
- what: "platform-tools",
34
- detail: e.message.split(". ")[0],
35
- fix: [INSTALL_AGAVE, "cargo-build-sbf --version # once: downloads the platform-tools TypeSOL compiles with"],
36
- };
31
+ if (!(e instanceof ToolchainMissing))
32
+ return { ok: false, what: "platform-tools", detail: e.message };
33
+ return { ok: false, what: "platform-tools", detail: e.summary, fix: installSteps(e.kind === "agave" ? "agave" : "platform-tools") };
37
34
  }
38
35
  }
36
+ /** The install commands for this host, each with its note on the line above when what it does is not obvious. */
37
+ export function installSteps(from, host = process) {
38
+ return installLines(from, host);
39
+ }
40
+ /** The Solana CLI (deploying only): the Agave installer, or on Linux arm64, where there is none, what to do instead. */
41
+ export function solanaCliFix(host = process) {
42
+ return linuxArm64(host)
43
+ ? "no Agave CLI is published for Linux arm64: deploy from macOS or Linux x86_64, or build it from source (https://docs.anza.xyz/cli/install)"
44
+ : INSTALL_AGAVE;
45
+ }
39
46
  /**
40
47
  * Whether the active platform-tools are the ones TypeSOL is tested with. An untested one is a warning, or an error
41
48
  * under TYPESOL_TOOLCHAIN=strict (as it is for a build then). Undefined when there are no platform-tools at all.
@@ -63,7 +70,7 @@ export function testedToolchainCheck() {
63
70
  optional: !strict,
64
71
  what: "toolchain",
65
72
  detail: `untested: ${shortClang(info.clang)}, platform-tools ${info.platformTools ?? "unknown"}; TypeSOL is tested with ${tested} (Agave ${TESTED_TOOLCHAIN.agave}): binaries from another toolchain are not covered by its tests${strict ? " (TYPESOL_TOOLCHAIN=strict refuses it)" : ""}`,
66
- fix: [`${INSTALL_TESTED_TOOLCHAIN[1]} # the tested platform-tools`],
73
+ fix: ["# The tested platform-tools:", INSTALL_TESTED_TOOLCHAIN[1]],
67
74
  };
68
75
  }
69
76
  /** Docker for `build --docker` / `verify --docker`: optional, a row either way. */
@@ -166,6 +173,61 @@ export async function cliRpc(url) {
166
173
  const sol = (lamports) => lamports === 0 ? "0 SOL" : lamports < 100_000 ? `${lamports} lamports` : `${(lamports / 1e9).toFixed(lamports < 1e7 ? 4 : 2)} SOL`;
167
174
  /** A cost, rounded up so the advice is enough. */
168
175
  const solUp = (lamports) => `${(Math.ceil(lamports / 1e7) / 100).toFixed(2)} SOL`;
176
+ /**
177
+ * Whether a `--keypair` / `keypair_path` value is a signer the Solana CLI resolves itself rather than a file: `ASK`,
178
+ * `-` (stdin) or a `usb:`, `prompt:` or `stdin:` URI (`usb://ledger?key=0`, `prompt://`, `stdin://`; the scheme in any
179
+ * case, as the Solana CLI reads it). Anything else is a file: `file:` through keypairFile.
180
+ */
181
+ export function isSignerUri(source) {
182
+ return source === "ASK" || source === "-" || /^(?:usb|prompt|stdin):/i.test(source);
183
+ }
184
+ /** The file a `--keypair` / `keypair_path` value names: the path of a `file:` URI (`file:id.json`, `file:///abs/id.json`), as the Solana CLI reads it, else the value. */
185
+ export function keypairFile(source) {
186
+ const m = /^file:(?:\/\/[^/?#]*)?([^?#]*)/i.exec(source);
187
+ return m ? m[1] : source;
188
+ }
189
+ /**
190
+ * A deploy's payer keypair file must exist: without it `solana program deploy` refuses only after the build, mid-way.
191
+ * A signer URI (a Ledger, a prompt, stdin) is the Solana CLI's to resolve, so it is passed through unchecked.
192
+ */
193
+ export function requirePayer(url, payer, source = { from: "default" }) {
194
+ if (isSignerUri(payer))
195
+ return;
196
+ const file = keypairFile(payer);
197
+ if (!file.trim()) {
198
+ if (source.from === "config")
199
+ throw new Error(`keypair_path in ${source.config.replace(os.homedir(), "~")} is empty: set it to the payer's keypair file, or pass --keypair <file>. Nothing was sent.`);
200
+ throw new Error("--keypair is empty: give the path of the payer's keypair file. Nothing was sent.");
201
+ }
202
+ if (existsSync(file))
203
+ return;
204
+ const shown = file.replace(os.homedir(), "~");
205
+ if (source.from === "flag")
206
+ throw new Error(`no keypair file at ${shown} (given with --keypair): check the path. Nothing was sent.`);
207
+ const cluster = clusterOf(url);
208
+ if (source.from === "config")
209
+ throw new Error(`no payer keypair at ${shown} (keypair_path in ${source.config.replace(os.homedir(), "~")}): create it with \`solana-keygen new --outfile ${shown}\`, or pass --keypair <file>` +
210
+ (cluster ? `; fund it with \`solana airdrop 2 --keypair ${shown} --url ${cluster}\`` : "") +
211
+ ". Nothing was sent.");
212
+ throw new Error(`no payer keypair at ${shown}: create one with \`solana-keygen new\` (or pass --keypair <file>)` +
213
+ (cluster ? `, then fund it with \`solana airdrop 2 --url ${cluster}\`` : "") +
214
+ ". Nothing was sent.");
215
+ }
216
+ /** `deploy` runs `solana program deploy`: without the Solana CLI on PATH it stops before building. */
217
+ export function requireSolanaCli() {
218
+ try {
219
+ execFileSync("solana", ["--version"], { stdio: "ignore" });
220
+ }
221
+ catch (e) {
222
+ if (e.code !== "ENOENT")
223
+ return; // there, if unwell: its own run says why
224
+ throw new Error(solanaNotFound());
225
+ }
226
+ }
227
+ /** The error for a missing `solana`, with how to get it on this host. */
228
+ export function solanaNotFound(host = process) {
229
+ return `\`solana\` was not found on PATH${linuxArm64(host) ? `: ${solanaCliFix(host)}` : `. Install the Agave CLI: ${solanaCliFix(host)}`}`;
230
+ }
169
231
  /**
170
232
  * Before `solana program deploy`: the RPC answers, and the payer holds enough for the program's rent (a first deploy
171
233
  * holds about twice the binary's rent while the buffer exists; an upgrade, the buffer's). Throws with what to do.
@@ -182,9 +244,10 @@ export async function deployPreflight(opts) {
182
244
  ? "Start a local validator in another terminal: `solana-test-validator`, or deploy to devnet with --url devnet."
183
245
  : "Check --url (or json_rpc_url in the Solana CLI config); for a test deploy use --url devnet or a local `solana-test-validator`."));
184
246
  }
185
- if (!opts.payer || !existsSync(opts.payer))
186
- return; // the Solana CLI reports a missing keypair itself
187
- const payer = base58(readKeypair(opts.payer).subarray(32));
247
+ // A signer URI (a Ledger, a prompt) has no address to read here: the Solana CLI resolves it and reports a shortfall.
248
+ if (!opts.payer || isSignerUri(opts.payer) || !existsSync(keypairFile(opts.payer)))
249
+ return;
250
+ const payer = base58(readKeypair(keypairFile(opts.payer)).subarray(32));
188
251
  let need = 0;
189
252
  for (const p of opts.programs) {
190
253
  const size = statSync(p.soPath).size;
@@ -226,7 +289,7 @@ export async function doctorChecks(opts) {
226
289
  }
227
290
  checks.push(solanaVersion
228
291
  ? { ok: true, what: "Solana CLI", detail: solanaVersion }
229
- : { ok: false, optional: true, what: "Solana CLI", detail: "not on PATH (needed to deploy, not to build or test)", fix: [INSTALL_AGAVE] });
292
+ : { ok: false, optional: true, what: "Solana CLI", detail: "not on PATH (needed to deploy, not to build or test)", fix: [solanaCliFix()] });
230
293
  checks.push(dockerCheck());
231
294
  const cfg = solanaConfig(opts.config);
232
295
  const keypair = cfg.keypair ?? path.join(os.homedir(), ".config/solana/id.json");
@@ -282,7 +345,7 @@ export async function doctorChecks(opts) {
282
345
  optional: true,
283
346
  what: "RPC",
284
347
  detail: `${rpcHost(url)} does not answer (${errText(e)})`,
285
- fix: cluster === "localhost" ? ["solana-test-validator # in another terminal"] : ["pass --url devnet, or fix json_rpc_url in the Solana CLI config"],
348
+ fix: cluster === "localhost" ? ["# In another terminal:", "solana-test-validator"] : ["pass --url devnet, or fix json_rpc_url in the Solana CLI config"],
286
349
  });
287
350
  }
288
351
  }
@@ -292,6 +355,25 @@ export async function doctorChecks(opts) {
292
355
  : { ok: true, optional: true, what: "project", detail: "none here (typesol init <dir> creates one)" });
293
356
  return checks;
294
357
  }
358
+ /** The last line of `doctor`: what is ready, and what the warnings are about. */
359
+ export function doctorSummary(checks) {
360
+ const list = (cs) => cs.map((c) => c.what).join(", ");
361
+ const failed = checks.filter((c) => !c.ok && !c.optional);
362
+ if (failed.length)
363
+ return `Not ready to build or test: fix the ERR rows (${list(failed)}) first.`;
364
+ const warned = checks.filter((c) => !c.ok);
365
+ const deploy = warned.filter((c) => ["Solana CLI", "keypair", "RPC", "balance"].includes(c.what));
366
+ const notes = [];
367
+ if (deploy.length)
368
+ notes.push(`deploying still needs: ${list(deploy)}`);
369
+ if (warned.some((c) => c.what === "docker"))
370
+ notes.push("Docker is only for --docker builds");
371
+ if (warned.some((c) => c.what === "toolchain"))
372
+ notes.push("the toolchain is not the tested one (builds work; their binaries are not covered by the tests)");
373
+ if (!notes.length)
374
+ return "Ready to build, test and deploy.";
375
+ return `Ready to build and test. The ! rows: ${notes.join("; ")}.`;
376
+ }
295
377
  export function formatChecks(checks) {
296
378
  const mark = (c) => (c.ok ? "ok " : c.optional ? " ! " : "ERR");
297
379
  const width = Math.max(...checks.map((c) => c.what.length));
@@ -80,8 +80,15 @@ export declare function deployArgs(soPath: string, keypair: string, opts: {
80
80
  payer?: string;
81
81
  config?: string;
82
82
  }): string[];
83
- /** Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included). Refuses to overwrite files. */
84
- export declare function scaffold(dir: string, name: string, template?: TemplateName): string[];
83
+ /** The files `scaffold` writes for AI coding agents (left out with `agentFiles: false`, `init --no-agent-files`). */
84
+ export declare const AGENT_FILES: readonly ["AGENTS.md", "CLAUDE.md", ".cursor/rules/typesol.mdc", ".mcp.json", ".cursor/mcp.json"];
85
+ /**
86
+ * Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included)
87
+ * and, unless `agentFiles` is false, the AGENT_FILES. Refuses to overwrite files.
88
+ */
89
+ export declare function scaffold(dir: string, name: string, template?: TemplateName, opts?: {
90
+ agentFiles?: boolean;
91
+ }): string[];
85
92
  /**
86
93
  * Add a program to an existing project: programs/<name>.ts and tests/<name>.test.ts from a template, and its entry in
87
94
  * typesol.json. Returns the files written and the template's extra devDependencies the package.json lacks.
package/dist/workspace.js CHANGED
@@ -316,8 +316,13 @@ export function deployArgs(soPath, keypair, opts) {
316
316
  args.push("--keypair", opts.payer);
317
317
  return args;
318
318
  }
319
- /** Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included). Refuses to overwrite files. */
320
- export function scaffold(dir, name, template = "counter") {
319
+ /** The files `scaffold` writes for AI coding agents (left out with `agentFiles: false`, `init --no-agent-files`). */
320
+ export const AGENT_FILES = ["AGENTS.md", "CLAUDE.md", ".cursor/rules/typesol.mdc", ".mcp.json", ".cursor/mcp.json"];
321
+ /**
322
+ * Create a project: typesol.json, one program from a template, its LiteSVM test, configs (editor settings included)
323
+ * and, unless `agentFiles` is false, the AGENT_FILES. Refuses to overwrite files.
324
+ */
325
+ export function scaffold(dir, name, template = "counter", opts = {}) {
321
326
  const t = TEMPLATES[template];
322
327
  if (!/^[a-z][a-z0-9_]*$/.test(name))
323
328
  throw new Error(`program name "${name}" must be snake_case`);
@@ -358,7 +363,6 @@ export function scaffold(dir, name, template = "counter") {
358
363
  typesol: `npm:@typesol/cli@^${COMPILER_VERSION}`,
359
364
  "@types/node": "^22.0.0",
360
365
  typescript: "^6.0.3",
361
- "@anchor-lang/core": "^1.2.1",
362
366
  "@solana/kit": "^8.5.0",
363
367
  litesvm: "^1.6.1",
364
368
  vitest: "^5.0.5",
@@ -389,9 +393,14 @@ export function scaffold(dir, name, template = "counter") {
389
393
  include: ["tests/**/*.ts"],
390
394
  }, null, 2) + "\n",
391
395
  };
396
+ if (opts.agentFiles === false)
397
+ for (const f of AGENT_FILES)
398
+ delete files[f];
392
399
  const existing = Object.keys(files).filter((f) => existsSync(path.join(dir, f)));
400
+ // An agent file in the way (a repository with its own AGENTS.md): the flag that leaves them out.
401
+ const agent = existing.some((f) => AGENT_FILES.includes(f));
393
402
  if (existing.length)
394
- throw new Error(`refusing to overwrite: ${existing.join(", ")}`);
403
+ throw new Error(`refusing to overwrite: ${existing.join(", ")}${agent ? " (--no-agent-files leaves out the files for AI coding agents)" : ""}`);
395
404
  for (const [file, text] of Object.entries(files)) {
396
405
  mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
397
406
  writeFileSync(path.join(dir, file), text);