@01.software/cli 0.15.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/lib/client.ts","../src/lib/credentials.ts","../src/lib/output.ts","../../errors/src/admin-error.ts","../src/lib/admin-error.ts","../src/lib/i18n.ts","../src/commands/crud.ts","../src/lib/collections.ts","../src/lib/parse.ts","../../contracts/src/tenant/index.ts","../../contracts/src/ecommerce/index.ts","../../contracts/src/ecommerce/product-upsert.ts","../src/commands/order.ts","../src/commands/return.ts","../src/commands/cart.ts","../src/commands/stock.ts","../src/commands/transaction.ts","../src/commands/product.ts","../src/commands/discount.ts","../src/commands/shipping.ts","../src/commands/auth.ts","../src/commands/schema.ts","../src/commands/feature.ts","../src/commands/agent.ts","../src/lib/agent-output.ts","../src/lib/agent-plan-allowlist.ts","../src/lib/agent-plan-auth.ts","../src/lib/agent-plan-store.ts","../src/lib/agent-plan-hash.ts","../src/lib/agent-plan-id.ts","../src/lib/agent-plan-stale.ts","../src/lib/agent-plan-confirm.ts","../src/lib/agent-plan-payload.ts","../src/lib/agent-plan-secrets.ts","../src/lib/agent-plan-token.ts","../src/commands/agent-plan.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { resolveClient, resolveClientOrThrow } from './lib/client.js'\nimport { exitWithError } from './lib/output.js'\nimport { setLocale, type Locale } from './lib/i18n.js'\nimport { registerCrudCommands } from './commands/crud.js'\nimport { registerOrderCommands } from './commands/order.js'\nimport { registerReturnCommands } from './commands/return.js'\nimport { registerCartCommands } from './commands/cart.js'\nimport { registerStockCommands } from './commands/stock.js'\nimport { registerTransactionCommands } from './commands/transaction.js'\nimport { registerProductCommands } from './commands/product.js'\nimport { registerDiscountCommands } from './commands/discount.js'\nimport { registerShippingCommands } from './commands/shipping.js'\nimport { registerAuthCommands } from './commands/auth.js'\nimport { registerSchemaCommands } from './commands/schema.js'\nimport { registerFeatureCommands } from './commands/feature.js'\nimport { registerAgentCommands } from './commands/agent.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../package.json') as { version: string }\n\nconst program = new Command()\n\nprogram\n .name('01')\n .description('CLI for the 01.software platform')\n .version(version)\n .option('--api-key <key>', 'API key (sk01_... or pat01_... token)')\n .option('--format <format>', 'Output format: json, table, or ndjson')\n .option('--lang <locale>', 'Force locale (ko or en)')\n\nconst getFormat = () =>\n (program.opts().format ?? process.env.OUTPUT_FORMAT ?? 'json') as string\n\n// Surface the explicit `--lang` flag (when supplied) so the i18n table\n// detection in `lib/i18n.ts` honours it before falling back to LC_ALL/LANG.\n// Also pin OUTPUT_FORMAT into the env so `exitWithError(e)` calls inside\n// command bodies pick up the format without threading it through every\n// call site.\nprogram.hook('preAction', () => {\n const lang = program.opts().lang as string | undefined\n if (lang === 'ko' || lang === 'en') setLocale(lang as Locale)\n process.env.OUTPUT_FORMAT = getFormat()\n})\n\nprocess.on('unhandledRejection', (err) => {\n exitWithError(err, { format: getFormat() })\n})\n\nconst getClient = () =>\n resolveClient(program.opts().apiKey as string | undefined)\nconst getAgentClient = () =>\n resolveClientOrThrow(program.opts().apiKey as string | undefined)\n\nregisterAgentCommands(program, getAgentClient)\nregisterCrudCommands(program, getClient, getFormat)\nregisterOrderCommands(program, getClient, getFormat)\nregisterReturnCommands(program, getClient, getFormat)\nregisterCartCommands(program, getClient, getFormat)\nregisterStockCommands(program, getClient, getFormat)\nregisterTransactionCommands(program, getClient, getFormat)\nregisterProductCommands(program, getClient, getFormat)\nregisterDiscountCommands(program, getClient, getFormat)\nregisterShippingCommands(program, getClient, getFormat)\nregisterSchemaCommands(program, getClient, getFormat)\nregisterFeatureCommands(program, getClient, getFormat)\nregisterAuthCommands(program)\n\nprogram.parse()\n","import {\n ServerCollectionClient,\n ServerCommerceClient,\n TenantIntrospectionApi,\n type TenantIntrospectionClient,\n} from '@01.software/sdk/server'\nimport { loadCredentials, loadLocalCredentials } from './credentials.js'\nimport { exitWithError } from './output.js'\nimport { t } from './i18n.js'\nimport type { AdminError } from './admin-error.js'\n\nexport interface ResolvedClient {\n collections: ServerCollectionClient\n commerce: ServerCommerceClient\n tenant: TenantIntrospectionClient\n publishableKey: string\n secretKey: string\n}\n\ninterface ResolvedCredentials {\n publishableKey: string\n secretKey: string\n}\n\n/**\n * Accepted opaque bearer token prefixes.\n * - `sk01_` = tenant-level API key (created in Console > Settings > API Keys)\n * - `pat01_` = user-level Personal Access Token\n * Hex HMAC secrets from the pre-2026-04 auth system are rejected.\n */\nfunction isValidBearerToken(secret: string): boolean {\n return secret.startsWith('sk01_') || secret.startsWith('pat01_')\n}\n\nfunction credentialError(detail: Record<string, unknown>): AdminError {\n return {\n type: 'permission',\n code: 'credential_invalid',\n detail,\n }\n}\n\n/**\n * Resolve credentials in priority order:\n * 1. `--api-key <token>` flag (overrides secretKey only; publishableKey still\n * comes from env/credentials)\n * 2. `SOFTWARE_PUBLISHABLE_KEY` + `SOFTWARE_SECRET_KEY` env vars\n * 3. Local project credentials (`./01software/credentials.json`)\n * 4. Global user credentials (`~/.01software/credentials.json`)\n */\nfunction resolveClientCredentials(apiKeyFlag?: string): ResolvedCredentials {\n let publishableKey: string | undefined = process.env.SOFTWARE_PUBLISHABLE_KEY\n let secretKey: string | undefined =\n apiKeyFlag ?? process.env.SOFTWARE_SECRET_KEY\n\n if (!publishableKey || !secretKey) {\n const local = loadLocalCredentials()\n if (local) {\n publishableKey = publishableKey ?? local.publishableKey\n secretKey = secretKey ?? local.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n const stored = loadCredentials()\n if (stored) {\n publishableKey = publishableKey ?? stored.publishableKey\n secretKey = secretKey ?? stored.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n throw credentialError({\n message: t('AuthenticationRequired'),\n steps: [t('RunLoginToAuthenticate'), t('PassApiKey'), t('SetEnvVars')],\n })\n }\n\n if (!isValidBearerToken(secretKey)) {\n throw credentialError({\n message: t('InvalidApiKeyFormat'),\n suggestion: t('RetiredHexCredentialsRejected'),\n })\n }\n\n return { publishableKey, secretKey }\n}\n\nexport function resolveClientOrThrow(apiKeyFlag?: string): ResolvedClient {\n const { publishableKey, secretKey } = resolveClientCredentials(apiKeyFlag)\n const serverOptions = { publishableKey, secretKey }\n\n return {\n collections: new ServerCollectionClient(\n publishableKey,\n secretKey,\n undefined,\n undefined,\n undefined,\n ),\n commerce: new ServerCommerceClient(serverOptions),\n tenant: new TenantIntrospectionApi(serverOptions),\n publishableKey,\n secretKey,\n }\n}\n\nexport function resolveClient(apiKeyFlag?: string): ResolvedClient {\n try {\n return resolveClientOrThrow(apiKeyFlag)\n } catch (error) {\n exitWithError(error)\n }\n}\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n unlinkSync,\n appendFileSync,\n} from 'node:fs'\nimport { join } from 'node:path'\nimport { homedir } from 'node:os'\n\nexport interface StoredCredentials {\n publishableKey: string\n /** Opaque bearer token — tenant API key (sk01_...) or PAT (pat01_...) */\n secretKey: string\n tenantId?: string\n tenantName: string\n storedAt: string\n}\n\nexport interface TenantInfo {\n id: string\n name: string\n}\n\nconst DIR_NAME = '.01software'\nconst FILE_NAME = 'credentials.json'\nconst TENANTS_FILE = 'tenants.json'\n\n// ---------------------------------------------------------------------------\n// Global credentials (~/.01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getCredentialsPath(): string {\n return join(homedir(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getCredentialsPath())\n}\n\nexport function saveCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function deleteCredentials(): boolean {\n const filePath = getCredentialsPath()\n if (!existsSync(filePath)) return false\n\n unlinkSync(filePath)\n return true\n}\n\n// ---------------------------------------------------------------------------\n// Local credentials (./01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getLocalCredentialsPath(): string {\n return join(process.cwd(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadLocalCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getLocalCredentialsPath())\n}\n\nexport function saveLocalCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const dir = join(process.cwd(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = getLocalCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeFileSync(filePath, JSON.stringify(data, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n\n // Ensure .01software/ is in .gitignore\n ensureGitignore()\n}\n\n// ---------------------------------------------------------------------------\n// Tenant list cache (~/.01software/tenants.json)\n// ---------------------------------------------------------------------------\n\nexport function saveTenantList(tenants: TenantInfo[]): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n writeFileSync(filePath, JSON.stringify(tenants, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function loadTenantList(): TenantInfo[] | null {\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw)\n if (!Array.isArray(data)) return null\n const valid = data.filter(\n (t): t is TenantInfo =>\n typeof t?.id === 'string' && typeof t?.name === 'string',\n )\n return valid.length > 0 ? valid : null\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction loadCredentialsFrom(filePath: string): StoredCredentials | null {\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw) as StoredCredentials\n if (!data.publishableKey || !data.secretKey) return null\n return data\n } catch {\n return null\n }\n}\n\nfunction ensureGitignore(): void {\n const gitignorePath = join(process.cwd(), '.gitignore')\n const entry = '.01software/'\n\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8')\n if (content.includes(entry)) return\n appendFileSync(gitignorePath, `\\n${entry}\\n`, 'utf-8')\n } else {\n writeFileSync(gitignorePath, `${entry}\\n`, 'utf-8')\n }\n}\n","import pc from 'picocolors'\nimport {\n type AdminError,\n classifyError,\n adminErrorExitCode,\n} from './admin-error.js'\nimport { CLI_I18N_KO, t } from './i18n.js'\n\n// Build a Set of valid i18n keys for fast lookup when localizing AdminError\n// codes. Reused below to choose between localized and fallback rendering.\nconst CLI_I18N_KEYS: readonly string[] = Object.keys(CLI_I18N_KO)\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2))\n}\n\nexport function printTable(data: unknown): void {\n if (Array.isArray(data)) {\n if (data.length === 0) {\n console.log(pc.dim(t('Empty')))\n return\n }\n const keys = Object.keys(data[0] as Record<string, unknown>)\n const widths = keys.map((k) =>\n Math.max(\n k.length,\n ...data.map(\n (row) => String((row as Record<string, unknown>)[k] ?? '').length,\n ),\n ),\n )\n\n // Header\n console.log(keys.map((k, i) => k.padEnd(widths[i]!)).join(' '))\n console.log(keys.map((_, i) => '-'.repeat(widths[i]!)).join(' '))\n\n // Rows\n for (const row of data) {\n console.log(\n keys\n .map((k, i) =>\n String((row as Record<string, unknown>)[k] ?? '').padEnd(\n widths[i]!,\n ),\n )\n .join(' '),\n )\n }\n } else if (data && typeof data === 'object') {\n const entries = Object.entries(data as Record<string, unknown>)\n const maxKey = Math.max(...entries.map(([k]) => k.length))\n for (const [key, value] of entries) {\n const display =\n typeof value === 'object' ? JSON.stringify(value) : String(value)\n console.log(`${pc.bold(key.padEnd(maxKey))} ${display}`)\n }\n } else {\n console.log(String(data))\n }\n}\n\nfunction printNdjson(data: unknown): void {\n if (Array.isArray(data)) {\n data.forEach((item) => console.log(JSON.stringify(item)))\n } else if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const { docs, ...meta } = data as {\n docs: unknown[]\n [key: string]: unknown\n }\n ;(docs as unknown[]).forEach((doc) => console.log(JSON.stringify(doc)))\n if (Object.keys(meta).length > 0)\n console.log(JSON.stringify({ _meta: meta }))\n } else {\n console.log(JSON.stringify(data))\n }\n}\n\nexport function printResult(data: unknown, format: string): void {\n if (format === 'ndjson') {\n printNdjson(data)\n } else if (format === 'table') {\n // For find responses with docs array, print the docs as table\n if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const resp = data as {\n docs: unknown[]\n totalDocs: number\n page: number\n totalPages: number\n }\n printTable(resp.docs)\n console.log(\n pc.dim(\n `\\n${t('Total', { n: resp.totalDocs })} | ${t('PageOf', {\n page: resp.page,\n total: resp.totalPages,\n })}`,\n ),\n )\n return\n }\n printTable(data)\n } else {\n printJson(data)\n }\n}\n\n/**\n * Map an unknown error → CLI exit code per `docs/packages/cli-exit-codes.md`.\n *\n * Routes through `classifyError()` (the AdminError discriminated union is\n * the canonical source). The SDK-error-name + HTTP-status heuristic lives\n * inside `classifyError` so existing thrown values keep their mapping.\n * The `unknown` code → exit 1 fallback is encoded in\n * `adminErrorExitCode` itself.\n */\nexport function getExitCode(error: unknown): number {\n return adminErrorExitCode(classifyError(error))\n}\n\nexport interface ErrorPrintOptions {\n format?: string\n}\n\n/**\n * Resolve the active output format. The entry point (`index.ts`) sets\n * `process.env.OUTPUT_FORMAT` from `--format` / fallback so command bodies\n * can call `exitWithError(e)` without threading the format through every\n * call site. Explicit `options.format` always wins.\n */\nfunction resolveFormat(options: ErrorPrintOptions): string {\n return options.format ?? process.env.OUTPUT_FORMAT ?? 'json'\n}\n\n/**\n * Render an error to the user. With `--format json` (or\n * `OUTPUT_FORMAT=json`), serialize the AdminError discriminated union to\n * stdout per the contract in `docs/packages/cli-exit-codes.md`. Otherwise\n * print a localized one-line message + supporting metadata to stderr.\n */\nexport function printError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): void {\n const adminError = classifyError(error)\n\n // Per docs/packages/cli-exit-codes.md: ALWAYS emit a one-line human\n // message on stderr before exiting non-zero. Under `--format json` the\n // AdminError JSON is ALSO serialized to stdout so scripts can parse it.\n const knownKey = CLI_I18N_KEYS.includes(adminError.code)\n ? (adminError.code as Parameters<typeof t>[0])\n : null\n const localized = knownKey ? t(knownKey) : null\n const rawErr =\n error && typeof error === 'object'\n ? (error as Record<string, unknown>)\n : null\n const rawMessage =\n rawErr && typeof rawErr.message === 'string' ? rawErr.message : ''\n const stringErr = typeof error === 'string' ? error : ''\n const detailMessage =\n rawErr &&\n rawErr.detail &&\n typeof rawErr.detail === 'object' &&\n typeof (rawErr.detail as Record<string, unknown>).message === 'string'\n ? String((rawErr.detail as Record<string, unknown>).message)\n : ''\n // Headline: prefer the most specific human-readable text on hand —\n // raw `message` (most common SDK shape), then a string-error directly,\n // then `detail.message`, then the localized AdminError-code translation,\n // then the bare code.\n const headline =\n rawMessage || stringErr || detailMessage || localized || adminError.code\n\n console.error(pc.red(`Error: ${headline}`))\n // Surface the raw `code`/`status` (when present and distinct) so callers\n // who throw SDK errors with proprietary codes don't lose them in the\n // human-readable rendering. The AdminError type/code is always emitted\n // — that's the canonical contract.\n if (\n rawErr &&\n typeof rawErr.code === 'string' &&\n rawErr.code !== adminError.code\n ) {\n console.error(pc.dim(`Code: ${rawErr.code}`))\n } else {\n console.error(pc.dim(`Code: ${adminError.code}`))\n }\n if (rawErr && typeof rawErr.status === 'number') {\n console.error(pc.dim(`Status: ${rawErr.status}`))\n }\n console.error(pc.dim(`Type: ${adminError.type}`))\n\n if (\n adminError.type === 'degraded' &&\n typeof adminError.retryAfter === 'number'\n ) {\n console.error(pc.yellow(`Retry after: ${adminError.retryAfter}s`))\n }\n if (rawErr && typeof rawErr.suggestion === 'string') {\n console.error(pc.yellow(rawErr.suggestion))\n }\n\n if (resolveFormat(options) === 'json') {\n console.log(JSON.stringify(adminError))\n }\n}\n\nexport function exitWithError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): never {\n printError(error, options)\n process.exit(getExitCode(error))\n}\n","export type ValidationCode = string\n\nexport type PermissionCode =\n | 'tenant_mismatch'\n | 'account_suspended'\n | 'feature_disabled'\n | 'role_denied'\n | 'credential_invalid'\n | 'pat_tenant_unpinned'\n | 'publishable_key_mismatch'\n | 'scope_denied'\n\nexport type DegradedCode =\n | 'redis_unavailable'\n | 'provider_unavailable'\n | 'rate_limited'\n\nexport type NetworkCode = 'upstream_timeout' | 'upstream_5xx' | 'dns_failure'\n\nexport type AdminErrorCode =\n | PermissionCode\n | DegradedCode\n | NetworkCode\n | ValidationCode\n\nexport type AdminError =\n | {\n type: 'validation'\n code: ValidationCode\n field?: string\n detail?: Record<string, unknown>\n }\n | {\n type: 'permission'\n code: PermissionCode\n detail?: Record<string, unknown>\n }\n | {\n type: 'degraded'\n code: DegradedCode\n retryAfter?: number\n detail?: Record<string, unknown>\n }\n | {\n type: 'network'\n code: NetworkCode\n detail?: Record<string, unknown>\n }\n\nexport const ADMIN_ERROR_CODES = {\n permission: [\n 'tenant_mismatch',\n 'account_suspended',\n 'feature_disabled',\n 'role_denied',\n 'credential_invalid',\n 'pat_tenant_unpinned',\n 'publishable_key_mismatch',\n 'scope_denied',\n ] as const satisfies readonly PermissionCode[],\n degraded: [\n 'redis_unavailable',\n 'provider_unavailable',\n 'rate_limited',\n ] as const satisfies readonly DegradedCode[],\n network: [\n 'upstream_timeout',\n 'upstream_5xx',\n 'dns_failure',\n ] as const satisfies readonly NetworkCode[],\n} as const\n\nconst PERMISSION_CODES = ADMIN_ERROR_CODES.permission\nconst DEGRADED_CODES = ADMIN_ERROR_CODES.degraded\nconst NETWORK_CODES = ADMIN_ERROR_CODES.network\n\nfunction isPermissionCode(code: string): code is PermissionCode {\n return (PERMISSION_CODES as readonly string[]).includes(code)\n}\n\nfunction isDegradedCode(code: string): code is DegradedCode {\n return (DEGRADED_CODES as readonly string[]).includes(code)\n}\n\nfunction isNetworkCode(code: string): code is NetworkCode {\n return (NETWORK_CODES as readonly string[]).includes(code)\n}\n\nexport function isUnknownAdminError(err: AdminError): boolean {\n return err.type === 'validation' && err.code === 'unknown'\n}\n\n/**\n * Shared AdminError classifier for literal codes and explicit validation shapes.\n * Surfaces that need SDK/HTTP heuristics wrap this and handle `unknown` locally.\n */\nexport function classifyAdminError(err: unknown): AdminError {\n if (err && typeof err === 'object') {\n const obj = err as Record<string, unknown>\n\n if (typeof obj.code === 'string') {\n const code = obj.code\n if (isPermissionCode(code)) {\n return { type: 'permission', code }\n }\n if (isDegradedCode(code)) {\n const out: AdminError = { type: 'degraded', code }\n if (typeof obj.retryAfter === 'number') {\n out.retryAfter = obj.retryAfter\n }\n return out\n }\n if (isNetworkCode(code)) {\n return { type: 'network', code }\n }\n }\n\n if (obj.type === 'validation' && typeof obj.code === 'string') {\n const out: AdminError = { type: 'validation', code: obj.code }\n if (typeof obj.field === 'string') out.field = obj.field\n if (obj.detail && typeof obj.detail === 'object') {\n out.detail = obj.detail as Record<string, unknown>\n }\n return out\n }\n }\n\n return {\n type: 'validation',\n code: 'unknown',\n detail: { message: err instanceof Error ? err.message : String(err) },\n }\n}\n","// CLI AdminError surface. Shared taxonomy and core classifier live in\n// `@01.software/errors`. Locale copy stays in `packages/cli/src/lib/i18n.ts`.\n// Drift is enforced by `pnpm verify:i18n-parity`.\n\nimport {\n ADMIN_ERROR_CODES,\n classifyAdminError,\n isUnknownAdminError,\n type AdminError,\n type AdminErrorCode,\n type DegradedCode,\n type NetworkCode,\n type PermissionCode,\n type ValidationCode,\n} from '@01.software/errors'\n\nexport type {\n AdminError,\n AdminErrorCode,\n DegradedCode,\n NetworkCode,\n PermissionCode,\n ValidationCode,\n}\n\nexport { ADMIN_ERROR_CODES }\n\nfunction classifyCliExtensions(err: unknown): AdminError | null {\n if (!err || typeof err !== 'object') return null\n\n const obj = err as Record<string, unknown>\n\n if (obj.code === 'auth_error' || obj.code === 'permission_error') {\n return { type: 'permission', code: 'credential_invalid' }\n }\n\n const name = typeof obj.name === 'string' ? obj.name : undefined\n const status = typeof obj.status === 'number' ? obj.status : undefined\n if (\n name === 'ConfigError' ||\n name === 'AuthError' ||\n name === 'PermissionError' ||\n status === 401 ||\n status === 403\n ) {\n return { type: 'permission', code: 'credential_invalid' }\n }\n if (\n name === 'NetworkError' ||\n name === 'TimeoutError' ||\n status === 408 ||\n status === 503\n ) {\n return { type: 'network', code: 'upstream_timeout' }\n }\n if (name === 'GoneError' || status === 404) {\n return {\n type: 'validation',\n code: 'not_found',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n if (name === 'UsageLimitError' || status === 429) {\n const out: AdminError = { type: 'degraded', code: 'rate_limited' }\n if (typeof obj.retryAfter === 'number') out.retryAfter = obj.retryAfter\n return out\n }\n if (name === 'ValidationError' || status === 400 || status === 422) {\n return {\n type: 'validation',\n code: 'invalid_argument',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n\n return null\n}\n\n/**\n * Classify an unknown thrown / rejected value into the AdminError union.\n * Applies shared taxonomy first, then CLI-only SDK/HTTP fallbacks.\n */\nexport function classifyError(err: unknown): AdminError {\n const classified = classifyAdminError(err)\n if (!isUnknownAdminError(classified)) return classified\n return classifyCliExtensions(err) ?? classified\n}\n\n/**\n * Map AdminError → CLI exit code per `docs/packages/cli-exit-codes.md`.\n */\nexport function adminErrorExitCode(err: AdminError): number {\n if (err.code === 'unknown') return 1\n switch (err.type) {\n case 'permission':\n return 2\n case 'validation':\n return err.code === 'not_found' ? 5 : 3\n case 'network':\n return 4\n case 'degraded':\n return err.code === 'rate_limited' ? 6 : 4\n }\n}\n","// CLI i18n table — mirrors `apps/console/src/lib/i18n/admin.ts` AdminError\n// code coverage so a single check (`apps/console/scripts/check-i18n-parity.ts`)\n// can verify the CLI carries every code with both KO and EN translations.\n//\n// Locale resolution:\n// 1. CLI `--lang <ko|en>` (resolved by the entry point and exported via\n// `setLocale`).\n// 2. `LANG` / `LC_ALL` environment variables — anything starting with\n// `ko` (`ko_KR.UTF-8`, `ko-KR`, …) → ko; else en.\n// 3. Default `en`.\n\nexport const CLI_I18N_KO = {\n // CLI-surface microcopy\n AuthenticationRequired: '인증이 필요합니다',\n RunLoginToAuthenticate: '`01 login` 명령으로 브라우저 인증을 진행하거나,',\n PassApiKey: '`--api-key <token>` 옵션을 전달하거나,',\n SetEnvVars:\n '`SOFTWARE_PUBLISHABLE_KEY` / `SOFTWARE_SECRET_KEY` 환경 변수를 설정하세요.',\n InvalidApiKeyFormat:\n 'API 키 형식이 올바르지 않습니다. `sk01_` 또는 `pat01_` 토큰이 필요합니다.',\n RetiredHexCredentialsRejected:\n '이전 hex 자격 증명은 더 이상 허용되지 않습니다 — `01 login`으로 다시 인증하세요.',\n InvalidJsonObject: '`--{{label}}` 인자는 JSON 객체여야 합니다.',\n InvalidJsonArray: '`--{{label}}` 인자는 JSON 배열이어야 합니다.',\n InvalidJsonValue: '`--{{label}}` 인자의 JSON 형식이 올바르지 않습니다: {{value}}',\n Empty: '(없음)',\n Total: '총 {{n}}개',\n PageOf: '{{page}} / {{total}} 페이지',\n\n // AdminError code translations (mirrors apps/console admin.ts).\n tenant_mismatch: '권한이 없는 테넌트',\n account_suspended: '계정이 정지되었습니다',\n feature_disabled: '이 기능이 비활성화되었습니다',\n role_denied: '권한이 부족합니다',\n credential_invalid: '자격 증명이 유효하지 않습니다',\n pat_tenant_unpinned: 'PAT 토큰의 테넌트가 고정되지 않았습니다',\n publishable_key_mismatch: '공개 키가 일치하지 않습니다',\n scope_denied: '범위 권한이 없습니다',\n redis_unavailable: '캐시가 일시적으로 사용 불가합니다',\n provider_unavailable: '외부 공급자가 응답하지 않습니다',\n rate_limited: '요청이 너무 많습니다 — 잠시 후 다시 시도하세요',\n upstream_timeout: '응답 시간이 초과되었습니다',\n upstream_5xx: '외부 서비스 오류',\n dns_failure: '네트워크 연결 오류',\n not_found: '리소스를 찾을 수 없습니다',\n invalid_argument: '인자가 올바르지 않습니다',\n unknown: '알 수 없는 오류',\n} as const\n\nexport type CliI18nKey = keyof typeof CLI_I18N_KO\n\nexport const CLI_I18N_EN: Record<CliI18nKey, string> = {\n AuthenticationRequired: 'Authentication required',\n RunLoginToAuthenticate:\n 'Run `01 login` to authenticate via browser, or',\n PassApiKey: 'pass `--api-key <token>`, or',\n SetEnvVars:\n 'set `SOFTWARE_PUBLISHABLE_KEY` and `SOFTWARE_SECRET_KEY` environment variables.',\n InvalidApiKeyFormat:\n 'Invalid API key format. Expected `sk01_` or `pat01_` token.',\n RetiredHexCredentialsRejected:\n 'Retired hex credentials are no longer accepted — run `01 login` to re-authenticate.',\n InvalidJsonObject: '--{{label}} must be a JSON object.',\n InvalidJsonArray: '--{{label}} must be a JSON array.',\n InvalidJsonValue: 'Invalid JSON for --{{label}}: {{value}}',\n Empty: '(empty)',\n Total: '{{n}} total',\n PageOf: 'page {{page}}/{{total}}',\n\n tenant_mismatch: 'Tenant access denied',\n account_suspended: 'Your account has been suspended',\n feature_disabled: 'This feature is disabled',\n role_denied: 'Insufficient role permissions',\n credential_invalid: 'Invalid credentials',\n pat_tenant_unpinned: 'PAT token tenant is not pinned',\n publishable_key_mismatch: 'Publishable key mismatch',\n scope_denied: 'Scope permission denied',\n redis_unavailable: 'Cache temporarily unavailable',\n provider_unavailable: 'Upstream provider unavailable',\n rate_limited: 'Too many requests — please try again shortly',\n upstream_timeout: 'Upstream request timed out',\n upstream_5xx: 'Upstream service error',\n dns_failure: 'Network connection error',\n not_found: 'Resource not found',\n invalid_argument: 'Invalid argument',\n unknown: 'Unknown error',\n}\n\nexport type Locale = 'ko' | 'en'\n\nlet activeLocale: Locale | null = null\n\nexport function detectLocale(): Locale {\n if (activeLocale) return activeLocale\n const raw =\n process.env.LC_ALL ?? process.env.LANG ?? process.env.LANGUAGE ?? ''\n return raw.toLowerCase().startsWith('ko') ? 'ko' : 'en'\n}\n\nexport function setLocale(locale: Locale | null | undefined): void {\n activeLocale = locale ?? null\n}\n\nexport function t(\n key: CliI18nKey,\n vars?: Record<string, string | number>,\n): string {\n const table = detectLocale() === 'ko' ? CLI_I18N_KO : CLI_I18N_EN\n let s: string = table[key]\n if (vars) {\n for (const [k, v] of Object.entries(vars)) {\n // Use a global regex (escape user-supplied key) instead of\n // String.prototype.replaceAll so we keep working on tsconfig\n // targets older than ES2021. Keys are statically declared above so\n // metacharacter escaping is defense-in-depth.\n const escaped = k.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n s = s.replace(new RegExp(`\\\\{\\\\{${escaped}\\\\}\\\\}`, 'g'), String(v))\n }\n }\n return s\n}\n","import { readFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { Command } from 'commander'\nimport type { ApiQueryOptions } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { parseSelect, validateCollection } from '../lib/collections.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson } from '../lib/parse.js'\n\nfunction readFileAsBlob(filePath: string): { blob: Blob; filename: string } {\n const buffer = readFileSync(filePath)\n return { blob: new Blob([buffer]), filename: basename(filePath) }\n}\n\nexport function registerCrudCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n program\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions (JSON)')\n .option('--limit <n>', 'Max results', (v: string) => parseInt(v, 10))\n .option('--page <n>', 'Page number', (v: string) => parseInt(v, 10))\n .option('--sort <field>', 'Sort field (prefix with - for descending)')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.where) options.where = parseJson(opts.where, 'where')\n if (opts.limit) options.limit = opts.limit\n if (opts.page) options.page = opts.page\n if (opts.sort) options.sort = opts.sort\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections.from(col).find(options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('get <collection> <id>')\n .description('Get a document by ID')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections.from(col).findById(id, options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('create <collection>')\n .description('Create a new document')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'create',\n collection: col,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections.from(col).create(data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update <collection> <id>')\n .description('Update a document by ID')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update',\n collection: col,\n id,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col)\n .update(id, data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete <collection> <id>')\n .description('Delete a document by ID')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete',\n collection: col,\n id,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections.from(col).remove(id)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update-many <collection>')\n .description('Update multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .requiredOption('--data <json>', 'Update data (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update-many',\n collection: col,\n where,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col)\n .updateMany(where, data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete-many <collection>')\n .description('Delete multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete-many',\n collection: col,\n where,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections.from(col).removeMany(where)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { SERVER_COLLECTIONS } from '@01.software/sdk'\n\nexport type CliCollection = (typeof SERVER_COLLECTIONS)[number]\n\nexport function validateCollection(name: string): CliCollection {\n if ((SERVER_COLLECTIONS as readonly string[]).includes(name)) {\n return name as CliCollection\n }\n\n const normalized = name.replace(/-/g, '').toLowerCase()\n const suggestions = (SERVER_COLLECTIONS as readonly string[])\n .filter((collection) => {\n const candidate = collection.replace(/-/g, '').toLowerCase()\n return (\n candidate.startsWith(normalized) ||\n normalized.startsWith(candidate) ||\n (normalized.length >= 3 && candidate.includes(normalized))\n )\n })\n .slice(0, 5)\n\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 --help\" for available collections.'\n\n throw new Error(`Unknown collection \"${name}\". ${hint}`)\n}\n\nexport function parseSelect(input: string): Record<string, boolean> {\n return Object.fromEntries(\n input\n .split(',')\n .map((field) => field.trim())\n .map((field) => [field, true]),\n )\n}\n","import { exitWithError } from './output.js'\nimport { t } from './i18n.js'\nimport type { z } from 'zod'\n\n/**\n * Throw an AdminError-shaped object so `exitWithError` can render it correctly\n * under `--format json` and exit with code 3 (validation). The `code` literal\n * `invalid_argument` is already in the validation bucket per `admin-error.ts`.\n */\nfunction failArg(\n label: string,\n value: string,\n expectedKind: 'object' | 'array' | 'value',\n): never {\n const message =\n expectedKind === 'object'\n ? t('InvalidJsonObject', { label })\n : expectedKind === 'array'\n ? t('InvalidJsonArray', { label })\n : t('InvalidJsonValue', { label, value })\n exitWithError({\n type: 'validation',\n code: 'invalid_argument',\n field: label,\n // `message` is read by `printError` for the stderr headline so the\n // user sees the label/value in the one-line summary; `detail` carries\n // the structured fields for `--format json` consumers.\n message,\n detail: { message, value, field: label },\n })\n}\n\nfunction stringifyValue(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n\nfunction formatSchemaIssues(\n label: string,\n issues: readonly { path: readonly string[]; message: string }[],\n): string {\n return issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join('.') : label\n return `${path}: ${issue.message}`\n })\n .join('; ')\n}\n\nexport function parseWithSchema<T>(\n value: unknown,\n label: string,\n schema: z.ZodType<T>,\n): T {\n const parsed = schema.safeParse(value)\n if (parsed.success) return parsed.data\n\n const issues = parsed.error.issues.map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n }))\n const message = `Invalid value for --${label}: ${formatSchemaIssues(label, issues)}`\n\n exitWithError({\n type: 'validation',\n code: 'invalid_argument',\n field: label,\n message,\n detail: {\n message,\n value: stringifyValue(value),\n field: label,\n issues,\n },\n })\n}\n\nexport function parseJson(\n value: string,\n label: string,\n options: { format?: string } = {},\n): Record<string, unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return failArg(label, value, 'object')\n }\n void options\n return parsed as Record<string, unknown>\n}\n\nexport function parseJsonArray(\n value: string,\n label: string,\n options: { format?: string } = {},\n): unknown[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (!Array.isArray(parsed)) {\n return failArg(label, value, 'array')\n }\n void options\n return parsed\n}\n","import { z } from 'zod'\n\nexport const tenantFieldConfigStateSchema = z\n .object({\n hiddenFields: z.array(z.string()),\n isHidden: z.boolean(),\n })\n .strict()\n\nexport const tenantContextQuerySchema = z\n .object({\n counts: z.literal('true').optional(),\n })\n .strict()\n\nexport const tenantContextToolInputSchema = z\n .object({\n includeCounts: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n 'Include per-collection document counts and config status (bypasses cache, slower)',\n ),\n })\n .strict()\n\nexport const tenantContextResponseSchema = z\n .object({\n tenant: z\n .object({\n id: z.string(),\n name: z.string(),\n plan: z.string(),\n planSource: z.string().optional(),\n authoritative: z.boolean().optional(),\n capabilityVersion: z.string().optional(),\n })\n .strict(),\n features: z.array(z.string()),\n collections: z\n .object({\n active: z.array(z.string()),\n inactive: z.array(z.string()),\n })\n .strict(),\n fieldConfigs: z.record(z.string(), tenantFieldConfigStateSchema),\n counts: z.record(z.string(), z.number()).optional(),\n config: z\n .object({\n webhookConfigured: z.boolean(),\n })\n .strict()\n .optional(),\n })\n .strict()\n\nexport const tenantFeatureProgressFeatureSchema = z.enum(['ecommerce'])\n\nexport const tenantFeatureProgressInputSchema = z\n .object({\n feature: tenantFeatureProgressFeatureSchema.describe(\n 'Feature to inspect for tenant implementation readiness',\n ),\n includeEvidence: z\n .boolean()\n .optional()\n .default(false)\n .describe('Include sanitized counts and static surface evidence'),\n })\n .strict()\n\nexport const tenantFeatureProgressStatusSchema = z.enum([\n 'ready',\n 'attention',\n 'blocked',\n])\n\nexport const tenantFeatureProgressItemStateSchema = z.enum([\n 'complete',\n 'incomplete',\n 'blocked',\n 'attention',\n 'optional',\n 'unknown',\n 'manual',\n 'not-applicable',\n])\n\nexport const tenantFeatureProgressSeveritySchema = z.enum([\n 'required',\n 'recommended',\n 'optional',\n])\n\nexport const tenantFeatureProgressEvidenceValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n])\n\nexport const tenantFeatureProgressItemSchema = z\n .object({\n id: z.string(),\n title: z.string(),\n state: tenantFeatureProgressItemStateSchema,\n severity: tenantFeatureProgressSeveritySchema,\n summary: z.string(),\n evidence: z\n .record(z.string(), tenantFeatureProgressEvidenceValueSchema)\n .optional(),\n })\n .strict()\n\nexport const tenantFeatureProgressGroupSchema = z\n .object({\n id: z.string(),\n title: z.string(),\n summary: z.string().optional(),\n items: z.array(tenantFeatureProgressItemSchema),\n })\n .strict()\n\nexport const tenantFeatureProgressResponseSchema = z\n .object({\n schemaVersion: z.literal(1),\n feature: tenantFeatureProgressFeatureSchema,\n status: tenantFeatureProgressStatusSchema,\n generatedAt: z.string(),\n tenant: z\n .object({\n id: z.string(),\n name: z.string(),\n plan: z.string(),\n })\n .strict(),\n capability: z\n .object({\n effectiveFeatures: z.array(z.string()),\n planBlocked: z.array(z.string()),\n closureAdded: z.array(z.string()),\n })\n .strict(),\n config: z\n .object({\n fulfillmentMode: z.enum(['shipping', 'none']),\n })\n .strict(),\n summary: z\n .object({\n complete: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n blocking: z.number().int().nonnegative(),\n manual: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n })\n .strict(),\n groups: z.array(tenantFeatureProgressGroupSchema),\n })\n .strict()\n\nexport const COLLECTION_SCHEMA_CONTRACT_VERSION = 1\n\nexport const collectionSchemaEndpointParamsSchema = z\n .object({\n collectionSlug: z.string().min(1, 'collectionSlug is required'),\n })\n .strict()\n\nexport function createCollectionSchemaToolInputSchema<\n const T extends readonly [string, ...string[]],\n>(collections: T) {\n return z\n .object({\n collection: z.enum(collections).describe('Collection name (required)'),\n })\n .strict()\n}\n\nexport const collectionFieldOptionSchema = z\n .object({\n label: z.string(),\n value: z.string(),\n })\n .strict()\n\nexport interface CollectionFieldSchema {\n name: string\n path: string\n type: string\n required?: true\n unique?: true\n hasMany?: true\n relationTo?: string | string[]\n options?: Array<{ label: string; value: string }>\n hidden?: true\n systemManaged?: true\n writable?: boolean\n fields?: CollectionFieldSchema[]\n}\n\nexport const collectionFieldSchema: z.ZodType<CollectionFieldSchema> = z.lazy(\n () =>\n z\n .object({\n name: z.string(),\n path: z.string(),\n type: z.string(),\n required: z.literal(true).optional(),\n unique: z.literal(true).optional(),\n hasMany: z.literal(true).optional(),\n relationTo: z.union([z.string(), z.array(z.string())]).optional(),\n options: z.array(collectionFieldOptionSchema).optional(),\n hidden: z.literal(true).optional(),\n systemManaged: z.literal(true).optional(),\n writable: z.boolean().optional(),\n fields: z.array(collectionFieldSchema).optional(),\n })\n .strict(),\n)\n\nexport const collectionSchemaResponseSchema = z\n .object({\n contractVersion: z.literal(COLLECTION_SCHEMA_CONTRACT_VERSION),\n mode: z.literal('effective'),\n collection: z\n .object({\n slug: z.string(),\n timestamps: z.boolean(),\n alwaysActive: z.boolean(),\n feature: z.string().nullable(),\n systemFields: z.array(z.string()),\n visibility: z\n .object({\n collectionHidden: z.boolean(),\n hiddenFields: z.array(z.string()),\n })\n .strict(),\n fields: z.array(collectionFieldSchema),\n })\n .strict(),\n })\n .strict()\n\nexport type TenantFieldConfigState = z.infer<\n typeof tenantFieldConfigStateSchema\n>\nexport type TenantContextQuery = z.input<typeof tenantContextQuerySchema>\nexport type TenantContextToolInput = z.infer<\n typeof tenantContextToolInputSchema\n>\nexport type TenantContextResponse = z.infer<typeof tenantContextResponseSchema>\nexport type TenantFeatureProgressFeature = z.infer<\n typeof tenantFeatureProgressFeatureSchema\n>\nexport type TenantFeatureProgressInput = z.infer<\n typeof tenantFeatureProgressInputSchema\n>\n/**\n * Raw feature-progress request input before schema defaults are applied.\n * `TenantFeatureProgressInput` is the parsed/effective shape.\n */\nexport type TenantFeatureProgressRequestInput = z.input<\n typeof tenantFeatureProgressInputSchema\n>\nexport type TenantFeatureProgressStatus = z.infer<\n typeof tenantFeatureProgressStatusSchema\n>\nexport type TenantFeatureProgressItemState = z.infer<\n typeof tenantFeatureProgressItemStateSchema\n>\nexport type TenantFeatureProgressSeverity = z.infer<\n typeof tenantFeatureProgressSeveritySchema\n>\nexport type TenantFeatureProgressEvidenceValue = z.infer<\n typeof tenantFeatureProgressEvidenceValueSchema\n>\nexport type TenantFeatureProgressItem = z.infer<\n typeof tenantFeatureProgressItemSchema\n>\nexport type TenantFeatureProgressGroup = z.infer<\n typeof tenantFeatureProgressGroupSchema\n>\nexport type TenantFeatureProgressResponse = z.infer<\n typeof tenantFeatureProgressResponseSchema\n>\nexport type CollectionSchemaEndpointParams = z.infer<\n typeof collectionSchemaEndpointParamsSchema\n>\nexport type CollectionFieldOption = z.infer<typeof collectionFieldOptionSchema>\nexport type CollectionSchemaResponse = z.infer<\n typeof collectionSchemaResponseSchema\n>\n","import { z } from 'zod'\n\nexport * from './product-detail'\nexport * from './product-patch'\nexport * from './product-catalog'\nexport * from './product-upsert'\nexport * from './product-options'\nexport * from './product-media'\nexport * from './product-selection-media'\nexport * from './product-gallery'\nexport * from './stock-snapshot'\nexport * from './cart-merge'\nexport * from './cart-mine'\nexport * from './checkout'\n\nexport const transactionStatusSchema = z.enum([\n 'pending',\n 'paid',\n 'failed',\n 'canceled',\n 'refunded',\n])\n\n// Order-level statuses carry no `failed`: payment failure is recorded as a\n// Transaction outcome (`Transaction.status = failed`) while the order stays\n// `pending`, and permanent abandonment uses cancellation. Transaction and\n// shipment `failed` remain supported below.\nexport const financialStatusSchema = z.enum([\n 'pending',\n 'paid',\n 'canceled',\n 'partially_refunded',\n 'refunded',\n])\n\nexport const orderDisplayFinancialStatusSchema = z.enum([\n 'pending',\n 'paid',\n 'partially_refunded',\n 'refunded',\n 'voided',\n])\n\nexport const confirmationStatusSchema = z.enum(['unconfirmed', 'confirmed'])\n\nexport const fulfillmentOrderStatusSchema = z.enum([\n 'open',\n 'in_progress',\n 'on_hold',\n 'canceled',\n 'closed',\n])\n\nexport const shipmentStatusSchema = z.enum([\n 'pending',\n 'shipped',\n 'delivered',\n 'canceled',\n 'failed',\n])\n\nexport const orderDisplayFulfillmentStatusSchema = z.enum([\n 'unfulfilled',\n 'in_progress',\n 'on_hold',\n 'partially_fulfilled',\n 'shipped',\n 'fulfilled',\n 'canceled',\n])\n\nexport const orderReturnStatusSchema = z.enum([\n 'no_return',\n 'return_requested',\n 'in_progress',\n 'returned',\n])\n\nexport type FinancialStatusValue = z.infer<typeof financialStatusSchema>\nexport type OrderDisplayFinancialStatusValue = z.infer<\n typeof orderDisplayFinancialStatusSchema\n>\nexport type ConfirmationStatusValue = z.infer<typeof confirmationStatusSchema>\nexport type FulfillmentOrderStatusValue = z.infer<\n typeof fulfillmentOrderStatusSchema\n>\nexport type ShipmentStatusValue = z.infer<typeof shipmentStatusSchema>\nexport type OrderDisplayFulfillmentStatusValue = z.infer<\n typeof orderDisplayFulfillmentStatusSchema\n>\nexport type OrderReturnStatusValue = z.infer<typeof orderReturnStatusSchema>\n\n/**\n * @deprecated This is a display-status compatibility alias for one release.\n * Do not use it as a mutation target; update financial, confirmation,\n * fulfillment-order, or shipment state through their explicit contracts.\n */\nexport const orderStatusSchema = z.enum([\n 'pending',\n 'paid',\n 'canceled',\n 'refunded',\n 'preparing',\n 'shipped',\n 'delivered',\n 'confirmed',\n 'return_requested',\n 'return_processing',\n 'returned',\n])\n\nexport const orderDisplayStatusSchema = orderStatusSchema\nexport type OrderDisplayStatusValue = z.infer<typeof orderDisplayStatusSchema>\n/** @deprecated Use OrderDisplayStatusValue for read-side display state. */\nexport type OrderStatusValue = z.infer<typeof orderStatusSchema>\n\nconst entityIdSchema = z\n .union([z.string().min(1), z.number()])\n .transform(String)\n\nexport const createOrderItemSchema = z\n .object({\n // `product` and `option` are storefront-optional: the create-order\n // endpoint derives the product from the variant's parent and snapshots\n // option selection from the variant.\n product: entityIdSchema.optional(),\n variant: entityIdSchema,\n option: entityIdSchema.optional(),\n quantity: z.number().int().positive('quantity must be a positive integer'),\n unitPrice: z.number().optional(),\n totalPrice: z.number().optional(),\n })\n .strict()\n\nexport const createOrderSchema = z\n .object({\n pgPaymentId: z.string().min(1).optional(),\n orderNumber: z.string().min(1, 'orderNumber is required'),\n customer: entityIdSchema.optional(),\n customerSnapshot: z\n .object({\n name: z.string().optional(),\n email: z.string().email('Invalid email format'),\n phone: z.string().optional(),\n })\n .strict(),\n shippingAddress: z\n .object({\n postalCode: z.string().optional(),\n address: z.string().optional(),\n detailAddress: z.string().optional(),\n deliveryMessage: z.string().optional(),\n recipientName: z.string().optional(),\n phone: z.string().optional(),\n })\n .strict()\n .optional(),\n orderItems: z\n .array(createOrderItemSchema)\n .min(1, 'At least one order item is required')\n .max(100, 'Maximum 100 items per order'),\n totalAmount: z.number().nonnegative('totalAmount must be non-negative'),\n shippingAmount: z.number().min(0).optional(),\n discountCode: z.string().optional(),\n })\n .strict()\n\nexport const CreateOrderSchema = createOrderSchema\n\nexport const updateTransactionSchema = z\n .object({\n pgPaymentId: z\n .string()\n .min(1, 'pgPaymentId is required')\n .describe('PG payment ID (required)'),\n status: transactionStatusSchema.describe(\n 'New transaction status (required)',\n ),\n paymentMethod: z.string().optional().describe('Payment method (optional)'),\n receiptUrl: z.string().optional().describe('Receipt URL (optional)'),\n paymentKey: z\n .string()\n .min(1)\n .optional()\n .describe('Provider payment key for verified paid confirmation'),\n amount: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('Provider-confirmed amount for verified paid confirmation'),\n })\n .strict()\n\nexport const UpdateTransactionSchema = updateTransactionSchema\n\nconst providerSlugSchema = z\n .string()\n .trim()\n .regex(/^[a-z0-9][a-z0-9_-]{0,63}$/, 'pgProvider must be lowercase slug')\n\nexport const confirmPaymentSchema = z\n .object({\n orderNumber: z.string().min(1).optional(),\n pgPaymentId: z\n .string()\n .min(1, 'pgPaymentId is required')\n .describe('Provider payment identifier stored on the transaction'),\n pgProvider: providerSlugSchema.describe(\n 'Payment provider slug, e.g. toss, portone, stripe',\n ),\n pgOrderId: z.string().min(1).optional(),\n amount: z\n .number()\n .int()\n .nonnegative('amount must be non-negative')\n .describe('Provider-confirmed amount in minor units'),\n currency: z.string().min(1).optional(),\n paymentMethod: z.string().optional(),\n receiptUrl: z.string().url().optional(),\n approvedAt: z.string().optional(),\n providerStatus: z.string().optional(),\n providerEventId: z.string().min(1).optional(),\n confirmationSource: z\n .enum([\n 'provider_webhook',\n 'provider_lookup',\n 'provider_api_confirm',\n 'manual_server',\n ])\n .optional(),\n paymentKey: z\n .string()\n .min(1)\n .optional()\n .describe(\n 'Optional provider payment key from the client confirm handshake; stored for BFF/provider refund workflows (also accepted as metadata.tossPaymentKey). Local cancel does not read this field.',\n ),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict()\n\nexport const ConfirmPaymentSchema = confirmPaymentSchema\n\n/**\n * Single-source `confirmPayment` response shape. Console\n * (`FinalizeProviderPaymentResult`) aliases this and the SDK hand-type\n * (`ConfirmPaymentResponse`) is locked to it by a bidirectional parity\n * `test-d`, so the wire response has one owner.\n */\nexport const confirmPaymentResponseSchema = z\n .object({\n orderId: z.string().min(1),\n transactionId: z.string().min(1),\n status: z.literal('paid'),\n alreadyConfirmed: z.boolean().optional(),\n })\n .strict()\n\nexport const ConfirmPaymentResponseSchema = confirmPaymentResponseSchema\n\n/**\n * Machine-readable return reason codes. Console label maps and the SDK\n * `ReturnReason` union derive from this single source (parity-tested), mirroring\n * the product-upsert reason-code precedent.\n */\nexport const RETURN_REASON_CODES = [\n 'change_of_mind',\n 'defective',\n 'wrong_delivery',\n 'damaged',\n 'other',\n] as const\n\nexport const returnReasonSchema = z.enum(RETURN_REASON_CODES)\n\n/**\n * Machine-readable return *rejection* reason codes. Distinct from the\n * customer-supplied return reasons above: these are operator-selected reasons\n * for denying a return (mirroring the cancel-reason-code precedent). The Console\n * label map and the persisted `returns.rejectionReasonCode` field derive from\n * this single source (parity-tested).\n */\nexport const RETURN_REJECTION_REASON_CODES = [\n 'window_expired',\n 'used_or_damaged',\n 'non_returnable',\n 'other',\n] as const\n\nexport const returnRejectionReasonCodeSchema = z.enum(\n RETURN_REJECTION_REASON_CODES,\n)\n\nexport const restockActionSchema = z.enum(['return_to_stock', 'discard'])\n\nexport const returnWithRefundItemSchema = z\n .object({\n orderItem: z.union([z.string().min(1), z.number()]).transform(String),\n quantity: z.number().int().positive('quantity must be a positive integer'),\n restockAction: restockActionSchema.default('return_to_stock'),\n restockingFee: z\n .number()\n .min(0, 'restockingFee must be non-negative')\n .optional()\n .describe('Restocking fee charged for this line (ADR 0005 §Gap 1)'),\n })\n .strict()\n\nexport const returnWithRefundSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number (required)'),\n reason: returnReasonSchema.optional().describe('Return reason (optional)'),\n reasonDetail: z\n .string()\n .optional()\n .describe('Detailed reason text (optional)'),\n returnItems: z\n .array(returnWithRefundItemSchema)\n .min(1, 'At least one return item is required')\n .max(100, 'Too many return items')\n .describe('Array of products to return (required)'),\n refundAmount: z\n .number()\n .min(0, 'refundAmount must be non-negative')\n .describe('Refund amount (required, min 0)'),\n returnShippingFee: z\n .number()\n .min(0, 'returnShippingFee must be non-negative')\n .optional()\n .describe(\n 'Return shipping fee charged to the customer (ADR 0005 §Gap 1)',\n ),\n initialShippingRefundAmount: z\n .number()\n .min(0, 'initialShippingRefundAmount must be non-negative')\n .optional()\n .describe('Initial order shipping amount refunded to the customer'),\n initialShippingRefundOverrideNote: z\n .string()\n .min(1)\n .optional()\n .describe(\n 'Operator audit note required when overriding policy suggestion',\n ),\n pgPaymentId: z\n .string()\n .min(1, 'pgPaymentId is required')\n .describe('PG payment ID for refund (required)'),\n paymentKey: z\n .string()\n .min(1)\n .optional()\n .describe('Provider payment key for verified refund'),\n refundReceiptUrl: z\n .string()\n .optional()\n .describe('Refund receipt URL (optional)'),\n })\n .strict()\n\nexport const createReturnSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number (required)'),\n reason: returnReasonSchema.optional().describe('Return reason (optional)'),\n reasonDetail: z\n .string()\n .optional()\n .describe('Detailed reason text (optional)'),\n returnItems: z\n .array(returnWithRefundItemSchema)\n .min(1, 'At least one return item is required')\n .max(100, 'Too many return items')\n .describe('Array of products to return (required)'),\n refundAmount: z\n .number()\n .min(0, 'refundAmount must be non-negative')\n .describe(\n 'Line refund amount before initial shipping refund (required, min 0)',\n ),\n returnShippingFee: z\n .number()\n .min(0, 'returnShippingFee must be non-negative')\n .optional()\n .describe('Return shipping fee charged to the customer'),\n initialShippingRefundAmount: z\n .number()\n .min(0, 'initialShippingRefundAmount must be non-negative')\n .optional()\n .describe('Initial order shipping amount refunded to the customer'),\n initialShippingRefundOverrideNote: z\n .string()\n .min(1)\n .optional()\n .describe(\n 'Operator audit note required when overriding policy suggestion',\n ),\n })\n .strict()\n\nexport const CreateReturnSchema = createReturnSchema\nexport const ReturnWithRefundSchema = returnWithRefundSchema\n\n/**\n * Machine-readable order cancellation reason codes. Console label maps and the\n * SDK `CancelReasonCode` union derive from this single source (parity-tested).\n */\nexport const CANCEL_REASON_CODES = [\n 'customer',\n 'inventory',\n 'fraud',\n 'declined',\n 'staff',\n 'other',\n] as const\n\nexport const cancelReasonCodeSchema = z.enum(CANCEL_REASON_CODES)\n\n/**\n * Machine-readable operator force-resolution reason codes (operational return /\n * fulfillment-mistake corrections). Single source for Console's\n * `forceResolveOrderMistake` reason union.\n */\nexport const FORCE_RESOLUTION_REASON_CODES = [\n 'staff_error',\n 'wrong_fulfillment',\n 'other',\n] as const\n\nexport const forceResolutionReasonCodeSchema = z.enum(\n FORCE_RESOLUTION_REASON_CODES,\n)\n\nexport const idempotencyKeySchema = z\n .string()\n .trim()\n .min(1, 'idempotencyKey is required')\n .max(255, 'idempotencyKey must be 255 characters or fewer')\n .regex(\n /^[\\x21-\\x7E]+$/,\n 'idempotencyKey must contain only printable header-safe characters',\n )\n\nexport const cancelOrderSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number to cancel'),\n reasonCode: cancelReasonCodeSchema\n .default('other')\n .describe('Operator-selected cancel reason code'),\n reasonDetail: z\n .string()\n .trim()\n .max(2000, 'reasonDetail must be 2000 characters or fewer')\n .optional()\n .describe('Internal cancellation detail stored on the order'),\n })\n .strict()\n\nexport const CancelOrderSchema = cancelOrderSchema\n\nconst cancelOrderResponseBaseSchema = {\n orderId: z.string().min(1),\n} satisfies z.ZodRawShape\n\nconst unpaidLocalCancelCommittedResponseFields = {\n refundedAmount: z.literal(0),\n providerRefunded: z.literal(false),\n} satisfies z.ZodRawShape\n\nconst paidLocalCancelCommittedResponseFields = {\n transactionId: z.string().min(1),\n refundedAmount: z.literal(0),\n providerRefunded: z.literal(false),\n refundPending: z.literal(true),\n} satisfies z.ZodRawShape\n\nconst legacyProviderRefundResponseFields = {\n transactionId: z.string().min(1),\n refundedAmount: z.number().int().positive(),\n refundSeq: z.number().int().positive(),\n providerRefunded: z.literal(true),\n} satisfies z.ZodRawShape\n\nconst alreadyCanceledResponseFields = {\n refundedAmount: z.number().int().nonnegative(),\n providerRefunded: z.literal(false),\n} satisfies z.ZodRawShape\n\nconst alreadyCanceledRefundPendingResponseFields = {\n transactionId: z.string().min(1),\n refundedAmount: z.number().int().nonnegative(),\n providerRefunded: z.literal(false),\n refundPending: z.literal(true),\n} satisfies z.ZodRawShape\n\n/** @deprecated Inline PG cancel reconciliation removed; retained for type migration only. */\nexport const cancelOrderReconciliationStatusSchema = z.enum([\n 'paid',\n 'preparing',\n 'shipped',\n 'delivered',\n 'confirmed',\n 'return_requested',\n 'return_processing',\n 'returned',\n 'refunded',\n])\n\nexport const cancelOrderResponseSchema = z.union([\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...paidLocalCancelCommittedResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(true),\n })\n .strict(),\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...unpaidLocalCancelCommittedResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(true),\n })\n .strict(),\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...alreadyCanceledResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(false),\n alreadyCanceled: z.literal(true),\n })\n .strict(),\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...alreadyCanceledRefundPendingResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(false),\n alreadyCanceled: z.literal(true),\n })\n .strict(),\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...legacyProviderRefundResponseFields,\n status: cancelOrderReconciliationStatusSchema,\n cancelCommitted: z.literal(false),\n reconciliationRequired: z.literal(true),\n })\n .strict(),\n])\n\nexport const CancelOrderResponseSchema = cancelOrderResponseSchema\n\nexport const resolveCancelRefundOutcomeSchema = z.enum(['succeeded', 'failed'])\n\nexport const resolveCancelRefundSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number whose pending cancel refund is being resolved'),\n idempotencyKey: idempotencyKeySchema.describe(\n 'Stable key for this PG refund result report',\n ),\n outcome: resolveCancelRefundOutcomeSchema.describe(\n 'PG refund result reported by the storefront or BFF',\n ),\n refundedAmount: z\n .number()\n .int('refundedAmount must be an integer minor-unit amount')\n .nonnegative('refundedAmount must be nonnegative'),\n pgProvider: z\n .string()\n .trim()\n .min(1, 'pgProvider is required')\n .regex(\n /^[a-z0-9][a-z0-9_-]*$/,\n 'pgProvider must be a lowercase provider slug',\n ),\n pgRefundId: z.string().trim().min(1).optional(),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (value.outcome === 'succeeded' && value.refundedAmount <= 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['refundedAmount'],\n message: 'refundedAmount must be positive when outcome is succeeded',\n })\n }\n\n if (value.outcome === 'succeeded' && !value.pgRefundId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['pgRefundId'],\n message: 'pgRefundId is required when outcome is succeeded',\n })\n }\n\n if (value.outcome === 'failed' && value.refundedAmount !== 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['refundedAmount'],\n message: 'refundedAmount must be 0 when outcome is failed',\n })\n }\n })\n\nexport const ResolveCancelRefundSchema = resolveCancelRefundSchema\n\nexport const resolveCancelRefundResponseSchema = z.union([\n z\n .object({\n orderId: z.string().min(1),\n transactionId: z.string().min(1),\n refundTransactionId: z.string().min(1),\n refundedAmount: z.number().int().positive(),\n refundStatus: z.literal('succeeded'),\n transactionStatus: z.literal('refunded'),\n })\n .strict(),\n z\n .object({\n orderId: z.string().min(1),\n transactionId: z.string().min(1),\n refundTransactionId: z.string().min(1),\n refundedAmount: z.literal(0),\n refundStatus: z.literal('failed'),\n transactionStatus: z.literal('paid'),\n })\n .strict(),\n])\n\nexport const ResolveCancelRefundResponseSchema =\n resolveCancelRefundResponseSchema\n\nexport type TransactionStatus = z.infer<typeof transactionStatusSchema>\nexport type UpdateTransactionParams = z.input<typeof UpdateTransactionSchema>\nexport type ParsedUpdateTransactionParams = z.output<\n typeof UpdateTransactionSchema\n>\nexport type CreateOrderParams = z.input<typeof CreateOrderSchema>\nexport type ParsedCreateOrderParams = z.output<typeof CreateOrderSchema>\nexport type CreateOrderItemParams = z.input<typeof createOrderItemSchema>\nexport type ParsedCreateOrderItemParams = z.output<typeof createOrderItemSchema>\nexport type ConfirmPaymentParams = z.input<typeof ConfirmPaymentSchema>\nexport type ParsedConfirmPaymentParams = z.output<typeof ConfirmPaymentSchema>\nexport type ConfirmPaymentResponse = z.output<\n typeof confirmPaymentResponseSchema\n>\nexport type ReturnReason = z.infer<typeof returnReasonSchema>\nexport type ReturnRejectionReasonCode = z.infer<\n typeof returnRejectionReasonCodeSchema\n>\nexport type RestockAction = z.infer<typeof restockActionSchema>\nexport type ReturnWithRefundItem = z.input<typeof returnWithRefundItemSchema>\nexport type ParsedReturnWithRefundItem = z.output<\n typeof returnWithRefundItemSchema\n>\nexport type ReturnWithRefundParams = z.input<typeof ReturnWithRefundSchema>\nexport type ParsedReturnWithRefundParams = z.output<\n typeof ReturnWithRefundSchema\n>\nexport type CreateReturnParams = z.input<typeof CreateReturnSchema>\nexport type ParsedCreateReturnParams = z.output<typeof CreateReturnSchema>\nexport type CancelReasonCode = z.infer<typeof cancelReasonCodeSchema>\nexport type ForceResolutionReasonCode = z.infer<\n typeof forceResolutionReasonCodeSchema\n>\nexport type IdempotencyKey = z.infer<typeof idempotencyKeySchema>\nexport type CancelOrderReconciliationStatus = z.infer<\n typeof cancelOrderReconciliationStatusSchema\n>\nexport type CancelOrderParams = z.input<typeof CancelOrderSchema>\nexport type ParsedCancelOrderParams = z.output<typeof CancelOrderSchema>\nexport type CancelOrderRequestParams = {\n orderNumber: string\n reasonCode?: CancelReasonCode\n reasonDetail?: string\n idempotencyKey?: IdempotencyKey\n}\nexport type CancelOrderResponse = z.output<typeof CancelOrderResponseSchema>\nexport type ResolveCancelRefundOutcome = z.infer<\n typeof resolveCancelRefundOutcomeSchema\n>\nexport type ResolveCancelRefundParams = z.input<\n typeof ResolveCancelRefundSchema\n>\nexport type ParsedResolveCancelRefundParams = z.output<\n typeof ResolveCancelRefundSchema\n>\nexport type ResolveCancelRefundSucceededRequestParams = Omit<\n ResolveCancelRefundParams,\n 'outcome' | 'refundedAmount' | 'pgRefundId'\n> & {\n outcome: 'succeeded'\n refundedAmount: number\n pgRefundId: string\n}\nexport type ResolveCancelRefundFailedRequestParams = Omit<\n ResolveCancelRefundParams,\n 'outcome' | 'refundedAmount'\n> & {\n outcome: 'failed'\n refundedAmount: 0\n}\nexport type ResolveCancelRefundRequestParams =\n | ResolveCancelRefundSucceededRequestParams\n | ResolveCancelRefundFailedRequestParams\nexport type ResolveCancelRefundResponse = z.output<\n typeof ResolveCancelRefundResponseSchema\n>\n","import { z } from 'zod'\n\nconst IdSchema = z.union([z.string(), z.number()]).transform(String)\nconst RemovedLegacyMediaFieldSchema = z.unknown().optional()\n\nexport const PRODUCT_UPSERT_UNKNOWN_FIELD_REASON = 'unknown_field' as const\nexport const PRODUCT_UPSERT_READONLY_FIELD_REASON =\n 'product_field_readonly' as const\nexport const PRODUCT_GRAPH_CONFLICT_REASON = 'graph_conflict' as const\nexport const PRODUCT_GRAPH_REVISION_REQUIRED_REASON =\n 'graph_revision_required' as const\n\nexport const PRODUCT_READONLY_FIELDS = [\n 'isSoldOut',\n '_order',\n 'tenant',\n] as const\n\nconst productFieldShape = {\n id: IdSchema.optional(),\n title: z.string().min(1).optional(),\n subtitle: z.string().optional().nullable(),\n description: z.string().optional().nullable(),\n status: z.string().optional(),\n slug: z.string().optional(),\n images: z.array(IdSchema).optional(),\n mediaSets: RemovedLegacyMediaFieldSchema,\n vendor: z.string().optional().nullable(),\n productType: z.string().optional().nullable(),\n brand: IdSchema.optional().nullable(),\n shippingPolicy: IdSchema.optional().nullable(),\n weight: z.number().int().min(0).optional().nullable(),\n minOrderQuantity: z.number().int().min(1).optional().nullable(),\n maxOrderQuantity: z.number().int().min(1).optional().nullable(),\n isFeatured: z.boolean().optional(),\n publishedAt: z.string().optional().nullable(),\n categories: z.array(IdSchema).optional(),\n tags: z.array(IdSchema).optional(),\n seo: z\n .object({\n title: z.string().optional().nullable(),\n description: z.string().optional().nullable(),\n })\n .optional()\n .nullable(),\n metadata: z.unknown().optional(),\n} as const\n\nexport const PRODUCT_UPSERT_PRODUCT_FIELDS = Object.keys(\n productFieldShape,\n) as (keyof typeof productFieldShape)[]\n\nexport const PRODUCT_UPSERT_EDIT_PRODUCT_FIELDS = ['id'] as const\n\nconst ProductFieldsSchema = z\n .object(productFieldShape)\n .passthrough()\n .superRefine((value, ctx) => {\n for (const field of ['primaryMediaItemId', 'thumbnail'] as const) {\n if (Object.prototype.hasOwnProperty.call(value, field)) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'Product media is ordered like Shopify. Use product.images and put the featured image first.',\n path: [field],\n })\n }\n }\n })\n\n/**\n * Base option-value object shape. Exported so strict consumers (e.g. the MCP\n * product-upsert tool) can reject unknown keys via `.strict()` without\n * duplicating the field list. The runtime `OptionValueInputSchema` keeps its\n * passthrough + legacy-`swatchColor` rejection semantics.\n */\nexport const OptionValueObjectSchema = z.object({\n id: IdSchema.optional(),\n value: z.string().min(1, 'Option value `value` is required'),\n slug: z.string().optional(),\n swatch: z\n .object({\n type: z.enum(['color', 'media']).optional().nullable(),\n color: z.string().optional().nullable(),\n mediaItemId: IdSchema.optional().nullable(),\n })\n .optional()\n .nullable(),\n thumbnail: RemovedLegacyMediaFieldSchema,\n images: RemovedLegacyMediaFieldSchema,\n metadata: z.unknown().optional(),\n})\n\nconst OptionValueInputSchema =\n OptionValueObjectSchema.passthrough().superRefine((value, ctx) => {\n if (Object.prototype.hasOwnProperty.call(value, 'swatchColor')) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'Option value field `swatchColor` was removed. Use nested `swatch.color` instead.',\n path: ['swatchColor'],\n })\n }\n })\n\nexport const OptionInputSchema = z.object({\n id: IdSchema.optional(),\n title: z.string().min(1, 'Option `title` is required'),\n slug: z.string().optional(),\n values: z\n .array(OptionValueInputSchema)\n .min(1, 'Each option must have at least one value'),\n})\n\nconst VariantOptionValueObjectSchema = z\n .object({\n valueSlug: z.string().optional(),\n valueId: IdSchema.optional(),\n value: z.string().optional(),\n })\n .refine((data) => Boolean(data.valueSlug ?? data.valueId ?? data.value), {\n message:\n 'Variant option value object requires valueSlug, valueId, or value',\n })\n\nexport const VariantInputSchema = z.object({\n id: IdSchema.optional(),\n optionValues: z\n .union([\n z.record(\n z.string(),\n z.union([z.string(), VariantOptionValueObjectSchema]),\n ),\n z.array(IdSchema),\n ])\n .optional(),\n sku: z.string().optional().nullable(),\n title: z.string().optional().nullable(),\n price: z.number().min(0),\n compareAtPrice: z.number().min(0).optional().nullable(),\n stock: z.number().int().min(0).optional(),\n isUnlimited: z.boolean().optional(),\n inventoryPolicy: z.enum(['deny', 'continue']).optional(),\n weight: z.number().int().min(0).optional().nullable(),\n requiresShipping: z.boolean().optional(),\n barcode: z.string().optional().nullable(),\n externalId: z.string().optional().nullable(),\n isActive: z.boolean().optional(),\n images: z.array(IdSchema).optional(),\n thumbnail: RemovedLegacyMediaFieldSchema,\n featuredMediaItemId: RemovedLegacyMediaFieldSchema,\n metadata: z.unknown().optional(),\n})\n\n/** Base object schema for `.shape` consumers (MCP tool fields). */\nexport const ProductUpsertObjectSchema = z.object({\n /** Required on graph edit when the server graph is non-empty (`productId` set); optional for first seed on an empty graph. */\n graphRevision: z.string().optional(),\n productId: IdSchema.optional(),\n product: ProductFieldsSchema.optional(),\n options: z.array(OptionInputSchema).max(10).optional().default([]),\n variants: z.array(VariantInputSchema).max(500).optional().default([]),\n})\n\nexport const ProductUpsertSchema = ProductUpsertObjectSchema.superRefine(\n (data, ctx) => {\n const nestedProductId = data.product?.id\n if (\n data.productId != null &&\n nestedProductId != null &&\n String(data.productId) !== String(nestedProductId)\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'productId must match product.id when both are set on graph upsert.',\n path: ['productId'],\n })\n }\n\n const productId = data.productId ?? nestedProductId\n const isEdit = productId != null\n\n if (!isEdit && data.productId != null) {\n ctx.addIssue({\n code: 'custom',\n message: 'productId is not allowed when creating a product.',\n path: ['productId'],\n })\n }\n\n if (!isEdit && !data.product?.title) {\n ctx.addIssue({\n code: 'custom',\n message: 'Product `title` is required when creating a new product.',\n path: ['product', 'title'],\n })\n }\n\n if (isEdit && data.product) {\n for (const key of Object.keys(data.product)) {\n if (key !== 'id') {\n ctx.addIssue({\n code: 'custom',\n message:\n 'Existing product graph upsert accepts only product identity. Save document fields through Payload.',\n path: ['product', key],\n })\n }\n }\n }\n },\n)\n\n/** Create: `product.title` required; no `productId`. */\nexport type ProductUpsertCreateInput = {\n graphRevision?: string\n product: ProductFieldsInput & { title: string }\n options?: OptionInput[]\n variants?: VariantInput[]\n}\n\n/** Edit: graph-only; document fields via Payload / Admin save. */\nexport type ProductUpsertEditInput = {\n graphRevision?: string\n productId: string\n options?: OptionInput[]\n variants?: VariantInput[]\n}\n\n/** Edit (legacy carrier): `product: { id }` only — prefer `productId`. */\nexport type ProductUpsertEditNestedIdInput = {\n graphRevision?: string\n product: { id: string }\n options?: OptionInput[]\n variants?: VariantInput[]\n}\n\n/** Parsed upsert body (Zod defaults + refine). Prefer this at API boundaries. */\nexport type ProductUpsertInput = z.infer<typeof ProductUpsertSchema>\n\nexport type ProductFieldsInput = z.infer<typeof ProductFieldsSchema>\nexport type OptionInput = z.infer<typeof OptionInputSchema>\nexport type OptionValueInput = z.infer<typeof OptionValueInputSchema>\nexport type VariantInput = z.infer<typeof VariantInputSchema>\n","import { Command } from 'commander'\nimport { createOrderSchema, cancelOrderSchema } from '@01.software/contracts'\nimport { z } from 'zod'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson, parseJsonArray, parseWithSchema } from '../lib/parse.js'\n\nconst idSchema = z.union([z.string().min(1), z.number()]).transform(String)\n\nconst customerSnapshotSchema = z\n .object({\n email: z.string().email('Invalid email format'),\n name: z.string().optional(),\n phone: z.string().optional(),\n })\n .strict()\n\nconst orderStatusSchema = z.enum(['confirmed'])\n\nconst fulfillmentStatusSchema = z.enum(['shipped', 'delivered', 'failed'])\n\nconst updateFulfillmentSchema = z\n .object({\n fulfillmentId: idSchema,\n status: fulfillmentStatusSchema.optional(),\n carrier: z.string().min(1).optional(),\n trackingNumber: z.string().min(1).optional(),\n })\n .refine(\n (value) =>\n value.status !== undefined ||\n value.carrier !== undefined ||\n value.trackingNumber !== undefined,\n {\n message: 'status, carrier, or trackingNumber is required',\n },\n )\n\nconst fulfillmentItemsSchema = z\n .array(\n z\n .object({\n orderItem: idSchema,\n quantity: z\n .number()\n .int()\n .positive('quantity must be a positive integer'),\n })\n .strict(),\n )\n .min(1, 'At least one fulfillment item is required')\n .max(100, 'Maximum 100 items per fulfillment')\n\nexport function registerOrderCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const order = program.command('order').description('Order management')\n\n order\n .command('create')\n .description('Create a new order')\n .option('--payment-id <id>', 'Payment ID')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--email <email>', 'Customer email')\n .option('--customer <id>', 'Customer ID')\n .option('--name <name>', 'Customer name')\n .option('--phone <phone>', 'Customer phone')\n .requiredOption('--shipping-address <json>', 'Shipping address (JSON)')\n .requiredOption('--products <json>', 'Order products array (JSON)')\n .requiredOption('--total-amount <n>', 'Total amount', parseFloat)\n .option('--shipping-amount <n>', 'Shipping amount', parseFloat)\n .option('--discount-code <code>', 'Discount code')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n {\n pgPaymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot: {\n email: opts.email,\n name: opts.name,\n phone: opts.phone,\n },\n customer: opts.customer,\n shippingAddress: parseJson(\n opts.shippingAddress,\n 'shipping-address',\n ),\n orderItems: parseJsonArray(opts.products, 'products'),\n totalAmount: opts.totalAmount,\n shippingAmount: opts.shippingAmount,\n discountCode: opts.discountCode,\n },\n 'order',\n createOrderSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.create(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('get <orderNumber>')\n .description('Get an order by order number')\n .action(async (orderNumber: string) => {\n try {\n const client = getClient()\n const {\n docs: [order],\n } = await client.collections\n .from('orders')\n .find({\n where: { orderNumber: { equals: orderNumber } },\n limit: 1,\n depth: 1,\n })\n if (!order) throw new Error('Order not found')\n printResult(order, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('update <orderNumber>')\n .description('Confirm a delivered order purchase')\n .requiredOption('--status <status>', 'New status (confirmed only)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const status = parseWithSchema(opts.status, 'status', orderStatusSchema)\n const data = { orderNumber, status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.update(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('cancel <orderNumber>')\n .description('Cancel an eligible order')\n .option(\n '--reason-code <code>',\n 'Cancel reason (customer, inventory, fraud, declined, staff, other)',\n )\n .option('--reason-detail <text>', 'Internal cancellation detail')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n orderNumber,\n ...(opts.reasonCode ? { reasonCode: opts.reasonCode } : {}),\n ...(opts.reasonDetail ? { reasonDetail: opts.reasonDetail } : {}),\n },\n 'cancel',\n cancelOrderSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order cancel', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.cancelOrder(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('checkout')\n .description('Convert a cart to an order')\n .requiredOption('--cart-id <id>', 'Cart ID')\n .option('--payment-id <id>', 'Payment ID (optional for free orders)')\n .requiredOption('--order-number <num>', 'Order number')\n .requiredOption('--customer <json>', 'Customer snapshot (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const customerSnapshot = parseWithSchema(\n parseJson(opts.customer, 'customer'),\n 'customer',\n customerSnapshotSchema,\n )\n const data = {\n cartId: opts.cartId,\n pgPaymentId: opts.paymentId,\n orderNumber: opts.orderNumber,\n customerSnapshot,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order checkout', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.checkout({\n ...data,\n customerSnapshot: customerSnapshot as Parameters<\n typeof client.commerce.orders.checkout\n >[0]['customerSnapshot'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('prepare <orderNumber>')\n .description('Move paid order fulfillment work to preparation')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = { orderNumber }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order prepare', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result =\n await client.commerce.orders.prepareFulfillmentOrder(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('fulfill <orderNumber>')\n .description('Create a shipment for a prepared order')\n .option('--items <json>', 'Fulfillment items array (JSON)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const items = opts.items\n ? parseWithSchema(\n parseJsonArray(opts.items, 'items'),\n 'items',\n fulfillmentItemsSchema,\n )\n : undefined\n const data = {\n orderNumber,\n ...(opts.carrier ? { carrier: opts.carrier } : {}),\n ...(opts.trackingNumber\n ? { trackingNumber: opts.trackingNumber }\n : {}),\n ...(items ? { items } : {}),\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order fulfill', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createFulfillment({\n ...data,\n ...(items\n ? {\n items: items as Parameters<\n typeof client.commerce.orders.createFulfillment\n >[0]['items'],\n }\n : {}),\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('update-fulfillment <fulfillmentId>')\n .description('Update shipment status or tracking information')\n .option('--status <status>', 'Shipment status (shipped, delivered, failed)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (fulfillmentId: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n fulfillmentId,\n ...(opts.status ? { status: opts.status } : {}),\n ...(opts.carrier ? { carrier: opts.carrier } : {}),\n ...(opts.trackingNumber\n ? { trackingNumber: opts.trackingNumber }\n : {}),\n },\n 'fulfillment',\n updateFulfillmentSchema,\n )\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'order update-fulfillment',\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateFulfillment(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport {\n createReturnSchema,\n returnWithRefundSchema,\n} from '@01.software/contracts'\nimport { z } from 'zod'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray, parseWithSchema } from '../lib/parse.js'\n\nconst returnStatusSchema = z.enum([\n 'processing',\n 'approved',\n 'rejected',\n 'completed',\n])\n\nexport function registerReturnCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const ret = program.command('return').description('Return management')\n\n ret\n .command('create <orderNumber>')\n .description('Create a return request')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .option(\n '--return-shipping-fee <n>',\n 'Return shipping fee charged to the customer',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-amount <n>',\n 'Initial order shipping refund amount',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-note <text>',\n 'Audit note for manual initial shipping refund override',\n )\n .option(\n '--reason <reason>',\n 'Return reason (change_of_mind, defective, wrong_delivery, damaged, other)',\n )\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n orderNumber,\n returnItems: parseJsonArray(opts.products, 'products'),\n refundAmount: opts.refundAmount,\n returnShippingFee: opts.returnShippingFee,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n initialShippingRefundAmount: opts.initialShippingRefundAmount,\n initialShippingRefundOverrideNote: opts.initialShippingRefundNote,\n },\n 'return',\n createReturnSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createReturn({\n ...data,\n returnItems: data.returnItems as Parameters<\n typeof client.commerce.orders.createReturn\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('update <returnId>')\n .description('Update return status')\n .requiredOption(\n '--status <status>',\n 'New status (processing, approved, rejected, completed)',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (returnId: string, opts) => {\n try {\n const status = parseWithSchema(\n opts.status,\n 'status',\n returnStatusSchema,\n )\n const data = { returnId, status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateReturn(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('refund <orderNumber>')\n .description('Return with refund')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .requiredOption('--payment-id <id>', 'Payment ID')\n .option(\n '--return-shipping-fee <n>',\n 'Return shipping fee charged to the customer',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-amount <n>',\n 'Initial order shipping refund amount',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-note <text>',\n 'Audit note for manual initial shipping refund override',\n )\n .option('--reason <reason>', 'Return reason')\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--refund-receipt-url <url>', 'Refund receipt URL')\n .option('--payment-key <key>', 'Provider payment key')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n orderNumber,\n returnItems: parseJsonArray(opts.products, 'products'),\n refundAmount: opts.refundAmount,\n returnShippingFee: opts.returnShippingFee,\n pgPaymentId: opts.paymentId,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n refundReceiptUrl: opts.refundReceiptUrl,\n paymentKey: opts.paymentKey,\n initialShippingRefundAmount: opts.initialShippingRefundAmount,\n initialShippingRefundOverrideNote: opts.initialShippingRefundNote,\n },\n 'return',\n returnWithRefundSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return refund', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.returnWithRefund({\n ...data,\n returnItems: data.returnItems as Parameters<\n typeof client.commerce.orders.returnWithRefund\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerCartCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const cart = program.command('cart').description('Cart management')\n\n cart\n .command('create')\n .description('Create a cart and print its cartToken handle')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart create', data: {} },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.create()\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('add <cartToken>')\n .description('Add an item to a cart (addressed by its cartToken)')\n .requiredOption('--product <id>', 'Product ID')\n .requiredOption('--variant <id>', 'Variant ID')\n .requiredOption('--option <id>', 'Option ID')\n .requiredOption('--quantity <n>', 'Quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartToken: string, opts) => {\n try {\n const data = {\n cartToken,\n product: opts.product,\n variant: opts.variant,\n option: opts.option,\n quantity: opts.quantity,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart add', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.addItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('update <cartItemId>')\n .description('Update cart item quantity')\n .requiredOption('--cart-token <token>', 'Cart token (cart handle)')\n .requiredOption('--quantity <n>', 'New quantity', (v: string) =>\n parseInt(v, 10),\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n const data = {\n cartToken: opts.cartToken,\n cartItemId,\n quantity: opts.quantity,\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.updateItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('remove <cartItemId>')\n .description('Remove an item from a cart')\n .requiredOption('--cart-token <token>', 'Cart token (cart handle)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartItemId: string, opts) => {\n try {\n const data = { cartToken: opts.cartToken, cartItemId }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart remove', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.removeItem(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('clear <cartToken>')\n .description('Remove all items from a cart')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartToken: string, opts) => {\n try {\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart clear', data: { cartToken } },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.clear({ cartToken })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('apply-discount <cartToken>')\n .description('Apply a discount code to a cart')\n .requiredOption('--code <code>', 'Discount code')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartToken: string, opts) => {\n try {\n const data = { cartToken, discountCode: opts.code }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'cart apply-discount', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.applyDiscount(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n cart\n .command('remove-discount <cartToken>')\n .description('Remove the discount from a cart')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (cartToken: string, opts) => {\n try {\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'cart remove-discount',\n data: { cartToken },\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.cart.removeDiscount({ cartToken })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerStockCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const stock = program.command('stock').description('Stock management')\n\n stock\n .command('check')\n .description('Check stock availability')\n .requiredOption(\n '--items <json>',\n 'Items to check (JSON array of { optionId, quantity })',\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const items = parseJsonArray(opts.items, 'items') as Parameters<\n typeof client.commerce.product.stockCheck\n >[0]['items']\n const result = await client.commerce.product.stockCheck({ items })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport {\n updateTransactionSchema,\n confirmPaymentSchema,\n idempotencyKeySchema,\n} from '@01.software/contracts'\nimport { z } from 'zod'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseWithSchema } from '../lib/parse.js'\n\nconst transactionAmountSchema = z.object({\n amount: z\n .string()\n .regex(/^[1-9]\\d*$/, 'amount must be a positive integer')\n .transform(Number),\n})\nconst confirmPaymentAmountSchema = z.object({\n amount: z\n .string()\n .regex(/^(0|[1-9]\\d*)$/, 'amount must be a non-negative integer')\n .transform(Number),\n})\nconst idempotencyKeyOptionSchema = z.object({\n idempotencyKey: idempotencyKeySchema,\n})\n\nfunction parseTransactionAmount(value: string | undefined) {\n if (value === undefined) return undefined\n return parseWithSchema({ amount: value }, 'amount', transactionAmountSchema)\n .amount\n}\n\nfunction parseConfirmPaymentAmount(value: string) {\n return parseWithSchema({ amount: value }, 'amount', confirmPaymentAmountSchema)\n .amount\n}\n\nfunction parseIdempotencyKey(value: string | undefined) {\n if (value === undefined) return undefined\n return parseWithSchema(\n { idempotencyKey: value },\n 'idempotencyKey',\n idempotencyKeyOptionSchema,\n ).idempotencyKey\n}\n\nexport function registerTransactionCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const tx = program\n .command('transaction')\n .description('Transaction management')\n\n tx.command('update')\n .description('Update transaction status')\n .requiredOption('--payment-id <id>', 'Payment ID')\n .requiredOption(\n '--status <status>',\n 'New status (pending, paid, failed, canceled, refunded)',\n )\n .option('--payment-method <method>', 'Payment method')\n .option('--receipt-url <url>', 'Receipt URL')\n .option('--payment-key <key>', 'Provider payment key')\n .option('--amount <n>', 'Provider-confirmed amount')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n {\n pgPaymentId: opts.paymentId,\n status: opts.status,\n paymentMethod: opts.paymentMethod,\n receiptUrl: opts.receiptUrl,\n paymentKey: opts.paymentKey,\n amount: parseTransactionAmount(opts.amount),\n },\n 'transaction',\n updateTransactionSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'transaction update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateTransaction(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n tx.command('confirm-payment')\n .description('Confirm a provider-verified payment for an order')\n .requiredOption('--payment-id <id>', 'Provider payment identifier (pgPaymentId)')\n .requiredOption(\n '--provider <slug>',\n 'Payment provider slug (toss, portone, stripe, ...)',\n )\n .requiredOption(\n '--amount <n>',\n 'Provider-confirmed amount in minor units',\n )\n .option('--order-number <num>', 'Order number')\n .option('--pg-order-id <id>', 'Provider order id')\n .option('--currency <code>', 'Currency code')\n .option('--payment-method <method>', 'Payment method')\n .option('--receipt-url <url>', 'Receipt URL')\n .option('--approved-at <ts>', 'Provider approval timestamp')\n .option('--provider-status <status>', 'Provider status')\n .option('--provider-event-id <id>', 'Provider event id (idempotency)')\n .option('--idempotency-key <key>', 'Idempotency key header override')\n .option(\n '--confirmation-source <src>',\n 'provider_webhook | provider_lookup | provider_api_confirm | manual_server',\n )\n .option('--payment-key <key>', 'Provider payment key')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n {\n pgPaymentId: opts.paymentId,\n pgProvider: opts.provider,\n amount: parseConfirmPaymentAmount(opts.amount),\n ...(opts.orderNumber ? { orderNumber: opts.orderNumber } : {}),\n ...(opts.pgOrderId ? { pgOrderId: opts.pgOrderId } : {}),\n ...(opts.currency ? { currency: opts.currency } : {}),\n ...(opts.paymentMethod\n ? { paymentMethod: opts.paymentMethod }\n : {}),\n ...(opts.receiptUrl ? { receiptUrl: opts.receiptUrl } : {}),\n ...(opts.approvedAt ? { approvedAt: opts.approvedAt } : {}),\n ...(opts.providerStatus\n ? { providerStatus: opts.providerStatus }\n : {}),\n ...(opts.providerEventId\n ? { providerEventId: opts.providerEventId }\n : {}),\n ...(opts.confirmationSource\n ? { confirmationSource: opts.confirmationSource }\n : {}),\n ...(opts.paymentKey ? { paymentKey: opts.paymentKey } : {}),\n },\n 'confirm-payment',\n confirmPaymentSchema,\n )\n const sdkParams = {\n ...data,\n ...(opts.idempotencyKey !== undefined\n ? { idempotencyKey: parseIdempotencyKey(opts.idempotencyKey) }\n : {}),\n }\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'transaction confirm-payment',\n data: sdkParams,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.confirmPayment(\n sdkParams as Parameters<typeof client.commerce.orders.confirmPayment>[0],\n )\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport { ProductUpsertSchema } from '@01.software/contracts'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson, parseWithSchema } from '../lib/parse.js'\n\nexport function registerProductCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const product = program.command('product').description('Product management')\n\n product\n .command('upsert')\n .description('Create or update a product graph (options, values, variants)')\n .requiredOption('--input <json>', 'Product upsert input (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n parseJson(opts.input, 'input'),\n 'input',\n ProductUpsertSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'product upsert', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.product.upsert(\n data as Parameters<typeof client.commerce.product.upsert>[0],\n )\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerDiscountCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const discount = program\n .command('discount')\n .description('Discount management')\n\n discount\n .command('validate')\n .description('Validate a discount code against an order amount')\n .requiredOption('--code <code>', 'Discount code')\n .requiredOption('--order-amount <n>', 'Order amount', (v: string) =>\n parseInt(v, 10),\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const result = await client.commerce.discounts.validate({\n code: opts.code,\n orderAmount: opts.orderAmount,\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerShippingCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const shipping = program\n .command('shipping')\n .description('Shipping calculation')\n\n shipping\n .command('calculate')\n .description('Calculate shipping for an order amount')\n .requiredOption('--order-amount <n>', 'Order amount', (v: string) =>\n parseInt(v, 10),\n )\n .option('--shipping-policy-id <id>', 'Shipping policy ID')\n .option('--postal-code <code>', 'Destination postal code')\n .action(async (opts) => {\n try {\n const client = getClient()\n const result = await client.commerce.shipping.calculate({\n orderAmount: opts.orderAmount,\n ...(opts.shippingPolicyId\n ? { shippingPolicyId: opts.shippingPolicyId }\n : {}),\n ...(opts.postalCode ? { postalCode: opts.postalCode } : {}),\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport { execFile, exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport { URL } from 'node:url'\nimport type { Command } from 'commander'\nimport pc from 'picocolors'\nimport {\n loadCredentials,\n saveCredentials,\n deleteCredentials,\n getCredentialsPath,\n loadLocalCredentials,\n saveLocalCredentials,\n getLocalCredentialsPath,\n loadTenantList,\n saveTenantList,\n type TenantInfo,\n} from '../lib/credentials.js'\n\nconst WEB_URL = process.env.SOFTWARE_WEB_URL || 'https://01.software'\nconst TIMEOUT_MS = 3 * 60 * 1000 // 3 minutes\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\nfunction openBrowser(url: string): void {\n const os = platform()\n\n const onError = () => {\n console.log(\n pc.yellow(\n `Could not open browser automatically. Open this URL manually:\\n${url}`,\n ),\n )\n }\n\n if (os === 'win32') {\n exec(`start \"\" \"${url}\"`, (err) => {\n if (err) onError()\n })\n } else {\n const cmd = os === 'darwin' ? 'open' : 'xdg-open'\n execFile(cmd, [url], (err) => {\n if (err) onError()\n })\n }\n}\n\nconst PAGE_STYLE = `*{margin:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#fff;color:#252525}\n@media(prefers-color-scheme:dark){body{background:#252525;color:#f5f5f5}}\n.card{text-align:center;padding:2rem 2.5rem;border-radius:10px;max-width:380px;width:100%}\n.icon{width:40px;height:40px;margin:0 auto 1rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.25rem}\n.icon.ok{background:rgba(0,0,0,.05);color:#252525}\n.icon.err{background:rgba(220,38,38,.08);color:#dc2626}\n@media(prefers-color-scheme:dark){.icon.ok{background:rgba(255,255,255,.08);color:#f5f5f5}}\nh1{font-size:.875rem;font-weight:600;margin-bottom:.375rem}\np{font-size:.75rem;color:#737373;line-height:1.5}`\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon ok\">\\u2713</div><h1>Authenticated</h1><p>You can close this tab and return to the terminal.</p></div></body></html>`\n\nconst ERROR_HTML = (msg: string) => `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login Error</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon err\">!</div><h1>Authentication failed</h1><p>${escapeHtml(msg)}</p></div></body></html>`\n\ninterface ExchangeResponse {\n publishableKey: string\n secretKey: string\n tenantName: string\n tenantId: string\n tenants?: TenantInfo[]\n}\n\nasync function exchangeCode(code: string): Promise<ExchangeResponse | null> {\n const url = `${WEB_URL}/api/cli/exchange`\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n console.error(\n pc.red(\n `Exchange failed: HTTP ${res.status} from ${url}${body ? ` — ${body.slice(0, 200)}` : ''}`,\n ),\n )\n return null\n }\n const data = (await res.json()) as Partial<ExchangeResponse>\n if (\n typeof data.publishableKey !== 'string' ||\n typeof data.secretKey !== 'string' ||\n typeof data.tenantName !== 'string' ||\n typeof data.tenantId !== 'string'\n ) {\n console.error(pc.red(`Exchange failed: malformed response from ${url}`))\n return null\n }\n return {\n publishableKey: data.publishableKey,\n secretKey: data.secretKey,\n tenantName: data.tenantName,\n tenantId: data.tenantId,\n tenants: Array.isArray(data.tenants)\n ? data.tenants.filter(\n (t): t is TenantInfo =>\n typeof (t as TenantInfo)?.id === 'string' &&\n typeof (t as TenantInfo)?.name === 'string',\n )\n : undefined,\n }\n } catch (err) {\n console.error(\n pc.red(\n `Exchange request to ${url} failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n return null\n }\n}\n\n/**\n * Start a local HTTP server that receives the OAuth-style redirect callback\n * from the browser. The browser top-level-navigates to\n * http://127.0.0.1:{port}/callback?code={encryptedCode}&state={state}\n * and the CLI exchanges the opaque code with the web API to receive the\n * actual credentials server-to-server. This path has no CORS or PNA\n * preflight because the browser never issues a subresource fetch.\n */\nfunction startAuthServer(options: {\n state: string\n saveFn: (creds: {\n publishableKey: string\n secretKey: string\n tenantId?: string\n tenantName: string\n }) => void\n}): Promise<{ port: number; cleanup: (exitCode?: number) => void }> {\n return new Promise((resolve, reject) => {\n const server = createServer((req, res) => {\n if (!req.url) {\n res.writeHead(400).end()\n return\n }\n\n const url = new URL(req.url, `http://localhost`)\n\n if (url.pathname !== '/callback' || req.method !== 'GET') {\n res.writeHead(404).end()\n return\n }\n\n const error = url.searchParams.get('error')\n if (error) {\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML(error))\n console.error(pc.red(`Login failed: ${error}`))\n cleanup(2)\n return\n }\n\n const code = url.searchParams.get('code')\n const receivedState = url.searchParams.get('state')\n\n if (!code || !receivedState) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Missing code or state. Start over with \"01 login\".'))\n cleanup(2)\n return\n }\n\n if (receivedState !== options.state) {\n res\n .writeHead(403, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('State mismatch. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: state mismatch.'))\n cleanup(2)\n return\n }\n\n exchangeCode(code).then((creds) => {\n if (!creds) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Invalid or expired code. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: code exchange failed.'))\n cleanup(2)\n return\n }\n\n options.saveFn({\n publishableKey: creds.publishableKey,\n secretKey: creds.secretKey,\n tenantId: creds.tenantId,\n tenantName: creds.tenantName,\n })\n\n if (creds.tenants && creds.tenants.length > 0) {\n saveTenantList(creds.tenants)\n }\n\n console.log(pc.green(`\\nLogged in successfully!`))\n console.log(pc.dim(`Tenant: ${creds.tenantName}`))\n\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(SUCCESS_HTML)\n cleanup(0)\n })\n })\n\n let timeout: ReturnType<typeof setTimeout>\n let completed = false\n\n function cleanup(exitCode = 0) {\n if (completed) return\n completed = true\n clearTimeout(timeout)\n server.closeAllConnections?.()\n server.close(() => process.exit(exitCode))\n }\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to start local server.'))\n return\n }\n\n timeout = setTimeout(() => {\n console.error(\n pc.red('\\nLogin timed out (3 minutes). Please try again.'),\n )\n cleanup(4)\n }, TIMEOUT_MS)\n\n resolve({ port: addr.port, cleanup })\n })\n\n server.on('error', (err) => {\n reject(err)\n })\n })\n}\n\nexport function registerAuthCommands(program: Command): void {\n program\n .command('login')\n .description('Login via browser and store credentials')\n .action(async () => {\n const state = randomBytes(32).toString('hex')\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n saveCredentials(creds)\n console.log(pc.dim(`Credentials saved to ${getCredentialsPath()}`))\n },\n })\n\n const params = new URLSearchParams({ port: String(port), state })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim('Opening browser for login...'))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n\n program\n .command('logout')\n .description('Remove stored credentials')\n .action(() => {\n const deleted = deleteCredentials()\n if (deleted) {\n console.log(pc.green('Logged out. Credentials removed.'))\n } else {\n console.log(pc.dim('No stored credentials found.'))\n }\n })\n\n program\n .command('whoami')\n .description('Show current authentication status')\n .action(() => {\n // Check local credentials first\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const creds = localCreds || globalCreds\n const isLocal = !!localCreds\n\n if (!creds) {\n console.log(pc.dim('Not logged in. Run \"01 login\" to authenticate.'))\n return\n }\n\n const masked =\n creds.publishableKey.length > 8\n ? creds.publishableKey.slice(0, 4) + '...' + creds.publishableKey.slice(-4)\n : '****'\n\n const scope = isLocal ? pc.cyan(' (local)') : ''\n console.log(`Tenant: ${pc.bold(creds.tenantName)}${scope}`)\n console.log(`Publishable Key: ${pc.dim(masked)}`)\n console.log(`Stored at: ${pc.dim(creds.storedAt)}`)\n console.log(\n `File: ${pc.dim(isLocal ? getLocalCredentialsPath() : getCredentialsPath())}`,\n )\n })\n\n // -------------------------------------------------------------------------\n // tenant subcommands\n // -------------------------------------------------------------------------\n const tenant = program\n .command('tenant')\n .description('Manage tenant switching')\n\n tenant\n .command('list')\n .description('Show cached tenant list')\n .action(() => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.log(pc.dim('No cached tenants. Run \"01 login\" first.'))\n return\n }\n\n // Determine active tenant\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const activeCreds = localCreds || globalCreds\n const activeId = activeCreds?.tenantId\n const activeName = activeCreds?.tenantName\n\n console.log(pc.bold('Cached tenants:\\n'))\n for (const t of tenants) {\n const active = (activeId ? t.id === activeId : t.name === activeName)\n ? pc.green(' *')\n : ''\n console.log(` ${t.name}${active}`)\n }\n console.log()\n if (activeName) {\n const scope = localCreds ? '(local)' : '(global)'\n console.log(pc.dim(`* active ${scope}`))\n }\n })\n\n tenant\n .command('use <name>')\n .description('Switch to a different tenant via browser')\n .option('--local', 'Save credentials locally in the current project')\n .action(async (name: string, opts: { local?: boolean }) => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.error(pc.red('No cached tenants. Run \"01 login\" first.'))\n process.exit(2)\n }\n\n const match = tenants.find(\n (t) => t.name.toLowerCase() === name.toLowerCase(),\n )\n if (!match) {\n console.error(pc.red(`Tenant \"${name}\" not found in cache.`))\n console.error(\n pc.dim(`Available: ${tenants.map((t) => t.name).join(', ')}`),\n )\n process.exit(3)\n }\n\n const state = randomBytes(32).toString('hex')\n const isLocal = !!opts.local\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n if (isLocal) {\n saveLocalCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getLocalCredentialsPath()}`),\n )\n } else {\n saveCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getCredentialsPath()}`),\n )\n }\n },\n })\n\n const params = new URLSearchParams({\n port: String(port),\n state,\n tenantId: match.id,\n })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim(`Switching to tenant \"${match.name}\"...`))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n}\n","import { Command } from 'commander'\nimport { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { validateCollection } from '../lib/collections.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerSchemaCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const schema = program\n .command('schema')\n .description('Collection schema introspection')\n\n schema\n .command('list')\n .description('List available collections')\n .action(() => {\n printResult(SERVER_COLLECTIONS, getFormat())\n })\n\n schema\n .command('show <collection>')\n .description('Show collection field schema')\n .action(async (collection: string) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const result = await client.tenant.collectionSchema(col)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport {\n tenantFeatureProgressInputSchema,\n tenantFeatureProgressResponseSchema,\n type TenantFeatureProgressResponse,\n} from '@01.software/contracts'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseWithSchema } from '../lib/parse.js'\n\nfunction flattenProgress(progress: TenantFeatureProgressResponse) {\n return progress.groups.flatMap((group) =>\n group.items.map((item) => ({\n group: group.title,\n item: item.title,\n state: item.state,\n severity: item.severity,\n summary: item.summary,\n })),\n )\n}\n\nexport function registerFeatureCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const feature = program\n .command('feature')\n .description('Feature implementation progress checks')\n\n feature\n .command('check <feature>')\n .description('Check tenant implementation progress for a feature')\n .option('--evidence', 'Include sanitized evidence counts and surface flags')\n .action(async (featureName: string, options: { evidence?: boolean }) => {\n try {\n const input = parseWithSchema(\n {\n feature: featureName,\n includeEvidence: Boolean(options.evidence),\n },\n 'feature',\n tenantFeatureProgressInputSchema,\n )\n const client = getClient()\n const result = tenantFeatureProgressResponseSchema.parse(\n await client.tenant.featureProgress(input),\n )\n const format = getFormat()\n printResult(\n format === 'table' ? flattenProgress(result) : result,\n format,\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n}\n","import { Command, type CommanderError } from 'commander'\nimport { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { isAgentPlanCollection } from '../lib/agent-plan-allowlist.js'\nimport { exitWithAgentError, printAgentSuccess } from '../lib/agent-output.js'\nimport {\n parseSelect,\n validateCollection,\n type CliCollection,\n} from '../lib/collections.js'\nimport { registerAgentPlanCommands } from './agent-plan.js'\n\nconst AGENT_PROTOCOL_VERSION = '1'\n\ntype AgentReadOperation = 'query' | 'get'\ntype AgentPlanOperationName = 'plan:create' | 'plan:update' | 'plan:delete'\ntype AgentOperation = AgentReadOperation | AgentPlanOperationName\n\ntype AgentFieldName = 'id' | 'createdAt' | 'updatedAt'\n\ninterface AgentFieldMetadata {\n type: 'string'\n queryable: boolean\n}\n\ntype AgentFieldMap = Record<AgentFieldName, AgentFieldMetadata>\n\nexport interface AgentManifest {\n version: typeof AGENT_PROTOCOL_VERSION\n collections: Record<\n CliCollection,\n {\n operations: readonly AgentOperation[]\n fields: AgentFieldMap\n }\n >\n}\n\nfunction buildStableAgentFields(): AgentFieldMap {\n return {\n id: { type: 'string', queryable: true },\n createdAt: { type: 'string', queryable: true },\n updatedAt: { type: 'string', queryable: true },\n }\n}\n\nfunction invalidInput(message: string, field: string, value?: unknown): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: 'invalid_argument',\n field,\n detail: { message, value, field },\n })\n return error\n}\n\nfunction parsePositiveInteger(\n value: string | undefined,\n field: 'limit' | 'page',\n): number | undefined {\n if (value == null) return undefined\n if (/^[1-9]\\d*$/.test(value)) return Number(value)\n throw invalidInput(`--${field} must be a positive integer`, field, value)\n}\n\nfunction handleCommanderError(error: CommanderError): never {\n if (error.code === 'commander.helpDisplayed') {\n process.exit(error.exitCode)\n }\n\n exitWithAgentError(invalidInput(error.message, 'command'))\n}\n\nfunction configureAgentParser(command: Command): Command {\n command.configureOutput({\n writeErr: () => {},\n writeOut: (str) => {\n process.stdout.write(str)\n },\n })\n command.exitOverride(handleCommanderError)\n return command\n}\n\nfunction parseWhere(\n value: string | undefined,\n): Record<string, unknown> | undefined {\n if (value == null) return undefined\n\n try {\n const parsed: unknown = JSON.parse(value)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n throw invalidInput('--where must be a JSON object', 'where', value)\n }\n\n throw invalidInput('--where must be a JSON object', 'where', value)\n}\n\nconst AGENT_READ_OPERATIONS = [\n 'query',\n 'get',\n] as const satisfies readonly AgentReadOperation[]\nconst AGENT_PLAN_OPERATIONS = [\n 'plan:create',\n 'plan:update',\n 'plan:delete',\n] as const satisfies readonly AgentPlanOperationName[]\n\nexport function buildAgentManifest(): AgentManifest {\n const collections = {} as AgentManifest['collections']\n for (const collection of SERVER_COLLECTIONS) {\n const operations: AgentOperation[] = isAgentPlanCollection(collection)\n ? [...AGENT_READ_OPERATIONS, ...AGENT_PLAN_OPERATIONS]\n : [...AGENT_READ_OPERATIONS]\n collections[collection] = {\n operations,\n fields: buildStableAgentFields(),\n }\n }\n\n return {\n version: AGENT_PROTOCOL_VERSION,\n collections,\n }\n}\n\nfunction validateAgentCollection(collection: string): CliCollection {\n try {\n return validateCollection(collection)\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : `Unknown collection \"${collection}\".`\n throw invalidInput(message, 'collection', collection)\n }\n}\n\nexport function registerAgentCommands(\n program: Command,\n getClient: () => ResolvedClient,\n): void {\n const agent = configureAgentParser(\n program\n .command('agent')\n .description('Machine-stable CLI namespace for coding agents')\n .addHelpText(\n 'after',\n '\\nContract: docs/agent-cli-contract.md\\nJSON only on stdout; no TTY effects.',\n ),\n )\n\n configureAgentParser(\n agent\n .command('manifest')\n .description('Print the Agent CLI protocol manifest')\n .option('--pretty', 'Print 2-space indented JSON')\n .action((opts: { pretty?: boolean }) => {\n printAgentSuccess(buildAgentManifest(), {\n pretty: Boolean(opts.pretty),\n })\n }),\n )\n\n configureAgentParser(\n agent\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions as a JSON object')\n .option('--limit <n>', 'Max results')\n .option('--page <n>', 'Page number')\n .option('--sort <field>', 'Sort field; prefix with - for descending')\n .option('--select <fields>', 'Comma-separated fields to select')\n .option('--pretty', 'Print 2-space indented JSON')\n .action(\n async (\n collection: string,\n opts: {\n where?: string\n limit?: string\n page?: string\n sort?: string\n select?: string\n pretty?: boolean\n },\n ) => {\n try {\n const col = validateAgentCollection(collection)\n const options: Record<string, unknown> = {}\n const where = parseWhere(opts.where)\n const limit = parsePositiveInteger(opts.limit, 'limit')\n const page = parsePositiveInteger(opts.page, 'page')\n\n if (where) options.where = where\n if (limit != null) options.limit = limit\n if (page != null) options.page = page\n if (opts.sort) options.sort = opts.sort\n if (opts.select) options.select = parseSelect(opts.select)\n\n const client = getClient()\n const result = await client.collections.from(col).find(options)\n printAgentSuccess(result, { pretty: Boolean(opts.pretty) })\n } catch (error) {\n exitWithAgentError(error, { pretty: Boolean(opts.pretty) })\n }\n },\n ),\n )\n\n configureAgentParser(\n agent\n .command('get <collection> [id]')\n .description('Get a document by ID')\n .option('--select <fields>', 'Comma-separated fields to select')\n .option('--pretty', 'Print 2-space indented JSON')\n .action(\n async (\n collection: string,\n id: string | undefined,\n opts: { select?: string; pretty?: boolean },\n ) => {\n try {\n const col = validateAgentCollection(collection)\n if (!id) {\n throw invalidInput('Missing required argument: id', 'id')\n }\n\n const options: Record<string, unknown> = {}\n if (opts.select) options.select = parseSelect(opts.select)\n\n const client = getClient()\n const result = await client.collections\n .from(col)\n .findById(id, options)\n printAgentSuccess(result, { pretty: Boolean(opts.pretty) })\n } catch (error) {\n exitWithAgentError(error, { pretty: Boolean(opts.pretty) })\n }\n },\n ),\n )\n\n registerAgentPlanCommands(agent, getClient)\n}\n","import { classifyError } from './admin-error.js'\n\nexport type AgentErrorCode =\n | 'INVALID_INPUT'\n | 'AUTH_FAILED'\n | 'NOT_FOUND'\n | 'INTERNAL'\n | 'PLAN_EXPIRED'\n | 'PLAN_MISMATCH'\n | 'PLAN_STALE'\n | 'UNSUPPORTED_OPERATION'\n\nconst PLAN_AGENT_ERROR_CODES: ReadonlySet<AgentErrorCode> = new Set([\n 'PLAN_EXPIRED',\n 'PLAN_MISMATCH',\n 'PLAN_STALE',\n 'UNSUPPORTED_OPERATION',\n])\n\nexport function agentPlanError(\n code:\n | 'PLAN_EXPIRED'\n | 'PLAN_MISMATCH'\n | 'PLAN_STALE'\n | 'UNSUPPORTED_OPERATION'\n | 'INVALID_INPUT',\n message: string,\n): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: code.toLowerCase(),\n agentCode: code,\n detail: { message, agentCode: code },\n })\n return error\n}\n\nexport interface AgentErrorEnvelope {\n error: {\n code: AgentErrorCode\n message: string\n }\n}\n\nexport interface AgentPrintOptions {\n pretty?: boolean\n}\n\nfunction stringifyAgentJson(\n data: unknown,\n options: AgentPrintOptions = {},\n): string {\n return options.pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data)\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value && typeof value === 'object'\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction errorMessage(error: unknown): string {\n const raw = asRecord(error)\n if (raw) {\n if (typeof raw.message === 'string' && raw.message.length > 0) {\n return raw.message\n }\n if (\n raw.detail &&\n typeof raw.detail === 'object' &&\n typeof (raw.detail as Record<string, unknown>).message === 'string'\n ) {\n return String((raw.detail as Record<string, unknown>).message)\n }\n }\n if (error instanceof Error && error.message.length > 0) {\n return error.message\n }\n if (typeof error === 'string' && error.length > 0) {\n return error\n }\n return 'Internal error'\n}\n\nfunction isRawNotFound(error: unknown): boolean {\n const raw = asRecord(error)\n return (\n raw?.status === 404 ||\n raw?.code === 'not_found' ||\n raw?.name === 'GoneError'\n )\n}\n\nexport function agentErrorExitCode(code: AgentErrorCode): number {\n switch (code) {\n case 'INVALID_INPUT':\n case 'PLAN_EXPIRED':\n case 'PLAN_MISMATCH':\n case 'PLAN_STALE':\n case 'UNSUPPORTED_OPERATION':\n return 2\n case 'AUTH_FAILED':\n return 3\n case 'NOT_FOUND':\n return 4\n case 'INTERNAL':\n return 1\n }\n}\n\nexport function classifyAgentError(error: unknown): AgentErrorEnvelope {\n const raw = asRecord(error)\n const message = errorMessage(error)\n const detail = raw?.detail\n const detailRecord =\n detail && typeof detail === 'object'\n ? (detail as Record<string, unknown>)\n : null\n const agentCode = raw?.agentCode ?? detailRecord?.agentCode\n if (\n typeof agentCode === 'string' &&\n PLAN_AGENT_ERROR_CODES.has(agentCode as AgentErrorCode)\n ) {\n return { error: { code: agentCode as AgentErrorCode, message } }\n }\n\n const adminError = classifyError(error)\n\n if (isRawNotFound(error) || adminError.code === 'not_found') {\n return { error: { code: 'NOT_FOUND', message } }\n }\n\n if (adminError.type === 'permission') {\n return { error: { code: 'AUTH_FAILED', message } }\n }\n\n if (adminError.type === 'validation' && adminError.code !== 'unknown') {\n return { error: { code: 'INVALID_INPUT', message } }\n }\n\n return { error: { code: 'INTERNAL', message } }\n}\n\nexport function printAgentSuccess(\n data: unknown,\n options: AgentPrintOptions = {},\n): void {\n console.log(stringifyAgentJson(data, options))\n}\n\nexport function printAgentError(\n error: unknown,\n options: AgentPrintOptions = {},\n): AgentErrorEnvelope {\n const envelope = classifyAgentError(error)\n console.log(stringifyAgentJson(envelope, options))\n return envelope\n}\n\nexport function exitWithAgentError(\n error: unknown,\n options: AgentPrintOptions = {},\n): never {\n const envelope = printAgentError(error, options)\n process.exit(agentErrorExitCode(envelope.error.code))\n}\n","import { agentPlanError } from './agent-output.js'\n\nexport const AGENT_PLAN_COLLECTIONS = [\n 'articles',\n 'article-categories',\n 'article-tags',\n 'links',\n 'link-categories',\n 'link-tags',\n] as const\n\nexport type AgentPlanCollection = (typeof AGENT_PLAN_COLLECTIONS)[number]\nexport type AgentPlanOperation = 'create' | 'update' | 'delete'\n\nconst AGENT_PLAN_COLLECTION_SET = new Set<string>(AGENT_PLAN_COLLECTIONS)\n\nexport function isAgentPlanCollection(\n collection: string,\n): collection is AgentPlanCollection {\n return AGENT_PLAN_COLLECTION_SET.has(collection)\n}\n\nexport function assertAgentPlanCollection(collection: string): AgentPlanCollection {\n if (isAgentPlanCollection(collection)) {\n return collection\n }\n throw agentPlanError(\n 'UNSUPPORTED_OPERATION',\n `Collection \"${collection}\" is not supported for agent plan mutations.`,\n )\n}\n\nexport function assertAgentPlanOperation(\n operation: string,\n): AgentPlanOperation {\n if (operation === 'create' || operation === 'update' || operation === 'delete') {\n return operation\n }\n throw agentPlanError(\n 'UNSUPPORTED_OPERATION',\n `Operation \"${operation}\" is not supported for agent plan mutations.`,\n )\n}\n","import { createHash } from 'node:crypto'\n\nexport function buildAuthContextFingerprint(input: {\n publishableKey: string\n secretKey: string\n apiUrl?: string\n tenantId?: string\n}): string {\n const apiUrl =\n input.apiUrl ??\n process.env.SOFTWARE_API_URL ??\n process.env.NEXT_PUBLIC_SOFTWARE_API_URL ??\n ''\n const tenantId = input.tenantId ?? process.env.SOFTWARE_TENANT_ID ?? ''\n const secretDigest = createHash('sha256').update(input.secretKey).digest('hex')\n const material = [input.publishableKey, secretDigest, apiUrl, tenantId].join('\\n')\n return createHash('sha256').update(material).digest('hex')\n}\n","import { mkdir, open, readFile, unlink, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport {\n isAgentPlanCollection,\n type AgentPlanCollection,\n type AgentPlanOperation,\n} from './agent-plan-allowlist.js'\nimport { hashAgentPlanEnvelope } from './agent-plan-hash.js'\nimport { assertValidPlanId, safePlanPath } from './agent-plan-id.js'\nimport { agentPlanError } from './agent-output.js'\n\nexport const AGENT_PLAN_TTL_MS = 15 * 60 * 1000\n\nexport type AgentPlanStatus = 'pending' | 'claimed' | 'consumed'\n\nexport interface StoredAgentPlan {\n planId: string\n planHash: string\n operation: AgentPlanOperation\n collection: AgentPlanCollection\n documentId?: string\n payload?: Record<string, unknown>\n baseUpdatedAt?: string\n authFingerprint: string\n createdAt: string\n expiresAt: string\n status: AgentPlanStatus\n}\n\nexport function resolveAgentPlanDir(): string {\n const override = process.env.SOFTWARE_AGENT_PLAN_DIR?.trim()\n if (override) {\n return override\n }\n return join(homedir(), '.01software', 'agent-plans')\n}\n\nfunction parseExpiresAtMs(expiresAt: string): number {\n const ms = Date.parse(expiresAt)\n if (!Number.isFinite(ms)) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has invalid expiresAt.')\n }\n return ms\n}\n\nfunction parseStoredAgentPlan(raw: unknown, planId: string): StoredAgentPlan {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan is corrupted.')\n }\n const record = raw as Record<string, unknown>\n if (record.planId !== planId) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan id does not match token.')\n }\n if (\n typeof record.planHash !== 'string' ||\n typeof record.operation !== 'string' ||\n typeof record.collection !== 'string' ||\n typeof record.authFingerprint !== 'string' ||\n typeof record.createdAt !== 'string' ||\n typeof record.expiresAt !== 'string' ||\n typeof record.status !== 'string'\n ) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan is missing required fields.')\n }\n if (\n record.status !== 'pending' &&\n record.status !== 'claimed' &&\n record.status !== 'consumed'\n ) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has invalid status.')\n }\n\n if (!isAgentPlanCollection(record.collection)) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has unsupported collection.')\n }\n const collection = record.collection\n const operation = record.operation\n if (operation !== 'create' && operation !== 'update' && operation !== 'delete') {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has invalid operation.')\n }\n\n const payload =\n record.payload == null\n ? undefined\n : typeof record.payload === 'object' && !Array.isArray(record.payload)\n ? (record.payload as Record<string, unknown>)\n : (() => {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan payload is invalid.')\n })()\n\n const documentId =\n record.documentId == null\n ? undefined\n : typeof record.documentId === 'string'\n ? record.documentId\n : (() => {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan documentId is invalid.')\n })()\n\n const baseUpdatedAt =\n record.baseUpdatedAt == null\n ? undefined\n : typeof record.baseUpdatedAt === 'string'\n ? record.baseUpdatedAt\n : (() => {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan baseUpdatedAt is invalid.')\n })()\n\n return {\n planId,\n planHash: record.planHash,\n operation,\n collection,\n documentId,\n payload,\n baseUpdatedAt,\n authFingerprint: record.authFingerprint,\n createdAt: record.createdAt,\n expiresAt: record.expiresAt,\n status: record.status,\n }\n}\n\nexport function assertStoredPlanHashMatches(plan: StoredAgentPlan): void {\n const expected = hashAgentPlanEnvelope({\n operation: plan.operation,\n collection: plan.collection,\n documentId: plan.documentId,\n payload: plan.payload,\n })\n if (plan.planHash !== expected) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan hash does not match plan contents.')\n }\n}\n\nfunction assertPlanNotExpired(plan: StoredAgentPlan): void {\n if (Date.now() > parseExpiresAtMs(plan.expiresAt)) {\n throw agentPlanError('PLAN_EXPIRED', 'Plan expired.')\n }\n}\n\nasync function readAgentPlanFile(\n planDir: string,\n planId: string,\n): Promise<StoredAgentPlan> {\n assertValidPlanId(planId)\n let raw: string\n try {\n raw = await readFile(safePlanPath(planDir, planId), 'utf8')\n } catch {\n throw agentPlanError('PLAN_MISMATCH', 'Plan not found.')\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan is corrupted.')\n }\n\n return parseStoredAgentPlan(parsed, planId)\n}\n\nasync function writeAgentPlanFile(\n planDir: string,\n plan: StoredAgentPlan,\n): Promise<void> {\n await writeFile(safePlanPath(planDir, plan.planId), JSON.stringify(plan), {\n encoding: 'utf8',\n mode: 0o600,\n })\n}\n\nexport async function writeAgentPlan(input: {\n planDir: string\n record: Omit<StoredAgentPlan, 'planId' | 'status'> & { planId?: string }\n}): Promise<StoredAgentPlan> {\n await mkdir(input.planDir, { recursive: true, mode: 0o700 })\n const planId = input.record.planId ?? randomUUID()\n assertValidPlanId(planId)\n const plan: StoredAgentPlan = {\n ...input.record,\n planId,\n status: 'pending',\n }\n assertStoredPlanHashMatches(plan)\n await writeAgentPlanFile(input.planDir, plan)\n return plan\n}\n\nexport async function claimAgentPlan(input: {\n planDir: string\n planId: string\n planHash: string\n authFingerprint: string\n}): Promise<StoredAgentPlan> {\n assertValidPlanId(input.planId)\n const planPath = safePlanPath(input.planDir, input.planId)\n const lockPath = `${planPath}.lock`\n let lockHandle: Awaited<ReturnType<typeof open>> | undefined\n\n try {\n lockHandle = await open(lockPath, 'wx', 0o600)\n } catch {\n throw agentPlanError('PLAN_MISMATCH', 'Plan was already claimed or consumed.')\n }\n\n try {\n const plan = await readAgentPlanFile(input.planDir, input.planId)\n assertPlanNotExpired(plan)\n assertStoredPlanHashMatches(plan)\n\n if (plan.planHash !== input.planHash) {\n throw agentPlanError('PLAN_MISMATCH', 'Plan hash does not match stored plan.')\n }\n\n if (plan.authFingerprint !== input.authFingerprint) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Plan auth context does not match current credentials.',\n )\n }\n\n if (plan.status !== 'pending') {\n throw agentPlanError('PLAN_MISMATCH', 'Plan was already claimed or consumed.')\n }\n\n const claimed: StoredAgentPlan = { ...plan, status: 'claimed' }\n await writeAgentPlanFile(input.planDir, claimed)\n return claimed\n } finally {\n if (lockHandle) {\n await lockHandle.close().catch(() => {})\n }\n await unlink(lockPath).catch(() => {})\n }\n}\n\nexport async function releaseAgentPlanClaim(input: {\n planDir: string\n planId: string\n}): Promise<void> {\n const plan = await readAgentPlanFile(input.planDir, input.planId)\n if (plan.status !== 'claimed') {\n return\n }\n await writeAgentPlanFile(input.planDir, { ...plan, status: 'pending' })\n}\n\nexport async function markAgentPlanConsumed(input: {\n planDir: string\n planId: string\n}): Promise<void> {\n const plan = await readAgentPlanFile(input.planDir, input.planId)\n await writeAgentPlanFile(input.planDir, { ...plan, status: 'consumed' })\n}\n","import { createHash } from 'node:crypto'\nimport type {\n AgentPlanCollection,\n AgentPlanOperation,\n} from './agent-plan-allowlist.js'\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeys)\n }\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = sortKeys((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nexport function hashPlanPayload(payload: unknown): string {\n const canonical = JSON.stringify(sortKeys(payload))\n return createHash('sha256').update(canonical).digest('hex')\n}\n\nexport interface AgentPlanHashInput {\n operation: AgentPlanOperation\n collection: AgentPlanCollection\n documentId?: string\n payload?: Record<string, unknown>\n}\n\nexport function hashAgentPlanEnvelope(input: AgentPlanHashInput): string {\n return hashPlanPayload({\n operation: input.operation,\n collection: input.collection,\n documentId: input.documentId,\n payload: input.payload,\n })\n}\n","import { resolve, sep } from 'node:path'\nimport { agentPlanError } from './agent-output.js'\n\nconst PLAN_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\nexport function assertValidPlanId(planId: string): void {\n if (!PLAN_ID_PATTERN.test(planId)) {\n throw agentPlanError('INVALID_INPUT', 'Invalid plan token.')\n }\n}\n\nexport function safePlanPath(planDir: string, planId: string): string {\n assertValidPlanId(planId)\n const resolvedDir = resolve(planDir)\n const resolvedPath = resolve(resolvedDir, `${planId}.json`)\n if (\n resolvedPath !== resolvedDir &&\n !resolvedPath.startsWith(`${resolvedDir}${sep}`)\n ) {\n throw agentPlanError('INVALID_INPUT', 'Invalid plan token.')\n }\n return resolvedPath\n}\n","import type { AgentPlanOperation } from './agent-plan-allowlist.js'\nimport { agentPlanError } from './agent-output.js'\n\nexport function readDocumentUpdatedAt(doc: unknown): string | undefined {\n if (!doc || typeof doc !== 'object') {\n return undefined\n }\n const updatedAt = (doc as Record<string, unknown>).updatedAt\n return typeof updatedAt === 'string' && updatedAt.length > 0\n ? updatedAt\n : undefined\n}\n\nexport function assertPlanBaseUpdatedAt(\n operation: AgentPlanOperation,\n baseUpdatedAt: string | undefined,\n): void {\n if (operation === 'create') {\n return\n }\n if (!baseUpdatedAt) {\n throw agentPlanError(\n 'INVALID_INPUT',\n 'Document is missing updatedAt; cannot plan update or delete.',\n )\n }\n}\n\nexport async function assertPlanNotStale(input: {\n operation: AgentPlanOperation\n baseUpdatedAt?: string\n currentUpdatedAt?: string\n}): Promise<void> {\n if (input.operation === 'create') {\n return\n }\n if (!input.baseUpdatedAt || !input.currentUpdatedAt) {\n throw agentPlanError(\n 'PLAN_STALE',\n 'Document is missing updatedAt for stale check.',\n )\n }\n if (input.baseUpdatedAt !== input.currentUpdatedAt) {\n throw agentPlanError(\n 'PLAN_STALE',\n 'Document changed since the plan was created.',\n )\n }\n}\n","import type { ResolvedClient } from './client.js'\nimport { agentPlanError } from './agent-output.js'\nimport type { StoredAgentPlan } from './agent-plan-store.js'\nimport {\n markAgentPlanConsumed,\n resolveAgentPlanDir,\n} from './agent-plan-store.js'\nimport {\n assertPlanNotStale,\n readDocumentUpdatedAt,\n} from './agent-plan-stale.js'\n\nexport async function executeAgentPlanMutation(\n client: ResolvedClient,\n plan: StoredAgentPlan,\n): Promise<unknown> {\n const collection = client.collections.from(plan.collection)\n\n if (plan.operation === 'create') {\n const response = await collection.create(plan.payload ?? {})\n return response.doc\n }\n\n if (!plan.documentId) {\n throw agentPlanError('PLAN_MISMATCH', 'Plan is missing document id.')\n }\n\n if (plan.operation === 'update') {\n const current = await collection.findById(plan.documentId)\n await assertPlanNotStale({\n operation: plan.operation,\n baseUpdatedAt: plan.baseUpdatedAt,\n currentUpdatedAt: readDocumentUpdatedAt(current),\n })\n const response = await collection.update(plan.documentId, plan.payload ?? {})\n return response.doc\n }\n\n const current = await collection.findById(plan.documentId)\n await assertPlanNotStale({\n operation: plan.operation,\n baseUpdatedAt: plan.baseUpdatedAt,\n currentUpdatedAt: readDocumentUpdatedAt(current),\n })\n return collection.remove(plan.documentId)\n}\n\nexport async function finalizeAgentPlan(plan: StoredAgentPlan): Promise<void> {\n await markAgentPlanConsumed({\n planDir: resolveAgentPlanDir(),\n planId: plan.planId,\n })\n}\n","import { readFileSync } from 'node:fs'\nimport { stdin } from 'node:process'\nimport { agentPlanError } from './agent-output.js'\n\nasync function readStdinUtf8(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n }\n return Buffer.concat(chunks).toString('utf8')\n}\n\nexport async function readAgentPlanPayload(opts: {\n dataStdin?: boolean\n dataFile?: string\n}): Promise<Record<string, unknown>> {\n const sourceCount = [opts.dataStdin, opts.dataFile].filter(Boolean).length\n if (sourceCount !== 1) {\n throw agentPlanError(\n 'INVALID_INPUT',\n 'Exactly one of --data-stdin or --data-file is required.',\n )\n }\n\n let raw: string\n try {\n raw = opts.dataStdin\n ? await readStdinUtf8()\n : readFileSync(opts.dataFile!, 'utf8')\n } catch {\n throw agentPlanError(\n 'INVALID_INPUT',\n 'Mutation data file could not be read.',\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw agentPlanError('INVALID_INPUT', 'Mutation data must be valid JSON.')\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw agentPlanError('INVALID_INPUT', 'Mutation data must be a JSON object.')\n }\n\n return parsed as Record<string, unknown>\n}\n","import { agentPlanError } from './agent-output.js'\n\nconst SECRET_KEY =\n /(?:^|_)(?:secret|password|token|api[_-]?key|private[_-]?key|credential)(?:$|_)/i\n\nfunction isSecretFieldName(key: string): boolean {\n if (SECRET_KEY.test(key)) {\n return true\n }\n const snake = key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()\n return SECRET_KEY.test(snake)\n}\n\nexport function assertNoSecretFields(value: unknown, path = ''): void {\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n assertNoSecretFields(item, `${path}[${index}]`)\n })\n return\n }\n\n if (!value || typeof value !== 'object') {\n return\n }\n\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const fieldPath = path ? `${path}.${key}` : key\n if (isSecretFieldName(key)) {\n throw agentPlanError(\n 'INVALID_INPUT',\n `Secret-looking field \"${fieldPath}\" is not allowed in agent mutation payloads.`,\n )\n }\n assertNoSecretFields(child, fieldPath)\n }\n}\n","import { assertValidPlanId } from './agent-plan-id.js'\nimport { agentPlanError } from './agent-output.js'\n\nexport interface AgentPlanToken {\n planId: string\n planHash: string\n expiresAt: string\n}\n\nexport function encodePlanToken(token: AgentPlanToken): string {\n return Buffer.from(JSON.stringify(token), 'utf8').toString('base64url')\n}\n\nexport function decodePlanToken(raw: string): AgentPlanToken {\n try {\n const parsed: unknown = JSON.parse(\n Buffer.from(raw, 'base64url').toString('utf8'),\n )\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('invalid token')\n }\n const record = parsed as Record<string, unknown>\n if (\n typeof record.planId !== 'string' ||\n typeof record.planHash !== 'string' ||\n typeof record.expiresAt !== 'string'\n ) {\n throw new Error('invalid token fields')\n }\n assertValidPlanId(record.planId)\n return {\n planId: record.planId,\n planHash: record.planHash,\n expiresAt: record.expiresAt,\n }\n } catch {\n throw agentPlanError('INVALID_INPUT', 'Invalid plan token.')\n }\n}\n\nexport function buildConfirmCommand(planToken: string, planHash: string): string {\n return `01 agent confirm ${planToken} --hash ${planHash}`\n}\n","import { Command, type CommanderError } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport {\n assertAgentPlanCollection,\n type AgentPlanOperation,\n} from '../lib/agent-plan-allowlist.js'\nimport { buildAuthContextFingerprint } from '../lib/agent-plan-auth.js'\nimport {\n executeAgentPlanMutation,\n finalizeAgentPlan,\n} from '../lib/agent-plan-confirm.js'\nimport { hashAgentPlanEnvelope } from '../lib/agent-plan-hash.js'\nimport { readAgentPlanPayload } from '../lib/agent-plan-payload.js'\nimport { assertNoSecretFields } from '../lib/agent-plan-secrets.js'\nimport {\n AGENT_PLAN_TTL_MS,\n claimAgentPlan,\n releaseAgentPlanClaim,\n resolveAgentPlanDir,\n writeAgentPlan,\n} from '../lib/agent-plan-store.js'\nimport {\n assertPlanBaseUpdatedAt,\n readDocumentUpdatedAt,\n} from '../lib/agent-plan-stale.js'\nimport {\n buildConfirmCommand,\n decodePlanToken,\n encodePlanToken,\n} from '../lib/agent-plan-token.js'\nimport {\n agentPlanError,\n exitWithAgentError,\n printAgentSuccess,\n} from '../lib/agent-output.js'\n\nfunction invalidInput(message: string, field: string): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: 'invalid_argument',\n field,\n detail: { message, field },\n })\n return error\n}\n\nfunction handleCommanderError(error: CommanderError): never {\n if (error.code === 'commander.helpDisplayed') {\n process.exit(error.exitCode)\n }\n exitWithAgentError(invalidInput(error.message, 'command'))\n}\n\nfunction configureAgentParser(command: Command): Command {\n command.configureOutput({\n writeErr: () => {},\n writeOut: (str) => {\n process.stdout.write(str)\n },\n })\n command.exitOverride(handleCommanderError)\n return command\n}\n\nasync function captureBaseUpdatedAt(\n client: ResolvedClient,\n collection: ReturnType<typeof assertAgentPlanCollection>,\n documentId: string,\n): Promise<string | undefined> {\n const doc = await client.collections.from(collection).findById(documentId)\n return readDocumentUpdatedAt(doc)\n}\n\nasync function runPlanAction(input: {\n operation: AgentPlanOperation\n collection: string\n documentId?: string\n dataStdin?: boolean\n dataFile?: string\n pretty?: boolean\n getClient: () => ResolvedClient\n}): Promise<void> {\n const collection = assertAgentPlanCollection(input.collection)\n\n if (input.operation !== 'create' && !input.documentId) {\n throw invalidInput('Missing required argument: id', 'id')\n }\n\n let payload: Record<string, unknown> | undefined\n if (input.operation === 'create' || input.operation === 'update') {\n payload = await readAgentPlanPayload({\n dataStdin: input.dataStdin,\n dataFile: input.dataFile,\n })\n assertNoSecretFields(payload)\n }\n\n const client = input.getClient()\n const authFingerprint = buildAuthContextFingerprint({\n publishableKey: client.publishableKey,\n secretKey: client.secretKey,\n })\n\n let baseUpdatedAt: string | undefined\n if (input.operation !== 'create' && input.documentId) {\n baseUpdatedAt = await captureBaseUpdatedAt(\n client,\n collection,\n input.documentId,\n )\n assertPlanBaseUpdatedAt(input.operation, baseUpdatedAt)\n }\n\n const planHash = hashAgentPlanEnvelope({\n operation: input.operation,\n collection,\n documentId: input.documentId,\n payload,\n })\n\n const createdAt = new Date()\n const expiresAt = new Date(createdAt.getTime() + AGENT_PLAN_TTL_MS)\n\n const stored = await writeAgentPlan({\n planDir: resolveAgentPlanDir(),\n record: {\n planHash,\n operation: input.operation,\n collection,\n documentId: input.documentId,\n payload,\n baseUpdatedAt,\n authFingerprint,\n createdAt: createdAt.toISOString(),\n expiresAt: expiresAt.toISOString(),\n },\n })\n\n const planToken = encodePlanToken({\n planId: stored.planId,\n planHash: stored.planHash,\n expiresAt: stored.expiresAt,\n })\n\n printAgentSuccess(\n {\n planToken,\n planHash: stored.planHash,\n planId: stored.planId,\n expiresAt: stored.expiresAt,\n operation: stored.operation,\n collection: stored.collection,\n documentId: stored.documentId,\n confirmCommand: buildConfirmCommand(planToken, stored.planHash),\n },\n { pretty: Boolean(input.pretty) },\n )\n}\n\nexport function registerAgentPlanCommands(\n agent: Command,\n getClient: () => ResolvedClient,\n): void {\n const plan = configureAgentParser(\n agent.command('plan').description('Plan a mutation without executing'),\n )\n\n configureAgentParser(\n plan\n .command('create <collection>')\n .description('Plan a document create')\n .option('--data-stdin', 'Read mutation JSON from stdin')\n .option('--data-file <path>', 'Read mutation JSON from file')\n .option('--pretty', 'Print 2-space indented JSON')\n .action(\n async (\n collection: string,\n opts: { dataStdin?: boolean; dataFile?: string; pretty?: boolean },\n ) => {\n try {\n await runPlanAction({\n operation: 'create',\n collection,\n dataStdin: opts.dataStdin,\n dataFile: opts.dataFile,\n pretty: opts.pretty,\n getClient,\n })\n } catch (error) {\n exitWithAgentError(error, { pretty: Boolean(opts.pretty) })\n }\n },\n ),\n )\n\n configureAgentParser(\n plan\n .command('update <collection> <id>')\n .description('Plan a document update')\n .option('--data-stdin', 'Read mutation JSON from stdin')\n .option('--data-file <path>', 'Read mutation JSON from file')\n .option('--pretty', 'Print 2-space indented JSON')\n .action(\n async (\n collection: string,\n id: string,\n opts: { dataStdin?: boolean; dataFile?: string; pretty?: boolean },\n ) => {\n try {\n await runPlanAction({\n operation: 'update',\n collection,\n documentId: id,\n dataStdin: opts.dataStdin,\n dataFile: opts.dataFile,\n pretty: opts.pretty,\n getClient,\n })\n } catch (error) {\n exitWithAgentError(error, { pretty: Boolean(opts.pretty) })\n }\n },\n ),\n )\n\n configureAgentParser(\n plan\n .command('delete <collection> <id>')\n .description('Plan a document delete')\n .option('--pretty', 'Print 2-space indented JSON')\n .action(\n async (\n collection: string,\n id: string,\n opts: { pretty?: boolean },\n ) => {\n try {\n await runPlanAction({\n operation: 'delete',\n collection,\n documentId: id,\n pretty: opts.pretty,\n getClient,\n })\n } catch (error) {\n exitWithAgentError(error, { pretty: Boolean(opts.pretty) })\n }\n },\n ),\n )\n\n configureAgentParser(\n agent\n .command('confirm <planToken>')\n .description('Execute a previously planned mutation')\n .requiredOption('--hash <planHash>', 'Plan hash from plan output')\n .option('--pretty', 'Print 2-space indented JSON')\n .action(\n async (\n planTokenRaw: string,\n opts: { hash: string; pretty?: boolean },\n ) => {\n try {\n const token = decodePlanToken(planTokenRaw)\n if (token.planHash !== opts.hash) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Plan token does not match --hash.',\n )\n }\n\n const client = getClient()\n const authFingerprint = buildAuthContextFingerprint({\n publishableKey: client.publishableKey,\n secretKey: client.secretKey,\n })\n\n const planDir = resolveAgentPlanDir()\n const plan = await claimAgentPlan({\n planDir,\n planId: token.planId,\n planHash: opts.hash,\n authFingerprint,\n })\n\n if (token.planId !== plan.planId) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Plan token does not match stored plan.',\n )\n }\n\n let doc: unknown\n try {\n doc = await executeAgentPlanMutation(client, plan)\n } catch (mutationError) {\n await releaseAgentPlanClaim({\n planDir,\n planId: plan.planId,\n }).catch(() => {})\n throw mutationError\n }\n\n await finalizeAgentPlan(plan)\n\n printAgentSuccess(\n {\n applied: true,\n operation: plan.operation,\n collection: plan.collection,\n id:\n doc && typeof doc === 'object' && 'id' in doc\n ? String((doc as Record<string, unknown>).id)\n : plan.documentId,\n doc,\n },\n { pretty: Boolean(opts.pretty) },\n )\n } catch (error) {\n exitWithAgentError(error, { pretty: Boolean(opts.pretty) })\n }\n },\n ),\n )\n}\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACDxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;ACLP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY;AACrB,SAAS,eAAe;AAgBxB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,eAAe;AAMd,SAAS,qBAA6B;AAC3C,SAAO,KAAK,QAAQ,GAAG,UAAU,SAAS;AAC5C;AAEO,SAAS,kBAA4C;AAC1D,SAAO,oBAAoB,mBAAmB,CAAC;AACjD;AAEO,SAAS,gBACd,OACM;AACN,QAAM,MAAM,KAAK,QAAQ,GAAG,QAAQ;AACpC,MAAI,CAAC,WAAW,GAAG,GAAG;AACpB,cAAU,KAAK,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,EACjD;AAEA,QAAM,WAAW,mBAAmB;AACpC,QAAM,OAA0B;AAAA,IAC9B,GAAG;AAAA,IACH,WAAU,oBAAI,KAAK,GAAE,YAAY;AAAA,EACnC;AACA,gBAAc,UAAU,KAAK,UAAU,MAAM,MAAM,CAAC,GAAG;AAAA,IACrD,UAAU;AAAA,IACV,MAAM;AAAA,EACR,CAAC;AACH;AAEO,SAAS,oBAA6B;AAC3C,QAAM,WAAW,mBAAmB;AACpC,MAAI,CAAC,WAAW,QAAQ,EAAG,QAAO;AAElC,aAAW,QAAQ;AACnB,SAAO;AACT;AAMO,SAAS,0BAAkC;AAChD,SAAO,KAAK,QAAQ,IAAI,GAAG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EAAE,MAA4B;AAElE,sBAAsB,SAAS,cAAc;AAC7C,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,uBAAuB,SAAS,WAAW,SAAS;AACpD,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,4BAA4B,SAAS,WAAW,SAAS;AACzD,wBAAwB,SAAS,WAAW,SAAS;AACrD,yBAAyB,SAAS,WAAW,SAAS;AACtD,yBAAyB,SAAS,WAAW,SAAS;AACtD,uBAAuB,SAAS,WAAW,SAAS;AACpD,wBAAwB,SAAS,WAAW,SAAS;AACrD,qBAAqB,OAAO;AAE5B,QAAQ,MAAM;","names":["t","readFileSync","readFileSync","program","getClient","getFormat","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","orderStatusSchema","program","getClient","getFormat","order","z","z","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","z","z","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","pc","pc","t","resolve","program","SERVER_COLLECTIONS","program","getClient","getFormat","SERVER_COLLECTIONS","program","getClient","getFormat","SERVER_COLLECTIONS","homedir","join","createHash","join","homedir","current","readFileSync","readFileSync","getClient","plan","invalidInput","handleCommanderError","configureAgentParser","SERVER_COLLECTIONS","program","getClient","require"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/lib/client.ts","../src/lib/credentials.ts","../src/lib/output.ts","../../../internal/errors/src/admin-error.ts","../src/lib/admin-error.ts","../src/lib/i18n.ts","../src/commands/crud.ts","../src/lib/collections.ts","../src/lib/parse.ts","../../../internal/contracts/src/tenant/index.ts","../../../internal/contracts/src/ecommerce/index.ts","../../../internal/contracts/src/ecommerce/product-upsert.ts","../../../internal/contracts/src/ecommerce/cart.ts","../../../internal/contracts/src/ecommerce/commerce-common.ts","../../../internal/contracts/src/ecommerce/checkout.ts","../../../internal/contracts/src/ecommerce/payment-session.ts","../src/commands/order.ts","../src/commands/return.ts","../src/lib/sensitive-json-input.ts","../src/commands/cart.ts","../src/commands/stock.ts","../src/commands/transaction.ts","../src/lib/product-detail-options.ts","../src/commands/product.ts","../src/commands/discount.ts","../src/commands/shipping.ts","../src/commands/auth.ts","../src/commands/schema.ts","../src/commands/feature.ts","../src/commands/agent.ts","../src/lib/agent-plan-allowlist.ts","../src/lib/agent-output.ts","../src/lib/agent-plan-auth.ts","../src/lib/agent-plan-store.ts","../src/lib/agent-plan-hash.ts","../src/lib/agent-plan-id.ts","../src/lib/agent-plan-stale.ts","../src/lib/agent-plan-confirm.ts","../src/lib/agent-plan-payload.ts","../src/lib/agent-plan-secrets.ts","../src/lib/agent-plan-token.ts","../src/commands/agent-plan.ts"],"sourcesContent":["import { createRequire } from 'node:module'\nimport { Command } from 'commander'\nimport { resolveClient, resolveClientOrThrow } from './lib/client.js'\nimport { exitWithError } from './lib/output.js'\nimport { setLocale, type Locale } from './lib/i18n.js'\nimport { registerCrudCommands } from './commands/crud.js'\nimport { registerOrderCommands } from './commands/order.js'\nimport { registerReturnCommands } from './commands/return.js'\nimport { registerCartCommands } from './commands/cart.js'\nimport { registerStockCommands } from './commands/stock.js'\nimport { registerCommerceSessionCommands } from './commands/transaction.js'\nimport { registerProductCommands } from './commands/product.js'\nimport { registerDiscountCommands } from './commands/discount.js'\nimport { registerShippingCommands } from './commands/shipping.js'\nimport { registerAuthCommands } from './commands/auth.js'\nimport { registerSchemaCommands } from './commands/schema.js'\nimport { registerFeatureCommands } from './commands/feature.js'\nimport { registerAgentCommands } from './commands/agent.js'\n\nconst require = createRequire(import.meta.url)\nconst { version } = require('../package.json') as { version: string }\n\nconst program = new Command()\n\nprogram\n .name('01')\n .description('CLI for the 01.software platform')\n .version(version)\n .option('--api-key <key>', 'API key (sk01_... or pat01_... token)')\n .option('--format <format>', 'Output format: json, table, or ndjson')\n .option('--lang <locale>', 'Force locale (ko or en)')\n\nconst getFormat = () =>\n (program.opts().format ?? process.env.OUTPUT_FORMAT ?? 'json') as string\n\n// Surface the explicit `--lang` flag (when supplied) so the i18n table\n// detection in `lib/i18n.ts` honours it before falling back to LC_ALL/LANG.\n// Also pin OUTPUT_FORMAT into the env so `exitWithError(e)` calls inside\n// command bodies pick up the format without threading it through every\n// call site.\nprogram.hook('preAction', () => {\n const lang = program.opts().lang as string | undefined\n if (lang === 'ko' || lang === 'en') setLocale(lang as Locale)\n process.env.OUTPUT_FORMAT = getFormat()\n})\n\nprocess.on('unhandledRejection', (err) => {\n exitWithError(err, { format: getFormat() })\n})\n\nconst getClient = () =>\n resolveClient(program.opts().apiKey as string | undefined)\nconst getAgentClient = () =>\n resolveClientOrThrow(program.opts().apiKey as string | undefined)\n\nregisterAgentCommands(program, getAgentClient)\nregisterCrudCommands(program, getClient, getFormat)\nregisterOrderCommands(program, getClient, getFormat)\nregisterReturnCommands(program, getClient, getFormat)\nregisterCartCommands(program, getClient, getFormat)\nregisterStockCommands(program, getClient, getFormat)\nregisterCommerceSessionCommands(program, getClient, getFormat)\nregisterProductCommands(program, getClient, getFormat)\nregisterDiscountCommands(program, getClient, getFormat)\nregisterShippingCommands(program, getClient, getFormat)\nregisterSchemaCommands(program, getClient, getFormat)\nregisterFeatureCommands(program, getClient, getFormat)\nregisterAuthCommands(program)\n\nprogram.parse()\n","import {\n ServerCollectionClient,\n ServerCommerceClient,\n TenantIntrospectionApi,\n type TenantIntrospectionClient,\n} from '@01.software/sdk/server'\nimport { loadCredentials, loadLocalCredentials } from './credentials.js'\nimport { exitWithError } from './output.js'\nimport { t } from './i18n.js'\nimport type { AdminError } from './admin-error.js'\n\nexport interface ResolvedClient {\n collections: ServerCollectionClient\n commerce: ServerCommerceClient\n tenant: TenantIntrospectionClient\n publishableKey: string\n secretKey: string\n}\n\ninterface ResolvedCredentials {\n publishableKey: string\n secretKey: string\n}\n\n/**\n * Accepted opaque bearer token prefixes.\n * - `sk01_` = tenant-level API key (created in Console > Settings > API Keys)\n * - `pat01_` = user-level Personal Access Token\n * Hex HMAC secrets from the pre-2026-04 auth system are rejected.\n */\nfunction isValidBearerToken(secret: string): boolean {\n return secret.startsWith('sk01_') || secret.startsWith('pat01_')\n}\n\nfunction credentialError(detail: Record<string, unknown>): AdminError {\n return {\n type: 'permission',\n code: 'credential_invalid',\n detail,\n }\n}\n\n/**\n * Resolve credentials in priority order:\n * 1. `--api-key <token>` flag (overrides secretKey only; publishableKey still\n * comes from env/credentials)\n * 2. `SOFTWARE_PUBLISHABLE_KEY` + `SOFTWARE_SECRET_KEY` env vars\n * 3. Local project credentials (`./.01software/credentials.json`)\n * 4. Global user credentials (`~/.01software/credentials.json`)\n */\nfunction resolveClientCredentials(apiKeyFlag?: string): ResolvedCredentials {\n let publishableKey: string | undefined = process.env.SOFTWARE_PUBLISHABLE_KEY\n let secretKey: string | undefined =\n apiKeyFlag ?? process.env.SOFTWARE_SECRET_KEY\n\n if (!publishableKey || !secretKey) {\n const local = loadLocalCredentials()\n if (local) {\n publishableKey = publishableKey ?? local.publishableKey\n secretKey = secretKey ?? local.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n const stored = loadCredentials()\n if (stored) {\n publishableKey = publishableKey ?? stored.publishableKey\n secretKey = secretKey ?? stored.secretKey\n }\n }\n\n if (!publishableKey || !secretKey) {\n throw credentialError({\n message: t('AuthenticationRequired'),\n steps: [t('RunLoginToAuthenticate'), t('PassApiKey'), t('SetEnvVars')],\n })\n }\n\n if (!isValidBearerToken(secretKey)) {\n throw credentialError({\n message: t('InvalidApiKeyFormat'),\n suggestion: t('RetiredHexCredentialsRejected'),\n })\n }\n\n return { publishableKey, secretKey }\n}\n\nexport function resolveClientOrThrow(apiKeyFlag?: string): ResolvedClient {\n const { publishableKey, secretKey } = resolveClientCredentials(apiKeyFlag)\n const serverOptions = { publishableKey, secretKey }\n\n return {\n collections: new ServerCollectionClient(\n publishableKey,\n secretKey,\n undefined,\n undefined,\n undefined,\n ),\n commerce: new ServerCommerceClient(serverOptions),\n tenant: new TenantIntrospectionApi(serverOptions),\n publishableKey,\n secretKey,\n }\n}\n\nexport function resolveClient(apiKeyFlag?: string): ResolvedClient {\n try {\n return resolveClientOrThrow(apiKeyFlag)\n } catch (error) {\n exitWithError(error)\n }\n}\n","import {\n chmodSync,\n closeSync,\n constants as fsConstants,\n existsSync,\n fchmodSync,\n fstatSync,\n fsyncSync,\n lstatSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n type Stats,\n unlinkSync,\n writeFileSync,\n appendFileSync,\n} from 'node:fs'\nimport { spawnSync } from 'node:child_process'\nimport { randomBytes } from 'node:crypto'\nimport { dirname, join } from 'node:path'\nimport { homedir } from 'node:os'\n\nexport interface StoredCredentials {\n publishableKey: string\n /** Opaque bearer token — tenant API key (sk01_...) or PAT (pat01_...) */\n secretKey: string\n tenantId?: string\n tenantName: string\n storedAt: string\n}\n\nexport interface TenantInfo {\n id: string\n name: string\n}\n\nconst DIR_NAME = '.01software'\nconst FILE_NAME = 'credentials.json'\nconst TENANTS_FILE = 'tenants.json'\nconst LOCAL_CREDENTIAL_PATH = `${DIR_NAME}/${FILE_NAME}`\nconst LOCAL_GITIGNORE_ENTRY = `${DIR_NAME}/`\nconst PRIVATE_DIRECTORY_MODE = 0o700\nconst PRIVATE_FILE_MODE = 0o600\nconst CURRENT_USER_ID =\n process.platform !== 'win32' && typeof process.getuid === 'function'\n ? process.getuid()\n : null\nconst HAS_POSIX_FILE_PERMISSIONS = CURRENT_USER_ID !== null\nconst SANITIZED_GIT_ENVIRONMENT_VARIABLES = new Set([\n 'GIT_ALTERNATE_OBJECT_DIRECTORIES',\n 'GIT_CEILING_DIRECTORIES',\n 'GIT_COMMON_DIR',\n 'GIT_CONFIG_COUNT',\n 'GIT_CONFIG_PARAMETERS',\n 'GIT_DIR',\n 'GIT_DISCOVERY_ACROSS_FILESYSTEM',\n 'GIT_INDEX_FILE',\n 'GIT_ICASE_PATHSPECS',\n 'GIT_GLOB_PATHSPECS',\n 'GIT_LITERAL_PATHSPECS',\n 'GIT_NOGLOB_PATHSPECS',\n 'GIT_OBJECT_DIRECTORY',\n 'GIT_PREFIX',\n 'GIT_WORK_TREE',\n])\n\n// ---------------------------------------------------------------------------\n// Global credentials (~/.01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getCredentialsPath(): string {\n return join(homedir(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getCredentialsPath())\n}\n\nexport function saveCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n): void {\n const filePath = getCredentialsPath()\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeCredentialFile(filePath, JSON.stringify(data, null, 2))\n}\n\nexport function deleteCredentials(): boolean {\n const filePath = getCredentialsPath()\n if (!existsSync(filePath)) return false\n\n unlinkSync(filePath)\n return true\n}\n\n// ---------------------------------------------------------------------------\n// Local credentials (./.01software/credentials.json)\n// ---------------------------------------------------------------------------\n\nexport function getLocalCredentialsPath(): string {\n return join(process.cwd(), DIR_NAME, FILE_NAME)\n}\n\nexport function loadLocalCredentials(): StoredCredentials | null {\n return loadCredentialsFrom(getLocalCredentialsPath())\n}\n\nexport function saveLocalCredentials(\n creds: Omit<StoredCredentials, 'storedAt'>,\n workingDirectory = process.cwd(),\n): void {\n // Fail closed before creating a secret-bearing file. The repository-level\n // .gitignore already covers this path, but callers may run the CLI elsewhere.\n const temporaryFileName = createTemporaryCredentialFileName()\n ensureGitignore(workingDirectory, `${DIR_NAME}/${temporaryFileName}`)\n\n const filePath = join(workingDirectory, DIR_NAME, FILE_NAME)\n const data: StoredCredentials = {\n ...creds,\n storedAt: new Date().toISOString(),\n }\n writeCredentialFile(\n filePath,\n JSON.stringify(data, null, 2),\n temporaryFileName,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Tenant list cache (~/.01software/tenants.json)\n// ---------------------------------------------------------------------------\n\nexport function saveTenantList(tenants: TenantInfo[]): void {\n const dir = join(homedir(), DIR_NAME)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n writeFileSync(filePath, JSON.stringify(tenants, null, 2), {\n encoding: 'utf-8',\n mode: 0o600,\n })\n}\n\nexport function loadTenantList(): TenantInfo[] | null {\n const filePath = join(homedir(), DIR_NAME, TENANTS_FILE)\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw)\n if (!Array.isArray(data)) return null\n const valid = data.filter(\n (t): t is TenantInfo =>\n typeof t?.id === 'string' && typeof t?.name === 'string',\n )\n return valid.length > 0 ? valid : null\n } catch {\n return null\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\ninterface FileIdentity {\n dev: number\n ino: number\n}\n\nfunction writeCredentialFile(\n filePath: string,\n content: string,\n temporaryFileName = createTemporaryCredentialFileName(),\n): void {\n const directoryPath = dirname(filePath)\n const directoryDescriptor = openPrivateCredentialDirectory(directoryPath)\n const initialTarget = inspectCredentialTarget(filePath)\n const tempPath = join(directoryPath, temporaryFileName)\n let tempDescriptor: number | undefined\n\n try {\n tempDescriptor = openSync(tempPath, 'wx', PRIVATE_FILE_MODE)\n const tempStats = fstatSync(tempDescriptor)\n assertRegularOwnedCredentialFile(tempStats, 'temporary credential file')\n if (HAS_POSIX_FILE_PERMISSIONS) {\n fchmodSync(tempDescriptor, PRIVATE_FILE_MODE)\n assertMode(\n fstatSync(tempDescriptor),\n PRIVATE_FILE_MODE,\n 'temporary credential file',\n )\n }\n\n writeFileSync(tempDescriptor, content, { encoding: 'utf-8' })\n fsyncSync(tempDescriptor)\n closeSync(tempDescriptor)\n tempDescriptor = undefined\n\n const currentTarget = inspectCredentialTarget(filePath)\n if (!sameFileIdentity(initialTarget, currentTarget)) {\n throw credentialFileProtectionError(\n 'credential target changed while being checked',\n )\n }\n\n renameSync(tempPath, filePath)\n const finalStats = lstatCredentialPath(filePath)\n if (!finalStats) {\n throw credentialFileProtectionError(\n 'credential target disappeared after atomic replacement',\n )\n }\n assertRegularOwnedCredentialFile(finalStats, 'credential target')\n if (HAS_POSIX_FILE_PERMISSIONS) {\n assertMode(finalStats, PRIVATE_FILE_MODE, 'credential target')\n if (directoryDescriptor !== undefined) {\n fsyncSync(directoryDescriptor)\n }\n }\n } catch (error) {\n if (tempDescriptor !== undefined) {\n try {\n closeSync(tempDescriptor)\n } catch {\n // Best-effort descriptor cleanup after a failed private-file write.\n }\n }\n try {\n unlinkSync(tempPath)\n } catch {\n // Best-effort cleanup after a failed write or atomic replacement.\n }\n throw error\n } finally {\n if (directoryDescriptor !== undefined) {\n closeSync(directoryDescriptor)\n }\n }\n}\n\nfunction openPrivateCredentialDirectory(\n directoryPath: string,\n): number | undefined {\n let directoryStats = lstatCredentialPath(directoryPath)\n if (!directoryStats) {\n try {\n mkdirSync(directoryPath, { mode: PRIVATE_DIRECTORY_MODE })\n if (HAS_POSIX_FILE_PERMISSIONS) {\n chmodSync(directoryPath, PRIVATE_DIRECTORY_MODE)\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n // Another process created the path after lstat. Inspect it below.\n }\n directoryStats = lstatCredentialPath(directoryPath)\n }\n\n if (\n !directoryStats ||\n directoryStats.isSymbolicLink() ||\n !directoryStats.isDirectory()\n ) {\n throw credentialFileProtectionError(\n 'credential directory must be a regular directory, not a symlink',\n )\n }\n assertCurrentUserOwns(directoryStats, 'credential directory')\n\n if (!HAS_POSIX_FILE_PERMISSIONS) return undefined\n\n const descriptor = openSync(\n directoryPath,\n fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,\n )\n try {\n const openedStats = fstatSync(descriptor)\n if (\n !openedStats.isDirectory() ||\n openedStats.dev !== directoryStats.dev ||\n openedStats.ino !== directoryStats.ino\n ) {\n throw credentialFileProtectionError(\n 'credential directory changed while being checked',\n )\n }\n assertCurrentUserOwns(openedStats, 'credential directory')\n fchmodSync(descriptor, PRIVATE_DIRECTORY_MODE)\n assertMode(\n fstatSync(descriptor),\n PRIVATE_DIRECTORY_MODE,\n 'credential directory',\n )\n return descriptor\n } catch (error) {\n closeSync(descriptor)\n throw error\n }\n}\n\nfunction inspectCredentialTarget(filePath: string): FileIdentity | null {\n const stats = lstatCredentialPath(filePath)\n if (!stats) return null\n\n assertRegularOwnedCredentialFile(stats, 'credential target')\n return { dev: stats.dev, ino: stats.ino }\n}\n\nfunction assertRegularOwnedCredentialFile(\n stats: Stats,\n description: string,\n): void {\n if (stats.isSymbolicLink()) {\n throw credentialFileProtectionError(`${description} must not be a symlink`)\n }\n if (!stats.isFile()) {\n throw credentialFileProtectionError(`${description} must be a regular file`)\n }\n if (HAS_POSIX_FILE_PERMISSIONS && stats.nlink > 1) {\n throw credentialFileProtectionError(\n `${description} must not have multiple hard links`,\n )\n }\n assertCurrentUserOwns(stats, description)\n}\n\nfunction assertCurrentUserOwns(stats: Stats, description: string): void {\n if (CURRENT_USER_ID !== null && stats.uid !== CURRENT_USER_ID) {\n throw credentialFileProtectionError(\n `${description} must be owned by the current user`,\n )\n }\n}\n\nfunction assertMode(stats: Stats, expectedMode: number, description: string) {\n if ((stats.mode & 0o777) !== expectedMode) {\n throw credentialFileProtectionError(\n `${description} permissions could not be secured`,\n )\n }\n}\n\nfunction sameFileIdentity(\n initial: FileIdentity | null,\n current: FileIdentity | null,\n): boolean {\n if (!initial || !current) return initial === current\n return initial.dev === current.dev && initial.ino === current.ino\n}\n\nfunction lstatCredentialPath(filePath: string): Stats | null {\n try {\n return lstatSync(filePath)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw credentialFileProtectionError(\n 'credential filesystem target could not be inspected',\n )\n }\n}\n\nfunction credentialFileProtectionError(message: string): Error {\n return new Error(`Cannot save credentials: ${message}`)\n}\n\nfunction loadCredentialsFrom(filePath: string): StoredCredentials | null {\n if (!existsSync(filePath)) return null\n\n try {\n const raw = readFileSync(filePath, 'utf-8')\n const data = JSON.parse(raw) as StoredCredentials\n if (!data.publishableKey || !data.secretKey) return null\n return data\n } catch {\n return null\n }\n}\n\nfunction ensureGitignore(cwd: string, temporaryCredentialPath: string): void {\n const gitignorePath = join(cwd, '.gitignore')\n assertSafeGitignorePath(gitignorePath)\n\n const gitState = detectGitWorkTree(cwd)\n if (gitState === 'inside') {\n assertCredentialPathIsUntracked(cwd)\n if (areCredentialPathsIgnored(cwd, temporaryCredentialPath)) return\n\n ensureTerminalGitignoreEntry(gitignorePath, true)\n if (!areCredentialPathsIgnored(cwd, temporaryCredentialPath)) {\n throw credentialProtectionError(\n 'Git still reports a credential path as unignored',\n )\n }\n return\n }\n\n // Outside a Git work tree, keep a durable rule for a future `git init`\n // without requiring Git to be installed.\n ensureTerminalGitignoreEntry(gitignorePath, false)\n}\n\nfunction assertSafeGitignorePath(gitignorePath: string): void {\n const stats = lstatIfPresent(gitignorePath)\n if (stats && (!stats.isFile() || stats.isSymbolicLink())) {\n throw credentialProtectionError('.gitignore must be a regular file')\n }\n}\n\nfunction ensureTerminalGitignoreEntry(\n gitignorePath: string,\n forceAppend: boolean,\n): void {\n const initialStats = lstatIfPresent(gitignorePath)\n if (!initialStats) {\n try {\n writeFileSync(gitignorePath, `${LOCAL_GITIGNORE_ENTRY}\\n`, {\n encoding: 'utf-8',\n flag: 'wx',\n })\n return\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n // Another process created the path after lstat. Re-inspect it below.\n return ensureTerminalGitignoreEntry(gitignorePath, forceAppend)\n }\n }\n\n if (!initialStats.isFile() || initialStats.isSymbolicLink()) {\n throw credentialProtectionError('.gitignore must be a regular file')\n }\n\n const descriptor = openSync(gitignorePath, 'a+')\n try {\n const openedStats = fstatSync(descriptor)\n if (\n !openedStats.isFile() ||\n openedStats.dev !== initialStats.dev ||\n openedStats.ino !== initialStats.ino\n ) {\n throw credentialProtectionError('.gitignore changed while being checked')\n }\n\n const content = readFileSync(descriptor, 'utf-8')\n const lastNonEmptyLine = content\n .split(/\\r?\\n/)\n .filter((line) => line.length > 0)\n .at(-1)\n if (\n !forceAppend &&\n (lastNonEmptyLine === LOCAL_GITIGNORE_ENTRY ||\n lastNonEmptyLine === `/${LOCAL_GITIGNORE_ENTRY}`)\n ) {\n return\n }\n\n const separator = content.length > 0 && !content.endsWith('\\n') ? '\\n' : ''\n appendFileSync(\n descriptor,\n `${separator}${LOCAL_GITIGNORE_ENTRY}\\n`,\n 'utf-8',\n )\n } finally {\n closeSync(descriptor)\n }\n}\n\nfunction detectGitWorkTree(cwd: string): 'inside' | 'outside' {\n const result = runGit(cwd, ['rev-parse', '--is-inside-work-tree'])\n if (result.error) {\n if (\n (result.error as NodeJS.ErrnoException).code === 'ENOENT' &&\n !hasGitMarker(cwd)\n ) {\n return 'outside'\n }\n throw credentialProtectionError('Git repository detection failed')\n }\n\n if (result.status === 0) {\n if (result.stdout.trim() === 'true') return 'inside'\n throw credentialProtectionError(\n 'the current directory is not a Git work tree',\n )\n }\n\n if (result.status === 128 && !hasGitMarker(cwd)) return 'outside'\n throw credentialProtectionError('Git repository detection failed')\n}\n\nfunction assertCredentialPathIsUntracked(cwd: string): void {\n const result = runGit(cwd, [\n 'ls-files',\n '-z',\n '--',\n `:(icase,literal)${LOCAL_CREDENTIAL_PATH}`,\n ])\n if (result.error || result.status !== 0) {\n throw credentialProtectionError('Git tracked-file verification failed')\n }\n if (result.stdout.length > 0) {\n throw credentialProtectionError(\n '.01software/credentials.json is already tracked by Git',\n )\n }\n}\n\nfunction createTemporaryCredentialFileName(): string {\n return `.${FILE_NAME}.${randomBytes(12).toString('hex')}.tmp`\n}\n\nfunction areCredentialPathsIgnored(\n cwd: string,\n temporaryCredentialPath: string,\n): boolean {\n // Both paths must be ignored. A directory-level rule can be followed by a\n // negation that makes either the credential or its atomic-write temporary\n // stageable again.\n return (\n isPathIgnored(cwd, LOCAL_CREDENTIAL_PATH) &&\n isPathIgnored(cwd, temporaryCredentialPath)\n )\n}\n\nfunction isPathIgnored(cwd: string, relativePath: string): boolean {\n const result = runGit(cwd, [\n 'check-ignore',\n '--quiet',\n '--no-index',\n '--',\n relativePath,\n ])\n if (result.error || (result.status !== 0 && result.status !== 1)) {\n throw credentialProtectionError('Git ignore verification failed')\n }\n return result.status === 0\n}\n\nfunction runGit(cwd: string, args: string[]) {\n const env: NodeJS.ProcessEnv = { ...process.env, LC_ALL: 'C' }\n for (const key of Object.keys(env)) {\n const normalizedKey = key.toUpperCase()\n if (\n SANITIZED_GIT_ENVIRONMENT_VARIABLES.has(normalizedKey) ||\n normalizedKey.startsWith('GIT_CONFIG_KEY_') ||\n normalizedKey.startsWith('GIT_CONFIG_VALUE_')\n ) {\n delete env[key]\n }\n }\n return spawnSync('git', args, {\n cwd,\n encoding: 'utf-8',\n env,\n })\n}\n\nfunction hasGitMarker(startPath: string): boolean {\n let currentPath = startPath\n while (true) {\n if (lstatIfPresent(join(currentPath, '.git'))) return true\n const parentPath = dirname(currentPath)\n if (parentPath === currentPath) return false\n currentPath = parentPath\n }\n}\n\nfunction lstatIfPresent(filePath: string) {\n try {\n return lstatSync(filePath)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw credentialProtectionError('local Git metadata could not be inspected')\n }\n}\n\nfunction credentialProtectionError(message: string): Error {\n return new Error(`Cannot save local credentials: ${message}`)\n}\n","import pc from 'picocolors'\nimport {\n type AdminError,\n classifyError,\n adminErrorExitCode,\n} from './admin-error.js'\nimport { CLI_I18N_KO, t } from './i18n.js'\n\n// Build a Set of valid i18n keys for fast lookup when localizing AdminError\n// codes. Reused below to choose between localized and fallback rendering.\nconst CLI_I18N_KEYS: readonly string[] = Object.keys(CLI_I18N_KO)\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2))\n}\n\nexport function printTable(data: unknown): void {\n if (Array.isArray(data)) {\n if (data.length === 0) {\n console.log(pc.dim(t('Empty')))\n return\n }\n const keys = Object.keys(data[0] as Record<string, unknown>)\n const widths = keys.map((k) =>\n Math.max(\n k.length,\n ...data.map(\n (row) => String((row as Record<string, unknown>)[k] ?? '').length,\n ),\n ),\n )\n\n // Header\n console.log(keys.map((k, i) => k.padEnd(widths[i]!)).join(' '))\n console.log(keys.map((_, i) => '-'.repeat(widths[i]!)).join(' '))\n\n // Rows\n for (const row of data) {\n console.log(\n keys\n .map((k, i) =>\n String((row as Record<string, unknown>)[k] ?? '').padEnd(\n widths[i]!,\n ),\n )\n .join(' '),\n )\n }\n } else if (data && typeof data === 'object') {\n const entries = Object.entries(data as Record<string, unknown>)\n const maxKey = Math.max(...entries.map(([k]) => k.length))\n for (const [key, value] of entries) {\n const display =\n typeof value === 'object' ? JSON.stringify(value) : String(value)\n console.log(`${pc.bold(key.padEnd(maxKey))} ${display}`)\n }\n } else {\n console.log(String(data))\n }\n}\n\nfunction printNdjson(data: unknown): void {\n if (Array.isArray(data)) {\n data.forEach((item) => console.log(JSON.stringify(item)))\n } else if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const { docs, ...meta } = data as {\n docs: unknown[]\n [key: string]: unknown\n }\n ;(docs as unknown[]).forEach((doc) => console.log(JSON.stringify(doc)))\n if (Object.keys(meta).length > 0)\n console.log(JSON.stringify({ _meta: meta }))\n } else {\n console.log(JSON.stringify(data))\n }\n}\n\nexport function printResult(data: unknown, format: string): void {\n if (format === 'ndjson') {\n printNdjson(data)\n } else if (format === 'table') {\n // For find responses with docs array, print the docs as table\n if (\n data &&\n typeof data === 'object' &&\n 'docs' in (data as Record<string, unknown>)\n ) {\n const resp = data as {\n docs: unknown[]\n totalDocs: number\n page: number\n totalPages: number\n }\n printTable(resp.docs)\n console.log(\n pc.dim(\n `\\n${t('Total', { n: resp.totalDocs })} | ${t('PageOf', {\n page: resp.page,\n total: resp.totalPages,\n })}`,\n ),\n )\n return\n }\n printTable(data)\n } else {\n printJson(data)\n }\n}\n\n/**\n * Map an unknown error → CLI exit code per `docs/packages/cli-exit-codes.md`.\n *\n * Routes through `classifyError()` (the AdminError discriminated union is\n * the canonical source). The SDK-error-name + HTTP-status heuristic lives\n * inside `classifyError` so existing thrown values keep their mapping.\n * The `unknown` code → exit 1 fallback is encoded in\n * `adminErrorExitCode` itself.\n */\nexport function getExitCode(error: unknown): number {\n return adminErrorExitCode(classifyError(error))\n}\n\nexport interface ErrorPrintOptions {\n format?: string\n}\n\n/**\n * Resolve the active output format. The entry point (`index.ts`) sets\n * `process.env.OUTPUT_FORMAT` from `--format` / fallback so command bodies\n * can call `exitWithError(e)` without threading the format through every\n * call site. Explicit `options.format` always wins.\n */\nfunction resolveFormat(options: ErrorPrintOptions): string {\n return options.format ?? process.env.OUTPUT_FORMAT ?? 'json'\n}\n\n/**\n * Render an error to the user. With `--format json` (or\n * `OUTPUT_FORMAT=json`), serialize the AdminError discriminated union to\n * stdout per the contract in `docs/packages/cli-exit-codes.md`. Otherwise\n * print a localized one-line message + supporting metadata to stderr.\n */\nexport function printError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): void {\n const adminError = classifyError(error)\n\n // Per docs/packages/cli-exit-codes.md: ALWAYS emit a one-line human\n // message on stderr before exiting non-zero. Under `--format json` the\n // AdminError JSON is ALSO serialized to stdout so scripts can parse it.\n const knownKey = CLI_I18N_KEYS.includes(adminError.code)\n ? (adminError.code as Parameters<typeof t>[0])\n : null\n const localized = knownKey ? t(knownKey) : null\n const rawErr =\n error && typeof error === 'object'\n ? (error as Record<string, unknown>)\n : null\n const rawMessage =\n rawErr && typeof rawErr.message === 'string' ? rawErr.message : ''\n const stringErr = typeof error === 'string' ? error : ''\n const detailMessage =\n rawErr &&\n rawErr.detail &&\n typeof rawErr.detail === 'object' &&\n typeof (rawErr.detail as Record<string, unknown>).message === 'string'\n ? String((rawErr.detail as Record<string, unknown>).message)\n : ''\n // Headline: prefer the most specific human-readable text on hand —\n // raw `message` (most common SDK shape), then a string-error directly,\n // then `detail.message`, then the localized AdminError-code translation,\n // then the bare code.\n const headline =\n rawMessage || stringErr || detailMessage || localized || adminError.code\n\n console.error(pc.red(`Error: ${headline}`))\n // Surface the raw `code`/`status` (when present and distinct) so callers\n // who throw SDK errors with proprietary codes don't lose them in the\n // human-readable rendering. The AdminError type/code is always emitted\n // — that's the canonical contract.\n if (\n rawErr &&\n typeof rawErr.code === 'string' &&\n rawErr.code !== adminError.code\n ) {\n console.error(pc.dim(`Code: ${rawErr.code}`))\n } else {\n console.error(pc.dim(`Code: ${adminError.code}`))\n }\n if (rawErr && typeof rawErr.status === 'number') {\n console.error(pc.dim(`Status: ${rawErr.status}`))\n }\n console.error(pc.dim(`Type: ${adminError.type}`))\n\n if (\n adminError.type === 'degraded' &&\n typeof adminError.retryAfter === 'number'\n ) {\n console.error(pc.yellow(`Retry after: ${adminError.retryAfter}s`))\n }\n if (rawErr && typeof rawErr.suggestion === 'string') {\n console.error(pc.yellow(rawErr.suggestion))\n }\n\n if (resolveFormat(options) === 'json') {\n console.log(JSON.stringify(adminError))\n }\n}\n\nexport function exitWithError(\n error: unknown,\n options: ErrorPrintOptions = {},\n): never {\n printError(error, options)\n process.exit(getExitCode(error))\n}\n","export type ValidationCode = string\n\nexport type PermissionCode =\n | 'tenant_mismatch'\n | 'account_suspended'\n | 'feature_disabled'\n | 'role_denied'\n | 'credential_invalid'\n | 'pat_tenant_unpinned'\n | 'publishable_key_mismatch'\n | 'scope_denied'\n\nexport type DegradedCode =\n | 'redis_unavailable'\n | 'provider_unavailable'\n | 'rate_limited'\n\nexport type NetworkCode = 'upstream_timeout' | 'upstream_5xx' | 'dns_failure'\n\nexport type AdminErrorCode =\n | PermissionCode\n | DegradedCode\n | NetworkCode\n | ValidationCode\n\nexport type AdminError =\n | {\n type: 'validation'\n code: ValidationCode\n field?: string\n detail?: Record<string, unknown>\n }\n | {\n type: 'permission'\n code: PermissionCode\n detail?: Record<string, unknown>\n }\n | {\n type: 'degraded'\n code: DegradedCode\n retryAfter?: number\n detail?: Record<string, unknown>\n }\n | {\n type: 'network'\n code: NetworkCode\n detail?: Record<string, unknown>\n }\n\nexport const ADMIN_ERROR_CODES = {\n permission: [\n 'tenant_mismatch',\n 'account_suspended',\n 'feature_disabled',\n 'role_denied',\n 'credential_invalid',\n 'pat_tenant_unpinned',\n 'publishable_key_mismatch',\n 'scope_denied',\n ] as const satisfies readonly PermissionCode[],\n degraded: [\n 'redis_unavailable',\n 'provider_unavailable',\n 'rate_limited',\n ] as const satisfies readonly DegradedCode[],\n network: [\n 'upstream_timeout',\n 'upstream_5xx',\n 'dns_failure',\n ] as const satisfies readonly NetworkCode[],\n} as const\n\nconst PERMISSION_CODES = ADMIN_ERROR_CODES.permission\nconst DEGRADED_CODES = ADMIN_ERROR_CODES.degraded\nconst NETWORK_CODES = ADMIN_ERROR_CODES.network\n\nfunction isPermissionCode(code: string): code is PermissionCode {\n return (PERMISSION_CODES as readonly string[]).includes(code)\n}\n\nfunction isDegradedCode(code: string): code is DegradedCode {\n return (DEGRADED_CODES as readonly string[]).includes(code)\n}\n\nfunction isNetworkCode(code: string): code is NetworkCode {\n return (NETWORK_CODES as readonly string[]).includes(code)\n}\n\nexport function isUnknownAdminError(err: AdminError): boolean {\n return err.type === 'validation' && err.code === 'unknown'\n}\n\n/**\n * Shared AdminError classifier for literal codes and explicit validation shapes.\n * Surfaces that need SDK/HTTP heuristics wrap this and handle `unknown` locally.\n */\nexport function classifyAdminError(err: unknown): AdminError {\n if (err && typeof err === 'object') {\n const obj = err as Record<string, unknown>\n\n if (typeof obj.code === 'string') {\n const code = obj.code\n if (isPermissionCode(code)) {\n return { type: 'permission', code }\n }\n if (isDegradedCode(code)) {\n const out: AdminError = { type: 'degraded', code }\n if (typeof obj.retryAfter === 'number') {\n out.retryAfter = obj.retryAfter\n }\n return out\n }\n if (isNetworkCode(code)) {\n return { type: 'network', code }\n }\n }\n\n if (obj.type === 'validation' && typeof obj.code === 'string') {\n const out: AdminError = { type: 'validation', code: obj.code }\n if (typeof obj.field === 'string') out.field = obj.field\n if (obj.detail && typeof obj.detail === 'object') {\n out.detail = obj.detail as Record<string, unknown>\n }\n return out\n }\n }\n\n return {\n type: 'validation',\n code: 'unknown',\n detail: { message: err instanceof Error ? err.message : String(err) },\n }\n}\n","// CLI AdminError surface. Shared taxonomy and core classifier live in\n// `@01.software/errors`. Locale copy stays in `packages/published/cli/src/lib/i18n.ts`.\n// Drift is enforced by `pnpm verify:i18n-parity`.\n\nimport {\n ADMIN_ERROR_CODES,\n classifyAdminError,\n isUnknownAdminError,\n type AdminError,\n type AdminErrorCode,\n type DegradedCode,\n type NetworkCode,\n type PermissionCode,\n type ValidationCode,\n} from '@01.software/errors'\n\nexport type {\n AdminError,\n AdminErrorCode,\n DegradedCode,\n NetworkCode,\n PermissionCode,\n ValidationCode,\n}\n\nexport { ADMIN_ERROR_CODES }\n\nfunction classifyCliExtensions(err: unknown): AdminError | null {\n if (!err || typeof err !== 'object') return null\n\n const obj = err as Record<string, unknown>\n\n if (obj.code === 'auth_error' || obj.code === 'permission_error') {\n return { type: 'permission', code: 'credential_invalid' }\n }\n\n const name = typeof obj.name === 'string' ? obj.name : undefined\n const status = typeof obj.status === 'number' ? obj.status : undefined\n if (\n name === 'ConfigError' ||\n name === 'AuthError' ||\n name === 'PermissionError' ||\n status === 401 ||\n status === 403\n ) {\n return { type: 'permission', code: 'credential_invalid' }\n }\n if (\n name === 'NetworkError' ||\n name === 'TimeoutError' ||\n status === 408 ||\n status === 503\n ) {\n return { type: 'network', code: 'upstream_timeout' }\n }\n if (name === 'GoneError' || status === 404) {\n return {\n type: 'validation',\n code: 'not_found',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n if (name === 'UsageLimitError' || status === 429) {\n const out: AdminError = { type: 'degraded', code: 'rate_limited' }\n if (typeof obj.retryAfter === 'number') out.retryAfter = obj.retryAfter\n return out\n }\n if (name === 'ValidationError' || status === 400 || status === 422) {\n return {\n type: 'validation',\n code: 'invalid_argument',\n detail:\n typeof obj.message === 'string' ? { message: obj.message } : undefined,\n }\n }\n\n return null\n}\n\n/**\n * Classify an unknown thrown / rejected value into the AdminError union.\n * Applies shared taxonomy first, then CLI-only SDK/HTTP fallbacks.\n */\nexport function classifyError(err: unknown): AdminError {\n const classified = classifyAdminError(err)\n if (!isUnknownAdminError(classified)) return classified\n return classifyCliExtensions(err) ?? classified\n}\n\n/**\n * Map AdminError → CLI exit code per `docs/packages/cli-exit-codes.md`.\n */\nexport function adminErrorExitCode(err: AdminError): number {\n if (err.code === 'unknown') return 1\n switch (err.type) {\n case 'permission':\n return 2\n case 'validation':\n return err.code === 'not_found' ? 5 : 3\n case 'network':\n return 4\n case 'degraded':\n return err.code === 'rate_limited' ? 6 : 4\n }\n}\n","// CLI i18n table — mirrors `apps/console/src/lib/i18n/admin.ts` AdminError\n// code coverage so a single check (`apps/console/scripts/check-i18n-parity.ts`)\n// can verify the CLI carries every code with both KO and EN translations.\n//\n// Locale resolution:\n// 1. CLI `--lang <ko|en>` (resolved by the entry point and exported via\n// `setLocale`).\n// 2. `LANG` / `LC_ALL` environment variables — anything starting with\n// `ko` (`ko_KR.UTF-8`, `ko-KR`, …) → ko; else en.\n// 3. Default `en`.\n\nexport const CLI_I18N_KO = {\n // CLI-surface microcopy\n AuthenticationRequired: '인증이 필요합니다',\n RunLoginToAuthenticate: '`01 login` 명령으로 브라우저 인증을 진행하거나,',\n PassApiKey: '`--api-key <token>` 옵션을 전달하거나,',\n SetEnvVars:\n '`SOFTWARE_PUBLISHABLE_KEY` / `SOFTWARE_SECRET_KEY` 환경 변수를 설정하세요.',\n InvalidApiKeyFormat:\n 'API 키 형식이 올바르지 않습니다. `sk01_` 또는 `pat01_` 토큰이 필요합니다.',\n RetiredHexCredentialsRejected:\n '이전 hex 자격 증명은 더 이상 허용되지 않습니다 — `01 login`으로 다시 인증하세요.',\n InvalidJsonObject: '`--{{label}}` 인자는 JSON 객체여야 합니다.',\n InvalidJsonArray: '`--{{label}}` 인자는 JSON 배열이어야 합니다.',\n InvalidJsonValue: '`--{{label}}` 인자의 JSON 형식이 올바르지 않습니다.',\n Empty: '(없음)',\n Total: '총 {{n}}개',\n PageOf: '{{page}} / {{total}} 페이지',\n\n // AdminError code translations (mirrors apps/console admin.ts).\n tenant_mismatch: '권한이 없는 테넌트',\n account_suspended: '계정이 정지되었습니다',\n feature_disabled: '이 기능이 비활성화되었습니다',\n role_denied: '권한이 부족합니다',\n credential_invalid: '자격 증명이 유효하지 않습니다',\n pat_tenant_unpinned: 'PAT 토큰의 테넌트가 고정되지 않았습니다',\n publishable_key_mismatch: '공개 키가 일치하지 않습니다',\n scope_denied: '범위 권한이 없습니다',\n redis_unavailable: '캐시가 일시적으로 사용 불가합니다',\n provider_unavailable: '외부 공급자가 응답하지 않습니다',\n rate_limited: '요청이 너무 많습니다 — 잠시 후 다시 시도하세요',\n upstream_timeout: '응답 시간이 초과되었습니다',\n upstream_5xx: '외부 서비스 오류',\n dns_failure: '네트워크 연결 오류',\n not_found: '리소스를 찾을 수 없습니다',\n invalid_argument: '인자가 올바르지 않습니다',\n unknown: '알 수 없는 오류',\n} as const\n\nexport type CliI18nKey = keyof typeof CLI_I18N_KO\n\nexport const CLI_I18N_EN: Record<CliI18nKey, string> = {\n AuthenticationRequired: 'Authentication required',\n RunLoginToAuthenticate: 'Run `01 login` to authenticate via browser, or',\n PassApiKey: 'pass `--api-key <token>`, or',\n SetEnvVars:\n 'set `SOFTWARE_PUBLISHABLE_KEY` and `SOFTWARE_SECRET_KEY` environment variables.',\n InvalidApiKeyFormat:\n 'Invalid API key format. Expected `sk01_` or `pat01_` token.',\n RetiredHexCredentialsRejected:\n 'Retired hex credentials are no longer accepted — run `01 login` to re-authenticate.',\n InvalidJsonObject: '--{{label}} must be a JSON object.',\n InvalidJsonArray: '--{{label}} must be a JSON array.',\n InvalidJsonValue: 'Invalid JSON for --{{label}}.',\n Empty: '(empty)',\n Total: '{{n}} total',\n PageOf: 'page {{page}}/{{total}}',\n\n tenant_mismatch: 'Tenant access denied',\n account_suspended: 'Your account has been suspended',\n feature_disabled: 'This feature is disabled',\n role_denied: 'Insufficient role permissions',\n credential_invalid: 'Invalid credentials',\n pat_tenant_unpinned: 'PAT token tenant is not pinned',\n publishable_key_mismatch: 'Publishable key mismatch',\n scope_denied: 'Scope permission denied',\n redis_unavailable: 'Cache temporarily unavailable',\n provider_unavailable: 'Upstream provider unavailable',\n rate_limited: 'Too many requests — please try again shortly',\n upstream_timeout: 'Upstream request timed out',\n upstream_5xx: 'Upstream service error',\n dns_failure: 'Network connection error',\n not_found: 'Resource not found',\n invalid_argument: 'Invalid argument',\n unknown: 'Unknown error',\n}\n\nexport type Locale = 'ko' | 'en'\n\nlet activeLocale: Locale | null = null\n\nexport function detectLocale(): Locale {\n if (activeLocale) return activeLocale\n const raw =\n process.env.LC_ALL ?? process.env.LANG ?? process.env.LANGUAGE ?? ''\n return raw.toLowerCase().startsWith('ko') ? 'ko' : 'en'\n}\n\nexport function setLocale(locale: Locale | null | undefined): void {\n activeLocale = locale ?? null\n}\n\nexport function t(\n key: CliI18nKey,\n vars?: Record<string, string | number>,\n): string {\n const table = detectLocale() === 'ko' ? CLI_I18N_KO : CLI_I18N_EN\n let s: string = table[key]\n if (vars) {\n for (const [k, v] of Object.entries(vars)) {\n // Use a global regex (escape user-supplied key) instead of\n // String.prototype.replaceAll so we keep working on tsconfig\n // targets older than ES2021. Keys are statically declared above so\n // metacharacter escaping is defense-in-depth.\n const escaped = k.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n s = s.replace(new RegExp(`\\\\{\\\\{${escaped}\\\\}\\\\}`, 'g'), String(v))\n }\n }\n return s\n}\n","import { readFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { Command } from 'commander'\nimport type { ApiQueryOptions } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { parseSelect, validateCollection } from '../lib/collections.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson } from '../lib/parse.js'\n\nfunction readFileAsBlob(filePath: string): { blob: Blob; filename: string } {\n const buffer = readFileSync(filePath)\n return { blob: new Blob([buffer]), filename: basename(filePath) }\n}\n\nexport function registerCrudCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n program\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions (JSON)')\n .option('--limit <n>', 'Max results', (v: string) => parseInt(v, 10))\n .option('--page <n>', 'Page number', (v: string) => parseInt(v, 10))\n .option('--sort <field>', 'Sort field (prefix with - for descending)')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.where) options.where = parseJson(opts.where, 'where')\n if (opts.limit) options.limit = opts.limit\n if (opts.page) options.page = opts.page\n if (opts.sort) options.sort = opts.sort\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections.from(col).find(options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('get <collection> <id>')\n .description('Get a document by ID')\n .option(\n '--depth <n>',\n 'Relationship depth (0 = no population)',\n (v: string) => parseInt(v, 10),\n )\n .option('--select <fields>', 'Comma-separated fields to select')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const options: Record<string, unknown> = {}\n if (opts.depth != null) options.depth = opts.depth\n if (opts.select) options.select = parseSelect(opts.select)\n const result = await client.collections.from(col).findById(id, options)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('create <collection>')\n .description('Create a new document')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'create',\n collection: col,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections.from(col).create(data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update <collection> <id>')\n .description('Update a document by ID')\n .requiredOption('--data <json>', 'Document data (JSON)')\n .option('--file <path>', 'File to upload (for upload collections)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update',\n collection: col,\n id,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n let fileOpts: { file: Blob; filename: string } | undefined\n if (opts.file) {\n const { blob, filename } = readFileAsBlob(opts.file)\n fileOpts = { file: blob, filename }\n }\n const result = await client.collections\n .from(col)\n .update(id, data, fileOpts)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete <collection> <id>')\n .description('Delete a document by ID')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, id: string, opts) => {\n try {\n const col = validateCollection(collection)\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete',\n collection: col,\n id,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections.from(col).remove(id)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('update-many <collection>')\n .description('Update multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .requiredOption('--data <json>', 'Update data (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n const data = parseJson(opts.data, 'data')\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'update-many',\n collection: col,\n where,\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections\n .from(col)\n .updateMany(where, data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n program\n .command('delete-many <collection>')\n .description('Delete multiple documents matching a filter')\n .requiredOption('--where <json>', 'Filter conditions (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (collection: string, opts) => {\n try {\n const col = validateCollection(collection)\n const where = parseJson(opts.where, 'where') as ApiQueryOptions['where']\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'delete-many',\n collection: col,\n where,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.collections.from(col).removeMany(where)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { SERVER_COLLECTIONS } from '@01.software/sdk'\n\nexport type CliCollection = (typeof SERVER_COLLECTIONS)[number]\n\nexport function validateCollection(name: string): CliCollection {\n if ((SERVER_COLLECTIONS as readonly string[]).includes(name)) {\n return name as CliCollection\n }\n\n const normalized = name.replace(/-/g, '').toLowerCase()\n const suggestions = (SERVER_COLLECTIONS as readonly string[])\n .filter((collection) => {\n const candidate = collection.replace(/-/g, '').toLowerCase()\n return (\n candidate.startsWith(normalized) ||\n normalized.startsWith(candidate) ||\n (normalized.length >= 3 && candidate.includes(normalized))\n )\n })\n .slice(0, 5)\n\n const hint =\n suggestions.length > 0\n ? `Did you mean: ${suggestions.join(', ')}?`\n : 'Run \"01 --help\" for available collections.'\n\n throw new Error(`Unknown collection \"${name}\". ${hint}`)\n}\n\nexport function parseSelect(input: string): Record<string, boolean> {\n return Object.fromEntries(\n input\n .split(',')\n .map((field) => field.trim())\n .map((field) => [field, true]),\n )\n}\n","import { exitWithError } from './output.js'\nimport { t } from './i18n.js'\nimport type { z } from 'zod'\n\n/**\n * Throw an AdminError-shaped object so `exitWithError` can render it correctly\n * under `--format json` and exit with code 3 (validation). The `code` literal\n * `invalid_argument` is already in the validation bucket per `admin-error.ts`.\n */\nfunction failArg(\n label: string,\n _value: string,\n expectedKind: 'object' | 'array' | 'value',\n): never {\n const message =\n expectedKind === 'object'\n ? t('InvalidJsonObject', { label })\n : expectedKind === 'array'\n ? t('InvalidJsonArray', { label })\n : t('InvalidJsonValue', { label })\n exitWithError({\n type: 'validation',\n code: 'invalid_argument',\n field: label,\n // Keep rejected values out of terminal and structured output. `message`\n // is the stderr headline; `detail` carries only the stable field label for\n // machine consumers.\n message,\n detail: { message, field: label },\n })\n}\n\nexport function parseWithSchema<T>(\n value: unknown,\n label: string,\n schema: z.ZodType<T>,\n): T {\n const parsed = schema.safeParse(value)\n if (parsed.success) return parsed.data\n\n // Zod paths and messages may contain payload-controlled record keys or\n // unknown property names. Commerce inputs include capabilities and provider\n // credentials, so expose only Zod's stable issue category.\n const issues = parsed.error.issues.map((issue) => ({ code: issue.code }))\n const message = `Invalid value for --${label}.`\n\n exitWithError({\n type: 'validation',\n code: 'invalid_argument',\n field: label,\n message,\n detail: {\n message,\n field: label,\n issues,\n },\n })\n}\n\nexport function parseJson(\n value: string,\n label: string,\n options: { format?: string } = {},\n): Record<string, unknown> {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return failArg(label, value, 'object')\n }\n void options\n return parsed as Record<string, unknown>\n}\n\nexport function parseJsonArray(\n value: string,\n label: string,\n options: { format?: string } = {},\n): unknown[] {\n let parsed: unknown\n try {\n parsed = JSON.parse(value)\n } catch {\n return failArg(label, value, 'value')\n }\n if (!Array.isArray(parsed)) {\n return failArg(label, value, 'array')\n }\n void options\n return parsed\n}\n","import { z } from 'zod'\n\nexport * from './features'\n\nexport const tenantFieldConfigStateSchema = z\n .object({\n hiddenFields: z.array(z.string()),\n isHidden: z.boolean(),\n })\n .strict()\n\nexport const tenantContextQuerySchema = z\n .object({\n counts: z.literal('true').optional(),\n })\n .strict()\n\nexport const tenantContextToolInputSchema = z\n .object({\n includeCounts: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n 'Include per-collection document counts and config status (bypasses cache, slower)',\n ),\n })\n .strict()\n\nexport const tenantContextResponseSchema = z\n .object({\n tenant: z\n .object({\n id: z.string(),\n name: z.string(),\n plan: z.string(),\n planSource: z.string().optional(),\n authoritative: z.boolean().optional(),\n capabilityVersion: z.string().optional(),\n })\n .strict(),\n features: z.array(z.string()),\n collections: z\n .object({\n active: z.array(z.string()),\n inactive: z.array(z.string()),\n })\n .strict(),\n fieldConfigs: z.record(z.string(), tenantFieldConfigStateSchema),\n counts: z.record(z.string(), z.number()).optional(),\n config: z\n .object({\n webhookConfigured: z.boolean(),\n })\n .strict()\n .optional(),\n })\n .strict()\n\nexport const tenantFeatureProgressFeatureSchema = z.enum(['ecommerce'])\n\nexport const tenantFeatureProgressInputSchema = z\n .object({\n feature: tenantFeatureProgressFeatureSchema.describe(\n 'Feature to inspect for tenant implementation readiness',\n ),\n includeEvidence: z\n .boolean()\n .optional()\n .default(false)\n .describe('Include sanitized counts and static surface evidence'),\n })\n .strict()\n\nexport const tenantFeatureProgressStatusSchema = z.enum([\n 'ready',\n 'attention',\n 'blocked',\n])\n\nexport const tenantFeatureProgressItemStateSchema = z.enum([\n 'complete',\n 'incomplete',\n 'blocked',\n 'attention',\n 'optional',\n 'unknown',\n 'manual',\n 'not-applicable',\n])\n\nexport const tenantFeatureProgressSeveritySchema = z.enum([\n 'required',\n 'recommended',\n 'optional',\n])\n\nexport const tenantFeatureProgressEvidenceValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n])\n\nexport const tenantFeatureProgressItemSchema = z\n .object({\n id: z.string(),\n title: z.string(),\n state: tenantFeatureProgressItemStateSchema,\n severity: tenantFeatureProgressSeveritySchema,\n summary: z.string(),\n evidence: z\n .record(z.string(), tenantFeatureProgressEvidenceValueSchema)\n .optional(),\n })\n .strict()\n\nexport const tenantFeatureProgressGroupSchema = z\n .object({\n id: z.string(),\n title: z.string(),\n summary: z.string().optional(),\n items: z.array(tenantFeatureProgressItemSchema),\n })\n .strict()\n\nexport const tenantFeatureProgressResponseSchema = z\n .object({\n schemaVersion: z.literal(1),\n feature: tenantFeatureProgressFeatureSchema,\n status: tenantFeatureProgressStatusSchema,\n generatedAt: z.string(),\n tenant: z\n .object({\n id: z.string(),\n name: z.string(),\n plan: z.string(),\n })\n .strict(),\n capability: z\n .object({\n effectiveFeatures: z.array(z.string()),\n planBlocked: z.array(z.string()),\n closureAdded: z.array(z.string()),\n })\n .strict(),\n config: z\n .object({\n fulfillmentMode: z.enum(['shipping', 'none']),\n })\n .strict(),\n summary: z\n .object({\n complete: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n blocking: z.number().int().nonnegative(),\n manual: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n })\n .strict(),\n groups: z.array(tenantFeatureProgressGroupSchema),\n })\n .strict()\n\nexport const COLLECTION_SCHEMA_CONTRACT_VERSION = 1\n\nexport const collectionSchemaEndpointParamsSchema = z\n .object({\n collectionSlug: z.string().min(1, 'collectionSlug is required'),\n })\n .strict()\n\nexport function createCollectionSchemaToolInputSchema<\n const T extends readonly [string, ...string[]],\n>(collections: T) {\n return z\n .object({\n collection: z.enum(collections).describe('Collection name (required)'),\n })\n .strict()\n}\n\nexport const collectionFieldOptionSchema = z\n .object({\n label: z.string(),\n value: z.string(),\n })\n .strict()\n\nexport interface CollectionFieldSchema {\n name: string\n path: string\n type: string\n required?: true\n unique?: true\n hasMany?: true\n relationTo?: string | string[]\n options?: Array<{ label: string; value: string }>\n hidden?: true\n systemManaged?: true\n writable?: boolean\n fields?: CollectionFieldSchema[]\n}\n\nexport const collectionFieldSchema: z.ZodType<CollectionFieldSchema> = z.lazy(\n () =>\n z\n .object({\n name: z.string(),\n path: z.string(),\n type: z.string(),\n required: z.literal(true).optional(),\n unique: z.literal(true).optional(),\n hasMany: z.literal(true).optional(),\n relationTo: z.union([z.string(), z.array(z.string())]).optional(),\n options: z.array(collectionFieldOptionSchema).optional(),\n hidden: z.literal(true).optional(),\n systemManaged: z.literal(true).optional(),\n writable: z.boolean().optional(),\n fields: z.array(collectionFieldSchema).optional(),\n })\n .strict(),\n)\n\nexport const collectionSchemaResponseSchema = z\n .object({\n contractVersion: z.literal(COLLECTION_SCHEMA_CONTRACT_VERSION),\n mode: z.literal('effective'),\n collection: z\n .object({\n slug: z.string(),\n timestamps: z.boolean(),\n alwaysActive: z.boolean(),\n feature: z.string().nullable(),\n systemFields: z.array(z.string()),\n visibility: z\n .object({\n collectionHidden: z.boolean(),\n hiddenFields: z.array(z.string()),\n })\n .strict(),\n fields: z.array(collectionFieldSchema),\n })\n .strict(),\n })\n .strict()\n\nexport type TenantFieldConfigState = z.infer<\n typeof tenantFieldConfigStateSchema\n>\nexport type TenantContextQuery = z.input<typeof tenantContextQuerySchema>\nexport type TenantContextToolInput = z.infer<\n typeof tenantContextToolInputSchema\n>\nexport type TenantContextResponse = z.infer<typeof tenantContextResponseSchema>\nexport type TenantFeatureProgressFeature = z.infer<\n typeof tenantFeatureProgressFeatureSchema\n>\nexport type TenantFeatureProgressInput = z.infer<\n typeof tenantFeatureProgressInputSchema\n>\n/**\n * Raw feature-progress request input before schema defaults are applied.\n * `TenantFeatureProgressInput` is the parsed/effective shape.\n */\nexport type TenantFeatureProgressRequestInput = z.input<\n typeof tenantFeatureProgressInputSchema\n>\nexport type TenantFeatureProgressStatus = z.infer<\n typeof tenantFeatureProgressStatusSchema\n>\nexport type TenantFeatureProgressItemState = z.infer<\n typeof tenantFeatureProgressItemStateSchema\n>\nexport type TenantFeatureProgressSeverity = z.infer<\n typeof tenantFeatureProgressSeveritySchema\n>\nexport type TenantFeatureProgressEvidenceValue = z.infer<\n typeof tenantFeatureProgressEvidenceValueSchema\n>\nexport type TenantFeatureProgressItem = z.infer<\n typeof tenantFeatureProgressItemSchema\n>\nexport type TenantFeatureProgressGroup = z.infer<\n typeof tenantFeatureProgressGroupSchema\n>\nexport type TenantFeatureProgressResponse = z.infer<\n typeof tenantFeatureProgressResponseSchema\n>\nexport type CollectionSchemaEndpointParams = z.infer<\n typeof collectionSchemaEndpointParamsSchema\n>\nexport type CollectionFieldOption = z.infer<typeof collectionFieldOptionSchema>\nexport type CollectionSchemaResponse = z.infer<\n typeof collectionSchemaResponseSchema\n>\n","import { z } from 'zod'\n\nexport * from './product-detail'\nexport * from './product-patch'\nexport * from './product-catalog'\nexport * from './product-upsert'\nexport * from './product-options'\nexport * from './product-media'\nexport * from './product-selection-media'\nexport * from './product-gallery'\nexport * from './stock-snapshot'\nexport * from './cart'\nexport * from './cart-merge'\nexport * from './cart-mine'\nexport {\n CanonicalCheckoutQueryResultSchema,\n CanonicalCheckoutQuerySchema,\n CanonicalPublicCheckoutItemSchema,\n CheckoutQueryResultSchema,\n CheckoutQuerySchema,\n CreateCheckoutBodySchema,\n CreateCheckoutParamsSchema,\n CreateCheckoutResultSchema,\n CreateServerCheckoutBodySchema,\n CreateServerCheckoutParamsSchema,\n CreateServerCheckoutResultSchema,\n PublicCheckoutSchema,\n RetrieveCheckoutParamsSchema,\n RetrieveServerCheckoutParamsSchema,\n ServerCheckoutSchema,\n canonicalCheckoutQueryResultSchema,\n canonicalCheckoutQuerySchema,\n canonicalPublicCheckoutItemSchema,\n checkoutAmountsSchema,\n checkoutListItemSchema,\n checkoutPaymentSessionRefSchema,\n createCheckoutBodySchema,\n createCheckoutParamsSchema,\n createCheckoutResultSchema,\n createServerCheckoutBodySchema,\n createServerCheckoutParamsSchema,\n createServerCheckoutResultSchema,\n openCheckoutPaymentStateSchema,\n publicCheckoutSchema,\n retrieveCheckoutParamsSchema,\n retrieveServerCheckoutParamsSchema,\n serverCheckoutSchema,\n spentCheckoutPaymentStateSchema,\n type CanonicalPublicCheckoutItem,\n type CheckoutAmounts,\n type CheckoutListItem,\n type CheckoutPaymentSessionRef,\n type CheckoutQueryParams,\n type CheckoutQueryResult,\n type CreateCheckoutParams,\n type CreateCheckoutResult,\n type CreateServerCheckoutParams,\n type CreateServerCheckoutResult,\n type OpenCheckoutPaymentState,\n type PublicCheckout,\n type RetrieveCheckoutParams,\n type RetrieveServerCheckoutParams,\n type ServerCheckout,\n type SpentCheckoutPaymentState,\n} from './checkout'\nexport * from './shipping-calculate'\nexport * from './fulfillment'\nexport * from './market-capability'\nexport * from './market'\nexport * from './commerce-common'\nexport * from './commerce-errors'\nexport * from './discount-errors'\nexport * from './canonical-fingerprint'\nexport * from './payment-session'\nexport {\n confirmationStatusSchema,\n financialStatusSchema,\n fulfillmentOrderStatusSchema,\n orderFulfillmentStatusSchema,\n orderPrimaryDisplayStatusSchema,\n orderReturnStatusSchema,\n shipmentStatusSchema,\n type ConfirmationStatusValue,\n type FinancialStatusValue,\n type FulfillmentOrderStatusValue,\n type OrderFulfillmentStatusValue,\n type OrderPrimaryDisplayStatusValue,\n type OrderReturnStatusValue,\n type ShipmentStatusValue,\n} from './order-status'\nexport * from './order'\n\nexport const transactionStatusSchema = z.enum([\n 'pending',\n 'paid',\n 'success',\n 'failed',\n 'error',\n 'canceled',\n 'refunded',\n])\n\nexport const transactionKindSchema = z.enum([\n 'authorization',\n 'sale',\n 'capture',\n 'void',\n 'refund',\n])\n\n/**\n * Machine-readable return reason codes. Console label maps and the SDK\n * `ReturnReason` union derive from this single source (parity-tested), mirroring\n * the product-upsert reason-code precedent.\n *\n * The trailing codes mirror Shopify `ReturnReason` granularity (size/color/style,\n * not-as-described, wrong-item, unknown) that fashion tenants need for\n * category-level returns reporting (#1857). The original five codes are retained\n * for legacy readability; `change_of_mind`/`wrong_delivery` predate and coexist\n * with the Shopify-aligned `unknown`/`wrong_item`.\n */\nexport const RETURN_REASON_CODES = [\n 'change_of_mind',\n 'defective',\n 'wrong_delivery',\n 'damaged',\n 'size_too_large',\n 'size_too_small',\n 'color',\n 'style',\n 'not_as_described',\n 'wrong_item',\n 'unknown',\n 'other',\n] as const\n\nexport const returnReasonSchema = z.enum(RETURN_REASON_CODES)\n\n/**\n * Machine-readable return *rejection* reason codes. Distinct from the\n * customer-supplied return reasons above: these are operator-selected reasons\n * for denying a return (mirroring the cancel-reason-code precedent). The Console\n * label map and the persisted `returns.rejectionReasonCode` field derive from\n * this single source (parity-tested).\n */\nexport const RETURN_REJECTION_REASON_CODES = [\n 'window_expired',\n 'used_or_damaged',\n 'non_returnable',\n 'other',\n] as const\n\nexport const returnRejectionReasonCodeSchema = z.enum(\n RETURN_REJECTION_REASON_CODES,\n)\n\n/** Operator-selected reasons for canceling a return after approval. */\nexport const RETURN_CANCELLATION_REASON_CODES = [\n 'items_not_received',\n 'customer_withdrew',\n 'merchant_decision',\n 'other',\n] as const\n\nexport const returnCancellationReasonCodeSchema = z.enum(\n RETURN_CANCELLATION_REASON_CODES,\n)\n\nexport const restockActionSchema = z.enum(['return_to_stock', 'discard'])\n\nexport const returnWithRefundItemSchema = z\n .object({\n orderItem: z.union([z.string().min(1), z.number()]).transform(String),\n quantity: z.number().int().positive('quantity must be a positive integer'),\n restockAction: restockActionSchema.default('return_to_stock'),\n restockingFee: z\n .number()\n .min(0, 'restockingFee must be non-negative')\n .optional()\n .describe('Restocking fee charged for this line (ADR 0005 §Gap 1)'),\n })\n .strict()\n\nexport const returnWithRefundSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number (required)'),\n reason: returnReasonSchema.optional().describe('Return reason (optional)'),\n reasonDetail: z\n .string()\n .optional()\n .describe('Detailed reason text (optional)'),\n returnItems: z\n .array(returnWithRefundItemSchema)\n .min(1, 'At least one return item is required')\n .max(100, 'Too many return items')\n .describe('Array of products to return (required)'),\n refundAmount: z\n .number()\n .min(0, 'refundAmount must be non-negative')\n .describe('Refund amount (required, min 0)'),\n returnShippingFee: z\n .number()\n .min(0, 'returnShippingFee must be non-negative')\n .optional()\n .describe(\n 'Return shipping fee charged to the customer (ADR 0005 §Gap 1)',\n ),\n initialShippingRefundAmount: z\n .number()\n .min(0, 'initialShippingRefundAmount must be non-negative')\n .optional()\n .describe('Initial order shipping amount refunded to the customer'),\n initialShippingRefundOverrideNote: z\n .string()\n .min(1)\n .optional()\n .describe(\n 'Operator audit note required when overriding policy suggestion',\n ),\n pgPaymentId: z\n .string()\n .min(1, 'pgPaymentId is required')\n .describe('PG payment ID for refund (required)'),\n paymentKey: z\n .string()\n .min(1)\n .optional()\n .describe('Provider payment key for verified refund'),\n refundReceiptUrl: z\n .string()\n .optional()\n .describe('Refund receipt URL (optional)'),\n })\n .strict()\n\nexport const createReturnSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number (required)'),\n reason: returnReasonSchema.optional().describe('Return reason (optional)'),\n reasonDetail: z\n .string()\n .optional()\n .describe('Detailed reason text (optional)'),\n returnItems: z\n .array(returnWithRefundItemSchema)\n .min(1, 'At least one return item is required')\n .max(100, 'Too many return items')\n .describe('Array of products to return (required)'),\n refundAmount: z\n .number()\n .min(0, 'refundAmount must be non-negative')\n .describe(\n 'Line refund amount before initial shipping refund (required, min 0)',\n ),\n returnShippingFee: z\n .number()\n .min(0, 'returnShippingFee must be non-negative')\n .optional()\n .describe('Return shipping fee charged to the customer'),\n initialShippingRefundAmount: z\n .number()\n .min(0, 'initialShippingRefundAmount must be non-negative')\n .optional()\n .describe('Initial order shipping amount refunded to the customer'),\n initialShippingRefundOverrideNote: z\n .string()\n .min(1)\n .optional()\n .describe(\n 'Operator audit note required when overriding policy suggestion',\n ),\n })\n .strict()\n\nexport const CreateReturnSchema = createReturnSchema\nexport const ReturnWithRefundSchema = returnWithRefundSchema\n\nexport const updateReturnSchema = z\n .object({\n returnId: z.union([z.string(), z.number()]).transform(String),\n // Only non-financial transitions are accepted here. `completed` is included\n // so the server can return the canonical `server_derived` error instead of\n // a generic validation failure.\n status: z.enum([\n 'processing',\n 'approved',\n 'rejected',\n 'canceled',\n 'completed',\n ]),\n reasonCode: returnRejectionReasonCodeSchema.optional(),\n cancellationReasonCode: returnCancellationReasonCodeSchema.optional(),\n cancellationReasonDetail: z.string().trim().min(1).max(2000).optional(),\n })\n .strict()\n\nexport const UpdateReturnSchema = updateReturnSchema\n\n/**\n * Machine-readable order cancellation reason codes. Console label maps and the\n * SDK `CancelReasonCode` union derive from this single source (parity-tested).\n */\nexport const CANCEL_REASON_CODES = [\n 'customer',\n 'inventory',\n 'fraud',\n 'declined',\n 'staff',\n 'other',\n] as const\n\nexport const cancelReasonCodeSchema = z.enum(CANCEL_REASON_CODES)\n\n/**\n * Machine-readable operator force-resolution reason codes (operational return /\n * fulfillment-mistake corrections). Single source for Console's\n * `forceResolveOrderMistake` reason union.\n */\nexport const FORCE_RESOLUTION_REASON_CODES = [\n 'staff_error',\n 'wrong_fulfillment',\n 'other',\n] as const\n\nexport const forceResolutionReasonCodeSchema = z.enum(\n FORCE_RESOLUTION_REASON_CODES,\n)\n\nexport const idempotencyKeySchema = z\n .string()\n .trim()\n .min(1, 'idempotencyKey is required')\n .max(255, 'idempotencyKey must be 255 characters or fewer')\n .regex(\n /^[\\x21-\\x7E]+$/,\n 'idempotencyKey must contain only printable header-safe characters',\n )\n\nexport const cancelOrderSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number to cancel'),\n reasonCode: cancelReasonCodeSchema\n .default('other')\n .describe('Operator-selected cancel reason code'),\n reasonDetail: z\n .string()\n .trim()\n .max(2000, 'reasonDetail must be 2000 characters or fewer')\n .optional()\n .describe('Internal cancellation detail stored on the order'),\n })\n .strict()\n\nexport const CancelOrderSchema = cancelOrderSchema\n\nconst cancelOrderResponseBaseSchema = {\n orderId: z.string().min(1),\n} satisfies z.ZodRawShape\n\nconst unpaidLocalCancelCommittedResponseFields = {\n refundedAmount: z.literal(0),\n providerRefunded: z.literal(false),\n} satisfies z.ZodRawShape\n\nconst paidLocalCancelCommittedResponseFields = {\n transactionId: z.string().min(1),\n refundedAmount: z.literal(0),\n providerRefunded: z.literal(false),\n refundPending: z.literal(true),\n} satisfies z.ZodRawShape\n\nconst alreadyCanceledResponseFields = {\n refundedAmount: z.number().int().nonnegative(),\n providerRefunded: z.literal(false),\n} satisfies z.ZodRawShape\n\nconst alreadyCanceledRefundPendingResponseFields = {\n transactionId: z.string().min(1),\n refundedAmount: z.number().int().nonnegative(),\n providerRefunded: z.literal(false),\n refundPending: z.literal(true),\n} satisfies z.ZodRawShape\n\nexport const cancelOrderResponseSchema = z.union([\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...paidLocalCancelCommittedResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(true),\n })\n .strict(),\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...unpaidLocalCancelCommittedResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(true),\n })\n .strict(),\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...alreadyCanceledResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(false),\n alreadyCanceled: z.literal(true),\n })\n .strict(),\n z\n .object({\n ...cancelOrderResponseBaseSchema,\n ...alreadyCanceledRefundPendingResponseFields,\n status: z.literal('canceled'),\n cancelCommitted: z.literal(false),\n alreadyCanceled: z.literal(true),\n })\n .strict(),\n])\n\nexport const CancelOrderResponseSchema = cancelOrderResponseSchema\n\nexport const resolveCancelRefundOutcomeSchema = z.enum(['succeeded', 'failed'])\n\nexport const resolveCancelRefundSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number whose pending cancel refund is being resolved'),\n idempotencyKey: idempotencyKeySchema.describe(\n 'Stable key for this PG refund result report',\n ),\n outcome: resolveCancelRefundOutcomeSchema.describe(\n 'PG refund result reported by the storefront or BFF',\n ),\n refundedAmount: z\n .number()\n .int('refundedAmount must be an integer minor-unit amount')\n .nonnegative('refundedAmount must be nonnegative'),\n pgProvider: z\n .string()\n .trim()\n .min(1, 'pgProvider is required')\n .regex(\n /^[a-z0-9][a-z0-9_-]*$/,\n 'pgProvider must be a lowercase provider slug',\n ),\n pgRefundId: z.string().trim().min(1).optional(),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (value.outcome === 'succeeded' && value.refundedAmount <= 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['refundedAmount'],\n message: 'refundedAmount must be positive when outcome is succeeded',\n })\n }\n\n if (value.outcome === 'succeeded' && !value.pgRefundId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['pgRefundId'],\n message: 'pgRefundId is required when outcome is succeeded',\n })\n }\n\n if (value.outcome === 'failed' && value.refundedAmount !== 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['refundedAmount'],\n message: 'refundedAmount must be 0 when outcome is failed',\n })\n }\n })\n\nexport const ResolveCancelRefundSchema = resolveCancelRefundSchema\n\nexport const resolveCancelRefundResponseSchema = z.union([\n z\n .object({\n orderId: z.string().min(1),\n transactionId: z.string().min(1),\n refundTransactionId: z.string().min(1),\n refundedAmount: z.number().int().positive(),\n refundStatus: z.literal('succeeded'),\n transactionStatus: z.enum(['paid', 'refunded']),\n })\n .strict(),\n z\n .object({\n orderId: z.string().min(1),\n transactionId: z.string().min(1),\n refundTransactionId: z.string().min(1),\n refundedAmount: z.literal(0),\n refundStatus: z.literal('failed'),\n transactionStatus: z.literal('paid'),\n })\n .strict(),\n])\n\nexport const ResolveCancelRefundResponseSchema =\n resolveCancelRefundResponseSchema\n\nexport type TransactionStatus = z.infer<typeof transactionStatusSchema>\nexport type TransactionKind = z.infer<typeof transactionKindSchema>\nexport type ReturnReason = z.infer<typeof returnReasonSchema>\nexport type ReturnRejectionReasonCode = z.infer<\n typeof returnRejectionReasonCodeSchema\n>\nexport type ReturnCancellationReasonCode = z.infer<\n typeof returnCancellationReasonCodeSchema\n>\nexport type RestockAction = z.infer<typeof restockActionSchema>\nexport type ReturnWithRefundItem = z.input<typeof returnWithRefundItemSchema>\nexport type ParsedReturnWithRefundItem = z.output<\n typeof returnWithRefundItemSchema\n>\nexport type ReturnWithRefundParams = z.input<typeof ReturnWithRefundSchema>\nexport type ParsedReturnWithRefundParams = z.output<\n typeof ReturnWithRefundSchema\n>\nexport type CreateReturnParams = z.input<typeof CreateReturnSchema>\nexport type ParsedCreateReturnParams = z.output<typeof CreateReturnSchema>\nexport type UpdateReturnParams = z.input<typeof UpdateReturnSchema>\nexport type ParsedUpdateReturnParams = z.output<typeof UpdateReturnSchema>\nexport type CancelReasonCode = z.infer<typeof cancelReasonCodeSchema>\nexport type ForceResolutionReasonCode = z.infer<\n typeof forceResolutionReasonCodeSchema\n>\nexport type IdempotencyKey = z.infer<typeof idempotencyKeySchema>\nexport type CancelOrderParams = z.input<typeof CancelOrderSchema>\nexport type ParsedCancelOrderParams = z.output<typeof CancelOrderSchema>\nexport type CancelOrderRequestParams = {\n orderNumber: string\n reasonCode?: CancelReasonCode\n reasonDetail?: string\n idempotencyKey?: IdempotencyKey\n}\nexport type CancelOrderResponse = z.output<typeof CancelOrderResponseSchema>\nexport type ResolveCancelRefundOutcome = z.infer<\n typeof resolveCancelRefundOutcomeSchema\n>\nexport type ResolveCancelRefundParams = z.input<\n typeof ResolveCancelRefundSchema\n>\nexport type ParsedResolveCancelRefundParams = z.output<\n typeof ResolveCancelRefundSchema\n>\nexport type ResolveCancelRefundSucceededRequestParams = Omit<\n ResolveCancelRefundParams,\n 'outcome' | 'refundedAmount' | 'pgRefundId'\n> & {\n outcome: 'succeeded'\n refundedAmount: number\n pgRefundId: string\n}\nexport type ResolveCancelRefundFailedRequestParams = Omit<\n ResolveCancelRefundParams,\n 'outcome' | 'refundedAmount'\n> & {\n outcome: 'failed'\n refundedAmount: 0\n}\nexport type ResolveCancelRefundRequestParams =\n | ResolveCancelRefundSucceededRequestParams\n | ResolveCancelRefundFailedRequestParams\nexport type ResolveCancelRefundResponse = z.output<\n typeof ResolveCancelRefundResponseSchema\n>\n","import { z } from 'zod'\n\nconst IdSchema = z.union([z.string(), z.number()]).transform(String)\nconst RemovedLegacyMediaFieldSchema = z.unknown().optional()\n\nexport const PRODUCT_UPSERT_UNKNOWN_FIELD_REASON = 'unknown_field' as const\nexport const PRODUCT_UPSERT_READONLY_FIELD_REASON =\n 'product_field_readonly' as const\nexport const PRODUCT_GRAPH_CONFLICT_REASON = 'graph_conflict' as const\nexport const PRODUCT_GRAPH_REVISION_REQUIRED_REASON =\n 'graph_revision_required' as const\n\nexport const PRODUCT_READONLY_FIELDS = [\n 'isSoldOut',\n '_order',\n 'tenant',\n] as const\n\nconst productFieldShape = {\n id: IdSchema.optional(),\n title: z.string().min(1).optional(),\n subtitle: z.string().optional().nullable(),\n description: z.string().optional().nullable(),\n status: z.string().optional(),\n slug: z.string().optional(),\n images: z.array(IdSchema).optional(),\n mediaSets: RemovedLegacyMediaFieldSchema,\n vendor: z.string().optional().nullable(),\n productType: z.string().optional().nullable(),\n brand: IdSchema.optional().nullable(),\n shippingPolicy: IdSchema.optional().nullable(),\n weight: z.number().int().min(0).optional().nullable(),\n minOrderQuantity: z.number().int().min(1).optional().nullable(),\n maxOrderQuantity: z.number().int().min(1).optional().nullable(),\n isFeatured: z.boolean().optional(),\n publishedAt: z.string().optional().nullable(),\n categories: z.array(IdSchema).optional(),\n tags: z.array(IdSchema).optional(),\n markets: z.array(IdSchema).optional().nullable(),\n seo: z\n .object({\n title: z.string().optional().nullable(),\n description: z.string().optional().nullable(),\n })\n .optional()\n .nullable(),\n metadata: z.unknown().optional(),\n} as const\n\nexport const PRODUCT_UPSERT_PRODUCT_FIELDS = Object.keys(\n productFieldShape,\n) as (keyof typeof productFieldShape)[]\n\nexport const PRODUCT_UPSERT_EDIT_PRODUCT_FIELDS = ['id'] as const\n\nconst ProductFieldsSchema = z\n .object(productFieldShape)\n .passthrough()\n .superRefine((value, ctx) => {\n for (const field of ['primaryMediaItemId', 'thumbnail'] as const) {\n if (Object.prototype.hasOwnProperty.call(value, field)) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'Product media is ordered like Shopify. Use product.images and put the featured image first.',\n path: [field],\n })\n }\n }\n })\n\n/**\n * Base option-value object shape. Exported so strict consumers (e.g. the MCP\n * product-upsert tool) can reject unknown keys via `.strict()` without\n * duplicating the field list. The runtime `OptionValueInputSchema` keeps its\n * passthrough + legacy-`swatchColor` rejection semantics.\n */\nexport const OptionValueObjectSchema = z.object({\n id: IdSchema.optional(),\n value: z.string().min(1, 'Option value `value` is required'),\n slug: z.string().optional(),\n swatch: z\n .object({\n type: z.enum(['color', 'media']).optional().nullable(),\n color: z.string().optional().nullable(),\n mediaItemId: IdSchema.optional().nullable(),\n })\n .optional()\n .nullable(),\n thumbnail: RemovedLegacyMediaFieldSchema,\n images: RemovedLegacyMediaFieldSchema,\n metadata: z.unknown().optional(),\n})\n\nconst OptionValueInputSchema =\n OptionValueObjectSchema.passthrough().superRefine((value, ctx) => {\n if (Object.prototype.hasOwnProperty.call(value, 'swatchColor')) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'Option value field `swatchColor` was removed. Use nested `swatch.color` instead.',\n path: ['swatchColor'],\n })\n }\n })\n\nexport const OptionInputSchema = z.object({\n id: IdSchema.optional(),\n title: z.string().min(1, 'Option `title` is required'),\n slug: z.string().optional(),\n values: z\n .array(OptionValueInputSchema)\n .min(1, 'Each option must have at least one value'),\n})\n\nconst VariantOptionValueObjectSchema = z\n .object({\n valueSlug: z.string().optional(),\n valueId: IdSchema.optional(),\n value: z.string().optional(),\n })\n .refine((data) => Boolean(data.valueSlug ?? data.valueId ?? data.value), {\n message:\n 'Variant option value object requires valueSlug, valueId, or value',\n })\n\n/**\n * Coarse minor-unit bound for catalog amounts.\n *\n * The wire body carries no currency (the tenant `shopCurrency` and each market's\n * `currency` live server-side), so this can only enforce the widest bound any\n * supported currency permits — two decimal places. The exact per-currency check\n * (KRW admits none) runs in the Console variant write hook, which knows the\n * currency. This refine is the early, currency-agnostic rejection of values such\n * as `15000.005` that no supported currency could represent.\n *\n * Not a representation change: ADR 0040 keeps decimal/minor-unit money a v1\n * non-goal, and amounts stay plain `number` on the wire.\n */\nexport const MAX_CATALOG_AMOUNT_DECIMAL_PLACES = 2\n\nexport function catalogAmountDecimalPlaces(value: number): number {\n if (!Number.isFinite(value)) return 0\n const text = String(value)\n const exponential = text.indexOf('e-')\n if (exponential !== -1) return Number(text.slice(exponential + 2)) || 0\n const dot = text.indexOf('.')\n return dot === -1 ? 0 : text.length - dot - 1\n}\n\nconst CatalogAmountSchema = z\n .number()\n .min(0)\n .refine(\n (value) =>\n catalogAmountDecimalPlaces(value) <= MAX_CATALOG_AMOUNT_DECIMAL_PLACES,\n {\n message: `Amount must have at most ${MAX_CATALOG_AMOUNT_DECIMAL_PLACES} decimal places; the store currency may allow fewer.`,\n },\n )\n\nexport const VariantMarketPriceInputSchema = z.object({\n market: IdSchema,\n price: CatalogAmountSchema,\n compareAtPrice: CatalogAmountSchema.optional().nullable(),\n})\n\nexport const VariantInputSchema = z.object({\n id: IdSchema.optional(),\n optionValues: z\n .union([\n z.record(\n z.string(),\n z.union([z.string(), VariantOptionValueObjectSchema]),\n ),\n z.array(IdSchema),\n ])\n .optional(),\n sku: z.string().optional().nullable(),\n title: z.string().optional().nullable(),\n price: CatalogAmountSchema,\n compareAtPrice: CatalogAmountSchema.optional().nullable(),\n stock: z.number().int().min(0).optional(),\n isUnlimited: z.boolean().optional(),\n inventoryPolicy: z.enum(['deny', 'continue']).optional(),\n weight: z.number().int().min(0).optional().nullable(),\n requiresShipping: z.boolean().optional(),\n barcode: z.string().optional().nullable(),\n externalId: z.string().optional().nullable(),\n isActive: z.boolean().optional(),\n images: z.array(IdSchema).optional(),\n marketPrices: z.array(VariantMarketPriceInputSchema).optional(),\n thumbnail: RemovedLegacyMediaFieldSchema,\n featuredMediaItemId: RemovedLegacyMediaFieldSchema,\n metadata: z.unknown().optional(),\n})\n\n/** Base object schema for `.shape` consumers (MCP tool fields). */\nexport const ProductUpsertObjectSchema = z.object({\n /** Required on graph edit when the server graph is non-empty (`productId` set); optional for first seed on an empty graph. */\n graphRevision: z.string().optional(),\n productId: IdSchema.optional(),\n product: ProductFieldsSchema.optional(),\n options: z.array(OptionInputSchema).max(10).optional().default([]),\n variants: z.array(VariantInputSchema).max(500).optional().default([]),\n})\n\nexport const ProductUpsertSchema = ProductUpsertObjectSchema.superRefine(\n (data, ctx) => {\n const nestedProductId = data.product?.id\n if (\n data.productId != null &&\n nestedProductId != null &&\n String(data.productId) !== String(nestedProductId)\n ) {\n ctx.addIssue({\n code: 'custom',\n message:\n 'productId must match product.id when both are set on graph upsert.',\n path: ['productId'],\n })\n }\n\n const productId = data.productId ?? nestedProductId\n const isEdit = productId != null\n\n if (!isEdit && data.productId != null) {\n ctx.addIssue({\n code: 'custom',\n message: 'productId is not allowed when creating a product.',\n path: ['productId'],\n })\n }\n\n if (!isEdit && !data.product?.title) {\n ctx.addIssue({\n code: 'custom',\n message: 'Product `title` is required when creating a new product.',\n path: ['product', 'title'],\n })\n }\n\n if (isEdit && data.product) {\n for (const key of Object.keys(data.product)) {\n if (key !== 'id') {\n ctx.addIssue({\n code: 'custom',\n message:\n 'Existing product graph upsert accepts only product identity. Save document fields through Payload.',\n path: ['product', key],\n })\n }\n }\n }\n },\n)\n\n/** Create: `product.title` required; no `productId`. */\nexport type ProductUpsertCreateInput = {\n graphRevision?: string\n product: ProductFieldsInput & { title: string }\n options?: OptionInput[]\n variants?: VariantInput[]\n}\n\n/** Edit: graph-only; document fields via Payload / Admin save. */\nexport type ProductUpsertEditInput = {\n graphRevision?: string\n productId: string\n options?: OptionInput[]\n variants?: VariantInput[]\n}\n\n/** Edit (legacy carrier): `product: { id }` only — prefer `productId`. */\nexport type ProductUpsertEditNestedIdInput = {\n graphRevision?: string\n product: { id: string }\n options?: OptionInput[]\n variants?: VariantInput[]\n}\n\n/** Parsed upsert body (Zod defaults + refine). Prefer this at API boundaries. */\nexport type ProductUpsertInput = z.infer<typeof ProductUpsertSchema>\n\nexport type ProductFieldsInput = z.infer<typeof ProductFieldsSchema>\nexport type OptionInput = z.infer<typeof OptionInputSchema>\nexport type OptionValueInput = z.infer<typeof OptionValueInputSchema>\nexport type VariantInput = z.infer<typeof VariantInputSchema>\nexport type VariantMarketPriceInput = z.infer<\n typeof VariantMarketPriceInputSchema\n>\n","import { z } from 'zod'\nimport {\n commerceCapabilitySchema,\n commerceIdempotencyKeySchema,\n commerceResourceIdSchema,\n currencyCodeSchema,\n minorAmountSchema,\n publicAttributesSchema,\n} from './commerce-common'\n\nexport const MAX_CART_LINE_QUANTITY = 99\nexport const MAX_CART_DISCOUNT_CODES = 250\nexport const MAX_CART_DISCOUNT_CODE_LENGTH = 128\n\nexport const cartDiscountCodeSchema = z\n .object({\n code: z.string().min(1).max(MAX_CART_DISCOUNT_CODE_LENGTH),\n applicable: z.boolean(),\n })\n .strict()\n\nexport const CART_WARNING_CODES = [\n 'DISCOUNT_CODE_NOT_HONOURED',\n 'DISCOUNT_CURRENTLY_INACTIVE',\n 'DISCOUNT_CUSTOMER_NOT_ELIGIBLE',\n 'DISCOUNT_CUSTOMER_USAGE_LIMIT_REACHED',\n 'DISCOUNT_ELIGIBLE_CUSTOMER_MISSING',\n 'DISCOUNT_NO_ENTITLED_LINE_ITEMS',\n 'DISCOUNT_NO_ENTITLED_SHIPPING_LINES',\n 'DISCOUNT_NOT_FOUND',\n 'DISCOUNT_PURCHASE_NOT_IN_RANGE',\n 'DISCOUNT_USAGE_LIMIT_REACHED',\n 'MERCHANDISE_NOT_ENOUGH_STOCK',\n 'MERCHANDISE_OUT_OF_STOCK',\n] as const\n\nexport const cartWarningCodeSchema = z.enum(CART_WARNING_CODES)\n\nexport const cartWarningSchema = z\n .object({\n code: cartWarningCodeSchema,\n message: z.string().min(1),\n target: z.string().min(1),\n })\n .strict()\n\nexport const updateDiscountCodesBodySchema = z\n .object({\n cartToken: commerceCapabilitySchema,\n expectedRevision: z.number().int().nonnegative(),\n discountCodes: z\n .array(z.string().trim().min(1).max(MAX_CART_DISCOUNT_CODE_LENGTH))\n .max(\n MAX_CART_DISCOUNT_CODES,\n `discountCodes cannot contain more than ${MAX_CART_DISCOUNT_CODES} values`,\n ),\n })\n .strict()\nexport const updateDiscountCodesParamsSchema =\n updateDiscountCodesBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n })\nexport const updateDiscountCodesSchema = updateDiscountCodesParamsSchema\n\nexport type CartDiscountCode = z.infer<typeof cartDiscountCodeSchema>\nexport type CartWarningCode = (typeof CART_WARNING_CODES)[number]\nexport type CartWarning = z.infer<typeof cartWarningSchema>\nexport type UpdateDiscountCodesParams = z.infer<\n typeof updateDiscountCodesParamsSchema\n>\n\nexport const MAX_CART_LINE_ADMISSIONS = 32\n\nexport const publicMediaSizeSchema = z\n .object({\n width: z.number().nullable().optional(),\n height: z.number().nullable().optional(),\n mimeType: z.string().nullable().optional(),\n filename: z.string().nullable().optional(),\n url: z.string().nullable().optional(),\n })\n .strict()\n\nexport const publicMediaAssetSchema = z.union([\n z.string(),\n z\n .object({\n id: z.union([z.string(), z.number()]).nullable().optional(),\n alt: z.string().nullable().optional(),\n width: z.number().nullable().optional(),\n height: z.number().nullable().optional(),\n mimeType: z.string().nullable().optional(),\n filename: z.string().nullable().optional(),\n url: z.string().nullable().optional(),\n sizes: z.record(z.string(), publicMediaSizeSchema).optional(),\n })\n .strict(),\n])\n\nexport const publicCartReferenceSchema = z\n .object({\n id: z.string().min(1),\n title: z.string().min(1),\n handle: z.string().min(1).nullable(),\n image: publicMediaAssetSchema.nullable(),\n })\n .strict()\n\nexport const publicCartMarketSchema = z\n .object({\n id: z.string().min(1),\n handle: z.string().min(1),\n name: z.string().min(1),\n })\n .strict()\n\nexport const publicCartItemAdmissionSchema = z\n .object({\n eventId: z.string().min(1),\n occurrenceId: z.string().min(1),\n admissionTypeId: z.string().min(1),\n })\n .strict()\n\nexport const cartLineAdmissionsInputSchema = z\n .array(publicCartItemAdmissionSchema)\n // Bound the raw input before the handler canonical-sorts it. Duplicate\n // removal must not let an oversized request through.\n .max(\n MAX_CART_LINE_ADMISSIONS,\n `admissions cannot contain more than ${MAX_CART_LINE_ADMISSIONS} values`,\n )\n .min(1, 'admissions must contain at least one value')\n .superRefine((admissions, ctx) => {\n const seen = new Set<string>()\n admissions.forEach((admission, index) => {\n const key = `${admission.eventId}:${admission.occurrenceId}:${admission.admissionTypeId}`\n if (seen.has(key)) {\n ctx.addIssue({\n code: 'custom',\n path: [index],\n message: 'admissions must be unique',\n })\n }\n seen.add(key)\n })\n })\n\nconst cartTokenField = z.string().min(1, 'cartToken is required')\nconst cartMarketField = z.string().trim().min(1).optional()\nconst cartEntityIdField = z.union([z.string(), z.number()]).transform(String)\n\nexport const createCartSchema = z\n .object({\n market: cartMarketField,\n attributes: publicAttributesSchema.optional(),\n })\n .strict()\n\nexport const getCartSchema = z.object({ cartToken: cartTokenField }).strict()\n\nexport const addCartItemSchema = z\n .object({\n cartToken: cartTokenField,\n product: cartEntityIdField,\n variant: cartEntityIdField,\n option: cartEntityIdField.optional(),\n quantity: z.number().int().positive('quantity must be a positive integer'),\n market: cartMarketField,\n admissions: cartLineAdmissionsInputSchema.optional(),\n })\n .strict()\n\nexport const updateCartItemSchema = z\n .object({\n cartToken: cartTokenField,\n cartItemId: cartEntityIdField,\n quantity: z.number().int().positive('quantity must be a positive integer'),\n })\n .strict()\n\nexport const removeCartItemSchema = z\n .object({\n cartToken: cartTokenField,\n cartItemId: cartEntityIdField,\n })\n .strict()\n\nexport const updateCartAttributesSchema = z\n .object({\n cartToken: cartTokenField,\n attributes: publicAttributesSchema,\n })\n .strict()\n\nexport const clearCartSchema = z.object({ cartToken: cartTokenField }).strict()\n\nfunction compareAdmissions(\n left: z.infer<typeof publicCartItemAdmissionSchema>,\n right: z.infer<typeof publicCartItemAdmissionSchema>,\n) {\n for (const field of ['eventId', 'occurrenceId', 'admissionTypeId'] as const) {\n if (left[field] < right[field]) return -1\n if (left[field] > right[field]) return 1\n }\n return 0\n}\n\nexport const publicCartItemAdmissionsSchema = z\n .array(publicCartItemAdmissionSchema)\n .max(MAX_CART_LINE_ADMISSIONS)\n .superRefine((admissions, ctx) => {\n let previous: z.infer<typeof publicCartItemAdmissionSchema> | undefined\n admissions.forEach((admission, index) => {\n const comparison = previous\n ? compareAdmissions(admission, previous)\n : undefined\n if (comparison !== undefined && comparison <= 0) {\n ctx.addIssue({\n code: 'custom',\n path: [index],\n message:\n comparison === 0\n ? 'admissions must be unique'\n : 'admissions must be in canonical order',\n })\n }\n previous = admission\n })\n })\n\nexport const publicCartItemSchema = z\n .object({\n id: z.string().min(1),\n product: publicCartReferenceSchema,\n variant: publicCartReferenceSchema,\n admissions: publicCartItemAdmissionsSchema,\n quantity: z.number().int().positive().max(MAX_CART_LINE_QUANTITY),\n unitPriceMinor: minorAmountSchema,\n discountMinor: minorAmountSchema,\n estimatedLineTotalMinor: minorAmountSchema,\n requiresShipping: z.boolean(),\n })\n .strict()\n .superRefine((item, ctx) => {\n const expectedLineTotal =\n BigInt(item.unitPriceMinor) * BigInt(item.quantity) -\n BigInt(item.discountMinor)\n\n if (expectedLineTotal < 0n) {\n ctx.addIssue({\n code: 'custom',\n path: ['discountMinor'],\n message: 'discountMinor cannot exceed the undiscounted line total',\n })\n return\n }\n\n if (BigInt(item.estimatedLineTotalMinor) !== expectedLineTotal) {\n ctx.addIssue({\n code: 'custom',\n path: ['estimatedLineTotalMinor'],\n message:\n 'estimatedLineTotalMinor must equal unitPriceMinor * quantity - discountMinor',\n })\n }\n })\n\nexport const publicCartSchema = z\n .object({\n id: z.string().min(1),\n status: z.enum(['active', 'completed', 'abandoned']),\n revision: z.number().int().nonnegative(),\n currency: currencyCodeSchema,\n market: publicCartMarketSchema,\n subtotalMinor: minorAmountSchema,\n discountMinor: minorAmountSchema,\n estimatedTotalMinor: minorAmountSchema,\n discountCodes: z.array(cartDiscountCodeSchema),\n attributes: publicAttributesSchema,\n items: z.array(publicCartItemSchema),\n expiresAt: z.string().datetime({ offset: true }),\n createdAt: z.string().datetime({ offset: true }),\n updatedAt: z.string().datetime({ offset: true }),\n })\n .strict()\n .superRefine((cart, ctx) => {\n const expectedSubtotal = cart.items.reduce(\n (total, item) =>\n total + BigInt(item.unitPriceMinor) * BigInt(item.quantity),\n 0n,\n )\n const expectedTotal = expectedSubtotal - BigInt(cart.discountMinor)\n const expectedDiscount = cart.items.reduce(\n (total, item) => total + BigInt(item.discountMinor),\n 0n,\n )\n\n if (BigInt(cart.subtotalMinor) !== expectedSubtotal) {\n ctx.addIssue({\n code: 'custom',\n path: ['subtotalMinor'],\n message:\n 'subtotalMinor must equal the sum of undiscounted cart line totals',\n })\n }\n if (BigInt(cart.discountMinor) !== expectedDiscount) {\n ctx.addIssue({\n code: 'custom',\n path: ['discountMinor'],\n message: 'discountMinor must equal the sum of cart line discounts',\n })\n }\n if (expectedTotal < 0n) {\n ctx.addIssue({\n code: 'custom',\n path: ['discountMinor'],\n message: 'discountMinor cannot exceed subtotalMinor',\n })\n } else if (BigInt(cart.estimatedTotalMinor) !== expectedTotal) {\n ctx.addIssue({\n code: 'custom',\n path: ['estimatedTotalMinor'],\n message: 'estimatedTotalMinor must equal subtotalMinor - discountMinor',\n })\n }\n })\n\nexport const cartMutationResultSchema = z\n .object({\n cart: publicCartSchema,\n warnings: z.array(cartWarningSchema),\n })\n .strict()\n\nexport const createCartParamsSchema = z\n .object({\n market: commerceResourceIdSchema.optional(),\n attributes: publicAttributesSchema.optional(),\n })\n .strict()\n\nexport const createCartResultSchema = z\n .object({\n cart: publicCartSchema,\n warnings: z.array(cartWarningSchema),\n cartToken: commerceCapabilitySchema,\n })\n .strict()\n .superRefine((result, ctx) => {\n if (result.cart.revision !== 0) {\n ctx.addIssue({\n code: 'custom',\n path: ['cart', 'revision'],\n message: 'a newly created Cart must start at revision 0',\n })\n }\n })\n\nexport const retrieveCartParamsSchema = z\n .object({ cartToken: commerceCapabilitySchema })\n .strict()\n\nconst addItemAdmissionsSchema = z\n .tuple([publicCartItemAdmissionSchema], publicCartItemAdmissionSchema)\n .readonly()\n .superRefine((admissions, ctx) => {\n if (admissions.length > MAX_CART_LINE_ADMISSIONS) {\n ctx.addIssue({\n code: 'too_big',\n origin: 'array',\n maximum: MAX_CART_LINE_ADMISSIONS,\n inclusive: true,\n message: `admissions cannot contain more than ${MAX_CART_LINE_ADMISSIONS} values`,\n })\n }\n admissions.forEach((admission, index) => {\n if (index === 0) return\n const comparison = compareAdmissions(admission, admissions[index - 1]!)\n if (comparison <= 0) {\n ctx.addIssue({\n code: 'custom',\n path: [index],\n message:\n comparison === 0\n ? 'admissions must be unique'\n : 'admissions must be in canonical order',\n })\n }\n })\n })\n\nexport const addItemBodySchema = z\n .object({\n cartToken: commerceCapabilitySchema,\n expectedRevision: z.number().int().nonnegative(),\n productId: commerceResourceIdSchema,\n variantId: commerceResourceIdSchema,\n quantity: z.number().int().positive().max(MAX_CART_LINE_QUANTITY),\n admissions: addItemAdmissionsSchema.optional(),\n })\n .strict()\nexport const addItemParamsSchema = addItemBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n})\n\nexport const updateItemBodySchema = z\n .object({\n cartToken: commerceCapabilitySchema,\n expectedRevision: z.number().int().nonnegative(),\n cartItemId: commerceResourceIdSchema,\n quantity: z.number().int().positive().max(MAX_CART_LINE_QUANTITY),\n })\n .strict()\nexport const updateItemParamsSchema = updateItemBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n})\n\nexport const removeItemBodySchema = z\n .object({\n cartToken: commerceCapabilitySchema,\n expectedRevision: z.number().int().nonnegative(),\n cartItemId: commerceResourceIdSchema,\n })\n .strict()\nexport const removeItemParamsSchema = removeItemBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n})\n\nexport const clearCartBodySchema = z\n .object({\n cartToken: commerceCapabilitySchema,\n expectedRevision: z.number().int().nonnegative(),\n })\n .strict()\nexport const clearCartParamsSchema = clearCartBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n})\n\nexport const updateCartAttributesBodySchema = z\n .object({\n cartToken: commerceCapabilitySchema,\n expectedRevision: z.number().int().nonnegative(),\n attributes: publicAttributesSchema,\n })\n .strict()\nexport const updateCartAttributesParamsSchema =\n updateCartAttributesBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n })\n\n// Browser and server bodies are identical for token-keyed operations. Server\n// credentials remain headers and never enter these schemas.\nexport const serverCreateCartParamsSchema = createCartParamsSchema\nexport const serverRetrieveCartParamsSchema = retrieveCartParamsSchema\nexport const serverAddItemParamsSchema = addItemParamsSchema\nexport const serverAddItemBodySchema = addItemBodySchema\nexport const serverUpdateItemParamsSchema = updateItemParamsSchema\nexport const serverUpdateItemBodySchema = updateItemBodySchema\nexport const serverRemoveItemParamsSchema = removeItemParamsSchema\nexport const serverRemoveItemBodySchema = removeItemBodySchema\nexport const serverClearCartParamsSchema = clearCartParamsSchema\nexport const serverClearCartBodySchema = clearCartBodySchema\nexport const serverUpdateDiscountCodesParamsSchema =\n updateDiscountCodesParamsSchema\nexport const serverUpdateDiscountCodesBodySchema = updateDiscountCodesBodySchema\nexport const serverUpdateCartAttributesParamsSchema =\n updateCartAttributesParamsSchema\nexport const serverUpdateCartAttributesBodySchema =\n updateCartAttributesBodySchema\n\nexport const addItemResultSchema = cartMutationResultSchema\nexport const updateItemResultSchema = cartMutationResultSchema\nexport const removeItemResultSchema = cartMutationResultSchema\nexport const clearCartResultSchema = cartMutationResultSchema\nexport const updateDiscountCodesResultSchema = cartMutationResultSchema\nexport const updateCartAttributesResultSchema = cartMutationResultSchema\nexport const serverCreateCartResultSchema = createCartResultSchema\nexport const serverAddItemResultSchema = cartMutationResultSchema\nexport const serverUpdateItemResultSchema = cartMutationResultSchema\nexport const serverRemoveItemResultSchema = cartMutationResultSchema\nexport const serverClearCartResultSchema = cartMutationResultSchema\nexport const serverUpdateDiscountCodesResultSchema = cartMutationResultSchema\nexport const serverUpdateCartAttributesResultSchema = cartMutationResultSchema\n\nexport const PublicCartSchema = publicCartSchema\nexport const PublicCartItemSchema = publicCartItemSchema\nexport const PublicCartItemAdmissionSchema = publicCartItemAdmissionSchema\n\nexport type PublicMediaSize = z.infer<typeof publicMediaSizeSchema>\nexport type PublicMediaAsset = z.infer<typeof publicMediaAssetSchema>\nexport type PublicCartReference = z.infer<typeof publicCartReferenceSchema>\nexport type PublicCartMarket = z.infer<typeof publicCartMarketSchema>\nexport type PublicCartItemAdmission = z.infer<\n typeof publicCartItemAdmissionSchema\n>\nexport type PublicCartItem = z.infer<typeof publicCartItemSchema>\nexport type PublicCart = z.infer<typeof publicCartSchema>\nexport type CartMutationResult = z.infer<typeof cartMutationResultSchema>\nexport type CreateCartParams = z.infer<typeof createCartParamsSchema>\nexport type CreateCartResult = z.infer<typeof createCartResultSchema>\nexport type RetrieveCartParams = z.infer<typeof retrieveCartParamsSchema>\nexport type AddItemParams = z.infer<typeof addItemParamsSchema>\nexport type UpdateItemParams = z.infer<typeof updateItemParamsSchema>\nexport type RemoveItemParams = z.infer<typeof removeItemParamsSchema>\nexport type ClearCartParams = z.infer<typeof clearCartParamsSchema>\nexport type UpdateCartAttributesParams = z.infer<\n typeof updateCartAttributesParamsSchema\n>\nexport type AddItemResult = CartMutationResult\nexport type UpdateItemResult = CartMutationResult\nexport type RemoveItemResult = CartMutationResult\nexport type ClearCartResult = CartMutationResult\nexport type UpdateDiscountCodesResult = CartMutationResult\nexport type UpdateCartAttributesResult = CartMutationResult\nexport type ServerCreateCartParams = CreateCartParams\nexport type ServerRetrieveCartParams = RetrieveCartParams\nexport type ServerAddItemParams = AddItemParams\nexport type ServerUpdateItemParams = UpdateItemParams\nexport type ServerRemoveItemParams = RemoveItemParams\nexport type ServerClearCartParams = ClearCartParams\nexport type ServerUpdateDiscountCodesParams = UpdateDiscountCodesParams\nexport type ServerUpdateCartAttributesParams = UpdateCartAttributesParams\nexport type ServerCreateCartResult = CreateCartResult\nexport type ServerAddItemResult = CartMutationResult\nexport type ServerUpdateItemResult = CartMutationResult\nexport type ServerRemoveItemResult = CartMutationResult\nexport type ServerClearCartResult = CartMutationResult\nexport type ServerUpdateDiscountCodesResult = CartMutationResult\nexport type ServerUpdateCartAttributesResult = CartMutationResult\n","import { z } from 'zod'\n\nexport type CurrencyCode = Uppercase<string>\n\nexport const currencyCodeSchema = z\n .string()\n .regex(\n /^[A-Z]{3}$/,\n 'currency must be a three-letter uppercase ISO 4217 code',\n ) as z.ZodType<CurrencyCode>\n\nexport const minorAmountSchema = z\n .number()\n .int()\n .nonnegative()\n .max(Number.MAX_SAFE_INTEGER)\n\nexport const moneySchema = z\n .object({\n amountMinor: minorAmountSchema,\n currency: currencyCodeSchema,\n })\n .strict()\n\nexport const MAX_COMMERCE_EXTENSION_ENTRIES = 50\nexport const MAX_COMMERCE_EXTENSION_KEY_LENGTH = 40\nexport const MAX_COMMERCE_EXTENSION_VALUE_LENGTH = 500\nexport const MAX_COMMERCE_RESOURCE_ID_LENGTH = 255\nexport const MAX_COMMERCE_CAPABILITY_LENGTH = 512\nexport const MAX_COMMERCE_CUSTOMER_TOKEN_LENGTH = 4096\nexport const MAX_COMMERCE_SHORT_TEXT_LENGTH = 200\nexport const MAX_COMMERCE_ADDRESS_LENGTH = 500\nexport const MAX_COMMERCE_EMAIL_LENGTH = 254\nexport const MAX_COMMERCE_PHONE_LENGTH = 32\nexport const MAX_COMMERCE_POSTAL_CODE_LENGTH = 32\n\nexport const commerceResourceIdSchema = z\n .string()\n .min(1)\n .max(MAX_COMMERCE_RESOURCE_ID_LENGTH)\nexport const commerceCapabilitySchema = z\n .string()\n .min(1)\n .max(MAX_COMMERCE_CAPABILITY_LENGTH)\nexport const commerceCustomerTokenSchema = z\n .string()\n .min(1)\n .max(MAX_COMMERCE_CUSTOMER_TOKEN_LENGTH)\n\nconst publicAttributeKeySchema = z\n .string()\n .min(1)\n .max(MAX_COMMERCE_EXTENSION_KEY_LENGTH)\n // Double-underscore names are already treated as reserved across the repo.\n .refine((key) => !key.startsWith('__'), {\n message: 'attribute key uses a reserved platform prefix',\n })\n\nexport const publicAttributeSchema = z\n .object({\n key: publicAttributeKeySchema,\n value: z.string().max(MAX_COMMERCE_EXTENSION_VALUE_LENGTH),\n })\n .strict()\n\nexport const publicAttributesSchema = z\n .array(publicAttributeSchema)\n .max(MAX_COMMERCE_EXTENSION_ENTRIES)\n .superRefine((attributes, ctx) => {\n const seen = new Set<string>()\n attributes.forEach(({ key }, index) => {\n if (seen.has(key)) {\n ctx.addIssue({\n code: 'custom',\n path: [index, 'key'],\n message: 'attribute keys must be unique',\n })\n }\n seen.add(key)\n })\n })\n\nconst integrationMetadataKeySchema = z\n .string()\n .min(1)\n .max(MAX_COMMERCE_EXTENSION_KEY_LENGTH)\n .refine((key) => !key.includes('[') && !key.includes(']'), {\n message: 'integration metadata keys must not use bracket notation',\n })\n\nexport const integrationMetadataSchema = z\n .record(\n integrationMetadataKeySchema,\n z.string().max(MAX_COMMERCE_EXTENSION_VALUE_LENGTH),\n )\n .superRefine((metadata, ctx) => {\n if (Object.keys(metadata).length > MAX_COMMERCE_EXTENSION_ENTRIES) {\n ctx.addIssue({\n code: 'too_big',\n origin: 'object',\n maximum: MAX_COMMERCE_EXTENSION_ENTRIES,\n inclusive: true,\n message: `integration metadata cannot contain more than ${MAX_COMMERCE_EXTENSION_ENTRIES} entries`,\n })\n }\n })\n\nexport const customerSnapshotSchema = z\n .object({\n email: z.string().email().max(MAX_COMMERCE_EMAIL_LENGTH),\n name: z.string().min(1).max(MAX_COMMERCE_SHORT_TEXT_LENGTH).optional(),\n phone: z.string().min(1).max(MAX_COMMERCE_PHONE_LENGTH).optional(),\n })\n .strict()\n\nexport const checkoutShippingAddressSchema = z\n .object({\n recipientName: z.string().min(1).max(MAX_COMMERCE_SHORT_TEXT_LENGTH),\n phone: z.string().min(1).max(MAX_COMMERCE_PHONE_LENGTH),\n countryCode: z.string().trim().length(2).optional(),\n regionCode: z.string().trim().min(1).max(64).optional(),\n postalCode: z.string().min(1).max(MAX_COMMERCE_POSTAL_CODE_LENGTH),\n address: z.string().min(1).max(MAX_COMMERCE_ADDRESS_LENGTH),\n detailAddress: z.string().min(1).max(MAX_COMMERCE_ADDRESS_LENGTH),\n deliveryMessage: z\n .string()\n .max(MAX_COMMERCE_EXTENSION_VALUE_LENGTH)\n .optional(),\n })\n .strict()\n\n/**\n * The two high-entropy formats accepted by ADR 0051. This is deliberately\n * stricter than the legacy order-operation idempotency key contract.\n */\nexport const commerceIdempotencyKeySchema = z\n .string()\n .max(255)\n .refine(\n (value) =>\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(\n value,\n ) || /^ik_[A-Za-z0-9_-]{22}$/.test(value),\n 'idempotencyKey must be a UUIDv4 or ik_-prefixed 128-bit base64url value',\n )\n\nexport const CurrencyCodeSchema = currencyCodeSchema\nexport const MoneySchema = moneySchema\nexport const CommerceIdempotencyKeySchema = commerceIdempotencyKeySchema\n\nexport type Money = z.infer<typeof moneySchema>\nexport type PublicAttribute = z.infer<typeof publicAttributeSchema>\nexport type PublicAttributes = z.infer<typeof publicAttributesSchema>\nexport type IntegrationMetadata = z.infer<typeof integrationMetadataSchema>\nexport type CustomerSnapshot = z.infer<typeof customerSnapshotSchema>\nexport type CanonicalCheckoutShippingAddress = z.infer<\n typeof checkoutShippingAddressSchema\n>\nexport type CommerceIdempotencyKey = z.infer<\n typeof commerceIdempotencyKeySchema\n>\n","import { z } from 'zod'\nimport {\n MAX_CART_LINE_QUANTITY,\n publicCartItemAdmissionsSchema,\n publicCartReferenceSchema,\n} from './cart'\nimport {\n checkoutShippingAddressSchema as canonicalCheckoutShippingAddressSchema,\n commerceCapabilitySchema,\n commerceIdempotencyKeySchema,\n commerceResourceIdSchema,\n currencyCodeSchema,\n customerSnapshotSchema,\n integrationMetadataSchema,\n minorAmountSchema,\n publicAttributesSchema,\n} from './commerce-common'\nimport { paymentProviderStatusSchema } from './payment-session'\n\nexport const canonicalPublicCheckoutItemSchema = z\n .object({\n id: z.string().min(1),\n product: publicCartReferenceSchema,\n variant: publicCartReferenceSchema,\n productTitle: z.string().min(1),\n variantTitle: z.string().min(1).nullable(),\n sku: z.string().min(1).nullable(),\n admissions: publicCartItemAdmissionsSchema,\n quantity: z.number().int().positive().max(MAX_CART_LINE_QUANTITY),\n unitPriceMinor: minorAmountSchema,\n discountMinor: minorAmountSchema,\n lineTotalMinor: minorAmountSchema,\n requiresShipping: z.boolean(),\n })\n .strict()\n .superRefine((item, ctx) => {\n const expectedLineTotal =\n BigInt(item.unitPriceMinor) * BigInt(item.quantity) -\n BigInt(item.discountMinor)\n\n if (expectedLineTotal < 0n) {\n ctx.addIssue({\n code: 'custom',\n path: ['discountMinor'],\n message: 'discountMinor cannot exceed the undiscounted line total',\n })\n return\n }\n\n if (BigInt(item.lineTotalMinor) !== expectedLineTotal) {\n ctx.addIssue({\n code: 'custom',\n path: ['lineTotalMinor'],\n message:\n 'lineTotalMinor must equal unitPriceMinor * quantity - discountMinor',\n })\n }\n })\n\nexport const checkoutAmountsSchema = z\n .object({\n currency: currencyCodeSchema,\n subtotalMinor: minorAmountSchema,\n shippingMinor: minorAmountSchema,\n discountMinor: minorAmountSchema,\n totalMinor: minorAmountSchema,\n })\n .strict()\n .superRefine((amounts, ctx) => {\n const expectedTotal =\n BigInt(amounts.subtotalMinor) +\n BigInt(amounts.shippingMinor) -\n BigInt(amounts.discountMinor)\n\n if (BigInt(amounts.totalMinor) !== expectedTotal) {\n ctx.addIssue({\n code: 'custom',\n path: ['totalMinor'],\n message:\n 'totalMinor must equal subtotalMinor + shippingMinor - discountMinor',\n })\n }\n })\n\nexport const checkoutPaymentSessionRefSchema = z\n .object({\n id: z.string().min(1),\n provider: z.literal('toss'),\n providerStatus: paymentProviderStatusSchema,\n })\n .strict()\n\nexport const openCheckoutPaymentStateSchema = z\n .object({\n activePaymentSession: checkoutPaymentSessionRefSchema.nullable(),\n })\n .strict()\n\nexport const spentCheckoutPaymentStateSchema = z\n .object({\n activePaymentSession: z.null(),\n })\n .strict()\n\nconst lightweightOrderReferenceSchema = z\n .object({\n id: z.string().min(1),\n orderNumber: z.string().min(1),\n })\n .strict()\n\nconst publicCheckoutBaseShape = {\n id: z.string().min(1),\n amounts: checkoutAmountsSchema,\n items: z.array(canonicalPublicCheckoutItemSchema).min(1),\n customerSnapshot: customerSnapshotSchema,\n shippingAddress: canonicalCheckoutShippingAddressSchema.nullable(),\n attributes: publicAttributesSchema,\n expiresAt: z.string().datetime({ offset: true }),\n createdAt: z.string().datetime({ offset: true }),\n updatedAt: z.string().datetime({ offset: true }),\n}\n\nconst abandonedReasonSchema = z.enum(['expired', 'customer', 'operator'])\n\nconst publicCheckoutVariants = [\n z\n .object({\n ...publicCheckoutBaseShape,\n status: z.literal('open'),\n paymentState: openCheckoutPaymentStateSchema,\n order: z.null(),\n })\n .strict(),\n z\n .object({\n ...publicCheckoutBaseShape,\n status: z.literal('placed'),\n placedAt: z.string().datetime({ offset: true }),\n paymentState: spentCheckoutPaymentStateSchema,\n order: lightweightOrderReferenceSchema,\n })\n .strict(),\n z\n .object({\n ...publicCheckoutBaseShape,\n status: z.literal('placed'),\n placedAt: z.string().datetime({ offset: true }),\n placedVia: z.literal('late_capture'),\n abandonedAt: z.string().datetime({ offset: true }),\n abandonedReason: abandonedReasonSchema,\n paymentState: spentCheckoutPaymentStateSchema,\n order: lightweightOrderReferenceSchema,\n })\n .strict(),\n z\n .object({\n ...publicCheckoutBaseShape,\n status: z.literal('abandoned'),\n abandonedAt: z.string().datetime({ offset: true }),\n abandonedReason: abandonedReasonSchema,\n paymentState: z\n .object({\n activePaymentSession: z.null(),\n })\n .strict(),\n order: z.null(),\n })\n .strict(),\n] as const\n\nfunction validateCheckoutSnapshot(input: unknown, ctx: z.RefinementCtx) {\n // The callback runs only after the strict variant schema succeeds. Keeping\n // the callback input unknown also lets the typed ServerCheckout union reuse\n // the same cross-field invariant without weakening its public Zod type.\n const checkout = input as {\n amounts: { subtotalMinor: number; discountMinor: number }\n items: Array<{\n unitPriceMinor: number\n discountMinor: number\n quantity: number\n }>\n }\n const expectedSubtotal = checkout.items.reduce(\n (total, item) =>\n total + BigInt(item.unitPriceMinor) * BigInt(item.quantity),\n 0n,\n )\n const expectedDiscount = checkout.items.reduce(\n (total, item) => total + BigInt(item.discountMinor),\n 0n,\n )\n\n if (BigInt(checkout.amounts.subtotalMinor) !== expectedSubtotal) {\n ctx.addIssue({\n code: 'custom',\n path: ['amounts', 'subtotalMinor'],\n message:\n 'subtotalMinor must equal the sum of undiscounted checkout line totals',\n })\n }\n if (BigInt(checkout.amounts.discountMinor) !== expectedDiscount) {\n ctx.addIssue({\n code: 'custom',\n path: ['amounts', 'discountMinor'],\n message: 'discountMinor must equal the sum of checkout line discounts',\n })\n }\n}\n\nexport const publicCheckoutSchema = z\n .union(publicCheckoutVariants)\n .superRefine(validateCheckoutSnapshot)\n\nconst serverCheckoutExtraShape = {\n clientReferenceId: commerceResourceIdSchema.nullable(),\n integrationMetadata: integrationMetadataSchema,\n}\n\nexport type ServerCheckout = PublicCheckout & {\n clientReferenceId: string | null\n integrationMetadata: Record<string, string>\n}\n\nconst serverCheckoutVariants = publicCheckoutVariants.map((variant) =>\n variant.extend(serverCheckoutExtraShape),\n) as unknown as [z.ZodType, z.ZodType, ...z.ZodType[]]\n\nexport const serverCheckoutSchema: z.ZodType<ServerCheckout> = z\n .union(serverCheckoutVariants)\n .superRefine(validateCheckoutSnapshot) as z.ZodType<ServerCheckout>\n\nexport const retrieveCheckoutParamsSchema = z\n .object({ checkoutToken: commerceCapabilitySchema })\n .strict()\n\nexport const retrieveServerCheckoutParamsSchema = z\n .object({ checkoutId: commerceResourceIdSchema })\n .strict()\n\nexport const createCheckoutBodySchema = z\n .object({\n cartToken: commerceCapabilitySchema,\n customer: customerSnapshotSchema,\n shippingAddress: canonicalCheckoutShippingAddressSchema.optional(),\n })\n .strict()\nexport const createCheckoutParamsSchema = createCheckoutBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n})\n\nexport const createServerCheckoutBodySchema = createCheckoutBodySchema\n .safeExtend({\n clientReferenceId: commerceResourceIdSchema.optional(),\n integrationMetadata: integrationMetadataSchema.optional(),\n })\n .strict()\nexport const createServerCheckoutParamsSchema =\n createServerCheckoutBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n })\n\nexport const createCheckoutResultSchema = z\n .object({\n checkout: publicCheckoutSchema,\n checkoutToken: commerceCapabilitySchema,\n })\n .strict()\n\nexport const createServerCheckoutResultSchema = z\n .object({\n checkout: serverCheckoutSchema,\n checkoutToken: commerceCapabilitySchema,\n })\n .strict()\n\nexport const canonicalCheckoutQuerySchema = z\n .object({\n limit: z.number().int().min(1).max(100).default(20),\n cursor: z.string().min(1).max(512).optional(),\n status: z.array(z.enum(['open', 'placed', 'abandoned'])).optional(),\n createdAtFrom: z.string().datetime({ offset: true }).optional(),\n createdAtTo: z.string().datetime({ offset: true }).optional(),\n clientReferenceId: commerceResourceIdSchema.optional(),\n })\n .strict()\n\nexport type CheckoutListItem = PublicCheckout extends infer Checkout\n ? Checkout extends unknown\n ? Omit<Checkout, 'items' | 'shippingAddress' | 'attributes'> & {\n clientReferenceId: string | null\n }\n : never\n : never\n\nconst checkoutListItemVariants = publicCheckoutVariants.map((variant) =>\n (variant as z.ZodObject<Record<string, z.ZodType>>)\n .omit({\n items: true,\n shippingAddress: true,\n attributes: true,\n })\n .extend({ clientReferenceId: commerceResourceIdSchema.nullable() }),\n) as unknown as [\n z.ZodType<CheckoutListItem>,\n z.ZodType<CheckoutListItem>,\n ...z.ZodType<CheckoutListItem>[],\n]\n\nexport const checkoutListItemSchema = z.union(checkoutListItemVariants)\n\nexport const canonicalCheckoutQueryResultSchema = z\n .object({\n data: z.array(checkoutListItemSchema),\n hasMore: z.boolean(),\n nextCursor: z.string().min(1).max(512).nullable(),\n })\n .strict()\n\nexport const CanonicalPublicCheckoutItemSchema =\n canonicalPublicCheckoutItemSchema\nexport const PublicCheckoutSchema = publicCheckoutSchema\nexport const ServerCheckoutSchema = serverCheckoutSchema\nexport const RetrieveCheckoutParamsSchema = retrieveCheckoutParamsSchema\nexport const RetrieveServerCheckoutParamsSchema =\n retrieveServerCheckoutParamsSchema\nexport const CreateCheckoutBodySchema = createCheckoutBodySchema\nexport const CreateCheckoutParamsSchema = createCheckoutParamsSchema\nexport const CreateServerCheckoutBodySchema = createServerCheckoutBodySchema\nexport const CreateServerCheckoutParamsSchema = createServerCheckoutParamsSchema\nexport const CreateCheckoutResultSchema = createCheckoutResultSchema\nexport const CreateServerCheckoutResultSchema = createServerCheckoutResultSchema\nexport const CanonicalCheckoutQuerySchema = canonicalCheckoutQuerySchema\nexport const CanonicalCheckoutQueryResultSchema =\n canonicalCheckoutQueryResultSchema\nexport const CheckoutQuerySchema = canonicalCheckoutQuerySchema\nexport const CheckoutQueryResultSchema = canonicalCheckoutQueryResultSchema\n\nexport type CanonicalPublicCheckoutItem = z.infer<\n typeof canonicalPublicCheckoutItemSchema\n>\nexport type CheckoutAmounts = z.infer<typeof checkoutAmountsSchema>\nexport type CheckoutPaymentSessionRef = z.infer<\n typeof checkoutPaymentSessionRefSchema\n>\nexport type OpenCheckoutPaymentState = z.infer<\n typeof openCheckoutPaymentStateSchema\n>\nexport type SpentCheckoutPaymentState = z.infer<\n typeof spentCheckoutPaymentStateSchema\n>\nexport type PublicCheckout = z.infer<typeof publicCheckoutSchema>\nexport type RetrieveCheckoutParams = z.infer<\n typeof retrieveCheckoutParamsSchema\n>\nexport type RetrieveServerCheckoutParams = z.infer<\n typeof retrieveServerCheckoutParamsSchema\n>\nexport type CreateCheckoutParams = z.input<typeof createCheckoutParamsSchema>\nexport type CreateServerCheckoutParams = z.input<\n typeof createServerCheckoutParamsSchema\n>\nexport type CreateCheckoutResult = z.infer<typeof createCheckoutResultSchema>\nexport type CreateServerCheckoutResult = z.infer<\n typeof createServerCheckoutResultSchema\n>\nexport type CheckoutQueryParams = z.input<typeof canonicalCheckoutQuerySchema>\nexport type CheckoutQueryResult = z.infer<\n typeof canonicalCheckoutQueryResultSchema\n>\n","import { z } from 'zod'\nimport {\n commerceCapabilitySchema,\n commerceIdempotencyKeySchema,\n commerceResourceIdSchema,\n currencyCodeSchema,\n moneySchema,\n} from './commerce-common'\n\nexport const tossProviderOrderIdSchema = z\n .string()\n .min(6)\n .max(64)\n .regex(\n /^[A-Za-z0-9_-]+$/,\n 'providerOrderId may contain only ASCII letters, digits, underscores, and hyphens',\n )\n\nconst accountAliasUuidV4Schema = z\n .string()\n .regex(\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,\n 'providerCustomerKey must be ANONYMOUS or a UUIDv4 account alias',\n )\n\nexport const tossProviderCustomerKeySchema = z.union([\n z.literal('ANONYMOUS'),\n accountAliasUuidV4Schema,\n])\n\nconst createPaymentSessionBaseBodyShape = {\n checkoutToken: commerceCapabilitySchema,\n}\n\nconst createTossPaymentSessionBodySchema = z\n .object({\n ...createPaymentSessionBaseBodyShape,\n provider: z.literal('toss'),\n providerOptions: z.object({ profile: z.literal('widget_v2') }).strict(),\n })\n .strict()\n\nexport const createPaymentSessionBodySchema = createTossPaymentSessionBodySchema\n\nexport const createPaymentSessionParamsSchema =\n createTossPaymentSessionBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n })\n\nexport const retrieveBrowserPaymentSessionParamsSchema = z\n .object({\n paymentSessionId: commerceResourceIdSchema,\n checkoutToken: commerceCapabilitySchema,\n })\n .strict()\n\nexport const retrieveServerPaymentSessionParamsSchema = z\n .object({ paymentSessionId: commerceResourceIdSchema })\n .strict()\n\nexport const cancelBrowserPaymentSessionBodySchema = z\n .object({\n paymentSessionId: commerceResourceIdSchema,\n checkoutToken: commerceCapabilitySchema,\n })\n .strict()\nexport const cancelBrowserPaymentSessionParamsSchema =\n cancelBrowserPaymentSessionBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n })\n\nexport const cancelServerPaymentSessionBodySchema = z\n .object({\n paymentSessionId: commerceResourceIdSchema,\n })\n .strict()\nexport const cancelServerPaymentSessionParamsSchema =\n cancelServerPaymentSessionBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n })\n\nexport const cancelPaymentSessionParamsSchema = z.union([\n cancelBrowserPaymentSessionParamsSchema,\n cancelServerPaymentSessionParamsSchema,\n])\n\nexport const confirmTossPaymentSessionBodySchema = z\n .object({\n paymentSessionId: commerceResourceIdSchema,\n action: z\n .object({\n type: z.literal('toss_authorization'),\n paymentKey: z.string().min(1).max(512),\n providerOrderId: tossProviderOrderIdSchema,\n })\n .strict(),\n })\n .strict()\nexport const confirmTossPaymentSessionParamsSchema =\n confirmTossPaymentSessionBodySchema.extend({\n idempotencyKey: commerceIdempotencyKeySchema,\n })\n\nexport const paymentNextActionSchema = z\n .object({\n type: z.literal('toss_widget'),\n clientKey: z.string().min(1).max(255),\n paymentMethodVariantKey: z.string().min(1).max(255),\n agreementVariantKey: z.string().min(1).max(255),\n providerOrderId: tossProviderOrderIdSchema,\n providerCustomerKey: tossProviderCustomerKeySchema,\n orderName: z.string().min(1).max(200),\n customerName: z.string().min(1).max(200).optional(),\n customerEmail: z.string().email().max(254).optional(),\n })\n .strict()\n\nexport const PAYMENT_SESSION_ROLES = [\n 'active',\n 'canonical_candidate',\n 'canonical',\n 'residual',\n 'historical',\n] as const\n\nexport const paymentSessionRoleSchema = z.enum(PAYMENT_SESSION_ROLES)\n\nexport const PAYMENT_PROVIDER_STATUSES = [\n 'requires_payment_method',\n 'requires_action',\n 'requires_confirmation',\n 'initializing',\n 'processing',\n 'authorized',\n 'canceling',\n 'unknown',\n 'captured',\n 'failed',\n 'canceled',\n] as const\n\nexport const paymentProviderStatusSchema = z.enum(PAYMENT_PROVIDER_STATUSES)\n\nexport const PAYMENT_RECONCILIATION_REASONS = [\n 'provider_outcome_unknown',\n 'local_commit_ambiguous',\n 'amount_mismatch',\n 'currency_mismatch',\n 'excess_capture_pending_order',\n 'inventory_unavailable',\n 'admission_unavailable',\n 'excess_capture',\n 'late_capture',\n 'cross_checkout_duplicate',\n] as const\n\nexport const paymentReconciliationReasonSchema = z.enum(\n PAYMENT_RECONCILIATION_REASONS,\n)\n\nfunction requiredReconciliationSchema<\n const T extends readonly [string, ...string[]],\n>(reasons: T) {\n const reasonSchema = z.enum(reasons)\n return z\n .object({\n status: z.literal('required'),\n reasons: z.array(reasonSchema).min(1).readonly(),\n })\n .strict()\n .superRefine((value, ctx) => {\n const indexes = new Map(reasons.map((reason, index) => [reason, index]))\n let previous = -1\n value.reasons.forEach((reason, index) => {\n const current = indexes.get(reason) ?? -1\n if (current <= previous) {\n ctx.addIssue({\n code: 'custom',\n path: ['reasons', index],\n message:\n 'reconciliation reasons must be unique and canonical-sorted',\n })\n }\n previous = current\n })\n })\n}\n\nconst noReconciliationSchema = z.object({ status: z.literal('none') }).strict()\n\nexport const publicCaptureEvidenceSchema = z\n .object({\n amountMinor: z.number().int().nonnegative(),\n currency: currencyCodeSchema,\n observedAt: z.string().datetime({ offset: true }),\n })\n .strict()\n\nexport const reconciliationRefundEvidenceSchema = z\n .object({\n providerRefundId: z.string().min(1),\n money: moneySchema,\n observedAt: z.string().datetime({ offset: true }),\n })\n .strict()\n\nexport const PAYMENT_FAILURE_REASONS = [\n 'payment_declined',\n 'authentication_failed',\n 'authorization_expired',\n 'payment_method_unavailable',\n 'provider_terminal_failure',\n 'unknown_provider_terminal_failure',\n] as const\n\nexport const paymentFailureReasonSchema = z.enum(PAYMENT_FAILURE_REASONS)\n\nexport type PaymentNextAction = z.infer<typeof paymentNextActionSchema>\nexport type PublicCaptureEvidence = z.infer<typeof publicCaptureEvidenceSchema>\nexport type PaymentFailureReason = z.infer<typeof paymentFailureReasonSchema>\n\nexport type ReconciliationRequired<Reason extends string> = {\n status: 'required'\n reasons: readonly [Reason, ...Reason[]]\n}\n\ntype PublicPaymentSessionBase = {\n id: string\n money: z.infer<typeof moneySchema>\n expiresAt: string | null\n sessionRole:\n | 'active'\n | 'canonical_candidate'\n | 'canonical'\n | 'residual'\n | 'historical'\n}\n\ntype PublicPaymentSessionState<Action extends PaymentNextAction> =\n | ({\n providerStatus: 'requires_payment_method' | 'requires_action'\n finalizationStatus: 'not_ready'\n reconciliation: { status: 'none' }\n order: null\n } & (\n | {\n sessionRole: 'active'\n presentationStatus: 'actionable'\n nextAction: Action\n }\n | {\n sessionRole: 'residual'\n presentationStatus: 'suppressed'\n nextAction?: never\n }\n ))\n | {\n providerStatus: 'requires_confirmation'\n sessionRole: 'active' | 'residual'\n presentationStatus: 'suppressed'\n finalizationStatus: 'not_ready'\n nextAction?: never\n reconciliation: { status: 'none' }\n order: null\n }\n | {\n providerStatus: 'initializing' | 'processing' | 'authorized'\n sessionRole: 'active' | 'residual'\n presentationStatus: 'suppressed'\n finalizationStatus: 'not_ready'\n nextAction?: never\n reconciliation: { status: 'none' }\n order: null\n }\n | {\n providerStatus: 'canceling'\n sessionRole: 'active' | 'residual'\n presentationStatus: 'suppressed'\n finalizationStatus: 'not_ready'\n nextAction?: never\n reconciliation: { status: 'none' }\n order: null\n }\n | {\n providerStatus: 'unknown'\n sessionRole: 'active' | 'residual'\n presentationStatus: 'suppressed'\n finalizationStatus: 'not_ready'\n nextAction?: never\n reconciliation: ReconciliationRequired<'provider_outcome_unknown'>\n order: null\n }\n | {\n providerStatus: 'captured'\n sessionRole: 'canonical_candidate' | 'residual'\n presentationStatus: 'suppressed'\n finalizationStatus: 'pending'\n nextAction?: never\n reconciliation: { status: 'none' }\n providerEvidence: PublicCaptureEvidence\n order: null\n }\n | {\n providerStatus: 'captured'\n sessionRole: 'canonical' | 'historical'\n presentationStatus: 'suppressed'\n finalizationStatus: 'committed'\n nextAction?: never\n reconciliation: { status: 'none' }\n providerEvidence: PublicCaptureEvidence\n order: { id: string; orderNumber: string }\n }\n | {\n providerStatus: 'captured'\n sessionRole: 'canonical_candidate' | 'residual'\n presentationStatus: 'suppressed'\n finalizationStatus: 'pending'\n nextAction?: never\n reconciliation: ReconciliationRequired<\n | 'local_commit_ambiguous'\n | 'amount_mismatch'\n | 'currency_mismatch'\n | 'excess_capture_pending_order'\n >\n providerEvidence: PublicCaptureEvidence\n order: null\n }\n | {\n providerStatus: 'captured'\n sessionRole: 'canonical' | 'residual'\n presentationStatus: 'suppressed'\n finalizationStatus: 'committed'\n nextAction?: never\n reconciliation: ReconciliationRequired<\n | 'inventory_unavailable'\n | 'admission_unavailable'\n | 'amount_mismatch'\n | 'currency_mismatch'\n | 'excess_capture'\n | 'late_capture'\n | 'cross_checkout_duplicate'\n >\n providerEvidence: PublicCaptureEvidence\n order: { id: string; orderNumber: string }\n }\n | {\n providerStatus: 'failed'\n sessionRole: 'historical'\n presentationStatus: 'suppressed'\n finalizationStatus: 'not_ready'\n nextAction?: never\n providerEvidence?: never\n cancellationReason?: never\n reconciliation: { status: 'none' }\n failure: { reason: PaymentFailureReason; message?: string }\n order: null\n }\n | {\n providerStatus: 'canceled'\n sessionRole: 'historical'\n presentationStatus: 'suppressed'\n finalizationStatus: 'not_ready'\n nextAction?: never\n providerEvidence?: never\n failure?: never\n cancellationReason: 'expired' | 'customer' | 'operator' | 'provider'\n reconciliation: { status: 'none' }\n order: null\n }\n\nexport type PublicPaymentSession = PublicPaymentSessionBase & {\n provider: 'toss'\n} & PublicPaymentSessionState<PaymentNextAction>\n\nconst orderReferenceSchema = z\n .object({\n id: z.string().min(1),\n orderNumber: z.string().min(1),\n })\n .strict()\n\nconst paymentSessionBaseShape = {\n id: z.string().min(1),\n money: moneySchema,\n expiresAt: z.string().datetime({ offset: true }).nullable(),\n}\n\nconst suppressedNotReadyShape = {\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('not_ready'),\n reconciliation: noReconciliationSchema,\n order: z.null(),\n}\n\nfunction stateSchemas(nextAction: z.ZodType) {\n return [\n z.object({\n providerStatus: z.enum(['requires_payment_method', 'requires_action']),\n sessionRole: z.literal('active'),\n presentationStatus: z.literal('actionable'),\n finalizationStatus: z.literal('not_ready'),\n nextAction,\n reconciliation: noReconciliationSchema,\n order: z.null(),\n }),\n z.object({\n providerStatus: z.enum(['requires_payment_method', 'requires_action']),\n sessionRole: z.literal('residual'),\n ...suppressedNotReadyShape,\n }),\n z.object({\n providerStatus: z.literal('requires_confirmation'),\n sessionRole: z.enum(['active', 'residual']),\n ...suppressedNotReadyShape,\n }),\n z.object({\n providerStatus: z.enum(['initializing', 'processing', 'authorized']),\n sessionRole: z.enum(['active', 'residual']),\n ...suppressedNotReadyShape,\n }),\n z.object({\n providerStatus: z.literal('canceling'),\n sessionRole: z.enum(['active', 'residual']),\n ...suppressedNotReadyShape,\n }),\n z.object({\n providerStatus: z.literal('unknown'),\n sessionRole: z.enum(['active', 'residual']),\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('not_ready'),\n reconciliation: requiredReconciliationSchema([\n 'provider_outcome_unknown',\n ]),\n order: z.null(),\n }),\n z.object({\n providerStatus: z.literal('captured'),\n sessionRole: z.enum(['canonical_candidate', 'residual']),\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('pending'),\n reconciliation: noReconciliationSchema,\n providerEvidence: publicCaptureEvidenceSchema,\n order: z.null(),\n }),\n z.object({\n providerStatus: z.literal('captured'),\n sessionRole: z.enum(['canonical', 'historical']),\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('committed'),\n reconciliation: noReconciliationSchema,\n providerEvidence: publicCaptureEvidenceSchema,\n order: orderReferenceSchema,\n }),\n z.object({\n providerStatus: z.literal('captured'),\n sessionRole: z.enum(['canonical_candidate', 'residual']),\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('pending'),\n reconciliation: requiredReconciliationSchema([\n 'local_commit_ambiguous',\n 'amount_mismatch',\n 'currency_mismatch',\n 'excess_capture_pending_order',\n ]),\n providerEvidence: publicCaptureEvidenceSchema,\n order: z.null(),\n }),\n z.object({\n providerStatus: z.literal('captured'),\n sessionRole: z.enum(['canonical', 'residual']),\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('committed'),\n reconciliation: requiredReconciliationSchema([\n 'inventory_unavailable',\n 'admission_unavailable',\n 'amount_mismatch',\n 'currency_mismatch',\n 'excess_capture',\n 'late_capture',\n 'cross_checkout_duplicate',\n ]),\n providerEvidence: publicCaptureEvidenceSchema,\n order: orderReferenceSchema,\n }),\n z.object({\n providerStatus: z.literal('failed'),\n sessionRole: z.literal('historical'),\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('not_ready'),\n reconciliation: noReconciliationSchema,\n failure: z\n .object({\n reason: paymentFailureReasonSchema,\n message: z.string().min(1).optional(),\n })\n .strict(),\n order: z.null(),\n }),\n z.object({\n providerStatus: z.literal('canceled'),\n sessionRole: z.literal('historical'),\n presentationStatus: z.literal('suppressed'),\n finalizationStatus: z.literal('not_ready'),\n cancellationReason: z.enum([\n 'expired',\n 'customer',\n 'operator',\n 'provider',\n ]),\n reconciliation: noReconciliationSchema,\n order: z.null(),\n }),\n ]\n}\n\nfunction providerSessionSchemas(action: z.ZodType) {\n return stateSchemas(action).map((state) =>\n z\n .object({\n ...paymentSessionBaseShape,\n provider: z.literal('toss'),\n ...state.shape,\n })\n .strict(),\n )\n}\n\nconst publicPaymentSessionVariants = [\n ...providerSessionSchemas(paymentNextActionSchema),\n] as unknown as [z.ZodType, z.ZodType, ...z.ZodType[]]\n\nexport const publicPaymentSessionSchema: z.ZodType<PublicPaymentSession> =\n z.union(publicPaymentSessionVariants) as z.ZodType<PublicPaymentSession>\n\nexport const CreatePaymentSessionParamsSchema = createPaymentSessionParamsSchema\nexport const CreatePaymentSessionBodySchema = createPaymentSessionBodySchema\nexport const PublicPaymentSessionSchema = publicPaymentSessionSchema\nexport const RetrieveBrowserPaymentSessionParamsSchema =\n retrieveBrowserPaymentSessionParamsSchema\nexport const RetrieveServerPaymentSessionParamsSchema =\n retrieveServerPaymentSessionParamsSchema\nexport const CancelBrowserPaymentSessionParamsSchema =\n cancelBrowserPaymentSessionParamsSchema\nexport const CancelBrowserPaymentSessionBodySchema =\n cancelBrowserPaymentSessionBodySchema\nexport const CancelServerPaymentSessionParamsSchema =\n cancelServerPaymentSessionParamsSchema\nexport const CancelServerPaymentSessionBodySchema =\n cancelServerPaymentSessionBodySchema\nexport const ConfirmTossPaymentSessionParamsSchema =\n confirmTossPaymentSessionParamsSchema\nexport const ConfirmTossPaymentSessionBodySchema =\n confirmTossPaymentSessionBodySchema\nexport const CancelPaymentSessionParamsSchema = cancelPaymentSessionParamsSchema\n\nexport type CreatePaymentSessionParams = z.infer<\n typeof createPaymentSessionParamsSchema\n>\nexport type RetrieveBrowserPaymentSessionParams = z.infer<\n typeof retrieveBrowserPaymentSessionParamsSchema\n>\nexport type RetrieveServerPaymentSessionParams = z.infer<\n typeof retrieveServerPaymentSessionParamsSchema\n>\nexport type CancelBrowserPaymentSessionParams = z.infer<\n typeof cancelBrowserPaymentSessionParamsSchema\n>\nexport type CancelServerPaymentSessionParams = z.infer<\n typeof cancelServerPaymentSessionParamsSchema\n>\nexport type CancelPaymentSessionParams = z.infer<\n typeof cancelPaymentSessionParamsSchema\n>\nexport type ConfirmTossPaymentSessionParams = z.infer<\n typeof confirmTossPaymentSessionParamsSchema\n>\nexport type PaymentSessionRole = z.infer<typeof paymentSessionRoleSchema>\nexport type PaymentProviderStatus = z.infer<typeof paymentProviderStatusSchema>\nexport type PaymentReconciliationReason = z.infer<\n typeof paymentReconciliationReasonSchema\n>\nexport type ReconciliationRefundEvidence = z.infer<\n typeof reconciliationRefundEvidenceSchema\n>\n","import { Command } from 'commander'\nimport { cancelOrderSchema } from '@01.software/contracts'\nimport { z } from 'zod'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray, parseWithSchema } from '../lib/parse.js'\n\nconst idSchema = z.union([z.string().min(1), z.number()]).transform(String)\n\nconst orderStatusSchema = z.enum(['confirmed'])\n\nconst fulfillmentStatusSchema = z.enum(['shipped', 'delivered', 'failed'])\n\nconst updateFulfillmentSchema = z\n .object({\n fulfillmentId: idSchema,\n status: fulfillmentStatusSchema.optional(),\n carrier: z.string().min(1).optional(),\n trackingNumber: z.string().min(1).optional(),\n })\n .refine(\n (value) =>\n value.status !== undefined ||\n value.carrier !== undefined ||\n value.trackingNumber !== undefined,\n {\n message: 'status, carrier, or trackingNumber is required',\n },\n )\n\nconst fulfillmentItemsSchema = z\n .array(\n z\n .object({\n orderItem: idSchema,\n quantity: z\n .number()\n .int()\n .positive('quantity must be a positive integer'),\n })\n .strict(),\n )\n .min(1, 'At least one fulfillment item is required')\n .max(100, 'Maximum 100 items per fulfillment')\n\nexport function registerOrderCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const order = program.command('order').description('Order management')\n\n order\n .command('update <orderNumber>')\n .description('Confirm a delivered order purchase')\n .requiredOption('--status <status>', 'New status (confirmed only)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const status = parseWithSchema(opts.status, 'status', orderStatusSchema)\n const data = { orderNumber, status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.update(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('cancel <orderNumber>')\n .description('Cancel an eligible order')\n .option(\n '--reason-code <code>',\n 'Cancel reason (customer, inventory, fraud, declined, staff, other)',\n )\n .option('--reason-detail <text>', 'Internal cancellation detail')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n orderNumber,\n ...(opts.reasonCode ? { reasonCode: opts.reasonCode } : {}),\n ...(opts.reasonDetail ? { reasonDetail: opts.reasonDetail } : {}),\n },\n 'cancel',\n cancelOrderSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order cancel', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.cancelOrder(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('prepare <orderNumber>')\n .description('Move paid order fulfillment work to preparation')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = { orderNumber }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order prepare', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result =\n await client.commerce.orders.prepareFulfillmentOrder(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('fulfill <orderNumber>')\n .description('Create a shipment for a prepared order')\n .option('--items <json>', 'Fulfillment items array (JSON)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const items = opts.items\n ? parseWithSchema(\n parseJsonArray(opts.items, 'items'),\n 'items',\n fulfillmentItemsSchema,\n )\n : undefined\n const data = {\n orderNumber,\n ...(opts.carrier ? { carrier: opts.carrier } : {}),\n ...(opts.trackingNumber\n ? { trackingNumber: opts.trackingNumber }\n : {}),\n ...(items ? { items } : {}),\n }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'order fulfill', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createFulfillment({\n ...data,\n ...(items\n ? {\n items: items as Parameters<\n typeof client.commerce.orders.createFulfillment\n >[0]['items'],\n }\n : {}),\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n order\n .command('update-fulfillment <fulfillmentId>')\n .description('Update shipment status or tracking information')\n .option('--status <status>', 'Shipment status (shipped, delivered, failed)')\n .option('--carrier <name>', 'Shipping carrier')\n .option('--tracking-number <num>', 'Tracking number')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (fulfillmentId: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n fulfillmentId,\n ...(opts.status ? { status: opts.status } : {}),\n ...(opts.carrier ? { carrier: opts.carrier } : {}),\n ...(opts.trackingNumber\n ? { trackingNumber: opts.trackingNumber }\n : {}),\n },\n 'fulfillment',\n updateFulfillmentSchema,\n )\n if (opts.dryRun) {\n printResult(\n {\n dryRun: true,\n valid: true,\n action: 'order update-fulfillment',\n data,\n },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateFulfillment(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport {\n createReturnSchema,\n returnWithRefundSchema,\n} from '@01.software/contracts'\nimport { z } from 'zod'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray, parseWithSchema } from '../lib/parse.js'\n\nconst returnStatusSchema = z.enum([\n 'processing',\n 'approved',\n 'rejected',\n 'completed',\n])\n\nexport function registerReturnCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const ret = program.command('return').description('Return management')\n\n ret\n .command('create <orderNumber>')\n .description('Create a return request')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .option(\n '--return-shipping-fee <n>',\n 'Return shipping fee charged to the customer',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-amount <n>',\n 'Initial order shipping refund amount',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-note <text>',\n 'Audit note for manual initial shipping refund override',\n )\n .option(\n '--reason <reason>',\n 'Return reason (change_of_mind, defective, wrong_delivery, damaged, other)',\n )\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n orderNumber,\n returnItems: parseJsonArray(opts.products, 'products'),\n refundAmount: opts.refundAmount,\n returnShippingFee: opts.returnShippingFee,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n initialShippingRefundAmount: opts.initialShippingRefundAmount,\n initialShippingRefundOverrideNote: opts.initialShippingRefundNote,\n },\n 'return',\n createReturnSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return create', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.createReturn({\n ...data,\n returnItems: data.returnItems as Parameters<\n typeof client.commerce.orders.createReturn\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('update <returnId>')\n .description('Update return status')\n .requiredOption(\n '--status <status>',\n 'New status (processing, approved, rejected, completed)',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (returnId: string, opts) => {\n try {\n const status = parseWithSchema(\n opts.status,\n 'status',\n returnStatusSchema,\n )\n const data = { returnId, status }\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return update', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.updateReturn(data)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n ret\n .command('refund <orderNumber>')\n .description('Return with refund')\n .requiredOption('--products <json>', 'Return products array (JSON)')\n .requiredOption('--refund-amount <n>', 'Refund amount', parseFloat)\n .requiredOption('--payment-id <id>', 'Payment ID')\n .option(\n '--return-shipping-fee <n>',\n 'Return shipping fee charged to the customer',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-amount <n>',\n 'Initial order shipping refund amount',\n parseFloat,\n )\n .option(\n '--initial-shipping-refund-note <text>',\n 'Audit note for manual initial shipping refund override',\n )\n .option('--reason <reason>', 'Return reason')\n .option('--reason-detail <text>', 'Detailed reason')\n .option('--refund-receipt-url <url>', 'Refund receipt URL')\n .option('--payment-key <key>', 'Provider payment key')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (orderNumber: string, opts) => {\n try {\n const data = parseWithSchema(\n {\n orderNumber,\n returnItems: parseJsonArray(opts.products, 'products'),\n refundAmount: opts.refundAmount,\n returnShippingFee: opts.returnShippingFee,\n pgPaymentId: opts.paymentId,\n reason: opts.reason,\n reasonDetail: opts.reasonDetail,\n refundReceiptUrl: opts.refundReceiptUrl,\n paymentKey: opts.paymentKey,\n initialShippingRefundAmount: opts.initialShippingRefundAmount,\n initialShippingRefundOverrideNote: opts.initialShippingRefundNote,\n },\n 'return',\n returnWithRefundSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'return refund', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.orders.returnWithRefund({\n ...data,\n returnItems: data.returnItems as Parameters<\n typeof client.commerce.orders.returnWithRefund\n >[0]['returnItems'],\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { createReadStream } from 'node:fs'\nimport { stdin as processStdin } from 'node:process'\n\nexport const SENSITIVE_JSON_MAX_BYTES = 1024 * 1024\n\ntype SensitiveReadable = AsyncIterable<Buffer | string> & {\n isTTY?: boolean\n destroy?: () => void\n}\n\nexport interface SensitiveJsonInputSources {\n stdin?: SensitiveReadable\n openFile?: (path: string) => SensitiveReadable\n}\n\nfunction invalidInput(message: string) {\n return {\n type: 'validation' as const,\n code: 'invalid_argument' as const,\n field: 'data',\n message,\n detail: { message, field: 'data' },\n }\n}\n\nfunction isInvalidInput(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false\n const value = error as Record<string, unknown>\n return value.type === 'validation' && value.code === 'invalid_argument'\n}\n\nasync function readBoundedUtf8(source: SensitiveReadable): Promise<string> {\n const chunks: Buffer[] = []\n let totalBytes = 0\n for await (const chunk of source) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n totalBytes += buffer.byteLength\n if (totalBytes > SENSITIVE_JSON_MAX_BYTES) {\n throw invalidInput(\n `Sensitive commerce data must be ${SENSITIVE_JSON_MAX_BYTES} bytes or fewer.`,\n )\n }\n chunks.push(buffer)\n }\n return Buffer.concat(chunks, totalBytes).toString('utf8')\n}\n\n/** Read secret-bearing JSON without placing it in argv or validation output. */\nexport async function readSensitiveJsonObject(\n opts: {\n dataStdin?: boolean\n dataFile?: string\n },\n sources: SensitiveJsonInputSources = {},\n): Promise<Record<string, unknown>> {\n const sourceCount = [opts.dataStdin, opts.dataFile].filter(Boolean).length\n if (sourceCount !== 1) {\n throw invalidInput(\n 'Exactly one of --data-stdin or --data-file is required for sensitive commerce data.',\n )\n }\n\n let raw: string\n const input = sources.stdin ?? processStdin\n try {\n if (opts.dataStdin) {\n if (input.isTTY === true) {\n throw invalidInput(\n 'Sensitive commerce data cannot be read from an interactive terminal. Pipe JSON to --data-stdin or use --data-file.',\n )\n }\n raw = await readBoundedUtf8(input)\n } else {\n const file = (sources.openFile ?? createReadStream)(opts.dataFile!)\n try {\n raw = await readBoundedUtf8(file)\n } finally {\n file.destroy?.()\n }\n }\n } catch (error) {\n if (isInvalidInput(error)) throw error\n throw invalidInput('Sensitive commerce data could not be read.')\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw invalidInput('Sensitive commerce data must be valid JSON.')\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw invalidInput('Sensitive commerce data must be a JSON object.')\n }\n return parsed as Record<string, unknown>\n}\n\n/** Build a dry-run result that proves validation without echoing secret input. */\nexport function sensitiveDryRunResult(action: string) {\n return { dryRun: true, valid: true, action } as const\n}\n","import {\n addItemParamsSchema,\n clearCartParamsSchema,\n createCartParamsSchema,\n removeItemParamsSchema,\n retrieveCartParamsSchema,\n updateCartAttributesParamsSchema,\n updateDiscountCodesParamsSchema,\n updateItemParamsSchema,\n} from '@01.software/contracts'\nimport { Command } from 'commander'\nimport {\n addCartItemSchema,\n cartLineAdmissionsInputSchema,\n clearCartSchema,\n removeCartItemSchema,\n updateCartItemSchema,\n updateDiscountCodesSchema,\n} from '@01.software/contracts'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { exitWithError, printResult } from '../lib/output.js'\nimport { parseWithSchema } from '../lib/parse.js'\nimport {\n readSensitiveJsonObject,\n sensitiveDryRunResult,\n} from '../lib/sensitive-json-input.js'\n\nexport function registerCartCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const cart = program.command('cart').description('Cart management')\n\n cart\n .command('create')\n .description('Create a cart and print its cartToken capability')\n .option('--data-stdin', 'Read market and attributes JSON from stdin')\n .option('--data-file <path>', 'Read market and attributes JSON from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const input =\n opts.dataStdin || opts.dataFile\n ? await readSensitiveJsonObject(opts)\n : {}\n const data = parseWithSchema(\n input,\n 'cart create',\n createCartParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('cart create'), getFormat())\n return\n }\n printResult(await getClient().commerce.carts.create(data), getFormat())\n } catch (error) {\n exitWithError(error)\n }\n })\n\n cart\n .command('retrieve')\n .description('Retrieve a cart by its capability token')\n .option('--data-stdin', 'Read the Cart capability JSON from stdin')\n .option('--data-file <path>', 'Read the Cart capability JSON from file')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'cart retrieve',\n retrieveCartParamsSchema,\n )\n printResult(\n await getClient().commerce.carts.retrieve(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n cart\n .command('add')\n .description('Add an item to a cart')\n .option('--data-stdin', 'Read capability and item JSON from stdin')\n .option('--data-file <path>', 'Read capability and item JSON from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'cart add',\n addItemParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('cart add'), getFormat())\n return\n }\n printResult(await getClient().commerce.carts.addItem(data), getFormat())\n } catch (error) {\n exitWithError(error)\n }\n })\n\n cart\n .command('update')\n .description('Update cart item quantity')\n .option('--data-stdin', 'Read capability and item JSON from stdin')\n .option('--data-file <path>', 'Read capability and item JSON from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'cart update',\n updateItemParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('cart update'), getFormat())\n return\n }\n printResult(\n await getClient().commerce.carts.updateItem(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n cart\n .command('remove')\n .description('Remove an item from a cart')\n .option('--data-stdin', 'Read capability and item JSON from stdin')\n .option('--data-file <path>', 'Read capability and item JSON from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'cart remove',\n removeItemParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('cart remove'), getFormat())\n return\n }\n printResult(\n await getClient().commerce.carts.removeItem(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n cart\n .command('clear')\n .description('Remove all items from a cart')\n .option('--data-stdin', 'Read the Cart capability JSON from stdin')\n .option('--data-file <path>', 'Read the Cart capability JSON from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'cart clear',\n clearCartParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('cart clear'), getFormat())\n return\n }\n printResult(await getClient().commerce.carts.clear(data), getFormat())\n } catch (error) {\n exitWithError(error)\n }\n })\n\n cart\n .command('discounts')\n .description('Replace all cart discount codes; pass [] to clear')\n .option('--data-stdin', 'Read capability and discount JSON from stdin')\n .option('--data-file <path>', 'Read capability and discount JSON from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'cart discounts',\n updateDiscountCodesParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('cart discounts'), getFormat())\n return\n }\n printResult(\n await getClient().commerce.carts.updateDiscountCodes(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n cart\n .command('attributes')\n .description('Replace all public cart attributes; pass [] to clear')\n .option('--data-stdin', 'Read capability and attributes JSON from stdin')\n .option(\n '--data-file <path>',\n 'Read capability and attributes JSON from file',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'cart attributes',\n updateCartAttributesParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('cart attributes'), getFormat())\n return\n }\n printResult(\n await getClient().commerce.carts.updateAttributes(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJsonArray } from '../lib/parse.js'\n\nexport function registerStockCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const stock = program.command('stock').description('Stock management')\n\n stock\n .command('check')\n .description('Check stock availability')\n .requiredOption(\n '--items <json>',\n 'Items to check (JSON array of { optionId, quantity })',\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const items = parseJsonArray(opts.items, 'items') as Parameters<\n typeof client.commerce.product.stockCheck\n >[0]['items']\n const result = await client.commerce.product.stockCheck({ items })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import {\n CancelServerPaymentSessionParamsSchema,\n CanonicalCheckoutQuerySchema,\n ConfirmTossPaymentSessionParamsSchema,\n CreatePaymentSessionParamsSchema,\n CreateServerCheckoutParamsSchema,\n} from '@01.software/contracts'\nimport { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { exitWithError, printResult } from '../lib/output.js'\nimport { parseJson, parseWithSchema } from '../lib/parse.js'\nimport {\n readSensitiveJsonObject,\n sensitiveDryRunResult,\n} from '../lib/sensitive-json-input.js'\n\nexport function registerCommerceSessionCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const checkout = program\n .command('checkout')\n .description('Checkout management')\n\n checkout\n .command('create')\n .description('Create a Checkout from a server-authoritative Cart')\n .option('--data-stdin', 'Read capability and customer JSON from stdin')\n .option('--data-file <path>', 'Read capability and customer JSON from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'checkout',\n CreateServerCheckoutParamsSchema,\n )\n if (opts.dryRun) {\n printResult(sensitiveDryRunResult('checkout create'), getFormat())\n return\n }\n printResult(\n await getClient().commerce.checkouts.create(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n checkout\n .command('retrieve <checkoutId>')\n .description('Retrieve a Checkout by ID with server credentials')\n .action(async (checkoutId: string) => {\n try {\n printResult(\n await getClient().commerce.checkouts.retrieve({ checkoutId }),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n checkout\n .command('query')\n .description('Query lightweight Checkouts with server credentials')\n .option('--params <json>', 'Checkout query parameters (JSON)', '{}')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n parseJson(opts.params, 'params'),\n 'checkout query',\n CanonicalCheckoutQuerySchema,\n )\n printResult(\n await getClient().commerce.checkouts.query(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n const sessions = program\n .command('payment-session')\n .description('PaymentSession management')\n\n sessions\n .command('create')\n .description('Create a canonical provider-configured PaymentSession')\n .option('--data-stdin', 'Read canonical create parameters from stdin')\n .option('--data-file <path>', 'Read canonical create parameters from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'payment-session',\n CreatePaymentSessionParamsSchema,\n )\n if (opts.dryRun) {\n printResult(\n sensitiveDryRunResult('payment-session create'),\n getFormat(),\n )\n return\n }\n printResult(\n await getClient().commerce.paymentSessions.create(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n sessions\n .command('retrieve <paymentSessionId>')\n .description('Retrieve a PaymentSession')\n .action(async (paymentSessionId: string) => {\n try {\n printResult(\n await getClient().commerce.paymentSessions.retrieve({\n paymentSessionId,\n }),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n sessions\n .command('cancel')\n .description('Cancel a PaymentSession and release its payment slot')\n .option('--data-stdin', 'Read session ID and idempotency key from stdin')\n .option(\n '--data-file <path>',\n 'Read session ID and idempotency key from file',\n )\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'payment-session cancel',\n CancelServerPaymentSessionParamsSchema,\n )\n if (opts.dryRun) {\n printResult(\n sensitiveDryRunResult('payment-session cancel'),\n getFormat(),\n )\n return\n }\n printResult(\n await getClient().commerce.paymentSessions.cancel(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n\n sessions\n .command('confirm-toss')\n .description('Confirm a Toss authorization with the typed server action')\n .option('--data-stdin', 'Read Toss confirmation params from stdin')\n .option('--data-file <path>', 'Read Toss confirmation params from file')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n await readSensitiveJsonObject(opts),\n 'payment-session confirm-toss',\n ConfirmTossPaymentSessionParamsSchema,\n )\n if (opts.dryRun) {\n printResult(\n sensitiveDryRunResult('payment-session confirm-toss'),\n getFormat(),\n )\n return\n }\n printResult(\n await getClient().commerce.paymentSessions.confirm(data),\n getFormat(),\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n}\n","import type {\n ProductDetailParams,\n ProductFallbackLocaleOption,\n ProductLocaleOption,\n} from '@01.software/sdk'\n\nexport interface ProductDetailCliOptions {\n id?: string\n slug?: string\n market?: string\n locale?: string\n fallbackLocale?: string\n}\n\nfunction invalidOption(message: string, field: string, value?: unknown): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: 'invalid_argument',\n field,\n detail: { message, value, field },\n })\n return error\n}\n\nfunction parseLocale(\n value: string | undefined,\n): ProductLocaleOption | undefined {\n if (value == null) return undefined\n if (value === 'ko' || value === 'en' || value === 'all') return value\n throw invalidOption('--locale must be one of: ko, en, all', 'locale', value)\n}\n\nfunction parseFallbackLocale(\n value: string | undefined,\n): ProductFallbackLocaleOption | undefined {\n if (value == null) return undefined\n if (value === 'ko' || value === 'en') return value\n if (value === 'none') return false\n throw invalidOption(\n '--fallback-locale must be one of: ko, en, none',\n 'fallbackLocale',\n value,\n )\n}\n\nexport function productDetailParamsFromOptions(\n options: ProductDetailCliOptions,\n): ProductDetailParams {\n const hasId = typeof options.id === 'string' && options.id.length > 0\n const hasSlug = typeof options.slug === 'string' && options.slug.length > 0\n\n if (hasId === hasSlug) {\n throw invalidOption(\n 'Exactly one of --id or --slug is required.',\n 'product',\n { id: options.id, slug: options.slug },\n )\n }\n\n const locale = parseLocale(options.locale)\n const fallbackLocale = parseFallbackLocale(options.fallbackLocale)\n const identifier = hasId ? { id: options.id! } : { slug: options.slug! }\n\n return {\n ...identifier,\n ...(options.market !== undefined ? { market: options.market } : {}),\n ...(locale !== undefined ? { locale } : {}),\n ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),\n }\n}\n","import { Command } from 'commander'\nimport { ProductUpsertSchema } from '@01.software/contracts'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseJson, parseWithSchema } from '../lib/parse.js'\nimport {\n productDetailParamsFromOptions,\n type ProductDetailCliOptions,\n} from '../lib/product-detail-options.js'\n\nexport function registerProductCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const product = program.command('product').description('Product management')\n\n product\n .command('detail')\n .description('Get shaped product detail by slug or ID')\n .option('--slug <slug>', 'Product slug')\n .option('--id <id>', 'Product ID')\n .option('--market <market>', 'Market slug')\n .option('--locale <locale>', 'Locale: ko, en, or all')\n .option('--fallback-locale <locale>', 'Fallback locale: ko, en, or none')\n .action(async (opts: ProductDetailCliOptions) => {\n try {\n const params = productDetailParamsFromOptions(opts)\n const client = getClient()\n const result = await client.commerce.product.detail(params)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n\n product\n .command('upsert')\n .description('Create or update a product graph (options, values, variants)')\n .requiredOption('--input <json>', 'Product upsert input (JSON)')\n .option('--dry-run', 'Validate inputs without executing')\n .action(async (opts) => {\n try {\n const data = parseWithSchema(\n parseJson(opts.input, 'input'),\n 'input',\n ProductUpsertSchema,\n )\n if (opts.dryRun) {\n printResult(\n { dryRun: true, valid: true, action: 'product upsert', data },\n getFormat(),\n )\n return\n }\n const client = getClient()\n const result = await client.commerce.product.upsert(\n data as Parameters<typeof client.commerce.product.upsert>[0],\n )\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerDiscountCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const discount = program\n .command('discount')\n .description('Discount management')\n\n discount\n .command('validate')\n .description('Validate a discount code against an order amount')\n .requiredOption('--code <code>', 'Discount code')\n .requiredOption('--order-amount <n>', 'Order amount', (v: string) =>\n parseInt(v, 10),\n )\n .action(async (opts) => {\n try {\n const client = getClient()\n const result = await client.commerce.discounts.validate({\n code: opts.code,\n orderAmount: opts.orderAmount,\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerShippingCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const shipping = program\n .command('shipping')\n .description('Shipping calculation')\n\n shipping\n .command('calculate')\n .description('Calculate shipping for an order amount')\n .requiredOption('--order-amount <n>', 'Order amount', (v: string) =>\n parseInt(v, 10),\n )\n .option('--shipping-policy-id <id>', 'Shipping policy ID')\n .option('--country-code <code>', 'Destination country code')\n .option('--region-code <code>', 'Destination region code')\n .option('--postal-code <code>', 'Destination postal code')\n .action(async (opts) => {\n try {\n const client = getClient()\n const result = await client.commerce.shipping.calculate({\n orderAmount: opts.orderAmount,\n ...(opts.shippingPolicyId\n ? { shippingPolicyId: opts.shippingPolicyId }\n : {}),\n ...(opts.countryCode ? { countryCode: opts.countryCode } : {}),\n ...(opts.regionCode ? { regionCode: opts.regionCode } : {}),\n ...(opts.postalCode ? { postalCode: opts.postalCode } : {}),\n })\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport { execFile, exec } from 'node:child_process'\nimport { platform } from 'node:os'\nimport { URL } from 'node:url'\nimport type { Command } from 'commander'\nimport pc from 'picocolors'\nimport {\n loadCredentials,\n saveCredentials,\n deleteCredentials,\n getCredentialsPath,\n loadLocalCredentials,\n saveLocalCredentials,\n getLocalCredentialsPath,\n loadTenantList,\n saveTenantList,\n type TenantInfo,\n} from '../lib/credentials.js'\n\nconst WEB_URL = process.env.SOFTWARE_WEB_URL || 'https://01.software'\nconst TIMEOUT_MS = 3 * 60 * 1000 // 3 minutes\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\nfunction openBrowser(url: string): void {\n const os = platform()\n\n const onError = () => {\n console.log(\n pc.yellow(\n `Could not open browser automatically. Open this URL manually:\\n${url}`,\n ),\n )\n }\n\n if (os === 'win32') {\n exec(`start \"\" \"${url}\"`, (err) => {\n if (err) onError()\n })\n } else {\n const cmd = os === 'darwin' ? 'open' : 'xdg-open'\n execFile(cmd, [url], (err) => {\n if (err) onError()\n })\n }\n}\n\nconst PAGE_STYLE = `*{margin:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;background:#fff;color:#252525}\n@media(prefers-color-scheme:dark){body{background:#252525;color:#f5f5f5}}\n.card{text-align:center;padding:2rem 2.5rem;border-radius:10px;max-width:380px;width:100%}\n.icon{width:40px;height:40px;margin:0 auto 1rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.25rem}\n.icon.ok{background:rgba(0,0,0,.05);color:#252525}\n.icon.err{background:rgba(220,38,38,.08);color:#dc2626}\n@media(prefers-color-scheme:dark){.icon.ok{background:rgba(255,255,255,.08);color:#f5f5f5}}\nh1{font-size:.875rem;font-weight:600;margin-bottom:.375rem}\np{font-size:.75rem;color:#737373;line-height:1.5}`\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon ok\">\\u2713</div><h1>Authenticated</h1><p>You can close this tab and return to the terminal.</p></div></body></html>`\n\nconst ERROR_HTML = (msg: string) => `<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><title>CLI Login Error</title>\n<style>${PAGE_STYLE}</style>\n</head><body><div class=\"card\"><div class=\"icon err\">!</div><h1>Authentication failed</h1><p>${escapeHtml(msg)}</p></div></body></html>`\n\ninterface ExchangeResponse {\n publishableKey: string\n secretKey: string\n tenantName: string\n tenantId: string\n tenants?: TenantInfo[]\n}\n\nasync function exchangeCode(code: string): Promise<ExchangeResponse | null> {\n const url = `${WEB_URL}/api/cli/exchange`\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ code }),\n })\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n console.error(\n pc.red(\n `Exchange failed: HTTP ${res.status} from ${url}${body ? ` — ${body.slice(0, 200)}` : ''}`,\n ),\n )\n return null\n }\n const data = (await res.json()) as Partial<ExchangeResponse>\n if (\n typeof data.publishableKey !== 'string' ||\n typeof data.secretKey !== 'string' ||\n typeof data.tenantName !== 'string' ||\n typeof data.tenantId !== 'string'\n ) {\n console.error(pc.red(`Exchange failed: malformed response from ${url}`))\n return null\n }\n return {\n publishableKey: data.publishableKey,\n secretKey: data.secretKey,\n tenantName: data.tenantName,\n tenantId: data.tenantId,\n tenants: Array.isArray(data.tenants)\n ? data.tenants.filter(\n (t): t is TenantInfo =>\n typeof (t as TenantInfo)?.id === 'string' &&\n typeof (t as TenantInfo)?.name === 'string',\n )\n : undefined,\n }\n } catch (err) {\n console.error(\n pc.red(\n `Exchange request to ${url} failed: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n return null\n }\n}\n\n/**\n * Start a local HTTP server that receives the OAuth-style redirect callback\n * from the browser. The browser top-level-navigates to\n * http://127.0.0.1:{port}/callback?code={encryptedCode}&state={state}\n * and the CLI exchanges the opaque code with the web API to receive the\n * actual credentials server-to-server. This path has no CORS or PNA\n * preflight because the browser never issues a subresource fetch.\n */\nfunction startAuthServer(options: {\n state: string\n saveFn: (creds: {\n publishableKey: string\n secretKey: string\n tenantId?: string\n tenantName: string\n }) => void\n}): Promise<{ port: number; cleanup: (exitCode?: number) => void }> {\n return new Promise((resolve, reject) => {\n const server = createServer((req, res) => {\n if (!req.url) {\n res.writeHead(400).end()\n return\n }\n\n const url = new URL(req.url, `http://localhost`)\n\n if (url.pathname !== '/callback' || req.method !== 'GET') {\n res.writeHead(404).end()\n return\n }\n\n const error = url.searchParams.get('error')\n if (error) {\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML(error))\n console.error(pc.red(`Login failed: ${error}`))\n cleanup(2)\n return\n }\n\n const code = url.searchParams.get('code')\n const receivedState = url.searchParams.get('state')\n\n if (!code || !receivedState) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Missing code or state. Start over with \"01 login\".'))\n cleanup(2)\n return\n }\n\n if (receivedState !== options.state) {\n res\n .writeHead(403, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('State mismatch. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: state mismatch.'))\n cleanup(2)\n return\n }\n\n exchangeCode(code).then((creds) => {\n if (!creds) {\n res\n .writeHead(400, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(ERROR_HTML('Invalid or expired code. Start over with \"01 login\".'))\n console.error(pc.red('Login failed: code exchange failed.'))\n cleanup(2)\n return\n }\n\n options.saveFn({\n publishableKey: creds.publishableKey,\n secretKey: creds.secretKey,\n tenantId: creds.tenantId,\n tenantName: creds.tenantName,\n })\n\n if (creds.tenants && creds.tenants.length > 0) {\n saveTenantList(creds.tenants)\n }\n\n console.log(pc.green(`\\nLogged in successfully!`))\n console.log(pc.dim(`Tenant: ${creds.tenantName}`))\n\n res\n .writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', Connection: 'close' })\n .end(SUCCESS_HTML)\n cleanup(0)\n })\n })\n\n let timeout: ReturnType<typeof setTimeout>\n let completed = false\n\n function cleanup(exitCode = 0) {\n if (completed) return\n completed = true\n clearTimeout(timeout)\n server.closeAllConnections?.()\n server.close(() => process.exit(exitCode))\n }\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to start local server.'))\n return\n }\n\n timeout = setTimeout(() => {\n console.error(\n pc.red('\\nLogin timed out (3 minutes). Please try again.'),\n )\n cleanup(4)\n }, TIMEOUT_MS)\n\n resolve({ port: addr.port, cleanup })\n })\n\n server.on('error', (err) => {\n reject(err)\n })\n })\n}\n\nexport function registerAuthCommands(program: Command): void {\n program\n .command('login')\n .description('Login via browser and store credentials')\n .action(async () => {\n const state = randomBytes(32).toString('hex')\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n saveCredentials(creds)\n console.log(pc.dim(`Credentials saved to ${getCredentialsPath()}`))\n },\n })\n\n const params = new URLSearchParams({ port: String(port), state })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim('Opening browser for login...'))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n\n program\n .command('logout')\n .description('Remove stored credentials')\n .action(() => {\n const deleted = deleteCredentials()\n if (deleted) {\n console.log(pc.green('Logged out. Credentials removed.'))\n } else {\n console.log(pc.dim('No stored credentials found.'))\n }\n })\n\n program\n .command('whoami')\n .description('Show current authentication status')\n .action(() => {\n // Check local credentials first\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const creds = localCreds || globalCreds\n const isLocal = !!localCreds\n\n if (!creds) {\n console.log(pc.dim('Not logged in. Run \"01 login\" to authenticate.'))\n return\n }\n\n const masked =\n creds.publishableKey.length > 8\n ? creds.publishableKey.slice(0, 4) + '...' + creds.publishableKey.slice(-4)\n : '****'\n\n const scope = isLocal ? pc.cyan(' (local)') : ''\n console.log(`Tenant: ${pc.bold(creds.tenantName)}${scope}`)\n console.log(`Publishable Key: ${pc.dim(masked)}`)\n console.log(`Stored at: ${pc.dim(creds.storedAt)}`)\n console.log(\n `File: ${pc.dim(isLocal ? getLocalCredentialsPath() : getCredentialsPath())}`,\n )\n })\n\n // -------------------------------------------------------------------------\n // tenant subcommands\n // -------------------------------------------------------------------------\n const tenant = program\n .command('tenant')\n .description('Manage tenant switching')\n\n tenant\n .command('list')\n .description('Show cached tenant list')\n .action(() => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.log(pc.dim('No cached tenants. Run \"01 login\" first.'))\n return\n }\n\n // Determine active tenant\n const localCreds = loadLocalCredentials()\n const globalCreds = loadCredentials()\n const activeCreds = localCreds || globalCreds\n const activeId = activeCreds?.tenantId\n const activeName = activeCreds?.tenantName\n\n console.log(pc.bold('Cached tenants:\\n'))\n for (const t of tenants) {\n const active = (activeId ? t.id === activeId : t.name === activeName)\n ? pc.green(' *')\n : ''\n console.log(` ${t.name}${active}`)\n }\n console.log()\n if (activeName) {\n const scope = localCreds ? '(local)' : '(global)'\n console.log(pc.dim(`* active ${scope}`))\n }\n })\n\n tenant\n .command('use <name>')\n .description('Switch to a different tenant via browser')\n .option('--local', 'Save credentials locally in the current project')\n .action(async (name: string, opts: { local?: boolean }) => {\n const tenants = loadTenantList()\n if (!tenants || tenants.length === 0) {\n console.error(pc.red('No cached tenants. Run \"01 login\" first.'))\n process.exit(2)\n }\n\n const match = tenants.find(\n (t) => t.name.toLowerCase() === name.toLowerCase(),\n )\n if (!match) {\n console.error(pc.red(`Tenant \"${name}\" not found in cache.`))\n console.error(\n pc.dim(`Available: ${tenants.map((t) => t.name).join(', ')}`),\n )\n process.exit(3)\n }\n\n const state = randomBytes(32).toString('hex')\n const isLocal = !!opts.local\n\n try {\n const { port } = await startAuthServer({\n state,\n saveFn: (creds) => {\n if (isLocal) {\n saveLocalCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getLocalCredentialsPath()}`),\n )\n } else {\n saveCredentials(creds)\n console.log(\n pc.dim(`Credentials saved to ${getCredentialsPath()}`),\n )\n }\n },\n })\n\n const params = new URLSearchParams({\n port: String(port),\n state,\n tenantId: match.id,\n })\n const loginUrl = `${WEB_URL}/cli-auth?${params.toString()}`\n\n console.log(pc.dim(`Switching to tenant \"${match.name}\"...`))\n console.log(pc.dim(`If the browser does not open, visit:\\n${loginUrl}`))\n openBrowser(loginUrl)\n } catch (err) {\n console.error(\n pc.red(\n `Server error: ${err instanceof Error ? err.message : String(err)}`,\n ),\n )\n process.exit(4)\n }\n })\n}\n","import { Command } from 'commander'\nimport { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { validateCollection } from '../lib/collections.js'\nimport { printResult, exitWithError } from '../lib/output.js'\n\nexport function registerSchemaCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const schema = program\n .command('schema')\n .description('Collection schema introspection')\n\n schema\n .command('list')\n .description('List available collections')\n .action(() => {\n printResult(SERVER_COLLECTIONS, getFormat())\n })\n\n schema\n .command('show <collection>')\n .description('Show collection field schema')\n .action(async (collection: string) => {\n try {\n const col = validateCollection(collection)\n const client = getClient()\n const result = await client.tenant.collectionSchema(col)\n printResult(result, getFormat())\n } catch (e) {\n exitWithError(e)\n }\n })\n}\n","import { Command } from 'commander'\nimport {\n tenantFeatureProgressInputSchema,\n tenantFeatureProgressResponseSchema,\n type TenantFeatureProgressResponse,\n} from '@01.software/contracts'\nimport type { ResolvedClient } from '../lib/client.js'\nimport { printResult, exitWithError } from '../lib/output.js'\nimport { parseWithSchema } from '../lib/parse.js'\n\nfunction flattenProgress(progress: TenantFeatureProgressResponse) {\n return progress.groups.flatMap((group) =>\n group.items.map((item) => ({\n group: group.title,\n item: item.title,\n state: item.state,\n severity: item.severity,\n summary: item.summary,\n })),\n )\n}\n\nexport function registerFeatureCommands(\n program: Command,\n getClient: () => ResolvedClient,\n getFormat: () => string,\n) {\n const feature = program\n .command('feature')\n .description('Feature implementation progress checks')\n\n feature\n .command('check <feature>')\n .description('Check tenant implementation progress for a feature')\n .option('--evidence', 'Include sanitized evidence counts and surface flags')\n .action(async (featureName: string, options: { evidence?: boolean }) => {\n try {\n const input = parseWithSchema(\n {\n feature: featureName,\n includeEvidence: Boolean(options.evidence),\n },\n 'feature',\n tenantFeatureProgressInputSchema,\n )\n const client = getClient()\n const result = tenantFeatureProgressResponseSchema.parse(\n await client.tenant.featureProgress(input),\n )\n const format = getFormat()\n printResult(\n format === 'table' ? flattenProgress(result) : result,\n format,\n )\n } catch (error) {\n exitWithError(error)\n }\n })\n}\n","import { Command, type CommanderError } from 'commander'\nimport { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport type { ResolvedClient } from '../lib/client.js'\nimport {\n getAgentPlanOperations,\n type AgentPlanOperation,\n} from '../lib/agent-plan-allowlist.js'\nimport {\n exitWithAgentError,\n printAgentSuccess,\n resolveAgentPrintOptions,\n validateAgentOutputTarget,\n} from '../lib/agent-output.js'\nimport {\n parseSelect,\n validateCollection,\n type CliCollection,\n} from '../lib/collections.js'\nimport {\n productDetailParamsFromOptions,\n type ProductDetailCliOptions,\n} from '../lib/product-detail-options.js'\nimport { registerAgentPlanCommands } from './agent-plan.js'\n\nconst AGENT_PROTOCOL_VERSION = '1'\n\ntype AgentReadOperation = 'query' | 'get' | 'detail'\ntype AgentPlanOperationName = `plan:${AgentPlanOperation}`\ntype AgentOperation = AgentReadOperation | AgentPlanOperationName\n\ntype AgentFieldName = 'id' | 'createdAt' | 'updatedAt'\n\ninterface AgentFieldMetadata {\n type: 'string'\n queryable: boolean\n}\n\ntype AgentFieldMap = Record<AgentFieldName, AgentFieldMetadata>\n\nexport interface AgentManifest {\n version: typeof AGENT_PROTOCOL_VERSION\n discovery: {\n context: {\n counts: boolean\n }\n schema: {\n mode: 'effective'\n }\n }\n collections: Record<\n CliCollection,\n {\n operations: readonly AgentOperation[]\n fields: AgentFieldMap\n }\n >\n}\n\nfunction buildStableAgentFields(): AgentFieldMap {\n return {\n id: { type: 'string', queryable: true },\n createdAt: { type: 'string', queryable: true },\n updatedAt: { type: 'string', queryable: true },\n }\n}\n\nfunction invalidInput(message: string, field: string, value?: unknown): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: 'invalid_argument',\n field,\n detail: { message, value, field },\n })\n return error\n}\n\nfunction parsePositiveInteger(\n value: string | undefined,\n field: 'limit' | 'page',\n): number | undefined {\n if (value == null) return undefined\n if (/^[1-9]\\d*$/.test(value)) return Number(value)\n throw invalidInput(`--${field} must be a positive integer`, field, value)\n}\n\nfunction handleCommanderError(error: CommanderError): never {\n if (error.code === 'commander.helpDisplayed') {\n process.exit(error.exitCode)\n }\n\n exitWithAgentError(invalidInput(error.message, 'command'))\n}\n\nfunction configureAgentParser(command: Command): Command {\n command.configureOutput({\n writeErr: () => {},\n writeOut: (str) => {\n process.stdout.write(str)\n },\n })\n command.exitOverride(handleCommanderError)\n return command\n}\n\nfunction parseWhere(\n value: string | undefined,\n): Record<string, unknown> | undefined {\n if (value == null) return undefined\n\n try {\n const parsed: unknown = JSON.parse(value)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>\n }\n } catch {\n throw invalidInput('--where must be a JSON object', 'where', value)\n }\n\n throw invalidInput('--where must be a JSON object', 'where', value)\n}\n\nconst AGENT_READ_OPERATIONS = [\n 'query',\n 'get',\n] as const satisfies readonly Exclude<AgentReadOperation, 'detail'>[]\nconst AGENT_PRODUCT_OPERATIONS = [\n 'detail',\n] as const satisfies readonly AgentReadOperation[]\nexport function buildAgentManifest(): AgentManifest {\n const collections = {} as AgentManifest['collections']\n for (const collection of SERVER_COLLECTIONS) {\n const operations: AgentOperation[] = [\n ...AGENT_READ_OPERATIONS,\n ...(collection === 'products' ? AGENT_PRODUCT_OPERATIONS : []),\n ...getAgentPlanOperations(collection).map(\n (operation): AgentPlanOperationName => `plan:${operation}`,\n ),\n ]\n collections[collection] = {\n operations,\n fields: buildStableAgentFields(),\n }\n }\n\n return {\n version: AGENT_PROTOCOL_VERSION,\n discovery: {\n context: { counts: true },\n schema: { mode: 'effective' },\n },\n collections,\n }\n}\n\nfunction validateAgentCollection(collection: string): CliCollection {\n try {\n return validateCollection(collection)\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : `Unknown collection \"${collection}\".`\n throw invalidInput(message, 'collection', collection)\n }\n}\n\nexport function registerAgentCommands(\n program: Command,\n getClient: () => ResolvedClient,\n): void {\n const agent = configureAgentParser(\n program\n .command('agent')\n .description('Machine-stable CLI namespace for coding agents')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .addHelpText(\n 'after',\n '\\nContract: docs/agent-cli-contract.md\\nJSON only on stdout; no TTY effects.',\n ),\n )\n\n configureAgentParser(\n agent\n .command('manifest')\n .description('Print the Agent CLI protocol manifest')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action((_opts: object, command: Command) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n printAgentSuccess(buildAgentManifest(), outputOptions)\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n }),\n )\n\n configureAgentParser(\n agent\n .command('context')\n .description('Get the active tenant context')\n .option('--counts', 'Include collection document counts')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(async (opts: { counts?: boolean }, command: Command) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n const client = getClient()\n const result = opts.counts\n ? await client.tenant.context({ includeCounts: true })\n : await client.tenant.context()\n printAgentSuccess(result, outputOptions)\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n }),\n )\n\n configureAgentParser(\n agent\n .command('schema <collection>')\n .description('Get the effective field schema for a collection')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(async (collection: string, _opts: object, command: Command) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n const col = validateAgentCollection(collection)\n const client = getClient()\n const result = await client.tenant.collectionSchema(col)\n printAgentSuccess(result, outputOptions)\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n }),\n )\n\n configureAgentParser(\n agent\n .command('query <collection>')\n .description('Query documents from a collection')\n .option('--where <json>', 'Filter conditions as a JSON object')\n .option('--limit <n>', 'Max results')\n .option('--page <n>', 'Page number')\n .option('--sort <field>', 'Sort field; prefix with - for descending')\n .option('--select <fields>', 'Comma-separated fields to select')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(\n async (\n collection: string,\n opts: {\n where?: string\n limit?: string\n page?: string\n sort?: string\n select?: string\n pretty?: boolean\n },\n command: Command,\n ) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n const col = validateAgentCollection(collection)\n const options: Record<string, unknown> = {}\n const where = parseWhere(opts.where)\n const limit = parsePositiveInteger(opts.limit, 'limit')\n const page = parsePositiveInteger(opts.page, 'page')\n\n if (where) options.where = where\n if (limit != null) options.limit = limit\n if (page != null) options.page = page\n if (opts.sort) options.sort = opts.sort\n if (opts.select) options.select = parseSelect(opts.select)\n\n const client = getClient()\n const result = await client.collections.from(col).find(options)\n printAgentSuccess(result, outputOptions)\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n },\n ),\n )\n\n configureAgentParser(\n agent\n .command('get <collection> [id]')\n .description('Get a document by ID')\n .option('--select <fields>', 'Comma-separated fields to select')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(\n async (\n collection: string,\n id: string | undefined,\n opts: { select?: string; pretty?: boolean },\n command: Command,\n ) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n const col = validateAgentCollection(collection)\n if (!id) {\n throw invalidInput('Missing required argument: id', 'id')\n }\n\n const options: Record<string, unknown> = {}\n if (opts.select) options.select = parseSelect(opts.select)\n\n const client = getClient()\n const result = await client.collections\n .from(col)\n .findById(id, options)\n printAgentSuccess(result, outputOptions)\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n },\n ),\n )\n\n const product = configureAgentParser(\n agent.command('product').description('Shaped product reads'),\n )\n\n configureAgentParser(\n product\n .command('detail')\n .description('Get shaped product detail by slug or ID')\n .option('--slug <slug>', 'Product slug')\n .option('--id <id>', 'Product ID')\n .option('--market <market>', 'Market slug')\n .option('--locale <locale>', 'Locale: ko, en, or all')\n .option('--fallback-locale <locale>', 'Fallback locale: ko, en, or none')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(\n async (\n opts: ProductDetailCliOptions & { pretty?: boolean },\n command: Command,\n ) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n const params = productDetailParamsFromOptions(opts)\n const client = getClient()\n const result = await client.commerce.product.detail(params)\n printAgentSuccess(result, outputOptions)\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n },\n ),\n )\n\n registerAgentPlanCommands(agent, getClient)\n}\n","import { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport { agentPlanError } from './agent-output.js'\n\nexport type AgentPlanOperation = 'create' | 'update' | 'delete'\ntype ServerCollection = (typeof SERVER_COLLECTIONS)[number]\n\nexport const AGENT_PLAN_CAPABILITIES = {\n articles: ['create', 'update', 'delete'],\n 'article-categories': ['create', 'update', 'delete'],\n 'article-tags': ['create', 'update', 'delete'],\n links: ['create', 'update', 'delete'],\n 'link-categories': ['create', 'update', 'delete'],\n 'link-tags': ['create', 'update', 'delete'],\n documents: ['create', 'update'],\n 'document-categories': ['create', 'update'],\n 'document-types': ['create', 'update'],\n canvases: ['create', 'update', 'delete'],\n 'canvas-categories': ['create', 'update', 'delete'],\n 'canvas-tags': ['create', 'update', 'delete'],\n} as const satisfies Partial<\n Record<ServerCollection, readonly AgentPlanOperation[]>\n>\n\nexport type AgentPlanCollection = keyof typeof AGENT_PLAN_CAPABILITIES\n\nconst SERVER_COLLECTION_SET = new Set<string>(SERVER_COLLECTIONS)\nconst AGENT_PLAN_OPERATIONS = new Set<AgentPlanOperation>([\n 'create',\n 'update',\n 'delete',\n])\n\nexport function assertAgentPlanCapabilityMatrix(\n matrix: Readonly<Record<string, readonly string[]>>,\n): void {\n for (const [collection, operations] of Object.entries(matrix)) {\n if (!SERVER_COLLECTION_SET.has(collection)) {\n throw new Error(\n `Agent plan capability collection \"${collection}\" is not a ServerCollection.`,\n )\n }\n if (operations.length === 0) {\n throw new Error(\n `Agent plan capability collection \"${collection}\" has no operations.`,\n )\n }\n\n const seen = new Set<string>()\n for (const operation of operations) {\n if (!AGENT_PLAN_OPERATIONS.has(operation as AgentPlanOperation)) {\n throw new Error(\n `Agent plan capability operation \"${operation}\" is invalid for \"${collection}\".`,\n )\n }\n if (seen.has(operation)) {\n throw new Error(\n `Agent plan capability operation \"${operation}\" is duplicated for \"${collection}\".`,\n )\n }\n seen.add(operation)\n }\n }\n}\n\nassertAgentPlanCapabilityMatrix(AGENT_PLAN_CAPABILITIES)\n\nexport function isAgentPlanCollection(\n collection: string,\n): collection is AgentPlanCollection {\n return Object.prototype.hasOwnProperty.call(\n AGENT_PLAN_CAPABILITIES,\n collection,\n )\n}\n\nexport function assertAgentPlanCollection(\n collection: string,\n): AgentPlanCollection {\n if (isAgentPlanCollection(collection)) {\n return collection\n }\n throw agentPlanError(\n 'UNSUPPORTED_OPERATION',\n `Collection \"${collection}\" is not supported for agent plan mutations.`,\n )\n}\n\nexport function getAgentPlanOperations(\n collection: ServerCollection,\n): readonly AgentPlanOperation[] {\n return isAgentPlanCollection(collection)\n ? AGENT_PLAN_CAPABILITIES[collection]\n : []\n}\n\nexport function isAgentPlanCapability(\n collection: string,\n operation: string,\n): collection is AgentPlanCollection {\n if (!isAgentPlanCollection(collection)) return false\n return (AGENT_PLAN_CAPABILITIES[collection] as readonly string[]).includes(\n operation,\n )\n}\n\nexport function assertAgentPlanCapability(\n collection: string,\n operation: AgentPlanOperation,\n): AgentPlanCollection {\n if (isAgentPlanCapability(collection, operation)) {\n return collection\n }\n throw agentPlanError(\n 'UNSUPPORTED_OPERATION',\n `Operation \"${operation}\" is not supported for collection \"${collection}\" in agent plan mutations.`,\n )\n}\n\nexport function assertAgentPlanOperation(\n operation: string,\n): AgentPlanOperation {\n if (AGENT_PLAN_OPERATIONS.has(operation as AgentPlanOperation)) {\n return operation as AgentPlanOperation\n }\n throw agentPlanError(\n 'UNSUPPORTED_OPERATION',\n `Operation \"${operation}\" is not supported for agent plan mutations.`,\n )\n}\n","import { randomBytes } from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { Command } from 'commander'\nimport { classifyError } from './admin-error.js'\n\nexport type AgentErrorCode =\n | 'INVALID_INPUT'\n | 'AUTH_FAILED'\n | 'NOT_FOUND'\n | 'INTERNAL'\n | 'PLAN_EXPIRED'\n | 'PLAN_MISMATCH'\n | 'PLAN_STALE'\n | 'UNSUPPORTED_OPERATION'\n\nconst PLAN_AGENT_ERROR_CODES: ReadonlySet<AgentErrorCode> = new Set([\n 'PLAN_EXPIRED',\n 'PLAN_MISMATCH',\n 'PLAN_STALE',\n 'UNSUPPORTED_OPERATION',\n])\n\nexport function agentPlanError(\n code:\n | 'PLAN_EXPIRED'\n | 'PLAN_MISMATCH'\n | 'PLAN_STALE'\n | 'UNSUPPORTED_OPERATION'\n | 'INVALID_INPUT',\n message: string,\n): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: code.toLowerCase(),\n agentCode: code,\n detail: { message, agentCode: code },\n })\n return error\n}\n\nexport interface AgentErrorEnvelope {\n error: {\n code: AgentErrorCode\n message: string\n retryable: boolean\n retryAfter?: number\n }\n}\n\nexport interface AgentPrintOptions {\n pretty?: boolean\n outputFile?: string\n}\n\ninterface AgentCommandOutputOptions {\n pretty?: boolean\n outputFile?: string\n}\n\ninterface AgentOutputReceipt {\n outputFile: string\n bytes: number\n}\n\nconst AGENT_OUTPUT_FILE_MODE = 0o600\nconst isWin32 = process.platform === 'win32'\n\nfunction stringifyAgentJson(\n data: unknown,\n options: AgentPrintOptions = {},\n): string {\n return options.pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data)\n}\n\nfunction invalidOutputTarget(message: string, outputFile: string): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: 'invalid_argument',\n field: 'outputFile',\n detail: { message, field: 'outputFile', value: outputFile },\n })\n return error\n}\n\nfunction assertSafeAgentOutputTarget(outputFile: string): void {\n let stat: fs.Stats\n try {\n stat = fs.lstatSync(outputFile)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n\n if (stat.isSymbolicLink()) {\n throw invalidOutputTarget(\n `Refusing to write Agent output through a symlink: ${outputFile}.`,\n outputFile,\n )\n }\n if (!stat.isFile()) {\n throw invalidOutputTarget(\n `Refusing to write Agent output to a non-regular file: ${outputFile}.`,\n outputFile,\n )\n }\n if (!isWin32 && stat.nlink > 1) {\n throw invalidOutputTarget(\n `Refusing to write Agent output to a file with multiple hard links: ${outputFile}.`,\n outputFile,\n )\n }\n}\n\nfunction writeAgentOutputFile(\n requestedPath: string,\n content: string,\n): AgentOutputReceipt {\n const outputFile = path.resolve(requestedPath)\n assertSafeAgentOutputTarget(outputFile)\n\n const tempFile = path.join(\n path.dirname(outputFile),\n `.${path.basename(outputFile)}.${randomBytes(12).toString('hex')}.tmp`,\n )\n let tempFd: number | undefined\n\n try {\n tempFd = fs.openSync(tempFile, 'wx', AGENT_OUTPUT_FILE_MODE)\n if (!isWin32) {\n fs.fchmodSync(tempFd, AGENT_OUTPUT_FILE_MODE)\n }\n fs.writeFileSync(tempFd, content, { encoding: 'utf8' })\n fs.closeSync(tempFd)\n tempFd = undefined\n fs.renameSync(tempFile, outputFile)\n } catch (error) {\n if (tempFd !== undefined) {\n try {\n fs.closeSync(tempFd)\n } catch {\n // Best-effort descriptor cleanup after a failed temp write.\n }\n }\n try {\n fs.unlinkSync(tempFile)\n } catch {\n // Best-effort cleanup after a failed temp write or atomic rename.\n }\n throw error\n }\n\n return {\n outputFile,\n bytes: Buffer.byteLength(content, 'utf8'),\n }\n}\n\nexport function resolveAgentPrintOptions(command: Command): AgentPrintOptions {\n const options = command.optsWithGlobals<AgentCommandOutputOptions>()\n return {\n pretty: Boolean(options.pretty),\n outputFile: options.outputFile,\n }\n}\n\nexport function validateAgentOutputTarget(options: AgentPrintOptions): void {\n if (options.outputFile !== undefined) {\n assertSafeAgentOutputTarget(path.resolve(options.outputFile))\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return value && typeof value === 'object'\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction errorMessage(error: unknown): string {\n const raw = asRecord(error)\n if (raw) {\n if (typeof raw.message === 'string' && raw.message.length > 0) {\n return raw.message\n }\n if (\n raw.detail &&\n typeof raw.detail === 'object' &&\n typeof (raw.detail as Record<string, unknown>).message === 'string'\n ) {\n return String((raw.detail as Record<string, unknown>).message)\n }\n }\n if (error instanceof Error && error.message.length > 0) {\n return error.message\n }\n if (typeof error === 'string' && error.length > 0) {\n return error\n }\n return 'Internal error'\n}\n\nfunction isRawNotFound(error: unknown): boolean {\n const raw = asRecord(error)\n return (\n raw?.status === 404 ||\n raw?.code === 'not_found' ||\n raw?.name === 'GoneError'\n )\n}\n\nfunction isSdkUsageLimitError(error: unknown): boolean {\n const raw = asRecord(error)\n return raw?.name === 'UsageLimitError' || raw?.code === 'USAGE_LIMIT_ERROR'\n}\n\nfunction agentErrorEnvelope(\n code: AgentErrorCode,\n message: string,\n retryable: boolean,\n retryAfter?: number,\n): AgentErrorEnvelope {\n return {\n error: {\n code,\n message,\n retryable,\n ...(typeof retryAfter === 'number' ? { retryAfter } : {}),\n },\n }\n}\n\nexport function agentErrorExitCode(code: AgentErrorCode): number {\n switch (code) {\n case 'INVALID_INPUT':\n case 'PLAN_EXPIRED':\n case 'PLAN_MISMATCH':\n case 'PLAN_STALE':\n case 'UNSUPPORTED_OPERATION':\n return 2\n case 'AUTH_FAILED':\n return 3\n case 'NOT_FOUND':\n return 4\n case 'INTERNAL':\n return 1\n }\n}\n\nexport function classifyAgentError(error: unknown): AgentErrorEnvelope {\n const raw = asRecord(error)\n const message = errorMessage(error)\n const detail = raw?.detail\n const detailRecord =\n detail && typeof detail === 'object'\n ? (detail as Record<string, unknown>)\n : null\n const agentCode = raw?.agentCode ?? detailRecord?.agentCode\n if (\n typeof agentCode === 'string' &&\n PLAN_AGENT_ERROR_CODES.has(agentCode as AgentErrorCode)\n ) {\n return agentErrorEnvelope(agentCode as AgentErrorCode, message, false)\n }\n\n const adminError = classifyError(error)\n\n if (isRawNotFound(error) || adminError.code === 'not_found') {\n return agentErrorEnvelope('NOT_FOUND', message, false)\n }\n\n if (adminError.type === 'permission') {\n return agentErrorEnvelope('AUTH_FAILED', message, false)\n }\n\n if (adminError.type === 'validation' && adminError.code !== 'unknown') {\n return agentErrorEnvelope('INVALID_INPUT', message, false)\n }\n\n const retryable =\n !isSdkUsageLimitError(error) &&\n (adminError.type === 'network' || adminError.type === 'degraded')\n const retryAfter =\n retryable &&\n adminError.type === 'degraded' &&\n adminError.code === 'rate_limited'\n ? adminError.retryAfter\n : undefined\n\n return agentErrorEnvelope('INTERNAL', message, retryable, retryAfter)\n}\n\nexport function printAgentSuccess(\n data: unknown,\n options: AgentPrintOptions = {},\n): void {\n const output = stringifyAgentJson(data, options)\n if (options.outputFile !== undefined) {\n const receipt = writeAgentOutputFile(options.outputFile, output)\n console.log(JSON.stringify(receipt))\n return\n }\n console.log(output)\n}\n\nexport function printAgentError(\n error: unknown,\n options: AgentPrintOptions = {},\n): AgentErrorEnvelope {\n const envelope = classifyAgentError(error)\n console.log(stringifyAgentJson(envelope, options))\n return envelope\n}\n\nexport function exitWithAgentError(\n error: unknown,\n options: AgentPrintOptions = {},\n): never {\n const envelope = printAgentError(error, options)\n process.exit(agentErrorExitCode(envelope.error.code))\n}\n","import { createHash } from 'node:crypto'\n\nexport function buildAuthContextFingerprint(input: {\n publishableKey: string\n secretKey: string\n apiUrl?: string\n tenantId?: string\n}): string {\n const apiUrl =\n input.apiUrl ??\n process.env.SOFTWARE_API_URL ??\n process.env.NEXT_PUBLIC_SOFTWARE_API_URL ??\n ''\n const tenantId = input.tenantId ?? process.env.SOFTWARE_TENANT_ID ?? ''\n const secretDigest = createHash('sha256').update(input.secretKey).digest('hex')\n const material = [input.publishableKey, secretDigest, apiUrl, tenantId].join('\\n')\n return createHash('sha256').update(material).digest('hex')\n}\n","import { mkdir, open, readFile, unlink, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\nimport {\n isAgentPlanCapability,\n isAgentPlanCollection,\n type AgentPlanCollection,\n type AgentPlanOperation,\n} from './agent-plan-allowlist.js'\nimport { hashAgentPlanEnvelope } from './agent-plan-hash.js'\nimport { assertValidPlanId, safePlanPath } from './agent-plan-id.js'\nimport { agentPlanError } from './agent-output.js'\n\nexport const AGENT_PLAN_TTL_MS = 15 * 60 * 1000\n\nexport type AgentPlanStatus = 'pending' | 'claimed' | 'consumed'\n\nexport interface StoredAgentPlan {\n planId: string\n planHash: string\n operation: AgentPlanOperation\n collection: AgentPlanCollection\n documentId?: string\n payload?: Record<string, unknown>\n baseUpdatedAt?: string\n authFingerprint: string\n createdAt: string\n expiresAt: string\n status: AgentPlanStatus\n}\n\nexport function resolveAgentPlanDir(): string {\n const override = process.env.SOFTWARE_AGENT_PLAN_DIR?.trim()\n if (override) {\n return override\n }\n return join(homedir(), '.01software', 'agent-plans')\n}\n\nfunction parseExpiresAtMs(expiresAt: string): number {\n const ms = Date.parse(expiresAt)\n if (!Number.isFinite(ms)) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has invalid expiresAt.')\n }\n return ms\n}\n\nfunction parseStoredAgentPlan(raw: unknown, planId: string): StoredAgentPlan {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan is corrupted.')\n }\n const record = raw as Record<string, unknown>\n if (record.planId !== planId) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan id does not match token.')\n }\n if (\n typeof record.planHash !== 'string' ||\n typeof record.operation !== 'string' ||\n typeof record.collection !== 'string' ||\n typeof record.authFingerprint !== 'string' ||\n typeof record.createdAt !== 'string' ||\n typeof record.expiresAt !== 'string' ||\n typeof record.status !== 'string'\n ) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan is missing required fields.')\n }\n if (\n record.status !== 'pending' &&\n record.status !== 'claimed' &&\n record.status !== 'consumed'\n ) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has invalid status.')\n }\n\n if (!isAgentPlanCollection(record.collection)) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has unsupported collection.')\n }\n const collection = record.collection\n const operation = record.operation\n if (operation !== 'create' && operation !== 'update' && operation !== 'delete') {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan has invalid operation.')\n }\n if (!isAgentPlanCapability(collection, operation)) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Stored plan has unsupported collection operation.',\n )\n }\n\n const payload =\n record.payload == null\n ? undefined\n : typeof record.payload === 'object' && !Array.isArray(record.payload)\n ? (record.payload as Record<string, unknown>)\n : (() => {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan payload is invalid.')\n })()\n\n const documentId =\n record.documentId == null\n ? undefined\n : typeof record.documentId === 'string'\n ? record.documentId\n : (() => {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan documentId is invalid.')\n })()\n\n const baseUpdatedAt =\n record.baseUpdatedAt == null\n ? undefined\n : typeof record.baseUpdatedAt === 'string'\n ? record.baseUpdatedAt\n : (() => {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan baseUpdatedAt is invalid.')\n })()\n\n return {\n planId,\n planHash: record.planHash,\n operation,\n collection,\n documentId,\n payload,\n baseUpdatedAt,\n authFingerprint: record.authFingerprint,\n createdAt: record.createdAt,\n expiresAt: record.expiresAt,\n status: record.status,\n }\n}\n\nexport function assertStoredPlanHashMatches(plan: StoredAgentPlan): void {\n if (!isAgentPlanCapability(plan.collection, plan.operation)) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Stored plan has unsupported collection operation.',\n )\n }\n const expected = hashAgentPlanEnvelope({\n operation: plan.operation,\n collection: plan.collection,\n documentId: plan.documentId,\n payload: plan.payload,\n })\n if (plan.planHash !== expected) {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan hash does not match plan contents.')\n }\n}\n\nfunction assertPlanNotExpired(plan: StoredAgentPlan): void {\n if (Date.now() > parseExpiresAtMs(plan.expiresAt)) {\n throw agentPlanError('PLAN_EXPIRED', 'Plan expired.')\n }\n}\n\nasync function readAgentPlanFile(\n planDir: string,\n planId: string,\n): Promise<StoredAgentPlan> {\n assertValidPlanId(planId)\n let raw: string\n try {\n raw = await readFile(safePlanPath(planDir, planId), 'utf8')\n } catch {\n throw agentPlanError('PLAN_MISMATCH', 'Plan not found.')\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw agentPlanError('PLAN_MISMATCH', 'Stored plan is corrupted.')\n }\n\n return parseStoredAgentPlan(parsed, planId)\n}\n\nasync function writeAgentPlanFile(\n planDir: string,\n plan: StoredAgentPlan,\n): Promise<void> {\n await writeFile(safePlanPath(planDir, plan.planId), JSON.stringify(plan), {\n encoding: 'utf8',\n mode: 0o600,\n })\n}\n\nexport async function writeAgentPlan(input: {\n planDir: string\n record: Omit<StoredAgentPlan, 'planId' | 'status'> & { planId?: string }\n}): Promise<StoredAgentPlan> {\n await mkdir(input.planDir, { recursive: true, mode: 0o700 })\n const planId = input.record.planId ?? randomUUID()\n assertValidPlanId(planId)\n const plan: StoredAgentPlan = {\n ...input.record,\n planId,\n status: 'pending',\n }\n assertStoredPlanHashMatches(plan)\n await writeAgentPlanFile(input.planDir, plan)\n return plan\n}\n\nexport async function claimAgentPlan(input: {\n planDir: string\n planId: string\n planHash: string\n authFingerprint: string\n}): Promise<StoredAgentPlan> {\n assertValidPlanId(input.planId)\n const planPath = safePlanPath(input.planDir, input.planId)\n const lockPath = `${planPath}.lock`\n let lockHandle: Awaited<ReturnType<typeof open>> | undefined\n\n try {\n lockHandle = await open(lockPath, 'wx', 0o600)\n } catch {\n throw agentPlanError('PLAN_MISMATCH', 'Plan was already claimed or consumed.')\n }\n\n try {\n const plan = await readAgentPlanFile(input.planDir, input.planId)\n assertPlanNotExpired(plan)\n assertStoredPlanHashMatches(plan)\n\n if (plan.planHash !== input.planHash) {\n throw agentPlanError('PLAN_MISMATCH', 'Plan hash does not match stored plan.')\n }\n\n if (plan.authFingerprint !== input.authFingerprint) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Plan auth context does not match current credentials.',\n )\n }\n\n if (plan.status !== 'pending') {\n throw agentPlanError('PLAN_MISMATCH', 'Plan was already claimed or consumed.')\n }\n\n const claimed: StoredAgentPlan = { ...plan, status: 'claimed' }\n await writeAgentPlanFile(input.planDir, claimed)\n return claimed\n } finally {\n if (lockHandle) {\n await lockHandle.close().catch(() => {})\n }\n await unlink(lockPath).catch(() => {})\n }\n}\n\nexport async function releaseAgentPlanClaim(input: {\n planDir: string\n planId: string\n}): Promise<void> {\n const plan = await readAgentPlanFile(input.planDir, input.planId)\n if (plan.status !== 'claimed') {\n return\n }\n await writeAgentPlanFile(input.planDir, { ...plan, status: 'pending' })\n}\n\nexport async function markAgentPlanConsumed(input: {\n planDir: string\n planId: string\n}): Promise<void> {\n const plan = await readAgentPlanFile(input.planDir, input.planId)\n await writeAgentPlanFile(input.planDir, { ...plan, status: 'consumed' })\n}\n","import { createHash } from 'node:crypto'\nimport type {\n AgentPlanCollection,\n AgentPlanOperation,\n} from './agent-plan-allowlist.js'\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeys)\n }\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = sortKeys((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nexport function hashPlanPayload(payload: unknown): string {\n const canonical = JSON.stringify(sortKeys(payload))\n return createHash('sha256').update(canonical).digest('hex')\n}\n\nexport interface AgentPlanHashInput {\n operation: AgentPlanOperation\n collection: AgentPlanCollection\n documentId?: string\n payload?: Record<string, unknown>\n}\n\nexport function hashAgentPlanEnvelope(input: AgentPlanHashInput): string {\n return hashPlanPayload({\n operation: input.operation,\n collection: input.collection,\n documentId: input.documentId,\n payload: input.payload,\n })\n}\n","import { resolve, sep } from 'node:path'\nimport { agentPlanError } from './agent-output.js'\n\nconst PLAN_ID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\nexport function assertValidPlanId(planId: string): void {\n if (!PLAN_ID_PATTERN.test(planId)) {\n throw agentPlanError('INVALID_INPUT', 'Invalid plan token.')\n }\n}\n\nexport function safePlanPath(planDir: string, planId: string): string {\n assertValidPlanId(planId)\n const resolvedDir = resolve(planDir)\n const resolvedPath = resolve(resolvedDir, `${planId}.json`)\n if (\n resolvedPath !== resolvedDir &&\n !resolvedPath.startsWith(`${resolvedDir}${sep}`)\n ) {\n throw agentPlanError('INVALID_INPUT', 'Invalid plan token.')\n }\n return resolvedPath\n}\n","import type { AgentPlanOperation } from './agent-plan-allowlist.js'\nimport { agentPlanError } from './agent-output.js'\n\nexport function readDocumentUpdatedAt(doc: unknown): string | undefined {\n if (!doc || typeof doc !== 'object') {\n return undefined\n }\n const updatedAt = (doc as Record<string, unknown>).updatedAt\n return typeof updatedAt === 'string' && updatedAt.length > 0\n ? updatedAt\n : undefined\n}\n\nexport function assertPlanBaseUpdatedAt(\n operation: AgentPlanOperation,\n baseUpdatedAt: string | undefined,\n): void {\n if (operation === 'create') {\n return\n }\n if (!baseUpdatedAt) {\n throw agentPlanError(\n 'INVALID_INPUT',\n 'Document is missing updatedAt; cannot plan update or delete.',\n )\n }\n}\n\nexport async function assertPlanNotStale(input: {\n operation: AgentPlanOperation\n baseUpdatedAt?: string\n currentUpdatedAt?: string\n}): Promise<void> {\n if (input.operation === 'create') {\n return\n }\n if (!input.baseUpdatedAt || !input.currentUpdatedAt) {\n throw agentPlanError(\n 'PLAN_STALE',\n 'Document is missing updatedAt for stale check.',\n )\n }\n if (input.baseUpdatedAt !== input.currentUpdatedAt) {\n throw agentPlanError(\n 'PLAN_STALE',\n 'Document changed since the plan was created.',\n )\n }\n}\n","import type { ResolvedClient } from './client.js'\nimport { agentPlanError } from './agent-output.js'\nimport type { StoredAgentPlan } from './agent-plan-store.js'\nimport {\n markAgentPlanConsumed,\n resolveAgentPlanDir,\n} from './agent-plan-store.js'\nimport {\n assertPlanNotStale,\n readDocumentUpdatedAt,\n} from './agent-plan-stale.js'\n\nexport async function executeAgentPlanMutation(\n client: ResolvedClient,\n plan: StoredAgentPlan,\n): Promise<unknown> {\n const collection = client.collections.from(plan.collection)\n\n if (plan.operation === 'create') {\n const response = await collection.create(plan.payload ?? {})\n return response.doc\n }\n\n if (!plan.documentId) {\n throw agentPlanError('PLAN_MISMATCH', 'Plan is missing document id.')\n }\n\n if (plan.operation === 'update') {\n const current = await collection.findById(plan.documentId)\n await assertPlanNotStale({\n operation: plan.operation,\n baseUpdatedAt: plan.baseUpdatedAt,\n currentUpdatedAt: readDocumentUpdatedAt(current),\n })\n const response = await collection.update(plan.documentId, plan.payload ?? {})\n return response.doc\n }\n\n const current = await collection.findById(plan.documentId)\n await assertPlanNotStale({\n operation: plan.operation,\n baseUpdatedAt: plan.baseUpdatedAt,\n currentUpdatedAt: readDocumentUpdatedAt(current),\n })\n return collection.remove(plan.documentId)\n}\n\nexport async function finalizeAgentPlan(plan: StoredAgentPlan): Promise<void> {\n await markAgentPlanConsumed({\n planDir: resolveAgentPlanDir(),\n planId: plan.planId,\n })\n}\n","import { readFileSync } from 'node:fs'\nimport { stdin } from 'node:process'\nimport { agentPlanError } from './agent-output.js'\n\nasync function readStdinUtf8(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n }\n return Buffer.concat(chunks).toString('utf8')\n}\n\nexport async function readAgentPlanPayload(opts: {\n dataStdin?: boolean\n dataFile?: string\n}): Promise<Record<string, unknown>> {\n const sourceCount = [opts.dataStdin, opts.dataFile].filter(Boolean).length\n if (sourceCount !== 1) {\n throw agentPlanError(\n 'INVALID_INPUT',\n 'Exactly one of --data-stdin or --data-file is required.',\n )\n }\n\n let raw: string\n try {\n raw = opts.dataStdin\n ? await readStdinUtf8()\n : readFileSync(opts.dataFile!, 'utf8')\n } catch {\n throw agentPlanError(\n 'INVALID_INPUT',\n 'Mutation data file could not be read.',\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n throw agentPlanError('INVALID_INPUT', 'Mutation data must be valid JSON.')\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw agentPlanError('INVALID_INPUT', 'Mutation data must be a JSON object.')\n }\n\n return parsed as Record<string, unknown>\n}\n","import { agentPlanError } from './agent-output.js'\n\nconst SECRET_KEY =\n /(?:^|_)(?:secret|password|token|api[_-]?key|private[_-]?key|credential)(?:$|_)/i\n\nfunction isSecretFieldName(key: string): boolean {\n if (SECRET_KEY.test(key)) {\n return true\n }\n const snake = key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()\n return SECRET_KEY.test(snake)\n}\n\nexport function assertNoSecretFields(value: unknown, path = ''): void {\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n assertNoSecretFields(item, `${path}[${index}]`)\n })\n return\n }\n\n if (!value || typeof value !== 'object') {\n return\n }\n\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const fieldPath = path ? `${path}.${key}` : key\n if (isSecretFieldName(key)) {\n throw agentPlanError(\n 'INVALID_INPUT',\n `Secret-looking field \"${fieldPath}\" is not allowed in agent mutation payloads.`,\n )\n }\n assertNoSecretFields(child, fieldPath)\n }\n}\n","import { assertValidPlanId } from './agent-plan-id.js'\nimport { agentPlanError } from './agent-output.js'\n\nexport interface AgentPlanToken {\n planId: string\n planHash: string\n expiresAt: string\n}\n\nexport function encodePlanToken(token: AgentPlanToken): string {\n return Buffer.from(JSON.stringify(token), 'utf8').toString('base64url')\n}\n\nexport function decodePlanToken(raw: string): AgentPlanToken {\n try {\n const parsed: unknown = JSON.parse(\n Buffer.from(raw, 'base64url').toString('utf8'),\n )\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('invalid token')\n }\n const record = parsed as Record<string, unknown>\n if (\n typeof record.planId !== 'string' ||\n typeof record.planHash !== 'string' ||\n typeof record.expiresAt !== 'string'\n ) {\n throw new Error('invalid token fields')\n }\n assertValidPlanId(record.planId)\n return {\n planId: record.planId,\n planHash: record.planHash,\n expiresAt: record.expiresAt,\n }\n } catch {\n throw agentPlanError('INVALID_INPUT', 'Invalid plan token.')\n }\n}\n\nexport function buildConfirmCommand(planToken: string, planHash: string): string {\n return `01 agent confirm ${planToken} --hash ${planHash}`\n}\n","import { Command, type CommanderError } from 'commander'\nimport type { ResolvedClient } from '../lib/client.js'\nimport {\n assertAgentPlanCapability,\n type AgentPlanOperation,\n} from '../lib/agent-plan-allowlist.js'\nimport { buildAuthContextFingerprint } from '../lib/agent-plan-auth.js'\nimport {\n executeAgentPlanMutation,\n finalizeAgentPlan,\n} from '../lib/agent-plan-confirm.js'\nimport { hashAgentPlanEnvelope } from '../lib/agent-plan-hash.js'\nimport { readAgentPlanPayload } from '../lib/agent-plan-payload.js'\nimport { assertNoSecretFields } from '../lib/agent-plan-secrets.js'\nimport {\n AGENT_PLAN_TTL_MS,\n claimAgentPlan,\n releaseAgentPlanClaim,\n resolveAgentPlanDir,\n writeAgentPlan,\n} from '../lib/agent-plan-store.js'\nimport {\n assertPlanBaseUpdatedAt,\n readDocumentUpdatedAt,\n} from '../lib/agent-plan-stale.js'\nimport {\n buildConfirmCommand,\n decodePlanToken,\n encodePlanToken,\n} from '../lib/agent-plan-token.js'\nimport {\n agentPlanError,\n exitWithAgentError,\n printAgentSuccess,\n resolveAgentPrintOptions,\n validateAgentOutputTarget,\n type AgentPrintOptions,\n} from '../lib/agent-output.js'\n\nfunction invalidInput(message: string, field: string): Error {\n const error = new Error(message)\n Object.assign(error, {\n type: 'validation',\n code: 'invalid_argument',\n field,\n detail: { message, field },\n })\n return error\n}\n\nfunction handleCommanderError(error: CommanderError): never {\n if (error.code === 'commander.helpDisplayed') {\n process.exit(error.exitCode)\n }\n exitWithAgentError(invalidInput(error.message, 'command'))\n}\n\nfunction configureAgentParser(command: Command): Command {\n command.configureOutput({\n writeErr: () => {},\n writeOut: (str) => {\n process.stdout.write(str)\n },\n })\n command.exitOverride(handleCommanderError)\n return command\n}\n\nasync function captureBaseUpdatedAt(\n client: ResolvedClient,\n collection: ReturnType<typeof assertAgentPlanCapability>,\n documentId: string,\n): Promise<string | undefined> {\n const doc = await client.collections.from(collection).findById(documentId)\n return readDocumentUpdatedAt(doc)\n}\n\nasync function runPlanAction(input: {\n operation: AgentPlanOperation\n collection: string\n documentId?: string\n dataStdin?: boolean\n dataFile?: string\n outputOptions: AgentPrintOptions\n getClient: () => ResolvedClient\n}): Promise<void> {\n const collection = assertAgentPlanCapability(\n input.collection,\n input.operation,\n )\n\n if (input.operation !== 'create' && !input.documentId) {\n throw invalidInput('Missing required argument: id', 'id')\n }\n\n let payload: Record<string, unknown> | undefined\n if (input.operation === 'create' || input.operation === 'update') {\n payload = await readAgentPlanPayload({\n dataStdin: input.dataStdin,\n dataFile: input.dataFile,\n })\n assertNoSecretFields(payload)\n }\n\n const client = input.getClient()\n const authFingerprint = buildAuthContextFingerprint({\n publishableKey: client.publishableKey,\n secretKey: client.secretKey,\n })\n\n let baseUpdatedAt: string | undefined\n if (input.operation !== 'create' && input.documentId) {\n baseUpdatedAt = await captureBaseUpdatedAt(\n client,\n collection,\n input.documentId,\n )\n assertPlanBaseUpdatedAt(input.operation, baseUpdatedAt)\n }\n\n const planHash = hashAgentPlanEnvelope({\n operation: input.operation,\n collection,\n documentId: input.documentId,\n payload,\n })\n\n const createdAt = new Date()\n const expiresAt = new Date(createdAt.getTime() + AGENT_PLAN_TTL_MS)\n\n const stored = await writeAgentPlan({\n planDir: resolveAgentPlanDir(),\n record: {\n planHash,\n operation: input.operation,\n collection,\n documentId: input.documentId,\n payload,\n baseUpdatedAt,\n authFingerprint,\n createdAt: createdAt.toISOString(),\n expiresAt: expiresAt.toISOString(),\n },\n })\n\n const planToken = encodePlanToken({\n planId: stored.planId,\n planHash: stored.planHash,\n expiresAt: stored.expiresAt,\n })\n\n printAgentSuccess(\n {\n planToken,\n planHash: stored.planHash,\n planId: stored.planId,\n expiresAt: stored.expiresAt,\n operation: stored.operation,\n collection: stored.collection,\n documentId: stored.documentId,\n confirmCommand: buildConfirmCommand(planToken, stored.planHash),\n },\n input.outputOptions,\n )\n}\n\nexport function registerAgentPlanCommands(\n agent: Command,\n getClient: () => ResolvedClient,\n): void {\n const plan = configureAgentParser(\n agent.command('plan').description('Plan a mutation without executing'),\n )\n\n configureAgentParser(\n plan\n .command('create <collection>')\n .description('Plan a document create')\n .option('--data-stdin', 'Read mutation JSON from stdin')\n .option('--data-file <path>', 'Read mutation JSON from file')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(\n async (\n collection: string,\n opts: { dataStdin?: boolean; dataFile?: string; pretty?: boolean },\n command: Command,\n ) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n await runPlanAction({\n operation: 'create',\n collection,\n dataStdin: opts.dataStdin,\n dataFile: opts.dataFile,\n outputOptions,\n getClient,\n })\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n },\n ),\n )\n\n configureAgentParser(\n plan\n .command('update <collection> <id>')\n .description('Plan a document update')\n .option('--data-stdin', 'Read mutation JSON from stdin')\n .option('--data-file <path>', 'Read mutation JSON from file')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(\n async (\n collection: string,\n id: string,\n opts: { dataStdin?: boolean; dataFile?: string; pretty?: boolean },\n command: Command,\n ) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n await runPlanAction({\n operation: 'update',\n collection,\n documentId: id,\n dataStdin: opts.dataStdin,\n dataFile: opts.dataFile,\n outputOptions,\n getClient,\n })\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n },\n ),\n )\n\n configureAgentParser(\n plan\n .command('delete <collection> <id>')\n .description('Plan a document delete')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(\n async (\n collection: string,\n id: string,\n opts: { pretty?: boolean },\n command: Command,\n ) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n await runPlanAction({\n operation: 'delete',\n collection,\n documentId: id,\n outputOptions,\n getClient,\n })\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n },\n ),\n )\n\n configureAgentParser(\n agent\n .command('confirm <planToken>')\n .description('Execute a previously planned mutation')\n .requiredOption('--hash <planHash>', 'Plan hash from plan output')\n .option('--pretty', 'Print 2-space indented success JSON')\n .option(\n '--output-file <path>',\n 'Write success JSON to a secure file and print a receipt',\n )\n .action(\n async (\n planTokenRaw: string,\n opts: { hash: string; pretty?: boolean },\n command: Command,\n ) => {\n const outputOptions = resolveAgentPrintOptions(command)\n try {\n validateAgentOutputTarget(outputOptions)\n const token = decodePlanToken(planTokenRaw)\n if (token.planHash !== opts.hash) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Plan token does not match --hash.',\n )\n }\n\n const client = getClient()\n const authFingerprint = buildAuthContextFingerprint({\n publishableKey: client.publishableKey,\n secretKey: client.secretKey,\n })\n\n const planDir = resolveAgentPlanDir()\n const plan = await claimAgentPlan({\n planDir,\n planId: token.planId,\n planHash: opts.hash,\n authFingerprint,\n })\n\n if (token.planId !== plan.planId) {\n throw agentPlanError(\n 'PLAN_MISMATCH',\n 'Plan token does not match stored plan.',\n )\n }\n\n let doc: unknown\n try {\n doc = await executeAgentPlanMutation(client, plan)\n } catch (mutationError) {\n await releaseAgentPlanClaim({\n planDir,\n planId: plan.planId,\n }).catch(() => {})\n throw mutationError\n }\n\n await finalizeAgentPlan(plan)\n\n printAgentSuccess(\n {\n applied: true,\n operation: plan.operation,\n collection: plan.collection,\n id:\n doc && typeof doc === 'object' && 'id' in doc\n ? String((doc as Record<string, unknown>).id)\n : plan.documentId,\n doc,\n },\n outputOptions,\n )\n } catch (error) {\n exitWithAgentError(error, outputOptions)\n }\n },\n ),\n )\n}\n"],"mappings":";;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACDxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;ACLP;AAAA,EACE;AAAA,EACA;AAAA,EACA,aAAa;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,SAAS,YAAY;AAC9B,SAAS,eAAe;AAgBxB,IAAM,WAAW;AACjB,IAAM,YAAY;AAClB,IAAM,eAAe;AACrB,IAAM,wBAAwB,GAAG,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c,YAAY,GAAG;AAC7C,IAAM,EAAE,QAAQ,IAAIA,SAAQ,iBAAiB;AAE7C,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,IAAI,EACT,YAAY,kCAAkC,EAC9C,QAAQ,OAAO,EACf,OAAO,mBAAmB,uCAAuC,EACjE,OAAO,qBAAqB,uCAAuC,EACnE,OAAO,mBAAmB,yBAAyB;AAEtD,IAAM,YAAY,MACf,QAAQ,KAAK,EAAE,UAAU,QAAQ,IAAI,iBAAiB;AAOzD,QAAQ,KAAK,aAAa,MAAM;AAC9B,QAAM,OAAO,QAAQ,KAAK,EAAE;AAC5B,MAAI,SAAS,QAAQ,SAAS,KAAM,WAAU,IAAc;AAC5D,UAAQ,IAAI,gBAAgB,UAAU;AACxC,CAAC;AAED,QAAQ,GAAG,sBAAsB,CAAC,QAAQ;AACxC,gBAAc,KAAK,EAAE,QAAQ,UAAU,EAAE,CAAC;AAC5C,CAAC;AAED,IAAM,YAAY,MAChB,cAAc,QAAQ,KAAK,EAAE,MAA4B;AAC3D,IAAM,iBAAiB,MACrB,qBAAqB,QAAQ,KAAK,EAAE,MAA4B;AAElE,sBAAsB,SAAS,cAAc;AAC7C,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,uBAAuB,SAAS,WAAW,SAAS;AACpD,qBAAqB,SAAS,WAAW,SAAS;AAClD,sBAAsB,SAAS,WAAW,SAAS;AACnD,gCAAgC,SAAS,WAAW,SAAS;AAC7D,wBAAwB,SAAS,WAAW,SAAS;AACrD,yBAAyB,SAAS,WAAW,SAAS;AACtD,yBAAyB,SAAS,WAAW,SAAS;AACtD,uBAAuB,SAAS,WAAW,SAAS;AACpD,wBAAwB,SAAS,WAAW,SAAS;AACrD,qBAAqB,OAAO;AAE5B,QAAQ,MAAM;","names":["t","readFileSync","readFileSync","program","getClient","getFormat","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","program","getClient","getFormat","z","z","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","program","getClient","getFormat","randomBytes","pc","pc","t","resolve","program","randomBytes","SERVER_COLLECTIONS","program","getClient","getFormat","SERVER_COLLECTIONS","program","getClient","getFormat","SERVER_COLLECTIONS","SERVER_COLLECTIONS","randomBytes","randomBytes","SERVER_COLLECTIONS","homedir","join","createHash","join","homedir","current","readFileSync","readFileSync","path","invalidInput","getClient","plan","invalidInput","handleCommanderError","configureAgentParser","SERVER_COLLECTIONS","program","getClient","require"]}