@tinycloud/cli 0.6.0 → 0.7.0-beta.1

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/output/errors.ts","../src/config/constants.ts","../src/output/formatter.ts","../src/output/theme.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/config/types.ts","../src/lib/sdk.ts","../src/lib/permissions.ts","../src/lib/space.ts","../src/commands/kv.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/manifest.ts","../src/commands/upgrade.ts","../src/commands/status.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 { registerManifestCommand } from \"./commands/manifest.js\";\nimport { registerUpgradeCommand } from \"./commands/upgrade.js\";\nimport { registerStatusCommand } from \"./commands/status.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\", \"status\"].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);\nregisterManifestCommand(program);\nregisterUpgradeCommand(program);\nregisterStatusCommand(program);\n\nprogram.addHelpText(\"before\", () => `${theme.label(\"Version:\")} ${theme.value(version)}\\n`);\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 secrets network init\")} ${theme.muted(\"Create the default secrets network\")}\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 { readFileSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { ExitCode, CONFIG_FILE, PROFILES_DIR, DEFAULT_PROFILE } from \"../config/constants.js\";\nimport { outputError } from \"./formatter.js\";\n\nlet activeProfileName: string | undefined;\n\n/** Recorded by ProfileManager.resolveContext so hints can name the right profile. */\nexport function setActiveProfileName(name: string): void {\n activeProfileName = name;\n}\n\nexport class CLIError extends Error {\n constructor(\n public code: string,\n message: string,\n public exitCode: number = ExitCode.ERROR,\n public metadata?: Record<string, unknown>,\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 const hint = buildAuthHint(cliError) ??\n (cliError.code === \"NETWORK_ERROR\" ? buildNetworkHint() : undefined);\n outputError(cliError.code, cliError.message, hint);\n process.exit(cliError.exitCode);\n}\n\nfunction buildAuthHint(error: CLIError): string | undefined {\n const resource = error.metadata?.resource;\n const requiredAction = error.metadata?.requiredAction;\n if (typeof resource !== \"string\" || typeof requiredAction !== \"string\") {\n return undefined;\n }\n\n const spec = capSpecFromAuthMeta(resource, requiredAction);\n if (!spec) return undefined;\n return [\n \"The active session is missing a TinyCloud capability.\",\n `Request it with: tc auth request --cap \"${spec}\"`,\n \"Then retry the original command.\",\n ].join(\"\\n\");\n}\n\nfunction capSpecFromAuthMeta(resource: string, action: string): string | undefined {\n const slash = resource.indexOf(\"/\");\n if (slash <= 0 || slash === resource.length - 1) return undefined;\n const spaceUri = resource.slice(0, slash);\n const rest = resource.slice(slash + 1);\n const nextSlash = rest.indexOf(\"/\");\n if (nextSlash <= 0) return undefined;\n\n const serviceShort = rest.slice(0, nextSlash);\n const path = rest.slice(nextSlash + 1);\n const actionName = action.includes(\"/\") ? action.slice(action.indexOf(\"/\") + 1) : action;\n const spaceName = spaceUri.startsWith(\"tinycloud:\")\n ? spaceUri.slice(spaceUri.lastIndexOf(\":\") + 1)\n : spaceUri;\n return `tinycloud.${serviceShort}:${spaceName}:${path}:${actionName}`;\n}\n\n/**\n * Suggests alternate profiles when the active profile's host is unreachable.\n * Sync fs reads keep handleError synchronous so call sites don't need to await.\n *\n * Silent fallback to a default host is intentionally NOT done: different hosts\n * back different data stores, so an automatic switch could split or clobber\n * user data without their knowledge.\n */\nfunction buildNetworkHint(): string | undefined {\n const readHost = (name: string): string | undefined => {\n try {\n const raw = readFileSync(join(PROFILES_DIR, name, \"profile.json\"), \"utf8\");\n return (JSON.parse(raw) as { host?: string }).host;\n } catch {\n return undefined;\n }\n };\n\n let activeName = activeProfileName ?? process.env.TC_PROFILE ?? DEFAULT_PROFILE;\n if (!activeProfileName) {\n try {\n const cfg = JSON.parse(readFileSync(CONFIG_FILE, \"utf8\")) as { defaultProfile?: string };\n activeName = process.env.TC_PROFILE ?? cfg.defaultProfile ?? DEFAULT_PROFILE;\n } catch {\n // Config file not present yet — fall through with env/default.\n }\n }\n\n let names: string[];\n try {\n names = readdirSync(PROFILES_DIR);\n } catch {\n return undefined;\n }\n\n const activeHost = readHost(activeName);\n const others = names\n .filter((n) => n !== activeName)\n .map((n) => ({ name: n, host: readHost(n) }))\n .filter((p): p is { name: string; host: string } => Boolean(p.host));\n\n const lines: string[] = [];\n lines.push(activeHost ? `Active profile \"${activeName}\" → ${activeHost}` : `Active profile \"${activeName}\"`);\n\n if (others.length === 0) {\n lines.push(`No other profiles configured. Run \\`tc profile create <name>\\` or \\`tc init\\`.`);\n } else {\n lines.push(`Switch to a reachable profile:`);\n const longest = Math.max(...others.map((p) => p.name.length));\n for (const { name, host } of others) {\n lines.push(` tc profile switch ${name.padEnd(longest)} # ${host}`);\n }\n }\n lines.push(`Or override per-command with --host or TC_HOST.`);\n return lines.join(\"\\n\");\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_OPENKEY_HOST = \"https://openkey.so\";\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, hint?: string): void {\n if (isInteractive()) {\n process.stderr.write(\n `${theme.error(\"✗\")} ${theme.label(code)}: ${message}\\n`\n );\n if (hint) {\n for (const line of hint.split(\"\\n\")) {\n process.stderr.write(` ${theme.hint(line)}\\n`);\n }\n }\n } else {\n const payload: { error: { code: string; message: string; hint?: string } } = {\n error: { code, message },\n };\n if (hint) payload.error.hint = hint;\n process.stderr.write(JSON.stringify(payload, null, 2) + \"\\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","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, setActiveProfileName } 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 setActiveProfileName(profile);\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, importKey, initPanicHook } from \"@tinycloud/node-sdk-wasm\";\nimport { PrivateKeySigner, pkhDid } 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 const keyId = importKey(mgr, JSON.stringify(jwk), \"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 pkhDid(address, chainId);\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 delegationHeader: { Authorization: string };\n delegationCid: string;\n jwk: object;\n verificationMethod: string;\n siwe?: string;\n signature?: string;\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 const session = node.session;\n if (!session) {\n throw new Error(\"Local key sign-in did not produce a TinyCloud session\");\n }\n\n return {\n spaceId: session.spaceId,\n address,\n chainId: 1,\n delegationHeader: session.delegationHeader,\n delegationCid: session.delegationCid,\n jwk: session.jwk,\n verificationMethod: session.verificationMethod,\n siwe: session.siwe,\n signature: session.signature,\n };\n}\n","import type { PermissionEntry } from \"@tinycloud/node-sdk\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { isInteractive } from \"../output/formatter.js\";\nimport { createInterface } from \"node:readline\";\nimport { DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\n\ninterface DelegationData {\n delegationHeader: { Authorization: string };\n delegationCid: string;\n spaceId: string;\n [key: string]: unknown;\n}\n\ninterface AuthFlowOptions {\n paste?: boolean;\n noPopup?: boolean;\n jwk?: object;\n host?: string;\n permissions?: PermissionEntry[];\n /**\n * OpenKey base URL. Resolution order in callers: TC_OPENKEY_HOST env →\n * profile.openkeyHost → DEFAULT_OPENKEY_HOST. Threaded explicitly so this\n * module stays free of profile lookups.\n */\n openkeyHost?: string;\n /**\n * Lifetime hint for the resulting delegation. Encoded into the\n * `/delegate?expiry=<value>` URL parameter so OpenKey can sign for the\n * requested window instead of its hardcoded default. Forwarded as-is —\n * OpenKey does the parsing and clamping server-side.\n */\n expiry?: string | number;\n}\n\nconst PRIVATE_JWK_FIELDS = new Set([\n \"d\",\n \"p\",\n \"q\",\n \"dp\",\n \"dq\",\n \"qi\",\n \"oth\",\n \"k\",\n]);\n\nexport function publicJwkForDelegation(jwk: object): object {\n const publicJwk: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(jwk)) {\n if (!PRIVATE_JWK_FIELDS.has(key)) {\n publicJwk[key] = value;\n }\n }\n\n return publicJwk;\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: AuthFlowOptions = {}\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\nexport function buildAuthUrl(did: string, options: AuthFlowOptions & { 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(\n JSON.stringify(publicJwkForDelegation(options.jwk)),\n ).toString(\"base64url\");\n params.set(\"jwk\", jwkB64);\n }\n if (options.host) {\n params.set(\"host\", options.host);\n }\n if (options.permissions?.length) {\n params.set(\n \"permissions\",\n Buffer.from(JSON.stringify({ permissions: options.permissions })).toString(\"base64url\"),\n );\n }\n if (options.expiry !== undefined) {\n params.set(\"expiry\", String(options.expiry));\n }\n const base = options.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n return `${base}/delegate?${params.toString()}`;\n}\n\nfunction shouldOpenBrowser(options: AuthFlowOptions): boolean {\n if (options.noPopup) return false;\n const env = process.env.TC_AUTH_NO_POPUP ?? process.env.TC_NO_POPUP;\n return env !== \"1\" && env !== \"true\";\n}\n\nasync function callbackFlow(did: string, options: AuthFlowOptions = {}): 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 const openBrowser = shouldOpenBrowser(options);\n\n if (openBrowser && isInteractive()) {\n console.error(`Opening browser for authentication...`);\n console.error(`If the browser doesn't open, visit: ${authUrl}`);\n } else if (!openBrowser || isInteractive()) {\n console.error(`Open this URL in a browser to authenticate: ${authUrl}`);\n }\n\n if (openBrowser) {\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\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: AuthFlowOptions = {}): 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 .option(\"--no-popup\", \"Print the OpenKey URL without opening a browser\")\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 noPopup: options.popup === false,\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 ownerDid: delegationData.ownerDid 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 { get as httpGet } from \"node:http\";\nimport { get as httpsGet } from \"node:https\";\nimport { spawn } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { IncomingMessage } from \"node:http\";\nimport type { PermissionEntry, PortableDelegation } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatField, formatTable, isInteractive, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_CHAIN_ID, DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type AuthMethod,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Resolve the OpenKey base URL for a profile.\n * Order: TC_OPENKEY_HOST env override → profile.openkeyHost → default.\n *\n * No prompts, no migration. To use a self-hosted OpenKey for a profile,\n * edit `~/.tinycloud/profiles/<profile>/profile.json` and add an\n * \"openkeyHost\": \"https://openkey.localhost\" field.\n */\nfunction resolveOpenKeyHost(profile: ProfileConfig): string {\n return process.env.TC_OPENKEY_HOST ?? profile.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n}\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\nimport {\n generateLocalIdentity,\n deriveAddress,\n addressToDID,\n localKeySignIn,\n generateKey,\n keyToDID,\n} from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport {\n appendAdditionalDelegation,\n appendPermissionRequestArtifact,\n createPermissionRequestArtifact,\n getLastPermissionRequestArtifact,\n getPermissionRequestArtifact,\n isDelegationImportArtifact,\n isPermissionRequestArtifact,\n appendGrantHistory,\n compactPermission,\n loadAdditionalDelegations,\n loadManifestPermissions,\n loadPermissionRequest,\n parseCapSpec,\n permissionsFromDelegation,\n readGrantHistory,\n storedAdditionalDelegation,\n type PermissionRequestArtifact,\n} from \"../lib/permissions.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(\"--no-popup\", \"Print the OpenKey URL without opening a browser\")\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, {\n paste: options.paste,\n noPopup: options.popup === false,\n });\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(\"rotate\")\n .description(\"Rotate the active profile session key\")\n .option(\"--paste\", \"Use manual paste mode instead of browser callback\")\n .option(\"--no-popup\", \"Print the OpenKey URL without opening a browser\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n await rotateAuthKey(ctx.profile, ctx.host, {\n paste: options.paste,\n noPopup: options.popup === false,\n });\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 const posture = profile ? resolveProfilePosture(profile) : null;\n const operatorType = profile ? resolveProfileOperatorType(profile) : null;\n\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n authenticated,\n did: profile?.did ?? null,\n sessionDid: profile?.sessionDid ?? null,\n ownerDid: profile?.ownerDid ?? null,\n spaceId: profile?.spaceId ?? null,\n host: ctx.host,\n profile: ctx.profile,\n hasKey: hasKey !== null,\n authMethod: profile?.authMethod ?? null,\n posture,\n operatorType,\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(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\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(\"Session DID\", profile?.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile?.ownerDid ?? 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(\"request\")\n .description(\"Create a TinyCloud permission request artifact\")\n .option(\n \"--cap <spec>\",\n \"Capability spec: tinycloud.<service>:<space>:<path>:<actions-csv> (repeatable)\",\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\"--permission <file>\", \"JSON permission request: { \\\"permissions\\\": PermissionEntry[] }\")\n .option(\"--manifest <fileOrBase64>\", \"Manifest file, base64:<json>, or raw base64 JSON\")\n .option(\n \"--expiry <duration>\",\n \"Lifetime of the granted delegation. ms-format string (e.g. \\\"7d\\\", \\\"30m\\\") or raw milliseconds. Defaults to 7d, capped by the active session's expiry.\",\n )\n .option(\"--emit [file]\", \"Emit the request artifact to stdout, or write it to file when provided\")\n .option(\"--grant\", \"Grant the requested permissions immediately with this owner profile\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .option(\"--no-popup\", \"Print the OpenKey URL without opening a browser when granting with OpenKey\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const requested = await collectRequestedPermissions(options, ctx.profile);\n const expiryOption = parseExpiryOption(options.expiry);\n\n if (requested.length === 0) {\n throw new CLIError(\n \"NO_CAPS_REQUESTED\",\n \"Provide at least one --cap, --permission, or --manifest.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (!options.grant) {\n const artifact = createPermissionRequestArtifact({\n profileName: ctx.profile,\n profile,\n host: ctx.host,\n requested,\n requestedExpiry: expiryOption,\n });\n await appendPermissionRequestArtifact(ctx.profile, artifact);\n await emitPermissionRequestArtifact(artifact, options.emit);\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n\n // Fast path: master's grantRuntimePermissions / hasRuntimePermissions\n // already does the diff against the live session + existing runtime\n // grants; no need to compute it ourselves.\n if (node.hasRuntimePermissions(requested)) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n if (profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(ctx.profile);\n if (!key) {\n throw new CLIError(\"NO_KEY\", `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`, ExitCode.AUTH_REQUIRED);\n }\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n const openkeyHost = resolveOpenKeyHost(profile);\n for (const group of groupPermissionsBySpace(requested)) {\n const delegationData = await startAuthFlow(profile.did, {\n jwk: key,\n host: ctx.host,\n permissions: group,\n openkeyHost,\n expiry: expiryOption,\n noPopup: options.popup === false,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, ctx.host);\n const stored = storedAdditionalDelegation(delegation, group);\n await appendAdditionalDelegation(ctx.profile, stored);\n await node.useRuntimeDelegation(delegation);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: group,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n outputJson({\n changed: delegationCids.length > 0,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n return;\n }\n\n if (isInteractive()) {\n if (!options.yes) {\n await confirmPermissionRequest(requested);\n }\n } else if (!options.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key permission requests in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n // Local-key flow: master's grantRuntimePermissions handles signing\n // through the SDK's wallet-mode signer, groups by space, and skips\n // anything already covered by the session or an existing grant.\n const delegations = await node.grantRuntimePermissions(\n requested,\n expiryOption !== undefined ? { expiry: expiryOption } : undefined,\n );\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n const stored = storedAdditionalDelegation(delegation, covering);\n await appendAdditionalDelegation(ctx.profile, stored);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: covering,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n\n if (delegationCids.length === 0) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n outputJson({\n changed: true,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"import [source]\")\n .description(\"Import a TinyCloud delegation or permission request artifact\")\n .option(\"--stdin\", \"Read the JSON artifact from stdin\")\n .option(\"--paste\", \"Read the JSON artifact from stdin\")\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (isPermissionRequestArtifact(parsed)) {\n await appendPermissionRequestArtifact(ctx.profile, parsed);\n outputJson({\n imported: true,\n kind: parsed.kind,\n requestId: parsed.requestId,\n requested: parsed.requested,\n next: `tc auth retry ${parsed.requestId}`,\n });\n return;\n }\n\n const imported = normalizeDelegationImport(parsed);\n const node = await ensureAuthenticated(ctx);\n await appendAdditionalDelegation(ctx.profile, storedAdditionalDelegation(\n imported.delegation,\n imported.permissions,\n ));\n await node.useRuntimeDelegation(imported.delegation);\n await appendGrantHistory(ctx.profile, {\n addedCaps: imported.permissions,\n source: \"cli\",\n delegationCid: imported.delegation.cid,\n expiry: imported.delegation.expiry.toISOString(),\n });\n\n outputJson({\n imported: true,\n kind: \"tinycloud.auth.delegation\",\n requestId: imported.requestId ?? null,\n delegationCid: imported.delegation.cid,\n permissions: imported.permissions,\n expiry: imported.delegation.expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"grant [request]\")\n .description(\"Grant a TinyCloud permission request artifact to its requester\")\n .option(\"--stdin\", \"Read the JSON request artifact from stdin\")\n .option(\"--paste\", \"Read the JSON request artifact from stdin\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (!isPermissionRequestArtifact(parsed)) {\n throw new CLIError(\n \"INVALID_AUTH_REQUEST\",\n \"Auth grant requires a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n await ensureDelegationAuthority({\n ctx,\n profile,\n node,\n requested: parsed.requested,\n expiryOption: parsed.requestedExpiry,\n yes: options.yes === true,\n });\n const result = await node.delegateTo(\n parsed.sessionDid,\n parsed.requested,\n parsed.requestedExpiry !== undefined\n ? { expiry: parsed.requestedExpiry }\n : undefined,\n );\n\n outputJson({\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: parsed.requestId,\n delegationCid: result.delegation.cid,\n delegation: result.delegation,\n permissions: parsed.requested,\n expiry: result.delegation.expiry.toISOString(),\n prompted: result.prompted,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"retry [requestId]\")\n .description(\"Check whether a stored permission request is now satisfied\")\n .option(\"--last\", \"Use the latest stored permission request for this profile\")\n .option(\"--exec\", \"Run the captured command when the request is covered\")\n .action(async (requestId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const artifact = options.last\n ? await getLastPermissionRequestArtifact(ctx.profile)\n : requestId\n ? await getPermissionRequestArtifact(ctx.profile, requestId)\n : null;\n\n if (!artifact) {\n throw new CLIError(\n \"REQUEST_NOT_FOUND\",\n options.last\n ? `No stored permission requests exist for profile \"${ctx.profile}\".`\n : \"Provide a requestId or use --last.\",\n ExitCode.NOT_FOUND,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n const covered = node.hasRuntimePermissions(artifact.requested);\n if (options.exec) {\n if (!covered) {\n throw new CLIError(\n \"PERMISSIONS_MISSING\",\n `Request ${artifact.requestId} is not covered yet. Import a delegation, then retry with --exec.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n if (!artifact.command?.argv?.length) {\n throw new CLIError(\n \"COMMAND_NOT_CAPTURED\",\n `Request ${artifact.requestId} does not include a captured command.`,\n ExitCode.USAGE_ERROR,\n );\n }\n await execCapturedCommand(artifact.command);\n return;\n }\n\n outputJson({\n requestId: artifact.requestId,\n covered,\n missing: covered ? [] : artifact.requested,\n command: artifact.command ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"caps\")\n .description(\"Show granted capabilities for the active session\")\n .option(\"--diff <spec>\", \"Show missing capabilities for a spec\")\n .option(\"--history\", \"Show recent permission grants\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n if (options.history) {\n const history = (await readGrantHistory(ctx.profile)).slice(-20);\n if (shouldOutputJson()) {\n outputJson({ grants: history });\n } else if (history.length === 0) {\n process.stdout.write(theme.muted(\"No grant history.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"time\", \"source\", \"delegation\", \"caps\"],\n history.map((entry) => [\n entry.ts,\n entry.source,\n entry.delegationCid ?? \"\",\n entry.addedCaps.map(compactPermission).join(\"; \"),\n ]),\n ) + \"\\n\");\n }\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n const runtimeDelegations = node.getRuntimePermissionDelegations();\n // Granted view = permissions covered by appended runtime delegations.\n // The base-session SIWE recap isn't enumerated here because the\n // node-sdk doesn't expose it as a list — `hasRuntimePermissions()`\n // is the trusted answer for \"is this covered?\".\n const granted = runtimeDelegations.flatMap(permissionsFromDelegation);\n\n if (options.diff) {\n const requested = [await parseCapSpec(options.diff, ctx.profile)];\n const covered = node.hasRuntimePermissions(requested);\n outputJson({\n requested,\n changed: !covered,\n covered,\n // `missing` retained for backwards-compatible callers.\n missing: covered ? [] : requested,\n });\n return;\n }\n\n const appended = await loadAdditionalDelegations(ctx.profile);\n if (shouldOutputJson()) {\n outputJson({ granted, appendedDelegations: appended.length });\n } else if (granted.length === 0) {\n process.stdout.write(theme.muted(\"No appended runtime delegations on this profile.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"service\", \"space\", \"path\", \"actions\"],\n granted.map((entry) => [\n entry.service,\n entry.space,\n entry.path,\n entry.actions.join(\", \"),\n ]),\n ) + \"\\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 const posture = resolveProfilePosture(profile);\n const operatorType = resolveProfileOperatorType(profile);\n\n if (shouldOutputJson()) {\n outputJson({\n profile: ctx.profile,\n did: profile.did,\n sessionDid: profile.sessionDid ?? null,\n ownerDid: profile.ownerDid ?? null,\n spaceId: profile.spaceId ?? null,\n host: profile.host,\n authenticated,\n authMethod: profile.authMethod ?? null,\n posture,\n operatorType,\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(\"Session DID\", profile.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile.ownerDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\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\nasync function emitPermissionRequestArtifact(\n artifact: PermissionRequestArtifact,\n emitOption: unknown,\n): Promise<void> {\n if (typeof emitOption === \"string\" && emitOption.length > 0) {\n await mkdir(dirname(emitOption), { recursive: true });\n await writeFile(emitOption, JSON.stringify(artifact, null, 2) + \"\\n\", \"utf8\");\n outputJson({\n emitted: true,\n path: emitOption,\n requestId: artifact.requestId,\n requested: artifact.requested,\n });\n return;\n }\n outputJson(artifact);\n}\n\nasync function readAuthArtifactSource(\n source: string | undefined,\n options: { stdin: boolean },\n): Promise<string> {\n if (options.stdin || source === \"-\" || (!source && !isInteractive())) {\n return readStdin();\n }\n\n if (!source) {\n throw new CLIError(\n \"IMPORT_SOURCE_REQUIRED\",\n \"Provide an artifact file, URL, or use --stdin.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (source.startsWith(\"http://\") || source.startsWith(\"https://\")) {\n return readUrl(source);\n }\n\n return readFile(source, \"utf8\");\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction readUrl(source: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const getter = source.startsWith(\"https://\") ? httpsGet : httpGet;\n const request = getter(source, (response: IncomingMessage) => {\n const status = response.statusCode ?? 0;\n if (status >= 300 && status < 400 && response.headers.location) {\n response.resume();\n readUrl(new URL(response.headers.location, source).toString()).then(resolve, reject);\n return;\n }\n if (status < 200 || status >= 300) {\n response.resume();\n reject(new CLIError(\n \"IMPORT_FETCH_FAILED\",\n `Failed to fetch ${source}: HTTP ${status}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n\n const chunks: Buffer[] = [];\n response.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n response.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n });\n request.on(\"error\", reject);\n });\n}\n\nfunction normalizeDelegationImport(value: unknown): {\n requestId?: string;\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n} {\n if (isDelegationImportArtifact(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n requestId: value.requestId,\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isStoredDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isPortableDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value);\n return {\n delegation,\n permissions: permissionsFromDelegation(delegation),\n };\n }\n\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Auth import must be a tinycloud.auth.delegation artifact, a portable delegation, or a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction isStoredDelegationLike(value: unknown): value is {\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n} {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as { delegation?: unknown };\n return isPortableDelegationLike(candidate.delegation);\n}\n\nfunction isPortableDelegationLike(value: unknown): value is PortableDelegation {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PortableDelegation>;\n return (\n typeof candidate.cid === \"string\" &&\n typeof candidate.spaceId === \"string\" &&\n typeof candidate.path === \"string\" &&\n Array.isArray(candidate.actions) &&\n candidate.delegationHeader !== undefined &&\n typeof candidate.delegationHeader === \"object\"\n );\n}\n\nfunction normalizePortableDelegation(delegation: PortableDelegation): PortableDelegation {\n const rawExpiry = (delegation as PortableDelegation & { expiry: unknown }).expiry;\n const expiry = rawExpiry instanceof Date ? rawExpiry : new Date(String(rawExpiry));\n if (Number.isNaN(expiry.getTime())) {\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Imported delegation must include a valid expiry.\",\n ExitCode.USAGE_ERROR,\n );\n }\n return { ...delegation, expiry };\n}\n\nexport async function ensureDelegationAuthority(params: {\n ctx: { profile: string; host: string };\n profile: ProfileConfig;\n node: Awaited<ReturnType<typeof ensureAuthenticated>>;\n requested: PermissionEntry[];\n expiryOption: string | number | undefined;\n yes: boolean;\n force?: boolean;\n}): Promise<void> {\n if (!params.force && params.node.hasRuntimePermissions(params.requested)) return;\n\n if (params.profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(params.ctx.profile);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${params.ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n const openkeyHost = resolveOpenKeyHost(params.profile);\n for (const group of groupPermissionsBySpace(params.requested)) {\n const delegationData = await startAuthFlow(params.profile.did, {\n jwk: key,\n host: params.ctx.host,\n permissions: group,\n openkeyHost,\n expiry: params.expiryOption,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, params.ctx.host);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, group),\n );\n await params.node.useRuntimeDelegation(delegation);\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: group,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n return;\n }\n\n if (isInteractive()) {\n if (!params.yes) {\n await confirmPermissionRequest(params.requested);\n }\n } else if (!params.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key auth grants in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const delegations = await params.node.grantRuntimePermissions(\n params.requested,\n params.expiryOption !== undefined ? { expiry: params.expiryOption } : undefined,\n );\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, covering),\n );\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: covering,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n}\n\nfunction execCapturedCommand(command: { argv: string[]; cwd: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [process.argv[1], ...command.argv], {\n cwd: command.cwd,\n env: process.env,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code, signal) => {\n if (signal) {\n reject(new CLIError(\n \"COMMAND_SIGNAL\",\n `Captured command exited from signal ${signal}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n if (code && code !== 0) {\n process.exitCode = code;\n }\n resolve();\n });\n });\n}\n\nasync function collectRequestedPermissions(\n options: {\n cap?: string[];\n permission?: string;\n manifest?: string;\n },\n profile: string,\n): Promise<PermissionEntry[]> {\n const permissions: PermissionEntry[] = [];\n for (const spec of options.cap ?? []) {\n permissions.push(await parseCapSpec(spec, profile));\n }\n if (options.permission) {\n permissions.push(...await loadPermissionRequest(options.permission, profile));\n }\n if (options.manifest) {\n permissions.push(...await loadManifestPermissions(options.manifest, profile));\n }\n return permissions;\n}\n\nasync function confirmPermissionRequest(permissions: PermissionEntry[]): Promise<void> {\n process.stderr.write(\"\\n\" + theme.heading(\"Additional Permissions\") + \"\\n\");\n for (const permission of permissions) {\n const dangerous = isDangerousPermission(permission);\n const line = ` ${compactPermission(permission)}`;\n process.stderr.write((dangerous ? theme.warn(line) : theme.value(line)) + \"\\n\");\n }\n process.stderr.write(\"\\n\");\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Approve local-key delegation? [y/N] \", resolve);\n });\n rl.close();\n\n if (!/^y(es)?$/i.test(answer.trim())) {\n throw new CLIError(\"REQUEST_CANCELLED\", \"Permission request cancelled.\", ExitCode.ERROR);\n }\n}\n\nfunction isDangerousPermission(permission: PermissionEntry): boolean {\n if (permission.path === \"\" || permission.path === \"/\") return true;\n return permission.actions.some((action) =>\n action.includes(\"*\") ||\n action.endsWith(\"/write\") ||\n action.endsWith(\"/admin\") ||\n action.endsWith(\"/ddl\") ||\n action.endsWith(\"/del\"),\n );\n}\n\n/**\n * Parse the `--expiry` flag into either a ms-format string (\"7d\", \"30m\") or\n * raw milliseconds. Returns undefined for missing input so the caller falls\n * back to the SDK's DEFAULT_DELEGATION_EXPIRY_MS.\n *\n * Pure-numeric strings are coerced to numbers so a shell-quoted ms count\n * (`--expiry 86400000`) works, but anything that contains a unit suffix\n * (`\"7d\"`, `\"30m\"`) is forwarded as-is to parseExpiry which understands\n * the ms-format vocabulary.\n */\nfunction parseExpiryOption(raw: unknown): string | number | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new CLIError(\n \"INVALID_EXPIRY\",\n `--expiry must be a string (e.g. \"7d\", \"30m\") or a millisecond integer.`,\n ExitCode.USAGE_ERROR,\n );\n }\n if (/^\\d+$/.test(raw.trim())) {\n const ms = Number(raw.trim());\n if (!Number.isFinite(ms) || ms <= 0) {\n throw new CLIError(\"INVALID_EXPIRY\", `--expiry must be a positive integer when numeric.`, ExitCode.USAGE_ERROR);\n }\n return ms;\n }\n return raw;\n}\n\nfunction groupPermissionsBySpace(permissions: PermissionEntry[]): PermissionEntry[][] {\n const groups = new Map<string, PermissionEntry[]>();\n const rawEntries: PermissionEntry[] = [];\n for (const permission of permissions) {\n if (isRawPermission(permission)) {\n rawEntries.push(permission);\n continue;\n }\n const group = groups.get(permission.space) ?? [];\n group.push(permission);\n groups.set(permission.space, group);\n }\n const grouped = Array.from(groups.values());\n if (grouped.length === 0) {\n return rawEntries.length > 0 ? [rawEntries] : [];\n }\n grouped[0].push(...rawEntries);\n return grouped;\n}\n\nfunction isRawPermission(permission: PermissionEntry): boolean {\n return permission.service === \"tinycloud.encryption\" &&\n permission.path.startsWith(\"urn:tinycloud:encryption:\");\n}\n\nfunction returnedSpaceMatchesExpected(returnedSpace: string, expectedSpace: string): boolean {\n if (returnedSpace === expectedSpace) return true;\n\n if (!returnedSpace.startsWith(\"tinycloud:\")) return false;\n const returnedName = returnedSpace.slice(returnedSpace.lastIndexOf(\":\") + 1);\n return returnedName === expectedSpace;\n}\n\nfunction portableFromOpenKeyDelegation(\n data: Record<string, unknown>,\n permissions: PermissionEntry[],\n host: string,\n): PortableDelegation {\n const primary = permissions.find((permission) => !isRawPermission(permission)) ?? permissions[0];\n const returnedSpace = String(data.spaceId ?? primary.space ?? \"encryption\");\n const expectedSpaces = new Set(\n permissions\n .filter((permission) => !isRawPermission(permission))\n .map((permission) => permission.space),\n );\n const matchesExpectedSpace = expectedSpaces.size === 1 &&\n returnedSpaceMatchesExpected(returnedSpace, Array.from(expectedSpaces)[0]!);\n if (expectedSpaces.size > 0 && !matchesExpectedSpace) {\n throw new CLIError(\n \"OPENKEY_SCOPE_MISMATCH\",\n `OpenKey returned delegation for ${returnedSpace}, expected ${Array.from(expectedSpaces).join(\", \")}.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n const expiry = inferDelegationExpiry(data);\n return {\n cid: String(data.delegationCid),\n delegationHeader: data.delegationHeader as { Authorization: string },\n spaceId: returnedSpace,\n path: primary.path,\n actions: primary.actions,\n resources: permissions.map((permission) => ({\n service: permission.service.startsWith(\"tinycloud.\")\n ? permission.service.slice(\"tinycloud.\".length)\n : permission.service,\n space: isRawPermission(permission) ? permission.space : returnedSpace,\n path: permission.path,\n actions: [...permission.actions],\n })),\n expiry,\n delegateDID: String(data.verificationMethod),\n ownerAddress: String(data.address ?? \"\"),\n chainId: typeof data.chainId === \"number\" ? data.chainId : DEFAULT_CHAIN_ID,\n host,\n };\n}\n\nfunction inferDelegationExpiry(data: Record<string, unknown>): Date {\n const direct = data.expiry ?? data.expiresAt;\n if (typeof direct === \"string\") {\n const parsed = new Date(direct);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n }\n return new Date(Date.now() + 60 * 60 * 1000);\n}\n\nasync function rotateAuthKey(\n profileName: string,\n host: string,\n options: { paste?: boolean; noPopup?: boolean } = {},\n): Promise<void> {\n const profile = await ProfileManager.getProfile(profileName);\n const posture = resolveProfilePosture(profile);\n const oldDid = profile.sessionDid ?? profile.did;\n\n if (posture === \"delegate-session\") {\n throw new CLIError(\n \"ROTATE_DELEGATE_SESSION_UNSUPPORTED\",\n `Profile \"${profileName}\" is a delegated session. Request or import a new owner delegation instead of rotating it locally.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n\n if (profile.authMethod === \"local\" || posture === \"local-owner-key\") {\n if (!profile.privateKey) {\n throw new CLIError(\n \"LOCAL_OWNER_KEY_REQUIRED\",\n `Profile \"${profileName}\" does not have a local owner private key. Run \\`tc auth login --method local\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n await ProfileManager.clearSession(profileName);\n const result = await handleLocalAuth(profileName, host, {\n emitOutput: false,\n forceSessionKey: true,\n });\n outputRotationResult(result.profile, profileName, oldDid, \"local\");\n return;\n }\n\n const { jwk, did } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n\n await ProfileManager.setKey(profileName, jwk);\n await ProfileManager.clearSession(profileName);\n await ProfileManager.setProfile(profileName, {\n ...profile,\n host,\n did,\n sessionDid: did,\n posture: profile.posture ?? \"owner-openkey\",\n operatorType: profile.operatorType ?? \"human\",\n authMethod: \"openkey\",\n });\n\n const result = await refreshOpenKeySession(profileName, host, {\n paste: options.paste,\n noPopup: options.noPopup,\n });\n outputRotationResult(result.profile, profileName, oldDid, \"openkey\");\n}\n\nfunction outputRotationResult(\n profile: ProfileConfig,\n profileName: string,\n oldDid: string,\n authMethod: AuthMethod,\n): void {\n outputJson({\n rotated: true,\n profile: profileName,\n oldDid,\n did: profile.did,\n sessionDid: profile.sessionDid ?? null,\n authMethod,\n spaceId: profile.spaceId ?? null,\n });\n}\n\ntype LocalAuthResult = {\n profile: ProfileConfig;\n sessionResult: Awaited<ReturnType<typeof localKeySignIn>>;\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(\n profileName: string,\n host: string,\n options: { emitOutput?: boolean; forceSessionKey?: boolean } = {},\n): Promise<LocalAuthResult> {\n const profile = await ProfileManager.getProfile(profileName).catch(() => null);\n const posture = profile ? resolveProfilePosture(profile) : null;\n\n let privateKey: string;\n let address: string;\n let did: string;\n let sessionDid = profile?.sessionDid;\n\n if ((profile?.authMethod === \"local\" || posture === \"local-owner-key\") && profile.privateKey) {\n // Reuse existing local key\n privateKey = profile.privateKey;\n address = profile.address ?? await deriveAddress(privateKey);\n did = profile.did.startsWith(\"did:pkh:\")\n ? profile.did\n : addressToDID(address, profile.chainId ?? DEFAULT_CHAIN_ID);\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 (options.forceSessionKey || !hasKey) {\n const { jwk, did: generatedSessionDid } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n await ProfileManager.setKey(profileName, jwk);\n sessionDid = generatedSessionDid;\n } else if (!sessionDid) {\n sessionDid = keyToDID(hasKey);\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 delegationHeader: sessionResult.delegationHeader,\n delegationCid: sessionResult.delegationCid,\n jwk: sessionResult.jwk,\n verificationMethod: sessionResult.verificationMethod,\n siwe: sessionResult.siwe,\n signature: sessionResult.signature,\n });\n sessionDid = sessionResult.verificationMethod;\n\n // Update profile\n const updatedProfile = {\n ...profile,\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n sessionDid,\n ownerDid: did,\n spaceId: sessionResult.spaceId,\n createdAt: profile?.createdAt ?? new Date().toISOString(),\n posture: profile?.posture ?? \"local-owner-key\",\n operatorType: profile?.operatorType ?? \"human\",\n authMethod: \"local\",\n privateKey,\n address,\n } satisfies ProfileConfig;\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n if (options.emitOutput ?? true) {\n outputJson({\n authenticated: true,\n profile: profileName,\n did,\n sessionDid,\n address,\n spaceId: sessionResult.spaceId,\n authMethod: \"local\",\n });\n }\n\n return { profile: updatedProfile, sessionResult };\n}\n\n/**\n * Handle OpenKey (browser-based) authentication.\n * This is the original auth flow.\n */\nasync function handleOpenKeyAuth(\n profileName: string,\n host: string,\n options: { paste?: boolean; noPopup?: boolean } = {},\n): Promise<void> {\n const { profile, delegationData } = await refreshOpenKeySession(profileName, host, options);\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did: profile.did,\n spaceId: delegationData.spaceId,\n authMethod: \"openkey\",\n });\n}\n\nexport async function refreshOpenKeySession(\n profileName: string,\n host: string,\n options: { paste?: boolean; noPopup?: boolean } = {},\n): Promise<{ profile: ProfileConfig; delegationData: Record<string, unknown> }> {\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: options.paste,\n noPopup: options.noPopup,\n jwk: key,\n host,\n openkeyHost: resolveOpenKeyHost(profile),\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with owner DID if present\n const updatedProfile = {\n ...profile,\n sessionDid: profile.sessionDid ?? profile.did,\n posture: profile.posture ?? \"owner-openkey\",\n operatorType: profile.operatorType ?? \"human\",\n authMethod: \"openkey\" as const,\n };\n\n if (delegationData.spaceId) {\n updatedProfile.spaceId = delegationData.spaceId;\n updatedProfile.ownerDid = delegationData.ownerDid as string | undefined;\n }\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n return { profile: updatedProfile, delegationData };\n}\n","export interface GlobalConfig {\n defaultProfile: string;\n version: number;\n}\n\nexport type AuthMethod = \"openkey\" | \"local\";\n\nexport const CLI_PROFILE_POSTURES = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n] as const;\n\nexport type CLIProfilePosture = typeof CLI_PROFILE_POSTURES[number];\n\nexport const CLI_OPERATOR_TYPES = [\"human\", \"agent\"] as const;\n\nexport type CLIOperatorType = typeof CLI_OPERATOR_TYPES[number];\n\nexport function isCLIProfilePosture(value: unknown): value is CLIProfilePosture {\n return typeof value === \"string\" && CLI_PROFILE_POSTURES.includes(value as CLIProfilePosture);\n}\n\nexport function isCLIOperatorType(value: unknown): value is CLIOperatorType {\n return typeof value === \"string\" && CLI_OPERATOR_TYPES.includes(value as CLIOperatorType);\n}\n\nexport function resolveProfilePosture(profile: {\n posture?: unknown;\n authMethod?: AuthMethod;\n}): CLIProfilePosture {\n if (isCLIProfilePosture(profile.posture)) return profile.posture;\n if (profile.authMethod === \"local\") return \"local-owner-key\";\n return \"owner-openkey\";\n}\n\nexport function resolveProfileOperatorType(profile: {\n operatorType?: unknown;\n}): CLIOperatorType {\n if (isCLIOperatorType(profile.operatorType)) return profile.operatorType;\n return \"human\";\n}\n\nexport interface ProfileConfig {\n name: string;\n host: string;\n chainId: number;\n spaceName: string;\n did: string;\n sessionDid?: string;\n ownerDid?: string;\n spaceId?: string;\n createdAt: string;\n posture?: CLIProfilePosture;\n operatorType?: CLIOperatorType;\n authMethod?: AuthMethod;\n /** Hex-encoded Ethereum private key (only present when authMethod is \"local\") */\n privateKey?: string;\n /** Ethereum address derived from privateKey (only present when authMethod is \"local\") */\n address?: string;\n /**\n * Optional OpenKey host override. Used for testing accounts or running\n * against a self-hosted OpenKey (e.g. https://openkey.localhost). Falls\n * back to DEFAULT_OPENKEY_HOST when unset. Edit profile.json directly\n * to change.\n */\n openkeyHost?: string;\n}\n\nexport interface CLIContext {\n profile: string;\n host: string;\n verbose: boolean;\n noCache: boolean;\n quiet: boolean;\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\";\nimport { replayAdditionalDelegations } from \"./permissions.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: prefer the persisted TinyCloud session so the CLI\n // keeps the same session key DID across request/grant/import flows.\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: effectivePrivateKey,\n });\n\n if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\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.sessionDid ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n } else {\n await node.signIn();\n }\n await replayAdditionalDelegations(node, ctx.profile);\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 siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n }\n\n await replayAdditionalDelegations(node, ctx.profile);\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 { randomBytes } from \"node:crypto\";\nimport { appendFile, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n expandActionShortNames,\n isCapabilitySubset,\n resolveManifest,\n type PermissionEntry,\n type PortableDelegation,\n type TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\nimport { PROFILES_DIR } from \"../config/constants.js\";\nimport { fileExists, readJson, writeJson, ensureDir } from \"../config/storage.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { resolveSpaceUri } from \"./space.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Stored shape for a runtime delegation appended to a profile.\n * `permissions` mirrors the request that produced this delegation so\n * `tc auth caps` can surface the originally-asked-for entries even after\n * the delegation has been baked into a recap.\n */\nexport interface StoredAdditionalDelegation {\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n}\n\nexport interface GrantHistoryEntry {\n ts: string;\n profile: string;\n addedCaps: PermissionEntry[];\n source: \"cli\" | \"401-hint\" | \"manifest\";\n delegationCid?: string;\n expiry?: string;\n}\n\nexport interface PermissionRequestArtifact {\n kind: \"tinycloud.auth.request\";\n version: 1;\n requestId: string;\n createdAt: string;\n profile: string;\n posture: CLIProfilePosture;\n operatorType: CLIOperatorType;\n host: string;\n sessionDid: string;\n ownerDid?: string;\n spaceId?: string;\n requestedExpiry?: string | number;\n requested: PermissionEntry[];\n command?: {\n argv: string[];\n cwd: string;\n };\n}\n\nexport interface DelegationImportArtifact {\n kind: \"tinycloud.auth.delegation\";\n version: 1;\n requestId?: string;\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n // Sibling file keeps legacy session.json schema unchanged for existing readers.\n return join(PROFILES_DIR, profile, \"additional-delegations.json\");\n}\n\nexport function permissionRequestsPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-requests.json\");\n}\n\nexport function grantHistoryPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-grants.jsonl\");\n}\n\nexport function createPermissionRequestArtifact(params: {\n profileName: string;\n profile: ProfileConfig;\n host: string;\n requested: PermissionEntry[];\n requestedExpiry?: string | number;\n argv?: string[];\n cwd?: string;\n}): PermissionRequestArtifact {\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: `req_${Date.now().toString(36)}_${randomBytes(4).toString(\"hex\")}`,\n createdAt: new Date().toISOString(),\n profile: params.profileName,\n posture: resolveProfilePosture(params.profile),\n operatorType: resolveProfileOperatorType(params.profile),\n host: params.host,\n sessionDid: didWithoutFragment(params.profile.sessionDid ?? params.profile.did),\n ownerDid: params.profile.ownerDid,\n spaceId: params.profile.spaceId,\n requestedExpiry: params.requestedExpiry,\n requested: params.requested,\n command: {\n argv: params.argv ?? process.argv.slice(2),\n cwd: params.cwd ?? process.cwd(),\n },\n };\n}\n\nfunction didWithoutFragment(did: string): string {\n const fragment = did.indexOf(\"#\");\n return fragment === -1 ? did : did.slice(0, fragment);\n}\n\nexport async function loadAdditionalDelegations(\n profile: string,\n): Promise<StoredAdditionalDelegation[]> {\n const raw = await readJson<StoredAdditionalDelegation[]>(\n additionalDelegationsPath(profile),\n );\n return Array.isArray(raw) ? raw : [];\n}\n\nexport async function saveAdditionalDelegations(\n profile: string,\n entries: StoredAdditionalDelegation[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(additionalDelegationsPath(profile), entries);\n}\n\nexport async function appendAdditionalDelegation(\n profile: string,\n entry: StoredAdditionalDelegation,\n): Promise<void> {\n const existing = await loadAdditionalDelegations(profile);\n const next = existing.filter((item) => item.delegation.cid !== entry.delegation.cid);\n next.push(entry);\n await saveAdditionalDelegations(profile, next);\n}\n\nexport async function loadPermissionRequestArtifacts(\n profile: string,\n): Promise<PermissionRequestArtifact[]> {\n const raw = await readJson<PermissionRequestArtifact[]>(\n permissionRequestsPath(profile),\n );\n return Array.isArray(raw) ? raw.filter(isPermissionRequestArtifact) : [];\n}\n\nexport async function savePermissionRequestArtifacts(\n profile: string,\n entries: PermissionRequestArtifact[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(permissionRequestsPath(profile), entries);\n}\n\nexport async function appendPermissionRequestArtifact(\n profile: string,\n artifact: PermissionRequestArtifact,\n): Promise<void> {\n const existing = await loadPermissionRequestArtifacts(profile);\n const next = existing.filter((item) => item.requestId !== artifact.requestId);\n next.push(artifact);\n await savePermissionRequestArtifacts(profile, next);\n}\n\nexport async function getPermissionRequestArtifact(\n profile: string,\n requestId: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.find((item) => item.requestId === requestId) ?? null;\n}\n\nexport async function getLastPermissionRequestArtifact(\n profile: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.at(-1) ?? null;\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PermissionRequestArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.request\" &&\n candidate.version === 1 &&\n typeof candidate.requestId === \"string\" &&\n Array.isArray(candidate.requested)\n );\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<DelegationImportArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.delegation\" &&\n candidate.version === 1 &&\n candidate.delegation !== undefined &&\n typeof candidate.delegation === \"object\"\n );\n}\n\nexport async function replayAdditionalDelegations(\n node: TinyCloudNode,\n profile: string,\n): Promise<void> {\n const entries = await loadAdditionalDelegations(profile);\n for (const entry of entries) {\n // Skip expired delegations rather than letting useRuntimeDelegation throw.\n const expiry = entry.delegation.expiry instanceof Date\n ? entry.delegation.expiry\n : new Date(entry.delegation.expiry as unknown as string);\n if (expiry.getTime() <= Date.now()) continue;\n try {\n await node.useRuntimeDelegation({ ...entry.delegation, expiry });\n } catch (err) {\n // A stored delegation can be invalid for several benign reasons (host\n // unreachable, key rotated). Don't fail the whole CLI invocation —\n // the user can re-run `tc auth request` to refresh the grant.\n if (process.env.TC_DEBUG_REPLAY === \"1\") {\n process.stderr.write(`[replay] skipping ${entry.delegation.cid}: ${(err as Error).message}\\n`);\n }\n }\n }\n}\n\n/**\n * Helper for `tc auth request` to construct the persisted record that\n * follows the runtime grant. Keeps the \"PortableDelegation + originating\n * permissions\" pair together so future `tc auth caps` output can show the\n * caller-friendly entries we agreed to grant.\n */\nexport function storedAdditionalDelegation(\n delegation: PortableDelegation,\n permissions: PermissionEntry[],\n): StoredAdditionalDelegation {\n return { delegation, permissions };\n}\n\nexport async function appendGrantHistory(\n profile: string,\n entry: Omit<GrantHistoryEntry, \"ts\" | \"profile\">,\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n const line = JSON.stringify({\n ts: new Date().toISOString(),\n profile,\n ...entry,\n }) + \"\\n\";\n await appendFile(grantHistoryPath(profile), line, \"utf8\");\n}\n\nexport async function readGrantHistory(\n profile: string,\n): Promise<GrantHistoryEntry[]> {\n const path = grantHistoryPath(profile);\n if (!(await fileExists(path))) return [];\n const raw = await readFile(path, \"utf8\");\n return raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => JSON.parse(line) as GrantHistoryEntry);\n}\n\nexport async function parseCapSpec(\n spec: string,\n profile: string,\n): Promise<PermissionEntry> {\n const firstColon = spec.indexOf(\":\");\n const lastColon = spec.lastIndexOf(\":\");\n if (firstColon <= 0 || lastColon <= firstColon) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Invalid --cap \"${spec}\". Expected tinycloud.<service>:<space>:<path>:<actions-csv>.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const service = normalizeService(spec.slice(0, firstColon));\n const actionsCsv = spec.slice(lastColon + 1);\n const spaceAndPath = spec.slice(firstColon + 1, lastColon);\n const { space, path } = splitSpaceAndPath(spaceAndPath);\n const resolvedSpace = await resolveSpaceUri(space, profile) ?? space;\n const actions = expandActionShortNames(\n service,\n actionsCsv.split(\",\").map((action) => action.trim()).filter(Boolean),\n );\n\n if (actions.length === 0) {\n throw new CLIError(\"INVALID_CAP\", `Capability \"${spec}\" has no actions.`, ExitCode.USAGE_ERROR);\n }\n\n return { service, space: resolvedSpace, path, actions };\n}\n\nexport async function loadPermissionRequest(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = JSON.parse(await readFile(source, \"utf8\")) as { permissions?: PermissionEntry[] };\n if (!Array.isArray(raw.permissions)) {\n throw new CLIError(\n \"INVALID_PERMISSION_REQUEST\",\n `Permission request ${source} must contain { \"permissions\": [...] }.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return resolvePermissionSpaces(raw.permissions, profile);\n}\n\nexport async function loadManifestPermissions(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = await loadManifestText(source);\n const manifest = JSON.parse(raw) as Record<string, unknown>;\n\n if (typeof manifest.id === \"string\") {\n const resolved = resolveManifest(manifest as Parameters<typeof resolveManifest>[0]);\n return resolvePermissionSpaces(resolved.resources, profile);\n }\n\n if (typeof manifest.app_id === \"string\") {\n const permissions = ((manifest.permissions as unknown[]) ?? [])\n .filter((entry): entry is Record<string, unknown> => entry !== null && typeof entry === \"object\")\n .map((entry) => {\n const service = normalizeService(String(entry.service ?? \"\"));\n const path = String(entry.path ?? \"\");\n const skipPrefix = entry.skipPrefix === true;\n const resolvedPath = skipPrefix\n ? path\n : prefixAppManifestPath(path, manifest.app_id as string);\n return {\n service,\n space: String(manifest.space ?? \"applications\"),\n path: resolvedPath,\n actions: expandActionShortNames(\n service,\n Array.isArray(entry.actions)\n ? entry.actions.map(String)\n : [],\n ),\n };\n });\n return resolvePermissionSpaces(permissions, profile);\n }\n\n throw new CLIError(\n \"INVALID_MANIFEST\",\n \"Manifest must contain either SDK field \\\"id\\\" or app manifest field \\\"app_id\\\".\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nexport function diffPermissions(\n requested: PermissionEntry[],\n granted: PermissionEntry[],\n): PermissionEntry[] {\n return isCapabilitySubset(requested, granted).missing;\n}\n\nexport function permissionsFromDelegation(\n delegation: PortableDelegation,\n): PermissionEntry[] {\n if (delegation.resources?.length) {\n return delegation.resources.map((resource) => ({\n service: resource.service.startsWith(\"tinycloud.\")\n ? resource.service\n : `tinycloud.${resource.service}`,\n space: resource.space,\n path: resource.path,\n actions: [...resource.actions],\n }));\n }\n return [{\n service: serviceFromActions(delegation.actions),\n space: delegation.spaceId,\n path: delegation.path,\n actions: [...delegation.actions],\n }];\n}\n\nexport function compactPermission(permission: PermissionEntry): string {\n const service = permission.service;\n const space = permission.space.startsWith(\"tinycloud:\")\n ? permission.space.slice(permission.space.lastIndexOf(\":\") + 1)\n : permission.space;\n const actions = permission.actions\n .map((action) => action.startsWith(`${service}/`) ? action.slice(service.length + 1) : action)\n .join(\",\");\n return `${service}:${space}:${permission.path}:${actions}`;\n}\n\nasync function resolvePermissionSpaces(\n entries: PermissionEntry[],\n profile: string,\n): Promise<PermissionEntry[]> {\n const resolved: PermissionEntry[] = [];\n for (const entry of entries) {\n const service = normalizeService(entry.service);\n resolved.push({\n ...entry,\n service,\n space: await resolveSpaceUri(entry.space, profile) ?? entry.space,\n actions: expandActionShortNames(service, entry.actions),\n });\n }\n return resolved;\n}\n\nasync function loadManifestText(source: string): Promise<string> {\n if (source.startsWith(\"base64:\")) {\n return Buffer.from(source.slice(\"base64:\".length), \"base64\").toString(\"utf8\");\n }\n if (await fileExists(source)) {\n return readFile(source, \"utf8\");\n }\n try {\n const decoded = Buffer.from(source, \"base64\").toString(\"utf8\");\n JSON.parse(decoded);\n return decoded;\n } catch {\n return readFile(source, \"utf8\");\n }\n}\n\nfunction normalizeService(service: string): string {\n if (!service) {\n throw new CLIError(\"INVALID_CAP\", \"Capability service is required.\", ExitCode.USAGE_ERROR);\n }\n return service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`;\n}\n\nfunction splitSpaceAndPath(input: string): { space: string; path: string } {\n if (input.startsWith(\"tinycloud:\")) {\n const parts = input.split(\":\");\n if (parts.length < 7) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Full tinycloud space specs must include a path after the space URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: parts.slice(0, 6).join(\":\"),\n path: parts.slice(6).join(\":\"),\n };\n }\n\n const colon = input.indexOf(\":\");\n if (colon <= 0) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Capability must include both space and path.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: input.slice(0, colon),\n path: input.slice(colon + 1),\n };\n}\n\nfunction prefixAppManifestPath(path: string, appId: string): string {\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n return `${path.slice(0, slash)}/${appId}/${path.slice(slash + 1)}`;\n}\n\nfunction serviceFromActions(actions: string[]): string {\n const first = actions[0] ?? \"tinycloud.unknown/read\";\n return first.includes(\"/\") ? first.slice(0, first.indexOf(\"/\")) : \"tinycloud.unknown\";\n}\n","import { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { ProfileConfig } from \"../config/types.js\";\nimport {\n buildSpaceUri,\n canonicalizeAddress,\n makePkhSpaceId,\n parsePkhDid,\n parseSpaceUri,\n} from \"@tinycloud/node-sdk\";\n\n/**\n * Resolve the active profile's Ethereum address. Source priority matches\n * what TinyCloudNode.signIn / restoreSession actually populates:\n * 1) session.address (set by both local-key and OpenKey auth flows)\n * 2) profile.address (local-key auth only)\n * 3) the address segment of profile.ownerDid (did:pkh:eip155:<chain>:<addr>)\n */\nfunction resolveAddress(profile: ProfileConfig, session: Record<string, unknown> | null): string {\n const sessAddr = session?.address;\n if (typeof sessAddr === \"string\" && sessAddr.length > 0) {\n return canonicalizeAddress(sessAddr);\n }\n\n if (profile.address) return canonicalizeAddress(profile.address);\n\n if (profile.ownerDid) {\n const pkh = parsePkhDid(profile.ownerDid);\n if (pkh) return pkh.address;\n }\n\n throw new CLIError(\n \"ADDRESS_UNKNOWN\",\n `Cannot determine Ethereum address for profile \"${profile.name}\". Run \\`tc auth login\\` to refresh the session.`,\n ExitCode.AUTH_REQUIRED,\n );\n}\n\nfunction resolveChainId(profile: ProfileConfig, session: Record<string, unknown> | null): number {\n const sessChain = session?.chainId;\n if (typeof sessChain === \"number\" && Number.isFinite(sessChain)) return sessChain;\n return profile.chainId;\n}\n\n/**\n * Resolve a --space CLI argument into a full TinyCloud space URI.\n *\n * - undefined → undefined (caller falls back to node.spaceId)\n * - \"tinycloud:...\" → returned verbatim\n * - bare name → tinycloud:pkh:eip155:<chain>:<address>:<name>\n */\nexport async function resolveSpaceUri(\n input: string | undefined,\n profileName: string,\n): Promise<string | undefined> {\n if (!input) return undefined;\n if (input.startsWith(\"tinycloud:\")) {\n const parsed = parseSpaceUri(input);\n if (!parsed) {\n throw new CLIError(\n \"INVALID_SPACE\",\n `Invalid --space \"${input}\". Use a short name ([A-Za-z0-9_-]) or a full tinycloud:... URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return buildSpaceUri(parsed.owner, parsed.name);\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(input)) {\n throw new CLIError(\n \"INVALID_SPACE\",\n `Invalid --space \"${input}\". Use a short name ([A-Za-z0-9_-]) or a full tinycloud:... URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const profile = await ProfileManager.getProfile(profileName);\n const session = (await ProfileManager.getSession(profileName)) as Record<string, unknown> | null;\n\n const address = resolveAddress(profile, session);\n const chainId = resolveChainId(profile, session);\n return makePkhSpaceId(address, chainId, input);\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 { resolveSpaceUri } from \"../lib/space.js\";\nimport { theme } from \"../output/theme.js\";\nimport type { TinyCloudNode } 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 * Pick a KV service for the requested space.\n *\n * `--space` is optional; when omitted, ops route through the node's primary\n * space (preserves prior behavior). When present, we use\n * TinyCloudNode.kvForSpace, which clones the active service context with a\n * session whose spaceId points at the target space — e.g. to read a manifest\n * app's data kept under the owner's `applications` space.\n */\nasync function kvHandle(\n node: TinyCloudNode,\n spaceInput: string | undefined,\n profileName: string,\n) {\n const spaceUri = await resolveSpaceUri(spaceInput, profileName);\n return spaceUri ? node.kvForSpace(spaceUri) : node.kv;\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 .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 kv = await kvHandle(node, options.space, ctx.profile);\n const result = await withSpinner(`Getting ${key}...`, () => 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 .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 kv = await kvHandle(node, options.space, ctx.profile);\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing keys...\", () => 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 .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 kv = await kvHandle(node, options.space, ctx.profile);\n const result = await withSpinner(`Checking ${key}...`, () => 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 { 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\";\nimport { principalDidEquals } from \"@tinycloud/node-sdk\";\n\nfunction didMatches(actual: string | undefined, expected: string): boolean {\n if (!actual) return false;\n try {\n return principalDidEquals(actual, expected);\n } catch {\n return actual === expected;\n }\n}\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) => didMatches(d.delegatorDID, myDid));\n } else if (options.received) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => didMatches(d.delegateDID, 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\";\nimport {\n CLI_OPERATOR_TYPES,\n CLI_PROFILE_POSTURES,\n isCLIOperatorType,\n isCLIProfilePosture,\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n} from \"../config/types.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 posture: resolveProfilePosture(p),\n operatorType: resolveProfileOperatorType(p),\n active: name === config.defaultProfile,\n };\n } catch {\n return {\n name,\n host: null,\n did: null,\n posture: null,\n operatorType: null,\n active: name === config.defaultProfile,\n };\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 const posture = p.posture ? theme.muted(String(p.posture)) : theme.muted(\"no posture\");\n process.stdout.write(`${marker}${name} ${host} ${posture}\\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 .option(\n \"--posture <posture>\",\n `Profile posture: ${CLI_PROFILE_POSTURES.join(\", \")}. Defaults to owner-openkey.`,\n )\n .option(\n \"--operator <type>\",\n `Operator type: ${CLI_OPERATOR_TYPES.join(\", \")}. Defaults to human.`,\n )\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 const posture = parseProfilePosture(options.posture);\n const operatorType = parseOperatorType(options.operator);\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 sessionDid: did,\n createdAt: new Date().toISOString(),\n posture,\n operatorType,\n });\n\n outputJson({ profile: name, did, host, posture, operatorType, 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 const posture = resolveProfilePosture(p);\n const operatorType = resolveProfileOperatorType(p);\n\n if (shouldOutputJson()) {\n outputJson({\n ...p,\n posture,\n operatorType,\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(\"Session DID\", p.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\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\nfunction parseProfilePosture(raw: unknown): CLIProfilePosture {\n if (raw === undefined || raw === null || raw === \"\") return \"owner-openkey\";\n if (isCLIProfilePosture(raw)) return raw;\n throw new CLIError(\n \"INVALID_POSTURE\",\n `Invalid posture \"${String(raw)}\". Use one of: ${CLI_PROFILE_POSTURES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction parseOperatorType(raw: unknown): CLIOperatorType {\n if (raw === undefined || raw === null || raw === \"\") return \"human\";\n if (isCLIOperatorType(raw)) return raw;\n throw new CLIError(\n \"INVALID_OPERATOR\",\n `Invalid operator \"${String(raw)}\". Use one of: ${CLI_OPERATOR_TYPES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\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 rotate 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 rotate 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 rotate 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 {\n resolveSecretListPrefix,\n resolveSecretPath,\n type PermissionEntry,\n type SecretScopeOptions,\n type TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\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 { resolveProfilePosture, type CLIContext, type ProfileConfig } from \"../config/types.js\";\nimport { ensureDelegationAuthority, refreshOpenKeySession } from \"./auth.js\";\n\nconst SECRETS_SPACE = \"secrets\";\ntype SecretAction = \"get\" | \"put\" | \"del\" | \"list\";\ntype SecretKvAbility =\n | \"tinycloud.kv/get\"\n | \"tinycloud.kv/put\"\n | \"tinycloud.kv/del\"\n | \"tinycloud.kv/list\";\nconst SECRET_KV_ABILITIES: Record<SecretAction, SecretKvAbility> = {\n get: \"tinycloud.kv/get\",\n put: \"tinycloud.kv/put\",\n del: \"tinycloud.kv/del\",\n list: \"tinycloud.kv/list\",\n};\ntype SecretResult<T> =\n | { ok: true; data: T }\n | { ok: false; error: { code: string; message: string; service?: string } };\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\nfunction authOptions(options: { privateKey?: string }): { privateKey?: string } | undefined {\n const privateKey = options.privateKey || process.env.TC_PRIVATE_KEY;\n return privateKey ? { privateKey } : undefined;\n}\n\nfunction resolveSecretScope(options: { scope?: string; space?: string }): { scope?: string } | undefined {\n const scope = options.scope ?? options.space;\n return scope ? { scope } : undefined;\n}\n\nasync function ensureSecretsNode(\n ctx: CLIContext,\n options: { privateKey?: string },\n): Promise<TinyCloudNode> {\n const auth = authOptions(options);\n if (auth?.privateKey) {\n return ensureAuthenticated(ctx, auth);\n }\n\n const profile = await ProfileManager.getProfile(ctx.profile).catch(() => null);\n if (profile?.authMethod === \"openkey\" && canRequestOwnerPermissions(profile)) {\n const session = await ProfileManager.getSession(ctx.profile);\n if (!session || isStoredSessionExpired(session)) {\n await withSpinner(\n session ? \"Refreshing TinyCloud session...\" : \"Creating TinyCloud session...\",\n () => refreshOpenKeySession(ctx.profile, ctx.host),\n );\n }\n }\n\n return ensureAuthenticated(ctx, auth);\n}\n\nasync function runSecretOperation<T>(params: {\n ctx: CLIContext;\n node: TinyCloudNode;\n action: SecretAction;\n name?: string;\n scopeOptions?: SecretScopeOptions;\n label: string;\n operation: () => Promise<SecretResult<T>>;\n}): Promise<SecretResult<T>> {\n const first = await runSecretOperationAttempt(params.label, params.operation);\n if (first.ok || !shouldRequestSecretPermissions(first.error)) {\n return first;\n }\n\n const profile = await ProfileManager.getProfile(params.ctx.profile);\n if (!canRequestOwnerPermissions(profile)) {\n return first;\n }\n\n const requested = secretPermissionEntries({\n action: params.action,\n name: params.name,\n options: params.scopeOptions,\n node: params.node,\n });\n await withSpinner(\"Requesting secret permissions...\", () =>\n ensureDelegationAuthority({\n ctx: params.ctx,\n profile,\n node: params.node,\n requested,\n expiryOption: undefined,\n yes: true,\n force: true,\n }),\n );\n\n return runSecretOperationAttempt(params.label, params.operation);\n}\n\nasync function runSecretOperationAttempt<T>(\n label: string,\n operation: () => Promise<SecretResult<T>>,\n): Promise<SecretResult<T>> {\n try {\n return await withSpinner(label, operation);\n } catch (error) {\n const permissionError = thrownPermissionError(error);\n if (permissionError) return permissionError;\n throw error;\n }\n}\n\nfunction canRequestOwnerPermissions(profile: ProfileConfig): boolean {\n const posture = resolveProfilePosture(profile);\n return posture === \"owner-openkey\" || posture === \"local-owner-key\";\n}\n\nfunction shouldRequestSecretPermissions(error: { code: string; message: string }): boolean {\n if (error.code !== \"PERMISSION_DENIED\") return false;\n return /permission|session expired|autosign|capabilit/i.test(error.message);\n}\n\nfunction thrownPermissionError<T>(error: unknown): SecretResult<T> | null {\n const record = error as { code?: unknown; message?: unknown };\n const message = typeof record?.message === \"string\" ? record.message : String(error);\n const code = typeof record?.code === \"string\" ? record.code : \"PERMISSION_DENIED\";\n if (code !== \"PERMISSION_DENIED\" && !/permission|session expired|autosign|capabilit/i.test(message)) {\n return null;\n }\n\n return {\n ok: false,\n error: {\n code: \"PERMISSION_DENIED\",\n message,\n },\n };\n}\n\nfunction isStoredSessionExpired(session: object): boolean {\n const record = session as Record<string, unknown>;\n const direct = parseDate(record.expiresAt ?? record.expiry ?? record.expirationTime);\n if (direct) return direct.getTime() <= Date.now();\n if (typeof record.siwe !== \"string\") return false;\n const match = record.siwe.match(/^Expiration Time:\\s*(.+)$/im);\n const expiry = match ? parseDate(match[1].trim()) : null;\n return expiry !== null && expiry.getTime() <= Date.now();\n}\n\nfunction parseDate(value: unknown): Date | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value;\n }\n if (typeof value !== \"string\" || value.trim() === \"\") return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction secretKvAbility(action: SecretAction): SecretKvAbility {\n return SECRET_KV_ABILITIES[action];\n}\n\nfunction secretPermissionEntries(params: {\n action: SecretAction;\n name?: string;\n options?: SecretScopeOptions;\n node: TinyCloudNode;\n}): PermissionEntry[] {\n const path = params.action === \"list\"\n ? resolveSecretListPrefix(params.options)\n : resolveSecretPath(params.name ?? \"\", params.options).permissionPaths.vault;\n const permissions: PermissionEntry[] = [{\n service: \"tinycloud.kv\",\n space: SECRETS_SPACE,\n path,\n actions: [secretKvAbility(params.action)],\n skipPrefix: true,\n }];\n\n if (params.action === \"get\") {\n permissions.push({\n service: \"tinycloud.encryption\",\n path: params.node.getDefaultEncryptionNetworkId(),\n actions: [\"tinycloud.encryption/decrypt\"],\n skipPrefix: true,\n });\n }\n\n return permissions;\n}\n\nexport function registerSecretsCommand(program: Command): void {\n const secrets = program.command(\"secrets\").description(\"Encrypted secrets management\");\n\n const network = secrets\n .command(\"network\")\n .description(\"Manage the default secrets encryption network\");\n\n network\n .command(\"show [nameOrNetworkId]\")\n .description(\"Show a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (nameOrNetworkId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const requested = nameOrNetworkId ?? \"default\";\n const networkId = requested.startsWith(\"urn:tinycloud:encryption:\")\n ? requested\n : node.getDefaultEncryptionNetworkId(requested);\n const descriptor = await withSpinner(\n \"Fetching encryption network...\",\n () => node.getEncryptionNetwork(requested),\n );\n outputJson({\n networkId,\n exists: descriptor !== null,\n ...(descriptor ? { descriptor } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n network\n .command(\"init [name]\")\n .description(\"Create a secrets encryption network if needed\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(name ?? \"default\"),\n );\n outputJson({\n networkId: descriptor.networkId,\n state: descriptor.state,\n descriptor,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets list\n secrets\n .command(\"list\")\n .description(\"List secrets\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\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 node = await ensureSecretsNode(ctx, options);\n const scopeOptions = resolveSecretScope(options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"list\",\n scopeOptions,\n label: \"Listing secrets...\",\n operation: () => node.secrets.list(scopeOptions),\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const secretNames = Array.isArray(result.data) ? result.data : [];\n const scope = options.scope ?? options.space;\n\n outputJson({\n secrets: secretNames,\n count: secretNames.length,\n ...(scope ? { scope } : {}),\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(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"--value-only\", \"Output only the secret value (alias for --raw)\")\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 node = await ensureSecretsNode(ctx, options);\n const scopeOptions = resolveSecretScope(options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"get\",\n name,\n scopeOptions,\n label: `Getting secret ${name}...`,\n operation: () => node.secrets.get(name, scopeOptions),\n });\n\n if (!result.ok) {\n if (\n result.error.code === \"NOT_FOUND\" ||\n result.error.code === \"KEY_NOT_FOUND\"\n ) {\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 value = String(result.data);\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 || options.valueOnly) {\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(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\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 node = await ensureSecretsNode(ctx, options);\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 scopeOptions = resolveSecretScope(options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"put\",\n name,\n scopeOptions,\n label: `Storing secret ${name}...`,\n operation: () => node.secrets.put(name, secretValue, scopeOptions),\n });\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(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\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 node = await ensureSecretsNode(ctx, options);\n const scopeOptions = resolveSecretScope(options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"del\",\n name,\n scopeOptions,\n label: `Deleting secret ${name}...`,\n operation: () => node.secrets.delete(name, scopeOptions),\n });\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 network\n .command(\"grant <recipientDid> [name]\")\n .description(\"Grant decrypt permission for a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (recipientDid: string, name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const networkName = name ?? \"default\";\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(networkName),\n );\n const permission = {\n service: \"tinycloud.encryption\",\n path: descriptor.networkId,\n actions: [\"decrypt\"],\n };\n const result = await withSpinner(\n `Granting decrypt permission to ${recipientDid}...`,\n () => node.delegateTo(recipientDid, [permission]),\n );\n\n outputJson({\n networkId: descriptor.networkId,\n recipientDid,\n cid: result.delegation.cid,\n prompted: result.prompted,\n path: result.delegation.path,\n actions: result.delegation.actions,\n });\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 type { TinyCloudNode, IDatabaseHandle } from \"@tinycloud/node-sdk\";\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 { resolveSpaceUri } from \"../lib/space.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Pick a database handle for the requested space + db name.\n *\n * `--space` is optional; when omitted, ops route through the node's\n * primary-space SQL service (preserves prior behavior). When present,\n * we use TinyCloudNode.sqlForSpace, which clones the active service\n * context with a session whose spaceId points at the target space.\n */\nasync function dbHandle(\n node: TinyCloudNode,\n dbName: string,\n spaceInput: string | undefined,\n profileName: string,\n): Promise<IDatabaseHandle> {\n const spaceUri = await resolveSpaceUri(spaceInput, profileName);\n const sql = spaceUri ? node.sqlForSpace(spaceUri) : node.sql;\n return sql.db(dbName);\n}\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. Pass\n--space to target a non-primary space (e.g. the manifest \"applications\" space).\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 query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\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 copy Copy rows between databases (optionally across spaces)\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 - --space accepts a short name (\"applications\") or full URI (\"tinycloud:pkh:eip155:1:0x...:applications\").\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(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 $ tc sql query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\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 const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Running query...\", () =>\n handle.query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\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(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 $ tc sql execute \"DELETE FROM conversation WHERE id = ?\" --space applications --db xyz.tinycloud.listen/conversations --params '[\"abc\"]'\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 const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Executing statement...\", () =>\n handle.execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\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(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 $ tc sql export --space applications --db xyz.tinycloud.listen/conversations --output listen.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 handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n handle.export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\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 sql copy\n sql\n .command(\"copy\")\n .description(\"Copy rows between SQL databases (optionally across spaces)\")\n .requiredOption(\"--from-db <name>\", \"Source database name\")\n .requiredOption(\"--to-db <name>\", \"Destination database name\")\n .option(\"--from-space <name|uri>\", \"Source space (defaults to primary)\")\n .option(\"--to-space <name|uri>\", \"Destination space (defaults to primary)\")\n .option(\"--table <name...>\", \"Restrict copy to specific tables (repeat or comma-separated)\")\n .option(\"--dry-run\", \"Print the plan without writing\", false)\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql copy --from-db com.tinycloud.conversation-sync/conversations \\\\\n --to-db xyz.tinycloud.listen/conversations \\\\\n --space applications --dry-run\n $ tc sql copy --from-space applications --from-db com.foo/data \\\\\n --to-space applications --to-db com.bar/data \\\\\n --table conversation --table participant\n\nNotes:\n - Refuses to run when (resolved space, db) is identical for source and destination.\n - Does NOT create destination tables. Run the target app once (or use \\`tc sql execute\\`)\n to materialize the schema before copying.\n - One row at a time; suitable for small/medium datasets. Large copies should\n use \\`tc sql export\\` + bulk import.\n - Authorization: the active session/delegation must cover sql/read on source\n AND sql/write on destination. Otherwise the relevant operation will fail.\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 // commander's `--space` shorthand supports both --from-space and a default.\n const fromSpaceInput: string | undefined = options.fromSpace ?? options.space;\n const toSpaceInput: string | undefined = options.toSpace ?? options.space;\n\n const fromSpaceUri = (await resolveSpaceUri(fromSpaceInput, ctx.profile)) ?? \"<primary>\";\n const toSpaceUri = (await resolveSpaceUri(toSpaceInput, ctx.profile)) ?? \"<primary>\";\n\n if (fromSpaceUri === toSpaceUri && options.fromDb === options.toDb) {\n throw new CLIError(\n \"SELF_COPY\",\n `Refusing to copy: source and destination resolve to the same (space, db) — ${fromSpaceUri} / ${options.fromDb}.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const fromHandle = await dbHandle(node, options.fromDb, fromSpaceInput, ctx.profile);\n const toHandle = await dbHandle(node, options.toDb, toSpaceInput, ctx.profile);\n\n // Resolve target tables: explicit list, or all user tables in source.\n let tables: string[];\n if (options.table && options.table.length > 0) {\n tables = options.table.flatMap((t: string) => t.split(\",\").map((s) => s.trim()).filter(Boolean));\n } else {\n const listing = await fromHandle.query(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n ) as any;\n if (!listing.ok) {\n throw new CLIError(listing.error.code, `Cannot list source tables: ${listing.error.message}`, ExitCode.ERROR, listing.error.meta);\n }\n tables = (listing.data.rows as unknown[][]).map((r) => String(r[0]));\n }\n\n if (tables.length === 0) {\n throw new CLIError(\n \"EMPTY_PLAN\",\n `No tables to copy. Use --table to specify tables, or check that the source database has user tables.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const plan: Array<{ table: string; rows: number; copied: number; skipped: number }> = [];\n\n for (const table of tables) {\n const safe = quoteIdent(table);\n const countResult = await fromHandle.query(`SELECT count(*) AS n FROM ${safe}`) as any;\n if (!countResult.ok) {\n throw new CLIError(\n countResult.error.code,\n `Cannot count rows in source table \"${table}\": ${countResult.error.message}`,\n ExitCode.ERROR,\n countResult.error.meta,\n );\n }\n const rows = Number(countResult.data.rows[0]?.[0] ?? 0);\n plan.push({ table, rows, copied: 0, skipped: 0 });\n }\n\n if (options.dryRun) {\n outputJson({\n dryRun: true,\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rows: p.rows })),\n });\n return;\n }\n\n for (const entry of plan) {\n const safe = quoteIdent(entry.table);\n const fetched = await fromHandle.query(`SELECT * FROM ${safe}`) as any;\n if (!fetched.ok) {\n throw new CLIError(fetched.error.code, `Failed to read \"${entry.table}\": ${fetched.error.message}`, ExitCode.ERROR, fetched.error.meta);\n }\n const columns: string[] = fetched.data.columns;\n const rows: unknown[][] = fetched.data.rows;\n\n if (rows.length === 0) continue;\n\n const colList = columns.map(quoteIdent).join(\", \");\n const placeholders = columns.map(() => \"?\").join(\", \");\n const insertSql = `INSERT INTO ${safe} (${colList}) VALUES (${placeholders})`;\n\n for (const row of rows) {\n const writeResult = await toHandle.execute(insertSql, row as any) as any;\n if (!writeResult.ok) {\n throw new CLIError(\n writeResult.error.code,\n `Insert into \"${entry.table}\" failed after ${entry.copied} row(s): ${writeResult.error.message}`,\n ExitCode.ERROR,\n writeResult.error.meta,\n );\n }\n entry.copied += writeResult.data.changes ?? 1;\n }\n }\n\n outputJson({\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rowsRead: p.rows, rowsWritten: p.copied })),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/** Quote a SQLite identifier defensively (table/column names). */\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\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 { readFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { resolveSpaceUri } from \"../lib/space.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { theme } from \"../output/theme.js\";\n\ninterface ManifestPermission {\n service: string;\n path: string;\n actions: string[];\n skipPrefix?: boolean;\n description?: string;\n}\n\ninterface Manifest {\n manifest_version?: number;\n app_id?: string;\n name?: string;\n description?: string;\n space?: string;\n defaults?: boolean;\n permissions?: ManifestPermission[];\n}\n\n/**\n * Default space for app data when the manifest omits `space`.\n * Mirrors the manifest spec at repositories/listen/SPEC-manifest-and-capability-chain.md.\n */\nconst DEFAULT_APP_SPACE = \"applications\";\n\nexport function registerManifestCommand(program: Command): void {\n const manifest = program\n .command(\"manifest\")\n .description(\"Inspect TinyCloud app manifests\");\n\n manifest\n .command(\"resolve <source>\")\n .description(\"Resolve a manifest file or URL to its effective space, paths, and DB basenames\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc manifest resolve ./manifest.json\n $ tc manifest resolve https://app.example.com/manifest.json --json\n\nWhat it shows:\n - app_id, name, manifest_version\n - effective space name (default: \"applications\") and full space URI for the active profile\n - per-permission: service, fully-qualified path, actions\n - inferred SQL database basenames for sql/<db>/... paths\n\nThis command is read-only and does NOT contact the node — it just resolves\nthe manifest against the active profile's address/chain so you know which\n\\`--space\\` and \\`--db\\` values to pass to other tc commands.\n`)\n .action(async (source: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const raw = await loadManifestSource(source);\n const parsed: Manifest = JSON.parse(raw);\n\n if (!parsed.app_id) {\n throw new CLIError(\n \"INVALID_MANIFEST\",\n `Manifest is missing required field \"app_id\".`,\n ExitCode.ERROR,\n );\n }\n\n // Make sure we have an authenticated profile so we can resolve\n // the user's space URI. We don't use the node — just the profile.\n await ensureAuthenticated(ctx);\n\n const spaceName = parsed.space ?? DEFAULT_APP_SPACE;\n const spaceUri = await resolveSpaceUri(spaceName, ctx.profile);\n\n const permissions = (parsed.permissions ?? []).map((p) => {\n const resolvedPath = p.skipPrefix ? p.path : prefixWithAppId(p.path, parsed.app_id!);\n return {\n service: p.service,\n path: resolvedPath,\n actions: p.actions,\n sqlDb: extractSqlDbName(resolvedPath),\n };\n });\n\n const sqlDbs = unique(\n permissions\n .map((p) => p.sqlDb)\n .filter((db): db is string => Boolean(db)),\n );\n\n const summary = {\n source,\n app_id: parsed.app_id,\n name: parsed.name,\n manifest_version: parsed.manifest_version,\n space: {\n name: spaceName,\n uri: spaceUri,\n },\n permissions,\n sqlDatabases: sqlDbs,\n };\n\n if (shouldOutputJson()) {\n outputJson(summary);\n return;\n }\n\n process.stdout.write(`${theme.heading(\"Manifest\")}: ${theme.value(parsed.app_id)}`);\n if (parsed.name) process.stdout.write(theme.muted(` (${parsed.name})`));\n process.stdout.write(\"\\n\");\n\n process.stdout.write(`${theme.label(\"Space\")}: ${theme.value(spaceName)}\\n`);\n if (spaceUri) {\n process.stdout.write(`${theme.label(\"Space URI\")}: ${theme.value(spaceUri)}\\n`);\n }\n\n if (sqlDbs.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"SQL databases\")}\\n`);\n for (const db of sqlDbs) {\n process.stdout.write(` ${theme.value(db)}\\n`);\n }\n process.stdout.write(theme.muted(`\\nUse with: tc sql query --space ${spaceName} --db <db> \"...\"\\n`));\n }\n\n if (permissions.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"Permissions\")}\\n`);\n const rows = permissions.map((p) => [p.service, p.path, p.actions.join(\", \")]);\n process.stdout.write(formatTable([\"service\", \"path\", \"actions\"], rows) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function loadManifestSource(source: string): Promise<string> {\n if (/^https?:\\/\\//i.test(source)) {\n const response = await fetch(source);\n if (!response.ok) {\n throw new CLIError(\n \"MANIFEST_FETCH_FAILED\",\n `Failed to fetch manifest from ${source}: ${response.status} ${response.statusText}`,\n ExitCode.NETWORK_ERROR,\n );\n }\n return response.text();\n }\n return readFile(source, \"utf8\");\n}\n\nfunction prefixWithAppId(path: string, appId: string): string {\n // Manifest paths are usually `<service-prefix>/<resource>`, e.g. `sql/foo/bar`.\n // When skipPrefix is false the app_id is inserted between the service prefix\n // and the resource, matching how resolveAppPath() lays out keys at runtime.\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n const head = path.slice(0, slash);\n const tail = path.slice(slash + 1);\n return `${head}/${appId}/${tail}`;\n}\n\n/**\n * For a path like `sql/<db-name>/<table>/...`, return `<db-name>`.\n * `<db-name>` itself may contain slashes when the app namespaces it\n * (e.g. `sql/xyz.tinycloud.listen/conversations/conversation`), so we drop\n * the trailing table segment(s) and reassemble.\n */\nfunction extractSqlDbName(path: string): string | undefined {\n if (!path.startsWith(\"sql/\")) return undefined;\n const rest = path.slice(4);\n const segments = rest.split(\"/\");\n if (segments.length < 2) return rest;\n // Drop the last segment (table name); the rest is the db name.\n return segments.slice(0, -1).join(\"/\");\n}\n\nfunction unique<T>(arr: T[]): T[] {\n return Array.from(new Set(arr));\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","import { Command } from \"commander\";\nimport {\n NodeWasmBindings,\n type PermissionEntry,\n} from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type ProfileConfig,\n} from \"../config/types.js\";\nimport { handleError } from \"../output/errors.js\";\nimport { outputJson, shouldOutputJson } from \"../output/formatter.js\";\nimport { theme } from \"../output/theme.js\";\nimport {\n compactPermission,\n loadAdditionalDelegations,\n permissionsFromDelegation,\n type StoredAdditionalDelegation,\n} from \"../lib/permissions.js\";\n\ninterface StatusSummary {\n generatedAt: string;\n activeProfile: string;\n defaultProfile: string;\n profileCount: number;\n authenticatedProfileCount: number;\n activeDelegationCount: number;\n profiles: StatusProfile[];\n}\n\ninterface StatusProfile {\n name: string;\n active: boolean;\n default: boolean;\n exists: boolean;\n status: \"logged-in\" | \"local-key\" | \"expired\" | \"signed-out\" | \"missing\";\n host: string | null;\n did: string | null;\n sessionDid: string | null;\n ownerDid: string | null;\n address: string | null;\n spaceId: string | null;\n authMethod: string | null;\n posture: string | null;\n operatorType: string | null;\n hasKey: boolean;\n hasPrivateKey: boolean;\n authenticated: boolean;\n session: StatusSession;\n delegations: StatusDelegation[];\n permissions: PermissionEntry[];\n permissionsCompact: string[];\n permissionCount: number;\n activeDelegationCount: number;\n delegationCount: number;\n issues: string[];\n}\n\ninterface StatusSession {\n present: boolean;\n expired: boolean | null;\n expiresAt: string | null;\n permissions: PermissionEntry[];\n permissionsCompact: string[];\n}\n\ninterface StatusDelegation {\n cid: string;\n active: boolean;\n expired: boolean | null;\n expiresAt: string | null;\n permissions: PermissionEntry[];\n permissionsCompact: string[];\n}\n\nlet wasmBindings: NodeWasmBindings | null = null;\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command(\"status\")\n .description(\"Show local TinyCloud profile, session, delegation, and permission state\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const config = await ProfileManager.getConfig();\n const names = (await ProfileManager.listProfiles()).sort((a, b) =>\n a.localeCompare(b),\n );\n const generatedAt = new Date().toISOString();\n const profiles = await Promise.all(\n names.map((name) =>\n inspectProfile({\n name,\n activeProfile: ctx.profile,\n defaultProfile: config.defaultProfile,\n }),\n ),\n );\n const summary: StatusSummary = {\n generatedAt,\n activeProfile: ctx.profile,\n defaultProfile: config.defaultProfile,\n profileCount: profiles.length,\n authenticatedProfileCount: profiles.filter((p) => p.authenticated)\n .length,\n activeDelegationCount: profiles.reduce(\n (sum, profile) => sum + profile.activeDelegationCount,\n 0,\n ),\n profiles,\n };\n\n if (shouldOutputJson()) {\n outputJson(summary);\n return;\n }\n\n process.stdout.write(formatStatus(summary));\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function inspectProfile(params: {\n name: string;\n activeProfile: string;\n defaultProfile: string;\n}): Promise<StatusProfile> {\n const issues: string[] = [];\n const profile = await readProfile(params.name, issues);\n const session = await readSession(params.name, issues);\n const hasKey = await readHasKey(params.name, issues);\n const storedDelegations = await readDelegations(params.name, issues);\n const sessionPermissions = session ? sessionPermissionsFromRecap(session) : [];\n const sessionExpiry = session ? extractSessionExpiry(session) : null;\n const sessionExpired =\n sessionExpiry === null ? null : sessionExpiry.getTime() <= Date.now();\n const statusSession: StatusSession = {\n present: session !== null,\n expired: session === null ? null : sessionExpired,\n expiresAt: sessionExpiry?.toISOString() ?? null,\n permissions: sessionPermissions,\n permissionsCompact: compactPermissions(sessionPermissions),\n };\n const delegations = storedDelegations.map(inspectDelegation);\n const activeDelegationPermissions = delegations\n .filter((delegation) => delegation.active)\n .flatMap((delegation) => delegation.permissions);\n const permissions = uniquePermissions([\n ...sessionPermissions,\n ...activeDelegationPermissions,\n ]);\n const hasPrivateKey = typeof profile?.privateKey === \"string\" && profile.privateKey.length > 0;\n const localKeyAuthenticated = profile?.authMethod === \"local\" && hasPrivateKey;\n const sessionAuthenticated = session !== null && sessionExpired !== true;\n const authenticated = localKeyAuthenticated || sessionAuthenticated;\n const status = resolveStatus({\n exists: profile !== null,\n authenticated,\n localKeyAuthenticated,\n sessionExpired,\n });\n\n return {\n name: params.name,\n active: params.name === params.activeProfile,\n default: params.name === params.defaultProfile,\n exists: profile !== null,\n status,\n host: profile?.host ?? null,\n did: profile?.did ?? null,\n sessionDid: profile?.sessionDid ?? null,\n ownerDid: profile?.ownerDid ?? null,\n address: profile?.address ?? null,\n spaceId: profile?.spaceId ?? null,\n authMethod: profile?.authMethod ?? null,\n posture: profile ? resolveProfilePosture(profile) : null,\n operatorType: profile ? resolveProfileOperatorType(profile) : null,\n hasKey,\n hasPrivateKey,\n authenticated,\n session: statusSession,\n delegations,\n permissions,\n permissionsCompact: compactPermissions(permissions),\n permissionCount: permissions.length,\n activeDelegationCount: delegations.filter((delegation) => delegation.active)\n .length,\n delegationCount: delegations.length,\n issues,\n };\n}\n\nasync function readProfile(\n name: string,\n issues: string[],\n): Promise<ProfileConfig | null> {\n try {\n return await ProfileManager.getProfile(name);\n } catch (error) {\n issues.push(`profile: ${messageFromError(error)}`);\n return null;\n }\n}\n\nasync function readSession(\n name: string,\n issues: string[],\n): Promise<Record<string, unknown> | null> {\n try {\n return asRecord(await ProfileManager.getSession(name));\n } catch (error) {\n issues.push(`session: ${messageFromError(error)}`);\n return null;\n }\n}\n\nasync function readHasKey(name: string, issues: string[]): Promise<boolean> {\n try {\n return (await ProfileManager.getKey(name)) !== null;\n } catch (error) {\n issues.push(`key: ${messageFromError(error)}`);\n return false;\n }\n}\n\nasync function readDelegations(\n name: string,\n issues: string[],\n): Promise<StoredAdditionalDelegation[]> {\n try {\n return await loadAdditionalDelegations(name);\n } catch (error) {\n issues.push(`delegations: ${messageFromError(error)}`);\n return [];\n }\n}\n\nfunction inspectDelegation(\n entry: StoredAdditionalDelegation,\n): StatusDelegation {\n const expiry = parseDate((entry.delegation as { expiry?: unknown }).expiry);\n const expired = expiry === null ? null : expiry.getTime() <= Date.now();\n const permissions = normalizePermissions(\n Array.isArray(entry.permissions) && entry.permissions.length > 0\n ? entry.permissions\n : permissionsFromDelegation(entry.delegation),\n );\n\n return {\n cid: entry.delegation.cid,\n active: expired !== true,\n expired,\n expiresAt: expiry?.toISOString() ?? null,\n permissions,\n permissionsCompact: compactPermissions(permissions),\n };\n}\n\nfunction resolveStatus(params: {\n exists: boolean;\n authenticated: boolean;\n localKeyAuthenticated: boolean;\n sessionExpired: boolean | null;\n}): StatusProfile[\"status\"] {\n if (!params.exists) return \"missing\";\n if (params.localKeyAuthenticated) return \"local-key\";\n if (params.authenticated) return \"logged-in\";\n if (params.sessionExpired === true) return \"expired\";\n return \"signed-out\";\n}\n\nfunction sessionPermissionsFromRecap(\n session: Record<string, unknown>,\n): PermissionEntry[] {\n if (typeof session.siwe !== \"string\" || session.siwe.length === 0) return [];\n try {\n const rawEntries = getWasmBindings().parseRecapFromSiwe(session.siwe);\n if (!Array.isArray(rawEntries)) return [];\n return normalizePermissions(rawEntries.map(permissionFromRawRecap));\n } catch {\n return [];\n }\n}\n\nfunction permissionFromRawRecap(value: unknown): PermissionEntry | null {\n const record = asRecord(value);\n if (!record) return null;\n const service = stringValue(record.service);\n const space = stringValue(record.space);\n const path = stringValue(record.path);\n const actions = Array.isArray(record.actions)\n ? record.actions.map(String).filter(Boolean)\n : [];\n if (!service || !space || path === null || actions.length === 0) return null;\n return {\n service: normalizeService(service),\n space,\n path,\n actions,\n };\n}\n\nfunction normalizePermissions(entries: unknown[]): PermissionEntry[] {\n const permissions: PermissionEntry[] = [];\n for (const entry of entries) {\n const permission = permissionFromUnknown(entry);\n if (permission) permissions.push(permission);\n }\n return uniquePermissions(permissions);\n}\n\nfunction permissionFromUnknown(value: unknown): PermissionEntry | null {\n const record = asRecord(value);\n if (!record) return null;\n const service = stringValue(record.service);\n const space = stringValue(record.space);\n const path = stringValue(record.path);\n const actions = Array.isArray(record.actions)\n ? record.actions.map(String).filter(Boolean)\n : [];\n if (!service || !space || path === null || actions.length === 0) return null;\n return {\n service: normalizeService(service),\n space,\n path,\n actions,\n };\n}\n\nfunction uniquePermissions(entries: PermissionEntry[]): PermissionEntry[] {\n const seen = new Set<string>();\n const unique: PermissionEntry[] = [];\n for (const entry of entries) {\n const key = compactPermission(entry);\n if (seen.has(key)) continue;\n seen.add(key);\n unique.push(entry);\n }\n return unique;\n}\n\nfunction compactPermissions(entries: PermissionEntry[]): string[] {\n return entries.map(compactPermission);\n}\n\nfunction extractSessionExpiry(session: Record<string, unknown>): Date | null {\n for (const key of [\"expiresAt\", \"expiry\", \"expirationTime\"]) {\n const parsed = parseDate(session[key]);\n if (parsed) return parsed;\n }\n if (typeof session.siwe !== \"string\") return null;\n const match = session.siwe.match(/^Expiration Time:\\s*(.+)$/im);\n return match ? parseDate(match[1].trim()) : null;\n}\n\nfunction parseDate(value: unknown): Date | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n const millis = value > 0 && value < 1_000_000_000_000 ? value * 1000 : value;\n const date = new Date(millis);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n if (typeof value !== \"string\" || value.trim() === \"\") return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction getWasmBindings(): NodeWasmBindings {\n wasmBindings ??= new NodeWasmBindings();\n return wasmBindings;\n}\n\nfunction normalizeService(service: string): string {\n return service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\"\n ? value as Record<string, unknown>\n : null;\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction messageFromError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction formatStatus(summary: StatusSummary): string {\n const lines: string[] = [];\n lines.push(theme.heading(\"TinyCloud Status\"));\n lines.push(`Active profile: ${theme.value(summary.activeProfile)}`);\n lines.push(`Default profile: ${theme.value(summary.defaultProfile)}`);\n lines.push(\"\");\n\n if (summary.profiles.length === 0) {\n lines.push(theme.muted(\"No profiles configured. Run: tc init\"));\n return `${lines.join(\"\\n\")}\\n`;\n }\n\n lines.push(theme.label(\"Profiles\"));\n for (const profile of summary.profiles) {\n lines.push(formatProfile(profile));\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction formatProfile(profile: StatusProfile): string {\n const marker = profile.active ? theme.success(\"*\") : \" \";\n const name = profile.default ? `${profile.name} (default)` : profile.name;\n const host = profile.host ? theme.muted(profile.host) : theme.muted(\"no host\");\n const summary = [\n `${marker} ${profile.active ? theme.brand(name) : name}`,\n formatProfileStatus(profile.status),\n profile.posture ?? \"no posture\",\n plural(profile.permissionCount, \"permission\"),\n `${profile.activeDelegationCount}/${profile.delegationCount} delegations`,\n host,\n ].join(\" \");\n const lines = [summary];\n\n lines.push(` session: ${formatSession(profile.session)}`);\n if (profile.permissionsCompact.length > 0) {\n lines.push(\" permissions:\");\n for (const permission of profile.permissionsCompact) {\n lines.push(` ${permission}`);\n }\n }\n if (profile.delegations.length > 0) {\n lines.push(\" delegations:\");\n for (const delegation of profile.delegations) {\n lines.push(` ${formatDelegation(delegation)}`);\n }\n }\n if (profile.issues.length > 0) {\n lines.push(\" issues:\");\n for (const issue of profile.issues) {\n lines.push(` ${theme.warn(issue)}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nfunction formatProfileStatus(status: StatusProfile[\"status\"]): string {\n switch (status) {\n case \"logged-in\":\n return theme.success(\"logged in\");\n case \"local-key\":\n return theme.success(\"local key\");\n case \"expired\":\n return theme.warn(\"expired\");\n case \"missing\":\n return theme.warn(\"missing\");\n case \"signed-out\":\n return theme.muted(\"signed out\");\n }\n}\n\nfunction formatSession(session: StatusSession): string {\n if (!session.present) return theme.muted(\"none\");\n if (session.expired === true) {\n return `${theme.warn(\"expired\")}${formatExpiresAt(session.expiresAt)}`;\n }\n if (session.expired === false) {\n return `${theme.success(\"active\")}${formatExpiresAt(session.expiresAt)}`;\n }\n return `${theme.success(\"present\")}${formatExpiresAt(session.expiresAt)}`;\n}\n\nfunction formatDelegation(delegation: StatusDelegation): string {\n const state = delegation.expired === true\n ? theme.warn(\"expired\")\n : theme.success(\"active\");\n return [\n delegation.cid,\n state,\n formatExpiresAt(delegation.expiresAt).trim(),\n plural(delegation.permissions.length, \"permission\"),\n ].filter(Boolean).join(\" \");\n}\n\nfunction formatExpiresAt(expiresAt: string | null): string {\n return expiresAt ? ` until ${expiresAt}` : \"\";\n}\n\nfunction plural(count: number, label: string): string {\n return `${count} ${label}${count === 1 ? \"\" : \"s\"}`;\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAoB;AAC7B,SAAS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,QAAQ,IAAI;AACvC,SAAS,OAAO;AACd,cAAY,KAAK;AACnB;","names":["readFileSync","join","join","version","join","rm","join","rm","TinyCloudNode","resolve","program","mkdir","readFile","writeFile","dirname","createInterface","randomBytes","readFile","join","join","randomBytes","readFile","readFile","node","createInterface","resolve","program","delegationCids","expiry","mkdir","dirname","writeFile","readFile","result","readFile","writeFile","readStdin","program","kv","writeFile","readFile","program","program","program","program","createInterface","program","createInterface","resolve","program","readFile","writeFile","PrivateKeySigner","readStdin","program","readFile","writeFile","readFile","writeFile","readStdin","program","writeFile","readFile","readFile","writeFile","readStdin","resolvePrivateKey","program","writeFile","readFile","program","writeFile","program","writeFile","readFile","writeFile","resolve","program","resolve","writeFile","readFile","readFile","program","readFile","execSync","readFileSync","readFileSync","execSync","program","program","parseDate","normalizeService","unique","date","readFileSync"]}
1
+ {"version":3,"sources":["../../../node_modules/ms/index.js","../src/index.ts","../src/output/errors.ts","../src/config/constants.ts","../src/output/formatter.ts","../src/output/theme.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/config/types.ts","../src/lib/sdk.ts","../src/lib/permissions.ts","../../sdk-core/src/manifest.ts","../../../node_modules/zod/v3/external.js","../../../node_modules/zod/v3/helpers/util.js","../../../node_modules/zod/v3/ZodError.js","../../../node_modules/zod/v3/locales/en.js","../../../node_modules/zod/v3/errors.js","../../../node_modules/zod/v3/helpers/parseUtil.js","../../../node_modules/zod/v3/helpers/errorUtil.js","../../../node_modules/zod/v3/types.js","../../sdk-services/src/types.ts","../../sdk-services/src/types.schema.ts","../../sdk-services/src/context.ts","../../sdk-services/src/errors.ts","../../sdk-services/src/base/BaseService.ts","../../sdk-services/src/kv/PrefixedKVService.ts","../../sdk-services/src/kv/types.ts","../../sdk-services/src/kv/KVService.ts","../../sdk-services/src/sql/DatabaseHandle.ts","../../sdk-services/src/sql/types.ts","../../sdk-services/src/sql/SQLService.ts","../../sdk-services/src/duckdb/DuckDbDatabaseHandle.ts","../../sdk-services/src/duckdb/types.ts","../../sdk-services/src/duckdb/DuckDbService.ts","../../sdk-services/src/hooks/HooksService.ts","../../sdk-services/src/quota/TinyCloudQuota.ts","../../sdk-services/src/vault/types.ts","../../sdk-services/src/vault/SignatureCache.ts","../../sdk-services/src/vault/DataVaultService.ts","../../sdk-services/src/vault/createVaultCrypto.ts","../../sdk-services/src/secrets/paths.ts","../../sdk-services/src/secrets/SecretsService.ts","../../sdk-services/src/encryption/canonical.ts","../../sdk-services/src/encryption/networkId.ts","../../sdk-services/src/encryption/types.ts","../../sdk-services/src/encryption/discovery.ts","../../sdk-services/src/encryption/envelope.ts","../../sdk-services/src/encryption/invocation.ts","../../sdk-services/src/encryption/receiverKey.ts","../../sdk-services/src/encryption/response.ts","../../sdk-services/src/encryption/EncryptionService.ts","../src/lib/space.ts","../src/commands/kv.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/manifest.ts","../src/commands/upgrade.ts","../src/commands/status.ts"],"sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","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 { registerManifestCommand } from \"./commands/manifest.js\";\nimport { registerUpgradeCommand } from \"./commands/upgrade.js\";\nimport { registerStatusCommand } from \"./commands/status.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\", \"status\"].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);\nregisterManifestCommand(program);\nregisterUpgradeCommand(program);\nregisterStatusCommand(program);\n\nprogram.addHelpText(\"before\", () => `${theme.label(\"Version:\")} ${theme.value(version)}\\n`);\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 secrets network init\")} ${theme.muted(\"Create the default secrets network\")}\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 { readFileSync, readdirSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { ExitCode, CONFIG_FILE, PROFILES_DIR, DEFAULT_PROFILE } from \"../config/constants.js\";\nimport { outputError } from \"./formatter.js\";\n\nlet activeProfileName: string | undefined;\n\n/** Recorded by ProfileManager.resolveContext so hints can name the right profile. */\nexport function setActiveProfileName(name: string): void {\n activeProfileName = name;\n}\n\nexport class CLIError extends Error {\n constructor(\n public code: string,\n message: string,\n public exitCode: number = ExitCode.ERROR,\n public metadata?: Record<string, unknown>,\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 const hint = buildAuthHint(cliError) ??\n (cliError.code === \"NETWORK_ERROR\" ? buildNetworkHint() : undefined);\n outputError(cliError.code, cliError.message, hint);\n process.exit(cliError.exitCode);\n}\n\nfunction buildAuthHint(error: CLIError): string | undefined {\n const resource = error.metadata?.resource;\n const requiredAction = error.metadata?.requiredAction;\n if (typeof resource !== \"string\" || typeof requiredAction !== \"string\") {\n return undefined;\n }\n\n const spec = capSpecFromAuthMeta(resource, requiredAction);\n if (!spec) return undefined;\n return [\n \"The active session is missing a TinyCloud capability.\",\n `Request it with: tc auth request --cap \"${spec}\"`,\n \"Then retry the original command.\",\n ].join(\"\\n\");\n}\n\nfunction capSpecFromAuthMeta(resource: string, action: string): string | undefined {\n const slash = resource.indexOf(\"/\");\n if (slash <= 0 || slash === resource.length - 1) return undefined;\n const spaceUri = resource.slice(0, slash);\n const rest = resource.slice(slash + 1);\n const nextSlash = rest.indexOf(\"/\");\n if (nextSlash <= 0) return undefined;\n\n const serviceShort = rest.slice(0, nextSlash);\n const path = rest.slice(nextSlash + 1);\n const actionName = action.includes(\"/\") ? action.slice(action.indexOf(\"/\") + 1) : action;\n const spaceName = spaceUri.startsWith(\"tinycloud:\")\n ? spaceUri.slice(spaceUri.lastIndexOf(\":\") + 1)\n : spaceUri;\n return `tinycloud.${serviceShort}:${spaceName}:${path}:${actionName}`;\n}\n\n/**\n * Suggests alternate profiles when the active profile's host is unreachable.\n * Sync fs reads keep handleError synchronous so call sites don't need to await.\n *\n * Silent fallback to a default host is intentionally NOT done: different hosts\n * back different data stores, so an automatic switch could split or clobber\n * user data without their knowledge.\n */\nfunction buildNetworkHint(): string | undefined {\n const readHost = (name: string): string | undefined => {\n try {\n const raw = readFileSync(join(PROFILES_DIR, name, \"profile.json\"), \"utf8\");\n return (JSON.parse(raw) as { host?: string }).host;\n } catch {\n return undefined;\n }\n };\n\n let activeName = activeProfileName ?? process.env.TC_PROFILE ?? DEFAULT_PROFILE;\n if (!activeProfileName) {\n try {\n const cfg = JSON.parse(readFileSync(CONFIG_FILE, \"utf8\")) as { defaultProfile?: string };\n activeName = process.env.TC_PROFILE ?? cfg.defaultProfile ?? DEFAULT_PROFILE;\n } catch {\n // Config file not present yet — fall through with env/default.\n }\n }\n\n let names: string[];\n try {\n names = readdirSync(PROFILES_DIR);\n } catch {\n return undefined;\n }\n\n const activeHost = readHost(activeName);\n const others = names\n .filter((n) => n !== activeName)\n .map((n) => ({ name: n, host: readHost(n) }))\n .filter((p): p is { name: string; host: string } => Boolean(p.host));\n\n const lines: string[] = [];\n lines.push(activeHost ? `Active profile \"${activeName}\" → ${activeHost}` : `Active profile \"${activeName}\"`);\n\n if (others.length === 0) {\n lines.push(`No other profiles configured. Run \\`tc profile create <name>\\` or \\`tc init\\`.`);\n } else {\n lines.push(`Switch to a reachable profile:`);\n const longest = Math.max(...others.map((p) => p.name.length));\n for (const { name, host } of others) {\n lines.push(` tc profile switch ${name.padEnd(longest)} # ${host}`);\n }\n }\n lines.push(`Or override per-command with --host or TC_HOST.`);\n return lines.join(\"\\n\");\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_OPENKEY_HOST = \"https://openkey.so\";\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, hint?: string): void {\n if (isInteractive()) {\n process.stderr.write(\n `${theme.error(\"✗\")} ${theme.label(code)}: ${message}\\n`\n );\n if (hint) {\n for (const line of hint.split(\"\\n\")) {\n process.stderr.write(` ${theme.hint(line)}\\n`);\n }\n }\n } else {\n const payload: { error: { code: string; message: string; hint?: string } } = {\n error: { code, message },\n };\n if (hint) payload.error.hint = hint;\n process.stderr.write(JSON.stringify(payload, null, 2) + \"\\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","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, setActiveProfileName } 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 setActiveProfileName(profile);\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, importKey, 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 const keyId = importKey(mgr, JSON.stringify(jwk), \"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 delegationHeader: { Authorization: string };\n delegationCid: string;\n jwk: object;\n verificationMethod: string;\n siwe?: string;\n signature?: string;\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 const session = node.session;\n if (!session) {\n throw new Error(\"Local key sign-in did not produce a TinyCloud session\");\n }\n\n return {\n spaceId: session.spaceId,\n address,\n chainId: 1,\n delegationHeader: session.delegationHeader,\n delegationCid: session.delegationCid,\n jwk: session.jwk,\n verificationMethod: session.verificationMethod,\n siwe: session.siwe,\n signature: session.signature,\n };\n}\n","import type { PermissionEntry } from \"@tinycloud/node-sdk\";\nimport { createServer, type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { isInteractive } from \"../output/formatter.js\";\nimport { createInterface } from \"node:readline\";\nimport { DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\n\ninterface DelegationData {\n delegationHeader: { Authorization: string };\n delegationCid: string;\n spaceId: string;\n [key: string]: unknown;\n}\n\ninterface AuthFlowOptions {\n paste?: boolean;\n noPopup?: boolean;\n jwk?: object;\n host?: string;\n permissions?: PermissionEntry[];\n /**\n * OpenKey base URL. Resolution order in callers: TC_OPENKEY_HOST env →\n * profile.openkeyHost → DEFAULT_OPENKEY_HOST. Threaded explicitly so this\n * module stays free of profile lookups.\n */\n openkeyHost?: string;\n /**\n * Lifetime hint for the resulting delegation. Encoded into the\n * `/delegate?expiry=<value>` URL parameter so OpenKey can sign for the\n * requested window instead of its hardcoded default. Forwarded as-is —\n * OpenKey does the parsing and clamping server-side.\n */\n expiry?: string | number;\n}\n\nconst PRIVATE_JWK_FIELDS = new Set([\n \"d\",\n \"p\",\n \"q\",\n \"dp\",\n \"dq\",\n \"qi\",\n \"oth\",\n \"k\",\n]);\n\nexport function publicJwkForDelegation(jwk: object): object {\n const publicJwk: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(jwk)) {\n if (!PRIVATE_JWK_FIELDS.has(key)) {\n publicJwk[key] = value;\n }\n }\n\n return publicJwk;\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: AuthFlowOptions = {}\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\nexport function buildAuthUrl(did: string, options: AuthFlowOptions & { 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(\n JSON.stringify(publicJwkForDelegation(options.jwk)),\n ).toString(\"base64url\");\n params.set(\"jwk\", jwkB64);\n }\n if (options.host) {\n params.set(\"host\", options.host);\n }\n if (options.permissions?.length) {\n params.set(\n \"permissions\",\n Buffer.from(JSON.stringify({ permissions: options.permissions })).toString(\"base64url\"),\n );\n }\n if (options.expiry !== undefined) {\n params.set(\"expiry\", String(options.expiry));\n }\n const base = options.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n return `${base}/delegate?${params.toString()}`;\n}\n\nfunction shouldOpenBrowser(options: AuthFlowOptions): boolean {\n if (options.noPopup) return false;\n const env = process.env.TC_AUTH_NO_POPUP ?? process.env.TC_NO_POPUP;\n return env !== \"1\" && env !== \"true\";\n}\n\nasync function callbackFlow(did: string, options: AuthFlowOptions = {}): 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 const openBrowser = shouldOpenBrowser(options);\n\n if (openBrowser && isInteractive()) {\n console.error(`Opening browser for authentication...`);\n console.error(`If the browser doesn't open, visit: ${authUrl}`);\n } else if (!openBrowser || isInteractive()) {\n console.error(`Open this URL in a browser to authenticate: ${authUrl}`);\n }\n\n if (openBrowser) {\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\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: AuthFlowOptions = {}): 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 .option(\"--no-popup\", \"Print the OpenKey URL without opening a browser\")\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 noPopup: options.popup === false,\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 ownerDid: delegationData.ownerDid 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 { get as httpGet } from \"node:http\";\nimport { get as httpsGet } from \"node:https\";\nimport { spawn } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { IncomingMessage } from \"node:http\";\nimport { principalDidEquals, type PermissionEntry, type PortableDelegation } from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { outputJson, shouldOutputJson, formatField, formatTable, isInteractive, withSpinner } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode, DEFAULT_CHAIN_ID, DEFAULT_OPENKEY_HOST } from \"../config/constants.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type AuthMethod,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Resolve the OpenKey base URL for a profile.\n * Order: TC_OPENKEY_HOST env override → profile.openkeyHost → default.\n *\n * No prompts, no migration. To use a self-hosted OpenKey for a profile,\n * edit `~/.tinycloud/profiles/<profile>/profile.json` and add an\n * \"openkeyHost\": \"https://openkey.localhost\" field.\n */\nfunction resolveOpenKeyHost(profile: ProfileConfig): string {\n return process.env.TC_OPENKEY_HOST ?? profile.openkeyHost ?? DEFAULT_OPENKEY_HOST;\n}\nimport { startAuthFlow } from \"../auth/browser-auth.js\";\nimport {\n generateLocalIdentity,\n deriveAddress,\n addressToDID,\n localKeySignIn,\n generateKey,\n keyToDID,\n} from \"../auth/local-key.js\";\nimport { theme } from \"../output/theme.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport {\n appendAdditionalDelegation,\n appendPermissionRequestArtifact,\n createPermissionRequestArtifact,\n getLastPermissionRequestArtifact,\n getPermissionRequestArtifact,\n isDelegationImportArtifact,\n isPermissionRequestArtifact,\n appendGrantHistory,\n compactPermission,\n loadAdditionalDelegations,\n loadManifestPermissions,\n loadPermissionRequest,\n parseCapSpec,\n permissionsFromDelegation,\n readGrantHistory,\n storedAdditionalDelegation,\n type PermissionRequestArtifact,\n} from \"../lib/permissions.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(\"--no-popup\", \"Print the OpenKey URL without opening a browser\")\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, {\n paste: options.paste,\n noPopup: options.popup === false,\n });\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(\"rotate\")\n .description(\"Rotate the active profile session key\")\n .option(\"--paste\", \"Use manual paste mode instead of browser callback\")\n .option(\"--no-popup\", \"Print the OpenKey URL without opening a browser\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n await rotateAuthKey(ctx.profile, ctx.host, {\n paste: options.paste,\n noPopup: options.popup === false,\n });\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 const posture = profile ? resolveProfilePosture(profile) : null;\n const operatorType = profile ? resolveProfileOperatorType(profile) : null;\n\n const authenticated = session !== null;\n\n if (shouldOutputJson()) {\n outputJson({\n authenticated,\n did: profile?.did ?? null,\n sessionDid: profile?.sessionDid ?? null,\n ownerDid: profile?.ownerDid ?? null,\n spaceId: profile?.spaceId ?? null,\n host: ctx.host,\n profile: ctx.profile,\n hasKey: hasKey !== null,\n authMethod: profile?.authMethod ?? null,\n posture,\n operatorType,\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(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\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(\"Session DID\", profile?.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile?.ownerDid ?? 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(\"request\")\n .description(\"Create a TinyCloud permission request artifact\")\n .option(\n \"--cap <spec>\",\n \"Capability spec: tinycloud.<service>:<space>:<path>:<actions-csv> (repeatable)\",\n (value, previous: string[]) => [...previous, value],\n [],\n )\n .option(\"--permission <file>\", \"JSON permission request: { \\\"permissions\\\": PermissionEntry[] }\")\n .option(\"--manifest <fileOrBase64>\", \"Manifest file, base64:<json>, or raw base64 JSON\")\n .option(\n \"--expiry <duration>\",\n \"Lifetime of the granted delegation. ms-format string (e.g. \\\"7d\\\", \\\"30m\\\") or raw milliseconds. Defaults to 7d, capped by the active session's expiry.\",\n )\n .option(\"--emit [file]\", \"Emit the request artifact to stdout, or write it to file when provided\")\n .option(\"--grant\", \"Grant the requested permissions immediately with this owner profile\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .option(\"--no-popup\", \"Print the OpenKey URL without opening a browser when granting with OpenKey\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const requested = await collectRequestedPermissions(options, ctx.profile);\n const expiryOption = parseExpiryOption(options.expiry);\n\n if (requested.length === 0) {\n throw new CLIError(\n \"NO_CAPS_REQUESTED\",\n \"Provide at least one --cap, --permission, or --manifest.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (!options.grant) {\n const artifact = createPermissionRequestArtifact({\n profileName: ctx.profile,\n profile,\n host: ctx.host,\n requested,\n requestedExpiry: expiryOption,\n });\n await appendPermissionRequestArtifact(ctx.profile, artifact);\n await emitPermissionRequestArtifact(artifact, options.emit);\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n\n // Fast path: master's grantRuntimePermissions / hasRuntimePermissions\n // already does the diff against the live session + existing runtime\n // grants; no need to compute it ourselves.\n if (node.hasRuntimePermissions(requested)) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n if (profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(ctx.profile);\n if (!key) {\n throw new CLIError(\"NO_KEY\", `No key found for profile \"${ctx.profile}\". Run \\`tc init\\` first.`, ExitCode.AUTH_REQUIRED);\n }\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n const openkeyHost = resolveOpenKeyHost(profile);\n for (const group of groupPermissionsBySpace(requested)) {\n const delegationData = await startAuthFlow(profile.did, {\n jwk: key,\n host: ctx.host,\n permissions: group,\n openkeyHost,\n expiry: expiryOption,\n noPopup: options.popup === false,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, ctx.host);\n const stored = storedAdditionalDelegation(delegation, group);\n await appendAdditionalDelegation(ctx.profile, stored);\n await node.useRuntimeDelegation(delegation);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: group,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n outputJson({\n changed: delegationCids.length > 0,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n return;\n }\n\n if (isInteractive()) {\n if (!options.yes) {\n await confirmPermissionRequest(requested);\n }\n } else if (!options.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key permission requests in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n // Local-key flow: master's grantRuntimePermissions handles signing\n // through the SDK's wallet-mode signer, groups by space, and skips\n // anything already covered by the session or an existing grant.\n const delegations = await node.grantRuntimePermissions(\n requested,\n expiryOption !== undefined ? { expiry: expiryOption } : undefined,\n );\n const delegationCids: string[] = [];\n let expiry: string | undefined;\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n const stored = storedAdditionalDelegation(delegation, covering);\n await appendAdditionalDelegation(ctx.profile, stored);\n delegationCids.push(delegation.cid);\n expiry = delegation.expiry.toISOString();\n await appendGrantHistory(ctx.profile, {\n addedCaps: covering,\n source: options.manifest ? \"manifest\" : \"cli\",\n delegationCid: delegation.cid,\n expiry,\n });\n }\n\n if (delegationCids.length === 0) {\n outputJson({ changed: false, missing: [], added: [] });\n return;\n }\n\n outputJson({\n changed: true,\n added: requested,\n delegationCid: delegationCids[0],\n delegationCids,\n expiry,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"import [source]\")\n .description(\"Import a TinyCloud delegation or permission request artifact\")\n .option(\"--stdin\", \"Read the JSON artifact from stdin\")\n .option(\"--paste\", \"Read the JSON artifact from stdin\")\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (isPermissionRequestArtifact(parsed)) {\n await appendPermissionRequestArtifact(ctx.profile, parsed);\n outputJson({\n imported: true,\n kind: parsed.kind,\n requestId: parsed.requestId,\n requested: parsed.requested,\n next: `tc auth retry ${parsed.requestId}`,\n });\n return;\n }\n\n const imported = normalizeDelegationImport(parsed);\n const node = await ensureAuthenticated(ctx);\n await appendAdditionalDelegation(ctx.profile, storedAdditionalDelegation(\n imported.delegation,\n imported.permissions,\n ));\n\n // A delegation whose audience is this profile's own session key can be\n // installed as a runtime grant (useRuntimeDelegation activates it for\n // matching service calls). A cross-user delegation — audience is this\n // profile's stable identity DID or another principal — cannot: the node\n // rejects runtime delegations that don't target the session key. Persist\n // it and let the read path activate it via useDelegation in wallet mode.\n const targetsSessionKey =\n typeof imported.delegation.delegateDID === \"string\" &&\n principalDidEquals(imported.delegation.delegateDID, node.sessionDid);\n let activated = false;\n if (targetsSessionKey) {\n await node.useRuntimeDelegation(imported.delegation);\n activated = true;\n }\n await appendGrantHistory(ctx.profile, {\n addedCaps: imported.permissions,\n source: \"cli\",\n delegationCid: imported.delegation.cid,\n expiry: imported.delegation.expiry.toISOString(),\n });\n\n outputJson({\n imported: true,\n activated,\n kind: \"tinycloud.auth.delegation\",\n requestId: imported.requestId ?? null,\n delegationCid: imported.delegation.cid,\n permissions: imported.permissions,\n expiry: imported.delegation.expiry.toISOString(),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"grant [request]\")\n .description(\"Grant a TinyCloud permission request artifact to its requester\")\n .option(\"--stdin\", \"Read the JSON request artifact from stdin\")\n .option(\"--paste\", \"Read the JSON request artifact from stdin\")\n .option(\"--yes\", \"Skip local-key TTY confirmation\", false)\n .action(async (source: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const profile = await ProfileManager.getProfile(ctx.profile);\n const raw = await readAuthArtifactSource(source, {\n stdin: options.stdin === true || options.paste === true,\n });\n const parsed = JSON.parse(raw) as unknown;\n\n if (!isPermissionRequestArtifact(parsed)) {\n throw new CLIError(\n \"INVALID_AUTH_REQUEST\",\n \"Auth grant requires a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n await ensureDelegationAuthority({\n ctx,\n profile,\n node,\n requested: parsed.requested,\n expiryOption: parsed.requestedExpiry,\n yes: options.yes === true,\n });\n const result = await node.delegateTo(\n parsed.sessionDid,\n parsed.requested,\n parsed.requestedExpiry !== undefined\n ? { expiry: parsed.requestedExpiry }\n : undefined,\n );\n\n outputJson({\n kind: \"tinycloud.auth.delegation\",\n version: 1,\n requestId: parsed.requestId,\n delegationCid: result.delegation.cid,\n delegation: result.delegation,\n permissions: parsed.requested,\n expiry: result.delegation.expiry.toISOString(),\n prompted: result.prompted,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"retry [requestId]\")\n .description(\"Check whether a stored permission request is now satisfied\")\n .option(\"--last\", \"Use the latest stored permission request for this profile\")\n .option(\"--exec\", \"Run the captured command when the request is covered\")\n .action(async (requestId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const artifact = options.last\n ? await getLastPermissionRequestArtifact(ctx.profile)\n : requestId\n ? await getPermissionRequestArtifact(ctx.profile, requestId)\n : null;\n\n if (!artifact) {\n throw new CLIError(\n \"REQUEST_NOT_FOUND\",\n options.last\n ? `No stored permission requests exist for profile \"${ctx.profile}\".`\n : \"Provide a requestId or use --last.\",\n ExitCode.NOT_FOUND,\n );\n }\n\n const node = await ensureAuthenticated(ctx);\n const covered = node.hasRuntimePermissions(artifact.requested);\n if (options.exec) {\n if (!covered) {\n throw new CLIError(\n \"PERMISSIONS_MISSING\",\n `Request ${artifact.requestId} is not covered yet. Import a delegation, then retry with --exec.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n if (!artifact.command?.argv?.length) {\n throw new CLIError(\n \"COMMAND_NOT_CAPTURED\",\n `Request ${artifact.requestId} does not include a captured command.`,\n ExitCode.USAGE_ERROR,\n );\n }\n await execCapturedCommand(artifact.command);\n return;\n }\n\n outputJson({\n requestId: artifact.requestId,\n covered,\n missing: covered ? [] : artifact.requested,\n command: artifact.command ?? null,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n auth\n .command(\"caps\")\n .description(\"Show granted capabilities for the active session\")\n .option(\"--diff <spec>\", \"Show missing capabilities for a spec\")\n .option(\"--history\", \"Show recent permission grants\")\n .action(async (options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n if (options.history) {\n const history = (await readGrantHistory(ctx.profile)).slice(-20);\n if (shouldOutputJson()) {\n outputJson({ grants: history });\n } else if (history.length === 0) {\n process.stdout.write(theme.muted(\"No grant history.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"time\", \"source\", \"delegation\", \"caps\"],\n history.map((entry) => [\n entry.ts,\n entry.source,\n entry.delegationCid ?? \"\",\n entry.addedCaps.map(compactPermission).join(\"; \"),\n ]),\n ) + \"\\n\");\n }\n return;\n }\n\n const node = await ensureAuthenticated(ctx);\n const runtimeDelegations = node.getRuntimePermissionDelegations();\n // Granted view = permissions covered by appended runtime delegations.\n // The base-session SIWE recap isn't enumerated here because the\n // node-sdk doesn't expose it as a list — `hasRuntimePermissions()`\n // is the trusted answer for \"is this covered?\".\n const granted = runtimeDelegations.flatMap(permissionsFromDelegation);\n\n if (options.diff) {\n const requested = [await parseCapSpec(options.diff, ctx.profile)];\n const covered = node.hasRuntimePermissions(requested);\n outputJson({\n requested,\n changed: !covered,\n covered,\n // `missing` retained for backwards-compatible callers.\n missing: covered ? [] : requested,\n });\n return;\n }\n\n const appended = await loadAdditionalDelegations(ctx.profile);\n if (shouldOutputJson()) {\n outputJson({ granted, appendedDelegations: appended.length });\n } else if (granted.length === 0) {\n process.stdout.write(theme.muted(\"No appended runtime delegations on this profile.\") + \"\\n\");\n } else {\n process.stdout.write(formatTable(\n [\"service\", \"space\", \"path\", \"actions\"],\n granted.map((entry) => [\n entry.service,\n entry.space,\n entry.path,\n entry.actions.join(\", \"),\n ]),\n ) + \"\\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 const posture = resolveProfilePosture(profile);\n const operatorType = resolveProfileOperatorType(profile);\n\n if (shouldOutputJson()) {\n outputJson({\n profile: ctx.profile,\n did: profile.did,\n sessionDid: profile.sessionDid ?? null,\n ownerDid: profile.ownerDid ?? null,\n spaceId: profile.spaceId ?? null,\n host: profile.host,\n authenticated,\n authMethod: profile.authMethod ?? null,\n posture,\n operatorType,\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(\"Session DID\", profile.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Owner DID\", profile.ownerDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Auth Method\", profile.authMethod ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\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\nasync function emitPermissionRequestArtifact(\n artifact: PermissionRequestArtifact,\n emitOption: unknown,\n): Promise<void> {\n if (typeof emitOption === \"string\" && emitOption.length > 0) {\n await mkdir(dirname(emitOption), { recursive: true });\n await writeFile(emitOption, JSON.stringify(artifact, null, 2) + \"\\n\", \"utf8\");\n outputJson({\n emitted: true,\n path: emitOption,\n requestId: artifact.requestId,\n requested: artifact.requested,\n });\n return;\n }\n outputJson(artifact);\n}\n\nasync function readAuthArtifactSource(\n source: string | undefined,\n options: { stdin: boolean },\n): Promise<string> {\n if (options.stdin || source === \"-\" || (!source && !isInteractive())) {\n return readStdin();\n }\n\n if (!source) {\n throw new CLIError(\n \"IMPORT_SOURCE_REQUIRED\",\n \"Provide an artifact file, URL, or use --stdin.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (source.startsWith(\"http://\") || source.startsWith(\"https://\")) {\n return readUrl(source);\n }\n\n return readFile(source, \"utf8\");\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction readUrl(source: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const getter = source.startsWith(\"https://\") ? httpsGet : httpGet;\n const request = getter(source, (response: IncomingMessage) => {\n const status = response.statusCode ?? 0;\n if (status >= 300 && status < 400 && response.headers.location) {\n response.resume();\n readUrl(new URL(response.headers.location, source).toString()).then(resolve, reject);\n return;\n }\n if (status < 200 || status >= 300) {\n response.resume();\n reject(new CLIError(\n \"IMPORT_FETCH_FAILED\",\n `Failed to fetch ${source}: HTTP ${status}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n\n const chunks: Buffer[] = [];\n response.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n response.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n });\n request.on(\"error\", reject);\n });\n}\n\nfunction normalizeDelegationImport(value: unknown): {\n requestId?: string;\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n} {\n if (isDelegationImportArtifact(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n requestId: value.requestId,\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isStoredDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value.delegation);\n return {\n delegation,\n permissions: Array.isArray(value.permissions) && value.permissions.length > 0\n ? value.permissions\n : permissionsFromDelegation(delegation),\n };\n }\n\n if (isPortableDelegationLike(value)) {\n const delegation = normalizePortableDelegation(value);\n return {\n delegation,\n permissions: permissionsFromDelegation(delegation),\n };\n }\n\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Auth import must be a tinycloud.auth.delegation artifact, a portable delegation, or a tinycloud.auth.request artifact.\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction isStoredDelegationLike(value: unknown): value is {\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n} {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as { delegation?: unknown };\n return isPortableDelegationLike(candidate.delegation);\n}\n\nfunction isPortableDelegationLike(value: unknown): value is PortableDelegation {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PortableDelegation>;\n return (\n typeof candidate.cid === \"string\" &&\n typeof candidate.spaceId === \"string\" &&\n typeof candidate.path === \"string\" &&\n Array.isArray(candidate.actions) &&\n candidate.delegationHeader !== undefined &&\n typeof candidate.delegationHeader === \"object\"\n );\n}\n\nfunction normalizePortableDelegation(delegation: PortableDelegation): PortableDelegation {\n const rawExpiry = (delegation as PortableDelegation & { expiry: unknown }).expiry;\n const expiry = rawExpiry instanceof Date ? rawExpiry : new Date(String(rawExpiry));\n if (Number.isNaN(expiry.getTime())) {\n throw new CLIError(\n \"INVALID_AUTH_IMPORT\",\n \"Imported delegation must include a valid expiry.\",\n ExitCode.USAGE_ERROR,\n );\n }\n return { ...delegation, expiry };\n}\n\nexport async function ensureDelegationAuthority(params: {\n ctx: { profile: string; host: string };\n profile: ProfileConfig;\n node: Awaited<ReturnType<typeof ensureAuthenticated>>;\n requested: PermissionEntry[];\n expiryOption: string | number | undefined;\n yes: boolean;\n force?: boolean;\n}): Promise<void> {\n if (!params.force && params.node.hasRuntimePermissions(params.requested)) return;\n\n if (params.profile.authMethod === \"openkey\") {\n const key = await ProfileManager.getKey(params.ctx.profile);\n if (!key) {\n throw new CLIError(\n \"NO_KEY\",\n `No key found for profile \"${params.ctx.profile}\". Run \\`tc init\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n const openkeyHost = resolveOpenKeyHost(params.profile);\n for (const group of groupPermissionsBySpace(params.requested)) {\n const delegationData = await startAuthFlow(params.profile.did, {\n jwk: key,\n host: params.ctx.host,\n permissions: group,\n openkeyHost,\n expiry: params.expiryOption,\n });\n const delegation = portableFromOpenKeyDelegation(delegationData, group, params.ctx.host);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, group),\n );\n await params.node.useRuntimeDelegation(delegation);\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: group,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n return;\n }\n\n if (isInteractive()) {\n if (!params.yes) {\n await confirmPermissionRequest(params.requested);\n }\n } else if (!params.yes) {\n throw new CLIError(\n \"CONFIRMATION_REQUIRED\",\n \"Local-key auth grants in non-interactive mode require --yes.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const delegations = await params.node.grantRuntimePermissions(\n params.requested,\n params.expiryOption !== undefined ? { expiry: params.expiryOption } : undefined,\n );\n for (const delegation of delegations) {\n const covering = permissionsFromDelegation(delegation);\n await appendAdditionalDelegation(\n params.ctx.profile,\n storedAdditionalDelegation(delegation, covering),\n );\n await appendGrantHistory(params.ctx.profile, {\n addedCaps: covering,\n source: \"cli\",\n delegationCid: delegation.cid,\n expiry: delegation.expiry.toISOString(),\n });\n }\n}\n\nfunction execCapturedCommand(command: { argv: string[]; cwd: string }): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [process.argv[1], ...command.argv], {\n cwd: command.cwd,\n env: process.env,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code, signal) => {\n if (signal) {\n reject(new CLIError(\n \"COMMAND_SIGNAL\",\n `Captured command exited from signal ${signal}.`,\n ExitCode.ERROR,\n ));\n return;\n }\n if (code && code !== 0) {\n process.exitCode = code;\n }\n resolve();\n });\n });\n}\n\nasync function collectRequestedPermissions(\n options: {\n cap?: string[];\n permission?: string;\n manifest?: string;\n },\n profile: string,\n): Promise<PermissionEntry[]> {\n const permissions: PermissionEntry[] = [];\n for (const spec of options.cap ?? []) {\n permissions.push(await parseCapSpec(spec, profile));\n }\n if (options.permission) {\n permissions.push(...await loadPermissionRequest(options.permission, profile));\n }\n if (options.manifest) {\n permissions.push(...await loadManifestPermissions(options.manifest, profile));\n }\n return permissions;\n}\n\nasync function confirmPermissionRequest(permissions: PermissionEntry[]): Promise<void> {\n process.stderr.write(\"\\n\" + theme.heading(\"Additional Permissions\") + \"\\n\");\n for (const permission of permissions) {\n const dangerous = isDangerousPermission(permission);\n const line = ` ${compactPermission(permission)}`;\n process.stderr.write((dangerous ? theme.warn(line) : theme.value(line)) + \"\\n\");\n }\n process.stderr.write(\"\\n\");\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stderr,\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(\"Approve local-key delegation? [y/N] \", resolve);\n });\n rl.close();\n\n if (!/^y(es)?$/i.test(answer.trim())) {\n throw new CLIError(\"REQUEST_CANCELLED\", \"Permission request cancelled.\", ExitCode.ERROR);\n }\n}\n\nfunction isDangerousPermission(permission: PermissionEntry): boolean {\n if (permission.path === \"\" || permission.path === \"/\") return true;\n return permission.actions.some((action) =>\n action.includes(\"*\") ||\n action.endsWith(\"/write\") ||\n action.endsWith(\"/admin\") ||\n action.endsWith(\"/ddl\") ||\n action.endsWith(\"/del\"),\n );\n}\n\n/**\n * Parse the `--expiry` flag into either a ms-format string (\"7d\", \"30m\") or\n * raw milliseconds. Returns undefined for missing input so the caller falls\n * back to the SDK's DEFAULT_DELEGATION_EXPIRY_MS.\n *\n * Pure-numeric strings are coerced to numbers so a shell-quoted ms count\n * (`--expiry 86400000`) works, but anything that contains a unit suffix\n * (`\"7d\"`, `\"30m\"`) is forwarded as-is to parseExpiry which understands\n * the ms-format vocabulary.\n */\nfunction parseExpiryOption(raw: unknown): string | number | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new CLIError(\n \"INVALID_EXPIRY\",\n `--expiry must be a string (e.g. \"7d\", \"30m\") or a millisecond integer.`,\n ExitCode.USAGE_ERROR,\n );\n }\n if (/^\\d+$/.test(raw.trim())) {\n const ms = Number(raw.trim());\n if (!Number.isFinite(ms) || ms <= 0) {\n throw new CLIError(\"INVALID_EXPIRY\", `--expiry must be a positive integer when numeric.`, ExitCode.USAGE_ERROR);\n }\n return ms;\n }\n return raw;\n}\n\nfunction groupPermissionsBySpace(permissions: PermissionEntry[]): PermissionEntry[][] {\n const groups = new Map<string, PermissionEntry[]>();\n const rawEntries: PermissionEntry[] = [];\n for (const permission of permissions) {\n if (isRawPermission(permission)) {\n rawEntries.push(permission);\n continue;\n }\n const group = groups.get(permission.space) ?? [];\n group.push(permission);\n groups.set(permission.space, group);\n }\n const grouped = Array.from(groups.values());\n if (grouped.length === 0) {\n return rawEntries.length > 0 ? [rawEntries] : [];\n }\n grouped[0].push(...rawEntries);\n return grouped;\n}\n\nfunction isRawPermission(permission: PermissionEntry): boolean {\n return permission.service === \"tinycloud.encryption\" &&\n permission.path.startsWith(\"urn:tinycloud:encryption:\");\n}\n\nfunction returnedSpaceMatchesExpected(returnedSpace: string, expectedSpace: string): boolean {\n if (returnedSpace === expectedSpace) return true;\n\n if (!returnedSpace.startsWith(\"tinycloud:\")) return false;\n const returnedName = returnedSpace.slice(returnedSpace.lastIndexOf(\":\") + 1);\n return returnedName === expectedSpace;\n}\n\nfunction portableFromOpenKeyDelegation(\n data: Record<string, unknown>,\n permissions: PermissionEntry[],\n host: string,\n): PortableDelegation {\n const primary = permissions.find((permission) => !isRawPermission(permission)) ?? permissions[0];\n const returnedSpace = String(data.spaceId ?? primary.space ?? \"encryption\");\n const expectedSpaces = new Set(\n permissions\n .filter((permission) => !isRawPermission(permission))\n .map((permission) => permission.space),\n );\n const matchesExpectedSpace = expectedSpaces.size === 1 &&\n returnedSpaceMatchesExpected(returnedSpace, Array.from(expectedSpaces)[0]!);\n if (expectedSpaces.size > 0 && !matchesExpectedSpace) {\n throw new CLIError(\n \"OPENKEY_SCOPE_MISMATCH\",\n `OpenKey returned delegation for ${returnedSpace}, expected ${Array.from(expectedSpaces).join(\", \")}.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n const expiry = inferDelegationExpiry(data);\n return {\n cid: String(data.delegationCid),\n delegationHeader: data.delegationHeader as { Authorization: string },\n spaceId: returnedSpace,\n path: primary.path,\n actions: primary.actions,\n resources: permissions.map((permission) => ({\n service: permission.service.startsWith(\"tinycloud.\")\n ? permission.service.slice(\"tinycloud.\".length)\n : permission.service,\n space: isRawPermission(permission) ? permission.space : returnedSpace,\n path: permission.path,\n actions: [...permission.actions],\n })),\n expiry,\n delegateDID: String(data.verificationMethod),\n ownerAddress: String(data.address ?? \"\"),\n chainId: typeof data.chainId === \"number\" ? data.chainId : DEFAULT_CHAIN_ID,\n host,\n };\n}\n\nfunction inferDelegationExpiry(data: Record<string, unknown>): Date {\n const direct = data.expiry ?? data.expiresAt;\n if (typeof direct === \"string\") {\n const parsed = new Date(direct);\n if (!Number.isNaN(parsed.getTime())) return parsed;\n }\n return new Date(Date.now() + 60 * 60 * 1000);\n}\n\nasync function rotateAuthKey(\n profileName: string,\n host: string,\n options: { paste?: boolean; noPopup?: boolean } = {},\n): Promise<void> {\n const profile = await ProfileManager.getProfile(profileName);\n const posture = resolveProfilePosture(profile);\n const oldDid = profile.sessionDid ?? profile.did;\n\n if (posture === \"delegate-session\") {\n throw new CLIError(\n \"ROTATE_DELEGATE_SESSION_UNSUPPORTED\",\n `Profile \"${profileName}\" is a delegated session. Request or import a new owner delegation instead of rotating it locally.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n\n if (profile.authMethod === \"local\" || posture === \"local-owner-key\") {\n if (!profile.privateKey) {\n throw new CLIError(\n \"LOCAL_OWNER_KEY_REQUIRED\",\n `Profile \"${profileName}\" does not have a local owner private key. Run \\`tc auth login --method local\\` first.`,\n ExitCode.AUTH_REQUIRED,\n );\n }\n\n await ProfileManager.clearSession(profileName);\n const result = await handleLocalAuth(profileName, host, {\n emitOutput: false,\n forceSessionKey: true,\n });\n outputRotationResult(result.profile, profileName, oldDid, \"local\");\n return;\n }\n\n const { jwk, did } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n\n await ProfileManager.setKey(profileName, jwk);\n await ProfileManager.clearSession(profileName);\n await ProfileManager.setProfile(profileName, {\n ...profile,\n host,\n did,\n sessionDid: did,\n posture: profile.posture ?? \"owner-openkey\",\n operatorType: profile.operatorType ?? \"human\",\n authMethod: \"openkey\",\n });\n\n const result = await refreshOpenKeySession(profileName, host, {\n paste: options.paste,\n noPopup: options.noPopup,\n });\n outputRotationResult(result.profile, profileName, oldDid, \"openkey\");\n}\n\nfunction outputRotationResult(\n profile: ProfileConfig,\n profileName: string,\n oldDid: string,\n authMethod: AuthMethod,\n): void {\n outputJson({\n rotated: true,\n profile: profileName,\n oldDid,\n did: profile.did,\n sessionDid: profile.sessionDid ?? null,\n authMethod,\n spaceId: profile.spaceId ?? null,\n });\n}\n\ntype LocalAuthResult = {\n profile: ProfileConfig;\n sessionResult: Awaited<ReturnType<typeof localKeySignIn>>;\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(\n profileName: string,\n host: string,\n options: { emitOutput?: boolean; forceSessionKey?: boolean } = {},\n): Promise<LocalAuthResult> {\n const profile = await ProfileManager.getProfile(profileName).catch(() => null);\n const posture = profile ? resolveProfilePosture(profile) : null;\n\n let privateKey: string;\n let address: string;\n let did: string;\n let sessionDid = profile?.sessionDid;\n\n if ((profile?.authMethod === \"local\" || posture === \"local-owner-key\") && profile.privateKey) {\n // Reuse existing local key\n privateKey = profile.privateKey;\n address = profile.address ?? await deriveAddress(privateKey);\n did = profile.did.startsWith(\"did:pkh:\")\n ? profile.did\n : addressToDID(address, profile.chainId ?? DEFAULT_CHAIN_ID);\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 (options.forceSessionKey || !hasKey) {\n const { jwk, did: generatedSessionDid } = await withSpinner(\"Generating session key...\", async () => {\n return generateKey();\n });\n await ProfileManager.setKey(profileName, jwk);\n sessionDid = generatedSessionDid;\n } else if (!sessionDid) {\n sessionDid = keyToDID(hasKey);\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 delegationHeader: sessionResult.delegationHeader,\n delegationCid: sessionResult.delegationCid,\n jwk: sessionResult.jwk,\n verificationMethod: sessionResult.verificationMethod,\n siwe: sessionResult.siwe,\n signature: sessionResult.signature,\n });\n sessionDid = sessionResult.verificationMethod;\n\n // Update profile\n const updatedProfile = {\n ...profile,\n name: profileName,\n host,\n chainId: DEFAULT_CHAIN_ID,\n spaceName: \"default\",\n did,\n sessionDid,\n ownerDid: did,\n spaceId: sessionResult.spaceId,\n createdAt: profile?.createdAt ?? new Date().toISOString(),\n posture: profile?.posture ?? \"local-owner-key\",\n operatorType: profile?.operatorType ?? \"human\",\n authMethod: \"local\",\n privateKey,\n address,\n } satisfies ProfileConfig;\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n if (options.emitOutput ?? true) {\n outputJson({\n authenticated: true,\n profile: profileName,\n did,\n sessionDid,\n address,\n spaceId: sessionResult.spaceId,\n authMethod: \"local\",\n });\n }\n\n return { profile: updatedProfile, sessionResult };\n}\n\n/**\n * Handle OpenKey (browser-based) authentication.\n * This is the original auth flow.\n */\nasync function handleOpenKeyAuth(\n profileName: string,\n host: string,\n options: { paste?: boolean; noPopup?: boolean } = {},\n): Promise<void> {\n const { profile, delegationData } = await refreshOpenKeySession(profileName, host, options);\n\n outputJson({\n authenticated: true,\n profile: profileName,\n did: profile.did,\n spaceId: delegationData.spaceId,\n authMethod: \"openkey\",\n });\n}\n\nexport async function refreshOpenKeySession(\n profileName: string,\n host: string,\n options: { paste?: boolean; noPopup?: boolean } = {},\n): Promise<{ profile: ProfileConfig; delegationData: Record<string, unknown> }> {\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: options.paste,\n noPopup: options.noPopup,\n jwk: key,\n host,\n openkeyHost: resolveOpenKeyHost(profile),\n });\n\n // Store session\n await ProfileManager.setSession(profileName, delegationData);\n\n // Update profile with owner DID if present\n const updatedProfile = {\n ...profile,\n sessionDid: profile.sessionDid ?? profile.did,\n posture: profile.posture ?? \"owner-openkey\",\n operatorType: profile.operatorType ?? \"human\",\n authMethod: \"openkey\" as const,\n };\n\n if (delegationData.spaceId) {\n updatedProfile.spaceId = delegationData.spaceId;\n updatedProfile.ownerDid = delegationData.ownerDid as string | undefined;\n }\n\n await ProfileManager.setProfile(profileName, updatedProfile);\n\n return { profile: updatedProfile, delegationData };\n}\n","export interface GlobalConfig {\n defaultProfile: string;\n version: number;\n}\n\nexport type AuthMethod = \"openkey\" | \"local\";\n\nexport const CLI_PROFILE_POSTURES = [\n \"owner-openkey\",\n \"delegate-session\",\n \"local-owner-key\",\n] as const;\n\nexport type CLIProfilePosture = typeof CLI_PROFILE_POSTURES[number];\n\nexport const CLI_OPERATOR_TYPES = [\"human\", \"agent\"] as const;\n\nexport type CLIOperatorType = typeof CLI_OPERATOR_TYPES[number];\n\nexport function isCLIProfilePosture(value: unknown): value is CLIProfilePosture {\n return typeof value === \"string\" && CLI_PROFILE_POSTURES.includes(value as CLIProfilePosture);\n}\n\nexport function isCLIOperatorType(value: unknown): value is CLIOperatorType {\n return typeof value === \"string\" && CLI_OPERATOR_TYPES.includes(value as CLIOperatorType);\n}\n\nexport function resolveProfilePosture(profile: {\n posture?: unknown;\n authMethod?: AuthMethod;\n}): CLIProfilePosture {\n if (isCLIProfilePosture(profile.posture)) return profile.posture;\n if (profile.authMethod === \"local\") return \"local-owner-key\";\n return \"owner-openkey\";\n}\n\nexport function resolveProfileOperatorType(profile: {\n operatorType?: unknown;\n}): CLIOperatorType {\n if (isCLIOperatorType(profile.operatorType)) return profile.operatorType;\n return \"human\";\n}\n\nexport interface ProfileConfig {\n name: string;\n host: string;\n chainId: number;\n spaceName: string;\n did: string;\n sessionDid?: string;\n ownerDid?: string;\n spaceId?: string;\n createdAt: string;\n posture?: CLIProfilePosture;\n operatorType?: CLIOperatorType;\n authMethod?: AuthMethod;\n /** Hex-encoded Ethereum private key (only present when authMethod is \"local\") */\n privateKey?: string;\n /** Ethereum address derived from privateKey (only present when authMethod is \"local\") */\n address?: string;\n /**\n * Optional OpenKey host override. Used for testing accounts or running\n * against a self-hosted OpenKey (e.g. https://openkey.localhost). Falls\n * back to DEFAULT_OPENKEY_HOST when unset. Edit profile.json directly\n * to change.\n */\n openkeyHost?: string;\n}\n\nexport interface CLIContext {\n profile: string;\n host: string;\n verbose: boolean;\n noCache: boolean;\n quiet: boolean;\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\";\nimport { replayAdditionalDelegations } from \"./permissions.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: prefer the persisted TinyCloud session so the CLI\n // keeps the same session key DID across request/grant/import flows.\n const node = new TinyCloudNode({\n host: ctx.host,\n privateKey: effectivePrivateKey,\n });\n\n if (session && session.delegationHeader && session.delegationCid && session.spaceId) {\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.sessionDid ?? profile.did,\n address: session.address as string | undefined,\n chainId: session.chainId as number | undefined,\n siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n } else {\n await node.signIn();\n }\n await replayAdditionalDelegations(node, ctx.profile);\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 siwe: session.siwe as string | undefined,\n signature: session.signature as string | undefined,\n });\n }\n\n await replayAdditionalDelegations(node, ctx.profile);\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 { randomBytes } from \"node:crypto\";\nimport { appendFile, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n expandActionShortNames,\n resolveManifest,\n} from \"../../../sdk-core/src/manifest.js\";\nimport { isCapabilitySubset } from \"../../../sdk-core/src/capabilities.js\";\nimport {\n type PermissionEntry,\n type PortableDelegation,\n type TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\nimport { PROFILES_DIR } from \"../config/constants.js\";\nimport { fileExists, readJson, writeJson, ensureDir } from \"../config/storage.js\";\nimport { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { resolveSpaceUri } from \"./space.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n type ProfileConfig,\n} from \"../config/types.js\";\n\n/**\n * Stored shape for a runtime delegation appended to a profile.\n * `permissions` mirrors the request that produced this delegation so\n * `tc auth caps` can surface the originally-asked-for entries even after\n * the delegation has been baked into a recap.\n */\nexport interface StoredAdditionalDelegation {\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n}\n\nexport interface GrantHistoryEntry {\n ts: string;\n profile: string;\n addedCaps: PermissionEntry[];\n source: \"cli\" | \"401-hint\" | \"manifest\";\n delegationCid?: string;\n expiry?: string;\n}\n\nexport interface PermissionRequestArtifact {\n kind: \"tinycloud.auth.request\";\n version: 1;\n requestId: string;\n createdAt: string;\n profile: string;\n posture: CLIProfilePosture;\n operatorType: CLIOperatorType;\n host: string;\n sessionDid: string;\n ownerDid?: string;\n spaceId?: string;\n requestedExpiry?: string | number;\n requested: PermissionEntry[];\n command?: {\n argv: string[];\n cwd: string;\n };\n}\n\nexport interface DelegationImportArtifact {\n kind: \"tinycloud.auth.delegation\";\n version: 1;\n requestId?: string;\n delegation: PortableDelegation;\n permissions?: PermissionEntry[];\n}\n\nexport function additionalDelegationsPath(profile: string): string {\n // Sibling file keeps legacy session.json schema unchanged for existing readers.\n return join(PROFILES_DIR, profile, \"additional-delegations.json\");\n}\n\nexport function permissionRequestsPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-requests.json\");\n}\n\nexport function grantHistoryPath(profile: string): string {\n return join(PROFILES_DIR, profile, \"auth-grants.jsonl\");\n}\n\nexport function createPermissionRequestArtifact(params: {\n profileName: string;\n profile: ProfileConfig;\n host: string;\n requested: PermissionEntry[];\n requestedExpiry?: string | number;\n argv?: string[];\n cwd?: string;\n}): PermissionRequestArtifact {\n return {\n kind: \"tinycloud.auth.request\",\n version: 1,\n requestId: `req_${Date.now().toString(36)}_${randomBytes(4).toString(\"hex\")}`,\n createdAt: new Date().toISOString(),\n profile: params.profileName,\n posture: resolveProfilePosture(params.profile),\n operatorType: resolveProfileOperatorType(params.profile),\n host: params.host,\n sessionDid: didWithoutFragment(params.profile.sessionDid ?? params.profile.did),\n ownerDid: params.profile.ownerDid,\n spaceId: params.profile.spaceId,\n requestedExpiry: params.requestedExpiry,\n requested: params.requested,\n command: {\n argv: params.argv ?? process.argv.slice(2),\n cwd: params.cwd ?? process.cwd(),\n },\n };\n}\n\nfunction didWithoutFragment(did: string): string {\n const fragment = did.indexOf(\"#\");\n return fragment === -1 ? did : did.slice(0, fragment);\n}\n\nexport async function loadAdditionalDelegations(\n profile: string,\n): Promise<StoredAdditionalDelegation[]> {\n const raw = await readJson<StoredAdditionalDelegation[]>(\n additionalDelegationsPath(profile),\n );\n return Array.isArray(raw) ? raw : [];\n}\n\nexport async function saveAdditionalDelegations(\n profile: string,\n entries: StoredAdditionalDelegation[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(additionalDelegationsPath(profile), entries);\n}\n\nexport async function appendAdditionalDelegation(\n profile: string,\n entry: StoredAdditionalDelegation,\n): Promise<void> {\n const existing = await loadAdditionalDelegations(profile);\n const next = existing.filter((item) => item.delegation.cid !== entry.delegation.cid);\n next.push(entry);\n await saveAdditionalDelegations(profile, next);\n}\n\nexport async function loadPermissionRequestArtifacts(\n profile: string,\n): Promise<PermissionRequestArtifact[]> {\n const raw = await readJson<PermissionRequestArtifact[]>(\n permissionRequestsPath(profile),\n );\n return Array.isArray(raw) ? raw.filter(isPermissionRequestArtifact) : [];\n}\n\nexport async function savePermissionRequestArtifacts(\n profile: string,\n entries: PermissionRequestArtifact[],\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n await writeJson(permissionRequestsPath(profile), entries);\n}\n\nexport async function appendPermissionRequestArtifact(\n profile: string,\n artifact: PermissionRequestArtifact,\n): Promise<void> {\n const existing = await loadPermissionRequestArtifacts(profile);\n const next = existing.filter((item) => item.requestId !== artifact.requestId);\n next.push(artifact);\n await savePermissionRequestArtifacts(profile, next);\n}\n\nexport async function getPermissionRequestArtifact(\n profile: string,\n requestId: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.find((item) => item.requestId === requestId) ?? null;\n}\n\nexport async function getLastPermissionRequestArtifact(\n profile: string,\n): Promise<PermissionRequestArtifact | null> {\n const existing = await loadPermissionRequestArtifacts(profile);\n return existing.at(-1) ?? null;\n}\n\nexport function isPermissionRequestArtifact(value: unknown): value is PermissionRequestArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<PermissionRequestArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.request\" &&\n candidate.version === 1 &&\n typeof candidate.requestId === \"string\" &&\n Array.isArray(candidate.requested)\n );\n}\n\nexport function isDelegationImportArtifact(value: unknown): value is DelegationImportArtifact {\n if (value === null || typeof value !== \"object\") return false;\n const candidate = value as Partial<DelegationImportArtifact>;\n return (\n candidate.kind === \"tinycloud.auth.delegation\" &&\n candidate.version === 1 &&\n candidate.delegation !== undefined &&\n typeof candidate.delegation === \"object\"\n );\n}\n\nexport async function replayAdditionalDelegations(\n node: TinyCloudNode,\n profile: string,\n): Promise<void> {\n const entries = await loadAdditionalDelegations(profile);\n for (const entry of entries) {\n // Skip expired delegations rather than letting useRuntimeDelegation throw.\n const expiry = entry.delegation.expiry instanceof Date\n ? entry.delegation.expiry\n : new Date(entry.delegation.expiry as unknown as string);\n if (expiry.getTime() <= Date.now()) continue;\n try {\n await node.useRuntimeDelegation({ ...entry.delegation, expiry });\n } catch (err) {\n // A stored delegation can be invalid for several benign reasons (host\n // unreachable, key rotated). Don't fail the whole CLI invocation —\n // the user can re-run `tc auth request` to refresh the grant.\n if (process.env.TC_DEBUG_REPLAY === \"1\") {\n process.stderr.write(`[replay] skipping ${entry.delegation.cid}: ${(err as Error).message}\\n`);\n }\n }\n }\n}\n\n/**\n * Helper for `tc auth request` to construct the persisted record that\n * follows the runtime grant. Keeps the \"PortableDelegation + originating\n * permissions\" pair together so future `tc auth caps` output can show the\n * caller-friendly entries we agreed to grant.\n */\nexport function storedAdditionalDelegation(\n delegation: PortableDelegation,\n permissions: PermissionEntry[],\n): StoredAdditionalDelegation {\n return { delegation, permissions };\n}\n\nexport async function appendGrantHistory(\n profile: string,\n entry: Omit<GrantHistoryEntry, \"ts\" | \"profile\">,\n): Promise<void> {\n const profileDir = join(PROFILES_DIR, profile);\n await ensureDir(profileDir);\n const line = JSON.stringify({\n ts: new Date().toISOString(),\n profile,\n ...entry,\n }) + \"\\n\";\n await appendFile(grantHistoryPath(profile), line, \"utf8\");\n}\n\nexport async function readGrantHistory(\n profile: string,\n): Promise<GrantHistoryEntry[]> {\n const path = grantHistoryPath(profile);\n if (!(await fileExists(path))) return [];\n const raw = await readFile(path, \"utf8\");\n return raw\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => JSON.parse(line) as GrantHistoryEntry);\n}\n\nexport async function parseCapSpec(\n spec: string,\n profile: string,\n): Promise<PermissionEntry> {\n const firstColon = spec.indexOf(\":\");\n const lastColon = spec.lastIndexOf(\":\");\n if (firstColon <= 0 || lastColon <= firstColon) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Invalid --cap \"${spec}\". Expected tinycloud.<service>:<space>:<path>:<actions-csv>.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const service = normalizeService(spec.slice(0, firstColon));\n const actionsCsv = spec.slice(lastColon + 1);\n const spaceAndPath = spec.slice(firstColon + 1, lastColon);\n const { space, path } = splitSpaceAndPath(spaceAndPath);\n const resolvedSpace = await resolveSpaceUri(space, profile) ?? space;\n const actions = expandActionShortNames(\n service,\n actionsCsv.split(\",\").map((action) => action.trim()).filter(Boolean),\n );\n\n if (actions.length === 0) {\n throw new CLIError(\"INVALID_CAP\", `Capability \"${spec}\" has no actions.`, ExitCode.USAGE_ERROR);\n }\n\n return { service, space: resolvedSpace, path, actions };\n}\n\nexport async function loadPermissionRequest(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = JSON.parse(await readFile(source, \"utf8\")) as { permissions?: PermissionEntry[] };\n if (!Array.isArray(raw.permissions)) {\n throw new CLIError(\n \"INVALID_PERMISSION_REQUEST\",\n `Permission request ${source} must contain { \"permissions\": [...] }.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return resolvePermissionSpaces(raw.permissions, profile);\n}\n\nexport async function loadManifestPermissions(\n source: string,\n profile: string,\n): Promise<PermissionEntry[]> {\n const raw = await loadManifestText(source);\n const manifest = JSON.parse(raw) as Record<string, unknown>;\n\n if (typeof manifest.id === \"string\") {\n const resolved = resolveManifest(manifest as Parameters<typeof resolveManifest>[0]);\n return resolvePermissionSpaces(resolved.resources, profile);\n }\n\n if (typeof manifest.app_id === \"string\") {\n const permissions = ((manifest.permissions as unknown[]) ?? [])\n .filter((entry): entry is Record<string, unknown> => entry !== null && typeof entry === \"object\")\n .map((entry) => {\n const service = normalizeService(String(entry.service ?? \"\"));\n const path = String(entry.path ?? \"\");\n const skipPrefix = entry.skipPrefix === true;\n const resolvedPath = skipPrefix\n ? path\n : prefixAppManifestPath(path, manifest.app_id as string);\n return {\n service,\n space: String(manifest.space ?? \"applications\"),\n path: resolvedPath,\n actions: expandActionShortNames(\n service,\n Array.isArray(entry.actions)\n ? entry.actions.map(String)\n : [],\n ),\n };\n });\n return resolvePermissionSpaces(permissions, profile);\n }\n\n throw new CLIError(\n \"INVALID_MANIFEST\",\n \"Manifest must contain either SDK field \\\"id\\\" or app manifest field \\\"app_id\\\".\",\n ExitCode.USAGE_ERROR,\n );\n}\n\nexport function diffPermissions(\n requested: PermissionEntry[],\n granted: PermissionEntry[],\n): PermissionEntry[] {\n return isCapabilitySubset(requested, granted).missing;\n}\n\nexport function permissionsFromDelegation(\n delegation: PortableDelegation,\n): PermissionEntry[] {\n if (delegation.resources?.length) {\n return delegation.resources.map((resource) => ({\n service: resource.service.startsWith(\"tinycloud.\")\n ? resource.service\n : `tinycloud.${resource.service}`,\n space: resource.space,\n path: resource.path,\n actions: [...resource.actions],\n }));\n }\n return [{\n service: serviceFromActions(delegation.actions),\n space: delegation.spaceId,\n path: delegation.path,\n actions: [...delegation.actions],\n }];\n}\n\nexport function compactPermission(permission: PermissionEntry): string {\n const service = permission.service;\n const space = permission.space.startsWith(\"tinycloud:\")\n ? permission.space.slice(permission.space.lastIndexOf(\":\") + 1)\n : permission.space;\n const actions = permission.actions\n .map((action) => action.startsWith(`${service}/`) ? action.slice(service.length + 1) : action)\n .join(\",\");\n return `${service}:${space}:${permission.path}:${actions}`;\n}\n\nasync function resolvePermissionSpaces(\n entries: PermissionEntry[],\n profile: string,\n): Promise<PermissionEntry[]> {\n const resolved: PermissionEntry[] = [];\n for (const entry of entries) {\n const service = normalizeService(entry.service);\n resolved.push({\n ...entry,\n service,\n space: await resolveSpaceUri(entry.space, profile) ?? entry.space,\n actions: expandActionShortNames(service, entry.actions),\n });\n }\n return resolved;\n}\n\nasync function loadManifestText(source: string): Promise<string> {\n if (source.startsWith(\"base64:\")) {\n return Buffer.from(source.slice(\"base64:\".length), \"base64\").toString(\"utf8\");\n }\n if (await fileExists(source)) {\n return readFile(source, \"utf8\");\n }\n try {\n const decoded = Buffer.from(source, \"base64\").toString(\"utf8\");\n JSON.parse(decoded);\n return decoded;\n } catch {\n return readFile(source, \"utf8\");\n }\n}\n\nfunction normalizeService(service: string): string {\n if (!service) {\n throw new CLIError(\"INVALID_CAP\", \"Capability service is required.\", ExitCode.USAGE_ERROR);\n }\n return service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`;\n}\n\nfunction splitSpaceAndPath(input: string): { space: string; path: string } {\n if (input.startsWith(\"tinycloud:\")) {\n const parts = input.split(\":\");\n if (parts.length < 7) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Full tinycloud space specs must include a path after the space URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: parts.slice(0, 6).join(\":\"),\n path: parts.slice(6).join(\":\"),\n };\n }\n\n const colon = input.indexOf(\":\");\n if (colon <= 0) {\n throw new CLIError(\n \"INVALID_CAP\",\n `Capability must include both space and path.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return {\n space: input.slice(0, colon),\n path: input.slice(colon + 1),\n };\n}\n\nfunction prefixAppManifestPath(path: string, appId: string): string {\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n return `${path.slice(0, slash)}/${appId}/${path.slice(slash + 1)}`;\n}\n\nfunction serviceFromActions(actions: string[]): string {\n const first = actions[0] ?? \"tinycloud.unknown/read\";\n return first.includes(\"/\") ? first.slice(0, first.indexOf(\"/\")) : \"tinycloud.unknown\";\n}\n","/**\n * TinyCloud App Manifest\n *\n * A declarative description of an app's identity and the capabilities it\n * needs. The manifest drives the SIWE recap at sign-in time, enabling a\n * single wallet prompt that covers the app's own permissions plus any\n * pre-declared delegations.\n *\n * The SDK does NOT fetch external manifests. Apps compose their own manifest\n * (optionally including backend or agent addenda) before handing it to the\n * SDK.\n *\n * Canonical spec: `.claude/specs/manifest.md`.\n *\n * @packageDocumentation\n */\n\nimport ms from \"ms\";\nimport { resolveSecretPath, SECRET_NAME_RE } from \"@tinycloud/sdk-services\";\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * A single permission entry inside a manifest. This is the shape apps write\n * in their `manifest.json` and the shape we compare against when performing\n * the capability-subset derivability check in the delegation flow.\n *\n * `service` uses the long form (e.g. `\"tinycloud.kv\"`, `\"tinycloud.sql\"`).\n * `\"tinycloud.vault\"` is an SDK-only shorthand that expands to the KV\n * resources the vault service uses; it is never encoded as a recap service.\n */\nexport interface PermissionEntry {\n /** Service namespace, e.g. \"tinycloud.kv\", \"tinycloud.sql\", \"tinycloud.duckdb\", \"tinycloud.capabilities\". */\n service: string;\n /** Space name or full space URI. Defaults to \"applications\" inside manifests. */\n space?: string;\n /**\n * Service-specific path.\n * - tinycloud.kv: hierarchical prefix. \"/\" = all, \"foo/\" = prefix match, \"foo\" = exact key\n * - tinycloud.sql: database name/file (e.g. \"data.sqlite\") or \"/\" for all\n * - tinycloud.duckdb: database name/file\n * - tinycloud.capabilities: capability key URI or \"/\" for all\n */\n path: string;\n /**\n * Short action names (e.g. \"get\", \"put\", \"read\", \"ddl\"). The SDK expands\n * these to full URNs (e.g. `tinycloud.kv/get`) during resolution.\n * Already-expanded URNs are passed through unchanged.\n */\n actions: string[];\n /** When true, the manifest prefix is NOT prepended to `path`. Default false. */\n skipPrefix?: boolean;\n /** Per-entry expiry override, ms-format. */\n expiry?: string;\n /** User/agent-facing context for why this permission is requested. */\n description?: string;\n}\n\nexport type ManifestSecretActions =\n | true\n | string\n | string[]\n | {\n /** Actual vault secret name. Defaults to the manifest object key. */\n name?: string;\n /** Optional scoped secret namespace. Omit for global secrets. */\n scope?: string;\n actions?: string | string[];\n expiry?: string;\n description?: string;\n };\n\n/**\n * The valid values for `Manifest.defaults`.\n *\n * - `false` → no auto-included permissions\n * - `true` → standard tier (KV + SQL read/write + capabilities:read)\n * - `\"admin\"` → standard + SQL ddl\n * - `\"all\"` → everything the SDK supports (including DuckDB)\n *\n * Unknown string values silently fall back to `true`. Values are normalized\n * (lowercase + trim) before matching.\n */\nexport type ManifestDefaults = boolean | \"admin\" | \"all\";\n\n/**\n * The raw manifest shape an app declares. See `.claude/specs/manifest.md`.\n */\nexport interface Manifest {\n /** Schema version. Optional, defaults to 1. */\n manifest_version?: 1;\n /** Application identifier / namespace prefix. Required. */\n app_id: string;\n /** Display name. Required. */\n name: string;\n /** Description of what the app or delegate does. Optional. */\n description?: string;\n /** DID of this manifest's delegate target. Optional. Required only for delegation materialization. */\n did?: string;\n /** URL to app icon. Optional. */\n icon?: string;\n /** App version string. Optional. */\n appVersion?: string;\n /** Default expiry for permissions. ms-format (\"30d\", \"2h\", \"1y\"). Default \"30d\". */\n expiry?: string;\n /** Space name or full space URI. Optional, defaults to \"applications\". */\n space?: string;\n /**\n * Path prefix auto-prepended to permission paths. Optional, defaults to\n * `app_id`. Set to `\"\"` to disable entirely. Individual permissions can opt\n * out with `skipPrefix: true`.\n */\n prefix?: string;\n /**\n * Default permission set to auto-include. Optional, defaults to `true`.\n * See {@link ManifestDefaults}.\n */\n defaults?: ManifestDefaults | string;\n /** Whether to include the public-space companion delegation. Default `true`. */\n includePublicSpace?: boolean;\n /**\n * Additional permissions beyond the defaults. Use for cross-space access,\n * DuckDB (opt-in), or `skipPrefix: true` entries.\n */\n permissions?: PermissionEntry[];\n /**\n * Secret name shorthand. Entries resolve to encrypted vault KV resources in\n * the `secrets` space.\n */\n secrets?: Record<string, ManifestSecretActions>;\n}\n\n/**\n * A resolved permission entry with fully-expanded paths and action URNs.\n * This is the shape the delegation flow compares against parsed recap\n * capabilities, and the shape the session-key delegation path actually uses.\n */\nexport interface ResourceCapability {\n /** Long-form service, e.g. \"tinycloud.kv\". */\n service: string;\n /** Space name or URI. Short names are resolved to full SpaceIds at sign-in time. */\n space: string;\n /** Path with the manifest prefix applied (or skipped per `skipPrefix`). */\n path: string;\n /** Full-URN actions, e.g. [\"tinycloud.kv/get\", \"tinycloud.kv/put\"]. */\n actions: string[];\n /** Per-entry expiry override in milliseconds. */\n expiryMs?: number;\n /** User/agent-facing context copied from the source permission entry. */\n description?: string;\n}\n\n/**\n * A resolved delegation entry with fully-expanded permissions.\n */\nexport interface ResolvedDelegate {\n /** DID of the delegate. */\n did: string;\n /** Informational display name. Optional. */\n name?: string;\n /** Expiry in milliseconds (per-delegation > manifest default > 30 days). */\n expiryMs: number;\n /** Fully resolved permissions. */\n permissions: ResourceCapability[];\n}\n\n/**\n * The output of {@link resolveManifest}: a fully-expanded capability set\n * ready to drive the SIWE recap.\n */\nexport interface ResolvedCapabilities {\n /** Application identifier copied from manifest.app_id. */\n app_id: string;\n /** Delegate DID copied from manifest.did, when present. */\n did?: string;\n /** Effective default space for this manifest. */\n space: string;\n /** All session-key resources with paths fully resolved (prefix applied). */\n resources: ResourceCapability[];\n /** Default expiry for the session, in milliseconds. */\n expiryMs: number;\n /** Whether to include the public-space companion. */\n includePublicSpace: boolean;\n /** Delegate targets derived from manifests that declare `did`. */\n additionalDelegates: ResolvedDelegate[];\n}\n\nexport interface ManifestRegistryRecord {\n /** KV key inside the account space. */\n key: string;\n /** App id this record describes. */\n app_id: string;\n /** Latest manifest payloads composed for this app id. */\n manifests: Manifest[];\n}\n\nexport interface ComposeManifestOptions {\n /** Include implicit account-space registry permissions. Default true. */\n includeAccountRegistryPermissions?: boolean;\n}\n\nexport interface ComposedManifestRequest {\n /** Validated manifests that were composed. */\n manifests: Manifest[];\n /** Full permission union requested from the user in one SIWE. */\n resources: ResourceCapability[];\n /** Delegations that can be materialized after sign-in. */\n delegationTargets: ResolvedDelegate[];\n /** Account-space registry records to write after successful sign-in. */\n registryRecords: ManifestRegistryRecord[];\n /** Effective session expiry, using the longest composed manifest expiry. */\n expiryMs: number;\n /** Whether to include the public-space companion behavior. */\n includePublicSpace: boolean;\n}\n\n/**\n * Thrown when the manifest fails validation (missing id/name, bad expiry,\n * empty actions on a permission, etc).\n */\nexport class ManifestValidationError extends Error {\n constructor(message: string) {\n super(`Manifest validation failed: ${message}`);\n this.name = \"ManifestValidationError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Default expiry when neither the manifest, delegation, nor permission\n * specifies one. APP tier — see `expiry.ts`. Spec: 30 days.\n *\n * Kept as an ms-format string because the manifest schema stores expiry\n * as a string and the parser is shared between this default and\n * caller-provided values; converting `EXPIRY.APP_MS` back to a string\n * here would duplicate that same `30d` literal in another form.\n */\nexport const DEFAULT_EXPIRY = \"30d\";\n\n/**\n * Default `defaults` value when the manifest omits it. Spec: standard tier.\n */\nexport const DEFAULT_DEFAULTS: ManifestDefaults = true;\n\n/** Default manifest schema version. */\nexport const DEFAULT_MANIFEST_VERSION = 1;\n\n/** Default space for manifest-declared app data. */\nexport const DEFAULT_MANIFEST_SPACE = \"applications\";\n\n/** Account-space name used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_SPACE = \"account\";\n\n/** Account-space KV prefix used for installed-application registry records. */\nexport const ACCOUNT_REGISTRY_PATH = \"applications/\";\n\nconst SECRETS_SPACE = \"secrets\";\n\n/** SDK-only permission service for encrypted vault resources. */\nexport const VAULT_PERMISSION_SERVICE = \"tinycloud.vault\";\n\ntype VaultKVBase = \"vault\";\n\ninterface VaultActionExpansion {\n bases: readonly VaultKVBase[];\n action: string;\n}\n\n/**\n * Known services and their short-form (recap URI) names. The TinyCloud\n * node encodes the recap resource URI with the short service name, while\n * action URNs and manifest entries use the long `tinycloud.<short>` form.\n * This table is the canonical bridge between the two.\n */\nexport const SERVICE_SHORT_TO_LONG: Readonly<Record<string, string>> =\n Object.freeze({\n kv: \"tinycloud.kv\",\n sql: \"tinycloud.sql\",\n duckdb: \"tinycloud.duckdb\",\n capabilities: \"tinycloud.capabilities\",\n hooks: \"tinycloud.hooks\",\n encryption: \"tinycloud.encryption\",\n });\n\n/**\n * Manifest service identifier for TinyCloud encryption network grants.\n *\n * Encryption permissions live on a network id URN\n * (`urn:tinycloud:encryption:<ownerDid>:<network>`), not on a space.\n * The `path` field is the literal networkId; `actions` are\n * `[\"decrypt\"]` (expanded to `[\"tinycloud.encryption/decrypt\"]`).\n *\n * Apps should omit `space` for encryption permissions. The SDK may emit\n * an internal `\"encryption\"` compatibility label after expansion so the\n * older `PermissionEntry`/`ResourceCapability` shape can still carry the\n * raw network URN through subset checks.\n */\nexport const ENCRYPTION_PERMISSION_SERVICE = \"tinycloud.encryption\";\n\n/** Synthetic space label used by encryption manifest entries. */\nexport const ENCRYPTION_MANIFEST_SPACE = \"encryption\";\n\n/**\n * Inverse of {@link SERVICE_SHORT_TO_LONG}.\n */\nexport const SERVICE_LONG_TO_SHORT: Readonly<Record<string, string>> =\n Object.freeze(\n Object.fromEntries(\n Object.entries(SERVICE_SHORT_TO_LONG).map(([s, l]) => [l, s]),\n ),\n );\n\n/**\n * Default permission entries for the `true` / standard tier.\n *\n * `tinycloud.capabilities/read` is added separately for every requested\n * space, without the app path prefix. That keeps capability introspection\n * space-scoped instead of app-data scoped.\n */\nconst DEFAULT_STANDARD_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n/**\n * Default permission entries for the `\"admin\"` tier: standard + sql/ddl.\n */\nconst DEFAULT_ADMIN_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"ddl\"],\n },\n];\n\n/**\n * Default permission entries for the `\"all\"` tier: admin + DuckDB.\n *\n * DuckDB is opt-in and only appears in this tier or in explicit manifest\n * `permissions` entries.\n */\nconst DEFAULT_ALL_ENTRIES: readonly PermissionEntry[] = [\n {\n service: \"tinycloud.kv\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"get\", \"put\", \"del\", \"list\", \"metadata\"],\n },\n {\n service: \"tinycloud.sql\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\", \"ddl\"],\n },\n {\n service: \"tinycloud.duckdb\",\n space: DEFAULT_MANIFEST_SPACE,\n path: \"/\",\n actions: [\"read\", \"write\"],\n },\n];\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Parse an ms-format duration string (e.g. \"30d\", \"2h\", \"1y\") into\n * milliseconds.\n *\n * @throws {ManifestValidationError} on empty string, non-string input, or\n * any input `ms()` cannot parse.\n */\nexport function parseExpiry(duration: string): number {\n if (typeof duration !== \"string\" || duration.length === 0) {\n throw new ManifestValidationError(\n `expiry must be a non-empty duration string (got ${JSON.stringify(duration)})`,\n );\n }\n // `ms` returns `undefined` for unparseable input and can return a number\n // or a string depending on the call signature; cast explicitly.\n const parsed = (ms as unknown as (v: string) => number | undefined)(duration);\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new ManifestValidationError(\n `invalid expiry duration: ${JSON.stringify(duration)}`,\n );\n }\n return parsed;\n}\n\n/**\n * Expand a list of action short names (or already-expanded URNs) into full\n * ability URNs of the form `<service>/<action>`.\n *\n * Examples:\n * `expandActionShortNames(\"tinycloud.kv\", [\"get\", \"put\"])`\n * → `[\"tinycloud.kv/get\", \"tinycloud.kv/put\"]`\n * `expandActionShortNames(\"tinycloud.kv\", [\"tinycloud.kv/get\"])`\n * → `[\"tinycloud.kv/get\"]` (passed through unchanged)\n */\nexport function expandActionShortNames(\n service: string,\n actions: readonly string[],\n): string[] {\n return actions.map((a) => {\n if (a.includes(\"/\")) {\n // Already a full URN — pass through.\n return a;\n }\n return `${service}/${a}`;\n });\n}\n\n/**\n * Expand SDK virtual permission services into concrete recap-capable services.\n *\n * Today this handles `\"tinycloud.vault\"`, which is backed by inline\n * network-encrypted KV records:\n * - read/get: `vault/<path>` with `tinycloud.kv/get`\n * - write/put: `vault/<path>` with `tinycloud.kv/put`\n * - delete/del: `vault/<path>` with `tinycloud.kv/del`\n * - list: `vault/<path>` with `tinycloud.kv/list`\n * - head: `vault/<path>` with `tinycloud.kv/get`\n * - metadata: `vault/<path>` with `tinycloud.kv/metadata`\n */\nexport function expandPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n if (entry.service === ENCRYPTION_PERMISSION_SERVICE) {\n return expandEncryptionPermissionEntry(entry);\n }\n if (entry.service !== VAULT_PERMISSION_SERVICE) {\n return [\n {\n ...entry,\n actions: expandActionShortNames(entry.service, entry.actions),\n },\n ];\n }\n\n return expandVaultPermissionEntry(entry);\n}\n\n/**\n * Expand a `tinycloud.encryption` manifest entry.\n *\n * - `path` MUST be a networkId URN (`urn:tinycloud:encryption:...`).\n * The manifest prefix is always skipped — network ids are top-level\n * owner-scoped resources, not space-scoped paths.\n * - `actions` must be `decrypt`, `network.create`, or `network.revoke`\n * (or their already-expanded `tinycloud.encryption/*` forms).\n *\n * The returned entry uses an internal `space = \"encryption\"` compatibility\n * label so old manifest grouping code does not collapse it into the app's\n * data space, and `skipPrefix` is forced to `true` so the prefix application\n * step is a no-op.\n */\nfunction expandEncryptionPermissionEntry(\n entry: PermissionEntry,\n): PermissionEntry[] {\n if (\n typeof entry.path !== \"string\" ||\n !entry.path.startsWith(\"urn:tinycloud:encryption:\")\n ) {\n throw new ManifestValidationError(\n `tinycloud.encryption entries require path to be a networkId URN ` +\n `(got ${JSON.stringify(entry.path)})`,\n );\n }\n const normalizedActions: string[] = [];\n for (const action of entry.actions) {\n if (action === \"decrypt\" || action === \"tinycloud.encryption/decrypt\") {\n normalizedActions.push(\"tinycloud.encryption/decrypt\");\n continue;\n }\n if (\n action === \"network.create\" ||\n action === \"tinycloud.encryption/network.create\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.create\");\n continue;\n }\n if (\n action === \"network.revoke\" ||\n action === \"tinycloud.encryption/network.revoke\"\n ) {\n normalizedActions.push(\"tinycloud.encryption/network.revoke\");\n continue;\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n throw new ManifestValidationError(\n `unknown encryption action ${JSON.stringify(action)}; expected decrypt, network.create, or network.revoke`,\n );\n }\n // Dedupe while preserving order\n const dedupedActions: string[] = [];\n const seen = new Set<string>();\n for (const a of normalizedActions) {\n if (!seen.has(a)) {\n dedupedActions.push(a);\n seen.add(a);\n }\n }\n // Encryption resources are network-scoped, not space-scoped. We\n // always emit the synthetic \"encryption\" space label so manifest\n // grouping can deal with it uniformly without collapsing the\n // networkId URN into an app data space.\n return [\n {\n service: ENCRYPTION_PERMISSION_SERVICE,\n space: ENCRYPTION_MANIFEST_SPACE,\n path: entry.path,\n actions: dedupedActions,\n skipPrefix: true,\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n },\n ];\n}\n\n/**\n * Expand a list of permission entries using {@link expandPermissionEntry}.\n */\nexport function expandPermissionEntries(\n entries: readonly PermissionEntry[],\n): PermissionEntry[] {\n return entries.flatMap(expandPermissionEntry);\n}\n\n/**\n * Apply the manifest prefix to a permission path per the spec rules.\n *\n * - `skipPrefix: true` → path is returned as-is\n * - `prefix === \"\"` → path is returned as-is\n * - path starts with \"/\" → `prefix + path` (e.g. \"com.listen.app\" + \"/\" → \"com.listen.app/\")\n * - otherwise → `prefix + \"/\" + path` (e.g. \"com.listen.app\" + \"data.sqlite\" → \"com.listen.app/data.sqlite\")\n */\nexport function applyPrefix(\n prefix: string,\n path: string,\n skipPrefix: boolean,\n): string {\n if (skipPrefix) {\n return path;\n }\n if (prefix === \"\") {\n return path;\n }\n if (path.startsWith(\"/\")) {\n return `${prefix}${path}`;\n }\n return `${prefix}/${path}`;\n}\n\n/**\n * Fetch and parse a manifest from a URL (browser) or file path (node).\n * The runtime decides the fetch strategy via `globalThis.fetch`; this is\n * platform-agnostic. Callers that want custom loading should JSON.parse a\n * Manifest themselves and skip this helper.\n *\n * @throws if the fetch fails, the JSON is invalid, or the manifest fails\n * validation.\n */\nexport async function loadManifest(url: string): Promise<Manifest> {\n const fetchFn: typeof fetch | undefined = (\n globalThis as { fetch?: typeof fetch }\n ).fetch;\n if (typeof fetchFn !== \"function\") {\n throw new ManifestValidationError(\n \"loadManifest requires a global fetch; pass the manifest object directly on runtimes without fetch\",\n );\n }\n const res = await fetchFn(url);\n if (!res.ok) {\n throw new ManifestValidationError(\n `failed to fetch manifest from ${url}: HTTP ${res.status}`,\n );\n }\n const json = (await res.json()) as unknown;\n return validateManifest(json);\n}\n\n/**\n * Validate a manifest-shaped object and return it strongly-typed.\n * Throws {@link ManifestValidationError} on any hard failure.\n */\nexport function validateManifest(input: unknown): Manifest {\n if (input === null || typeof input !== \"object\") {\n throw new ManifestValidationError(\"manifest must be an object\");\n }\n const m = input as Manifest;\n if (\n m.manifest_version !== undefined &&\n m.manifest_version !== DEFAULT_MANIFEST_VERSION\n ) {\n throw new ManifestValidationError(\n `manifest.manifest_version must be ${DEFAULT_MANIFEST_VERSION}`,\n );\n }\n if (typeof m.app_id !== \"string\" || m.app_id.length === 0) {\n throw new ManifestValidationError(\n \"manifest.app_id is required and must be a non-empty string\",\n );\n }\n if (typeof m.name !== \"string\" || m.name.length === 0) {\n throw new ManifestValidationError(\n \"manifest.name is required and must be a non-empty string\",\n );\n }\n if (\n m.did !== undefined &&\n (typeof m.did !== \"string\" || m.did.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.did must be a non-empty DID string\",\n );\n }\n if (\n m.space !== undefined &&\n (typeof m.space !== \"string\" || m.space.length === 0)\n ) {\n throw new ManifestValidationError(\n \"manifest.space must be a non-empty string\",\n );\n }\n if (m.expiry !== undefined) {\n // Will throw with a clear error if invalid.\n parseExpiry(m.expiry);\n }\n if (m.permissions !== undefined) {\n if (!Array.isArray(m.permissions)) {\n throw new ManifestValidationError(\n \"manifest.permissions must be an array\",\n );\n }\n m.permissions.forEach((p, i) =>\n validatePermissionEntry(p, `permissions[${i}]`),\n );\n }\n if (m.secrets !== undefined) {\n validateManifestSecrets(m.secrets);\n }\n return m;\n}\n\nfunction validateManifestSecrets(secrets: unknown): void {\n if (secrets === null || typeof secrets !== \"object\" || Array.isArray(secrets)) {\n throw new ManifestValidationError(\"manifest.secrets must be an object\");\n }\n\n for (const [name, spec] of Object.entries(secrets)) {\n if (!SECRET_NAME_RE.test(name)) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`,\n );\n }\n try {\n resolveSecretPath(\n secretNameFromSpec(name, spec as ManifestSecretActions),\n { scope: secretScopeFromSpec(spec as ManifestSecretActions) },\n );\n } catch (error) {\n throw new ManifestValidationError(\n `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n const actions = secretActionsFromSpec(name, spec as ManifestSecretActions);\n if (actions.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty`,\n );\n }\n for (const action of actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `manifest.secrets.${name} actions must be non-empty strings`,\n );\n }\n }\n if (\n spec !== null &&\n typeof spec === \"object\" &&\n !Array.isArray(spec) &&\n (spec as { expiry?: unknown }).expiry !== undefined\n ) {\n parseExpiry((spec as { expiry: string }).expiry);\n }\n }\n}\n\nfunction validatePermissionEntry(p: unknown, path: string): void {\n if (p === null || typeof p !== \"object\") {\n throw new ManifestValidationError(`${path} must be an object`);\n }\n const entry = p as PermissionEntry;\n if (typeof entry.service !== \"string\" || entry.service.length === 0) {\n throw new ManifestValidationError(`${path}.service is required`);\n }\n if (\n entry.space !== undefined &&\n (typeof entry.space !== \"string\" || entry.space.length === 0)\n ) {\n throw new ManifestValidationError(\n `${path}.space must be a non-empty string`,\n );\n }\n if (typeof entry.path !== \"string\") {\n throw new ManifestValidationError(\n `${path}.path is required (use \"\" or \"/\" for root)`,\n );\n }\n if (!Array.isArray(entry.actions) || entry.actions.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must be a non-empty array`,\n );\n }\n for (const action of entry.actions) {\n if (typeof action !== \"string\" || action.length === 0) {\n throw new ManifestValidationError(\n `${path}.actions must contain non-empty strings`,\n );\n }\n if (entry.service === VAULT_PERMISSION_SERVICE) {\n vaultActionExpansion(action);\n }\n }\n if (entry.expiry !== undefined) {\n parseExpiry(entry.expiry);\n }\n}\n\n/**\n * Normalize a `defaults` value: lowercase + trim, then match against known\n * tiers. Unknown string values silently fall back to `true` (standard).\n * Boolean values pass through.\n */\nexport function normalizeDefaults(\n value: Manifest[\"defaults\"] | undefined,\n): ManifestDefaults {\n if (value === undefined) {\n return DEFAULT_DEFAULTS;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value !== \"string\") {\n // Spec says unknown values silently fall back to `true`.\n return true;\n }\n const normalized = value.trim().toLowerCase();\n if (normalized === \"admin\" || normalized === \"all\") {\n return normalized;\n }\n // Anything else, including \"true\"/\"false\"/\"standard\"/garbage, falls back\n // to the standard tier per spec.\n return true;\n}\n\n/**\n * Return the default permission entries for the given tier. Entries are\n * deep-cloned so callers can mutate them without affecting the constants.\n */\nfunction defaultEntriesForTier(tier: ManifestDefaults): PermissionEntry[] {\n if (tier === false) {\n return [];\n }\n const source =\n tier === \"admin\"\n ? DEFAULT_ADMIN_ENTRIES\n : tier === \"all\"\n ? DEFAULT_ALL_ENTRIES\n : DEFAULT_STANDARD_ENTRIES;\n return source.map((e) => ({\n service: e.service,\n space: e.space,\n path: e.path,\n actions: [...e.actions],\n ...(e.skipPrefix !== undefined ? { skipPrefix: e.skipPrefix } : {}),\n }));\n}\n\n/**\n * Resolve a raw manifest into a {@link ResolvedCapabilities} object: expand\n * shortform actions, apply the prefix, merge defaults, and compute effective\n * expiries. Pure function — does no I/O.\n *\n * Resolution semantics (spec):\n * - `prefix` defaults to `app_id`; set to `\"\"` to disable prefix application entirely.\n * - `space` defaults to `applications`; per-permission `space` overrides it.\n * - `defaults` defaults to `true` (standard tier); unknown string values fall back to `true`.\n * - Per-entry expiry overrides per-delegation overrides manifest > `DEFAULT_EXPIRY`.\n * - Default entries use `skipPrefix: false` so they inherit the manifest prefix.\n */\nexport function resolveManifest(input: Manifest): ResolvedCapabilities {\n const manifest = validateManifest(input);\n\n const prefix =\n manifest.prefix !== undefined ? manifest.prefix : manifest.app_id;\n const space = manifest.space ?? DEFAULT_MANIFEST_SPACE;\n const expiryMs = parseExpiry(manifest.expiry ?? DEFAULT_EXPIRY);\n const includePublicSpace = manifest.includePublicSpace ?? true;\n const tier = normalizeDefaults(manifest.defaults);\n\n const defaultEntries = defaultEntriesForTier(tier);\n const explicitEntries = manifest.permissions ?? [];\n const secretEntries = secretEntriesForManifest(manifest.secrets);\n\n // Merge order: defaults first, then explicit entries, so explicit entries\n // for the same (service, space, path) tuple override defaults.\n const allEntries: PermissionEntry[] = [\n ...defaultEntries,\n ...explicitEntries,\n ...secretEntries,\n ];\n\n const resources: ResourceCapability[] = withCapabilitiesReadForSpaces(\n allEntries.flatMap((entry) => resolveEntry(entry, prefix, expiryMs, space)),\n );\n\n const additionalDelegates: ResolvedDelegate[] =\n manifest.did === undefined\n ? []\n : [\n {\n did: manifest.did,\n name: manifest.name,\n expiryMs,\n permissions: resources.map(cloneResourceCapability),\n },\n ];\n\n return {\n app_id: manifest.app_id,\n ...(manifest.did !== undefined ? { did: manifest.did } : {}),\n space,\n resources,\n expiryMs,\n includePublicSpace,\n additionalDelegates,\n };\n}\n\nfunction normalizeSecretActions(actions: readonly string[]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n const add = (action: string) => {\n if (!seen.has(action)) {\n out.push(action);\n seen.add(action);\n }\n };\n\n for (const action of actions) {\n if (action === \"read\") {\n add(\"get\");\n continue;\n }\n if (action === \"write\") {\n add(\"put\");\n continue;\n }\n if (action === \"delete\") {\n add(\"del\");\n continue;\n }\n if (\n action === \"get\" ||\n action === \"put\" ||\n action === \"del\" ||\n action === \"list\" ||\n action === \"metadata\"\n ) {\n add(action);\n continue;\n }\n if (\n action === \"tinycloud.kv/get\" ||\n action === \"tinycloud.kv/put\" ||\n action === \"tinycloud.kv/del\" ||\n action === \"tinycloud.kv/list\" ||\n action === \"tinycloud.kv/metadata\"\n ) {\n add(action);\n continue;\n }\n throw new ManifestValidationError(\n `unknown secret action ${JSON.stringify(action)}; expected read, write, delete, list, or metadata`,\n );\n }\n\n return out;\n}\n\nfunction secretNameFromSpec(\n fallbackName: string,\n spec: ManifestSecretActions,\n): string {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.name ?? fallbackName;\n }\n return fallbackName;\n}\n\nfunction secretScopeFromSpec(\n spec: ManifestSecretActions,\n): string | undefined {\n if (spec !== null && typeof spec === \"object\" && !Array.isArray(spec)) {\n return spec.scope;\n }\n return undefined;\n}\n\nfunction secretActionsFromSpec(\n name: string,\n spec: ManifestSecretActions,\n): string[] {\n if (spec === true) {\n return [\"read\"];\n }\n if (typeof spec === \"string\") {\n return [spec];\n }\n if (Array.isArray(spec)) {\n return spec;\n }\n if (spec === null || typeof spec !== \"object\") {\n throw new ManifestValidationError(\n `manifest.secrets.${name} must be true, a string action, an actions array, or an object`,\n );\n }\n if (spec.actions === undefined) {\n return [\"read\"];\n }\n if (typeof spec.actions === \"string\") {\n return [spec.actions];\n }\n if (Array.isArray(spec.actions)) {\n return spec.actions;\n }\n throw new ManifestValidationError(\n `manifest.secrets.${name}.actions must be a string or array`,\n );\n}\n\nfunction secretEntriesForManifest(\n secrets: Manifest[\"secrets\"] | undefined,\n): PermissionEntry[] {\n if (secrets === undefined) {\n return [];\n }\n\n const entries: PermissionEntry[] = [];\n for (const [name, spec] of Object.entries(secrets)) {\n const actions = secretActionsFromSpec(name, spec);\n const secretPath = resolveSecretPath(\n secretNameFromSpec(name, spec),\n { scope: secretScopeFromSpec(spec) },\n );\n const extra: { expiry?: string; description?: string } =\n spec !== true && typeof spec === \"object\" && !Array.isArray(spec)\n ? spec\n : {};\n entries.push({\n service: VAULT_PERMISSION_SERVICE,\n space: SECRETS_SPACE,\n path: secretPath.vaultKey,\n actions: normalizeSecretActions(actions),\n skipPrefix: true,\n ...(extra.expiry !== undefined ? { expiry: extra.expiry } : {}),\n ...(extra.description !== undefined\n ? { description: extra.description }\n : {}),\n });\n }\n return entries;\n}\n\n/**\n * Expand a single permission entry into a {@link ResourceCapability}:\n * apply the prefix to the path and expand short actions into full URNs.\n */\nfunction resolveEntry(\n entry: PermissionEntry,\n prefix: string,\n _inheritedExpiryMs: number,\n inheritedSpace: string,\n): ResourceCapability[] {\n // Encryption permissions reference a networkId URN as their resource\n // — the manifest prefix is meaningless against a top-level\n // owner-scoped resource and would corrupt the URN. Always skip.\n const skipPrefixForEntry =\n entry.skipPrefix === true ||\n entry.service === ENCRYPTION_PERMISSION_SERVICE;\n const resolvedPath = applyPrefix(prefix, entry.path, skipPrefixForEntry);\n const entryExpiryMs =\n entry.expiry !== undefined ? parseExpiry(entry.expiry) : undefined;\n return expandPermissionEntry({\n ...entry,\n space: entry.space ?? inheritedSpace,\n path: resolvedPath,\n skipPrefix: true,\n }).map((expanded) => ({\n service: expanded.service,\n space: expanded.space ?? inheritedSpace,\n path: expanded.path,\n actions: expanded.actions,\n // Only populate `expiryMs` when the entry had its own expiry override.\n // When absent, callers use the parent (delegation or manifest) expiry\n // which is carried on ResolvedDelegate.expiryMs / ResolvedCapabilities.expiryMs.\n ...(entryExpiryMs !== undefined ? { expiryMs: entryExpiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n }));\n}\n\nfunction expandVaultPermissionEntry(entry: PermissionEntry): PermissionEntry[] {\n const byBase = new Map<VaultKVBase, string[]>();\n\n for (const action of entry.actions) {\n const expansion = vaultActionExpansion(action);\n for (const base of expansion.bases) {\n const actions = byBase.get(base) ?? [];\n if (!actions.includes(expansion.action)) {\n actions.push(expansion.action);\n }\n byBase.set(base, actions);\n }\n }\n\n return [...byBase.entries()].map(([base, actions]) => ({\n ...entry,\n service: \"tinycloud.kv\",\n path: vaultKVPath(base, entry.path),\n actions,\n skipPrefix: true,\n }));\n}\n\nfunction vaultActionExpansion(action: string): VaultActionExpansion {\n const normalized = normalizeVaultAction(action);\n if (normalized === \"read\" || normalized === \"get\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"write\" || normalized === \"put\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/put\" };\n }\n if (normalized === \"delete\" || normalized === \"del\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/del\" };\n }\n if (normalized === \"list\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/list\" };\n }\n if (normalized === \"head\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/get\" };\n }\n if (normalized === \"metadata\") {\n return { bases: [\"vault\"], action: \"tinycloud.kv/metadata\" };\n }\n\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected read, write, delete, get, put, del, list, head, or metadata`,\n );\n}\n\nfunction normalizeVaultAction(action: string): string {\n if (action.startsWith(`${VAULT_PERMISSION_SERVICE}/`)) {\n return action.slice(`${VAULT_PERMISSION_SERVICE}/`.length);\n }\n if (action.startsWith(\"tinycloud.kv/\")) {\n return action.slice(\"tinycloud.kv/\".length);\n }\n if (action.includes(\"/\")) {\n throw new ManifestValidationError(\n `unknown vault action ${JSON.stringify(action)}; expected a tinycloud.vault or tinycloud.kv action`,\n );\n }\n return action;\n}\n\nfunction vaultKVPath(base: VaultKVBase, path: string): string {\n const normalized = path.startsWith(\"/\") ? path.slice(1) : path;\n return `${base}/${normalized}`;\n}\n\nfunction cloneResourceCapability(\n entry: ResourceCapability,\n): ResourceCapability {\n return {\n service: entry.service,\n space: entry.space,\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.expiryMs !== undefined ? { expiryMs: entry.expiryMs } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction clonePermissionEntry(entry: PermissionEntry): PermissionEntry {\n return {\n service: entry.service,\n ...(entry.space !== undefined ? { space: entry.space } : {}),\n path: entry.path,\n actions: [...entry.actions],\n ...(entry.skipPrefix !== undefined ? { skipPrefix: entry.skipPrefix } : {}),\n ...(entry.expiry !== undefined ? { expiry: entry.expiry } : {}),\n ...(entry.description !== undefined\n ? { description: entry.description }\n : {}),\n };\n}\n\nfunction dedupeResources(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n const byKey = new Map<string, ResourceCapability>();\n\n for (const resource of resources) {\n const key = `${resource.service}\\u0000${resource.space}\\u0000${resource.path}\\u0000${resource.expiryMs ?? \"\"}`;\n const existing = byKey.get(key);\n if (existing === undefined) {\n byKey.set(key, cloneResourceCapability(resource));\n continue;\n }\n\n const seen = new Set(existing.actions);\n for (const action of resource.actions) {\n if (!seen.has(action)) {\n existing.actions.push(action);\n seen.add(action);\n }\n }\n if (\n existing.description === undefined &&\n resource.description !== undefined\n ) {\n existing.description = resource.description;\n }\n }\n\n return [...byKey.values()];\n}\n\nfunction capabilitiesReadPermission(space: string): ResourceCapability {\n return {\n service: \"tinycloud.capabilities\",\n space,\n path: \"\",\n actions: [\"tinycloud.capabilities/read\"],\n };\n}\n\nfunction withCapabilitiesReadForSpaces(\n resources: readonly ResourceCapability[],\n): ResourceCapability[] {\n if (resources.length === 0) {\n return [];\n }\n\n const spaces = new Set(\n resources\n .filter((resource) => resource.service !== ENCRYPTION_PERMISSION_SERVICE)\n .map((resource) => resource.space),\n );\n return dedupeResources([\n ...resources,\n ...[...spaces].map(capabilitiesReadPermission),\n ]);\n}\n\nfunction accountRegistryPermission(): ResourceCapability {\n return {\n service: \"tinycloud.kv\",\n space: ACCOUNT_REGISTRY_SPACE,\n path: ACCOUNT_REGISTRY_PATH,\n actions: [\"tinycloud.kv/get\", \"tinycloud.kv/put\", \"tinycloud.kv/list\"],\n };\n}\n\n/**\n * Compose one or more manifests into the single capability request that should\n * be signed. Fetching manifests is intentionally out of band; callers pass the\n * already-loaded manifest objects.\n */\nexport function composeManifestRequest(\n inputs: readonly Manifest[],\n options: ComposeManifestOptions = {},\n): ComposedManifestRequest {\n if (!Array.isArray(inputs) || inputs.length === 0) {\n throw new ManifestValidationError(\n \"composeManifestRequest requires at least one manifest\",\n );\n }\n\n const includeAccountRegistryPermissions =\n options.includeAccountRegistryPermissions ?? true;\n const manifests = inputs.map(validateManifest);\n const resolved = manifests.map(resolveManifest);\n const resources = resolved.flatMap((entry) => entry.resources);\n const delegationTargets = resolved.flatMap((entry) =>\n entry.additionalDelegates.map((delegate) => ({\n ...delegate,\n permissions: dedupeResources(delegate.permissions),\n })),\n );\n\n if (includeAccountRegistryPermissions) {\n resources.push(accountRegistryPermission());\n }\n const resourcesWithImplicitCapabilities =\n withCapabilitiesReadForSpaces(resources);\n\n const manifestsByAppId = new Map<string, Manifest[]>();\n for (const manifest of manifests) {\n const current = manifestsByAppId.get(manifest.app_id);\n if (current === undefined) {\n manifestsByAppId.set(manifest.app_id, [manifest]);\n } else {\n current.push(manifest);\n }\n }\n\n const registryRecords: ManifestRegistryRecord[] =\n includeAccountRegistryPermissions\n ? [...manifestsByAppId.entries()].map(([app_id, appManifests]) => ({\n key: `${ACCOUNT_REGISTRY_PATH}${app_id}`,\n app_id,\n manifests: appManifests.map((manifest) => ({\n ...manifest,\n permissions: manifest.permissions?.map(clonePermissionEntry),\n })),\n }))\n : [];\n\n return {\n manifests,\n resources: resourcesWithImplicitCapabilities,\n delegationTargets,\n registryRecords,\n expiryMs: Math.max(...resolved.map((entry) => entry.expiryMs)),\n includePublicSpace: resolved.some((entry) => entry.includePublicSpace),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Abilities map construction (bridge to WASM prepareSession / createDelegation)\n// ---------------------------------------------------------------------------\n\n/**\n * The shape `prepareSession` and the multi-resource `createDelegation` WASM\n * export both accept:\n *\n * ```\n * { [shortService]: { [path]: [fullUrnAction, ...] } }\n * ```\n *\n * - `shortService` is the recap-level service segment (`\"kv\"`, `\"sql\"`,\n * `\"duckdb\"`, `\"capabilities\"`, `\"hooks\"`) — not the manifest long form.\n * - `path` is the fully-resolved path (prefix already applied). An empty\n * string means \"no path segment\" on the resource URI.\n * - Action strings are full URNs like `\"tinycloud.kv/get\"`.\n *\n * This is a single source of truth for both the session's own recap (at\n * sign-in) and the delegations it can derive (post sign-in). We re-use it\n * for both so one manifest drives both sides.\n */\nexport type AbilitiesMap = Record<string, Record<string, string[]>>;\n\n/**\n * Per-space abilities map accepted by the newer WASM session config:\n *\n * ```\n * { [spaceIdOrName]: { [shortService]: { [path]: [fullUrnAction, ...] } } }\n * ```\n */\nexport type SpaceAbilitiesMap = Record<string, AbilitiesMap>;\n\n/**\n * Convert a list of {@link ResourceCapability} entries (manifest\n * long-form service, full-URN actions) into the {@link AbilitiesMap}\n * shape the WASM layer expects.\n *\n * When multiple entries target the same `(service, path)` pair, their\n * action lists are merged and deduped. Entries whose service has no\n * short-form mapping in {@link SERVICE_LONG_TO_SHORT} are rejected with\n * a {@link ManifestValidationError} — the SDK does not silently drop\n * unknown services because the recap encoding would lose them.\n *\n * Paths are kept verbatim: this function does NOT collapse\n * `\"com.listen.app/\"` and `\"com.listen.app\"` or reinterpret empty /\n * slash strings. Callers that care about path canonicalization should\n * normalize before calling.\n */\nexport function resourceCapabilitiesToAbilitiesMap(\n resources: readonly ResourceCapability[],\n): AbilitiesMap {\n const out: AbilitiesMap = {};\n for (const r of resources) {\n const shortService = SERVICE_LONG_TO_SHORT[r.service];\n if (shortService === undefined) {\n throw new ManifestValidationError(\n `unknown service '${r.service}' — no short-form mapping. Known services: ${Object.keys(SERVICE_LONG_TO_SHORT).join(\", \")}`,\n );\n }\n if (out[shortService] === undefined) {\n out[shortService] = {};\n }\n const pathsMap = out[shortService];\n const existing = pathsMap[r.path];\n if (existing === undefined) {\n // Copy so downstream mutation can't leak back into the input.\n pathsMap[r.path] = [...r.actions];\n } else {\n // Merge + dedupe while preserving first-seen order.\n const seen = new Set(existing);\n for (const action of r.actions) {\n if (!seen.has(action)) {\n existing.push(action);\n seen.add(action);\n }\n }\n }\n }\n return out;\n}\n\n/**\n * Group resolved capabilities by `space`, then convert each group into a WASM\n * abilities map. Short space names are left as-is here; platform layers that\n * know the wallet address and chain id turn them into full SpaceIds.\n */\nexport function resourceCapabilitiesToSpaceAbilitiesMap(\n resources: readonly ResourceCapability[],\n): SpaceAbilitiesMap {\n const grouped = new Map<string, ResourceCapability[]>();\n for (const resource of resources) {\n const entries = grouped.get(resource.space);\n if (entries === undefined) {\n grouped.set(resource.space, [resource]);\n } else {\n entries.push(resource);\n }\n }\n\n const out: SpaceAbilitiesMap = {};\n for (const [space, entries] of grouped.entries()) {\n out[space] = resourceCapabilitiesToAbilitiesMap(entries);\n }\n return out;\n}\n\n/**\n * Build the {@link AbilitiesMap} that a session should be signed with,\n * given a {@link ResolvedCapabilities} (i.e. the output of\n * {@link resolveManifest}).\n *\n * The resulting map is the **union** of:\n * 1. the app's own resources (`resolved.resources`), and\n * 2. every permission declared in every `additionalDelegates[*]` entry.\n *\n * The union is what makes the manifest's delegations ergonomic: at\n * sign-in, the session key acquires recap coverage for both the app's\n * runtime needs and every downstream delegation target. Post sign-in,\n * `delegateTo(backendDID, backendPermissions)` can then issue the\n * sub-delegation via the session key (no wallet prompt) because the\n * caps are already part of the granted set.\n *\n * Duplicate `(service, path, action)` triples across resources and\n * delegations are merged and deduped — the session SIWE doesn't need\n * them repeated.\n */\nexport function manifestAbilitiesUnion(\n resolved: ResolvedCapabilities,\n): AbilitiesMap {\n const all: ResourceCapability[] = [...resolved.resources];\n for (const delegate of resolved.additionalDelegates) {\n for (const perm of delegate.permissions) {\n all.push(perm);\n }\n }\n return resourceCapabilitiesToAbilitiesMap(all);\n}\n","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","/**\n * SDK Services - Core Types\n *\n * These types define the service architecture for TinyCloud SDK.\n * Services use dependency injection via IServiceContext for platform independence.\n */\n\n// =============================================================================\n// Result Type Pattern\n// =============================================================================\n\n/**\n * Result type for service operations.\n * Services return Result instead of throwing, making error handling explicit.\n *\n * @template T - The success data type\n * @template E - The error type (defaults to ServiceError)\n *\n * @example\n * ```typescript\n * const result = await kv.get('key');\n * if (result.ok) {\n * console.log(result.data);\n * } else {\n * console.error(result.error.code);\n * }\n * ```\n */\nexport type Result<T, E = ServiceError> =\n | { ok: true; data: T }\n | { ok: false; error: E };\n\n/**\n * Service error with structured information.\n */\nexport interface ServiceError {\n /** Error code for programmatic handling (e.g., 'KV_NOT_FOUND', 'AUTH_EXPIRED') */\n code: string;\n /** Human-readable error message */\n message: string;\n /** Service that produced the error (e.g., 'kv', 'sql') */\n service: string;\n /** Original error if this wraps another error */\n cause?: Error;\n /** Additional metadata about the error */\n meta?: Record<string, unknown>;\n}\n\n/**\n * Storage quota information returned with quota-related errors.\n */\nexport interface StorageQuotaInfo {\n usedBytes: number;\n limitBytes: number;\n service: string;\n}\n\n/**\n * Standard error codes used across services.\n */\nexport const ErrorCodes = {\n // Common errors\n NOT_FOUND: \"NOT_FOUND\",\n AUTH_EXPIRED: \"AUTH_EXPIRED\",\n AUTH_REQUIRED: \"AUTH_REQUIRED\",\n AUTH_UNAUTHORIZED: \"AUTH_UNAUTHORIZED\",\n NETWORK_ERROR: \"NETWORK_ERROR\",\n TIMEOUT: \"TIMEOUT\",\n ABORTED: \"ABORTED\",\n INVALID_INPUT: \"INVALID_INPUT\",\n PERMISSION_DENIED: \"PERMISSION_DENIED\",\n\n // KV-specific errors\n KV_NOT_FOUND: \"KV_NOT_FOUND\",\n KV_WRITE_FAILED: \"KV_WRITE_FAILED\",\n\n // SQL-specific errors\n SQL_ERROR: \"SQL_ERROR\",\n SQL_PERMISSION_DENIED: \"SQL_PERMISSION_DENIED\",\n SQL_DATABASE_NOT_FOUND: \"SQL_DATABASE_NOT_FOUND\",\n SQL_RESPONSE_TOO_LARGE: \"SQL_RESPONSE_TOO_LARGE\",\n SQL_QUOTA_EXCEEDED: \"SQL_QUOTA_EXCEEDED\",\n SQL_INVALID_STATEMENT: \"SQL_INVALID_STATEMENT\",\n SQL_SCHEMA_ERROR: \"SQL_SCHEMA_ERROR\",\n SQL_READONLY_VIOLATION: \"SQL_READONLY_VIOLATION\",\n\n // Storage quota errors\n STORAGE_QUOTA_EXCEEDED: \"STORAGE_QUOTA_EXCEEDED\",\n STORAGE_LIMIT_REACHED: \"STORAGE_LIMIT_REACHED\",\n\n // DuckDB-specific errors\n DUCKDB_ERROR: \"DUCKDB_ERROR\",\n DUCKDB_PERMISSION_DENIED: \"DUCKDB_PERMISSION_DENIED\",\n DUCKDB_DATABASE_NOT_FOUND: \"DUCKDB_DATABASE_NOT_FOUND\",\n DUCKDB_RESPONSE_TOO_LARGE: \"DUCKDB_RESPONSE_TOO_LARGE\",\n DUCKDB_QUOTA_EXCEEDED: \"DUCKDB_QUOTA_EXCEEDED\",\n DUCKDB_INVALID_STATEMENT: \"DUCKDB_INVALID_STATEMENT\",\n DUCKDB_SCHEMA_ERROR: \"DUCKDB_SCHEMA_ERROR\",\n DUCKDB_READONLY_VIOLATION: \"DUCKDB_READONLY_VIOLATION\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n// =============================================================================\n// Service Session\n// =============================================================================\n\n/**\n * Session data required for authenticated service operations.\n * Both TinyCloudSession and web-sdk Session can be cast to this interface.\n */\nexport interface ServiceSession {\n /** The delegation header containing the UCAN */\n delegationHeader: { Authorization: string };\n /** The delegation CID */\n delegationCid: string;\n /** The space ID for this session */\n spaceId: string;\n /** The verification method DID */\n verificationMethod: string;\n /** The session key JWK (required for invoke) */\n jwk: object;\n}\n\n// =============================================================================\n// Platform Dependencies (Injected)\n// =============================================================================\n\n/**\n * Headers type - compatible with both browser and Node.js.\n */\nexport type ServiceHeaders = Record<string, string> | [string, string][];\n\n/**\n * A single fact object to include in the UCAN invocation.\n * Facts are key-value objects that the server reads from the UCAN facts field.\n */\nexport interface InvocationFact {\n [key: string]: unknown;\n}\n\n/**\n * Facts to include in the UCAN invocation.\n * This is an array of fact objects per the UCAN spec.\n * Used to pass additional parameters that the server reads from the UCAN facts field.\n */\nexport type InvocationFacts = InvocationFact[];\n\n/**\n * Invoke function signature - platform-specific implementation injected via DI.\n * Both node-sdk-wasm and web-sdk-wasm export this with identical signature.\n *\n * @param session - The service session with delegation data\n * @param service - Service name (e.g., \"kv\")\n * @param path - Resource path or key\n * @param action - Action to perform (e.g., \"tinycloud.kv/get\")\n * @param facts - Optional facts to include in the UCAN (e.g., for capabilities/read params)\n * @returns Headers to include in the request\n */\nexport type InvokeFunction = (\n session: ServiceSession,\n service: string,\n path: string,\n action: string,\n facts?: InvocationFacts,\n) => ServiceHeaders;\n\n/**\n * Multi-resource invocation entry.\n */\nexport interface InvokeAnyEntry {\n /**\n * Legacy space-scoped resource. Optional when `resource` is provided.\n */\n spaceId?: string;\n service: string;\n path: string;\n action: string;\n /** Optional raw resource URI. When set, WASM signs this URI directly. */\n resource?: string;\n}\n\n/**\n * Invoke function for minting a single authorization header that covers\n * multiple capabilities across one effective invoker.\n */\nexport type InvokeAnyFunction = (\n session: ServiceSession,\n entries: InvokeAnyEntry[],\n facts?: InvocationFacts,\n) => ServiceHeaders;\n\n/**\n * Fetch request options - compatible with standard fetch API.\n */\nexport interface FetchRequestInit {\n method?: string;\n headers?: ServiceHeaders;\n body?: Blob | FormData | string;\n signal?: AbortSignal;\n}\n\n/**\n * Fetch response interface - compatible with standard Response.\n */\nexport interface FetchResponse {\n ok: boolean;\n status: number;\n statusText: string;\n body?: unknown;\n headers: {\n get(name: string): string | null;\n };\n json(): Promise<unknown>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n blob(): Promise<Blob>;\n}\n\n/**\n * Fetch function signature - allows for custom fetch implementations.\n * Compatible with both browser fetch and Node.js fetch.\n */\nexport type FetchFunction = (\n url: string,\n init?: FetchRequestInit,\n) => Promise<FetchResponse>;\n\n// =============================================================================\n// Retry Policy\n// =============================================================================\n\n/**\n * Configuration for automatic retry of failed requests.\n */\nexport interface RetryPolicy {\n /** Maximum number of attempts (including initial) */\n maxAttempts: number;\n /** Backoff strategy between retries */\n backoff: \"none\" | \"linear\" | \"exponential\";\n /** Base delay in milliseconds for backoff calculation */\n baseDelayMs: number;\n /** Maximum delay in milliseconds between retries */\n maxDelayMs: number;\n /** Error codes that should trigger a retry */\n retryableErrors: string[];\n}\n\n/**\n * Default retry policy.\n */\nexport const defaultRetryPolicy: RetryPolicy = {\n maxAttempts: 3,\n backoff: \"exponential\",\n baseDelayMs: 1000,\n maxDelayMs: 10000,\n retryableErrors: [ErrorCodes.NETWORK_ERROR, ErrorCodes.TIMEOUT],\n};\n\n// =============================================================================\n// Service Context\n// =============================================================================\n\n/**\n * Event handler function type.\n */\nexport type EventHandler = (data: unknown) => void;\n\n/**\n * SDK telemetry event handler.\n */\nexport type TelemetryEventHandler = (event: string, data: unknown) => void;\n\n/**\n * Default-off telemetry configuration.\n */\nexport type TelemetryConfig =\n | boolean\n | {\n enabled?: boolean;\n onEvent?: TelemetryEventHandler;\n };\n\n/**\n * Service interface - base contract for all services.\n */\nexport interface IService {\n /** Initialize service with context */\n initialize(context: IServiceContext): void;\n\n /** Called when session changes (sign-in, sign-out, refresh) */\n onSessionChange(session: ServiceSession | null): void;\n\n /** Called when SDK signs out - should abort pending operations */\n onSignOut(): void;\n\n /** Service-specific configuration */\n readonly config: Record<string, unknown>;\n}\n\n/**\n * Context provided to services for accessing platform dependencies.\n * The SDK creates this context and passes it to services during initialization.\n */\nexport interface IServiceContext {\n // Session management\n /** Current active session, or null if not authenticated */\n readonly session: ServiceSession | null;\n /** Whether there is an active authenticated session */\n readonly isAuthenticated: boolean;\n\n // Platform dependencies (injected by SDK)\n /** Platform-specific invoke function from WASM binding */\n readonly invoke: InvokeFunction;\n /** Optional multi-resource invoke function */\n readonly invokeAny?: InvokeAnyFunction;\n /** Fetch function (defaults to globalThis.fetch) */\n readonly fetch: FetchFunction;\n /** Available TinyCloud host URLs */\n readonly hosts: string[];\n\n // Cross-service access\n /** Get another registered service by name */\n getService<T extends IService>(name: string): T | undefined;\n\n // Telemetry/Events\n /** Emit a telemetry event */\n emit(event: string, data: unknown): void;\n /** Subscribe to events */\n on(event: string, handler: EventHandler): () => void;\n\n // Lifecycle\n /** Abort signal that fires when SDK signs out */\n readonly abortSignal: AbortSignal;\n\n // Retry policy\n /** Retry policy for failed requests */\n readonly retryPolicy: RetryPolicy;\n}\n\n// =============================================================================\n// Telemetry Events\n// =============================================================================\n\n/**\n * Event emitted before a service request.\n */\nexport interface ServiceRequestEvent {\n service: string;\n action: string;\n span?: string;\n key?: string;\n timestamp: number;\n}\n\n/**\n * Event emitted after a service response.\n */\nexport interface ServiceResponseEvent {\n service: string;\n action: string;\n span?: string;\n ok: boolean;\n duration: number;\n durationMs?: number;\n status?: number;\n}\n\n/**\n * Event emitted on service error.\n */\nexport interface ServiceErrorEvent {\n service: string;\n span?: string;\n error: ServiceError;\n}\n\n/**\n * Event emitted on retry attempt.\n */\nexport interface ServiceRetryEvent {\n service: string;\n attempt: number;\n maxAttempts: number;\n error: ServiceError;\n}\n\n/**\n * Generic named span event for aggregating operation timings.\n */\nexport interface TelemetrySpanEvent {\n span: string;\n ok: boolean;\n durationMs: number;\n service?: string;\n action?: string;\n status?: number;\n error?: ServiceError;\n}\n\n/**\n * Telemetry event names.\n */\nexport const TelemetryEvents = {\n SPAN: \"telemetry.span\",\n SERVICE_REQUEST: \"service.request\",\n SERVICE_RESPONSE: \"service.response\",\n SERVICE_ERROR: \"service.error\",\n SERVICE_RETRY: \"service.retry\",\n SESSION_CHANGED: \"session.changed\",\n SESSION_EXPIRED: \"session.expired\",\n} as const;\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/**\n * Create a success result.\n */\nexport function ok<T>(data: T): Result<T> {\n return { ok: true, data };\n}\n\n/**\n * Create an error result.\n */\nexport function err<E = ServiceError>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n/**\n * Create a ServiceError.\n */\nexport function serviceError(\n code: string,\n message: string,\n service: string,\n options?: { cause?: Error; meta?: Record<string, unknown> },\n): ServiceError {\n return {\n code,\n message,\n service,\n cause: options?.cause,\n meta: options?.meta,\n };\n}\n","/**\n * Zod schemas for SDK Services API response types.\n *\n * This is the source of truth for service response types. TypeScript types\n * are derived from these schemas using z.infer<>.\n *\n * @packageDocumentation\n */\n\nimport { z } from \"zod\";\n\n// =============================================================================\n// Validation Error Type\n// =============================================================================\n\n/**\n * Validation error type for schema validation failures.\n */\nexport interface ValidationError {\n code: \"VALIDATION_ERROR\";\n message: string;\n service: string;\n meta?: {\n issues: z.ZodIssue[];\n path?: string;\n };\n}\n\n// =============================================================================\n// Service Error Schema\n// =============================================================================\n\n/**\n * Schema for service error with structured information.\n */\nexport const ServiceErrorSchema = z.object({\n /** Error code for programmatic handling (e.g., 'KV_NOT_FOUND', 'AUTH_EXPIRED') */\n code: z.string(),\n /** Human-readable error message */\n message: z.string(),\n /** Service that produced the error (e.g., 'kv', 'sql') */\n service: z.string(),\n /** Original error if this wraps another error - not validated since Error is a class */\n cause: z.unknown().optional(),\n /** Additional metadata about the error - passthrough allows any object properties */\n meta: z.object({}).passthrough().optional(),\n});\n\nexport type ServiceErrorType = z.infer<typeof ServiceErrorSchema>;\n\n// =============================================================================\n// Result Schema Factory\n// =============================================================================\n\n/**\n * Creates a Result schema for a given data type.\n * Result is a discriminated union: { ok: true, data: T } | { ok: false, error: E }\n *\n * @param dataSchema - Zod schema for the success data type\n * @param errorSchema - Zod schema for the error type (defaults to ServiceErrorSchema)\n * @returns A Zod schema for Result<T, E>\n *\n * @example\n * ```typescript\n * const KVGetResultSchema = createResultSchema(z.string());\n * type KVGetResult = z.infer<typeof KVGetResultSchema>;\n * ```\n */\nexport function createResultSchema<T extends z.ZodTypeAny, E extends z.ZodTypeAny>(\n dataSchema: T,\n errorSchema: E = ServiceErrorSchema as unknown as E\n) {\n return z.discriminatedUnion(\"ok\", [\n z.object({\n ok: z.literal(true),\n data: dataSchema,\n }),\n z.object({\n ok: z.literal(false),\n error: errorSchema,\n }),\n ]);\n}\n\n/**\n * Pre-built Result schema with unknown data and ServiceError.\n * Useful for generic validation before type narrowing.\n */\nexport const GenericResultSchema = createResultSchema(z.unknown(), ServiceErrorSchema);\n\n// =============================================================================\n// KV Response Schemas\n// =============================================================================\n\n/**\n * Schema for KV response headers metadata.\n * Note: The `get` method is a function and cannot be validated with Zod.\n * This schema validates the data properties only.\n */\nexport const KVResponseHeadersSchema = z.object({\n /** ETag for conditional requests */\n etag: z.string().optional(),\n /** Content type of the stored value */\n contentType: z.string().optional(),\n /** Last modification timestamp */\n lastModified: z.string().optional(),\n /** Content length in bytes */\n contentLength: z.number().optional(),\n});\n\nexport type KVResponseHeadersType = z.infer<typeof KVResponseHeadersSchema>;\n\n/**\n * Creates a KVResponse schema for a given data type.\n *\n * @param dataSchema - Zod schema for the data payload type\n * @returns A Zod schema for KVResponse<T>\n *\n * @example\n * ```typescript\n * const UserResponseSchema = createKVResponseSchema(UserSchema);\n * type UserResponse = z.infer<typeof UserResponseSchema>;\n * ```\n */\nexport function createKVResponseSchema<T extends z.ZodTypeAny>(dataSchema: T) {\n return z.object({\n /** The data payload */\n data: dataSchema,\n /** Response headers with metadata */\n headers: KVResponseHeadersSchema,\n });\n}\n\n/**\n * Generic KVResponse schema with unknown data.\n * Useful for generic validation before type narrowing.\n */\nexport const GenericKVResponseSchema = createKVResponseSchema(z.unknown());\n\nexport type GenericKVResponseType = z.infer<typeof GenericKVResponseSchema>;\n\n/**\n * Schema for KV list response.\n */\nexport const KVListResponseSchema = z.object({\n /** Array of keys matching the list criteria */\n keys: z.array(z.string()),\n});\n\nexport type KVListResponseType = z.infer<typeof KVListResponseSchema>;\n\n/**\n * Result schema for KV list operations.\n */\nexport const KVListResultSchema = createResultSchema(KVListResponseSchema);\n\nexport type KVListResultType = z.infer<typeof KVListResultSchema>;\n\n// =============================================================================\n// Telemetry Event Schemas\n// =============================================================================\n\n/**\n * Schema for service request event.\n */\nexport const ServiceRequestEventSchema = z.object({\n service: z.string(),\n action: z.string(),\n span: z.string().optional(),\n key: z.string().optional(),\n timestamp: z.number(),\n});\n\nexport type ServiceRequestEventType = z.infer<typeof ServiceRequestEventSchema>;\n\n/**\n * Schema for service response event.\n */\nexport const ServiceResponseEventSchema = z.object({\n service: z.string(),\n action: z.string(),\n span: z.string().optional(),\n ok: z.boolean(),\n duration: z.number(),\n durationMs: z.number().optional(),\n status: z.number().optional(),\n});\n\nexport type ServiceResponseEventType = z.infer<typeof ServiceResponseEventSchema>;\n\n/**\n * Schema for service error event.\n */\nexport const ServiceErrorEventSchema = z.object({\n service: z.string(),\n span: z.string().optional(),\n error: ServiceErrorSchema,\n});\n\nexport type ServiceErrorEventType = z.infer<typeof ServiceErrorEventSchema>;\n\n/**\n * Schema for service retry event.\n */\nexport const ServiceRetryEventSchema = z.object({\n service: z.string(),\n attempt: z.number().int().positive(),\n maxAttempts: z.number().int().positive(),\n error: ServiceErrorSchema,\n});\n\nexport type ServiceRetryEventType = z.infer<typeof ServiceRetryEventSchema>;\n\n/**\n * Schema for generic named span event.\n */\nexport const TelemetrySpanEventSchema = z.object({\n span: z.string(),\n ok: z.boolean(),\n durationMs: z.number(),\n service: z.string().optional(),\n action: z.string().optional(),\n status: z.number().optional(),\n error: ServiceErrorSchema.optional(),\n});\n\nexport type TelemetrySpanEventType = z.infer<typeof TelemetrySpanEventSchema>;\n\n// =============================================================================\n// Retry Policy Schema\n// =============================================================================\n\n/**\n * Schema for retry policy configuration.\n */\nexport const RetryPolicySchema = z.object({\n /** Maximum number of attempts (including initial) */\n maxAttempts: z.number().int().positive(),\n /** Backoff strategy between retries */\n backoff: z.enum([\"none\", \"linear\", \"exponential\"]),\n /** Base delay in milliseconds for backoff calculation */\n baseDelayMs: z.number().nonnegative(),\n /** Maximum delay in milliseconds between retries */\n maxDelayMs: z.number().nonnegative(),\n /** Error codes that should trigger a retry */\n retryableErrors: z.array(z.string()),\n});\n\nexport type RetryPolicyType = z.infer<typeof RetryPolicySchema>;\n\n// =============================================================================\n// Service Session Schema\n// =============================================================================\n\n/**\n * Schema for service session data required for authenticated operations.\n */\nexport const ServiceSessionSchema = z.object({\n /** The delegation header containing the UCAN */\n delegationHeader: z.object({\n Authorization: z.string(),\n }),\n /** The delegation CID */\n delegationCid: z.string(),\n /** The space ID for this session */\n spaceId: z.string(),\n /** The verification method DID */\n verificationMethod: z.string(),\n /** The session key JWK (required for invoke) */\n jwk: z.object({}).passthrough(),\n});\n\nexport type ServiceSessionType = z.infer<typeof ServiceSessionSchema>;\n\n// =============================================================================\n// Validation Helpers\n// =============================================================================\n\n/**\n * Validate service error against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateServiceError(\n data: unknown\n): { ok: true; data: ServiceErrorType } | { ok: false; error: ValidationError } {\n const result = ServiceErrorSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"validation\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validate KV list response against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateKVListResponse(\n data: unknown\n): { ok: true; data: KVListResponseType } | { ok: false; error: ValidationError } {\n const result = KVListResponseSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"kv\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validate KV response headers against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateKVResponseHeaders(\n data: unknown\n): { ok: true; data: KVResponseHeadersType } | { ok: false; error: ValidationError } {\n const result = KVResponseHeadersSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"kv\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validate service session against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateServiceSession(\n data: unknown\n): { ok: true; data: ServiceSessionType } | { ok: false; error: ValidationError } {\n const result = ServiceSessionSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"session\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validate retry policy against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateRetryPolicy(\n data: unknown\n): { ok: true; data: RetryPolicyType } | { ok: false; error: ValidationError } {\n const result = RetryPolicySchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"config\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validate service request event against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateServiceRequestEvent(\n data: unknown\n): { ok: true; data: ServiceRequestEventType } | { ok: false; error: ValidationError } {\n const result = ServiceRequestEventSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"telemetry\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validate service response event against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateServiceResponseEvent(\n data: unknown\n): { ok: true; data: ServiceResponseEventType } | { ok: false; error: ValidationError } {\n const result = ServiceResponseEventSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"telemetry\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n\n/**\n * Validate named telemetry span event against the schema.\n *\n * @param data - Unknown data to validate\n * @returns Result with validated data or validation error\n */\nexport function validateTelemetrySpanEvent(\n data: unknown\n): { ok: true; data: TelemetrySpanEventType } | { ok: false; error: ValidationError } {\n const result = TelemetrySpanEventSchema.safeParse(data);\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"VALIDATION_ERROR\",\n message: result.error.message,\n service: \"telemetry\",\n meta: { issues: result.error.issues },\n },\n };\n }\n return { ok: true, data: result.data };\n}\n","/**\n * ServiceContext implementation for TinyCloud SDK Services\n * @module @tinycloud/sdk-services\n */\n\nimport {\n IServiceContext,\n IService,\n ServiceSession,\n RetryPolicy,\n InvokeFunction,\n InvokeAnyFunction,\n FetchFunction,\n defaultRetryPolicy,\n EventHandler,\n TelemetryEventHandler,\n TelemetryConfig,\n} from \"./types\";\n\n/**\n * Configuration options for ServiceContext.\n */\nexport interface ServiceContextConfig {\n /** Function to invoke WASM operations */\n invoke: InvokeFunction;\n /** Optional function to mint a single authorization header for multiple capabilities */\n invokeAny?: InvokeAnyFunction;\n /** Function to make HTTP requests (defaults to globalThis.fetch) */\n fetch?: FetchFunction;\n /** List of TinyCloud host URLs */\n hosts: string[];\n /** Initial session (optional) */\n session?: ServiceSession | null;\n /** Retry policy configuration */\n retryPolicy?: Partial<RetryPolicy>;\n /** Default-off telemetry event delivery. */\n telemetry?: TelemetryConfig;\n}\n\n/**\n * ServiceContext provides platform dependencies and cross-service access to services.\n * This is the primary interface services use to interact with the SDK runtime.\n *\n * @example\n * ```typescript\n * const context = new ServiceContext({\n * invoke: wasmInvoke,\n * hosts: ['https://node.tinycloud.xyz'],\n * retryPolicy: { maxAttempts: 5 },\n * });\n *\n * // Register a service\n * const kvService = new KVService({});\n * context.registerService('kv', kvService);\n * kvService.initialize(context);\n *\n * // Update session when user signs in\n * context.setSession(userSession);\n * ```\n */\nexport class ServiceContext implements IServiceContext {\n private _session: ServiceSession | null = null;\n private _services: Map<string, IService> = new Map();\n private _eventHandlers: Map<string, Set<EventHandler>> = new Map();\n private _abortController: AbortController = new AbortController();\n private readonly _invoke: InvokeFunction;\n private readonly _invokeAny?: InvokeAnyFunction;\n private readonly _fetch: FetchFunction;\n private readonly _hosts: string[];\n private readonly _retryPolicy: RetryPolicy;\n private readonly _telemetryEnabled: boolean;\n private readonly _telemetryHandler?: TelemetryEventHandler;\n\n constructor(config: ServiceContextConfig) {\n this._invoke = config.invoke;\n this._invokeAny = config.invokeAny;\n this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n this._hosts = config.hosts;\n this._session = config.session ?? null;\n this._retryPolicy = {\n ...defaultRetryPolicy,\n ...config.retryPolicy,\n };\n this._telemetryEnabled =\n typeof config.telemetry === \"boolean\"\n ? config.telemetry\n : config.telemetry?.enabled === true;\n this._telemetryHandler =\n typeof config.telemetry === \"object\" ? config.telemetry.onEvent : undefined;\n }\n\n // ============================================================\n // Session Management\n // ============================================================\n\n /**\n * Get the current session.\n */\n get session(): ServiceSession | null {\n return this._session;\n }\n\n /**\n * Check if the context has an authenticated session.\n */\n get isAuthenticated(): boolean {\n return this._session !== null;\n }\n\n /**\n * Update the session and notify all registered services.\n *\n * @param session - New session or null to clear\n */\n setSession(session: ServiceSession | null): void {\n this._session = session;\n this.emit('session.changed', { authenticated: session !== null });\n\n // Notify all services of session change\n for (const service of this._services.values()) {\n service.onSessionChange(session);\n }\n }\n\n // ============================================================\n // Platform Dependencies\n // ============================================================\n\n /**\n * Get the invoke function for WASM operations.\n */\n get invoke(): InvokeFunction {\n return this._invoke;\n }\n\n /**\n * Get the multi-resource invoke function when available.\n */\n get invokeAny(): InvokeAnyFunction | undefined {\n return this._invokeAny;\n }\n\n /**\n * Get the fetch function for HTTP requests.\n */\n get fetch(): FetchFunction {\n return this._fetch;\n }\n\n /**\n * Get the list of TinyCloud host URLs.\n */\n get hosts(): string[] {\n return this._hosts;\n }\n\n // ============================================================\n // Service Registry\n // ============================================================\n\n /**\n * Register a service with the context.\n *\n * @param name - Service name (e.g., 'kv')\n * @param service - Service instance\n */\n registerService(name: string, service: IService): void {\n this._services.set(name, service);\n }\n\n /**\n * Unregister a service from the context.\n *\n * @param name - Service name to remove\n */\n unregisterService(name: string): void {\n this._services.delete(name);\n }\n\n /**\n * Get a registered service by name.\n *\n * @param name - Service name\n * @returns The service instance or undefined if not registered\n */\n getService<T extends IService>(name: string): T | undefined {\n return this._services.get(name) as T | undefined;\n }\n\n // ============================================================\n // Event System (Telemetry)\n // ============================================================\n\n /**\n * Emit a telemetry event.\n *\n * @param event - Event name\n * @param data - Event data\n */\n emit(event: string, data: unknown): void {\n if (this._telemetryEnabled && this._telemetryHandler) {\n try {\n this._telemetryHandler(event, data);\n } catch (error) {\n // Don't let telemetry handlers break SDK operations.\n console.error(`Error in telemetry handler for \"${event}\":`, error);\n }\n }\n\n const handlers = this._eventHandlers.get(event);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(data);\n } catch (error) {\n // Don't let event handler errors break the flow\n console.error(`Error in event handler for \"${event}\":`, error);\n }\n }\n }\n }\n\n /**\n * Subscribe to telemetry events.\n *\n * @param event - Event name to subscribe to\n * @param handler - Handler function\n * @returns Unsubscribe function\n */\n on(event: string, handler: EventHandler): () => void {\n if (!this._eventHandlers.has(event)) {\n this._eventHandlers.set(event, new Set());\n }\n this._eventHandlers.get(event)!.add(handler);\n\n // Return unsubscribe function\n return () => {\n const handlers = this._eventHandlers.get(event);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n this._eventHandlers.delete(event);\n }\n }\n };\n }\n\n /**\n * Remove all event handlers for an event.\n *\n * @param event - Event name (if omitted, clears all events)\n */\n clearEventHandlers(event?: string): void {\n if (event) {\n this._eventHandlers.delete(event);\n } else {\n this._eventHandlers.clear();\n }\n }\n\n // ============================================================\n // Lifecycle\n // ============================================================\n\n /**\n * Get the abort signal for cancelling operations.\n */\n get abortSignal(): AbortSignal {\n return this._abortController.signal;\n }\n\n /**\n * Abort all pending operations and notify services.\n * Creates a new AbortController for future operations.\n */\n abort(): void {\n this._abortController.abort();\n this._abortController = new AbortController();\n\n // Notify all services\n for (const service of this._services.values()) {\n service.onSignOut();\n }\n }\n\n /**\n * Sign out - abort operations and clear session.\n */\n signOut(): void {\n this.abort();\n this.setSession(null);\n this.emit('session.expired', {});\n }\n\n // ============================================================\n // Retry Policy\n // ============================================================\n\n /**\n * Get the retry policy configuration.\n */\n get retryPolicy(): RetryPolicy {\n return this._retryPolicy;\n }\n}\n","/**\n * SDK Services - Error Utilities\n *\n * Utilities for creating and handling service errors.\n */\n\nimport { ServiceError, ErrorCodes, err, serviceError } from \"./types\";\n\n/**\n * Create a service error for authentication required.\n */\nexport function authRequiredError(service: string): ServiceError {\n return {\n code: ErrorCodes.AUTH_REQUIRED,\n message: \"Authentication required. Please sign in first.\",\n service,\n };\n}\n\n/**\n * Create a service error for expired authentication.\n */\nexport function authExpiredError(service: string): ServiceError {\n return {\n code: ErrorCodes.AUTH_EXPIRED,\n message: \"Session has expired. Please sign in again.\",\n service,\n };\n}\n\n/**\n * Create a service error for network issues.\n */\nexport function networkError(\n service: string,\n message: string,\n cause?: Error\n): ServiceError {\n return {\n code: ErrorCodes.NETWORK_ERROR,\n message,\n service,\n cause,\n };\n}\n\n/**\n * Create a service error for timeouts.\n */\nexport function timeoutError(service: string): ServiceError {\n return {\n code: ErrorCodes.TIMEOUT,\n message: \"Request timed out.\",\n service,\n };\n}\n\n/**\n * Create a service error for aborted requests.\n */\nexport function abortedError(service: string): ServiceError {\n return {\n code: ErrorCodes.ABORTED,\n message: \"Request was aborted.\",\n service,\n };\n}\n\n/**\n * Create a service error for not found resources.\n */\nexport function notFoundError(\n service: string,\n resource: string\n): ServiceError {\n return {\n code: ErrorCodes.NOT_FOUND,\n message: `Resource not found: ${resource}`,\n service,\n };\n}\n\n/**\n * Create a service error for permission denied.\n */\nexport function permissionDeniedError(\n service: string,\n action: string\n): ServiceError {\n return {\n code: ErrorCodes.PERMISSION_DENIED,\n message: `Permission denied for action: ${action}`,\n service,\n };\n}\n\n/**\n * Parse the server's \"Unauthorized Action: {resource} / {ability}\" pattern.\n */\nexport function parseAuthError(responseText: string): { resource?: string; action?: string } {\n const match = responseText.match(/^Unauthorized Action:\\s*(.+?)\\s*\\/\\s*(tinycloud\\.\\S+)$/m);\n if (match) {\n return { resource: match[1].trim(), action: match[2].trim() };\n }\n return {};\n}\n\n/**\n * Create a service error for unauthorized action (missing capability).\n */\nexport function authUnauthorizedError(\n service: string,\n message: string,\n meta?: Record<string, unknown>\n): ServiceError {\n return serviceError(ErrorCodes.AUTH_UNAUTHORIZED, message, service, { meta });\n}\n\n/**\n * Create a service error for storage quota exceeded (402 Payment Required).\n */\nexport function storageQuotaExceededError(\n service: string,\n message: string,\n meta?: Record<string, unknown>\n): ServiceError {\n return {\n code: ErrorCodes.STORAGE_QUOTA_EXCEEDED,\n message,\n service,\n meta,\n };\n}\n\n/**\n * Create a service error for storage limit reached (413 Payload Too Large).\n */\nexport function storageLimitReachedError(\n service: string,\n message: string,\n meta?: Record<string, unknown>\n): ServiceError {\n return {\n code: ErrorCodes.STORAGE_LIMIT_REACHED,\n message,\n service,\n meta,\n };\n}\n\n/**\n * Wrap an unknown error in a ServiceError.\n */\nexport function wrapError(\n service: string,\n error: unknown,\n defaultCode: string = ErrorCodes.NETWORK_ERROR\n): ServiceError {\n if (error instanceof Error) {\n // Check for abort errors\n if (error.name === \"AbortError\") {\n return abortedError(service);\n }\n\n // Check for timeout errors (varies by platform)\n if (\n error.name === \"TimeoutError\" ||\n error.message.toLowerCase().includes(\"timeout\")\n ) {\n return timeoutError(service);\n }\n\n return {\n code: defaultCode,\n message: error.message,\n service,\n cause: error,\n };\n }\n\n return {\n code: defaultCode,\n message: String(error),\n service,\n };\n}\n\n/**\n * Create an error Result from a ServiceError.\n */\nexport function errorResult(error: ServiceError) {\n return err(error);\n}\n","/**\n * BaseService - Abstract base class for all TinyCloud services.\n *\n * Provides common functionality:\n * - Context management\n * - Session lifecycle hooks\n * - Abort signal handling\n * - Telemetry emission\n */\n\nimport {\n IService,\n IServiceContext,\n ServiceSession,\n ServiceError,\n TelemetryEvents,\n err,\n Result,\n} from \"../types\";\nimport { authRequiredError, wrapError } from \"../errors\";\n\n/**\n * Abstract base class for TinyCloud services.\n *\n * Services extend this class to get common functionality like\n * context management, session lifecycle, and abort handling.\n *\n * @example\n * ```typescript\n * class MyService extends BaseService implements IMyService {\n * static readonly serviceName = 'myservice';\n *\n * constructor(config: MyServiceConfig = {}) {\n * super();\n * this._config = config;\n * }\n *\n * async doSomething(): Promise<Result<Data>> {\n * if (!this.requireAuth()) {\n * return err(authRequiredError('myservice'));\n * }\n * // ... implementation\n * }\n * }\n * ```\n */\nexport abstract class BaseService implements IService {\n /**\n * Service identifier used for registration.\n * Must be overridden by subclasses.\n */\n static readonly serviceName: string;\n\n /**\n * Service context providing access to platform dependencies.\n * Set during initialize().\n */\n protected context!: IServiceContext;\n\n /**\n * Abort controller for this service's operations.\n * Reset on sign-out.\n */\n protected abortController: AbortController = new AbortController();\n\n /**\n * Service-specific configuration.\n */\n protected _config: Record<string, unknown> = {};\n\n /**\n * Get the service configuration.\n */\n get config(): Record<string, unknown> {\n return this._config;\n }\n\n /**\n * Initialize the service with context.\n * Called by the SDK after instantiation.\n *\n * @param context - The service context\n */\n initialize(context: IServiceContext): void {\n this.context = context;\n }\n\n /**\n * Called when session changes (sign-in, sign-out, refresh).\n * Override in subclasses to handle session changes.\n *\n * @param session - The new session, or null if signed out\n */\n onSessionChange(session: ServiceSession | null): void {\n // Override in subclass if needed\n }\n\n /**\n * Called when SDK signs out.\n * Aborts all pending operations.\n */\n onSignOut(): void {\n this.abortController.abort();\n this.abortController = new AbortController();\n }\n\n /**\n * Get the abort signal for this service.\n * Combines the service-level abort with context-level abort.\n */\n protected get abortSignal(): AbortSignal {\n return this.abortController.signal;\n }\n\n /**\n * Check if the service is authenticated.\n */\n protected get isAuthenticated(): boolean {\n return this.context?.isAuthenticated ?? false;\n }\n\n /**\n * Get the current session.\n * Throws if not authenticated.\n */\n protected get session(): ServiceSession {\n if (!this.context?.session) {\n throw new Error(\"Not authenticated\");\n }\n return this.context.session;\n }\n\n /**\n * Check authentication and return error result if not authenticated.\n * Use this at the start of methods that require authentication.\n *\n * @returns true if authenticated, false otherwise\n */\n protected requireAuth(): boolean {\n return this.isAuthenticated;\n }\n\n /**\n * Emit a telemetry event.\n *\n * @param event - Event name\n * @param data - Event data\n */\n protected emit(event: string, data: unknown): void {\n this.context?.emit(event, data);\n }\n\n /**\n * Emit a service request event.\n *\n * @param action - The action being performed\n * @param key - Optional key/path being accessed\n */\n protected emitRequest(action: string, key?: string): void {\n const service = this.getServiceName();\n this.emit(TelemetryEvents.SERVICE_REQUEST, {\n service,\n action,\n span: this.spanName(action),\n key,\n timestamp: Date.now(),\n });\n }\n\n /**\n * Emit a service response event.\n *\n * @param action - The action that was performed\n * @param ok - Whether the request was successful\n * @param startTime - Start time for duration calculation\n * @param status - Optional HTTP status code\n */\n protected emitResponse(\n action: string,\n ok: boolean,\n startTime: number,\n status?: number\n ): void {\n const service = this.getServiceName();\n const durationMs = Date.now() - startTime;\n const span = this.spanName(action);\n this.emit(TelemetryEvents.SERVICE_RESPONSE, {\n service,\n action,\n span,\n ok,\n duration: durationMs,\n durationMs,\n status,\n });\n this.emit(TelemetryEvents.SPAN, {\n span,\n service,\n action,\n ok,\n durationMs,\n status,\n });\n }\n\n /**\n * Emit a service error event.\n *\n * @param error - The service error\n */\n protected emitError(error: ServiceError, action?: string): void {\n const span = action ? this.spanName(action) : undefined;\n this.emit(TelemetryEvents.SERVICE_ERROR, {\n service: this.getServiceName(),\n ...(span ? { span } : {}),\n error,\n });\n }\n\n /**\n * Get the service name from the static property.\n * Subclasses must define static serviceName.\n */\n protected getServiceName(): string {\n return (this.constructor as typeof BaseService).serviceName;\n }\n\n /**\n * Stable span name used by SDK telemetry sinks.\n */\n protected spanName(action: string): string {\n return `sdk.${this.getServiceName()}.${action}`;\n }\n\n /**\n * Create a combined abort signal from multiple sources.\n *\n * @param signals - Additional abort signals to combine\n * @returns A combined abort signal\n */\n protected combineSignals(...signals: (AbortSignal | undefined)[]): AbortSignal {\n const controller = new AbortController();\n const allSignals = [this.abortSignal, ...signals.filter(Boolean)] as AbortSignal[];\n\n for (const signal of allSignals) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n return controller.signal;\n }\n signal.addEventListener(\"abort\", () => controller.abort(signal.reason), {\n once: true,\n });\n }\n\n return controller.signal;\n }\n\n /**\n * Wrap an operation with error handling and telemetry.\n *\n * @param action - The action name for telemetry\n * @param key - Optional key for telemetry\n * @param operation - The operation to execute\n * @returns Result of the operation\n */\n protected async withTelemetry<T>(\n action: string,\n key: string | undefined,\n operation: () => Promise<Result<T>>\n ): Promise<Result<T>> {\n const startTime = Date.now();\n this.emitRequest(action, key);\n\n try {\n const result = await operation();\n\n if (result.ok) {\n this.emitResponse(action, true, startTime);\n } else {\n this.emitResponse(action, false, startTime);\n this.emitError(result.error, action);\n }\n\n return result;\n } catch (error) {\n const serviceError = wrapError(this.getServiceName(), error);\n this.emitResponse(action, false, startTime);\n this.emitError(serviceError, action);\n return err(serviceError);\n }\n }\n}\n","/**\n * PrefixedKVService - A prefix-scoped view of KVService.\n *\n * Provides key-value operations scoped to a specific prefix.\n * All operations automatically prefix keys, enabling app data isolation\n * within a shared space.\n *\n * @example\n * ```typescript\n * const space = sdk.space('default');\n *\n * // Create prefix-scoped views\n * const myApp = space.kv.withPrefix('/app.myapp.com');\n * const sharedPhotos = space.kv.withPrefix('/photos');\n *\n * // Operations are automatically prefixed\n * await myApp.put('settings.json', { theme: 'dark' });\n * // -> Actually writes to: /app.myapp.com/settings.json\n *\n * await myApp.get('settings.json');\n * // -> Actually reads from: /app.myapp.com/settings.json\n *\n * await sharedPhotos.list();\n * // -> Lists: /photos/*\n *\n * // Nested prefixes\n * const settings = myApp.withPrefix('/settings');\n * await settings.get('theme.json'); // -> /app.myapp.com/settings/theme.json\n * ```\n */\n\nimport { Result } from \"../types\";\nimport {\n KVGetOptions,\n KVPutOptions,\n KVBatchPutItem,\n KVBatchPutOptions,\n KVBatchPutResponse,\n KVListOptions,\n KVDeleteOptions,\n KVHeadOptions,\n KVCreateSignedReadUrlOptions,\n KVResponse,\n KVListResponse,\n KVSignedReadUrlResponse,\n} from \"./types\";\n\n/**\n * Interface for prefixed KV operations.\n *\n * Provides the same operations as IKVService but scoped to a prefix.\n * Supports nested prefixes via withPrefix().\n */\nexport interface IPrefixedKVService {\n /**\n * The current prefix for this scoped view.\n */\n readonly prefix: string;\n\n /**\n * Get a value by key.\n *\n * The key is automatically prefixed with this service's prefix.\n *\n * @param key - The key to retrieve (will be prefixed)\n * @param options - Optional get configuration\n * @returns Result with the stored value and headers\n *\n * @example\n * ```typescript\n * const myApp = kv.withPrefix('/app.myapp.com');\n * const result = await myApp.get('settings.json');\n * // -> Reads from: /app.myapp.com/settings.json\n * ```\n */\n get<T = unknown>(\n key: string,\n options?: Omit<KVGetOptions, 'prefix'>\n ): Promise<Result<KVResponse<T>>>;\n\n /**\n * Store a value at a key.\n *\n * The key is automatically prefixed with this service's prefix.\n *\n * @param key - The key to store under (will be prefixed)\n * @param value - The value to store\n * @param options - Optional put configuration\n * @returns Result indicating success/failure\n *\n * @example\n * ```typescript\n * const myApp = kv.withPrefix('/app.myapp.com');\n * await myApp.put('settings.json', { theme: 'dark' });\n * // -> Stores at: /app.myapp.com/settings.json\n * ```\n */\n put(\n key: string,\n value: unknown,\n options?: Omit<KVPutOptions, 'prefix'>\n ): Promise<Result<KVResponse<void>>>;\n\n /**\n * Store multiple values within this prefix in one TinyCloud KV invocation.\n */\n batchPut(\n items: KVBatchPutItem[],\n options?: Omit<KVBatchPutOptions, 'prefix'>\n ): Promise<Result<KVBatchPutResponse>>;\n\n /**\n * List keys within this prefix.\n *\n * Returns keys that match the prefix, with keys returned relative\n * to the prefix when removePrefix is true (default for prefixed service).\n *\n * @param options - Optional list configuration\n * @returns Result with array of matching keys\n *\n * @example\n * ```typescript\n * const myApp = kv.withPrefix('/app.myapp.com');\n * const result = await myApp.list();\n * // -> Lists keys under: /app.myapp.com/*\n * // Returns: ['settings.json', 'data/user.json', ...]\n * ```\n */\n list(options?: Omit<KVListOptions, 'prefix'>): Promise<Result<KVListResponse>>;\n\n /**\n * Delete a key.\n *\n * The key is automatically prefixed with this service's prefix.\n *\n * @param key - The key to delete (will be prefixed)\n * @param options - Optional delete configuration\n * @returns Result indicating success/failure\n *\n * @example\n * ```typescript\n * const myApp = kv.withPrefix('/app.myapp.com');\n * await myApp.delete('old-settings.json');\n * // -> Deletes: /app.myapp.com/old-settings.json\n * ```\n */\n delete(key: string, options?: Omit<KVDeleteOptions, 'prefix'>): Promise<Result<void>>;\n\n /**\n * Get metadata for a key without retrieving the value.\n *\n * The key is automatically prefixed with this service's prefix.\n *\n * @param key - The key to check (will be prefixed)\n * @param options - Optional head configuration\n * @returns Result with headers only\n *\n * @example\n * ```typescript\n * const myApp = kv.withPrefix('/app.myapp.com');\n * const result = await myApp.head('large-file.bin');\n * // -> Gets metadata for: /app.myapp.com/large-file.bin\n * ```\n */\n head(key: string, options?: Omit<KVHeadOptions, 'prefix'>): Promise<Result<KVResponse<void>>>;\n\n /**\n * Create a short-lived signed URL for reading a KV object.\n *\n * The key is automatically prefixed with this service's prefix.\n *\n * @param key - The key to expose via a signed read URL (will be prefixed)\n * @param options - Optional signed URL configuration\n * @returns Result with URL and expiry metadata\n */\n createSignedReadUrl(\n key: string,\n options?: Omit<KVCreateSignedReadUrlOptions, 'prefix'>\n ): Promise<Result<KVSignedReadUrlResponse>>;\n\n /**\n * Create a nested prefix-scoped view.\n *\n * The subPrefix is appended to the current prefix.\n *\n * @param subPrefix - The sub-prefix to append\n * @returns A new PrefixedKVService with the combined prefix\n *\n * @example\n * ```typescript\n * const myApp = kv.withPrefix('/app.myapp.com');\n * const settings = myApp.withPrefix('/settings');\n * await settings.get('theme.json');\n * // -> Reads from: /app.myapp.com/settings/theme.json\n * ```\n */\n withPrefix(subPrefix: string): IPrefixedKVService;\n}\n\n/**\n * Interface for a KV service that supports prefix delegation.\n *\n * This is the subset of IKVService methods needed by PrefixedKVService.\n */\ninterface IKVServiceLike {\n get<T = unknown>(\n key: string,\n options?: KVGetOptions\n ): Promise<Result<KVResponse<T>>>;\n\n put(\n key: string,\n value: unknown,\n options?: KVPutOptions\n ): Promise<Result<KVResponse<void>>>;\n\n batchPut(\n items: KVBatchPutItem[],\n options?: KVBatchPutOptions\n ): Promise<Result<KVBatchPutResponse>>;\n\n list(options?: KVListOptions): Promise<Result<KVListResponse>>;\n\n delete(key: string, options?: KVDeleteOptions): Promise<Result<void>>;\n\n head(key: string, options?: KVHeadOptions): Promise<Result<KVResponse<void>>>;\n\n createSignedReadUrl(\n key: string,\n options?: KVCreateSignedReadUrlOptions\n ): Promise<Result<KVSignedReadUrlResponse>>;\n}\n\n/**\n * PrefixedKVService - Implementation of prefix-scoped KV operations.\n *\n * This class wraps a KVService (or another PrefixedKVService) and\n * automatically prefixes all key operations with the configured prefix.\n *\n * ## Prefix Convention\n *\n * | Pattern | Use Case | Example |\n * | -- | -- | -- |\n * | `/app.{domain}/` | App-private data | `/app.photos.xyz/settings.json` |\n * | `/{type}/` | Shared data type | `/photos/vacation.jpg` |\n * | `/.{name}/` | Hidden/system data | `/.cache/thumbnails/` |\n * | `/public/` | Explicitly shareable | `/public/profile.json` |\n *\n * @example\n * ```typescript\n * // Create from KVService\n * const prefixed = new PrefixedKVService(kvService, '/app.myapp.com');\n *\n * // Or use the withPrefix factory method on KVService\n * const prefixed = kvService.withPrefix('/app.myapp.com');\n *\n * // All operations are automatically prefixed\n * await prefixed.put('settings.json', { theme: 'dark' });\n * await prefixed.get('settings.json');\n *\n * // Nested prefixes\n * const nested = prefixed.withPrefix('/settings');\n * await nested.get('theme.json'); // -> /app.myapp.com/settings/theme.json\n * ```\n */\nexport class PrefixedKVService implements IPrefixedKVService {\n /**\n * The underlying KV service.\n */\n private readonly _kv: IKVServiceLike;\n\n /**\n * The prefix for this scoped view.\n */\n private readonly _prefix: string;\n\n /**\n * Create a new PrefixedKVService.\n *\n * @param kv - The underlying KV service to delegate to\n * @param prefix - The prefix to apply to all operations\n */\n constructor(kv: IKVServiceLike, prefix: string) {\n this._kv = kv;\n // Normalize prefix: ensure it doesn't end with slash\n this._prefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;\n }\n\n /**\n * The current prefix for this scoped view.\n */\n get prefix(): string {\n return this._prefix;\n }\n\n /**\n * Compute the full key path by combining prefix and key.\n *\n * @param key - The key to prefix\n * @returns The full path including prefix\n */\n private getFullKey(key: string): string {\n // Handle keys that start with slash\n const normalizedKey = key.startsWith('/') ? key : `/${key}`;\n return `${this._prefix}${normalizedKey}`;\n }\n\n /**\n * Get a value by key.\n */\n async get<T = unknown>(\n key: string,\n options?: Omit<KVGetOptions, 'prefix'>\n ): Promise<Result<KVResponse<T>>> {\n const fullKey = this.getFullKey(key);\n // Use empty prefix override to use the full key as-is\n return this._kv.get<T>(fullKey, { ...options, prefix: '' });\n }\n\n /**\n * Store a value at a key.\n */\n async put(\n key: string,\n value: unknown,\n options?: Omit<KVPutOptions, 'prefix'>\n ): Promise<Result<KVResponse<void>>> {\n const fullKey = this.getFullKey(key);\n return this._kv.put(fullKey, value, { ...options, prefix: '' });\n }\n\n /**\n * Store multiple values within this prefix in one TinyCloud KV invocation.\n */\n async batchPut(\n items: KVBatchPutItem[],\n options?: Omit<KVBatchPutOptions, 'prefix'>\n ): Promise<Result<KVBatchPutResponse>> {\n return this._kv.batchPut(\n items.map((item) => ({\n ...item,\n key: this.getFullKey(item.key),\n })),\n { ...options, prefix: '' }\n );\n }\n\n /**\n * List keys within this prefix.\n */\n async list(options?: Omit<KVListOptions, 'prefix'>): Promise<Result<KVListResponse>> {\n // List uses the prefix directly, and by default removes the prefix from results\n const removePrefix = options?.removePrefix ?? true;\n return this._kv.list({\n ...options,\n prefix: this._prefix,\n removePrefix,\n });\n }\n\n /**\n * Delete a key.\n */\n async delete(key: string, options?: Omit<KVDeleteOptions, 'prefix'>): Promise<Result<void>> {\n const fullKey = this.getFullKey(key);\n return this._kv.delete(fullKey, { ...options, prefix: '' });\n }\n\n /**\n * Get metadata for a key without retrieving the value.\n */\n async head(\n key: string,\n options?: Omit<KVHeadOptions, 'prefix'>\n ): Promise<Result<KVResponse<void>>> {\n const fullKey = this.getFullKey(key);\n return this._kv.head(fullKey, { ...options, prefix: '' });\n }\n\n /**\n * Create a short-lived signed URL for reading a KV object.\n */\n async createSignedReadUrl(\n key: string,\n options?: Omit<KVCreateSignedReadUrlOptions, 'prefix'>\n ): Promise<Result<KVSignedReadUrlResponse>> {\n const fullKey = this.getFullKey(key);\n return this._kv.createSignedReadUrl(fullKey, { ...options, prefix: '' });\n }\n\n /**\n * Create a nested prefix-scoped view.\n */\n withPrefix(subPrefix: string): IPrefixedKVService {\n // Normalize subPrefix\n const normalizedSubPrefix = subPrefix.startsWith('/')\n ? subPrefix\n : `/${subPrefix}`;\n const combinedPrefix = `${this._prefix}${normalizedSubPrefix}`;\n return new PrefixedKVService(this._kv, combinedPrefix);\n }\n}\n","/**\n * KV Service Types\n *\n * Type definitions for the KV (Key-Value) service operations.\n */\n\n/**\n * Configuration for KVService.\n */\nexport interface KVServiceConfig {\n /**\n * Default prefix for all keys.\n * Useful for namespacing data within a space.\n *\n * @example\n * ```typescript\n * const kv = new KVService({ prefix: 'myapp/settings' });\n * await kv.put('theme', 'dark'); // Stores at 'myapp/settings/theme'\n * ```\n */\n prefix?: string;\n\n /**\n * Default timeout in milliseconds for KV operations.\n * Overrides the context-level timeout if set.\n */\n timeout?: number;\n\n /** Allow additional config properties */\n [key: string]: unknown;\n}\n\n/**\n * Options for KV get operations.\n */\nexport interface KVGetOptions {\n /**\n * Override the default prefix for this operation.\n */\n prefix?: string;\n\n /**\n * Return raw response instead of parsed JSON.\n * When true, data will be the raw response text.\n */\n raw?: boolean;\n\n /**\n * Custom timeout for this operation in milliseconds.\n */\n timeout?: number;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for KV put operations.\n */\nexport interface KVPutOptions {\n /**\n * Override the default prefix for this operation.\n */\n prefix?: string;\n\n /**\n * Content type for the value.\n * Defaults to 'application/json' for objects.\n */\n contentType?: string;\n\n /**\n * Custom metadata headers to store with the value.\n */\n metadata?: Record<string, string>;\n\n /**\n * Custom timeout for this operation in milliseconds.\n */\n timeout?: number;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * One entry in a KV batch put request.\n */\nexport interface KVBatchPutItem {\n /**\n * The key to store under.\n */\n key: string;\n\n /**\n * The value to store.\n *\n * Objects are JSON stringified. Strings are stored as text. Binary values\n * should be supplied as Blob, ArrayBuffer, or Uint8Array.\n */\n value: unknown;\n\n /**\n * Content type for this item. Defaults to application/json for objects and\n * application/octet-stream for binary values.\n */\n contentType?: string;\n}\n\n/**\n * Options for KV batch put operations.\n */\nexport interface KVBatchPutOptions {\n /**\n * Override the default prefix for all entries in this batch.\n */\n prefix?: string;\n\n /**\n * Custom timeout for this operation in milliseconds.\n */\n timeout?: number;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Response from KV batch put operations.\n */\nexport interface KVBatchPutResponse {\n /**\n * Keys successfully written by the batch.\n */\n written: string[];\n\n /**\n * Number of written keys.\n */\n count: number;\n}\n\n/**\n * Options for KV list operations.\n */\nexport interface KVListOptions {\n /**\n * Override the default prefix for this operation.\n */\n prefix?: string;\n\n /**\n * Additional path to append to the prefix.\n */\n path?: string;\n\n /**\n * Whether to remove the prefix from returned keys.\n * When true, keys are returned relative to the prefix.\n */\n removePrefix?: boolean;\n\n /**\n * Return raw response instead of parsed JSON.\n */\n raw?: boolean;\n\n /**\n * Custom timeout for this operation in milliseconds.\n */\n timeout?: number;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for KV delete operations.\n */\nexport interface KVDeleteOptions {\n /**\n * Override the default prefix for this operation.\n */\n prefix?: string;\n\n /**\n * Custom timeout for this operation in milliseconds.\n */\n timeout?: number;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for KV head (metadata) operations.\n */\nexport interface KVHeadOptions {\n /**\n * Override the default prefix for this operation.\n */\n prefix?: string;\n\n /**\n * Custom timeout for this operation in milliseconds.\n */\n timeout?: number;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Default lifetime for signed KV read URLs when a caller omits expiresInSeconds.\n * SDK duration defaults are stored in milliseconds; createSignedReadUrl converts\n * this to the node endpoint's ttl_seconds field.\n *\n * Keep this in sync with EXPIRY.SIGNED_READ_URL_MS in @tinycloud/sdk-core.\n * sdk-services cannot import sdk-core because sdk-core depends on sdk-services.\n */\nexport const DEFAULT_SIGNED_READ_URL_EXPIRY_MS = 5 * 60 * 1000;\n\n/**\n * Options for creating a signed KV read URL.\n */\nexport interface KVCreateSignedReadUrlOptions {\n /**\n * Override the default prefix for this operation.\n */\n prefix?: string;\n\n /**\n * Requested URL lifetime in seconds.\n * Defaults to {@link DEFAULT_SIGNED_READ_URL_EXPIRY_MS} converted to seconds.\n * The node may cap this by its configured maximum, the invocation expiry,\n * or the parent delegation expiry.\n */\n expiresInSeconds?: number;\n\n /**\n * Optional blake3 content hash to bind the signed URL to a specific object.\n */\n contentHash?: string;\n\n /**\n * Optional ETag to bind the signed URL to a specific object version.\n */\n etag?: string;\n\n /**\n * Custom timeout for this operation in milliseconds.\n */\n timeout?: number;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Response headers from KV operations.\n */\nexport interface KVResponseHeaders {\n /**\n * ETag for conditional requests.\n */\n etag?: string;\n\n /**\n * Content type of the stored value.\n */\n contentType?: string;\n\n /**\n * Last modification timestamp.\n */\n lastModified?: string;\n\n /**\n * Content length in bytes.\n */\n contentLength?: number;\n\n /**\n * Get a header value by name.\n * @param name - Header name (case-insensitive)\n */\n get(name: string): string | null;\n}\n\n/**\n * Response from KV get/put operations.\n *\n * @template T - Type of the data payload\n */\nexport interface KVResponse<T = unknown> {\n /**\n * The data payload.\n * For get: the stored value.\n * For put: undefined.\n */\n data: T;\n\n /**\n * Response headers with metadata.\n */\n headers: KVResponseHeaders;\n}\n\n/**\n * Response from KV list operations.\n */\nexport interface KVListResponse {\n /**\n * Array of keys matching the list criteria.\n */\n keys: string[];\n}\n\n/**\n * Response from signed KV read URL creation.\n */\nexport interface KVSignedReadUrlResponse {\n /**\n * Absolute URL suitable for passing to external readers.\n */\n url: string;\n\n /**\n * Opaque URL returned by tinycloud-node, usually relative to the node host.\n */\n relativeUrl: string;\n\n /**\n * Opaque signed KV ticket identifier.\n */\n ticketId: string;\n\n /**\n * Expiry timestamp as returned by tinycloud-node.\n */\n expiresAt: string;\n}\n\n/**\n * KV service action types.\n */\nexport const KVAction = {\n GET: \"tinycloud.kv/get\",\n PUT: \"tinycloud.kv/put\",\n LIST: \"tinycloud.kv/list\",\n DELETE: \"tinycloud.kv/del\",\n HEAD: \"tinycloud.kv/metadata\",\n} as const;\n\nexport type KVActionType = (typeof KVAction)[keyof typeof KVAction];\n","/**\n * KVService - Key-Value storage service implementation.\n *\n * Platform-agnostic KV service that works with both web-sdk and node-sdk.\n * Uses dependency injection via IServiceContext for platform dependencies.\n */\n\nimport { BaseService } from \"../base/BaseService\";\nimport {\n Result,\n ok,\n err,\n ErrorCodes,\n serviceError,\n FetchResponse,\n ServiceHeaders,\n} from \"../types\";\nimport {\n authRequiredError,\n wrapError,\n storageQuotaExceededError,\n storageLimitReachedError,\n parseAuthError,\n authUnauthorizedError,\n} from \"../errors\";\nimport { IKVService } from \"./IKVService\";\nimport { PrefixedKVService, IPrefixedKVService } from \"./PrefixedKVService\";\nimport {\n DEFAULT_SIGNED_READ_URL_EXPIRY_MS,\n KVServiceConfig,\n KVGetOptions,\n KVPutOptions,\n KVBatchPutItem,\n KVBatchPutOptions,\n KVBatchPutResponse,\n KVListOptions,\n KVDeleteOptions,\n KVHeadOptions,\n KVCreateSignedReadUrlOptions,\n KVResponse,\n KVListResponse,\n KVResponseHeaders,\n KVSignedReadUrlResponse,\n KVAction,\n} from \"./types\";\n\ninterface SignedKvUrlNodeResponse {\n url: string;\n ticketId: string;\n expiresAt: string;\n}\n\nfunction encodeKvBatchPartName(path: string): string {\n return encodeURIComponent(path).replace(/[!'()*]/g, (char) =>\n `%${char.charCodeAt(0).toString(16).toUpperCase()}`\n );\n}\n\n/**\n * KV service implementation.\n *\n * Provides key-value storage operations using TinyCloud's KV API.\n * Uses the Result type pattern for explicit error handling.\n *\n * @example\n * ```typescript\n * // Register with SDK\n * const sdk = new TinyCloud({\n * services: { kv: KVService },\n * serviceConfigs: { kv: { prefix: 'myapp' } },\n * });\n *\n * // Use the service\n * const result = await sdk.kv.get('settings');\n * if (result.ok) {\n * console.log(result.data.data);\n * }\n * ```\n */\nexport class KVService extends BaseService implements IKVService {\n /**\n * Service identifier for registration.\n */\n static readonly serviceName = \"kv\";\n\n /**\n * Service configuration.\n */\n declare protected _config: KVServiceConfig;\n\n /**\n * Create a new KVService instance.\n *\n * @param config - Service configuration\n */\n constructor(config: KVServiceConfig = {}) {\n super();\n this._config = config;\n }\n\n /**\n * Get the service configuration.\n */\n get config(): KVServiceConfig {\n return this._config;\n }\n\n // Parses \"Used: X bytes, Limit: Y bytes\" from tinycloud-node error responses\n private parseQuotaInfo(\n errorText: string\n ): { usedBytes: number; limitBytes: number } | undefined {\n const match = errorText.match(\n /Used:\\s*(\\d+)\\s*bytes,\\s*Limit:\\s*(\\d+)\\s*bytes/i\n );\n if (match) {\n return {\n usedBytes: parseInt(match[1], 10),\n limitBytes: parseInt(match[2], 10),\n };\n }\n return undefined;\n }\n\n private handleQuotaErrorResponse(\n response: FetchResponse,\n errorText: string,\n key: string\n ): Result<never> | undefined {\n if (response.status === 402) {\n const quotaInfo = this.parseQuotaInfo(errorText);\n return err(\n storageQuotaExceededError(\n \"kv\",\n `Storage quota exceeded for key \"${key}\": ${errorText}`,\n {\n status: response.status,\n ...(quotaInfo\n ? { usedBytes: quotaInfo.usedBytes, limitBytes: quotaInfo.limitBytes }\n : {}),\n }\n )\n );\n }\n\n if (response.status === 413) {\n const quotaInfo = this.parseQuotaInfo(errorText);\n return err(\n storageLimitReachedError(\n \"kv\",\n `Storage limit reached for key \"${key}\": ${errorText}`,\n {\n status: response.status,\n ...(quotaInfo\n ? { usedBytes: quotaInfo.usedBytes, limitBytes: quotaInfo.limitBytes }\n : {}),\n }\n )\n );\n }\n\n return undefined;\n }\n\n /**\n * Get the full path with optional prefix.\n *\n * @param key - The key\n * @param prefixOverride - Optional prefix override\n * @returns The full path\n */\n private getFullPath(key: string, prefixOverride?: string): string {\n const prefix = prefixOverride ?? this._config.prefix ?? \"\";\n return prefix ? `${prefix}/${key}` : key;\n }\n\n /**\n * Get the host URL.\n */\n private get host(): string {\n return this.context.hosts[0];\n }\n\n private withJsonContentType(headers: ServiceHeaders): ServiceHeaders {\n if (Array.isArray(headers)) {\n return [...headers, [\"content-type\", \"application/json\"]];\n }\n\n return {\n ...headers,\n \"content-type\": \"application/json\",\n };\n }\n\n /**\n * Execute an invoke operation.\n *\n * @param path - Resource path\n * @param action - KV action\n * @param body - Optional request body\n * @param signal - Optional abort signal\n * @returns Fetch response\n */\n private async invokeOperation(\n path: string,\n action: string,\n body?: Blob | string,\n signal?: AbortSignal\n ): Promise<FetchResponse> {\n const session = this.context.session!;\n const headers = this.context.invoke(\n session,\n \"kv\",\n path,\n action\n );\n\n return this.context.fetch(`${this.host}/invoke`, {\n method: \"POST\",\n headers,\n body,\n signal: this.combineSignals(signal),\n });\n }\n\n private serializeBatchPutValue(item: KVBatchPutItem): Blob {\n const contentType = item.contentType;\n\n if (item.value instanceof Blob) {\n if (!contentType || item.value.type === contentType) {\n return item.value;\n }\n return new Blob([item.value], { type: contentType });\n }\n\n if (item.value instanceof ArrayBuffer) {\n return new Blob([item.value], {\n type: contentType ?? \"application/octet-stream\",\n });\n }\n\n if (ArrayBuffer.isView(item.value)) {\n const value = item.value;\n const bytes = new Uint8Array(value.byteLength);\n bytes.set(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));\n return new Blob([bytes], {\n type: contentType ?? \"application/octet-stream\",\n });\n }\n\n if (typeof item.value === \"string\") {\n return new Blob([item.value], {\n type: contentType ?? \"text/plain;charset=UTF-8\",\n });\n }\n\n const json = JSON.stringify(item.value);\n if (json === undefined) {\n throw new Error(`Cannot JSON serialize KV batch value for key \"${item.key}\"`);\n }\n\n return new Blob([json], {\n type: contentType ?? \"application/json\",\n });\n }\n\n private normalizeBatchPutResponse(data: unknown): KVBatchPutResponse | undefined {\n if (!data || typeof data !== \"object\") {\n return undefined;\n }\n\n const response = data as Partial<KVBatchPutResponse>;\n if (\n !Array.isArray(response.written) ||\n !response.written.every((key) => typeof key === \"string\") ||\n typeof response.count !== \"number\"\n ) {\n return undefined;\n }\n\n return {\n written: response.written,\n count: response.count,\n };\n }\n\n /**\n * Create KVResponseHeaders from fetch response headers.\n *\n * @param headers - Fetch response headers\n * @returns KVResponseHeaders object\n */\n private createResponseHeaders(headers: {\n get(name: string): string | null;\n }): KVResponseHeaders {\n return {\n etag: headers.get(\"etag\") ?? undefined,\n contentType: headers.get(\"content-type\") ?? undefined,\n lastModified: headers.get(\"last-modified\") ?? undefined,\n contentLength: headers.get(\"content-length\")\n ? parseInt(headers.get(\"content-length\")!, 10)\n : undefined,\n get: (name: string) => headers.get(name),\n };\n }\n\n /**\n * Parse response body based on content type.\n *\n * @param response - Fetch response\n * @param raw - Whether to return raw text\n * @returns Parsed data\n */\n private async parseResponse<T>(\n response: FetchResponse,\n raw: boolean = false\n ): Promise<T | undefined> {\n if (!response.ok) {\n return undefined;\n }\n\n if (raw) {\n return (await response.text()) as unknown as T;\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else if (contentType?.startsWith(\"text/\")) {\n return (await response.text()) as unknown as T;\n }\n\n // No content-type header - try to parse as JSON, fall back to text\n const text = await response.text();\n if (!text) {\n return undefined;\n }\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n }\n\n private async createSignedReadUrlError(\n response: FetchResponse,\n key: string\n ): Promise<Result<never>> {\n let errorText = response.statusText;\n try {\n const text = await response.text();\n if (text) {\n errorText = text;\n }\n } catch {\n // Ignore secondary body read failure.\n }\n\n if (response.status === 401 || response.status === 403) {\n const { resource, action } = parseAuthError(errorText);\n return err(authUnauthorizedError(\"kv\", errorText, {\n status: response.status,\n ...(action && { requiredAction: action }),\n ...(resource && { resource }),\n }));\n }\n\n const code =\n response.status === 400 ? ErrorCodes.INVALID_INPUT : ErrorCodes.NETWORK_ERROR;\n return err(\n serviceError(\n code,\n `Failed to create signed read URL for key \"${key}\": ${response.status} - ${errorText}`,\n \"kv\",\n { meta: { status: response.status, statusText: response.statusText } }\n )\n );\n }\n\n private normalizeSignedReadUrlResponse(\n data: unknown\n ): KVSignedReadUrlResponse | undefined {\n if (!data || typeof data !== \"object\") {\n return undefined;\n }\n\n const response = data as Partial<SignedKvUrlNodeResponse>;\n if (\n typeof response.url !== \"string\" ||\n typeof response.ticketId !== \"string\" ||\n typeof response.expiresAt !== \"string\"\n ) {\n return undefined;\n }\n\n return {\n url: new URL(response.url, this.host).toString(),\n relativeUrl: response.url,\n ticketId: response.ticketId,\n expiresAt: response.expiresAt,\n };\n }\n\n /**\n * Get a value by key.\n */\n async get<T = unknown>(\n key: string,\n options?: KVGetOptions\n ): Promise<Result<KVResponse<T>>> {\n return this.withTelemetry(\"get\", key, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"kv\"));\n }\n\n const path = this.getFullPath(key, options?.prefix);\n\n try {\n const response = await this.invokeOperation(\n path,\n KVAction.GET,\n undefined,\n options?.signal\n );\n\n if (!response.ok) {\n if (response.status === 401) {\n const errorText = await response.text();\n const { resource, action } = parseAuthError(errorText);\n return err(authUnauthorizedError(\"kv\", errorText, {\n status: response.status,\n ...(action && { requiredAction: action }),\n ...(resource && { resource }),\n }));\n }\n\n if (response.status === 404) {\n return err(\n serviceError(\n ErrorCodes.KV_NOT_FOUND,\n `Key not found: ${key}`,\n \"kv\"\n )\n );\n }\n\n const errorText = await response.text();\n return err(\n serviceError(\n ErrorCodes.NETWORK_ERROR,\n `Failed to get key \"${key}\": ${response.status} - ${errorText}`,\n \"kv\",\n { meta: { status: response.status, statusText: response.statusText } }\n )\n );\n }\n\n const data = await this.parseResponse<T>(response, options?.raw);\n return ok({\n data: data as T,\n headers: this.createResponseHeaders(response.headers),\n });\n } catch (error) {\n return err(wrapError(\"kv\", error));\n }\n });\n }\n\n /**\n * Store a value at a key.\n */\n async put(\n key: string,\n value: unknown,\n options?: KVPutOptions\n ): Promise<Result<KVResponse<void>>> {\n return this.withTelemetry(\"put\", key, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"kv\"));\n }\n\n const path = this.getFullPath(key, options?.prefix);\n\n // Serialize value to string\n let body: string;\n if (typeof value === \"string\") {\n body = value;\n } else {\n body = JSON.stringify(value);\n }\n\n try {\n const response = await this.invokeOperation(\n path,\n KVAction.PUT,\n body,\n options?.signal\n );\n\n if (!response.ok) {\n if (response.status === 401) {\n const errorText = await response.text();\n const { resource, action } = parseAuthError(errorText);\n return err(authUnauthorizedError(\"kv\", errorText, {\n status: response.status,\n ...(action && { requiredAction: action }),\n ...(resource && { resource }),\n }));\n }\n\n const errorText = await response.text();\n\n // Check for storage quota errors (402, 413)\n const quotaError = this.handleQuotaErrorResponse(\n response,\n errorText,\n key\n );\n if (quotaError) {\n return quotaError;\n }\n\n return err(\n serviceError(\n ErrorCodes.KV_WRITE_FAILED,\n `Failed to put key \"${key}\": ${response.status} - ${errorText}`,\n \"kv\",\n { meta: { status: response.status, statusText: response.statusText } }\n )\n );\n }\n\n return ok({\n data: undefined as void,\n headers: this.createResponseHeaders(response.headers),\n });\n } catch (error) {\n return err(wrapError(\"kv\", error));\n }\n });\n }\n\n /**\n * Store multiple values in one TinyCloud KV invocation.\n */\n async batchPut(\n items: KVBatchPutItem[],\n options?: KVBatchPutOptions\n ): Promise<Result<KVBatchPutResponse>> {\n return this.withTelemetry(\"batchPut\", String(items.length), async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"kv\"));\n }\n\n if (items.length === 0) {\n return ok({ written: [], count: 0 });\n }\n\n if (!this.context.invokeAny) {\n return err(\n serviceError(\n ErrorCodes.INVALID_INPUT,\n \"KV batchPut requires SDK runtime support for multi-resource invocations\",\n \"kv\"\n )\n );\n }\n\n const session = this.context.session!;\n const paths = items.map((item) => this.getFullPath(item.key, options?.prefix));\n const seen = new Set<string>();\n for (const path of paths) {\n if (seen.has(path)) {\n return err(\n serviceError(\n ErrorCodes.INVALID_INPUT,\n `KV batchPut received duplicate key after prefix resolution: ${path}`,\n \"kv\"\n )\n );\n }\n seen.add(path);\n }\n\n try {\n const body = new FormData();\n for (let index = 0; index < items.length; index++) {\n body.append(\n encodeKvBatchPartName(paths[index]!),\n this.serializeBatchPutValue(items[index]!)\n );\n }\n\n const headers = this.context.invokeAny(\n session,\n paths.map((path) => ({\n spaceId: session.spaceId,\n service: \"kv\",\n path,\n action: KVAction.PUT,\n }))\n );\n\n const response = await this.context.fetch(`${this.host}/invoke`, {\n method: \"POST\",\n headers,\n body,\n signal: this.combineSignals(options?.signal),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n\n if (response.status === 401 || response.status === 403) {\n const { resource, action } = parseAuthError(errorText);\n return err(authUnauthorizedError(\"kv\", errorText, {\n status: response.status,\n ...(action && { requiredAction: action }),\n ...(resource && { resource }),\n }));\n }\n\n const quotaError = this.handleQuotaErrorResponse(\n response,\n errorText,\n \"batch\"\n );\n if (quotaError) {\n return quotaError;\n }\n\n return err(\n serviceError(\n ErrorCodes.KV_WRITE_FAILED,\n `Failed to batch put ${items.length} key(s): ${response.status} - ${errorText}`,\n \"kv\",\n { meta: { status: response.status, statusText: response.statusText } }\n )\n );\n }\n\n const batchResponse = this.normalizeBatchPutResponse(await response.json());\n if (!batchResponse || batchResponse.count !== batchResponse.written.length) {\n return err(\n serviceError(\n ErrorCodes.NETWORK_ERROR,\n \"KV batchPut response did not include matching written keys and count\",\n \"kv\"\n )\n );\n }\n\n return ok(batchResponse);\n } catch (error) {\n return err(wrapError(\"kv\", error));\n }\n });\n }\n\n /**\n * List keys with optional prefix filtering.\n */\n async list(options?: KVListOptions): Promise<Result<KVListResponse>> {\n return this.withTelemetry(\"list\", options?.prefix, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"kv\"));\n }\n\n // Build the path from prefix and optional path\n let listPath = options?.prefix ?? this._config.prefix ?? \"\";\n if (options?.path) {\n listPath = listPath ? `${listPath}/${options.path}` : options.path;\n }\n\n try {\n const response = await this.invokeOperation(\n listPath,\n KVAction.LIST,\n undefined,\n options?.signal\n );\n\n if (!response.ok) {\n if (response.status === 401) {\n const errorText = await response.text();\n const { resource, action } = parseAuthError(errorText);\n return err(authUnauthorizedError(\"kv\", errorText, {\n status: response.status,\n ...(action && { requiredAction: action }),\n ...(resource && { resource }),\n }));\n }\n\n const errorText = await response.text();\n return err(\n serviceError(\n ErrorCodes.NETWORK_ERROR,\n `Failed to list keys: ${response.status} - ${errorText}`,\n \"kv\",\n { meta: { status: response.status, statusText: response.statusText } }\n )\n );\n }\n\n let keys = await this.parseResponse<string[]>(response, options?.raw);\n keys = keys ?? [];\n\n // Optionally remove prefix from keys\n if (options?.removePrefix && listPath) {\n const prefixWithSlash = listPath.endsWith(\"/\")\n ? listPath\n : `${listPath}/`;\n keys = keys.map((key) =>\n key.startsWith(prefixWithSlash)\n ? key.slice(prefixWithSlash.length)\n : key\n );\n }\n\n return ok({ keys });\n } catch (error) {\n return err(wrapError(\"kv\", error));\n }\n });\n }\n\n /**\n * Delete a key.\n */\n async delete(key: string, options?: KVDeleteOptions): Promise<Result<void>> {\n return this.withTelemetry(\"delete\", key, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"kv\"));\n }\n\n const path = this.getFullPath(key, options?.prefix);\n\n try {\n const response = await this.invokeOperation(\n path,\n KVAction.DELETE,\n undefined,\n options?.signal\n );\n\n if (!response.ok) {\n if (response.status === 401) {\n const errorText = await response.text();\n const { resource, action } = parseAuthError(errorText);\n return err(authUnauthorizedError(\"kv\", errorText, {\n status: response.status,\n ...(action && { requiredAction: action }),\n ...(resource && { resource }),\n }));\n }\n\n if (response.status === 404) {\n return err(\n serviceError(\n ErrorCodes.KV_NOT_FOUND,\n `Key not found: ${key}`,\n \"kv\"\n )\n );\n }\n\n const errorText = await response.text();\n return err(\n serviceError(\n ErrorCodes.NETWORK_ERROR,\n `Failed to delete key \"${key}\": ${response.status} - ${errorText}`,\n \"kv\",\n { meta: { status: response.status, statusText: response.statusText } }\n )\n );\n }\n\n return ok(undefined);\n } catch (error) {\n return err(wrapError(\"kv\", error));\n }\n });\n }\n\n /**\n * Get metadata for a key without retrieving the value.\n */\n async head(\n key: string,\n options?: KVHeadOptions\n ): Promise<Result<KVResponse<void>>> {\n return this.withTelemetry(\"head\", key, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"kv\"));\n }\n\n const path = this.getFullPath(key, options?.prefix);\n\n try {\n const response = await this.invokeOperation(\n path,\n KVAction.HEAD,\n undefined,\n options?.signal\n );\n\n if (!response.ok) {\n if (response.status === 401) {\n const errorText = await response.text();\n const { resource, action } = parseAuthError(errorText);\n return err(authUnauthorizedError(\"kv\", errorText, {\n status: response.status,\n ...(action && { requiredAction: action }),\n ...(resource && { resource }),\n }));\n }\n\n if (response.status === 404) {\n return err(\n serviceError(\n ErrorCodes.KV_NOT_FOUND,\n `Key not found: ${key}`,\n \"kv\"\n )\n );\n }\n\n const errorText = await response.text();\n return err(\n serviceError(\n ErrorCodes.NETWORK_ERROR,\n `Failed to get metadata for key \"${key}\": ${response.status} - ${errorText}`,\n \"kv\",\n { meta: { status: response.status, statusText: response.statusText } }\n )\n );\n }\n\n return ok({\n data: undefined as void,\n headers: this.createResponseHeaders(response.headers),\n });\n } catch (error) {\n return err(wrapError(\"kv\", error));\n }\n });\n }\n\n /**\n * Create a short-lived signed URL for reading a KV object.\n */\n async createSignedReadUrl(\n key: string,\n options?: KVCreateSignedReadUrlOptions\n ): Promise<Result<KVSignedReadUrlResponse>> {\n return this.withTelemetry(\"createSignedReadUrl\", key, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"kv\"));\n }\n\n const path = this.getFullPath(key, options?.prefix);\n const session = this.context.session!;\n const headers = this.context.invoke(\n session,\n \"kv\",\n path,\n KVAction.GET\n );\n\n const body: {\n space: string;\n path: string;\n ttl_seconds: number;\n content_hash?: string;\n etag?: string;\n } = {\n space: session.spaceId,\n path,\n ttl_seconds:\n options?.expiresInSeconds ??\n Math.ceil(DEFAULT_SIGNED_READ_URL_EXPIRY_MS / 1000),\n };\n\n if (options?.contentHash !== undefined) {\n body.content_hash = options.contentHash;\n }\n if (options?.etag !== undefined) {\n body.etag = options.etag;\n }\n\n try {\n const response = await this.context.fetch(`${this.host}/signed/kv`, {\n method: \"POST\",\n headers: this.withJsonContentType(headers),\n body: JSON.stringify(body),\n signal: this.combineSignals(options?.signal),\n });\n\n if (!response.ok) {\n return this.createSignedReadUrlError(response, key);\n }\n\n const signedUrl = this.normalizeSignedReadUrlResponse(\n await response.json()\n );\n if (!signedUrl) {\n return err(\n serviceError(\n ErrorCodes.NETWORK_ERROR,\n \"Signed read URL response did not include url, ticketId, and expiresAt\",\n \"kv\"\n )\n );\n }\n\n return ok(signedUrl);\n } catch (error) {\n return err(wrapError(\"kv\", error));\n }\n });\n }\n\n /**\n * Create a prefix-scoped view of this KV service.\n *\n * Returns a PrefixedKVService that automatically prefixes all\n * key operations with the specified prefix. This enables apps\n * to isolate their data within a shared space.\n *\n * @param prefix - The prefix to apply to all operations\n * @returns A PrefixedKVService scoped to the prefix\n *\n * ## Prefix Conventions\n *\n * | Pattern | Use Case | Example |\n * | -- | -- | -- |\n * | `/app.{domain}/` | App-private data | `/app.photos.xyz/settings.json` |\n * | `/{type}/` | Shared data type | `/photos/vacation.jpg` |\n * | `/.{name}/` | Hidden/system data | `/.cache/thumbnails/` |\n * | `/public/` | Explicitly shareable | `/public/profile.json` |\n *\n * @example\n * ```typescript\n * const space = sdk.space('default');\n *\n * // Create prefix-scoped views\n * const myApp = space.kv.withPrefix('/app.myapp.com');\n * const sharedPhotos = space.kv.withPrefix('/photos');\n *\n * // Operations are automatically prefixed\n * await myApp.put('settings.json', { theme: 'dark' });\n * // -> Actually writes to: /app.myapp.com/settings.json\n *\n * await myApp.get('settings.json');\n * // -> Actually reads from: /app.myapp.com/settings.json\n *\n * await sharedPhotos.list();\n * // -> Lists: /photos/*\n *\n * // Nested prefixes\n * const settings = myApp.withPrefix('/settings');\n * await settings.get('theme.json'); // -> /app.myapp.com/settings/theme.json\n * ```\n */\n withPrefix(prefix: string): IPrefixedKVService {\n return new PrefixedKVService(this, prefix);\n }\n}\n","/**\n * DatabaseHandle - Handle for operations on a specific named database.\n *\n * Delegates all operations to the parent SQLService with the database name.\n */\n\nimport type { Result } from \"../types\";\nimport type { IDatabaseHandle } from \"./ISQLService\";\nimport type { SQLService } from \"./SQLService\";\nimport type {\n SqlValue,\n SqlStatement,\n QueryResponse,\n ExecuteResponse,\n BatchResponse,\n QueryOptions,\n ExecuteOptions,\n BatchOptions,\n} from \"./types\";\n\nexport class DatabaseHandle implements IDatabaseHandle {\n private service: SQLService;\n public readonly name: string;\n\n constructor(service: SQLService, name: string) {\n this.service = service;\n this.name = name;\n }\n\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: SqlValue[],\n options?: QueryOptions\n ): Promise<Result<QueryResponse<T>>> {\n return this.service.queryOnDb<T>(this.name, sql, params, options);\n }\n\n async execute(\n sql: string,\n params?: SqlValue[],\n options?: ExecuteOptions\n ): Promise<Result<ExecuteResponse>> {\n return this.service.executeOnDb(this.name, sql, params, options);\n }\n\n async batch(\n statements: SqlStatement[],\n options?: BatchOptions\n ): Promise<Result<BatchResponse>> {\n return this.service.batchOnDb(this.name, statements, options);\n }\n\n async executeStatement(\n name: string,\n params?: SqlValue[],\n options?: QueryOptions\n ): Promise<Result<QueryResponse | ExecuteResponse>> {\n return this.service.executeStatementOnDb(this.name, name, params, options);\n }\n\n async export(options?: QueryOptions): Promise<Result<Blob>> {\n return this.service.exportDb(this.name, options);\n }\n}\n","/**\n * SQL Service Types\n *\n * Type definitions for the SQL service operations.\n */\n\n/**\n * Configuration for SQLService.\n */\nexport interface SQLServiceConfig {\n /**\n * Default database name.\n * If not set, operations default to \"default\".\n */\n defaultDatabase?: string;\n\n /**\n * Default timeout in milliseconds for SQL operations.\n */\n timeout?: number;\n\n /** Allow additional config properties */\n [key: string]: unknown;\n}\n\n/**\n * Options for SQL query operations.\n */\nexport interface QueryOptions {\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for SQL execute operations.\n */\nexport interface ExecuteOptions {\n /**\n * Schema initialization statements (CREATE TABLE IF NOT EXISTS ...).\n * Executed before the main statement on first write.\n */\n schema?: string[];\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for SQL batch operations.\n */\nexport interface BatchOptions {\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * A SQL value: null, number, string, or binary data.\n */\nexport type SqlValue = null | number | string | Uint8Array;\n\n/**\n * A SQL statement with optional parameters.\n */\nexport interface SqlStatement {\n sql: string;\n params?: SqlValue[];\n}\n\n/**\n * Response from SQL query operations.\n */\nexport interface QueryResponse<T = Record<string, unknown>> {\n columns: string[];\n rows: T[][];\n rowCount: number;\n}\n\n/**\n * Response from SQL execute operations.\n */\nexport interface ExecuteResponse {\n changes: number;\n lastInsertRowId: number;\n}\n\n/**\n * Response from SQL batch operations.\n */\nexport interface BatchResponse {\n results: ExecuteResponse[];\n}\n\n/**\n * SQL service action types.\n */\nexport const SQLAction = {\n READ: \"tinycloud.sql/read\",\n WRITE: \"tinycloud.sql/write\",\n ADMIN: \"tinycloud.sql/admin\",\n SELECT: \"tinycloud.sql/select\",\n INSERT: \"tinycloud.sql/insert\",\n UPDATE: \"tinycloud.sql/update\",\n DELETE: \"tinycloud.sql/delete\",\n EXECUTE: \"tinycloud.sql/execute\",\n EXPORT: \"tinycloud.sql/export\",\n ALL: \"tinycloud.sql/*\",\n} as const;\n\nexport type SQLActionType = (typeof SQLAction)[keyof typeof SQLAction];\n","/**\n * SQLService - SQL database service implementation.\n *\n * Platform-agnostic SQL service that works with both web-sdk and node-sdk.\n * Uses dependency injection via IServiceContext for platform dependencies.\n */\n\nimport { BaseService } from \"../base/BaseService\";\nimport {\n Result,\n ok,\n err,\n ErrorCodes,\n serviceError,\n type FetchResponse,\n} from \"../types\";\nimport { authRequiredError, wrapError, parseAuthError } from \"../errors\";\nimport type { ISQLService } from \"./ISQLService\";\nimport type { IDatabaseHandle } from \"./ISQLService\";\nimport { DatabaseHandle } from \"./DatabaseHandle\";\nimport {\n type SQLServiceConfig,\n type QueryOptions,\n type ExecuteOptions,\n type BatchOptions,\n type SqlValue,\n type SqlStatement,\n type QueryResponse,\n type ExecuteResponse,\n type BatchResponse,\n SQLAction,\n} from \"./types\";\n\nexport class SQLService extends BaseService implements ISQLService {\n static readonly serviceName = \"sql\";\n\n declare protected _config: SQLServiceConfig;\n\n constructor(config: SQLServiceConfig = {}) {\n super();\n this._config = config;\n }\n\n get config(): SQLServiceConfig {\n return this._config;\n }\n\n private get defaultDbName(): string {\n return this._config.defaultDatabase ?? \"default\";\n }\n\n private get host(): string {\n return this.context.hosts[0];\n }\n\n /**\n * Get a handle to a named database.\n */\n db(name?: string): IDatabaseHandle {\n return new DatabaseHandle(this, name ?? this.defaultDbName);\n }\n\n /**\n * Shortcut: query the default database.\n */\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: SqlValue[],\n options?: QueryOptions\n ): Promise<Result<QueryResponse<T>>> {\n return this.queryOnDb<T>(this.defaultDbName, sql, params, options);\n }\n\n /**\n * Shortcut: execute on the default database.\n */\n async execute(\n sql: string,\n params?: SqlValue[],\n options?: ExecuteOptions\n ): Promise<Result<ExecuteResponse>> {\n return this.executeOnDb(this.defaultDbName, sql, params, options);\n }\n\n /**\n * Shortcut: batch on the default database.\n */\n async batch(\n statements: SqlStatement[],\n options?: BatchOptions\n ): Promise<Result<BatchResponse>> {\n return this.batchOnDb(this.defaultDbName, statements, options);\n }\n\n // === Internal methods called by DatabaseHandle ===\n\n async queryOnDb<T = Record<string, unknown>>(\n dbName: string,\n sql: string,\n params?: SqlValue[],\n options?: QueryOptions\n ): Promise<Result<QueryResponse<T>>> {\n return this.withTelemetry(\"query\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"sql\"));\n }\n\n try {\n const response = await this.invokeSQL(\n dbName,\n this.actionForSql(sql, SQLAction.READ),\n { action: \"query\", sql, params: params ?? [] },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"query\");\n }\n\n const data = (await response.json()) as QueryResponse<T>;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"sql\", error));\n }\n });\n }\n\n async executeOnDb(\n dbName: string,\n sql: string,\n params?: SqlValue[],\n options?: ExecuteOptions\n ): Promise<Result<ExecuteResponse>> {\n return this.withTelemetry(\"execute\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"sql\"));\n }\n\n try {\n const body: Record<string, unknown> = {\n action: \"execute\",\n sql,\n params: params ?? [],\n };\n if (options?.schema) {\n body.schema = options.schema;\n }\n\n const response = await this.invokeSQL(\n dbName,\n this.actionForSql(sql, SQLAction.WRITE),\n body,\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"execute\");\n }\n\n const data = (await response.json()) as ExecuteResponse;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"sql\", error));\n }\n });\n }\n\n async batchOnDb(\n dbName: string,\n statements: SqlStatement[],\n options?: BatchOptions\n ): Promise<Result<BatchResponse>> {\n return this.withTelemetry(\"batch\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"sql\"));\n }\n\n try {\n const response = await this.invokeSQL(\n dbName,\n this.actionForSqlBatch(statements),\n { action: \"batch\", statements },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"batch\");\n }\n\n const data = (await response.json()) as BatchResponse;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"sql\", error));\n }\n });\n }\n\n async executeStatementOnDb(\n dbName: string,\n name: string,\n params?: SqlValue[],\n options?: QueryOptions\n ): Promise<Result<QueryResponse | ExecuteResponse>> {\n return this.withTelemetry(\"executeStatement\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"sql\"));\n }\n\n try {\n const response = await this.invokeSQL(\n dbName,\n SQLAction.EXECUTE,\n { action: \"execute_statement\", name, params: params ?? [] },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"executeStatement\");\n }\n\n const data = (await response.json()) as\n | QueryResponse\n | ExecuteResponse;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"sql\", error));\n }\n });\n }\n\n async exportDb(\n dbName: string,\n options?: QueryOptions\n ): Promise<Result<Blob>> {\n return this.withTelemetry(\"export\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"sql\"));\n }\n\n try {\n const response = await this.invokeSQL(\n dbName,\n SQLAction.EXPORT,\n { action: \"export\" },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"export\");\n }\n\n // FetchResponse doesn't expose blob(), so access it from the\n // underlying response which is a standard fetch Response at runtime\n const resp = response as any;\n if (typeof resp.blob === \"function\") {\n const blob = await resp.blob();\n return ok(blob as Blob);\n }\n // If blob() is not available, return the raw text as a Blob-like\n const text = await response.text();\n return ok(text as unknown as Blob);\n } catch (error) {\n return err(wrapError(\"sql\", error));\n }\n });\n }\n\n // === Private helpers ===\n\n private async invokeSQL(\n dbName: string,\n action: string,\n body: Record<string, unknown>,\n signal?: AbortSignal\n ): Promise<FetchResponse> {\n const session = this.context.session!;\n const headers = this.context.invoke(session, \"sql\", dbName, action);\n\n return this.context.fetch(`${this.host}/invoke`, {\n method: \"POST\",\n headers: {\n ...(headers as Record<string, string>),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body) as any,\n signal: this.combineSignals(signal),\n });\n }\n\n private actionForSql(sql: string, fallback: string): string {\n return firstSqlToken(sql) === \"pragma\" ? SQLAction.ADMIN : fallback;\n }\n\n private actionForSqlBatch(statements: SqlStatement[]): string {\n return statements.some(\n (statement) => this.actionForSql(statement.sql, SQLAction.WRITE) === SQLAction.ADMIN,\n )\n ? SQLAction.ADMIN\n : SQLAction.WRITE;\n }\n\n private async handleErrorResponse(\n response: FetchResponse,\n operation: string\n ): Promise<Result<never>> {\n const errorText = await response.text();\n\n let errorBody: { error?: string; message?: string; code?: string } = {};\n try {\n errorBody = JSON.parse(errorText);\n } catch {\n // Not JSON\n }\n\n const errorCode = this.mapHttpStatusToErrorCode(\n response.status,\n errorBody.error\n );\n const message =\n errorBody.message ||\n `SQL ${operation} failed: ${response.status} - ${errorText}`;\n\n const meta: Record<string, unknown> = { status: response.status, statusText: response.statusText };\n\n if (response.status === 401) {\n const { resource, action } = parseAuthError(errorText);\n if (action) meta.requiredAction = action;\n if (resource) meta.resource = resource;\n }\n\n return err(\n serviceError(errorCode, message, \"sql\", { meta })\n );\n }\n\n private mapHttpStatusToErrorCode(\n status: number,\n serverError?: string\n ): string {\n switch (status) {\n case 400:\n return ErrorCodes.SQL_ERROR;\n case 401:\n return ErrorCodes.AUTH_UNAUTHORIZED;\n case 403:\n if (serverError === \"sql_readonly_violation\") {\n return ErrorCodes.SQL_READONLY_VIOLATION;\n }\n return ErrorCodes.SQL_PERMISSION_DENIED;\n case 404:\n return ErrorCodes.SQL_DATABASE_NOT_FOUND;\n case 413:\n return ErrorCodes.SQL_RESPONSE_TOO_LARGE;\n case 429:\n return ErrorCodes.SQL_QUOTA_EXCEEDED;\n default:\n return ErrorCodes.NETWORK_ERROR;\n }\n }\n}\n\nfunction firstSqlToken(sql: string): string | undefined {\n let index = 0;\n\n while (index < sql.length) {\n while (index < sql.length && /\\s/.test(sql[index])) {\n index++;\n }\n\n if (sql.startsWith(\"--\", index)) {\n const newline = sql.indexOf(\"\\n\", index + 2);\n if (newline === -1) {\n return undefined;\n }\n index = newline + 1;\n continue;\n }\n\n if (sql.startsWith(\"/*\", index)) {\n const end = sql.indexOf(\"*/\", index + 2);\n if (end === -1) {\n return undefined;\n }\n index = end + 2;\n continue;\n }\n\n break;\n }\n\n const match = /^[A-Za-z_]+/.exec(sql.slice(index));\n return match?.[0].toLowerCase();\n}\n","/**\n * DuckDbDatabaseHandle - Handle for operations on a specific named database.\n *\n * Delegates all operations to the parent DuckDbService with the database name.\n */\n\nimport type { Result } from \"../types\";\nimport type { IDuckDbDatabaseHandle } from \"./IDuckDbService\";\nimport type { DuckDbService } from \"./DuckDbService\";\nimport type {\n DuckDbValue,\n DuckDbStatement,\n QueryResponse,\n ExecuteResponse,\n BatchResponse,\n SchemaInfo,\n DuckDbQueryOptions,\n DuckDbExecuteOptions,\n DuckDbBatchOptions,\n DuckDbOptions,\n} from \"./types\";\n\nexport class DuckDbDatabaseHandle implements IDuckDbDatabaseHandle {\n private service: DuckDbService;\n public readonly name: string;\n\n constructor(service: DuckDbService, name: string) {\n this.service = service;\n this.name = name;\n }\n\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<QueryResponse<T>>> {\n return this.service.queryOnDb<T>(this.name, sql, params, options);\n }\n\n async queryArrow(\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<ArrayBuffer>> {\n return this.service.queryArrowOnDb(this.name, sql, params, options);\n }\n\n async execute(\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbExecuteOptions\n ): Promise<Result<ExecuteResponse>> {\n return this.service.executeOnDb(this.name, sql, params, options);\n }\n\n async batch(\n statements: DuckDbStatement[],\n options?: DuckDbBatchOptions\n ): Promise<Result<BatchResponse>> {\n return this.service.batchOnDb(this.name, statements, options);\n }\n\n async executeStatement(\n name: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<QueryResponse | ExecuteResponse>> {\n return this.service.executeStatementOnDb(this.name, name, params, options);\n }\n\n async describe(options?: DuckDbOptions): Promise<Result<SchemaInfo>> {\n return this.service.describeDb(this.name, options);\n }\n\n async export(options?: DuckDbOptions): Promise<Result<Blob>> {\n return this.service.exportOnDb(this.name, options);\n }\n\n async import(data: Uint8Array, options?: DuckDbOptions): Promise<Result<void>> {\n return this.service.importOnDb(this.name, data, options);\n }\n}\n","/**\n * DuckDB Service Types\n *\n * Type definitions for the DuckDB service operations.\n */\n\n/**\n * Configuration for DuckDbService.\n */\nexport interface DuckDbServiceConfig {\n /**\n * Default database name.\n * If not set, operations default to \"default\".\n */\n defaultDatabase?: string;\n\n /**\n * Default timeout in milliseconds for DuckDB operations.\n */\n timeout?: number;\n\n /** Allow additional config properties */\n [key: string]: unknown;\n}\n\n/**\n * Options for DuckDB query operations.\n */\nexport interface DuckDbQueryOptions {\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for DuckDB execute operations.\n */\nexport interface DuckDbExecuteOptions {\n /**\n * Schema initialization statements (CREATE TABLE IF NOT EXISTS ...).\n * Executed before the main statement on first write.\n */\n schema?: string[];\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for DuckDB batch operations.\n */\nexport interface DuckDbBatchOptions {\n /**\n * Whether to run statements in a transaction.\n */\n transactional?: boolean;\n\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Options for DuckDB operations that only need an abort signal.\n */\nexport interface DuckDbOptions {\n /**\n * Custom abort signal for this operation.\n */\n signal?: AbortSignal;\n}\n\n/**\n * A DuckDB value: null, boolean, number, string, binary, array, or object.\n */\nexport type DuckDbValue =\n | null\n | boolean\n | number\n | string\n | Uint8Array\n | DuckDbValueArray\n | DuckDbValueRecord;\n\n/** Array of DuckDB values (workaround for circular type alias). */\nexport interface DuckDbValueArray extends Array<DuckDbValue> {}\n\n/** Record of DuckDB values (workaround for circular type alias). */\nexport interface DuckDbValueRecord {\n [key: string]: DuckDbValue;\n}\n\n/**\n * A DuckDB statement with optional parameters.\n */\nexport interface DuckDbStatement {\n sql: string;\n params?: DuckDbValue[];\n}\n\n/**\n * Response from DuckDB query operations.\n */\nexport interface QueryResponse<T = Record<string, unknown>> {\n columns: string[];\n rows: T[][];\n rowCount: number;\n}\n\n/**\n * Response from DuckDB execute operations.\n */\nexport interface ExecuteResponse {\n changes: number;\n}\n\n/**\n * Response from DuckDB batch operations.\n */\nexport interface BatchResponse {\n results: ExecuteResponse[];\n}\n\n/**\n * Schema information for a DuckDB database.\n */\nexport interface SchemaInfo {\n tables: TableInfo[];\n views: ViewInfo[];\n}\n\n/**\n * Information about a table.\n */\nexport interface TableInfo {\n name: string;\n columns: ColumnInfo[];\n}\n\n/**\n * Information about a column.\n */\nexport interface ColumnInfo {\n name: string;\n type: string;\n nullable: boolean;\n}\n\n/**\n * Information about a view.\n */\nexport interface ViewInfo {\n name: string;\n sql: string;\n}\n\n/**\n * DuckDB service action types.\n */\nexport const DuckDbAction = {\n READ: \"tinycloud.duckdb/read\",\n WRITE: \"tinycloud.duckdb/write\",\n ADMIN: \"tinycloud.duckdb/admin\",\n DESCRIBE: \"tinycloud.duckdb/describe\",\n EXPORT: \"tinycloud.duckdb/export\",\n IMPORT: \"tinycloud.duckdb/import\",\n EXECUTE: \"tinycloud.duckdb/execute\",\n ALL: \"tinycloud.duckdb/*\",\n} as const;\n\nexport type DuckDbActionType = (typeof DuckDbAction)[keyof typeof DuckDbAction];\n","/**\n * DuckDbService - DuckDB database service implementation.\n *\n * Platform-agnostic DuckDB service that works with both web-sdk and node-sdk.\n * Uses dependency injection via IServiceContext for platform dependencies.\n */\n\nimport { BaseService } from \"../base/BaseService\";\nimport {\n Result,\n ok,\n err,\n ErrorCodes,\n serviceError,\n type FetchResponse,\n} from \"../types\";\nimport { authRequiredError, wrapError, parseAuthError } from \"../errors\";\nimport type { IDuckDbService, IDuckDbDatabaseHandle } from \"./IDuckDbService\";\nimport { DuckDbDatabaseHandle } from \"./DuckDbDatabaseHandle\";\nimport {\n type DuckDbServiceConfig,\n type DuckDbQueryOptions,\n type DuckDbExecuteOptions,\n type DuckDbBatchOptions,\n type DuckDbOptions,\n type DuckDbValue,\n type DuckDbStatement,\n type QueryResponse,\n type ExecuteResponse,\n type BatchResponse,\n type SchemaInfo,\n DuckDbAction,\n} from \"./types\";\n\nexport class DuckDbService extends BaseService implements IDuckDbService {\n static readonly serviceName = \"duckdb\";\n\n declare protected _config: DuckDbServiceConfig;\n\n constructor(config: DuckDbServiceConfig = {}) {\n super();\n this._config = config;\n }\n\n get config(): DuckDbServiceConfig {\n return this._config;\n }\n\n private get defaultDbName(): string {\n return this._config.defaultDatabase ?? \"default\";\n }\n\n private get host(): string {\n return this.context.hosts[0];\n }\n\n /**\n * Get a handle to a named database.\n */\n db(name?: string): IDuckDbDatabaseHandle {\n return new DuckDbDatabaseHandle(this, name ?? this.defaultDbName);\n }\n\n /**\n * Shortcut: query the default database (JSON format).\n */\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<QueryResponse<T>>> {\n return this.queryOnDb<T>(this.defaultDbName, sql, params, options);\n }\n\n /**\n * Shortcut: query the default database (Arrow IPC format).\n */\n async queryArrow(\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<ArrayBuffer>> {\n return this.queryArrowOnDb(this.defaultDbName, sql, params, options);\n }\n\n /**\n * Shortcut: execute on the default database.\n */\n async execute(\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbExecuteOptions\n ): Promise<Result<ExecuteResponse>> {\n return this.executeOnDb(this.defaultDbName, sql, params, options);\n }\n\n /**\n * Shortcut: batch on the default database.\n */\n async batch(\n statements: DuckDbStatement[],\n options?: DuckDbBatchOptions\n ): Promise<Result<BatchResponse>> {\n return this.batchOnDb(this.defaultDbName, statements, options);\n }\n\n // === Internal methods called by DuckDbDatabaseHandle ===\n\n async queryOnDb<T = Record<string, unknown>>(\n dbName: string,\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<QueryResponse<T>>> {\n return this.withTelemetry<QueryResponse<T>>(\"query\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const response = await this.invokeDuckDb(\n dbName,\n DuckDbAction.READ,\n { action: \"query\", sql, params: params ?? [] },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"query\");\n }\n\n const data = (await response.json()) as QueryResponse<T>;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n async queryArrowOnDb(\n dbName: string,\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<ArrayBuffer>> {\n return this.withTelemetry<ArrayBuffer>(\"queryArrow\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const response = await this.invokeDuckDb(\n dbName,\n DuckDbAction.READ,\n { action: \"query\", sql, params: params ?? [] },\n options?.signal,\n { Accept: \"application/vnd.apache.arrow.stream\" }\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"queryArrow\");\n }\n\n const buffer = await response.arrayBuffer();\n return ok(buffer);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n async executeOnDb(\n dbName: string,\n sql: string,\n params?: DuckDbValue[],\n options?: DuckDbExecuteOptions\n ): Promise<Result<ExecuteResponse>> {\n return this.withTelemetry(\"execute\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const body: Record<string, unknown> = {\n action: \"execute\",\n sql,\n params: params ?? [],\n };\n if (options?.schema) {\n body.schema = options.schema;\n }\n\n const response = await this.invokeDuckDb(\n dbName,\n DuckDbAction.WRITE,\n body,\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"execute\");\n }\n\n const data = (await response.json()) as ExecuteResponse;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n async batchOnDb(\n dbName: string,\n statements: DuckDbStatement[],\n options?: DuckDbBatchOptions\n ): Promise<Result<BatchResponse>> {\n return this.withTelemetry(\"batch\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const body: Record<string, unknown> = {\n action: \"batch\",\n statements,\n };\n if (options?.transactional !== undefined) {\n body.transactional = options.transactional;\n }\n\n const response = await this.invokeDuckDb(\n dbName,\n DuckDbAction.WRITE,\n body,\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"batch\");\n }\n\n const data = (await response.json()) as BatchResponse;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n async executeStatementOnDb(\n dbName: string,\n name: string,\n params?: DuckDbValue[],\n options?: DuckDbQueryOptions\n ): Promise<Result<QueryResponse | ExecuteResponse>> {\n return this.withTelemetry(\"executeStatement\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const response = await this.invokeDuckDb(\n dbName,\n DuckDbAction.EXECUTE,\n { action: \"executeStatement\", name, params: params ?? [] },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"executeStatement\");\n }\n\n const data = (await response.json()) as\n | QueryResponse\n | ExecuteResponse;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n async describeDb(\n dbName: string,\n options?: DuckDbOptions\n ): Promise<Result<SchemaInfo>> {\n return this.withTelemetry(\"describe\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const response = await this.invokeDuckDb(\n dbName,\n DuckDbAction.DESCRIBE,\n { action: \"describe\" },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"describe\");\n }\n\n const data = (await response.json()) as SchemaInfo;\n return ok(data);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n async exportOnDb(\n dbName: string,\n options?: DuckDbOptions\n ): Promise<Result<Blob>> {\n return this.withTelemetry(\"export\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const response = await this.invokeDuckDb(\n dbName,\n DuckDbAction.EXPORT,\n { action: \"export\" },\n options?.signal\n );\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"export\");\n }\n\n const blob = await response.blob();\n return ok(blob);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n async importOnDb(\n dbName: string,\n data: Uint8Array,\n options?: DuckDbOptions\n ): Promise<Result<void>> {\n return this.withTelemetry(\"import\", dbName, async () => {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"duckdb\"));\n }\n\n try {\n const session = this.context.session!;\n const headers = this.context.invoke(\n session,\n \"duckdb\",\n dbName,\n DuckDbAction.IMPORT\n );\n\n const response = await this.context.fetch(`${this.host}/invoke`, {\n method: \"POST\",\n headers: {\n ...(headers as Record<string, string>),\n \"Content-Type\": \"application/x-duckdb\",\n },\n body: new Blob([data]),\n signal: this.combineSignals(options?.signal),\n });\n\n if (!response.ok) {\n return this.handleErrorResponse(response, \"import\");\n }\n\n return ok(undefined);\n } catch (error) {\n return err(wrapError(\"duckdb\", error));\n }\n });\n }\n\n // === Private helpers ===\n\n private async invokeDuckDb(\n dbName: string,\n action: string,\n body: Record<string, unknown>,\n signal?: AbortSignal,\n extraHeaders?: Record<string, string>\n ): Promise<FetchResponse> {\n const session = this.context.session!;\n const headers = this.context.invoke(session, \"duckdb\", dbName, action);\n\n return this.context.fetch(`${this.host}/invoke`, {\n method: \"POST\",\n headers: {\n ...(headers as Record<string, string>),\n \"Content-Type\": \"application/json\",\n ...extraHeaders,\n },\n body: JSON.stringify(body),\n signal: this.combineSignals(signal),\n });\n }\n\n private async handleErrorResponse(\n response: FetchResponse,\n operation: string\n ): Promise<Result<never>> {\n const errorText = await response.text();\n\n let errorBody: { error?: string; message?: string; code?: string } = {};\n try {\n errorBody = JSON.parse(errorText);\n } catch {\n // Not JSON\n }\n\n const errorCode = this.mapHttpStatusToErrorCode(\n response.status,\n errorBody.error\n );\n const message =\n errorBody.message ||\n `DuckDB ${operation} failed: ${response.status} - ${errorText}`;\n\n const meta: Record<string, unknown> = { status: response.status, statusText: response.statusText };\n\n if (response.status === 401) {\n const { resource, action } = parseAuthError(errorText);\n if (action) meta.requiredAction = action;\n if (resource) meta.resource = resource;\n }\n\n return err(\n serviceError(errorCode, message, \"duckdb\", { meta })\n );\n }\n\n private mapHttpStatusToErrorCode(\n status: number,\n serverError?: string\n ): string {\n switch (status) {\n case 400:\n return ErrorCodes.DUCKDB_ERROR;\n case 401:\n return ErrorCodes.AUTH_UNAUTHORIZED;\n case 403:\n if (serverError === \"duckdb_readonly_violation\") {\n return ErrorCodes.DUCKDB_READONLY_VIOLATION;\n }\n return ErrorCodes.DUCKDB_PERMISSION_DENIED;\n case 404:\n return ErrorCodes.DUCKDB_DATABASE_NOT_FOUND;\n case 413:\n return ErrorCodes.DUCKDB_RESPONSE_TOO_LARGE;\n case 429:\n return ErrorCodes.DUCKDB_QUOTA_EXCEEDED;\n default:\n return ErrorCodes.NETWORK_ERROR;\n }\n }\n}\n","import { BaseService } from \"../base/BaseService\";\nimport type {\n FetchResponse,\n InvokeAnyEntry,\n ServiceHeaders,\n Result,\n} from \"../types\";\nimport { ErrorCodes, err, ok, serviceError } from \"../types\";\nimport { authRequiredError, wrapError } from \"../errors\";\nimport type { IHooksService } from \"./IHooksService\";\nimport type {\n HookEvent,\n HookStreamEvent,\n HookSubscription,\n HooksServiceConfig,\n SubscribeOptions,\n HookWebhookListOptions,\n HookWebhookRecord,\n HookWebhookRegistration,\n HookWebhookUnregisterOptions,\n} from \"./types\";\n\ninterface HookTicketResponse {\n ticket: string;\n expiresAt: string;\n}\n\ninterface HookSubscriber {\n requested: HookSubscription[];\n ttlSeconds?: number;\n queue: AsyncQueue<HookEvent>;\n}\n\nclass AsyncQueue<T> implements AsyncIterable<T>, AsyncIterator<T> {\n private readonly values: T[] = [];\n private readonly waiters: Array<(result: IteratorResult<T>) => void> = [];\n private closed = false;\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this;\n }\n\n push(value: T): void {\n if (this.closed) {\n return;\n }\n\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter({ value, done: false });\n return;\n }\n\n this.values.push(value);\n }\n\n close(): void {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n while (this.waiters.length > 0) {\n const waiter = this.waiters.shift();\n waiter?.({ value: undefined as never, done: true });\n }\n }\n\n next(): Promise<IteratorResult<T>> {\n if (this.values.length > 0) {\n const value = this.values.shift()!;\n return Promise.resolve({ value, done: false });\n }\n\n if (this.closed) {\n return Promise.resolve({ value: undefined as never, done: true });\n }\n\n return new Promise<IteratorResult<T>>((resolve) => {\n this.waiters.push(resolve);\n });\n }\n}\n\nexport class HooksService extends BaseService implements IHooksService {\n static readonly serviceName = \"hooks\";\n\n declare protected _config: HooksServiceConfig;\n private readonly _subscribers: Set<HookSubscriber> = new Set();\n private _sharedStreamTask?: Promise<void>;\n private _sharedStreamAbort?: AbortController;\n private _refreshChain: Promise<void> = Promise.resolve();\n private _activeSignature = \"\";\n\n constructor(config: HooksServiceConfig = {}) {\n super();\n this._config = config;\n }\n\n get config(): HooksServiceConfig {\n return this._config;\n }\n\n private get host(): string {\n return this._config.host ?? this.context.hosts[0];\n }\n\n async *subscribe(\n subscriptions: HookSubscription[],\n options: SubscribeOptions = {},\n ): AsyncIterable<HookEvent> {\n if (!this.requireAuth()) {\n throw new Error(\"Authentication required for hooks subscription\");\n }\n if (subscriptions.length === 0) {\n throw new Error(\"At least one hook subscription is required\");\n }\n\n const normalized = subscriptions.map(normalizeSubscription);\n const subscriber: HookSubscriber = {\n requested: normalized,\n ttlSeconds: options.ttlSeconds,\n queue: new AsyncQueue<HookEvent>(),\n };\n\n this._subscribers.add(subscriber);\n const abortHandler = () => {\n this._subscribers.delete(subscriber);\n subscriber.queue.close();\n void this.scheduleSharedStreamRefresh();\n };\n\n if (options.signal) {\n if (options.signal.aborted) {\n abortHandler();\n } else {\n options.signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n }\n\n void this.scheduleSharedStreamRefresh();\n\n try {\n for await (const event of subscriber.queue) {\n yield event;\n }\n } finally {\n if (options.signal) {\n options.signal.removeEventListener(\"abort\", abortHandler);\n }\n abortHandler();\n }\n }\n\n async register(\n webhook: HookWebhookRegistration,\n ): Promise<Result<HookWebhookRecord>> {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"hooks\"));\n }\n\n if (typeof webhook.secret !== \"string\" || webhook.secret.trim().length === 0) {\n return err(\n serviceError(\n ErrorCodes.INVALID_INPUT,\n \"Webhook secret is required\",\n \"hooks\",\n { meta: { field: \"secret\" } },\n ),\n );\n }\n\n try {\n const response = await this.context.fetch(`${this.host}/hooks/webhooks`, {\n method: \"POST\",\n headers: {\n ...serviceHeadersToRecord(\n this.createHookHeaders(\n \"tinycloud.hooks/register\",\n buildScopePath(webhook.service, webhook.pathPrefix),\n ),\n ),\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n space: webhook.space,\n service: webhook.service,\n pathPrefix: normalizePathPrefix(webhook.pathPrefix),\n abilities: webhook.abilities ?? [],\n callbackUrl: webhook.callbackUrl,\n secret: webhook.secret,\n }),\n });\n\n if (!response.ok) {\n return err(\n await responseError(\"hooks\", \"failed to register webhook\", response),\n );\n }\n\n const data = normalizeWebhookRecord(await response.json());\n if (!data) {\n return err(\n wrapError(\n \"hooks\",\n new Error(\"Webhook registration response did not include a record\"),\n ),\n );\n }\n\n return ok(data);\n } catch (error) {\n return err(wrapError(\"hooks\", error));\n }\n }\n\n async list(\n options: HookWebhookListOptions = {},\n ): Promise<Result<HookWebhookRecord[]>> {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"hooks\"));\n }\n\n try {\n const query = new URLSearchParams();\n if (options.space) {\n query.set(\"space\", options.space);\n }\n if (options.service) {\n query.set(\"service\", options.service);\n }\n if (options.pathPrefix) {\n const normalizedPrefix = normalizePathPrefix(options.pathPrefix);\n if (normalizedPrefix) {\n query.set(\"prefix\", normalizedPrefix);\n }\n }\n\n const response = await this.context.fetch(\n `${this.host}/hooks/webhooks${query.size > 0 ? `?${query.toString()}` : \"\"}`,\n {\n method: \"GET\",\n headers: serviceHeadersToRecord(\n this.createHookHeaders(\n \"tinycloud.hooks/list\",\n options.service\n ? buildScopePath(options.service, options.pathPrefix)\n : \"webhooks\",\n ),\n ),\n },\n );\n\n if (!response.ok) {\n return err(\n await responseError(\"hooks\", \"failed to list webhooks\", response),\n );\n }\n\n const payload = await response.json();\n const records = normalizeWebhookRecordList(payload);\n if (!records) {\n return err(\n wrapError(\n \"hooks\",\n new Error(\"Webhook list response did not include records\"),\n ),\n );\n }\n\n return ok(records);\n } catch (error) {\n return err(wrapError(\"hooks\", error));\n }\n }\n\n async unregister(\n id: string,\n options: HookWebhookUnregisterOptions = {},\n ): Promise<Result<void>> {\n if (!this.requireAuth()) {\n return err(authRequiredError(\"hooks\"));\n }\n\n try {\n const response = await this.context.fetch(\n `${this.host}/hooks/webhooks/${encodeURIComponent(id)}`,\n {\n method: \"DELETE\",\n headers: serviceHeadersToRecord(\n this.createHookHeaders(\n \"tinycloud.hooks/unregister\",\n options.target\n ? buildScopePath(\n options.target.service,\n options.target.pathPrefix,\n )\n : `webhooks/${id}`,\n ),\n ),\n },\n );\n\n if (!response.ok) {\n return err(\n await responseError(\n \"hooks\",\n \"failed to unregister webhook\",\n response,\n ),\n );\n }\n\n return ok(undefined);\n } catch (error) {\n return err(wrapError(\"hooks\", error));\n }\n }\n\n private async scheduleSharedStreamRefresh(): Promise<void> {\n this._refreshChain = this._refreshChain\n .then(() => this.refreshSharedStream())\n .catch(() => undefined);\n await this._refreshChain;\n }\n\n private async refreshSharedStream(): Promise<void> {\n if (!this.requireAuth() || this._subscribers.size === 0) {\n this.abortSharedStream();\n this._activeSignature = \"\";\n return;\n }\n\n const state = this.collectSharedStreamState();\n if (state.signature !== this._activeSignature) {\n this._activeSignature = state.signature;\n this.abortSharedStream();\n }\n\n if (!this._sharedStreamTask) {\n this._sharedStreamTask = this.runSharedStream(state)\n .catch((error: unknown) => {\n if (!isAbortError(error)) {\n throw error;\n }\n })\n .finally(() => {\n this._sharedStreamTask = undefined;\n this._sharedStreamAbort = undefined;\n if (this._subscribers.size > 0) {\n void this.scheduleSharedStreamRefresh();\n }\n });\n }\n }\n\n private collectSharedStreamState(): {\n subscriptions: HookSubscription[];\n ttlSeconds?: number;\n signature: string;\n } {\n const merged = new Map<string, HookSubscription>();\n const ttlCandidates: number[] = [];\n\n for (const subscriber of this._subscribers) {\n if (typeof subscriber.ttlSeconds === \"number\") {\n ttlCandidates.push(subscriber.ttlSeconds);\n }\n for (const subscription of subscriber.requested) {\n merged.set(subscriptionSignature(subscription), subscription);\n }\n }\n\n const subscriptions = [...merged.values()].sort((left, right) =>\n subscriptionSignature(left).localeCompare(subscriptionSignature(right)),\n );\n const ttlSeconds =\n ttlCandidates.length > 0 ? Math.min(...ttlCandidates) : undefined;\n const signature = JSON.stringify({\n subscriptions: subscriptions.map(subscriptionSignature),\n ttlSeconds,\n });\n\n return {\n subscriptions,\n ttlSeconds,\n signature,\n };\n }\n\n private async runSharedStream(state: {\n subscriptions: HookSubscription[];\n ttlSeconds?: number;\n }): Promise<void> {\n const abortController = new AbortController();\n this._sharedStreamAbort = abortController;\n\n try {\n const host = this._config.host ?? this.context.hosts[0];\n const ticketResponse = await this.mintHookTicket(\n state.subscriptions,\n state.ttlSeconds,\n abortController.signal,\n );\n const streamResponse = await this.openHookStream(\n host,\n ticketResponse.ticket,\n abortController.signal,\n );\n\n for await (const message of parseSseStream(\n streamResponse.body,\n abortController.signal,\n )) {\n if (!message.data) {\n continue;\n }\n const event = parseHookEvent(message);\n for (const subscriber of this._subscribers) {\n if (matchesAnySubscription(event, subscriber.requested)) {\n subscriber.queue.push(event);\n }\n }\n }\n } finally {\n if (this._sharedStreamAbort === abortController) {\n this._sharedStreamAbort = undefined;\n }\n }\n }\n\n private abortSharedStream(): void {\n this._sharedStreamAbort?.abort();\n }\n\n private createHookHeaders(action: string, path: string): ServiceHeaders {\n return this.context.invoke(this.session, \"hooks\", path, action);\n }\n\n private async mintHookTicket(\n subscriptions: HookSubscription[],\n ttlSeconds: number | undefined,\n signal?: AbortSignal,\n ): Promise<HookTicketResponse> {\n const host = this._config.host ?? this.context.hosts[0];\n const headers = this.createInvokeHeaders(subscriptions);\n const ticketResponse = await this.context.fetch(`${host}/hooks/tickets`, {\n method: \"POST\",\n headers: {\n ...serviceHeadersToRecord(headers),\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n subscriptions,\n ttlSeconds,\n }),\n signal,\n });\n\n if (!ticketResponse.ok) {\n throw await responseError(\n \"hooks\",\n \"failed to mint hook ticket\",\n ticketResponse,\n );\n }\n\n const ticketJson = (await ticketResponse.json()) as HookTicketResponse;\n if (!ticketJson?.ticket) {\n throw new Error(\"Hook ticket response did not include a ticket\");\n }\n\n return ticketJson;\n }\n\n private async openHookStream(\n host: string,\n ticket: string,\n signal?: AbortSignal,\n ): Promise<FetchResponse> {\n const streamResponse = await this.context.fetch(\n `${host}/hooks/events?ticket=${encodeURIComponent(ticket)}`,\n {\n method: \"GET\",\n headers: { accept: \"text/event-stream\" },\n signal,\n },\n );\n\n if (!streamResponse.ok) {\n throw await responseError(\n \"hooks\",\n \"failed to open hook stream\",\n streamResponse,\n );\n }\n\n return streamResponse;\n }\n\n private createInvokeHeaders(\n subscriptions: HookSubscription[],\n ): ServiceHeaders {\n const entries: InvokeAnyEntry[] = subscriptions.map((subscription) => ({\n spaceId: subscription.space,\n service: \"hooks\",\n path: subscription.pathPrefix\n ? `${subscription.service}/${subscription.pathPrefix}`\n : subscription.service,\n action: \"tinycloud.hooks/subscribe\",\n }));\n\n if (this.context.invokeAny) {\n return this.context.invokeAny(this.session, entries);\n }\n\n if (entries.length === 1) {\n const entry = entries[0];\n return this.context.invoke(\n this.session,\n entry.service,\n entry.path,\n entry.action,\n );\n }\n\n throw new Error(\n \"This SDK runtime does not support multi-scope hook invocations\",\n );\n }\n}\n\nfunction buildScopePath(\n service: HookSubscription[\"service\"],\n pathPrefix?: string,\n): string {\n const normalized = normalizePathPrefix(pathPrefix);\n return normalized ? `${service}/${normalized}` : service;\n}\n\nfunction normalizeSubscription(\n subscription: HookSubscription,\n): HookSubscription {\n return {\n ...subscription,\n pathPrefix: normalizePathPrefix(subscription.pathPrefix),\n abilities: subscription.abilities ?? [],\n };\n}\n\nfunction subscriptionSignature(subscription: HookSubscription): string {\n return JSON.stringify({\n space: subscription.space,\n service: subscription.service,\n pathPrefix: subscription.pathPrefix ?? \"\",\n abilities: [...(subscription.abilities ?? [])].sort(),\n });\n}\n\nfunction matchesAnySubscription(\n event: HookEvent,\n subscriptions: HookSubscription[],\n): boolean {\n return subscriptions.some((subscription) =>\n matchesSubscription(event, subscription),\n );\n}\n\nfunction matchesSubscription(\n event: HookEvent,\n subscription: HookSubscription,\n): boolean {\n if (event.space !== subscription.space) {\n return false;\n }\n if (event.service !== subscription.service) {\n return false;\n }\n if (subscription.pathPrefix) {\n const prefix = subscription.pathPrefix.endsWith(\"/\")\n ? subscription.pathPrefix\n : `${subscription.pathPrefix}/`;\n if (\n event.path &&\n event.path !== subscription.pathPrefix &&\n !event.path.startsWith(prefix)\n ) {\n return false;\n }\n }\n const abilities = subscription.abilities ?? [];\n if (abilities.length > 0 && !abilities.includes(event.ability)) {\n return false;\n }\n return true;\n}\n\nfunction normalizePathPrefix(pathPrefix?: string): string | undefined {\n if (!pathPrefix) {\n return undefined;\n }\n const trimmed = pathPrefix.replace(/^\\/+|\\/+$/g, \"\");\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction serviceHeadersToRecord(\n headers: ServiceHeaders,\n): Record<string, string> {\n if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n }\n return { ...headers };\n}\n\nasync function responseError(\n service: string,\n message: string,\n response: FetchResponse,\n): Promise<ReturnType<typeof wrapError>> {\n let detail = response.statusText;\n try {\n const text = await response.text();\n if (text) {\n detail = text;\n }\n } catch {\n // Ignore secondary body read failure.\n }\n return wrapError(\n service,\n new Error(`${message}: ${response.status} ${detail}`),\n );\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"AbortError\";\n}\n\nasync function* parseSseStream(\n body: unknown,\n signal?: AbortSignal,\n): AsyncIterable<HookStreamEvent> {\n if (!body) {\n throw new Error(\"Hook stream response does not expose a readable body\");\n }\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n for await (const chunk of readBodyChunks(body, signal)) {\n buffer += decoder.decode(chunk, { stream: true }).replace(/\\r\\n/g, \"\\n\");\n\n let separatorIndex = buffer.indexOf(\"\\n\\n\");\n while (separatorIndex >= 0) {\n const rawEvent = buffer.slice(0, separatorIndex);\n buffer = buffer.slice(separatorIndex + 2);\n const parsed = parseSseEvent(rawEvent);\n if (parsed) {\n yield parsed;\n }\n separatorIndex = buffer.indexOf(\"\\n\\n\");\n }\n }\n\n buffer += decoder.decode();\n const trailing = parseSseEvent(buffer.trim());\n if (trailing) {\n yield trailing;\n }\n}\n\nasync function* readBodyChunks(\n body: unknown,\n signal?: AbortSignal,\n): AsyncIterable<Uint8Array> {\n const asyncIterable = body as AsyncIterable<Uint8Array>;\n if (typeof asyncIterable?.[Symbol.asyncIterator] === \"function\") {\n for await (const chunk of asyncIterable) {\n if (signal?.aborted) {\n break;\n }\n yield chunk;\n }\n return;\n }\n\n const stream = body as {\n getReader?: () => {\n read: () => Promise<{ done: boolean; value?: Uint8Array }>;\n releaseLock?: () => void;\n cancel?: () => Promise<void>;\n };\n };\n\n if (typeof stream.getReader !== \"function\") {\n throw new Error(\"Unsupported hook stream body type\");\n }\n\n const reader = stream.getReader();\n try {\n while (!signal?.aborted) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (value) {\n yield value;\n }\n }\n } finally {\n try {\n await reader.cancel?.();\n } catch {\n // Ignore cancellation failures.\n }\n reader.releaseLock?.();\n }\n}\n\nfunction parseSseEvent(rawEvent: string): HookStreamEvent | null {\n if (!rawEvent) {\n return null;\n }\n\n let event = \"message\";\n let id: string | undefined;\n const dataLines: string[] = [];\n\n for (const line of rawEvent.split(\"\\n\")) {\n if (!line || line.startsWith(\":\")) {\n continue;\n }\n const [field, ...rest] = line.split(\":\");\n const value = rest.join(\":\").replace(/^ /, \"\");\n switch (field) {\n case \"event\":\n event = value;\n break;\n case \"id\":\n id = value;\n break;\n case \"data\":\n dataLines.push(value);\n break;\n default:\n break;\n }\n }\n\n if (dataLines.length === 0) {\n return null;\n }\n\n return {\n event,\n id,\n data: dataLines.join(\"\\n\"),\n };\n}\n\nfunction parseHookEvent(message: HookStreamEvent): HookEvent {\n const parsed = JSON.parse(message.data) as Partial<HookEvent>;\n return {\n type: \"write\",\n id: parsed.id ?? message.id ?? \"\",\n space: parsed.space ?? \"\",\n service: parsed.service ?? \"\",\n ability: parsed.ability ?? \"\",\n path: parsed.path,\n actor: parsed.actor ?? \"\",\n epoch: parsed.epoch ?? \"\",\n eventIndex: parsed.eventIndex ?? 0,\n timestamp: parsed.timestamp ?? \"\",\n };\n}\n\nfunction normalizeWebhookRecord(data: unknown): HookWebhookRecord | null {\n if (!data || typeof data !== \"object\") {\n return null;\n }\n\n const record = isRecordContainer(data);\n const candidate =\n pickWebhookRecord(record) ??\n normalizeWebhookRecord(record.webhook) ??\n normalizeWebhookRecord(record.hook) ??\n normalizeWebhookRecord(record.subscription) ??\n normalizeWebhookRecord(record.data);\n return candidate ?? null;\n}\n\nfunction normalizeWebhookRecordList(data: unknown): HookWebhookRecord[] | null {\n if (Array.isArray(data)) {\n const records = data\n .map((entry) => normalizeWebhookRecord(entry))\n .filter((entry): entry is HookWebhookRecord => entry !== null);\n return records;\n }\n\n if (!data || typeof data !== \"object\") {\n return null;\n }\n\n const record = isRecordContainer(data);\n const nested =\n maybeRecordArray(record.webhooks) ??\n maybeRecordArray(record.subscriptions) ??\n maybeRecordArray(record.hooks) ??\n maybeRecordArray(record.data);\n if (nested) {\n return nested;\n }\n\n const single = pickWebhookRecord(record);\n return single ? [single] : null;\n}\n\nfunction maybeRecordArray(value: unknown): HookWebhookRecord[] | null {\n if (!Array.isArray(value)) {\n return null;\n }\n\n const records = value\n .map((entry) => normalizeWebhookRecord(entry))\n .filter((entry): entry is HookWebhookRecord => entry !== null);\n return records;\n}\n\nfunction pickWebhookRecord(\n value: Record<string, unknown>,\n): HookWebhookRecord | null {\n const id = stringField(value, \"id\");\n const space = stringField(value, \"space\") ?? stringField(value, \"spaceId\");\n const service = stringField(value, \"service\");\n const callbackUrl =\n stringField(value, \"callbackUrl\") ?? stringField(value, \"callback_url\");\n if (!id || !space || !service || !callbackUrl) {\n return null;\n }\n\n return {\n id,\n space,\n service: service as HookWebhookRecord[\"service\"],\n pathPrefix:\n optionalStringField(value, \"pathPrefix\") ??\n optionalStringField(value, \"path_prefix\"),\n abilities:\n stringArrayField(value, \"abilities\") ??\n parsedStringArrayField(value, \"abilitiesJson\") ??\n parsedStringArrayField(value, \"abilities_json\"),\n callbackUrl,\n active: booleanField(value, \"active\") ?? true,\n createdAt:\n stringField(value, \"createdAt\") ??\n stringField(value, \"created_at\") ??\n new Date().toISOString(),\n subscriberDid:\n optionalStringField(value, \"subscriberDid\") ??\n optionalStringField(value, \"subscriber_did\"),\n };\n}\n\nfunction isRecordContainer(value: object): Record<string, unknown> {\n return value as Record<string, unknown>;\n}\n\nfunction stringField(\n value: Record<string, unknown>,\n key: string,\n): string | undefined {\n const field = value[key];\n return typeof field === \"string\" ? field : undefined;\n}\n\nfunction optionalStringField(\n value: Record<string, unknown>,\n key: string,\n): string | undefined {\n return stringField(value, key);\n}\n\nfunction booleanField(\n value: Record<string, unknown>,\n key: string,\n): boolean | undefined {\n const field = value[key];\n return typeof field === \"boolean\" ? field : undefined;\n}\n\nfunction stringArrayField(\n value: Record<string, unknown>,\n key: string,\n): string[] | undefined {\n const field = value[key];\n if (!Array.isArray(field)) {\n return undefined;\n }\n const strings = field.filter(\n (item): item is string => typeof item === \"string\",\n );\n return strings.length === field.length ? strings : undefined;\n}\n\nfunction parsedStringArrayField(\n value: Record<string, unknown>,\n key: string,\n): string[] | undefined {\n const field = value[key];\n if (typeof field !== \"string\") {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(field) as unknown;\n if (!Array.isArray(parsed)) {\n return undefined;\n }\n const strings = parsed.filter(\n (item): item is string => typeof item === \"string\",\n );\n return strings.length === parsed.length ? strings : undefined;\n } catch {\n return undefined;\n }\n}\n","import type { StorageQuotaInfo } from \"../types\";\n\nexport interface QuotaConfig {\n /** Called when a storage quota error is detected (402/413) */\n onUpgradeRequired?: (info: StorageQuotaInfo) => void;\n}\n\nexport interface QuotaStatus {\n /** Storage limit in bytes for this space */\n limitBytes: number;\n /** Storage used in bytes for this space */\n usedBytes?: number;\n /** Remaining storage in bytes */\n remainingBytes?: number;\n}\n\nexport class TinyCloudQuota {\n private config: QuotaConfig;\n private quotaUrl: string | null = null;\n\n constructor(config: QuotaConfig = {}) {\n this.config = config;\n }\n\n /** Set the quota URL discovered from the /info endpoint */\n setQuotaUrl(url: string | null): void {\n this.quotaUrl = url;\n }\n\n /** Whether a quota service is available */\n get available(): boolean {\n return this.quotaUrl !== null;\n }\n\n /** Query quota status for a space from the quota URL */\n async getQuota(spaceId: string): Promise<QuotaStatus | null> {\n if (!this.quotaUrl) return null;\n\n const resp = await fetch(\n `${this.quotaUrl}/api/quota/${encodeURIComponent(spaceId)}`\n );\n if (!resp.ok) return null;\n\n const data = (await resp.json()) as { storage_limit_bytes?: number };\n return {\n limitBytes: data.storage_limit_bytes ?? 0,\n };\n }\n\n /** Trigger the upgrade callback when a quota error is encountered */\n handleQuotaError(info: StorageQuotaInfo): void {\n this.config.onUpgradeRequired?.(info);\n }\n}\n","/**\n * Data Vault Service Types\n *\n * Type definitions for the Data Vault (encrypted KV) service operations.\n */\n\nimport type {\n DecryptCapabilityProof,\n IEncryptionService,\n} from \"../encryption\";\n\nexport interface VaultNetworkEncryptionConfig {\n /** Default encryption network used for inline vault envelopes. */\n networkId: string;\n /** TinyCloud encryption module used for local encrypt and node-mediated decrypt. */\n service: IEncryptionService;\n /** Proof material presented to the encryption module for decrypt requests. */\n decryptCapabilityProof?:\n | DecryptCapabilityProof\n | (() => DecryptCapabilityProof | Promise<DecryptCapabilityProof>);\n}\n\n/**\n * Configuration for DataVaultService.\n */\nexport interface DataVaultConfig {\n /** Space ID for encrypted data storage */\n spaceId: string;\n /** Key rotation policy */\n keyRotation?: \"per-write\" | \"per-key\"; // default: \"per-write\"\n /** Network-envelope encryption mode. When set, vault.unlock/key grants are not used. */\n encryption?: VaultNetworkEncryptionConfig;\n}\n\n/**\n * Options for vault put operations.\n */\nexport interface VaultPutOptions {\n /** Custom metadata tags appended to the envelope */\n metadata?: Record<string, string>;\n /** Content type hint for deserialization (default: auto-detect) */\n contentType?: string;\n /** Custom serializer (default: JSON.stringify for objects) */\n serialize?: (value: unknown) => Uint8Array;\n}\n\n/**\n * Options for vault get operations.\n */\nexport interface VaultGetOptions<T = unknown> {\n /** Custom deserializer (default: JSON.parse if content-type is JSON) */\n deserialize?: (data: Uint8Array) => T;\n /** Return raw decrypted bytes without deserialization */\n raw?: boolean;\n /** Delegated KV service for reading from the grantor's space (used by getShared) */\n kv?: { get<V>(key: string, options?: { raw?: boolean }): Promise<{ ok: boolean; data?: { data: V }; error?: { message: string } }> };\n}\n\n/**\n * Options for vault list operations.\n */\nexport interface VaultListOptions {\n /** Prefix filter for key names */\n prefix?: string;\n /** Remove prefix from returned keys */\n removePrefix?: boolean;\n}\n\n/**\n * Options for vault grant (sharing) operations.\n */\nexport interface VaultGrantOptions {\n /** Additional metadata on the grant */\n metadata?: Record<string, string>;\n}\n\n/**\n * A decrypted vault entry returned by get operations.\n *\n * @template T - Type of the decrypted value\n */\nexport interface VaultEntry<T> {\n /** Decrypted value */\n value: T;\n /** Envelope metadata */\n metadata: Record<string, string>;\n /** Key ID used for encryption */\n keyId: string;\n}\n\n/**\n * Structured error codes for vault operations.\n */\n/**\n * Input types for creating vault errors (service field added automatically).\n */\nexport type VaultErrorInput =\n | { code: \"DECRYPTION_FAILED\"; message?: string; cause?: Error }\n | { code: \"KEY_NOT_FOUND\"; key: string; message?: string }\n | { code: \"INTEGRITY_ERROR\"; message?: string; cause?: Error }\n | { code: \"GRANT_NOT_FOUND\"; grantor: string; key: string; message?: string }\n | { code: \"VAULT_LOCKED\"; message?: string }\n | { code: \"PUBLIC_KEY_NOT_FOUND\"; did: string; message?: string }\n | { code: \"STORAGE_ERROR\"; cause: Error; message?: string };\n\n/**\n * Vault error with service field (compatible with ServiceError).\n */\nexport type VaultError = VaultErrorInput & { service: \"vault\"; message: string };\n\n\n/** KV actions the vault needs on the public space for key publishing. */\nexport const VaultPublicSpaceKVActions = [\n \"tinycloud.kv/get\",\n \"tinycloud.kv/put\",\n \"tinycloud.kv/metadata\",\n] as const;\n\n/** Version-keyed signing message configuration for vault key derivation. */\nexport const VaultVersionConfig = {\n \"1\": {\n masterMessage: (spaceId: string) => `tinycloud-vault-master-v1:${spaceId}`,\n identityMessage: \"tinycloud-encryption-identity-v1\",\n },\n} as const;\n\nexport const CURRENT_VAULT_VERSION = \"1\" as const;\n\n/** Metadata header keys used in vault envelopes */\nexport const VaultHeaders = {\n VERSION: \"x-vault-version\",\n CIPHER: \"x-vault-cipher\",\n KEY_ID: \"x-vault-key-id\",\n CONTENT_TYPE: \"x-vault-content-type\",\n KDF: \"x-vault-kdf\",\n KEY_ROTATION: \"x-vault-key-rotation\",\n GRANT_VERSION: \"x-vault-grant-version\",\n GRANTOR: \"x-vault-grantor\",\n} as const;\n","/**\n * Caches vault signatures in IndexedDB, encrypted with a\n * non-extractable CryptoKey. Browser-only — no-ops in Node.\n */\n\n// Minimal type declarations for browser APIs used below.\n// The sdk-services tsconfig targets ES2020 without DOM lib;\n// these declarations let the file compile while the runtime\n// guards (isBrowser()) ensure we never call them in Node.\ndeclare const indexedDB: {\n open(name: string, version?: number): IDBOpenDBRequest;\n};\ninterface IDBOpenDBRequest {\n result: IDBDatabase;\n error: DOMException | null;\n onupgradeneeded: ((this: IDBOpenDBRequest) => void) | null;\n onsuccess: ((this: IDBOpenDBRequest) => void) | null;\n onerror: ((this: IDBOpenDBRequest) => void) | null;\n}\ninterface IDBDatabase {\n objectStoreNames: { contains(name: string): boolean };\n createObjectStore(name: string): void;\n transaction(storeNames: string | string[], mode?: string): IDBTransaction;\n}\ninterface IDBTransaction {\n objectStore(name: string): IDBObjectStore;\n}\ninterface IDBObjectStore {\n get(key: string): IDBRequest;\n put(value: unknown, key: string): IDBRequest;\n delete(key: string): IDBRequest;\n getAllKeys(): IDBRequest;\n}\ninterface IDBRequest<T = unknown> {\n result: T;\n error: DOMException | null;\n onsuccess: ((this: IDBRequest<T>) => void) | null;\n onerror: ((this: IDBRequest<T>) => void) | null;\n}\ntype IDBValidKey = string | number | Date | ArrayBuffer | Uint8Array | IDBValidKey[];\n\nconst DB_NAME = \"tinycloud-vault-cache\";\nconst DB_VERSION = 1;\nconst STORE_NAME = \"signatures\";\nconst WRAP_KEY_ID = \"__wrap_key__\";\n\n/** Check whether we're in a browser with IndexedDB + SubtleCrypto support. */\nfunction isBrowser(): boolean {\n try {\n return (\n typeof indexedDB !== \"undefined\" &&\n typeof crypto !== \"undefined\" &&\n typeof crypto.subtle !== \"undefined\"\n );\n } catch {\n return false;\n }\n}\n\n/** Open (or create) the IndexedDB database. */\nfunction openDB(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(STORE_NAME)) {\n db.createObjectStore(STORE_NAME);\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/** Generic IDB get helper. */\nfunction idbGet<T>(db: IDBDatabase, key: string): Promise<T | undefined> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE_NAME, \"readonly\");\n const store = tx.objectStore(STORE_NAME);\n const req = store.get(key);\n req.onsuccess = () => resolve(req.result as T | undefined);\n req.onerror = () => reject(req.error);\n });\n}\n\n/** Generic IDB put helper. */\nfunction idbPut(db: IDBDatabase, key: string, value: unknown): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE_NAME, \"readwrite\");\n const store = tx.objectStore(STORE_NAME);\n const req = store.put(value, key);\n req.onsuccess = () => resolve();\n req.onerror = () => reject(req.error);\n });\n}\n\n/** Generic IDB delete helper. */\nfunction idbDelete(db: IDBDatabase, key: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE_NAME, \"readwrite\");\n const store = tx.objectStore(STORE_NAME);\n const req = store.delete(key);\n req.onsuccess = () => resolve();\n req.onerror = () => reject(req.error);\n });\n}\n\n/** List all keys in the store. */\nfunction idbKeys(db: IDBDatabase): Promise<string[]> {\n return new Promise((resolve, reject) => {\n const tx = db.transaction(STORE_NAME, \"readonly\");\n const store = tx.objectStore(STORE_NAME);\n const req = store.getAllKeys();\n req.onsuccess = () =>\n resolve((req.result as IDBValidKey[]).filter((k) => typeof k === \"string\") as string[]);\n req.onerror = () => reject(req.error);\n });\n}\n\ninterface EncryptedEntry {\n iv: Uint8Array;\n ciphertext: Uint8Array;\n}\n\n/**\n * Get or create the non-extractable AES-GCM wrapping key.\n * The key is stored directly in IndexedDB (structured-clone preserves CryptoKey).\n */\nasync function getWrapKey(db: IDBDatabase): Promise<CryptoKey> {\n const existing = await idbGet<CryptoKey>(db, WRAP_KEY_ID);\n if (existing) return existing;\n\n const key = await crypto.subtle.generateKey(\n { name: \"AES-GCM\", length: 256 },\n false, // non-extractable\n [\"encrypt\", \"decrypt\"]\n );\n await idbPut(db, WRAP_KEY_ID, key);\n return key;\n}\n\n/** Encrypt signature bytes with the wrap key. */\nasync function encryptSig(\n wrapKey: CryptoKey,\n sigBytes: Uint8Array\n): Promise<EncryptedEntry> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv }, wrapKey, sigBytes)\n );\n return { iv, ciphertext };\n}\n\n/** Decrypt an encrypted entry back to signature bytes. */\nasync function decryptSig(\n wrapKey: CryptoKey,\n entry: EncryptedEntry\n): Promise<Uint8Array> {\n const plaintext = await crypto.subtle.decrypt(\n { name: \"AES-GCM\", iv: entry.iv },\n wrapKey,\n entry.ciphertext\n );\n return new Uint8Array(plaintext);\n}\n\n/** Cache key for a given spaceId. */\nfunction cacheKey(spaceId: string): string {\n return `sig:${spaceId}`;\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Load a cached signature for the given spaceId.\n * Returns null on cache miss or in non-browser environments.\n */\nexport async function loadCachedSignature(\n spaceId: string\n): Promise<Uint8Array | null> {\n if (!isBrowser()) return null;\n try {\n const db = await openDB();\n const entry = await idbGet<EncryptedEntry>(db, cacheKey(spaceId));\n if (!entry) return null;\n const wrapKey = await getWrapKey(db);\n return await decryptSig(wrapKey, entry);\n } catch {\n return null;\n }\n}\n\n/**\n * Cache a signature for the given spaceId.\n * No-ops in non-browser environments.\n */\nexport async function cacheSignature(\n spaceId: string,\n sigBytes: Uint8Array\n): Promise<void> {\n if (!isBrowser()) return;\n try {\n const db = await openDB();\n const wrapKey = await getWrapKey(db);\n const encrypted = await encryptSig(wrapKey, sigBytes);\n await idbPut(db, cacheKey(spaceId), encrypted);\n } catch {\n // Best-effort — swallow errors\n }\n}\n\n/**\n * Clear cached signature(s).\n * If spaceId is provided, clears only that entry; otherwise clears all.\n */\nexport async function clearSignatureCache(\n spaceId?: string\n): Promise<void> {\n if (!isBrowser()) return;\n try {\n const db = await openDB();\n if (spaceId) {\n await idbDelete(db, cacheKey(spaceId));\n } else {\n // Clear all sig entries but keep the wrap key\n const keys = await idbKeys(db);\n for (const k of keys) {\n if (k.startsWith(\"sig:\")) {\n await idbDelete(db, k);\n }\n }\n }\n } catch {\n // Best-effort\n }\n}\n","/**\n * DataVaultService - Encrypted key-value storage service implementation.\n *\n * Platform-agnostic encrypted KV service that wraps KVService internally.\n * Uses dependency injection via VaultCrypto for WASM crypto operations\n * and DataVaultServiceConfig for platform dependencies.\n *\n * Architecture:\n * - Extends BaseService (not KVService)\n * - Wraps two KV instances: dataKV (prefix \"vault/\") and keyKV (prefix \"keys/\")\n * - Master key and encryption identity live in memory only (cleared on lock)\n */\n\nimport { BaseService } from \"../base/BaseService\";\nimport {\n Result,\n ok,\n err,\n serviceError,\n IServiceContext,\n ServiceSession,\n} from \"../types\";\nimport { wrapError } from \"../errors\";\nimport type { IKVService } from \"../kv/IKVService\";\nimport type { KVService } from \"../kv/KVService\";\nimport type {\n DecryptCapabilityProof,\n InlineEncryptedEnvelope,\n} from \"../encryption\";\nimport type { IDataVaultService } from \"./IDataVaultService\";\nimport {\n DataVaultConfig,\n VaultPutOptions,\n VaultGetOptions,\n VaultListOptions,\n VaultGrantOptions,\n VaultEntry,\n VaultError,\n VaultErrorInput,\n VaultHeaders,\n VaultVersionConfig,\n CURRENT_VAULT_VERSION,\n} from \"./types\";\nimport {\n loadCachedSignature,\n cacheSignature,\n clearSignatureCache,\n} from \"./SignatureCache\";\n\n// =============================================================================\n// Crypto Interface\n// =============================================================================\n\n/**\n * Crypto operations interface - implementations provided by WASM bindings.\n * Passed via DataVaultServiceConfig to keep the service platform-agnostic.\n */\nexport interface VaultCrypto {\n encrypt(key: Uint8Array, plaintext: Uint8Array): Uint8Array;\n decrypt(key: Uint8Array, blob: Uint8Array): Uint8Array;\n deriveKey(\n signature: Uint8Array,\n salt: Uint8Array,\n info: Uint8Array\n ): Uint8Array;\n x25519FromSeed(\n seed: Uint8Array\n ): { publicKey: Uint8Array; privateKey: Uint8Array };\n x25519Dh(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array;\n randomBytes(length: number): Uint8Array;\n sha256(data: Uint8Array): Uint8Array;\n}\n\n// =============================================================================\n// Extended Config\n// =============================================================================\n\n/**\n * Extended config used internally by DataVaultService.\n * Includes crypto operations and TinyCloud instance references.\n */\ninterface DataVaultServiceConfig extends DataVaultConfig {\n [key: string]: unknown;\n /** Crypto operations (WASM bindings) */\n crypto: VaultCrypto;\n /** TinyCloud instance for space/kv/delegation operations */\n tc: {\n kv: IKVService;\n ensurePublicSpace(): Promise<Result<void>>;\n publicKV: IKVService;\n readPublicSpace<T>(\n host: string,\n spaceId: string,\n key: string\n ): Promise<Result<T>>;\n makePublicSpaceId(address: string, chainId: number): string;\n did: string;\n address: string;\n chainId: number;\n hosts: string[];\n };\n}\n\n// =============================================================================\n// Helper Functions\n// =============================================================================\n\n/** Convert a caught value to an Error. WASM throws plain objects, not Error instances. */\nfunction toError(error: unknown): Error {\n if (error instanceof Error) return error;\n if (typeof error === \"object\" && error !== null) {\n return new Error(JSON.stringify(error));\n }\n return new Error(String(error));\n}\n\nfunction toBytes(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\nfunction fromBytes(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\nfunction hexEncode(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\nfunction concatBytes(...arrays: Uint8Array[]): Uint8Array {\n const total = arrays.reduce((acc, arr) => acc + arr.length, 0);\n const result = new Uint8Array(total);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\nfunction base64Encode(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\nfunction base64Decode(str: string): Uint8Array {\n const binary = atob(str);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nfunction unwrapKVData<T = unknown>(value: unknown): T {\n if (value !== null && typeof value === \"object\" && \"data\" in value) {\n return (value as { data: T }).data;\n }\n return value as T;\n}\n\nfunction isUnlockSigner(\n signer: unknown\n): signer is { signMessage(message: string): Promise<string> } {\n return (\n typeof signer === \"object\" &&\n signer !== null &&\n typeof (signer as { signMessage?: unknown }).signMessage === \"function\"\n );\n}\n\nfunction defaultVaultMessage(input: VaultErrorInput): string {\n switch (input.code) {\n case \"DECRYPTION_FAILED\": return input.message ?? \"Decryption failed\";\n case \"KEY_NOT_FOUND\": return input.message ?? `Key not found: ${input.key}`;\n case \"INTEGRITY_ERROR\": return input.message ?? \"Integrity check failed\";\n case \"GRANT_NOT_FOUND\": return input.message ?? `Grant not found: ${input.grantor} / ${input.key}`;\n case \"VAULT_LOCKED\": return input.message ?? \"Vault is locked\";\n case \"PUBLIC_KEY_NOT_FOUND\": return input.message ?? `Public key not found for ${input.did}`;\n case \"STORAGE_ERROR\": return input.message ?? input.cause.message;\n }\n}\n\nfunction vaultError(input: VaultErrorInput): Result<never, VaultError> {\n const error: VaultError = {\n ...input,\n service: \"vault\",\n message: defaultVaultMessage(input),\n };\n return { ok: false, error };\n}\n\n// =============================================================================\n// DataVaultService\n// =============================================================================\n\n/**\n * Data Vault service implementation.\n *\n * Provides encrypted key-value storage with client-side encryption,\n * key management, and sharing via X25519 grants.\n *\n * @example\n * ```typescript\n * // Unlock the vault\n * await vault.unlock(signer);\n *\n * // Store encrypted data\n * await vault.put('secret/notes', { content: 'Hello' });\n *\n * // Retrieve and decrypt\n * const entry = await vault.get<{ content: string }>('secret/notes');\n * if (entry.ok) {\n * console.log(entry.data.value.content); // 'Hello'\n * }\n *\n * // Share with another user\n * await vault.grant('secret/notes', recipientDID);\n * ```\n */\nexport class DataVaultService extends BaseService implements IDataVaultService {\n /**\n * Service identifier for registration.\n */\n static readonly serviceName = \"vault\";\n\n /**\n * Service configuration.\n */\n declare protected _config: DataVaultServiceConfig;\n\n private masterKey: Uint8Array | null = null;\n private encryptionIdentity: {\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n } | null = null;\n private _isUnlocked = false;\n private vaultConfig: DataVaultServiceConfig;\n private unlockInFlight: Promise<Result<void, VaultError>> | null = null;\n\n /**\n * Create a new DataVaultService instance.\n *\n * @param config - Service configuration including crypto and tc references\n */\n constructor(config: DataVaultServiceConfig) {\n super();\n this.vaultConfig = config;\n this._config = config;\n }\n\n /**\n * Get the service configuration.\n */\n get config(): DataVaultServiceConfig {\n return this._config;\n }\n\n /**\n * Whether the vault is currently unlocked.\n */\n get isUnlocked(): boolean {\n return this.usesNetworkEncryption || this._isUnlocked;\n }\n\n /**\n * The vault's public encryption key (X25519).\n * Throws if vault is locked.\n */\n get publicKey(): Uint8Array {\n if (this.usesNetworkEncryption) {\n throw new Error(\"Network-encrypted vaults do not expose a local public key\");\n }\n if (!this.encryptionIdentity) {\n throw new Error(\"Vault is locked\");\n }\n return this.encryptionIdentity.publicKey;\n }\n\n /**\n * Convenience accessor for crypto operations.\n */\n private get crypto(): VaultCrypto {\n return this.vaultConfig.crypto;\n }\n\n /**\n * Convenience accessor for TinyCloud instance.\n */\n private get tc() {\n return this.vaultConfig.tc;\n }\n\n private get networkEncryption() {\n return this.vaultConfig.encryption;\n }\n\n private get usesNetworkEncryption(): boolean {\n return this.networkEncryption !== undefined;\n }\n\n /**\n * Get the host URL.\n */\n private get host(): string {\n return this.tc.hosts[0];\n }\n\n private async decryptCapabilityProof(): Promise<DecryptCapabilityProof> {\n const proof = this.networkEncryption?.decryptCapabilityProof;\n if (typeof proof === \"function\") {\n return await proof();\n }\n return proof ?? { proofs: [] };\n }\n\n private serializeValue(\n value: unknown,\n options?: VaultPutOptions,\n ): { plaintext: Uint8Array; contentType: string } {\n let plaintext: Uint8Array;\n if (value instanceof Uint8Array) {\n plaintext = value;\n } else if (options?.serialize) {\n plaintext = options.serialize(value);\n } else if (typeof value === \"string\") {\n plaintext = toBytes(value);\n } else {\n plaintext = toBytes(JSON.stringify(value));\n }\n\n const contentType =\n options?.contentType ??\n (value instanceof Uint8Array ? \"application/octet-stream\" : \"application/json\");\n return { plaintext, contentType };\n }\n\n private deserializeValue<T>(\n plaintext: Uint8Array,\n contentType: string,\n options?: VaultGetOptions<T>,\n ): T {\n if (options?.raw) {\n return plaintext as unknown as T;\n }\n if (options?.deserialize) {\n return options.deserialize(plaintext);\n }\n if (contentType === \"application/json\") {\n return JSON.parse(fromBytes(plaintext)) as T;\n }\n return plaintext as unknown as T;\n }\n\n // =========================================================================\n // Phase 1: Core Operations\n // =========================================================================\n\n /**\n * Unlock the vault. Derives keys from two wallet signatures:\n * 1. Master signature (per-space) — used to derive the master encryption key\n * 2. Identity signature (per-address) — used to derive X25519 encryption identity\n *\n * If the identity public key already exists in the public space, the identity\n * signature is skipped entirely (no wallet popup). The identity private key is\n * only needed for sharing operations.\n *\n * @param signer - Object with signMessage method. Optional when cached\n * signatures exist (browser only).\n */\n async unlock(\n signer?: { signMessage(message: string): Promise<string> } | unknown\n ): Promise<Result<void, VaultError>> {\n if (this.usesNetworkEncryption) {\n this._isUnlocked = true;\n return { ok: true, data: undefined };\n }\n\n const unlockSigner = isUnlockSigner(signer) ? signer : undefined;\n if (\n this._isUnlocked &&\n this.masterKey &&\n (this.encryptionIdentity || !unlockSigner)\n ) {\n return { ok: true, data: undefined };\n }\n\n if (this.unlockInFlight) {\n return this.unlockInFlight;\n }\n\n this.unlockInFlight = this.withTelemetry(\"unlock\", undefined, async () => {\n const spaceId = this.vaultConfig.spaceId;\n const versionConfig = VaultVersionConfig[CURRENT_VAULT_VERSION];\n const masterCacheKey = `vault-master:${spaceId}`;\n const identityCacheKey = `vault-identity:${this.tc.address}`;\n\n try {\n // -----------------------------------------------------------------\n // Step 1: Master signature → master key\n // -----------------------------------------------------------------\n if (!this.masterKey) {\n let masterSigBytes = await loadCachedSignature(masterCacheKey);\n\n if (!masterSigBytes) {\n if (!unlockSigner) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Signer is required when no cached master signature exists\",\n });\n }\n const sig = await unlockSigner.signMessage(\n versionConfig.masterMessage(spaceId)\n );\n masterSigBytes = toBytes(sig);\n await cacheSignature(masterCacheKey, masterSigBytes);\n }\n\n // Derive master key: deriveKey(sigBytes, sha256(spaceId), \"vault-master\")\n this.masterKey = this.crypto.deriveKey(\n masterSigBytes,\n this.crypto.sha256(toBytes(spaceId)),\n toBytes(\"vault-master\")\n );\n }\n\n // -----------------------------------------------------------------\n // Step 2: Identity — check public space first, then sign if needed\n // -----------------------------------------------------------------\n const publicSpaceId = this.tc.makePublicSpaceId(this.tc.address, this.tc.chainId);\n\n // Check public space for existing vault pubkey\n let existingPubKey: string | null = null;\n try {\n const existing = await this.tc.readPublicSpace<string>(\n this.host, publicSpaceId, \".well-known/vault-pubkey\"\n );\n if (existing.ok && existing.data) {\n existingPubKey = existing.data as string;\n }\n } catch {\n // Read failed — treat as missing\n }\n\n if (existingPubKey) {\n // Public key exists — trust it, skip identity signing entirely\n this.encryptionIdentity = {\n publicKey: base64Decode(existingPubKey),\n privateKey: new Uint8Array(0), // private key not available without signing\n };\n } else {\n // Public key missing — need identity signature to derive keypair\n let identitySigBytes = await loadCachedSignature(identityCacheKey);\n\n if (!identitySigBytes) {\n if (!unlockSigner) {\n // No signer available — skip identity derivation.\n // Vault still works for get/put (only needs master key).\n this.encryptionIdentity = null;\n this._isUnlocked = true;\n return ok(undefined);\n }\n const sig = await unlockSigner.signMessage(\n versionConfig.identityMessage\n );\n identitySigBytes = toBytes(sig);\n await cacheSignature(identityCacheKey, identitySigBytes);\n }\n\n // Derive X25519 keypair from identity signature\n const seed = this.crypto.deriveKey(\n identitySigBytes,\n toBytes(\"tinycloud-x25519\"),\n toBytes(\"encryption-identity\")\n );\n this.encryptionIdentity = this.crypto.x25519FromSeed(seed);\n\n // Publish public key to public space\n try {\n const pubKeyB64 = base64Encode(this.encryptionIdentity.publicKey);\n await this.tc.ensurePublicSpace();\n await this.tc.publicKV.put(\".well-known/vault-pubkey\", pubKeyB64);\n await this.tc.publicKV.put(\".well-known/vault-version\", CURRENT_VAULT_VERSION);\n await this.tc.publicKV.put(\".well-known/vault-space\", this.vaultConfig.spaceId);\n } catch {\n // Publishing failed — vault still usable\n }\n }\n\n this._isUnlocked = true;\n return ok(undefined);\n } catch (error) {\n // Clear key material on failure\n this.masterKey = null;\n this.encryptionIdentity = null;\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<void, VaultError>>;\n\n try {\n return await this.unlockInFlight;\n } finally {\n this.unlockInFlight = null;\n }\n }\n\n /**\n * Clear the cached vault signatures.\n *\n * @param spaceId - Clear only this space's master cache. If omitted, clears all.\n */\n async clearCache(spaceId?: string): Promise<void> {\n if (spaceId) {\n await clearSignatureCache(`vault-master:${spaceId}`);\n } else {\n await clearSignatureCache();\n }\n }\n\n /**\n * Lock the vault, clearing all key material from memory.\n */\n lock(): void {\n this.masterKey = null;\n this.encryptionIdentity = null;\n this._isUnlocked = false;\n }\n\n /**\n * Called when SDK signs out. Locks the vault and aborts operations.\n */\n onSignOut(): void {\n this.lock();\n super.onSignOut();\n }\n\n private async putNetworkEncrypted(\n key: string,\n value: unknown,\n options?: VaultPutOptions,\n ): Promise<Result<void, VaultError>> {\n const config = this.networkEncryption;\n if (!config) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Network encryption is not configured\",\n });\n }\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n const { plaintext, contentType } = this.serializeValue(value, options);\n const metadata: Record<string, string> = {\n [VaultHeaders.VERSION]: \"2\",\n [VaultHeaders.CIPHER]: \"tinycloud-network-envelope\",\n [VaultHeaders.CONTENT_TYPE]: contentType,\n ...(options?.metadata ?? {}),\n };\n const aad = toBytes(`tinycloud.vault:${this.vaultConfig.spaceId}:${key}`);\n const envelopeResult = await config.service.encryptToNetwork(\n config.networkId,\n plaintext,\n { aad, metadata },\n );\n if (!envelopeResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(envelopeResult.error.message),\n });\n }\n\n const valuePutResult = await this.tc.kv.put(\n `vault/${key}`,\n JSON.stringify(envelopeResult.data),\n );\n if (!valuePutResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to store encrypted value: ${valuePutResult.error.message}`,\n ),\n });\n }\n\n return { ok: true, data: undefined };\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: toError(error),\n });\n }\n }\n\n private async getNetworkEncrypted<T = unknown>(\n key: string,\n options?: VaultGetOptions<T>,\n ): Promise<Result<VaultEntry<T>, VaultError>> {\n const config = this.networkEncryption;\n if (!config) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Network encryption is not configured\",\n });\n }\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n const valueResult = await this.tc.kv.get<string>(`vault/${key}`, {\n raw: true,\n });\n if (!valueResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n\n const rawEnvelope = unwrapKVData<string>(valueResult.data);\n const envelope = (\n typeof rawEnvelope === \"string\" ? JSON.parse(rawEnvelope) : rawEnvelope\n ) as InlineEncryptedEnvelope;\n const proof = await this.decryptCapabilityProof();\n const plaintextResult = await config.service.decryptEnvelope(envelope, proof);\n if (!plaintextResult.ok) {\n return vaultError({\n code: \"DECRYPTION_FAILED\",\n message: plaintextResult.error.message,\n });\n }\n\n const metadata: Record<string, string> = envelope.metadata ?? {};\n const contentType =\n metadata[VaultHeaders.CONTENT_TYPE] ?? \"application/json\";\n const keyId =\n metadata[VaultHeaders.KEY_ID] ??\n envelope.encryptedSymmetricKeyHash.slice(0, 16);\n const value = this.deserializeValue<T>(\n plaintextResult.data,\n contentType,\n options,\n );\n\n return { ok: true, data: { value, metadata, keyId } };\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: toError(error),\n });\n }\n }\n\n private async headNetworkEncrypted(\n key: string,\n ): Promise<Result<Record<string, string>, VaultError>> {\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n const valueResult = await this.tc.kv.get<string>(`vault/${key}`, {\n raw: true,\n });\n if (!valueResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n const rawEnvelope = unwrapKVData<string>(valueResult.data);\n const envelope = (\n typeof rawEnvelope === \"string\" ? JSON.parse(rawEnvelope) : rawEnvelope\n ) as InlineEncryptedEnvelope;\n return { ok: true, data: envelope.metadata ?? {} };\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: toError(error),\n });\n }\n }\n\n /**\n * Encrypt and store a value at the given key.\n *\n * @param key - The key to store under\n * @param value - The value to encrypt and store\n * @param options - Optional put configuration\n */\n async put(\n key: string,\n value: unknown,\n options?: VaultPutOptions\n ): Promise<Result<void, VaultError>> {\n return this.withTelemetry(\"put\", key, async () => {\n if (this.usesNetworkEncryption) {\n return this.putNetworkEncrypted(key, value, options);\n }\n\n if (!this._isUnlocked || !this.masterKey) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before storing data\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n // Serialize value\n let plaintext: Uint8Array;\n if (value instanceof Uint8Array) {\n plaintext = value;\n } else if (options?.serialize) {\n plaintext = options.serialize(value);\n } else if (typeof value === \"string\") {\n plaintext = toBytes(value);\n } else {\n plaintext = toBytes(JSON.stringify(value));\n }\n\n const contentType =\n options?.contentType ??\n (value instanceof Uint8Array\n ? \"application/octet-stream\"\n : \"application/json\");\n\n // Generate per-entry key\n const entryKey = this.crypto.randomBytes(32);\n const keyId = hexEncode(this.crypto.sha256(entryKey)).slice(0, 16);\n\n // Encrypt value with entry key\n const encrypted = this.crypto.encrypt(entryKey, plaintext);\n\n // Encrypt entry key with master key\n const keyBlob = this.crypto.encrypt(this.masterKey, entryKey);\n\n // Build metadata\n const metadata: Record<string, string> = {\n [VaultHeaders.VERSION]: \"1\",\n [VaultHeaders.CIPHER]: \"aes-256-gcm\",\n [VaultHeaders.KEY_ID]: keyId,\n [VaultHeaders.CONTENT_TYPE]: contentType,\n [VaultHeaders.KDF]: \"hkdf-sha256\",\n [VaultHeaders.KEY_ROTATION]:\n this.vaultConfig.keyRotation ?? \"per-write\",\n ...(options?.metadata ?? {}),\n };\n\n // Store encrypted entry key in key space\n const keyMetadata = JSON.stringify({\n keyId,\n contentType,\n ...metadata,\n });\n const keyPayload = JSON.stringify({\n key: base64Encode(keyBlob),\n metadata: keyMetadata,\n });\n const keyPutResult = await this.tc.kv.put(\n `keys/${key}`,\n keyPayload\n );\n if (!keyPutResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to store key blob: ${keyPutResult.error.message}`\n ),\n });\n }\n\n // Store encrypted value in data space\n const valuePayload = JSON.stringify({\n data: base64Encode(encrypted),\n metadata,\n });\n const valuePutResult = await this.tc.kv.put(\n `vault/${key}`,\n valuePayload\n );\n if (!valuePutResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to store encrypted value: ${valuePutResult.error.message}`\n ),\n });\n }\n\n return ok(undefined);\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<void, VaultError>>;\n }\n\n /**\n * Retrieve and decrypt a value by key.\n *\n * @param key - The key to retrieve\n * @param options - Optional get configuration\n * @returns Result with the decrypted entry\n */\n async get<T = unknown>(\n key: string,\n options?: VaultGetOptions<T>\n ): Promise<Result<VaultEntry<T>, VaultError>> {\n return this.withTelemetry(\"get\", key, async () => {\n if (this.usesNetworkEncryption) {\n return this.getNetworkEncrypted<T>(key, options);\n }\n\n if (!this._isUnlocked || !this.masterKey) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before reading data\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n // Fetch encrypted entry key from key space\n const keyResult = await this.tc.kv.get<string>(`keys/${key}`, {\n raw: true,\n });\n if (!keyResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n\n const keyEnvelope = JSON.parse(keyResult.data.data as string);\n const keyBlobBytes = base64Decode(keyEnvelope.key);\n const entryKey = this.crypto.decrypt(this.masterKey, keyBlobBytes);\n\n // Fetch encrypted value from data space\n const valueResult = await this.tc.kv.get<string>(`vault/${key}`, {\n raw: true,\n });\n if (!valueResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n\n const valueEnvelope = JSON.parse(valueResult.data.data as string);\n const encryptedBytes = base64Decode(valueEnvelope.data);\n const plaintext = this.crypto.decrypt(entryKey, encryptedBytes);\n\n // Read metadata\n const metadata: Record<string, string> = valueEnvelope.metadata ?? {};\n const contentType =\n metadata[VaultHeaders.CONTENT_TYPE] ?? \"application/json\";\n const keyId = metadata[VaultHeaders.KEY_ID] ?? \"\";\n\n // Deserialize\n let value: T;\n if (options?.raw) {\n value = plaintext as unknown as T;\n } else if (options?.deserialize) {\n value = options.deserialize(plaintext);\n } else if (contentType === \"application/json\") {\n value = JSON.parse(fromBytes(plaintext)) as T;\n } else {\n value = plaintext as unknown as T;\n }\n\n return ok({ value, metadata, keyId });\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"decryption\")\n ) {\n return vaultError({\n code: \"DECRYPTION_FAILED\",\n message: error.message,\n });\n }\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<VaultEntry<T>, VaultError>>;\n }\n\n /**\n * Delete an encrypted key.\n * Removes both the encrypted value and the key blob.\n *\n * @param key - The key to delete\n */\n async delete(key: string): Promise<Result<void, VaultError>> {\n return this.withTelemetry(\"delete\", key, async () => {\n if (!this.isUnlocked) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before deleting data\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n if (this.usesNetworkEncryption) {\n const valueDelResult = await this.tc.kv.delete(`vault/${key}`);\n if (!valueDelResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n return ok(undefined);\n }\n\n // Delete from both key space and data space\n const [keyDelResult, valueDelResult] = await Promise.all([\n this.tc.kv.delete(`keys/${key}`),\n this.tc.kv.delete(`vault/${key}`),\n ]);\n\n if (!keyDelResult.ok && !valueDelResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n\n return ok(undefined);\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<void, VaultError>>;\n }\n\n /**\n * List vault keys with optional prefix filtering.\n *\n * @param options - Optional list configuration\n * @returns Result with array of key names (vault/ prefix stripped)\n */\n async list(\n options?: VaultListOptions\n ): Promise<Result<string[], VaultError>> {\n return this.withTelemetry(\"list\", options?.prefix, async () => {\n if (!this.isUnlocked) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before listing data\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n const listPrefix = options?.prefix\n ? `vault/${options.prefix}`\n : \"vault/\";\n\n const listResult = await this.tc.kv.list({\n prefix: listPrefix,\n removePrefix: true,\n });\n\n if (!listResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to list vault keys: ${listResult.error.message}`\n ),\n });\n }\n\n // Keys are already stripped of the \"vault/\" prefix by removePrefix\n let keys = listResult.data.keys;\n\n // If a user prefix was provided, strip it too if requested\n if (options?.removePrefix && options.prefix) {\n const userPrefix = options.prefix.endsWith(\"/\")\n ? options.prefix\n : `${options.prefix}/`;\n keys = keys.map((k) =>\n k.startsWith(userPrefix) ? k.slice(userPrefix.length) : k\n );\n }\n\n return ok(keys);\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<string[], VaultError>>;\n }\n\n /**\n * Get envelope metadata for a key without decrypting the value.\n *\n * @param key - The key to inspect\n * @returns Result with metadata headers\n */\n async head(\n key: string\n ): Promise<Result<Record<string, string>, VaultError>> {\n return this.withTelemetry(\"head\", key, async () => {\n if (this.usesNetworkEncryption) {\n return this.headNetworkEncrypted(key);\n }\n\n if (!this._isUnlocked) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before reading metadata\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n // Fetch envelope without decrypting\n const valueResult = await this.tc.kv.get<string>(`vault/${key}`, {\n raw: true,\n });\n if (!valueResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n\n const valueEnvelope = JSON.parse(valueResult.data.data as string);\n const metadata: Record<string, string> = valueEnvelope.metadata ?? {};\n return ok(metadata);\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<Record<string, string>, VaultError>>;\n }\n\n // =========================================================================\n // Batch Operations\n // =========================================================================\n\n /**\n * Encrypt and store multiple entries.\n *\n * @param entries - Array of key/value pairs with optional per-entry options\n * @returns Array of results, one per entry\n */\n async putMany(\n entries: Array<{ key: string; value: unknown; options?: VaultPutOptions }>\n ): Promise<Result<void, VaultError>[]> {\n return Promise.all(\n entries.map((entry) => this.put(entry.key, entry.value, entry.options))\n );\n }\n\n /**\n * Retrieve and decrypt multiple keys.\n *\n * @param keys - Array of keys to retrieve\n * @param options - Optional get configuration applied to all entries\n * @returns Array of results, one per key\n */\n async getMany<T = unknown>(\n keys: string[],\n options?: VaultGetOptions<T>\n ): Promise<Result<VaultEntry<T>, VaultError>[]> {\n return Promise.all(keys.map((key) => this.get<T>(key, options)));\n }\n\n // =========================================================================\n // Phase 2: Sharing\n // =========================================================================\n\n /**\n * Re-encrypt a vault key for another user (renamed from grant).\n * Re-encrypts the data key to the recipient's public key via X25519 DH.\n *\n * @param key - The key to share\n * @param recipientDID - The recipient's primary DID (did:pkh:...)\n * @param options - Optional grant configuration\n */\n async reencrypt(\n key: string,\n recipientDID: string,\n options?: VaultGrantOptions\n ): Promise<Result<void, VaultError>> {\n return this.withTelemetry(\"reencrypt\", key, async () => {\n if (this.usesNetworkEncryption) {\n void recipientDID;\n void options;\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n \"Vault key grants are deprecated for network-encrypted vaults; grant tinycloud.encryption/decrypt on the network plus KV access to vault data.\",\n ),\n });\n }\n\n if (!this._isUnlocked || !this.masterKey) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before granting access\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n // Step 1: Resolve recipient's public key\n const pubKeyResult = await this.resolvePublicKey(recipientDID);\n if (!pubKeyResult.ok) {\n return pubKeyResult;\n }\n const bobPubKey = pubKeyResult.data;\n\n // Step 2: Fetch and decrypt entry key from key space\n const keyResult = await this.tc.kv.get<string>(`keys/${key}`, {\n raw: true,\n });\n if (!keyResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n\n const keyEnvelope = JSON.parse(keyResult.data.data as string);\n const keyBlobBytes = base64Decode(keyEnvelope.key);\n const entryKey = this.crypto.decrypt(this.masterKey, keyBlobBytes);\n\n // Step 3: Create ephemeral X25519 key pair\n const ephemeralSeed = this.crypto.randomBytes(32);\n const ephemeralKeyPair = this.crypto.x25519FromSeed(ephemeralSeed);\n\n // Step 4: Compute shared secret via DH\n const sharedSecret = this.crypto.x25519Dh(\n ephemeralKeyPair.privateKey,\n bobPubKey\n );\n\n // Step 5: Derive encryption key from shared secret\n const encryptionKey = this.crypto.deriveKey(\n sharedSecret,\n toBytes(\"tinycloud-x25519\"),\n toBytes(\"vault-grant\")\n );\n\n // Step 6: Encrypt entry key with derived key\n const encryptedGrant = this.crypto.encrypt(encryptionKey, entryKey);\n\n // Step 7: Concatenate ephemeral public key + encrypted grant\n const grantBlob = concatBytes(\n ephemeralKeyPair.publicKey,\n encryptedGrant\n );\n\n // Step 8: Store grant in key space\n const grantPayload = JSON.stringify({\n grant: base64Encode(grantBlob),\n spaceId: this.vaultConfig.spaceId,\n metadata: {\n [VaultHeaders.GRANT_VERSION]: \"1\",\n [VaultHeaders.GRANTOR]: this.tc.did,\n ...(options?.metadata ?? {}),\n },\n });\n // Store grant in the vault's space (main space)\n const grantPutResult = await this.tc.kv.put(\n `grants/${recipientDID}/${key}`,\n grantPayload\n );\n if (!grantPutResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to store grant: ${grantPutResult.error.message}`\n ),\n });\n }\n\n return ok(undefined);\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<void, VaultError>>;\n }\n\n /**\n * @deprecated Use reencrypt() instead.\n */\n async grant(\n key: string,\n recipientDID: string,\n options?: VaultGrantOptions\n ): Promise<Result<void, VaultError>> {\n return this.reencrypt(key, recipientDID, options);\n }\n\n /**\n * Retrieve and decrypt a value shared by another user.\n *\n * @param grantorDID - The DID of the user who shared the data\n * @param key - The key that was shared\n * @param options - Optional get configuration\n * @returns Result with the decrypted entry\n */\n async getShared<T = unknown>(\n grantorDID: string,\n key: string,\n options?: VaultGetOptions<T>\n ): Promise<Result<VaultEntry<T>, VaultError>> {\n return this.withTelemetry(\"getShared\", key, async () => {\n if (this.usesNetworkEncryption) {\n const grantorKV = options?.kv;\n if (!grantorKV) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n \"getShared requires a delegated KV service via options.kv.\",\n ),\n });\n }\n\n const config = this.networkEncryption;\n if (!config) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Network encryption is not configured\",\n });\n }\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n const valueResult = await grantorKV.get<string>(`vault/${key}`, {\n raw: true,\n });\n if (!valueResult.ok) {\n return vaultError({ code: \"KEY_NOT_FOUND\", key });\n }\n const rawEnvelope = unwrapKVData<string>(valueResult.data);\n const envelope = (\n typeof rawEnvelope === \"string\" ? JSON.parse(rawEnvelope) : rawEnvelope\n ) as InlineEncryptedEnvelope;\n const proof = await this.decryptCapabilityProof();\n const plaintextResult = await config.service.decryptEnvelope(\n envelope,\n proof,\n );\n if (!plaintextResult.ok) {\n return vaultError({\n code: \"DECRYPTION_FAILED\",\n message: plaintextResult.error.message,\n });\n }\n\n const metadata: Record<string, string> = envelope.metadata ?? {};\n const contentType =\n metadata[VaultHeaders.CONTENT_TYPE] ?? \"application/json\";\n const keyId =\n metadata[VaultHeaders.KEY_ID] ??\n envelope.encryptedSymmetricKeyHash.slice(0, 16);\n const value = this.deserializeValue<T>(\n plaintextResult.data,\n contentType,\n options,\n );\n void grantorDID;\n return { ok: true, data: { value, metadata, keyId } };\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: toError(error),\n });\n }\n }\n\n if (\n !this._isUnlocked ||\n !this.masterKey ||\n !this.encryptionIdentity\n ) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before reading shared data\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n const myDID = this.tc.did;\n const grantorKV = options?.kv;\n\n if (!grantorKV) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n \"getShared requires a delegated KV service via options.kv. \" +\n \"Use useDelegation() to get delegated access, then pass { kv: access.kv }.\"\n ),\n });\n }\n\n // Step 1: Fetch grant from grantor's space via delegated KV\n const grantResult = await grantorKV.get<string>(`grants/${myDID}/${key}`, {\n raw: true,\n });\n if (!grantResult.ok) {\n return vaultError({\n code: \"GRANT_NOT_FOUND\",\n grantor: grantorDID,\n key,\n });\n }\n\n const grantEnvelope = typeof grantResult.data?.data === \"string\"\n ? JSON.parse(grantResult.data.data as string)\n : grantResult.data?.data;\n const grantBlobBytes = base64Decode((grantEnvelope as any).grant);\n\n // Step 2: Extract ephemeral public key and encrypted grant\n const ephemeralPubKey = grantBlobBytes.slice(0, 32);\n const encryptedGrant = grantBlobBytes.slice(32);\n\n // Step 3: Compute shared secret using our private key\n const sharedSecret = this.crypto.x25519Dh(\n this.encryptionIdentity.privateKey,\n ephemeralPubKey\n );\n\n // Step 4: Derive decryption key\n const encryptionKey = this.crypto.deriveKey(\n sharedSecret,\n toBytes(\"tinycloud-x25519\"),\n toBytes(\"vault-grant\")\n );\n\n // Step 5: Decrypt entry key\n const entryKey = this.crypto.decrypt(encryptionKey, encryptedGrant);\n\n // Step 6: Fetch encrypted value from grantor's space via delegated KV\n const valueResult = await grantorKV.get<string>(`vault/${key}`, {\n raw: true,\n });\n if (!valueResult.ok) {\n return vaultError({\n code: \"KEY_NOT_FOUND\",\n key,\n });\n }\n\n const valueEnvelope = typeof valueResult.data?.data === \"string\"\n ? JSON.parse(valueResult.data.data as string)\n : valueResult.data?.data;\n const encryptedBytes = base64Decode((valueEnvelope as any).data);\n const plaintext = this.crypto.decrypt(entryKey, encryptedBytes);\n\n // Read metadata\n const metadata: Record<string, string> = (valueEnvelope as any).metadata ?? {};\n const contentType =\n metadata[VaultHeaders.CONTENT_TYPE] ?? \"application/json\";\n const keyId = metadata[VaultHeaders.KEY_ID] ?? \"\";\n\n // Deserialize\n let value: T;\n if (options?.raw) {\n value = plaintext as unknown as T;\n } else if (options?.deserialize) {\n value = options.deserialize(plaintext);\n } else if (contentType === \"application/json\") {\n value = JSON.parse(fromBytes(plaintext)) as T;\n } else {\n value = plaintext as unknown as T;\n }\n\n return ok({ value, metadata, keyId });\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"decryption\")\n ) {\n return vaultError({\n code: \"DECRYPTION_FAILED\",\n message: error.message,\n });\n }\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<VaultEntry<T>, VaultError>>;\n }\n\n /**\n * Resolve another user's public encryption key from their DID.\n *\n * @param did - The DID to resolve (did:pkh:eip155:{chainId}:{address})\n * @returns Result with the public key bytes\n */\n async resolvePublicKey(\n did: string\n ): Promise<Result<Uint8Array, VaultError>> {\n try {\n const parts = this.parseDID(did);\n if (!parts) {\n return vaultError({ code: \"PUBLIC_KEY_NOT_FOUND\", did });\n }\n\n const spaceId = this.tc.makePublicSpaceId(\n parts.address,\n parts.chainId\n );\n\n const result = await this.tc.readPublicSpace<string>(\n this.host,\n spaceId,\n \".well-known/vault-pubkey\"\n );\n\n if (!result.ok) {\n return vaultError({ code: \"PUBLIC_KEY_NOT_FOUND\", did });\n }\n\n const pubKeyBytes = base64Decode(result.data as string);\n return { ok: true, data: pubKeyBytes } as Result<Uint8Array, VaultError>;\n } catch (error) {\n return vaultError({ code: \"PUBLIC_KEY_NOT_FOUND\", did });\n }\n }\n\n /**\n * List DIDs that have been granted access to a key.\n *\n * @param key - The key to list grants for\n * @returns Result with array of recipient DIDs\n */\n async listGrants(\n key: string\n ): Promise<Result<string[], VaultError>> {\n return this.withTelemetry(\"listGrants\", key, async () => {\n if (this.usesNetworkEncryption) {\n void key;\n return { ok: true, data: [] };\n }\n\n if (!this._isUnlocked) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before listing grants\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n const listResult = await this.tc.kv.list({\n prefix: \"grants/\",\n removePrefix: true,\n });\n\n if (!listResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to list grants: ${listResult.error.message}`\n ),\n });\n }\n\n // Grant paths are: {recipientDID}/{key}\n // Filter for the specific key and extract DIDs\n const dids: string[] = [];\n for (const grantPath of listResult.data.keys) {\n // Path format: {recipientDID}/{key}\n // The key may contain slashes, so we need to match the suffix\n if (grantPath.endsWith(`/${key}`)) {\n const did = grantPath.slice(\n 0,\n grantPath.length - key.length - 1\n );\n if (did) {\n dids.push(did);\n }\n }\n }\n\n return ok(dids);\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<string[], VaultError>>;\n }\n\n // =========================================================================\n // Phase 3: Key Rotation / Revocation\n // =========================================================================\n\n /**\n * Revoke a previously issued grant.\n *\n * This performs a full key rotation:\n * 1. Lists current grantees\n * 2. Removes the revoked recipient\n * 3. Re-encrypts the value with a new entry key\n * 4. Re-issues grants to remaining recipients\n *\n * @param key - The key to revoke access to\n * @param recipientDID - The recipient whose access to revoke\n */\n async revoke(\n key: string,\n recipientDID: string\n ): Promise<Result<void, VaultError>> {\n return this.withTelemetry(\"revoke\", key, async () => {\n if (this.usesNetworkEncryption) {\n void recipientDID;\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n \"Vault key grants are deprecated for network-encrypted vaults; revoke KV and tinycloud.encryption/decrypt grants instead.\",\n ),\n });\n }\n\n if (!this._isUnlocked || !this.masterKey) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Vault must be unlocked before revoking access\",\n });\n }\n\n if (!this.requireAuth()) {\n return vaultError({\n code: \"VAULT_LOCKED\",\n message: \"Authentication required\",\n });\n }\n\n try {\n // Step 1: List all current grantees\n const granteesResult = await this.listGrants(key);\n if (!granteesResult.ok) {\n return granteesResult;\n }\n\n const remainingGrantees = granteesResult.data.filter(\n (did) => did !== recipientDID\n );\n\n // Step 2: Delete the grant for the revoked recipient\n const deleteGrantResult = await this.tc.kv.delete(\n `grants/${recipientDID}/${key}`\n );\n // Grant may already be deleted, that's fine\n\n // Step 3: Fetch and decrypt current value\n const getResult = await this.get(key);\n if (!getResult.ok) {\n return getResult as Result<never, VaultError>;\n }\n\n const currentEntry = getResult.data;\n\n // Step 4: Generate new entry key\n const newEntryKey = this.crypto.randomBytes(32);\n const newKeyId = hexEncode(this.crypto.sha256(newEntryKey)).slice(\n 0,\n 16\n );\n\n // Step 5: Re-serialize and re-encrypt value with new key\n let plaintext: Uint8Array;\n if (currentEntry.value instanceof Uint8Array) {\n plaintext = currentEntry.value;\n } else {\n plaintext = toBytes(JSON.stringify(currentEntry.value));\n }\n\n const encrypted = this.crypto.encrypt(newEntryKey, plaintext);\n\n // Step 6: Encrypt new entry key with master key\n const newKeyBlob = this.crypto.encrypt(this.masterKey, newEntryKey);\n\n // Step 7: Update metadata with new key ID\n const metadata: Record<string, string> = {\n ...currentEntry.metadata,\n [VaultHeaders.KEY_ID]: newKeyId,\n };\n\n // Step 8: Store updated key blob\n const keyPayload = JSON.stringify({\n key: base64Encode(newKeyBlob),\n metadata: JSON.stringify({\n keyId: newKeyId,\n ...metadata,\n }),\n });\n const keyPutResult = await this.tc.kv.put(\n `keys/${key}`,\n keyPayload\n );\n if (!keyPutResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to store rotated key blob: ${keyPutResult.error.message}`\n ),\n });\n }\n\n // Step 9: Store re-encrypted value\n const valuePayload = JSON.stringify({\n data: base64Encode(encrypted),\n metadata,\n });\n const valuePutResult = await this.tc.kv.put(\n `vault/${key}`,\n valuePayload\n );\n if (!valuePutResult.ok) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause: new Error(\n `Failed to store re-encrypted value: ${valuePutResult.error.message}`\n ),\n });\n }\n\n // Step 10: Re-issue grants to remaining recipients\n for (const did of remainingGrantees) {\n const grantResult = await this.reencrypt(key, did);\n if (!grantResult.ok) {\n // Continue re-issuing to other recipients even if one fails\n // The failed grant can be re-issued manually\n }\n }\n\n return ok(undefined);\n } catch (error) {\n return vaultError({\n code: \"STORAGE_ERROR\",\n cause:\n toError(error),\n });\n }\n }) as Promise<Result<void, VaultError>>;\n }\n\n // =========================================================================\n // Internal Helpers\n // =========================================================================\n\n /**\n * Parse a DID string to extract address and chainId.\n * Expected format: did:pkh:eip155:{chainId}:{address}\n *\n * @param did - The DID to parse\n * @returns Parsed address and chainId, or null if invalid\n */\n private parseDID(\n did: string\n ): { address: string; chainId: number } | null {\n // did:pkh:eip155:{chainId}:{address}\n const parts = did.split(\":\");\n if (\n parts.length !== 5 ||\n parts[0] !== \"did\" ||\n parts[1] !== \"pkh\" ||\n parts[2] !== \"eip155\"\n ) {\n return null;\n }\n\n const chainId = parseInt(parts[3], 10);\n const address = parts[4];\n if (isNaN(chainId) || !address) {\n return null;\n }\n\n return { address, chainId };\n }\n}\n","import type { VaultCrypto } from \"./DataVaultService\";\n\nexport interface WasmVaultFunctions {\n vault_encrypt(key: Uint8Array, plaintext: Uint8Array): Uint8Array;\n vault_decrypt(key: Uint8Array, blob: Uint8Array): Uint8Array;\n /** WASM order: (salt, signature, info) — NOT (signature, salt, info) */\n vault_derive_key(salt: Uint8Array, signature: Uint8Array, info: Uint8Array): Uint8Array;\n vault_x25519_from_seed(seed: Uint8Array): { publicKey: Uint8Array; privateKey: Uint8Array };\n vault_x25519_dh(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array;\n vault_random_bytes(length: number): Uint8Array;\n vault_sha256(data: Uint8Array): Uint8Array;\n}\n\nexport function createVaultCrypto(wasm: WasmVaultFunctions): VaultCrypto {\n return {\n encrypt: (key, plaintext) => wasm.vault_encrypt(key, plaintext),\n decrypt: (key, blob) => wasm.vault_decrypt(key, blob),\n deriveKey: (signature, salt, info) => wasm.vault_derive_key(salt, signature, info),\n x25519FromSeed: (seed) => wasm.vault_x25519_from_seed(seed),\n x25519Dh: (privateKey, publicKey) => wasm.vault_x25519_dh(privateKey, publicKey),\n randomBytes: (length) => wasm.vault_random_bytes(length),\n sha256: (data) => wasm.vault_sha256(data),\n };\n}\n","export const SECRET_NAME_RE = /^[A-Z][A-Z0-9_]*$/;\n\nconst SECRET_PREFIX = \"secrets/\";\nconst SCOPED_SECRET_PREFIX = \"secrets/scoped/\";\nconst RESERVED_SECRET_SCOPES = new Set([\"default\", \"global\"]);\n\nexport interface SecretScopeOptions {\n /** Optional logical scope. Omit for the global secret namespace. */\n scope?: string;\n}\n\nexport interface ResolvedSecretPath {\n /** Canonical env-style secret name. */\n name: string;\n /** Canonical scope. Undefined means global. */\n scope?: string;\n /** Key passed to the data vault service. */\n vaultKey: string;\n /** KV permission path that backs the encrypted vault entry. */\n permissionPaths: {\n vault: string;\n };\n}\n\nexport function canonicalizeSecretScope(scope: string | undefined): string | undefined {\n if (scope === undefined) {\n return undefined;\n }\n\n const trimmed = scope.trim();\n if (trimmed === \"\") {\n throw new Error(\"Secret scope must be non-empty; omit scope for global secrets.\");\n }\n\n const canonical = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n\n if (canonical === \"\") {\n throw new Error(\"Secret scope must contain at least one letter or number.\");\n }\n if (RESERVED_SECRET_SCOPES.has(canonical)) {\n throw new Error(\n `Secret scope ${JSON.stringify(scope)} is reserved; omit scope for global secrets.`,\n );\n }\n\n return canonical;\n}\n\nexport function resolveSecretPath(\n name: string,\n options: SecretScopeOptions = {},\n): ResolvedSecretPath {\n const normalizedName = name.trim();\n if (!SECRET_NAME_RE.test(normalizedName)) {\n throw new Error(\n `Invalid secret name ${JSON.stringify(name)}. Secret names must match ${SECRET_NAME_RE.source}.`,\n );\n }\n\n const scope = canonicalizeSecretScope(options.scope);\n const vaultKey = scope === undefined\n ? `${SECRET_PREFIX}${normalizedName}`\n : `${SCOPED_SECRET_PREFIX}${scope}/${normalizedName}`;\n\n return {\n name: normalizedName,\n ...(scope !== undefined ? { scope } : {}),\n vaultKey,\n permissionPaths: {\n vault: `vault/${vaultKey}`,\n },\n };\n}\n\nexport function resolveSecretListPrefix(\n options: SecretScopeOptions = {},\n): string {\n const scope = canonicalizeSecretScope(options.scope);\n return scope === undefined\n ? \"vault/secrets/\"\n : `vault/secrets/scoped/${scope}/`;\n}\n","import {\n ErrorCodes,\n err,\n type Result,\n type ServiceError,\n} from \"../types\";\nimport type { IDataVaultService } from \"../vault/IDataVaultService\";\nimport type { VaultError } from \"../vault/types\";\nimport type {\n ISecretsService,\n SecretPayload,\n SecretsError,\n} from \"./ISecretsService\";\nimport {\n canonicalizeSecretScope,\n resolveSecretPath,\n SECRET_NAME_RE,\n type ResolvedSecretPath,\n type SecretScopeOptions,\n} from \"./paths\";\n\nfunction invalidSecretInput(message: string): Result<never, ServiceError> {\n return err({\n code: ErrorCodes.INVALID_INPUT,\n service: \"secrets\",\n message,\n });\n}\n\nfunction resolveSecretPathResult(\n name: string,\n options?: SecretScopeOptions,\n): ResolvedSecretPath | Result<never, ServiceError> {\n try {\n return resolveSecretPath(name, options);\n } catch (error) {\n return invalidSecretInput(error instanceof Error ? error.message : String(error));\n }\n}\n\nexport class SecretsService implements ISecretsService {\n private readonly getVault: () => IDataVaultService;\n\n constructor(vault: IDataVaultService | (() => IDataVaultService)) {\n this.getVault = typeof vault === \"function\" ? vault : () => vault;\n }\n\n get vault(): IDataVaultService {\n return this.getVault();\n }\n\n get isUnlocked(): boolean {\n return this.vault.isUnlocked;\n }\n\n unlock(signer?: unknown): Promise<Result<void, VaultError>> {\n return this.vault.unlock(signer);\n }\n\n lock(): void {\n this.vault.lock();\n }\n\n async get(\n name: string,\n options?: SecretScopeOptions,\n ): Promise<Result<string, SecretsError>> {\n const secretPath = resolveSecretPathResult(name, options);\n if (\"ok\" in secretPath) return secretPath;\n\n const result = await this.vault.get<SecretPayload>(secretPath.vaultKey);\n if (!result.ok) {\n return result;\n }\n return { ok: true, data: result.data.value.value };\n }\n\n async put(\n name: string,\n value: string,\n options?: SecretScopeOptions,\n ): Promise<Result<void, SecretsError>> {\n const secretPath = resolveSecretPathResult(name, options);\n if (\"ok\" in secretPath) return secretPath;\n\n const now = new Date().toISOString();\n return this.vault.put(secretPath.vaultKey, {\n value,\n createdAt: now,\n updatedAt: now,\n } satisfies SecretPayload);\n }\n\n async delete(\n name: string,\n options?: SecretScopeOptions,\n ): Promise<Result<void, SecretsError>> {\n const secretPath = resolveSecretPathResult(name, options);\n if (\"ok\" in secretPath) return secretPath;\n\n return this.vault.delete(secretPath.vaultKey);\n }\n\n async list(options?: SecretScopeOptions): Promise<Result<string[], SecretsError>> {\n let prefix: string;\n try {\n const scope = canonicalizeSecretScope(options?.scope);\n prefix = scope === undefined ? \"secrets/\" : `secrets/scoped/${scope}/`;\n } catch (error) {\n return invalidSecretInput(error instanceof Error ? error.message : String(error));\n }\n\n const result = await this.vault.list({\n prefix,\n removePrefix: true,\n });\n if (!result.ok) {\n return result;\n }\n return {\n ok: true,\n data: result.data.filter((name) => SECRET_NAME_RE.test(name)),\n };\n }\n}\n","/**\n * Canonical JSON serialization and content hashing for TinyCloud\n * encryption requests/responses.\n *\n * The node and SDK must agree byte-for-byte on the canonical form so\n * that body-hash bindings (`bodyHash`, `encryptedSymmetricKeyHash`,\n * `receiverPublicKeyHash`) verify on both sides.\n *\n * Canonical rules:\n * - Object keys are sorted lexicographically by code point.\n * - Strings are encoded with the JSON.stringify default (RFC 8259).\n * - Numbers are emitted via JSON.stringify; callers should restrict to\n * integers or use string fields for high-precision values.\n * - `undefined` properties are dropped. `null` is preserved.\n * - Arrays preserve element order.\n *\n * Hashing uses SHA-256 supplied by the caller (via an `EncryptionCrypto`\n * binding) so this module stays platform-agnostic.\n */\n\nexport type Json =\n | null\n | boolean\n | number\n | string\n | Json[]\n | { [key: string]: Json | undefined };\n\n/**\n * Produce the canonical JSON string for {@link value}. Object keys are\n * sorted, `undefined` properties are dropped, and primitive types are\n * encoded by `JSON.stringify`.\n */\nexport function canonicalize(value: Json | undefined): string {\n if (value === undefined) {\n return \"\";\n }\n return stringify(value);\n}\n\nfunction stringify(value: Json): string {\n if (value === null) return \"null\";\n switch (typeof value) {\n case \"boolean\":\n case \"number\":\n return JSON.stringify(value);\n case \"string\":\n return JSON.stringify(value);\n case \"object\": {\n if (Array.isArray(value)) {\n return `[${value.map(stringify).join(\",\")}]`;\n }\n const keys = Object.keys(value).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const v = value[k];\n if (v === undefined) continue;\n parts.push(`${JSON.stringify(k)}:${stringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n default:\n throw new TypeError(\n `canonicalize: unsupported value type ${typeof value}`,\n );\n }\n}\n\nconst HEX = \"0123456789abcdef\";\n\nexport function hexEncode(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) {\n const b = bytes[i];\n out += HEX[(b >> 4) & 0xf] + HEX[b & 0xf];\n }\n return out;\n}\n\nexport function hexDecode(hex: string): Uint8Array {\n if (hex.length % 2 !== 0) {\n throw new Error(\"hex string must have even length\");\n }\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n const hi = parseInt(hex[i * 2], 16);\n const lo = parseInt(hex[i * 2 + 1], 16);\n if (Number.isNaN(hi) || Number.isNaN(lo)) {\n throw new Error(\"invalid hex character\");\n }\n out[i] = (hi << 4) | lo;\n }\n return out;\n}\n\nexport function base64Encode(bytes: Uint8Array): string {\n // base64 (standard, not url-safe) so envelopes pass through JSON cleanly.\n // We avoid `btoa` to stay node-friendly without polyfills.\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i];\n const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;\n const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;\n out += chars[(b0 >> 2) & 0x3f];\n out += chars[((b0 << 4) | (b1 >> 4)) & 0x3f];\n out += i + 1 < bytes.length ? chars[((b1 << 2) | (b2 >> 6)) & 0x3f] : \"=\";\n out += i + 2 < bytes.length ? chars[b2 & 0x3f] : \"=\";\n }\n return out;\n}\n\nexport function base64Decode(s: string): Uint8Array {\n const clean = s.replace(/[^A-Za-z0-9+/=]/g, \"\");\n const len = clean.length;\n if (len % 4 !== 0) {\n throw new Error(\"invalid base64 input\");\n }\n const padding =\n clean.endsWith(\"==\") ? 2 : clean.endsWith(\"=\") ? 1 : 0;\n const outLen = (len / 4) * 3 - padding;\n const out = new Uint8Array(outLen);\n const lookup: Record<string, number> = {};\n const chars =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n for (let i = 0; i < chars.length; i++) lookup[chars[i]] = i;\n\n let outIdx = 0;\n for (let i = 0; i < len; i += 4) {\n const v0 = lookup[clean[i]] ?? 0;\n const v1 = lookup[clean[i + 1]] ?? 0;\n const v2 = clean[i + 2] === \"=\" ? 0 : (lookup[clean[i + 2]] ?? 0);\n const v3 = clean[i + 3] === \"=\" ? 0 : (lookup[clean[i + 3]] ?? 0);\n const b0 = (v0 << 2) | (v1 >> 4);\n const b1 = ((v1 & 0x0f) << 4) | (v2 >> 2);\n const b2 = ((v2 & 0x03) << 6) | v3;\n if (outIdx < outLen) out[outIdx++] = b0;\n if (outIdx < outLen) out[outIdx++] = b1;\n if (outIdx < outLen) out[outIdx++] = b2;\n }\n return out;\n}\n\nexport function utf8Encode(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\nexport function utf8Decode(b: Uint8Array): string {\n return new TextDecoder().decode(b);\n}\n\n/**\n * Compute `hexEncode(sha256(canonicalize(value)))`. The SHA-256 binding\n * is injected so the module remains usable in both the WASM and pure-JS\n * paths.\n */\nexport function canonicalHashHex(\n sha256: (bytes: Uint8Array) => Uint8Array,\n value: Json,\n): string {\n const canonical = canonicalize(value);\n return hexEncode(sha256(utf8Encode(canonical)));\n}\n","/**\n * TinyCloud encryption network identifiers.\n *\n * A network id is `urn:tinycloud:encryption:<ownerDid>:<network>` where\n * `ownerDid` is the owner's DID and `network` is a\n * non-empty label drawn from `[a-z0-9][a-z0-9-]*`.\n *\n * The embedded owner DID is the root authority for the network: any\n * delegation chain ending in a `tinycloud.encryption/decrypt` grant on\n * the network must root at this owner DID.\n */\n\nconst URN_PREFIX = \"urn:tinycloud:encryption:\";\nconst NETWORK_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;\nconst PKH_EIP155_DID_RE = /^did:pkh:eip155:(\\d+):(0x[a-fA-F0-9]{40})$/;\n\nexport interface ParsedNetworkId {\n /** The full URN string. */\n networkId: string;\n /** Owner DID embedded in the URN (the network's root authority). */\n ownerDid: string;\n /** Network label (the suffix after the owner DID). */\n name: string;\n}\n\nexport class NetworkIdError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NetworkIdError\";\n }\n}\n\n/**\n * Parse a network id string into its owner DID and name components.\n *\n * Throws {@link NetworkIdError} when the input does not match\n * `urn:tinycloud:encryption:<did>:<name>`, when the embedded DID is\n * malformed, or when the network name fails {@link NETWORK_NAME_RE}.\n */\nexport function parseNetworkId(networkId: string): ParsedNetworkId {\n if (typeof networkId !== \"string\" || networkId.length === 0) {\n throw new NetworkIdError(\"networkId must be a non-empty string\");\n }\n if (!networkId.startsWith(URN_PREFIX)) {\n throw new NetworkIdError(\n `networkId must start with ${URN_PREFIX} (got ${JSON.stringify(networkId)})`,\n );\n }\n const body = networkId.slice(URN_PREFIX.length);\n // `body` = \"<ownerDid>:<network>\"\n // ownerDid contains ':' (e.g. did:key:z6Mk...), so we split on the LAST colon\n // and treat the suffix as the network name.\n const lastColon = body.lastIndexOf(\":\");\n if (lastColon <= 0 || lastColon === body.length - 1) {\n throw new NetworkIdError(\n `networkId missing ownerDid or name segment (got ${JSON.stringify(networkId)})`,\n );\n }\n const ownerDid = body.slice(0, lastColon);\n const name = body.slice(lastColon + 1);\n\n if (!ownerDid.startsWith(\"did:\")) {\n throw new NetworkIdError(\n `networkId ownerDid must be a DID (got ${JSON.stringify(ownerDid)})`,\n );\n }\n // Minimal DID shape: did:<method>:<id> — three colon-separated segments,\n // each non-empty.\n const didParts = ownerDid.split(\":\");\n if (didParts.length < 3 || didParts.some((p) => p.length === 0)) {\n throw new NetworkIdError(\n `networkId ownerDid is not a well-formed DID (got ${JSON.stringify(ownerDid)})`,\n );\n }\n if (!NETWORK_NAME_RE.test(name)) {\n throw new NetworkIdError(\n `networkId name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`,\n );\n }\n return { networkId, ownerDid, name };\n}\n\n/**\n * Construct a network id URN from an owner DID and a network name.\n * Validates inputs and throws {@link NetworkIdError} on bad shape.\n */\nexport function buildNetworkId(ownerDid: string, name: string): string {\n if (typeof ownerDid !== \"string\" || !ownerDid.startsWith(\"did:\")) {\n throw new NetworkIdError(\"ownerDid must be a DID\");\n }\n if (typeof name !== \"string\" || !NETWORK_NAME_RE.test(name)) {\n throw new NetworkIdError(\n `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`,\n );\n }\n const networkId = `${URN_PREFIX}${ownerDid}:${name}`;\n // Re-validate the composed result so the same error path triggers\n // for caller inputs that compose into a malformed URN.\n parseNetworkId(networkId);\n return networkId;\n}\n\n/**\n * Returns true when {@link networkId} is a syntactically valid network URN.\n */\nexport function isNetworkId(networkId: unknown): networkId is string {\n if (typeof networkId !== \"string\") {\n return false;\n }\n try {\n parseNetworkId(networkId);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction parsePkhOwnerDid(ownerDid: string):\n | { chainId: string; address: string }\n | null {\n const match = ownerDid.match(PKH_EIP155_DID_RE);\n if (!match) return null;\n return {\n chainId: match[1],\n address: match[2].toLowerCase(),\n };\n}\n\n/**\n * Compare owner DIDs as network principals. For `did:pkh:eip155`, EVM\n * address casing is not part of principal identity; other DID methods\n * remain exact string matches.\n */\nexport function ownerDidMatches(a: string, b: string): boolean {\n const aPkh = parsePkhOwnerDid(a);\n const bPkh = parsePkhOwnerDid(b);\n if (aPkh && bPkh) {\n return aPkh.chainId === bPkh.chainId && aPkh.address === bPkh.address;\n }\n return a === b;\n}\n\n/**\n * Resolve the discovery key used to look up a network's descriptor under\n * an owner's public account-space.\n *\n * Format: `.well-known/encryption/network/<name>`.\n */\nexport function networkDiscoveryKey(name: string): string {\n if (!NETWORK_NAME_RE.test(name)) {\n throw new NetworkIdError(\n `network name ${JSON.stringify(name)} must match ${NETWORK_NAME_RE.source}`,\n );\n }\n return `.well-known/encryption/network/${name}`;\n}\n\nexport const ENCRYPTION_NETWORK_URN_PREFIX = URN_PREFIX;\nexport const NETWORK_NAME_PATTERN = NETWORK_NAME_RE;\n","/**\n * Type definitions for TinyCloud one-of-one encryption.\n *\n * Wire shapes mirror the protocol described in the encryption\n * architecture: inline envelopes carry the encrypted symmetric key\n * alongside the ciphertext; decrypt requests are short-lived UCAN\n * invocations against a target node plus networkId.\n */\n\nimport type { Json } from \"./canonical\";\n\n/** Default ciphersuite identifier for v1 envelopes. */\nexport const DEFAULT_ENCRYPTION_ALG = \"x25519-aes256gcm/v1\" as const;\n\n/** Inline-envelope schema version. */\nexport const ENVELOPE_VERSION = 1 as const;\n\n/** Default key version on freshly-created networks. */\nexport const DEFAULT_KEY_VERSION = 1 as const;\n\n/** Decrypt-invocation fact type. */\nexport const DECRYPT_FACT_TYPE = \"tinycloud.encryption.decrypt/v1\" as const;\n\n/** Decrypt response type. */\nexport const DECRYPT_RESULT_TYPE =\n \"tinycloud.encryption.decrypt-result/v1\" as const;\n\n/** Encryption service identifier (manifest long form). */\nexport const ENCRYPTION_SERVICE = \"tinycloud.encryption\" as const;\n\n/** Short form used in recap/abilities maps. */\nexport const ENCRYPTION_SERVICE_SHORT = \"encryption\" as const;\n\n/** Decrypt ability URN. */\nexport const DECRYPT_ACTION = \"tinycloud.encryption/decrypt\" as const;\n\n/**\n * Inline encrypted envelope persisted in KV/SQL records.\n *\n * - `encryptedSymmetricKey` is opaque to the SDK; only the network can\n * unwrap it.\n * - `encryptedSymmetricKeyHash` is the canonical hash of the wrapped key\n * bytes (hex-encoded sha-256 of the base64 string's canonical JSON\n * form). The node recomputes this on every decrypt request.\n * - `ciphertext` and `aad` are payload bytes only; the node never sees\n * them.\n */\nexport interface InlineEncryptedEnvelope {\n /** Schema version. */\n v: typeof ENVELOPE_VERSION;\n /** Network id URN. */\n networkId: string;\n /** Ciphersuite identifier. */\n alg: string;\n /** Network key version that was used to wrap the symmetric key. */\n keyVersion: number;\n /** Base64-encoded wrapped symmetric key / capsule. */\n encryptedSymmetricKey: string;\n /** Hex sha-256 of the canonical encryptedSymmetricKey string. */\n encryptedSymmetricKeyHash: string;\n /** Base64-encoded payload ciphertext. */\n ciphertext: string;\n /** Base64-encoded associated data, if any. */\n aad?: string;\n /** Caller-supplied metadata. Not authenticated against the node. */\n metadata?: Record<string, string>;\n}\n\n/**\n * Node-published network descriptor. The node DB is authoritative; a\n * cached copy may also live under\n * `.well-known/encryption/network/<name>` in the owner's account\n * space (a discovery record only).\n */\nexport interface NetworkDescriptor {\n networkId: string;\n ownerDid: string;\n name: string;\n members: ReadonlyArray<{ nodeId: string; role: \"primary\" | \"share\" }>;\n threshold: { n: number; t: number };\n state: \"pending\" | \"generating\" | \"active\" | \"rotating\" | \"revoked\" | \"failed\";\n /** Base64-encoded network public key. */\n publicEncryptionKey: string;\n alg: string;\n keyVersion: number;\n keyBackend: \"local-one-of-one\" | \"dstack\" | \"threshold\";\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Decrypt-request body sent over the wire. Hashed (canonically) and\n * bound to the UCAN invocation via `facts.bodyHash`.\n */\nexport interface DecryptRequestBody {\n type: typeof DECRYPT_FACT_TYPE;\n targetNode: string;\n networkId: string;\n alg: string;\n keyVersion: number;\n /** Base64-encoded wrapped symmetric key from the envelope. */\n encryptedSymmetricKey: string;\n /** Recomputed hash of the wrapped key. */\n encryptedSymmetricKeyHash: string;\n /** Base64-encoded per-request receiver public key. */\n receiverPublicKey: string;\n /** Hash of the receiver public key. */\n receiverPublicKeyHash: string;\n}\n\n/**\n * Decrypt-response body returned by the node. The SDK verifies the\n * signature, recomputes hashes, then unwraps `wrappedKey` with the\n * per-request receiver private key before decrypting the payload.\n */\nexport interface DecryptResponseBody {\n type: typeof DECRYPT_RESULT_TYPE;\n targetNode: string;\n networkId: string;\n invocationCid: string;\n encryptedSymmetricKeyHash: string;\n receiverPublicKeyHash: string;\n /** Base64-encoded symmetric key re-encrypted to receiverPublicKey. */\n wrappedKey: string;\n alg: string;\n keyVersion: number;\n requestHash: string;\n nodeId: string;\n /** Base64-encoded ed25519 signature over canonical(response - signature field). */\n nodeSignature: string;\n}\n\n/**\n * Decrypt-invocation facts attached to the UCAN. Verifiers recompute\n * `bodyHash`, `encryptedSymmetricKeyHash`, and `receiverPublicKeyHash`\n * from the request body and reject any mismatch.\n */\nexport interface DecryptInvocationFact {\n type: typeof DECRYPT_FACT_TYPE;\n targetNode: string;\n networkId: string;\n bodyHash: string;\n encryptedSymmetricKeyHash: string;\n receiverPublicKeyHash: string;\n alg: string;\n keyVersion: number;\n}\n\n/**\n * Per-request receiver key pair (x25519). The private key never\n * leaves the SDK; the public key is sent to the node so the node can\n * rewrap the symmetric key.\n */\nexport interface ReceiverKeyPair {\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n}\n\n/**\n * Crypto primitives injected into the encryption module. The SDK\n * provides these via WASM bindings; tests provide simple in-memory\n * implementations.\n */\nexport interface EncryptionCrypto {\n /** SHA-256 → 32-byte digest. */\n sha256(data: Uint8Array): Uint8Array;\n /** Cryptographically secure random bytes. */\n randomBytes(length: number): Uint8Array;\n /** Derive an x25519 key pair from a 32-byte seed. */\n x25519FromSeed(seed: Uint8Array): ReceiverKeyPair;\n /** Compute the x25519 ECDH shared secret. */\n x25519Dh(privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array;\n /** Authenticated symmetric encryption (the node's symmetric scheme). */\n authEncrypt(\n key: Uint8Array,\n plaintext: Uint8Array,\n aad?: Uint8Array,\n ): Uint8Array;\n /** Authenticated symmetric decryption (matched to authEncrypt). */\n authDecrypt(\n key: Uint8Array,\n ciphertext: Uint8Array,\n aad?: Uint8Array,\n ): Uint8Array;\n /**\n * Wrap a symmetric key for the network's public encryption key using\n * a sealed-box / hpke / x25519+symmetric construction. Implementation\n * is opaque; only the node can unwrap.\n */\n sealToNetworkKey(\n networkPublicKey: Uint8Array,\n symmetricKey: Uint8Array,\n ): Uint8Array;\n /**\n * Open a wrapped symmetric key that was re-encrypted to the\n * per-request receiver public key. The matching private key must be\n * supplied here; the SDK never sends it to the node.\n */\n openWithReceiverKey(\n receiverPrivateKey: Uint8Array,\n wrappedKey: Uint8Array,\n ): Uint8Array;\n /**\n * Verify an ed25519 signature over `message` produced by the node\n * identified by `nodeId` (the public-key DID).\n */\n verifyNodeSignature(\n nodeId: string,\n message: Uint8Array,\n signature: Uint8Array,\n ): boolean;\n}\n\n/**\n * Signer interface used to derive a receiver key pair from a wallet or\n * session signer. The signature is HKDF-extracted into the receiver\n * seed so the public key is reproducible given the same context.\n */\nexport interface ReceiverKeySigner {\n signMessage(message: string): Promise<string>;\n}\n\n/** Capability proof material accompanying a decrypt invocation. */\nexport interface DecryptCapabilityProof {\n /** Delegation chain CIDs rooted at the network owner DID. */\n proofs: ReadonlyArray<string>;\n /** Optional Authorization header value to use instead of building one. */\n authorization?: string;\n}\n\n/**\n * Inputs to the decrypt invocation builder.\n */\nexport interface BuildDecryptInvocationInput {\n /** Target node DID — also the UCAN audience. */\n targetNode: string;\n /** Network id URN — also the recap resource. */\n networkId: string;\n /** Canonical body that will be POSTed. */\n body: DecryptRequestBody;\n /** Facts include hashes bound to the canonical body. */\n facts: DecryptInvocationFact;\n /** Capability proof chain. */\n proof: DecryptCapabilityProof;\n /** Optional `nbf` UCAN field as an ISO date string. */\n notBefore?: string;\n /** Optional `exp` UCAN field as an ISO date string. */\n expiration?: string;\n}\n\n/**\n * The output of {@link buildDecryptInvocation}.\n */\nexport interface BuiltDecryptInvocation {\n /** HTTP `Authorization` header value. */\n authorization: string;\n /** CID of the invocation (used by the node response binding). */\n invocationCid: string;\n /** Canonical body string the node will hash. */\n canonicalBody: string;\n}\n\n/**\n * Signer interface for producing the decrypt invocation. WASM bindings\n * implement this with the same session signer used for KV/SQL\n * invocations; tests can stub it.\n */\nexport interface DecryptInvocationSigner {\n signDecryptInvocation(input: BuildDecryptInvocationInput): Promise<BuiltDecryptInvocation>;\n}\n\n/**\n * Errors thrown / returned from the encryption module.\n */\nexport type EncryptionErrorInput =\n | { code: \"NETWORK_NOT_FOUND\"; networkId?: string; name?: string; message?: string }\n | { code: \"NETWORK_NOT_ACTIVE\"; state: string; message?: string }\n | { code: \"INVALID_NETWORK_ID\"; message: string }\n | { code: \"INVALID_ENVELOPE\"; message: string }\n | { code: \"DECRYPT_DENIED\"; message: string }\n | { code: \"INVALID_RESPONSE\"; message: string }\n | { code: \"RESPONSE_SIGNATURE_INVALID\"; message?: string }\n | { code: \"RESPONSE_BINDING_MISMATCH\"; field: string; message?: string }\n | { code: \"TRANSPORT_ERROR\"; cause: Error; message?: string }\n | { code: \"INVALID_INPUT\"; message: string };\n\nexport type EncryptionError = EncryptionErrorInput & {\n service: \"encryption\";\n message: string;\n};\n\nfunction defaultEncryptionMessage(input: EncryptionErrorInput): string {\n switch (input.code) {\n case \"NETWORK_NOT_FOUND\":\n return (\n input.message ??\n `Network not found: ${input.networkId ?? input.name ?? \"<unknown>\"}`\n );\n case \"NETWORK_NOT_ACTIVE\":\n return input.message ?? `Network not active (state=${input.state})`;\n case \"INVALID_NETWORK_ID\":\n return input.message;\n case \"INVALID_ENVELOPE\":\n return input.message;\n case \"DECRYPT_DENIED\":\n return input.message;\n case \"INVALID_RESPONSE\":\n return input.message;\n case \"RESPONSE_SIGNATURE_INVALID\":\n return input.message ?? \"Node response signature failed to verify\";\n case \"RESPONSE_BINDING_MISMATCH\":\n return (\n input.message ??\n `Node response binding mismatch on field ${JSON.stringify(input.field)}`\n );\n case \"TRANSPORT_ERROR\":\n return input.message ?? input.cause.message;\n case \"INVALID_INPUT\":\n return input.message;\n }\n}\n\nexport function encryptionError(input: EncryptionErrorInput): EncryptionError {\n return {\n ...input,\n service: \"encryption\",\n message: defaultEncryptionMessage(input),\n };\n}\n\n/** Helper for the test/runtime layers to coerce arbitrary throwables. */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) return error;\n if (typeof error === \"object\" && error !== null) {\n return new Error(JSON.stringify(error));\n }\n return new Error(String(error));\n}\n\n/** Re-export for ergonomic typing of canonical payloads. */\nexport type CanonicalJson = Json;\n","/**\n * Network-descriptor discovery.\n *\n * Resolution order (per architecture):\n *\n * 1. The node's authoritative endpoint\n * `GET /encryption/networks/<networkId>` returns the current\n * descriptor (`state`, `publicEncryptionKey`, `keyVersion`, ...).\n * 2. If the node is unreachable, fall back to the cached discovery\n * record at `.well-known/encryption/network/<name>` inside the\n * owner's public space.\n *\n * The node DB is authoritative on conflict; cached records are\n * advisory only.\n */\n\nimport {\n NetworkIdError,\n networkDiscoveryKey,\n ownerDidMatches,\n parseNetworkId,\n} from \"./networkId\";\nimport {\n encryptionError,\n type EncryptionError,\n type NetworkDescriptor,\n} from \"./types\";\n\nexport type DiscoverySource = \"node\" | \"well-known\";\n\nexport interface DiscoveredNetwork {\n descriptor: NetworkDescriptor;\n source: DiscoverySource;\n}\n\nexport interface NodeDescriptorFetcher {\n /** Fetch the descriptor by full networkId URN. */\n fetchByNetworkId(networkId: string): Promise<NetworkDescriptor | null>;\n}\n\nexport interface WellKnownDescriptorFetcher {\n /**\n * Read the cached well-known descriptor by owner DID + network name.\n * Returns null if no record exists or the record is unreadable.\n */\n fetchWellKnown(\n ownerDid: string,\n discoveryKey: string,\n ): Promise<NetworkDescriptor | null>;\n}\n\nexport interface DiscoverNetworkInput {\n /** Either a networkId URN or a bare network name (paired with `ownerDid`). */\n identifier: string;\n /** Required when identifier is a bare name. */\n ownerDid?: string;\n node?: NodeDescriptorFetcher;\n wellKnown?: WellKnownDescriptorFetcher;\n}\n\n/**\n * Resolve a network descriptor. The node fetcher is preferred; the\n * well-known fallback is used only on transport failure.\n *\n * The returned descriptor is sanity-checked: `networkId`, `ownerDid`,\n * and `name` must agree with the URN, and the public key field must\n * be non-empty.\n */\nexport async function discoverNetwork(\n input: DiscoverNetworkInput,\n):\n | Promise<{ ok: true; data: DiscoveredNetwork } | { ok: false; error: EncryptionError }> {\n let networkId: string;\n let ownerDid: string;\n let name: string;\n try {\n if (input.identifier.startsWith(\"urn:tinycloud:encryption:\")) {\n const parsed = parseNetworkId(input.identifier);\n networkId = parsed.networkId;\n ownerDid = parsed.ownerDid;\n name = parsed.name;\n } else {\n if (input.ownerDid === undefined) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message:\n \"discoverNetwork requires `ownerDid` when identifier is a bare network name\",\n }),\n };\n }\n networkId = `urn:tinycloud:encryption:${input.ownerDid}:${input.identifier}`;\n const parsed = parseNetworkId(networkId);\n ownerDid = parsed.ownerDid;\n name = parsed.name;\n }\n } catch (err) {\n if (err instanceof NetworkIdError) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_NETWORK_ID\",\n message: err.message,\n }),\n };\n }\n throw err;\n }\n\n // 1) Try the node first.\n if (input.node !== undefined) {\n try {\n const descriptor = await input.node.fetchByNetworkId(networkId);\n if (descriptor !== null) {\n const validated = validateDescriptor(descriptor, networkId, ownerDid, name);\n if (!validated.ok) return validated;\n return { ok: true, data: { descriptor: validated.data, source: \"node\" } };\n }\n } catch (err) {\n // Fall through to well-known\n }\n }\n\n // 2) Fallback to well-known cache.\n if (input.wellKnown !== undefined) {\n try {\n const descriptor = await input.wellKnown.fetchWellKnown(\n ownerDid,\n networkDiscoveryKey(name),\n );\n if (descriptor !== null) {\n const validated = validateDescriptor(descriptor, networkId, ownerDid, name);\n if (!validated.ok) return validated;\n return {\n ok: true,\n data: { descriptor: validated.data, source: \"well-known\" },\n };\n }\n } catch (err) {\n // Fall through to NOT_FOUND\n }\n }\n\n return {\n ok: false,\n error: encryptionError({\n code: \"NETWORK_NOT_FOUND\",\n networkId,\n name,\n }),\n };\n}\n\nfunction validateDescriptor(\n descriptor: NetworkDescriptor,\n networkId: string,\n ownerDid: string,\n name: string,\n):\n | { ok: true; data: NetworkDescriptor }\n | { ok: false; error: EncryptionError } {\n let descriptorNetwork;\n try {\n descriptorNetwork = parseNetworkId(descriptor.networkId);\n } catch (err) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_NETWORK_ID\",\n message: `descriptor networkId is malformed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n }),\n };\n }\n\n if (\n descriptorNetwork.name !== name ||\n !ownerDidMatches(descriptorNetwork.ownerDid, ownerDid)\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_NETWORK_ID\",\n message: `descriptor networkId ${JSON.stringify(descriptor.networkId)} does not match expected ${JSON.stringify(networkId)}`,\n }),\n };\n }\n\n const descriptorOwnerDid = descriptorOwner(descriptor);\n if (\n descriptorOwnerDid === undefined ||\n !ownerDidMatches(descriptorOwnerDid, ownerDid) ||\n !ownerDidMatches(descriptorOwnerDid, descriptorNetwork.ownerDid)\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_NETWORK_ID\",\n message: \"descriptor ownerDid does not match networkId ownerDid\",\n }),\n };\n }\n if (descriptor.name !== name) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_NETWORK_ID\",\n message: \"descriptor name does not match networkId name\",\n }),\n };\n }\n if (\n typeof descriptor.publicEncryptionKey !== \"string\" ||\n descriptor.publicEncryptionKey.length === 0\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_NETWORK_ID\",\n message: \"descriptor publicEncryptionKey must be a non-empty string\",\n }),\n };\n }\n return {\n ok: true,\n data: {\n ...descriptor,\n ownerDid: descriptorOwnerDid,\n },\n };\n}\n\nfunction descriptorOwner(descriptor: NetworkDescriptor): string | undefined {\n if (typeof descriptor.ownerDid === \"string\" && descriptor.ownerDid.length > 0) {\n return descriptor.ownerDid;\n }\n\n const legacyDescriptor = descriptor as NetworkDescriptor & {\n principal?: unknown;\n };\n return typeof legacyDescriptor.principal === \"string\" &&\n legacyDescriptor.principal.length > 0\n ? legacyDescriptor.principal\n : undefined;\n}\n\n/**\n * Reject a descriptor that is not in a state that accepts decrypt\n * requests. Only `active` and `rotating` networks may decrypt; revoked\n * or pending networks reject.\n */\nexport function ensureNetworkUsableForDecrypt(\n descriptor: NetworkDescriptor,\n):\n | { ok: true; data: NetworkDescriptor }\n | { ok: false; error: EncryptionError } {\n if (descriptor.state === \"active\" || descriptor.state === \"rotating\") {\n return { ok: true, data: descriptor };\n }\n return {\n ok: false,\n error: encryptionError({\n code: \"NETWORK_NOT_ACTIVE\",\n state: descriptor.state,\n }),\n };\n}\n","/**\n * Inline-envelope encrypt / decrypt helpers.\n *\n * Encryption is fully local: the SDK generates a per-record symmetric\n * key, encrypts the payload, then wraps the symmetric key against the\n * network's public encryption key. The wrapped key (and key hash)\n * travels alongside the ciphertext inside an\n * {@link InlineEncryptedEnvelope}.\n *\n * Decryption is split: the node unwraps the symmetric key to the\n * per-request receiver public key (see {@link buildDecryptInvocation}\n * and the decrypt route); this module is responsible for the local\n * payload decryption once the symmetric key is available.\n */\n\nimport {\n base64Decode,\n base64Encode,\n canonicalHashHex,\n} from \"./canonical\";\nimport {\n DEFAULT_ENCRYPTION_ALG,\n DEFAULT_KEY_VERSION,\n ENVELOPE_VERSION,\n encryptionError,\n type EncryptionCrypto,\n type EncryptionError,\n type InlineEncryptedEnvelope,\n} from \"./types\";\nimport { parseNetworkId } from \"./networkId\";\n\nexport interface EncryptToNetworkInput {\n /** Target network id URN. */\n networkId: string;\n /** Network public key bytes (already discovered). */\n networkPublicKey: Uint8Array;\n /** Payload bytes to encrypt. Callers serialize objects to bytes themselves. */\n plaintext: Uint8Array;\n /** Optional associated authenticated data. */\n aad?: Uint8Array;\n /** Ciphersuite identifier. Defaults to {@link DEFAULT_ENCRYPTION_ALG}. */\n alg?: string;\n /** Key version. Defaults to {@link DEFAULT_KEY_VERSION}. */\n keyVersion?: number;\n /** Caller-supplied envelope metadata. */\n metadata?: Record<string, string>;\n}\n\nexport interface EncryptToNetworkResult {\n envelope: InlineEncryptedEnvelope;\n /** Symmetric key returned for caller bookkeeping; do NOT persist. */\n symmetricKey: Uint8Array;\n}\n\n/**\n * Local-only encrypt: generates a symmetric key, encrypts the payload,\n * wraps the key against the network public key, and returns the\n * inline envelope.\n */\nexport function encryptToNetwork(\n crypto: EncryptionCrypto,\n input: EncryptToNetworkInput,\n): EncryptToNetworkResult {\n parseNetworkId(input.networkId);\n const alg = input.alg ?? DEFAULT_ENCRYPTION_ALG;\n const keyVersion = input.keyVersion ?? DEFAULT_KEY_VERSION;\n\n const symmetricKey = crypto.randomBytes(32);\n const ciphertext = crypto.authEncrypt(symmetricKey, input.plaintext, input.aad);\n const wrapped = crypto.sealToNetworkKey(input.networkPublicKey, symmetricKey);\n const encryptedSymmetricKey = base64Encode(wrapped);\n const encryptedSymmetricKeyHash = canonicalHashHex(\n crypto.sha256,\n encryptedSymmetricKey,\n );\n\n const envelope: InlineEncryptedEnvelope = {\n v: ENVELOPE_VERSION,\n networkId: input.networkId,\n alg,\n keyVersion,\n encryptedSymmetricKey,\n encryptedSymmetricKeyHash,\n ciphertext: base64Encode(ciphertext),\n ...(input.aad !== undefined ? { aad: base64Encode(input.aad) } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n\n return { envelope, symmetricKey };\n}\n\n/**\n * Validate an inline envelope shape. Returns an error if the envelope\n * is missing required fields or fails internal hash recomputation.\n */\nexport function validateEnvelope(\n crypto: EncryptionCrypto,\n envelope: unknown,\n): { ok: true; data: InlineEncryptedEnvelope } | { ok: false; error: EncryptionError } {\n if (envelope === null || typeof envelope !== \"object\") {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_ENVELOPE\",\n message: \"envelope must be an object\",\n }),\n };\n }\n const e = envelope as InlineEncryptedEnvelope;\n if (e.v !== ENVELOPE_VERSION) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_ENVELOPE\",\n message: `envelope.v must be ${ENVELOPE_VERSION} (got ${e.v as unknown as string})`,\n }),\n };\n }\n try {\n parseNetworkId(e.networkId);\n } catch (err) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_ENVELOPE\",\n message: `envelope.networkId is malformed: ${\n err instanceof Error ? err.message : String(err)\n }`,\n }),\n };\n }\n for (const field of [\n \"alg\",\n \"encryptedSymmetricKey\",\n \"encryptedSymmetricKeyHash\",\n \"ciphertext\",\n ] as const) {\n if (typeof e[field] !== \"string\" || (e[field] as string).length === 0) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_ENVELOPE\",\n message: `envelope.${field} must be a non-empty string`,\n }),\n };\n }\n }\n if (typeof e.keyVersion !== \"number\" || !Number.isInteger(e.keyVersion)) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_ENVELOPE\",\n message: \"envelope.keyVersion must be an integer\",\n }),\n };\n }\n const expectedHash = canonicalHashHex(crypto.sha256, e.encryptedSymmetricKey);\n if (expectedHash !== e.encryptedSymmetricKeyHash) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_ENVELOPE\",\n message:\n \"envelope.encryptedSymmetricKeyHash does not match canonical hash of encryptedSymmetricKey\",\n }),\n };\n }\n return { ok: true, data: e };\n}\n\n/**\n * Decrypt an inline envelope given the unwrapped symmetric key.\n *\n * Callers typically obtain the symmetric key via the node decrypt\n * endpoint plus the per-request receiver key pair (see\n * `EncryptionService.decryptEnvelope`).\n */\nexport function decryptEnvelopeWithKey(\n crypto: EncryptionCrypto,\n envelope: InlineEncryptedEnvelope,\n symmetricKey: Uint8Array,\n): Uint8Array {\n const ciphertext = base64Decode(envelope.ciphertext);\n const aad = envelope.aad !== undefined ? base64Decode(envelope.aad) : undefined;\n return crypto.authDecrypt(symmetricKey, ciphertext, aad);\n}\n","/**\n * TinyCloud encryption decrypt-invocation builder.\n *\n * The decrypt invocation is a UCAN-style TinyCloud invocation against\n * a node plus a network id. It is structurally distinct from the\n * existing space-shaped invocations:\n *\n * - `aud` (audience) is the **target node DID** (not a space owner).\n * - `att` (attenuation) uses the **networkId URN** as the resource\n * key (not a `tinycloud:pkh:...:<space>` URI).\n * - `fct` (facts) binds `bodyHash`, `encryptedSymmetricKeyHash`, and\n * `receiverPublicKeyHash` so the node can recompute them from the\n * POST body.\n *\n * Production callers inject a `DecryptInvocationSigner` backed by the\n * WASM UCAN/session signer. Tests pass a deterministic stub.\n */\n\nimport { canonicalize, canonicalHashHex, hexEncode, utf8Encode } from \"./canonical\";\nimport { parseNetworkId } from \"./networkId\";\nimport {\n DECRYPT_ACTION,\n DECRYPT_FACT_TYPE,\n ENCRYPTION_SERVICE,\n encryptionError,\n type BuildDecryptInvocationInput,\n type BuiltDecryptInvocation,\n type CanonicalJson,\n type DecryptCapabilityProof,\n type DecryptInvocationFact,\n type DecryptInvocationSigner,\n type DecryptRequestBody,\n type EncryptionCrypto,\n type EncryptionError,\n} from \"./types\";\n\nexport interface CanonicalDecryptRequest {\n /** The canonical body that the node will hash. */\n canonicalBody: string;\n /** Hex sha-256 of the canonical body bytes. */\n bodyHash: string;\n /** Hex sha-256 of the receiver public key bytes. */\n receiverPublicKeyHash: string;\n}\n\nexport interface BuildCanonicalDecryptRequestInput {\n crypto: EncryptionCrypto;\n body: DecryptRequestBody;\n receiverPublicKey: Uint8Array;\n}\n\n/**\n * Build the canonical body string and its bound hashes for a decrypt\n * request. The output is what gets POSTed to the node, and what the\n * node will hash to verify `facts.bodyHash`.\n */\nexport function buildCanonicalDecryptRequest(\n input: BuildCanonicalDecryptRequestInput,\n): CanonicalDecryptRequest {\n const canonicalBody = canonicalize(input.body as unknown as CanonicalJson);\n const bodyHash = canonicalHashHex(\n input.crypto.sha256,\n input.body as unknown as CanonicalJson,\n );\n const receiverPublicKeyHash = canonicalHashHex(\n input.crypto.sha256,\n input.body.receiverPublicKey,\n );\n return { canonicalBody, bodyHash, receiverPublicKeyHash };\n}\n\nexport interface BuildDecryptFactsInput {\n crypto: EncryptionCrypto;\n body: DecryptRequestBody;\n /** Encrypted symmetric key hash from the envelope (already canonical). */\n encryptedSymmetricKeyHash: string;\n /** Receiver public key bytes. */\n receiverPublicKey: Uint8Array;\n /** Canonical body string used to derive bodyHash. */\n canonicalBody?: string;\n}\n\n/**\n * Build the {@link DecryptInvocationFact} that will be embedded in the\n * UCAN `fct` field. Hashes are recomputed here so callers cannot drift\n * from the canonical body without the node noticing.\n */\nexport function buildDecryptFacts(\n input: BuildDecryptFactsInput,\n): DecryptInvocationFact {\n // When a precomputed canonicalBody string is supplied, hash its bytes\n // directly. Don't route it through canonicalHashHex, which would\n // re-canonicalize the string itself (escaping it as a JSON value).\n const bodyHash =\n input.canonicalBody !== undefined\n ? hexEncode(input.crypto.sha256(utf8Encode(input.canonicalBody)))\n : canonicalHashHex(\n input.crypto.sha256,\n input.body as unknown as CanonicalJson,\n );\n const receiverPublicKeyHash = canonicalHashHex(\n input.crypto.sha256,\n input.body.receiverPublicKey,\n );\n return {\n type: DECRYPT_FACT_TYPE,\n targetNode: input.body.targetNode,\n networkId: input.body.networkId,\n bodyHash,\n encryptedSymmetricKeyHash: input.encryptedSymmetricKeyHash,\n receiverPublicKeyHash,\n alg: input.body.alg,\n keyVersion: input.body.keyVersion,\n };\n}\n\n/**\n * Recap-shaped attenuation for the decrypt invocation. The resource\n * key is the networkId URN; the ability is the long-form\n * `tinycloud.encryption/decrypt`. This is intentionally distinct from\n * the existing space-shaped invocation map so callers cannot\n * accidentally fake a space prefix.\n */\nexport function buildDecryptAttenuation(\n networkId: string,\n): Record<string, Record<string, Record<string, never>>> {\n parseNetworkId(networkId);\n return {\n [networkId]: {\n [DECRYPT_ACTION]: {},\n },\n };\n}\n\n/**\n * Validate a {@link BuildDecryptInvocationInput} payload — the body\n * shape, the facts bindings, and the audience contract — without\n * actually signing. Returns either the input (typed) or a structured\n * error so callers can short-circuit before calling into WASM.\n */\nexport function checkDecryptInvocationInput(\n crypto: EncryptionCrypto,\n input: BuildDecryptInvocationInput,\n):\n | { ok: true; data: BuildDecryptInvocationInput; canonicalBody: string }\n | { ok: false; error: EncryptionError } {\n if (input.body.type !== DECRYPT_FACT_TYPE) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: `body.type must be ${DECRYPT_FACT_TYPE}`,\n }),\n };\n }\n if (input.facts.type !== DECRYPT_FACT_TYPE) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: `facts.type must be ${DECRYPT_FACT_TYPE}`,\n }),\n };\n }\n if (input.facts.targetNode !== input.targetNode) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message:\n \"facts.targetNode must equal targetNode — the UCAN audience binds the request to a single node\",\n }),\n };\n }\n if (input.body.targetNode !== input.targetNode) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: \"body.targetNode must equal targetNode\",\n }),\n };\n }\n if (input.facts.networkId !== input.networkId) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: \"facts.networkId must equal networkId\",\n }),\n };\n }\n if (input.body.networkId !== input.networkId) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: \"body.networkId must equal networkId\",\n }),\n };\n }\n if (input.facts.alg !== input.body.alg) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: \"facts.alg must equal body.alg\",\n }),\n };\n }\n if (input.facts.keyVersion !== input.body.keyVersion) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: \"facts.keyVersion must equal body.keyVersion\",\n }),\n };\n }\n if (\n input.facts.encryptedSymmetricKeyHash !==\n input.body.encryptedSymmetricKeyHash\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message:\n \"facts.encryptedSymmetricKeyHash must equal body.encryptedSymmetricKeyHash\",\n }),\n };\n }\n if (\n input.facts.receiverPublicKeyHash !== input.body.receiverPublicKeyHash\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message:\n \"facts.receiverPublicKeyHash must equal body.receiverPublicKeyHash\",\n }),\n };\n }\n try {\n parseNetworkId(input.networkId);\n } catch (err) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_NETWORK_ID\",\n message: err instanceof Error ? err.message : String(err),\n }),\n };\n }\n const canonicalBody = canonicalize(\n input.body as unknown as CanonicalJson,\n );\n const expectedBodyHash = canonicalHashHex(crypto.sha256, input.body as unknown as CanonicalJson);\n if (expectedBodyHash !== input.facts.bodyHash) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message: \"facts.bodyHash does not match the canonical body hash\",\n }),\n };\n }\n return { ok: true, data: input, canonicalBody };\n}\n\n/**\n * Compose the high-level decrypt invocation and hand it to the signer\n * for UCAN minting. The signer returns the Authorization header value\n * plus the invocation CID; this function only validates and\n * orchestrates — it does not perform crypto signing itself.\n */\nexport async function buildDecryptInvocation(\n crypto: EncryptionCrypto,\n signer: DecryptInvocationSigner,\n input: BuildDecryptInvocationInput,\n): Promise<{ ok: true; data: BuiltDecryptInvocation } | { ok: false; error: EncryptionError }> {\n const checked = checkDecryptInvocationInput(crypto, input);\n if (!checked.ok) {\n return checked;\n }\n try {\n const built = await signer.signDecryptInvocation(checked.data);\n if (!built.authorization || !built.invocationCid) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message:\n \"decrypt-invocation signer returned an empty authorization or invocationCid\",\n }),\n };\n }\n if (built.canonicalBody !== checked.canonicalBody) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_INPUT\",\n message:\n \"decrypt-invocation signer returned a canonicalBody that does not match the SDK's canonicalization — signer must use the SDK-provided body\",\n }),\n };\n }\n return { ok: true, data: built };\n } catch (err) {\n return {\n ok: false,\n error: encryptionError({\n code: \"TRANSPORT_ERROR\",\n cause: err instanceof Error ? err : new Error(String(err)),\n message: `failed to sign decrypt invocation: ${\n err instanceof Error ? err.message : String(err)\n }`,\n }),\n };\n }\n}\n\n/** Re-export so callers can introspect the service+action constants. */\nexport { DECRYPT_ACTION, ENCRYPTION_SERVICE };\n","/**\n * Per-request receiver key generation.\n *\n * The receiver key pair is generated for a single decrypt request: the\n * SDK sends `receiverPublicKey` to the node so the node can rewrap the\n * symmetric key; the matching private key never leaves the SDK.\n *\n * Two derivation modes are supported:\n *\n * 1. **Random** — `crypto.randomBytes(32)` seeds a fresh x25519 pair.\n * This is the default for one-of-one flows.\n *\n * 2. **Signed-context** — the caller provides a signer that signs a\n * deterministic context message (network id + nonce + invocation\n * intent). The signature bytes are SHA-256'd into the seed. This is\n * useful when callers want the receiver key to be reproducible by\n * the same session signer (e.g. for delegated reads where the\n * signer is the only stable secret).\n */\n\nimport { utf8Encode } from \"./canonical\";\nimport type {\n EncryptionCrypto,\n ReceiverKeyPair,\n ReceiverKeySigner,\n} from \"./types\";\n\nexport interface RandomReceiverKeyInput {\n crypto: EncryptionCrypto;\n}\n\nexport function generateRandomReceiverKey(\n input: RandomReceiverKeyInput,\n): ReceiverKeyPair {\n const seed = input.crypto.randomBytes(32);\n return input.crypto.x25519FromSeed(seed);\n}\n\nexport interface SignedReceiverKeyInput {\n crypto: EncryptionCrypto;\n signer: ReceiverKeySigner;\n networkId: string;\n /** Optional extra context (e.g. invocation nonce) folded into the message. */\n context?: string;\n}\n\n/**\n * Deterministic receiver-key derivation: signs a context string with\n * the supplied signer, then SHA-256s the signature bytes into the\n * x25519 seed.\n *\n * The context message is:\n * `tinycloud.encryption.receiver-key/v1:<networkId>:<context>`\n *\n * Callers MUST include unique context (e.g. a fresh nonce) on every\n * request unless they explicitly want reproducibility.\n */\nexport async function deriveSignedReceiverKey(\n input: SignedReceiverKeyInput,\n): Promise<ReceiverKeyPair> {\n const message = `tinycloud.encryption.receiver-key/v1:${input.networkId}:${input.context ?? \"\"}`;\n const sig = await input.signer.signMessage(message);\n // Treat the signature as opaque bytes; sha256 collapses to a 32-byte seed.\n const sigBytes = utf8Encode(sig);\n const seed = input.crypto.sha256(sigBytes);\n return input.crypto.x25519FromSeed(seed);\n}\n","/**\n * Decrypt-response verification.\n *\n * The node returns the unwrapped symmetric key re-encrypted to the\n * per-request receiver public key. Before the SDK uses the wrapped\n * key, it must:\n *\n * 1. Verify the node signature over the canonical response (excluding\n * the signature field).\n * 2. Recompute every binding hash and reject any mismatch.\n * 3. Confirm `targetNode`, `networkId`, `alg`, and `keyVersion` echo\n * what the SDK sent.\n *\n * After verification, the SDK opens `wrappedKey` with the per-request\n * receiver private key and uses the resulting symmetric key to\n * decrypt the inline envelope payload.\n */\n\nimport { base64Decode, canonicalize, hexEncode, utf8Encode } from \"./canonical\";\nimport {\n DECRYPT_RESULT_TYPE,\n encryptionError,\n type CanonicalJson,\n type DecryptInvocationFact,\n type DecryptRequestBody,\n type DecryptResponseBody,\n type EncryptionCrypto,\n type EncryptionError,\n} from \"./types\";\n\n/**\n * Construct the canonical bytes that the node signed.\n *\n * The signature covers the response with `nodeSignature` removed. We\n * canonicalize and hash the same way the node does so the binding is\n * stable.\n */\nexport function canonicalSignedResponse(\n response: DecryptResponseBody,\n): string {\n // Strip the signature; canonicalize sorts keys for us.\n const { nodeSignature: _drop, ...rest } = response;\n return canonicalize(rest as unknown as CanonicalJson);\n}\n\nexport interface VerifyDecryptResponseInput {\n crypto: EncryptionCrypto;\n request: DecryptRequestBody;\n facts: DecryptInvocationFact;\n /** CID of the signed invocation that produced this response. */\n invocationCid: string;\n /** Hex bodyHash that was bound in `facts.bodyHash`. */\n requestBodyHash: string;\n response: DecryptResponseBody;\n}\n\n/**\n * Verify the node's decrypt response. Returns the response on success;\n * a structured error on signature, binding, or shape failure.\n */\nexport function verifyDecryptResponse(\n input: VerifyDecryptResponseInput,\n):\n | { ok: true; data: DecryptResponseBody }\n | { ok: false; error: EncryptionError } {\n const { crypto, request, facts, invocationCid, requestBodyHash, response } =\n input;\n\n if (response.type !== DECRYPT_RESULT_TYPE) {\n return {\n ok: false,\n error: encryptionError({\n code: \"INVALID_RESPONSE\",\n message: `response.type must be ${DECRYPT_RESULT_TYPE}`,\n }),\n };\n }\n if (response.targetNode !== request.targetNode) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"targetNode\",\n }),\n };\n }\n if (response.networkId !== request.networkId) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"networkId\",\n }),\n };\n }\n if (response.nodeId !== request.targetNode) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"nodeId\",\n }),\n };\n }\n if (response.alg !== request.alg) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"alg\",\n }),\n };\n }\n if (response.keyVersion !== request.keyVersion) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"keyVersion\",\n }),\n };\n }\n if (\n response.encryptedSymmetricKeyHash !==\n request.encryptedSymmetricKeyHash\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"encryptedSymmetricKeyHash\",\n }),\n };\n }\n if (response.receiverPublicKeyHash !== request.receiverPublicKeyHash) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"receiverPublicKeyHash\",\n }),\n };\n }\n if (response.invocationCid !== invocationCid) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"invocationCid\",\n }),\n };\n }\n // requestHash binds invocationCid || requestBodyHash per spec. The `||`\n // notation is concatenation, not a literal delimiter.\n const expectedRequestHash = hexEncode(\n crypto.sha256(utf8Encode(`${invocationCid}${requestBodyHash}`)),\n );\n if (response.requestHash !== expectedRequestHash) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"requestHash\",\n }),\n };\n }\n // The facts must agree with the response (defensive: catches a node\n // that returns a fresh body bound to a different invocation).\n if (\n facts.encryptedSymmetricKeyHash !== response.encryptedSymmetricKeyHash ||\n facts.receiverPublicKeyHash !== response.receiverPublicKeyHash ||\n facts.networkId !== response.networkId ||\n facts.targetNode !== response.targetNode ||\n facts.alg !== response.alg ||\n facts.keyVersion !== response.keyVersion\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_BINDING_MISMATCH\",\n field: \"facts\",\n }),\n };\n }\n\n const signedBytes = new TextEncoder().encode(\n canonicalSignedResponse(response),\n );\n const signatureBytes = base64Decode(response.nodeSignature);\n if (\n !crypto.verifyNodeSignature(response.nodeId, signedBytes, signatureBytes)\n ) {\n return {\n ok: false,\n error: encryptionError({\n code: \"RESPONSE_SIGNATURE_INVALID\",\n }),\n };\n }\n return { ok: true, data: response };\n}\n\n/**\n * After verification, open the response's `wrappedKey` with the\n * per-request receiver private key and return the symmetric key.\n */\nexport function openWrappedKey(\n crypto: EncryptionCrypto,\n receiverPrivateKey: Uint8Array,\n response: DecryptResponseBody,\n): Uint8Array {\n const wrapped = base64Decode(response.wrappedKey);\n return crypto.openWithReceiverKey(receiverPrivateKey, wrapped);\n}\n","/**\n * EncryptionService — TinyCloud one-of-one encryption service.\n *\n * Responsibilities:\n * - Network discovery (`discoverNetwork`).\n * - Local envelope encryption (`encryptToNetwork`).\n * - Node-mediated decrypt with full request/response binding\n * verification (`decryptEnvelope`).\n *\n * Non-responsibilities:\n * - KV/SQL access. Callers fetch encrypted envelopes from their data\n * service of choice and pass them in.\n * - Network onboarding/ceremony. Those routes are node-only.\n */\n\nimport { BaseService } from \"../base/BaseService\";\nimport { type Result } from \"../types\";\nimport {\n base64Decode,\n base64Encode,\n canonicalHashHex,\n} from \"./canonical\";\nimport {\n discoverNetwork as discoverNetworkFn,\n ensureNetworkUsableForDecrypt,\n type NodeDescriptorFetcher,\n type WellKnownDescriptorFetcher,\n} from \"./discovery\";\nimport {\n decryptEnvelopeWithKey,\n encryptToNetwork as encryptToNetworkFn,\n validateEnvelope,\n} from \"./envelope\";\nimport {\n buildCanonicalDecryptRequest,\n buildDecryptFacts,\n buildDecryptInvocation,\n} from \"./invocation\";\nimport { generateRandomReceiverKey } from \"./receiverKey\";\nimport {\n openWrappedKey,\n verifyDecryptResponse,\n} from \"./response\";\nimport {\n DECRYPT_FACT_TYPE,\n encryptionError,\n type DecryptCapabilityProof,\n type DecryptInvocationSigner,\n type DecryptRequestBody,\n type DecryptResponseBody,\n type EncryptionCrypto,\n type EncryptionError,\n type InlineEncryptedEnvelope,\n type NetworkDescriptor,\n toError,\n} from \"./types\";\nimport type {\n EncryptToNetworkOptions,\n DecryptEnvelopeOptions,\n IEncryptionService,\n} from \"./IEncryptionService\";\n\n// Local Result helpers typed to EncryptionError. The shared `ok` / `err`\n// from `../types` default the error generic to `ServiceError`, which\n// widens our return-type inference here.\nfunction encOk<T>(data: T): Result<T, EncryptionError> {\n return { ok: true, data };\n}\nfunction encErr<T = never>(error: EncryptionError): Result<T, EncryptionError> {\n return { ok: false, error };\n}\n\n/**\n * Transport for posting decrypt requests to a TinyCloud node.\n *\n * Implementations supply the `Authorization` header (built by the\n * decrypt-invocation signer) and POST the canonical body. The\n * response body is JSON-decoded into a {@link DecryptResponseBody}.\n */\nexport interface DecryptTransport {\n postDecrypt(input: {\n targetNode: string;\n networkId: string;\n authorization: string;\n canonicalBody: string;\n }): Promise<DecryptResponseBody>;\n}\n\nexport interface EncryptionServiceConfig {\n crypto: EncryptionCrypto;\n signer: DecryptInvocationSigner;\n transport: DecryptTransport;\n node?: NodeDescriptorFetcher;\n wellKnown?: WellKnownDescriptorFetcher;\n [key: string]: unknown;\n}\n\nexport class EncryptionService\n extends BaseService\n implements IEncryptionService\n{\n static readonly serviceName = \"encryption\";\n\n declare protected _config: EncryptionServiceConfig;\n\n constructor(config: EncryptionServiceConfig) {\n super();\n this._config = config;\n }\n\n get config(): EncryptionServiceConfig {\n return this._config;\n }\n\n private get crypto(): EncryptionCrypto {\n return this._config.crypto;\n }\n\n async discoverNetwork(\n identifier: string,\n ownerDid?: string,\n ): Promise<Result<NetworkDescriptor, EncryptionError>> {\n const result = await discoverNetworkFn({\n identifier,\n ...(ownerDid !== undefined ? { ownerDid } : {}),\n ...(this._config.node !== undefined ? { node: this._config.node } : {}),\n ...(this._config.wellKnown !== undefined\n ? { wellKnown: this._config.wellKnown }\n : {}),\n });\n if (!result.ok) return result;\n return encOk(result.data.descriptor);\n }\n\n async encryptToNetwork(\n networkId: string,\n plaintext: Uint8Array,\n options?: EncryptToNetworkOptions,\n ): Promise<Result<InlineEncryptedEnvelope, EncryptionError>> {\n try {\n const discovered = await this.discoverNetwork(networkId);\n if (!discovered.ok) return discovered;\n const usable = ensureNetworkUsableForDecrypt(discovered.data);\n // For encryption we tolerate \"rotating\" but reject revoked/failed/pending —\n // ensureNetworkUsableForDecrypt enforces exactly that constraint.\n if (!usable.ok) return usable;\n\n const descriptor = usable.data;\n const networkPublicKey = base64Decode(descriptor.publicEncryptionKey);\n const result = encryptToNetworkFn(this.crypto, {\n networkId,\n networkPublicKey,\n plaintext,\n ...(options?.aad !== undefined ? { aad: options.aad } : {}),\n alg: options?.alg ?? descriptor.alg,\n keyVersion: options?.keyVersion ?? descriptor.keyVersion,\n ...(options?.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n return encOk(result.envelope);\n } catch (error) {\n return encErr(\n encryptionError({\n code: \"TRANSPORT_ERROR\",\n cause: toError(error),\n }),\n );\n }\n }\n\n async decryptEnvelope(\n envelope: InlineEncryptedEnvelope,\n capabilityProof: DecryptCapabilityProof,\n options?: DecryptEnvelopeOptions,\n ): Promise<Result<Uint8Array, EncryptionError>> {\n try {\n const validated = validateEnvelope(this.crypto, envelope);\n if (!validated.ok) return validated;\n if (\n options?.aad !== undefined &&\n validated.data.aad !== base64Encode(options.aad)\n ) {\n return encErr(\n encryptionError({\n code: \"INVALID_INPUT\",\n message: \"decryptEnvelope aad does not match the envelope\",\n }),\n );\n }\n\n let descriptor: NetworkDescriptor;\n if (options?.descriptor !== undefined) {\n descriptor = options.descriptor;\n } else {\n const discovered = await this.discoverNetwork(envelope.networkId);\n if (!discovered.ok) return discovered;\n descriptor = discovered.data;\n }\n const usable = ensureNetworkUsableForDecrypt(descriptor);\n if (!usable.ok) return usable;\n\n const targetNode =\n options?.targetNode ?? descriptor.members[0]?.nodeId;\n if (targetNode === undefined) {\n return encErr(\n encryptionError({\n code: \"INVALID_INPUT\",\n message: \"no target node available from descriptor\",\n }),\n );\n }\n\n // Generate per-request receiver key. We use the random mode by\n // default; callers wanting deterministic derivation must wrap\n // this service directly.\n const receiverKey = generateRandomReceiverKey({ crypto: this.crypto });\n const receiverPublicKey = base64Encode(receiverKey.publicKey);\n const receiverPublicKeyHash = canonicalHashHex(\n this.crypto.sha256,\n receiverPublicKey,\n );\n\n const body: DecryptRequestBody = {\n type: DECRYPT_FACT_TYPE,\n targetNode,\n networkId: envelope.networkId,\n alg: envelope.alg,\n keyVersion: envelope.keyVersion,\n encryptedSymmetricKey: envelope.encryptedSymmetricKey,\n encryptedSymmetricKeyHash: envelope.encryptedSymmetricKeyHash,\n receiverPublicKey,\n receiverPublicKeyHash,\n };\n const canonicalRequest = buildCanonicalDecryptRequest({\n crypto: this.crypto,\n body,\n receiverPublicKey: receiverKey.publicKey,\n });\n const facts = buildDecryptFacts({\n crypto: this.crypto,\n body,\n encryptedSymmetricKeyHash: envelope.encryptedSymmetricKeyHash,\n receiverPublicKey: receiverKey.publicKey,\n canonicalBody: canonicalRequest.canonicalBody,\n });\n\n const built = await buildDecryptInvocation(this.crypto, this._config.signer, {\n targetNode,\n networkId: envelope.networkId,\n body,\n facts,\n proof: capabilityProof,\n });\n if (!built.ok) return built;\n\n let response: DecryptResponseBody;\n try {\n response = await this._config.transport.postDecrypt({\n targetNode,\n networkId: envelope.networkId,\n authorization: built.data.authorization,\n canonicalBody: built.data.canonicalBody,\n });\n } catch (error) {\n return encErr(\n encryptionError({\n code: \"TRANSPORT_ERROR\",\n cause: toError(error),\n }),\n );\n }\n\n const verified = verifyDecryptResponse({\n crypto: this.crypto,\n request: body,\n facts,\n invocationCid: built.data.invocationCid,\n requestBodyHash: facts.bodyHash,\n response,\n });\n if (!verified.ok) return verified;\n\n const symmetricKey = openWrappedKey(\n this.crypto,\n receiverKey.privateKey,\n verified.data,\n );\n const plaintext = decryptEnvelopeWithKey(\n this.crypto,\n envelope,\n symmetricKey,\n );\n return encOk(plaintext);\n } catch (error) {\n return encErr(\n encryptionError({\n code: \"TRANSPORT_ERROR\",\n cause: toError(error),\n }),\n );\n }\n }\n}\n","import { CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport type { ProfileConfig } from \"../config/types.js\";\n\ninterface ParsedPkhDid {\n address: string;\n chainId: number;\n}\n\nfunction canonicalizeAddress(address: string): string {\n const trimmed = address.trim();\n return trimmed.startsWith(\"0x\")\n ? `0x${trimmed.slice(2).toLowerCase()}`\n : trimmed.toLowerCase();\n}\n\nfunction parsePkhDid(did: string): ParsedPkhDid | null {\n const match = did.match(/^did:pkh:eip155:(\\d+):(0x[a-fA-F0-9]{40})$/);\n if (!match) return null;\n return {\n chainId: Number(match[1]),\n address: canonicalizeAddress(match[2]),\n };\n}\n\nfunction makePkhSpaceId(address: string, chainId: number, name: string): string {\n return `tinycloud:pkh:eip155:${chainId}:${canonicalizeAddress(address)}:${name}`;\n}\n\nfunction parseSpaceUri(input: string): { owner: string; name: string } | null {\n if (!input.startsWith(\"tinycloud:\")) return null;\n const parts = input.split(\":\");\n if (parts.length < 3) return null;\n const name = parts.at(-1);\n if (!name) return null;\n return {\n owner: parts.slice(1, -1).join(\":\"),\n name,\n };\n}\n\nfunction buildSpaceUri(owner: string, name: string): string {\n return `tinycloud:${owner}:${name}`;\n}\n\n/**\n * Resolve the active profile's Ethereum address. Source priority matches\n * what TinyCloudNode.signIn / restoreSession actually populates:\n * 1) session.address (set by both local-key and OpenKey auth flows)\n * 2) profile.address (local-key auth only)\n * 3) the address segment of profile.ownerDid (did:pkh:eip155:<chain>:<addr>)\n */\nfunction resolveAddress(profile: ProfileConfig, session: Record<string, unknown> | null): string {\n const sessAddr = session?.address;\n if (typeof sessAddr === \"string\" && sessAddr.length > 0) {\n return canonicalizeAddress(sessAddr);\n }\n\n if (profile.address) return canonicalizeAddress(profile.address);\n\n if (profile.ownerDid) {\n const pkh = parsePkhDid(profile.ownerDid);\n if (pkh) return pkh.address;\n }\n\n throw new CLIError(\n \"ADDRESS_UNKNOWN\",\n `Cannot determine Ethereum address for profile \"${profile.name}\". Run \\`tc auth login\\` to refresh the session.`,\n ExitCode.AUTH_REQUIRED,\n );\n}\n\nfunction resolveChainId(profile: ProfileConfig, session: Record<string, unknown> | null): number {\n const sessChain = session?.chainId;\n if (typeof sessChain === \"number\" && Number.isFinite(sessChain)) return sessChain;\n return profile.chainId;\n}\n\n/**\n * Resolve a --space CLI argument into a full TinyCloud space URI.\n *\n * - undefined → undefined (caller falls back to node.spaceId)\n * - \"tinycloud:...\" → returned verbatim\n * - bare name → tinycloud:pkh:eip155:<chain>:<address>:<name>\n */\nexport async function resolveSpaceUri(\n input: string | undefined,\n profileName: string,\n): Promise<string | undefined> {\n if (!input) return undefined;\n if (input.startsWith(\"tinycloud:\")) {\n const parsed = parseSpaceUri(input);\n if (!parsed) {\n throw new CLIError(\n \"INVALID_SPACE\",\n `Invalid --space \"${input}\". Use a short name ([A-Za-z0-9_-]) or a full tinycloud:... URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n return buildSpaceUri(parsed.owner, parsed.name);\n }\n\n if (!/^[A-Za-z0-9_-]+$/.test(input)) {\n throw new CLIError(\n \"INVALID_SPACE\",\n `Invalid --space \"${input}\". Use a short name ([A-Za-z0-9_-]) or a full tinycloud:... URI.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const profile = await ProfileManager.getProfile(profileName);\n const session = (await ProfileManager.getSession(profileName)) as Record<string, unknown> | null;\n\n const address = resolveAddress(profile, session);\n const chainId = resolveChainId(profile, session);\n return makePkhSpaceId(address, chainId, input);\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 { resolveSpaceUri } from \"../lib/space.js\";\nimport { theme } from \"../output/theme.js\";\nimport type { TinyCloudNode } 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 * Pick a KV service for the requested space.\n *\n * `--space` is optional; when omitted, ops route through the node's primary\n * space (preserves prior behavior). When present, we use\n * TinyCloudNode.kvForSpace, which clones the active service context with a\n * session whose spaceId points at the target space — e.g. to read a manifest\n * app's data kept under the owner's `applications` space.\n */\nasync function kvHandle(\n node: TinyCloudNode,\n spaceInput: string | undefined,\n profileName: string,\n) {\n const spaceUri = await resolveSpaceUri(spaceInput, profileName);\n return spaceUri ? node.kvForSpace(spaceUri) : node.kv;\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 .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 kv = await kvHandle(node, options.space, ctx.profile);\n const result = await withSpinner(`Getting ${key}...`, () => 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 .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 kv = await kvHandle(node, options.space, ctx.profile);\n const listOptions = options.prefix ? { prefix: options.prefix } : undefined;\n const result = await withSpinner(\"Listing keys...\", () => 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 .option(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 kv = await kvHandle(node, options.space, ctx.profile);\n const result = await withSpinner(`Checking ${key}...`, () => 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 { 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\nfunction normalizeDid(input: string): string {\n const normalized = input.trim();\n const fragmentIndex = normalized.indexOf(\"#\");\n return (fragmentIndex === -1 ? normalized : normalized.slice(0, fragmentIndex)).toLowerCase();\n}\n\nfunction didMatches(actual: string | undefined, expected: string): boolean {\n if (!actual) return false;\n try {\n return normalizeDid(actual) === normalizeDid(expected);\n } catch {\n return actual === expected;\n }\n}\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) => didMatches(d.delegatorDID, myDid));\n } else if (options.received) {\n const myDid = node.did;\n delegations = delegations.filter((d: any) => didMatches(d.delegateDID, 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\";\nimport {\n CLI_OPERATOR_TYPES,\n CLI_PROFILE_POSTURES,\n isCLIOperatorType,\n isCLIProfilePosture,\n resolveProfileOperatorType,\n resolveProfilePosture,\n type CLIOperatorType,\n type CLIProfilePosture,\n} from \"../config/types.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 posture: resolveProfilePosture(p),\n operatorType: resolveProfileOperatorType(p),\n active: name === config.defaultProfile,\n };\n } catch {\n return {\n name,\n host: null,\n did: null,\n posture: null,\n operatorType: null,\n active: name === config.defaultProfile,\n };\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 const posture = p.posture ? theme.muted(String(p.posture)) : theme.muted(\"no posture\");\n process.stdout.write(`${marker}${name} ${host} ${posture}\\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 .option(\n \"--posture <posture>\",\n `Profile posture: ${CLI_PROFILE_POSTURES.join(\", \")}. Defaults to owner-openkey.`,\n )\n .option(\n \"--operator <type>\",\n `Operator type: ${CLI_OPERATOR_TYPES.join(\", \")}. Defaults to human.`,\n )\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 const posture = parseProfilePosture(options.posture);\n const operatorType = parseOperatorType(options.operator);\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 sessionDid: did,\n createdAt: new Date().toISOString(),\n posture,\n operatorType,\n });\n\n outputJson({ profile: name, did, host, posture, operatorType, 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 const posture = resolveProfilePosture(p);\n const operatorType = resolveProfileOperatorType(p);\n\n if (shouldOutputJson()) {\n outputJson({\n ...p,\n posture,\n operatorType,\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(\"Session DID\", p.sessionDid ?? null) + \"\\n\");\n process.stdout.write(formatField(\"Posture\", posture) + \"\\n\");\n process.stdout.write(formatField(\"Operator\", operatorType) + \"\\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\nfunction parseProfilePosture(raw: unknown): CLIProfilePosture {\n if (raw === undefined || raw === null || raw === \"\") return \"owner-openkey\";\n if (isCLIProfilePosture(raw)) return raw;\n throw new CLIError(\n \"INVALID_POSTURE\",\n `Invalid posture \"${String(raw)}\". Use one of: ${CLI_PROFILE_POSTURES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\n );\n}\n\nfunction parseOperatorType(raw: unknown): CLIOperatorType {\n if (raw === undefined || raw === null || raw === \"\") return \"human\";\n if (isCLIOperatorType(raw)) return raw;\n throw new CLIError(\n \"INVALID_OPERATOR\",\n `Invalid operator \"${String(raw)}\". Use one of: ${CLI_OPERATOR_TYPES.join(\", \")}.`,\n ExitCode.USAGE_ERROR,\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 rotate 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 rotate 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 rotate 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 { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport {\n type PermissionEntry,\n type PortableDelegation,\n type TinyCloudNode,\n} from \"@tinycloud/node-sdk\";\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 { resolveProfilePosture, type CLIContext, type ProfileConfig } from \"../config/types.js\";\nimport { ensureDelegationAuthority, refreshOpenKeySession } from \"./auth.js\";\n\nconst SECRETS_SPACE = \"secrets\";\ntype SecretAction = \"get\" | \"put\" | \"del\" | \"list\";\ntype SecretKvAbility =\n | \"tinycloud.kv/get\"\n | \"tinycloud.kv/put\"\n | \"tinycloud.kv/del\"\n | \"tinycloud.kv/list\";\nconst SECRET_KV_ABILITIES: Record<SecretAction, SecretKvAbility> = {\n get: \"tinycloud.kv/get\",\n put: \"tinycloud.kv/put\",\n del: \"tinycloud.kv/del\",\n list: \"tinycloud.kv/list\",\n};\ntype SecretResult<T> =\n | { ok: true; data: T }\n | { ok: false; error: { code: string; message: string; service?: string } };\n\ninterface SecretScopeOptions {\n scope?: string;\n}\n\ninterface DelegationCandidate {\n delegation: PortableDelegation;\n permissions: PermissionEntry[];\n}\n\ninterface ResolvedDelegatedSecretSource extends DelegationCandidate {\n source: string;\n}\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\nfunction authOptions(options: { privateKey?: string }): { privateKey?: string } | undefined {\n const privateKey = options.privateKey || process.env.TC_PRIVATE_KEY;\n return privateKey ? { privateKey } : undefined;\n}\n\nfunction resolveSecretScope(options: { scope?: string; space?: string }): { scope?: string } | undefined {\n const scope = options.scope ?? options.space;\n return scope ? { scope } : undefined;\n}\n\nconst SECRET_NAME_RE = /^[A-Z][A-Z0-9_]*$/;\nconst RESERVED_SECRET_SCOPES = new Set([\"default\", \"global\"]);\n\nfunction canonicalizeSecretScope(scope: string | undefined): string | undefined {\n if (scope === undefined) return undefined;\n\n const trimmed = scope.trim();\n if (trimmed === \"\") {\n throw new CLIError(\n \"INVALID_SECRET_SCOPE\",\n \"Secret scope must be non-empty; omit scope for global secrets.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const canonical = trimmed\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n\n if (canonical === \"\") {\n throw new CLIError(\n \"INVALID_SECRET_SCOPE\",\n \"Secret scope must contain at least one letter or number.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n if (RESERVED_SECRET_SCOPES.has(canonical)) {\n throw new CLIError(\n \"INVALID_SECRET_SCOPE\",\n `Secret scope ${JSON.stringify(scope)} is reserved; omit scope for global secrets.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n return canonical;\n}\n\nfunction resolveSecretPath(\n name: string,\n options: SecretScopeOptions = {},\n): { name: string; scope?: string; vaultKey: string; permissionPaths: { vault: string } } {\n const normalizedName = name.trim();\n if (!SECRET_NAME_RE.test(normalizedName)) {\n throw new CLIError(\n \"INVALID_SECRET_NAME\",\n `Invalid secret name ${JSON.stringify(name)}. Secret names must match ${SECRET_NAME_RE.source}.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const scope = canonicalizeSecretScope(options.scope);\n const vaultKey = scope === undefined\n ? `secrets/${normalizedName}`\n : `secrets/scoped/${scope}/${normalizedName}`;\n\n return {\n name: normalizedName,\n ...(scope !== undefined ? { scope } : {}),\n vaultKey,\n permissionPaths: {\n vault: `vault/${vaultKey}`,\n },\n };\n}\n\nfunction resolveSecretListPrefix(options: SecretScopeOptions = {}): string {\n const scope = canonicalizeSecretScope(options.scope);\n return scope === undefined\n ? \"vault/secrets/\"\n : `vault/secrets/scoped/${scope}/`;\n}\n\nfunction resolveProfilesDir(): string {\n const home = process.env.TC_HOME ?? process.env.HOME ?? process.env.USERPROFILE ?? homedir();\n return join(home, \".tinycloud\", \"profiles\");\n}\n\nasync function ensureSecretsNode(\n ctx: CLIContext,\n options: { privateKey?: string },\n): Promise<TinyCloudNode> {\n const auth = authOptions(options);\n if (auth?.privateKey) {\n return ensureAuthenticated(ctx, auth);\n }\n\n const profile = await ProfileManager.getProfile(ctx.profile).catch(() => null);\n if (profile?.authMethod === \"openkey\" && canRequestOwnerPermissions(profile)) {\n const session = await ProfileManager.getSession(ctx.profile);\n if (!session || isStoredSessionExpired(session)) {\n await withSpinner(\n session ? \"Refreshing TinyCloud session...\" : \"Creating TinyCloud session...\",\n () => refreshOpenKeySession(ctx.profile, ctx.host),\n );\n }\n }\n\n return ensureAuthenticated(ctx, auth);\n}\n\nasync function runSecretOperation<T>(params: {\n ctx: CLIContext;\n node: TinyCloudNode;\n action: SecretAction;\n name?: string;\n scopeOptions?: SecretScopeOptions;\n label: string;\n operation: () => Promise<SecretResult<T>>;\n}): Promise<SecretResult<T>> {\n const first = await runSecretOperationAttempt(params.label, params.operation);\n if (first.ok || !shouldRequestSecretPermissions(first.error)) {\n return first;\n }\n\n const profile = await ProfileManager.getProfile(params.ctx.profile);\n if (!canRequestOwnerPermissions(profile)) {\n return first;\n }\n\n const requested = secretPermissionEntries({\n action: params.action,\n name: params.name,\n options: params.scopeOptions,\n node: params.node,\n });\n await withSpinner(\"Requesting secret permissions...\", () =>\n ensureDelegationAuthority({\n ctx: params.ctx,\n profile,\n node: params.node,\n requested,\n expiryOption: undefined,\n yes: true,\n force: true,\n }),\n );\n\n return runSecretOperationAttempt(params.label, params.operation);\n}\n\nasync function runSecretOperationAttempt<T>(\n label: string,\n operation: () => Promise<SecretResult<T>>,\n): Promise<SecretResult<T>> {\n try {\n return await withSpinner(label, operation);\n } catch (error) {\n const permissionError = thrownPermissionError(error);\n if (permissionError) return permissionError;\n throw error;\n }\n}\n\nfunction canRequestOwnerPermissions(profile: ProfileConfig): boolean {\n const posture = resolveProfilePosture(profile);\n return posture === \"owner-openkey\" || posture === \"local-owner-key\";\n}\n\nfunction shouldRequestSecretPermissions(error: { code: string; message: string }): boolean {\n if (error.code !== \"PERMISSION_DENIED\") return false;\n return /permission|session expired|autosign|capabilit/i.test(error.message);\n}\n\nfunction thrownPermissionError<T>(error: unknown): SecretResult<T> | null {\n const record = error as { code?: unknown; message?: unknown };\n const message = typeof record?.message === \"string\" ? record.message : String(error);\n const code = typeof record?.code === \"string\" ? record.code : \"PERMISSION_DENIED\";\n if (code !== \"PERMISSION_DENIED\" && !/permission|session expired|autosign|capabilit/i.test(message)) {\n return null;\n }\n\n return {\n ok: false,\n error: {\n code: \"PERMISSION_DENIED\",\n message,\n },\n };\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n const typed = error as NodeJS.ErrnoException | null;\n return typed?.code === \"ENOENT\";\n}\n\nfunction hasPermissionAction(actions: string[], action: string): boolean {\n return actions.some(\n (entry) =>\n entry === action ||\n entry.endsWith(`/${action.split(\"/\").at(-1)}`) ||\n entry === action.split(\"/\").at(-1),\n );\n}\n\nfunction delegationCoversPath(\n permissions: PermissionEntry[],\n path: string,\n): boolean {\n return permissions.some((permission) => {\n if (permission.service !== \"tinycloud.kv\") return false;\n if (!permissionTargetsSecretsSpace(permission)) return false;\n if (!hasPermissionAction(permission.actions, \"tinycloud.kv/get\")) return false;\n return permission.path === path || (permission.path.endsWith(\"/\") && path.startsWith(permission.path));\n });\n}\n\nfunction permissionTargetsSecretsSpace(permission: PermissionEntry): boolean {\n if (permission.service !== \"tinycloud.kv\") return false;\n if (typeof permission.space !== \"string\") return false;\n const space = permission.space.trim().toLowerCase();\n if (space === \"\") return false;\n return space === SECRETS_SPACE || space.endsWith(`:${SECRETS_SPACE}`);\n}\n\nfunction delegationCoversDecrypt(\n permissions: PermissionEntry[],\n networkId: string,\n): boolean {\n return permissions.some((permission) => {\n if (permission.service !== \"tinycloud.encryption\") return false;\n if (!hasPermissionAction(permission.actions, \"tinycloud.encryption/decrypt\")) return false;\n return permission.path === networkId;\n });\n}\n\nfunction parseDelegationExpiry(expiry: unknown): Date {\n const parsed =\n expiry instanceof Date\n ? expiry\n : typeof expiry === \"number\"\n ? new Date(expiry)\n : new Date(String(expiry));\n if (Number.isNaN(parsed.getTime())) {\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n \"Delegation must include a valid expiry.\",\n ExitCode.USAGE_ERROR,\n );\n }\n return parsed;\n}\n\nfunction normalizePortableDelegation(value: unknown): PortableDelegation {\n if (value === null || typeof value !== \"object\") {\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n \"Delegation source must contain a PortableDelegation object.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n const candidate = value as Partial<PortableDelegation> & {\n expiry?: unknown;\n delegationHeader?: unknown;\n };\n const authorization = candidate.delegationHeader as { Authorization?: unknown } | undefined;\n if (\n typeof candidate.cid !== \"string\" ||\n typeof candidate.spaceId !== \"string\" ||\n typeof candidate.path !== \"string\" ||\n !Array.isArray(candidate.actions) ||\n typeof candidate.delegateDID !== \"string\" ||\n typeof candidate.ownerAddress !== \"string\" ||\n typeof candidate.chainId !== \"number\" ||\n typeof authorization !== \"object\" ||\n authorization === null ||\n typeof authorization.Authorization !== \"string\"\n ) {\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n \"Delegation source must contain a PortableDelegation object.\",\n ExitCode.USAGE_ERROR,\n );\n }\n\n return {\n ...candidate,\n actions: [...candidate.actions],\n expiry: parseDelegationExpiry(candidate.expiry),\n delegationHeader: { Authorization: authorization.Authorization },\n } as PortableDelegation;\n}\n\nfunction normalizeDelegationCandidates(\n value: unknown,\n source: string,\n): DelegationCandidate[] {\n if (Array.isArray(value)) {\n return value.flatMap((entry) => normalizeDelegationCandidates(entry, source));\n }\n\n if (value === null || typeof value !== \"object\") {\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n `Delegation source \"${source}\" must be a delegation file or imported profile reference.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const candidate = value as Record<string, unknown> & {\n delegation?: unknown;\n permissions?: PermissionEntry[];\n };\n\n if (candidate.delegation !== undefined) {\n const delegation = normalizePortableDelegation(candidate.delegation);\n return [{\n delegation,\n permissions: Array.isArray(candidate.permissions) && candidate.permissions.length > 0\n ? candidate.permissions\n : permissionsFromDelegation(delegation),\n }];\n }\n\n const delegation = normalizePortableDelegation(candidate);\n return [{\n delegation,\n permissions: permissionsFromDelegation(delegation),\n }];\n}\n\nfunction permissionsFromDelegation(delegation: PortableDelegation): PermissionEntry[] {\n if (delegation.resources?.length) {\n return delegation.resources.map((resource) => ({\n service: resource.service.startsWith(\"tinycloud.\")\n ? resource.service\n : `tinycloud.${resource.service}`,\n space: resource.space,\n path: resource.path,\n actions: [...resource.actions],\n }));\n }\n\n const service = delegation.actions[0]?.includes(\"/\")\n ? delegation.actions[0].slice(0, delegation.actions[0].indexOf(\"/\"))\n : \"tinycloud.unknown\";\n\n return [{\n service,\n space: delegation.spaceId,\n path: delegation.path,\n actions: [...delegation.actions],\n }];\n}\n\nasync function loadDelegationCandidates(source: string): Promise<DelegationCandidate[]> {\n try {\n const raw = JSON.parse(await readFile(source, \"utf8\")) as unknown;\n return normalizeDelegationCandidates(raw, source);\n } catch (error) {\n if (!isMissingFileError(error)) {\n if (error instanceof SyntaxError) {\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n `Delegation source \"${source}\" must be valid JSON.`,\n ExitCode.USAGE_ERROR,\n );\n }\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n `Delegation source \"${source}\" could not be read.`,\n ExitCode.USAGE_ERROR,\n );\n }\n }\n\n try {\n const importedPath = join(resolveProfilesDir(), source, \"additional-delegations.json\");\n const raw = JSON.parse(await readFile(importedPath, \"utf8\")) as unknown;\n return normalizeDelegationCandidates(raw, source);\n } catch (error) {\n if (isMissingFileError(error)) {\n return [];\n }\n if (error instanceof SyntaxError) {\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n `Delegation source \"${source}\" must be valid JSON.`,\n ExitCode.USAGE_ERROR,\n );\n }\n throw new CLIError(\n \"INVALID_DELEGATION_SOURCE\",\n `Delegation source \"${source}\" could not be read.`,\n ExitCode.USAGE_ERROR,\n );\n }\n}\n\nfunction selectDelegationCandidate(\n candidates: DelegationCandidate[],\n source: string,\n secretPath: string,\n): DelegationCandidate {\n const liveCandidates = candidates.filter((candidate) => candidate.delegation.expiry.getTime() > Date.now());\n if (liveCandidates.length === 0) {\n throw new CLIError(\n \"DELEGATION_EXPIRED\",\n `Delegation source \"${source}\" has no live delegations.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n\n const secretsSpaceCandidates = liveCandidates.filter((candidate) =>\n candidate.permissions.some(permissionTargetsSecretsSpace)\n );\n if (secretsSpaceCandidates.length === 0) {\n throw new CLIError(\n \"PERMISSION_DENIED\",\n `Delegation source \"${source}\" does not target the secrets space.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n\n const exact = secretsSpaceCandidates.find((candidate) => delegationCoversPath(candidate.permissions, secretPath));\n if (exact) {\n return exact;\n }\n\n throw new CLIError(\n \"PERMISSION_DENIED\",\n `Delegation source \"${source}\" does not cover secret \"${secretPath}\".`,\n ExitCode.PERMISSION_DENIED,\n );\n}\n\nasync function resolveDelegatedSecretSource(\n source: string,\n secretPath: string,\n): Promise<ResolvedDelegatedSecretSource> {\n const candidates = await loadDelegationCandidates(source);\n if (candidates.length === 0) {\n throw new CLIError(\n \"DELEGATION_NOT_FOUND\",\n `Delegation source \"${source}\" did not resolve to any imported delegations.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n\n const selected = selectDelegationCandidate(candidates, source, secretPath);\n return { ...selected, source };\n}\n\nfunction mapEncryptionResultError(error: { code: string; message: string }): CLIError {\n const code = error.code || \"DECRYPTION_FAILED\";\n const exitCode =\n code === \"PERMISSION_DENIED\" ? ExitCode.PERMISSION_DENIED :\n code === \"NOT_FOUND\" ? ExitCode.NOT_FOUND :\n code === \"NETWORK_ERROR\" || code === \"TRANSPORT_ERROR\" ? ExitCode.NETWORK_ERROR :\n ExitCode.ERROR;\n\n return new CLIError(code, error.message, exitCode);\n}\n\nfunction parseDecryptedSecretPayload(\n data: Uint8Array,\n secretPath: string,\n): string {\n const text = new TextDecoder().decode(data);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new CLIError(\n \"INVALID_SECRET_PAYLOAD\",\n `Delegated secret \"${secretPath}\" did not decrypt to valid JSON.`,\n ExitCode.ERROR,\n );\n }\n\n if (parsed === null || typeof parsed !== \"object\" || typeof (parsed as { value?: unknown }).value !== \"string\") {\n throw new CLIError(\n \"INVALID_SECRET_PAYLOAD\",\n `Delegated secret \"${secretPath}\" did not decrypt to { value: string }.`,\n ExitCode.ERROR,\n );\n }\n\n return (parsed as { value: string }).value;\n}\n\nasync function readDelegatedSecretValue(params: {\n node: TinyCloudNode;\n delegation: PortableDelegation;\n delegationCid: string;\n permissions: PermissionEntry[];\n secretPath: string;\n name: string;\n}): Promise<string> {\n if (!delegationCoversPath(params.permissions, params.secretPath)) {\n throw new CLIError(\n \"PERMISSION_DENIED\",\n `Delegation \"${params.delegationCid}\" does not cover secret \"${params.secretPath}\".`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n\n const access = await params.node.useDelegation(params.delegation);\n if (typeof access?.kv?.get !== \"function\") {\n throw new CLIError(\n \"DELEGATION_INVALID\",\n `Delegation \"${params.delegationCid}\" did not resolve delegated KV access.`,\n ExitCode.ERROR,\n );\n }\n\n const envelopeResult = await access.kv.get<unknown>(params.secretPath, {\n raw: true,\n prefix: \"\",\n });\n\n if (!envelopeResult.ok) {\n if (\n envelopeResult.error.code === \"NOT_FOUND\" ||\n envelopeResult.error.code === \"KEY_NOT_FOUND\" ||\n envelopeResult.error.code === \"KV_NOT_FOUND\"\n ) {\n throw new CLIError(\n \"NOT_FOUND\",\n `Secret \"${params.name}\" not found`,\n ExitCode.NOT_FOUND,\n );\n }\n if (envelopeResult.error.code === \"PERMISSION_DENIED\") {\n throw new CLIError(\n \"PERMISSION_DENIED\",\n `Delegation \"${params.delegationCid}\" does not cover secret \"${params.secretPath}\".`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n throw new CLIError(\n envelopeResult.error.code,\n envelopeResult.error.message,\n ExitCode.ERROR,\n );\n }\n\n const rawEnvelope = envelopeResult.data.data;\n if (typeof rawEnvelope !== \"string\") {\n throw new CLIError(\n \"INVALID_ENVELOPE\",\n `Secret \"${params.secretPath}\" did not contain an encrypted envelope.`,\n ExitCode.ERROR,\n );\n }\n\n let envelope: Record<string, unknown>;\n try {\n envelope = JSON.parse(rawEnvelope) as Record<string, unknown>;\n } catch {\n throw new CLIError(\n \"INVALID_ENVELOPE\",\n `Secret \"${params.secretPath}\" did not contain an encrypted envelope.`,\n ExitCode.ERROR,\n );\n }\n\n const networkId = envelope.networkId;\n if (typeof networkId !== \"string\") {\n throw new CLIError(\n \"INVALID_ENVELOPE\",\n `Secret \"${params.secretPath}\" did not contain an encrypted envelope.`,\n ExitCode.ERROR,\n );\n }\n\n if (!delegationCoversDecrypt(params.permissions, networkId)) {\n throw new CLIError(\n \"PERMISSION_DENIED\",\n `Delegation \"${params.delegationCid}\" does not include tinycloud.encryption/decrypt for ${networkId}.`,\n ExitCode.PERMISSION_DENIED,\n );\n }\n\n const decrypted = await params.node.encryption.decryptEnvelope(\n envelope as never,\n { proofs: [params.delegationCid] },\n );\n if (!decrypted.ok) {\n throw mapEncryptionResultError(decrypted.error);\n }\n\n return parseDecryptedSecretPayload(decrypted.data, params.secretPath);\n}\n\nfunction isStoredSessionExpired(session: object): boolean {\n const record = session as Record<string, unknown>;\n const direct = parseDate(record.expiresAt ?? record.expiry ?? record.expirationTime);\n if (direct) return direct.getTime() <= Date.now();\n if (typeof record.siwe !== \"string\") return false;\n const match = record.siwe.match(/^Expiration Time:\\s*(.+)$/im);\n const expiry = match ? parseDate(match[1].trim()) : null;\n return expiry !== null && expiry.getTime() <= Date.now();\n}\n\nfunction parseDate(value: unknown): Date | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value;\n }\n if (typeof value !== \"string\" || value.trim() === \"\") return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction secretKvAbility(action: SecretAction): SecretKvAbility {\n return SECRET_KV_ABILITIES[action];\n}\n\nfunction secretPermissionEntries(params: {\n action: SecretAction;\n name?: string;\n options?: SecretScopeOptions;\n node: TinyCloudNode;\n}): PermissionEntry[] {\n const path = params.action === \"list\"\n ? resolveSecretListPrefix(params.options)\n : resolveSecretPath(params.name ?? \"\", params.options).permissionPaths.vault;\n const permissions: PermissionEntry[] = [{\n service: \"tinycloud.kv\",\n space: SECRETS_SPACE,\n path,\n actions: [secretKvAbility(params.action)],\n skipPrefix: true,\n }];\n\n if (params.action === \"get\") {\n permissions.push({\n service: \"tinycloud.encryption\",\n path: params.node.getDefaultEncryptionNetworkId(),\n actions: [\"tinycloud.encryption/decrypt\"],\n skipPrefix: true,\n });\n }\n\n return permissions;\n}\n\nexport function registerSecretsCommand(program: Command): void {\n const secrets = program.command(\"secrets\").description(\"Encrypted secrets management\");\n\n const network = secrets\n .command(\"network\")\n .description(\"Manage the default secrets encryption network\");\n\n network\n .command(\"show [nameOrNetworkId]\")\n .description(\"Show a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (nameOrNetworkId: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const requested = nameOrNetworkId ?? \"default\";\n const networkId = requested.startsWith(\"urn:tinycloud:encryption:\")\n ? requested\n : node.getDefaultEncryptionNetworkId(requested);\n const descriptor = await withSpinner(\n \"Fetching encryption network...\",\n () => node.getEncryptionNetwork(requested),\n );\n outputJson({\n networkId,\n exists: descriptor !== null,\n ...(descriptor ? { descriptor } : {}),\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n network\n .command(\"init [name]\")\n .description(\"Create a secrets encryption network if needed\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(name ?? \"default\"),\n );\n outputJson({\n networkId: descriptor.networkId,\n state: descriptor.state,\n descriptor,\n });\n } catch (error) {\n handleError(error);\n }\n });\n\n // tc secrets list\n secrets\n .command(\"list\")\n .description(\"List secrets\")\n .option(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\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 node = await ensureSecretsNode(ctx, options);\n const scopeOptions = resolveSecretScope(options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"list\",\n scopeOptions,\n label: \"Listing secrets...\",\n operation: () => node.secrets.list(scopeOptions),\n });\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR);\n }\n\n const secretNames = Array.isArray(result.data) ? result.data : [];\n const scope = options.scope ?? options.space;\n\n outputJson({\n secrets: secretNames,\n count: secretNames.length,\n ...(scope ? { scope } : {}),\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(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\n .option(\"--raw\", \"Output raw value (no JSON wrapping)\")\n .option(\"--value-only\", \"Output only the secret value (alias for --raw)\")\n .option(\"-o, --output <file>\", \"Write value to file\")\n .option(\"--delegation <source>\", \"Delegation file path or imported profile name\")\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 scopeOptions = resolveSecretScope(options);\n const secretPath = resolveSecretPath(name, scopeOptions).permissionPaths.vault;\n\n if (options.delegation) {\n const delegated = await resolveDelegatedSecretSource(options.delegation, secretPath);\n const effectiveHost = globalOpts.host ?? delegated.delegation.host ?? ctx.host;\n const delegatedCtx = { ...ctx, host: effectiveHost };\n const node = await ensureSecretsNode(delegatedCtx, options);\n const value = await withSpinner(\n `Getting secret ${name}...`,\n () => readDelegatedSecretValue({\n node,\n delegation: delegated.delegation,\n delegationCid: delegated.delegation.cid,\n permissions: delegated.permissions,\n secretPath,\n name,\n }),\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 return;\n }\n\n const node = await ensureSecretsNode(ctx, options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"get\",\n name,\n scopeOptions,\n label: `Getting secret ${name}...`,\n operation: () => node.secrets.get(name, scopeOptions),\n });\n\n if (!result.ok) {\n if (\n result.error.code === \"NOT_FOUND\" ||\n result.error.code === \"KEY_NOT_FOUND\"\n ) {\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 value = String(result.data);\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 || options.valueOnly) {\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(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\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 node = await ensureSecretsNode(ctx, options);\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 scopeOptions = resolveSecretScope(options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"put\",\n name,\n scopeOptions,\n label: `Storing secret ${name}...`,\n operation: () => node.secrets.put(name, secretValue, scopeOptions),\n });\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(\"--scope <scope>\", \"Logical secret scope\")\n .option(\"--space <scope>\", \"Deprecated alias for --scope\")\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 node = await ensureSecretsNode(ctx, options);\n const scopeOptions = resolveSecretScope(options);\n const result = await runSecretOperation({\n ctx,\n node,\n action: \"del\",\n name,\n scopeOptions,\n label: `Deleting secret ${name}...`,\n operation: () => node.secrets.delete(name, scopeOptions),\n });\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 network\n .command(\"grant <recipientDid> [name]\")\n .description(\"Grant decrypt permission for a secrets encryption network\")\n .option(\"--private-key <hex>\", \"Ethereum private key override (or set TC_PRIVATE_KEY)\")\n .action(async (recipientDid: string, name: string | undefined, options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const node = await ensureAuthenticated(ctx, authOptions(options));\n const networkName = name ?? \"default\";\n const descriptor = await withSpinner(\n \"Ensuring encryption network...\",\n () => node.ensureEncryptionNetwork(networkName),\n );\n const permission = {\n service: \"tinycloud.encryption\",\n path: descriptor.networkId,\n actions: [\"decrypt\"],\n };\n const result = await withSpinner(\n `Granting decrypt permission to ${recipientDid}...`,\n () => node.delegateTo(recipientDid, [permission]),\n );\n\n outputJson({\n networkId: descriptor.networkId,\n recipientDid,\n cid: result.delegation.cid,\n prompted: result.prompted,\n path: result.delegation.path,\n actions: result.delegation.actions,\n });\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 type { TinyCloudNode, IDatabaseHandle } from \"@tinycloud/node-sdk\";\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 { resolveSpaceUri } from \"../lib/space.js\";\nimport { theme } from \"../output/theme.js\";\n\n/**\n * Pick a database handle for the requested space + db name.\n *\n * `--space` is optional; when omitted, ops route through the node's\n * primary-space SQL service (preserves prior behavior). When present,\n * we use TinyCloudNode.sqlForSpace, which clones the active service\n * context with a session whose spaceId points at the target space.\n */\nasync function dbHandle(\n node: TinyCloudNode,\n dbName: string,\n spaceInput: string | undefined,\n profileName: string,\n): Promise<IDatabaseHandle> {\n const spaceUri = await resolveSpaceUri(spaceInput, profileName);\n const sql = spaceUri ? node.sqlForSpace(spaceUri) : node.sql;\n return sql.db(dbName);\n}\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. Pass\n--space to target a non-primary space (e.g. the manifest \"applications\" space).\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 query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\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 copy Copy rows between databases (optionally across spaces)\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 - --space accepts a short name (\"applications\") or full URI (\"tinycloud:pkh:eip155:1:0x...:applications\").\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(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 $ tc sql query \"SELECT count(*) FROM conversation\" --space applications --db xyz.tinycloud.listen/conversations\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 const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Running query...\", () =>\n handle.query(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\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(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 $ tc sql execute \"DELETE FROM conversation WHERE id = ?\" --space applications --db xyz.tinycloud.listen/conversations --params '[\"abc\"]'\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 const handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Executing statement...\", () =>\n handle.execute(sqlStr, params)\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\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(\"--space <name|uri>\", \"Target a non-primary space (short name or full URI)\")\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 $ tc sql export --space applications --db xyz.tinycloud.listen/conversations --output listen.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 handle = await dbHandle(node, options.db, options.space, ctx.profile);\n\n const result = await withSpinner(\"Exporting database...\", () =>\n handle.export()\n ) as any;\n\n if (!result.ok) {\n throw new CLIError(result.error.code, result.error.message, ExitCode.ERROR, result.error.meta);\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 sql copy\n sql\n .command(\"copy\")\n .description(\"Copy rows between SQL databases (optionally across spaces)\")\n .requiredOption(\"--from-db <name>\", \"Source database name\")\n .requiredOption(\"--to-db <name>\", \"Destination database name\")\n .option(\"--from-space <name|uri>\", \"Source space (defaults to primary)\")\n .option(\"--to-space <name|uri>\", \"Destination space (defaults to primary)\")\n .option(\"--table <name...>\", \"Restrict copy to specific tables (repeat or comma-separated)\")\n .option(\"--dry-run\", \"Print the plan without writing\", false)\n .addHelpText(\"after\", `\n\nExamples:\n $ tc sql copy --from-db com.tinycloud.conversation-sync/conversations \\\\\n --to-db xyz.tinycloud.listen/conversations \\\\\n --space applications --dry-run\n $ tc sql copy --from-space applications --from-db com.foo/data \\\\\n --to-space applications --to-db com.bar/data \\\\\n --table conversation --table participant\n\nNotes:\n - Refuses to run when (resolved space, db) is identical for source and destination.\n - Does NOT create destination tables. Run the target app once (or use \\`tc sql execute\\`)\n to materialize the schema before copying.\n - One row at a time; suitable for small/medium datasets. Large copies should\n use \\`tc sql export\\` + bulk import.\n - Authorization: the active session/delegation must cover sql/read on source\n AND sql/write on destination. Otherwise the relevant operation will fail.\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 // commander's `--space` shorthand supports both --from-space and a default.\n const fromSpaceInput: string | undefined = options.fromSpace ?? options.space;\n const toSpaceInput: string | undefined = options.toSpace ?? options.space;\n\n const fromSpaceUri = (await resolveSpaceUri(fromSpaceInput, ctx.profile)) ?? \"<primary>\";\n const toSpaceUri = (await resolveSpaceUri(toSpaceInput, ctx.profile)) ?? \"<primary>\";\n\n if (fromSpaceUri === toSpaceUri && options.fromDb === options.toDb) {\n throw new CLIError(\n \"SELF_COPY\",\n `Refusing to copy: source and destination resolve to the same (space, db) — ${fromSpaceUri} / ${options.fromDb}.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const fromHandle = await dbHandle(node, options.fromDb, fromSpaceInput, ctx.profile);\n const toHandle = await dbHandle(node, options.toDb, toSpaceInput, ctx.profile);\n\n // Resolve target tables: explicit list, or all user tables in source.\n let tables: string[];\n if (options.table && options.table.length > 0) {\n tables = options.table.flatMap((t: string) => t.split(\",\").map((s) => s.trim()).filter(Boolean));\n } else {\n const listing = await fromHandle.query(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name\",\n ) as any;\n if (!listing.ok) {\n throw new CLIError(listing.error.code, `Cannot list source tables: ${listing.error.message}`, ExitCode.ERROR, listing.error.meta);\n }\n tables = (listing.data.rows as unknown[][]).map((r) => String(r[0]));\n }\n\n if (tables.length === 0) {\n throw new CLIError(\n \"EMPTY_PLAN\",\n `No tables to copy. Use --table to specify tables, or check that the source database has user tables.`,\n ExitCode.USAGE_ERROR,\n );\n }\n\n const plan: Array<{ table: string; rows: number; copied: number; skipped: number }> = [];\n\n for (const table of tables) {\n const safe = quoteIdent(table);\n const countResult = await fromHandle.query(`SELECT count(*) AS n FROM ${safe}`) as any;\n if (!countResult.ok) {\n throw new CLIError(\n countResult.error.code,\n `Cannot count rows in source table \"${table}\": ${countResult.error.message}`,\n ExitCode.ERROR,\n countResult.error.meta,\n );\n }\n const rows = Number(countResult.data.rows[0]?.[0] ?? 0);\n plan.push({ table, rows, copied: 0, skipped: 0 });\n }\n\n if (options.dryRun) {\n outputJson({\n dryRun: true,\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rows: p.rows })),\n });\n return;\n }\n\n for (const entry of plan) {\n const safe = quoteIdent(entry.table);\n const fetched = await fromHandle.query(`SELECT * FROM ${safe}`) as any;\n if (!fetched.ok) {\n throw new CLIError(fetched.error.code, `Failed to read \"${entry.table}\": ${fetched.error.message}`, ExitCode.ERROR, fetched.error.meta);\n }\n const columns: string[] = fetched.data.columns;\n const rows: unknown[][] = fetched.data.rows;\n\n if (rows.length === 0) continue;\n\n const colList = columns.map(quoteIdent).join(\", \");\n const placeholders = columns.map(() => \"?\").join(\", \");\n const insertSql = `INSERT INTO ${safe} (${colList}) VALUES (${placeholders})`;\n\n for (const row of rows) {\n const writeResult = await toHandle.execute(insertSql, row as any) as any;\n if (!writeResult.ok) {\n throw new CLIError(\n writeResult.error.code,\n `Insert into \"${entry.table}\" failed after ${entry.copied} row(s): ${writeResult.error.message}`,\n ExitCode.ERROR,\n writeResult.error.meta,\n );\n }\n entry.copied += writeResult.data.changes ?? 1;\n }\n }\n\n outputJson({\n from: { space: fromSpaceUri, db: options.fromDb },\n to: { space: toSpaceUri, db: options.toDb },\n tables: plan.map((p) => ({ table: p.table, rowsRead: p.rows, rowsWritten: p.copied })),\n });\n } catch (error) {\n handleError(error);\n }\n });\n}\n\n/** Quote a SQLite identifier defensively (table/column names). */\nfunction quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\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 { readFile } from \"node:fs/promises\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport { ensureAuthenticated } from \"../lib/sdk.js\";\nimport { resolveSpaceUri } from \"../lib/space.js\";\nimport { outputJson, shouldOutputJson, formatTable } from \"../output/formatter.js\";\nimport { handleError, CLIError } from \"../output/errors.js\";\nimport { ExitCode } from \"../config/constants.js\";\nimport { theme } from \"../output/theme.js\";\n\ninterface ManifestPermission {\n service: string;\n path: string;\n actions: string[];\n skipPrefix?: boolean;\n description?: string;\n}\n\ninterface Manifest {\n manifest_version?: number;\n app_id?: string;\n name?: string;\n description?: string;\n space?: string;\n defaults?: boolean;\n permissions?: ManifestPermission[];\n}\n\n/**\n * Default space for app data when the manifest omits `space`.\n * Mirrors the manifest spec at repositories/listen/SPEC-manifest-and-capability-chain.md.\n */\nconst DEFAULT_APP_SPACE = \"applications\";\n\nexport function registerManifestCommand(program: Command): void {\n const manifest = program\n .command(\"manifest\")\n .description(\"Inspect TinyCloud app manifests\");\n\n manifest\n .command(\"resolve <source>\")\n .description(\"Resolve a manifest file or URL to its effective space, paths, and DB basenames\")\n .addHelpText(\"after\", `\n\nExamples:\n $ tc manifest resolve ./manifest.json\n $ tc manifest resolve https://app.example.com/manifest.json --json\n\nWhat it shows:\n - app_id, name, manifest_version\n - effective space name (default: \"applications\") and full space URI for the active profile\n - per-permission: service, fully-qualified path, actions\n - inferred SQL database basenames for sql/<db>/... paths\n\nThis command is read-only and does NOT contact the node — it just resolves\nthe manifest against the active profile's address/chain so you know which\n\\`--space\\` and \\`--db\\` values to pass to other tc commands.\n`)\n .action(async (source: string, _options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n\n const raw = await loadManifestSource(source);\n const parsed: Manifest = JSON.parse(raw);\n\n if (!parsed.app_id) {\n throw new CLIError(\n \"INVALID_MANIFEST\",\n `Manifest is missing required field \"app_id\".`,\n ExitCode.ERROR,\n );\n }\n\n // Make sure we have an authenticated profile so we can resolve\n // the user's space URI. We don't use the node — just the profile.\n await ensureAuthenticated(ctx);\n\n const spaceName = parsed.space ?? DEFAULT_APP_SPACE;\n const spaceUri = await resolveSpaceUri(spaceName, ctx.profile);\n\n const permissions = (parsed.permissions ?? []).map((p) => {\n const resolvedPath = p.skipPrefix ? p.path : prefixWithAppId(p.path, parsed.app_id!);\n return {\n service: p.service,\n path: resolvedPath,\n actions: p.actions,\n sqlDb: extractSqlDbName(resolvedPath),\n };\n });\n\n const sqlDbs = unique(\n permissions\n .map((p) => p.sqlDb)\n .filter((db): db is string => Boolean(db)),\n );\n\n const summary = {\n source,\n app_id: parsed.app_id,\n name: parsed.name,\n manifest_version: parsed.manifest_version,\n space: {\n name: spaceName,\n uri: spaceUri,\n },\n permissions,\n sqlDatabases: sqlDbs,\n };\n\n if (shouldOutputJson()) {\n outputJson(summary);\n return;\n }\n\n process.stdout.write(`${theme.heading(\"Manifest\")}: ${theme.value(parsed.app_id)}`);\n if (parsed.name) process.stdout.write(theme.muted(` (${parsed.name})`));\n process.stdout.write(\"\\n\");\n\n process.stdout.write(`${theme.label(\"Space\")}: ${theme.value(spaceName)}\\n`);\n if (spaceUri) {\n process.stdout.write(`${theme.label(\"Space URI\")}: ${theme.value(spaceUri)}\\n`);\n }\n\n if (sqlDbs.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"SQL databases\")}\\n`);\n for (const db of sqlDbs) {\n process.stdout.write(` ${theme.value(db)}\\n`);\n }\n process.stdout.write(theme.muted(`\\nUse with: tc sql query --space ${spaceName} --db <db> \"...\"\\n`));\n }\n\n if (permissions.length > 0) {\n process.stdout.write(`\\n${theme.heading(\"Permissions\")}\\n`);\n const rows = permissions.map((p) => [p.service, p.path, p.actions.join(\", \")]);\n process.stdout.write(formatTable([\"service\", \"path\", \"actions\"], rows) + \"\\n\");\n }\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function loadManifestSource(source: string): Promise<string> {\n if (/^https?:\\/\\//i.test(source)) {\n const response = await fetch(source);\n if (!response.ok) {\n throw new CLIError(\n \"MANIFEST_FETCH_FAILED\",\n `Failed to fetch manifest from ${source}: ${response.status} ${response.statusText}`,\n ExitCode.NETWORK_ERROR,\n );\n }\n return response.text();\n }\n return readFile(source, \"utf8\");\n}\n\nfunction prefixWithAppId(path: string, appId: string): string {\n // Manifest paths are usually `<service-prefix>/<resource>`, e.g. `sql/foo/bar`.\n // When skipPrefix is false the app_id is inserted between the service prefix\n // and the resource, matching how resolveAppPath() lays out keys at runtime.\n const slash = path.indexOf(\"/\");\n if (slash === -1) return `${appId}/${path}`;\n const head = path.slice(0, slash);\n const tail = path.slice(slash + 1);\n return `${head}/${appId}/${tail}`;\n}\n\n/**\n * For a path like `sql/<db-name>/<table>/...`, return `<db-name>`.\n * `<db-name>` itself may contain slashes when the app namespaces it\n * (e.g. `sql/xyz.tinycloud.listen/conversations/conversation`), so we drop\n * the trailing table segment(s) and reassemble.\n */\nfunction extractSqlDbName(path: string): string | undefined {\n if (!path.startsWith(\"sql/\")) return undefined;\n const rest = path.slice(4);\n const segments = rest.split(\"/\");\n if (segments.length < 2) return rest;\n // Drop the last segment (table name); the rest is the db name.\n return segments.slice(0, -1).join(\"/\");\n}\n\nfunction unique<T>(arr: T[]): T[] {\n return Array.from(new Set(arr));\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","import { Command } from \"commander\";\nimport {\n NodeWasmBindings,\n type PermissionEntry,\n} from \"@tinycloud/node-sdk\";\nimport { ProfileManager } from \"../config/profiles.js\";\nimport {\n resolveProfileOperatorType,\n resolveProfilePosture,\n type ProfileConfig,\n} from \"../config/types.js\";\nimport { handleError } from \"../output/errors.js\";\nimport { outputJson, shouldOutputJson } from \"../output/formatter.js\";\nimport { theme } from \"../output/theme.js\";\nimport {\n compactPermission,\n loadAdditionalDelegations,\n permissionsFromDelegation,\n type StoredAdditionalDelegation,\n} from \"../lib/permissions.js\";\n\ninterface StatusSummary {\n generatedAt: string;\n activeProfile: string;\n defaultProfile: string;\n profileCount: number;\n authenticatedProfileCount: number;\n activeDelegationCount: number;\n profiles: StatusProfile[];\n}\n\ninterface StatusProfile {\n name: string;\n active: boolean;\n default: boolean;\n exists: boolean;\n status: \"logged-in\" | \"local-key\" | \"expired\" | \"signed-out\" | \"missing\";\n host: string | null;\n did: string | null;\n sessionDid: string | null;\n ownerDid: string | null;\n address: string | null;\n spaceId: string | null;\n authMethod: string | null;\n posture: string | null;\n operatorType: string | null;\n hasKey: boolean;\n hasPrivateKey: boolean;\n authenticated: boolean;\n session: StatusSession;\n delegations: StatusDelegation[];\n permissions: PermissionEntry[];\n permissionsCompact: string[];\n permissionCount: number;\n activeDelegationCount: number;\n delegationCount: number;\n issues: string[];\n}\n\ninterface StatusSession {\n present: boolean;\n expired: boolean | null;\n expiresAt: string | null;\n permissions: PermissionEntry[];\n permissionsCompact: string[];\n}\n\ninterface StatusDelegation {\n cid: string;\n active: boolean;\n expired: boolean | null;\n expiresAt: string | null;\n permissions: PermissionEntry[];\n permissionsCompact: string[];\n}\n\nlet wasmBindings: NodeWasmBindings | null = null;\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command(\"status\")\n .description(\"Show local TinyCloud profile, session, delegation, and permission state\")\n .action(async (_options, cmd) => {\n try {\n const globalOpts = cmd.optsWithGlobals();\n const ctx = await ProfileManager.resolveContext(globalOpts);\n const config = await ProfileManager.getConfig();\n const names = (await ProfileManager.listProfiles()).sort((a, b) =>\n a.localeCompare(b),\n );\n const generatedAt = new Date().toISOString();\n const profiles = await Promise.all(\n names.map((name) =>\n inspectProfile({\n name,\n activeProfile: ctx.profile,\n defaultProfile: config.defaultProfile,\n }),\n ),\n );\n const summary: StatusSummary = {\n generatedAt,\n activeProfile: ctx.profile,\n defaultProfile: config.defaultProfile,\n profileCount: profiles.length,\n authenticatedProfileCount: profiles.filter((p) => p.authenticated)\n .length,\n activeDelegationCount: profiles.reduce(\n (sum, profile) => sum + profile.activeDelegationCount,\n 0,\n ),\n profiles,\n };\n\n if (shouldOutputJson()) {\n outputJson(summary);\n return;\n }\n\n process.stdout.write(formatStatus(summary));\n } catch (error) {\n handleError(error);\n }\n });\n}\n\nasync function inspectProfile(params: {\n name: string;\n activeProfile: string;\n defaultProfile: string;\n}): Promise<StatusProfile> {\n const issues: string[] = [];\n const profile = await readProfile(params.name, issues);\n const session = await readSession(params.name, issues);\n const hasKey = await readHasKey(params.name, issues);\n const storedDelegations = await readDelegations(params.name, issues);\n const sessionPermissions = session ? sessionPermissionsFromRecap(session) : [];\n const sessionExpiry = session ? extractSessionExpiry(session) : null;\n const sessionExpired =\n sessionExpiry === null ? null : sessionExpiry.getTime() <= Date.now();\n const statusSession: StatusSession = {\n present: session !== null,\n expired: session === null ? null : sessionExpired,\n expiresAt: sessionExpiry?.toISOString() ?? null,\n permissions: sessionPermissions,\n permissionsCompact: compactPermissions(sessionPermissions),\n };\n const delegations = storedDelegations.map(inspectDelegation);\n const activeDelegationPermissions = delegations\n .filter((delegation) => delegation.active)\n .flatMap((delegation) => delegation.permissions);\n const permissions = uniquePermissions([\n ...sessionPermissions,\n ...activeDelegationPermissions,\n ]);\n const hasPrivateKey = typeof profile?.privateKey === \"string\" && profile.privateKey.length > 0;\n const localKeyAuthenticated = profile?.authMethod === \"local\" && hasPrivateKey;\n const sessionAuthenticated = session !== null && sessionExpired !== true;\n const authenticated = localKeyAuthenticated || sessionAuthenticated;\n const status = resolveStatus({\n exists: profile !== null,\n authenticated,\n localKeyAuthenticated,\n sessionExpired,\n });\n\n return {\n name: params.name,\n active: params.name === params.activeProfile,\n default: params.name === params.defaultProfile,\n exists: profile !== null,\n status,\n host: profile?.host ?? null,\n did: profile?.did ?? null,\n sessionDid: profile?.sessionDid ?? null,\n ownerDid: profile?.ownerDid ?? null,\n address: profile?.address ?? null,\n spaceId: profile?.spaceId ?? null,\n authMethod: profile?.authMethod ?? null,\n posture: profile ? resolveProfilePosture(profile) : null,\n operatorType: profile ? resolveProfileOperatorType(profile) : null,\n hasKey,\n hasPrivateKey,\n authenticated,\n session: statusSession,\n delegations,\n permissions,\n permissionsCompact: compactPermissions(permissions),\n permissionCount: permissions.length,\n activeDelegationCount: delegations.filter((delegation) => delegation.active)\n .length,\n delegationCount: delegations.length,\n issues,\n };\n}\n\nasync function readProfile(\n name: string,\n issues: string[],\n): Promise<ProfileConfig | null> {\n try {\n return await ProfileManager.getProfile(name);\n } catch (error) {\n issues.push(`profile: ${messageFromError(error)}`);\n return null;\n }\n}\n\nasync function readSession(\n name: string,\n issues: string[],\n): Promise<Record<string, unknown> | null> {\n try {\n return asRecord(await ProfileManager.getSession(name));\n } catch (error) {\n issues.push(`session: ${messageFromError(error)}`);\n return null;\n }\n}\n\nasync function readHasKey(name: string, issues: string[]): Promise<boolean> {\n try {\n return (await ProfileManager.getKey(name)) !== null;\n } catch (error) {\n issues.push(`key: ${messageFromError(error)}`);\n return false;\n }\n}\n\nasync function readDelegations(\n name: string,\n issues: string[],\n): Promise<StoredAdditionalDelegation[]> {\n try {\n return await loadAdditionalDelegations(name);\n } catch (error) {\n issues.push(`delegations: ${messageFromError(error)}`);\n return [];\n }\n}\n\nfunction inspectDelegation(\n entry: StoredAdditionalDelegation,\n): StatusDelegation {\n const expiry = parseDate((entry.delegation as { expiry?: unknown }).expiry);\n const expired = expiry === null ? null : expiry.getTime() <= Date.now();\n const permissions = normalizePermissions(\n Array.isArray(entry.permissions) && entry.permissions.length > 0\n ? entry.permissions\n : permissionsFromDelegation(entry.delegation),\n );\n\n return {\n cid: entry.delegation.cid,\n active: expired !== true,\n expired,\n expiresAt: expiry?.toISOString() ?? null,\n permissions,\n permissionsCompact: compactPermissions(permissions),\n };\n}\n\nfunction resolveStatus(params: {\n exists: boolean;\n authenticated: boolean;\n localKeyAuthenticated: boolean;\n sessionExpired: boolean | null;\n}): StatusProfile[\"status\"] {\n if (!params.exists) return \"missing\";\n if (params.localKeyAuthenticated) return \"local-key\";\n if (params.authenticated) return \"logged-in\";\n if (params.sessionExpired === true) return \"expired\";\n return \"signed-out\";\n}\n\nfunction sessionPermissionsFromRecap(\n session: Record<string, unknown>,\n): PermissionEntry[] {\n if (typeof session.siwe !== \"string\" || session.siwe.length === 0) return [];\n try {\n const rawEntries = getWasmBindings().parseRecapFromSiwe(session.siwe);\n if (!Array.isArray(rawEntries)) return [];\n return normalizePermissions(rawEntries.map(permissionFromRawRecap));\n } catch {\n return [];\n }\n}\n\nfunction permissionFromRawRecap(value: unknown): PermissionEntry | null {\n const record = asRecord(value);\n if (!record) return null;\n const service = stringValue(record.service);\n const space = stringValue(record.space);\n const path = stringValue(record.path);\n const actions = Array.isArray(record.actions)\n ? record.actions.map(String).filter(Boolean)\n : [];\n if (!service || !space || path === null || actions.length === 0) return null;\n return {\n service: normalizeService(service),\n space,\n path,\n actions,\n };\n}\n\nfunction normalizePermissions(entries: unknown[]): PermissionEntry[] {\n const permissions: PermissionEntry[] = [];\n for (const entry of entries) {\n const permission = permissionFromUnknown(entry);\n if (permission) permissions.push(permission);\n }\n return uniquePermissions(permissions);\n}\n\nfunction permissionFromUnknown(value: unknown): PermissionEntry | null {\n const record = asRecord(value);\n if (!record) return null;\n const service = stringValue(record.service);\n const space = stringValue(record.space);\n const path = stringValue(record.path);\n const actions = Array.isArray(record.actions)\n ? record.actions.map(String).filter(Boolean)\n : [];\n if (!service || !space || path === null || actions.length === 0) return null;\n return {\n service: normalizeService(service),\n space,\n path,\n actions,\n };\n}\n\nfunction uniquePermissions(entries: PermissionEntry[]): PermissionEntry[] {\n const seen = new Set<string>();\n const unique: PermissionEntry[] = [];\n for (const entry of entries) {\n const key = compactPermission(entry);\n if (seen.has(key)) continue;\n seen.add(key);\n unique.push(entry);\n }\n return unique;\n}\n\nfunction compactPermissions(entries: PermissionEntry[]): string[] {\n return entries.map(compactPermission);\n}\n\nfunction extractSessionExpiry(session: Record<string, unknown>): Date | null {\n for (const key of [\"expiresAt\", \"expiry\", \"expirationTime\"]) {\n const parsed = parseDate(session[key]);\n if (parsed) return parsed;\n }\n if (typeof session.siwe !== \"string\") return null;\n const match = session.siwe.match(/^Expiration Time:\\s*(.+)$/im);\n return match ? parseDate(match[1].trim()) : null;\n}\n\nfunction parseDate(value: unknown): Date | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n const millis = value > 0 && value < 1_000_000_000_000 ? value * 1000 : value;\n const date = new Date(millis);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n if (typeof value !== \"string\" || value.trim() === \"\") return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction getWasmBindings(): NodeWasmBindings {\n wasmBindings ??= new NodeWasmBindings();\n return wasmBindings;\n}\n\nfunction normalizeService(service: string): string {\n return service.startsWith(\"tinycloud.\") ? service : `tinycloud.${service}`;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\"\n ? value as Record<string, unknown>\n : null;\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction messageFromError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction formatStatus(summary: StatusSummary): string {\n const lines: string[] = [];\n lines.push(theme.heading(\"TinyCloud Status\"));\n lines.push(`Active profile: ${theme.value(summary.activeProfile)}`);\n lines.push(`Default profile: ${theme.value(summary.defaultProfile)}`);\n lines.push(\"\");\n\n if (summary.profiles.length === 0) {\n lines.push(theme.muted(\"No profiles configured. Run: tc init\"));\n return `${lines.join(\"\\n\")}\\n`;\n }\n\n lines.push(theme.label(\"Profiles\"));\n for (const profile of summary.profiles) {\n lines.push(formatProfile(profile));\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction formatProfile(profile: StatusProfile): string {\n const marker = profile.active ? theme.success(\"*\") : \" \";\n const name = profile.default ? `${profile.name} (default)` : profile.name;\n const host = profile.host ? theme.muted(profile.host) : theme.muted(\"no host\");\n const summary = [\n `${marker} ${profile.active ? theme.brand(name) : name}`,\n formatProfileStatus(profile.status),\n profile.posture ?? \"no posture\",\n plural(profile.permissionCount, \"permission\"),\n `${profile.activeDelegationCount}/${profile.delegationCount} delegations`,\n host,\n ].join(\" \");\n const lines = [summary];\n\n lines.push(` session: ${formatSession(profile.session)}`);\n if (profile.permissionsCompact.length > 0) {\n lines.push(\" permissions:\");\n for (const permission of profile.permissionsCompact) {\n lines.push(` ${permission}`);\n }\n }\n if (profile.delegations.length > 0) {\n lines.push(\" delegations:\");\n for (const delegation of profile.delegations) {\n lines.push(` ${formatDelegation(delegation)}`);\n }\n }\n if (profile.issues.length > 0) {\n lines.push(\" issues:\");\n for (const issue of profile.issues) {\n lines.push(` ${theme.warn(issue)}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nfunction formatProfileStatus(status: StatusProfile[\"status\"]): string {\n switch (status) {\n case \"logged-in\":\n return theme.success(\"logged in\");\n case \"local-key\":\n return theme.success(\"local key\");\n case \"expired\":\n return theme.warn(\"expired\");\n case \"missing\":\n return theme.warn(\"missing\");\n case \"signed-out\":\n return theme.muted(\"signed out\");\n }\n}\n\nfunction formatSession(session: StatusSession): string {\n if (!session.present) return theme.muted(\"none\");\n if (session.expired === true) {\n return `${theme.warn(\"expired\")}${formatExpiresAt(session.expiresAt)}`;\n }\n if (session.expired === false) {\n return `${theme.success(\"active\")}${formatExpiresAt(session.expiresAt)}`;\n }\n return `${theme.success(\"present\")}${formatExpiresAt(session.expiresAt)}`;\n}\n\nfunction formatDelegation(delegation: StatusDelegation): string {\n const state = delegation.expired === true\n ? theme.warn(\"expired\")\n : theme.success(\"active\");\n return [\n delegation.cid,\n state,\n formatExpiresAt(delegation.expiresAt).trim(),\n plural(delegation.permissions.length, \"permission\"),\n ].filter(Boolean).join(\" \");\n}\n\nfunction formatExpiresAt(expiresAt: string | null): string {\n return expiresAt ? ` until ${expiresAt}` : \"\";\n}\n\nfunction plural(count: number, label: string): string {\n return `${count} ${label}${count === 1 ? \"\" : \"s\"}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,QAAI,IAAI;AACR,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AAgBZ,WAAO,UAAU,SAAU,KAAK,SAAS;AACvC,gBAAU,WAAW,CAAC;AACtB,UAAI,OAAO,OAAO;AAClB,UAAI,SAAS,YAAY,IAAI,SAAS,GAAG;AACvC,eAAO,MAAM,GAAG;AAAA,MAClB,WAAW,SAAS,YAAY,SAAS,GAAG,GAAG;AAC7C,eAAO,QAAQ,OAAO,QAAQ,GAAG,IAAI,SAAS,GAAG;AAAA,MACnD;AACA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AC;AAAA,IACrF,MAAM,QAAQ,yBAAyB,CAAC,iBAAiB,MAAM,MAAM,oCAAoC,CAAC;AAAA,IAC1G,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":["ms","plural","readFileSync","join","ok","join","version","join","rm","err","join","rm","err","TinyCloudNode","resolve","err","program","mkdir","readFile","writeFile","dirname","createInterface","randomBytes","readFile","join","util","objectUtil","errorUtil","errorMap","err","version","ctx","result","issues","elements","processed","result","r","ZodFirstPartyTypeKind","wrapError","ok","serviceError","wrapError","errorText","resolve","resolve","valueDelResult","hexEncode","base64Encode","base64Decode","hexEncode","toError","err","crypto","base64Encode","base64Decode","hexEncode","crypto","err","crypto","hexEncode","base64Decode","toError","base64Encode","ms","join","randomBytes","err","readFile","readFile","node","createInterface","resolve","program","delegationCids","expiry","mkdir","dirname","writeFile","readFile","ms","result","readFile","writeFile","readStdin","program","kv","writeFile","readFile","program","ms","parseExpiry","program","parseExpiry","program","parseExpiry","program","createInterface","program","createInterface","resolve","program","readFile","writeFile","PrivateKeySigner","readStdin","program","readFile","writeFile","readFile","writeFile","join","homedir","SECRETS_SPACE","readStdin","SECRET_NAME_RE","RESERVED_SECRET_SCOPES","canonicalizeSecretScope","resolveSecretPath","homedir","join","normalizePortableDelegation","delegation","permissionsFromDelegation","readFile","program","node","value","writeFile","readFile","writeFile","readStdin","resolvePrivateKey","program","writeFile","readFile","program","writeFile","program","writeFile","readFile","writeFile","resolve","program","resolve","writeFile","readFile","readFile","program","readFile","execSync","readFileSync","readFileSync","execSync","program","program","parseDate","normalizeService","unique","date","readFileSync"]}