@tinycloud/cli 0.4.7-beta.4 → 0.4.7-beta.6

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/README.md CHANGED
@@ -43,6 +43,9 @@ tc delegation create --to did:pkh:eip155:1:0x...
43
43
  | `tc kv get <key>` | Retrieve a value |
44
44
  | `tc kv put <key> <value>` | Store a value |
45
45
  | `tc kv list` | List all keys |
46
+ | `tc sql query <sql>` | Run a SQLite SELECT query |
47
+ | `tc sql execute <sql>` | Run a SQLite write or schema statement |
48
+ | `tc sql export` | Export a SQLite database file |
46
49
  | `tc space list` | List your spaces |
47
50
  | `tc space create` | Create a new space |
48
51
  | `tc delegation create` | Grant access to another user |
package/dist/index.js CHANGED
@@ -2422,8 +2422,39 @@ function registerDoctorCommand(program2) {
2422
2422
  import { writeFile as writeFile6 } from "fs/promises";
2423
2423
  import { resolve } from "path";
2424
2424
  function registerSqlCommand(program2) {
2425
- const sql = program2.command("sql").description("SQL database operations");
2426
- sql.command("query <sql>").description("Run a SELECT query").option("--db <name>", "Database name", "default").option("--params <json>", "Bind parameters as JSON array").action(async (sqlStr, options, cmd) => {
2425
+ const sql = program2.command("sql").description("SQLite database operations for your TinyCloud space").addHelpText("after", `
2426
+
2427
+ TinyCloud SQL gives each space isolated SQLite databases. Use the default
2428
+ database for simple apps, or pass --db to target a named database.
2429
+
2430
+ Common workflows:
2431
+ $ tc sql execute "CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)"
2432
+ $ tc sql execute "INSERT INTO notes (body) VALUES (?)" --params '["ship docs"]'
2433
+ $ tc sql query "SELECT id, body FROM notes ORDER BY id"
2434
+ $ tc sql query "SELECT * FROM events WHERE type = ?" --db analytics --params '["signup"]'
2435
+ $ tc sql export --db analytics --output analytics.db
2436
+
2437
+ Commands:
2438
+ query Read rows with SELECT statements
2439
+ execute Run writes and schema changes such as INSERT, UPDATE, DELETE, CREATE, DROP
2440
+ export Download the raw SQLite database file
2441
+
2442
+ Tips:
2443
+ - SQL strings should usually be quoted so your shell passes them as one argument.
2444
+ - --params accepts a JSON array and binds values to ? placeholders.
2445
+ - Add --json for scripting-friendly output.
2446
+ `);
2447
+ sql.command("query <sql>").description("Run a read-only SELECT query").option("--db <name>", "SQLite database name within the current space", "default").option("--params <json>", "Bind parameters as a JSON array for ? placeholders").addHelpText("after", `
2448
+
2449
+ Examples:
2450
+ $ tc sql query "SELECT * FROM notes ORDER BY id"
2451
+ $ tc sql query "SELECT * FROM notes WHERE id = ?" --params '[42]'
2452
+ $ tc sql query "SELECT count(*) AS total FROM events" --db analytics --json
2453
+
2454
+ Output:
2455
+ Human output is formatted as a table. Piped output or --json returns
2456
+ { "columns": string[], "rows": unknown[][], "rowCount": number }.
2457
+ `).action(async (sqlStr, options, cmd) => {
2427
2458
  try {
2428
2459
  const globalOpts = cmd.optsWithGlobals();
2429
2460
  const ctx = await ProfileManager.resolveContext(globalOpts);
@@ -2455,7 +2486,17 @@ ${rowCount} row${rowCount === 1 ? "" : "s"} returned`) + "\n");
2455
2486
  handleError(error);
2456
2487
  }
2457
2488
  });
2458
- sql.command("execute <sql>").description("Run INSERT/UPDATE/DELETE/DDL statement").option("--db <name>", "Database name", "default").option("--params <json>", "Bind parameters as JSON array").action(async (sqlStr, options, cmd) => {
2489
+ sql.command("execute <sql>").description("Run a write or schema statement").option("--db <name>", "SQLite database name within the current space", "default").option("--params <json>", "Bind parameters as a JSON array for ? placeholders").addHelpText("after", `
2490
+
2491
+ Examples:
2492
+ $ tc sql execute "CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)"
2493
+ $ tc sql execute "INSERT INTO notes (body) VALUES (?)" --params '["first note"]'
2494
+ $ tc sql execute "UPDATE notes SET body = ? WHERE id = ?" --params '["edited", 1]'
2495
+ $ tc sql execute "DROP TABLE old_notes" --db archive
2496
+
2497
+ Output:
2498
+ Returns JSON with the changed row count and last inserted row id when available.
2499
+ `).action(async (sqlStr, options, cmd) => {
2459
2500
  try {
2460
2501
  const globalOpts = cmd.optsWithGlobals();
2461
2502
  const ctx = await ProfileManager.resolveContext(globalOpts);
@@ -2476,7 +2517,15 @@ ${rowCount} row${rowCount === 1 ? "" : "s"} returned`) + "\n");
2476
2517
  handleError(error);
2477
2518
  }
2478
2519
  });
2479
- sql.command("export").description("Export database as binary file").option("--db <name>", "Database name", "default").option("-o, --output <file>", "Output file path", "export.db").action(async (options, cmd) => {
2520
+ sql.command("export").description("Export a SQLite database as a binary .db file").option("--db <name>", "SQLite database name within the current space", "default").option("-o, --output <file>", "Output file path", "export.db").addHelpText("after", `
2521
+
2522
+ Examples:
2523
+ $ tc sql export
2524
+ $ tc sql export --db analytics --output analytics.db
2525
+
2526
+ Output:
2527
+ Writes the database file locally and returns JSON with the path and size.
2528
+ `).action(async (options, cmd) => {
2480
2529
  try {
2481
2530
  const globalOpts = cmd.optsWithGlobals();
2482
2531
  const ctx = await ProfileManager.resolveContext(globalOpts);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/config/constants.ts","../src/output/formatter.ts","../src/output/theme.ts","../src/output/errors.ts","../src/output/taglines.ts","../src/output/banner.ts","../src/config/profiles.ts","../src/config/storage.ts","../src/auth/local-key.ts","../src/auth/browser-auth.ts","../src/commands/init.ts","../src/commands/auth.ts","../src/commands/kv.ts","../src/lib/sdk.ts","../src/commands/space.ts","../src/lib/duration.ts","../src/commands/delegation.ts","../src/commands/share.ts","../src/commands/node.ts","../src/commands/profile.ts","../src/commands/completion.ts","../src/commands/vault.ts","../src/commands/secrets.ts","../src/commands/vars.ts","../src/commands/doctor.ts","../src/commands/sql.ts","../src/commands/duckdb.ts","../src/commands/upgrade.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport { handleError } from \"./output/errors.js\";\nimport { emitBanner } from \"./output/banner.js\";\n\nconst { version } = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n);\nimport { theme } from \"./output/theme.js\";\nimport { isInteractive } from \"./output/formatter.js\";\nimport { ProfileManager } from \"./config/profiles.js\";\nimport { registerInitCommand } from \"./commands/init.js\";\nimport { registerAuthCommand } from \"./commands/auth.js\";\nimport { registerKvCommand } from \"./commands/kv.js\";\nimport { registerSpaceCommand } from \"./commands/space.js\";\nimport { registerDelegationCommand } from \"./commands/delegation.js\";\nimport { registerShareCommand } from \"./commands/share.js\";\nimport { registerNodeCommand } from \"./commands/node.js\";\nimport { registerProfileCommand } from \"./commands/profile.js\";\nimport { registerCompletionCommand } from \"./commands/completion.js\";\nimport { registerVaultCommand } from \"./commands/vault.js\";\nimport { registerSecretsCommand } from \"./commands/secrets.js\";\nimport { registerVarsCommand } from \"./commands/vars.js\";\nimport { registerDoctorCommand } from \"./commands/doctor.js\";\nimport { registerSqlCommand } from \"./commands/sql.js\";\nimport { registerDuckdbCommand } from \"./commands/duckdb.js\";\nimport { registerUpgradeCommand } from \"./commands/upgrade.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"tc\")\n .description(\"TinyCloud CLI — self-sovereign storage from the terminal\")\n .version(version)\n .option(\"-p, --profile <name>\", \"Profile to use\")\n .option(\"-H, --host <url>\", \"TinyCloud node URL\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--no-cache\", \"Disable caching\")\n .option(\"-q, --quiet\", \"Suppress non-essential output\")\n .option(\"--json\", \"Force JSON output\");\n\nprogram.hook(\"preAction\", async (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n if (!opts.quiet) {\n emitBanner(version);\n }\n\n // Config guard — warn if not configured for auth-required commands\n const commandName = thisCommand.name();\n const parentName = thisCommand.parent?.name();\n const fullCommand = parentName && parentName !== \"tc\" ? `${parentName} ${commandName}` : commandName;\n const skipGuard = [\"tc\", \"init\", \"doctor\", \"completion\", \"help\", \"upgrade\"].includes(commandName) ||\n fullCommand === \"profile create\";\n if (!skipGuard && !opts.quiet && isInteractive()) {\n try {\n const config = await ProfileManager.getConfig();\n const profileName = opts.profile || config.defaultProfile;\n const hasProfile = await ProfileManager.profileExists(profileName);\n if (!hasProfile) {\n process.stderr.write(theme.warn(\"⚠ No profile configured.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n } else {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n process.stderr.write(theme.warn(\"⚠ No key found.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n }\n }\n } catch {\n // Config dir doesn't exist yet — that's fine, commands will handle it\n }\n }\n});\n\nregisterInitCommand(program);\nregisterAuthCommand(program);\nregisterKvCommand(program);\nregisterSpaceCommand(program);\nregisterDelegationCommand(program);\nregisterShareCommand(program);\nregisterNodeCommand(program);\nregisterProfileCommand(program);\nregisterCompletionCommand(program);\nregisterVaultCommand(program);\nregisterSecretsCommand(program);\nregisterVarsCommand(program);\nregisterDoctorCommand(program);\nregisterSqlCommand(program);\nregisterDuckdbCommand(program);\nregisterUpgradeCommand(program);\n\nprogram.addHelpText(\"afterAll\", () => {\n if (!process.stdout.isTTY) return \"\";\n return `\n${theme.heading(\"Examples:\")}\n ${theme.command(\"tc init\")} ${theme.muted(\"Set up a profile and generate keys\")}\n ${theme.command(\"tc auth login\")} ${theme.muted(\"Authenticate via browser\")}\n ${theme.command('tc kv put greeting \"Hello\"')} ${theme.muted(\"Store a value\")}\n ${theme.command(\"tc kv list\")} ${theme.muted(\"List all keys\")}\n ${theme.command(\"tc delegation create --to did:pkh:...\")} ${theme.muted(\"Grant access to another user\")}\n ${theme.command(\"tc space list\")} ${theme.muted(\"Show your spaces\")}\n\n${theme.muted(\"Docs:\")} ${theme.accent(\"https://docs.tinycloud.xyz/cli\")}\n${theme.muted(\"Repo:\")} ${theme.accent(\"https://github.com/tinycloudlabs/web-sdk\")}\n`;\n});\n\ntry {\n await program.parseAsync(process.argv);\n} catch (error) {\n handleError(error);\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const CONFIG_DIR = join(homedir(), \".tinycloud\");\nexport const PROFILES_DIR = join(CONFIG_DIR, \"profiles\");\nexport const CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\n\nexport const DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nexport const DEFAULT_PROFILE = \"default\";\nexport const DEFAULT_CHAIN_ID = 1;\n\nexport const ExitCode = {\n SUCCESS: 0,\n ERROR: 1,\n USAGE_ERROR: 2,\n AUTH_REQUIRED: 3,\n NOT_FOUND: 4,\n PERMISSION_DENIED: 5,\n NETWORK_ERROR: 6,\n NODE_ERROR: 7,\n} as const;\n","import ora from \"ora\";\nimport { theme } from \"./theme.js\";\n\nexport function outputJson(data: unknown): void {\n process.stdout.write(JSON.stringify(data, null, 2) + \"\\n\");\n}\n\nexport function outputError(code: string, message: string): void {\n if (isInteractive()) {\n process.stderr.write(\n `${theme.error(\"✗\")} ${theme.label(code)}: ${message}\\n`\n );\n } else {\n process.stderr.write(\n JSON.stringify({ error: { code, message } }, null, 2) + \"\\n\"\n );\n }\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdout.isTTY);\n}\n\nexport async function withSpinner<T>(label: string, fn: () => Promise<T>): Promise<T> {\n if (!isInteractive()) {\n return fn();\n }\n const spinner = ora(label).start();\n try {\n const result = await fn();\n spinner.succeed(label);\n return result;\n } catch (error) {\n spinner.fail(label);\n throw error;\n }\n}\n\n/** Check if output should be JSON (non-TTY or --json flag) */\nexport function shouldOutputJson(): boolean {\n return !isInteractive() || process.argv.includes(\"--json\");\n}\n\n/** Format a key-value pair for human display */\nexport function formatField(label: string, value: string | number | boolean | null | undefined): string {\n if (value === null || value === undefined) return ` ${theme.label(label + \":\")} ${theme.muted(\"—\")}`;\n if (typeof value === \"boolean\") {\n return ` ${theme.label(label + \":\")} ${value ? theme.success(\"yes\") : theme.muted(\"no\")}`;\n }\n return ` ${theme.label(label + \":\")} ${theme.value(String(value))}`;\n}\n\n/** Format a list of items as a simple table */\nexport function formatTable(headers: string[], rows: string[][]): string {\n // Calculate column widths\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map(r => (r[i] || \"\").length))\n );\n\n const headerLine = headers.map((h, i) => theme.label(h.padEnd(widths[i]))).join(\" \");\n const separator = widths.map(w => theme.dim(\"─\".repeat(w))).join(\" \");\n const dataLines = rows.map(row =>\n row.map((cell, i) => (cell || \"\").padEnd(widths[i])).join(\" \")\n );\n\n return [headerLine, separator, ...dataLines].join(\"\\n\");\n}\n\n/** Output data in either JSON or human-friendly format */\nexport function output(data: unknown, humanFormatter?: () => string): void {\n if (shouldOutputJson() || !humanFormatter) {\n outputJson(data);\n } else {\n process.stdout.write(humanFormatter() + \"\\n\");\n }\n}\n\n/** Format a status check line (for doctor command etc.) */\nexport function formatCheck(ok: boolean | \"warn\", label: string, detail?: string): string {\n const icon = ok === \"warn\" ? theme.warn(\"⚠\") : ok ? theme.success(\"✓\") : theme.error(\"✗\");\n const detailStr = detail ? ` ${theme.muted(`(${detail})`)}` : \"\";\n return `${icon} ${label}${detailStr}`;\n}\n\n/** Format a section heading */\nexport function formatSection(title: string): string {\n return `\\n${theme.heading(title)}`;\n}\n\n/** Format bytes to human readable */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Format relative time */\nexport function formatTimeAgo(date: Date | string): string {\n const d = typeof date === \"string\" ? new Date(date) : date;\n const seconds = Math.floor((Date.now() - d.getTime()) / 1000);\n if (seconds < 60) return \"just now\";\n if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;\n if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;\n return `${Math.floor(seconds / 86400)}d ago`;\n}\n","import chalk from \"chalk\";\n\nexport const TC_PALETTE = {\n primary: \"#4473b9\",\n accent: \"#5b9bd5\",\n success: \"#2fba6a\",\n warn: \"#e8a838\",\n error: \"#d94040\",\n muted: \"#808080\",\n dim: \"#5a5a5a\",\n} as const;\n\nexport const theme = {\n primary: chalk.hex(TC_PALETTE.primary),\n accent: chalk.hex(TC_PALETTE.accent),\n success: chalk.hex(TC_PALETTE.success),\n warn: chalk.hex(TC_PALETTE.warn),\n error: chalk.hex(TC_PALETTE.error),\n muted: chalk.hex(TC_PALETTE.muted),\n dim: chalk.hex(TC_PALETTE.dim),\n heading: chalk.bold.hex(TC_PALETTE.primary),\n command: chalk.hex(TC_PALETTE.accent),\n brand: chalk.bold.hex(TC_PALETTE.primary),\n label: chalk.bold,\n value: chalk.white,\n hint: chalk.italic.hex(TC_PALETTE.muted),\n};\n","import { ExitCode } from \"../config/constants.js\";\nimport { outputError } from \"./formatter.js\";\n\nexport class CLIError extends Error {\n constructor(\n public code: string,\n message: string,\n public exitCode: number = ExitCode.ERROR\n ) {\n super(message);\n this.name = \"CLIError\";\n }\n}\n\nexport function wrapError(error: unknown): CLIError {\n if (error instanceof CLIError) return error;\n\n const message = error instanceof Error ? error.message : String(error);\n\n // Map known error patterns to exit codes\n if (message.includes(\"Not signed in\") || message.includes(\"AUTH_EXPIRED\") || message.includes(\"Session expired\")) {\n return new CLIError(\"AUTH_REQUIRED\", message, ExitCode.AUTH_REQUIRED);\n }\n if (message.includes(\"NOT_FOUND\") || message.includes(\"KV_NOT_FOUND\")) {\n return new CLIError(\"NOT_FOUND\", message, ExitCode.NOT_FOUND);\n }\n if (message.includes(\"PERMISSION_DENIED\")) {\n return new CLIError(\"PERMISSION_DENIED\", message, ExitCode.PERMISSION_DENIED);\n }\n if (message.includes(\"ECONNREFUSED\") || message.includes(\"ETIMEDOUT\") || message.includes(\"fetch failed\")) {\n return new CLIError(\"NETWORK_ERROR\", message, ExitCode.NETWORK_ERROR);\n }\n\n return new CLIError(\"ERROR\", message, ExitCode.ERROR);\n}\n\nexport function handleError(error: unknown): never {\n const cliError = wrapError(error);\n outputError(cliError.code, cliError.message);\n process.exit(cliError.exitCode);\n}\n","interface HolidayTagline {\n month: number;\n day: number;\n range?: number; // days before/after to show\n tagline: string;\n}\n\nconst HOLIDAY_TAGLINES: HolidayTagline[] = [\n { month: 1, day: 1, range: 1, tagline: \"New year, new keys, same cloud.\" },\n { month: 2, day: 14, tagline: \"We love your data as much as you do.\" },\n { month: 3, day: 14, tagline: \"3.14159 reasons to encrypt everything.\" },\n { month: 5, day: 4, tagline: \"May the fourth be with your keys.\" },\n { month: 10, day: 31, tagline: \"Nothing scarier than plaintext secrets.\" },\n { month: 12, day: 25, range: 2, tagline: \"Unwrap your data, not your keys.\" },\n { month: 12, day: 31, tagline: \"Encrypt your resolutions.\" },\n];\n\nconst TAGLINES = [\n // Professional\n \"Your data, your keys, your cloud.\",\n \"Self-sovereign storage for the modern web.\",\n \"The cloud you actually own.\",\n \"Encrypted by default, decentralized by design.\",\n \"Where your data answers only to you.\",\n \"End-to-end encrypted. No exceptions.\",\n \"Like S3 but you hold the keys.\",\n \"Privacy isn't a feature. It's the architecture.\",\n \"Sovereign storage, zero knowledge.\",\n \"Your .env is safe here — we use real cryptography.\",\n // Playful / nerdy\n \"UCAN do anything.\",\n \"Keys generated, delegations granted, data liberated.\",\n \"Decentralized storage, centralized vibes.\",\n \"Trust nobody, delegate everything.\",\n \"sudo make me a sandwich, encrypted.\",\n \"Have you tried turning your keys off and on again?\",\n \"All your base are belong to you.\",\n \"In UCAN we trust.\",\n \"0 knowledge, 100% confidence.\",\n \"Keeping secrets since 2024.\",\n];\n\nfunction getHolidayTagline(): string | null {\n const now = new Date();\n const month = now.getMonth() + 1;\n const day = now.getDate();\n\n for (const h of HOLIDAY_TAGLINES) {\n const range = h.range ?? 0;\n if (h.month === month && Math.abs(day - h.day) <= range) {\n return h.tagline;\n }\n }\n return null;\n}\n\nexport function pickTagline(): string {\n const holiday = getHolidayTagline();\n if (holiday) return holiday;\n return TAGLINES[Math.floor(Math.random() * TAGLINES.length)];\n}\n","import { isInteractive } from \"./formatter.js\";\nimport { pickTagline } from \"./taglines.js\";\nimport { theme } from \"./theme.js\";\nimport { execSync } from \"node:child_process\";\n\nlet bannerEmitted = false;\n\nfunction resolveCommitHash(): string | null {\n try {\n return (\n execSync(\"git rev-parse --short HEAD\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim() || null\n );\n } catch {\n return null;\n }\n}\n\nfunction formatBannerLine(version: string): string {\n const commit = resolveCommitHash();\n const tagline = pickTagline();\n\n const versionPart = `tc v${version}`;\n const commitPart = commit ? ` (${commit})` : \"\";\n const separator = \" — \";\n\n if (!isInteractive()) {\n return `${versionPart}${commitPart}${separator}${tagline}`;\n }\n\n return [\n theme.brand(\"☁️ tc\"),\n \" \",\n theme.muted(`v${version}`),\n commit ? theme.dim(` (${commit})`) : \"\",\n theme.dim(separator),\n theme.primary(tagline),\n ].join(\"\");\n}\n\nexport function emitBanner(version: string): void {\n if (bannerEmitted) return;\n if (!isInteractive()) return;\n if (process.env.TC_HIDE_BANNER === \"1\") return;\n\n bannerEmitted = true;\n process.stderr.write(formatBannerLine(version) + \"\\n\\n\");\n}\n","import { join } from \"node:path\";\nimport {\n CONFIG_DIR,\n PROFILES_DIR,\n CONFIG_FILE,\n DEFAULT_PROFILE,\n DEFAULT_HOST,\n} from \"./constants.js\";\nimport { rm } from \"node:fs/promises\";\nimport {\n readJson,\n writeJson,\n fileExists,\n ensureDir,\n removeDir,\n listDirs,\n} from \"./storage.js\";\nimport type { GlobalConfig, ProfileConfig, CLIContext } from \"./types.js\";\nimport { CLIError } from \"../output/errors.js\";\n\nexport class ProfileManager {\n // ── Initialization ──────────────────────────────────────────────────\n\n /**\n * Creates ~/.tinycloud/ and ~/.tinycloud/profiles/ if they don't exist.\n */\n static async ensureConfigDir(): Promise<void> {\n await ensureDir(CONFIG_DIR);\n await ensureDir(PROFILES_DIR);\n }\n\n // ── Global config ───────────────────────────────────────────────────\n\n /**\n * Reads config.json. Returns a default config if the file is missing.\n */\n static async getConfig(): Promise<GlobalConfig> {\n const config = await readJson<GlobalConfig>(CONFIG_FILE);\n if (!config) {\n return { defaultProfile: DEFAULT_PROFILE, version: 1 };\n }\n return config;\n }\n\n /**\n * Writes the global config to config.json.\n */\n static async setConfig(config: GlobalConfig): Promise<void> {\n await ProfileManager.ensureConfigDir();\n await writeJson(CONFIG_FILE, config);\n }\n\n // ── Profile CRUD ────────────────────────────────────────────────────\n\n /**\n * Returns the profile config for the given name.\n * Throws CLIError if the profile doesn't exist.\n */\n static async getProfile(name: string): Promise<ProfileConfig> {\n const profilePath = join(PROFILES_DIR, name, \"profile.json\");\n const profile = await readJson<ProfileConfig>(profilePath);\n if (!profile) {\n throw new CLIError(\n \"PROFILE_NOT_FOUND\",\n `Profile \"${name}\" does not exist. Run \\`tc init\\` or \\`tc profile create ${name}\\` first.`,\n );\n }\n return profile;\n }\n\n /**\n * Saves a profile config, creating the profile directory if needed.\n */\n static async setProfile(name: string, data: ProfileConfig): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"profile.json\"), data);\n }\n\n /**\n * Returns true if a profile directory exists.\n */\n static async profileExists(name: string): Promise<boolean> {\n return fileExists(join(PROFILES_DIR, name, \"profile.json\"));\n }\n\n /**\n * Returns an array of profile directory names.\n */\n static async listProfiles(): Promise<string[]> {\n return listDirs(PROFILES_DIR);\n }\n\n /**\n * Deletes a profile directory.\n * Throws if trying to delete the current default profile.\n */\n static async deleteProfile(name: string): Promise<void> {\n const config = await ProfileManager.getConfig();\n if (config.defaultProfile === name) {\n throw new CLIError(\n \"PROFILE_DELETE_DEFAULT\",\n `Cannot delete the default profile \"${name}\". Change the default first with \\`tc profile default <other>\\`.`,\n );\n }\n const profileDir = join(PROFILES_DIR, name);\n await removeDir(profileDir);\n }\n\n // ── Key management ──────────────────────────────────────────────────\n\n /**\n * Returns the parsed JWK for a profile, or null if no key exists.\n */\n static async getKey(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"key.json\"));\n }\n\n /**\n * Saves a JWK key for a profile.\n */\n static async setKey(name: string, jwk: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"key.json\"), jwk);\n }\n\n // ── Session management ──────────────────────────────────────────────\n\n /**\n * Returns the parsed session for a profile, or null if none exists.\n */\n static async getSession(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"session.json\"));\n }\n\n /**\n * Saves session data for a profile.\n */\n static async setSession(name: string, session: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"session.json\"), session);\n }\n\n /**\n * Removes the session file for a profile.\n */\n static async clearSession(name: string): Promise<void> {\n const sessionPath = join(PROFILES_DIR, name, \"session.json\");\n try {\n await rm(sessionPath);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n }\n\n // ── Cache management ────────────────────────────────────────────────\n\n /**\n * Returns the path to the profile's cache directory, creating it if needed.\n */\n static async getCacheDir(name: string): Promise<string> {\n const cacheDir = join(PROFILES_DIR, name, \"cache\");\n await ensureDir(cacheDir);\n return cacheDir;\n }\n\n // ── Resolution helpers ──────────────────────────────────────────────\n\n /**\n * Resolves the full CLI context from flags, env vars, and config.\n *\n * Profile resolution: options.profile > TC_PROFILE env > config.defaultProfile > \"default\"\n * Host resolution: options.host > TC_HOST env > profile.host > DEFAULT_HOST\n */\n static async resolveContext(options: {\n profile?: string;\n host?: string;\n verbose?: boolean;\n noCache?: boolean;\n quiet?: boolean;\n }): Promise<CLIContext> {\n // Resolve profile name\n const config = await ProfileManager.getConfig();\n const profile =\n options.profile ??\n process.env.TC_PROFILE ??\n config.defaultProfile ??\n DEFAULT_PROFILE;\n\n // Resolve host — try profile config if it exists, but don't fail if it doesn't\n let profileHost: string | undefined;\n try {\n const profileConfig = await ProfileManager.getProfile(profile);\n profileHost = profileConfig.host;\n } catch {\n // Profile may not exist yet (e.g., during `tc init`)\n }\n\n const host =\n options.host ??\n process.env.TC_HOST ??\n profileHost ??\n DEFAULT_HOST;\n\n return {\n profile,\n host,\n verbose: options.verbose ?? false,\n noCache: options.noCache ?? false,\n quiet: options.quiet ?? false,\n };\n }\n}\n","import { readFile, writeFile, stat, mkdir, rm, readdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Read and parse a JSON file. Returns null if the file does not exist.\n * Throws on any other error (permission denied, invalid JSON, etc.).\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n const data = await readFile(filePath, \"utf-8\");\n return JSON.parse(data) as T;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n}\n\n/**\n * Write data as JSON to a file. Creates parent directories if needed.\n */\nexport async function writeJson(filePath: string, data: unknown): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(data, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Check if a file exists at the given path.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await stat(filePath);\n return true;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n}\n\n/**\n * Ensure a directory exists (mkdir -p).\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Remove a directory recursively (rm -rf).\n */\nexport async function removeDir(dirPath: string): Promise<void> {\n await rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * List directory names (not files) inside a directory.\n * Returns an empty array if the directory does not exist.\n */\nexport async function listDirs(dirPath: string): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n","import { TCWSessionManager, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\nimport { randomBytes } from \"node:crypto\";\n\nlet wasmInitialized = false;\n\nfunction ensureWasm(): void {\n if (!wasmInitialized) {\n initPanicHook();\n wasmInitialized = true;\n }\n}\n\n/**\n * Generate a new Ed25519 keypair. Returns the JWK.\n */\nexport function generateKey(): { jwk: object; did: string } {\n ensureWasm();\n const mgr = new TCWSessionManager();\n const keyId = mgr.createSessionKey(\"cli\");\n const jwkStr = mgr.jwk(keyId);\n if (!jwkStr) throw new Error(\"Failed to generate key\");\n const jwk = JSON.parse(jwkStr);\n const did = mgr.getDID(keyId);\n return { jwk, did };\n}\n\n/**\n * Get the DID from an existing JWK.\n */\nexport function keyToDID(jwk: object): string {\n ensureWasm();\n const mgr = new TCWSessionManager();\n // Import key by creating with known ID, then getting DID\n // For now, re-generate and return — TODO: import support\n const keyId = mgr.createSessionKey(\"imported\");\n return mgr.getDID(keyId);\n}\n\n/**\n * Generate a new random Ethereum private key.\n * Returns the hex-encoded key with 0x prefix.\n */\nexport function generateEthereumPrivateKey(): string {\n const keyBytes = randomBytes(32);\n return \"0x\" + keyBytes.toString(\"hex\");\n}\n\n/**\n * Derive the Ethereum address from a private key.\n * Uses PrivateKeySigner from node-sdk.\n */\nexport async function deriveAddress(privateKey: string): Promise<string> {\n const signer = new PrivateKeySigner(privateKey);\n return signer.getAddress();\n}\n\n/**\n * Create a did:pkh DID from an Ethereum address.\n * Uses EIP-155 chain ID 1 (mainnet).\n */\nexport function addressToDID(address: string, chainId: number = 1): string {\n return `did:pkh:eip155:${chainId}:${address}`;\n}\n\n/**\n * Generate a new local Ethereum key and return all identity info.\n */\nexport async function generateLocalIdentity(chainId: number = 1): Promise<{\n privateKey: string;\n address: string;\n did: string;\n}> {\n const privateKey = generateEthereumPrivateKey();\n const address = await deriveAddress(privateKey);\n const did = addressToDID(address, chainId);\n return { privateKey, address, did };\n}\n\n/**\n * Sign in to TinyCloud using a local Ethereum private key.\n * Creates a TinyCloudNode with the private key and calls signIn().\n */\nexport async function localKeySignIn(options: {\n privateKey: string;\n host: string;\n}): Promise<{\n spaceId: string;\n address: string;\n chainId: number;\n}> {\n const { TinyCloudNode } = await import(\"@tinycloud/node-sdk\");\n\n const node = new TinyCloudNode({\n privateKey: options.privateKey,\n host: options.host,\n autoCreateSpace: true,\n });\n\n await node.signIn();\n\n const address = await new PrivateKeySigner(options.privateKey).getAddress();\n\n return {\n spaceId: node.spaceId ?? \"\",\n address,\n chainId: 1,\n };\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { isInteractive } from \"../output/formatter.js\";\nimport { createInterface } from \"node:readline\";\n\nconst OPENKEY_BASE = \"https://openkey.so\";\n\ninterface DelegationData {\n delegationHeader: { Authorization: string };\n delegationCid: string;\n spaceId: string;\n [key: string]: unknown;\n}\n\n/**\n * Start the browser auth flow.\n * Mode 1 (default): local HTTP callback server\n * Mode 2 (--paste): manual code paste\n */\nexport async function startAuthFlow(\n did: string,\n options: { paste?: boolean; jwk?: object; host?: string } = {}\n): Promise<DelegationData> {\n if (options.paste) {\n return pasteFlow(did, options);\n }\n\n try {\n return await callbackFlow(did, options);\n } catch {\n // Fallback to paste if browser can't open\n if (isInteractive()) {\n console.error(\"Could not open browser. Falling back to manual paste mode.\");\n return pasteFlow(did, options);\n }\n throw new Error(\"Cannot open browser in non-interactive mode. Use --paste flag.\");\n }\n}\n\nfunction buildAuthUrl(did: string, options: { jwk?: object; host?: string; callback?: string } = {}): string {\n const params = new URLSearchParams();\n params.set(\"did\", did);\n if (options.callback) {\n params.set(\"callback\", options.callback);\n }\n if (options.jwk) {\n // base64url-encode the JWK\n const jwkB64 = Buffer.from(JSON.stringify(options.jwk)).toString(\"base64url\");\n params.set(\"jwk\", jwkB64);\n }\n if (options.host) {\n params.set(\"host\", options.host);\n }\n return `${OPENKEY_BASE}/delegate?${params.toString()}`;\n}\n\nasync function callbackFlow(did: string, options: { jwk?: object; host?: string } = {}): Promise<DelegationData> {\n return new Promise((resolve, reject) => {\n let timeout: ReturnType<typeof setTimeout>;\n let settled = false;\n let rl: ReturnType<typeof createInterface> | undefined;\n\n function settle(result: { data?: DelegationData; error?: Error }) {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n server.close();\n if (rl) {\n rl.close();\n }\n if (result.data) {\n resolve(result.data);\n } else {\n reject(result.error);\n }\n }\n\n function parsePasteInput(input: string): DelegationData {\n const trimmed = input.trim();\n // Try parsing as JSON directly\n try {\n return JSON.parse(trimmed) as DelegationData;\n } catch {\n // Try base64 decoding first\n const decoded = Buffer.from(trimmed, \"base64\").toString(\"utf-8\");\n return JSON.parse(decoded) as DelegationData;\n }\n }\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n if (req.method === \"POST\" && req.url === \"/callback\") {\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => { body += chunk.toString(); });\n req.on(\"end\", () => {\n try {\n const data = JSON.parse(body) as DelegationData;\n // Send CORS headers and success response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n res.end(JSON.stringify({ success: true }));\n settle({ data });\n } catch (err) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON\" }));\n settle({ error: new Error(\"Invalid delegation data received\") });\n }\n });\n } else if (req.method === \"OPTIONS\") {\n // CORS preflight\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end();\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.listen(0, \"127.0.0.1\", async () => {\n const addr = server.address();\n if (!addr || typeof addr === \"string\") {\n settle({ error: new Error(\"Failed to start callback server\") });\n return;\n }\n const port = addr.port;\n const callbackUrl = `http://127.0.0.1:${port}/callback`;\n const authUrl = buildAuthUrl(did, { ...options, callback: callbackUrl });\n\n if (isInteractive()) {\n console.error(`Opening browser for authentication...`);\n console.error(`If the browser doesn't open, visit: ${authUrl}`);\n }\n\n try {\n const open = (await import(\"open\")).default;\n await open(authUrl);\n } catch {\n server.close();\n throw new Error(\"Failed to open browser\");\n }\n\n // In interactive mode, also accept paste input while waiting for callback\n if (isInteractive()) {\n console.error(`\\nIf the browser can't connect back, paste the delegation code here:`);\n rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n rl.on(\"line\", (input) => {\n if (settled) return;\n try {\n const data = parsePasteInput(input);\n settle({ data });\n } catch {\n console.error(\"Invalid delegation code. Expected JSON or base64-encoded JSON. Try again:\");\n }\n });\n }\n });\n\n // Timeout after 5 minutes\n timeout = setTimeout(() => {\n settle({ error: new Error(\"Authentication timed out after 5 minutes\") });\n }, 5 * 60 * 1000);\n });\n}\n\nasync function pasteFlow(did: string, options: { jwk?: object; host?: string } = {}): Promise<DelegationData> {\n const authUrl = buildAuthUrl(did, options);\n\n console.error(`\\nOpen this URL in a browser to authenticate:\\n`);\n console.error(` ${authUrl}\\n`);\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise((resolve, reject) => {\n rl.question(\"Paste delegation code: \", (input) => {\n rl.close();\n try {\n // Try parsing as JSON directly\n const data = JSON.parse(input.trim()) as DelegationData;\n resolve(data);\n } catch {\n // Try base64 decoding first\n try {\n const decoded = Buffer.from(input.trim(), \"base64\").toString(\"utf-8\");\n const data = JSON.parse(decoded) as DelegationData;\n resolve(data);\n } catch {\n reject(new Error(\"Invalid delegation code. Expected JSON or base64-encoded JSON.\"));\n }\n }\n });\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_HOST, DEFAULT_CHAIN_ID } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Initialize a new TinyCloud profile\")\n .option(\"--name <profile>\", \"Profile name\", \"default\")\n .option(\"--key-only\", \"Only generate key, skip authentication\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .option(\"--paste\", \"Use manual paste mode for authentication\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const profileName: string = options.name;\n const host: string = options.host ?? globalOpts.host ?? DEFAULT_HOST;\n\n // Check if profile already exists\n if (await ProfileManager.profileExists(profileName)) {\n throw new CLIError(\n \"PROFILE_EXISTS\",\n `Profile \"${profileName}\" already exists. Use \\`tc profile delete ${profileName}\\` first or choose a different name.`,\n ExitCode.ERROR,\n );\n }\n\n await ProfileManager.ensureConfigDir();\n\n // Generate key\n const { jwk, did } = await withSpinner(\"Generating key...\", async () => {\n return generateKey();\n });\n\n await ProfileManager.setKey(profileName, jwk);\n\n // Create initial profile\n const profileConfig = {\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n createdAt: new Date().toISOString(),\n };\n\n await ProfileManager.setProfile(profileName, profileConfig);\n\n // Set as default if this is \"default\" or no default exists\n const config = await ProfileManager.getConfig();\n if (profileName === \"default\" || !await ProfileManager.profileExists(config.defaultProfile)) {\n await ProfileManager.setConfig({ ...config, defaultProfile: profileName });\n }\n\n if (options.keyOnly) {\n outputJson({\n profile: profileName,\n did,\n host,\n authenticated: false,\n });\n return;\n }\n\n // Auth flow\n const delegationData = await startAuthFlow(did, {\n paste: options.paste,\n jwk,\n host,\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with auth data\n await ProfileManager.setProfile(profileName, {\n ...profileConfig,\n spaceId: delegationData.spaceId,\n primaryDid: delegationData.primaryDid as string | undefined,\n });\n\n outputJson({\n profile: profileName,\n did,\n host,\n spaceId: delegationData.spaceId,\n authenticated: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatField, isInteractive, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_CHAIN_ID } from \"../config/constants.js\";\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\nimport {\n generateLocalIdentity,\n deriveAddress,\n addressToDID,\n localKeySignIn,\n generateKey,\n} from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport type { AuthMethod } from \"../config/types.js\";\n\n/**\n * Prompt user to choose an auth method interactively.\n * Returns \"local\" for non-interactive (CI/headless) environments.\n */\nasync function promptAuthMethod(): Promise<AuthMethod> {\n if (!isInteractive()) {\n return \"local\";\n }\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise<AuthMethod>((resolve) => {\n process.stderr.write(\"\\n\" + theme.heading(\"Choose authentication method:\") + \"\\n\");\n process.stderr.write(` ${theme.accent(\"1)\")} OpenKey ${theme.muted(\"(browser-based, for interactive use)\")}\\n`);\n process.stderr.write(` ${theme.accent(\"2)\")} Local key ${theme.muted(\"(Ethereum private key, for agents/CI)\")}\\n\\n`);\n\n rl.question(\"Enter choice [1]: \", (answer) => {\n rl.close();\n const trimmed = answer.trim();\n if (trimmed === \"2\" || trimmed.toLowerCase() === \"local\") {\n resolve(\"local\");\n } else {\n resolve(\"openkey\");\n }\n });\n });\n}\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command(\"auth\").description(\"Authentication management\");\n\n auth\n .command(\"login\")\n .description(\"Authenticate with TinyCloud\")\n .option(\"--paste\", \"Use manual paste mode instead of browser callback\")\n .option(\"--method <method>\", \"Authentication method: local or openkey\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n // Determine auth method\n let method: AuthMethod;\n if (options.method) {\n if (options.method !== \"local\" && options.method !== \"openkey\") {\n throw new CLIError(\n \"INVALID_METHOD\",\n `Invalid auth method \"${options.method}\". Use \"local\" or \"openkey\".`,\n ExitCode.USAGE_ERROR,\n );\n }\n method = options.method;\n } else {\n method = await promptAuthMethod();\n }\n\n if (method === \"local\") {\n await handleLocalAuth(ctx.profile, ctx.host);\n } else {\n await handleOpenKeyAuth(ctx.profile, ctx.host, options.paste);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"logout\")\n .description(\"Clear session (keep key)\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n await ProfileManager.clearSession(ctx.profile);\n outputJson({ profile: ctx.profile, authenticated: false });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"status\")\n .description(\"Show current authentication state\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const hasKey = await ProfileManager.getKey(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n let profile;\n try {\n profile = await ProfileManager.getProfile(ctx.profile);\n } catch {\n profile = null;\n }\n\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n authenticated,\n did: profile?.did ?? null,\n primaryDid: profile?.primaryDid ?? null,\n spaceId: profile?.spaceId ?? null,\n host: ctx.host,\n profile: ctx.profile,\n hasKey: hasKey !== null,\n authMethod: profile?.authMethod ?? null,\n address: profile?.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Authentication Status\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile?.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Host\", ctx.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile?.did ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Primary DID\", profile?.primaryDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile?.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile?.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Has Key\", hasKey !== null) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"whoami\")\n .description(\"Show identity information\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n profile: ctx.profile,\n did: profile.did,\n primaryDid: profile.primaryDid ?? null,\n spaceId: profile.spaceId ?? null,\n host: profile.host,\n authenticated,\n authMethod: profile.authMethod ?? null,\n address: profile.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Identity\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile.did) + \"\\n\");\n process.stdout.write(formatField(\"Primary DID\", profile.primaryDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Host\", profile.host) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/**\n * Handle local Ethereum key authentication.\n * Generates or reuses a local private key, creates a did:pkh identity,\n * and signs in to TinyCloud directly (no browser needed).\n */\nasync function handleLocalAuth(profileName: string, host: string): Promise<void> {\n const profile = await ProfileManager.getProfile(profileName).catch(() => null);\n\n let privateKey: string;\n let address: string;\n let did: string;\n\n if (profile?.authMethod === \"local\" && profile.privateKey && profile.address) {\n // Reuse existing local key\n privateKey = profile.privateKey;\n address = profile.address;\n did = profile.did;\n\n if (isInteractive()) {\n process.stderr.write(theme.muted(\"Using existing local key\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n }\n } else {\n // Generate new local identity\n const identity = await withSpinner(\"Generating Ethereum key...\", async () => {\n return generateLocalIdentity(DEFAULT_CHAIN_ID);\n });\n\n privateKey = identity.privateKey;\n address = identity.address;\n did = identity.did;\n\n if (isInteractive()) {\n process.stderr.write(\"\\n\" + theme.heading(\"Local Key Generated\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n process.stderr.write(formatField(\"DID\", did) + \"\\n\\n\");\n }\n }\n\n // We also need a session key (Ed25519 JWK) for the profile\n const hasKey = await ProfileManager.getKey(profileName);\n if (!hasKey) {\n const { jwk } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n await ProfileManager.setKey(profileName, jwk);\n }\n\n // Sign in using the private key\n const sessionResult = await withSpinner(\"Signing in...\", async () => {\n return localKeySignIn({ privateKey, host });\n });\n\n // Store session data\n await ProfileManager.setSession(profileName, {\n authMethod: \"local\",\n address,\n chainId: DEFAULT_CHAIN_ID,\n spaceId: sessionResult.spaceId,\n });\n\n // Update profile\n await ProfileManager.setProfile(profileName, {\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n primaryDid: did,\n spaceId: sessionResult.spaceId,\n createdAt: profile?.createdAt ?? new Date().toISOString(),\n authMethod: \"local\",\n privateKey,\n address,\n });\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did,\n address,\n spaceId: sessionResult.spaceId,\n authMethod: \"local\",\n });\n}\n\n/**\n * Handle OpenKey (browser-based) authentication.\n * This is the original auth flow.\n */\nasync function handleOpenKeyAuth(profileName: string, host: string, paste?: boolean): Promise<void> {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${profileName}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n // Get DID from profile\n const profile = await ProfileManager.getProfile(profileName);\n\n // Start browser auth flow\n const delegationData = await startAuthFlow(profile.did, {\n paste,\n jwk: key,\n host,\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with primary DID if present\n const updatedProfile = {\n ...profile,\n authMethod: \"openkey\" as const,\n };\n\n if (delegationData.spaceId) {\n updatedProfile.spaceId = delegationData.spaceId;\n updatedProfile.primaryDid = delegationData.primaryDid as string | undefined;\n }\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did: profile.did,\n spaceId: delegationData.spaceId,\n authMethod: \"openkey\",\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes, formatTimeAgo } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\nexport function registerKvCommand(program: Command): void {\n const kv = program.command(\"kv\").description(\"Key-value store operations\");\n\n // tc kv get <key>\n kv\n .command(\"get <key>\")\n .description(\"Get a value by key\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Getting ${key}...`, () => node.kv.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n const metadata = result.data.headers ?? {};\n\n if (options.output) {\n // Write to file\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n // Raw output - write directly to stdout\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n // Output value\n if (shouldOutputJson()) {\n outputJson({\n key,\n data,\n metadata,\n });\n } else {\n // Just output the raw value for get - useful for piping\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv put <key> [value]\n kv\n .command(\"put <key> [value]\")\n .description(\"Set a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n // Determine value source\n let putValue: string | Buffer;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = await readFile(options.file);\n } else if (options.stdin) {\n putValue = await readStdin();\n } else {\n // Try to parse as JSON, fall back to string\n try {\n putValue = JSON.parse(value!);\n } catch {\n putValue = value!;\n }\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.kv.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv delete <key>\n kv\n .command(\"delete <key>\")\n .description(\"Delete a key\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.kv.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv list\n kv\n .command(\"list\")\n .description(\"List keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing keys...\", () => node.kv.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n if (shouldOutputJson()) {\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } else {\n if (keyList.length === 0) {\n process.stdout.write(theme.muted(\"No keys found.\") + \"\\n\");\n } else {\n const rows = keyList.map((e: any) => [\n e.key || e,\n e.contentLength ? formatBytes(e.contentLength) : \"—\",\n e.updatedAt ? formatTimeAgo(e.updatedAt) : \"—\",\n ]);\n process.stdout.write(formatTable([\"Key\", \"Size\", \"Updated\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv head <key>\n kv\n .command(\"head <key>\")\n .description(\"Get metadata for a key (no body)\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Checking ${key}...`, () => node.kv.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? {},\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { CLIContext } from \"../config/types.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\n\n/**\n * Create a TinyCloudNode instance from the current CLI context.\n * Uses the profile's persisted session and key.\n *\n * Supports both auth methods:\n * - \"local\": Uses the stored Ethereum private key directly\n * - \"openkey\": Restores session from stored delegation data (browser auth flow)\n */\nexport async function createSDKInstance(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile) as Record<string, unknown> | null;\n const key = await ProfileManager.getKey(ctx.profile);\n\n // For local auth, use the stored private key\n const effectivePrivateKey = options?.privateKey ?? profile.privateKey;\n\n if (!key && !effectivePrivateKey) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n if (profile.authMethod === \"local\" && effectivePrivateKey) {\n // Local key auth: create node with private key and sign in\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: effectivePrivateKey,\n });\n\n await node.signIn();\n return node;\n }\n\n // OpenKey / delegation-based auth\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: options?.privateKey,\n });\n\n if (options?.privateKey) {\n // Sign in with private key (existing behavior)\n await node.signIn();\n } else if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\n // Restore session from stored delegation data (browser auth flow)\n await node.restoreSession({\n delegationHeader: session.delegationHeader as { Authorization: string },\n delegationCid: session.delegationCid as string,\n spaceId: session.spaceId as string,\n jwk: (session.jwk as object) ?? key,\n verificationMethod: (session.verificationMethod as string) ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n });\n }\n\n return node;\n}\n\n/**\n * Ensure the user is authenticated.\n * Throws AUTH_REQUIRED if no session exists.\n */\nexport async function ensureAuthenticated(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile).catch(() => null);\n\n // For local auth, we can sign in directly without a stored session\n if (profile?.authMethod === \"local\" && profile.privateKey) {\n return createSDKInstance(ctx, { privateKey: profile.privateKey });\n }\n\n const session = await ProfileManager.getSession(ctx.profile);\n\n if (!session) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `Not authenticated. Run \\`tc auth login\\` or \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n return createSDKInstance(ctx, options);\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerSpaceCommand(program: Command): void {\n const space = program.command(\"space\").description(\"Space management\");\n\n space\n .command(\"list\")\n .description(\"List spaces\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n if (shouldOutputJson()) {\n outputJson({ spaces: result.data, count: result.data.length });\n } else {\n if (result.data.length === 0) {\n process.stdout.write(theme.muted(\"No spaces found.\") + \"\\n\");\n } else {\n const rows = result.data.map((s: any) => [\n s.id || s.spaceId || \"—\",\n s.name || \"—\",\n s.owner || \"—\",\n ]);\n process.stdout.write(formatTable([\"Space ID\", \"Name\", \"Owner\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"create <name>\")\n .description(\"Create a new space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.create(name);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n outputJson({ spaceId: result.data.id, name });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"info [space-id]\")\n .description(\"Get space info\")\n .action(async (spaceId: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const targetId = spaceId ?? node.spaceId;\n if (!targetId) {\n throw new CLIError(\"NO_SPACE\", \"No space ID specified and no active space\", ExitCode.ERROR);\n }\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n outputJson({\n spaceId: targetId,\n name: profile.spaceName,\n owner: node.did,\n host: ctx.host,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"switch <name>\")\n .description(\"Switch active space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n await ProfileManager.setProfile(ctx.profile, { ...profile, spaceName: name });\n\n outputJson({ profile: ctx.profile, spaceName: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","/**\n * Parse a duration string into milliseconds.\n * Supports: \"1h\", \"30m\", \"7d\", \"1w\", or ISO date string.\n */\nexport function parseDuration(input: string): number {\n const match = input.match(/^(\\d+)(m|h|d|w)$/);\n if (match) {\n const value = parseInt(match[1], 10);\n const unit = match[2];\n const multipliers: Record<string, number> = {\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n };\n return value * multipliers[unit];\n }\n\n // Try as ISO date\n const date = new Date(input);\n if (!isNaN(date.getTime())) {\n const ms = date.getTime() - Date.now();\n if (ms <= 0) {\n throw new Error(`Expiry date \"${input}\" is in the past`);\n }\n return ms;\n }\n\n throw new Error(`Invalid duration: \"${input}\". Use format like \"1h\", \"7d\", or an ISO date.`);\n}\n\n/**\n * Parse duration to an expiry Date.\n */\nexport function parseExpiry(input: string): Date {\n return new Date(Date.now() + parseDuration(input));\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\n\nexport function registerDelegationCommand(program: Command): void {\n const delegation = program.command(\"delegation\").description(\"Manage delegations\");\n\n delegation\n .command(\"create\")\n .description(\"Create a delegation\")\n .requiredOption(\"--to <did>\", \"Recipient DID\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .requiredOption(\"--actions <actions>\", \"Comma-separated actions (e.g., kv/get,kv/list)\")\n .option(\"--expiry <duration>\", \"Expiry duration (e.g., 1h, 7d, ISO date)\", \"1h\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.delegationManager.create({\n delegateDID: options.to,\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n cid: result.data.cid,\n delegateDid: options.to,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"list\")\n .description(\"List delegations\")\n .option(\"--granted\", \"Show only delegations I've granted\")\n .option(\"--received\", \"Show only delegations I've received\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n let delegations: any[] = result.data;\n\n // Filter if requested\n if (options.granted) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => d.delegatorDID === myDid);\n } else if (options.received) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => d.delegateDID === myDid || d.delegateDID?.includes(myDid));\n }\n\n outputJson({\n delegations: delegations.map((d: any) => ({\n cid: d.cid,\n delegatee: d.delegateDID,\n delegator: d.delegatorDID,\n path: d.path,\n actions: d.actions,\n expiry: d.expiry instanceof Date ? d.expiry.toISOString() : d.expiry,\n })),\n count: delegations.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"info <cid>\")\n .description(\"Get delegation details\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.get(cid);\n if (!result.ok) {\n throw new CLIError(\"NOT_FOUND\", `Delegation \"${cid}\" not found`, ExitCode.NOT_FOUND);\n }\n\n outputJson(result.data);\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"revoke <cid>\")\n .description(\"Revoke a delegation\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.revoke(cid);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ cid, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\n\nexport function registerShareCommand(program: Command): void {\n const share = program.command(\"share\").description(\"Share data with others\");\n\n share\n .command(\"create\")\n .description(\"Create a share link\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .option(\"--actions <actions>\", \"Comma-separated actions\", \"kv/get\")\n .option(\"--expiry <duration>\", \"Expiry duration\", \"7d\")\n .option(\"--web-link\", \"Generate a web UI link for non-technical recipients\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.sharing.generate({\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const output: Record<string, unknown> = {\n token: result.data.token ?? result.data.cid,\n shareData: result.data.encodedData ?? result.data.url,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n };\n\n if (options.webLink) {\n const shareData = result.data.encodedData ?? result.data.url ?? \"\";\n output.webLink = `https://openkey.cloud/share?data=${encodeURIComponent(shareData)}`;\n }\n\n outputJson(output);\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"receive [data]\")\n .description(\"Receive a share\")\n .option(\"--stdin\", \"Read share data from stdin\")\n .action(async (data: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n let shareData: string;\n if (options.stdin) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n shareData = Buffer.concat(chunks).toString(\"utf-8\").trim();\n } else if (data) {\n shareData = data;\n } else {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide share data or use --stdin\", ExitCode.USAGE_ERROR);\n }\n\n const result = await node.sharing.receive(shareData);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n received: true,\n spaceId: result.data.spaceId,\n path: result.data.path,\n actions: result.data.actions,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"list\")\n .description(\"List active shares\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ shares: result.data, count: result.data.length });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"revoke <token>\")\n .description(\"Revoke a share\")\n .action(async (token: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.revoke(token);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ token, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\n\nexport function registerNodeCommand(program: Command): void {\n const node = program.command(\"node\").description(\"Node health and info\");\n\n node\n .command(\"health\")\n .description(\"Check node health\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n const response = await fetch(`${ctx.host}/healthz`);\n const latencyMs = Date.now() - start;\n\n outputJson({\n healthy: response.ok,\n host: ctx.host,\n latencyMs,\n });\n } catch (error) {\n if (error instanceof TypeError && (error as Error).message.includes(\"fetch\")) {\n outputJson({ healthy: false, host: (await ProfileManager.resolveContext(cmd.optsWithGlobals())).host, error: \"Connection refused\" });\n } else {\n handleError(error);\n }\n }\n });\n\n node\n .command(\"version\")\n .description(\"Get node version\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const response = await fetch(`${ctx.host}/info`);\n if (!response.ok) {\n throw new CLIError(\"NODE_ERROR\", `Node returned ${response.status}`, ExitCode.NODE_ERROR);\n }\n\n const data = await response.json() as Record<string, unknown>;\n outputJson({ ...data, host: ctx.host });\n } catch (error) {\n handleError(error);\n }\n });\n\n node\n .command(\"status\")\n .description(\"Combined health and version info\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n\n // Fetch health and version in parallel\n const [healthRes, versionRes] = await Promise.allSettled([\n fetch(`${ctx.host}/healthz`),\n fetch(`${ctx.host}/info`),\n ]);\n\n const latencyMs = Date.now() - start;\n const healthy = healthRes.status === \"fulfilled\" && healthRes.value.ok;\n\n let versionData: Record<string, unknown> = {};\n if (versionRes.status === \"fulfilled\" && versionRes.value.ok) {\n versionData = await versionRes.value.json() as Record<string, unknown>;\n }\n\n outputJson({\n healthy,\n host: ctx.host,\n latencyMs,\n ...versionData,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, isInteractive, shouldOutputJson, formatField } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerProfileCommand(program: Command): void {\n const profile = program.command(\"profile\").description(\"Profile management\");\n\n profile\n .command(\"list\")\n .description(\"List all profiles\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const config = await ProfileManager.getConfig();\n const names = await ProfileManager.listProfiles();\n\n const profiles = await Promise.all(\n names.map(async (name) => {\n try {\n const p = await ProfileManager.getProfile(name);\n return {\n name: p.name,\n host: p.host,\n did: p.did,\n active: name === config.defaultProfile,\n };\n } catch {\n return { name, host: null, did: null, active: name === config.defaultProfile };\n }\n })\n );\n\n if (shouldOutputJson()) {\n outputJson({\n profiles,\n defaultProfile: config.defaultProfile,\n });\n } else {\n for (const p of profiles) {\n const marker = p.active ? theme.success(\"● \") : \" \";\n const name = p.active ? theme.brand(p.name) : p.name;\n const host = theme.muted(p.host || \"no host\");\n process.stdout.write(`${marker}${name} ${host}\\n`);\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"create <name>\")\n .description(\"Create a new profile\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const host = options.host ?? globalOpts.host ?? \"https://node.tinycloud.xyz\";\n\n if (await ProfileManager.profileExists(name)) {\n throw new CLIError(\"PROFILE_EXISTS\", `Profile \"${name}\" already exists`, ExitCode.ERROR);\n }\n\n await ProfileManager.ensureConfigDir();\n const { jwk, did } = generateKey();\n await ProfileManager.setKey(name, jwk);\n await ProfileManager.setProfile(name, {\n name,\n host,\n chainId: 1,\n spaceName: \"default\",\n did,\n createdAt: new Date().toISOString(),\n });\n\n outputJson({ profile: name, did, host, created: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"show [name]\")\n .description(\"Show profile details\")\n .action(async (name: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profileName = name ?? ctx.profile;\n\n const p = await ProfileManager.getProfile(profileName);\n const hasKey = (await ProfileManager.getKey(profileName)) !== null;\n const hasSession = (await ProfileManager.getSession(profileName)) !== null;\n const config = await ProfileManager.getConfig();\n const isDefault = profileName === config.defaultProfile;\n\n if (shouldOutputJson()) {\n outputJson({\n ...p,\n hasKey,\n hasSession,\n isDefault,\n });\n } else {\n process.stdout.write(`${theme.heading(p.name)}${isDefault ? theme.success(\" (default)\") : \"\"}\\n`);\n process.stdout.write(formatField(\"Host\", p.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", p.did) + \"\\n\");\n process.stdout.write(formatField(\"Space\", p.spaceId || null) + \"\\n\");\n process.stdout.write(formatField(\"Key\", hasKey) + \"\\n\");\n process.stdout.write(formatField(\"Session\", hasSession) + \"\\n\");\n process.stdout.write(formatField(\"Created\", p.createdAt) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"switch <name>\")\n .description(\"Set default profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n if (!(await ProfileManager.profileExists(name))) {\n throw new CLIError(\"PROFILE_NOT_FOUND\", `Profile \"${name}\" does not exist`, ExitCode.NOT_FOUND);\n }\n\n const config = await ProfileManager.getConfig();\n await ProfileManager.setConfig({ ...config, defaultProfile: name });\n\n outputJson({ defaultProfile: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"delete <name>\")\n .description(\"Delete a profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n // Confirmation prompt if interactive\n if (isInteractive()) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Delete profile \"${name}\"? This cannot be undone. [y/N] `, resolve);\n });\n rl.close();\n if (answer.toLowerCase() !== \"y\") {\n outputJson({ profile: name, deleted: false, reason: \"Cancelled by user\" });\n return;\n }\n }\n\n await ProfileManager.deleteProfile(name);\n outputJson({ profile: name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\n\nexport function registerCompletionCommand(program: Command): void {\n const completion = program.command(\"completion\").description(\"Generate shell completions\");\n\n completion\n .command(\"bash\")\n .description(\"Output bash completions\")\n .action(() => {\n const script = generateBashCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"zsh\")\n .description(\"Output zsh completions\")\n .action(() => {\n const script = generateZshCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"fish\")\n .description(\"Output fish completions\")\n .action(() => {\n const script = generateFishCompletion();\n process.stdout.write(script);\n });\n}\n\nfunction generateBashCompletion(): string {\n return `# tc bash completion\n_tc_completions() {\n local cur prev commands subcommands\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n\n commands=\"init auth kv space delegation share node profile completion\"\n\n case \"\\${COMP_WORDS[1]}\" in\n auth) subcommands=\"login logout status whoami\" ;;\n kv) subcommands=\"get put delete list head\" ;;\n space) subcommands=\"list create info switch\" ;;\n delegation) subcommands=\"create list info revoke\" ;;\n share) subcommands=\"create receive list revoke\" ;;\n node) subcommands=\"health version status\" ;;\n profile) subcommands=\"list create show switch delete\" ;;\n completion) subcommands=\"bash zsh fish\" ;;\n *) COMPREPLY=( $(compgen -W \"\\${commands}\" -- \"\\${cur}\") ); return ;;\n esac\n\n if [ \\${COMP_CWORD} -eq 2 ]; then\n COMPREPLY=( $(compgen -W \"\\${subcommands}\" -- \"\\${cur}\") )\n fi\n}\ncomplete -F _tc_completions tc\n`;\n}\n\nfunction generateZshCompletion(): string {\n return `#compdef tc\n\n_tc() {\n local -a commands\n commands=(\n 'init:Initialize a new TinyCloud profile'\n 'auth:Authentication management'\n 'kv:Key-value store operations'\n 'space:Space management'\n 'delegation:Manage delegations'\n 'share:Share data with others'\n 'node:Node health and info'\n 'profile:Profile management'\n 'completion:Generate shell completions'\n )\n\n _arguments -C \\\\\n '(-p --profile)'{-p,--profile}'[Profile to use]:profile:' \\\\\n '(-H --host)'{-H,--host}'[TinyCloud node URL]:url:' \\\\\n '(-v --verbose)'{-v,--verbose}'[Enable verbose output]' \\\\\n '--no-cache[Disable caching]' \\\\\n '(-q --quiet)'{-q,--quiet}'[Suppress non-essential output]' \\\\\n '1:command:->cmd' \\\\\n '*::arg:->args'\n\n case $state in\n cmd)\n _describe 'command' commands\n ;;\n args)\n case $words[1] in\n auth) _values 'subcommand' login logout status whoami ;;\n kv) _values 'subcommand' get put delete list head ;;\n space) _values 'subcommand' list create info switch ;;\n delegation) _values 'subcommand' create list info revoke ;;\n share) _values 'subcommand' create receive list revoke ;;\n node) _values 'subcommand' health version status ;;\n profile) _values 'subcommand' list create show switch delete ;;\n completion) _values 'subcommand' bash zsh fish ;;\n esac\n ;;\n esac\n}\n\n_tc\n`;\n}\n\nfunction generateFishCompletion(): string {\n return `# tc fish completion\nset -l commands init auth kv space delegation share node profile completion\n\n# Disable file completion by default\ncomplete -c tc -f\n\n# Top-level commands\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a init -d \"Initialize a new TinyCloud profile\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a auth -d \"Authentication management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a kv -d \"Key-value store operations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a space -d \"Space management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a delegation -d \"Manage delegations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a share -d \"Share data with others\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a node -d \"Node health and info\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a profile -d \"Profile management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a completion -d \"Generate shell completions\"\n\n# Subcommands\ncomplete -c tc -n \"__fish_seen_subcommand_from auth\" -a \"login logout status whoami\"\ncomplete -c tc -n \"__fish_seen_subcommand_from kv\" -a \"get put delete list head\"\ncomplete -c tc -n \"__fish_seen_subcommand_from space\" -a \"list create info switch\"\ncomplete -c tc -n \"__fish_seen_subcommand_from delegation\" -a \"create list info revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from share\" -a \"create receive list revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from node\" -a \"health version status\"\ncomplete -c tc -n \"__fish_seen_subcommand_from profile\" -a \"list create show switch delete\"\ncomplete -c tc -n \"__fish_seen_subcommand_from completion\" -a \"bash zsh fish\"\n\n# Global options\ncomplete -c tc -l profile -s p -d \"Profile to use\"\ncomplete -c tc -l host -s H -d \"TinyCloud node URL\"\ncomplete -c tc -l verbose -s v -d \"Enable verbose output\"\ncomplete -c tc -l no-cache -d \"Disable caching\"\ncomplete -c tc -l quiet -s q -d \"Suppress non-essential output\"\n`;\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\n/**\n * Unlock the vault on a TinyCloudNode instance.\n */\nasync function unlockVault(\n node: { vault: { unlock(signer: { signMessage(message: string): Promise<string> }): Promise<any> } },\n privateKey: string,\n): Promise<void> {\n const signer = new PrivateKeySigner(privateKey);\n const result = await node.vault.unlock(signer);\n if (result && !result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n}\n\nexport function registerVaultCommand(program: Command): void {\n const vault = program.command(\"vault\").description(\"Encrypted vault operations\");\n\n // tc vault unlock\n vault\n .command(\"unlock\")\n .description(\"Verify vault unlock works\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n outputJson({ unlocked: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault put <key> [value]\n vault\n .command(\"put <key> [value]\")\n .description(\"Encrypt and store a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // Determine value source\n let putValue: string | Uint8Array;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = new Uint8Array(await readFile(options.file));\n } else if (options.stdin) {\n putValue = new Uint8Array(await readStdin());\n } else {\n putValue = value!;\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.vault.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault get <key>\n vault\n .command(\"get <key>\")\n .description(\"Decrypt and retrieve a value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Getting ${key}...`, () => node.vault.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data ?? result.data;\n\n if (options.output) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n outputJson({\n key,\n data: data instanceof Uint8Array ? Buffer.from(data).toString(\"base64\") : data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault delete <key>\n vault\n .command(\"delete <key>\")\n .description(\"Delete an encrypted key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.vault.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault list\n vault\n .command(\"list\")\n .description(\"List vault keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing vault keys...\", () => node.vault.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const keys = result.data.data ?? result.data;\n const keyList = Array.isArray(keys) ? keys : [];\n\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault head <key>\n vault\n .command(\"head <key>\")\n .description(\"Get metadata for a vault key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Checking ${key}...`, () => node.vault.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? result.data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\n\nconst SECRETS_PREFIX = \"secrets/\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\n/**\n * Unlock the vault on a TinyCloudNode instance.\n */\nasync function unlockVault(\n node: { vault: { unlock(signer: { signMessage(message: string): Promise<string> }): Promise<any> } },\n privateKey: string,\n): Promise<void> {\n const signer = new PrivateKeySigner(privateKey);\n const result = await node.vault.unlock(signer);\n if (result && !result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n}\n\nexport function registerSecretsCommand(program: Command): void {\n const secrets = program.command(\"secrets\").description(\"Encrypted secrets management\");\n\n // tc secrets list\n secrets\n .command(\"list\")\n .description(\"List secrets\")\n .option(\"--space <spaceId>\", \"Space to list secrets from (for delegated access)\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // TODO: SDK-level support for targeting a specific space via vault.list().\n // The vault service currently operates on the space bound to the session.\n // When --space is provided, we would need the SDK to accept a spaceId\n // parameter on vault operations or support switching the active space.\n if (options.space) {\n throw new CLIError(\n \"NOT_IMPLEMENTED\",\n `Listing secrets from a delegated space (${options.space}) is not yet supported at the SDK level. ` +\n \"The vault service currently operates on the space bound to the active session. \" +\n \"SDK support for cross-space vault operations is planned.\",\n ExitCode.ERROR,\n );\n }\n\n const result = await withSpinner(\"Listing secrets...\", () => node.vault.list({ prefix: SECRETS_PREFIX })) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const keys = result.data.data ?? result.data;\n const keyList = Array.isArray(keys) ? keys : [];\n\n // Strip the secrets/ prefix from key names\n const secretNames = keyList.map((k: string) =>\n typeof k === \"string\" && k.startsWith(SECRETS_PREFIX) ? k.slice(SECRETS_PREFIX.length) : k\n );\n\n outputJson({\n secrets: secretNames,\n count: secretNames.length,\n ...(options.space ? { space: options.space } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets get <name>\n secrets\n .command(\"get <name>\")\n .description(\"Get a secret value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const vaultKey = `${SECRETS_PREFIX}${name}`;\n const result = await withSpinner(`Getting secret ${name}...`, () => node.vault.get(vaultKey)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Secret \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data ?? result.data;\n\n // Parse the stored payload to extract the value\n let value: string;\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data);\n value = parsed.value;\n } catch {\n value = data;\n }\n } else if (data instanceof Uint8Array) {\n try {\n const parsed = JSON.parse(Buffer.from(data).toString(\"utf-8\"));\n value = parsed.value;\n } catch {\n value = Buffer.from(data).toString(\"utf-8\");\n }\n } else {\n value = data.value ?? data;\n }\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets put <name> [value]\n secrets\n .command(\"put <name> [value]\")\n .description(\"Store a secret\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // Determine value source\n let secretValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n secretValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n secretValue = (await readStdin()).toString(\"utf-8\");\n } else {\n secretValue = value!;\n }\n\n const payload = JSON.stringify({\n value: secretValue,\n createdAt: new Date().toISOString(),\n });\n\n const vaultKey = `${SECRETS_PREFIX}${name}`;\n const result = await withSpinner(`Storing secret ${name}...`, () => node.vault.put(vaultKey, payload)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets delete <name>\n secrets\n .command(\"delete <name>\")\n .description(\"Delete a secret\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const vaultKey = `${SECRETS_PREFIX}${name}`;\n const result = await withSpinner(`Deleting secret ${name}...`, () => node.vault.delete(vaultKey)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets manage\n secrets\n .command(\"manage\")\n .description(\"Open the TinyCloud Secrets Manager in your browser\")\n .action(async () => {\n try {\n const open = (await import(\"open\")).default;\n await open(\"https://secrets.tinycloud.xyz\");\n outputJson({ opened: \"https://secrets.tinycloud.xyz\" });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\n\nconst VARIABLES_PREFIX = \"variables/\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\nexport function registerVarsCommand(program: Command): void {\n const vars = program.command(\"vars\").description(\"Plaintext variable management\");\n\n // tc vars list\n vars\n .command(\"list\")\n .description(\"List variables\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(\"Listing variables...\", () => prefixedKv.list()) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n outputJson({\n variables: keyList,\n count: keyList.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars get <name>\n vars\n .command(\"get <name>\")\n .description(\"Get a variable value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Getting variable ${name}...`, () => prefixedKv.get(name)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Variable \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n\n // Extract value from the stored payload\n let value: string;\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data);\n value = parsed.value;\n } catch {\n value = data;\n }\n } else if (data && typeof data === \"object\" && \"value\" in data) {\n value = data.value;\n } else {\n value = typeof data === \"string\" ? data : JSON.stringify(data);\n }\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars put <name> [value]\n vars\n .command(\"put <name> [value]\")\n .description(\"Set a variable\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n // Determine value source\n let varValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n varValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n varValue = (await readStdin()).toString(\"utf-8\");\n } else {\n varValue = value!;\n }\n\n const payload = {\n value: varValue,\n createdAt: new Date().toISOString(),\n };\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Setting variable ${name}...`, () => prefixedKv.put(name, payload)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars delete <name>\n vars\n .command(\"delete <name>\")\n .description(\"Delete a variable\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Deleting variable ${name}...`, () => prefixedKv.delete(name)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { DEFAULT_HOST } from \"../config/constants.js\";\nimport { outputJson, shouldOutputJson, formatCheck, formatSection } from \"../output/formatter.js\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\ninterface DoctorResult {\n checks: Array<{ name: string; ok: boolean; detail?: string }>;\n healthy: boolean;\n}\n\nexport function registerDoctorCommand(program: Command): void {\n program\n .command(\"doctor\")\n .description(\"Run diagnostic checks\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const checks: DoctorResult[\"checks\"] = [];\n\n // 1. Node.js version\n const nodeVersion = process.version;\n const nodeOk = parseInt(nodeVersion.slice(1)) >= 18;\n checks.push({ name: \"Node.js\", ok: nodeOk, detail: nodeVersion });\n\n // 2. Profile configured\n let profileName = globalOpts.profile;\n let profileOk = false;\n let profileDetail = \"\";\n try {\n const config = await ProfileManager.getConfig();\n profileName = profileName || config.defaultProfile;\n const profile = await ProfileManager.getProfile(profileName);\n profileOk = true;\n profileDetail = `\"${profileName}\" at ${profile.host}`;\n } catch {\n profileDetail = profileName ? `\"${profileName}\" not found` : \"no profiles configured\";\n }\n checks.push({ name: \"Profile\", ok: profileOk, detail: profileDetail });\n\n // 3. Key exists\n let keyOk = false;\n let keyDetail = \"\";\n if (profileOk && profileName) {\n try {\n const key = await ProfileManager.getKey(profileName);\n keyOk = key !== null;\n if (keyOk) {\n const profile = await ProfileManager.getProfile(profileName);\n keyDetail = profile.did ? `${profile.did.slice(0, 20)}...` : \"key found\";\n } else {\n keyDetail = \"no key — run tc init\";\n }\n } catch {\n keyDetail = \"error reading key\";\n }\n } else {\n keyDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Key\", ok: keyOk, detail: keyDetail });\n\n // 4. Session active\n let sessionOk = false;\n let sessionDetail = \"\";\n if (profileOk && profileName) {\n try {\n const session = await ProfileManager.getSession(profileName);\n sessionOk = session !== null;\n sessionDetail = sessionOk ? \"active\" : \"no session — run tc auth login\";\n } catch {\n sessionDetail = \"error reading session\";\n }\n } else {\n sessionDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Session\", ok: sessionOk, detail: sessionDetail });\n\n // 5. Node reachable\n let nodeReachable = false;\n let nodeDetail = \"\";\n try {\n const host = profileOk && profileName\n ? (await ProfileManager.getProfile(profileName)).host\n : globalOpts.host || DEFAULT_HOST;\n const start = Date.now();\n const response = await fetch(`${host}/health`);\n const latency = Date.now() - start;\n nodeReachable = response.ok;\n nodeDetail = nodeReachable\n ? `${host} (${latency}ms)`\n : `${host} returned ${response.status}`;\n } catch (e) {\n nodeDetail = `unreachable — ${e instanceof Error ? e.message : \"connection failed\"}`;\n }\n checks.push({ name: \"Node\", ok: nodeReachable, detail: nodeDetail });\n\n // 6. Space exists (only if session active)\n let spaceOk = false;\n let spaceDetail = \"\";\n if (sessionOk && profileName) {\n try {\n const profile = await ProfileManager.getProfile(profileName);\n spaceOk = Boolean(profile.spaceId);\n spaceDetail = spaceOk\n ? `${profile.spaceId!.slice(0, 16)}...`\n : \"no space — run tc space create\";\n } catch {\n spaceDetail = \"error checking space\";\n }\n } else {\n spaceDetail = \"skipped (no session)\";\n }\n checks.push({ name: \"Space\", ok: spaceOk, detail: spaceDetail });\n\n const result: DoctorResult = {\n checks,\n healthy: checks.every((c) => c.ok),\n };\n\n if (shouldOutputJson()) {\n outputJson(result);\n } else {\n process.stderr.write(formatSection(\"Diagnostics\") + \"\\n\");\n for (const check of checks) {\n process.stdout.write(formatCheck(check.ok, check.name, check.detail) + \"\\n\");\n }\n process.stdout.write(\"\\n\");\n if (result.healthy) {\n process.stdout.write(theme.success(\"All checks passed.\") + \"\\n\");\n } else {\n const failed = checks.filter((c) => !c.ok).length;\n process.stdout.write(theme.warn(`${failed} check${failed > 1 ? \"s\" : \"\"} need attention.`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerSqlCommand(program: Command): void {\n const sql = program.command(\"sql\").description(\"SQL database operations\");\n\n // tc sql query <sql>\n sql\n .command(\"query <sql>\")\n .description(\"Run a SELECT query\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Running query...\", () =>\n node.sql.db(options.db).query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql execute <sql>\n sql\n .command(\"execute <sql>\")\n .description(\"Run INSERT/UPDATE/DELETE/DDL statement\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Executing statement...\", () =>\n node.sql.db(options.db).execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n changes: result.data.changes,\n lastInsertRowId: result.data.lastInsertRowId,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql export\n sql\n .command(\"export\")\n .description(\"Export database as binary file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.db\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n node.sql.db(options.db).export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerDuckdbCommand(program: Command): void {\n const duckdb = program.command(\"duckdb\").description(\"DuckDB database operations\");\n\n // tc duckdb query <sql>\n duckdb\n .command(\"query <sql>\")\n .description(\"Run a SELECT query\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Running query...\", () =>\n node.duckdb.db(options.db).query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb execute <sql>\n duckdb\n .command(\"execute <sql>\")\n .description(\"Run INSERT/UPDATE/DELETE/DDL statement\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Executing statement...\", () =>\n node.duckdb.db(options.db).execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ changes: result.data.changes });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb describe\n duckdb\n .command(\"describe\")\n .description(\"Show database schema (tables, columns, views)\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Describing schema...\", () =>\n node.duckdb.db(options.db).describe()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const schema = result.data;\n\n if (shouldOutputJson()) {\n outputJson(schema);\n } else {\n const { tables, views } = schema;\n\n if (tables.length === 0 && views.length === 0) {\n process.stdout.write(theme.muted(\"No tables or views found.\") + \"\\n\");\n return;\n }\n\n if (tables.length > 0) {\n process.stdout.write(theme.label(\"Tables:\") + \"\\n\\n\");\n for (const table of tables) {\n process.stdout.write(` ${theme.value(table.name)}\\n`);\n const colRows = table.columns.map((col: any) => [\n col.name,\n col.type,\n col.nullable ? \"YES\" : \"NO\",\n ]);\n const colTable = formatTable([\"Column\", \"Type\", \"Nullable\"], colRows);\n process.stdout.write(colTable.split(\"\\n\").map((l: string) => \" \" + l).join(\"\\n\") + \"\\n\\n\");\n }\n }\n\n if (views.length > 0) {\n process.stdout.write(theme.label(\"Views:\") + \"\\n\\n\");\n const viewRows = views.map((v: any) => [v.name, v.sql]);\n process.stdout.write(formatTable([\"View\", \"SQL\"], viewRows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb export\n duckdb\n .command(\"export\")\n .description(\"Export database as binary file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.duckdb\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n node.duckdb.db(options.db).export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb import <file>\n duckdb\n .command(\"import <file>\")\n .description(\"Import a DuckDB database file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (file: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const filePath = resolve(file);\n const bytes = new Uint8Array(await readFile(filePath));\n\n const result = await withSpinner(\"Importing database...\", () =>\n node.duckdb.db(options.db).import(bytes)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n file: filePath,\n size: bytes.byteLength,\n sizeHuman: formatBytes(bytes.byteLength),\n imported: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { execSync } from \"child_process\";\nimport { readFileSync } from \"fs\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\nconst PACKAGE_NAME = \"@tinycloud/cli\";\n\nfunction getCurrentVersion(): string {\n const pkg = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n );\n return pkg.version;\n}\n\nasync function getLatestVersion(): Promise<string> {\n const res = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`);\n if (!res.ok) {\n throw new Error(`Failed to fetch latest version: ${res.status} ${res.statusText}`);\n }\n const data = (await res.json()) as { version: string };\n return data.version;\n}\n\nfunction detectPackageManager(): \"bun\" | \"npm\" {\n // Check if bun installed the package globally\n try {\n const bunGlobals = execSync(\"bun pm ls -g\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (bunGlobals.includes(PACKAGE_NAME)) {\n return \"bun\";\n }\n } catch {\n // bun not available or failed\n }\n\n // Check if npm installed the package globally\n try {\n const npmGlobals = execSync(\"npm ls -g --depth=0\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (npmGlobals.includes(PACKAGE_NAME)) {\n return \"npm\";\n }\n } catch {\n // npm not available or failed\n }\n\n // Fallback to bun since the CLI shebang uses it\n return \"bun\";\n}\n\nexport function registerUpgradeCommand(program: Command): void {\n program\n .command(\"upgrade\")\n .description(\"Upgrade the TinyCloud CLI to the latest version\")\n .action(async () => {\n try {\n const current = getCurrentVersion();\n\n process.stderr.write(theme.muted(\"Checking for updates...\") + \"\\n\");\n const latest = await getLatestVersion();\n\n if (current === latest) {\n process.stdout.write(theme.success(`Already on latest version (${current})`) + \"\\n\");\n return;\n }\n\n process.stdout.write(`Current: ${theme.warn(current)} → Latest: ${theme.success(latest)}\\n`);\n\n const pm = detectPackageManager();\n const cmd = pm === \"bun\"\n ? `bun install -g ${PACKAGE_NAME}@latest`\n : `npm install -g ${PACKAGE_NAME}@latest`;\n\n process.stderr.write(theme.muted(`Upgrading via ${pm}...`) + \"\\n\\n\");\n\n try {\n execSync(cmd, { stdio: \"inherit\" });\n process.stdout.write(\"\\n\" + theme.success(`Upgraded to ${latest}`) + \"\\n\");\n } catch {\n process.stderr.write(\"\\n\" + theme.warn(\"Automatic upgrade failed.\") + \"\\n\");\n process.stderr.write(theme.muted(\"Try running manually:\") + \"\\n\");\n process.stderr.write(` ${theme.command(`bun install -g ${PACKAGE_NAME}@latest`)}\\n`);\n process.stderr.write(theme.muted(\" or\") + \"\\n\");\n process.stderr.write(` ${theme.command(`npm install -g ${PACKAGE_NAME}@latest`)}\\n`);\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAS,eAAe;;;ACDxB,SAAS,eAAe;AACxB,SAAS,YAAY;AAEd,IAAM,aAAa,KAAK,QAAQ,GAAG,YAAY;AAC/C,IAAM,eAAe,KAAK,YAAY,UAAU;AAChD,IAAM,cAAc,KAAK,YAAY,aAAa;AAElD,IAAM,eAAe;AACrB,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAEzB,IAAM,WAAW;AAAA,EACtB,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,WAAW;AAAA,EACX,mBAAmB;AAAA,EACnB,eAAe;AAAA,EACf,YAAY;AACd;;;ACpBA,OAAO,SAAS;;;ACAhB,OAAO,WAAW;AAEX,IAAM,aAAa;AAAA,EACxB,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,KAAK;AACP;AAEO,IAAM,QAAQ;AAAA,EACnB,SAAS,MAAM,IAAI,WAAW,OAAO;AAAA,EACrC,QA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AAC;AAAA,IAC1G,MAAM,QAAQ,eAAe,CAAC,2BAA2B,MAAM,MAAM,0BAA0B,CAAC;AAAA,IAChG,MAAM,QAAQ,4BAA4B,CAAC,cAAc,MAAM,MAAM,eAAe,CAAC;AAAA,IACrF,MAAM,QAAQ,YAAY,CAAC,8BAA8B,MAAM,MAAM,eAAe,CAAC;AAAA,IACrF,MAAM,QAAQ,uCAAuC,CAAC,KAAK,MAAM,MAAM,8BAA8B,CAAC;AAAA,IACtG,MAAM,QAAQ,eAAe,CAAC,2BAA2B,MAAM,MAAM,kBAAkB,CAAC;AAAA;AAAA,EAE1F,MAAM,MAAM,OAAO,CAAC,IAAI,MAAM,OAAO,gCAAgC,CAAC;AAAA,EACtE,MAAM,MAAM,OAAO,CAAC,IAAI,MAAM,OAAO,0CAA0C,CAAC;AAAA;AAElF,CAAC;AAED,IAAI;AACF,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC,SAAS,OAAO;AACd,cAAY,KAAK;AACnB;","names":["readFileSync","version","join","rm","join","rm","TinyCloudNode","resolve","program","createInterface","createInterface","resolve","program","readFile","writeFile","node","program","writeFile","readFile","program","program","program","program","createInterface","program","createInterface","resolve","program","readFile","writeFile","PrivateKeySigner","readStdin","program","readFile","writeFile","readFile","writeFile","PrivateKeySigner","readStdin","resolvePrivateKey","unlockVault","program","writeFile","readFile","readFile","writeFile","readStdin","resolvePrivateKey","program","writeFile","readFile","program","writeFile","program","writeFile","readFile","writeFile","resolve","program","resolve","writeFile","readFile","execSync","execSync","program","readFileSync"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/config/constants.ts","../src/output/formatter.ts","../src/output/theme.ts","../src/output/errors.ts","../src/output/taglines.ts","../src/output/banner.ts","../src/config/profiles.ts","../src/config/storage.ts","../src/auth/local-key.ts","../src/auth/browser-auth.ts","../src/commands/init.ts","../src/commands/auth.ts","../src/commands/kv.ts","../src/lib/sdk.ts","../src/commands/space.ts","../src/lib/duration.ts","../src/commands/delegation.ts","../src/commands/share.ts","../src/commands/node.ts","../src/commands/profile.ts","../src/commands/completion.ts","../src/commands/vault.ts","../src/commands/secrets.ts","../src/commands/vars.ts","../src/commands/doctor.ts","../src/commands/sql.ts","../src/commands/duckdb.ts","../src/commands/upgrade.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { Command } from \"commander\";\nimport { handleError } from \"./output/errors.js\";\nimport { emitBanner } from \"./output/banner.js\";\n\nconst { version } = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n);\nimport { theme } from \"./output/theme.js\";\nimport { isInteractive } from \"./output/formatter.js\";\nimport { ProfileManager } from \"./config/profiles.js\";\nimport { registerInitCommand } from \"./commands/init.js\";\nimport { registerAuthCommand } from \"./commands/auth.js\";\nimport { registerKvCommand } from \"./commands/kv.js\";\nimport { registerSpaceCommand } from \"./commands/space.js\";\nimport { registerDelegationCommand } from \"./commands/delegation.js\";\nimport { registerShareCommand } from \"./commands/share.js\";\nimport { registerNodeCommand } from \"./commands/node.js\";\nimport { registerProfileCommand } from \"./commands/profile.js\";\nimport { registerCompletionCommand } from \"./commands/completion.js\";\nimport { registerVaultCommand } from \"./commands/vault.js\";\nimport { registerSecretsCommand } from \"./commands/secrets.js\";\nimport { registerVarsCommand } from \"./commands/vars.js\";\nimport { registerDoctorCommand } from \"./commands/doctor.js\";\nimport { registerSqlCommand } from \"./commands/sql.js\";\nimport { registerDuckdbCommand } from \"./commands/duckdb.js\";\nimport { registerUpgradeCommand } from \"./commands/upgrade.js\";\n\nconst program = new Command();\n\nprogram\n .name(\"tc\")\n .description(\"TinyCloud CLI — self-sovereign storage from the terminal\")\n .version(version)\n .option(\"-p, --profile <name>\", \"Profile to use\")\n .option(\"-H, --host <url>\", \"TinyCloud node URL\")\n .option(\"-v, --verbose\", \"Enable verbose output\")\n .option(\"--no-cache\", \"Disable caching\")\n .option(\"-q, --quiet\", \"Suppress non-essential output\")\n .option(\"--json\", \"Force JSON output\");\n\nprogram.hook(\"preAction\", async (thisCommand) => {\n const opts = thisCommand.optsWithGlobals();\n if (!opts.quiet) {\n emitBanner(version);\n }\n\n // Config guard — warn if not configured for auth-required commands\n const commandName = thisCommand.name();\n const parentName = thisCommand.parent?.name();\n const fullCommand = parentName && parentName !== \"tc\" ? `${parentName} ${commandName}` : commandName;\n const skipGuard = [\"tc\", \"init\", \"doctor\", \"completion\", \"help\", \"upgrade\"].includes(commandName) ||\n fullCommand === \"profile create\";\n if (!skipGuard && !opts.quiet && isInteractive()) {\n try {\n const config = await ProfileManager.getConfig();\n const profileName = opts.profile || config.defaultProfile;\n const hasProfile = await ProfileManager.profileExists(profileName);\n if (!hasProfile) {\n process.stderr.write(theme.warn(\"⚠ No profile configured.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n } else {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n process.stderr.write(theme.warn(\"⚠ No key found.\") + \" \" + theme.muted(\"Run: tc init\") + \"\\n\\n\");\n }\n }\n } catch {\n // Config dir doesn't exist yet — that's fine, commands will handle it\n }\n }\n});\n\nregisterInitCommand(program);\nregisterAuthCommand(program);\nregisterKvCommand(program);\nregisterSpaceCommand(program);\nregisterDelegationCommand(program);\nregisterShareCommand(program);\nregisterNodeCommand(program);\nregisterProfileCommand(program);\nregisterCompletionCommand(program);\nregisterVaultCommand(program);\nregisterSecretsCommand(program);\nregisterVarsCommand(program);\nregisterDoctorCommand(program);\nregisterSqlCommand(program);\nregisterDuckdbCommand(program);\nregisterUpgradeCommand(program);\n\nprogram.addHelpText(\"afterAll\", () => {\n if (!process.stdout.isTTY) return \"\";\n return `\n${theme.heading(\"Examples:\")}\n ${theme.command(\"tc init\")} ${theme.muted(\"Set up a profile and generate keys\")}\n ${theme.command(\"tc auth login\")} ${theme.muted(\"Authenticate via browser\")}\n ${theme.command('tc kv put greeting \"Hello\"')} ${theme.muted(\"Store a value\")}\n ${theme.command(\"tc kv list\")} ${theme.muted(\"List all keys\")}\n ${theme.command(\"tc delegation create --to did:pkh:...\")} ${theme.muted(\"Grant access to another user\")}\n ${theme.command(\"tc space list\")} ${theme.muted(\"Show your spaces\")}\n\n${theme.muted(\"Docs:\")} ${theme.accent(\"https://docs.tinycloud.xyz/cli\")}\n${theme.muted(\"Repo:\")} ${theme.accent(\"https://github.com/tinycloudlabs/web-sdk\")}\n`;\n});\n\ntry {\n await program.parseAsync(process.argv);\n} catch (error) {\n handleError(error);\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const CONFIG_DIR = join(homedir(), \".tinycloud\");\nexport const PROFILES_DIR = join(CONFIG_DIR, \"profiles\");\nexport const CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\n\nexport const DEFAULT_HOST = \"https://node.tinycloud.xyz\";\nexport const DEFAULT_PROFILE = \"default\";\nexport const DEFAULT_CHAIN_ID = 1;\n\nexport const ExitCode = {\n SUCCESS: 0,\n ERROR: 1,\n USAGE_ERROR: 2,\n AUTH_REQUIRED: 3,\n NOT_FOUND: 4,\n PERMISSION_DENIED: 5,\n NETWORK_ERROR: 6,\n NODE_ERROR: 7,\n} as const;\n","import ora from \"ora\";\nimport { theme } from \"./theme.js\";\n\nexport function outputJson(data: unknown): void {\n process.stdout.write(JSON.stringify(data, null, 2) + \"\\n\");\n}\n\nexport function outputError(code: string, message: string): void {\n if (isInteractive()) {\n process.stderr.write(\n `${theme.error(\"✗\")} ${theme.label(code)}: ${message}\\n`\n );\n } else {\n process.stderr.write(\n JSON.stringify({ error: { code, message } }, null, 2) + \"\\n\"\n );\n }\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdout.isTTY);\n}\n\nexport async function withSpinner<T>(label: string, fn: () => Promise<T>): Promise<T> {\n if (!isInteractive()) {\n return fn();\n }\n const spinner = ora(label).start();\n try {\n const result = await fn();\n spinner.succeed(label);\n return result;\n } catch (error) {\n spinner.fail(label);\n throw error;\n }\n}\n\n/** Check if output should be JSON (non-TTY or --json flag) */\nexport function shouldOutputJson(): boolean {\n return !isInteractive() || process.argv.includes(\"--json\");\n}\n\n/** Format a key-value pair for human display */\nexport function formatField(label: string, value: string | number | boolean | null | undefined): string {\n if (value === null || value === undefined) return ` ${theme.label(label + \":\")} ${theme.muted(\"—\")}`;\n if (typeof value === \"boolean\") {\n return ` ${theme.label(label + \":\")} ${value ? theme.success(\"yes\") : theme.muted(\"no\")}`;\n }\n return ` ${theme.label(label + \":\")} ${theme.value(String(value))}`;\n}\n\n/** Format a list of items as a simple table */\nexport function formatTable(headers: string[], rows: string[][]): string {\n // Calculate column widths\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map(r => (r[i] || \"\").length))\n );\n\n const headerLine = headers.map((h, i) => theme.label(h.padEnd(widths[i]))).join(\" \");\n const separator = widths.map(w => theme.dim(\"─\".repeat(w))).join(\" \");\n const dataLines = rows.map(row =>\n row.map((cell, i) => (cell || \"\").padEnd(widths[i])).join(\" \")\n );\n\n return [headerLine, separator, ...dataLines].join(\"\\n\");\n}\n\n/** Output data in either JSON or human-friendly format */\nexport function output(data: unknown, humanFormatter?: () => string): void {\n if (shouldOutputJson() || !humanFormatter) {\n outputJson(data);\n } else {\n process.stdout.write(humanFormatter() + \"\\n\");\n }\n}\n\n/** Format a status check line (for doctor command etc.) */\nexport function formatCheck(ok: boolean | \"warn\", label: string, detail?: string): string {\n const icon = ok === \"warn\" ? theme.warn(\"⚠\") : ok ? theme.success(\"✓\") : theme.error(\"✗\");\n const detailStr = detail ? ` ${theme.muted(`(${detail})`)}` : \"\";\n return `${icon} ${label}${detailStr}`;\n}\n\n/** Format a section heading */\nexport function formatSection(title: string): string {\n return `\\n${theme.heading(title)}`;\n}\n\n/** Format bytes to human readable */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Format relative time */\nexport function formatTimeAgo(date: Date | string): string {\n const d = typeof date === \"string\" ? new Date(date) : date;\n const seconds = Math.floor((Date.now() - d.getTime()) / 1000);\n if (seconds < 60) return \"just now\";\n if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;\n if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;\n return `${Math.floor(seconds / 86400)}d ago`;\n}\n","import chalk from \"chalk\";\n\nexport const TC_PALETTE = {\n primary: \"#4473b9\",\n accent: \"#5b9bd5\",\n success: \"#2fba6a\",\n warn: \"#e8a838\",\n error: \"#d94040\",\n muted: \"#808080\",\n dim: \"#5a5a5a\",\n} as const;\n\nexport const theme = {\n primary: chalk.hex(TC_PALETTE.primary),\n accent: chalk.hex(TC_PALETTE.accent),\n success: chalk.hex(TC_PALETTE.success),\n warn: chalk.hex(TC_PALETTE.warn),\n error: chalk.hex(TC_PALETTE.error),\n muted: chalk.hex(TC_PALETTE.muted),\n dim: chalk.hex(TC_PALETTE.dim),\n heading: chalk.bold.hex(TC_PALETTE.primary),\n command: chalk.hex(TC_PALETTE.accent),\n brand: chalk.bold.hex(TC_PALETTE.primary),\n label: chalk.bold,\n value: chalk.white,\n hint: chalk.italic.hex(TC_PALETTE.muted),\n};\n","import { ExitCode } from \"../config/constants.js\";\nimport { outputError } from \"./formatter.js\";\n\nexport class CLIError extends Error {\n constructor(\n public code: string,\n message: string,\n public exitCode: number = ExitCode.ERROR\n ) {\n super(message);\n this.name = \"CLIError\";\n }\n}\n\nexport function wrapError(error: unknown): CLIError {\n if (error instanceof CLIError) return error;\n\n const message = error instanceof Error ? error.message : String(error);\n\n // Map known error patterns to exit codes\n if (message.includes(\"Not signed in\") || message.includes(\"AUTH_EXPIRED\") || message.includes(\"Session expired\")) {\n return new CLIError(\"AUTH_REQUIRED\", message, ExitCode.AUTH_REQUIRED);\n }\n if (message.includes(\"NOT_FOUND\") || message.includes(\"KV_NOT_FOUND\")) {\n return new CLIError(\"NOT_FOUND\", message, ExitCode.NOT_FOUND);\n }\n if (message.includes(\"PERMISSION_DENIED\")) {\n return new CLIError(\"PERMISSION_DENIED\", message, ExitCode.PERMISSION_DENIED);\n }\n if (message.includes(\"ECONNREFUSED\") || message.includes(\"ETIMEDOUT\") || message.includes(\"fetch failed\")) {\n return new CLIError(\"NETWORK_ERROR\", message, ExitCode.NETWORK_ERROR);\n }\n\n return new CLIError(\"ERROR\", message, ExitCode.ERROR);\n}\n\nexport function handleError(error: unknown): never {\n const cliError = wrapError(error);\n outputError(cliError.code, cliError.message);\n process.exit(cliError.exitCode);\n}\n","interface HolidayTagline {\n month: number;\n day: number;\n range?: number; // days before/after to show\n tagline: string;\n}\n\nconst HOLIDAY_TAGLINES: HolidayTagline[] = [\n { month: 1, day: 1, range: 1, tagline: \"New year, new keys, same cloud.\" },\n { month: 2, day: 14, tagline: \"We love your data as much as you do.\" },\n { month: 3, day: 14, tagline: \"3.14159 reasons to encrypt everything.\" },\n { month: 5, day: 4, tagline: \"May the fourth be with your keys.\" },\n { month: 10, day: 31, tagline: \"Nothing scarier than plaintext secrets.\" },\n { month: 12, day: 25, range: 2, tagline: \"Unwrap your data, not your keys.\" },\n { month: 12, day: 31, tagline: \"Encrypt your resolutions.\" },\n];\n\nconst TAGLINES = [\n // Professional\n \"Your data, your keys, your cloud.\",\n \"Self-sovereign storage for the modern web.\",\n \"The cloud you actually own.\",\n \"Encrypted by default, decentralized by design.\",\n \"Where your data answers only to you.\",\n \"End-to-end encrypted. No exceptions.\",\n \"Like S3 but you hold the keys.\",\n \"Privacy isn't a feature. It's the architecture.\",\n \"Sovereign storage, zero knowledge.\",\n \"Your .env is safe here — we use real cryptography.\",\n // Playful / nerdy\n \"UCAN do anything.\",\n \"Keys generated, delegations granted, data liberated.\",\n \"Decentralized storage, centralized vibes.\",\n \"Trust nobody, delegate everything.\",\n \"sudo make me a sandwich, encrypted.\",\n \"Have you tried turning your keys off and on again?\",\n \"All your base are belong to you.\",\n \"In UCAN we trust.\",\n \"0 knowledge, 100% confidence.\",\n \"Keeping secrets since 2024.\",\n];\n\nfunction getHolidayTagline(): string | null {\n const now = new Date();\n const month = now.getMonth() + 1;\n const day = now.getDate();\n\n for (const h of HOLIDAY_TAGLINES) {\n const range = h.range ?? 0;\n if (h.month === month && Math.abs(day - h.day) <= range) {\n return h.tagline;\n }\n }\n return null;\n}\n\nexport function pickTagline(): string {\n const holiday = getHolidayTagline();\n if (holiday) return holiday;\n return TAGLINES[Math.floor(Math.random() * TAGLINES.length)];\n}\n","import { isInteractive } from \"./formatter.js\";\nimport { pickTagline } from \"./taglines.js\";\nimport { theme } from \"./theme.js\";\nimport { execSync } from \"node:child_process\";\n\nlet bannerEmitted = false;\n\nfunction resolveCommitHash(): string | null {\n try {\n return (\n execSync(\"git rev-parse --short HEAD\", {\n encoding: \"utf-8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }).trim() || null\n );\n } catch {\n return null;\n }\n}\n\nfunction formatBannerLine(version: string): string {\n const commit = resolveCommitHash();\n const tagline = pickTagline();\n\n const versionPart = `tc v${version}`;\n const commitPart = commit ? ` (${commit})` : \"\";\n const separator = \" — \";\n\n if (!isInteractive()) {\n return `${versionPart}${commitPart}${separator}${tagline}`;\n }\n\n return [\n theme.brand(\"☁️ tc\"),\n \" \",\n theme.muted(`v${version}`),\n commit ? theme.dim(` (${commit})`) : \"\",\n theme.dim(separator),\n theme.primary(tagline),\n ].join(\"\");\n}\n\nexport function emitBanner(version: string): void {\n if (bannerEmitted) return;\n if (!isInteractive()) return;\n if (process.env.TC_HIDE_BANNER === \"1\") return;\n\n bannerEmitted = true;\n process.stderr.write(formatBannerLine(version) + \"\\n\\n\");\n}\n","import { join } from \"node:path\";\nimport {\n CONFIG_DIR,\n PROFILES_DIR,\n CONFIG_FILE,\n DEFAULT_PROFILE,\n DEFAULT_HOST,\n} from \"./constants.js\";\nimport { rm } from \"node:fs/promises\";\nimport {\n readJson,\n writeJson,\n fileExists,\n ensureDir,\n removeDir,\n listDirs,\n} from \"./storage.js\";\nimport type { GlobalConfig, ProfileConfig, CLIContext } from \"./types.js\";\nimport { CLIError } from \"../output/errors.js\";\n\nexport class ProfileManager {\n // ── Initialization ──────────────────────────────────────────────────\n\n /**\n * Creates ~/.tinycloud/ and ~/.tinycloud/profiles/ if they don't exist.\n */\n static async ensureConfigDir(): Promise<void> {\n await ensureDir(CONFIG_DIR);\n await ensureDir(PROFILES_DIR);\n }\n\n // ── Global config ───────────────────────────────────────────────────\n\n /**\n * Reads config.json. Returns a default config if the file is missing.\n */\n static async getConfig(): Promise<GlobalConfig> {\n const config = await readJson<GlobalConfig>(CONFIG_FILE);\n if (!config) {\n return { defaultProfile: DEFAULT_PROFILE, version: 1 };\n }\n return config;\n }\n\n /**\n * Writes the global config to config.json.\n */\n static async setConfig(config: GlobalConfig): Promise<void> {\n await ProfileManager.ensureConfigDir();\n await writeJson(CONFIG_FILE, config);\n }\n\n // ── Profile CRUD ────────────────────────────────────────────────────\n\n /**\n * Returns the profile config for the given name.\n * Throws CLIError if the profile doesn't exist.\n */\n static async getProfile(name: string): Promise<ProfileConfig> {\n const profilePath = join(PROFILES_DIR, name, \"profile.json\");\n const profile = await readJson<ProfileConfig>(profilePath);\n if (!profile) {\n throw new CLIError(\n \"PROFILE_NOT_FOUND\",\n `Profile \"${name}\" does not exist. Run \\`tc init\\` or \\`tc profile create ${name}\\` first.`,\n );\n }\n return profile;\n }\n\n /**\n * Saves a profile config, creating the profile directory if needed.\n */\n static async setProfile(name: string, data: ProfileConfig): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"profile.json\"), data);\n }\n\n /**\n * Returns true if a profile directory exists.\n */\n static async profileExists(name: string): Promise<boolean> {\n return fileExists(join(PROFILES_DIR, name, \"profile.json\"));\n }\n\n /**\n * Returns an array of profile directory names.\n */\n static async listProfiles(): Promise<string[]> {\n return listDirs(PROFILES_DIR);\n }\n\n /**\n * Deletes a profile directory.\n * Throws if trying to delete the current default profile.\n */\n static async deleteProfile(name: string): Promise<void> {\n const config = await ProfileManager.getConfig();\n if (config.defaultProfile === name) {\n throw new CLIError(\n \"PROFILE_DELETE_DEFAULT\",\n `Cannot delete the default profile \"${name}\". Change the default first with \\`tc profile default <other>\\`.`,\n );\n }\n const profileDir = join(PROFILES_DIR, name);\n await removeDir(profileDir);\n }\n\n // ── Key management ──────────────────────────────────────────────────\n\n /**\n * Returns the parsed JWK for a profile, or null if no key exists.\n */\n static async getKey(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"key.json\"));\n }\n\n /**\n * Saves a JWK key for a profile.\n */\n static async setKey(name: string, jwk: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"key.json\"), jwk);\n }\n\n // ── Session management ──────────────────────────────────────────────\n\n /**\n * Returns the parsed session for a profile, or null if none exists.\n */\n static async getSession(name: string): Promise<object | null> {\n return readJson<object>(join(PROFILES_DIR, name, \"session.json\"));\n }\n\n /**\n * Saves session data for a profile.\n */\n static async setSession(name: string, session: object): Promise<void> {\n const profileDir = join(PROFILES_DIR, name);\n await ensureDir(profileDir);\n await writeJson(join(profileDir, \"session.json\"), session);\n }\n\n /**\n * Removes the session file for a profile.\n */\n static async clearSession(name: string): Promise<void> {\n const sessionPath = join(PROFILES_DIR, name, \"session.json\");\n try {\n await rm(sessionPath);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n }\n\n // ── Cache management ────────────────────────────────────────────────\n\n /**\n * Returns the path to the profile's cache directory, creating it if needed.\n */\n static async getCacheDir(name: string): Promise<string> {\n const cacheDir = join(PROFILES_DIR, name, \"cache\");\n await ensureDir(cacheDir);\n return cacheDir;\n }\n\n // ── Resolution helpers ──────────────────────────────────────────────\n\n /**\n * Resolves the full CLI context from flags, env vars, and config.\n *\n * Profile resolution: options.profile > TC_PROFILE env > config.defaultProfile > \"default\"\n * Host resolution: options.host > TC_HOST env > profile.host > DEFAULT_HOST\n */\n static async resolveContext(options: {\n profile?: string;\n host?: string;\n verbose?: boolean;\n noCache?: boolean;\n quiet?: boolean;\n }): Promise<CLIContext> {\n // Resolve profile name\n const config = await ProfileManager.getConfig();\n const profile =\n options.profile ??\n process.env.TC_PROFILE ??\n config.defaultProfile ??\n DEFAULT_PROFILE;\n\n // Resolve host — try profile config if it exists, but don't fail if it doesn't\n let profileHost: string | undefined;\n try {\n const profileConfig = await ProfileManager.getProfile(profile);\n profileHost = profileConfig.host;\n } catch {\n // Profile may not exist yet (e.g., during `tc init`)\n }\n\n const host =\n options.host ??\n process.env.TC_HOST ??\n profileHost ??\n DEFAULT_HOST;\n\n return {\n profile,\n host,\n verbose: options.verbose ?? false,\n noCache: options.noCache ?? false,\n quiet: options.quiet ?? false,\n };\n }\n}\n","import { readFile, writeFile, stat, mkdir, rm, readdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Read and parse a JSON file. Returns null if the file does not exist.\n * Throws on any other error (permission denied, invalid JSON, etc.).\n */\nexport async function readJson<T>(filePath: string): Promise<T | null> {\n try {\n const data = await readFile(filePath, \"utf-8\");\n return JSON.parse(data) as T;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n}\n\n/**\n * Write data as JSON to a file. Creates parent directories if needed.\n */\nexport async function writeJson(filePath: string, data: unknown): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, JSON.stringify(data, null, 2) + \"\\n\", \"utf-8\");\n}\n\n/**\n * Check if a file exists at the given path.\n */\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n await stat(filePath);\n return true;\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n}\n\n/**\n * Ensure a directory exists (mkdir -p).\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Remove a directory recursively (rm -rf).\n */\nexport async function removeDir(dirPath: string): Promise<void> {\n await rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * List directory names (not files) inside a directory.\n * Returns an empty array if the directory does not exist.\n */\nexport async function listDirs(dirPath: string): Promise<string[]> {\n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory()).map((e) => e.name);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n","import { TCWSessionManager, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\nimport { randomBytes } from \"node:crypto\";\n\nlet wasmInitialized = false;\n\nfunction ensureWasm(): void {\n if (!wasmInitialized) {\n initPanicHook();\n wasmInitialized = true;\n }\n}\n\n/**\n * Generate a new Ed25519 keypair. Returns the JWK.\n */\nexport function generateKey(): { jwk: object; did: string } {\n ensureWasm();\n const mgr = new TCWSessionManager();\n const keyId = mgr.createSessionKey(\"cli\");\n const jwkStr = mgr.jwk(keyId);\n if (!jwkStr) throw new Error(\"Failed to generate key\");\n const jwk = JSON.parse(jwkStr);\n const did = mgr.getDID(keyId);\n return { jwk, did };\n}\n\n/**\n * Get the DID from an existing JWK.\n */\nexport function keyToDID(jwk: object): string {\n ensureWasm();\n const mgr = new TCWSessionManager();\n // Import key by creating with known ID, then getting DID\n // For now, re-generate and return — TODO: import support\n const keyId = mgr.createSessionKey(\"imported\");\n return mgr.getDID(keyId);\n}\n\n/**\n * Generate a new random Ethereum private key.\n * Returns the hex-encoded key with 0x prefix.\n */\nexport function generateEthereumPrivateKey(): string {\n const keyBytes = randomBytes(32);\n return \"0x\" + keyBytes.toString(\"hex\");\n}\n\n/**\n * Derive the Ethereum address from a private key.\n * Uses PrivateKeySigner from node-sdk.\n */\nexport async function deriveAddress(privateKey: string): Promise<string> {\n const signer = new PrivateKeySigner(privateKey);\n return signer.getAddress();\n}\n\n/**\n * Create a did:pkh DID from an Ethereum address.\n * Uses EIP-155 chain ID 1 (mainnet).\n */\nexport function addressToDID(address: string, chainId: number = 1): string {\n return `did:pkh:eip155:${chainId}:${address}`;\n}\n\n/**\n * Generate a new local Ethereum key and return all identity info.\n */\nexport async function generateLocalIdentity(chainId: number = 1): Promise<{\n privateKey: string;\n address: string;\n did: string;\n}> {\n const privateKey = generateEthereumPrivateKey();\n const address = await deriveAddress(privateKey);\n const did = addressToDID(address, chainId);\n return { privateKey, address, did };\n}\n\n/**\n * Sign in to TinyCloud using a local Ethereum private key.\n * Creates a TinyCloudNode with the private key and calls signIn().\n */\nexport async function localKeySignIn(options: {\n privateKey: string;\n host: string;\n}): Promise<{\n spaceId: string;\n address: string;\n chainId: number;\n}> {\n const { TinyCloudNode } = await import(\"@tinycloud/node-sdk\");\n\n const node = new TinyCloudNode({\n privateKey: options.privateKey,\n host: options.host,\n autoCreateSpace: true,\n });\n\n await node.signIn();\n\n const address = await new PrivateKeySigner(options.privateKey).getAddress();\n\n return {\n spaceId: node.spaceId ?? \"\",\n address,\n chainId: 1,\n };\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { isInteractive } from \"../output/formatter.js\";\nimport { createInterface } from \"node:readline\";\n\nconst OPENKEY_BASE = \"https://openkey.so\";\n\ninterface DelegationData {\n delegationHeader: { Authorization: string };\n delegationCid: string;\n spaceId: string;\n [key: string]: unknown;\n}\n\n/**\n * Start the browser auth flow.\n * Mode 1 (default): local HTTP callback server\n * Mode 2 (--paste): manual code paste\n */\nexport async function startAuthFlow(\n did: string,\n options: { paste?: boolean; jwk?: object; host?: string } = {}\n): Promise<DelegationData> {\n if (options.paste) {\n return pasteFlow(did, options);\n }\n\n try {\n return await callbackFlow(did, options);\n } catch {\n // Fallback to paste if browser can't open\n if (isInteractive()) {\n console.error(\"Could not open browser. Falling back to manual paste mode.\");\n return pasteFlow(did, options);\n }\n throw new Error(\"Cannot open browser in non-interactive mode. Use --paste flag.\");\n }\n}\n\nfunction buildAuthUrl(did: string, options: { jwk?: object; host?: string; callback?: string } = {}): string {\n const params = new URLSearchParams();\n params.set(\"did\", did);\n if (options.callback) {\n params.set(\"callback\", options.callback);\n }\n if (options.jwk) {\n // base64url-encode the JWK\n const jwkB64 = Buffer.from(JSON.stringify(options.jwk)).toString(\"base64url\");\n params.set(\"jwk\", jwkB64);\n }\n if (options.host) {\n params.set(\"host\", options.host);\n }\n return `${OPENKEY_BASE}/delegate?${params.toString()}`;\n}\n\nasync function callbackFlow(did: string, options: { jwk?: object; host?: string } = {}): Promise<DelegationData> {\n return new Promise((resolve, reject) => {\n let timeout: ReturnType<typeof setTimeout>;\n let settled = false;\n let rl: ReturnType<typeof createInterface> | undefined;\n\n function settle(result: { data?: DelegationData; error?: Error }) {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n server.close();\n if (rl) {\n rl.close();\n }\n if (result.data) {\n resolve(result.data);\n } else {\n reject(result.error);\n }\n }\n\n function parsePasteInput(input: string): DelegationData {\n const trimmed = input.trim();\n // Try parsing as JSON directly\n try {\n return JSON.parse(trimmed) as DelegationData;\n } catch {\n // Try base64 decoding first\n const decoded = Buffer.from(trimmed, \"base64\").toString(\"utf-8\");\n return JSON.parse(decoded) as DelegationData;\n }\n }\n\n const server = createServer((req: IncomingMessage, res: ServerResponse) => {\n if (req.method === \"POST\" && req.url === \"/callback\") {\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => { body += chunk.toString(); });\n req.on(\"end\", () => {\n try {\n const data = JSON.parse(body) as DelegationData;\n // Send CORS headers and success response\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n });\n res.end(JSON.stringify({ success: true }));\n settle({ data });\n } catch (err) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON\" }));\n settle({ error: new Error(\"Invalid delegation data received\") });\n }\n });\n } else if (req.method === \"OPTIONS\") {\n // CORS preflight\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end();\n } else {\n res.writeHead(404);\n res.end();\n }\n });\n\n server.listen(0, \"127.0.0.1\", async () => {\n const addr = server.address();\n if (!addr || typeof addr === \"string\") {\n settle({ error: new Error(\"Failed to start callback server\") });\n return;\n }\n const port = addr.port;\n const callbackUrl = `http://127.0.0.1:${port}/callback`;\n const authUrl = buildAuthUrl(did, { ...options, callback: callbackUrl });\n\n if (isInteractive()) {\n console.error(`Opening browser for authentication...`);\n console.error(`If the browser doesn't open, visit: ${authUrl}`);\n }\n\n try {\n const open = (await import(\"open\")).default;\n await open(authUrl);\n } catch {\n server.close();\n throw new Error(\"Failed to open browser\");\n }\n\n // In interactive mode, also accept paste input while waiting for callback\n if (isInteractive()) {\n console.error(`\\nIf the browser can't connect back, paste the delegation code here:`);\n rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n rl.on(\"line\", (input) => {\n if (settled) return;\n try {\n const data = parsePasteInput(input);\n settle({ data });\n } catch {\n console.error(\"Invalid delegation code. Expected JSON or base64-encoded JSON. Try again:\");\n }\n });\n }\n });\n\n // Timeout after 5 minutes\n timeout = setTimeout(() => {\n settle({ error: new Error(\"Authentication timed out after 5 minutes\") });\n }, 5 * 60 * 1000);\n });\n}\n\nasync function pasteFlow(did: string, options: { jwk?: object; host?: string } = {}): Promise<DelegationData> {\n const authUrl = buildAuthUrl(did, options);\n\n console.error(`\\nOpen this URL in a browser to authenticate:\\n`);\n console.error(` ${authUrl}\\n`);\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise((resolve, reject) => {\n rl.question(\"Paste delegation code: \", (input) => {\n rl.close();\n try {\n // Try parsing as JSON directly\n const data = JSON.parse(input.trim()) as DelegationData;\n resolve(data);\n } catch {\n // Try base64 decoding first\n try {\n const decoded = Buffer.from(input.trim(), \"base64\").toString(\"utf-8\");\n const data = JSON.parse(decoded) as DelegationData;\n resolve(data);\n } catch {\n reject(new Error(\"Invalid delegation code. Expected JSON or base64-encoded JSON.\"));\n }\n }\n });\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_HOST, DEFAULT_CHAIN_ID } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Initialize a new TinyCloud profile\")\n .option(\"--name <profile>\", \"Profile name\", \"default\")\n .option(\"--key-only\", \"Only generate key, skip authentication\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .option(\"--paste\", \"Use manual paste mode for authentication\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const profileName: string = options.name;\n const host: string = options.host ?? globalOpts.host ?? DEFAULT_HOST;\n\n // Check if profile already exists\n if (await ProfileManager.profileExists(profileName)) {\n throw new CLIError(\n \"PROFILE_EXISTS\",\n `Profile \"${profileName}\" already exists. Use \\`tc profile delete ${profileName}\\` first or choose a different name.`,\n ExitCode.ERROR,\n );\n }\n\n await ProfileManager.ensureConfigDir();\n\n // Generate key\n const { jwk, did } = await withSpinner(\"Generating key...\", async () => {\n return generateKey();\n });\n\n await ProfileManager.setKey(profileName, jwk);\n\n // Create initial profile\n const profileConfig = {\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n createdAt: new Date().toISOString(),\n };\n\n await ProfileManager.setProfile(profileName, profileConfig);\n\n // Set as default if this is \"default\" or no default exists\n const config = await ProfileManager.getConfig();\n if (profileName === \"default\" || !await ProfileManager.profileExists(config.defaultProfile)) {\n await ProfileManager.setConfig({ ...config, defaultProfile: profileName });\n }\n\n if (options.keyOnly) {\n outputJson({\n profile: profileName,\n did,\n host,\n authenticated: false,\n });\n return;\n }\n\n // Auth flow\n const delegationData = await startAuthFlow(did, {\n paste: options.paste,\n jwk,\n host,\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with auth data\n await ProfileManager.setProfile(profileName, {\n ...profileConfig,\n spaceId: delegationData.spaceId,\n primaryDid: delegationData.primaryDid as string | undefined,\n });\n\n outputJson({\n profile: profileName,\n did,\n host,\n spaceId: delegationData.spaceId,\n authenticated: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatField, isInteractive, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_CHAIN_ID } from \"../config/constants.js\";\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\nimport {\n generateLocalIdentity,\n deriveAddress,\n addressToDID,\n localKeySignIn,\n generateKey,\n} from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport type { AuthMethod } from \"../config/types.js\";\n\n/**\n * Prompt user to choose an auth method interactively.\n * Returns \"local\" for non-interactive (CI/headless) environments.\n */\nasync function promptAuthMethod(): Promise<AuthMethod> {\n if (!isInteractive()) {\n return \"local\";\n }\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n return new Promise<AuthMethod>((resolve) => {\n process.stderr.write(\"\\n\" + theme.heading(\"Choose authentication method:\") + \"\\n\");\n process.stderr.write(` ${theme.accent(\"1)\")} OpenKey ${theme.muted(\"(browser-based, for interactive use)\")}\\n`);\n process.stderr.write(` ${theme.accent(\"2)\")} Local key ${theme.muted(\"(Ethereum private key, for agents/CI)\")}\\n\\n`);\n\n rl.question(\"Enter choice [1]: \", (answer) => {\n rl.close();\n const trimmed = answer.trim();\n if (trimmed === \"2\" || trimmed.toLowerCase() === \"local\") {\n resolve(\"local\");\n } else {\n resolve(\"openkey\");\n }\n });\n });\n}\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command(\"auth\").description(\"Authentication management\");\n\n auth\n .command(\"login\")\n .description(\"Authenticate with TinyCloud\")\n .option(\"--paste\", \"Use manual paste mode instead of browser callback\")\n .option(\"--method <method>\", \"Authentication method: local or openkey\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n // Determine auth method\n let method: AuthMethod;\n if (options.method) {\n if (options.method !== \"local\" && options.method !== \"openkey\") {\n throw new CLIError(\n \"INVALID_METHOD\",\n `Invalid auth method \"${options.method}\". Use \"local\" or \"openkey\".`,\n ExitCode.USAGE_ERROR,\n );\n }\n method = options.method;\n } else {\n method = await promptAuthMethod();\n }\n\n if (method === \"local\") {\n await handleLocalAuth(ctx.profile, ctx.host);\n } else {\n await handleOpenKeyAuth(ctx.profile, ctx.host, options.paste);\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"logout\")\n .description(\"Clear session (keep key)\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n await ProfileManager.clearSession(ctx.profile);\n outputJson({ profile: ctx.profile, authenticated: false });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"status\")\n .description(\"Show current authentication state\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const hasKey = await ProfileManager.getKey(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n let profile;\n try {\n profile = await ProfileManager.getProfile(ctx.profile);\n } catch {\n profile = null;\n }\n\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n authenticated,\n did: profile?.did ?? null,\n primaryDid: profile?.primaryDid ?? null,\n spaceId: profile?.spaceId ?? null,\n host: ctx.host,\n profile: ctx.profile,\n hasKey: hasKey !== null,\n authMethod: profile?.authMethod ?? null,\n address: profile?.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Authentication Status\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile?.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Host\", ctx.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile?.did ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Primary DID\", profile?.primaryDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile?.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile?.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Has Key\", hasKey !== null) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"whoami\")\n .description(\"Show identity information\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile);\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n profile: ctx.profile,\n did: profile.did,\n primaryDid: profile.primaryDid ?? null,\n spaceId: profile.spaceId ?? null,\n host: profile.host,\n authenticated,\n authMethod: profile.authMethod ?? null,\n address: profile.address ?? null,\n });\n } else {\n process.stdout.write(theme.heading(\"Identity\") + \"\\n\");\n process.stdout.write(formatField(\"Profile\", ctx.profile) + \"\\n\");\n process.stdout.write(formatField(\"DID\", profile.did) + \"\\n\");\n process.stdout.write(formatField(\"Primary DID\", profile.primaryDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Address\", profile.address ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Space ID\", profile.spaceId ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Host\", profile.host) + \"\\n\");\n process.stdout.write(formatField(\"Authenticated\", authenticated) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/**\n * Handle local Ethereum key authentication.\n * Generates or reuses a local private key, creates a did:pkh identity,\n * and signs in to TinyCloud directly (no browser needed).\n */\nasync function handleLocalAuth(profileName: string, host: string): Promise<void> {\n const profile = await ProfileManager.getProfile(profileName).catch(() => null);\n\n let privateKey: string;\n let address: string;\n let did: string;\n\n if (profile?.authMethod === \"local\" && profile.privateKey && profile.address) {\n // Reuse existing local key\n privateKey = profile.privateKey;\n address = profile.address;\n did = profile.did;\n\n if (isInteractive()) {\n process.stderr.write(theme.muted(\"Using existing local key\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n }\n } else {\n // Generate new local identity\n const identity = await withSpinner(\"Generating Ethereum key...\", async () => {\n return generateLocalIdentity(DEFAULT_CHAIN_ID);\n });\n\n privateKey = identity.privateKey;\n address = identity.address;\n did = identity.did;\n\n if (isInteractive()) {\n process.stderr.write(\"\\n\" + theme.heading(\"Local Key Generated\") + \"\\n\");\n process.stderr.write(formatField(\"Address\", address) + \"\\n\");\n process.stderr.write(formatField(\"DID\", did) + \"\\n\\n\");\n }\n }\n\n // We also need a session key (Ed25519 JWK) for the profile\n const hasKey = await ProfileManager.getKey(profileName);\n if (!hasKey) {\n const { jwk } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n await ProfileManager.setKey(profileName, jwk);\n }\n\n // Sign in using the private key\n const sessionResult = await withSpinner(\"Signing in...\", async () => {\n return localKeySignIn({ privateKey, host });\n });\n\n // Store session data\n await ProfileManager.setSession(profileName, {\n authMethod: \"local\",\n address,\n chainId: DEFAULT_CHAIN_ID,\n spaceId: sessionResult.spaceId,\n });\n\n // Update profile\n await ProfileManager.setProfile(profileName, {\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n primaryDid: did,\n spaceId: sessionResult.spaceId,\n createdAt: profile?.createdAt ?? new Date().toISOString(),\n authMethod: \"local\",\n privateKey,\n address,\n });\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did,\n address,\n spaceId: sessionResult.spaceId,\n authMethod: \"local\",\n });\n}\n\n/**\n * Handle OpenKey (browser-based) authentication.\n * This is the original auth flow.\n */\nasync function handleOpenKeyAuth(profileName: string, host: string, paste?: boolean): Promise<void> {\n const key = await ProfileManager.getKey(profileName);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${profileName}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n // Get DID from profile\n const profile = await ProfileManager.getProfile(profileName);\n\n // Start browser auth flow\n const delegationData = await startAuthFlow(profile.did, {\n paste,\n jwk: key,\n host,\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with primary DID if present\n const updatedProfile = {\n ...profile,\n authMethod: \"openkey\" as const,\n };\n\n if (delegationData.spaceId) {\n updatedProfile.spaceId = delegationData.spaceId;\n updatedProfile.primaryDid = delegationData.primaryDid as string | undefined;\n }\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did: profile.did,\n spaceId: delegationData.spaceId,\n authMethod: \"openkey\",\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes, formatTimeAgo } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\nexport function registerKvCommand(program: Command): void {\n const kv = program.command(\"kv\").description(\"Key-value store operations\");\n\n // tc kv get <key>\n kv\n .command(\"get <key>\")\n .description(\"Get a value by key\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Getting ${key}...`, () => node.kv.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n const metadata = result.data.headers ?? {};\n\n if (options.output) {\n // Write to file\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n // Raw output - write directly to stdout\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n // Output value\n if (shouldOutputJson()) {\n outputJson({\n key,\n data,\n metadata,\n });\n } else {\n // Just output the raw value for get - useful for piping\n const content = typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv put <key> [value]\n kv\n .command(\"put <key> [value]\")\n .description(\"Set a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n // Determine value source\n let putValue: string | Buffer;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = await readFile(options.file);\n } else if (options.stdin) {\n putValue = await readStdin();\n } else {\n // Try to parse as JSON, fall back to string\n try {\n putValue = JSON.parse(value!);\n } catch {\n putValue = value!;\n }\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.kv.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv delete <key>\n kv\n .command(\"delete <key>\")\n .description(\"Delete a key\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.kv.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv list\n kv\n .command(\"list\")\n .description(\"List keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing keys...\", () => node.kv.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n if (shouldOutputJson()) {\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } else {\n if (keyList.length === 0) {\n process.stdout.write(theme.muted(\"No keys found.\") + \"\\n\");\n } else {\n const rows = keyList.map((e: any) => [\n e.key || e,\n e.contentLength ? formatBytes(e.contentLength) : \"—\",\n e.updatedAt ? formatTimeAgo(e.updatedAt) : \"—\",\n ]);\n process.stdout.write(formatTable([\"Key\", \"Size\", \"Updated\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc kv head <key>\n kv\n .command(\"head <key>\")\n .description(\"Get metadata for a key (no body)\")\n .action(async (key: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(`Checking ${key}...`, () => node.kv.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? {},\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { TinyCloudNode } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { CLIContext } from \"../config/types.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\n\n/**\n * Create a TinyCloudNode instance from the current CLI context.\n * Uses the profile's persisted session and key.\n *\n * Supports both auth methods:\n * - \"local\": Uses the stored Ethereum private key directly\n * - \"openkey\": Restores session from stored delegation data (browser auth flow)\n */\nexport async function createSDKInstance(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile);\n const session = await ProfileManager.getSession(ctx.profile) as Record<string, unknown> | null;\n const key = await ProfileManager.getKey(ctx.profile);\n\n // For local auth, use the stored private key\n const effectivePrivateKey = options?.privateKey ?? profile.privateKey;\n\n if (!key && !effectivePrivateKey) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n if (profile.authMethod === \"local\" && effectivePrivateKey) {\n // Local key auth: create node with private key and sign in\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: effectivePrivateKey,\n });\n\n await node.signIn();\n return node;\n }\n\n // OpenKey / delegation-based auth\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: options?.privateKey,\n });\n\n if (options?.privateKey) {\n // Sign in with private key (existing behavior)\n await node.signIn();\n } else if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\n // Restore session from stored delegation data (browser auth flow)\n await node.restoreSession({\n delegationHeader: session.delegationHeader as { Authorization: string },\n delegationCid: session.delegationCid as string,\n spaceId: session.spaceId as string,\n jwk: (session.jwk as object) ?? key,\n verificationMethod: (session.verificationMethod as string) ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n });\n }\n\n return node;\n}\n\n/**\n * Ensure the user is authenticated.\n * Throws AUTH_REQUIRED if no session exists.\n */\nexport async function ensureAuthenticated(\n ctx: CLIContext,\n options?: { privateKey?: string }\n): Promise<TinyCloudNode> {\n const profile = await ProfileManager.getProfile(ctx.profile).catch(() => null);\n\n // For local auth, we can sign in directly without a stored session\n if (profile?.authMethod === \"local\" && profile.privateKey) {\n return createSDKInstance(ctx, { privateKey: profile.privateKey });\n }\n\n const session = await ProfileManager.getSession(ctx.profile);\n\n if (!session) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n `Not authenticated. Run \\`tc auth login\\` or \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n return createSDKInstance(ctx, options);\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerSpaceCommand(program: Command): void {\n const space = program.command(\"space\").description(\"Space management\");\n\n space\n .command(\"list\")\n .description(\"List spaces\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n if (shouldOutputJson()) {\n outputJson({ spaces: result.data, count: result.data.length });\n } else {\n if (result.data.length === 0) {\n process.stdout.write(theme.muted(\"No spaces found.\") + \"\\n\");\n } else {\n const rows = result.data.map((s: any) => [\n s.id || s.spaceId || \"—\",\n s.name || \"—\",\n s.owner || \"—\",\n ]);\n process.stdout.write(formatTable([\"Space ID\", \"Name\", \"Owner\"], rows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"create <name>\")\n .description(\"Create a new space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.spaces.create(name);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n outputJson({ spaceId: result.data.id, name });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"info [space-id]\")\n .description(\"Get space info\")\n .action(async (spaceId: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const targetId = spaceId ?? node.spaceId;\n if (!targetId) {\n throw new CLIError(\"NO_SPACE\", \"No space ID specified and no active space\", ExitCode.ERROR);\n }\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n outputJson({\n spaceId: targetId,\n name: profile.spaceName,\n owner: node.did,\n host: ctx.host,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n space\n .command(\"switch <name>\")\n .description(\"Switch active space\")\n .action(async (name: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const profile = await ProfileManager.getProfile(ctx.profile);\n await ProfileManager.setProfile(ctx.profile, { ...profile, spaceName: name });\n\n outputJson({ profile: ctx.profile, spaceName: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","/**\n * Parse a duration string into milliseconds.\n * Supports: \"1h\", \"30m\", \"7d\", \"1w\", or ISO date string.\n */\nexport function parseDuration(input: string): number {\n const match = input.match(/^(\\d+)(m|h|d|w)$/);\n if (match) {\n const value = parseInt(match[1], 10);\n const unit = match[2];\n const multipliers: Record<string, number> = {\n m: 60 * 1000,\n h: 60 * 60 * 1000,\n d: 24 * 60 * 60 * 1000,\n w: 7 * 24 * 60 * 60 * 1000,\n };\n return value * multipliers[unit];\n }\n\n // Try as ISO date\n const date = new Date(input);\n if (!isNaN(date.getTime())) {\n const ms = date.getTime() - Date.now();\n if (ms <= 0) {\n throw new Error(`Expiry date \"${input}\" is in the past`);\n }\n return ms;\n }\n\n throw new Error(`Invalid duration: \"${input}\". Use format like \"1h\", \"7d\", or an ISO date.`);\n}\n\n/**\n * Parse duration to an expiry Date.\n */\nexport function parseExpiry(input: string): Date {\n return new Date(Date.now() + parseDuration(input));\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\n\nexport function registerDelegationCommand(program: Command): void {\n const delegation = program.command(\"delegation\").description(\"Manage delegations\");\n\n delegation\n .command(\"create\")\n .description(\"Create a delegation\")\n .requiredOption(\"--to <did>\", \"Recipient DID\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .requiredOption(\"--actions <actions>\", \"Comma-separated actions (e.g., kv/get,kv/list)\")\n .option(\"--expiry <duration>\", \"Expiry duration (e.g., 1h, 7d, ISO date)\", \"1h\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.delegationManager.create({\n delegateDID: options.to,\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n cid: result.data.cid,\n delegateDid: options.to,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"list\")\n .description(\"List delegations\")\n .option(\"--granted\", \"Show only delegations I've granted\")\n .option(\"--received\", \"Show only delegations I've received\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n let delegations: any[] = result.data;\n\n // Filter if requested\n if (options.granted) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => d.delegatorDID === myDid);\n } else if (options.received) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => d.delegateDID === myDid || d.delegateDID?.includes(myDid));\n }\n\n outputJson({\n delegations: delegations.map((d: any) => ({\n cid: d.cid,\n delegatee: d.delegateDID,\n delegator: d.delegatorDID,\n path: d.path,\n actions: d.actions,\n expiry: d.expiry instanceof Date ? d.expiry.toISOString() : d.expiry,\n })),\n count: delegations.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"info <cid>\")\n .description(\"Get delegation details\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.get(cid);\n if (!result.ok) {\n throw new CLIError(\"NOT_FOUND\", `Delegation \"${cid}\" not found`, ExitCode.NOT_FOUND);\n }\n\n outputJson(result.data);\n } catch (error) {\n handleError(error);\n }\n });\n\n delegation\n .command(\"revoke <cid>\")\n .description(\"Revoke a delegation\")\n .action(async (cid: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.delegationManager.revoke(cid);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ cid, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { parseExpiry } from \"../lib/duration.js\";\n\nexport function registerShareCommand(program: Command): void {\n const share = program.command(\"share\").description(\"Share data with others\");\n\n share\n .command(\"create\")\n .description(\"Create a share link\")\n .requiredOption(\"--path <path>\", \"KV path scope\")\n .option(\"--actions <actions>\", \"Comma-separated actions\", \"kv/get\")\n .option(\"--expiry <duration>\", \"Expiry duration\", \"7d\")\n .option(\"--web-link\", \"Generate a web UI link for non-technical recipients\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const actions = options.actions.split(\",\").map((a: string) => {\n const trimmed = a.trim();\n return trimmed.startsWith(\"tinycloud.\") ? trimmed : `tinycloud.${trimmed}`;\n });\n\n const expiry = parseExpiry(options.expiry);\n\n const result = await node.sharing.generate({\n path: options.path,\n actions,\n expiry,\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const output: Record<string, unknown> = {\n token: result.data.token ?? result.data.cid,\n shareData: result.data.encodedData ?? result.data.url,\n path: options.path,\n actions,\n expiry: expiry.toISOString(),\n };\n\n if (options.webLink) {\n const shareData = result.data.encodedData ?? result.data.url ?? \"\";\n output.webLink = `https://openkey.cloud/share?data=${encodeURIComponent(shareData)}`;\n }\n\n outputJson(output);\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"receive [data]\")\n .description(\"Receive a share\")\n .option(\"--stdin\", \"Read share data from stdin\")\n .action(async (data: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n let shareData: string;\n if (options.stdin) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n shareData = Buffer.concat(chunks).toString(\"utf-8\").trim();\n } else if (data) {\n shareData = data;\n } else {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide share data or use --stdin\", ExitCode.USAGE_ERROR);\n }\n\n const result = await node.sharing.receive(shareData);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n received: true,\n spaceId: result.data.spaceId,\n path: result.data.path,\n actions: result.data.actions,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"list\")\n .description(\"List active shares\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.list();\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ shares: result.data, count: result.data.length });\n } catch (error) {\n handleError(error);\n }\n });\n\n share\n .command(\"revoke <token>\")\n .description(\"Revoke a share\")\n .action(async (token: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await node.sharing.revoke(token);\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ token, revoked: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\n\nexport function registerNodeCommand(program: Command): void {\n const node = program.command(\"node\").description(\"Node health and info\");\n\n node\n .command(\"health\")\n .description(\"Check node health\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n const response = await fetch(`${ctx.host}/healthz`);\n const latencyMs = Date.now() - start;\n\n outputJson({\n healthy: response.ok,\n host: ctx.host,\n latencyMs,\n });\n } catch (error) {\n if (error instanceof TypeError && (error as Error).message.includes(\"fetch\")) {\n outputJson({ healthy: false, host: (await ProfileManager.resolveContext(cmd.optsWithGlobals())).host, error: \"Connection refused\" });\n } else {\n handleError(error);\n }\n }\n });\n\n node\n .command(\"version\")\n .description(\"Get node version\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const response = await fetch(`${ctx.host}/info`);\n if (!response.ok) {\n throw new CLIError(\"NODE_ERROR\", `Node returned ${response.status}`, ExitCode.NODE_ERROR);\n }\n\n const data = await response.json() as Record<string, unknown>;\n outputJson({ ...data, host: ctx.host });\n } catch (error) {\n handleError(error);\n }\n });\n\n node\n .command(\"status\")\n .description(\"Combined health and version info\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const start = Date.now();\n\n // Fetch health and version in parallel\n const [healthRes, versionRes] = await Promise.allSettled([\n fetch(`${ctx.host}/healthz`),\n fetch(`${ctx.host}/info`),\n ]);\n\n const latencyMs = Date.now() - start;\n const healthy = healthRes.status === \"fulfilled\" && healthRes.value.ok;\n\n let versionData: Record<string, unknown> = {};\n if (versionRes.status === \"fulfilled\" && versionRes.value.ok) {\n versionData = await versionRes.value.json() as Record<string, unknown>;\n }\n\n outputJson({\n healthy,\n host: ctx.host,\n latencyMs,\n ...versionData,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { createInterface } from \"node:readline\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, isInteractive, shouldOutputJson, formatField } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { generateKey } from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerProfileCommand(program: Command): void {\n const profile = program.command(\"profile\").description(\"Profile management\");\n\n profile\n .command(\"list\")\n .description(\"List all profiles\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const config = await ProfileManager.getConfig();\n const names = await ProfileManager.listProfiles();\n\n const profiles = await Promise.all(\n names.map(async (name) => {\n try {\n const p = await ProfileManager.getProfile(name);\n return {\n name: p.name,\n host: p.host,\n did: p.did,\n active: name === config.defaultProfile,\n };\n } catch {\n return { name, host: null, did: null, active: name === config.defaultProfile };\n }\n })\n );\n\n if (shouldOutputJson()) {\n outputJson({\n profiles,\n defaultProfile: config.defaultProfile,\n });\n } else {\n for (const p of profiles) {\n const marker = p.active ? theme.success(\"● \") : \" \";\n const name = p.active ? theme.brand(p.name) : p.name;\n const host = theme.muted(p.host || \"no host\");\n process.stdout.write(`${marker}${name} ${host}\\n`);\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"create <name>\")\n .description(\"Create a new profile\")\n .option(\"--host <url>\", \"TinyCloud node URL\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const host = options.host ?? globalOpts.host ?? \"https://node.tinycloud.xyz\";\n\n if (await ProfileManager.profileExists(name)) {\n throw new CLIError(\"PROFILE_EXISTS\", `Profile \"${name}\" already exists`, ExitCode.ERROR);\n }\n\n await ProfileManager.ensureConfigDir();\n const { jwk, did } = generateKey();\n await ProfileManager.setKey(name, jwk);\n await ProfileManager.setProfile(name, {\n name,\n host,\n chainId: 1,\n spaceName: \"default\",\n did,\n createdAt: new Date().toISOString(),\n });\n\n outputJson({ profile: name, did, host, created: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"show [name]\")\n .description(\"Show profile details\")\n .action(async (name: string | undefined, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profileName = name ?? ctx.profile;\n\n const p = await ProfileManager.getProfile(profileName);\n const hasKey = (await ProfileManager.getKey(profileName)) !== null;\n const hasSession = (await ProfileManager.getSession(profileName)) !== null;\n const config = await ProfileManager.getConfig();\n const isDefault = profileName === config.defaultProfile;\n\n if (shouldOutputJson()) {\n outputJson({\n ...p,\n hasKey,\n hasSession,\n isDefault,\n });\n } else {\n process.stdout.write(`${theme.heading(p.name)}${isDefault ? theme.success(\" (default)\") : \"\"}\\n`);\n process.stdout.write(formatField(\"Host\", p.host) + \"\\n\");\n process.stdout.write(formatField(\"DID\", p.did) + \"\\n\");\n process.stdout.write(formatField(\"Space\", p.spaceId || null) + \"\\n\");\n process.stdout.write(formatField(\"Key\", hasKey) + \"\\n\");\n process.stdout.write(formatField(\"Session\", hasSession) + \"\\n\");\n process.stdout.write(formatField(\"Created\", p.createdAt) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"switch <name>\")\n .description(\"Set default profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n if (!(await ProfileManager.profileExists(name))) {\n throw new CLIError(\"PROFILE_NOT_FOUND\", `Profile \"${name}\" does not exist`, ExitCode.NOT_FOUND);\n }\n\n const config = await ProfileManager.getConfig();\n await ProfileManager.setConfig({ ...config, defaultProfile: name });\n\n outputJson({ defaultProfile: name, switched: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n profile\n .command(\"delete <name>\")\n .description(\"Delete a profile\")\n .action(async (name: string, _options, cmd) => {\n try {\n // Confirmation prompt if interactive\n if (isInteractive()) {\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await new Promise<string>((resolve) => {\n rl.question(`Delete profile \"${name}\"? This cannot be undone. [y/N] `, resolve);\n });\n rl.close();\n if (answer.toLowerCase() !== \"y\") {\n outputJson({ profile: name, deleted: false, reason: \"Cancelled by user\" });\n return;\n }\n }\n\n await ProfileManager.deleteProfile(name);\n outputJson({ profile: name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\n\nexport function registerCompletionCommand(program: Command): void {\n const completion = program.command(\"completion\").description(\"Generate shell completions\");\n\n completion\n .command(\"bash\")\n .description(\"Output bash completions\")\n .action(() => {\n const script = generateBashCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"zsh\")\n .description(\"Output zsh completions\")\n .action(() => {\n const script = generateZshCompletion();\n process.stdout.write(script);\n });\n\n completion\n .command(\"fish\")\n .description(\"Output fish completions\")\n .action(() => {\n const script = generateFishCompletion();\n process.stdout.write(script);\n });\n}\n\nfunction generateBashCompletion(): string {\n return `# tc bash completion\n_tc_completions() {\n local cur prev commands subcommands\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n\n commands=\"init auth kv space delegation share node profile completion\"\n\n case \"\\${COMP_WORDS[1]}\" in\n auth) subcommands=\"login logout status whoami\" ;;\n kv) subcommands=\"get put delete list head\" ;;\n space) subcommands=\"list create info switch\" ;;\n delegation) subcommands=\"create list info revoke\" ;;\n share) subcommands=\"create receive list revoke\" ;;\n node) subcommands=\"health version status\" ;;\n profile) subcommands=\"list create show switch delete\" ;;\n completion) subcommands=\"bash zsh fish\" ;;\n *) COMPREPLY=( $(compgen -W \"\\${commands}\" -- \"\\${cur}\") ); return ;;\n esac\n\n if [ \\${COMP_CWORD} -eq 2 ]; then\n COMPREPLY=( $(compgen -W \"\\${subcommands}\" -- \"\\${cur}\") )\n fi\n}\ncomplete -F _tc_completions tc\n`;\n}\n\nfunction generateZshCompletion(): string {\n return `#compdef tc\n\n_tc() {\n local -a commands\n commands=(\n 'init:Initialize a new TinyCloud profile'\n 'auth:Authentication management'\n 'kv:Key-value store operations'\n 'space:Space management'\n 'delegation:Manage delegations'\n 'share:Share data with others'\n 'node:Node health and info'\n 'profile:Profile management'\n 'completion:Generate shell completions'\n )\n\n _arguments -C \\\\\n '(-p --profile)'{-p,--profile}'[Profile to use]:profile:' \\\\\n '(-H --host)'{-H,--host}'[TinyCloud node URL]:url:' \\\\\n '(-v --verbose)'{-v,--verbose}'[Enable verbose output]' \\\\\n '--no-cache[Disable caching]' \\\\\n '(-q --quiet)'{-q,--quiet}'[Suppress non-essential output]' \\\\\n '1:command:->cmd' \\\\\n '*::arg:->args'\n\n case $state in\n cmd)\n _describe 'command' commands\n ;;\n args)\n case $words[1] in\n auth) _values 'subcommand' login logout status whoami ;;\n kv) _values 'subcommand' get put delete list head ;;\n space) _values 'subcommand' list create info switch ;;\n delegation) _values 'subcommand' create list info revoke ;;\n share) _values 'subcommand' create receive list revoke ;;\n node) _values 'subcommand' health version status ;;\n profile) _values 'subcommand' list create show switch delete ;;\n completion) _values 'subcommand' bash zsh fish ;;\n esac\n ;;\n esac\n}\n\n_tc\n`;\n}\n\nfunction generateFishCompletion(): string {\n return `# tc fish completion\nset -l commands init auth kv space delegation share node profile completion\n\n# Disable file completion by default\ncomplete -c tc -f\n\n# Top-level commands\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a init -d \"Initialize a new TinyCloud profile\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a auth -d \"Authentication management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a kv -d \"Key-value store operations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a space -d \"Space management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a delegation -d \"Manage delegations\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a share -d \"Share data with others\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a node -d \"Node health and info\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a profile -d \"Profile management\"\ncomplete -c tc -n \"not __fish_seen_subcommand_from $commands\" -a completion -d \"Generate shell completions\"\n\n# Subcommands\ncomplete -c tc -n \"__fish_seen_subcommand_from auth\" -a \"login logout status whoami\"\ncomplete -c tc -n \"__fish_seen_subcommand_from kv\" -a \"get put delete list head\"\ncomplete -c tc -n \"__fish_seen_subcommand_from space\" -a \"list create info switch\"\ncomplete -c tc -n \"__fish_seen_subcommand_from delegation\" -a \"create list info revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from share\" -a \"create receive list revoke\"\ncomplete -c tc -n \"__fish_seen_subcommand_from node\" -a \"health version status\"\ncomplete -c tc -n \"__fish_seen_subcommand_from profile\" -a \"list create show switch delete\"\ncomplete -c tc -n \"__fish_seen_subcommand_from completion\" -a \"bash zsh fish\"\n\n# Global options\ncomplete -c tc -l profile -s p -d \"Profile to use\"\ncomplete -c tc -l host -s H -d \"TinyCloud node URL\"\ncomplete -c tc -l verbose -s v -d \"Enable verbose output\"\ncomplete -c tc -l no-cache -d \"Disable caching\"\ncomplete -c tc -l quiet -s q -d \"Suppress non-essential output\"\n`;\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\n/**\n * Unlock the vault on a TinyCloudNode instance.\n */\nasync function unlockVault(\n node: { vault: { unlock(signer: { signMessage(message: string): Promise<string> }): Promise<any> } },\n privateKey: string,\n): Promise<void> {\n const signer = new PrivateKeySigner(privateKey);\n const result = await node.vault.unlock(signer);\n if (result && !result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n}\n\nexport function registerVaultCommand(program: Command): void {\n const vault = program.command(\"vault\").description(\"Encrypted vault operations\");\n\n // tc vault unlock\n vault\n .command(\"unlock\")\n .description(\"Verify vault unlock works\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n outputJson({ unlocked: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault put <key> [value]\n vault\n .command(\"put <key> [value]\")\n .description(\"Encrypt and store a value\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // Determine value source\n let putValue: string | Uint8Array;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n putValue = new Uint8Array(await readFile(options.file));\n } else if (options.stdin) {\n putValue = new Uint8Array(await readStdin());\n } else {\n putValue = value!;\n }\n\n const result = await withSpinner(`Writing ${key}...`, () => node.vault.put(key, putValue)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault get <key>\n vault\n .command(\"get <key>\")\n .description(\"Decrypt and retrieve a value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Getting ${key}...`, () => node.vault.get(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Key \"${key}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data ?? result.data;\n\n if (options.output) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n await writeFile(options.output, content);\n outputJson({ key, written: options.output });\n return;\n }\n\n if (options.raw) {\n const content = data instanceof Uint8Array ? Buffer.from(data) : typeof data === \"string\" ? data : JSON.stringify(data);\n process.stdout.write(content);\n return;\n }\n\n outputJson({\n key,\n data: data instanceof Uint8Array ? Buffer.from(data).toString(\"base64\") : data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault delete <key>\n vault\n .command(\"delete <key>\")\n .description(\"Delete an encrypted key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Deleting ${key}...`, () => node.vault.delete(key)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ key, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault list\n vault\n .command(\"list\")\n .description(\"List vault keys\")\n .option(\"--prefix <prefix>\", \"Filter by key prefix\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing vault keys...\", () => node.vault.list(listOptions)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const keys = result.data.data ?? result.data;\n const keyList = Array.isArray(keys) ? keys : [];\n\n outputJson({\n keys: keyList,\n count: keyList.length,\n prefix: options.prefix ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vault head <key>\n vault\n .command(\"head <key>\")\n .description(\"Get metadata for a vault key\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (key: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const result = await withSpinner(`Checking ${key}...`, () => node.vault.head(key)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n outputJson({ key, exists: false, metadata: {} });\n return;\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n key,\n exists: true,\n metadata: result.data.headers ?? result.data,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { PrivateKeySigner } from \"@tinycloud/node-sdk\";\n\nconst SECRETS_PREFIX = \"secrets/\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\n/**\n * Unlock the vault on a TinyCloudNode instance.\n */\nasync function unlockVault(\n node: { vault: { unlock(signer: { signMessage(message: string): Promise<string> }): Promise<any> } },\n privateKey: string,\n): Promise<void> {\n const signer = new PrivateKeySigner(privateKey);\n const result = await node.vault.unlock(signer);\n if (result && !result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n}\n\nexport function registerSecretsCommand(program: Command): void {\n const secrets = program.command(\"secrets\").description(\"Encrypted secrets management\");\n\n // tc secrets list\n secrets\n .command(\"list\")\n .description(\"List secrets\")\n .option(\"--space <spaceId>\", \"Space to list secrets from (for delegated access)\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // TODO: SDK-level support for targeting a specific space via vault.list().\n // The vault service currently operates on the space bound to the session.\n // When --space is provided, we would need the SDK to accept a spaceId\n // parameter on vault operations or support switching the active space.\n if (options.space) {\n throw new CLIError(\n \"NOT_IMPLEMENTED\",\n `Listing secrets from a delegated space (${options.space}) is not yet supported at the SDK level. ` +\n \"The vault service currently operates on the space bound to the active session. \" +\n \"SDK support for cross-space vault operations is planned.\",\n ExitCode.ERROR,\n );\n }\n\n const result = await withSpinner(\"Listing secrets...\", () => node.vault.list({ prefix: SECRETS_PREFIX })) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const keys = result.data.data ?? result.data;\n const keyList = Array.isArray(keys) ? keys : [];\n\n // Strip the secrets/ prefix from key names\n const secretNames = keyList.map((k: string) =>\n typeof k === \"string\" && k.startsWith(SECRETS_PREFIX) ? k.slice(SECRETS_PREFIX.length) : k\n );\n\n outputJson({\n secrets: secretNames,\n count: secretNames.length,\n ...(options.space ? { space: options.space } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets get <name>\n secrets\n .command(\"get <name>\")\n .description(\"Get a secret value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const vaultKey = `${SECRETS_PREFIX}${name}`;\n const result = await withSpinner(`Getting secret ${name}...`, () => node.vault.get(vaultKey)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Secret \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data ?? result.data;\n\n // Parse the stored payload to extract the value\n let value: string;\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data);\n value = parsed.value;\n } catch {\n value = data;\n }\n } else if (data instanceof Uint8Array) {\n try {\n const parsed = JSON.parse(Buffer.from(data).toString(\"utf-8\"));\n value = parsed.value;\n } catch {\n value = Buffer.from(data).toString(\"utf-8\");\n }\n } else {\n value = data.value ?? data;\n }\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets put <name> [value]\n secrets\n .command(\"put <name> [value]\")\n .description(\"Store a secret\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n // Determine value source\n let secretValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n secretValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n secretValue = (await readStdin()).toString(\"utf-8\");\n } else {\n secretValue = value!;\n }\n\n const payload = JSON.stringify({\n value: secretValue,\n createdAt: new Date().toISOString(),\n });\n\n const vaultKey = `${SECRETS_PREFIX}${name}`;\n const result = await withSpinner(`Storing secret ${name}...`, () => node.vault.put(vaultKey, payload)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets delete <name>\n secrets\n .command(\"delete <name>\")\n .description(\"Delete a secret\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n await withSpinner(\"Unlocking vault...\", () => unlockVault(node, privateKey));\n\n const vaultKey = `${SECRETS_PREFIX}${name}`;\n const result = await withSpinner(`Deleting secret ${name}...`, () => node.vault.delete(vaultKey)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets manage\n secrets\n .command(\"manage\")\n .description(\"Open the TinyCloud Secrets Manager in your browser\")\n .action(async () => {\n try {\n const open = (await import(\"open\")).default;\n await open(\"https://secrets.tinycloud.xyz\");\n outputJson({ opened: \"https://secrets.tinycloud.xyz\" });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile } from \"node:fs/promises\";\nimport { writeFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\n\nconst VARIABLES_PREFIX = \"variables/\";\n\n/**\n * Read all data from stdin.\n */\nasync function readStdin(): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks);\n}\n\n/**\n * Resolve private key from CLI options or environment variable.\n */\nfunction resolvePrivateKey(options: { privateKey?: string }): string {\n const key = options.privateKey || process.env.TC_PRIVATE_KEY;\n if (!key) {\n throw new CLIError(\n \"AUTH_REQUIRED\",\n \"Private key required. Use --private-key <hex> or set TC_PRIVATE_KEY env var.\",\n ExitCode.AUTH_REQUIRED,\n );\n }\n return key;\n}\n\nexport function registerVarsCommand(program: Command): void {\n const vars = program.command(\"vars\").description(\"Plaintext variable management\");\n\n // tc vars list\n vars\n .command(\"list\")\n .description(\"List variables\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(\"Listing variables...\", () => prefixedKv.list()) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const rawData = result.data.data ?? result.data;\n const keyList = Array.isArray(rawData) ? rawData : (rawData?.keys ?? []);\n\n outputJson({\n variables: keyList,\n count: keyList.length,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars get <name>\n vars\n .command(\"get <name>\")\n .description(\"Get a variable value\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Getting variable ${name}...`, () => prefixedKv.get(name)) as any;\n\n if (!result.ok) {\n if (result.error.code === \"KV_NOT_FOUND\" || result.error.code === \"NOT_FOUND\") {\n throw new CLIError(\"NOT_FOUND\", `Variable \"${name}\" not found`, ExitCode.NOT_FOUND);\n }\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const data = result.data.data;\n\n // Extract value from the stored payload\n let value: string;\n if (typeof data === \"string\") {\n try {\n const parsed = JSON.parse(data);\n value = parsed.value;\n } catch {\n value = data;\n }\n } else if (data && typeof data === \"object\" && \"value\" in data) {\n value = data.value;\n } else {\n value = typeof data === \"string\" ? data : JSON.stringify(data);\n }\n\n if (options.output) {\n await writeFile(options.output, value);\n outputJson({ name, written: options.output });\n return;\n }\n\n if (options.raw) {\n process.stdout.write(value);\n return;\n }\n\n outputJson({ name, value });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars put <name> [value]\n vars\n .command(\"put <name> [value]\")\n .description(\"Set a variable\")\n .option(\"--file <path>\", \"Read value from file\")\n .option(\"--stdin\", \"Read value from stdin\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, value: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n // Determine value source\n let varValue: string;\n const sources = [value !== undefined, !!options.file, !!options.stdin].filter(Boolean);\n\n if (sources.length === 0) {\n throw new CLIError(\"USAGE_ERROR\", \"Must provide a value, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n if (sources.length > 1) {\n throw new CLIError(\"USAGE_ERROR\", \"Provide only one of: value argument, --file, or --stdin\", ExitCode.USAGE_ERROR);\n }\n\n if (options.file) {\n varValue = (await readFile(options.file, \"utf-8\")) as string;\n } else if (options.stdin) {\n varValue = (await readStdin()).toString(\"utf-8\");\n } else {\n varValue = value!;\n }\n\n const payload = {\n value: varValue,\n createdAt: new Date().toISOString(),\n };\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Setting variable ${name}...`, () => prefixedKv.put(name, payload)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, written: true });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc vars delete <name>\n vars\n .command(\"delete <name>\")\n .description(\"Delete a variable\")\n .option(\"--private-key <hex>\", \"Ethereum private key (or set TC_PRIVATE_KEY)\")\n .action(async (name: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const privateKey = resolvePrivateKey(options);\n const node = await ensureAuthenticated(ctx, { privateKey });\n\n const prefixedKv = node.kv.withPrefix(VARIABLES_PREFIX);\n const result = await withSpinner(`Deleting variable ${name}...`, () => prefixedKv.delete(name)) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ name, deleted: true });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { DEFAULT_HOST } from \"../config/constants.js\";\nimport { outputJson, shouldOutputJson, formatCheck, formatSection } from \"../output/formatter.js\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\ninterface DoctorResult {\n checks: Array<{ name: string; ok: boolean; detail?: string }>;\n healthy: boolean;\n}\n\nexport function registerDoctorCommand(program: Command): void {\n program\n .command(\"doctor\")\n .description(\"Run diagnostic checks\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const checks: DoctorResult[\"checks\"] = [];\n\n // 1. Node.js version\n const nodeVersion = process.version;\n const nodeOk = parseInt(nodeVersion.slice(1)) >= 18;\n checks.push({ name: \"Node.js\", ok: nodeOk, detail: nodeVersion });\n\n // 2. Profile configured\n let profileName = globalOpts.profile;\n let profileOk = false;\n let profileDetail = \"\";\n try {\n const config = await ProfileManager.getConfig();\n profileName = profileName || config.defaultProfile;\n const profile = await ProfileManager.getProfile(profileName);\n profileOk = true;\n profileDetail = `\"${profileName}\" at ${profile.host}`;\n } catch {\n profileDetail = profileName ? `\"${profileName}\" not found` : \"no profiles configured\";\n }\n checks.push({ name: \"Profile\", ok: profileOk, detail: profileDetail });\n\n // 3. Key exists\n let keyOk = false;\n let keyDetail = \"\";\n if (profileOk && profileName) {\n try {\n const key = await ProfileManager.getKey(profileName);\n keyOk = key !== null;\n if (keyOk) {\n const profile = await ProfileManager.getProfile(profileName);\n keyDetail = profile.did ? `${profile.did.slice(0, 20)}...` : \"key found\";\n } else {\n keyDetail = \"no key — run tc init\";\n }\n } catch {\n keyDetail = \"error reading key\";\n }\n } else {\n keyDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Key\", ok: keyOk, detail: keyDetail });\n\n // 4. Session active\n let sessionOk = false;\n let sessionDetail = \"\";\n if (profileOk && profileName) {\n try {\n const session = await ProfileManager.getSession(profileName);\n sessionOk = session !== null;\n sessionDetail = sessionOk ? \"active\" : \"no session — run tc auth login\";\n } catch {\n sessionDetail = \"error reading session\";\n }\n } else {\n sessionDetail = \"skipped (no profile)\";\n }\n checks.push({ name: \"Session\", ok: sessionOk, detail: sessionDetail });\n\n // 5. Node reachable\n let nodeReachable = false;\n let nodeDetail = \"\";\n try {\n const host = profileOk && profileName\n ? (await ProfileManager.getProfile(profileName)).host\n : globalOpts.host || DEFAULT_HOST;\n const start = Date.now();\n const response = await fetch(`${host}/health`);\n const latency = Date.now() - start;\n nodeReachable = response.ok;\n nodeDetail = nodeReachable\n ? `${host} (${latency}ms)`\n : `${host} returned ${response.status}`;\n } catch (e) {\n nodeDetail = `unreachable — ${e instanceof Error ? e.message : \"connection failed\"}`;\n }\n checks.push({ name: \"Node\", ok: nodeReachable, detail: nodeDetail });\n\n // 6. Space exists (only if session active)\n let spaceOk = false;\n let spaceDetail = \"\";\n if (sessionOk && profileName) {\n try {\n const profile = await ProfileManager.getProfile(profileName);\n spaceOk = Boolean(profile.spaceId);\n spaceDetail = spaceOk\n ? `${profile.spaceId!.slice(0, 16)}...`\n : \"no space — run tc space create\";\n } catch {\n spaceDetail = \"error checking space\";\n }\n } else {\n spaceDetail = \"skipped (no session)\";\n }\n checks.push({ name: \"Space\", ok: spaceOk, detail: spaceDetail });\n\n const result: DoctorResult = {\n checks,\n healthy: checks.every((c) => c.ok),\n };\n\n if (shouldOutputJson()) {\n outputJson(result);\n } else {\n process.stderr.write(formatSection(\"Diagnostics\") + \"\\n\");\n for (const check of checks) {\n process.stdout.write(formatCheck(check.ok, check.name, check.detail) + \"\\n\");\n }\n process.stdout.write(\"\\n\");\n if (result.healthy) {\n process.stdout.write(theme.success(\"All checks passed.\") + \"\\n\");\n } else {\n const failed = checks.filter((c) => !c.ok).length;\n process.stdout.write(theme.warn(`${failed} check${failed > 1 ? \"s\" : \"\"} need attention.`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerSqlCommand(program: Command): void {\n const sql = program\n .command(\"sql\")\n .description(\"SQLite database operations for your TinyCloud space\")\n .addHelpText(\"after\", `\n\nTinyCloud SQL gives each space isolated SQLite databases. Use the default\ndatabase for simple apps, or pass --db to target a named database.\n\nCommon workflows:\n $ tc sql execute \"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)\"\n $ tc sql execute \"INSERT INTO notes (body) VALUES (?)\" --params '[\"ship docs\"]'\n $ tc sql query \"SELECT id, body FROM notes ORDER BY id\"\n $ tc sql query \"SELECT * FROM events WHERE type = ?\" --db analytics --params '[\"signup\"]'\n $ tc sql export --db analytics --output analytics.db\n\nCommands:\n query Read rows with SELECT statements\n execute Run writes and schema changes such as INSERT, UPDATE, DELETE, CREATE, DROP\n export Download the raw SQLite database file\n\nTips:\n - SQL strings should usually be quoted so your shell passes them as one argument.\n - --params accepts a JSON array and binds values to ? placeholders.\n - Add --json for scripting-friendly output.\n`);\n\n // tc sql query <sql>\n sql\n .command(\"query <sql>\")\n .description(\"Run a read-only SELECT query\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as a JSON array for ? placeholders\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql query \"SELECT * FROM notes ORDER BY id\"\n $ tc sql query \"SELECT * FROM notes WHERE id = ?\" --params '[42]'\n $ tc sql query \"SELECT count(*) AS total FROM events\" --db analytics --json\n\nOutput:\n Human output is formatted as a table. Piped output or --json returns\n { \"columns\": string[], \"rows\": unknown[][], \"rowCount\": number }.\n`)\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Running query...\", () =>\n node.sql.db(options.db).query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql execute <sql>\n sql\n .command(\"execute <sql>\")\n .description(\"Run a write or schema statement\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as a JSON array for ? placeholders\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql execute \"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT)\"\n $ tc sql execute \"INSERT INTO notes (body) VALUES (?)\" --params '[\"first note\"]'\n $ tc sql execute \"UPDATE notes SET body = ? WHERE id = ?\" --params '[\"edited\", 1]'\n $ tc sql execute \"DROP TABLE old_notes\" --db archive\n\nOutput:\n Returns JSON with the changed row count and last inserted row id when available.\n`)\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Executing statement...\", () =>\n node.sql.db(options.db).execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n changes: result.data.changes,\n lastInsertRowId: result.data.lastInsertRowId,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc sql export\n sql\n .command(\"export\")\n .description(\"Export a SQLite database as a binary .db file\")\n .option(\"--db <name>\", \"SQLite database name within the current space\", \"default\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.db\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql export\n $ tc sql export --db analytics --output analytics.db\n\nOutput:\n Writes the database file locally and returns JSON with the path and size.\n`)\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n node.sql.db(options.db).export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, withSpinner, shouldOutputJson, formatTable, formatBytes } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { theme } from \"../output/theme.js\";\n\nexport function registerDuckdbCommand(program: Command): void {\n const duckdb = program.command(\"duckdb\").description(\"DuckDB database operations\");\n\n // tc duckdb query <sql>\n duckdb\n .command(\"query <sql>\")\n .description(\"Run a SELECT query\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Running query...\", () =>\n node.duckdb.db(options.db).query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const { columns, rows, rowCount } = result.data;\n\n if (shouldOutputJson()) {\n outputJson({ columns, rows, rowCount });\n } else {\n if (rows.length === 0) {\n process.stdout.write(theme.muted(\"No rows returned.\") + \"\\n\");\n } else {\n const stringRows = rows.map((row: unknown[]) =>\n row.map((v: unknown) => v === null ? \"NULL\" : String(v))\n );\n process.stdout.write(formatTable(columns, stringRows) + \"\\n\");\n process.stdout.write(theme.muted(`\\n${rowCount} row${rowCount === 1 ? \"\" : \"s\"} returned`) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb execute <sql>\n duckdb\n .command(\"execute <sql>\")\n .description(\"Run INSERT/UPDATE/DELETE/DDL statement\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"--params <json>\", \"Bind parameters as JSON array\")\n .action(async (sqlStr: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const params = options.params ? JSON.parse(options.params) : undefined;\n\n const result = await withSpinner(\"Executing statement...\", () =>\n node.duckdb.db(options.db).execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({ changes: result.data.changes });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb describe\n duckdb\n .command(\"describe\")\n .description(\"Show database schema (tables, columns, views)\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Describing schema...\", () =>\n node.duckdb.db(options.db).describe()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const schema = result.data;\n\n if (shouldOutputJson()) {\n outputJson(schema);\n } else {\n const { tables, views } = schema;\n\n if (tables.length === 0 && views.length === 0) {\n process.stdout.write(theme.muted(\"No tables or views found.\") + \"\\n\");\n return;\n }\n\n if (tables.length > 0) {\n process.stdout.write(theme.label(\"Tables:\") + \"\\n\\n\");\n for (const table of tables) {\n process.stdout.write(` ${theme.value(table.name)}\\n`);\n const colRows = table.columns.map((col: any) => [\n col.name,\n col.type,\n col.nullable ? \"YES\" : \"NO\",\n ]);\n const colTable = formatTable([\"Column\", \"Type\", \"Nullable\"], colRows);\n process.stdout.write(colTable.split(\"\\n\").map((l: string) => \" \" + l).join(\"\\n\") + \"\\n\\n\");\n }\n }\n\n if (views.length > 0) {\n process.stdout.write(theme.label(\"Views:\") + \"\\n\\n\");\n const viewRows = views.map((v: any) => [v.name, v.sql]);\n process.stdout.write(formatTable([\"View\", \"SQL\"], viewRows) + \"\\n\");\n }\n }\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb export\n duckdb\n .command(\"export\")\n .description(\"Export database as binary file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .option(\"-o, --output <file>\", \"Output file path\", \"export.duckdb\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n node.duckdb.db(options.db).export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const blob: Blob = result.data;\n const buffer = Buffer.from(await blob.arrayBuffer());\n const outputPath = resolve(options.output);\n await writeFile(outputPath, buffer);\n\n outputJson({\n file: outputPath,\n size: blob.size,\n sizeHuman: formatBytes(blob.size),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc duckdb import <file>\n duckdb\n .command(\"import <file>\")\n .description(\"Import a DuckDB database file\")\n .option(\"--db <name>\", \"Database name\", \"default\")\n .action(async (file: string, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx);\n\n const filePath = resolve(file);\n const bytes = new Uint8Array(await readFile(filePath));\n\n const result = await withSpinner(\"Importing database...\", () =>\n node.duckdb.db(options.db).import(bytes)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n outputJson({\n file: filePath,\n size: bytes.byteLength,\n sizeHuman: formatBytes(bytes.byteLength),\n imported: true,\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n","import { Command } from \"commander\";\nimport { execSync } from \"child_process\";\nimport { readFileSync } from \"fs\";\nimport { theme } from \"../output/theme.js\";\nimport { handleError } from \"../output/errors.js\";\n\nconst PACKAGE_NAME = \"@tinycloud/cli\";\n\nfunction getCurrentVersion(): string {\n const pkg = JSON.parse(\n readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\")\n );\n return pkg.version;\n}\n\nasync function getLatestVersion(): Promise<string> {\n const res = await fetch(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`);\n if (!res.ok) {\n throw new Error(`Failed to fetch latest version: ${res.status} ${res.statusText}`);\n }\n const data = (await res.json()) as { version: string };\n return data.version;\n}\n\nfunction detectPackageManager(): \"bun\" | \"npm\" {\n // Check if bun installed the package globally\n try {\n const bunGlobals = execSync(\"bun pm ls -g\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (bunGlobals.includes(PACKAGE_NAME)) {\n return \"bun\";\n }\n } catch {\n // bun not available or failed\n }\n\n // Check if npm installed the package globally\n try {\n const npmGlobals = execSync(\"npm ls -g --depth=0\", { encoding: \"utf-8\", stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n if (npmGlobals.includes(PACKAGE_NAME)) {\n return \"npm\";\n }\n } catch {\n // npm not available or failed\n }\n\n // Fallback to bun since the CLI shebang uses it\n return \"bun\";\n}\n\nexport function registerUpgradeCommand(program: Command): void {\n program\n .command(\"upgrade\")\n .description(\"Upgrade the TinyCloud CLI to the latest version\")\n .action(async () => {\n try {\n const current = getCurrentVersion();\n\n process.stderr.write(theme.muted(\"Checking for updates...\") + \"\\n\");\n const latest = await getLatestVersion();\n\n if (current === latest) {\n process.stdout.write(theme.success(`Already on latest version (${current})`) + \"\\n\");\n return;\n }\n\n process.stdout.write(`Current: ${theme.warn(current)} → Latest: ${theme.success(latest)}\\n`);\n\n const pm = detectPackageManager();\n const cmd = pm === \"bun\"\n ? `bun install -g ${PACKAGE_NAME}@latest`\n : `npm install -g ${PACKAGE_NAME}@latest`;\n\n process.stderr.write(theme.muted(`Upgrading via ${pm}...`) + \"\\n\\n\");\n\n try {\n execSync(cmd, { stdio: \"inherit\" });\n process.stdout.write(\"\\n\" + theme.success(`Upgraded to ${latest}`) + \"\\n\");\n } catch {\n process.stderr.write(\"\\n\" + theme.warn(\"Automatic upgrade failed.\") + \"\\n\");\n process.stderr.write(theme.muted(\"Try running manually:\") + \"\\n\");\n process.stderr.write(` ${theme.command(`bun install -g ${PACKAGE_NAME}@latest`)}\\n`);\n process.stderr.write(theme.muted(\" or\") + \"\\n\");\n process.stderr.write(` ${theme.command(`npm install -g ${PACKAGE_NAME}@latest`)}\\n`);\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAS,eAAe;;;ACDxB,SAAS,eAAe;AACxB,SAAS,YAAY;AAEd,IAAM,aAAa,KAAK,QAAQ,GAAG,YAAY;AAC/C,IAAM,eAAe,KAAK,YAAY,UAAU;AAChD,IAAM,cAAc,KAAK,YAAY,aAAa;AAElD,IAAM,eAAe;AACrB,IAAM,kBAAkB;AACxB,IAAM,mBAAmB;AAEzB,IAAM,WAAW;AAAA,EACtB,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,WAAW;AAAA,EACX,mBAAmB;AAAA,EACnB,eAA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,WAAW,QAAQ,IAAI;AACvC,SAAS,OAAO;AACd,cAAY,KAAK;AACnB;","names":["readFileSync","version","join","rm","join","rm","TinyCloudNode","resolve","program","createInterface","createInterface","resolve","program","readFile","writeFile","node","program","writeFile","readFile","program","program","program","program","createInterface","program","createInterface","resolve","program","readFile","writeFile","PrivateKeySigner","readStdin","program","readFile","writeFile","readFile","writeFile","PrivateKeySigner","readStdin","resolvePrivateKey","unlockVault","program","writeFile","readFile","readFile","writeFile","readStdin","resolvePrivateKey","program","writeFile","readFile","program","writeFile","program","writeFile","readFile","writeFile","resolve","program","resolve","writeFile","readFile","execSync","execSync","program","readFileSync"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinycloud/cli",
3
- "version": "0.4.7-beta.4",
3
+ "version": "0.4.7-beta.6",
4
4
  "description": "TinyCloud CLI - manage data, delegations, and nodes from the terminal",
5
5
  "author": "TinyCloud, Inc.",
6
6
  "license": "EGPL",
@@ -23,7 +23,7 @@
23
23
  "dev": "tsup --watch"
24
24
  },
25
25
  "dependencies": {
26
- "@tinycloud/node-sdk": "2.1.0-beta.4",
26
+ "@tinycloud/node-sdk": "2.1.0-beta.5",
27
27
  "@tinycloud/node-sdk-wasm": "1.7.2-beta.2",
28
28
  "chalk": "^5.3.0",
29
29
  "commander": "^14.0.0",