@kashdao/cli 0.1.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.
- package/CHANGELOG.md +78 -0
- package/CONTRIBUTING.md +159 -0
- package/LICENSE +21 -0
- package/README.md +868 -0
- package/SECURITY.md +110 -0
- package/dist/account-AVFLEM5D.js +90 -0
- package/dist/account-AVFLEM5D.js.map +1 -0
- package/dist/auth-GUJCVKTD.js +239 -0
- package/dist/auth-GUJCVKTD.js.map +1 -0
- package/dist/chunk-BN2CUM42.js +9 -0
- package/dist/chunk-BN2CUM42.js.map +1 -0
- package/dist/chunk-BRK7KJ4O.js +154 -0
- package/dist/chunk-BRK7KJ4O.js.map +1 -0
- package/dist/chunk-KMBMQIZ7.js +393 -0
- package/dist/chunk-KMBMQIZ7.js.map +1 -0
- package/dist/chunk-LBIRQHX5.js +133 -0
- package/dist/chunk-LBIRQHX5.js.map +1 -0
- package/dist/chunk-MIXOZU2S.js +366 -0
- package/dist/chunk-MIXOZU2S.js.map +1 -0
- package/dist/chunk-QJMF73M5.js +129 -0
- package/dist/chunk-QJMF73M5.js.map +1 -0
- package/dist/chunk-UZNSYATZ.js +680 -0
- package/dist/chunk-UZNSYATZ.js.map +1 -0
- package/dist/chunk-VIADBYFY.js +94 -0
- package/dist/chunk-VIADBYFY.js.map +1 -0
- package/dist/chunk-YHCG2SUC.js +159 -0
- package/dist/chunk-YHCG2SUC.js.map +1 -0
- package/dist/chunk-YJX3JJ4M.js +174 -0
- package/dist/chunk-YJX3JJ4M.js.map +1 -0
- package/dist/client-IOM55ZCS.js +14 -0
- package/dist/client-IOM55ZCS.js.map +1 -0
- package/dist/completion-ZZGX5BQC.js +100 -0
- package/dist/completion-ZZGX5BQC.js.map +1 -0
- package/dist/config-XJL5TSYK.js +690 -0
- package/dist/config-XJL5TSYK.js.map +1 -0
- package/dist/config-store-3ZSYGXMQ.js +44 -0
- package/dist/config-store-3ZSYGXMQ.js.map +1 -0
- package/dist/docs-MDKKSJDC.js +102 -0
- package/dist/docs-MDKKSJDC.js.map +1 -0
- package/dist/eoa-IQ72EIHR.js +551 -0
- package/dist/eoa-IQ72EIHR.js.map +1 -0
- package/dist/errors-WMZIEGQI.js +18 -0
- package/dist/errors-WMZIEGQI.js.map +1 -0
- package/dist/explain-H4EH3KH3.js +165 -0
- package/dist/explain-H4EH3KH3.js.map +1 -0
- package/dist/global-options-XOLJUPTT.js +18 -0
- package/dist/global-options-XOLJUPTT.js.map +1 -0
- package/dist/health-VZEIII74.js +98 -0
- package/dist/health-VZEIII74.js.map +1 -0
- package/dist/help-footer-GTANVDNP.js +43 -0
- package/dist/help-footer-GTANVDNP.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +251 -0
- package/dist/index.js.map +1 -0
- package/dist/intro-PQQTYWR7.js +41 -0
- package/dist/intro-PQQTYWR7.js.map +1 -0
- package/dist/markets-C37JZDPE.js +295 -0
- package/dist/markets-C37JZDPE.js.map +1 -0
- package/dist/output-VCBZ3FM7.js +22 -0
- package/dist/output-VCBZ3FM7.js.map +1 -0
- package/dist/portfolio-2AEPIJIG.js +115 -0
- package/dist/portfolio-2AEPIJIG.js.map +1 -0
- package/dist/protocol-XEQXF2GW.js +1572 -0
- package/dist/protocol-XEQXF2GW.js.map +1 -0
- package/dist/quote-I4DVJ7ZB.js +144 -0
- package/dist/quote-I4DVJ7ZB.js.map +1 -0
- package/dist/schema-PIFQ65TS.js +410 -0
- package/dist/schema-PIFQ65TS.js.map +1 -0
- package/dist/setup-USZ6IODD.js +260 -0
- package/dist/setup-USZ6IODD.js.map +1 -0
- package/dist/stdin-YW2CEQXU.js +28 -0
- package/dist/stdin-YW2CEQXU.js.map +1 -0
- package/dist/trace-IZBYTUFO.js +103 -0
- package/dist/trace-IZBYTUFO.js.map +1 -0
- package/dist/trade-IIZSEXEI.js +586 -0
- package/dist/trade-IIZSEXEI.js.map +1 -0
- package/dist/version-JDK3PEP5.js +117 -0
- package/dist/version-JDK3PEP5.js.map +1 -0
- package/dist/version-check-TDCION37.js +138 -0
- package/dist/version-check-TDCION37.js.map +1 -0
- package/dist/webhooks-PTVRKICZ.js +680 -0
- package/dist/webhooks-PTVRKICZ.js.map +1 -0
- package/dist/with-retry-4FIZG3A7.js +223 -0
- package/dist/with-retry-4FIZG3A7.js.map +1 -0
- package/package.json +99 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/formatting.ts"],"sourcesContent":["/**\n * Display formatters: tables, addresses, USDC amounts, status colors.\n *\n * Atomic USDC values from the API are integer strings (6 decimals). The\n * SDK does not assume a math library, so we format with simple integer\n * division here — the precision constraint is purely cosmetic.\n */\n\nimport Table from 'cli-table3';\n\nimport { style } from './output.js';\n\n/**\n * ASCII ellipsis used for all truncation glyphs. We use three dots\n * rather than the Unicode horizontal-ellipsis (U+2026) because the\n * latter renders as `?` on Windows cmd.exe and in restricted locales\n * — `gh`, `aws`, and `stripe` all standardise on ASCII.\n */\nconst ELLIPSIS = '...';\n\n/**\n * Code-point-safe slice. `String.prototype.slice` operates on UTF-16\n * code units, so an emoji or other surrogate pair near a boundary\n * could split. None of the inputs we slice (API keys, hex addresses,\n * UUIDs) carry surrogates today — but defensive slicing matches\n * `gh`/`aws` and the cost is negligible.\n */\nfunction codepointSlice(s: string, start: number, end?: number): string {\n return Array.from(s).slice(start, end).join('');\n}\n\nfunction codepointLength(s: string): number {\n return Array.from(s).length;\n}\n\n/** Truncate a UUID/long ID to \"abcdef12...\" for tables. */\nexport function shortId(id: string, prefix = 8): string {\n if (codepointLength(id) <= prefix + ELLIPSIS.length) return id;\n return `${codepointSlice(id, 0, prefix)}${ELLIPSIS}`;\n}\n\n/**\n * Truncate a free-form string to fit within a column. Appends an\n * ellipsis when shortened so the user sees that data was elided.\n * Different from `shortId`, which uses a leading-prefix heuristic\n * suited to UUIDs and tx hashes.\n */\nexport function truncate(s: string, max: number): string {\n return codepointLength(s) > max ? `${codepointSlice(s, 0, max - ELLIPSIS.length)}${ELLIPSIS}` : s;\n}\n\n/**\n * Redact an API key for display. Always shows enough leading\n * characters (`kash_live_` / `kash_test_` prefix) to confirm the key\n * type, plus the last four characters so users can match it to a\n * value they have on record. Inputs shorter than 8 characters are\n * masked entirely so we never accidentally leak a partial key from\n * truncated input.\n */\nexport function redact(key: string): string {\n if (codepointLength(key) <= 8) return '***';\n return `${codepointSlice(key, 0, 8)}${ELLIPSIS}${codepointSlice(key, -4)}`;\n}\n\n/** Capitalise the first letter. Empty strings pass through. */\nexport function capitalize(s: string): string {\n if (s.length === 0) return s;\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\n/** Format an EVM address as `0x1234...abcd`. */\nexport function formatAddress(address: string, lead = 6, tail = 4): string {\n if (codepointLength(address) <= lead + tail + ELLIPSIS.length) return address;\n return `${codepointSlice(address, 0, lead)}${ELLIPSIS}${codepointSlice(address, -tail)}`;\n}\n\n/** Format a UTC ISO string as a local-readable date+time. */\nexport function formatDate(value: string | Date | null | undefined): string {\n if (!value) return '-';\n const d = typeof value === 'string' ? new Date(value) : value;\n if (Number.isNaN(d.getTime())) return '-';\n return d.toLocaleString();\n}\n\n/**\n * Format a USDC value as `$1,234.56`.\n *\n * Two input shapes are accepted:\n *\n * 1. **Atomic** — bigint, integer string, or finite Number,\n * interpreted as micro-USDC (6 decimals). This is the canonical\n * shape on every API response (`totalCostBasisAtomic`,\n * `tokensOut`, etc.). Formatted with bigint math so values past\n * Number.MAX_SAFE_INTEGER round-trip exactly.\n * 2. **Decimal string** — only used by analytics endpoints that\n * return human-formatted dollar amounts (e.g. `\"1234.56\"`).\n * These pass through `Number.parseFloat`, which means values\n * with more than ~15 significant decimal digits round at IEEE-754\n * precision. This is acceptable for *display* (the underlying\n * authoritative value is always atomic), but consumers writing\n * reconciliation logic should call the upstream atomic field\n * directly rather than re-parsing a formatted decimal.\n *\n * The atomic branch rounds the cents column **toward zero** (cheaper\n * than half-even for tables; the trade engine reconciles to atomic\n * precision elsewhere). Cosmetic only.\n */\nexport function formatUsdcAtomic(atomic: string | bigint | number): string {\n if (typeof atomic === 'string' && atomic.includes('.')) {\n // Decimal-string branch (analytics only). Documented loss: values\n // > 15 significant digits round at parseFloat precision.\n const n = Number.parseFloat(atomic);\n if (Number.isNaN(n)) return '$0.00';\n return n.toLocaleString('en-US', {\n style: 'currency',\n currency: 'USD',\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n });\n }\n let big: bigint;\n try {\n big = typeof atomic === 'bigint' ? atomic : BigInt(atomic);\n } catch {\n return '$0.00';\n }\n const negative = big < 0n;\n const abs = negative ? -big : big;\n const whole = abs / 1_000_000n;\n const frac = abs % 1_000_000n;\n const wholeStr = whole.toLocaleString('en-US');\n const cents = (frac / 10_000n).toString().padStart(2, '0');\n return `${negative ? '-' : ''}$${wholeStr}.${cents}`;\n}\n\n/**\n * Format a human USDC decimal string (e.g. `'12.5'`) as `$12.50`.\n * Used when the API hands back already-decimal amounts (the trade\n * resource's `amount` field).\n */\nexport function formatUsdcDecimal(value: string): string {\n const n = Number.parseFloat(value);\n if (Number.isNaN(n)) return value;\n return n.toLocaleString('en-US', {\n style: 'currency',\n currency: 'USD',\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n });\n}\n\n/** Format a probability in [0,1] as a percentage string. */\nexport function formatProbability(p: number | null | undefined): string {\n if (p === null || p === undefined || Number.isNaN(p)) return '-';\n return `${(p * 100).toFixed(1)}%`;\n}\n\n/**\n * Generic fixed-point bigint→decimal-display formatter. Used by every\n * CLI helper that needs to render an atomic-units bigint (WAD-18,\n * gwei-9, ETH-18, USDC-6) as a human-readable decimal string.\n *\n * Two parameters control shape:\n *\n * - `baseDecimals` — the unit's atomic precision (18 for WAD/ETH,\n * 9 for gwei, 6 for USDC).\n * - `displayDecimals` — how many fractional digits to emit. Must\n * be ≤ `baseDecimals`. Truncates rather than rounds — display\n * only, `--json` preserves the full atomic-string precision.\n *\n * Sign is extracted before the magnitude split so `-` rendering\n * lives at one site. The whole part is rendered with thousand-\n * separator commas via `toLocaleString` (consistent with\n * `formatUsdcAtomic`); call sites that need the raw integer-shape\n * (e.g. `formatGwei`'s historical \"no commas\" form) opt out via\n * `thousandSeparator: false`.\n *\n * Accepts `string | bigint` for the same reason `formatWad` did:\n * direct-mode SDKs return `bigint`, indexer-backed views return\n * integer-string. The `try/catch` around `BigInt(value)` is the\n * defensive never-throw guarantee on display paths — a malformed\n * input falls through to the input itself rather than crashing.\n */\nexport function formatBigDecimal(\n value: string | bigint,\n options: { baseDecimals: number; displayDecimals: number; thousandSeparator?: boolean }\n): string {\n const { baseDecimals, displayDecimals } = options;\n const useThousandSeparator = options.thousandSeparator ?? true;\n let big: bigint;\n try {\n big = typeof value === 'bigint' ? value : BigInt(value);\n } catch {\n return typeof value === 'string' ? value : '0';\n }\n const negative = big < 0n;\n const abs = negative ? -big : big;\n const baseScale = 10n ** BigInt(baseDecimals);\n const whole = abs / baseScale;\n const frac = abs % baseScale;\n const truncated = (frac / 10n ** BigInt(baseDecimals - displayDecimals))\n .toString()\n .padStart(displayDecimals, '0');\n const wholeStr = useThousandSeparator ? whole.toLocaleString('en-US') : whole.toString();\n return `${negative ? '-' : ''}${wholeStr}.${truncated}`;\n}\n\n/**\n * Format a WAD-18 (1e18) value as a 4-decimal token display string.\n * Twin of `formatUsdcAtomic` but for outcome-token quantities.\n * Direct-mode SDK returns bigint; indexer-backed views return string.\n */\nexport function formatWad(wad: string | bigint): string {\n return formatBigDecimal(wad, { baseDecimals: 18, displayDecimals: 4 });\n}\n\n/**\n * Format a wei bigint as a 3-decimal gwei display string. Used by\n * direct-mode commands that emit gas balances and fee estimates.\n * Truncates rather than rounds — fees are display-only and operators\n * who need exact wei should use `--json` (which preserves the bigint\n * as a decimal string).\n *\n * No thousand-separator on the whole part: the gwei convention in\n * the broader EVM ecosystem (etherscan, foundry, viem's display\n * helpers) renders bare integers, and operators piping our output\n * through `awk '{print $2 + 0}'` or similar rely on it.\n */\nexport function formatGwei(wei: bigint): string {\n return formatBigDecimal(wei, {\n baseDecimals: 9,\n displayDecimals: 3,\n thousandSeparator: false,\n });\n}\n\n/** Apply a status color (green/yellow/red/blue/gray) by status string. */\nexport function colorStatus(value: string | null | undefined): string {\n if (!value) return style.dim('-');\n switch (value.toUpperCase()) {\n case 'ACTIVE':\n case 'COMPLETED':\n return style.success(value);\n case 'EXECUTING':\n case 'VALIDATING':\n case 'PENDING':\n return style.cyan(value);\n case 'PENDING_CONFIRMATION':\n return style.warn(value);\n case 'RESOLVED':\n return style.info(value);\n case 'REJECTED':\n case 'FAILED':\n return style.error(value);\n case 'UNSEEDED':\n case 'FROZEN':\n return style.dim(value);\n default:\n return value;\n }\n}\n\n/** Build a cli-table3 with bold headers and consistent style. */\nexport function createTable(headers: string[]): Table.Table {\n return new Table({\n head: headers.map((h) => style.bold(h)),\n style: { head: [], border: [] },\n });\n}\n"],"mappings":";;;;;;AAQA,OAAO,WAAW;AAUlB,IAAM,WAAW;AASjB,SAAS,eAAe,GAAW,OAAe,KAAsB;AACtE,SAAO,MAAM,KAAK,CAAC,EAAE,MAAM,OAAO,GAAG,EAAE,KAAK,EAAE;AAChD;AAEA,SAAS,gBAAgB,GAAmB;AAC1C,SAAO,MAAM,KAAK,CAAC,EAAE;AACvB;AAGO,SAAS,QAAQ,IAAY,SAAS,GAAW;AACtD,MAAI,gBAAgB,EAAE,KAAK,SAAS,SAAS,OAAQ,QAAO;AAC5D,SAAO,GAAG,eAAe,IAAI,GAAG,MAAM,CAAC,GAAG,QAAQ;AACpD;AAQO,SAAS,SAAS,GAAW,KAAqB;AACvD,SAAO,gBAAgB,CAAC,IAAI,MAAM,GAAG,eAAe,GAAG,GAAG,MAAM,SAAS,MAAM,CAAC,GAAG,QAAQ,KAAK;AAClG;AAUO,SAAS,OAAO,KAAqB;AAC1C,MAAI,gBAAgB,GAAG,KAAK,EAAG,QAAO;AACtC,SAAO,GAAG,eAAe,KAAK,GAAG,CAAC,CAAC,GAAG,QAAQ,GAAG,eAAe,K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AAmB;AAAA,EACrB,CAAC;AACH;AAGO,SAAS,YAAY,OAA0C;AACpE,MAAI,CAAC,MAAO,QAAO,MAAM,IAAI,GAAG;AAChC,UAAQ,MAAM,YAAY,GAAG;AAAA,IAC3B,KAAK;AAAA,IACL,KAAK;AACH,aAAO,MAAM,QAAQ,KAAK;AAAA,IAC5B,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,MAAM,KAAK,KAAK;AAAA,IACzB,KAAK;AACH,aAAO,MAAM,KAAK,KAAK;AAAA,IACzB,KAAK;AACH,aAAO,MAAM,KAAK,KAAK;AAAA,IACzB,KAAK;AAAA,IACL,KAAK;AACH,aAAO,MAAM,MAAM,KAAK;AAAA,IAC1B,KAAK;AAAA,IACL,KAAK;AACH,aAAO,MAAM,IAAI,KAAK;AAAA,IACxB;AACE,aAAO;AAAA,EACX;AACF;AAGO,SAAS,YAAY,SAAgC;AAC1D,SAAO,IAAI,MAAM;AAAA,IACf,MAAM,QAAQ,IAAI,CAAC,MAAM,MAAM,KAAK,CAAC,CAAC;AAAA,IACtC,OAAO,EAAE,MAAM,CAAC,GAAG,QAAQ,CAAC,EAAE;AAAA,EAChC,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
HEX_ADDRESS_REGEX
|
|
4
|
+
} from "./chunk-YHCG2SUC.js";
|
|
5
|
+
import {
|
|
6
|
+
CliConfigurationError
|
|
7
|
+
} from "./chunk-UZNSYATZ.js";
|
|
8
|
+
|
|
9
|
+
// src/utils/config-store.ts
|
|
10
|
+
import { existsSync } from "fs";
|
|
11
|
+
import { chmod, mkdir, readFile, unlink, writeFile } from "fs/promises";
|
|
12
|
+
import { homedir } from "os";
|
|
13
|
+
import { dirname, join } from "path";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
function omitKey(obj, key) {
|
|
16
|
+
const result = {};
|
|
17
|
+
for (const k of Object.keys(obj)) {
|
|
18
|
+
if (k !== key) result[k] = obj[k];
|
|
19
|
+
}
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
function resolveConfigPaths(home = homedir()) {
|
|
23
|
+
const dir = join(home, ".kash");
|
|
24
|
+
return { home, dir, file: join(dir, "config.json") };
|
|
25
|
+
}
|
|
26
|
+
function resolveConfigPathsForOverride(override, envOverride = process.env["KASH_CONFIG"]) {
|
|
27
|
+
const explicit = override ?? envOverride;
|
|
28
|
+
if (explicit) {
|
|
29
|
+
const dir = dirname(explicit);
|
|
30
|
+
return { home: dirname(dir), dir, file: explicit };
|
|
31
|
+
}
|
|
32
|
+
return resolveConfigPaths();
|
|
33
|
+
}
|
|
34
|
+
var DEFAULT_PROFILE = "default";
|
|
35
|
+
var RESERVED_PROFILE_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
36
|
+
var profileNameSchema = z.string().min(1, "profile name cannot be empty").max(64, "profile name must be \u2264 64 characters").regex(/^[A-Za-z0-9_.-]+$/, "profile name allows letters, digits, underscore, dot, and dash only").refine((name) => !RESERVED_PROFILE_NAMES.has(name), {
|
|
37
|
+
message: "profile name uses a reserved word (__proto__, constructor, prototype) \u2014 would walk the object prototype chain"
|
|
38
|
+
});
|
|
39
|
+
var signerKeyRefSchema = z.string().regex(/^(file:|env:)\S+$/, 'signerKeyRef must start with "file:<path>" or "env:<NAME>"');
|
|
40
|
+
var bundlerProviderSchema = z.enum(["flashbots", "pimlico", "alchemy", "generic"]);
|
|
41
|
+
var hexAddressSchema = z.string().regex(HEX_ADDRESS_REGEX, "must be a 0x-prefixed 40-char hex address");
|
|
42
|
+
var customChainSchema = z.object({
|
|
43
|
+
/** Human-readable label, surfaced on `client.addresses.name`. */
|
|
44
|
+
name: z.string().min(1, "customChain.name must not be empty").optional(),
|
|
45
|
+
factoryAddress: hexAddressSchema.optional(),
|
|
46
|
+
usdcAddress: hexAddressSchema.optional(),
|
|
47
|
+
oracleAddress: hexAddressSchema.optional(),
|
|
48
|
+
vaultAddress: hexAddressSchema.optional(),
|
|
49
|
+
tokens1155Address: hexAddressSchema.optional(),
|
|
50
|
+
paramRegistryAddress: hexAddressSchema.optional(),
|
|
51
|
+
/** Smart-account factory + EntryPoint config (SA mode only). */
|
|
52
|
+
smartAccount: z.object({
|
|
53
|
+
factoryAddress: hexAddressSchema.optional(),
|
|
54
|
+
implementationAddress: hexAddressSchema.optional(),
|
|
55
|
+
entryPointAddress: hexAddressSchema.optional()
|
|
56
|
+
}).strict().optional()
|
|
57
|
+
}).strict();
|
|
58
|
+
var cliConfigSchema = z.object({
|
|
59
|
+
// ── Kash-orchestrated mode (API-backed) ─────────────────────────────
|
|
60
|
+
apiKey: z.string().startsWith("kash_", 'API keys start with "kash_"').min(16, "API key looks too short").optional(),
|
|
61
|
+
baseUrl: z.string().url("baseUrl must be a valid URL").optional(),
|
|
62
|
+
defaultChainId: z.number().int().positive().optional(),
|
|
63
|
+
// ── Direct mode (`kash protocol …`, on-chain) ───────────────
|
|
64
|
+
/** RPC endpoint for the chain. Consumer-owned; the CLI never proxies. */
|
|
65
|
+
rpcUrl: z.string().url("rpcUrl must be a valid URL").optional(),
|
|
66
|
+
/** Smart account address (the ERC-4337 account whose funds are used). */
|
|
67
|
+
smartAccount: z.string().regex(HEX_ADDRESS_REGEX, "smartAccount must be a 0x-prefixed 40-char hex address").optional(),
|
|
68
|
+
/** Bundler URL (overrides the protocol-sdk's Flashbots Protect default). */
|
|
69
|
+
bundlerUrl: z.string().url("bundlerUrl must be a valid URL").optional(),
|
|
70
|
+
/** Bundler provider preset (selects the right header dialect). */
|
|
71
|
+
bundlerProvider: bundlerProviderSchema.optional(),
|
|
72
|
+
/** Reference to the EOA private key that owns the smart account. */
|
|
73
|
+
signerKeyRef: signerKeyRefSchema.optional(),
|
|
74
|
+
/**
|
|
75
|
+
* Custom-chain addresses for chains outside the static registry
|
|
76
|
+
* (local Anvil, forks, sidechains). When present, the CLI's
|
|
77
|
+
* direct-mode and EOA-mode commands use these addresses instead
|
|
78
|
+
* of looking the chain up in the registry. Required for chainId
|
|
79
|
+
* 31337 (Anvil); optional for Base mainnet/testnet (registry covers them).
|
|
80
|
+
*/
|
|
81
|
+
customChain: customChainSchema.optional()
|
|
82
|
+
}).strict();
|
|
83
|
+
var cliFileSchema = z.object({
|
|
84
|
+
version: z.literal(1),
|
|
85
|
+
currentProfile: profileNameSchema.optional(),
|
|
86
|
+
profiles: z.record(profileNameSchema, cliConfigSchema).default({})
|
|
87
|
+
}).strict();
|
|
88
|
+
var PRODUCTION_BASE_URL = "https://api.kash.bot/v1";
|
|
89
|
+
var STAGING_BASE_URL = "https://api-staging.kash.bot/v1";
|
|
90
|
+
function inferBaseUrlFromApiKey(apiKey) {
|
|
91
|
+
if (!apiKey) return void 0;
|
|
92
|
+
if (apiKey.startsWith("kash_test_")) return STAGING_BASE_URL;
|
|
93
|
+
if (apiKey.startsWith("kash_live_")) return PRODUCTION_BASE_URL;
|
|
94
|
+
return void 0;
|
|
95
|
+
}
|
|
96
|
+
var DEFAULTS = {
|
|
97
|
+
baseUrl: PRODUCTION_BASE_URL,
|
|
98
|
+
defaultChainId: 8453
|
|
99
|
+
};
|
|
100
|
+
async function readConfig(opts = {}) {
|
|
101
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
102
|
+
const file = await readFileConfig(paths);
|
|
103
|
+
return resolveActive(file, opts.profile);
|
|
104
|
+
}
|
|
105
|
+
async function readFileConfig(paths) {
|
|
106
|
+
if (!existsSync(paths.file)) return emptyFile();
|
|
107
|
+
let raw;
|
|
108
|
+
try {
|
|
109
|
+
raw = await readFile(paths.file, "utf8");
|
|
110
|
+
} catch (cause) {
|
|
111
|
+
throw new CliConfigurationError(
|
|
112
|
+
`Failed to read config file at ${paths.file}: ${cause.message}`,
|
|
113
|
+
"Run 'kash config reset' to start fresh."
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
return parseFileContents(raw, paths.file);
|
|
117
|
+
}
|
|
118
|
+
function parseFileContents(raw, file) {
|
|
119
|
+
let parsed;
|
|
120
|
+
try {
|
|
121
|
+
parsed = JSON.parse(raw);
|
|
122
|
+
} catch (cause) {
|
|
123
|
+
throw new CliConfigurationError(
|
|
124
|
+
`Config file at ${file} is not valid JSON: ${cause.message}`,
|
|
125
|
+
"Run 'kash config reset' to overwrite it with defaults."
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
129
|
+
throw new CliConfigurationError(
|
|
130
|
+
`Config file at ${file} must contain a JSON object at the top level (got ${describeJsonRoot(parsed)}).`,
|
|
131
|
+
"Run 'kash config reset' to overwrite it with defaults."
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
const migrated = migrateLegacyShape(parsed);
|
|
135
|
+
const result = cliFileSchema.safeParse(migrated);
|
|
136
|
+
if (!result.success) {
|
|
137
|
+
const first = result.error.issues[0];
|
|
138
|
+
const path = first?.path.join(".") ?? "(root)";
|
|
139
|
+
throw new CliConfigurationError(
|
|
140
|
+
`Config file at ${file} is invalid (${path}): ${first?.message ?? "validation failed"}`,
|
|
141
|
+
"Run 'kash config reset' to overwrite it with defaults."
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
return result.data;
|
|
145
|
+
}
|
|
146
|
+
function describeJsonRoot(value) {
|
|
147
|
+
if (value === null) return "null";
|
|
148
|
+
if (Array.isArray(value)) return "array";
|
|
149
|
+
return typeof value;
|
|
150
|
+
}
|
|
151
|
+
function migrateLegacyShape(parsed) {
|
|
152
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
153
|
+
return parsed;
|
|
154
|
+
}
|
|
155
|
+
const obj = parsed;
|
|
156
|
+
if ("version" in obj || "profiles" in obj) {
|
|
157
|
+
return parsed;
|
|
158
|
+
}
|
|
159
|
+
const flat = cliConfigSchema.safeParse(obj);
|
|
160
|
+
if (!flat.success) {
|
|
161
|
+
return parsed;
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
version: 1,
|
|
165
|
+
currentProfile: DEFAULT_PROFILE,
|
|
166
|
+
profiles: { [DEFAULT_PROFILE]: flat.data }
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function emptyFile() {
|
|
170
|
+
return cliFileSchema.parse({ version: 1 });
|
|
171
|
+
}
|
|
172
|
+
function pickProfileName(file, flagOverride) {
|
|
173
|
+
if (flagOverride !== void 0) {
|
|
174
|
+
validateProfileName(flagOverride, "--profile flag");
|
|
175
|
+
return { name: flagOverride, source: "flag" };
|
|
176
|
+
}
|
|
177
|
+
const env = process.env["KASH_PROFILE"];
|
|
178
|
+
if (env !== void 0 && env.length > 0) {
|
|
179
|
+
validateProfileName(env, "KASH_PROFILE environment variable");
|
|
180
|
+
return { name: env, source: "env" };
|
|
181
|
+
}
|
|
182
|
+
if (file.currentProfile !== void 0) {
|
|
183
|
+
return { name: file.currentProfile, source: "file" };
|
|
184
|
+
}
|
|
185
|
+
return { name: DEFAULT_PROFILE, source: "default" };
|
|
186
|
+
}
|
|
187
|
+
function validateProfileName(value, source) {
|
|
188
|
+
const result = profileNameSchema.safeParse(value);
|
|
189
|
+
if (!result.success) {
|
|
190
|
+
const issue = result.error.issues[0];
|
|
191
|
+
throw new CliConfigurationError(
|
|
192
|
+
`Profile name from ${source} is invalid: ${issue?.message ?? "validation failed"}.`,
|
|
193
|
+
"Profile names accept letters, digits, underscore, dot, and dash; must be 1-64 characters."
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
function resolveActive(file, flagOverride) {
|
|
198
|
+
const { name: profileName, source: profileSource } = pickProfileName(file, flagOverride);
|
|
199
|
+
const profile = file.profiles[profileName];
|
|
200
|
+
if (profile === void 0 && (profileSource === "env" || profileSource === "flag") && Object.keys(file.profiles).length > 0 && !isTruthyEnv(process.env["KASH_QUIET"])) {
|
|
201
|
+
const known = Object.keys(file.profiles).sort().join(", ");
|
|
202
|
+
const sourceLabel = profileSource === "env" ? "KASH_PROFILE" : "--profile";
|
|
203
|
+
process.stderr.write(
|
|
204
|
+
`\u26A0 Profile "${profileName}" (${sourceLabel}) is not in the config file. Known profiles: ${known}. Did you typo the name? (Set KASH_QUIET=1 to mute this warning.)
|
|
205
|
+
`
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
return mergeWithEnv(profile ?? {}, profileName, profileSource);
|
|
209
|
+
}
|
|
210
|
+
function isTruthyEnv(value) {
|
|
211
|
+
if (value === void 0) return false;
|
|
212
|
+
const v = value.trim().toLowerCase();
|
|
213
|
+
return v === "1" || v === "true" || v === "yes" || v === "on";
|
|
214
|
+
}
|
|
215
|
+
function mergeWithEnv(profile, profileName, profileSource) {
|
|
216
|
+
const envApiKey = process.env["KASH_API_KEY"];
|
|
217
|
+
const envBaseUrl = process.env["KASH_BASE_URL"];
|
|
218
|
+
const envChainIdRaw = process.env["KASH_CHAIN_ID"];
|
|
219
|
+
const envRpcUrl = process.env["KASH_RPC_URL"];
|
|
220
|
+
const envSmartAccount = process.env["KASH_SMART_ACCOUNT"];
|
|
221
|
+
const envBundlerUrl = process.env["KASH_BUNDLER_URL"];
|
|
222
|
+
const envBundlerProviderRaw = process.env["KASH_BUNDLER_PROVIDER"];
|
|
223
|
+
const envSignerKeyRef = process.env["KASH_SIGNER_KEY_REF"];
|
|
224
|
+
let envChainId;
|
|
225
|
+
if (envChainIdRaw !== void 0) {
|
|
226
|
+
const n = Number.parseInt(envChainIdRaw, 10);
|
|
227
|
+
if (Number.isNaN(n) || n <= 0) {
|
|
228
|
+
throw new CliConfigurationError(
|
|
229
|
+
`KASH_CHAIN_ID is not a positive integer: ${envChainIdRaw}`,
|
|
230
|
+
"Set KASH_CHAIN_ID to a chain id like 8453 or 84532, or unset it to use the default."
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
envChainId = n;
|
|
234
|
+
}
|
|
235
|
+
let envBundlerProvider;
|
|
236
|
+
if (envBundlerProviderRaw !== void 0) {
|
|
237
|
+
const allowed = ["flashbots", "pimlico", "alchemy", "generic"];
|
|
238
|
+
if (!allowed.includes(envBundlerProviderRaw)) {
|
|
239
|
+
throw new CliConfigurationError(
|
|
240
|
+
`KASH_BUNDLER_PROVIDER must be one of ${allowed.join(", ")} (got "${envBundlerProviderRaw}").`,
|
|
241
|
+
"Unset the variable or set it to a supported preset."
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
envBundlerProvider = envBundlerProviderRaw;
|
|
245
|
+
}
|
|
246
|
+
const apiKey = envApiKey ?? profile.apiKey;
|
|
247
|
+
const baseUrl = envBaseUrl ?? profile.baseUrl ?? inferBaseUrlFromApiKey(apiKey) ?? DEFAULTS.baseUrl;
|
|
248
|
+
const defaultChainId = envChainId ?? profile.defaultChainId ?? DEFAULTS.defaultChainId;
|
|
249
|
+
const rpcUrl = envRpcUrl ?? profile.rpcUrl;
|
|
250
|
+
const smartAccount = envSmartAccount ?? profile.smartAccount;
|
|
251
|
+
const bundlerUrl = envBundlerUrl ?? profile.bundlerUrl;
|
|
252
|
+
const bundlerProvider = envBundlerProvider ?? profile.bundlerProvider;
|
|
253
|
+
const signerKeyRef = envSignerKeyRef ?? profile.signerKeyRef;
|
|
254
|
+
const customChain = profile.customChain;
|
|
255
|
+
return {
|
|
256
|
+
apiKey,
|
|
257
|
+
baseUrl,
|
|
258
|
+
defaultChainId,
|
|
259
|
+
rpcUrl,
|
|
260
|
+
smartAccount,
|
|
261
|
+
bundlerUrl,
|
|
262
|
+
bundlerProvider,
|
|
263
|
+
signerKeyRef,
|
|
264
|
+
customChain,
|
|
265
|
+
profile: profileName,
|
|
266
|
+
sources: {
|
|
267
|
+
apiKey: envApiKey ? "env" : profile.apiKey ? "file" : "unset",
|
|
268
|
+
baseUrl: envBaseUrl ? "env" : profile.baseUrl ? "file" : inferBaseUrlFromApiKey(apiKey) ? "inferred" : "default",
|
|
269
|
+
defaultChainId: envChainId !== void 0 ? "env" : profile.defaultChainId !== void 0 ? "file" : "default",
|
|
270
|
+
profile: profileSource,
|
|
271
|
+
rpcUrl: envRpcUrl ? "env" : profile.rpcUrl ? "file" : "unset",
|
|
272
|
+
smartAccount: envSmartAccount ? "env" : profile.smartAccount ? "file" : "unset",
|
|
273
|
+
bundlerUrl: envBundlerUrl ? "env" : profile.bundlerUrl ? "file" : "unset",
|
|
274
|
+
bundlerProvider: envBundlerProvider ? "env" : profile.bundlerProvider ? "file" : "unset",
|
|
275
|
+
signerKeyRef: envSignerKeyRef ? "env" : profile.signerKeyRef ? "file" : "unset",
|
|
276
|
+
customChain: profile.customChain ? "file" : "unset"
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
async function updateConfig(patch, opts = {}) {
|
|
281
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
282
|
+
const file = await readFileConfig(paths);
|
|
283
|
+
const profileName = opts.profile ?? file.currentProfile ?? DEFAULT_PROFILE;
|
|
284
|
+
profileNameSchema.parse(profileName);
|
|
285
|
+
const current = file.profiles[profileName] ?? {};
|
|
286
|
+
const next = cliConfigSchema.parse({ ...current, ...patch });
|
|
287
|
+
const updated = {
|
|
288
|
+
...file,
|
|
289
|
+
profiles: { ...file.profiles, [profileName]: next }
|
|
290
|
+
};
|
|
291
|
+
await writeFileConfig(paths, updated);
|
|
292
|
+
return { profile: profileName, stored: next };
|
|
293
|
+
}
|
|
294
|
+
async function clearConfigField(field, opts = {}) {
|
|
295
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
296
|
+
const file = await readFileConfig(paths);
|
|
297
|
+
const profileName = opts.profile ?? file.currentProfile ?? DEFAULT_PROFILE;
|
|
298
|
+
const current = file.profiles[profileName] ?? {};
|
|
299
|
+
if (!(field in current)) return { profile: profileName, stored: current };
|
|
300
|
+
const next = cliConfigSchema.parse(omitKey(current, field));
|
|
301
|
+
const updated = {
|
|
302
|
+
...file,
|
|
303
|
+
profiles: { ...file.profiles, [profileName]: next }
|
|
304
|
+
};
|
|
305
|
+
await writeFileConfig(paths, updated);
|
|
306
|
+
return { profile: profileName, stored: next };
|
|
307
|
+
}
|
|
308
|
+
async function listProfiles(opts = {}) {
|
|
309
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
310
|
+
const file = await readFileConfig(paths);
|
|
311
|
+
return {
|
|
312
|
+
current: file.currentProfile ?? DEFAULT_PROFILE,
|
|
313
|
+
profiles: Object.keys(file.profiles).sort()
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
async function setCurrentProfile(name, opts = {}) {
|
|
317
|
+
profileNameSchema.parse(name);
|
|
318
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
319
|
+
const file = await readFileConfig(paths);
|
|
320
|
+
const updated = { ...file, currentProfile: name };
|
|
321
|
+
await writeFileConfig(paths, updated);
|
|
322
|
+
return updated;
|
|
323
|
+
}
|
|
324
|
+
async function deleteProfile(name, opts = {}) {
|
|
325
|
+
profileNameSchema.parse(name);
|
|
326
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
327
|
+
const file = await readFileConfig(paths);
|
|
328
|
+
if (file.currentProfile === name) {
|
|
329
|
+
throw new CliConfigurationError(
|
|
330
|
+
`Cannot delete the active profile "${name}".`,
|
|
331
|
+
"Switch to another profile first with `kash config use <name>`."
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
if (!(name in file.profiles)) {
|
|
335
|
+
return file;
|
|
336
|
+
}
|
|
337
|
+
const updated = { ...file, profiles: omitKey(file.profiles, name) };
|
|
338
|
+
await writeFileConfig(paths, updated);
|
|
339
|
+
return updated;
|
|
340
|
+
}
|
|
341
|
+
async function deleteConfig(opts = {}) {
|
|
342
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
343
|
+
if (!existsSync(paths.file)) return;
|
|
344
|
+
await unlink(paths.file);
|
|
345
|
+
}
|
|
346
|
+
async function readWholeFile(opts = {}) {
|
|
347
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
348
|
+
return await readFileConfig(paths);
|
|
349
|
+
}
|
|
350
|
+
async function writeWholeFile(file, opts = {}) {
|
|
351
|
+
const paths = resolveConfigPathsForOverride(opts.configPath);
|
|
352
|
+
const validated = cliFileSchema.parse(file);
|
|
353
|
+
await writeFileConfig(paths, validated);
|
|
354
|
+
}
|
|
355
|
+
async function writeFileConfig(paths, file) {
|
|
356
|
+
await ensureDir(paths.dir);
|
|
357
|
+
await writeFile(paths.file, JSON.stringify(file, null, 2), "utf8");
|
|
358
|
+
await chmodSafe(paths.file, 384);
|
|
359
|
+
}
|
|
360
|
+
async function ensureDir(dir) {
|
|
361
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
362
|
+
await chmodSafe(dir, 448);
|
|
363
|
+
}
|
|
364
|
+
async function chmodSafe(target, mode) {
|
|
365
|
+
if (mode === void 0) return;
|
|
366
|
+
if (process.platform === "win32") return;
|
|
367
|
+
try {
|
|
368
|
+
await chmod(target, mode);
|
|
369
|
+
} catch {
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export {
|
|
374
|
+
resolveConfigPaths,
|
|
375
|
+
resolveConfigPathsForOverride,
|
|
376
|
+
DEFAULT_PROFILE,
|
|
377
|
+
cliConfigSchema,
|
|
378
|
+
cliFileSchema,
|
|
379
|
+
PRODUCTION_BASE_URL,
|
|
380
|
+
STAGING_BASE_URL,
|
|
381
|
+
inferBaseUrlFromApiKey,
|
|
382
|
+
DEFAULTS,
|
|
383
|
+
readConfig,
|
|
384
|
+
updateConfig,
|
|
385
|
+
clearConfigField,
|
|
386
|
+
listProfiles,
|
|
387
|
+
setCurrentProfile,
|
|
388
|
+
deleteProfile,
|
|
389
|
+
deleteConfig,
|
|
390
|
+
readWholeFile,
|
|
391
|
+
writeWholeFile
|
|
392
|
+
};
|
|
393
|
+
//# sourceMappingURL=chunk-KMBMQIZ7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/config-store.ts"],"sourcesContent":["/**\n * Persistent CLI configuration with multi-profile support.\n *\n * The on-disk shape (v1+):\n *\n * {\n * \"version\": 1,\n * \"currentProfile\": \"default\",\n * \"profiles\": {\n * \"default\": { \"apiKey\": \"kash_live_…\", \"baseUrl\": \"…\", \"defaultChainId\": 8453 },\n * \"test\": { \"apiKey\": \"kash_test_…\" }\n * }\n * }\n *\n * Flat-shape configs from earlier CLI versions are migrated transparently\n * on first read into a `default` profile. The on-disk file is rewritten\n * in the new shape only on the next write — readers don't mutate state.\n *\n * The file is created and re-written at mode `0600` on POSIX. The\n * directory is created with `0700`. chmod is best-effort — Windows and\n * some network filesystems silently ignore it.\n *\n * Resolution order (highest precedence first):\n *\n * 1. Environment variables: `KASH_API_KEY`, `KASH_BASE_URL`,\n * `KASH_CHAIN_ID`. Always win.\n * 2. The active profile's fields.\n * 3. Built-in defaults (api.kash.bot/v1, chain 8453).\n *\n * Active-profile resolution (highest precedence first):\n *\n * 1. Explicit `--profile <name>` flag (via `options.profile`).\n * 2. `KASH_PROFILE` env var.\n * 3. `currentProfile` field in the config file.\n * 4. `'default'`.\n *\n * Pinning env-var precedence makes CI runs predictable and lets a\n * human override a profile field without editing the file.\n */\n\nimport { existsSync } from 'node:fs';\nimport { chmod, mkdir, readFile, unlink, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nimport { z } from 'zod';\n\nimport { CliConfigurationError } from '../errors.js';\n\nimport { HEX_ADDRESS_REGEX } from './trade-input.js';\n\n/**\n * Return a shallow copy of `obj` without the named property. Cleaner\n * than the `const { [k]: _removed, ...rest } = obj` rest-spread idiom\n * because it avoids the unused-variable lint dance.\n */\nfunction omitKey<T extends Record<string, unknown>, K extends keyof T>(obj: T, key: K): Omit<T, K> {\n const result: Record<string, unknown> = {};\n for (const k of Object.keys(obj)) {\n if (k !== key) result[k] = obj[k];\n }\n return result as Omit<T, K>;\n}\n\n/** Filesystem layout for the config — exposed for tests to override `home`. */\nexport type ConfigPaths = {\n readonly home: string;\n readonly dir: string;\n readonly file: string;\n};\n\nexport function resolveConfigPaths(home: string = homedir()): ConfigPaths {\n const dir = join(home, '.kash');\n return { home, dir, file: join(dir, 'config.json') };\n}\n\n/**\n * Resolve config paths with an optional explicit override path\n * (typically from the `--config` flag or `KASH_CONFIG` env var). The\n * explicit override sets the file directly and derives `dir`/`home`\n * from it for chmod-on-write.\n */\nexport function resolveConfigPathsForOverride(\n override: string | undefined,\n envOverride: string | undefined = process.env['KASH_CONFIG']\n): ConfigPaths {\n const explicit = override ?? envOverride;\n if (explicit) {\n const dir = dirname(explicit);\n return { home: dirname(dir), dir, file: explicit };\n }\n return resolveConfigPaths();\n}\n\nexport const DEFAULT_PROFILE = 'default';\n\n/**\n * Profile-name reserved words. Even though the regex below already\n * blocks the most-dangerous shapes (no `[`, no `<`, no whitespace),\n * the `__proto__` / `constructor` / `prototype` strings ARE allowed\n * by `[A-Za-z0-9_.-]+` — and using them as keys on a plain object\n * (`file.profiles`) walks the prototype chain on read. The denylist\n * makes the prototype-walk impossible at the schema layer.\n *\n * Defence-in-depth: the file format already uses `Object.create(null)`\n * boundaries downstream where possible, but pinning the validator\n * here makes the invariant grep-discoverable.\n */\nconst RESERVED_PROFILE_NAMES = new Set(['__proto__', 'constructor', 'prototype']);\n\n/** Profile name validator — keeps file structure deterministic. */\nconst profileNameSchema = z\n .string()\n .min(1, 'profile name cannot be empty')\n .max(64, 'profile name must be ≤ 64 characters')\n .regex(/^[A-Za-z0-9_.-]+$/, 'profile name allows letters, digits, underscore, dot, and dash only')\n .refine((name) => !RESERVED_PROFILE_NAMES.has(name), {\n message:\n 'profile name uses a reserved word (__proto__, constructor, prototype) — would walk the object prototype chain',\n });\n\n/**\n * Schema for a single profile. Every field is optional so the profile\n * can hold partial state — e.g. only override `baseUrl` while\n * inheriting the API key from env.\n */\n/**\n * Reference to a private key the CLI will load when constructing the\n * direct-mode signer. We never persist the raw key — only a reference\n * to where to read it from at invocation time:\n *\n * - `file:<path>` — read the key from a file (mode 0600 enforced\n * at read time, not write).\n * - `env:<name>` — read the key from an environment variable.\n *\n * This keeps `~/.kash/config.json` free of secret material; the\n * config file itself is only `0600`-protected for the API key, not\n * for arbitrary private keys that could fund-drain a smart account.\n *\n * Future extensions: `keystore:<path>`, `aws-kms:<key-id>`,\n * `gcp-kms:<resource>`, `ledger:<derivation-path>`.\n */\nconst signerKeyRefSchema = z\n .string()\n .regex(/^(file:|env:)\\S+$/, 'signerKeyRef must start with \"file:<path>\" or \"env:<NAME>\"');\n\n/** Bundler provider preset. */\nconst bundlerProviderSchema = z.enum(['flashbots', 'pimlico', 'alchemy', 'generic']);\n\nconst hexAddressSchema = z\n .string()\n .regex(HEX_ADDRESS_REGEX, 'must be a 0x-prefixed 40-char hex address');\n\n/**\n * Custom-chain config — bypasses the protocol-sdk's static chain\n * registry. Required for any chain Kash hasn't deployed canonical\n * contracts on (local Anvil, Hardhat, Tenderly forks, sidechains).\n *\n * The CLI derives the `viemChain` argument the SDK needs from the\n * profile's `defaultChainId` + `rpcUrl` + `customChain.name`; the\n * consumer never has to hand-construct a viem Chain. `addresses`\n * mirrors the SDK's `CustomChainAddresses`. `smartAccount` is required\n * only when the consumer is using SA mode (`kash protocol …`) on a\n * custom chain — EOA mode ignores it.\n */\n/**\n * Custom-chain schema. Every field is optional at the persistence\n * layer because `kash config set customChain.<leaf>` writes one leaf\n * at a time — requiring the full shape at write time would force the\n * user into a single mega-set call. Completeness (name +\n * factoryAddress + usdcAddress required, smartAccount triple all-or-\n * nothing) is enforced at use time in `resolveCliCustomChain`,\n * where the missing field has actionable error context (the SDK call\n * that needs it).\n */\nconst customChainSchema = z\n .object({\n /** Human-readable label, surfaced on `client.addresses.name`. */\n name: z.string().min(1, 'customChain.name must not be empty').optional(),\n factoryAddress: hexAddressSchema.optional(),\n usdcAddress: hexAddressSchema.optional(),\n oracleAddress: hexAddressSchema.optional(),\n vaultAddress: hexAddressSchema.optional(),\n tokens1155Address: hexAddressSchema.optional(),\n paramRegistryAddress: hexAddressSchema.optional(),\n /** Smart-account factory + EntryPoint config (SA mode only). */\n smartAccount: z\n .object({\n factoryAddress: hexAddressSchema.optional(),\n implementationAddress: hexAddressSchema.optional(),\n entryPointAddress: hexAddressSchema.optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\n\nexport const cliConfigSchema = z\n .object({\n // ── Kash-orchestrated mode (API-backed) ─────────────────────────────\n apiKey: z\n .string()\n .startsWith('kash_', 'API keys start with \"kash_\"')\n .min(16, 'API key looks too short')\n .optional(),\n baseUrl: z.string().url('baseUrl must be a valid URL').optional(),\n defaultChainId: z.number().int().positive().optional(),\n\n // ── Direct mode (`kash protocol …`, on-chain) ───────────────\n /** RPC endpoint for the chain. Consumer-owned; the CLI never proxies. */\n rpcUrl: z.string().url('rpcUrl must be a valid URL').optional(),\n /** Smart account address (the ERC-4337 account whose funds are used). */\n smartAccount: z\n .string()\n .regex(HEX_ADDRESS_REGEX, 'smartAccount must be a 0x-prefixed 40-char hex address')\n .optional(),\n /** Bundler URL (overrides the protocol-sdk's Flashbots Protect default). */\n bundlerUrl: z.string().url('bundlerUrl must be a valid URL').optional(),\n /** Bundler provider preset (selects the right header dialect). */\n bundlerProvider: bundlerProviderSchema.optional(),\n /** Reference to the EOA private key that owns the smart account. */\n signerKeyRef: signerKeyRefSchema.optional(),\n /**\n * Custom-chain addresses for chains outside the static registry\n * (local Anvil, forks, sidechains). When present, the CLI's\n * direct-mode and EOA-mode commands use these addresses instead\n * of looking the chain up in the registry. Required for chainId\n * 31337 (Anvil); optional for Base mainnet/testnet (registry covers them).\n */\n customChain: customChainSchema.optional(),\n })\n .strict();\n\nexport type CliConfig = z.infer<typeof cliConfigSchema>;\n\n/**\n * Schema for the v1 multi-profile file shape.\n *\n * `currentProfile` is intentionally optional (no `.default()`) so the\n * source-attribution logic in `pickProfileName` can distinguish\n * \"user explicitly persisted `default` via `kash config use default`\"\n * (source: 'file') from \"we fell through to the built-in default\n * because the file didn't carry a `currentProfile` field\" (source:\n * 'default'). Both result in `'default'` as the active profile, but\n * the source attribution they report is different.\n */\nconst cliFileSchema = z\n .object({\n version: z.literal(1),\n currentProfile: profileNameSchema.optional(),\n profiles: z.record(profileNameSchema, cliConfigSchema).default({}),\n })\n .strict();\n\nexport type CliFile = z.infer<typeof cliFileSchema>;\n\n/**\n * Canonical API base URLs by environment. The CLI auto-routes based on\n * the API-key prefix: a `kash_test_*` key targets staging, a\n * `kash_live_*` key (or no key) targets production. An explicit\n * `baseUrl` config or `KASH_BASE_URL` env var always wins so consumers\n * can target a private mirror, a local mock, or a future region.\n *\n * Mirrors the `inferBaseUrlFromApiKey()` logic in `@kashdao/sdk`'s\n * `internal/config.ts` so the CLI and the SDK route a given key to the\n * same environment without the user having to configure two places.\n */\nexport const PRODUCTION_BASE_URL = 'https://api.kash.bot/v1' as const;\nexport const STAGING_BASE_URL = 'https://api-staging.kash.bot/v1' as const;\n\n/**\n * Derive the API base URL from an API key when neither config nor env\n * sets one explicitly. Returns `undefined` if the key shape isn't\n * recognised — the caller then falls back to {@link DEFAULTS.baseUrl}.\n */\nexport function inferBaseUrlFromApiKey(apiKey: string | undefined): string | undefined {\n if (!apiKey) return undefined;\n if (apiKey.startsWith('kash_test_')) return STAGING_BASE_URL;\n if (apiKey.startsWith('kash_live_')) return PRODUCTION_BASE_URL;\n return undefined;\n}\n\n/** Default values applied when a field is missing from both file and env. */\nexport const DEFAULTS = {\n baseUrl: PRODUCTION_BASE_URL,\n defaultChainId: 8453,\n} as const;\n\nexport type ResolvedConfig = {\n // ── Kash-orchestrated fields ──────────────────────────────────────────\n readonly apiKey: string | undefined;\n readonly baseUrl: string;\n readonly defaultChainId: number;\n // ── Direct-mode fields (`kash protocol …`) ────────────────────\n readonly rpcUrl: string | undefined;\n readonly smartAccount: string | undefined;\n readonly bundlerUrl: string | undefined;\n readonly bundlerProvider: 'flashbots' | 'pimlico' | 'alchemy' | 'generic' | undefined;\n readonly signerKeyRef: string | undefined;\n /**\n * Custom-chain config — present only when the profile explicitly sets\n * `customChain.*`. Bypasses the protocol-sdk's static chain registry\n * and is required for chains the registry doesn't cover (Anvil,\n * forks, sidechains).\n */\n readonly customChain: CliConfig['customChain'];\n // ── Meta ──────────────────────────────────────────────────────\n /** Active profile name. */\n readonly profile: string;\n /** Where each non-default value came from — useful for `kash config show`. */\n readonly sources: {\n readonly apiKey: 'env' | 'file' | 'unset';\n readonly baseUrl: 'env' | 'file' | 'inferred' | 'default';\n readonly defaultChainId: 'env' | 'file' | 'default';\n readonly profile: 'flag' | 'env' | 'file' | 'default';\n readonly rpcUrl: 'env' | 'file' | 'unset';\n readonly smartAccount: 'env' | 'file' | 'unset';\n readonly bundlerUrl: 'env' | 'file' | 'unset';\n readonly bundlerProvider: 'env' | 'file' | 'unset';\n readonly signerKeyRef: 'env' | 'file' | 'unset';\n readonly customChain: 'file' | 'unset';\n };\n};\n\nexport type ReadConfigOptions = {\n /** Override which profile to read; takes precedence over env + file. */\n readonly profile?: string;\n /** Override the config file path; takes precedence over `KASH_CONFIG`. */\n readonly configPath?: string;\n};\n\n/**\n * Read the config file and return the resolved active profile merged\n * with environment variables and defaults.\n */\nexport async function readConfig(opts: ReadConfigOptions = {}): Promise<ResolvedConfig> {\n const paths = resolveConfigPathsForOverride(opts.configPath);\n const file = await readFileConfig(paths);\n return resolveActive(file, opts.profile);\n}\n\nasync function readFileConfig(paths: ConfigPaths): Promise<CliFile> {\n if (!existsSync(paths.file)) return emptyFile();\n let raw: string;\n try {\n raw = await readFile(paths.file, 'utf8');\n } catch (cause) {\n throw new CliConfigurationError(\n `Failed to read config file at ${paths.file}: ${(cause as Error).message}`,\n \"Run 'kash config reset' to start fresh.\"\n );\n }\n return parseFileContents(raw, paths.file);\n}\n\nfunction parseFileContents(raw: string, file: string): CliFile {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new CliConfigurationError(\n `Config file at ${file} is not valid JSON: ${(cause as Error).message}`,\n \"Run 'kash config reset' to overwrite it with defaults.\"\n );\n }\n // Guard against valid-JSON-but-wrong-top-level (e.g. someone wrote\n // a string, a number, an array, or `null` to the file). Without this,\n // the v1 schema's \"Expected object, received string\" Zod error\n // bubbles up with no actionable hint.\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new CliConfigurationError(\n `Config file at ${file} must contain a JSON object at the top level (got ${describeJsonRoot(parsed)}).`,\n \"Run 'kash config reset' to overwrite it with defaults.\"\n );\n }\n const migrated = migrateLegacyShape(parsed);\n const result = cliFileSchema.safeParse(migrated);\n if (!result.success) {\n const first = result.error.issues[0];\n const path = first?.path.join('.') ?? '(root)';\n throw new CliConfigurationError(\n `Config file at ${file} is invalid (${path}): ${first?.message ?? 'validation failed'}`,\n \"Run 'kash config reset' to overwrite it with defaults.\"\n );\n }\n return result.data;\n}\n\n/** Describe a non-object JSON root for the user-facing error message. */\nfunction describeJsonRoot(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\n/**\n * If the file looks like the legacy flat shape ({ apiKey?, baseUrl?,\n * defaultChainId? } at the root), wrap it as the default profile of a\n * v1 file. Otherwise pass through.\n */\nfunction migrateLegacyShape(parsed: unknown): unknown {\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return parsed;\n }\n const obj = parsed as Record<string, unknown>;\n if ('version' in obj || 'profiles' in obj) {\n return parsed; // already in v1 shape\n }\n // Legacy flat shape — wrap it as the default profile.\n const flat = cliConfigSchema.safeParse(obj);\n if (!flat.success) {\n return parsed; // let the v1 schema raise the structured error\n }\n return {\n version: 1,\n currentProfile: DEFAULT_PROFILE,\n profiles: { [DEFAULT_PROFILE]: flat.data },\n };\n}\n\nfunction emptyFile(): CliFile {\n return cliFileSchema.parse({ version: 1 });\n}\n\n/**\n * Compute the active profile name. Order: explicit flag > env >\n * file's `currentProfile` (when present) > built-in `'default'`.\n *\n * Crucially, when the file persists `currentProfile: \"default\"`\n * (e.g. after `kash config use default`), source is `'file'` — not\n * `'default'`. That keeps the JSON contract honest: agents debugging\n * \"why is my profile X?\" need to know it came from a write, not a\n * fallback.\n */\nfunction pickProfileName(\n file: CliFile,\n flagOverride: string | undefined\n): { name: string; source: 'flag' | 'env' | 'file' | 'default' } {\n if (flagOverride !== undefined) {\n validateProfileName(flagOverride, '--profile flag');\n return { name: flagOverride, source: 'flag' };\n }\n const env = process.env['KASH_PROFILE'];\n if (env !== undefined && env.length > 0) {\n validateProfileName(env, 'KASH_PROFILE environment variable');\n return { name: env, source: 'env' };\n }\n if (file.currentProfile !== undefined) {\n return { name: file.currentProfile, source: 'file' };\n }\n return { name: DEFAULT_PROFILE, source: 'default' };\n}\n\n/**\n * Wrap `profileNameSchema.parse` so a malformed value surfaces as a\n * typed `CliConfigurationError` with a `check_input`-friendly\n * suggestion, instead of a raw `ZodError` that the top-level\n * boundary maps to `UNEXPECTED`.\n */\nfunction validateProfileName(value: string, source: string): void {\n const result = profileNameSchema.safeParse(value);\n if (!result.success) {\n const issue = result.error.issues[0];\n throw new CliConfigurationError(\n `Profile name from ${source} is invalid: ${issue?.message ?? 'validation failed'}.`,\n 'Profile names accept letters, digits, underscore, dot, and dash; must be 1-64 characters.'\n );\n }\n}\n\nfunction resolveActive(file: CliFile, flagOverride: string | undefined): ResolvedConfig {\n const { name: profileName, source: profileSource } = pickProfileName(file, flagOverride);\n const profile = file.profiles[profileName];\n // It's not an error to ask for a profile that isn't in the file —\n // env-only setups (CI, agents) are normal. We surface this via the\n // `sources.apiKey === 'unset'` value if no env var fills the gap.\n //\n // BUT: when the missing profile was named via `KASH_PROFILE` or\n // `--profile`, an intentional env-only setup is the rare case and\n // a typo (e.g. `KASH_PROFILE=staing` vs `staging`) is the common\n // case. The operator otherwise sees an empty config + a confusing\n // `AUTH_REQUIRED` later. Nudge them on stderr (no JSON pollution,\n // no behaviour change). `KASH_QUIET=1` mutes the warning for CI.\n if (\n profile === undefined &&\n (profileSource === 'env' || profileSource === 'flag') &&\n Object.keys(file.profiles).length > 0 &&\n !isTruthyEnv(process.env['KASH_QUIET'])\n ) {\n const known = Object.keys(file.profiles).sort().join(', ');\n const sourceLabel = profileSource === 'env' ? 'KASH_PROFILE' : '--profile';\n process.stderr.write(\n `\\u26a0 Profile \"${profileName}\" (${sourceLabel}) is not in the config file. ` +\n `Known profiles: ${known}. ` +\n `Did you typo the name? (Set KASH_QUIET=1 to mute this warning.)\\n`\n );\n }\n return mergeWithEnv(profile ?? {}, profileName, profileSource);\n}\n\n/** Same truthy-env recognizer as `utils/global-options.ts:isTruthyEnv`. */\nfunction isTruthyEnv(value: string | undefined): boolean {\n if (value === undefined) return false;\n const v = value.trim().toLowerCase();\n return v === '1' || v === 'true' || v === 'yes' || v === 'on';\n}\n\nfunction mergeWithEnv(\n profile: CliConfig,\n profileName: string,\n profileSource: 'flag' | 'env' | 'file' | 'default'\n): ResolvedConfig {\n const envApiKey = process.env['KASH_API_KEY'];\n const envBaseUrl = process.env['KASH_BASE_URL'];\n const envChainIdRaw = process.env['KASH_CHAIN_ID'];\n // Direct-mode env vars\n const envRpcUrl = process.env['KASH_RPC_URL'];\n const envSmartAccount = process.env['KASH_SMART_ACCOUNT'];\n const envBundlerUrl = process.env['KASH_BUNDLER_URL'];\n const envBundlerProviderRaw = process.env['KASH_BUNDLER_PROVIDER'];\n const envSignerKeyRef = process.env['KASH_SIGNER_KEY_REF'];\n\n let envChainId: number | undefined;\n if (envChainIdRaw !== undefined) {\n const n = Number.parseInt(envChainIdRaw, 10);\n if (Number.isNaN(n) || n <= 0) {\n throw new CliConfigurationError(\n `KASH_CHAIN_ID is not a positive integer: ${envChainIdRaw}`,\n 'Set KASH_CHAIN_ID to a chain id like 8453 or 84532, or unset it to use the default.'\n );\n }\n envChainId = n;\n }\n\n let envBundlerProvider: ResolvedConfig['bundlerProvider'];\n if (envBundlerProviderRaw !== undefined) {\n const allowed = ['flashbots', 'pimlico', 'alchemy', 'generic'] as const;\n if (!(allowed as readonly string[]).includes(envBundlerProviderRaw)) {\n throw new CliConfigurationError(\n `KASH_BUNDLER_PROVIDER must be one of ${allowed.join(', ')} (got \"${envBundlerProviderRaw}\").`,\n 'Unset the variable or set it to a supported preset.'\n );\n }\n envBundlerProvider = envBundlerProviderRaw as ResolvedConfig['bundlerProvider'];\n }\n\n const apiKey = envApiKey ?? profile.apiKey;\n // Resolution order for `baseUrl`:\n // 1. KASH_BASE_URL env var — always wins\n // 2. profile.baseUrl — explicit profile config\n // 3. inferred from apiKey prefix — kash_test_* → staging, kash_live_* → production\n // 4. DEFAULTS.baseUrl — production (final fallback)\n //\n // Step 3 mirrors `@kashdao/sdk`'s `inferBaseUrlFromApiKey()` so the\n // CLI and the SDK route the same key to the same environment without\n // requiring the user to configure two places. Without this, a user\n // with only a `kash_test_*` key would hit production (and a DNS error\n // pre-launch) until they remembered to also set `--base-url`.\n const baseUrl =\n envBaseUrl ?? profile.baseUrl ?? inferBaseUrlFromApiKey(apiKey) ?? DEFAULTS.baseUrl;\n const defaultChainId = envChainId ?? profile.defaultChainId ?? DEFAULTS.defaultChainId;\n const rpcUrl = envRpcUrl ?? profile.rpcUrl;\n const smartAccount = envSmartAccount ?? profile.smartAccount;\n const bundlerUrl = envBundlerUrl ?? profile.bundlerUrl;\n const bundlerProvider = envBundlerProvider ?? profile.bundlerProvider;\n const signerKeyRef = envSignerKeyRef ?? profile.signerKeyRef;\n // customChain has no env-var override — it's a structured object,\n // not a single string, and the right place to set it is `kash\n // config set customChain.<leaf>` so partial sets compose. CI use\n // cases that need a custom chain mount the config file directly\n // (KASH_CONFIG=...).\n const customChain = profile.customChain;\n\n return {\n apiKey,\n baseUrl,\n defaultChainId,\n rpcUrl,\n smartAccount,\n bundlerUrl,\n bundlerProvider,\n signerKeyRef,\n customChain,\n profile: profileName,\n sources: {\n apiKey: envApiKey ? 'env' : profile.apiKey ? 'file' : 'unset',\n baseUrl: envBaseUrl\n ? 'env'\n : profile.baseUrl\n ? 'file'\n : inferBaseUrlFromApiKey(apiKey)\n ? 'inferred'\n : 'default',\n defaultChainId:\n envChainId !== undefined\n ? 'env'\n : profile.defaultChainId !== undefined\n ? 'file'\n : 'default',\n profile: profileSource,\n rpcUrl: envRpcUrl ? 'env' : profile.rpcUrl ? 'file' : 'unset',\n smartAccount: envSmartAccount ? 'env' : profile.smartAccount ? 'file' : 'unset',\n bundlerUrl: envBundlerUrl ? 'env' : profile.bundlerUrl ? 'file' : 'unset',\n bundlerProvider: envBundlerProvider ? 'env' : profile.bundlerProvider ? 'file' : 'unset',\n signerKeyRef: envSignerKeyRef ? 'env' : profile.signerKeyRef ? 'file' : 'unset',\n customChain: profile.customChain ? 'file' : 'unset',\n },\n };\n}\n\nexport type WriteConfigOptions = {\n /** Profile to write to. Defaults to the current active profile. */\n readonly profile?: string;\n /** Override the config file path. */\n readonly configPath?: string;\n};\n\n/**\n * Result of {@link updateConfig} / {@link clearConfigField}. Carries\n * the resolved profile name so callers can render an accurate\n * \"wrote to profile X\" message instead of guessing — important for\n * the JSON contract that `kash auth set-key --json` ships, since\n * `--profile` may be unset and we want to report the actually-written\n * profile (which falls back to the file's `currentProfile`).\n */\nexport type UpdateConfigResult = {\n readonly profile: string;\n readonly stored: CliConfig;\n};\n\n/**\n * Mutate (and persist) a single field of the active (or named) profile.\n * Used by `auth set-key`, `auth logout`, `config set`. Writes the file\n * with `0600` permissions.\n */\nexport async function updateConfig(\n patch: Partial<CliConfig>,\n opts: WriteConfigOptions = {}\n): Promise<UpdateConfigResult> {\n const paths = resolveConfigPathsForOverride(opts.configPath);\n const file = await readFileConfig(paths);\n const profileName = opts.profile ?? file.currentProfile ?? DEFAULT_PROFILE;\n profileNameSchema.parse(profileName);\n const current = file.profiles[profileName] ?? {};\n const next = cliConfigSchema.parse({ ...current, ...patch });\n const updated: CliFile = {\n ...file,\n profiles: { ...file.profiles, [profileName]: next },\n };\n await writeFileConfig(paths, updated);\n return { profile: profileName, stored: next };\n}\n\n/** Wipe a single field from a profile (used by `auth logout`). */\nexport async function clearConfigField(\n field: keyof CliConfig,\n opts: WriteConfigOptions = {}\n): Promise<UpdateConfigResult> {\n const paths = resolveConfigPathsForOverride(opts.configPath);\n const file = await readFileConfig(paths);\n const profileName = opts.profile ?? file.currentProfile ?? DEFAULT_PROFILE;\n const current = file.profiles[profileName] ?? {};\n if (!(field in current)) return { profile: profileName, stored: current };\n const next = cliConfigSchema.parse(omitKey(current, field));\n const updated: CliFile = {\n ...file,\n profiles: { ...file.profiles, [profileName]: next },\n };\n await writeFileConfig(paths, updated);\n return { profile: profileName, stored: next };\n}\n\n/** List every profile name present in the config file. */\nexport async function listProfiles(\n opts: { configPath?: string } = {}\n): Promise<{ readonly current: string; readonly profiles: readonly string[] }> {\n const paths = resolveConfigPathsForOverride(opts.configPath);\n const file = await readFileConfig(paths);\n return {\n current: file.currentProfile ?? DEFAULT_PROFILE,\n profiles: Object.keys(file.profiles).sort(),\n };\n}\n\n/** Set the file's `currentProfile` field. Validates the name. */\nexport async function setCurrentProfile(\n name: string,\n opts: { configPath?: string } = {}\n): Promise<CliFile> {\n profileNameSchema.parse(name);\n const paths = resolveConfigPathsForOverride(opts.configPath);\n const file = await readFileConfig(paths);\n const updated: CliFile = { ...file, currentProfile: name };\n await writeFileConfig(paths, updated);\n return updated;\n}\n\n/** Remove a named profile. Refuses to remove the active one. */\nexport async function deleteProfile(\n name: string,\n opts: { configPath?: string } = {}\n): Promise<CliFile> {\n profileNameSchema.parse(name);\n const paths = resolveConfigPathsForOverride(opts.configPath);\n const file = await readFileConfig(paths);\n if (file.currentProfile === name) {\n throw new CliConfigurationError(\n `Cannot delete the active profile \"${name}\".`,\n 'Switch to another profile first with `kash config use <name>`.'\n );\n }\n if (!(name in file.profiles)) {\n return file;\n }\n const updated: CliFile = { ...file, profiles: omitKey(file.profiles, name) };\n await writeFileConfig(paths, updated);\n return updated;\n}\n\n/** Delete the entire config file. Used by `config reset`. */\nexport async function deleteConfig(opts: { configPath?: string } = {}): Promise<void> {\n const paths = resolveConfigPathsForOverride(opts.configPath);\n if (!existsSync(paths.file)) return;\n await unlink(paths.file);\n}\n\n/**\n * Return the full multi-profile file as-is. Used by `kash config\n * export` to dump every profile (vs `readConfig` which resolves a\n * single active profile). When the file doesn't exist, returns an\n * empty file shape so callers don't have to special-case \"no config\n * yet\".\n */\nexport async function readWholeFile(opts: { configPath?: string } = {}): Promise<CliFile> {\n const paths = resolveConfigPathsForOverride(opts.configPath);\n return await readFileConfig(paths);\n}\n\n/**\n * Replace the entire on-disk file with the supplied shape. Used by\n * `kash config import`. Validates against the `cliFileSchema` to\n * prevent garbage from landing on disk.\n *\n * Caller-side concerns (merge vs. overwrite, redaction policy, etc.)\n * are handled in the import command — this helper is pure persistence.\n */\nexport async function writeWholeFile(\n file: CliFile,\n opts: { configPath?: string } = {}\n): Promise<void> {\n const paths = resolveConfigPathsForOverride(opts.configPath);\n const validated = cliFileSchema.parse(file);\n await writeFileConfig(paths, validated);\n}\n\n/** Public re-export of the file-level schema for the import command. */\nexport { cliFileSchema };\n\nasync function writeFileConfig(paths: ConfigPaths, file: CliFile): Promise<void> {\n await ensureDir(paths.dir);\n // Use writeFile + chmod rather than writeFile({mode}) because the\n // mode flag only takes effect on first creation; rewrites would\n // keep the old (potentially looser) permissions.\n await writeFile(paths.file, JSON.stringify(file, null, 2), 'utf8');\n await chmodSafe(paths.file, 0o600);\n}\n\nasync function ensureDir(dir: string): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n await chmodSafe(dir, 0o700);\n}\n\nasync function chmodSafe(target: string, mode: number | undefined): Promise<void> {\n if (mode === undefined) return;\n if (process.platform === 'win32') return;\n try {\n await chmod(target, mode);\n } catch {\n // chmod can fail on some filesystems (e.g. mounted FAT volumes,\n // network shares). Treat as best-effort — the user's data still\n // landed, we just couldn't tighten perms.\n }\n}\n"],"mappings":";;;;;;;;;AAwCA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,OAAO,UAAU,QAAQ,iBAAiB;AAC1D,SA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ACpF,QAAM,QAAQ,8BAA8B,KAAK,UAAU;AAC3D,MAAI,CAAC,WAAW,MAAM,IAAI,EAAG;AAC7B,QAAM,OAAO,MAAM,IAAI;AACzB;AASA,eAAsB,cAAc,OAAgC,CAAC,GAAqB;AACxF,QAAM,QAAQ,8BAA8B,KAAK,UAAU;AAC3D,SAAO,MAAM,eAAe,KAAK;AACnC;AAUA,eAAsB,eACpB,MACA,OAAgC,CAAC,GAClB;AACf,QAAM,QAAQ,8BAA8B,KAAK,UAAU;AAC3D,QAAM,YAAY,cAAc,MAAM,IAAI;AAC1C,QAAM,gBAAgB,OAAO,SAAS;AACxC;AAKA,eAAe,gBAAgB,OAAoB,MAA8B;AAC/E,QAAM,UAAU,MAAM,GAAG;AAIzB,QAAM,UAAU,MAAM,MAAM,KAAK,UAAU,MAAM,MAAM,CAAC,GAAG,MAAM;AACjE,QAAM,UAAU,MAAM,MAAM,GAAK;AACnC;AAEA,eAAe,UAAU,KAA4B;AACnD,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AACjD,QAAM,UAAU,KAAK,GAAK;AAC5B;AAEA,eAAe,UAAU,QAAgB,MAAyC;AAChF,MAAI,SAAS,OAAW;AACxB,MAAI,QAAQ,aAAa,QAAS;AAClC,MAAI;AACF,UAAM,MAAM,QAAQ,IAAI;AAAA,EAC1B,QAAQ;AAAA,EAIR;AACF;","names":[]}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
parseFieldsList,
|
|
4
|
+
parseFilter
|
|
5
|
+
} from "./chunk-MIXOZU2S.js";
|
|
6
|
+
import {
|
|
7
|
+
CliValidationError
|
|
8
|
+
} from "./chunk-UZNSYATZ.js";
|
|
9
|
+
|
|
10
|
+
// src/utils/global-options.ts
|
|
11
|
+
function readGlobals(cmd) {
|
|
12
|
+
const opts = cmd.optsWithGlobals();
|
|
13
|
+
return {
|
|
14
|
+
json: opts.json === true,
|
|
15
|
+
quiet: opts.quiet === true,
|
|
16
|
+
noColor: opts.color === false,
|
|
17
|
+
// `KASH_DEBUG=1` (or any truthy value) mirrors `--debug`. Common
|
|
18
|
+
// case: CI matrix configs and parent processes that can't easily
|
|
19
|
+
// edit the invocation. Explicit `--debug` always wins (a user can
|
|
20
|
+
// force it on even when the env says off).
|
|
21
|
+
debug: opts.debug === true || isTruthyEnv(process.env["KASH_DEBUG"]),
|
|
22
|
+
profile: opts.profile,
|
|
23
|
+
configPath: opts.config,
|
|
24
|
+
baseUrl: opts.baseUrl === void 0 ? void 0 : parseUrl(opts.baseUrl, "base-url"),
|
|
25
|
+
maxRetries: opts.maxRetries === void 0 ? void 0 : (
|
|
26
|
+
// Cap at 10 to match the SDK's `kashClientConfigSchema`
|
|
27
|
+
// (`maxRetries: z.number().int().min(0).max(10)`). Bouncing
|
|
28
|
+
// out-of-range values here gives the agent an `INVALID_INPUT`
|
|
29
|
+
// with a clear field, instead of a cryptic SDK
|
|
30
|
+
// `KashConfigurationError` after the client tries to construct.
|
|
31
|
+
parseBoundedUnsigned(opts.maxRetries, "max-retries", 0, 10)
|
|
32
|
+
),
|
|
33
|
+
timeoutMs: opts.timeoutMs === void 0 ? void 0 : parsePositive(opts.timeoutMs, "timeout-ms"),
|
|
34
|
+
// `--api-version` is forwarded to the SDK as `apiVersion`. Format
|
|
35
|
+
// validation (`YYYY-MM-DD`) is enforced by the SDK's
|
|
36
|
+
// `kashClientConfigSchema`. We don't pre-validate here — letting
|
|
37
|
+
// the SDK be the single source of truth keeps the format rule in
|
|
38
|
+
// one place. A malformed value surfaces as
|
|
39
|
+
// `KashConfigurationError` from client construction, which the
|
|
40
|
+
// CLI's error mapper converts to a structured envelope.
|
|
41
|
+
apiVersion: opts.apiVersion,
|
|
42
|
+
fields: opts.fields === void 0 ? void 0 : parseFieldsList(opts.fields),
|
|
43
|
+
filter: opts.filter === void 0 ? void 0 : parseFilter(opts.filter)
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function parseBoundedUnsigned(raw, name, min, max) {
|
|
47
|
+
if (!/^\+?\d+$/.test(raw)) {
|
|
48
|
+
throw new CliValidationError(
|
|
49
|
+
`--${name} must be an integer between ${String(min)} and ${String(max)}.`,
|
|
50
|
+
`Got "${raw}". Pass digits only \u2014 no decimals or scientific notation.`,
|
|
51
|
+
name
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
const n = Number.parseInt(raw, 10);
|
|
55
|
+
if (!Number.isFinite(n) || n < min || n > max) {
|
|
56
|
+
throw new CliValidationError(
|
|
57
|
+
`--${name} must be an integer between ${String(min)} and ${String(max)}.`,
|
|
58
|
+
`Got "${raw}".`,
|
|
59
|
+
name
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return n;
|
|
63
|
+
}
|
|
64
|
+
function parseUrl(raw, name) {
|
|
65
|
+
let url;
|
|
66
|
+
try {
|
|
67
|
+
url = new URL(raw);
|
|
68
|
+
} catch {
|
|
69
|
+
throw new CliValidationError(
|
|
70
|
+
`--${name} must be a valid URL.`,
|
|
71
|
+
`Got "${raw}". Include the scheme, e.g. https://api.kash.bot/v1.`,
|
|
72
|
+
name
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
76
|
+
throw new CliValidationError(
|
|
77
|
+
`--${name} must use http:// or https:// (got "${url.protocol}").`,
|
|
78
|
+
`Schemes like file:, data:, javascript:, and about: are rejected \u2014 they would either silently fail in the SDK or open an attack vector.`,
|
|
79
|
+
name
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
return raw;
|
|
83
|
+
}
|
|
84
|
+
function parsePositiveInt(raw, name) {
|
|
85
|
+
if (!/^\+?\d+$/.test(raw)) {
|
|
86
|
+
throw new CliValidationError(
|
|
87
|
+
`--${name} must be a positive integer.`,
|
|
88
|
+
`Got "${raw}". Pass digits only \u2014 no decimals, scientific notation, or sign except a leading +.`,
|
|
89
|
+
name
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
const n = Number.parseInt(raw, 10);
|
|
93
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
94
|
+
throw new CliValidationError(
|
|
95
|
+
`--${name} must be a positive integer.`,
|
|
96
|
+
`Got "${raw}". Pass an integer > 0.`,
|
|
97
|
+
name
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
return n;
|
|
101
|
+
}
|
|
102
|
+
var parsePositive = parsePositiveInt;
|
|
103
|
+
function parseOptionalPositiveInt(raw, name) {
|
|
104
|
+
return raw === void 0 ? void 0 : parsePositiveInt(raw, name);
|
|
105
|
+
}
|
|
106
|
+
function parsePositiveFloat(raw, name) {
|
|
107
|
+
const n = Number.parseFloat(raw);
|
|
108
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
109
|
+
throw new CliValidationError(
|
|
110
|
+
`--${name} must be a positive number.`,
|
|
111
|
+
`Got "${raw}". Pass a finite number > 0.`,
|
|
112
|
+
name
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
return n;
|
|
116
|
+
}
|
|
117
|
+
function parseOptionalPositiveFloat(raw, name) {
|
|
118
|
+
return raw === void 0 ? void 0 : parsePositiveFloat(raw, name);
|
|
119
|
+
}
|
|
120
|
+
function isTruthyEnv(value) {
|
|
121
|
+
if (value === void 0) return false;
|
|
122
|
+
const v = value.trim().toLowerCase();
|
|
123
|
+
return v === "1" || v === "true" || v === "yes" || v === "on";
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export {
|
|
127
|
+
readGlobals,
|
|
128
|
+
parsePositiveInt,
|
|
129
|
+
parseOptionalPositiveInt,
|
|
130
|
+
parsePositiveFloat,
|
|
131
|
+
parseOptionalPositiveFloat
|
|
132
|
+
};
|
|
133
|
+
//# sourceMappingURL=chunk-LBIRQHX5.js.map
|