@whop/cli 0.5.0 → 0.7.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/README.md +24 -0
- package/dist/{api-E6Y2WAEG.js → api-YDHSDKDV.js} +4 -2
- package/dist/{chunk-X34EUMEM.js → chunk-BSCOWFVU.js} +17668 -15981
- package/dist/chunk-BSCOWFVU.js.map +1 -0
- package/dist/index.js +697 -200
- package/dist/index.js.map +1 -1
- package/package.json +4 -3
- package/skills/whop-accounts/SKILL.md +24 -0
- package/skills/whop-ad-campaigns/SKILL.md +24 -0
- package/skills/whop-ad-groups/SKILL.md +24 -0
- package/skills/whop-ads/SKILL.md +100 -0
- package/skills/whop-apps/SKILL.md +18 -0
- package/skills/whop-audiences/SKILL.md +20 -0
- package/skills/whop-cards/SKILL.md +21 -0
- package/skills/whop-checkout-configurations/SKILL.md +21 -0
- package/skills/whop-deposits/SKILL.md +19 -0
- package/skills/whop-events/SKILL.md +19 -0
- package/skills/whop-ledgers/SKILL.md +19 -0
- package/skills/whop-media/SKILL.md +23 -0
- package/skills/whop-payouts/SKILL.md +20 -0
- package/skills/whop-people/SKILL.md +19 -0
- package/skills/whop-plans/SKILL.md +23 -0
- package/skills/whop-products/SKILL.md +22 -0
- package/skills/whop-referrals/SKILL.md +22 -0
- package/skills/whop-social-accounts/SKILL.md +26 -0
- package/skills/whop-swaps/SKILL.md +21 -0
- package/skills/whop-transfers/SKILL.md +20 -0
- package/skills/whop-users/SKILL.md +22 -0
- package/skills/whop-verifications/SKILL.md +25 -0
- package/dist/chunk-X34EUMEM.js.map +0 -1
- /package/dist/{api-E6Y2WAEG.js.map → api-YDHSDKDV.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/groups.json","../src/auth/commands.ts","../src/apps/commands.ts","../src/journey/client.ts","../src/apps/api.ts","../src/apps/config.ts","../src/apps/scaffold.ts","../src/journey/quickstart.ts","../src/journey/billing.ts","../src/lib/colors.ts","../package.json","../src/lib/update/check.ts","../src/lib/colorize-output.ts","../src/lib/update/self-update.ts","../src/lib/update/command.ts","../src/commands.ts","../src/lib/renderer.ts","../src/cli.ts","../src/api/api-structure.json","../src/api/tag-descriptions.json","../src/lib/grouped-help.ts","../src/index.ts"],"sourcesContent":["[\n [\n \"accounts\",\n \"Accounts\"\n ],\n [\n \"users\",\n \"Users\"\n ],\n [\n \"stats\",\n \"Stats\"\n ],\n [\n \"ledgers\",\n \"Ledgers\"\n ],\n [\n \"payouts\",\n \"Payouts\"\n ],\n [\n \"cards\",\n \"Cards\"\n ],\n [\n \"transfers\",\n \"Transfers\"\n ],\n [\n \"deposits\",\n \"Deposits\"\n ],\n [\n \"swaps\",\n \"Swaps\"\n ],\n [\n \"verifications\",\n \"Verifications\"\n ],\n [\n \"products\",\n \"Products\"\n ],\n [\n \"plans\",\n \"Plans\"\n ],\n [\n \"checkout-configurations\",\n \"Checkout Configurations\"\n ],\n [\n \"referrals\",\n \"Referrals\"\n ],\n [\n \"people\",\n \"People\"\n ],\n [\n \"events\",\n \"Events\"\n ],\n [\n \"ads\",\n \"Ads\"\n ],\n [\n \"ad-campaigns\",\n \"Ad Campaigns\"\n ],\n [\n \"ad-groups\",\n \"Ad Groups\"\n ],\n [\n \"audiences\",\n \"Audiences\"\n ],\n [\n \"media\",\n \"Media\"\n ],\n [\n \"social-accounts\",\n \"Social Accounts\"\n ]\n]\n","import { Cli, z } from \"incur\";\nimport { validateApiKey, apiBaseUrl } from \"./client\";\nimport { readConfig } from \"./config\";\nimport { getSecret } from \"./secret-store\";\nimport { OAuthError, performOAuthLogin } from \"./oauth\";\nimport {\n\tderiveProfileName,\n\tgetActiveProfile,\n\tgetValidAccessToken,\n\tlistProfiles,\n\tremoveAllProfiles,\n\tremoveProfile,\n\tswitchProfile,\n\tupsertProfile,\n} from \"./profiles\";\nimport {\n\tchooseAuthMethod,\n\tPromptCancelledError,\n\tpromptApiKey,\n\tselectProfile,\n\tstartSpinner,\n} from \"./prompts\";\nimport { AuthMethod, Identity, Profile } from \"./types\";\n\n/**\n * Auth commands: `whop auth login | logout | switch | status | list`.\n *\n * The login/logout business logic is context-free (`performLogin`,\n * `removeProfile`) and the incur run handlers are thin adapters. `loginAdapter`\n * and `logoutAdapter` are shared so the top-level `whop login` / `whop logout`\n * (registered in `index.ts`) behave identically without duplicating logic —\n * incur aliases can't cross from a group into a top-level command.\n */\n\n// --- CTA / error shapes accepted by the run context (kept minimal & structural) ---\ntype CtaCommand =\n\t| string\n\t| {\n\t\t\tcommand: string;\n\t\t\tdescription?: string | undefined;\n\t\t\toptions?: Record<string, unknown> | undefined;\n\t\t\targs?: Record<string, unknown> | undefined;\n\t };\ntype CtaInput = { description?: string | undefined; commands: CtaCommand[] };\ntype ErrorInput = {\n\tcode: string;\n\tmessage: string;\n\tcta?: CtaInput | undefined;\n\texitCode?: number | undefined;\n\tretryable?: boolean | undefined;\n};\n\n// --- Shared schemas ---\nexport const loginOptions = z.object({\n\tapiKey: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"API key for non-interactive login (skips the prompt)\"),\n\tprofile: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Name for this profile (defaults to the account route)\"),\n\taccountId: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Business account to act on behalf of (biz_xxx) — for OAuth users who manage more than one\",\n\t\t),\n});\n\nexport const loginEnv = z.object({\n\tWHOP_API_KEY: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"API key for non-interactive login\"),\n\tWHOP_API_BASE_URL: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Override the Whop API base URL\"),\n\tWHOP_CONFIG_DIR: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Override the CLI config directory\"),\n});\n\nexport const loginOutput = z.object({\n\tprofile: z.string().describe(\"The profile name\"),\n\tactive: z.boolean().describe(\"Whether this profile is now the active one\"),\n\tmethod: AuthMethod.describe(\"The authentication method\"),\n\tidentity: Identity.describe(\"The authenticated account or user identity\"),\n});\nexport type LoginOutput = z.infer<typeof loginOutput>;\n\nexport const logoutOptions = z.object({\n\tprofile: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Profile to remove (defaults to the active profile)\"),\n\tall: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\"Remove every profile and its stored secret (full reset)\"),\n});\nexport const logoutOutput = z.object({\n\tremoved: z.array(z.string()).describe(\"The removed profile name(s)\"),\n\tnewActive: z\n\t\t.string()\n\t\t.nullable()\n\t\t.describe(\"The profile that is now active, if any\"),\n});\nexport type LogoutOutput = z.infer<typeof logoutOutput>;\n\nconst statusOutput = z.object({\n\tloggedIn: z\n\t\t.boolean()\n\t\t.describe(\"Whether the active profile has a usable stored credential\"),\n\tprofile: z.string().nullable(),\n\tmethod: AuthMethod.nullable(),\n\tidentity: Identity.nullable().describe(\n\t\t\"The logged-in user (OAuth) or the account (API key)\",\n\t),\n\taccount: Identity.nullable().describe(\n\t\t\"The account auto-filled for scoped commands (account_id/company_id)\",\n\t),\n\thasSecret: z\n\t\t.boolean()\n\t\t.describe(\"Whether a secret was found in the OS keychain for this profile\"),\n});\n\nconst listOutput = z.object({\n\tactive: z.string().nullable(),\n\tprofiles: z.array(Profile),\n});\n\nconst switchArgs = z.object({\n\tname: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Profile to switch to (interactive picker if omitted)\"),\n});\nconst switchOutput = z.object({\n\tactive: z.string().describe(\"The newly active profile\"),\n});\n\nexport const loginExamples = [\n\t{ description: \"Interactive login\" },\n\t{\n\t\toptions: { apiKey: \"whop_xxx\" },\n\t\tdescription: \"Non-interactive login (CI / agents)\",\n\t},\n\t{\n\t\toptions: { apiKey: \"whop_xxx\", profile: \"prod\" },\n\t\tdescription: \"Log in and name the profile\",\n\t},\n];\nexport const loginHint =\n\t\"Agents / CI: pass --api-key or set WHOP_API_KEY to skip the prompt.\";\n\n// --- Context-free login flows ---\ntype LoginResult =\n\t| { ok: true; output: LoginOutput; existed: boolean; underscoped: boolean }\n\t| { ok: false; code: string; message: string };\n\nexport async function performLogin(input: {\n\tagent: boolean;\n\tapiKey?: string | undefined;\n\tprofile?: string | undefined;\n\taccountId?: string | undefined;\n}): Promise<LoginResult> {\n\tlet method: AuthMethod = \"api_key\";\n\tif (!input.agent && !input.apiKey) method = await chooseAuthMethod();\n\n\t// Route to the OAuth browser flow.\n\tif (method === \"oauth\") {\n\t\ttry {\n\t\t\tconst { profileName, identity, existed } = await performOAuthLogin({\n\t\t\t\tprofile: input.profile,\n\t\t\t\tagent: input.agent,\n\t\t\t\taccountId: input.accountId,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\texisted,\n\t\t\t\tunderscoped: false,\n\t\t\t\toutput: {\n\t\t\t\t\tprofile: profileName,\n\t\t\t\t\tactive: true,\n\t\t\t\t\tmethod: \"oauth\",\n\t\t\t\t\tidentity,\n\t\t\t\t},\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) {\n\t\t\t\treturn { ok: false, code: err.code, message: err.message };\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t// Resolve the API key: flag/env > interactive prompt > error in agent mode.\n\tlet apiKey = input.apiKey;\n\tif (!apiKey) {\n\t\tif (input.agent) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"API_KEY_REQUIRED\",\n\t\t\t\tmessage: \"No API key provided and not running interactively.\",\n\t\t\t};\n\t\t}\n\t\tapiKey = await promptApiKey();\n\t}\n\t// Normalize: the SDK adds the `Bearer ` prefix itself, so strip one if pasted.\n\tconst key = apiKey.replace(/^Bearer\\s+/i, \"\").trim();\n\n\t// 3. Validate against the API.\n\tlet result: Awaited<ReturnType<typeof validateApiKey>>;\n\tif (input.agent) {\n\t\tresult = await validateApiKey(key, apiBaseUrl());\n\t} else {\n\t\tconst s = startSpinner(\"Validating API key…\");\n\t\tresult = await validateApiKey(key, apiBaseUrl());\n\t\tconst okay = result.status === \"valid\" || result.status === \"underscoped\";\n\t\ts.stop(okay ? \"API key validated.\" : \"API key check failed.\");\n\t}\n\tif (result.status === \"invalid\") {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"INVALID_API_KEY\",\n\t\t\tmessage: \"That API key was rejected (401 Unauthorized).\",\n\t\t};\n\t}\n\tif (result.status === \"error\") {\n\t\treturn { ok: false, code: \"VALIDATION_FAILED\", message: result.message };\n\t}\n\n\t// 4. Persist (secret → keychain, metadata → config) and activate.\n\tconst identity = result.identity;\n\tconst name = input.profile ?? deriveProfileName(identity);\n\tconst existed = listProfiles().some((profile) => profile.name === name);\n\tconst profile = upsertProfile({ name, method, secret: key, identity });\n\n\treturn {\n\t\tok: true,\n\t\texisted,\n\t\tunderscoped: result.status === \"underscoped\",\n\t\toutput: { profile: profile.name, active: true, method, identity },\n\t};\n}\n\n// --- Shared adapters (used by the group command and the top-level alias) ---\ntype LoginAdapterCtx = {\n\tagent: boolean;\n\toptions: {\n\t\tapiKey?: string | undefined;\n\t\tprofile?: string | undefined;\n\t\taccountId?: string | undefined;\n\t};\n\tenv: { WHOP_API_KEY?: string | undefined };\n\tok: (data: LoginOutput, meta?: { cta?: CtaInput | undefined }) => never;\n\terror: (options: ErrorInput) => never;\n};\n\nexport async function loginAdapter(c: LoginAdapterCtx): Promise<never> {\n\tlet result: LoginResult;\n\ttry {\n\t\tresult = await performLogin({\n\t\t\tagent: c.agent,\n\t\t\tapiKey: c.options.apiKey ?? c.env.WHOP_API_KEY,\n\t\t\tprofile: c.options.profile,\n\t\t\taccountId: c.options.accountId,\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof PromptCancelledError) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Login cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!result.ok) {\n\t\tlet cta: CtaInput | undefined;\n\t\tif (result.code === \"API_KEY_REQUIRED\") {\n\t\t\tcta = {\n\t\t\t\tdescription: \"Provide a key non-interactively:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"auth login\",\n\t\t\t\t\t\toptions: { apiKey: true },\n\t\t\t\t\t\tdescription: \"Pass --api-key <key>\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} else if (\n\t\t\tresult.code === \"MULTIPLE_ACCOUNTS\" ||\n\t\t\tresult.code === \"ACCOUNT_NOT_FOUND\"\n\t\t) {\n\t\t\tcta = {\n\t\t\t\tdescription: \"Choose which business account to use:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"auth login\",\n\t\t\t\t\t\toptions: { accountId: true },\n\t\t\t\t\t\tdescription: \"Pass --account-id biz_xxx\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\treturn c.error({\n\t\t\tcode: result.code,\n\t\t\tmessage: result.message,\n\t\t\tretryable: result.code !== \"INVALID_API_KEY\",\n\t\t\tcta,\n\t\t});\n\t}\n\n\t// First-run vs returning user: check whether they have any products yet.\n\t// Probe whenever we have an account so a returning\n\t// user with zero products still gets the \"start selling\" path. Use the\n\t// resolved account id (not the user id, which is what identity holds for\n\t// OAuth). On failure just fall back to the generic CTA — don't block login.\n\tlet firstRun = !result.existed;\n\tconst accountId = getActiveProfile()?.accountId ?? \"\";\n\tif (accountId) {\n\t\ttry {\n\t\t\tconst { createWhopFetch } = await import(\"../api/index.js\");\n\t\t\tconst fetch = createWhopFetch();\n\t\t\tconst res = await fetch(\n\t\t\t\tnew Request(\n\t\t\t\t\t`https://api.whop.com/products?company_id=${accountId}&first=1`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tif (res.ok) {\n\t\t\t\tconst data = (await res.json()) as { data?: unknown[] };\n\t\t\t\tfirstRun = (data.data?.length ?? 0) === 0;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Non-fatal — use generic CTA\n\t\t}\n\t}\n\n\t// No business account resolved (e.g. OAuth account with no business yet).\n\t// quickstart creates one — interactively, or via --business_name.\n\tif (!accountId) {\n\t\treturn c.ok(result.output, {\n\t\t\tcta: {\n\t\t\t\tdescription:\n\t\t\t\t\t\"You're logged in, but you don't have a business account yet. Create one and start selling in one command:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Create your business account, product, and checkout link\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\treturn c.ok(result.output, {\n\t\tcta: firstRun\n\t\t\t? {\n\t\t\t\t\tdescription: \"You're logged in. Start selling in one command:\",\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Create your product, set a price, get a checkout link\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tdescription: result.existed\n\t\t\t\t\t\t? \"Updated and switched to this profile:\"\n\t\t\t\t\t\t: \"Welcome back:\",\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\t\tdescription: \"See your status and what's next\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ command: \"auth status\", description: \"Show the active identity\" },\n\t\t\t\t\t],\n\t\t\t\t},\n\t});\n}\n\ntype LogoutAdapterCtx = {\n\toptions: { profile?: string | undefined; all?: boolean | undefined };\n\tok: (data: LogoutOutput, meta?: { cta?: CtaInput | undefined }) => never;\n\terror: (options: ErrorInput) => never;\n};\n\nexport function logoutAdapter(c: LogoutAdapterCtx): never {\n\tif (c.options.all) {\n\t\tif (c.options.profile) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CONFLICTING_OPTIONS\",\n\t\t\t\tmessage: \"--all removes every profile — don't combine it with --profile.\",\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\tconst removed = removeAllProfiles();\n\t\tif (removed.length === 0) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"NO_PROFILES\",\n\t\t\t\tmessage: \"No profiles to remove.\",\n\t\t\t\tretryable: false,\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: \"Log in first:\",\n\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\treturn c.ok(\n\t\t\t{ removed, newActive: null },\n\t\t\t{\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: `Removed ${removed.length} profile${removed.length === 1 ? \"\" : \"s\"}. To authenticate again:`,\n\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\tconst target = c.options.profile ?? getActiveProfile()?.name;\n\tif (!target) {\n\t\treturn c.error({\n\t\t\tcode: \"NO_ACTIVE_PROFILE\",\n\t\t\tmessage: \"No active profile to log out from.\",\n\t\t\tretryable: false,\n\t\t\tcta: {\n\t\t\t\tdescription: \"Log in first:\",\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\tconst { removed, newActive } = removeProfile(target);\n\tif (!removed) {\n\t\treturn c.error({\n\t\t\tcode: \"PROFILE_NOT_FOUND\",\n\t\t\tmessage: `No profile named \"${target}\".`,\n\t\t\tretryable: false,\n\t\t});\n\t}\n\treturn c.ok(\n\t\t{ removed: [target], newActive },\n\t\tnewActive\n\t\t\t? {\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: `Now using \"${newActive}\".`,\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"auth status\",\n\t\t\t\t\t\t\t\tdescription: \"Show the active identity\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n}\n\n// --- The `auth` command group ---\nexport function buildAuthGroup() {\n\tconst auth = Cli.create(\"auth\", {\n\t\tdescription: \"Manage Whop authentication\",\n\t});\n\n\tauth.command(\"login\", {\n\t\tdescription: \"Log in to Whop\",\n\t\taliases: [\"add\"],\n\t\toptions: loginOptions,\n\t\tenv: loginEnv,\n\t\toutput: loginOutput,\n\t\texamples: loginExamples,\n\t\thint: loginHint,\n\t\trun: (c) => loginAdapter(c),\n\t});\n\n\tauth.command(\"logout\", {\n\t\tdescription: \"Log out — remove a saved profile, or all with --all\",\n\t\taliases: [\"remove\", \"rm\"],\n\t\toptions: logoutOptions,\n\t\toutput: logoutOutput,\n\t\texamples: [\n\t\t\t{ description: \"Remove the active profile\" },\n\t\t\t{\n\t\t\t\toptions: { all: true },\n\t\t\t\tdescription: \"Remove every profile (full reset)\",\n\t\t\t},\n\t\t],\n\t\trun: (c) => logoutAdapter(c),\n\t});\n\n\tauth.command(\"switch\", {\n\t\tdescription: \"Switch the active profile\",\n\t\targs: switchArgs,\n\t\toutput: switchOutput,\n\t\trun: async (c) => {\n\t\t\tconst profiles = listProfiles();\n\t\t\tif (profiles.length === 0) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"NO_PROFILES\",\n\t\t\t\t\tmessage: \"No profiles yet — log in first.\",\n\t\t\t\t\tretryable: true,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: \"To authenticate:\",\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{ command: \"auth login\", description: \"Log in to Whop\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet name = c.args.name;\n\t\t\tif (!name) {\n\t\t\t\tif (c.agent) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"PROFILE_REQUIRED\",\n\t\t\t\t\t\tmessage: `Specify a profile name. Available: ${profiles.map((p) => p.name).join(\", \")}.`,\n\t\t\t\t\t\tretryable: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tname = await selectProfile(profiles);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof PromptCancelledError) {\n\t\t\t\t\t\treturn c.error({\n\t\t\t\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\t\t\t\tmessage: \"Switch cancelled.\",\n\t\t\t\t\t\t\texitCode: 130,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst profile = switchProfile(name);\n\t\t\tif (!profile) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"PROFILE_NOT_FOUND\",\n\t\t\t\t\tmessage: `No profile named \"${name}\". Available: ${profiles.map((p) => p.name).join(\", \")}.`,\n\t\t\t\t\tretryable: true,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn c.ok(\n\t\t\t\t{ active: profile.name },\n\t\t\t\t{\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"auth status\",\n\t\t\t\t\t\t\t\tdescription: \"Show the active identity\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t});\n\n\tauth.command(\"status\", {\n\t\tdescription: \"Show the active identity (whoami)\",\n\t\taliases: [\"whoami\"],\n\t\toutput: statusOutput,\n\t\trun: async (c) => {\n\t\t\tconst profile = getActiveProfile();\n\t\t\tif (!profile) {\n\t\t\t\treturn c.ok(\n\t\t\t\t\t{\n\t\t\t\t\t\tloggedIn: false,\n\t\t\t\t\t\tprofile: null,\n\t\t\t\t\t\tmethod: null,\n\t\t\t\t\t\tidentity: null,\n\t\t\t\t\t\taccount: null,\n\t\t\t\t\t\thasSecret: false,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcta: {\n\t\t\t\t\t\t\tdescription: \"To authenticate:\",\n\t\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t\t{ command: \"auth login\", description: \"Log in to Whop\" },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst hasSecret = getSecret(profile.name) !== null;\n\t\t\t// \"Logged in\" means we can actually obtain a Bearer token. For oauth\n\t\t\t// this may refresh the access token; a revoked/expired refresh token\n\t\t\t// resolves to null instead of throwing, so the reported state is honest.\n\t\t\tlet loggedIn = hasSecret;\n\t\t\tif (hasSecret) {\n\t\t\t\ttry {\n\t\t\t\t\tloggedIn = (await getValidAccessToken(profile)) !== null;\n\t\t\t\t} catch {\n\t\t\t\t\tloggedIn = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst account =\n\t\t\t\tprofile.accountId || profile.accountTitle || profile.accountRoute\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tid: profile.accountId,\n\t\t\t\t\t\t\ttitle: profile.accountTitle,\n\t\t\t\t\t\t\troute: profile.accountRoute,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null;\n\t\t\treturn c.ok(\n\t\t\t\t{\n\t\t\t\t\tloggedIn,\n\t\t\t\t\tprofile: profile.name,\n\t\t\t\t\tmethod: profile.method,\n\t\t\t\t\tidentity:\n\t\t\t\t\t\tprofile.method === \"oauth\"\n\t\t\t\t\t\t\t? { id: profile.userId, email: profile.userEmail }\n\t\t\t\t\t\t\t: account,\n\t\t\t\t\taccount,\n\t\t\t\t\thasSecret,\n\t\t\t\t},\n\t\t\t\tloggedIn\n\t\t\t\t\t? undefined\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tcta: {\n\t\t\t\t\t\t\t\tdescription: hasSecret\n\t\t\t\t\t\t\t\t\t? \"Your session is no longer valid — log in again:\"\n\t\t\t\t\t\t\t\t\t: \"The stored secret is missing — log in again:\",\n\t\t\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t\t\t{ command: \"auth login\", description: \"Log in to Whop\" },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t);\n\t\t},\n\t});\n\n\tauth.command(\"list\", {\n\t\tdescription: \"List saved authentication profiles\",\n\t\taliases: [\"ls\"],\n\t\toutput: listOutput,\n\t\trun: () => {\n\t\t\tconst { activeProfile, profiles } = readConfig();\n\t\t\tconst active =\n\t\t\t\tprofiles.find((p) => p.name === activeProfile)?.name ?? null;\n\t\t\treturn { active, profiles };\n\t\t},\n\t});\n\n\treturn auth;\n}\n","import { isCancel, select, spinner, text } from \"@clack/prompts\";\nimport { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\nimport chalk from \"chalk\";\nimport { Cli, Openapi, z } from \"incur\";\nimport { appsSpec, createWhopFetch, filterSpecByTag } from \"../api/index.js\";\nimport {\n\tcreateApp,\n\tcreateAppBuild,\n\tcreateDevAccessToken,\n\tgetApp,\n\tlistApps,\n\tpromoteAppBuild,\n\tupdateAppRoute,\n\tupdateAppSecrets,\n\tuploadBuildArchive,\n\twaitForBuildPromotion,\n\twaitForFileReady,\n\ttype WhopApp,\n} from \"./api.js\";\nimport {\n\tAPP_CONFIG_FILENAME,\n\tfindProjectDir,\n\treadAppConfig,\n\tslugify,\n\twriteAppConfig,\n\ttype AppConfig,\n} from \"./config.js\";\nimport {\n\tdetectPackageManager as detectInstalledPackageManager,\n\tfindViteConfig,\n\toutputTail,\n\tpmInstallHint,\n\trunTanstackCreate,\n\ttanstackCreateCommand,\n\twhopifyProject,\n\ttype PackageManager,\n} from \"./scaffold.js\";\n\n// The whop() vite plugin writes this archive into the build output directory.\nconst BUILD_ARCHIVE = \"dist/whop-build.zip\";\n\n// Env names that control the local Node/package-manager runtime rather than\n// the app. Injecting them from remotely-stored secrets would let anyone with\n// developer:update_app on the app execute code on a teammate's machine the\n// next time they run `whop apps dev`.\nconst UNSAFE_DEV_ENV_KEYS = new Set([\n\t\"PATH\",\n\t\"NODE_OPTIONS\",\n\t\"NODE_EXTRA_CA_CERTS\",\n\t\"NODE_REPL_EXTERNAL_MODULE\",\n]);\nconst UNSAFE_DEV_ENV_PREFIXES = [\"NPM_\", \"PNPM_\", \"YARN_\", \"BUN_\", \"LD_\", \"DYLD_\"];\n\nfunction isUnsafeDevEnvKey(key: string): boolean {\n\tconst upper = key.toUpperCase();\n\treturn (\n\t\tUNSAFE_DEV_ENV_KEYS.has(upper) ||\n\t\tUNSAFE_DEV_ENV_PREFIXES.some((prefix) => upper.startsWith(prefix))\n\t);\n}\n\nconst BuildSchema = z.object({\n\tid: z.string(),\n\tstatus: z.string(),\n\tis_production: z.boolean().optional(),\n\turl: z.string().optional(),\n});\n\ntype ErrorOptions = {\n\tcode: string;\n\tmessage: string;\n\tretryable?: boolean;\n\texitCode?: number;\n\tcta?: {\n\t\tdescription?: string;\n\t\tcommands: { command: string; description?: string }[];\n\t};\n};\n\n/**\n * incur's `c.error()` builds a result that only takes effect when returned\n * from the command's own `run` — so helper functions abort by throwing this,\n * and `deploy` converts it back into `c.error(...)` at the top level.\n */\nclass DeployAbort extends Error {\n\tconstructor(readonly options: ErrorOptions) {\n\t\tsuper(options.message);\n\t}\n}\n\ntype DeployContext = {\n\tagent: boolean;\n};\n\n/**\n * The project's lockfile decides the package manager; without one (e.g. a\n * fresh scaffold that hasn't installed yet) fall back to whatever is\n * installed, preferring bun — never blindly npm.\n */\nfunction detectProjectPackageManager(projectDir: string): string {\n\tif (\n\t\texistsSync(join(projectDir, \"bun.lock\")) ||\n\t\texistsSync(join(projectDir, \"bun.lockb\"))\n\t)\n\t\treturn \"bun\";\n\tif (existsSync(join(projectDir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n\tif (existsSync(join(projectDir, \"yarn.lock\"))) return \"yarn\";\n\tif (existsSync(join(projectDir, \"package-lock.json\"))) return \"npm\";\n\treturn detectInstalledPackageManager() ?? \"npm\";\n}\n\nfunction hasScript(projectDir: string, script: string): boolean {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(projectDir, \"package.json\"), \"utf-8\"),\n\t\t) as { scripts?: Record<string, string> };\n\t\treturn Boolean(pkg.scripts?.[script]);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// npm/pnpm/yarn are .cmd shims on Windows, which can't be spawned without a\n// shell. Everywhere else, spawning without a shell avoids quoting pitfalls.\nconst SPAWN_VIA_SHELL = process.platform === \"win32\";\n\nfunction runScript(\n\tprojectDir: string,\n\tscript: string,\n\textraEnv: Record<string, string> = {},\n): void {\n\tconst pm = detectProjectPackageManager(projectDir);\n\tconst result = spawnSync(pm, [\"run\", script], {\n\t\tcwd: projectDir,\n\t\tstdio: \"inherit\",\n\t\tshell: SPAWN_VIA_SHELL,\n\t\tenv: { ...process.env, ...extraEnv },\n\t});\n\tif (result.error) {\n\t\tthrow new Error(\n\t\t\t`Could not run \\`${pm} run ${script}\\`: ${result.error.message}`,\n\t\t);\n\t}\n\tif (result.status !== 0) {\n\t\tthrow new Error(\n\t\t\t`\\`${pm} run ${script}\\` failed with exit code ${result.status ?? \"unknown\"}`,\n\t\t);\n\t}\n}\n\nfunction runInstall(c: { agent: boolean }, projectDir: string): void {\n\tconst pm = detectProjectPackageManager(projectDir);\n\tconst spin = c.agent ? null : spinner();\n\tspin?.start(`Installing dependencies with ${pm}`);\n\tconst result = spawnSync(pm, [\"install\"], {\n\t\tcwd: projectDir,\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\tencoding: \"utf-8\",\n\t\tshell: SPAWN_VIA_SHELL,\n\t});\n\tif (result.error || result.status !== 0) {\n\t\tspin?.error(`${pm} install failed`);\n\t\tthrow new Error(\n\t\t\t`\\`${pm} install\\` failed${result.status != null ? ` with exit code ${result.status}` : \"\"} — run it manually inside ${projectDir}, then re-run \\`whop apps deploy\\`.${outputTail(result)}`,\n\t\t);\n\t}\n\tspin?.stop(`Installed dependencies with ${pm}`);\n}\n\nfunction log(c: { agent: boolean }, message: string): void {\n\tif (!c.agent) console.log(message);\n}\n\nasync function promptText(\n\tmessage: string,\n\tplaceholder: string,\n\tinitialValue?: string,\n): Promise<string | null> {\n\tconst value = await text({ message, placeholder, initialValue });\n\tif (isCancel(value)) return null;\n\treturn String(value);\n}\n\nfunction cancelled(): never {\n\tthrow new DeployAbort({\n\t\tcode: \"CANCELLED\",\n\t\tmessage: \"Cancelled.\",\n\t\texitCode: 130,\n\t});\n}\n\nfunction formatManualSteps(steps: string[]): string {\n\treturn steps.map((step, i) => ` ${i + 1}. ${step}`).join(\"\\n\");\n}\n\nfunction formatAppList(apps: WhopApp[]): string {\n\tconst recent = [...apps]\n\t\t.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))\n\t\t.slice(0, 10);\n\treturn recent\n\t\t.map(\n\t\t\t(a) => ` ${a.id} ${a.name}${a.route ? ` (${a.route}.whop.app)` : \"\"}`,\n\t\t)\n\t\t.join(\"\\n\");\n}\n\n/**\n * Registers the OpenAPI-generated commands for one tag of the apps spec\n * directly onto a command group. Done explicitly (instead of incur's\n * `{ fetch, openapi }` group registration) so generated commands and\n * hand-written ones like `deploy` can live in the same group.\n */\nasync function registerSpecCommands(\n\tgroup: ReturnType<typeof Cli.create>,\n\ttag: string,\n): Promise<void> {\n\tconst spec = filterSpecByTag(appsSpec as Record<string, unknown>, tag);\n\tconst generated = await Openapi.generateCommands(\n\t\tspec as Openapi.OpenAPISpec,\n\t\tcreateWhopFetch(),\n\t);\n\tfor (const [name, entry] of generated) {\n\t\tif (\"run\" in entry) group.command(name, entry);\n\t}\n}\n\n/**\n * Step 1: a package manager must exist before anything else — scaffolding,\n * installing, and building all need one.\n */\nfunction ensurePackageManager(): PackageManager {\n\tconst pm = detectInstalledPackageManager();\n\tif (pm) return pm;\n\tthrow new DeployAbort({\n\t\tcode: \"NO_PACKAGE_MANAGER\",\n\t\tmessage: `No package manager found (looked for bun, pnpm, npm). Install one and re-run \\`whop apps deploy\\`:\\n\\n bun (recommended): ${pmInstallHint(\"bun\")}\\n pnpm: ${pmInstallHint(\"pnpm\")}\\n npm: ${pmInstallHint(\"npm\")}`,\n\t});\n}\n\n/**\n * Step 2: the current directory must contain a Vite app (package.json + vite\n * config). Interactively offers to scaffold one; in agent mode prints the\n * exact scaffold command so the agent can run it and re-invoke deploy.\n */\nasync function ensureViteApp(\n\tc: DeployContext,\n\tpm: PackageManager,\n\tdirOption: string | undefined,\n): Promise<{ projectDir: string; freshlyScaffolded: boolean }> {\n\tconst projectDir = dirOption\n\t\t? resolve(dirOption)\n\t\t: (findProjectDir() ?? process.cwd());\n\n\tconst isViteApp =\n\t\texistsSync(join(projectDir, \"package.json\")) &&\n\t\tfindViteConfig(projectDir) !== undefined;\n\tif (isViteApp) return { projectDir, freshlyScaffolded: false };\n\n\tif (c.agent) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"NOT_A_VITE_APP\",\n\t\t\tmessage: [\n\t\t\t\t`${projectDir} doesn't look like a Vite app (missing package.json or vite config).`,\n\t\t\t\t\"\",\n\t\t\t\t\"Ask the user whether to scaffold a new app here, or locate their existing Vite app.\",\n\t\t\t\t\"\",\n\t\t\t\t\"To scaffold a new app (TanStack Start), run:\",\n\t\t\t\t` ${tanstackCreateCommand(pm, \"<app-name>\")}`,\n\t\t\t\t` cd <app-name> && ${pm} install`,\n\t\t\t\t\"\",\n\t\t\t\t\"Then re-run `whop apps deploy` from inside the app directory.\",\n\t\t\t\t\"Or, if a Vite app already exists somewhere else, re-run `whop apps deploy --dir <path-to-app>`.\",\n\t\t\t].join(\"\\n\"),\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"apps deploy\",\n\t\t\t\t\t\tdescription: \"Re-run from inside a Vite app directory\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tconst choice = await select({\n\t\tmessage: `${projectDir} doesn't look like a Vite app. What do you want to do?`,\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: \"scaffold\",\n\t\t\t\tlabel: \"Scaffold a new Whop app here (TanStack Start)\",\n\t\t\t},\n\t\t\t{ value: \"cancel\", label: \"Cancel — I'll cd into my app directory\" },\n\t\t],\n\t});\n\tif (isCancel(choice) || choice === \"cancel\") cancelled();\n\n\tconst scaffolded = await scaffoldNewApp(c, pm);\n\treturn { projectDir: scaffolded, freshlyScaffolded: true };\n}\n\n/**\n * Interactive scaffold: asks for name + route, registers the app on Whop\n * (claiming the route before any files are written, so a taken route fails\n * fast), scaffolds the TanStack Start template, and links it.\n */\nasync function scaffoldNewApp(\n\tc: DeployContext,\n\tpm: PackageManager,\n): Promise<string> {\n\tconst name = await promptText(\"What is your app called?\", \"My Site\");\n\tif (name === null) cancelled();\n\n\tconst slug = slugify(name);\n\tconst routeInput = await promptText(\n\t\t\"Which route should it live at? (your-route.whop.app)\",\n\t\tslug,\n\t\tslug,\n\t);\n\tif (routeInput === null) cancelled();\n\tconst route = slugify(routeInput);\n\tif (!route) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\tmessage: `Couldn't derive a route from \"${routeInput}\" — use letters and numbers (e.g. my-site).`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\n\tconst targetDir = resolve(`./${route}`);\n\tif (existsSync(targetDir) && readdirSync(targetDir).length > 0) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"TARGET_NOT_EMPTY\",\n\t\t\tmessage: `Target directory is not empty: ${targetDir}. Pick a different route, or run \\`whop apps deploy\\` from an empty directory.`,\n\t\t});\n\t}\n\n\tlet app: WhopApp;\n\ttry {\n\t\tapp = await createApp({ name, route });\n\t} catch (err) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"CREATE_FAILED\",\n\t\t\tmessage:\n\t\t\t\terr instanceof Error ? err.message : \"Failed to register the app\",\n\t\t\tretryable: true,\n\t\t});\n\t}\n\n\tconst spin = c.agent ? null : spinner();\n\tspin?.start(\"Scaffolding the latest TanStack Start template\");\n\ttry {\n\t\trunTanstackCreate({ targetDir, projectName: route, pm });\n\t\tspin?.stop(`Scaffolded ${route} from the latest TanStack Start template`);\n\t} catch (err) {\n\t\tspin?.error(\"Scaffold failed\");\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"SCAFFOLD_FAILED\",\n\t\t\tmessage: `${err instanceof Error ? err.message : \"Failed to scaffold the project\"}\\n\\nThe app ${app.id} is already registered — scaffold into a fresh directory and re-run \\`whop apps deploy --app ${app.id}\\` there.`,\n\t\t});\n\t}\n\n\twriteAppConfig(targetDir, { app_id: app.id, name, route });\n\treturn targetDir;\n}\n\n/**\n * Step 3b: the project must be linked to a Whop app via whop.app.json.\n * `--app` links explicitly; otherwise offers to select or create one\n * (always creating when the account has no apps yet). In agent mode, prints\n * the exact commands — including recently created apps so the agent can ask\n * the user about reusing one.\n */\nasync function ensureAppLinked(\n\tc: DeployContext,\n\tprojectDir: string,\n\tappOption: string | undefined,\n): Promise<AppConfig> {\n\tif (appOption) {\n\t\tlet app: WhopApp;\n\t\ttry {\n\t\t\tapp = await getApp(appOption);\n\t\t} catch (err) {\n\t\t\tthrow new DeployAbort({\n\t\t\t\tcode: \"APP_NOT_FOUND\",\n\t\t\t\tmessage: `Could not load app ${appOption}: ${err instanceof Error ? err.message : \"unknown error\"}`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\tconst config = await withRoute(c, app);\n\t\twriteAppConfig(projectDir, config);\n\t\tlog(\n\t\t\tc,\n\t\t\tchalk.dim(\n\t\t\t\t`Linked ${config.name} (${config.app_id}) → ${APP_CONFIG_FILENAME}`,\n\t\t\t),\n\t\t);\n\t\treturn config;\n\t}\n\n\tconst existing = readAppConfig(projectDir);\n\tif (existing) return existing;\n\n\tconst apps = await listApps();\n\n\tif (c.agent) {\n\t\tconst reuse =\n\t\t\tapps.length > 0\n\t\t\t\t? `This account has existing apps — ask the user whether to reuse one:\\n${formatAppList(apps)}\\n\\nTo reuse one: whop apps deploy --app <app_id>\\n\\n`\n\t\t\t\t: \"This account has no apps yet, so a new one must be created.\\n\\n\";\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"NO_APP_LINKED\",\n\t\t\tmessage: [\n\t\t\t\t`No ${APP_CONFIG_FILENAME} here — this project isn't linked to a Whop app yet.`,\n\t\t\t\t\"\",\n\t\t\t\t`${reuse}To create a new app, ask the user for a name and route (the route becomes <route>.whop.app), then run:`,\n\t\t\t\t' whop apps create --name \"My Site\" --route my-site',\n\t\t\t\t\"\",\n\t\t\t\t\"Then deploy with the returned app id:\",\n\t\t\t\t\" whop apps deploy --app <app_id>\",\n\t\t\t].join(\"\\n\"),\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"apps create\",\n\t\t\t\t\t\tdescription: \"Create a new app (pass --name and --route)\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"apps deploy\",\n\t\t\t\t\t\tdescription: \"Re-run with --app <app_id> to link and deploy\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tlet selected: WhopApp | null = null;\n\tif (apps.length > 0) {\n\t\tconst recent = [...apps].sort(\n\t\t\t(a, b) => (b.created_at ?? 0) - (a.created_at ?? 0),\n\t\t);\n\t\tconst choice = await select({\n\t\t\tmessage: \"Which app should this project deploy to?\",\n\t\t\toptions: [\n\t\t\t\t...recent.map((a) => ({\n\t\t\t\t\tvalue: a.id,\n\t\t\t\t\tlabel: `${a.name} (${a.id}${a.route ? `, ${a.route}.whop.app` : \"\"})`,\n\t\t\t\t})),\n\t\t\t\t{ value: \"__new__\", label: \"Create a new app\" },\n\t\t\t],\n\t\t});\n\t\tif (isCancel(choice)) cancelled();\n\t\tif (choice !== \"__new__\") {\n\t\t\tselected = recent.find((a) => a.id === choice) ?? null;\n\t\t}\n\t}\n\n\tif (!selected) {\n\t\tconst name = await promptText(\"What is your app called?\", \"My Site\");\n\t\tif (name === null) cancelled();\n\t\tconst slug = slugify(name);\n\t\tconst routeInput = await promptText(\n\t\t\t\"Which route should it live at? (your-route.whop.app)\",\n\t\t\tslug,\n\t\t\tslug,\n\t\t);\n\t\tif (routeInput === null) cancelled();\n\t\tconst route = slugify(routeInput);\n\t\tif (!route) {\n\t\t\tthrow new DeployAbort({\n\t\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\t\tmessage: `Couldn't derive a route from \"${routeInput}\" — use letters and numbers (e.g. my-site).`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tselected = await createApp({ name, route });\n\t\t} catch (err) {\n\t\t\tthrow new DeployAbort({\n\t\t\t\tcode: \"CREATE_FAILED\",\n\t\t\t\tmessage:\n\t\t\t\t\terr instanceof Error ? err.message : \"Failed to register the app\",\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst config = await withRoute(c, selected);\n\twriteAppConfig(projectDir, config);\n\tlog(\n\t\tc,\n\t\tchalk.dim(\n\t\t\t`Linked ${config.name} (${config.app_id}) → ${APP_CONFIG_FILENAME}`,\n\t\t),\n\t);\n\treturn config;\n}\n\n/**\n * Hosted deploys serve from <route>.whop.app, so a linked app must have a\n * route. Prompts for one interactively; in agent mode prints the exact\n * update command.\n */\nasync function withRoute(c: DeployContext, app: WhopApp): Promise<AppConfig> {\n\tif (app.route) return { app_id: app.id, name: app.name, route: app.route };\n\n\tif (c.agent) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\tmessage: `App ${app.id} (${app.name}) has no route — hosted apps are served from <route>.whop.app. Ask the user which route to claim, then run:\\n whop apps update ${app.id} --route <route>\\n whop apps deploy --app ${app.id}`,\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: `apps update ${app.id}`,\n\t\t\t\t\t\tdescription: \"Set the route (pass --route)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tconst slug = slugify(app.name);\n\tconst routeInput = await promptText(\n\t\t`${app.name} has no route yet. Which route should it live at? (your-route.whop.app)`,\n\t\tslug,\n\t\tslug,\n\t);\n\tif (routeInput === null) cancelled();\n\tconst route = slugify(routeInput);\n\tif (!route) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\tmessage: `Couldn't derive a route from \"${routeInput}\" — use letters and numbers (e.g. my-site).`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\ttry {\n\t\tconst updated = await updateAppRoute(app.id, route);\n\t\treturn {\n\t\t\tapp_id: updated.id,\n\t\t\tname: updated.name,\n\t\t\troute: updated.route ?? route,\n\t\t};\n\t} catch (err) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"UPDATE_FAILED\",\n\t\t\tmessage: err instanceof Error ? err.message : \"Failed to set the route\",\n\t\t\tretryable: true,\n\t\t});\n\t}\n}\n\nfunction resolveSecretsAppId(appOption: string | undefined): string {\n\tif (appOption) return appOption;\n\tconst projectDir = findProjectDir();\n\tconst config = projectDir ? readAppConfig(projectDir) : null;\n\tif (config) return config.app_id;\n\tthrow new Error(\n\t\t`No app specified. Pass --app app_xxx or run inside a project with ${APP_CONFIG_FILENAME}.`,\n\t);\n}\n\nfunction buildSecretsGroup() {\n\tconst secrets = Cli.create(\"secrets\", {\n\t\tdescription:\n\t\t\t\"Manage app secrets — encrypted at rest, injected as env bindings into the hosted runtime and `whop apps dev`\",\n\t});\n\n\tsecrets.command(\"list\", {\n\t\tdescription: \"Show the app's secrets\",\n\t\toptions: z.object({\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"App id (defaults to the project's linked app)\"),\n\t\t}),\n\t\trun: async (c) => {\n\t\t\tconst remote = await getApp(resolveSecretsAppId(c.options.app));\n\t\t\treturn c.ok({ app_id: remote.id, secrets: remote.secrets ?? {} });\n\t\t},\n\t});\n\n\tsecrets.command(\"set\", {\n\t\tdescription: \"Add or overwrite secrets\",\n\t\toptions: z.object({\n\t\t\tsecret: z\n\t\t\t\t.array(z.string())\n\t\t\t\t.min(1)\n\t\t\t\t.describe(\"KEY=VALUE pair (repeatable)\"),\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"App id (defaults to the project's linked app)\"),\n\t\t}),\n\t\texamples: [\n\t\t\t{ options: { secret: [\"MAIL_API_KEY=mail-key-123\"] } },\n\t\t\t{ options: { secret: [\"A=1\", \"B=2\"], app: \"app_xxxxxxxx\" } },\n\t\t],\n\t\trun: async (c) => {\n\t\t\tconst updates: Record<string, string> = {};\n\t\t\tfor (const pair of c.options.secret) {\n\t\t\t\tconst eq = pair.indexOf(\"=\");\n\t\t\t\tif (eq <= 0) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"INVALID_SECRET\",\n\t\t\t\t\t\tmessage: `\"${pair}\" is not KEY=VALUE. Use --secret NAME=value (an empty value deletes the secret).`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tupdates[pair.slice(0, eq)] = pair.slice(eq + 1);\n\t\t\t}\n\t\t\tconst remote = await updateAppSecrets(\n\t\t\t\tresolveSecretsAppId(c.options.app),\n\t\t\t\tupdates,\n\t\t\t);\n\t\t\treturn c.ok({ app_id: remote.id, secrets: remote.secrets ?? {} });\n\t\t},\n\t});\n\n\tsecrets.command(\"unset\", {\n\t\tdescription: \"Delete secrets by name\",\n\t\toptions: z.object({\n\t\t\tkey: z.array(z.string()).min(1).describe(\"Secret name (repeatable)\"),\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"App id (defaults to the project's linked app)\"),\n\t\t}),\n\t\texamples: [{ options: { key: [\"MAIL_API_KEY\"] } }],\n\t\trun: async (c) => {\n\t\t\tconst updates: Record<string, string | null> = {};\n\t\t\tfor (const key of c.options.key) updates[key] = null;\n\t\t\tconst remote = await updateAppSecrets(\n\t\t\t\tresolveSecretsAppId(c.options.app),\n\t\t\t\tupdates,\n\t\t\t);\n\t\t\treturn c.ok({ app_id: remote.id, secrets: remote.secrets ?? {} });\n\t\t},\n\t});\n\n\treturn secrets;\n}\n\nexport async function buildAppGroup() {\n\tconst app = Cli.create(\"apps\", {\n\t\tdescription: \"Build and deploy fully-hosted web apps on Whop (*.whop.app)\",\n\t});\n\n\tawait registerSpecCommands(app, \"Apps\");\n\n\tconst builds = Cli.create(\"builds\", {\n\t\tdescription: \"Manage app builds (list, inspect, promote)\",\n\t});\n\tawait registerSpecCommands(builds, \"App builds\");\n\tapp.command(builds);\n\n\tapp.command(buildSecretsGroup());\n\n\tapp.command(\"dev\", {\n\t\tdescription: \"Run the local dev server for this app\",\n\t\thint: \"Starts the project's dev script with WHOP_APP_ID set and a short-lived access token injected as WHOP_API_KEY (minted from your CLI credential), so server-side SDK calls work locally without env setup. An explicitly exported WHOP_API_KEY is used as-is.\",\n\t\toptions: z.object({\n\t\t\tdir: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Project directory (defaults to the current directory)\"),\n\t\t}),\n\t\trun: async (c) => {\n\t\t\tconst projectDir = c.options.dir\n\t\t\t\t? resolve(c.options.dir)\n\t\t\t\t: findProjectDir();\n\t\t\tconst config = projectDir ? readAppConfig(projectDir) : null;\n\t\t\tif (!projectDir || !config) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"NO_PROJECT\",\n\t\t\t\t\tmessage: `No ${APP_CONFIG_FILENAME} found in this directory or any parent. Run \\`whop apps deploy\\` to link this project to a Whop app.`,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"apps deploy\",\n\t\t\t\t\t\t\t\tdescription: \"Link this project to a Whop app and ship it\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Server-side SDK calls read WHOP_API_KEY; mint a short-lived access\n\t\t\t// token from the CLI's credential so they work in local dev with zero\n\t\t\t// env setup. An explicitly exported WHOP_API_KEY wins.\n\t\t\tconst injected: Record<string, string> = {\n\t\t\t\tWHOP_APP_ID: config.app_id,\n\t\t\t};\n\t\t\tif (process.env.WHOP_API_KEY) {\n\t\t\t\tlog(\n\t\t\t\t\tc,\n\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t\"Using the WHOP_API_KEY from your environment for server-side calls.\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst minted = await createDevAccessToken();\n\t\t\t\t\tinjected.WHOP_API_KEY = minted.token;\n\t\t\t\t\tconst expiresAt =\n\t\t\t\t\t\ttypeof minted.expires_at === \"number\"\n\t\t\t\t\t\t\t? new Date(minted.expires_at * 1000)\n\t\t\t\t\t\t\t: minted.expires_at\n\t\t\t\t\t\t\t\t? new Date(minted.expires_at)\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\tconst expiry = expiresAt\n\t\t\t\t\t\t? ` (expires ${expiresAt.toLocaleTimeString()})`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t\t`Injected a temporary access token as WHOP_API_KEY${expiry} — server-side SDK calls just work. Restart \\`whop apps dev\\` to refresh it.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Couldn't mint a temporary access token (${err instanceof Error ? err.message : \"unknown error\"}) — set WHOP_API_KEY manually for server-side calls.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Mirror the hosted runtime: the app's secrets become env vars for the\n\t\t\t// dev server. Explicitly exported env vars win over stored secrets.\n\t\t\ttry {\n\t\t\t\tconst remote = await getApp(config.app_id);\n\t\t\t\tconst secretEntries = Object.entries(remote.secrets ?? {}).filter(\n\t\t\t\t\t([key]) => !(key in process.env) && !(key in injected),\n\t\t\t\t);\n\t\t\t\tconst unsafe = secretEntries.filter(([key]) => isUnsafeDevEnvKey(key));\n\t\t\t\tfor (const [key, value] of secretEntries) {\n\t\t\t\t\tif (!isUnsafeDevEnvKey(key)) injected[key] = value;\n\t\t\t\t}\n\t\t\t\tif (unsafe.length > 0) {\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Skipped app secret${unsafe.length === 1 ? \"\" : \"s\"} ${unsafe.map(([key]) => key).join(\", \")} — these names control the local runtime and are never injected by \\`whop apps dev\\`.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst injectedCount = secretEntries.length - unsafe.length;\n\t\t\t\tif (injectedCount > 0) {\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t\t`Injected ${injectedCount} app secret${injectedCount === 1 ? \"\" : \"s\"} into the environment (${secretEntries\n\t\t\t\t\t\t\t\t.filter(([key]) => !isUnsafeDevEnvKey(key))\n\t\t\t\t\t\t\t\t.map(([key]) => key)\n\t\t\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlog(\n\t\t\t\t\tc,\n\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t`Couldn't fetch app secrets (${err instanceof Error ? err.message : \"unknown error\"}) — continuing without them.`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(c, chalk.dim(`Starting dev server for ${config.name}...`));\n\t\t\ttry {\n\t\t\t\trunScript(projectDir, \"dev\", injected);\n\t\t\t} catch (err) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"DEV_FAILED\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\terr instanceof Error\n\t\t\t\t\t\t\t? err.message\n\t\t\t\t\t\t\t: \"Dev server exited with an error\",\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn c.ok({ success: true });\n\t\t},\n\t});\n\n\tapp.command(\"deploy\", {\n\t\tdescription: \"Build, upload and ship this app live\",\n\t\thint: \"The one-stop deploy: verifies the project is a Whop-ready Vite app (offering to scaffold or link one if not), builds, typechecks, uploads the build, and promotes it to production. Use --skip_promote to upload a preview-only build, then promote it later with `whop apps builds promote <build_id>`.\",\n\t\toptions: z.object({\n\t\t\tdir: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Project directory (defaults to the current directory)\"),\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t\"Link this project to an app (app_xxx) before deploying — writes whop.app.json, replacing any existing link\",\n\t\t\t\t),\n\t\t\tskip_promote: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Upload the build without promoting it to production\"),\n\t\t\tskip_typecheck: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Skip the typecheck step\"),\n\t\t\tskip_build: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Skip the build step and upload the existing dist/ output\"),\n\t\t}),\n\t\toutput: BuildSchema,\n\t\toutputPolicy: \"agent-only\",\n\t\texamples: [\n\t\t\t{ description: \"Build and ship to production\" },\n\t\t\t{\n\t\t\t\toptions: { app: \"app_xxxxxxxx\" },\n\t\t\t\tdescription: \"Link this project to an existing app, then deploy\",\n\t\t\t},\n\t\t\t{\n\t\t\t\toptions: { skip_promote: true },\n\t\t\t\tdescription: \"Upload a preview build without promoting\",\n\t\t\t},\n\t\t],\n\t\trun: async (c) => {\n\t\t\ttry {\n\t\t\t\tconst pm = ensurePackageManager();\n\n\t\t\t\tconst { projectDir, freshlyScaffolded } = await ensureViteApp(\n\t\t\t\t\tc,\n\t\t\t\t\tpm,\n\t\t\t\t\tc.options.dir,\n\t\t\t\t);\n\n\t\t\t\tconst config = await ensureAppLinked(c, projectDir, c.options.app);\n\n\t\t\t\tconst { manualSteps } = whopifyProject({\n\t\t\t\t\ttargetDir: projectDir,\n\t\t\t\t\troute: config.route,\n\t\t\t\t});\n\t\t\t\tif (manualSteps.length > 0) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"WHOPIFY_INCOMPLETE\",\n\t\t\t\t\t\tmessage: `${config.name} is linked (${config.app_id}), but the project isn't fully wired for Whop hosting yet. Complete these steps:\\n\\n${formatManualSteps(manualSteps)}\\n\\nThen re-run \\`whop apps deploy\\` — it re-checks the wiring and applies anything it can.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (!c.options.skip_build) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfreshlyScaffolded ||\n\t\t\t\t\t\t!existsSync(join(projectDir, \"node_modules\", \"@whop\", \"cli\"))\n\t\t\t\t\t) {\n\t\t\t\t\t\t// whopifyProject adds @whop/cli as a devDependency (the vite\n\t\t\t\t\t\t// config imports whop() from @whop/cli/vite), so the build needs\n\t\t\t\t\t\t// it installed.\n\t\t\t\t\t\trunInstall(c, projectDir);\n\t\t\t\t\t}\n\t\t\t\t\t// Build BEFORE typecheck: framework builds generate typed artifacts\n\t\t\t\t\t// the typecheck depends on (TanStack's routeTree.gen), so a fresh\n\t\t\t\t\t// never-built project would otherwise always fail its first deploy.\n\t\t\t\t\tlog(c, chalk.dim(\"[1/4] Building...\"));\n\t\t\t\t\trunScript(projectDir, \"build\", { WHOP_APP_ID: config.app_id });\n\t\t\t\t\tif (!c.options.skip_typecheck && hasScript(projectDir, \"typecheck\")) {\n\t\t\t\t\t\tlog(c, chalk.dim(\"[2/4] Typechecking...\"));\n\t\t\t\t\t\trunScript(projectDir, \"typecheck\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst archivePath = join(projectDir, BUILD_ARCHIVE);\n\t\t\t\tif (!existsSync(archivePath)) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"NO_BUILD_ARCHIVE\",\n\t\t\t\t\t\tmessage: `No build archive at ${BUILD_ARCHIVE}. Add the whop() plugin from @whop/cli/vite to your vite config, then build. See https://whop.com/docs/apps/hosting.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst zip = readFileSync(archivePath);\n\t\t\t\tconst sizeMb = (zip.byteLength / 1024 / 1024).toFixed(1);\n\t\t\t\tconst checksum = createHash(\"sha256\").update(zip).digest(\"hex\");\n\n\t\t\t\tconst spin = c.agent ? null : spinner();\n\t\t\t\tspin?.start(`[3/4] Uploading build archive (${sizeMb} MB)`);\n\t\t\t\tlet build;\n\t\t\t\ttry {\n\t\t\t\t\tconst fileId = await uploadBuildArchive(\n\t\t\t\t\t\tnew Uint8Array(zip),\n\t\t\t\t\t\t`${config.route}-build.zip`,\n\t\t\t\t\t);\n\t\t\t\t\tspin?.message(\"[3/4] Processing archive\");\n\t\t\t\t\tawait waitForFileReady(fileId);\n\t\t\t\t\tspin?.message(\"[3/4] Creating build\");\n\t\t\t\t\tbuild = await createAppBuild({\n\t\t\t\t\t\tapp_id: config.app_id,\n\t\t\t\t\t\tchecksum,\n\t\t\t\t\t\tfile_id: fileId,\n\t\t\t\t\t});\n\t\t\t\t\tspin?.stop(`[3/4] Build uploaded (${build.id})`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tspin?.error(\"[3/4] Upload failed\");\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tif (!c.options.skip_promote) {\n\t\t\t\t\tconst promoteSpin = c.agent ? null : spinner();\n\t\t\t\t\tpromoteSpin?.start(\"[4/4] Promoting to production\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait promoteAppBuild(build.id);\n\t\t\t\t\t\tbuild = await waitForBuildPromotion(build.id);\n\t\t\t\t\t\tpromoteSpin?.stop(\n\t\t\t\t\t\t\tbuild.is_production\n\t\t\t\t\t\t\t\t? \"[4/4] Promoted to production\"\n\t\t\t\t\t\t\t\t: `[4/4] Promotion pending (status: ${build.status})`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tpromoteSpin?.error(\"[4/4] Promote failed\");\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog(c, chalk.dim(\"[4/4] Skipping promotion (--skip_promote)\"));\n\t\t\t\t}\n\n\t\t\t\tconst promoted = build.is_production === true;\n\t\t\t\tconst productionUrl = promoted\n\t\t\t\t\t? ((await getApp(config.app_id)).hosted_url ?? undefined)\n\t\t\t\t\t: undefined;\n\n\t\t\t\tif (!c.agent && !c.formatExplicit) {\n\t\t\t\t\tconst cdTarget = relative(process.cwd(), projectDir) || \".\";\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\tchalk.green.bold(\n\t\t\t\t\t\t\t\tpromoted ? \"✓ Deployed to production\" : \"✓ Build uploaded\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t` ${chalk.dim(build.id)}`,\n\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\t...(promoted && productionUrl\n\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t` ${chalk.bold(\"Live\")} ${chalk.cyan.underline(productionUrl)}`,\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t`${chalk.bold(\"Promote when ready\")} ${chalk.cyan.bold(`whop apps builds promote ${build.id}`)}`,\n\t\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t...(freshlyScaffolded\n\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\t\t\t\tchalk.bold(\"Next\"),\n\t\t\t\t\t\t\t\t\t\t...(cdTarget !== \".\" ? [` cd ${cdTarget}`] : []),\n\t\t\t\t\t\t\t\t\t\t` ${chalk.cyan.bold(\"whop apps dev\")} ${chalk.dim(\"→ local dev server\")}`,\n\t\t\t\t\t\t\t\t\t\t` ${chalk.cyan.bold(\"whop apps deploy\")} ${chalk.dim(\"→ ship your changes\")}`,\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t: []),\n\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn c.ok(\n\t\t\t\t\t{\n\t\t\t\t\t\tid: build.id,\n\t\t\t\t\t\tstatus: build.status,\n\t\t\t\t\t\tis_production: promoted,\n\t\t\t\t\t\turl: productionUrl,\n\t\t\t\t\t},\n\t\t\t\t\tpromoted\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tcta: {\n\t\t\t\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcommand: `apps builds promote ${build.id}`,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Promote this build to production\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof DeployAbort) return c.error(err.options);\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"DEPLOY_FAILED\",\n\t\t\t\t\tmessage: err instanceof Error ? err.message : \"Deploy failed\",\n\t\t\t\t\tretryable: true,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t});\n\n\treturn app;\n}\n","import { createWhopFetch } from \"../api/index.js\";\n\nconst PLACEHOLDER = \"https://api.whop.com\";\nconst whopFetch = createWhopFetch();\n\n/**\n * Thin wrapper around the API fetch proxy for hand-written commands. The proxy\n * strips the host and uses apiBaseUrl() internally, auto-fills the active\n * account, and normalizes errors to a top-level `message` — so we only need the\n * pathname (a query string in `path` is fine) and can surface `message` directly.\n */\nexport async function makeWhopRequest<T>(\n\tmethod: \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\",\n\tpath: string,\n\tbody?: Record<string, unknown>,\n): Promise<T> {\n\tconst init: RequestInit = { method };\n\tif (body !== undefined) init.body = JSON.stringify(body);\n\tconst res = await whopFetch(new Request(`${PLACEHOLDER}${path}`, init));\n\n\tif (!res.ok) {\n\t\tconst payload = (await res.json().catch(() => null)) as {\n\t\t\tmessage?: string;\n\t\t} | null;\n\t\tthrow new Error(payload?.message ?? res.statusText);\n\t}\n\n\t// DELETE (and other 204s) can return an empty body, which `res.json()` would\n\t// reject — treat an empty body as a successful, content-less response.\n\tconst text = await res.text();\n\treturn (text ? JSON.parse(text) : { success: true }) as T;\n}\n","import { resolveActiveAccountId } from \"../api/index.js\";\nimport { makeWhopRequest } from \"../journey/client.js\";\n\nexport type WhopApp = {\n\tid: string;\n\tname: string;\n\troute?: string | null;\n\thosted_url?: string | null;\n\tsecrets?: Record<string, string> | null;\n\tcreated_at?: number;\n};\n\nexport type WhopAppBuild = {\n\tid: string;\n\tstatus: \"draft\" | \"pending\" | \"approved\" | \"rejected\";\n\tplatform: string;\n\tchecksum: string;\n\tis_production: boolean;\n\tcreated_at?: number;\n};\n\ntype WhopFile = {\n\tid: string;\n\tupload_status: string;\n\tupload_url?: string | null;\n\tupload_headers?: Record<string, string> | null;\n};\n\nexport async function createApp(input: {\n\tname: string;\n\troute: string;\n\tcompany_id?: string;\n}): Promise<WhopApp> {\n\tconst company_id = input.company_id ?? (await resolveActiveAccountId());\n\treturn makeWhopRequest<WhopApp>(\"POST\", \"/apps\", { ...input, company_id });\n}\n\nconst DEV_TOKEN_TTL_MS = (3 * 60 - 1) * 60 * 1000;\n\n/**\n * Mints a short-lived access token from the CLI's credential (POST\n * /access_tokens): with an API key it's a company token inheriting the key's\n * permissions; with OAuth login the user and scopes come from the token\n * itself (which also pins the expiry). `whop apps dev` injects it into the\n * dev server so server-side SDK calls work without manual env vars.\n */\nexport async function createDevAccessToken(): Promise<{\n\ttoken: string;\n\texpires_at?: string | number | null;\n}> {\n\tconst company_id = await resolveActiveAccountId();\n\treturn makeWhopRequest(\"POST\", \"/access_tokens\", {\n\t\t...(company_id ? { company_id } : {}),\n\t\texpires_at: new Date(Date.now() + DEV_TOKEN_TTL_MS).toISOString(),\n\t});\n}\n\nexport async function listApps(): Promise<WhopApp[]> {\n\tconst companyId = await resolveActiveAccountId();\n\tconst query = companyId ? `?company_id=${encodeURIComponent(companyId)}` : \"\";\n\tconst response = await makeWhopRequest<{ data?: WhopApp[] }>(\n\t\t\"GET\",\n\t\t`/apps${query}`,\n\t);\n\treturn response.data ?? [];\n}\n\nexport async function getApp(appId: string): Promise<WhopApp> {\n\treturn makeWhopRequest<WhopApp>(\"GET\", `/apps/${appId}`);\n}\n\nexport async function updateAppRoute(\n\tappId: string,\n\troute: string,\n): Promise<WhopApp> {\n\treturn makeWhopRequest<WhopApp>(\"PATCH\", `/apps/${appId}`, { route });\n}\n\nexport async function updateAppSecrets(\n\tappId: string,\n\tsecrets: Record<string, string | null>,\n): Promise<WhopApp> {\n\treturn makeWhopRequest<WhopApp>(\"PATCH\", `/apps/${appId}`, { secrets });\n}\n\nexport async function createAppBuild(input: {\n\tapp_id: string;\n\tchecksum: string;\n\tfile_id: string;\n}): Promise<WhopAppBuild> {\n\treturn makeWhopRequest<WhopAppBuild>(\"POST\", \"/app_builds\", {\n\t\tapp_id: input.app_id,\n\t\tplatform: \"web\",\n\t\tchecksum: input.checksum,\n\t\tattachment: { id: input.file_id },\n\t});\n}\n\nexport async function getAppBuild(buildId: string): Promise<WhopAppBuild> {\n\treturn makeWhopRequest<WhopAppBuild>(\"GET\", `/app_builds/${buildId}`);\n}\n\nexport async function promoteAppBuild(buildId: string): Promise<WhopAppBuild> {\n\treturn makeWhopRequest<WhopAppBuild>(\n\t\t\"POST\",\n\t\t`/app_builds/${buildId}/promote`,\n\t\t{},\n\t);\n}\n\n/**\n * Uploads a build archive: creates a file record, PUTs the bytes to the\n * presigned URL, and returns the file id. The archive is public so the hosting\n * worker can fetch it from a stable CDN URL. The file is still `pending` when\n * this returns — call waitForFileReady before attaching it to a build.\n */\nexport async function uploadBuildArchive(\n\tzip: Uint8Array,\n\tfilename: string,\n): Promise<string> {\n\tconst file = await makeWhopRequest<WhopFile>(\"POST\", \"/files\", {\n\t\tfilename,\n\t\tvisibility: \"public\",\n\t});\n\n\tif (!file.upload_url) {\n\t\tthrow new Error(\"File creation did not return an upload URL.\");\n\t}\n\n\tconst body = new Uint8Array(zip).buffer as ArrayBuffer;\n\tconst uploadResponse = await fetch(file.upload_url, {\n\t\tmethod: \"PUT\",\n\t\theaders: file.upload_headers ?? { \"Content-Type\": \"application/zip\" },\n\t\tbody,\n\t});\n\tif (!uploadResponse.ok) {\n\t\tthrow new Error(\n\t\t\t`Archive upload failed: ${uploadResponse.status} ${await uploadResponse.text()}`,\n\t\t);\n\t}\n\n\treturn file.id;\n}\n\n/**\n * Polls the file until upload processing marks it `ready`. Direct-to-S3 uploads\n * complete asynchronously (the S3 event pipeline verifies the object and flips\n * the status), so a build can only attach the file once it is ready.\n */\nexport async function waitForFileReady(\n\tfileId: string,\n\ttimeoutMs = 60_000,\n): Promise<void> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() < deadline) {\n\t\tconst file = await makeWhopRequest<WhopFile>(\"GET\", `/files/${fileId}`);\n\t\tif (file.upload_status === \"ready\") return;\n\t\tawait sleep(1_000);\n\t}\n\tthrow new Error(\n\t\t\"Timed out waiting for the build archive to finish processing.\",\n\t);\n}\n\nexport async function waitForBuildPromotion(\n\tbuildId: string,\n\ttimeoutMs = 30_000,\n): Promise<WhopAppBuild> {\n\tconst deadline = Date.now() + timeoutMs;\n\tlet latest = await getAppBuild(buildId);\n\twhile (Date.now() < deadline) {\n\t\tif (latest.is_production) return latest;\n\t\tif (latest.status === \"rejected\") {\n\t\t\tthrow new Error(\"Build was rejected and cannot be promoted.\");\n\t\t}\n\t\tawait sleep(750);\n\t\tlatest = await getAppBuild(buildId);\n\t}\n\treturn latest;\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nexport const APP_CONFIG_FILENAME = \"whop.app.json\";\n\nexport type AppConfig = {\n\tapp_id: string;\n\tname: string;\n\troute: string;\n};\n\nexport function findProjectDir(startDir?: string): string | null {\n\tlet dir = resolve(startDir ?? process.cwd());\n\tfor (let i = 0; i < 25; i++) {\n\t\tif (existsSync(join(dir, APP_CONFIG_FILENAME))) return dir;\n\t\tconst parent = resolve(dir, \"..\");\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\treturn null;\n}\n\nexport function readAppConfig(projectDir: string): AppConfig | null {\n\tconst path = join(projectDir, APP_CONFIG_FILENAME);\n\tif (!existsSync(path)) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(\n\t\t\treadFileSync(path, \"utf-8\"),\n\t\t) as Partial<AppConfig>;\n\t\tif (\n\t\t\ttypeof parsed.app_id === \"string\" &&\n\t\t\ttypeof parsed.name === \"string\" &&\n\t\t\ttypeof parsed.route === \"string\"\n\t\t) {\n\t\t\treturn { app_id: parsed.app_id, name: parsed.name, route: parsed.route };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function writeAppConfig(projectDir: string, config: AppConfig): void {\n\twriteFileSync(\n\t\tjoin(projectDir, APP_CONFIG_FILENAME),\n\t\t`${JSON.stringify(config, null, \"\\t\")}\\n`,\n\t);\n}\n\nexport function slugify(name: string): string {\n\treturn name\n\t\t.toLowerCase()\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t.replace(/^-+|-+$/g, \"\")\n\t\t.slice(0, 63);\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport { buildVersion } from \"../lib/build-info.js\";\n\n/**\n * Scaffolding for `whop apps deploy`.\n *\n * Instead of shipping a template inside this package, we run TanStack's\n * official create command (`@tanstack/cli create`) with the Cloudflare\n * deployment adapter — always the latest upstream template — and then apply\n * the minimal Whop edits on top: the `whop()` vite plugin (imported from\n * `@whop/cli/vite`), a `deploy` script, and the worker name.\n */\n\n// Windows needs shell resolution for npx/pnpm/bunx (they are .cmd shims).\nconst SPAWN_VIA_SHELL = process.platform === \"win32\";\n\nexport type PackageManager = \"npm\" | \"pnpm\" | \"bun\" | \"yarn\";\n\nconst DLX_RUNNERS: Record<PackageManager, string[]> = {\n\tnpm: [\"npx\", \"-y\"],\n\tpnpm: [\"pnpm\", \"dlx\"],\n\tbun: [\"bunx\"],\n\tyarn: [\"yarn\", \"dlx\"],\n};\n\n/** Auto-detection order when --pm is not passed. */\nexport const PM_PRIORITY = [\n\t\"bun\",\n\t\"pnpm\",\n\t\"npm\",\n] as const satisfies readonly PackageManager[];\n\nexport function isPmInstalled(pm: PackageManager): boolean {\n\tconst result = spawnSync(pm, [\"--version\"], {\n\t\tstdio: \"ignore\",\n\t\tshell: SPAWN_VIA_SHELL,\n\t});\n\treturn !result.error && result.status === 0;\n}\n\n/** First installed package manager, preferring bun, then pnpm, then npm. */\nexport function detectPackageManager(): PackageManager | null {\n\treturn PM_PRIORITY.find(isPmInstalled) ?? null;\n}\n\nexport function pmInstallHint(pm: PackageManager): string {\n\tconst win = process.platform === \"win32\";\n\tswitch (pm) {\n\t\tcase \"bun\":\n\t\t\treturn win\n\t\t\t\t? 'powershell -c \"irm bun.sh/install.ps1 | iex\"'\n\t\t\t\t: \"curl -fsSL https://bun.sh/install | bash\";\n\t\tcase \"pnpm\":\n\t\t\treturn win\n\t\t\t\t? 'powershell -c \"irm get.pnpm.io/install.ps1 | iex\"'\n\t\t\t\t: \"curl -fsSL https://get.pnpm.io/install.sh | sh -\";\n\t\tcase \"npm\":\n\t\t\treturn \"install Node.js (includes npm): https://nodejs.org\";\n\t\tcase \"yarn\":\n\t\t\treturn \"npm install -g yarn\";\n\t}\n}\n\nconst TANSTACK_CREATE_FLAGS = [\n\t\"--framework\",\n\t\"React\",\n\t\"--deployment\",\n\t\"cloudflare\",\n\t\"--no-git\",\n\t\"--no-install\",\n\t\"--no-intent\",\n\t\"--no-toolchain\",\n\t\"--no-examples\",\n\t\"--non-interactive\",\n];\n\n/** The exact scaffold command an agent (or human) can run themselves. */\nexport function tanstackCreateCommand(\n\tpm: PackageManager,\n\tprojectName: string,\n): string {\n\treturn [\n\t\t...DLX_RUNNERS[pm],\n\t\t\"@tanstack/cli@latest\",\n\t\t\"create\",\n\t\tprojectName,\n\t\t...TANSTACK_CREATE_FLAGS,\n\t].join(\" \");\n}\n\n/** The last lines of a captured child process's output, for error messages. */\nexport function outputTail(result: {\n\tstdout: string | null;\n\tstderr: string | null;\n}): string {\n\tconst combined = [result.stdout, result.stderr]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tif (!combined) return \"\";\n\treturn `\\n\\n${combined.split(\"\\n\").slice(-15).join(\"\\n\")}`;\n}\n\n/**\n * Output is captured, not streamed: the template's own banner and \"next\n * steps\" would conflict with the deploy flow's single summary at the end.\n * It resurfaces in the error message when the create fails.\n */\nexport function runTanstackCreate(options: {\n\ttargetDir: string;\n\tprojectName: string;\n\tpm: PackageManager;\n}): void {\n\tconst [runner, ...runnerArgs] = DLX_RUNNERS[options.pm];\n\tconst result = spawnSync(\n\t\trunner!,\n\t\t[\n\t\t\t...runnerArgs,\n\t\t\t\"@tanstack/cli@latest\",\n\t\t\t\"create\",\n\t\t\toptions.projectName,\n\t\t\t\"--target-dir\",\n\t\t\toptions.targetDir,\n\t\t\t...TANSTACK_CREATE_FLAGS,\n\t\t],\n\t\t{\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tencoding: \"utf-8\",\n\t\t\tshell: SPAWN_VIA_SHELL,\n\t\t},\n\t);\n\tif (result.error) throw result.error;\n\tif (result.status !== 0) {\n\t\tthrow new Error(\n\t\t\t`\\`${options.pm === \"npm\" ? \"npx\" : options.pm} @tanstack/cli create\\` failed (exit ${result.status}). Check your network connection and try again.${outputTail(result)}`,\n\t\t);\n\t}\n}\n\nconst VITE_CONFIG_NAMES = [\n\t\"vite.config.ts\",\n\t\"vite.config.mts\",\n\t\"vite.config.js\",\n\t\"vite.config.mjs\",\n];\n\nexport function findViteConfig(dir: string): string | undefined {\n\treturn VITE_CONFIG_NAMES.map((name) => join(dir, name)).find((path) =>\n\t\texistsSync(path),\n\t);\n}\n\nconst WRANGLER_CONFIG_NAMES = [\"wrangler.jsonc\", \"wrangler.json\"];\n\nfunction cliDependencyVersion(): string {\n\treturn buildVersion ? `^${buildVersion}` : \"latest\";\n}\n\n/**\n * Wires a Vite project for Whop hosting: the whop() pack plugin, deploy\n * script, @whop/cli devDependency, and the worker name. Works on any Vite\n * project, not just fresh scaffolds — every edit is idempotent, so re-running\n * after fixing something is safe.\n *\n * Anything that can't be applied automatically is returned as a manual step:\n * a self-contained instruction precise enough for an agent (or human) to\n * finish the whopification by hand.\n */\nexport function whopifyProject(options: { targetDir: string; route: string }): {\n\tmanualSteps: string[];\n} {\n\tconst manualSteps: string[] = [];\n\tpatchPackageJson(options.targetDir, manualSteps);\n\tpatchViteConfig(options.targetDir, manualSteps);\n\tpatchWranglerConfig(options.targetDir, options.route, manualSteps);\n\treturn { manualSteps };\n}\n\nfunction patchPackageJson(dir: string, manualSteps: string[]): void {\n\tconst file = join(dir, \"package.json\");\n\tlet pkg: {\n\t\tscripts?: Record<string, string>;\n\t\tdevDependencies?: Record<string, string>;\n\t};\n\ttry {\n\t\tpkg = JSON.parse(readFileSync(file, \"utf-8\")) as typeof pkg;\n\t} catch {\n\t\tmanualSteps.push(\n\t\t\t`package.json could not be parsed. Add a \"deploy\": \"whop apps deploy\" script, a \"typecheck\" script, and a devDependency \"@whop/cli\": \"${cliDependencyVersion()}\".`,\n\t\t);\n\t\treturn;\n\t}\n\n\tpkg.scripts = {\n\t\t...pkg.scripts,\n\t\tdeploy: \"whop apps deploy\",\n\t\ttypecheck: pkg.scripts?.typecheck ?? \"tsc --noEmit\",\n\t};\n\tpkg.devDependencies = {\n\t\t...pkg.devDependencies,\n\t\t// The project imports the whop() vite plugin from @whop/cli/vite.\n\t\t\"@whop/cli\": pkg.devDependencies?.[\"@whop/cli\"] ?? cliDependencyVersion(),\n\t};\n\n\twriteFileSync(file, `${JSON.stringify(pkg, null, 2)}\\n`);\n}\n\nfunction patchViteConfig(dir: string, manualSteps: string[]): void {\n\tconst file = findViteConfig(dir);\n\tif (!file) {\n\t\tmanualSteps.push(\n\t\t\t\"No vite config found (looked for vite.config.ts/.mts/.js/.mjs). Whop hosting serves Vite builds — create a vite config that builds with @cloudflare/vite-plugin (emitting dist/client and, for SSR, dist/server) and includes the whop() plugin from @whop/cli/vite in its plugins array.\",\n\t\t);\n\t\treturn;\n\t}\n\n\tlet content = readFileSync(file, \"utf-8\");\n\tconst hasWhopPlugin = content.includes(\"@whop/cli/vite\");\n\n\tif (!hasWhopPlugin) {\n\t\tconst pluginsOpen = /plugins:\\s*\\[/;\n\t\tif (!pluginsOpen.test(content)) {\n\t\t\tmanualSteps.push(\n\t\t\t\t`Could not find a \\`plugins: [...]\\` array in ${basename(file)}. Add \\`import { whop } from '@whop/cli/vite'\\` and include \\`whop()\\` in the config's plugins so builds pack dist/whop-build.zip.`,\n\t\t\t);\n\t\t} else {\n\t\t\tcontent = `import { whop } from '@whop/cli/vite'\\n${content}`;\n\t\t\tcontent = content.replace(\n\t\t\t\tpluginsOpen,\n\t\t\t\t(match) => `${match}\\n whop(),`,\n\t\t\t);\n\t\t\twriteFileSync(file, content);\n\t\t}\n\t}\n\n\tif (!content.includes(\"@cloudflare/vite-plugin\")) {\n\t\tmanualSteps.push(\n\t\t\t`${basename(file)} does not use @cloudflare/vite-plugin. Whop hosting runs builds on Cloudflare Workers: install @cloudflare/vite-plugin and wrangler, add \\`cloudflare({ viteEnvironment: { name: 'ssr' } })\\` to the plugins array (before your framework plugin), and make sure \\`vite build\\` emits dist/client (static assets) and dist/server (worker modules with an index.js entry).`,\n\t\t);\n\t}\n}\n\nfunction patchWranglerConfig(\n\tdir: string,\n\troute: string,\n\tmanualSteps: string[],\n): void {\n\tconst file = WRANGLER_CONFIG_NAMES.map((name) => join(dir, name)).find(\n\t\t(path) => existsSync(path),\n\t);\n\tif (!file) {\n\t\tmanualSteps.push(\n\t\t\t`No wrangler config found. Create wrangler.jsonc with: { \"name\": \"${route}\", \"compatibility_date\": \"<today>\", \"compatibility_flags\": [\"nodejs_compat\"], \"main\": \"<your framework's server entry>\" } (for TanStack Start the main is \"@tanstack/react-start/server-entry\").`,\n\t\t);\n\t\treturn;\n\t}\n\n\tconst content = readFileSync(file, \"utf-8\");\n\tconst updated = replaceTopLevelName(content, route);\n\tif (updated) {\n\t\twriteFileSync(file, updated);\n\t} else {\n\t\tmanualSteps.push(\n\t\t\t`Set the top-level \"name\" in ${basename(file)} to \"${route}\" so the worker is named after the app's route.`,\n\t\t);\n\t}\n}\n\n// Rewrites the top-level \"name\" key's value in a wrangler.json(c) document.\n// A plain first-match regex could hit a nested \"name\" (e.g. a kv_namespaces\n// entry) or a string value, so this walks the document skipping strings and\n// JSONC comments while tracking nesting depth. Returns null when no top-level\n// name key exists.\nfunction replaceTopLevelName(content: string, route: string): string | null {\n\tlet depth = 0;\n\tlet i = 0;\n\twhile (i < content.length) {\n\t\tconst ch = content[i];\n\t\tif (ch === '\"') {\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < content.length && content[j] !== '\"') {\n\t\t\t\tj += content[j] === \"\\\\\" ? 2 : 1;\n\t\t\t}\n\t\t\tif (depth === 1 && content.slice(i + 1, j) === \"name\") {\n\t\t\t\tconst after = content.slice(j + 1);\n\t\t\t\tconst value = after.match(/^(\\s*:\\s*)\"(?:[^\"\\\\]|\\\\.)*\"/);\n\t\t\t\tif (value) {\n\t\t\t\t\tconst start = j + 1 + value[1]!.length;\n\t\t\t\t\tconst end = j + 1 + value[0]!.length;\n\t\t\t\t\treturn `${content.slice(0, start)}\"${route}\"${content.slice(end)}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti = j + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"/\" && content[i + 1] === \"/\") {\n\t\t\tconst newline = content.indexOf(\"\\n\", i);\n\t\t\ti = newline === -1 ? content.length : newline + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"/\" && content[i + 1] === \"*\") {\n\t\t\tconst close = content.indexOf(\"*/\", i + 2);\n\t\t\ti = close === -1 ? content.length : close + 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"{\" || ch === \"[\") depth++;\n\t\tif (ch === \"}\" || ch === \"]\") depth--;\n\t\ti++;\n\t}\n\treturn null;\n}\n","import { z } from \"incur\";\nimport chalk from \"chalk\";\nimport { text, select, isCancel } from \"@clack/prompts\";\nimport { makeWhopRequest } from \"./client.js\";\nimport { resolveActiveAccountId } from \"../api/index.js\";\nimport { BILLING_PERIOD_DAYS } from \"./billing.js\";\nimport {\n\tgetActiveProfile,\n\tsetActiveProfileAccount,\n} from \"../auth/profiles.js\";\nimport { c } from \"../lib/colors.js\";\n\ninterface ListItem {\n\tid: string;\n\ttitle?: string | null;\n\tpurchase_url?: string | null;\n}\ninterface ListResponse {\n\tdata: ListItem[];\n}\n\nconst StepSchema = z.object({\n\tid: z.string(),\n\tlabel: z.string(),\n\tcomplete: z.boolean(),\n\tcount: z.number().optional(),\n\tfirstId: z.string().optional(),\n\tfirstTitle: z.string().optional(),\n});\n\nconst NextStepSchema = z.object({\n\tcommand: z.string(),\n\toptions: z.record(z.string(), z.string()).optional(),\n\tdescription: z.string(),\n\thint: z.string().optional(),\n});\n\nexport const quickstartOptions = z.object({\n\ttitle: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Product name — providing this (or --price/--billing_period) makes quickstart create your product\",\n\t\t),\n\tprice: z.coerce\n\t\t.number()\n\t\t.optional()\n\t\t.describe(\"Price in the plan's currency (e.g. 9.99 for $9.99, 0 = free)\"),\n\tbilling_period: z\n\t\t.enum([\n\t\t\t\"monthly\",\n\t\t\t\"annually\",\n\t\t\t\"quarterly\",\n\t\t\t\"weekly\",\n\t\t\t\"daily\",\n\t\t\t\"every_two_years\",\n\t\t\t\"one_time\",\n\t\t])\n\t\t.optional()\n\t\t.describe(\"Billing interval — use 'one_time' for a single payment\"),\n\tbusiness_name: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Name for a new business account — quickstart creates it and sets up your product under it (user logins only; ignored with API-key auth, which already belongs to a business)\",\n\t\t),\n\taccount_id: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Business account to act on behalf of (biz_xxx); defaults to your active account\",\n\t\t),\n});\n\nexport const quickstartOutput = z.object({\n\taccount: z.string().nullable().describe(\"Authenticated account name\"),\n\tready: z\n\t\t.boolean()\n\t\t.describe(\"Whether you can take a sale now (a product with a plan exists)\"),\n\tcheckoutUrl: z\n\t\t.string()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t\"The live checkout link to share — the journey's payoff, present once a plan exists\",\n\t\t),\n\tcreated: z\n\t\t.object({\n\t\t\taccountId: z.string().optional(),\n\t\t\tproductId: z.string().optional(),\n\t\t\tplanId: z.string().optional(),\n\t\t})\n\t\t.nullable()\n\t\t.describe(\n\t\t\t\"What this run created, if anything — null for a read-only status check\",\n\t\t),\n\tsteps: z.array(StepSchema).describe(\"The path to your first sale\"),\n\tnextStep: NextStepSchema.nullable().describe(\n\t\t\"The single command to run next, pre-filled — null when nothing is required\",\n\t),\n});\n\ntype Step = z.infer<typeof StepSchema>;\ntype NextStep = z.infer<typeof NextStepSchema>;\n\ntype CtaCommand = {\n\tcommand: string;\n\tdescription?: string;\n\toptions?: Record<string, string>;\n};\n\ntype RunCtx = {\n\tagent: boolean;\n\tformatExplicit: boolean;\n\toptions: z.infer<typeof quickstartOptions>;\n\tsetupAgents?: () => Promise<void>;\n\tok: (data: z.infer<typeof quickstartOutput>) => never;\n\terror: (opts: {\n\t\tcode: string;\n\t\tmessage: string;\n\t\tretryable?: boolean;\n\t\texitCode?: number;\n\t\tcta?: { description?: string; commands: CtaCommand[] };\n\t}) => never;\n};\n\ntype ErrorEnvelope = Parameters<RunCtx[\"error\"]>[0];\n\n// incur's `c.error` is a sentinel that only takes effect when returned from the\n// command `run`. Nested helpers can't force the caller to return, so they throw\n// this instead; runCreate's caller catches it and returns `c.error(envelope)`,\n// preserving code/retryable/cta (which a plain thrown Error would lose).\nclass QuickstartError extends Error {\n\tconstructor(readonly envelope: ErrorEnvelope) {\n\t\tsuper(envelope.message);\n\t}\n}\n\nexport async function runQuickstart(c: RunCtx): Promise<never> {\n\tconst profile = getActiveProfile();\n\t// Mirror the auth middleware: a saved profile OR a WHOP_API_KEY env var (the\n\t// agent / CI path) is enough — don't reject env-key auth the gate let through.\n\tif (!profile && !process.env.WHOP_API_KEY) {\n\t\treturn c.error({\n\t\t\tcode: \"NOT_AUTHENTICATED\",\n\t\t\tmessage: \"Not logged in.\",\n\t\t\tcta: {\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\n\tif (!c.agent && !c.formatExplicit && c.setupAgents) {\n\t\ttry {\n\t\t\tawait c.setupAgents();\n\t\t} catch (err) {\n\t\t\tconst message =\n\t\t\t\terr instanceof Error ? err.message : \"Couldn't set up Whop for agents.\";\n\t\t\tconsole.log(`\\n${chalk.yellow(\"!\")} Agent setup skipped: ${message}`);\n\t\t\tconsole.log(\n\t\t\t\tchalk.dim(\n\t\t\t\t\t\" You can retry later with `whop skills add` and `whop mcp add`.\",\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst accountId =\n\t\tc.options.account_id ?? (await resolveActiveAccountId()) ?? \"\";\n\tconst accountName =\n\t\tprofile?.accountTitle ??\n\t\tprofile?.accountRoute ??\n\t\tprofile?.name ??\n\t\t\"your account\";\n\n\tconst interactive = !c.agent && !c.formatExplicit;\n\t// Business accounts belong to a user: an API key IS a business, so the\n\t// create-business flow only applies to user (OAuth) logins. With key auth,\n\t// quickstart just runs under the key's business — never errors, never\n\t// tries to create a sibling.\n\tconst canCreateBusiness = profile?.method === \"oauth\";\n\tlet newBusinessName = canCreateBusiness ? c.options.business_name : undefined;\n\tif (!canCreateBusiness && c.options.business_name !== undefined && interactive) {\n\t\tconsole.log(\n\t\t\t`\\n${chalk.dim(\"Ignoring --business_name — this API key already belongs to a business.\")}`,\n\t\t);\n\t}\n\n\tif (!accountId && newBusinessName === undefined) {\n\t\tif (!canCreateBusiness) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"NO_ACCOUNT\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"Couldn't resolve the business account for this API key. Check the key, or log in again.\",\n\t\t\t\tretryable: true,\n\t\t\t\tcta: {\n\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tif (!interactive) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"NO_ACCOUNT\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"No business account is linked to this login. Pass --business_name to create one and continue.\",\n\t\t\t\tretryable: true,\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: \"Create your business account and product in one run:\",\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\t\toptions: { business_name: \"My Business\" },\n\t\t\t\t\t\t\tdescription: \"Create a business account, then your product\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconsole.log(\n\t\t\t`\\n${chalk.bold(\"You don't have a business account yet — let's create one.\")}`,\n\t\t);\n\t\tconst name = await text({\n\t\t\tmessage: \"What's your business called?\",\n\t\t\tplaceholder: \"My Business\",\n\t\t});\n\t\tif (isCancel(name)) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Setup cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tnewBusinessName = name;\n\t}\n\n\tif (newBusinessName !== undefined) {\n\t\ttry {\n\t\t\treturn await runCreate(c, {\n\t\t\t\taccountId: \"\",\n\t\t\t\taccountName,\n\t\t\t\tproducts: [],\n\t\t\t\tnewBusinessName,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (err instanceof QuickstartError) return c.error(err.envelope);\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tconst [productsRes, plansRes, checkoutRes] = await Promise.allSettled([\n\t\tmakeWhopRequest<ListResponse>(\n\t\t\t\"GET\",\n\t\t\t`/products?company_id=${accountId}&first=100`,\n\t\t),\n\t\tmakeWhopRequest<ListResponse>(\n\t\t\t\"GET\",\n\t\t\t`/plans?account_id=${accountId}&first=100`,\n\t\t),\n\t\tmakeWhopRequest<ListResponse>(\n\t\t\t\"GET\",\n\t\t\t`/checkout_configurations?company_id=${accountId}&first=100`,\n\t\t),\n\t]);\n\n\t// Don't let a failed products/plans lookup masquerade as \"nothing exists\" —\n\t// that would show empty steps or, worse, prompt a duplicate create. Surface\n\t// the real error instead. A failed checkout lookup is non-critical.\n\tconst critical = [productsRes, plansRes].find((r) => r.status === \"rejected\");\n\tif (critical && critical.status === \"rejected\") {\n\t\tconst reason = critical.reason;\n\t\treturn c.error({\n\t\t\tcode: \"STATUS_CHECK_FAILED\",\n\t\t\tmessage: `Couldn't load your current setup: ${reason instanceof Error ? reason.message : \"API error\"}`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\n\tconst products =\n\t\tproductsRes.status === \"fulfilled\" ? (productsRes.value.data ?? []) : [];\n\tconst plans =\n\t\tplansRes.status === \"fulfilled\" ? (plansRes.value.data ?? []) : [];\n\tconst checkouts =\n\t\tcheckoutRes.status === \"fulfilled\" ? (checkoutRes.value.data ?? []) : [];\n\n\tconst ready = products.length > 0 && plans.length > 0;\n\tconst hasCreationFlags =\n\t\tc.options.title !== undefined ||\n\t\tc.options.price !== undefined ||\n\t\tc.options.billing_period !== undefined;\n\n\t// Mutate-gate: explicit creation flags always create (the user asked for it,\n\t// even on an already-set-up account). Without flags we only auto-guide a\n\t// create when something is missing AND we're interactive — so a ready account\n\t// in agent mode or with `--format`/`--json` stays a pure read-only status check.\n\tconst shouldCreate = hasCreationFlags || (!ready && interactive);\n\n\tif (shouldCreate) {\n\t\ttry {\n\t\t\treturn await runCreate(c, {\n\t\t\t\taccountId,\n\t\t\t\taccountName,\n\t\t\t\tproducts,\n\t\t\t\t// Only offer the new-business choice in the fully-guided flow —\n\t\t\t\t// flags mean the user already said what they want.\n\t\t\t\tofferNewBusiness:\n\t\t\t\t\tinteractive &&\n\t\t\t\t\t!hasCreationFlags &&\n\t\t\t\t\tc.options.account_id === undefined &&\n\t\t\t\t\tcanCreateBusiness,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (err instanceof QuickstartError) return c.error(err.envelope);\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tconst steps = buildSteps(products, plans);\n\tconst checkoutUrl = plans.find((p) => p.purchase_url)?.purchase_url ?? null;\n\tconst nextStep = resolveNextStep(products, plans, checkouts.length > 0);\n\n\tif (!c.agent && !c.formatExplicit) {\n\t\tprintSummary(accountName, steps, ready, checkoutUrl, nextStep);\n\t}\n\n\treturn c.ok({\n\t\taccount: accountName,\n\t\tready,\n\t\tcheckoutUrl,\n\t\tcreated: null,\n\t\tsteps,\n\t\tnextStep,\n\t});\n}\n\n/** Returns the provided value, errors in agent mode, or prompts interactively. */\nasync function resolveOrPrompt<T>(\n\tc: RunCtx,\n\tprovided: T | undefined,\n\tmissing: { code: string; message: string; example: string },\n\tprompt: () => Promise<T | symbol>,\n): Promise<T> {\n\tif (provided !== undefined) return provided;\n\tif (c.agent) {\n\t\tthrow new QuickstartError({\n\t\t\tcode: missing.code,\n\t\t\tmessage: `${missing.message} Example: ${missing.example}`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\tconst value = await prompt();\n\tif (isCancel(value))\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"CANCELLED\",\n\t\t\tmessage: \"Setup cancelled.\",\n\t\t\texitCode: 130,\n\t\t});\n\treturn value as T;\n}\n\nconst FULL_EXAMPLE =\n\t'whop quickstart --title \"My Course\" --price 9.99 --billing_period monthly';\n\nasync function runCreate(\n\tc: RunCtx,\n\tstate: {\n\t\taccountId: string;\n\t\taccountName: string;\n\t\tproducts: ListItem[];\n\t\tnewBusinessName?: string;\n\t\tofferNewBusiness?: boolean;\n\t},\n): Promise<never> {\n\tif (!c.agent) {\n\t\tconsole.log(`\\n${chalk.bold(\"Let's get you set up to sell.\")}\\n`);\n\t}\n\n\tlet { accountId, accountName, products, newBusinessName } = state;\n\n\tif (state.offerNewBusiness) {\n\t\tconst choice = await select<string>({\n\t\t\tmessage: \"Which business account is this for?\",\n\t\t\toptions: [\n\t\t\t\t{ value: \"current\", label: accountName, hint: accountId },\n\t\t\t\t{ value: \"new\", label: \"Create a new business account\" },\n\t\t\t],\n\t\t});\n\t\tif (isCancel(choice)) {\n\t\t\tthrow new QuickstartError({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Setup cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tif (choice === \"new\") {\n\t\t\tconst name = await text({\n\t\t\t\tmessage: \"What's your new business called?\",\n\t\t\t\tplaceholder: \"My Business\",\n\t\t\t});\n\t\t\tif (isCancel(name)) {\n\t\t\t\tthrow new QuickstartError({\n\t\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\t\tmessage: \"Setup cancelled.\",\n\t\t\t\t\texitCode: 130,\n\t\t\t\t});\n\t\t\t}\n\t\t\tnewBusinessName = name;\n\t\t\tproducts = [];\n\t\t}\n\t}\n\n\t// Create a new product when none exist or when an explicit --title is given\n\t// (the user named a product, so honor that intent even if they already have\n\t// others). Otherwise attach the new plan to an existing one.\n\t//\n\t// Gather every input up front, before any POST, so a partial invocation (e.g.\n\t// an agent passes --title but omits --price) fails cleanly without leaving an\n\t// orphaned business account or product behind — and so a cancelled TTY prompt\n\t// creates nothing.\n\tconst needsNewProduct =\n\t\tproducts.length === 0 || c.options.title !== undefined;\n\tconst newTitle = needsNewProduct\n\t\t? await resolveOrPrompt(\n\t\t\t\tc,\n\t\t\t\tc.options.title,\n\t\t\t\t{\n\t\t\t\t\tcode: \"TITLE_REQUIRED\",\n\t\t\t\t\tmessage: \"Pass --title to name your product.\",\n\t\t\t\t\texample: FULL_EXAMPLE,\n\t\t\t\t},\n\t\t\t\t() =>\n\t\t\t\t\ttext({\n\t\t\t\t\t\tmessage: \"What are you selling?\",\n\t\t\t\t\t\tplaceholder: \"My Online Course\",\n\t\t\t\t\t}),\n\t\t\t)\n\t\t: undefined;\n\tconst existing = needsNewProduct\n\t\t? undefined\n\t\t: await resolveExistingProduct(c, products);\n\n\tconst price = await resolveOrPrompt(\n\t\tc,\n\t\tc.options.price,\n\t\t{\n\t\t\tcode: \"PRICE_REQUIRED\",\n\t\t\tmessage: \"Pass --price in dollars (9.99 = $9.99, 0 = free).\",\n\t\t\texample: FULL_EXAMPLE,\n\t\t},\n\t\tasync () => {\n\t\t\tconst p = await text({\n\t\t\t\tmessage: \"Price in dollars (9.99 = $9.99, 0 = free):\",\n\t\t\t\tplaceholder: \"9.99\",\n\t\t\t\tvalidate: (v) => (isNaN(Number(v)) ? \"Enter a number\" : undefined),\n\t\t\t});\n\t\t\treturn isCancel(p) ? p : Number(p);\n\t\t},\n\t);\n\n\tconst billingPeriod = await resolveOrPrompt(\n\t\tc,\n\t\tc.options.billing_period,\n\t\t{\n\t\t\tcode: \"BILLING_PERIOD_REQUIRED\",\n\t\t\tmessage: \"Pass --billing_period (one_time, monthly, annually, …).\",\n\t\t\texample: FULL_EXAMPLE,\n\t\t},\n\t\t() =>\n\t\t\tselect({\n\t\t\t\tmessage: \"How should customers be charged?\",\n\t\t\t\toptions: [\n\t\t\t\t\t{ value: \"one_time\", label: \"One-time payment\" },\n\t\t\t\t\t{ value: \"monthly\", label: \"Monthly subscription\" },\n\t\t\t\t\t{ value: \"annually\", label: \"Annual subscription\" },\n\t\t\t\t\t{ value: \"quarterly\", label: \"Quarterly\" },\n\t\t\t\t],\n\t\t\t}) as Promise<NonNullable<typeof c.options.billing_period> | symbol>,\n\t);\n\n\tlet accountCreated = false;\n\tif (newBusinessName !== undefined) {\n\t\tlet account: { id: string; title?: string | null; route?: string | null };\n\t\ttry {\n\t\t\taccount = await makeWhopRequest<{\n\t\t\t\tid: string;\n\t\t\t\ttitle?: string | null;\n\t\t\t\troute?: string | null;\n\t\t\t}>(\"POST\", \"/accounts\", { title: newBusinessName });\n\t\t} catch (err) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"ACCOUNT_FAILED\",\n\t\t\t\tmessage: `Failed to create the business account: ${err instanceof Error ? err.message : \"unknown error\"}`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\taccountId = account.id;\n\t\taccountName = account.title ?? newBusinessName;\n\t\taccountCreated = true;\n\t\tsetActiveProfileAccount({\n\t\t\tid: account.id,\n\t\t\ttitle: account.title ?? undefined,\n\t\t\troute: account.route ?? undefined,\n\t\t});\n\t\tif (!c.agent) {\n\t\t\tconsole.log(\n\t\t\t\t`\\n${chalk.green(\"✓\")} Created business account \"${accountName}\" ${chalk.dim(`(${accountId})`)} — the CLI now acts on behalf of it.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet productId: string;\n\tlet productTitle: string;\n\tlet productCreated = false;\n\tif (existing) {\n\t\tproductId = existing.id;\n\t\tproductTitle = existing.title ?? existing.id;\n\t} else {\n\t\tlet product: { id: string; title: string };\n\t\ttry {\n\t\t\tproduct = await makeWhopRequest<{ id: string; title: string }>(\n\t\t\t\t\"POST\",\n\t\t\t\t\"/products\",\n\t\t\t\t{\n\t\t\t\t\ttitle: newTitle,\n\t\t\t\t\tcompany_id: accountId,\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"API_ERROR\",\n\t\t\t\tmessage: `Failed to create product: ${err instanceof Error ? err.message : \"unknown error\"}`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\tproductId = product.id;\n\t\tproductTitle = product.title;\n\t\tproductCreated = true;\n\t}\n\n\tconst isRenewal = billingPeriod !== \"one_time\";\n\tconst planBody: Record<string, unknown> = {\n\t\tproduct_id: productId,\n\t\taccount_id: accountId,\n\t\tinitial_price: price,\n\t\tplan_type: isRenewal ? \"renewal\" : \"one_time\",\n\t};\n\tif (isRenewal) {\n\t\tplanBody.billing_period = BILLING_PERIOD_DAYS[billingPeriod];\n\t\tplanBody.renewal_price = price;\n\t}\n\n\tlet plan: { id: string; purchase_url?: string | null };\n\ttry {\n\t\tplan = await makeWhopRequest<{ id: string; purchase_url?: string | null }>(\n\t\t\t\"POST\",\n\t\t\t\"/plans\",\n\t\t\tplanBody,\n\t\t);\n\t} catch (err) {\n\t\t// Product is ready but the plan failed — hand back a recovery command with\n\t\t// the product id already filled in. Only claim the product \"was created\"\n\t\t// when we actually created it this run (vs reused an existing one).\n\t\tconst detail = err instanceof Error ? err.message : \"unknown error\";\n\t\treturn c.error({\n\t\t\tcode: \"PLAN_FAILED\",\n\t\t\tmessage: productCreated\n\t\t\t\t? `Your product \"${productTitle}\" (${productId}) was created, but the plan failed: ${detail}`\n\t\t\t\t: `Couldn't add a plan to \"${productTitle}\" (${productId}): ${detail}`,\n\t\t\tretryable: false,\n\t\t\tcta: {\n\t\t\t\tdescription: \"Finish by adding a plan to your product:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"plans create\",\n\t\t\t\t\t\toptions: { product_id: productId },\n\t\t\t\t\t\tdescription: \"Add a pricing plan\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tconst checkoutUrl = plan.purchase_url ?? null;\n\tconst steps: Step[] = [\n\t\t{ id: \"auth\", label: \"Log in\", complete: true },\n\t\t...(accountCreated\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"account\",\n\t\t\t\t\t\tlabel: \"Create a business account\",\n\t\t\t\t\t\tcomplete: true,\n\t\t\t\t\t\tfirstId: accountId,\n\t\t\t\t\t\tfirstTitle: accountName,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t\t{\n\t\t\tid: \"products\",\n\t\t\tlabel: \"Create a product\",\n\t\t\tcomplete: true,\n\t\t\tcount: 1,\n\t\t\tfirstId: productId,\n\t\t\tfirstTitle: productTitle,\n\t\t},\n\t\t{\n\t\t\tid: \"plans\",\n\t\t\tlabel: \"Add a pricing plan\",\n\t\t\tcomplete: true,\n\t\t\tcount: 1,\n\t\t\tfirstId: plan.id,\n\t\t},\n\t];\n\tconst nextStep = resolveNextStep(\n\t\t[{ id: productId }],\n\t\t[{ id: plan.id }],\n\t\tfalse,\n\t);\n\n\tif (!c.agent && !c.formatExplicit) {\n\t\tprintSummary(accountName, steps, true, checkoutUrl, nextStep, productTitle);\n\t}\n\n\treturn c.ok({\n\t\taccount: accountName,\n\t\tready: true,\n\t\tcheckoutUrl,\n\t\tcreated: {\n\t\t\t...(accountCreated ? { accountId: accountId } : {}),\n\t\t\tproductId,\n\t\t\tplanId: plan.id,\n\t\t},\n\t\tsteps,\n\t\tnextStep,\n\t});\n}\n\nasync function resolveExistingProduct(\n\tc: RunCtx,\n\tproducts: ListItem[],\n): Promise<ListItem> {\n\tif (products.length === 1) return products[0];\n\tif (c.agent) {\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"PRODUCT_REQUIRED\",\n\t\t\tmessage: `You have ${products.length} products — add the plan to a specific one with plans create --product_id.`,\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tdescription: \"Pick a product:\",\n\t\t\t\tcommands: products.map((p) => ({\n\t\t\t\t\tcommand: \"plans create\",\n\t\t\t\t\toptions: { product_id: p.id },\n\t\t\t\t\tdescription: p.title ?? p.id,\n\t\t\t\t})),\n\t\t\t},\n\t\t});\n\t}\n\tconst chosen = await select<string>({\n\t\tmessage: \"Which product is this plan for?\",\n\t\toptions: products.map((p) => ({\n\t\t\tvalue: p.id,\n\t\t\tlabel: p.title ?? p.id,\n\t\t\thint: p.id,\n\t\t})),\n\t});\n\tif (isCancel(chosen))\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"CANCELLED\",\n\t\t\tmessage: \"Setup cancelled.\",\n\t\t\texitCode: 130,\n\t\t});\n\tconst match = products.find((p) => p.id === chosen);\n\tif (!match) {\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"PRODUCT_NOT_FOUND\",\n\t\t\tmessage: `Selected product \"${chosen}\" is no longer available.`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\treturn match;\n}\n\nfunction buildSteps(products: ListItem[], plans: ListItem[]): Step[] {\n\treturn [\n\t\t{ id: \"auth\", label: \"Log in\", complete: true },\n\t\t{\n\t\t\tid: \"products\",\n\t\t\tlabel: \"Create a product\",\n\t\t\tcomplete: products.length > 0,\n\t\t\tcount: products.length,\n\t\t\tfirstId: products[0]?.id,\n\t\t\tfirstTitle: products[0]?.title ?? undefined,\n\t\t},\n\t\t{\n\t\t\tid: \"plans\",\n\t\t\tlabel: \"Add a pricing plan\",\n\t\t\tcomplete: plans.length > 0,\n\t\t\tcount: plans.length,\n\t\t\tfirstId: plans[0]?.id,\n\t\t},\n\t];\n}\n\nfunction resolveNextStep(\n\tproducts: Array<{ id: string }>,\n\tplans: Array<{ id: string }>,\n\thasCheckoutConfig: boolean,\n): NextStep | null {\n\tif (products.length === 0 || plans.length === 0) {\n\t\treturn {\n\t\t\tcommand: \"quickstart\",\n\t\t\tdescription:\n\t\t\t\t\"Create your product and pricing — ends with a checkout link\",\n\t\t\thint: \"Walks you through name, price, and billing. Pass --title/--price/--billing_period to skip the prompts.\",\n\t\t};\n\t}\n\tif (!hasCheckoutConfig) {\n\t\treturn {\n\t\t\tcommand: \"checkout-configurations create\",\n\t\t\toptions: plans[0]?.id ? { plan_id: plans[0].id } : undefined,\n\t\t\tdescription: \"Optional: customize your checkout page\",\n\t\t\thint: \"Your checkout link already works — this only tweaks currency, redirect, and payment mode\",\n\t\t};\n\t}\n\treturn null;\n}\n\nfunction printSummary(\n\taccount: string | null,\n\tsteps: Step[],\n\tready: boolean,\n\tcheckoutUrl: string | null,\n\tnextStep: NextStep | null,\n\tcreatedLabel?: string,\n): void {\n\tconst heading = createdLabel\n\t\t? `You're set up to sell \"${createdLabel}\"`\n\t\t: `Setup for \"${account ?? \"your account\"}\"`;\n\tconsole.log(`\\n${chalk.bold(heading)}\\n`);\n\n\tlet pendingMarked = false;\n\tfor (const step of steps) {\n\t\tif (step.complete) {\n\t\t\tlet label = step.label;\n\t\t\tif (step.count !== undefined) {\n\t\t\t\tlabel += chalk.dim(` (${step.count})`);\n\t\t\t\tif (step.firstTitle) label += chalk.dim(` — \"${step.firstTitle}\"`);\n\t\t\t}\n\t\t\tconsole.log(` ${c.success(\"✓\")} ${label}`);\n\t\t} else if (!pendingMarked) {\n\t\t\tpendingMarked = true;\n\t\t\tconsole.log(` ${chalk.cyan(\"●\")} ${chalk.bold(step.label)}`);\n\t\t} else {\n\t\t\tconsole.log(` ${chalk.dim(\"○\")} ${chalk.dim(step.label)}`);\n\t\t}\n\t}\n\n\tif (ready && checkoutUrl) {\n\t\tconsole.log(\n\t\t\t`\\n${chalk.green.bold(\"🎉 You're ready to sell.\")} Share your checkout link:`,\n\t\t);\n\t\tconsole.log(` ${chalk.cyan.underline(checkoutUrl)}`);\n\t}\n\n\tif (nextStep) {\n\t\tconst opts = nextStep.options\n\t\t\t? \" \" +\n\t\t\t\tObject.entries(nextStep.options)\n\t\t\t\t\t.map(([k, v]) => `--${k} ${v}`)\n\t\t\t\t\t.join(\" \")\n\t\t\t: \"\";\n\t\tconst label = ready ? \"Optional next\" : chalk.bold(\"Next step\");\n\t\tconsole.log(\n\t\t\t`\\n${label} ${chalk.cyan.bold(`whop ${nextStep.command}${opts}`)}`,\n\t\t);\n\t\tif (nextStep.hint) console.log(` ${chalk.dim(`→ ${nextStep.hint}`)}`);\n\t} else if (ready) {\n\t\tconsole.log(`\\n${c.success(\"✓ Your store is fully set up.\")}`);\n\t}\n\tconsole.log(\"\");\n}\n","/**\n * Friendly billing-interval names → days, the unit the API expects for a plan's\n * `billing_period` (e.g. 30 for monthly, 365 for annual). The CLI exposes the\n * names for readability and converts before sending.\n */\nexport const BILLING_PERIOD_DAYS: Record<string, number> = {\n\tdaily: 1,\n\tweekly: 7,\n\tmonthly: 30,\n\tquarterly: 90,\n\tannually: 365,\n\tevery_two_years: 730,\n};\n","import chalk from \"chalk\";\n\nexport const c = {\n heading: chalk.bold,\n command: chalk.bold,\n description: chalk.dim,\n flag: chalk.yellow,\n tableHeader: chalk.bold,\n separator: chalk.dim,\n number: chalk.dim,\n muted: chalk.dim,\n id: chalk.cyan,\n link: chalk.cyan.underline,\n success: chalk.green,\n error: chalk.red.bold,\n};\n","{\n\t\"name\": \"@whop/cli\",\n\t\"version\": \"0.5.0\",\n\t\"description\": \"The Whop CLI — build and manage Whop apps from your terminal. Human and agent friendly.\",\n\t\"keywords\": [\n\t\t\"agent\",\n\t\t\"apps\",\n\t\t\"cli\",\n\t\t\"developer\",\n\t\t\"whop\"\n\t],\n\t\"homepage\": \"https://whop.com/developers/\",\n\t\"bugs\": \"https://github.com/whopio/whop-public-cli/issues\",\n\t\"license\": \"MIT\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/whopio/whop-public-cli.git\"\n\t},\n\t\"bin\": {\n\t\t\"whop\": \"dist/index.js\",\n\t\t\"whop-cli\": \"dist/index.js\"\n\t},\n\t\"files\": [\n\t\t\"dist\"\n\t],\n\t\"type\": \"module\",\n\t\"exports\": {\n\t\t\".\": \"./dist/index.js\",\n\t\t\"./vite\": {\n\t\t\t\"types\": \"./dist/vite.d.ts\",\n\t\t\t\"import\": \"./dist/vite.js\"\n\t\t}\n\t},\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"scripts\": {\n\t\t\"build\": \"tsx scripts/sync-spec.ts && pnpm run clean && tsup\",\n\t\t\"build:binary\": \"tsx scripts/build-binary.ts\",\n\t\t\"clean\": \"rm -rf dist\",\n\t\t\"dev\": \"tsx scripts/sync-spec.ts && tsx src/index.ts\",\n\t\t\"start\": \"node dist/index.js\",\n\t\t\"check-types\": \"tsx scripts/sync-spec.ts && tsc --noEmit\",\n\t\t\"lint\": \"oxlint .\",\n\t\t\"lint:fix\": \"oxlint --fix --fix-suggestions && oxfmt\",\n\t\t\"ci:lint\": \"oxlint -f github .\",\n\t\t\"format\": \"oxfmt\",\n\t\t\"sync-spec\": \"tsx scripts/sync-spec.ts\",\n\t\t\"test\": \"tsx --test scripts/*.test.ts\"\n\t},\n\t\"dependencies\": {\n\t\t\"@clack/prompts\": \"^1.5.1\",\n\t\t\"@napi-rs/keyring\": \"^1.3.0\",\n\t\t\"@whop/sdk\": \"^0.0.40\",\n\t\t\"chalk\": \"5.4.1\",\n\t\t\"yaml\": \"2.8.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"25.3.5\",\n\t\t\"fflate\": \"0.8.2\",\n\t\t\"incur\": \"github:whopio/incur#4b9ca91dc02472db944fb103984ffc4a13251b6f\",\n\t\t\"tsup\": \"8.5.0\",\n\t\t\"tsx\": \"4.19.4\",\n\t\t\"typescript\": \"5.9.3\",\n\t\t\"vite\": \"7.3.6\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=22\"\n\t},\n\t\"packageManager\": \"pnpm@10.23.0\"\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { configDir } from \"../../auth/config\";\nimport { detectChannel, type Channel } from \"../build-info\";\nimport { hasStructuredOutputFlag } from \"../colorize-output\";\n\n/**\n * Background update check, modeled on update-notifier: never block or slow a\n * command. Each run synchronously reads a small cache file; if a newer version\n * was recorded by a previous check, a notice is printed to stderr when the\n * process exits. When the cache is stale (>1h) a detached `whop upgrade`\n * child refreshes it (and, for standalone installs, applies the update) in the\n * background — the current invocation never waits on the network.\n */\n\nexport const DEFAULT_MANIFEST_URL =\n\t\"https://github.com/whopio/whop-public-cli/releases/latest/download/manifest.json\";\n\nexport function manifestUrl(env: NodeJS.ProcessEnv = process.env): string {\n\treturn env.WHOP_CLI_MANIFEST_URL?.trim() || DEFAULT_MANIFEST_URL;\n}\n\nconst CHECK_INTERVAL_MS = 60 * 60 * 1000;\n\nexport interface UpdateCache {\n\tlastCheckedAt?: string;\n\tlatestVersion?: string;\n\t/** Set by a background self-update so the next run can announce it. */\n\tupdatedTo?: string;\n}\n\nfunction cachePath(env: NodeJS.ProcessEnv): string {\n\treturn path.join(configDir(env), \"update-check.json\");\n}\n\nexport function readUpdateCache(\n\tenv: NodeJS.ProcessEnv = process.env,\n): UpdateCache {\n\ttry {\n\t\tconst parsed = JSON.parse(\n\t\t\tfs.readFileSync(cachePath(env), \"utf8\"),\n\t\t) as unknown;\n\t\tif (parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\treturn parsed as UpdateCache;\n\t\t}\n\t} catch {\n\t\t// missing or corrupt cache — same as never checked\n\t}\n\treturn {};\n}\n\nexport function writeUpdateCache(\n\tcache: UpdateCache,\n\tenv: NodeJS.ProcessEnv = process.env,\n): void {\n\ttry {\n\t\tfs.mkdirSync(configDir(env), { recursive: true, mode: 0o700 });\n\t\tfs.writeFileSync(cachePath(env), `${JSON.stringify(cache, null, 2)}\\n`, {\n\t\t\tmode: 0o600,\n\t\t});\n\t} catch {\n\t\t// a failed cache write must never break the command being run\n\t}\n}\n\nexport function isNewerVersion(candidate: string, current: string): boolean {\n\tconst parse = (v: string) =>\n\t\tv\n\t\t\t.replace(/^v/, \"\")\n\t\t\t.split(\"-\")[0]\n\t\t\t.split(\".\")\n\t\t\t.map((part) => Number.parseInt(part, 10) || 0);\n\tconst a = parse(candidate);\n\tconst b = parse(current);\n\tfor (let i = 0; i < Math.max(a.length, b.length); i++) {\n\t\tif ((a[i] ?? 0) > (b[i] ?? 0)) return true;\n\t\tif ((a[i] ?? 0) < (b[i] ?? 0)) return false;\n\t}\n\treturn false;\n}\n\nexport function upgradeCommandFor(channel: Channel): string {\n\tswitch (channel) {\n\t\tcase \"npm\":\n\t\t\treturn \"npm install -g @whop/cli\";\n\t\tcase \"brew\":\n\t\t\treturn \"brew upgrade whop\";\n\t\tdefault:\n\t\t\treturn \"whop upgrade\";\n\t}\n}\n\n/** True when update noise would corrupt output or is unwanted: agents, CI, pipes, opt-out. */\nexport function updateCheckSuppressed(\n\targv: string[],\n\tenv: NodeJS.ProcessEnv = process.env,\n\tstderrIsTty: boolean = process.stderr.isTTY ?? false,\n): boolean {\n\tif (env.WHOP_CLI_NO_UPDATE_CHECK) return true;\n\tif (env.CI) return true;\n\tif (!stderrIsTty) return true;\n\t// Any machine-output flag means the caller is parsing the output (incur's\n\t// human rendering is the no-flag TTY default). Reuses the predicate that\n\t// also disables colorization, so the two stay in sync.\n\tif (hasStructuredOutputFlag(argv)) return true;\n\tconst first = argv[0];\n\tif (\n\t\tfirst === \"upgrade\" ||\n\t\tfirst === \"mcp\" ||\n\t\tfirst === \"completions\" ||\n\t\tfirst?.startsWith(\"--\")\n\t) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction spawnBackgroundCheck(): void {\n\tconst args =\n\t\tdetectChannel() === \"standalone\" || detectChannel() === \"brew\"\n\t\t\t? [\"upgrade\", \"--background\"]\n\t\t\t: [process.argv[1], \"upgrade\", \"--background\"];\n\ttry {\n\t\tspawn(process.execPath, args, {\n\t\t\tdetached: true,\n\t\t\tstdio: \"ignore\",\n\t\t}).unref();\n\t} catch {\n\t\t// background check is best-effort\n\t}\n}\n\nexport function scheduleUpdateNotice(\n\targv: string[],\n\tcurrentVersion: string,\n\tenv: NodeJS.ProcessEnv = process.env,\n): void {\n\tconst channel = detectChannel(env);\n\tif (channel === \"dev\") return;\n\tif (updateCheckSuppressed(argv, env)) return;\n\n\tconst cache = readUpdateCache(env);\n\n\tif (cache.updatedTo && cache.updatedTo === currentVersion) {\n\t\twriteUpdateCache({ ...cache, updatedTo: undefined }, env);\n\t\tprocess.on(\"exit\", () => {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`\\nwhop was updated to v${currentVersion} automatically.\\n`,\n\t\t\t);\n\t\t});\n\t\treturn;\n\t}\n\n\tif (cache.latestVersion && isNewerVersion(cache.latestVersion, currentVersion)) {\n\t\tconst latest = cache.latestVersion;\n\t\tprocess.on(\"exit\", () => {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`\\nA new version of whop is available: v${currentVersion} → v${latest}\\nRun \\`${upgradeCommandFor(channel)}\\` to update.\\n`,\n\t\t\t);\n\t\t});\n\t}\n\n\tconst lastChecked = cache.lastCheckedAt\n\t\t? new Date(cache.lastCheckedAt).getTime()\n\t\t: 0;\n\tif (Date.now() - lastChecked > CHECK_INTERVAL_MS) {\n\t\twriteUpdateCache({ ...cache, lastCheckedAt: new Date().toISOString() }, env);\n\t\tspawnBackgroundCheck();\n\t}\n}\n","import { c } from \"./colors\";\n\n/**\n * Themes incur's built-in help / error / CTA text so the whole CLI looks\n * consistent with our hand-rendered surfaces (root help, quickstart, tables).\n *\n * incur exposes a `renderer` hook only for command *data*, not for help or\n * errors, so we post-process the text it writes to stdout instead. This runs\n * only in human TTY mode (see `shouldColorize`) — structured output\n * (`--json`, `--format`, piped/agent) is passed through untouched, so machine\n * consumers never see ANSI codes.\n */\n\nconst SECTION_HEADERS = new Set([\n\t\"Usage\",\n\t\"Arguments\",\n\t\"Options\",\n\t\"Examples\",\n\t\"Environment Variables\",\n\t\"Global Options\",\n\t\"Integrations\",\n\t\"Commands\",\n\t\"Aliases\",\n]);\n\nconst FORMAT_FLAGS = [\"--json\", \"--format\", \"--full-output\", \"--schema\", \"--llms\", \"--llms-full\", \"--mcp\", \"--token-count\", \"--token-limit\", \"--token-offset\"];\n\n/** True when argv carries any machine-output flag (`--json`, `--format <fmt>`, `--format=<fmt>`, `--schema`, …). */\nexport function hasStructuredOutputFlag(argv: string[]): boolean {\n\treturn argv.some((a) => FORMAT_FLAGS.includes(a) || a.startsWith(\"--format=\"));\n}\n\n/** Color only when writing for a human: a TTY, with no structured-output flag. */\nexport function shouldColorize(argv: string[]): boolean {\n\tif (!process.stdout.isTTY) return false;\n\treturn !hasStructuredOutputFlag(argv);\n}\n\n/** Highlights a flag token and any `<placeholder>` inside an option/flag row. */\nfunction paintFlag(flag: string): string {\n\treturn flag.replace(/(<[^>]+>)/g, (m) => c.muted(m)).replace(/(--[\\w-]+|-[\\w])/g, (m) => c.flag(m));\n}\n\n/** An indented command line (` whop products create # desc`) — in help examples or a CTA. */\nconst COMMAND_ROW = /^(\\s+)(whop\\s+\\S.*?)(\\s{2,}#\\s.*)?$/;\n\n/** Underlines any URL so links (checkout pages, dashboards) stand out. */\nfunction highlightUrls(text: string): string {\n\treturn text.replace(/https?:\\/\\/[^\\s)]+/g, (m) => c.link(m));\n}\n\nfunction colorizeLine(\n\tline: string,\n\tsection: string | null,\n\tnextLine: string | undefined,\n): { line: string; section: string | null } {\n\t// Error header, e.g. \"Error: msg\" or \"Error (HTTP_403): msg\".\n\tconst errMatch = line.match(/^(Error(?: \\([^)]+\\))?:)(.*)$/);\n\tif (errMatch) return { line: c.error(errMatch[1]) + highlightUrls(errMatch[2]), section };\n\tif (line.startsWith(\"Run `\")) return { line: c.heading(line), section };\n\n\t// Section header, e.g. \"Options:\" or \"Usage: whop products create\".\n\tconst header = line.match(/^([A-Z][A-Za-z ]+):(.*)$/);\n\tif (header && SECTION_HEADERS.has(header[1])) {\n\t\tconst rest = header[2].replace(/(whop[\\w\\s-]*)/g, (m) => c.command(m));\n\t\treturn { line: c.heading(`${header[1]}:`) + rest, section: header[1] };\n\t}\n\n\t// A `whop …` command line anywhere (help examples and CTAs alike).\n\tconst cmd = line.match(COMMAND_ROW);\n\tif (cmd) {\n\t\treturn { line: `${cmd[1]}${c.command(cmd[2])}${cmd[3] ? c.description(cmd[3]) : \"\"}`, section };\n\t}\n\n\t// A header-like line (\"Suggested command:\", a CTA description) immediately\n\t// followed by a command — bold it for emphasis.\n\tif (line.trim().endsWith(\":\") && nextLine !== undefined && COMMAND_ROW.test(nextLine)) {\n\t\treturn { line: c.heading(line), section };\n\t}\n\n\tif (line.trim() === \"\") return { line, section: null };\n\n\t// Rows inside a known section.\n\tif (section === \"Options\" || section === \"Global Options\" || section === \"Environment Variables\") {\n\t\tconst m = line.match(/^(\\s+)(\\S.*?)(\\s{2,})(.*)$/);\n\t\tif (m) return { line: `${m[1]}${paintFlag(m[2])}${m[3]}${c.description(m[4])}`, section };\n\t}\n\tif (section === \"Commands\" || section === \"Integrations\" || section === \"Aliases\") {\n\t\tconst m = line.match(/^(\\s+)(\\S+)(\\s{2,})(.*)$/);\n\t\tif (m) return { line: `${m[1]}${c.command(m[2])}${m[3]}${c.description(m[4])}`, section };\n\t}\n\tif (section === \"Arguments\") {\n\t\tconst m = line.match(/^(\\s+)(\\S+)(\\s{2,})(.*)$/);\n\t\tif (m) return { line: `${m[1]}${c.id(m[2])}${m[3]}${c.description(m[4])}`, section };\n\t}\n\n\t// Plain text (messages, CTA descriptions): make any link stand out.\n\treturn { line: highlightUrls(line), section };\n}\n\n/** Themes a chunk of incur help/error/CTA text. Safe to call per write. */\nexport function colorizeOutput(text: string): string {\n\tlet section: string | null = null;\n\tconst lines = text.split(\"\\n\");\n\treturn lines\n\t\t.map((line, i) => {\n\t\t\tconst result = colorizeLine(line, section, lines[i + 1]);\n\t\t\tsection = result.section;\n\t\t\treturn result.line;\n\t\t})\n\t\t.join(\"\\n\");\n}\n","import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { buildTarget } from \"../build-info\";\nimport { manifestUrl } from \"./check\";\n\n/**\n * Self-update for standalone binaries: download the raw binary asset for this\n * build's target from the release manifest, verify its sha256, and atomically\n * rename it over the running executable (safe on macOS/Linux — the running\n * process keeps its open inode). The temp file is created next to the target\n * so the rename never crosses filesystems.\n */\n\nexport interface ManifestAsset {\n\turl: string;\n\tsha256: string;\n}\n\nexport interface UpdateManifest {\n\tversion: string;\n\tassets: Record<string, ManifestAsset>;\n}\n\nexport class SelfUpdateError extends Error {\n\tconstructor(\n\t\tpublic code: string,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\nexport async function fetchManifest(\n\tenv: NodeJS.ProcessEnv = process.env,\n): Promise<UpdateManifest> {\n\tconst url = manifestUrl(env);\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tsignal: AbortSignal.timeout(10_000),\n\t\t\tredirect: \"follow\",\n\t\t});\n\t} catch {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_UNREACHABLE\",\n\t\t\t`Could not reach the update manifest at ${url}.`,\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_UNAVAILABLE\",\n\t\t\t`Update manifest request failed with HTTP ${response.status}.`,\n\t\t);\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = await response.json();\n\t} catch {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_INVALID\",\n\t\t\t\"Update manifest is not valid JSON.\",\n\t\t);\n\t}\n\tconst manifest = parsed as UpdateManifest;\n\tif (\n\t\ttypeof manifest?.version !== \"string\" ||\n\t\tmanifest.assets == null ||\n\t\ttypeof manifest.assets !== \"object\"\n\t) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_INVALID\",\n\t\t\t\"Update manifest is missing version or assets.\",\n\t\t);\n\t}\n\treturn manifest;\n}\n\nexport function assetForThisBinary(\n\tmanifest: UpdateManifest,\n): ManifestAsset & { target: string } {\n\tif (!buildTarget) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"NOT_A_STANDALONE_BUILD\",\n\t\t\t\"This build has no compile target — self-update only applies to standalone binaries.\",\n\t\t);\n\t}\n\tconst asset = manifest.assets[buildTarget];\n\tif (!asset?.url || !asset.sha256) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"NO_ASSET_FOR_TARGET\",\n\t\t\t`The latest release has no binary for ${buildTarget}.`,\n\t\t);\n\t}\n\treturn { ...asset, target: buildTarget };\n}\n\nexport async function downloadAndSwap(\n\tasset: ManifestAsset,\n\texecPath: string = process.execPath,\n): Promise<void> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(asset.url, {\n\t\t\tsignal: AbortSignal.timeout(120_000),\n\t\t\tredirect: \"follow\",\n\t\t});\n\t} catch {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"DOWNLOAD_FAILED\",\n\t\t\t`Could not download ${asset.url}.`,\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"DOWNLOAD_FAILED\",\n\t\t\t`Binary download failed with HTTP ${response.status}.`,\n\t\t);\n\t}\n\tconst bytes = Buffer.from(await response.arrayBuffer());\n\n\tconst digest = crypto.createHash(\"sha256\").update(bytes).digest(\"hex\");\n\tif (digest !== asset.sha256.toLowerCase()) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"CHECKSUM_MISMATCH\",\n\t\t\t`Downloaded binary checksum ${digest} does not match the manifest — aborting.`,\n\t\t);\n\t}\n\n\tconst dir = path.dirname(execPath);\n\tconst tmp = path.join(dir, `.${path.basename(execPath)}.${process.pid}.new`);\n\ttry {\n\t\tfs.writeFileSync(tmp, bytes, { mode: 0o755 });\n\t\tfs.renameSync(tmp, execPath);\n\t} catch (err) {\n\t\ttry {\n\t\t\tfs.rmSync(tmp, { force: true });\n\t\t} catch {\n\t\t\t// best-effort cleanup\n\t\t}\n\t\tconst code = (err as NodeJS.ErrnoException).code;\n\t\tif (code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\") {\n\t\t\tthrow new SelfUpdateError(\n\t\t\t\t\"PERMISSION_DENIED\",\n\t\t\t\t`No write access to ${dir}. Re-run with elevated permissions (e.g. \\`sudo whop upgrade\\`) or reinstall.`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n","import { z } from \"incur\";\nimport pkg from \"../../../package.json\" with { type: \"json\" };\nimport { detectChannel } from \"../build-info\";\nimport {\n\tisNewerVersion,\n\treadUpdateCache,\n\tupgradeCommandFor,\n\twriteUpdateCache,\n} from \"./check\";\nimport {\n\tassetForThisBinary,\n\tdownloadAndSwap,\n\tfetchManifest,\n\tSelfUpdateError,\n} from \"./self-update\";\n\nexport const upgradeOptions = z.object({\n\tcheck: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\"Only check for a newer version, don't install it\"),\n\tbackground: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Internal: refresh the update cache silently (spawned by the automatic check)\",\n\t\t),\n});\n\nexport const upgradeOutput = z.object({\n\tstatus: z\n\t\t.enum([\"up-to-date\", \"update-available\", \"updated\"])\n\t\t.describe(\"Result of the upgrade check\"),\n\tcurrent: z.string().describe(\"The version currently running\"),\n\tlatest: z.string().describe(\"The latest released version\"),\n\tchannel: z\n\t\t.enum([\"npm\", \"brew\", \"standalone\", \"dev\"])\n\t\t.describe(\"How this CLI was installed\"),\n\tupgradeCommand: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Run this shell command to install the available update\"),\n});\nexport type UpgradeOutput = z.infer<typeof upgradeOutput>;\n\ntype CtaCommand = { command: string; description?: string | undefined };\ntype UpgradeCtx = {\n\toptions: { check?: boolean | undefined; background?: boolean | undefined };\n\tok: (\n\t\tdata: UpgradeOutput,\n\t\tmeta?: {\n\t\t\tcta?:\n\t\t\t\t| { description?: string | undefined; commands: CtaCommand[] }\n\t\t\t\t| undefined;\n\t\t},\n\t) => never;\n\terror: (options: {\n\t\tcode: string;\n\t\tmessage: string;\n\t\tretryable?: boolean | undefined;\n\t}) => never;\n};\n\nasync function runBackground(env: NodeJS.ProcessEnv): Promise<void> {\n\tconst manifest = await fetchManifest(env);\n\tconst cache = readUpdateCache(env);\n\twriteUpdateCache(\n\t\t{\n\t\t\t...cache,\n\t\t\tlastCheckedAt: new Date().toISOString(),\n\t\t\tlatestVersion: manifest.version,\n\t\t},\n\t\tenv,\n\t);\n\tif (\n\t\tdetectChannel(env) === \"standalone\" &&\n\t\tenv.WHOP_CLI_AUTO_UPDATE !== \"0\" &&\n\t\tisNewerVersion(manifest.version, pkg.version)\n\t) {\n\t\tawait downloadAndSwap(assetForThisBinary(manifest));\n\t\twriteUpdateCache(\n\t\t\t{\n\t\t\t\tlastCheckedAt: new Date().toISOString(),\n\t\t\t\tlatestVersion: manifest.version,\n\t\t\t\tupdatedTo: manifest.version,\n\t\t\t},\n\t\t\tenv,\n\t\t);\n\t}\n}\n\nexport async function runUpgrade(\n\tc: UpgradeCtx,\n\tenv: NodeJS.ProcessEnv = process.env,\n): Promise<never> {\n\tif (c.options.background) {\n\t\ttry {\n\t\t\tawait runBackground(env);\n\t\t} catch {\n\t\t\t// silent by design — the next foreground run retries after the interval\n\t\t}\n\t\treturn c.ok({\n\t\t\tstatus: \"up-to-date\",\n\t\t\tcurrent: pkg.version,\n\t\t\tlatest: pkg.version,\n\t\t\tchannel: detectChannel(env),\n\t\t});\n\t}\n\n\tconst channel = detectChannel(env);\n\n\tlet manifest;\n\ttry {\n\t\tmanifest = await fetchManifest(env);\n\t} catch (err) {\n\t\tif (err instanceof SelfUpdateError) {\n\t\t\treturn c.error({ code: err.code, message: err.message, retryable: true });\n\t\t}\n\t\tthrow err;\n\t}\n\n\twriteUpdateCache(\n\t\t{\n\t\t\t...readUpdateCache(env),\n\t\t\tlastCheckedAt: new Date().toISOString(),\n\t\t\tlatestVersion: manifest.version,\n\t\t},\n\t\tenv,\n\t);\n\n\tconst base = { current: pkg.version, latest: manifest.version, channel };\n\n\tif (!isNewerVersion(manifest.version, pkg.version)) {\n\t\treturn c.ok({ status: \"up-to-date\", ...base });\n\t}\n\n\tif (channel === \"npm\" || channel === \"brew\") {\n\t\treturn c.ok({\n\t\t\tstatus: \"update-available\",\n\t\t\t...base,\n\t\t\tupgradeCommand: upgradeCommandFor(channel),\n\t\t});\n\t}\n\n\tif (channel === \"dev\") {\n\t\treturn c.error({\n\t\t\tcode: \"DEV_BUILD\",\n\t\t\tmessage: \"Running from source — pull the latest instead of upgrading.\",\n\t\t\tretryable: false,\n\t\t});\n\t}\n\n\tif (c.options.check) {\n\t\treturn c.ok(\n\t\t\t{\n\t\t\t\tstatus: \"update-available\",\n\t\t\t\t...base,\n\t\t\t\tupgradeCommand: upgradeCommandFor(channel),\n\t\t\t},\n\t\t\t{\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: `v${manifest.version} is available (you have v${pkg.version}). To update:`,\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{ command: \"upgrade\", description: \"Install the latest version\" },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\ttry {\n\t\tawait downloadAndSwap(assetForThisBinary(manifest));\n\t} catch (err) {\n\t\tif (err instanceof SelfUpdateError) {\n\t\t\treturn c.error({\n\t\t\t\tcode: err.code,\n\t\t\t\tmessage: err.message,\n\t\t\t\tretryable: err.code !== \"PERMISSION_DENIED\",\n\t\t\t});\n\t\t}\n\t\tthrow err;\n\t}\n\n\treturn c.ok({ status: \"updated\", ...base });\n}\n","import groups from \"./api/groups.json\" with { type: \"json\" };\nimport {\n\tbuildAuthGroup,\n\tloginAdapter,\n\tloginEnv,\n\tloginExamples,\n\tloginHint,\n\tloginOptions,\n\tloginOutput,\n\tlogoutAdapter,\n\tlogoutOptions,\n\tlogoutOutput,\n} from \"./auth/commands\";\nimport { buildAppGroup } from \"./apps/commands\";\nimport {\n\tquickstartOptions,\n\tquickstartOutput,\n\trunQuickstart,\n} from \"./journey/quickstart\";\nimport {\n\trunUpgrade,\n\tupgradeOptions,\n\tupgradeOutput,\n} from \"./lib/update/command\";\n\ntype CliRegistration = {\n\tcommand: (...args: any[]) => unknown;\n\tserve: (\n\t\targv: string[],\n\t\toptions?: {\n\t\t\texit?: (code: number) => void;\n\t\t\tstdout?: (chunk: string) => void;\n\t\t},\n\t) => Promise<void>;\n};\n\ntype HandwrittenGroup = {\n\tname: string;\n\tdescription: string;\n\tsection: \"get-started\" | \"auth\";\n\tregister: (cli: CliRegistration) => unknown | Promise<unknown>;\n};\n\nexport const HANDWRITTEN_GROUPS = [\n\t{\n\t\tname: \"quickstart\",\n\t\tdescription:\n\t\t\t\"Start here — check status and create your first product + checkout link\",\n\t\tsection: \"get-started\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"quickstart\", {\n\t\t\t\tdescription:\n\t\t\t\t\t\"Start selling — check your status and create what's missing\",\n\t\t\t\thint: \"In a terminal it guides you to your first sale — including creating a business account if you don't have one. Agents: a read-only status check unless you pass --business_name/--title/--price/--billing_period.\",\n\t\t\t\toptions: quickstartOptions,\n\t\t\t\toutput: quickstartOutput,\n\t\t\t\texamples: [\n\t\t\t\t\t{ description: \"Check status / get guided to your first sale\" },\n\t\t\t\t\t{\n\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\ttitle: \"My Course\",\n\t\t\t\t\t\t\tprice: 9.99,\n\t\t\t\t\t\t\tbilling_period: \"monthly\" as const,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdescription: \"Create a $9.99/mo product non-interactively\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\tbusiness_name: \"My Business\",\n\t\t\t\t\t\t\ttitle: \"My Course\",\n\t\t\t\t\t\t\tprice: 9.99,\n\t\t\t\t\t\t\tbilling_period: \"one_time\" as const,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"No business account yet? Create it and the product in one run\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\toutputPolicy: \"agent-only\",\n\t\t\t\trun: (c: Parameters<typeof runQuickstart>[0]) =>\n\t\t\t\t\trunQuickstart({ ...c, setupAgents: () => setupAgents(cli) }),\n\t\t\t}),\n\t},\n\t{\n\t\tname: \"apps\",\n\t\tdescription: \"Build and deploy fully-hosted web apps (*.whop.app)\",\n\t\tsection: \"get-started\",\n\t\tregister: async (cli: CliRegistration) =>\n\t\t\tcli.command(await buildAppGroup()),\n\t},\n\t{\n\t\tname: \"upgrade\",\n\t\tdescription: \"Update the CLI to the latest version\",\n\t\tsection: \"get-started\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"upgrade\", {\n\t\t\t\tdescription: \"Update the whop CLI to the latest version\",\n\t\t\t\toptions: upgradeOptions,\n\t\t\t\toutput: upgradeOutput,\n\t\t\t\texamples: [\n\t\t\t\t\t{ description: \"Update to the latest version\" },\n\t\t\t\t\t{\n\t\t\t\t\t\toptions: { check: true },\n\t\t\t\t\t\tdescription: \"Check for a newer version without installing\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\trun: (c: Parameters<typeof runUpgrade>[0]) => runUpgrade(c),\n\t\t\t}),\n\t},\n\t{\n\t\tname: \"auth\",\n\t\tdescription: \"Manage authentication\",\n\t\tsection: \"auth\",\n\t\tregister: (cli: CliRegistration) => cli.command(buildAuthGroup()),\n\t},\n\t{\n\t\tname: \"login\",\n\t\tdescription: \"Sign in to Whop\",\n\t\tsection: \"auth\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"login\", {\n\t\t\t\tdescription: \"Log in to Whop (alias for `auth login`)\",\n\t\t\t\toptions: loginOptions,\n\t\t\t\tenv: loginEnv,\n\t\t\t\toutput: loginOutput,\n\t\t\t\texamples: loginExamples,\n\t\t\t\thint: loginHint,\n\t\t\t\trun: (c: Parameters<typeof loginAdapter>[0]) => loginAdapter(c),\n\t\t\t}),\n\t},\n\t{\n\t\tname: \"logout\",\n\t\tdescription: \"Sign out\",\n\t\tsection: \"auth\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"logout\", {\n\t\t\t\tdescription: \"Log out (alias for `auth logout`)\",\n\t\t\t\toptions: logoutOptions,\n\t\t\t\toutput: logoutOutput,\n\t\t\t\trun: (c: Parameters<typeof logoutAdapter>[0]) => logoutAdapter(c),\n\t\t\t}),\n\t},\n] satisfies HandwrittenGroup[];\n\nexport const HANDWRITTEN_GROUP_NAMES = new Set(\n\tHANDWRITTEN_GROUPS.map(({ name }) => name),\n);\n\nexport const API_GROUPS = groups\n\t.map(([name, tag]) => ({ name, tag }))\n\t.filter(({ name }) => !HANDWRITTEN_GROUP_NAMES.has(name));\n\nexport const COMMAND_GROUPS = [...API_GROUPS, ...HANDWRITTEN_GROUPS] as const;\n\nexport async function registerHandwrittenGroups(cli: CliRegistration) {\n\tfor (const group of HANDWRITTEN_GROUPS) await group.register(cli);\n}\n\nasync function setupAgents(cli: CliRegistration) {\n\tfor (const argv of [\n\t\t[\"skills\", \"add\"],\n\t\t[\"mcp\", \"add\"],\n\t]) {\n\t\tlet exitCode = 0;\n\t\tawait cli.serve(argv, {\n\t\t\texit: (code) => {\n\t\t\t\texitCode = code;\n\t\t\t},\n\t\t\tstdout: (chunk) => process.stdout.write(chunk),\n\t\t});\n\t\tif (exitCode !== 0) throw new Error(`whop ${argv.join(\" \")} failed.`);\n\t}\n}\n","import { c } from \"./colors\";\n\nconst MAX_CELL_WIDTH = 40\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isObjectArray(value: unknown): value is Record<string, unknown>[] {\n return Array.isArray(value) && value.length > 0 && value.every(isPlainObject)\n}\n\nconst WHOP_TAG = /^[a-z]+_[A-Za-z0-9]+$/\n\n/** Plain truncated string — used for column width calculation (no ANSI codes). */\nfunction cellText(value: unknown): string {\n if (value == null) return ''\n const text = String(value)\n return text.length > MAX_CELL_WIDTH ? text.slice(0, MAX_CELL_WIDTH - 1) + '…' : text\n}\n\n/** Colored display string — used for rendering. */\nfunction formatCell(value: unknown): string {\n const text = cellText(value)\n if (typeof value === 'boolean') return value ? c.success(text) : c.error(text)\n if (typeof value === 'string' && WHOP_TAG.test(value)) return c.id(text)\n return text\n}\n\n/** Total printable width of one row: sum of column widths plus two-space separators between them. */\nfunction totalRowWidth(colWidths: number[]): number {\n const columnTotal = colWidths.reduce((sum, colWidth) => sum + colWidth, 0)\n return columnTotal + (colWidths.length - 1) * 2\n}\n\n/**\n * Renders an array of plain objects as an aligned terminal grid.\n * Drops columns from the right when the row would exceed the terminal width.\n */\nfunction renderRows(rows: Record<string, unknown>[]): string {\n // Only include keys that are scalar across every row — a column where some rows\n // have an object and others have null would render as \"[object Object]\".\n const isScalar = (value: unknown) => typeof value !== 'object' || value === null\n const scalarKeys = Object.keys(rows[0]!).filter((key) =>\n rows.every((row) => isScalar(row[key])),\n )\n\n if (scalarKeys.length === 0) return '(no displayable columns)'\n\n // Column width = max of the header label and the widest cell value across all rows.\n const allWidths = scalarKeys.map((key) =>\n Math.max(key.length, ...rows.map((row) => cellText(row[key]).length)),\n )\n\n // Drop the rightmost columns until the row fits within the terminal width.\n const termWidth = process.stdout.columns ?? 80\n let numVisible = allWidths.length\n while (numVisible > 1 && totalRowWidth(allWidths.slice(0, numVisible)) > termWidth) {\n numVisible--\n }\n\n const visibleKeys = scalarKeys.slice(0, numVisible)\n const visibleWidths = allWidths.slice(0, numVisible)\n\n const header = visibleKeys\n .map((key, i) => c.tableHeader(key.toUpperCase().padEnd(visibleWidths[i]!)))\n .join(' ')\n\n const separator = c.separator(visibleWidths.map((w) => '─'.repeat(w)).join('──'))\n\n const body = rows.map((row) =>\n visibleKeys\n .map((key, i) => {\n const value = row[key]\n const formatted = formatCell(value)\n const width = visibleWidths[i]!\n const pad = width - cellText(value).length\n // Right-align numbers, left-align everything else.\n return typeof value === 'number'\n ? c.number(' '.repeat(pad) + formatted)\n : formatted + ' '.repeat(pad)\n })\n .join(' '),\n )\n\n const hiddenCount = scalarKeys.length - numVisible\n const overflowHint =\n hiddenCount > 0\n ? `\\n${c.muted(`& ${hiddenCount} more columns — use --format json to see all`)}`\n : ''\n\n return [header, separator, ...body].join('\\n') + overflowHint\n}\n\n/**\n * Human-mode renderer passed to incur as `renderer`.\n * Handles top-level arrays and single-array wrapped responses (e.g. `{ accounts: [...], pagination: {...} }`).\n * Returns null for anything that can't be meaningfully rendered as a grid, falling back to incur's TOON formatter.\n */\nexport function render(data: unknown): string | null {\n if (isObjectArray(data)) return renderRows(data)\n\n if (isPlainObject(data)) {\n const arrayFields = Object.values(data).filter(isObjectArray)\n // Only render when there's exactly one array field — avoids guessing which to show.\n if (arrayFields.length === 1) {\n return renderRows(arrayFields[0] as Record<string, unknown>[])\n }\n }\n\n return null\n}\n","import { Cli } from \"incur\";\nimport { nativeSpec, filterSpecByTag, createWhopFetch } from \"./api\";\nimport { API_GROUPS, registerHandwrittenGroups } from \"./commands\";\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport { render } from \"./lib/renderer\";\nimport { performLogin } from \"./auth/commands\";\nimport { getActiveProfile } from \"./auth/profiles\";\nimport { PromptCancelledError } from \"./auth/prompts\";\n\nconst cli = Cli.create(\"whop\", {\n\tversion: pkg.version,\n\tdescription: \"Build and manage Whop apps from your terminal.\",\n\trenderer: render,\n\tsync: {\n\t\tsuggestions: [\n\t\t\t\"start selling on Whop\",\n\t\t\t\"show my Whop business accounts\",\n\t\t\t\"create a Whop product and pricing plan\",\n\t\t],\n\t},\n\tmcp: {\n\t\tagents: [\"claude-desktop\"],\n\t},\n});\n\nconst spec = (tag: string) =>\n\tfilterSpecByTag(nativeSpec as Record<string, unknown>, tag);\nconst fetch = createWhopFetch();\n\nconst isAuthExempt = (cmd: string) =>\n\t!cmd ||\n\tcmd === \"login\" ||\n\tcmd === \"logout\" ||\n\tcmd === \"completions\" ||\n\tcmd === \"upgrade\" ||\n\tcmd.startsWith(\"auth\") ||\n\tcmd.startsWith(\"mcp\");\n\ncli.use(async (c, next) => {\n\tif (isAuthExempt(c.command)) return next();\n\tif (getActiveProfile()) return next();\n\tif (process.env.WHOP_API_KEY) return next();\n\n\tif (c.agent) {\n\t\treturn c.error({\n\t\t\tcode: \"NOT_AUTHENTICATED\",\n\t\t\tmessage: \"Not logged in. Set WHOP_API_KEY or run `whop login` first.\",\n\t\t\tcta: {\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\n\tlet result;\n\ttry {\n\t\tresult = await performLogin({ agent: false });\n\t} catch (err) {\n\t\tif (err instanceof PromptCancelledError) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Login cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tthrow err;\n\t}\n\n\tif (!result.ok) {\n\t\treturn c.error({\n\t\t\tcode: result.code,\n\t\t\tmessage: result.message,\n\t\t\tcta: {\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\n\treturn next();\n});\n\nawait registerHandwrittenGroups(cli);\n\nfor (const { name, tag } of API_GROUPS) {\n\tcli.command(name, { fetch, openapi: spec(tag) });\n}\n\nexport default cli;\n","[\n {\n \"group\": \"Core Resources\",\n \"tags\": [\n \"Accounts\",\n \"Users\",\n \"Webhooks\",\n \"Stats\"\n ]\n },\n {\n \"group\": \"Money\",\n \"tags\": [\n \"Ledgers\",\n \"Payouts\",\n \"Cards\",\n \"Transfers\",\n \"Deposits\",\n \"Swaps\",\n \"Payout Methods\",\n \"Verifications\"\n ]\n },\n {\n \"group\": \"Commerce\",\n \"tags\": [\n \"Products\",\n \"Plans\",\n \"Checkout Configurations\",\n \"Referrals\"\n ]\n },\n {\n \"group\": \"Tracking\",\n \"tags\": [\n \"People\",\n \"Events\"\n ]\n },\n {\n \"group\": \"Ads\",\n \"tags\": [\n \"Ads\",\n \"Ad Campaigns\",\n \"Ad Groups\",\n \"Audiences\"\n ]\n },\n {\n \"group\": \"Media\",\n \"tags\": [\n \"Media\"\n ]\n },\n {\n \"group\": \"Identity\",\n \"tags\": [\n \"Social Accounts\"\n ]\n }\n]\n","{\n \"Accounts\": \"Your Whop account\",\n \"Users\": \"Users on your platform\",\n \"Stats\": \"Platform-wide statistics\",\n \"Ledgers\": \"Transaction history\",\n \"Payouts\": \"Withdraw earnings\",\n \"Cards\": \"Issued virtual cards\",\n \"Transfers\": \"Move funds between accounts\",\n \"Deposits\": \"Add funds to your balance\",\n \"Swaps\": \"Convert between currencies\",\n \"Verifications\": \"Identity verification status\",\n \"Products\": \"What you're selling\",\n \"Plans\": \"Pricing for your products\",\n \"Checkout Configurations\": \"Optional / advanced: customize the checkout page\",\n \"Referrals\": \"Referral programs\",\n \"Ads\": \"Ad creatives\",\n \"Ad Campaigns\": \"Top-level campaign organization\",\n \"Ad Groups\": \"Sets of related ads\",\n \"Audiences\": \"Who sees your ads\",\n \"Social Accounts\": \"Linked social profiles\"\n}\n","import apiStructure from \"../api/api-structure.json\" with { type: \"json\" };\nimport tagDescriptions from \"../api/tag-descriptions.json\" with { type: \"json\" };\nimport { API_GROUPS, HANDWRITTEN_GROUPS } from \"../commands\";\nimport { c } from \"./colors\";\n\nconst descriptions: Record<string, string> = tagDescriptions;\nconst toCliName = (tag: string) => tag.toLowerCase().replace(/\\s+/g, \"-\");\n\nconst SECTION_LABELS = {\n\t\"get-started\": \"Get Started\",\n\tauth: \"Auth\",\n} as const;\n\nconst INTEGRATIONS = [\n\t{ name: \"completions\", desc: \"Generate shell completion script\" },\n\t{ name: \"mcp add\", desc: \"Register as MCP server\" },\n\t{ name: \"skills\", desc: \"Sync skill files to agents (add, list)\" },\n];\n\nconst GLOBAL_FLAGS = [\n\t{\n\t\tflag: \"--filter-output <keys>\",\n\t\tdesc: \"Filter output by key paths (e.g. foo,bar.baz,a[0,3])\",\n\t},\n\t{ flag: \"--format <toon|json|yaml|md|jsonl>\", desc: \"Output format\" },\n\t{ flag: \"--full-output\", desc: \"Show full output envelope\" },\n\t{ flag: \"--help\", desc: \"Show help\" },\n\t{ flag: \"--llms, --llms-full\", desc: \"Print LLM-readable manifest\" },\n\t{ flag: \"--mcp\", desc: \"Start as MCP stdio server\" },\n\t{ flag: \"--schema\", desc: \"Show JSON Schema for command\" },\n\t{\n\t\tflag: \"--token-count\",\n\t\tdesc: \"Print token count of output (instead of output)\",\n\t},\n\t{ flag: \"--token-limit <n>\", desc: \"Limit output to n tokens\" },\n\t{ flag: \"--token-offset <n>\", desc: \"Skip first n tokens of output\" },\n\t{ flag: \"--version\", desc: \"Show version\" },\n];\n\ntype HelpCommand = {\n\tname: string;\n\tdescription: string;\n};\n\ntype HelpSection = {\n\tlabel: string;\n\tcommands: HelpCommand[];\n};\n\nconst handwrittenSection = (\n\tsection: (typeof HANDWRITTEN_GROUPS)[number][\"section\"],\n): HelpSection => ({\n\tlabel: SECTION_LABELS[section],\n\tcommands: HANDWRITTEN_GROUPS.filter((group) => group.section === section).map(\n\t\t({ name, description }) => ({ name, description }),\n\t),\n});\n\nexport function buildGroupedHelp(version: string, description: string): string {\n\tconst lines: string[] = [];\n\n\tconst presentCommands = new Set(API_GROUPS.map(({ name }) => name));\n\n\tconst apiSections = apiStructure\n\t\t.map(({ group, tags }) => ({\n\t\t\tlabel: group,\n\t\t\tcommands: (tags as string[])\n\t\t\t\t.filter((tag) => presentCommands.has(toCliName(tag)))\n\t\t\t\t.map((tag) => ({\n\t\t\t\t\tname: toCliName(tag),\n\t\t\t\t\tdescription: descriptions[tag] ?? \"\",\n\t\t\t\t})),\n\t\t}))\n\t\t.filter((section) => section.commands.length > 0);\n\n\tconst commerceSections = apiSections.filter(\n\t\t(section) => section.label.toLowerCase() === \"commerce\",\n\t);\n\tconst otherApiSections = apiSections.filter(\n\t\t(section) => section.label.toLowerCase() !== \"commerce\",\n\t);\n\tconst allSections = [\n\t\thandwrittenSection(\"get-started\"),\n\t\t...commerceSections,\n\t\t...otherApiSections,\n\t\thandwrittenSection(\"auth\"),\n\t].filter((section) => section.commands.length > 0);\n\tconst maxCmdLen = Math.max(\n\t\t...allSections.flatMap((section) =>\n\t\t\tsection.commands.map((command) => command.name.length),\n\t\t),\n\t);\n\n\tlines.push(`whop@${version} — ${description}`);\n\tlines.push(\"\");\n\tlines.push(\"Usage: whop <command>\");\n\n\tfor (const section of allSections) {\n\t\tlines.push(\"\");\n\t\tlines.push(c.heading(section.label.toUpperCase()));\n\t\tfor (const cmd of section.commands) {\n\t\t\tconst pad = \" \".repeat(maxCmdLen - cmd.name.length);\n\t\t\tlines.push(\n\t\t\t\t` ${c.command(cmd.name)}${pad} ${c.description(cmd.description)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst maxIntLen = Math.max(...INTEGRATIONS.map((i) => i.name.length));\n\tlines.push(\"\");\n\tlines.push(\"Integrations:\");\n\tfor (const i of INTEGRATIONS) {\n\t\tlines.push(\n\t\t\t` ${c.command(i.name)}${\" \".repeat(maxIntLen - i.name.length)} ${c.description(i.desc)}`,\n\t\t);\n\t}\n\n\tconst maxFlagLen = Math.max(...GLOBAL_FLAGS.map((f) => f.flag.length));\n\tlines.push(\"\");\n\tlines.push(\"Global Options:\");\n\tfor (const f of GLOBAL_FLAGS) {\n\t\tlines.push(\n\t\t\t` ${c.flag(f.flag)}${\" \".repeat(maxFlagLen - f.flag.length)} ${c.description(f.desc)}`,\n\t\t);\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n","import cli from \"./cli\";\nimport { getActiveProfile } from \"./auth/profiles\";\nimport { buildGroupedHelp } from \"./lib/grouped-help\";\nimport { colorizeOutput, shouldColorize } from \"./lib/colorize-output\";\nimport { scheduleUpdateNotice } from \"./lib/update/check\";\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nconst argv = process.argv.slice(2);\nscheduleUpdateNotice(argv, pkg.version);\n\nasync function serve(argv: string[]) {\n\tif (shouldColorize(argv)) {\n\t\tawait cli.serve(argv, {\n\t\t\tstdout: (s) => process.stdout.write(colorizeOutput(s)),\n\t\t});\n\t} else {\n\t\tawait cli.serve(argv);\n\t}\n}\n\nif (argv.length === 0 && !getActiveProfile() && !process.env.WHOP_API_KEY) {\n\tawait serve([\"quickstart\"]);\n} else if (argv.length === 0 || (argv.length === 1 && argv[0] === \"--help\")) {\n\tprocess.stdout.write(\n\t\tbuildGroupedHelp(\n\t\t\tpkg.version,\n\t\t\tcli.description ?? \"Build and manage Whop apps from your terminal.\",\n\t\t) + \"\\n\",\n\t);\n\tprocess.exit(0);\n} else {\n\tawait serve(argv);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAAA,EACA;AAAA,IACE;AAAA,IACA;A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K,WAAW,KAAM,KAAK,WAAW,KAAK,KAAK,CAAC,MAAM,UAAW;AAC5E,UAAQ,OAAO;AAAA,IACd;AAAA,MACC,gBAAI;AAAA,MACJ,YAAI,eAAe;AAAA,IACpB,IAAI;AAAA,EACL;AACA,UAAQ,KAAK,CAAC;AACf,OAAO;AACN,QAAM,MAAM,IAAI;AACjB;","names":["identity","existed","profile","c","createWhopFetch","fetch","removed","spawnSync","existsSync","readFileSync","join","resolve","path","text","resolve","path","existsSync","readFileSync","writeFileSync","join","join","path","existsSync","readFileSync","writeFileSync","existsSync","join","readFileSync","SPAWN_VIA_SHELL","spawnSync","c","spec","resolve","config","chalk","text","select","isCancel","chalk","c","chalk","text","isCancel","select","argv","text","argv","fs","path","path","fs","c","cli","c","argv","text","fetch","c","argv"]}
|
|
1
|
+
{"version":3,"sources":["../src/api/groups.json","../src/auth/commands.ts","../src/apps/commands.ts","../src/journey/client.ts","../src/apps/api.ts","../src/apps/config.ts","../src/apps/scaffold.ts","../src/journey/quickstart.ts","../src/journey/billing.ts","../src/lib/colors.ts","../package.json","../src/lib/update/check.ts","../src/lib/colorize-output.ts","../src/lib/update/self-update.ts","../src/lib/update/command.ts","../src/commands.ts","../src/media/commands.ts","../src/lib/renderer.ts","../src/cli.ts","../src/lib/grouped-help.ts","../src/index.ts"],"sourcesContent":["[\n {\n \"name\": \"accounts\",\n \"tag\": \"Accounts\",\n \"description\": \"A business on Whop: profile, wallet, capabilities, settings.\",\n \"group\": \"Core Resources\"\n },\n {\n \"name\": \"users\",\n \"tag\": \"Users\",\n \"description\": \"A person on Whop: profile and connected identities.\",\n \"group\": \"Core Resources\"\n },\n {\n \"name\": \"stats\",\n \"tag\": \"Stats\",\n \"description\": \"Aggregated financial time series for reporting.\",\n \"group\": \"Core Resources\"\n },\n {\n \"name\": \"ledgers\",\n \"tag\": \"Ledgers\",\n \"description\": \"The activity feed behind an account or user's balance.\",\n \"group\": \"Money\"\n },\n {\n \"name\": \"payouts\",\n \"tag\": \"Payouts\",\n \"description\": \"Send money from a balance to a bank or wallet.\",\n \"group\": \"Money\"\n },\n {\n \"name\": \"cards\",\n \"tag\": \"Cards\",\n \"description\": \"Issue cards that spend from a balance.\",\n \"group\": \"Money\"\n },\n {\n \"name\": \"transfers\",\n \"tag\": \"Transfers\",\n \"description\": \"Move funds between Whop accounts and users.\",\n \"group\": \"Money\"\n },\n {\n \"name\": \"deposits\",\n \"tag\": \"Deposits\",\n \"description\": \"Add funds to a balance.\",\n \"group\": \"Money\"\n },\n {\n \"name\": \"swaps\",\n \"tag\": \"Swaps\",\n \"description\": \"Convert a balance between currencies.\",\n \"group\": \"Money\"\n },\n {\n \"name\": \"verifications\",\n \"tag\": \"Verifications\",\n \"description\": \"Identity review required before payouts and card issuing.\",\n \"group\": \"Money\"\n },\n {\n \"name\": \"products\",\n \"tag\": \"Products\",\n \"description\": \"The things you sell. Each owns plans and a store page.\",\n \"group\": \"Commerce\"\n },\n {\n \"name\": \"plans\",\n \"tag\": \"Plans\",\n \"description\": \"Pricing for a product: one-time, recurring, trials, stock.\",\n \"group\": \"Commerce\"\n },\n {\n \"name\": \"checkout-configurations\",\n \"tag\": \"Checkout Configurations\",\n \"description\": \"Turn a plan into a shareable, prefilled checkout link.\",\n \"group\": \"Commerce\"\n },\n {\n \"name\": \"referrals\",\n \"tag\": \"Referrals\",\n \"description\": \"Track who referred a purchase and what they earn.\",\n \"group\": \"Commerce\"\n },\n {\n \"name\": \"people\",\n \"tag\": \"People\",\n \"description\": \"Visitors and customers of an account, aggregated from pixel events.\",\n \"group\": \"Tracking\"\n },\n {\n \"name\": \"events\",\n \"tag\": \"Events\",\n \"description\": \"Conversion and engagement events tracked for attribution.\",\n \"group\": \"Tracking\"\n },\n {\n \"name\": \"ads\",\n \"tag\": \"Ads\",\n \"description\": \"The creative: copy, assets, and destination URL.\",\n \"group\": \"Ads\"\n },\n {\n \"name\": \"ad-campaigns\",\n \"tag\": \"Ad Campaigns\",\n \"description\": \"Platform, objective, and budget for a set of ads.\",\n \"group\": \"Ads\"\n },\n {\n \"name\": \"ad-groups\",\n \"tag\": \"Ad Groups\",\n \"description\": \"Audience, placements, and schedule within a campaign.\",\n \"group\": \"Ads\"\n },\n {\n \"name\": \"audiences\",\n \"tag\": \"Audiences\",\n \"description\": \"Reusable targeting lists for ad groups.\",\n \"group\": \"Ads\"\n },\n {\n \"name\": \"media\",\n \"tag\": \"Media\",\n \"description\": \"AI-generated assets, billed from a balance, attachable wherever files are accepted.\",\n \"group\": \"Media\"\n },\n {\n \"name\": \"social-accounts\",\n \"tag\": \"Social Accounts\",\n \"description\": \"Connected Facebook and Instagram accounts that run ads.\",\n \"group\": \"Identity\"\n },\n {\n \"name\": \"apps\",\n \"tag\": \"Apps\",\n \"description\": \"Apps you build on Whop: metadata, hosted builds, runtime logs.\",\n \"group\": \"Developer\"\n }\n]\n","import { Cli, z } from \"incur\";\nimport { validateApiKey, apiBaseUrl } from \"./client\";\nimport { readConfig } from \"./config\";\nimport { getSecret } from \"./secret-store\";\nimport { OAuthError, listOAuthAccounts, performOAuthLogin } from \"./oauth\";\nimport {\n\tderiveProfileName,\n\tgetActiveProfile,\n\tgetValidAccessToken,\n\tlistProfiles,\n\tremoveAllProfiles,\n\tremoveProfile,\n\tsetActiveProfileAccount,\n\tswitchProfile,\n\tupsertProfile,\n} from \"./profiles\";\nimport {\n\ttype AccountChoice,\n\tchooseAuthMethod,\n\tPromptCancelledError,\n\tpromptApiKey,\n\tselectAccount,\n\tselectProfile,\n\tstartSpinner,\n} from \"./prompts\";\nimport { AuthMethod, Identity, Profile } from \"./types\";\n\n/**\n * Auth commands: `whop auth login | logout | switch | account | status | list`.\n *\n * The login/logout business logic is context-free (`performLogin`,\n * `removeProfile`) and the incur run handlers are thin adapters. `loginAdapter`\n * and `logoutAdapter` are shared so the top-level `whop login` / `whop logout`\n * (registered in `index.ts`) behave identically without duplicating logic —\n * incur aliases can't cross from a group into a top-level command.\n */\n\n// --- CTA / error shapes accepted by the run context (kept minimal & structural) ---\ntype CtaCommand =\n\t| string\n\t| {\n\t\t\tcommand: string;\n\t\t\tdescription?: string | undefined;\n\t\t\toptions?: Record<string, unknown> | undefined;\n\t\t\targs?: Record<string, unknown> | undefined;\n\t };\ntype CtaInput = { description?: string | undefined; commands: CtaCommand[] };\ntype ErrorInput = {\n\tcode: string;\n\tmessage: string;\n\tcta?: CtaInput | undefined;\n\texitCode?: number | undefined;\n\tretryable?: boolean | undefined;\n};\n\n// --- Shared schemas ---\nexport const loginOptions = z.object({\n\tapiKey: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"API key for non-interactive login (skips the prompt)\"),\n\tprofile: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Name for this profile (defaults to the account route)\"),\n\taccountId: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Business account to act on behalf of (biz_xxx) — for OAuth users who manage more than one\",\n\t\t),\n});\n\nexport const loginEnv = z.object({\n\tWHOP_API_KEY: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"API key for non-interactive login\"),\n\tWHOP_API_BASE_URL: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Override the Whop API base URL\"),\n\tWHOP_CONFIG_DIR: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Override the CLI config directory\"),\n});\n\nexport const loginOutput = z.object({\n\tprofile: z.string().describe(\"The profile name\"),\n\tactive: z.boolean().describe(\"Whether this profile is now the active one\"),\n\tmethod: AuthMethod.describe(\"The authentication method\"),\n\tidentity: Identity.describe(\"The authenticated account or user identity\"),\n});\nexport type LoginOutput = z.infer<typeof loginOutput>;\n\nexport const logoutOptions = z.object({\n\tprofile: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Profile to remove (defaults to the active profile)\"),\n\tall: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\"Remove every profile and its stored secret (full reset)\"),\n});\nexport const logoutOutput = z.object({\n\tremoved: z.array(z.string()).describe(\"The removed profile name(s)\"),\n\tnewActive: z\n\t\t.string()\n\t\t.nullable()\n\t\t.describe(\"The profile that is now active, if any\"),\n});\nexport type LogoutOutput = z.infer<typeof logoutOutput>;\n\nconst statusOutput = z.object({\n\tloggedIn: z\n\t\t.boolean()\n\t\t.describe(\"Whether the active profile has a usable stored credential\"),\n\tprofile: z.string().nullable(),\n\tmethod: AuthMethod.nullable(),\n\tidentity: Identity.nullable().describe(\n\t\t\"The logged-in user (OAuth) or the account (API key)\",\n\t),\n\taccount: Identity.nullable().describe(\n\t\t\"The account auto-filled for scoped commands (account_id/company_id)\",\n\t),\n\thasSecret: z\n\t\t.boolean()\n\t\t.describe(\"Whether a secret was found in the OS keychain for this profile\"),\n});\n\nconst listOutput = z.object({\n\tactive: z.string().nullable(),\n\tprofiles: z.array(Profile),\n});\n\nconst switchArgs = z.object({\n\tname: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Profile to switch to (interactive picker if omitted)\"),\n});\nconst switchOutput = z.object({\n\tactive: z.string().describe(\"The newly active profile\"),\n});\n\nconst accountArgs = z.object({\n\tid: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Business account to make the default — id (biz_xxx) or route (interactive picker if omitted)\",\n\t\t),\n});\nconst accountOptions = z.object({\n\tlist: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"List the business accounts you can manage without changing the default\",\n\t\t),\n});\nconst accountListItem = z.object({\n\tid: z.string(),\n\ttitle: z.string(),\n\troute: z.string(),\n\tactive: z\n\t\t.boolean()\n\t\t.describe(\"Whether this is the profile's default business account\"),\n});\nconst accountOutput = z.object({\n\tprofile: z.string().describe(\"The active profile\"),\n\taccount: Identity.nullable().describe(\n\t\t\"The default business account passed to scoped commands\",\n\t),\n\taccounts: z\n\t\t.array(accountListItem)\n\t\t.describe(\"Business accounts this user can manage\"),\n});\n\nexport const loginExamples = [\n\t{ description: \"Interactive login\" },\n\t{\n\t\toptions: { apiKey: \"whop_xxx\" },\n\t\tdescription: \"Non-interactive login (CI / agents)\",\n\t},\n\t{\n\t\toptions: { apiKey: \"whop_xxx\", profile: \"prod\" },\n\t\tdescription: \"Log in and name the profile\",\n\t},\n];\nexport const loginHint =\n\t\"Agents / CI: pass --api-key or set WHOP_API_KEY to skip the prompt.\";\n\n// --- Context-free login flows ---\ntype LoginResult =\n\t| { ok: true; output: LoginOutput; existed: boolean; underscoped: boolean }\n\t| { ok: false; code: string; message: string };\n\nexport async function performLogin(input: {\n\tagent: boolean;\n\tapiKey?: string | undefined;\n\tprofile?: string | undefined;\n\taccountId?: string | undefined;\n}): Promise<LoginResult> {\n\tlet method: AuthMethod = \"api_key\";\n\tif (!input.agent && !input.apiKey) method = await chooseAuthMethod();\n\n\t// Route to the OAuth browser flow.\n\tif (method === \"oauth\") {\n\t\ttry {\n\t\t\tconst { profileName, identity, existed } = await performOAuthLogin({\n\t\t\t\tprofile: input.profile,\n\t\t\t\tagent: input.agent,\n\t\t\t\taccountId: input.accountId,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\texisted,\n\t\t\t\tunderscoped: false,\n\t\t\t\toutput: {\n\t\t\t\t\tprofile: profileName,\n\t\t\t\t\tactive: true,\n\t\t\t\t\tmethod: \"oauth\",\n\t\t\t\t\tidentity,\n\t\t\t\t},\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) {\n\t\t\t\treturn { ok: false, code: err.code, message: err.message };\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\t// Resolve the API key: flag/env > interactive prompt > error in agent mode.\n\tlet apiKey = input.apiKey;\n\tif (!apiKey) {\n\t\tif (input.agent) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tcode: \"API_KEY_REQUIRED\",\n\t\t\t\tmessage: \"No API key provided and not running interactively.\",\n\t\t\t};\n\t\t}\n\t\tapiKey = await promptApiKey();\n\t}\n\t// Normalize: the SDK adds the `Bearer ` prefix itself, so strip one if pasted.\n\tconst key = apiKey.replace(/^Bearer\\s+/i, \"\").trim();\n\n\t// 3. Validate against the API.\n\tlet result: Awaited<ReturnType<typeof validateApiKey>>;\n\tif (input.agent) {\n\t\tresult = await validateApiKey(key, apiBaseUrl());\n\t} else {\n\t\tconst s = startSpinner(\"Validating API key…\");\n\t\tresult = await validateApiKey(key, apiBaseUrl());\n\t\tconst okay = result.status === \"valid\" || result.status === \"underscoped\";\n\t\ts.stop(okay ? \"API key validated.\" : \"API key check failed.\");\n\t}\n\tif (result.status === \"invalid\") {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tcode: \"INVALID_API_KEY\",\n\t\t\tmessage: \"That API key was rejected (401 Unauthorized).\",\n\t\t};\n\t}\n\tif (result.status === \"error\") {\n\t\treturn { ok: false, code: \"VALIDATION_FAILED\", message: result.message };\n\t}\n\n\t// 4. Persist (secret → keychain, metadata → config) and activate.\n\tconst identity = result.identity;\n\tconst name = input.profile ?? deriveProfileName(identity);\n\tconst existed = listProfiles().some((profile) => profile.name === name);\n\tconst profile = upsertProfile({ name, method, secret: key, identity });\n\n\treturn {\n\t\tok: true,\n\t\texisted,\n\t\tunderscoped: result.status === \"underscoped\",\n\t\toutput: { profile: profile.name, active: true, method, identity },\n\t};\n}\n\n// --- Shared adapters (used by the group command and the top-level alias) ---\ntype LoginAdapterCtx = {\n\tagent: boolean;\n\toptions: {\n\t\tapiKey?: string | undefined;\n\t\tprofile?: string | undefined;\n\t\taccountId?: string | undefined;\n\t};\n\tenv: { WHOP_API_KEY?: string | undefined };\n\tok: (data: LoginOutput, meta?: { cta?: CtaInput | undefined }) => never;\n\terror: (options: ErrorInput) => never;\n};\n\nexport async function loginAdapter(c: LoginAdapterCtx): Promise<never> {\n\tlet result: LoginResult;\n\ttry {\n\t\tresult = await performLogin({\n\t\t\tagent: c.agent,\n\t\t\tapiKey: c.options.apiKey ?? c.env.WHOP_API_KEY,\n\t\t\tprofile: c.options.profile,\n\t\t\taccountId: c.options.accountId,\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof PromptCancelledError) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Login cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!result.ok) {\n\t\tlet cta: CtaInput | undefined;\n\t\tif (result.code === \"API_KEY_REQUIRED\") {\n\t\t\tcta = {\n\t\t\t\tdescription: \"Provide a key non-interactively:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"auth login\",\n\t\t\t\t\t\toptions: { apiKey: true },\n\t\t\t\t\t\tdescription: \"Pass --api-key <key>\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t} else if (\n\t\t\tresult.code === \"MULTIPLE_ACCOUNTS\" ||\n\t\t\tresult.code === \"ACCOUNT_NOT_FOUND\"\n\t\t) {\n\t\t\tcta = {\n\t\t\t\tdescription: \"Choose which business account to use:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"auth login\",\n\t\t\t\t\t\toptions: { accountId: true },\n\t\t\t\t\t\tdescription: \"Pass --account-id biz_xxx\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t}\n\t\treturn c.error({\n\t\t\tcode: result.code,\n\t\t\tmessage: result.message,\n\t\t\tretryable: result.code !== \"INVALID_API_KEY\",\n\t\t\tcta,\n\t\t});\n\t}\n\n\t// First-run vs returning user: check whether they have any products yet.\n\t// Probe whenever we have an account so a returning\n\t// user with zero products still gets the \"start selling\" path. Use the\n\t// resolved account id (not the user id, which is what identity holds for\n\t// OAuth). On failure just fall back to the generic CTA — don't block login.\n\tlet firstRun = !result.existed;\n\tconst accountId = getActiveProfile()?.accountId ?? \"\";\n\tif (accountId) {\n\t\ttry {\n\t\t\tconst { createWhopFetch } = await import(\"../api/index.js\");\n\t\t\tconst fetch = createWhopFetch();\n\t\t\tconst res = await fetch(\n\t\t\t\tnew Request(\n\t\t\t\t\t`https://api.whop.com/products?company_id=${accountId}&first=1`,\n\t\t\t\t),\n\t\t\t);\n\t\t\tif (res.ok) {\n\t\t\t\tconst data = (await res.json()) as { data?: unknown[] };\n\t\t\t\tfirstRun = (data.data?.length ?? 0) === 0;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Non-fatal — use generic CTA\n\t\t}\n\t}\n\n\t// No business account resolved (e.g. OAuth account with no business yet).\n\t// quickstart creates one — interactively, or via --business_name.\n\tif (!accountId) {\n\t\treturn c.ok(result.output, {\n\t\t\tcta: {\n\t\t\t\tdescription:\n\t\t\t\t\t\"You're logged in, but you don't have a business account yet. Create one and start selling in one command:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Create your business account, product, and checkout link\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\treturn c.ok(result.output, {\n\t\tcta: firstRun\n\t\t\t? {\n\t\t\t\t\tdescription: \"You're logged in. Start selling in one command:\",\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\"Create your product, set a price, get a checkout link\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tdescription: result.existed\n\t\t\t\t\t\t? \"Updated and switched to this profile:\"\n\t\t\t\t\t\t: \"Welcome back:\",\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\t\tdescription: \"See your status and what's next\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ command: \"auth status\", description: \"Show the active identity\" },\n\t\t\t\t\t],\n\t\t\t\t},\n\t});\n}\n\ntype LogoutAdapterCtx = {\n\toptions: { profile?: string | undefined; all?: boolean | undefined };\n\tok: (data: LogoutOutput, meta?: { cta?: CtaInput | undefined }) => never;\n\terror: (options: ErrorInput) => never;\n};\n\nexport function logoutAdapter(c: LogoutAdapterCtx): never {\n\tif (c.options.all) {\n\t\tif (c.options.profile) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CONFLICTING_OPTIONS\",\n\t\t\t\tmessage: \"--all removes every profile — don't combine it with --profile.\",\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\tconst removed = removeAllProfiles();\n\t\tif (removed.length === 0) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"NO_PROFILES\",\n\t\t\t\tmessage: \"No profiles to remove.\",\n\t\t\t\tretryable: false,\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: \"Log in first:\",\n\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\treturn c.ok(\n\t\t\t{ removed, newActive: null },\n\t\t\t{\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: `Removed ${removed.length} profile${removed.length === 1 ? \"\" : \"s\"}. To authenticate again:`,\n\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\tconst target = c.options.profile ?? getActiveProfile()?.name;\n\tif (!target) {\n\t\treturn c.error({\n\t\t\tcode: \"NO_ACTIVE_PROFILE\",\n\t\t\tmessage: \"No active profile to log out from.\",\n\t\t\tretryable: false,\n\t\t\tcta: {\n\t\t\t\tdescription: \"Log in first:\",\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\tconst { removed, newActive } = removeProfile(target);\n\tif (!removed) {\n\t\treturn c.error({\n\t\t\tcode: \"PROFILE_NOT_FOUND\",\n\t\t\tmessage: `No profile named \"${target}\".`,\n\t\t\tretryable: false,\n\t\t});\n\t}\n\treturn c.ok(\n\t\t{ removed: [target], newActive },\n\t\tnewActive\n\t\t\t? {\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: `Now using \"${newActive}\".`,\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"auth status\",\n\t\t\t\t\t\t\t\tdescription: \"Show the active identity\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: undefined,\n\t);\n}\n\n// --- The `auth` command group ---\nexport function buildAuthGroup() {\n\tconst auth = Cli.create(\"auth\", {\n\t\tdescription: \"Manage Whop authentication\",\n\t});\n\n\tauth.command(\"login\", {\n\t\tdescription: \"Log in to Whop\",\n\t\taliases: [\"add\"],\n\t\toptions: loginOptions,\n\t\tenv: loginEnv,\n\t\toutput: loginOutput,\n\t\texamples: loginExamples,\n\t\thint: loginHint,\n\t\trun: (c) => loginAdapter(c),\n\t});\n\n\tauth.command(\"logout\", {\n\t\tdescription: \"Log out — remove a saved profile, or all with --all\",\n\t\taliases: [\"remove\", \"rm\"],\n\t\toptions: logoutOptions,\n\t\toutput: logoutOutput,\n\t\texamples: [\n\t\t\t{ description: \"Remove the active profile\" },\n\t\t\t{\n\t\t\t\toptions: { all: true },\n\t\t\t\tdescription: \"Remove every profile (full reset)\",\n\t\t\t},\n\t\t],\n\t\trun: (c) => logoutAdapter(c),\n\t});\n\n\tauth.command(\"switch\", {\n\t\tdescription: \"Switch the active profile\",\n\t\targs: switchArgs,\n\t\toutput: switchOutput,\n\t\trun: async (c) => {\n\t\t\tconst profiles = listProfiles();\n\t\t\tif (profiles.length === 0) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"NO_PROFILES\",\n\t\t\t\t\tmessage: \"No profiles yet — log in first.\",\n\t\t\t\t\tretryable: true,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: \"To authenticate:\",\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{ command: \"auth login\", description: \"Log in to Whop\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet name = c.args.name;\n\t\t\tif (!name) {\n\t\t\t\tif (c.agent) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"PROFILE_REQUIRED\",\n\t\t\t\t\t\tmessage: `Specify a profile name. Available: ${profiles.map((p) => p.name).join(\", \")}.`,\n\t\t\t\t\t\tretryable: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tname = await selectProfile(profiles);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof PromptCancelledError) {\n\t\t\t\t\t\treturn c.error({\n\t\t\t\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\t\t\t\tmessage: \"Switch cancelled.\",\n\t\t\t\t\t\t\texitCode: 130,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst profile = switchProfile(name);\n\t\t\tif (!profile) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"PROFILE_NOT_FOUND\",\n\t\t\t\t\tmessage: `No profile named \"${name}\". Available: ${profiles.map((p) => p.name).join(\", \")}.`,\n\t\t\t\t\tretryable: true,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn c.ok(\n\t\t\t\t{ active: profile.name },\n\t\t\t\t{\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"auth status\",\n\t\t\t\t\t\t\t\tdescription: \"Show the active identity\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t});\n\n\tauth.command(\"account\", {\n\t\tdescription:\n\t\t\t\"List your business accounts or set the default one for the active profile\",\n\t\taliases: [\"accounts\"],\n\t\targs: accountArgs,\n\t\toptions: accountOptions,\n\t\toutput: accountOutput,\n\t\texamples: [\n\t\t\t{ description: \"Pick the default business account interactively\" },\n\t\t\t{\n\t\t\t\toptions: { list: true },\n\t\t\t\tdescription: \"List the business accounts you can manage\",\n\t\t\t},\n\t\t\t{\n\t\t\t\targs: { id: \"biz_xxx\" },\n\t\t\t\tdescription: \"Set the default business account\",\n\t\t\t},\n\t\t],\n\t\thint: \"OAuth profiles only — API key profiles are tied to a single business account.\",\n\t\trun: async (c) => {\n\t\t\tconst profile = getActiveProfile();\n\t\t\tif (!profile) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"NO_ACTIVE_PROFILE\",\n\t\t\t\t\tmessage: \"No active profile — log in first.\",\n\t\t\t\t\tretryable: true,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: \"To authenticate:\",\n\t\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (profile.method !== \"oauth\") {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"API_KEY_PROFILE\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"API key profiles are tied to a single business account. Log in with Whop (OAuth) to switch between the businesses you manage.\",\n\t\t\t\t\tretryable: false,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: \"To use a different business account:\",\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"auth login\",\n\t\t\t\t\t\t\t\tdescription: 'Choose \"Log in with Whop\"',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet token: string | null;\n\t\t\ttry {\n\t\t\t\ttoken = await getValidAccessToken(profile);\n\t\t\t} catch {\n\t\t\t\ttoken = null;\n\t\t\t}\n\t\t\tif (!token) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"SESSION_EXPIRED\",\n\t\t\t\t\tmessage: \"Your session is no longer valid — log in again.\",\n\t\t\t\t\tretryable: false,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: \"To authenticate:\",\n\t\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst s = c.agent ? null : startSpinner(\"Loading your business accounts…\");\n\t\t\tlet accounts: AccountChoice[];\n\t\t\ttry {\n\t\t\t\taccounts = await listOAuthAccounts(token);\n\t\t\t\ts?.stop(\n\t\t\t\t\t`Found ${accounts.length} business account${accounts.length === 1 ? \"\" : \"s\"}.`,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\ts?.stop(\"Couldn't load your business accounts.\");\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"ACCOUNT_LOOKUP_FAILED\",\n\t\t\t\t\tmessage: \"Couldn't load your business accounts. Please try again.\",\n\t\t\t\t\tretryable: true,\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (accounts.length === 0) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"NO_ACCOUNTS\",\n\t\t\t\t\tmessage: \"You don't have a business account yet.\",\n\t\t\t\t\tretryable: false,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: \"Create one and start selling in one command:\",\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\t\t\"Create your business account, product, and checkout link\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst currentAccount =\n\t\t\t\tprofile.accountId || profile.accountTitle || profile.accountRoute\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tid: profile.accountId,\n\t\t\t\t\t\t\ttitle: profile.accountTitle,\n\t\t\t\t\t\t\troute: profile.accountRoute,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null;\n\n\t\t\tif (c.options.list) {\n\t\t\t\treturn c.ok(\n\t\t\t\t\t{\n\t\t\t\t\t\tprofile: profile.name,\n\t\t\t\t\t\taccount: currentAccount,\n\t\t\t\t\t\taccounts: accounts.map((account) => ({\n\t\t\t\t\t\t\t...account,\n\t\t\t\t\t\t\tactive: account.id === profile.accountId,\n\t\t\t\t\t\t})),\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcta: {\n\t\t\t\t\t\t\tdescription: \"Change the default business account:\",\n\t\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcommand: \"auth account\",\n\t\t\t\t\t\t\t\t\targs: { id: true },\n\t\t\t\t\t\t\t\t\tdescription: \"Pass a business account id or route\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet requested = c.args.id;\n\t\t\tif (!requested) {\n\t\t\t\tif (c.agent) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"ACCOUNT_REQUIRED\",\n\t\t\t\t\t\tmessage: `Specify a business account. Available: ${accounts\n\t\t\t\t\t\t\t.map((account) => `${account.id} (${account.title})`)\n\t\t\t\t\t\t\t.join(\", \")}.`,\n\t\t\t\t\t\tretryable: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\trequested = (await selectAccount(accounts, profile.accountId)).id;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof PromptCancelledError) {\n\t\t\t\t\t\treturn c.error({\n\t\t\t\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\t\t\t\tmessage: \"Switch cancelled.\",\n\t\t\t\t\t\t\texitCode: 130,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst match =\n\t\t\t\taccounts.find((account) => account.id === requested) ??\n\t\t\t\taccounts.find((account) => account.route === requested);\n\t\t\tif (!match) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"ACCOUNT_NOT_FOUND\",\n\t\t\t\t\tmessage: `No business account \"${requested}\" for this user. Available: ${accounts\n\t\t\t\t\t\t.map((account) => `${account.id} (${account.title})`)\n\t\t\t\t\t\t.join(\", \")}.`,\n\t\t\t\t\tretryable: true,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!setActiveProfileAccount(match, profile.name)) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"PROFILE_REMOVED\",\n\t\t\t\t\tmessage: `Profile \"${profile.name}\" was removed while switching — log in again.`,\n\t\t\t\t\tretryable: false,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: \"To authenticate:\",\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{ command: \"auth login\", description: \"Log in to Whop\" },\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn c.ok(\n\t\t\t\t{\n\t\t\t\t\tprofile: profile.name,\n\t\t\t\t\taccount: match,\n\t\t\t\t\taccounts: accounts.map((account) => ({\n\t\t\t\t\t\t...account,\n\t\t\t\t\t\tactive: account.id === match.id,\n\t\t\t\t\t})),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tdescription: `Now acting on behalf of ${match.title}.`,\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"auth status\",\n\t\t\t\t\t\t\t\tdescription: \"Show the active identity\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t});\n\n\tauth.command(\"status\", {\n\t\tdescription: \"Show the active identity (whoami)\",\n\t\taliases: [\"whoami\"],\n\t\toutput: statusOutput,\n\t\trun: async (c) => {\n\t\t\tconst profile = getActiveProfile();\n\t\t\tif (!profile) {\n\t\t\t\treturn c.ok(\n\t\t\t\t\t{\n\t\t\t\t\t\tloggedIn: false,\n\t\t\t\t\t\tprofile: null,\n\t\t\t\t\t\tmethod: null,\n\t\t\t\t\t\tidentity: null,\n\t\t\t\t\t\taccount: null,\n\t\t\t\t\t\thasSecret: false,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcta: {\n\t\t\t\t\t\t\tdescription: \"To authenticate:\",\n\t\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t\t{ command: \"auth login\", description: \"Log in to Whop\" },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst hasSecret = getSecret(profile.name) !== null;\n\t\t\t// \"Logged in\" means we can actually obtain a Bearer token. For oauth\n\t\t\t// this may refresh the access token; a revoked/expired refresh token\n\t\t\t// resolves to null instead of throwing, so the reported state is honest.\n\t\t\tlet loggedIn = hasSecret;\n\t\t\tif (hasSecret) {\n\t\t\t\ttry {\n\t\t\t\t\tloggedIn = (await getValidAccessToken(profile)) !== null;\n\t\t\t\t} catch {\n\t\t\t\t\tloggedIn = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst account =\n\t\t\t\tprofile.accountId || profile.accountTitle || profile.accountRoute\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tid: profile.accountId,\n\t\t\t\t\t\t\ttitle: profile.accountTitle,\n\t\t\t\t\t\t\troute: profile.accountRoute,\n\t\t\t\t\t\t}\n\t\t\t\t\t: null;\n\t\t\treturn c.ok(\n\t\t\t\t{\n\t\t\t\t\tloggedIn,\n\t\t\t\t\tprofile: profile.name,\n\t\t\t\t\tmethod: profile.method,\n\t\t\t\t\tidentity:\n\t\t\t\t\t\tprofile.method === \"oauth\"\n\t\t\t\t\t\t\t? { id: profile.userId, email: profile.userEmail }\n\t\t\t\t\t\t\t: account,\n\t\t\t\t\taccount,\n\t\t\t\t\thasSecret,\n\t\t\t\t},\n\t\t\t\tloggedIn\n\t\t\t\t\t? undefined\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tcta: {\n\t\t\t\t\t\t\t\tdescription: hasSecret\n\t\t\t\t\t\t\t\t\t? \"Your session is no longer valid — log in again:\"\n\t\t\t\t\t\t\t\t\t: \"The stored secret is missing — log in again:\",\n\t\t\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t\t\t{ command: \"auth login\", description: \"Log in to Whop\" },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t);\n\t\t},\n\t});\n\n\tauth.command(\"list\", {\n\t\tdescription: \"List saved authentication profiles\",\n\t\taliases: [\"ls\"],\n\t\toutput: listOutput,\n\t\trun: () => {\n\t\t\tconst { activeProfile, profiles } = readConfig();\n\t\t\tconst active =\n\t\t\t\tprofiles.find((p) => p.name === activeProfile)?.name ?? null;\n\t\t\treturn { active, profiles };\n\t\t},\n\t});\n\n\treturn auth;\n}\n","import { isCancel, select, spinner, text } from \"@clack/prompts\";\nimport { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { join, relative, resolve } from \"node:path\";\nimport chalk from \"chalk\";\nimport { Cli, Openapi, z } from \"incur\";\nimport { appsSpec, createWhopFetch, filterSpecByTag } from \"../api/index.js\";\nimport {\n\tcreateApp,\n\tcreateAppBuild,\n\tcreateDevAccessToken,\n\tgetApp,\n\tlistAppLogs,\n\tlistApps,\n\tpromoteAppBuild,\n\tupdateAppRoute,\n\tupdateAppSecrets,\n\tuploadBuildArchive,\n\twaitForBuildPromotion,\n\twaitForFileReady,\n\ttype WhopApp,\n\ttype WhopAppLog,\n} from \"./api.js\";\nimport {\n\tAPP_CONFIG_FILENAME,\n\tfindProjectDir,\n\treadAppConfig,\n\tslugify,\n\twriteAppConfig,\n\ttype AppConfig,\n} from \"./config.js\";\nimport {\n\tdetectPackageManager as detectInstalledPackageManager,\n\tfindViteConfig,\n\toutputTail,\n\tpmInstallHint,\n\trunTanstackCreate,\n\ttanstackCreateCommand,\n\twhopifyProject,\n\ttype PackageManager,\n} from \"./scaffold.js\";\n\n// The whop() vite plugin writes this archive into the build output directory.\nconst BUILD_ARCHIVE = \"dist/whop-build.zip\";\n\n// Env names that control the local Node/package-manager runtime rather than\n// the app. Injecting them from remotely-stored secrets would let anyone with\n// developer:update_app on the app execute code on a teammate's machine the\n// next time they run `whop apps dev`.\nconst UNSAFE_DEV_ENV_KEYS = new Set([\n\t\"PATH\",\n\t\"NODE_OPTIONS\",\n\t\"NODE_EXTRA_CA_CERTS\",\n\t\"NODE_REPL_EXTERNAL_MODULE\",\n]);\nconst UNSAFE_DEV_ENV_PREFIXES = [\"NPM_\", \"PNPM_\", \"YARN_\", \"BUN_\", \"LD_\", \"DYLD_\"];\n\nfunction isUnsafeDevEnvKey(key: string): boolean {\n\tconst upper = key.toUpperCase();\n\treturn (\n\t\tUNSAFE_DEV_ENV_KEYS.has(upper) ||\n\t\tUNSAFE_DEV_ENV_PREFIXES.some((prefix) => upper.startsWith(prefix))\n\t);\n}\n\nconst BuildSchema = z.object({\n\tid: z.string(),\n\tstatus: z.string(),\n\tis_production: z.boolean().optional(),\n\turl: z.string().optional(),\n});\n\ntype ErrorOptions = {\n\tcode: string;\n\tmessage: string;\n\tretryable?: boolean;\n\texitCode?: number;\n\tcta?: {\n\t\tdescription?: string;\n\t\tcommands: { command: string; description?: string }[];\n\t};\n};\n\n/**\n * incur's `c.error()` builds a result that only takes effect when returned\n * from the command's own `run` — so helper functions abort by throwing this,\n * and `deploy` converts it back into `c.error(...)` at the top level.\n */\nclass DeployAbort extends Error {\n\tconstructor(readonly options: ErrorOptions) {\n\t\tsuper(options.message);\n\t}\n}\n\ntype DeployContext = {\n\tagent: boolean;\n};\n\n/**\n * The project's lockfile decides the package manager; without one (e.g. a\n * fresh scaffold that hasn't installed yet) fall back to whatever is\n * installed, preferring bun — never blindly npm.\n */\nfunction detectProjectPackageManager(projectDir: string): string {\n\tif (\n\t\texistsSync(join(projectDir, \"bun.lock\")) ||\n\t\texistsSync(join(projectDir, \"bun.lockb\"))\n\t)\n\t\treturn \"bun\";\n\tif (existsSync(join(projectDir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n\tif (existsSync(join(projectDir, \"yarn.lock\"))) return \"yarn\";\n\tif (existsSync(join(projectDir, \"package-lock.json\"))) return \"npm\";\n\treturn detectInstalledPackageManager() ?? \"npm\";\n}\n\nfunction hasScript(projectDir: string, script: string): boolean {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(projectDir, \"package.json\"), \"utf-8\"),\n\t\t) as { scripts?: Record<string, string> };\n\t\treturn Boolean(pkg.scripts?.[script]);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n// npm/pnpm/yarn are .cmd shims on Windows, which can't be spawned without a\n// shell. Everywhere else, spawning without a shell avoids quoting pitfalls.\nconst SPAWN_VIA_SHELL = process.platform === \"win32\";\n\nfunction runScript(\n\tprojectDir: string,\n\tscript: string,\n\textraEnv: Record<string, string> = {},\n): void {\n\tconst pm = detectProjectPackageManager(projectDir);\n\tconst result = spawnSync(pm, [\"run\", script], {\n\t\tcwd: projectDir,\n\t\tstdio: \"inherit\",\n\t\tshell: SPAWN_VIA_SHELL,\n\t\tenv: { ...process.env, ...extraEnv },\n\t});\n\tif (result.error) {\n\t\tthrow new Error(\n\t\t\t`Could not run \\`${pm} run ${script}\\`: ${result.error.message}`,\n\t\t);\n\t}\n\tif (result.status !== 0) {\n\t\tthrow new Error(\n\t\t\t`\\`${pm} run ${script}\\` failed with exit code ${result.status ?? \"unknown\"}`,\n\t\t);\n\t}\n}\n\nfunction runInstall(c: { agent: boolean }, projectDir: string): void {\n\tconst pm = detectProjectPackageManager(projectDir);\n\tconst spin = c.agent ? null : spinner();\n\tspin?.start(`Installing dependencies with ${pm}`);\n\tconst result = spawnSync(pm, [\"install\"], {\n\t\tcwd: projectDir,\n\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\tencoding: \"utf-8\",\n\t\tshell: SPAWN_VIA_SHELL,\n\t});\n\tif (result.error || result.status !== 0) {\n\t\tspin?.error(`${pm} install failed`);\n\t\tthrow new Error(\n\t\t\t`\\`${pm} install\\` failed${result.status != null ? ` with exit code ${result.status}` : \"\"} — run it manually inside ${projectDir}, then re-run \\`whop apps deploy\\`.${outputTail(result)}`,\n\t\t);\n\t}\n\tspin?.stop(`Installed dependencies with ${pm}`);\n}\n\nfunction log(c: { agent: boolean }, message: string): void {\n\tif (!c.agent) console.log(message);\n}\n\nasync function promptText(\n\tmessage: string,\n\tplaceholder: string,\n\tinitialValue?: string,\n): Promise<string | null> {\n\tconst value = await text({ message, placeholder, initialValue });\n\tif (isCancel(value)) return null;\n\treturn String(value);\n}\n\nfunction cancelled(): never {\n\tthrow new DeployAbort({\n\t\tcode: \"CANCELLED\",\n\t\tmessage: \"Cancelled.\",\n\t\texitCode: 130,\n\t});\n}\n\nfunction formatManualSteps(steps: string[]): string {\n\treturn steps.map((step, i) => ` ${i + 1}. ${step}`).join(\"\\n\");\n}\n\nfunction formatAppList(apps: WhopApp[]): string {\n\tconst recent = [...apps]\n\t\t.sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))\n\t\t.slice(0, 10);\n\treturn recent\n\t\t.map(\n\t\t\t(a) => ` ${a.id} ${a.name}${a.route ? ` (${a.route}.whop.app)` : \"\"}`,\n\t\t)\n\t\t.join(\"\\n\");\n}\n\n/**\n * Registers the OpenAPI-generated commands for one tag of the apps spec\n * directly onto a command group. Done explicitly (instead of incur's\n * `{ fetch, openapi }` group registration) so generated commands and\n * hand-written ones like `deploy` can live in the same group.\n */\nasync function registerSpecCommands(\n\tgroup: ReturnType<typeof Cli.create>,\n\ttag: string,\n): Promise<void> {\n\tconst spec = filterSpecByTag(appsSpec as Record<string, unknown>, tag);\n\tconst generated = await Openapi.generateCommands(\n\t\tspec as Openapi.OpenAPISpec,\n\t\tcreateWhopFetch(),\n\t);\n\tfor (const [name, entry] of generated) {\n\t\tif (\"run\" in entry) group.command(name, entry);\n\t}\n}\n\n/**\n * Step 1: a package manager must exist before anything else — scaffolding,\n * installing, and building all need one.\n */\nfunction ensurePackageManager(): PackageManager {\n\tconst pm = detectInstalledPackageManager();\n\tif (pm) return pm;\n\tthrow new DeployAbort({\n\t\tcode: \"NO_PACKAGE_MANAGER\",\n\t\tmessage: `No package manager found (looked for bun, pnpm, npm). Install one and re-run \\`whop apps deploy\\`:\\n\\n bun (recommended): ${pmInstallHint(\"bun\")}\\n pnpm: ${pmInstallHint(\"pnpm\")}\\n npm: ${pmInstallHint(\"npm\")}`,\n\t});\n}\n\n/**\n * Step 2: the current directory must contain a Vite app (package.json + vite\n * config). Interactively offers to scaffold one; in agent mode prints the\n * exact scaffold command so the agent can run it and re-invoke deploy.\n */\nasync function ensureViteApp(\n\tc: DeployContext,\n\tpm: PackageManager,\n\tdirOption: string | undefined,\n): Promise<{ projectDir: string; freshlyScaffolded: boolean }> {\n\tconst projectDir = dirOption\n\t\t? resolve(dirOption)\n\t\t: (findProjectDir() ?? process.cwd());\n\n\tconst isViteApp =\n\t\texistsSync(join(projectDir, \"package.json\")) &&\n\t\tfindViteConfig(projectDir) !== undefined;\n\tif (isViteApp) return { projectDir, freshlyScaffolded: false };\n\n\tif (c.agent) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"NOT_A_VITE_APP\",\n\t\t\tmessage: [\n\t\t\t\t`${projectDir} doesn't look like a Vite app (missing package.json or vite config).`,\n\t\t\t\t\"\",\n\t\t\t\t\"Ask the user whether to scaffold a new app here, or locate their existing Vite app.\",\n\t\t\t\t\"\",\n\t\t\t\t\"To scaffold a new app (TanStack Start), run:\",\n\t\t\t\t` ${tanstackCreateCommand(pm, \"<app-name>\")}`,\n\t\t\t\t` cd <app-name> && ${pm} install`,\n\t\t\t\t\"\",\n\t\t\t\t\"Then re-run `whop apps deploy` from inside the app directory.\",\n\t\t\t\t\"Or, if a Vite app already exists somewhere else, re-run `whop apps deploy --dir <path-to-app>`.\",\n\t\t\t].join(\"\\n\"),\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"apps deploy\",\n\t\t\t\t\t\tdescription: \"Re-run from inside a Vite app directory\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tconst choice = await select({\n\t\tmessage: `${projectDir} doesn't look like a Vite app. What do you want to do?`,\n\t\toptions: [\n\t\t\t{\n\t\t\t\tvalue: \"scaffold\",\n\t\t\t\tlabel: \"Scaffold a new Whop app here (TanStack Start)\",\n\t\t\t},\n\t\t\t{ value: \"cancel\", label: \"Cancel — I'll cd into my app directory\" },\n\t\t],\n\t});\n\tif (isCancel(choice) || choice === \"cancel\") cancelled();\n\n\tconst scaffolded = await scaffoldNewApp(c, pm);\n\treturn { projectDir: scaffolded, freshlyScaffolded: true };\n}\n\n/**\n * Interactive scaffold: asks for name + route, registers the app on Whop\n * (claiming the route before any files are written, so a taken route fails\n * fast), scaffolds the TanStack Start template, and links it.\n */\nasync function scaffoldNewApp(\n\tc: DeployContext,\n\tpm: PackageManager,\n): Promise<string> {\n\tconst name = await promptText(\"What is your app called?\", \"My Site\");\n\tif (name === null) cancelled();\n\n\tconst slug = slugify(name);\n\tconst routeInput = await promptText(\n\t\t\"Which route should it live at? (your-route.whop.app)\",\n\t\tslug,\n\t\tslug,\n\t);\n\tif (routeInput === null) cancelled();\n\tconst route = slugify(routeInput);\n\tif (!route) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\tmessage: `Couldn't derive a route from \"${routeInput}\" — use letters and numbers (e.g. my-site).`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\n\tconst targetDir = resolve(`./${route}`);\n\tif (existsSync(targetDir) && readdirSync(targetDir).length > 0) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"TARGET_NOT_EMPTY\",\n\t\t\tmessage: `Target directory is not empty: ${targetDir}. Pick a different route, or run \\`whop apps deploy\\` from an empty directory.`,\n\t\t});\n\t}\n\n\tlet app: WhopApp;\n\ttry {\n\t\tapp = await createApp({ name, route });\n\t} catch (err) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"CREATE_FAILED\",\n\t\t\tmessage:\n\t\t\t\terr instanceof Error ? err.message : \"Failed to register the app\",\n\t\t\tretryable: true,\n\t\t});\n\t}\n\n\tconst spin = c.agent ? null : spinner();\n\tspin?.start(\"Scaffolding the latest TanStack Start template\");\n\ttry {\n\t\trunTanstackCreate({ targetDir, projectName: route, pm });\n\t\tspin?.stop(`Scaffolded ${route} from the latest TanStack Start template`);\n\t} catch (err) {\n\t\tspin?.error(\"Scaffold failed\");\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"SCAFFOLD_FAILED\",\n\t\t\tmessage: `${err instanceof Error ? err.message : \"Failed to scaffold the project\"}\\n\\nThe app ${app.id} is already registered — scaffold into a fresh directory and re-run \\`whop apps deploy --app ${app.id}\\` there.`,\n\t\t});\n\t}\n\n\twriteAppConfig(targetDir, { app_id: app.id, name, route });\n\treturn targetDir;\n}\n\n/**\n * Step 3b: the project must be linked to a Whop app via whop.app.json.\n * `--app` links explicitly; otherwise offers to select or create one\n * (always creating when the account has no apps yet). In agent mode, prints\n * the exact commands — including recently created apps so the agent can ask\n * the user about reusing one.\n */\nasync function ensureAppLinked(\n\tc: DeployContext,\n\tprojectDir: string,\n\tappOption: string | undefined,\n): Promise<AppConfig> {\n\tif (appOption) {\n\t\tlet app: WhopApp;\n\t\ttry {\n\t\t\tapp = await getApp(appOption);\n\t\t} catch (err) {\n\t\t\tthrow new DeployAbort({\n\t\t\t\tcode: \"APP_NOT_FOUND\",\n\t\t\t\tmessage: `Could not load app ${appOption}: ${err instanceof Error ? err.message : \"unknown error\"}`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\tconst config = await withRoute(c, app);\n\t\twriteAppConfig(projectDir, config);\n\t\tlog(\n\t\t\tc,\n\t\t\tchalk.dim(\n\t\t\t\t`Linked ${config.name} (${config.app_id}) → ${APP_CONFIG_FILENAME}`,\n\t\t\t),\n\t\t);\n\t\treturn config;\n\t}\n\n\tconst existing = readAppConfig(projectDir);\n\tif (existing) return existing;\n\n\tconst apps = await listApps();\n\n\tif (c.agent) {\n\t\tconst reuse =\n\t\t\tapps.length > 0\n\t\t\t\t? `This account has existing apps — ask the user whether to reuse one:\\n${formatAppList(apps)}\\n\\nTo reuse one: whop apps deploy --app <app_id>\\n\\n`\n\t\t\t\t: \"This account has no apps yet, so a new one must be created.\\n\\n\";\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"NO_APP_LINKED\",\n\t\t\tmessage: [\n\t\t\t\t`No ${APP_CONFIG_FILENAME} here — this project isn't linked to a Whop app yet.`,\n\t\t\t\t\"\",\n\t\t\t\t`${reuse}To create a new app, ask the user for a name and route (the route becomes <route>.whop.app), then run:`,\n\t\t\t\t' whop apps create --name \"My Site\" --route my-site',\n\t\t\t\t\"\",\n\t\t\t\t\"Then deploy with the returned app id:\",\n\t\t\t\t\" whop apps deploy --app <app_id>\",\n\t\t\t].join(\"\\n\"),\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"apps create\",\n\t\t\t\t\t\tdescription: \"Create a new app (pass --name and --route)\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"apps deploy\",\n\t\t\t\t\t\tdescription: \"Re-run with --app <app_id> to link and deploy\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tlet selected: WhopApp | null = null;\n\tif (apps.length > 0) {\n\t\tconst recent = [...apps].sort(\n\t\t\t(a, b) => (b.created_at ?? 0) - (a.created_at ?? 0),\n\t\t);\n\t\tconst choice = await select({\n\t\t\tmessage: \"Which app should this project deploy to?\",\n\t\t\toptions: [\n\t\t\t\t...recent.map((a) => ({\n\t\t\t\t\tvalue: a.id,\n\t\t\t\t\tlabel: `${a.name} (${a.id}${a.route ? `, ${a.route}.whop.app` : \"\"})`,\n\t\t\t\t})),\n\t\t\t\t{ value: \"__new__\", label: \"Create a new app\" },\n\t\t\t],\n\t\t});\n\t\tif (isCancel(choice)) cancelled();\n\t\tif (choice !== \"__new__\") {\n\t\t\tselected = recent.find((a) => a.id === choice) ?? null;\n\t\t}\n\t}\n\n\tif (!selected) {\n\t\tconst name = await promptText(\"What is your app called?\", \"My Site\");\n\t\tif (name === null) cancelled();\n\t\tconst slug = slugify(name);\n\t\tconst routeInput = await promptText(\n\t\t\t\"Which route should it live at? (your-route.whop.app)\",\n\t\t\tslug,\n\t\t\tslug,\n\t\t);\n\t\tif (routeInput === null) cancelled();\n\t\tconst route = slugify(routeInput);\n\t\tif (!route) {\n\t\t\tthrow new DeployAbort({\n\t\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\t\tmessage: `Couldn't derive a route from \"${routeInput}\" — use letters and numbers (e.g. my-site).`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\ttry {\n\t\t\tselected = await createApp({ name, route });\n\t\t} catch (err) {\n\t\t\tthrow new DeployAbort({\n\t\t\t\tcode: \"CREATE_FAILED\",\n\t\t\t\tmessage:\n\t\t\t\t\terr instanceof Error ? err.message : \"Failed to register the app\",\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t}\n\n\tconst config = await withRoute(c, selected);\n\twriteAppConfig(projectDir, config);\n\tlog(\n\t\tc,\n\t\tchalk.dim(\n\t\t\t`Linked ${config.name} (${config.app_id}) → ${APP_CONFIG_FILENAME}`,\n\t\t),\n\t);\n\treturn config;\n}\n\n/**\n * Hosted deploys serve from <route>.whop.app, so a linked app must have a\n * route. Prompts for one interactively; in agent mode prints the exact\n * update command.\n */\nasync function withRoute(c: DeployContext, app: WhopApp): Promise<AppConfig> {\n\tif (app.route) return { app_id: app.id, name: app.name, route: app.route };\n\n\tif (c.agent) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\tmessage: `App ${app.id} (${app.name}) has no route — hosted apps are served from <route>.whop.app. Ask the user which route to claim, then run:\\n whop apps update ${app.id} --route <route>\\n whop apps deploy --app ${app.id}`,\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: `apps update ${app.id}`,\n\t\t\t\t\t\tdescription: \"Set the route (pass --route)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tconst slug = slugify(app.name);\n\tconst routeInput = await promptText(\n\t\t`${app.name} has no route yet. Which route should it live at? (your-route.whop.app)`,\n\t\tslug,\n\t\tslug,\n\t);\n\tif (routeInput === null) cancelled();\n\tconst route = slugify(routeInput);\n\tif (!route) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"ROUTE_REQUIRED\",\n\t\t\tmessage: `Couldn't derive a route from \"${routeInput}\" — use letters and numbers (e.g. my-site).`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\ttry {\n\t\tconst updated = await updateAppRoute(app.id, route);\n\t\treturn {\n\t\t\tapp_id: updated.id,\n\t\t\tname: updated.name,\n\t\t\troute: updated.route ?? route,\n\t\t};\n\t} catch (err) {\n\t\tthrow new DeployAbort({\n\t\t\tcode: \"UPDATE_FAILED\",\n\t\t\tmessage: err instanceof Error ? err.message : \"Failed to set the route\",\n\t\t\tretryable: true,\n\t\t});\n\t}\n}\n\nfunction resolveLinkedAppId(appOption: string | undefined): string {\n\tif (appOption) return appOption;\n\tconst projectDir = findProjectDir();\n\tconst config = projectDir ? readAppConfig(projectDir) : null;\n\tif (config) return config.app_id;\n\tthrow new Error(\n\t\t`No app specified. Pass --app app_xxx or run inside a project with ${APP_CONFIG_FILENAME}.`,\n\t);\n}\n\n// `--since`/`--until` accept a relative duration (\"30s\", \"10m\", \"2h\", \"1d\")\n// or anything the API parses as an ISO 8601 timestamp.\nconst DURATION_MS: Record<string, number> = {\n\ts: 1000,\n\tm: 60_000,\n\th: 3_600_000,\n\td: 86_400_000,\n};\n\nfunction parseTimeOption(value: string | undefined): string | undefined {\n\tif (!value) return undefined;\n\tconst match = /^(\\d+)([smhd])$/.exec(value);\n\tif (!match) return value;\n\treturn new Date(\n\t\tDate.now() - Number(match[1]) * DURATION_MS[match[2]],\n\t).toISOString();\n}\n\nconst LOG_LEVEL_COLORS: Record<string, (s: string) => string> = {\n\terror: chalk.red,\n\twarn: chalk.yellow,\n};\n\nfunction printLogLine(row: WhopAppLog): void {\n\tconst time = row.created_at.replace(\"T\", \" \").replace(\"Z\", \"\");\n\tconst color = LOG_LEVEL_COLORS[row.level] ?? chalk.dim;\n\tconst request = row.request_method\n\t\t? chalk.dim(` ${row.request_method} ${row.request_path ?? \"\"}`)\n\t\t: \"\";\n\tconsole.log(\n\t\t`${chalk.dim(time)} ${color(row.level.padEnd(5))}${request} ${row.message}`,\n\t);\n\tif (row.stack) console.log(chalk.dim(row.stack));\n}\n\nfunction buildSecretsGroup() {\n\tconst secrets = Cli.create(\"secrets\", {\n\t\tdescription:\n\t\t\t\"Manage app secrets — encrypted at rest, injected as env bindings into the hosted runtime and `whop apps dev`\",\n\t});\n\n\tsecrets.command(\"list\", {\n\t\tdescription: \"Show the app's secrets\",\n\t\toptions: z.object({\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"App id (defaults to the project's linked app)\"),\n\t\t}),\n\t\trun: async (c) => {\n\t\t\tconst remote = await getApp(resolveLinkedAppId(c.options.app));\n\t\t\treturn c.ok({ app_id: remote.id, secrets: remote.secrets ?? {} });\n\t\t},\n\t});\n\n\tsecrets.command(\"set\", {\n\t\tdescription: \"Add or overwrite secrets\",\n\t\toptions: z.object({\n\t\t\tsecret: z\n\t\t\t\t.array(z.string())\n\t\t\t\t.min(1)\n\t\t\t\t.describe(\"KEY=VALUE pair (repeatable)\"),\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"App id (defaults to the project's linked app)\"),\n\t\t}),\n\t\texamples: [\n\t\t\t{ options: { secret: [\"MAIL_API_KEY=mail-key-123\"] } },\n\t\t\t{ options: { secret: [\"A=1\", \"B=2\"], app: \"app_xxxxxxxx\" } },\n\t\t],\n\t\trun: async (c) => {\n\t\t\tconst updates: Record<string, string> = {};\n\t\t\tfor (const pair of c.options.secret) {\n\t\t\t\tconst eq = pair.indexOf(\"=\");\n\t\t\t\tif (eq <= 0) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"INVALID_SECRET\",\n\t\t\t\t\t\tmessage: `\"${pair}\" is not KEY=VALUE. Use --secret NAME=value (an empty value deletes the secret).`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tupdates[pair.slice(0, eq)] = pair.slice(eq + 1);\n\t\t\t}\n\t\t\tconst remote = await updateAppSecrets(\n\t\t\t\tresolveLinkedAppId(c.options.app),\n\t\t\t\tupdates,\n\t\t\t);\n\t\t\treturn c.ok({ app_id: remote.id, secrets: remote.secrets ?? {} });\n\t\t},\n\t});\n\n\tsecrets.command(\"unset\", {\n\t\tdescription: \"Delete secrets by name\",\n\t\toptions: z.object({\n\t\t\tkey: z.array(z.string()).min(1).describe(\"Secret name (repeatable)\"),\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"App id (defaults to the project's linked app)\"),\n\t\t}),\n\t\texamples: [{ options: { key: [\"MAIL_API_KEY\"] } }],\n\t\trun: async (c) => {\n\t\t\tconst updates: Record<string, string | null> = {};\n\t\t\tfor (const key of c.options.key) updates[key] = null;\n\t\t\tconst remote = await updateAppSecrets(\n\t\t\t\tresolveLinkedAppId(c.options.app),\n\t\t\t\tupdates,\n\t\t\t);\n\t\t\treturn c.ok({ app_id: remote.id, secrets: remote.secrets ?? {} });\n\t\t},\n\t});\n\n\treturn secrets;\n}\n\nexport async function buildAppGroup() {\n\tconst app = Cli.create(\"apps\", {\n\t\tdescription: \"Build and deploy fully-hosted web apps on Whop (*.whop.app)\",\n\t});\n\n\tawait registerSpecCommands(app, \"Apps\");\n\n\tconst builds = Cli.create(\"builds\", {\n\t\tdescription: \"Manage app builds (list, inspect, promote)\",\n\t});\n\tawait registerSpecCommands(builds, \"App builds\");\n\tapp.command(builds);\n\n\tapp.command(buildSecretsGroup());\n\n\tapp.command(\"logs\", {\n\t\tdescription:\n\t\t\t\"Read the app's server runtime logs — console output, uncaught exceptions, failed requests (kept 7 days)\",\n\t\thint: \"Newest first in the structured output; the terminal view prints oldest to newest. Deploy, hit your app, then read its logs to debug server code.\",\n\t\toptions: z.object({\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"App id (defaults to the project's linked app)\"),\n\t\t\tlevel: z\n\t\t\t\t.enum([\"log\", \"debug\", \"info\", \"warn\", \"error\"])\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Only console lines of this level\"),\n\t\t\tquery: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Only logs whose message contains this text\"),\n\t\t\tbuild: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Only logs from this build (abld_xxx)\"),\n\t\t\tsince: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t'Start of the window — a duration like \"10m\"/\"2h\"/\"1d\" or an ISO 8601 timestamp',\n\t\t\t\t),\n\t\t\tuntil: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe('End of the window — a duration or ISO 8601 timestamp'),\n\t\t\tfirst: z\n\t\t\t\t.number()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Number of log lines to return (max 500)\"),\n\t\t\tafter: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Cursor from a previous page's page_info\"),\n\t\t}),\n\t\texamples: [\n\t\t\t{ description: \"Recent logs for the linked app\" },\n\t\t\t{\n\t\t\t\toptions: { level: \"error\" as const, since: \"1h\" },\n\t\t\t\tdescription: \"Errors from the last hour\",\n\t\t\t},\n\t\t\t{\n\t\t\t\toptions: { query: \"checkout\", app: \"app_xxxxxxxx\" },\n\t\t\t\tdescription: \"Search another app's logs by message text\",\n\t\t\t},\n\t\t],\n\t\toutputPolicy: \"agent-only\",\n\t\trun: async (c) => {\n\t\t\tconst appId = resolveLinkedAppId(c.options.app);\n\t\t\tconst page = await listAppLogs(appId, {\n\t\t\t\tlevel: c.options.level,\n\t\t\t\tquery: c.options.query,\n\t\t\t\tapp_build_id: c.options.build,\n\t\t\t\tcreated_after: parseTimeOption(c.options.since),\n\t\t\t\tcreated_before: parseTimeOption(c.options.until),\n\t\t\t\tfirst: c.options.first,\n\t\t\t\tafter: c.options.after,\n\t\t\t});\n\t\t\tconst logs = page.data ?? [];\n\n\t\t\tif (!c.agent && !c.formatExplicit) {\n\t\t\t\tif (logs.length === 0) {\n\t\t\t\t\tconsole.log(chalk.dim(\"No logs in this window.\"));\n\t\t\t\t}\n\t\t\t\tfor (const row of [...logs].reverse()) printLogLine(row);\n\t\t\t}\n\n\t\t\treturn c.ok({ app_id: appId, logs, page_info: page.page_info });\n\t\t},\n\t});\n\n\tapp.command(\"dev\", {\n\t\tdescription: \"Run the local dev server for this app\",\n\t\thint: \"Starts the project's dev script with WHOP_APP_ID set and a short-lived access token injected as WHOP_API_KEY (minted from your CLI credential), so server-side SDK calls work locally without env setup. An explicitly exported WHOP_API_KEY is used as-is.\",\n\t\toptions: z.object({\n\t\t\tdir: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Project directory (defaults to the current directory)\"),\n\t\t}),\n\t\trun: async (c) => {\n\t\t\tconst projectDir = c.options.dir\n\t\t\t\t? resolve(c.options.dir)\n\t\t\t\t: findProjectDir();\n\t\t\tconst config = projectDir ? readAppConfig(projectDir) : null;\n\t\t\tif (!projectDir || !config) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"NO_PROJECT\",\n\t\t\t\t\tmessage: `No ${APP_CONFIG_FILENAME} found in this directory or any parent. Run \\`whop apps deploy\\` to link this project to a Whop app.`,\n\t\t\t\t\tcta: {\n\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcommand: \"apps deploy\",\n\t\t\t\t\t\t\t\tdescription: \"Link this project to a Whop app and ship it\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Server-side SDK calls read WHOP_API_KEY; mint a short-lived access\n\t\t\t// token from the CLI's credential so they work in local dev with zero\n\t\t\t// env setup. An explicitly exported WHOP_API_KEY wins.\n\t\t\tconst injected: Record<string, string> = {\n\t\t\t\tWHOP_APP_ID: config.app_id,\n\t\t\t};\n\t\t\tif (process.env.WHOP_API_KEY) {\n\t\t\t\tlog(\n\t\t\t\t\tc,\n\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t\"Using the WHOP_API_KEY from your environment for server-side calls.\",\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst minted = await createDevAccessToken();\n\t\t\t\t\tinjected.WHOP_API_KEY = minted.token;\n\t\t\t\t\tconst expiresAt =\n\t\t\t\t\t\ttypeof minted.expires_at === \"number\"\n\t\t\t\t\t\t\t? new Date(minted.expires_at * 1000)\n\t\t\t\t\t\t\t: minted.expires_at\n\t\t\t\t\t\t\t\t? new Date(minted.expires_at)\n\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\tconst expiry = expiresAt\n\t\t\t\t\t\t? ` (expires ${expiresAt.toLocaleTimeString()})`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t\t`Injected a temporary access token as WHOP_API_KEY${expiry} — server-side SDK calls just work. Restart \\`whop apps dev\\` to refresh it.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Couldn't mint a temporary access token (${err instanceof Error ? err.message : \"unknown error\"}) — set WHOP_API_KEY manually for server-side calls.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Mirror the hosted runtime: the app's secrets become env vars for the\n\t\t\t// dev server. Explicitly exported env vars win over stored secrets.\n\t\t\ttry {\n\t\t\t\tconst remote = await getApp(config.app_id);\n\t\t\t\tconst secretEntries = Object.entries(remote.secrets ?? {}).filter(\n\t\t\t\t\t([key]) => !(key in process.env) && !(key in injected),\n\t\t\t\t);\n\t\t\t\tconst unsafe = secretEntries.filter(([key]) => isUnsafeDevEnvKey(key));\n\t\t\t\tfor (const [key, value] of secretEntries) {\n\t\t\t\t\tif (!isUnsafeDevEnvKey(key)) injected[key] = value;\n\t\t\t\t}\n\t\t\t\tif (unsafe.length > 0) {\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t\t`Skipped app secret${unsafe.length === 1 ? \"\" : \"s\"} ${unsafe.map(([key]) => key).join(\", \")} — these names control the local runtime and are never injected by \\`whop apps dev\\`.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst injectedCount = secretEntries.length - unsafe.length;\n\t\t\t\tif (injectedCount > 0) {\n\t\t\t\t\tlog(\n\t\t\t\t\t\tc,\n\t\t\t\t\t\tchalk.dim(\n\t\t\t\t\t\t\t`Injected ${injectedCount} app secret${injectedCount === 1 ? \"\" : \"s\"} into the environment (${secretEntries\n\t\t\t\t\t\t\t\t.filter(([key]) => !isUnsafeDevEnvKey(key))\n\t\t\t\t\t\t\t\t.map(([key]) => key)\n\t\t\t\t\t\t\t\t.join(\", \")}).`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlog(\n\t\t\t\t\tc,\n\t\t\t\t\tchalk.yellow(\n\t\t\t\t\t\t`Couldn't fetch app secrets (${err instanceof Error ? err.message : \"unknown error\"}) — continuing without them.`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlog(c, chalk.dim(`Starting dev server for ${config.name}...`));\n\t\t\ttry {\n\t\t\t\trunScript(projectDir, \"dev\", injected);\n\t\t\t} catch (err) {\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"DEV_FAILED\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\terr instanceof Error\n\t\t\t\t\t\t\t? err.message\n\t\t\t\t\t\t\t: \"Dev server exited with an error\",\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn c.ok({ success: true });\n\t\t},\n\t});\n\n\tapp.command(\"deploy\", {\n\t\tdescription: \"Build, upload and ship this app live\",\n\t\thint: \"The one-stop deploy: verifies the project is a Whop-ready Vite app (offering to scaffold or link one if not), builds, typechecks, uploads the build, and promotes it to production. Use --skip_promote to upload a preview-only build, then promote it later with `whop apps builds promote <build_id>`.\",\n\t\toptions: z.object({\n\t\t\tdir: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Project directory (defaults to the current directory)\"),\n\t\t\tapp: z\n\t\t\t\t.string()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\n\t\t\t\t\t\"Link this project to an app (app_xxx) before deploying — writes whop.app.json, replacing any existing link\",\n\t\t\t\t),\n\t\t\tskip_promote: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Upload the build without promoting it to production\"),\n\t\t\tskip_typecheck: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Skip the typecheck step\"),\n\t\t\tskip_build: z\n\t\t\t\t.boolean()\n\t\t\t\t.optional()\n\t\t\t\t.describe(\"Skip the build step and upload the existing dist/ output\"),\n\t\t}),\n\t\toutput: BuildSchema,\n\t\toutputPolicy: \"agent-only\",\n\t\texamples: [\n\t\t\t{ description: \"Build and ship to production\" },\n\t\t\t{\n\t\t\t\toptions: { app: \"app_xxxxxxxx\" },\n\t\t\t\tdescription: \"Link this project to an existing app, then deploy\",\n\t\t\t},\n\t\t\t{\n\t\t\t\toptions: { skip_promote: true },\n\t\t\t\tdescription: \"Upload a preview build without promoting\",\n\t\t\t},\n\t\t],\n\t\trun: async (c) => {\n\t\t\ttry {\n\t\t\t\tconst pm = ensurePackageManager();\n\n\t\t\t\tconst { projectDir, freshlyScaffolded } = await ensureViteApp(\n\t\t\t\t\tc,\n\t\t\t\t\tpm,\n\t\t\t\t\tc.options.dir,\n\t\t\t\t);\n\n\t\t\t\tconst config = await ensureAppLinked(c, projectDir, c.options.app);\n\n\t\t\t\tconst { manualSteps } = whopifyProject({\n\t\t\t\t\ttargetDir: projectDir,\n\t\t\t\t\troute: config.route,\n\t\t\t\t});\n\t\t\t\tif (manualSteps.length > 0) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"WHOPIFY_INCOMPLETE\",\n\t\t\t\t\t\tmessage: `${config.name} is linked (${config.app_id}), but the project isn't fully wired for Whop hosting yet. Complete these steps:\\n\\n${formatManualSteps(manualSteps)}\\n\\nThen re-run \\`whop apps deploy\\` — it re-checks the wiring and applies anything it can.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (!c.options.skip_build) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfreshlyScaffolded ||\n\t\t\t\t\t\t!existsSync(join(projectDir, \"node_modules\", \"@whop\", \"cli\"))\n\t\t\t\t\t) {\n\t\t\t\t\t\t// whopifyProject adds @whop/cli as a devDependency (the vite\n\t\t\t\t\t\t// config imports whop() from @whop/cli/vite), so the build needs\n\t\t\t\t\t\t// it installed.\n\t\t\t\t\t\trunInstall(c, projectDir);\n\t\t\t\t\t}\n\t\t\t\t\t// Build BEFORE typecheck: framework builds generate typed artifacts\n\t\t\t\t\t// the typecheck depends on (TanStack's routeTree.gen), so a fresh\n\t\t\t\t\t// never-built project would otherwise always fail its first deploy.\n\t\t\t\t\tlog(c, chalk.dim(\"[1/4] Building...\"));\n\t\t\t\t\trunScript(projectDir, \"build\", { WHOP_APP_ID: config.app_id });\n\t\t\t\t\tif (!c.options.skip_typecheck && hasScript(projectDir, \"typecheck\")) {\n\t\t\t\t\t\tlog(c, chalk.dim(\"[2/4] Typechecking...\"));\n\t\t\t\t\t\trunScript(projectDir, \"typecheck\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst archivePath = join(projectDir, BUILD_ARCHIVE);\n\t\t\t\tif (!existsSync(archivePath)) {\n\t\t\t\t\treturn c.error({\n\t\t\t\t\t\tcode: \"NO_BUILD_ARCHIVE\",\n\t\t\t\t\t\tmessage: `No build archive at ${BUILD_ARCHIVE}. Add the whop() plugin from @whop/cli/vite to your vite config, then build. See https://whop.com/docs/apps/hosting.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tconst zip = readFileSync(archivePath);\n\t\t\t\tconst sizeMb = (zip.byteLength / 1024 / 1024).toFixed(1);\n\t\t\t\tconst checksum = createHash(\"sha256\").update(zip).digest(\"hex\");\n\n\t\t\t\tconst spin = c.agent ? null : spinner();\n\t\t\t\tspin?.start(`[3/4] Uploading build archive (${sizeMb} MB)`);\n\t\t\t\tlet build;\n\t\t\t\ttry {\n\t\t\t\t\tconst fileId = await uploadBuildArchive(\n\t\t\t\t\t\tnew Uint8Array(zip),\n\t\t\t\t\t\t`${config.route}-build.zip`,\n\t\t\t\t\t);\n\t\t\t\t\tspin?.message(\"[3/4] Processing archive\");\n\t\t\t\t\tawait waitForFileReady(fileId);\n\t\t\t\t\tspin?.message(\"[3/4] Creating build\");\n\t\t\t\t\tbuild = await createAppBuild({\n\t\t\t\t\t\tapp_id: config.app_id,\n\t\t\t\t\t\tchecksum,\n\t\t\t\t\t\tfile_id: fileId,\n\t\t\t\t\t});\n\t\t\t\t\tspin?.stop(`[3/4] Build uploaded (${build.id})`);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tspin?.error(\"[3/4] Upload failed\");\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tif (!c.options.skip_promote) {\n\t\t\t\t\tconst promoteSpin = c.agent ? null : spinner();\n\t\t\t\t\tpromoteSpin?.start(\"[4/4] Promoting to production\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait promoteAppBuild(build.id);\n\t\t\t\t\t\tbuild = await waitForBuildPromotion(build.id);\n\t\t\t\t\t\tpromoteSpin?.stop(\n\t\t\t\t\t\t\tbuild.is_production\n\t\t\t\t\t\t\t\t? \"[4/4] Promoted to production\"\n\t\t\t\t\t\t\t\t: `[4/4] Promotion pending (status: ${build.status})`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tpromoteSpin?.error(\"[4/4] Promote failed\");\n\t\t\t\t\t\tthrow err;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog(c, chalk.dim(\"[4/4] Skipping promotion (--skip_promote)\"));\n\t\t\t\t}\n\n\t\t\t\tconst promoted = build.is_production === true;\n\t\t\t\tconst productionUrl = promoted\n\t\t\t\t\t? ((await getApp(config.app_id)).hosted_url ?? undefined)\n\t\t\t\t\t: undefined;\n\n\t\t\t\tif (!c.agent && !c.formatExplicit) {\n\t\t\t\t\tconst cdTarget = relative(process.cwd(), projectDir) || \".\";\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\tchalk.green.bold(\n\t\t\t\t\t\t\t\tpromoted ? \"✓ Deployed to production\" : \"✓ Build uploaded\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t` ${chalk.dim(build.id)}`,\n\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\t...(promoted && productionUrl\n\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t` ${chalk.bold(\"Live\")} ${chalk.cyan.underline(productionUrl)}`,\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t: [\n\t\t\t\t\t\t\t\t\t\t`${chalk.bold(\"Promote when ready\")} ${chalk.cyan.bold(`whop apps builds promote ${build.id}`)}`,\n\t\t\t\t\t\t\t\t\t]),\n\t\t\t\t\t\t\t...(freshlyScaffolded\n\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t\t\t\t\tchalk.bold(\"Next\"),\n\t\t\t\t\t\t\t\t\t\t...(cdTarget !== \".\" ? [` cd ${cdTarget}`] : []),\n\t\t\t\t\t\t\t\t\t\t` ${chalk.cyan.bold(\"whop apps dev\")} ${chalk.dim(\"→ local dev server\")}`,\n\t\t\t\t\t\t\t\t\t\t` ${chalk.cyan.bold(\"whop apps deploy\")} ${chalk.dim(\"→ ship your changes\")}`,\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t: []),\n\t\t\t\t\t\t\t\"\",\n\t\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn c.ok(\n\t\t\t\t\t{\n\t\t\t\t\t\tid: build.id,\n\t\t\t\t\t\tstatus: build.status,\n\t\t\t\t\t\tis_production: promoted,\n\t\t\t\t\t\turl: productionUrl,\n\t\t\t\t\t},\n\t\t\t\t\tpromoted\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tcta: {\n\t\t\t\t\t\t\t\t\tcommands: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcommand: `apps builds promote ${build.id}`,\n\t\t\t\t\t\t\t\t\t\t\tdescription: \"Promote this build to production\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof DeployAbort) return c.error(err.options);\n\t\t\t\treturn c.error({\n\t\t\t\t\tcode: \"DEPLOY_FAILED\",\n\t\t\t\t\tmessage: err instanceof Error ? err.message : \"Deploy failed\",\n\t\t\t\t\tretryable: true,\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t});\n\n\treturn app;\n}\n","import { createWhopFetch } from \"../api/index.js\";\n\nconst PLACEHOLDER = \"https://api.whop.com\";\nconst whopFetch = createWhopFetch();\n\n/**\n * Thin wrapper around the API fetch proxy for hand-written commands. The proxy\n * strips the host and uses apiBaseUrl() internally, auto-fills the active\n * account, and normalizes errors to a top-level `message` — so we only need the\n * pathname (a query string in `path` is fine) and can surface `message` directly.\n */\nexport async function makeWhopRequest<T>(\n\tmethod: \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\",\n\tpath: string,\n\tbody?: Record<string, unknown>,\n): Promise<T> {\n\tconst init: RequestInit = { method };\n\tif (body !== undefined) init.body = JSON.stringify(body);\n\tconst res = await whopFetch(new Request(`${PLACEHOLDER}${path}`, init));\n\n\tif (!res.ok) {\n\t\tconst payload = (await res.json().catch(() => null)) as {\n\t\t\tmessage?: string;\n\t\t} | null;\n\t\tthrow new Error(payload?.message ?? res.statusText);\n\t}\n\n\t// DELETE (and other 204s) can return an empty body, which `res.json()` would\n\t// reject — treat an empty body as a successful, content-less response.\n\tconst text = await res.text();\n\treturn (text ? JSON.parse(text) : { success: true }) as T;\n}\n","import { resolveActiveAccountId } from \"../api/index.js\";\nimport { makeWhopRequest } from \"../journey/client.js\";\n\nexport type WhopApp = {\n\tid: string;\n\tname: string;\n\troute?: string | null;\n\thosted_url?: string | null;\n\tsecrets?: Record<string, string> | null;\n\tcreated_at?: number;\n};\n\nexport type WhopAppBuild = {\n\tid: string;\n\tstatus: \"draft\" | \"pending\" | \"approved\" | \"rejected\";\n\tplatform: string;\n\tchecksum: string;\n\tis_production: boolean;\n\tcreated_at?: number;\n};\n\ntype WhopFile = {\n\tid: string;\n\tupload_status: string;\n\tupload_url?: string | null;\n\tupload_headers?: Record<string, string> | null;\n};\n\nexport async function createApp(input: {\n\tname: string;\n\troute: string;\n\tcompany_id?: string;\n}): Promise<WhopApp> {\n\tconst company_id = input.company_id ?? (await resolveActiveAccountId());\n\treturn makeWhopRequest<WhopApp>(\"POST\", \"/apps\", { ...input, company_id });\n}\n\nconst DEV_TOKEN_TTL_MS = (3 * 60 - 1) * 60 * 1000;\n\n/**\n * Mints a short-lived access token from the CLI's credential (POST\n * /access_tokens): with an API key it's a company token inheriting the key's\n * permissions; with OAuth login the user and scopes come from the token\n * itself (which also pins the expiry). `whop apps dev` injects it into the\n * dev server so server-side SDK calls work without manual env vars.\n */\nexport async function createDevAccessToken(): Promise<{\n\ttoken: string;\n\texpires_at?: string | number | null;\n}> {\n\tconst company_id = await resolveActiveAccountId();\n\treturn makeWhopRequest(\"POST\", \"/access_tokens\", {\n\t\t...(company_id ? { company_id } : {}),\n\t\texpires_at: new Date(Date.now() + DEV_TOKEN_TTL_MS).toISOString(),\n\t});\n}\n\nexport async function listApps(): Promise<WhopApp[]> {\n\tconst companyId = await resolveActiveAccountId();\n\tconst query = companyId ? `?company_id=${encodeURIComponent(companyId)}` : \"\";\n\tconst response = await makeWhopRequest<{ data?: WhopApp[] }>(\n\t\t\"GET\",\n\t\t`/apps${query}`,\n\t);\n\treturn response.data ?? [];\n}\n\nexport async function getApp(appId: string): Promise<WhopApp> {\n\treturn makeWhopRequest<WhopApp>(\"GET\", `/apps/${appId}`);\n}\n\nexport async function updateAppRoute(\n\tappId: string,\n\troute: string,\n): Promise<WhopApp> {\n\treturn makeWhopRequest<WhopApp>(\"PATCH\", `/apps/${appId}`, { route });\n}\n\nexport async function updateAppSecrets(\n\tappId: string,\n\tsecrets: Record<string, string | null>,\n): Promise<WhopApp> {\n\treturn makeWhopRequest<WhopApp>(\"PATCH\", `/apps/${appId}`, { secrets });\n}\n\nexport type WhopAppLog = {\n\tapp_id: string;\n\tapp_build_id: string;\n\trequest_id: string;\n\tcreated_at: string;\n\tsource: string;\n\tlevel: string;\n\tmessage: string;\n\tstack?: string | null;\n\trequest_method?: string | null;\n\trequest_path?: string | null;\n\tresponse_status?: number | null;\n\toutcome?: string | null;\n\tcpu_time_ms?: number;\n\twall_time_ms?: number;\n\ttruncated?: boolean;\n};\n\nexport type WhopAppLogsPage = {\n\tdata: WhopAppLog[];\n\tpage_info?: {\n\t\tend_cursor?: string | null;\n\t\tstart_cursor?: string | null;\n\t\thas_next_page?: boolean;\n\t\thas_previous_page?: boolean;\n\t};\n};\n\nexport async function listAppLogs(\n\tappId: string,\n\tparams: Record<string, string | number | undefined>,\n): Promise<WhopAppLogsPage> {\n\tconst query = new URLSearchParams();\n\tfor (const [key, value] of Object.entries(params)) {\n\t\tif (value !== undefined && value !== \"\") query.set(key, String(value));\n\t}\n\tconst qs = query.size > 0 ? `?${query}` : \"\";\n\treturn makeWhopRequest<WhopAppLogsPage>(\"GET\", `/apps/${appId}/logs${qs}`);\n}\n\nexport async function createAppBuild(input: {\n\tapp_id: string;\n\tchecksum: string;\n\tfile_id: string;\n}): Promise<WhopAppBuild> {\n\treturn makeWhopRequest<WhopAppBuild>(\"POST\", \"/app_builds\", {\n\t\tapp_id: input.app_id,\n\t\tplatform: \"web\",\n\t\tchecksum: input.checksum,\n\t\tattachment: { id: input.file_id },\n\t});\n}\n\nexport async function getAppBuild(buildId: string): Promise<WhopAppBuild> {\n\treturn makeWhopRequest<WhopAppBuild>(\"GET\", `/app_builds/${buildId}`);\n}\n\nexport async function promoteAppBuild(buildId: string): Promise<WhopAppBuild> {\n\treturn makeWhopRequest<WhopAppBuild>(\n\t\t\"POST\",\n\t\t`/app_builds/${buildId}/promote`,\n\t\t{},\n\t);\n}\n\n/**\n * Uploads a build archive: creates a file record, PUTs the bytes to the\n * presigned URL, and returns the file id. The archive is public so the hosting\n * worker can fetch it from a stable CDN URL. The file is still `pending` when\n * this returns — call waitForFileReady before attaching it to a build.\n */\nexport async function uploadBuildArchive(\n\tzip: Uint8Array,\n\tfilename: string,\n): Promise<string> {\n\tconst file = await makeWhopRequest<WhopFile>(\"POST\", \"/files\", {\n\t\tfilename,\n\t\tvisibility: \"public\",\n\t});\n\n\tif (!file.upload_url) {\n\t\tthrow new Error(\"File creation did not return an upload URL.\");\n\t}\n\n\tconst body = new Uint8Array(zip).buffer as ArrayBuffer;\n\tconst uploadResponse = await fetch(file.upload_url, {\n\t\tmethod: \"PUT\",\n\t\theaders: file.upload_headers ?? { \"Content-Type\": \"application/zip\" },\n\t\tbody,\n\t});\n\tif (!uploadResponse.ok) {\n\t\tthrow new Error(\n\t\t\t`Archive upload failed: ${uploadResponse.status} ${await uploadResponse.text()}`,\n\t\t);\n\t}\n\n\treturn file.id;\n}\n\n/**\n * Polls the file until upload processing marks it `ready`. Direct-to-S3 uploads\n * complete asynchronously (the S3 event pipeline verifies the object and flips\n * the status), so a build can only attach the file once it is ready.\n */\nexport async function waitForFileReady(\n\tfileId: string,\n\ttimeoutMs = 60_000,\n): Promise<void> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() < deadline) {\n\t\tconst file = await makeWhopRequest<WhopFile>(\"GET\", `/files/${fileId}`);\n\t\tif (file.upload_status === \"ready\") return;\n\t\tawait sleep(1_000);\n\t}\n\tthrow new Error(\n\t\t\"Timed out waiting for the build archive to finish processing.\",\n\t);\n}\n\nexport async function waitForBuildPromotion(\n\tbuildId: string,\n\ttimeoutMs = 30_000,\n): Promise<WhopAppBuild> {\n\tconst deadline = Date.now() + timeoutMs;\n\tlet latest = await getAppBuild(buildId);\n\twhile (Date.now() < deadline) {\n\t\tif (latest.is_production) return latest;\n\t\tif (latest.status === \"rejected\") {\n\t\t\tthrow new Error(\"Build was rejected and cannot be promoted.\");\n\t\t}\n\t\tawait sleep(750);\n\t\tlatest = await getAppBuild(buildId);\n\t}\n\treturn latest;\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nexport const APP_CONFIG_FILENAME = \"whop.app.json\";\n\nexport type AppConfig = {\n\tapp_id: string;\n\tname: string;\n\troute: string;\n};\n\nexport function findProjectDir(startDir?: string): string | null {\n\tlet dir = resolve(startDir ?? process.cwd());\n\tfor (let i = 0; i < 25; i++) {\n\t\tif (existsSync(join(dir, APP_CONFIG_FILENAME))) return dir;\n\t\tconst parent = resolve(dir, \"..\");\n\t\tif (parent === dir) break;\n\t\tdir = parent;\n\t}\n\treturn null;\n}\n\nexport function readAppConfig(projectDir: string): AppConfig | null {\n\tconst path = join(projectDir, APP_CONFIG_FILENAME);\n\tif (!existsSync(path)) return null;\n\ttry {\n\t\tconst parsed = JSON.parse(\n\t\t\treadFileSync(path, \"utf-8\"),\n\t\t) as Partial<AppConfig>;\n\t\tif (\n\t\t\ttypeof parsed.app_id === \"string\" &&\n\t\t\ttypeof parsed.name === \"string\" &&\n\t\t\ttypeof parsed.route === \"string\"\n\t\t) {\n\t\t\treturn { app_id: parsed.app_id, name: parsed.name, route: parsed.route };\n\t\t}\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function writeAppConfig(projectDir: string, config: AppConfig): void {\n\twriteFileSync(\n\t\tjoin(projectDir, APP_CONFIG_FILENAME),\n\t\t`${JSON.stringify(config, null, \"\\t\")}\\n`,\n\t);\n}\n\nexport function slugify(name: string): string {\n\treturn name\n\t\t.toLowerCase()\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t.replace(/^-+|-+$/g, \"\")\n\t\t.slice(0, 63);\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport { buildVersion } from \"../lib/build-info.js\";\n\n/**\n * Scaffolding for `whop apps deploy`.\n *\n * Instead of shipping a template inside this package, we run TanStack's\n * official create command (`@tanstack/cli create`) with the Cloudflare\n * deployment adapter — always the latest upstream template — and then apply\n * the minimal Whop edits on top: the `whop()` vite plugin (imported from\n * `@whop/cli/vite`), a `deploy` script, and the worker name.\n */\n\n// Windows needs shell resolution for npx/pnpm/bunx (they are .cmd shims).\nconst SPAWN_VIA_SHELL = process.platform === \"win32\";\n\nexport type PackageManager = \"npm\" | \"pnpm\" | \"bun\" | \"yarn\";\n\nconst DLX_RUNNERS: Record<PackageManager, string[]> = {\n\tnpm: [\"npx\", \"-y\"],\n\tpnpm: [\"pnpm\", \"dlx\"],\n\tbun: [\"bunx\"],\n\tyarn: [\"yarn\", \"dlx\"],\n};\n\n/** Auto-detection order when --pm is not passed. */\nexport const PM_PRIORITY = [\n\t\"bun\",\n\t\"pnpm\",\n\t\"npm\",\n] as const satisfies readonly PackageManager[];\n\nexport function isPmInstalled(pm: PackageManager): boolean {\n\tconst result = spawnSync(pm, [\"--version\"], {\n\t\tstdio: \"ignore\",\n\t\tshell: SPAWN_VIA_SHELL,\n\t});\n\treturn !result.error && result.status === 0;\n}\n\n/** First installed package manager, preferring bun, then pnpm, then npm. */\nexport function detectPackageManager(): PackageManager | null {\n\treturn PM_PRIORITY.find(isPmInstalled) ?? null;\n}\n\nexport function pmInstallHint(pm: PackageManager): string {\n\tconst win = process.platform === \"win32\";\n\tswitch (pm) {\n\t\tcase \"bun\":\n\t\t\treturn win\n\t\t\t\t? 'powershell -c \"irm bun.sh/install.ps1 | iex\"'\n\t\t\t\t: \"curl -fsSL https://bun.sh/install | bash\";\n\t\tcase \"pnpm\":\n\t\t\treturn win\n\t\t\t\t? 'powershell -c \"irm get.pnpm.io/install.ps1 | iex\"'\n\t\t\t\t: \"curl -fsSL https://get.pnpm.io/install.sh | sh -\";\n\t\tcase \"npm\":\n\t\t\treturn \"install Node.js (includes npm): https://nodejs.org\";\n\t\tcase \"yarn\":\n\t\t\treturn \"npm install -g yarn\";\n\t}\n}\n\nconst TANSTACK_CREATE_FLAGS = [\n\t\"--framework\",\n\t\"React\",\n\t\"--deployment\",\n\t\"cloudflare\",\n\t\"--no-git\",\n\t\"--no-install\",\n\t\"--no-intent\",\n\t\"--no-toolchain\",\n\t\"--no-examples\",\n\t\"--non-interactive\",\n];\n\n/** The exact scaffold command an agent (or human) can run themselves. */\nexport function tanstackCreateCommand(\n\tpm: PackageManager,\n\tprojectName: string,\n): string {\n\treturn [\n\t\t...DLX_RUNNERS[pm],\n\t\t\"@tanstack/cli@latest\",\n\t\t\"create\",\n\t\tprojectName,\n\t\t...TANSTACK_CREATE_FLAGS,\n\t].join(\" \");\n}\n\n/** The last lines of a captured child process's output, for error messages. */\nexport function outputTail(result: {\n\tstdout: string | null;\n\tstderr: string | null;\n}): string {\n\tconst combined = [result.stdout, result.stderr]\n\t\t.filter(Boolean)\n\t\t.join(\"\\n\")\n\t\t.trim();\n\tif (!combined) return \"\";\n\treturn `\\n\\n${combined.split(\"\\n\").slice(-15).join(\"\\n\")}`;\n}\n\n/**\n * Output is captured, not streamed: the template's own banner and \"next\n * steps\" would conflict with the deploy flow's single summary at the end.\n * It resurfaces in the error message when the create fails.\n */\nexport function runTanstackCreate(options: {\n\ttargetDir: string;\n\tprojectName: string;\n\tpm: PackageManager;\n}): void {\n\tconst [runner, ...runnerArgs] = DLX_RUNNERS[options.pm];\n\tconst result = spawnSync(\n\t\trunner!,\n\t\t[\n\t\t\t...runnerArgs,\n\t\t\t\"@tanstack/cli@latest\",\n\t\t\t\"create\",\n\t\t\toptions.projectName,\n\t\t\t\"--target-dir\",\n\t\t\toptions.targetDir,\n\t\t\t...TANSTACK_CREATE_FLAGS,\n\t\t],\n\t\t{\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tencoding: \"utf-8\",\n\t\t\tshell: SPAWN_VIA_SHELL,\n\t\t},\n\t);\n\tif (result.error) throw result.error;\n\tif (result.status !== 0) {\n\t\tthrow new Error(\n\t\t\t`\\`${options.pm === \"npm\" ? \"npx\" : options.pm} @tanstack/cli create\\` failed (exit ${result.status}). Check your network connection and try again.${outputTail(result)}`,\n\t\t);\n\t}\n}\n\nconst VITE_CONFIG_NAMES = [\n\t\"vite.config.ts\",\n\t\"vite.config.mts\",\n\t\"vite.config.js\",\n\t\"vite.config.mjs\",\n];\n\nexport function findViteConfig(dir: string): string | undefined {\n\treturn VITE_CONFIG_NAMES.map((name) => join(dir, name)).find((path) =>\n\t\texistsSync(path),\n\t);\n}\n\nconst WRANGLER_CONFIG_NAMES = [\"wrangler.jsonc\", \"wrangler.json\"];\n\nfunction cliDependencyVersion(): string {\n\treturn buildVersion ? `^${buildVersion}` : \"latest\";\n}\n\n/**\n * Wires a Vite project for Whop hosting: the whop() pack plugin, deploy\n * script, @whop/cli devDependency, and the worker name. Works on any Vite\n * project, not just fresh scaffolds — every edit is idempotent, so re-running\n * after fixing something is safe.\n *\n * Anything that can't be applied automatically is returned as a manual step:\n * a self-contained instruction precise enough for an agent (or human) to\n * finish the whopification by hand.\n */\nexport function whopifyProject(options: { targetDir: string; route: string }): {\n\tmanualSteps: string[];\n} {\n\tconst manualSteps: string[] = [];\n\tpatchPackageJson(options.targetDir, manualSteps);\n\tpatchViteConfig(options.targetDir, manualSteps);\n\tpatchWranglerConfig(options.targetDir, options.route, manualSteps);\n\treturn { manualSteps };\n}\n\nfunction patchPackageJson(dir: string, manualSteps: string[]): void {\n\tconst file = join(dir, \"package.json\");\n\tlet pkg: {\n\t\tscripts?: Record<string, string>;\n\t\tdevDependencies?: Record<string, string>;\n\t};\n\ttry {\n\t\tpkg = JSON.parse(readFileSync(file, \"utf-8\")) as typeof pkg;\n\t} catch {\n\t\tmanualSteps.push(\n\t\t\t`package.json could not be parsed. Add a \"deploy\": \"whop apps deploy\" script, a \"typecheck\" script, and a devDependency \"@whop/cli\": \"${cliDependencyVersion()}\".`,\n\t\t);\n\t\treturn;\n\t}\n\n\tpkg.scripts = {\n\t\t...pkg.scripts,\n\t\tdeploy: \"whop apps deploy\",\n\t\ttypecheck: pkg.scripts?.typecheck ?? \"tsc --noEmit\",\n\t};\n\tpkg.devDependencies = {\n\t\t...pkg.devDependencies,\n\t\t// The project imports the whop() vite plugin from @whop/cli/vite.\n\t\t\"@whop/cli\": pkg.devDependencies?.[\"@whop/cli\"] ?? cliDependencyVersion(),\n\t};\n\n\twriteFileSync(file, `${JSON.stringify(pkg, null, 2)}\\n`);\n}\n\nfunction patchViteConfig(dir: string, manualSteps: string[]): void {\n\tconst file = findViteConfig(dir);\n\tif (!file) {\n\t\tmanualSteps.push(\n\t\t\t\"No vite config found (looked for vite.config.ts/.mts/.js/.mjs). Whop hosting serves Vite builds — create a vite config that builds with @cloudflare/vite-plugin (emitting dist/client and, for SSR, dist/server) and includes the whop() plugin from @whop/cli/vite in its plugins array.\",\n\t\t);\n\t\treturn;\n\t}\n\n\tlet content = readFileSync(file, \"utf-8\");\n\tconst hasWhopPlugin = content.includes(\"@whop/cli/vite\");\n\n\tif (!hasWhopPlugin) {\n\t\tconst pluginsOpen = /plugins:\\s*\\[/;\n\t\tif (!pluginsOpen.test(content)) {\n\t\t\tmanualSteps.push(\n\t\t\t\t`Could not find a \\`plugins: [...]\\` array in ${basename(file)}. Add \\`import { whop } from '@whop/cli/vite'\\` and include \\`whop()\\` in the config's plugins so builds pack dist/whop-build.zip.`,\n\t\t\t);\n\t\t} else {\n\t\t\tcontent = `import { whop } from '@whop/cli/vite'\\n${content}`;\n\t\t\tcontent = content.replace(\n\t\t\t\tpluginsOpen,\n\t\t\t\t(match) => `${match}\\n whop(),`,\n\t\t\t);\n\t\t\twriteFileSync(file, content);\n\t\t}\n\t}\n\n\tif (!content.includes(\"@cloudflare/vite-plugin\")) {\n\t\tmanualSteps.push(\n\t\t\t`${basename(file)} does not use @cloudflare/vite-plugin. Whop hosting runs builds on Cloudflare Workers: install @cloudflare/vite-plugin and wrangler, add \\`cloudflare({ viteEnvironment: { name: 'ssr' } })\\` to the plugins array (before your framework plugin), and make sure \\`vite build\\` emits dist/client (static assets) and dist/server (worker modules with an index.js entry).`,\n\t\t);\n\t}\n}\n\nfunction patchWranglerConfig(\n\tdir: string,\n\troute: string,\n\tmanualSteps: string[],\n): void {\n\tconst file = WRANGLER_CONFIG_NAMES.map((name) => join(dir, name)).find(\n\t\t(path) => existsSync(path),\n\t);\n\tif (!file) {\n\t\tmanualSteps.push(\n\t\t\t`No wrangler config found. Create wrangler.jsonc with: { \"name\": \"${route}\", \"compatibility_date\": \"<today>\", \"compatibility_flags\": [\"nodejs_compat\"], \"main\": \"<your framework's server entry>\" } (for TanStack Start the main is \"@tanstack/react-start/server-entry\").`,\n\t\t);\n\t\treturn;\n\t}\n\n\tconst content = readFileSync(file, \"utf-8\");\n\tconst updated = replaceTopLevelName(content, route);\n\tif (updated) {\n\t\twriteFileSync(file, updated);\n\t} else {\n\t\tmanualSteps.push(\n\t\t\t`Set the top-level \"name\" in ${basename(file)} to \"${route}\" so the worker is named after the app's route.`,\n\t\t);\n\t}\n}\n\n// Rewrites the top-level \"name\" key's value in a wrangler.json(c) document.\n// A plain first-match regex could hit a nested \"name\" (e.g. a kv_namespaces\n// entry) or a string value, so this walks the document skipping strings and\n// JSONC comments while tracking nesting depth. Returns null when no top-level\n// name key exists.\nfunction replaceTopLevelName(content: string, route: string): string | null {\n\tlet depth = 0;\n\tlet i = 0;\n\twhile (i < content.length) {\n\t\tconst ch = content[i];\n\t\tif (ch === '\"') {\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < content.length && content[j] !== '\"') {\n\t\t\t\tj += content[j] === \"\\\\\" ? 2 : 1;\n\t\t\t}\n\t\t\tif (depth === 1 && content.slice(i + 1, j) === \"name\") {\n\t\t\t\tconst after = content.slice(j + 1);\n\t\t\t\tconst value = after.match(/^(\\s*:\\s*)\"(?:[^\"\\\\]|\\\\.)*\"/);\n\t\t\t\tif (value) {\n\t\t\t\t\tconst start = j + 1 + value[1]!.length;\n\t\t\t\t\tconst end = j + 1 + value[0]!.length;\n\t\t\t\t\treturn `${content.slice(0, start)}\"${route}\"${content.slice(end)}`;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti = j + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"/\" && content[i + 1] === \"/\") {\n\t\t\tconst newline = content.indexOf(\"\\n\", i);\n\t\t\ti = newline === -1 ? content.length : newline + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"/\" && content[i + 1] === \"*\") {\n\t\t\tconst close = content.indexOf(\"*/\", i + 2);\n\t\t\ti = close === -1 ? content.length : close + 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (ch === \"{\" || ch === \"[\") depth++;\n\t\tif (ch === \"}\" || ch === \"]\") depth--;\n\t\ti++;\n\t}\n\treturn null;\n}\n","import { z } from \"incur\";\nimport chalk from \"chalk\";\nimport { text, select, isCancel } from \"@clack/prompts\";\nimport { makeWhopRequest } from \"./client.js\";\nimport { resolveActiveAccountId } from \"../api/index.js\";\nimport { BILLING_PERIOD_DAYS } from \"./billing.js\";\nimport {\n\tgetActiveProfile,\n\tsetActiveProfileAccount,\n} from \"../auth/profiles.js\";\nimport { c } from \"../lib/colors.js\";\n\ninterface ListItem {\n\tid: string;\n\ttitle?: string | null;\n\tpurchase_url?: string | null;\n}\ninterface ListResponse {\n\tdata: ListItem[];\n}\n\nconst StepSchema = z.object({\n\tid: z.string(),\n\tlabel: z.string(),\n\tcomplete: z.boolean(),\n\tcount: z.number().optional(),\n\tfirstId: z.string().optional(),\n\tfirstTitle: z.string().optional(),\n});\n\nconst NextStepSchema = z.object({\n\tcommand: z.string(),\n\toptions: z.record(z.string(), z.string()).optional(),\n\tdescription: z.string(),\n\thint: z.string().optional(),\n});\n\nexport const quickstartOptions = z.object({\n\ttitle: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Product name — providing this (or --price/--billing_period) makes quickstart create your product\",\n\t\t),\n\tprice: z.coerce\n\t\t.number()\n\t\t.optional()\n\t\t.describe(\"Price in the plan's currency (e.g. 9.99 for $9.99, 0 = free)\"),\n\tbilling_period: z\n\t\t.enum([\n\t\t\t\"monthly\",\n\t\t\t\"annually\",\n\t\t\t\"quarterly\",\n\t\t\t\"weekly\",\n\t\t\t\"daily\",\n\t\t\t\"every_two_years\",\n\t\t\t\"one_time\",\n\t\t])\n\t\t.optional()\n\t\t.describe(\"Billing interval — use 'one_time' for a single payment\"),\n\tbusiness_name: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Name for a new business account — quickstart creates it and sets up your product under it (user logins only; ignored with API-key auth, which already belongs to a business)\",\n\t\t),\n\taccount_id: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Business account to act on behalf of (biz_xxx); defaults to your active account\",\n\t\t),\n});\n\nexport const quickstartOutput = z.object({\n\taccount: z.string().nullable().describe(\"Authenticated account name\"),\n\tready: z\n\t\t.boolean()\n\t\t.describe(\"Whether you can take a sale now (a product with a plan exists)\"),\n\tcheckoutUrl: z\n\t\t.string()\n\t\t.nullable()\n\t\t.describe(\n\t\t\t\"The live checkout link to share — the journey's payoff, present once a plan exists\",\n\t\t),\n\tcreated: z\n\t\t.object({\n\t\t\taccountId: z.string().optional(),\n\t\t\tproductId: z.string().optional(),\n\t\t\tplanId: z.string().optional(),\n\t\t})\n\t\t.nullable()\n\t\t.describe(\n\t\t\t\"What this run created, if anything — null for a read-only status check\",\n\t\t),\n\tsteps: z.array(StepSchema).describe(\"The path to your first sale\"),\n\tnextStep: NextStepSchema.nullable().describe(\n\t\t\"The single command to run next, pre-filled — null when nothing is required\",\n\t),\n});\n\ntype Step = z.infer<typeof StepSchema>;\ntype NextStep = z.infer<typeof NextStepSchema>;\n\ntype CtaCommand = {\n\tcommand: string;\n\tdescription?: string;\n\toptions?: Record<string, string>;\n};\n\ntype RunCtx = {\n\tagent: boolean;\n\tformatExplicit: boolean;\n\toptions: z.infer<typeof quickstartOptions>;\n\tsetupAgents?: () => Promise<void>;\n\tok: (data: z.infer<typeof quickstartOutput>) => never;\n\terror: (opts: {\n\t\tcode: string;\n\t\tmessage: string;\n\t\tretryable?: boolean;\n\t\texitCode?: number;\n\t\tcta?: { description?: string; commands: CtaCommand[] };\n\t}) => never;\n};\n\ntype ErrorEnvelope = Parameters<RunCtx[\"error\"]>[0];\n\n// incur's `c.error` is a sentinel that only takes effect when returned from the\n// command `run`. Nested helpers can't force the caller to return, so they throw\n// this instead; runCreate's caller catches it and returns `c.error(envelope)`,\n// preserving code/retryable/cta (which a plain thrown Error would lose).\nclass QuickstartError extends Error {\n\tconstructor(readonly envelope: ErrorEnvelope) {\n\t\tsuper(envelope.message);\n\t}\n}\n\nexport async function runQuickstart(c: RunCtx): Promise<never> {\n\tconst profile = getActiveProfile();\n\t// Mirror the auth middleware: a saved profile OR a WHOP_API_KEY env var (the\n\t// agent / CI path) is enough — don't reject env-key auth the gate let through.\n\tif (!profile && !process.env.WHOP_API_KEY) {\n\t\treturn c.error({\n\t\t\tcode: \"NOT_AUTHENTICATED\",\n\t\t\tmessage: \"Not logged in.\",\n\t\t\tcta: {\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\n\tif (!c.agent && !c.formatExplicit && c.setupAgents) {\n\t\ttry {\n\t\t\tawait c.setupAgents();\n\t\t} catch (err) {\n\t\t\tconst message =\n\t\t\t\terr instanceof Error ? err.message : \"Couldn't set up Whop for agents.\";\n\t\t\tconsole.log(`\\n${chalk.yellow(\"!\")} Agent setup skipped: ${message}`);\n\t\t\tconsole.log(\n\t\t\t\tchalk.dim(\n\t\t\t\t\t\" You can retry later with `whop skills add` and `whop mcp add`.\",\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t}\n\n\tconst accountId =\n\t\tc.options.account_id ?? (await resolveActiveAccountId()) ?? \"\";\n\tconst accountName =\n\t\tprofile?.accountTitle ??\n\t\tprofile?.accountRoute ??\n\t\tprofile?.name ??\n\t\t\"your account\";\n\n\tconst interactive = !c.agent && !c.formatExplicit;\n\t// Business accounts belong to a user: an API key IS a business, so the\n\t// create-business flow only applies to user (OAuth) logins. With key auth,\n\t// quickstart just runs under the key's business — never errors, never\n\t// tries to create a sibling.\n\tconst canCreateBusiness = profile?.method === \"oauth\";\n\tlet newBusinessName = canCreateBusiness ? c.options.business_name : undefined;\n\tif (!canCreateBusiness && c.options.business_name !== undefined && interactive) {\n\t\tconsole.log(\n\t\t\t`\\n${chalk.dim(\"Ignoring --business_name — this API key already belongs to a business.\")}`,\n\t\t);\n\t}\n\n\tif (!accountId && newBusinessName === undefined) {\n\t\tif (!canCreateBusiness) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"NO_ACCOUNT\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"Couldn't resolve the business account for this API key. Check the key, or log in again.\",\n\t\t\t\tretryable: true,\n\t\t\t\tcta: {\n\t\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tif (!interactive) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"NO_ACCOUNT\",\n\t\t\t\tmessage:\n\t\t\t\t\t\"No business account is linked to this login. Pass --business_name to create one and continue.\",\n\t\t\t\tretryable: true,\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: \"Create your business account and product in one run:\",\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommand: \"quickstart\",\n\t\t\t\t\t\t\toptions: { business_name: \"My Business\" },\n\t\t\t\t\t\t\tdescription: \"Create a business account, then your product\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t\tconsole.log(\n\t\t\t`\\n${chalk.bold(\"You don't have a business account yet — let's create one.\")}`,\n\t\t);\n\t\tconst name = await text({\n\t\t\tmessage: \"What's your business called?\",\n\t\t\tplaceholder: \"My Business\",\n\t\t});\n\t\tif (isCancel(name)) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Setup cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tnewBusinessName = name;\n\t}\n\n\tif (newBusinessName !== undefined) {\n\t\ttry {\n\t\t\treturn await runCreate(c, {\n\t\t\t\taccountId: \"\",\n\t\t\t\taccountName,\n\t\t\t\tproducts: [],\n\t\t\t\tnewBusinessName,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (err instanceof QuickstartError) return c.error(err.envelope);\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tconst [productsRes, plansRes, checkoutRes] = await Promise.allSettled([\n\t\tmakeWhopRequest<ListResponse>(\n\t\t\t\"GET\",\n\t\t\t`/products?company_id=${accountId}&first=100`,\n\t\t),\n\t\tmakeWhopRequest<ListResponse>(\n\t\t\t\"GET\",\n\t\t\t`/plans?account_id=${accountId}&first=100`,\n\t\t),\n\t\tmakeWhopRequest<ListResponse>(\n\t\t\t\"GET\",\n\t\t\t`/checkout_configurations?company_id=${accountId}&first=100`,\n\t\t),\n\t]);\n\n\t// Don't let a failed products/plans lookup masquerade as \"nothing exists\" —\n\t// that would show empty steps or, worse, prompt a duplicate create. Surface\n\t// the real error instead. A failed checkout lookup is non-critical.\n\tconst critical = [productsRes, plansRes].find((r) => r.status === \"rejected\");\n\tif (critical && critical.status === \"rejected\") {\n\t\tconst reason = critical.reason;\n\t\treturn c.error({\n\t\t\tcode: \"STATUS_CHECK_FAILED\",\n\t\t\tmessage: `Couldn't load your current setup: ${reason instanceof Error ? reason.message : \"API error\"}`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\n\tconst products =\n\t\tproductsRes.status === \"fulfilled\" ? (productsRes.value.data ?? []) : [];\n\tconst plans =\n\t\tplansRes.status === \"fulfilled\" ? (plansRes.value.data ?? []) : [];\n\tconst checkouts =\n\t\tcheckoutRes.status === \"fulfilled\" ? (checkoutRes.value.data ?? []) : [];\n\n\tconst ready = products.length > 0 && plans.length > 0;\n\tconst hasCreationFlags =\n\t\tc.options.title !== undefined ||\n\t\tc.options.price !== undefined ||\n\t\tc.options.billing_period !== undefined;\n\n\t// Mutate-gate: explicit creation flags always create (the user asked for it,\n\t// even on an already-set-up account). Without flags we only auto-guide a\n\t// create when something is missing AND we're interactive — so a ready account\n\t// in agent mode or with `--format`/`--json` stays a pure read-only status check.\n\tconst shouldCreate = hasCreationFlags || (!ready && interactive);\n\n\tif (shouldCreate) {\n\t\ttry {\n\t\t\treturn await runCreate(c, {\n\t\t\t\taccountId,\n\t\t\t\taccountName,\n\t\t\t\tproducts,\n\t\t\t\t// Only offer the new-business choice in the fully-guided flow —\n\t\t\t\t// flags mean the user already said what they want.\n\t\t\t\tofferNewBusiness:\n\t\t\t\t\tinteractive &&\n\t\t\t\t\t!hasCreationFlags &&\n\t\t\t\t\tc.options.account_id === undefined &&\n\t\t\t\t\tcanCreateBusiness,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (err instanceof QuickstartError) return c.error(err.envelope);\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tconst steps = buildSteps(products, plans);\n\tconst checkoutUrl = plans.find((p) => p.purchase_url)?.purchase_url ?? null;\n\tconst nextStep = resolveNextStep(products, plans, checkouts.length > 0);\n\n\tif (!c.agent && !c.formatExplicit) {\n\t\tprintSummary(accountName, steps, ready, checkoutUrl, nextStep);\n\t}\n\n\treturn c.ok({\n\t\taccount: accountName,\n\t\tready,\n\t\tcheckoutUrl,\n\t\tcreated: null,\n\t\tsteps,\n\t\tnextStep,\n\t});\n}\n\n/** Returns the provided value, errors in agent mode, or prompts interactively. */\nasync function resolveOrPrompt<T>(\n\tc: RunCtx,\n\tprovided: T | undefined,\n\tmissing: { code: string; message: string; example: string },\n\tprompt: () => Promise<T | symbol>,\n): Promise<T> {\n\tif (provided !== undefined) return provided;\n\tif (c.agent) {\n\t\tthrow new QuickstartError({\n\t\t\tcode: missing.code,\n\t\t\tmessage: `${missing.message} Example: ${missing.example}`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\tconst value = await prompt();\n\tif (isCancel(value))\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"CANCELLED\",\n\t\t\tmessage: \"Setup cancelled.\",\n\t\t\texitCode: 130,\n\t\t});\n\treturn value as T;\n}\n\nconst FULL_EXAMPLE =\n\t'whop quickstart --title \"My Course\" --price 9.99 --billing_period monthly';\n\nasync function runCreate(\n\tc: RunCtx,\n\tstate: {\n\t\taccountId: string;\n\t\taccountName: string;\n\t\tproducts: ListItem[];\n\t\tnewBusinessName?: string;\n\t\tofferNewBusiness?: boolean;\n\t},\n): Promise<never> {\n\tif (!c.agent) {\n\t\tconsole.log(`\\n${chalk.bold(\"Let's get you set up to sell.\")}\\n`);\n\t}\n\n\tlet { accountId, accountName, products, newBusinessName } = state;\n\n\tif (state.offerNewBusiness) {\n\t\tconst choice = await select<string>({\n\t\t\tmessage: \"Which business account is this for?\",\n\t\t\toptions: [\n\t\t\t\t{ value: \"current\", label: accountName, hint: accountId },\n\t\t\t\t{ value: \"new\", label: \"Create a new business account\" },\n\t\t\t],\n\t\t});\n\t\tif (isCancel(choice)) {\n\t\t\tthrow new QuickstartError({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Setup cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tif (choice === \"new\") {\n\t\t\tconst name = await text({\n\t\t\t\tmessage: \"What's your new business called?\",\n\t\t\t\tplaceholder: \"My Business\",\n\t\t\t});\n\t\t\tif (isCancel(name)) {\n\t\t\t\tthrow new QuickstartError({\n\t\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\t\tmessage: \"Setup cancelled.\",\n\t\t\t\t\texitCode: 130,\n\t\t\t\t});\n\t\t\t}\n\t\t\tnewBusinessName = name;\n\t\t\tproducts = [];\n\t\t}\n\t}\n\n\t// Create a new product when none exist or when an explicit --title is given\n\t// (the user named a product, so honor that intent even if they already have\n\t// others). Otherwise attach the new plan to an existing one.\n\t//\n\t// Gather every input up front, before any POST, so a partial invocation (e.g.\n\t// an agent passes --title but omits --price) fails cleanly without leaving an\n\t// orphaned business account or product behind — and so a cancelled TTY prompt\n\t// creates nothing.\n\tconst needsNewProduct =\n\t\tproducts.length === 0 || c.options.title !== undefined;\n\tconst newTitle = needsNewProduct\n\t\t? await resolveOrPrompt(\n\t\t\t\tc,\n\t\t\t\tc.options.title,\n\t\t\t\t{\n\t\t\t\t\tcode: \"TITLE_REQUIRED\",\n\t\t\t\t\tmessage: \"Pass --title to name your product.\",\n\t\t\t\t\texample: FULL_EXAMPLE,\n\t\t\t\t},\n\t\t\t\t() =>\n\t\t\t\t\ttext({\n\t\t\t\t\t\tmessage: \"What are you selling?\",\n\t\t\t\t\t\tplaceholder: \"My Online Course\",\n\t\t\t\t\t}),\n\t\t\t)\n\t\t: undefined;\n\tconst existing = needsNewProduct\n\t\t? undefined\n\t\t: await resolveExistingProduct(c, products);\n\n\tconst price = await resolveOrPrompt(\n\t\tc,\n\t\tc.options.price,\n\t\t{\n\t\t\tcode: \"PRICE_REQUIRED\",\n\t\t\tmessage: \"Pass --price in dollars (9.99 = $9.99, 0 = free).\",\n\t\t\texample: FULL_EXAMPLE,\n\t\t},\n\t\tasync () => {\n\t\t\tconst p = await text({\n\t\t\t\tmessage: \"Price in dollars (9.99 = $9.99, 0 = free):\",\n\t\t\t\tplaceholder: \"9.99\",\n\t\t\t\tvalidate: (v) => (isNaN(Number(v)) ? \"Enter a number\" : undefined),\n\t\t\t});\n\t\t\treturn isCancel(p) ? p : Number(p);\n\t\t},\n\t);\n\n\tconst billingPeriod = await resolveOrPrompt(\n\t\tc,\n\t\tc.options.billing_period,\n\t\t{\n\t\t\tcode: \"BILLING_PERIOD_REQUIRED\",\n\t\t\tmessage: \"Pass --billing_period (one_time, monthly, annually, …).\",\n\t\t\texample: FULL_EXAMPLE,\n\t\t},\n\t\t() =>\n\t\t\tselect({\n\t\t\t\tmessage: \"How should customers be charged?\",\n\t\t\t\toptions: [\n\t\t\t\t\t{ value: \"one_time\", label: \"One-time payment\" },\n\t\t\t\t\t{ value: \"monthly\", label: \"Monthly subscription\" },\n\t\t\t\t\t{ value: \"annually\", label: \"Annual subscription\" },\n\t\t\t\t\t{ value: \"quarterly\", label: \"Quarterly\" },\n\t\t\t\t],\n\t\t\t}) as Promise<NonNullable<typeof c.options.billing_period> | symbol>,\n\t);\n\n\tlet accountCreated = false;\n\tif (newBusinessName !== undefined) {\n\t\tlet account: { id: string; title?: string | null; route?: string | null };\n\t\ttry {\n\t\t\taccount = await makeWhopRequest<{\n\t\t\t\tid: string;\n\t\t\t\ttitle?: string | null;\n\t\t\t\troute?: string | null;\n\t\t\t}>(\"POST\", \"/accounts\", { title: newBusinessName });\n\t\t} catch (err) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"ACCOUNT_FAILED\",\n\t\t\t\tmessage: `Failed to create the business account: ${err instanceof Error ? err.message : \"unknown error\"}`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\taccountId = account.id;\n\t\taccountName = account.title ?? newBusinessName;\n\t\taccountCreated = true;\n\t\tsetActiveProfileAccount({\n\t\t\tid: account.id,\n\t\t\ttitle: account.title ?? undefined,\n\t\t\troute: account.route ?? undefined,\n\t\t});\n\t\tif (!c.agent) {\n\t\t\tconsole.log(\n\t\t\t\t`\\n${chalk.green(\"✓\")} Created business account \"${accountName}\" ${chalk.dim(`(${accountId})`)} — the CLI now acts on behalf of it.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tlet productId: string;\n\tlet productTitle: string;\n\tlet productCreated = false;\n\tif (existing) {\n\t\tproductId = existing.id;\n\t\tproductTitle = existing.title ?? existing.id;\n\t} else {\n\t\tlet product: { id: string; title: string };\n\t\ttry {\n\t\t\tproduct = await makeWhopRequest<{ id: string; title: string }>(\n\t\t\t\t\"POST\",\n\t\t\t\t\"/products\",\n\t\t\t\t{\n\t\t\t\t\ttitle: newTitle,\n\t\t\t\t\tcompany_id: accountId,\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (err) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"API_ERROR\",\n\t\t\t\tmessage: `Failed to create product: ${err instanceof Error ? err.message : \"unknown error\"}`,\n\t\t\t\tretryable: true,\n\t\t\t});\n\t\t}\n\t\tproductId = product.id;\n\t\tproductTitle = product.title;\n\t\tproductCreated = true;\n\t}\n\n\tconst isRenewal = billingPeriod !== \"one_time\";\n\tconst planBody: Record<string, unknown> = {\n\t\tproduct_id: productId,\n\t\taccount_id: accountId,\n\t\tinitial_price: price,\n\t\tplan_type: isRenewal ? \"renewal\" : \"one_time\",\n\t};\n\tif (isRenewal) {\n\t\tplanBody.billing_period = BILLING_PERIOD_DAYS[billingPeriod];\n\t\tplanBody.renewal_price = price;\n\t}\n\n\tlet plan: { id: string; purchase_url?: string | null };\n\ttry {\n\t\tplan = await makeWhopRequest<{ id: string; purchase_url?: string | null }>(\n\t\t\t\"POST\",\n\t\t\t\"/plans\",\n\t\t\tplanBody,\n\t\t);\n\t} catch (err) {\n\t\t// Product is ready but the plan failed — hand back a recovery command with\n\t\t// the product id already filled in. Only claim the product \"was created\"\n\t\t// when we actually created it this run (vs reused an existing one).\n\t\tconst detail = err instanceof Error ? err.message : \"unknown error\";\n\t\treturn c.error({\n\t\t\tcode: \"PLAN_FAILED\",\n\t\t\tmessage: productCreated\n\t\t\t\t? `Your product \"${productTitle}\" (${productId}) was created, but the plan failed: ${detail}`\n\t\t\t\t: `Couldn't add a plan to \"${productTitle}\" (${productId}): ${detail}`,\n\t\t\tretryable: false,\n\t\t\tcta: {\n\t\t\t\tdescription: \"Finish by adding a plan to your product:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcommand: \"plans create\",\n\t\t\t\t\t\toptions: { product_id: productId },\n\t\t\t\t\t\tdescription: \"Add a pricing plan\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\tconst checkoutUrl = plan.purchase_url ?? null;\n\tconst steps: Step[] = [\n\t\t{ id: \"auth\", label: \"Log in\", complete: true },\n\t\t...(accountCreated\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"account\",\n\t\t\t\t\t\tlabel: \"Create a business account\",\n\t\t\t\t\t\tcomplete: true,\n\t\t\t\t\t\tfirstId: accountId,\n\t\t\t\t\t\tfirstTitle: accountName,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: []),\n\t\t{\n\t\t\tid: \"products\",\n\t\t\tlabel: \"Create a product\",\n\t\t\tcomplete: true,\n\t\t\tcount: 1,\n\t\t\tfirstId: productId,\n\t\t\tfirstTitle: productTitle,\n\t\t},\n\t\t{\n\t\t\tid: \"plans\",\n\t\t\tlabel: \"Add a pricing plan\",\n\t\t\tcomplete: true,\n\t\t\tcount: 1,\n\t\t\tfirstId: plan.id,\n\t\t},\n\t];\n\tconst nextStep = resolveNextStep(\n\t\t[{ id: productId }],\n\t\t[{ id: plan.id }],\n\t\tfalse,\n\t);\n\n\tif (!c.agent && !c.formatExplicit) {\n\t\tprintSummary(accountName, steps, true, checkoutUrl, nextStep, productTitle);\n\t}\n\n\treturn c.ok({\n\t\taccount: accountName,\n\t\tready: true,\n\t\tcheckoutUrl,\n\t\tcreated: {\n\t\t\t...(accountCreated ? { accountId: accountId } : {}),\n\t\t\tproductId,\n\t\t\tplanId: plan.id,\n\t\t},\n\t\tsteps,\n\t\tnextStep,\n\t});\n}\n\nasync function resolveExistingProduct(\n\tc: RunCtx,\n\tproducts: ListItem[],\n): Promise<ListItem> {\n\tif (products.length === 1) return products[0];\n\tif (c.agent) {\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"PRODUCT_REQUIRED\",\n\t\t\tmessage: `You have ${products.length} products — add the plan to a specific one with plans create --product_id.`,\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tdescription: \"Pick a product:\",\n\t\t\t\tcommands: products.map((p) => ({\n\t\t\t\t\tcommand: \"plans create\",\n\t\t\t\t\toptions: { product_id: p.id },\n\t\t\t\t\tdescription: p.title ?? p.id,\n\t\t\t\t})),\n\t\t\t},\n\t\t});\n\t}\n\tconst chosen = await select<string>({\n\t\tmessage: \"Which product is this plan for?\",\n\t\toptions: products.map((p) => ({\n\t\t\tvalue: p.id,\n\t\t\tlabel: p.title ?? p.id,\n\t\t\thint: p.id,\n\t\t})),\n\t});\n\tif (isCancel(chosen))\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"CANCELLED\",\n\t\t\tmessage: \"Setup cancelled.\",\n\t\t\texitCode: 130,\n\t\t});\n\tconst match = products.find((p) => p.id === chosen);\n\tif (!match) {\n\t\tthrow new QuickstartError({\n\t\t\tcode: \"PRODUCT_NOT_FOUND\",\n\t\t\tmessage: `Selected product \"${chosen}\" is no longer available.`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\treturn match;\n}\n\nfunction buildSteps(products: ListItem[], plans: ListItem[]): Step[] {\n\treturn [\n\t\t{ id: \"auth\", label: \"Log in\", complete: true },\n\t\t{\n\t\t\tid: \"products\",\n\t\t\tlabel: \"Create a product\",\n\t\t\tcomplete: products.length > 0,\n\t\t\tcount: products.length,\n\t\t\tfirstId: products[0]?.id,\n\t\t\tfirstTitle: products[0]?.title ?? undefined,\n\t\t},\n\t\t{\n\t\t\tid: \"plans\",\n\t\t\tlabel: \"Add a pricing plan\",\n\t\t\tcomplete: plans.length > 0,\n\t\t\tcount: plans.length,\n\t\t\tfirstId: plans[0]?.id,\n\t\t},\n\t];\n}\n\nfunction resolveNextStep(\n\tproducts: Array<{ id: string }>,\n\tplans: Array<{ id: string }>,\n\thasCheckoutConfig: boolean,\n): NextStep | null {\n\tif (products.length === 0 || plans.length === 0) {\n\t\treturn {\n\t\t\tcommand: \"quickstart\",\n\t\t\tdescription:\n\t\t\t\t\"Create your product and pricing — ends with a checkout link\",\n\t\t\thint: \"Walks you through name, price, and billing. Pass --title/--price/--billing_period to skip the prompts.\",\n\t\t};\n\t}\n\tif (!hasCheckoutConfig) {\n\t\treturn {\n\t\t\tcommand: \"checkout-configurations create\",\n\t\t\toptions: plans[0]?.id ? { plan_id: plans[0].id } : undefined,\n\t\t\tdescription: \"Optional: customize your checkout page\",\n\t\t\thint: \"Your checkout link already works — this only tweaks currency, redirect, and payment mode\",\n\t\t};\n\t}\n\treturn null;\n}\n\nfunction printSummary(\n\taccount: string | null,\n\tsteps: Step[],\n\tready: boolean,\n\tcheckoutUrl: string | null,\n\tnextStep: NextStep | null,\n\tcreatedLabel?: string,\n): void {\n\tconst heading = createdLabel\n\t\t? `You're set up to sell \"${createdLabel}\"`\n\t\t: `Setup for \"${account ?? \"your account\"}\"`;\n\tconsole.log(`\\n${chalk.bold(heading)}\\n`);\n\n\tlet pendingMarked = false;\n\tfor (const step of steps) {\n\t\tif (step.complete) {\n\t\t\tlet label = step.label;\n\t\t\tif (step.count !== undefined) {\n\t\t\t\tlabel += chalk.dim(` (${step.count})`);\n\t\t\t\tif (step.firstTitle) label += chalk.dim(` — \"${step.firstTitle}\"`);\n\t\t\t}\n\t\t\tconsole.log(` ${c.success(\"✓\")} ${label}`);\n\t\t} else if (!pendingMarked) {\n\t\t\tpendingMarked = true;\n\t\t\tconsole.log(` ${chalk.cyan(\"●\")} ${chalk.bold(step.label)}`);\n\t\t} else {\n\t\t\tconsole.log(` ${chalk.dim(\"○\")} ${chalk.dim(step.label)}`);\n\t\t}\n\t}\n\n\tif (ready && checkoutUrl) {\n\t\tconsole.log(\n\t\t\t`\\n${chalk.green.bold(\"🎉 You're ready to sell.\")} Share your checkout link:`,\n\t\t);\n\t\tconsole.log(` ${chalk.cyan.underline(checkoutUrl)}`);\n\t}\n\n\tif (nextStep) {\n\t\tconst opts = nextStep.options\n\t\t\t? \" \" +\n\t\t\t\tObject.entries(nextStep.options)\n\t\t\t\t\t.map(([k, v]) => `--${k} ${v}`)\n\t\t\t\t\t.join(\" \")\n\t\t\t: \"\";\n\t\tconst label = ready ? \"Optional next\" : chalk.bold(\"Next step\");\n\t\tconsole.log(\n\t\t\t`\\n${label} ${chalk.cyan.bold(`whop ${nextStep.command}${opts}`)}`,\n\t\t);\n\t\tif (nextStep.hint) console.log(` ${chalk.dim(`→ ${nextStep.hint}`)}`);\n\t} else if (ready) {\n\t\tconsole.log(`\\n${c.success(\"✓ Your store is fully set up.\")}`);\n\t}\n\tconsole.log(\"\");\n}\n","/**\n * Friendly billing-interval names → days, the unit the API expects for a plan's\n * `billing_period` (e.g. 30 for monthly, 365 for annual). The CLI exposes the\n * names for readability and converts before sending.\n */\nexport const BILLING_PERIOD_DAYS: Record<string, number> = {\n\tdaily: 1,\n\tweekly: 7,\n\tmonthly: 30,\n\tquarterly: 90,\n\tannually: 365,\n\tevery_two_years: 730,\n};\n","import chalk from \"chalk\";\n\nexport const c = {\n heading: chalk.bold,\n command: chalk.bold,\n description: chalk.dim,\n flag: chalk.yellow,\n tableHeader: chalk.bold,\n separator: chalk.dim,\n number: chalk.dim,\n muted: chalk.dim,\n id: chalk.cyan,\n link: chalk.cyan.underline,\n success: chalk.green,\n error: chalk.red.bold,\n};\n","{\n\t\"name\": \"@whop/cli\",\n\t\"version\": \"0.7.0\",\n\t\"description\": \"The Whop CLI — build and manage Whop apps from your terminal. Human and agent friendly.\",\n\t\"keywords\": [\n\t\t\"agent\",\n\t\t\"apps\",\n\t\t\"cli\",\n\t\t\"developer\",\n\t\t\"whop\"\n\t],\n\t\"homepage\": \"https://whop.com/developers/\",\n\t\"bugs\": \"https://github.com/whopio/whop-public-cli/issues\",\n\t\"license\": \"MIT\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/whopio/whop-public-cli.git\"\n\t},\n\t\"bin\": {\n\t\t\"whop\": \"dist/index.js\",\n\t\t\"whop-cli\": \"dist/index.js\"\n\t},\n\t\"files\": [\n\t\t\"dist\",\n\t\t\"skills\"\n\t],\n\t\"type\": \"module\",\n\t\"exports\": {\n\t\t\".\": \"./dist/index.js\",\n\t\t\"./vite\": {\n\t\t\t\"types\": \"./dist/vite.d.ts\",\n\t\t\t\"import\": \"./dist/vite.js\"\n\t\t}\n\t},\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"scripts\": {\n\t\t\"build\": \"tsx scripts/sync-spec.ts && pnpm run clean && tsup\",\n\t\t\"build:binary\": \"tsx scripts/build-binary.ts\",\n\t\t\"clean\": \"rm -rf dist\",\n\t\t\"dev\": \"tsx scripts/sync-spec.ts && tsx src/index.ts\",\n\t\t\"start\": \"node dist/index.js\",\n\t\t\"check-types\": \"tsx scripts/sync-spec.ts && tsc --noEmit\",\n\t\t\"lint\": \"oxlint .\",\n\t\t\"lint:fix\": \"oxlint --fix --fix-suggestions && oxfmt\",\n\t\t\"ci:lint\": \"oxlint -f github .\",\n\t\t\"format\": \"oxfmt\",\n\t\t\"sync-spec\": \"tsx scripts/sync-spec.ts\",\n\t\t\"test\": \"tsx --test scripts/*.test.ts\"\n\t},\n\t\"dependencies\": {\n\t\t\"@clack/prompts\": \"^1.5.1\",\n\t\t\"@napi-rs/keyring\": \"^1.3.0\",\n\t\t\"@whop/sdk\": \"^0.0.40\",\n\t\t\"chalk\": \"5.4.1\",\n\t\t\"yaml\": \"2.8.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@types/node\": \"25.3.5\",\n\t\t\"fflate\": \"0.8.2\",\n\t\t\"incur\": \"github:whopio/incur#fbe3f4dbf48f1bc780cb1bca476f7dade1fe12d3\",\n\t\t\"tsup\": \"8.5.0\",\n\t\t\"tsx\": \"4.19.4\",\n\t\t\"typescript\": \"5.9.3\",\n\t\t\"vite\": \"7.3.6\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=22\"\n\t},\n\t\"packageManager\": \"pnpm@10.23.0\"\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport { configDir } from \"../../auth/config\";\nimport { detectChannel, type Channel } from \"../build-info\";\nimport { hasStructuredOutputFlag } from \"../colorize-output\";\n\n/**\n * Background update check, modeled on update-notifier: never block or slow a\n * command. Each run synchronously reads a small cache file; if a newer version\n * was recorded by a previous check, a notice is printed to stderr when the\n * process exits. When the cache is stale (>1h) a detached `whop upgrade`\n * child refreshes it (and, for standalone installs, applies the update) in the\n * background — the current invocation never waits on the network.\n */\n\nexport const DEFAULT_MANIFEST_URL =\n\t\"https://github.com/whopio/whop-public-cli/releases/latest/download/manifest.json\";\n\nexport function manifestUrl(env: NodeJS.ProcessEnv = process.env): string {\n\treturn env.WHOP_CLI_MANIFEST_URL?.trim() || DEFAULT_MANIFEST_URL;\n}\n\nconst CHECK_INTERVAL_MS = 60 * 60 * 1000;\n\nexport interface UpdateCache {\n\tlastCheckedAt?: string;\n\tlatestVersion?: string;\n\t/** Set by a background self-update so the next run can announce it. */\n\tupdatedTo?: string;\n}\n\nfunction cachePath(env: NodeJS.ProcessEnv): string {\n\treturn path.join(configDir(env), \"update-check.json\");\n}\n\nexport function readUpdateCache(\n\tenv: NodeJS.ProcessEnv = process.env,\n): UpdateCache {\n\ttry {\n\t\tconst parsed = JSON.parse(\n\t\t\tfs.readFileSync(cachePath(env), \"utf8\"),\n\t\t) as unknown;\n\t\tif (parsed != null && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n\t\t\treturn parsed as UpdateCache;\n\t\t}\n\t} catch {\n\t\t// missing or corrupt cache — same as never checked\n\t}\n\treturn {};\n}\n\nexport function writeUpdateCache(\n\tcache: UpdateCache,\n\tenv: NodeJS.ProcessEnv = process.env,\n): void {\n\ttry {\n\t\tfs.mkdirSync(configDir(env), { recursive: true, mode: 0o700 });\n\t\tfs.writeFileSync(cachePath(env), `${JSON.stringify(cache, null, 2)}\\n`, {\n\t\t\tmode: 0o600,\n\t\t});\n\t} catch {\n\t\t// a failed cache write must never break the command being run\n\t}\n}\n\nexport function isNewerVersion(candidate: string, current: string): boolean {\n\tconst parse = (v: string) =>\n\t\tv\n\t\t\t.replace(/^v/, \"\")\n\t\t\t.split(\"-\")[0]\n\t\t\t.split(\".\")\n\t\t\t.map((part) => Number.parseInt(part, 10) || 0);\n\tconst a = parse(candidate);\n\tconst b = parse(current);\n\tfor (let i = 0; i < Math.max(a.length, b.length); i++) {\n\t\tif ((a[i] ?? 0) > (b[i] ?? 0)) return true;\n\t\tif ((a[i] ?? 0) < (b[i] ?? 0)) return false;\n\t}\n\treturn false;\n}\n\nexport function upgradeCommandFor(channel: Channel): string {\n\tswitch (channel) {\n\t\tcase \"npm\":\n\t\t\treturn \"npm install -g @whop/cli\";\n\t\tcase \"brew\":\n\t\t\treturn \"brew upgrade whop\";\n\t\tdefault:\n\t\t\treturn \"whop upgrade\";\n\t}\n}\n\n/** True when update noise would corrupt output or is unwanted: agents, CI, pipes, opt-out. */\nexport function updateCheckSuppressed(\n\targv: string[],\n\tenv: NodeJS.ProcessEnv = process.env,\n\tstderrIsTty: boolean = process.stderr.isTTY ?? false,\n): boolean {\n\tif (env.WHOP_CLI_NO_UPDATE_CHECK) return true;\n\tif (env.CI) return true;\n\tif (!stderrIsTty) return true;\n\t// Any machine-output flag means the caller is parsing the output (incur's\n\t// human rendering is the no-flag TTY default). Reuses the predicate that\n\t// also disables colorization, so the two stay in sync.\n\tif (hasStructuredOutputFlag(argv)) return true;\n\tconst first = argv[0];\n\tif (\n\t\tfirst === \"upgrade\" ||\n\t\tfirst === \"mcp\" ||\n\t\tfirst === \"completions\" ||\n\t\tfirst?.startsWith(\"--\")\n\t) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction spawnBackgroundCheck(): void {\n\tconst args =\n\t\tdetectChannel() === \"standalone\" || detectChannel() === \"brew\"\n\t\t\t? [\"upgrade\", \"--background\"]\n\t\t\t: [process.argv[1], \"upgrade\", \"--background\"];\n\ttry {\n\t\tspawn(process.execPath, args, {\n\t\t\tdetached: true,\n\t\t\tstdio: \"ignore\",\n\t\t}).unref();\n\t} catch {\n\t\t// background check is best-effort\n\t}\n}\n\nexport function scheduleUpdateNotice(\n\targv: string[],\n\tcurrentVersion: string,\n\tenv: NodeJS.ProcessEnv = process.env,\n): void {\n\tconst channel = detectChannel(env);\n\tif (channel === \"dev\") return;\n\tif (updateCheckSuppressed(argv, env)) return;\n\n\tconst cache = readUpdateCache(env);\n\n\tif (cache.updatedTo && cache.updatedTo === currentVersion) {\n\t\twriteUpdateCache({ ...cache, updatedTo: undefined }, env);\n\t\tprocess.on(\"exit\", () => {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`\\nwhop was updated to v${currentVersion} automatically.\\n`,\n\t\t\t);\n\t\t});\n\t\treturn;\n\t}\n\n\tif (cache.latestVersion && isNewerVersion(cache.latestVersion, currentVersion)) {\n\t\tconst latest = cache.latestVersion;\n\t\tprocess.on(\"exit\", () => {\n\t\t\tprocess.stderr.write(\n\t\t\t\t`\\nA new version of whop is available: v${currentVersion} → v${latest}\\nRun \\`${upgradeCommandFor(channel)}\\` to update.\\n`,\n\t\t\t);\n\t\t});\n\t}\n\n\tconst lastChecked = cache.lastCheckedAt\n\t\t? new Date(cache.lastCheckedAt).getTime()\n\t\t: 0;\n\tif (Date.now() - lastChecked > CHECK_INTERVAL_MS) {\n\t\twriteUpdateCache({ ...cache, lastCheckedAt: new Date().toISOString() }, env);\n\t\tspawnBackgroundCheck();\n\t}\n}\n","import { c } from \"./colors\";\n\n/**\n * Themes incur's built-in help / error / CTA text so the whole CLI looks\n * consistent with our hand-rendered surfaces (root help, quickstart, tables).\n *\n * incur exposes a `renderer` hook only for command *data*, not for help or\n * errors, so we post-process the text it writes to stdout instead. This runs\n * only in human TTY mode (see `shouldColorize`) — structured output\n * (`--json`, `--format`, piped/agent) is passed through untouched, so machine\n * consumers never see ANSI codes.\n */\n\nconst SECTION_HEADERS = new Set([\n\t\"Usage\",\n\t\"Arguments\",\n\t\"Options\",\n\t\"Examples\",\n\t\"Environment Variables\",\n\t\"Global Options\",\n\t\"Integrations\",\n\t\"Commands\",\n\t\"Aliases\",\n]);\n\nconst FORMAT_FLAGS = [\"--json\", \"--format\", \"--full-output\", \"--schema\", \"--llms\", \"--llms-full\", \"--mcp\", \"--token-count\", \"--token-limit\", \"--token-offset\"];\n\n/** True when argv carries any machine-output flag (`--json`, `--format <fmt>`, `--format=<fmt>`, `--schema`, …). */\nexport function hasStructuredOutputFlag(argv: string[]): boolean {\n\treturn argv.some((a) => FORMAT_FLAGS.includes(a) || a.startsWith(\"--format=\"));\n}\n\n/** Color only when writing for a human: a TTY, with no structured-output flag. */\nexport function shouldColorize(argv: string[]): boolean {\n\tif (!process.stdout.isTTY) return false;\n\treturn !hasStructuredOutputFlag(argv);\n}\n\n/** Highlights a flag token and any `<placeholder>` inside an option/flag row. */\nfunction paintFlag(flag: string): string {\n\treturn flag.replace(/(<[^>]+>)/g, (m) => c.muted(m)).replace(/(--[\\w-]+|-[\\w])/g, (m) => c.flag(m));\n}\n\n/** An indented command line (` whop products create # desc`) — in help examples or a CTA. */\nconst COMMAND_ROW = /^(\\s+)(whop\\s+\\S.*?)(\\s{2,}#\\s.*)?$/;\n\n/** Underlines any URL so links (checkout pages, dashboards) stand out. */\nfunction highlightUrls(text: string): string {\n\treturn text.replace(/https?:\\/\\/[^\\s)]+/g, (m) => c.link(m));\n}\n\nfunction colorizeLine(\n\tline: string,\n\tsection: string | null,\n\tnextLine: string | undefined,\n): { line: string; section: string | null } {\n\t// Error header, e.g. \"Error: msg\" or \"Error (HTTP_403): msg\".\n\tconst errMatch = line.match(/^(Error(?: \\([^)]+\\))?:)(.*)$/);\n\tif (errMatch) return { line: c.error(errMatch[1]) + highlightUrls(errMatch[2]), section };\n\tif (line.startsWith(\"Run `\")) return { line: c.heading(line), section };\n\n\t// Section header, e.g. \"Options:\" or \"Usage: whop products create\".\n\tconst header = line.match(/^([A-Z][A-Za-z ]+):(.*)$/);\n\tif (header && SECTION_HEADERS.has(header[1])) {\n\t\tconst rest = header[2].replace(/(whop[\\w\\s-]*)/g, (m) => c.command(m));\n\t\treturn { line: c.heading(`${header[1]}:`) + rest, section: header[1] };\n\t}\n\n\t// A `whop …` command line anywhere (help examples and CTAs alike).\n\tconst cmd = line.match(COMMAND_ROW);\n\tif (cmd) {\n\t\treturn { line: `${cmd[1]}${c.command(cmd[2])}${cmd[3] ? c.description(cmd[3]) : \"\"}`, section };\n\t}\n\n\t// A header-like line (\"Suggested command:\", a CTA description) immediately\n\t// followed by a command — bold it for emphasis.\n\tif (line.trim().endsWith(\":\") && nextLine !== undefined && COMMAND_ROW.test(nextLine)) {\n\t\treturn { line: c.heading(line), section };\n\t}\n\n\tif (line.trim() === \"\") return { line, section: null };\n\n\t// Rows inside a known section.\n\tif (section === \"Options\" || section === \"Global Options\" || section === \"Environment Variables\") {\n\t\tconst m = line.match(/^(\\s+)(\\S.*?)(\\s{2,})(.*)$/);\n\t\tif (m) return { line: `${m[1]}${paintFlag(m[2])}${m[3]}${c.description(m[4])}`, section };\n\t}\n\tif (section === \"Commands\" || section === \"Integrations\" || section === \"Aliases\") {\n\t\tconst m = line.match(/^(\\s+)(\\S+)(\\s{2,})(.*)$/);\n\t\tif (m) return { line: `${m[1]}${c.command(m[2])}${m[3]}${c.description(m[4])}`, section };\n\t}\n\tif (section === \"Arguments\") {\n\t\tconst m = line.match(/^(\\s+)(\\S+)(\\s{2,})(.*)$/);\n\t\tif (m) return { line: `${m[1]}${c.id(m[2])}${m[3]}${c.description(m[4])}`, section };\n\t}\n\n\t// Plain text (messages, CTA descriptions): make any link stand out.\n\treturn { line: highlightUrls(line), section };\n}\n\n/** Themes a chunk of incur help/error/CTA text. Safe to call per write. */\nexport function colorizeOutput(text: string): string {\n\tlet section: string | null = null;\n\tconst lines = text.split(\"\\n\");\n\treturn lines\n\t\t.map((line, i) => {\n\t\t\tconst result = colorizeLine(line, section, lines[i + 1]);\n\t\t\tsection = result.section;\n\t\t\treturn result.line;\n\t\t})\n\t\t.join(\"\\n\");\n}\n","import crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { buildTarget } from \"../build-info\";\nimport { manifestUrl } from \"./check\";\n\n/**\n * Self-update for standalone binaries: download the raw binary asset for this\n * build's target from the release manifest, verify its sha256, and atomically\n * rename it over the running executable (safe on macOS/Linux — the running\n * process keeps its open inode). The temp file is created next to the target\n * so the rename never crosses filesystems.\n */\n\nexport interface ManifestAsset {\n\turl: string;\n\tsha256: string;\n}\n\nexport interface UpdateManifest {\n\tversion: string;\n\tassets: Record<string, ManifestAsset>;\n}\n\nexport class SelfUpdateError extends Error {\n\tconstructor(\n\t\tpublic code: string,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t}\n}\n\nexport async function fetchManifest(\n\tenv: NodeJS.ProcessEnv = process.env,\n): Promise<UpdateManifest> {\n\tconst url = manifestUrl(env);\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tsignal: AbortSignal.timeout(10_000),\n\t\t\tredirect: \"follow\",\n\t\t});\n\t} catch {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_UNREACHABLE\",\n\t\t\t`Could not reach the update manifest at ${url}.`,\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_UNAVAILABLE\",\n\t\t\t`Update manifest request failed with HTTP ${response.status}.`,\n\t\t);\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = await response.json();\n\t} catch {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_INVALID\",\n\t\t\t\"Update manifest is not valid JSON.\",\n\t\t);\n\t}\n\tconst manifest = parsed as UpdateManifest;\n\tif (\n\t\ttypeof manifest?.version !== \"string\" ||\n\t\tmanifest.assets == null ||\n\t\ttypeof manifest.assets !== \"object\"\n\t) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"MANIFEST_INVALID\",\n\t\t\t\"Update manifest is missing version or assets.\",\n\t\t);\n\t}\n\treturn manifest;\n}\n\nexport function assetForThisBinary(\n\tmanifest: UpdateManifest,\n): ManifestAsset & { target: string } {\n\tif (!buildTarget) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"NOT_A_STANDALONE_BUILD\",\n\t\t\t\"This build has no compile target — self-update only applies to standalone binaries.\",\n\t\t);\n\t}\n\tconst asset = manifest.assets[buildTarget];\n\tif (!asset?.url || !asset.sha256) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"NO_ASSET_FOR_TARGET\",\n\t\t\t`The latest release has no binary for ${buildTarget}.`,\n\t\t);\n\t}\n\treturn { ...asset, target: buildTarget };\n}\n\nexport async function downloadAndSwap(\n\tasset: ManifestAsset,\n\texecPath: string = process.execPath,\n): Promise<void> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(asset.url, {\n\t\t\tsignal: AbortSignal.timeout(120_000),\n\t\t\tredirect: \"follow\",\n\t\t});\n\t} catch {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"DOWNLOAD_FAILED\",\n\t\t\t`Could not download ${asset.url}.`,\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"DOWNLOAD_FAILED\",\n\t\t\t`Binary download failed with HTTP ${response.status}.`,\n\t\t);\n\t}\n\tconst bytes = Buffer.from(await response.arrayBuffer());\n\n\tconst digest = crypto.createHash(\"sha256\").update(bytes).digest(\"hex\");\n\tif (digest !== asset.sha256.toLowerCase()) {\n\t\tthrow new SelfUpdateError(\n\t\t\t\"CHECKSUM_MISMATCH\",\n\t\t\t`Downloaded binary checksum ${digest} does not match the manifest — aborting.`,\n\t\t);\n\t}\n\n\tconst dir = path.dirname(execPath);\n\tconst tmp = path.join(dir, `.${path.basename(execPath)}.${process.pid}.new`);\n\ttry {\n\t\tfs.writeFileSync(tmp, bytes, { mode: 0o755 });\n\t\tfs.renameSync(tmp, execPath);\n\t} catch (err) {\n\t\ttry {\n\t\t\tfs.rmSync(tmp, { force: true });\n\t\t} catch {\n\t\t\t// best-effort cleanup\n\t\t}\n\t\tconst code = (err as NodeJS.ErrnoException).code;\n\t\tif (code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\") {\n\t\t\tthrow new SelfUpdateError(\n\t\t\t\t\"PERMISSION_DENIED\",\n\t\t\t\t`No write access to ${dir}. Re-run with elevated permissions (e.g. \\`sudo whop upgrade\\`) or reinstall.`,\n\t\t\t);\n\t\t}\n\t\tthrow err;\n\t}\n}\n","import { z } from \"incur\";\nimport pkg from \"../../../package.json\" with { type: \"json\" };\nimport { detectChannel } from \"../build-info\";\nimport {\n\tisNewerVersion,\n\treadUpdateCache,\n\tupgradeCommandFor,\n\twriteUpdateCache,\n} from \"./check\";\nimport {\n\tassetForThisBinary,\n\tdownloadAndSwap,\n\tfetchManifest,\n\tSelfUpdateError,\n} from \"./self-update\";\n\nexport const upgradeOptions = z.object({\n\tcheck: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\"Only check for a newer version, don't install it\"),\n\tbackground: z\n\t\t.boolean()\n\t\t.optional()\n\t\t.describe(\n\t\t\t\"Internal: refresh the update cache silently (spawned by the automatic check)\",\n\t\t),\n});\n\nexport const upgradeOutput = z.object({\n\tstatus: z\n\t\t.enum([\"up-to-date\", \"update-available\", \"updated\"])\n\t\t.describe(\"Result of the upgrade check\"),\n\tcurrent: z.string().describe(\"The version currently running\"),\n\tlatest: z.string().describe(\"The latest released version\"),\n\tchannel: z\n\t\t.enum([\"npm\", \"brew\", \"standalone\", \"dev\"])\n\t\t.describe(\"How this CLI was installed\"),\n\tupgradeCommand: z\n\t\t.string()\n\t\t.optional()\n\t\t.describe(\"Run this shell command to install the available update\"),\n});\nexport type UpgradeOutput = z.infer<typeof upgradeOutput>;\n\ntype CtaCommand = { command: string; description?: string | undefined };\ntype UpgradeCtx = {\n\toptions: { check?: boolean | undefined; background?: boolean | undefined };\n\tok: (\n\t\tdata: UpgradeOutput,\n\t\tmeta?: {\n\t\t\tcta?:\n\t\t\t\t| { description?: string | undefined; commands: CtaCommand[] }\n\t\t\t\t| undefined;\n\t\t},\n\t) => never;\n\terror: (options: {\n\t\tcode: string;\n\t\tmessage: string;\n\t\tretryable?: boolean | undefined;\n\t}) => never;\n};\n\nasync function runBackground(env: NodeJS.ProcessEnv): Promise<void> {\n\tconst manifest = await fetchManifest(env);\n\tconst cache = readUpdateCache(env);\n\twriteUpdateCache(\n\t\t{\n\t\t\t...cache,\n\t\t\tlastCheckedAt: new Date().toISOString(),\n\t\t\tlatestVersion: manifest.version,\n\t\t},\n\t\tenv,\n\t);\n\tif (\n\t\tdetectChannel(env) === \"standalone\" &&\n\t\tenv.WHOP_CLI_AUTO_UPDATE !== \"0\" &&\n\t\tisNewerVersion(manifest.version, pkg.version)\n\t) {\n\t\tawait downloadAndSwap(assetForThisBinary(manifest));\n\t\twriteUpdateCache(\n\t\t\t{\n\t\t\t\tlastCheckedAt: new Date().toISOString(),\n\t\t\t\tlatestVersion: manifest.version,\n\t\t\t\tupdatedTo: manifest.version,\n\t\t\t},\n\t\t\tenv,\n\t\t);\n\t}\n}\n\nexport async function runUpgrade(\n\tc: UpgradeCtx,\n\tenv: NodeJS.ProcessEnv = process.env,\n): Promise<never> {\n\tif (c.options.background) {\n\t\ttry {\n\t\t\tawait runBackground(env);\n\t\t} catch {\n\t\t\t// silent by design — the next foreground run retries after the interval\n\t\t}\n\t\treturn c.ok({\n\t\t\tstatus: \"up-to-date\",\n\t\t\tcurrent: pkg.version,\n\t\t\tlatest: pkg.version,\n\t\t\tchannel: detectChannel(env),\n\t\t});\n\t}\n\n\tconst channel = detectChannel(env);\n\n\tlet manifest;\n\ttry {\n\t\tmanifest = await fetchManifest(env);\n\t} catch (err) {\n\t\tif (err instanceof SelfUpdateError) {\n\t\t\treturn c.error({ code: err.code, message: err.message, retryable: true });\n\t\t}\n\t\tthrow err;\n\t}\n\n\twriteUpdateCache(\n\t\t{\n\t\t\t...readUpdateCache(env),\n\t\t\tlastCheckedAt: new Date().toISOString(),\n\t\t\tlatestVersion: manifest.version,\n\t\t},\n\t\tenv,\n\t);\n\n\tconst base = { current: pkg.version, latest: manifest.version, channel };\n\n\tif (!isNewerVersion(manifest.version, pkg.version)) {\n\t\treturn c.ok({ status: \"up-to-date\", ...base });\n\t}\n\n\tif (channel === \"npm\" || channel === \"brew\") {\n\t\treturn c.ok({\n\t\t\tstatus: \"update-available\",\n\t\t\t...base,\n\t\t\tupgradeCommand: upgradeCommandFor(channel),\n\t\t});\n\t}\n\n\tif (channel === \"dev\") {\n\t\treturn c.error({\n\t\t\tcode: \"DEV_BUILD\",\n\t\t\tmessage: \"Running from source — pull the latest instead of upgrading.\",\n\t\t\tretryable: false,\n\t\t});\n\t}\n\n\tif (c.options.check) {\n\t\treturn c.ok(\n\t\t\t{\n\t\t\t\tstatus: \"update-available\",\n\t\t\t\t...base,\n\t\t\t\tupgradeCommand: upgradeCommandFor(channel),\n\t\t\t},\n\t\t\t{\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: `v${manifest.version} is available (you have v${pkg.version}). To update:`,\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{ command: \"upgrade\", description: \"Install the latest version\" },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t}\n\n\ttry {\n\t\tawait downloadAndSwap(assetForThisBinary(manifest));\n\t} catch (err) {\n\t\tif (err instanceof SelfUpdateError) {\n\t\t\treturn c.error({\n\t\t\t\tcode: err.code,\n\t\t\t\tmessage: err.message,\n\t\t\t\tretryable: err.code !== \"PERMISSION_DENIED\",\n\t\t\t});\n\t\t}\n\t\tthrow err;\n\t}\n\n\treturn c.ok({ status: \"updated\", ...base });\n}\n","import groups from \"./api/groups.json\" with { type: \"json\" };\nimport {\n\tbuildAuthGroup,\n\tloginAdapter,\n\tloginEnv,\n\tloginExamples,\n\tloginHint,\n\tloginOptions,\n\tloginOutput,\n\tlogoutAdapter,\n\tlogoutOptions,\n\tlogoutOutput,\n} from \"./auth/commands\";\nimport { buildAppGroup } from \"./apps/commands\";\nimport {\n\tquickstartOptions,\n\tquickstartOutput,\n\trunQuickstart,\n} from \"./journey/quickstart\";\nimport {\n\trunUpgrade,\n\tupgradeOptions,\n\tupgradeOutput,\n} from \"./lib/update/command\";\n\ntype CliRegistration = {\n\tcommand: (...args: any[]) => unknown;\n\tserve: (\n\t\targv: string[],\n\t\toptions?: {\n\t\t\texit?: (code: number) => void;\n\t\t\tstdout?: (chunk: string) => void;\n\t\t},\n\t) => Promise<void>;\n};\n\ntype HandwrittenGroup = {\n\tname: string;\n\tdescription: string;\n\tsection: \"get-started\" | \"auth\";\n\tregister: (cli: CliRegistration) => unknown | Promise<unknown>;\n};\n\nexport const HANDWRITTEN_GROUPS = [\n\t{\n\t\tname: \"quickstart\",\n\t\tdescription:\n\t\t\t\"Start here — check status and create your first product + checkout link\",\n\t\tsection: \"get-started\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"quickstart\", {\n\t\t\t\tdescription:\n\t\t\t\t\t\"Start selling — check your status and create what's missing\",\n\t\t\t\thint: \"In a terminal it guides you to your first sale — including creating a business account if you don't have one. Agents: a read-only status check unless you pass --business_name/--title/--price/--billing_period.\",\n\t\t\t\toptions: quickstartOptions,\n\t\t\t\toutput: quickstartOutput,\n\t\t\t\texamples: [\n\t\t\t\t\t{ description: \"Check status / get guided to your first sale\" },\n\t\t\t\t\t{\n\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\ttitle: \"My Course\",\n\t\t\t\t\t\t\tprice: 9.99,\n\t\t\t\t\t\t\tbilling_period: \"monthly\" as const,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdescription: \"Create a $9.99/mo product non-interactively\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\tbusiness_name: \"My Business\",\n\t\t\t\t\t\t\ttitle: \"My Course\",\n\t\t\t\t\t\t\tprice: 9.99,\n\t\t\t\t\t\t\tbilling_period: \"one_time\" as const,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"No business account yet? Create it and the product in one run\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\toutputPolicy: \"agent-only\",\n\t\t\t\trun: (c: Parameters<typeof runQuickstart>[0]) =>\n\t\t\t\t\trunQuickstart({ ...c, setupAgents: () => setupAgents(cli) }),\n\t\t\t}),\n\t},\n\t{\n\t\tname: \"apps\",\n\t\tdescription: \"Build and deploy fully-hosted web apps (*.whop.app)\",\n\t\tsection: \"get-started\",\n\t\tregister: async (cli: CliRegistration) =>\n\t\t\tcli.command(await buildAppGroup()),\n\t},\n\t{\n\t\tname: \"upgrade\",\n\t\tdescription: \"Update the CLI to the latest version\",\n\t\tsection: \"get-started\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"upgrade\", {\n\t\t\t\tdescription: \"Update the whop CLI to the latest version\",\n\t\t\t\toptions: upgradeOptions,\n\t\t\t\toutput: upgradeOutput,\n\t\t\t\texamples: [\n\t\t\t\t\t{ description: \"Update to the latest version\" },\n\t\t\t\t\t{\n\t\t\t\t\t\toptions: { check: true },\n\t\t\t\t\t\tdescription: \"Check for a newer version without installing\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\trun: (c: Parameters<typeof runUpgrade>[0]) => runUpgrade(c),\n\t\t\t}),\n\t},\n\t{\n\t\tname: \"auth\",\n\t\tdescription: \"Manage authentication\",\n\t\tsection: \"auth\",\n\t\tregister: (cli: CliRegistration) => cli.command(buildAuthGroup()),\n\t},\n\t{\n\t\tname: \"login\",\n\t\tdescription: \"Sign in to Whop\",\n\t\tsection: \"auth\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"login\", {\n\t\t\t\tdescription: \"Log in to Whop (alias for `auth login`)\",\n\t\t\t\toptions: loginOptions,\n\t\t\t\tenv: loginEnv,\n\t\t\t\toutput: loginOutput,\n\t\t\t\texamples: loginExamples,\n\t\t\t\thint: loginHint,\n\t\t\t\trun: (c: Parameters<typeof loginAdapter>[0]) => loginAdapter(c),\n\t\t\t}),\n\t},\n\t{\n\t\tname: \"logout\",\n\t\tdescription: \"Sign out\",\n\t\tsection: \"auth\",\n\t\tregister: (cli: CliRegistration) =>\n\t\t\tcli.command(\"logout\", {\n\t\t\t\tdescription: \"Log out (alias for `auth logout`)\",\n\t\t\t\toptions: logoutOptions,\n\t\t\t\toutput: logoutOutput,\n\t\t\t\trun: (c: Parameters<typeof logoutAdapter>[0]) => logoutAdapter(c),\n\t\t\t}),\n\t},\n] satisfies HandwrittenGroup[];\n\nexport const HANDWRITTEN_GROUP_NAMES = new Set(\n\tHANDWRITTEN_GROUPS.map(({ name }) => name),\n);\n\nexport const API_GROUPS = groups.filter(\n\t({ name }) => !HANDWRITTEN_GROUP_NAMES.has(name),\n);\n\nexport const COMMAND_GROUPS = [...API_GROUPS, ...HANDWRITTEN_GROUPS] as const;\n\nexport async function registerHandwrittenGroups(cli: CliRegistration) {\n\tfor (const group of HANDWRITTEN_GROUPS) await group.register(cli);\n}\n\nasync function setupAgents(cli: CliRegistration) {\n\tfor (const argv of [\n\t\t[\"skills\", \"add\"],\n\t\t[\"mcp\", \"add\"],\n\t]) {\n\t\tlet exitCode = 0;\n\t\tawait cli.serve(argv, {\n\t\t\texit: (code) => {\n\t\t\t\texitCode = code;\n\t\t\t},\n\t\t\tstdout: (chunk) => process.stdout.write(chunk),\n\t\t});\n\t\tif (exitCode !== 0) throw new Error(`whop ${argv.join(\" \")} failed.`);\n\t}\n}\n","import { spinner } from \"@clack/prompts\";\nimport { Cli, Openapi, z } from \"incur\";\nimport { createWhopFetch, filterSpecByTag, nativeSpec } from \"../api/index.js\";\n\nconst POLL_INTERVAL_MS = 3_000;\n\nconst whopFetch = createWhopFetch();\n\ninterface MediaAsset {\n\tid: string;\n\tmedia_type?: string;\n\tstatus: \"processing\" | \"ready\" | \"failed\";\n\terror_message?: string | null;\n\tamount_charged?: number | null;\n\tfile?: { id: string; url: string } | null;\n}\n\ntype CtaCommand = {\n\tcommand: string;\n\tdescription?: string;\n\toptions?: Record<string, string>;\n};\n\ntype RunCtx = {\n\tagent: boolean;\n\toptions: Record<string, unknown>;\n\terror: (opts: {\n\t\tcode: string;\n\t\tmessage: string;\n\t\tretryable?: boolean;\n\t\tcta?: { description?: string; commands: CtaCommand[] };\n\t}) => never;\n};\n\n/**\n * The media group is spec-driven except `generate`, which is hand-written to\n * add `--wait`: generation is async (the API returns a `processing` asset),\n * so waiting collapses the create-then-poll loop into one blocking call that\n * returns the terminal asset with its `file.id` — the value every downstream\n * step (ad creatives, attachments) actually needs.\n */\nexport async function buildMediaGroup(description: string) {\n\tconst media = Cli.create(\"media\", { description });\n\tconst spec = filterSpecByTag(nativeSpec as Record<string, unknown>, \"Media\");\n\tconst generated = await Openapi.generateCommands(\n\t\tspec as Openapi.OpenAPISpec,\n\t\twhopFetch,\n\t);\n\n\tfor (const [name, entry] of generated) {\n\t\tif (!(\"run\" in entry)) continue;\n\t\tif (name === \"generate\") {\n\t\t\tmedia.command(name, buildGenerateCommand(entry));\n\t\t\tcontinue;\n\t\t}\n\t\tmedia.command(name, entry);\n\t}\n\n\treturn media;\n}\n\nfunction buildGenerateCommand(entry: {\n\tdescription?: string | undefined;\n\toptions?: z.ZodObject<Record<string, z.ZodType>> | undefined;\n\trun: (c: never) => unknown;\n}) {\n\tconst options = (entry.options ?? z.object({})).extend({\n\t\twait: z\n\t\t\t.boolean()\n\t\t\t.optional()\n\t\t\t.describe(\n\t\t\t\t\"Block until generation finishes and return the terminal asset (with file.id when ready)\",\n\t\t\t),\n\t\ttimeout: z.coerce\n\t\t\t.number()\n\t\t\t.default(600)\n\t\t\t.describe(\"Max seconds to wait with --wait before giving up\"),\n\t});\n\n\treturn {\n\t\tdescription: entry.description,\n\t\toptions,\n\t\texamples: [\n\t\t\t{\n\t\t\t\toptions: {\n\t\t\t\t\ttype: \"image\",\n\t\t\t\t\tprompt: \"A running club jogging across a bridge at sunrise\",\n\t\t\t\t\twait: true,\n\t\t\t\t},\n\t\t\t\tdescription: \"Generate an image and wait for the finished file\",\n\t\t\t},\n\t\t\t{\n\t\t\t\toptions: {\n\t\t\t\t\ttype: \"video\",\n\t\t\t\t\tprompt: \"Sneaker product spin on a white background\",\n\t\t\t\t\tduration_seconds: 5,\n\t\t\t\t\twait: true,\n\t\t\t\t},\n\t\t\t\tdescription: \"Generate a 5s video and wait\",\n\t\t\t},\n\t\t],\n\t\trun: async (c: RunCtx) => {\n\t\t\tconst { wait, timeout, ...body } = c.options;\n\t\t\tconst request = Object.fromEntries(\n\t\t\t\tObject.entries(body).filter(([, value]) => value !== undefined),\n\t\t\t);\n\n\t\t\tconst asset = await createGeneration(c, request);\n\t\t\tif (!wait) return asset;\n\n\t\t\treturn awaitGeneration(c, asset, Number(timeout));\n\t\t},\n\t};\n}\n\nasync function createGeneration(\n\tc: RunCtx,\n\tbody: Record<string, unknown>,\n): Promise<MediaAsset> {\n\tconst res = await whopFetch(\n\t\tnew Request(\"https://api.whop.com/media/generate\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(body),\n\t\t}),\n\t);\n\tconst payload = (await res.json().catch(() => null)) as\n\t\t| (MediaAsset & { message?: string; error?: { deposit_url?: string } })\n\t\t| null;\n\n\tif (res.ok && payload) return payload;\n\n\tif (res.status === 402) {\n\t\tconst depositUrl = payload?.error?.deposit_url;\n\t\treturn c.error({\n\t\t\tcode: \"INSUFFICIENT_BALANCE\",\n\t\t\tmessage: `${payload?.message ?? \"Insufficient balance to fund this generation.\"}${depositUrl ? ` Deposit at ${depositUrl}` : \"\"}`,\n\t\t\tretryable: true,\n\t\t\tcta: {\n\t\t\t\tdescription: \"Fund your balance, then retry:\",\n\t\t\t\tcommands: [\n\t\t\t\t\t{ command: \"deposits create\", description: \"Add funds to your balance\" },\n\t\t\t\t],\n\t\t\t},\n\t\t});\n\t}\n\n\treturn c.error({\n\t\tcode: \"API_ERROR\",\n\t\tmessage: payload?.message ?? `Generation request failed (HTTP ${res.status})`,\n\t\tretryable: true,\n\t});\n}\n\nasync function awaitGeneration(\n\tc: RunCtx,\n\tcreated: MediaAsset,\n\ttimeoutSeconds: number,\n): Promise<MediaAsset> {\n\tconst interactive = !c.agent && process.stdout.isTTY;\n\tconst progress = interactive ? spinner() : null;\n\tprogress?.start(`Generating ${created.media_type ?? \"asset\"}…`);\n\n\tconst startedAt = Date.now();\n\tlet asset = created;\n\n\twhile (asset.status === \"processing\") {\n\t\tif (Date.now() - startedAt > timeoutSeconds * 1000) {\n\t\t\tprogress?.stop(`Still processing after ${timeoutSeconds}s.`);\n\t\t\treturn c.error({\n\t\t\t\tcode: \"WAIT_TIMEOUT\",\n\t\t\t\tmessage: `Generation ${asset.id} is still processing after ${timeoutSeconds}s. It keeps running server-side — check on it later.`,\n\t\t\t\tretryable: true,\n\t\t\t\tcta: {\n\t\t\t\t\tdescription: \"Check the asset:\",\n\t\t\t\t\tcommands: [\n\t\t\t\t\t\t{ command: `media get ${asset.id}`, description: \"Poll the asset status\" },\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tawait sleep(POLL_INTERVAL_MS);\n\t\tprogress?.message(\n\t\t\t`Generating ${created.media_type ?? \"asset\"}… ${Math.round((Date.now() - startedAt) / 1000)}s`,\n\t\t);\n\t\tasset = await fetchAsset(c, asset.id, progress);\n\t}\n\n\tif (asset.status === \"failed\") {\n\t\tprogress?.stop(\"Generation failed.\");\n\t\treturn c.error({\n\t\t\tcode: \"GENERATION_FAILED\",\n\t\t\tmessage: `${asset.error_message ?? \"Generation failed.\"} The charge was refunded — adjust the prompt and retry.`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\n\tprogress?.stop(\n\t\t`Generated ${asset.file?.id ?? asset.id} in ${Math.round((Date.now() - startedAt) / 1000)}s.`,\n\t);\n\treturn asset;\n}\n\nasync function fetchAsset(\n\tc: RunCtx,\n\tid: string,\n\tprogress: ReturnType<typeof spinner> | null,\n): Promise<MediaAsset> {\n\tconst res = await whopFetch(\n\t\tnew Request(`https://api.whop.com/media/${id}`, { method: \"GET\" }),\n\t);\n\tconst payload = (await res.json().catch(() => null)) as\n\t\t| (MediaAsset & { message?: string })\n\t\t| null;\n\tif (!res.ok || !payload) {\n\t\tprogress?.stop(\"Polling failed.\");\n\t\treturn c.error({\n\t\t\tcode: \"API_ERROR\",\n\t\t\tmessage:\n\t\t\t\tpayload?.message ?? `Couldn't poll media asset ${id} (HTTP ${res.status})`,\n\t\t\tretryable: true,\n\t\t});\n\t}\n\treturn payload;\n}\n\nfunction sleep(ms: number): Promise<void> {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import { c } from \"./colors\";\n\nconst MAX_CELL_WIDTH = 40\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isObjectArray(value: unknown): value is Record<string, unknown>[] {\n return Array.isArray(value) && value.length > 0 && value.every(isPlainObject)\n}\n\nconst WHOP_TAG = /^[a-z]+_[A-Za-z0-9]+$/\n\n/** Plain truncated string — used for column width calculation (no ANSI codes). */\nfunction cellText(value: unknown): string {\n if (value == null) return ''\n const text = String(value)\n return text.length > MAX_CELL_WIDTH ? text.slice(0, MAX_CELL_WIDTH - 1) + '…' : text\n}\n\n/** Colored display string — used for rendering. */\nfunction formatCell(value: unknown): string {\n const text = cellText(value)\n if (typeof value === 'boolean') return value ? c.success(text) : c.error(text)\n if (typeof value === 'string' && WHOP_TAG.test(value)) return c.id(text)\n return text\n}\n\n/** Total printable width of one row: sum of column widths plus two-space separators between them. */\nfunction totalRowWidth(colWidths: number[]): number {\n const columnTotal = colWidths.reduce((sum, colWidth) => sum + colWidth, 0)\n return columnTotal + (colWidths.length - 1) * 2\n}\n\n/**\n * Renders an array of plain objects as an aligned terminal grid.\n * Drops columns from the right when the row would exceed the terminal width.\n */\nfunction renderRows(rows: Record<string, unknown>[]): string {\n // Only include keys that are scalar across every row — a column where some rows\n // have an object and others have null would render as \"[object Object]\".\n const isScalar = (value: unknown) => typeof value !== 'object' || value === null\n const scalarKeys = Object.keys(rows[0]!).filter((key) =>\n rows.every((row) => isScalar(row[key])),\n )\n\n if (scalarKeys.length === 0) return '(no displayable columns)'\n\n // Column width = max of the header label and the widest cell value across all rows.\n const allWidths = scalarKeys.map((key) =>\n Math.max(key.length, ...rows.map((row) => cellText(row[key]).length)),\n )\n\n // Drop the rightmost columns until the row fits within the terminal width.\n const termWidth = process.stdout.columns ?? 80\n let numVisible = allWidths.length\n while (numVisible > 1 && totalRowWidth(allWidths.slice(0, numVisible)) > termWidth) {\n numVisible--\n }\n\n const visibleKeys = scalarKeys.slice(0, numVisible)\n const visibleWidths = allWidths.slice(0, numVisible)\n\n const header = visibleKeys\n .map((key, i) => c.tableHeader(key.toUpperCase().padEnd(visibleWidths[i]!)))\n .join(' ')\n\n const separator = c.separator(visibleWidths.map((w) => '─'.repeat(w)).join('──'))\n\n const body = rows.map((row) =>\n visibleKeys\n .map((key, i) => {\n const value = row[key]\n const formatted = formatCell(value)\n const width = visibleWidths[i]!\n const pad = width - cellText(value).length\n // Right-align numbers, left-align everything else.\n return typeof value === 'number'\n ? c.number(' '.repeat(pad) + formatted)\n : formatted + ' '.repeat(pad)\n })\n .join(' '),\n )\n\n const hiddenCount = scalarKeys.length - numVisible\n const overflowHint =\n hiddenCount > 0\n ? `\\n${c.muted(`& ${hiddenCount} more columns — use --format json to see all`)}`\n : ''\n\n return [header, separator, ...body].join('\\n') + overflowHint\n}\n\n/**\n * Recursively drops empty values (null, undefined, empty arrays, and objects\n * that become empty once pruned), counting how many fields were dropped so the\n * renderer can tell the user what's hidden.\n */\nfunction pruneEmpty(value: unknown): { kept: unknown; hidden: number } {\n if (value == null) return { kept: undefined, hidden: 1 }\n\n if (Array.isArray(value)) {\n if (value.length === 0) return { kept: undefined, hidden: 1 }\n if (!value.every(isPlainObject)) return { kept: value, hidden: 0 }\n let hidden = 0\n const items: Record<string, unknown>[] = []\n for (const item of value) {\n const pruned = pruneEmpty(item)\n hidden += pruned.hidden\n if (pruned.kept !== undefined) items.push(pruned.kept as Record<string, unknown>)\n }\n if (items.length === 0) return { kept: undefined, hidden }\n return { kept: items, hidden }\n }\n\n if (isPlainObject(value)) {\n let hidden = 0\n const out: Record<string, unknown> = {}\n for (const [key, entry] of Object.entries(value)) {\n const pruned = pruneEmpty(entry)\n hidden += pruned.hidden\n if (pruned.kept !== undefined) out[key] = pruned.kept\n }\n if (Object.keys(out).length === 0) return { kept: undefined, hidden: Math.max(hidden, 1) }\n return { kept: out, hidden }\n }\n\n return { kept: value, hidden: 0 }\n}\n\n/** Colored display string for a scalar in the detail view — no truncation. */\nfunction formatScalar(value: unknown): string {\n const text = String(value)\n if (typeof value === 'boolean') return value ? c.success(text) : c.error(text)\n if (typeof value === 'number') return c.number(text)\n if (typeof value === 'string') {\n if (WHOP_TAG.test(value)) return c.id(text)\n if (/^https?:\\/\\//.test(value)) return c.link(text)\n }\n return text\n}\n\nfunction renderEntries(obj: Record<string, unknown>, depth: number): string[] {\n const pad = ' '.repeat(depth)\n const lines: string[] = []\n for (const [key, value] of Object.entries(obj)) {\n const label = c.muted(`${key}:`)\n if (isPlainObject(value)) {\n lines.push(`${pad}${label}`)\n lines.push(...renderEntries(value, depth + 1))\n } else if (isObjectArray(value)) {\n lines.push(`${pad}${label}`)\n for (const item of value) {\n const itemLines = renderEntries(item, depth + 1)\n itemLines[0] = `${pad}- ${itemLines[0]!.slice(pad.length + 2)}`\n lines.push(...itemLines)\n }\n } else if (Array.isArray(value)) {\n lines.push(`${pad}${label} ${value.map(formatScalar).join(', ')}`)\n } else {\n lines.push(`${pad}${label} ${formatScalar(value)}`)\n }\n }\n return lines\n}\n\n/**\n * Renders a single object (e.g. a create/get response) as key: value lines,\n * hiding empty fields instead of drowning the useful ones in nulls.\n */\nfunction renderObject(data: Record<string, unknown>): string {\n const { kept, hidden } = pruneEmpty(data)\n const lines =\n kept === undefined\n ? [c.muted('(all fields empty)')]\n : renderEntries(kept as Record<string, unknown>, 0)\n const hint =\n hidden > 0\n ? `\\n${c.muted(`${hidden} empty ${hidden === 1 ? 'field' : 'fields'} hidden — use --format json to see all`)}`\n : ''\n return lines.join('\\n') + hint\n}\n\n/**\n * Human-mode renderer passed to incur as `renderer`.\n * Arrays and single-array wrapped responses (e.g. `{ accounts: [...], pagination: {...} }`)\n * become an aligned grid; any other object (create/get responses) becomes a\n * detail view with empty fields hidden. Returns null for non-object data,\n * falling back to incur's TOON formatter.\n */\nexport function render(data: unknown): string | null {\n if (Array.isArray(data)) {\n if (data.length === 0) return c.muted('(no results)')\n return isObjectArray(data) ? renderRows(data) : null\n }\n\n if (isPlainObject(data)) {\n const values = Object.values(data)\n // A wrapped list response has exactly one object-array field and no scalar\n // fields (only companions like `pagination`). A detail object with a nested\n // array (e.g. an account with `balances`) has scalars and gets the detail view.\n const hasScalarField = values.some((v) => v !== null && typeof v !== 'object')\n if (!hasScalarField) {\n const objectArrays = values.filter(isObjectArray)\n if (objectArrays.length === 1) return renderRows(objectArrays[0])\n const arrays = values.filter(Array.isArray)\n if (objectArrays.length === 0 && arrays.length === 1 && arrays[0]!.length === 0) {\n return c.muted('(no results)')\n }\n }\n return renderObject(data)\n }\n\n return null\n}\n","import { Cli } from \"incur\";\nimport { nativeSpec, filterSpecByTag, createWhopFetch } from \"./api\";\nimport { API_GROUPS, registerHandwrittenGroups } from \"./commands\";\nimport { buildMediaGroup } from \"./media/commands\";\nimport pkg from \"../package.json\" with { type: \"json\" };\nimport { render } from \"./lib/renderer\";\nimport { performLogin } from \"./auth/commands\";\nimport { getActiveProfile } from \"./auth/profiles\";\nimport { PromptCancelledError } from \"./auth/prompts\";\n\nconst cli = Cli.create(\"whop\", {\n\tversion: pkg.version,\n\tdescription: \"Build and manage Whop apps from your terminal.\",\n\trenderer: render,\n\tsync: {\n\t\t// Shipped skill files generated by scripts/sync-spec.ts from the\n\t\t// spec's own tag copy (x-whop-summary + description, authored in\n\t\t// backend/openapi/v1/tags.yml). A matching directory name overrides\n\t\t// the auto-generated skill for that command group.\n\t\tinclude: [\"skills/*\"],\n\t\tsuggestions: [\n\t\t\t\"start selling on Whop\",\n\t\t\t\"show my Whop business accounts\",\n\t\t\t\"create a Whop product and pricing plan\",\n\t\t],\n\t},\n\tmcp: {\n\t\tagents: [\"claude-desktop\"],\n\t},\n});\n\nconst spec = (tag: string) =>\n\tfilterSpecByTag(nativeSpec as Record<string, unknown>, tag);\nconst fetch = createWhopFetch();\n\nconst isAuthExempt = (cmd: string) =>\n\t!cmd ||\n\tcmd === \"login\" ||\n\tcmd === \"logout\" ||\n\tcmd === \"completions\" ||\n\tcmd === \"upgrade\" ||\n\tcmd.startsWith(\"auth\") ||\n\tcmd.startsWith(\"mcp\");\n\ncli.use(async (c, next) => {\n\tif (isAuthExempt(c.command)) return next();\n\tif (getActiveProfile()) return next();\n\tif (process.env.WHOP_API_KEY) return next();\n\n\tif (c.agent) {\n\t\treturn c.error({\n\t\t\tcode: \"NOT_AUTHENTICATED\",\n\t\t\tmessage: \"Not logged in. Set WHOP_API_KEY or run `whop login` first.\",\n\t\t\tcta: {\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\n\tlet result;\n\ttry {\n\t\tresult = await performLogin({ agent: false });\n\t} catch (err) {\n\t\tif (err instanceof PromptCancelledError) {\n\t\t\treturn c.error({\n\t\t\t\tcode: \"CANCELLED\",\n\t\t\t\tmessage: \"Login cancelled.\",\n\t\t\t\texitCode: 130,\n\t\t\t});\n\t\t}\n\t\tthrow err;\n\t}\n\n\tif (!result.ok) {\n\t\treturn c.error({\n\t\t\tcode: result.code,\n\t\t\tmessage: result.message,\n\t\t\tcta: {\n\t\t\t\tcommands: [{ command: \"auth login\", description: \"Log in to Whop\" }],\n\t\t\t},\n\t\t});\n\t}\n\n\treturn next();\n});\n\nawait registerHandwrittenGroups(cli);\n\nfor (const { name, tag, description } of API_GROUPS) {\n\t// Media is hybrid: spec commands plus a hand-written `generate --wait`.\n\t// Registered here (not HANDWRITTEN_GROUPS) so it keeps its taxonomy slot in help.\n\tif (name === \"media\") {\n\t\tcli.command(await buildMediaGroup(description));\n\t\tcontinue;\n\t}\n\tcli.command(name, { description, fetch, openapi: spec(tag) });\n}\n\nexport default cli;\n","import { API_GROUPS, HANDWRITTEN_GROUPS } from \"../commands\";\nimport { c } from \"./colors\";\n\nconst SECTION_LABELS = {\n\t\"get-started\": \"Get Started\",\n\tauth: \"Auth\",\n} as const;\n\nconst INTEGRATIONS = [\n\t{ name: \"completions\", desc: \"Generate shell completion script\" },\n\t{ name: \"mcp add\", desc: \"Register as MCP server\" },\n\t{ name: \"skills\", desc: \"Sync skill files to agents (add, list)\" },\n];\n\nconst GLOBAL_FLAGS = [\n\t{\n\t\tflag: \"--filter-output <keys>\",\n\t\tdesc: \"Filter output by key paths (e.g. foo,bar.baz,a[0,3])\",\n\t},\n\t{ flag: \"--format <toon|json|yaml|md|jsonl>\", desc: \"Output format\" },\n\t{ flag: \"--full-output\", desc: \"Show full output envelope\" },\n\t{ flag: \"--help\", desc: \"Show help\" },\n\t{ flag: \"--llms, --llms-full\", desc: \"Print LLM-readable manifest\" },\n\t{ flag: \"--mcp\", desc: \"Start as MCP stdio server\" },\n\t{ flag: \"--schema\", desc: \"Show JSON Schema for command\" },\n\t{\n\t\tflag: \"--token-count\",\n\t\tdesc: \"Print token count of output (instead of output)\",\n\t},\n\t{ flag: \"--token-limit <n>\", desc: \"Limit output to n tokens\" },\n\t{ flag: \"--token-offset <n>\", desc: \"Skip first n tokens of output\" },\n\t{ flag: \"--version\", desc: \"Show version\" },\n];\n\ntype HelpCommand = {\n\tname: string;\n\tdescription: string;\n};\n\ntype HelpSection = {\n\tlabel: string;\n\tcommands: HelpCommand[];\n};\n\nconst handwrittenSection = (\n\tsection: (typeof HANDWRITTEN_GROUPS)[number][\"section\"],\n): HelpSection => ({\n\tlabel: SECTION_LABELS[section],\n\tcommands: HANDWRITTEN_GROUPS.filter((group) => group.section === section).map(\n\t\t({ name, description }) => ({ name, description }),\n\t),\n});\n\nexport function buildGroupedHelp(version: string, description: string): string {\n\tconst lines: string[] = [];\n\n\t// groups.json is ordered by the spec's x-tagGroups taxonomy, so grouping\n\t// by each command's `group` label preserves both section and command order.\n\tconst apiSections: HelpSection[] = [];\n\tfor (const { name, description, group } of API_GROUPS) {\n\t\tlet section = apiSections.find((s) => s.label === group);\n\t\tif (!section) apiSections.push((section = { label: group, commands: [] }));\n\t\tsection.commands.push({ name, description });\n\t}\n\n\tconst commerceSections = apiSections.filter(\n\t\t(section) => section.label.toLowerCase() === \"commerce\",\n\t);\n\tconst otherApiSections = apiSections.filter(\n\t\t(section) => section.label.toLowerCase() !== \"commerce\",\n\t);\n\tconst allSections = [\n\t\thandwrittenSection(\"get-started\"),\n\t\t...commerceSections,\n\t\t...otherApiSections,\n\t\thandwrittenSection(\"auth\"),\n\t].filter((section) => section.commands.length > 0);\n\tconst maxCmdLen = Math.max(\n\t\t...allSections.flatMap((section) =>\n\t\t\tsection.commands.map((command) => command.name.length),\n\t\t),\n\t);\n\n\tlines.push(`whop@${version} — ${description}`);\n\tlines.push(\"\");\n\tlines.push(\"Usage: whop <command>\");\n\n\tfor (const section of allSections) {\n\t\tlines.push(\"\");\n\t\tlines.push(c.heading(section.label.toUpperCase()));\n\t\tfor (const cmd of section.commands) {\n\t\t\tconst pad = \" \".repeat(maxCmdLen - cmd.name.length);\n\t\t\tlines.push(\n\t\t\t\t` ${c.command(cmd.name)}${pad} ${c.description(cmd.description)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst maxIntLen = Math.max(...INTEGRATIONS.map((i) => i.name.length));\n\tlines.push(\"\");\n\tlines.push(\"Integrations:\");\n\tfor (const i of INTEGRATIONS) {\n\t\tlines.push(\n\t\t\t` ${c.command(i.name)}${\" \".repeat(maxIntLen - i.name.length)} ${c.description(i.desc)}`,\n\t\t);\n\t}\n\n\tconst maxFlagLen = Math.max(...GLOBAL_FLAGS.map((f) => f.flag.length));\n\tlines.push(\"\");\n\tlines.push(\"Global Options:\");\n\tfor (const f of GLOBAL_FLAGS) {\n\t\tlines.push(\n\t\t\t` ${c.flag(f.flag)}${\" \".repeat(maxFlagLen - f.flag.length)} ${c.description(f.desc)}`,\n\t\t);\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n","import cli from \"./cli\";\nimport { getActiveProfile } from \"./auth/profiles\";\nimport { buildGroupedHelp } from \"./lib/grouped-help\";\nimport { colorizeOutput, shouldColorize } from \"./lib/colorize-output\";\nimport { scheduleUpdateNotice } from \"./lib/update/check\";\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nconst argv = process.argv.slice(2);\nscheduleUpdateNotice(argv, pkg.version);\n\nasync function serve(argv: string[]) {\n\tif (shouldColorize(argv)) {\n\t\tawait cli.serve(argv, {\n\t\t\tstdout: (s) => process.stdout.write(colorizeOutput(s)),\n\t\t});\n\t} else {\n\t\tawait cli.serve(argv);\n\t}\n}\n\nif (argv.length === 0 && !getActiveProfile() && !process.env.WHOP_API_KEY) {\n\tawait serve([\"quickstart\"]);\n} else if (argv.length === 0 || (argv.length === 1 && argv[0] === \"--help\")) {\n\tprocess.stdout.write(\n\t\tbuildGroupedHelp(\n\t\t\tpkg.version,\n\t\t\tcli.description ?? \"Build and manage Whop apps from your terminal.\",\n\t\t) + \"\\n\",\n\t);\n\tprocess.exit(0);\n} else {\n\tawait serve(argv);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE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UAAQ,KAAK,CAAC;AACf,OAAO;AACN,QAAM,MAAM,IAAI;AACjB;","names":["identity","existed","profile","c","createWhopFetch","fetch","removed","spawnSync","existsSync","readFileSync","join","resolve","path","text","resolve","path","existsSync","readFileSync","writeFileSync","join","join","path","existsSync","readFileSync","writeFileSync","existsSync","join","readFileSync","SPAWN_VIA_SHELL","spawnSync","c","spec","resolve","config","chalk","text","select","isCancel","chalk","c","chalk","text","isCancel","select","argv","text","argv","fs","path","path","fs","c","cli","c","argv","spinner","whopFetch","spec","c","spinner","sleep","resolve","text","fetch","c","description","argv"]}
|