@purpleturret/cli 0.6.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 +1 -0
- package/dist/cli.js +28 -6
- package/dist/cli.js.map +1 -1
- package/package.json +3 -3
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/main.ts","../src/commands/groups.ts","../src/lib/context.ts","../../sdk/src/version.ts","../../sdk/src/config/schema.ts","../../sdk/src/config/define.ts","../../sdk/src/client/wire.ts","../../sdk/src/client/areas/account.ts","../../sdk/src/client/areas/orders.ts","../../sdk/src/client/areas/pixels.ts","../../sdk/src/client/areas/pages.ts","../../sdk/src/client/areas/tracking.ts","../../sdk/src/client/areas/domains.ts","../../sdk/src/client/areas/webhooks.ts","../../sdk/src/client/errors.ts","../../sdk/src/client/areas/uploads.ts","../../sdk/src/client/client.ts","../src/version.ts","../src/lib/credentials.ts","../src/lib/errors.ts","../src/lib/output.ts","../src/lib/run.ts","../src/lib/table.ts","../src/commands/webhooks.ts","../src/commands/orders.ts","../src/lib/render.ts","../src/commands/subscriptions.ts","../src/commands/customers.ts","../src/commands/leads.ts","../src/commands/pixels.ts","../src/commands/pages.ts","../src/commands/tracking.ts","../src/commands/domains.ts","../src/commands/account.ts","../src/commands/support.ts","../src/commands/init.ts","../src/lib/pull-writer.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/mcp.ts","../../mcp/src/index.ts","../../mcp/src/tools/core.ts","../../mcp/src/tools/account.ts","../../mcp/src/tools/products.ts","../../mcp/src/tools/orders.ts","../../mcp/src/tools/pixels.ts","../../mcp/src/tools/pages.ts","../../mcp/src/tools/tracking.ts","../../mcp/src/tools/domains.ts","../../mcp/src/tools/webhooks.ts","../src/commands/products.ts","../src/commands/pull.ts","../src/commands/push.ts","../src/lib/config-loader.ts","../src/commands/status.ts","../src/commands/whoami.ts","../src/cli.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage, type CommandDef } from \"citty\";\n\nimport { groups } from \"./commands/groups\";\nimport { orders } from \"./commands/orders\";\nimport { subscriptions } from \"./commands/subscriptions\";\nimport { customers } from \"./commands/customers\";\nimport { leads } from \"./commands/leads\";\nimport { pixels } from \"./commands/pixels\";\nimport { pages } from \"./commands/pages\";\nimport { tracking } from \"./commands/tracking\";\nimport { domains } from \"./commands/domains\";\nimport { webhooks } from \"./commands/webhooks\";\nimport { account } from \"./commands/account\";\nimport { support } from \"./commands/support\";\nimport { init } from \"./commands/init\";\nimport { login } from \"./commands/login\";\nimport { logout } from \"./commands/logout\";\nimport { mcp } from \"./commands/mcp\";\nimport { products } from \"./commands/products\";\nimport { pull } from \"./commands/pull\";\nimport { push } from \"./commands/push\";\nimport { status } from \"./commands/status\";\nimport { whoami } from \"./commands/whoami\";\nimport { globalArgs, stashGlobalFlags, type GlobalFlags } from \"./lib/context\";\nimport { CliError, EXIT } from \"./lib/errors\";\nimport { Output, createPalette, shouldUseColor } from \"./lib/output\";\nimport { CLI_VERSION } from \"./version\";\n\nexport const main = defineCommand({\n meta: {\n name: \"purpleturret\",\n version: CLI_VERSION,\n description: \"Sync purpleturret.config.ts with your Purpleturret account. Also available as `pt`.\",\n },\n args: { ...globalArgs },\n setup({ args }) {\n stashGlobalFlags(args as GlobalFlags);\n },\n subCommands: {\n init,\n login,\n logout,\n whoami,\n status,\n push,\n pull,\n mcp,\n products,\n groups,\n orders,\n subscriptions,\n customers,\n leads,\n pixels,\n pages,\n tracking,\n domains,\n webhooks,\n account,\n support,\n },\n});\n\ntype AnyCommand = CommandDef<Record<string, never>>;\n\nasync function resolveSubCommand(cmd: AnyCommand, rawArgs: string[]): Promise<[AnyCommand, AnyCommand | undefined]> {\n let current: AnyCommand = cmd;\n let parent: AnyCommand | undefined;\n let args = rawArgs;\n for (;;) {\n const subCommands = (await current.subCommands) as Record<string, AnyCommand> | undefined;\n if (!subCommands) return [current, parent];\n const index = args.findIndex((arg) => !arg.startsWith(\"-\"));\n const name = index >= 0 ? args[index] : undefined;\n const next = name ? subCommands[name] : undefined;\n if (!next) return [current, parent];\n parent = current;\n current = next;\n args = args.slice(index + 1);\n }\n}\n\nfunction isCittyError(error: unknown): error is Error & { code?: string } {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\nconst GLOBAL_STRING_FLAGS = new Set([\"--config\", \"--api-url\", \"--api-key\", \"--profile\"]);\n\n/**\n * citty picks the first token that does not start with \"-\" as the subcommand, so `pt --api-key x push`\n * would treat `x` as the command. Move flags that precede the subcommand behind it instead.\n */\nexport function hoistLeadingFlags(rawArgs: string[]): string[] {\n const leading: string[] = [];\n let index = 0;\n while (index < rawArgs.length) {\n const token = rawArgs[index]!;\n if (!token.startsWith(\"-\")) break;\n leading.push(token);\n index += 1;\n const next = rawArgs[index];\n if (GLOBAL_STRING_FLAGS.has(token) && next !== undefined && !next.startsWith(\"-\")) {\n leading.push(next);\n index += 1;\n }\n }\n if (index === 0 || index >= rawArgs.length) return rawArgs;\n return [...rawArgs.slice(index), ...leading];\n}\n\n/** Entry point shared by the bin shim and tests. Sets `process.exitCode`; never calls `process.exit`. */\nexport async function runCli(argv: string[] = process.argv.slice(2)): Promise<void> {\n const root = main as unknown as AnyCommand;\n const rawArgs = hoistLeadingFlags(argv);\n try {\n if (rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n return;\n }\n if (rawArgs.length === 1 && rawArgs[0] === \"--version\") {\n process.stdout.write(`${CLI_VERSION}\\n`);\n return;\n }\n if (rawArgs.length === 0) {\n await showUsage(root);\n return;\n }\n await runCommand(root, { rawArgs });\n } catch (error) {\n const flags = parseLooseGlobals(rawArgs);\n const out = new Output({ json: flags.json, verbose: flags.verbose, palette: createPalette(shouldUseColor({ flag: flags.color })) });\n if (isCittyError(error)) {\n out.fail(new CliError(error.message, EXIT.USAGE, { code: \"usage\" }));\n if (!flags.json) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n }\n process.exitCode = EXIT.USAGE;\n return;\n }\n const cliError =\n error instanceof CliError ? error : new CliError(error instanceof Error ? error.message : String(error), EXIT.ERROR, { cause: error });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n}\n\nfunction parseLooseGlobals(rawArgs: string[]): { json: boolean; verbose: boolean; color: boolean | undefined } {\n return {\n json: rawArgs.includes(\"--json\"),\n verbose: rawArgs.includes(\"--verbose\"),\n color: rawArgs.includes(\"--no-color\") ? false : undefined,\n };\n}\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\nimport { confirmOrYes } from \"./webhooks\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List integration groups\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().groups.list();\n if (ctx.json) return ctx.out.printJson({ groups: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No integration groups yet. Run `purpleturret groups create <key> <name>`.\"));\n const rows = data.map((g) => [g.key, g.name, new Date(g.createdAt).toISOString()]);\n for (const line of renderTable([\"KEY\", \"NAME\", \"CREATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst create = defineCommand({\n meta: { name: \"create\", description: \"Create an integration group\" },\n args: {\n ...globalArgs,\n key: { type: \"positional\", required: true, description: \"Group key (2-64 letters, numbers, dashes, underscores)\" },\n name: { type: \"positional\", required: true, description: \"Display name (1-80 chars)\" },\n },\n run: defineRun(async (ctx, args) => {\n const group = await ctx.client().groups.create({ key: args.key, name: args.name });\n ctx.json ? ctx.out.printJson(group) : ctx.out.print(`Created group ${group.key} (${group.name})`);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Rename an integration group\" },\n args: { ...globalArgs, key: { type: \"positional\", required: true }, name: { type: \"string\", required: true, description: \"New display name\" } },\n run: defineRun(async (ctx, args) => {\n const group = await ctx.client().groups.update(args.key, { name: args.name });\n ctx.json ? ctx.out.printJson(group) : ctx.out.print(`Renamed group ${group.key} to ${group.name}`);\n }),\n});\n\nconst del = defineCommand({\n meta: { name: \"delete\", description: \"Delete an integration group (cascades to its webhooks; products keep selling without a tier)\" },\n args: {\n ...globalArgs,\n key: { type: \"positional\", required: true },\n yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt (required in CI)\" },\n },\n run: defineRun(async (ctx, args) => {\n await confirmOrYes(\n Boolean(args.yes),\n ctx.json,\n `Delete group ${args.key}? This also deletes its webhook endpoints, deliveries and events, and clears the group and tier on its products.`,\n );\n const group = await ctx.client().groups.delete(args.key);\n ctx.json ? ctx.out.printJson(group) : ctx.out.print(`Deleted group ${group.key}`);\n }),\n});\n\nexport const groups = defineCommand({\n meta: { name: \"groups\", description: \"Integration groups\" },\n args: { ...globalArgs },\n subCommands: { list, create, update, delete: del },\n});\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { DEFAULT_BASE_URL, PurpleturretClient } from \"@purpleturret/sdk\";\nimport dotenv from \"dotenv\";\n\nimport { CLI_VERSION } from \"../version\";\nimport { CredentialsStore, DEFAULT_PROFILE, credentialsPath, type Profile } from \"./credentials\";\nimport { CliError, EXIT, type ErrorContext } from \"./errors\";\nimport { Output, createPalette, shouldUseColor } from \"./output\";\n\n/** Flags accepted by every command. */\nexport interface GlobalFlags {\n config?: string;\n \"api-url\"?: string;\n apiUrl?: string;\n \"api-key\"?: string;\n apiKey?: string;\n profile?: string;\n json?: boolean;\n color?: boolean;\n verbose?: boolean;\n}\n\nexport const globalArgs = {\n config: { type: \"string\", description: \"Path to purpleturret.config.{ts,mts,js,mjs,json} (default: search up to the git root)\" },\n \"api-url\": { type: \"string\", description: \"API origin (default: PURPLETURRET_API_URL, saved profile, or https://api.purpleturret.com)\" },\n \"api-key\": { type: \"string\", description: \"Seller API key (default: PURPLETURRET_API_KEY, .env.local/.env, or saved profile)\" },\n profile: { type: \"string\", description: 'Credentials profile name (default: \"default\")' },\n json: { type: \"boolean\", description: \"Print machine-readable JSON on stdout\" },\n color: { type: \"boolean\", description: \"Colorize output (disable with --no-color or NO_COLOR)\" },\n verbose: { type: \"boolean\", description: \"Log requests and stack traces to stderr\" },\n} as const;\n\nlet stashedGlobals: GlobalFlags = {};\n\n/** Remember flags parsed on the root command so `pt --json push` works as well as `pt push --json`. */\nexport function stashGlobalFlags(flags: GlobalFlags): void {\n stashedGlobals = { ...flags };\n}\n\nexport function mergeGlobalFlags(flags: GlobalFlags): GlobalFlags {\n const merged: GlobalFlags = { ...stashedGlobals };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) (merged as Record<string, unknown>)[key] = value;\n }\n return merged;\n}\n\nexport type Source = \"flag\" | \"env\" | \"profile\" | \"default\" | \"none\";\n\nexport interface CliContext extends ErrorContext {\n cwd: string;\n env: NodeJS.ProcessEnv;\n flags: GlobalFlags;\n json: boolean;\n verbose: boolean;\n out: Output;\n profileName: string;\n profile: Profile | null;\n credentials: CredentialsStore;\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n apiKey: string | null;\n credentialSource: \"flag\" | \"env\" | \"profile\" | \"none\";\n configPath: string | undefined;\n /** Build an authenticated client, or fail with exit 3 when no key is available. */\n client(): PurpleturretClient;\n /** Build a client for an explicit key (used by `login`). */\n clientFor(apiKey: string): PurpleturretClient;\n}\n\nexport interface CreateContextOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n credentialsFile?: string;\n}\n\nexport function loadDotenv(cwd: string, env: NodeJS.ProcessEnv): string[] {\n const loaded: string[] = [];\n for (const name of [\".env.local\", \".env\"]) {\n const path = join(cwd, name);\n if (!existsSync(path)) continue;\n dotenv.config({ path, override: false, quiet: true, processEnv: env as Record<string, string> });\n loaded.push(path);\n }\n return loaded;\n}\n\nexport async function createContext(rawFlags: GlobalFlags, options: CreateContextOptions = {}): Promise<CliContext> {\n const cwd = options.cwd ?? process.cwd();\n const env = options.env ?? process.env;\n const flags = mergeGlobalFlags(rawFlags);\n const json = Boolean(flags.json);\n const verbose = Boolean(flags.verbose);\n const palette = createPalette(\n shouldUseColor({ flag: flags.color, env, stream: (options.stderr as { isTTY?: boolean } | undefined) ?? process.stderr }),\n );\n const out = new Output({ json, verbose, palette, stdout: options.stdout, stderr: options.stderr });\n\n const loadedEnvFiles = loadDotenv(cwd, env);\n if (loadedEnvFiles.length) out.debug(`loaded ${loadedEnvFiles.join(\", \")}`);\n\n const profileName = flags.profile?.trim() || DEFAULT_PROFILE;\n const credentials = new CredentialsStore(options.credentialsFile ?? credentialsPath(env));\n const profile = await credentials.getProfile(profileName);\n\n const flagKey = (flags[\"api-key\"] ?? flags.apiKey)?.trim();\n const envKey = env.PURPLETURRET_API_KEY?.trim();\n let apiKey: string | null = null;\n let credentialSource: CliContext[\"credentialSource\"] = \"none\";\n if (flagKey) [apiKey, credentialSource] = [flagKey, \"flag\"];\n else if (envKey) [apiKey, credentialSource] = [envKey, \"env\"];\n else if (profile?.apiKey) [apiKey, credentialSource] = [profile.apiKey, \"profile\"];\n\n const flagUrl = (flags[\"api-url\"] ?? flags.apiUrl)?.trim();\n const envUrl = env.PURPLETURRET_API_URL?.trim();\n let apiUrl = DEFAULT_BASE_URL;\n let apiUrlSource: CliContext[\"apiUrlSource\"] = \"default\";\n if (flagUrl) [apiUrl, apiUrlSource] = [flagUrl, \"flag\"];\n else if (envUrl) [apiUrl, apiUrlSource] = [envUrl, \"env\"];\n else if (profile?.apiUrl) [apiUrl, apiUrlSource] = [profile.apiUrl, \"profile\"];\n apiUrl = apiUrl.replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(apiUrl)) {\n throw new CliError(`Invalid API URL \"${apiUrl}\"; it must start with http:// or https://`, EXIT.USAGE, { code: \"invalid_api_url\" });\n }\n\n let announcedUrl = false;\n const announceUrl = () => {\n if (announcedUrl || apiUrlSource === \"default\") return;\n announcedUrl = true;\n out.info(palette.yellow(`Using API ${apiUrl} (from ${describeSource(apiUrlSource)})`));\n };\n\n const fetchImpl: typeof fetch = async (input, init) => {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n out.debug(`${init?.method ?? \"GET\"} ${url}`);\n const started = Date.now();\n const response = await fetch(input, init);\n out.debug(`→ ${response.status} ${response.headers.get(\"x-request-id\") ?? \"\"} (${Date.now() - started}ms)`.trimEnd());\n return response;\n };\n\n const clientFor = (key: string) => {\n announceUrl();\n return new PurpleturretClient({ apiKey: key, baseUrl: apiUrl, fetch: fetchImpl, userAgent: `purpleturret-cli/${CLI_VERSION}` });\n };\n\n const context: CliContext = {\n cwd,\n env,\n flags,\n json,\n verbose,\n out,\n profileName,\n profile,\n credentials,\n apiUrl,\n apiUrlSource,\n apiKey,\n credentialSource,\n configPath: flags.config,\n clientFor,\n client() {\n if (!apiKey) {\n throw new CliError(`No API key found for profile \"${profileName}\".`, EXIT.AUTH, {\n code: \"no_credentials\",\n hint: \"Run `purpleturret login`, pass --api-key, or set PURPLETURRET_API_KEY (also read from .env.local / .env in the current directory).\",\n });\n }\n return clientFor(apiKey);\n },\n };\n return context;\n}\n\nexport function describeSource(source: Source): string {\n switch (source) {\n case \"flag\":\n return \"command-line flag\";\n case \"env\":\n return \"environment\";\n case \"profile\":\n return \"saved profile\";\n case \"default\":\n return \"default\";\n default:\n return \"none\";\n }\n}\n","/** Keep in sync with package.json. */\nexport const SDK_VERSION = \"0.6.0\";\n","import { z } from \"zod\";\n\nimport type { ProductInput, PurpleturretConfig } from \"../types\";\n\n/** Product keys and credit meters: 1-64 chars, lowercase letters, digits, `_` or `-`, starting with a letter or digit. */\nexport const KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n/** Public checkout slugs: 3-64 chars, lowercase letters, digits, or `-`. */\nexport const SLUG_PATTERN = /^[a-z0-9-]{3,64}$/;\nconst HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\nconst KEY_MESSAGE = \"must be 1-64 characters of lowercase letters, digits, '_' or '-', starting with a letter or digit\";\n\nexport const keySchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\nexport const meterSchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\n\nexport const moneySchema = z.strictObject({\n amount: z\n .number(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .int(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .min(50, \"must be at least 50 (e.g. $0.50); use usd(dollars) to convert\"),\n currency: z\n .string()\n .trim()\n .toLowerCase()\n .regex(/^[a-z]{3}$/, \"must be a 3-letter ISO currency code\"),\n});\n\nexport const billingSchema = z.discriminatedUnion(\"type\", [\n z.strictObject({ type: z.literal(\"one_time\") }),\n z.strictObject({ type: z.literal(\"recurring\"), interval: z.enum([\"month\", \"year\"]) }),\n]);\n\nexport const tierSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(80),\n rank: z.number().int(\"must be an integer\").min(0),\n});\n\nexport const groupSchema = z.strictObject({\n key: keySchema,\n tier: tierSchema.optional(),\n});\n\nexport const creditGrantSchema = z.strictObject({\n meter: meterSchema,\n amount: z.number().int(\"must be an integer\").positive(\"must be a positive integer\"),\n renewal: z.enum([\"reset\", \"accumulate\"]),\n expiresAfterDays: z.number().int(\"must be an integer\").positive(\"must be a positive integer\").optional(),\n});\n\nexport const deliverySchema = z.discriminatedUnion(\"method\", [\n z.strictObject({ method: z.literal(\"none\") }),\n z.strictObject({\n method: z.literal(\"redirect\"),\n url: z\n .string()\n .url(\"must be an absolute URL\")\n .refine((value) => value.startsWith(\"https://\"), \"must be an https:// URL\"),\n }),\n z.strictObject({ method: z.literal(\"instructions\"), instructions: z.string().trim().min(1, \"must not be empty\").max(10_000) }),\n]);\n\nexport const checkoutSchema = z.strictObject({\n layoutMode: z.enum([\"two_step\", \"one_step\"]).optional(),\n paymentStyle: z.enum([\"classic\", \"express\"]).optional(),\n providerMode: z.enum([\"inherit\", \"stripe\", \"paypal\", \"both\"]).optional(),\n contactFields: z.strictObject({ name: z.boolean().optional(), phone: z.boolean().optional() }).optional(),\n});\n\nexport const themeSchema = z.strictObject({\n primaryColor: z.string().regex(HEX_COLOR_PATTERN, \"must be a hex color such as #5F34CC\").optional(),\n buttonRadius: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n accentMode: z.enum([\"light\", \"dark\", \"system\"]).optional(),\n});\n\nexport const stripeSchema = z.strictObject({\n priceId: z.string().trim().min(1, \"must be a Stripe price id (price_…)\"),\n});\n\nexport const productInputSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(120),\n description: z.string().max(5_000).optional(),\n price: moneySchema,\n billing: billingSchema,\n group: groupSchema.optional(),\n credits: z.array(creditGrantSchema).optional(),\n delivery: deliverySchema.optional(),\n checkout: checkoutSchema.optional(),\n theme: themeSchema.optional(),\n slug: z.string().regex(SLUG_PATTERN, \"must be 3-64 characters of lowercase letters, digits, or '-'\").optional(),\n stripe: stripeSchema.optional(),\n active: z.boolean().optional(),\n buyerEmails: z.boolean().optional(),\n offers: z\n .record(\n z.string().regex(/^[a-z0-9-]{1,32}$/, \"must be 1-32 characters of lowercase letters, digits, or '-'\"),\n z.strictObject({ title: z.string().trim().min(1, \"must not be empty\").max(120), subtitle: z.string().trim().max(120).optional() }),\n )\n .refine((offers) => Object.keys(offers).length <= 10, \"must have 10 entries or fewer\")\n .optional(),\n tabTitle: z.string().trim().max(80).optional(),\n});\n\nexport const configSchema = z\n .strictObject({\n products: z.array(productInputSchema),\n })\n .superRefine((config, ctx) => {\n const seenKeys = new Map<string, number>();\n config.products.forEach((product, index) => {\n const firstIndex = seenKeys.get(product.key);\n if (firstIndex !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"key\"],\n message: `duplicate product key \"${product.key}\" (also used by products[${firstIndex}])`,\n });\n } else {\n seenKeys.set(product.key, index);\n }\n const seenMeters = new Map<string, number>();\n product.credits?.forEach((grant, grantIndex) => {\n const firstMeter = seenMeters.get(grant.meter);\n if (firstMeter !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"credits\", grantIndex, \"meter\"],\n message: `duplicate credit meter \"${grant.meter}\" (also used by credits[${firstMeter}])`,\n });\n } else {\n seenMeters.set(grant.meter, grantIndex);\n }\n });\n });\n });\n\nexport interface ConfigIssue {\n /** Dotted path such as `products[0].price.amount`. */\n path: string;\n message: string;\n}\n\nexport class ConfigValidationError extends Error {\n override readonly name = \"ConfigValidationError\";\n readonly issues: ConfigIssue[];\n\n constructor(issues: ConfigIssue[]) {\n super(formatIssues(issues));\n this.issues = issues;\n }\n}\n\nexport function formatIssuePath(path: ReadonlyArray<PropertyKey>): string {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else out += out ? `.${String(segment)}` : String(segment);\n }\n return out || \"(root)\";\n}\n\nfunction formatIssues(issues: ConfigIssue[]): string {\n const lines = issues.map((issue) => ` - ${issue.path}: ${issue.message}`);\n return `Invalid Purpleturret config (${issues.length} issue${issues.length === 1 ? \"\" : \"s\"}):\\n${lines.join(\"\\n\")}`;\n}\n\n/**\n * Validate an arbitrary value as a Purpleturret config. Returns the normalized config (currencies\n * lowercased, strings trimmed) or throws `ConfigValidationError` listing every problem found.\n */\nexport function validateConfig(input: unknown): PurpleturretConfig {\n const result = configSchema.safeParse(input);\n if (result.success) return result.data as PurpleturretConfig;\n const issues: ConfigIssue[] = result.error.issues.map((issue) => ({\n path: formatIssuePath(issue.path),\n message: issue.message,\n }));\n throw new ConfigValidationError(issues);\n}\n\n/** Validate a single product declaration. */\nexport function validateProduct(input: unknown): ProductInput {\n const result = productInputSchema.safeParse(input);\n if (result.success) return result.data as ProductInput;\n throw new ConfigValidationError(result.error.issues.map((issue) => ({ path: formatIssuePath(issue.path), message: issue.message })));\n}\n","import type { Money, ProductInput, PurpleturretConfig } from \"../types\";\n\n/** Identity helper that gives `purpleturret.config.ts` type checking and editor completion. */\nexport function defineConfig(config: PurpleturretConfig): PurpleturretConfig {\n return config;\n}\n\n/** Identity helper for a single product declaration. */\nexport function product(input: ProductInput): ProductInput {\n return input;\n}\n\n/** Build a price from an integer amount in the smallest currency unit and a 3-letter currency code. */\nexport function money(amount: number, currency: string): Money {\n if (!Number.isInteger(amount)) {\n throw new TypeError(`money(): amount must be an integer in the smallest currency unit (got ${amount}); use usd(dollars) for dollars`);\n }\n return { amount, currency: currency.trim().toLowerCase() };\n}\n\n/** Build a USD price from a dollar amount (`usd(29)` → 2900 cents, `usd(19.99)` → 1999). */\nexport function usd(dollars: number): Money {\n if (!Number.isFinite(dollars)) throw new TypeError(`usd(): expected a finite number of dollars (got ${dollars})`);\n return { amount: Math.round((dollars + Number.EPSILON) * 100), currency: \"usd\" };\n}\n","import type {\n Account,\n Billing,\n CheckoutSettings,\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CreditGrant,\n CustomerRef,\n Delivery,\n Entitlement,\n LedgerEntry,\n Page,\n PlanAction,\n PlanItem,\n Product,\n ProductBump,\n ProductDelivery,\n ProductOffer,\n ProductGroup,\n ProductInput,\n ProductTheme,\n StripeSettings,\n Tier,\n} from \"../types\";\n\n/*\n * Wire (snake_case) shapes as sent and received by the REST API.\n */\n\nexport interface WireMoney {\n amount: number;\n currency: string;\n}\n\nexport type WireBilling = { type: \"one_time\" } | { type: \"recurring\"; interval: \"month\" | \"year\" };\n\nexport interface WireTier {\n key: string;\n name: string;\n rank: number;\n}\n\nexport interface WireGroup {\n key: string;\n tier?: WireTier | null;\n}\n\nexport interface WireCreditGrant {\n meter: string;\n amount: number;\n renewal: \"reset\" | \"accumulate\";\n expires_after_days?: number | null;\n}\n\nexport type WireDelivery = { method: \"none\" } | { method: \"redirect\"; url: string } | { method: \"instructions\"; instructions: string };\n\nexport interface WireCheckout {\n layout_mode?: \"two_step\" | \"one_step\" | null;\n payment_style?: \"classic\" | \"express\" | null;\n provider_mode?: \"inherit\" | \"stripe\" | \"paypal\" | \"both\" | null;\n contact_fields?: { name?: boolean | null; phone?: boolean | null } | null;\n}\n\nexport interface WireTheme {\n primary_color?: string | null;\n button_radius?: \"sm\" | \"md\" | \"lg\" | null;\n accent_mode?: \"light\" | \"dark\" | \"system\" | null;\n}\n\nexport interface WireStripe {\n price_id: string;\n}\n\nexport interface WireProductInput {\n key: string;\n name: string;\n description?: string | null;\n price: WireMoney;\n billing: WireBilling;\n group?: WireGroup | null;\n credits?: WireCreditGrant[] | null;\n delivery?: WireDelivery | null;\n checkout?: WireCheckout | null;\n theme?: WireTheme | null;\n slug?: string | null;\n stripe?: WireStripe | null;\n active?: boolean;\n buyer_emails?: boolean;\n offers?: Record<string, ProductOffer>;\n tab_title?: string | null;\n}\n\nexport type WireProductDelivery =\n | WireDelivery\n | { method: \"file\"; file_count: number; files?: { file_name: string; content_type: string; file_size: number }[] };\n\nexport interface WireBump {\n product_id: string;\n headline: string;\n description: string;\n}\n\nexport interface WireProduct extends Omit<WireProductInput, \"key\" | \"slug\" | \"active\" | \"delivery\" | \"theme\"> {\n key: string | null;\n id: string;\n slug: string | null;\n url: string | null;\n active: boolean;\n delivery?: WireProductDelivery | null;\n theme?: (WireTheme & { logo_storage_id?: string | null; logo_url?: string | null }) | null;\n bumps?: WireBump[] | null;\n upsell?: WireBump | null;\n pixel_id?: string | null;\n archived_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface WirePlanChange {\n path: string;\n from: unknown;\n to: unknown;\n note?: string | null;\n}\n\nexport interface WirePlanItem {\n key: string;\n action: PlanAction;\n changes?: WirePlanChange[] | null;\n product?: WireProduct | null;\n error?: { code?: string; message?: string } | string | null;\n}\n\nexport interface WireConfigPushResult {\n applied: boolean;\n summary: { create: number; update: number; unchanged: number; archive: number; conflict: number; error: number };\n results: WirePlanItem[];\n}\n\nexport interface WireConfigGetResult {\n products: WireProduct[];\n unmanaged_count: number;\n}\n\nexport interface WireAccount {\n id: string;\n email: string;\n name?: string | null;\n stripe: { connected: boolean; charges_enabled: boolean };\n paypal: { connected: boolean };\n key: { prefix: string; name?: string | null; scopes: string[] };\n}\n\nexport interface WirePage<T> {\n data: T[];\n next_cursor?: string | null;\n}\n\nexport interface WireCustomerRef {\n email?: string | null;\n external_id?: string | null;\n}\n\nexport interface WireCreditBalance {\n meter: string;\n balance: number;\n expires_at?: number | null;\n lifetime_granted: number;\n lifetime_consumed: number;\n}\n\nexport interface WireCreditBalancesResult {\n customer: WireCustomerRef;\n balances: WireCreditBalance[];\n}\n\nexport interface WireCreditConsumeResult {\n meter: string;\n balance: number;\n consumed: number;\n replayed: boolean;\n}\n\nexport interface WireCreditAdjustResult {\n meter: string;\n balance: number;\n}\n\nexport type WireLedgerEntry = Record<string, unknown>;\n\nexport type WireEntitlement = Record<string, unknown>;\n\n/*\n * Mappers.\n */\n\nfunction omitUndefined<T extends object>(value: T): T {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = entry;\n }\n return out as T;\n}\n\nexport function toWireProduct(input: ProductInput): WireProductInput {\n const wire: WireProductInput = {\n key: input.key,\n name: input.name,\n description: input.description,\n price: { amount: input.price.amount, currency: input.price.currency },\n billing: input.billing.type === \"recurring\" ? { type: \"recurring\", interval: input.billing.interval } : { type: \"one_time\" },\n group: input.group ? toWireGroup(input.group) : undefined,\n credits: input.credits?.map(toWireCreditGrant),\n delivery: input.delivery ? toWireDelivery(input.delivery) : undefined,\n checkout: input.checkout ? toWireCheckout(input.checkout) : undefined,\n theme: input.theme ? toWireTheme(input.theme) : undefined,\n slug: input.slug,\n stripe: input.stripe ? { price_id: input.stripe.priceId } : undefined,\n active: input.active,\n buyer_emails: input.buyerEmails,\n offers: input.offers,\n tab_title: input.tabTitle,\n };\n return omitUndefined(wire);\n}\n\nfunction toWireGroup(group: ProductGroup): WireGroup {\n return omitUndefined({ key: group.key, tier: group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined });\n}\n\nfunction toWireCreditGrant(grant: CreditGrant): WireCreditGrant {\n return omitUndefined({ meter: grant.meter, amount: grant.amount, renewal: grant.renewal, expires_after_days: grant.expiresAfterDays });\n}\n\nfunction toWireDelivery(delivery: Delivery): WireDelivery {\n switch (delivery.method) {\n case \"none\":\n return { method: \"none\" };\n case \"redirect\":\n return { method: \"redirect\", url: delivery.url };\n case \"instructions\":\n return { method: \"instructions\", instructions: delivery.instructions };\n }\n}\n\nfunction toWireCheckout(checkout: CheckoutSettings): WireCheckout {\n return omitUndefined({\n layout_mode: checkout.layoutMode,\n payment_style: checkout.paymentStyle,\n provider_mode: checkout.providerMode,\n contact_fields: checkout.contactFields ? omitUndefined({ name: checkout.contactFields.name, phone: checkout.contactFields.phone }) : undefined,\n });\n}\n\nfunction toWireTheme(theme: ProductTheme): WireTheme {\n return omitUndefined({ primary_color: theme.primaryColor, button_radius: theme.buttonRadius, accent_mode: theme.accentMode });\n}\n\nexport function fromWireProduct(wire: WireProduct): Product {\n const product: Product = {\n key: wire.key ?? null,\n id: wire.id,\n slug: wire.slug ?? null,\n url: wire.url ?? null,\n name: wire.name,\n description: wire.description ?? undefined,\n price: { amount: wire.price.amount, currency: wire.price.currency },\n billing: fromWireBilling(wire.billing),\n group: wire.group ? fromWireGroup(wire.group) : undefined,\n credits: wire.credits ? wire.credits.map(fromWireCreditGrant) : undefined,\n delivery: wire.delivery ? (camelizeKeys(wire.delivery) as ProductDelivery) : undefined,\n checkout: wire.checkout ? fromWireCheckout(wire.checkout) : undefined,\n theme: wire.theme ? fromWireTheme(wire.theme) : undefined,\n stripe: wire.stripe ? fromWireStripe(wire.stripe) : undefined,\n active: wire.active,\n buyerEmails: wire.buyer_emails ?? undefined,\n offers: wire.offers,\n tabTitle: wire.tab_title ?? undefined,\n bumps: wire.bumps ? (camelizeKeys(wire.bumps) as ProductBump[]) : undefined,\n upsell: wire.upsell === undefined ? undefined : wire.upsell && (camelizeKeys(wire.upsell) as ProductBump),\n pixelId: wire.pixel_id,\n archivedAt: wire.archived_at ?? null,\n createdAt: wire.created_at,\n updatedAt: wire.updated_at,\n };\n return omitUndefined(product);\n}\n\nfunction fromWireBilling(billing: WireBilling): Billing {\n return billing.type === \"recurring\" ? { type: \"recurring\", interval: billing.interval } : { type: \"one_time\" };\n}\n\nfunction fromWireGroup(group: WireGroup): ProductGroup {\n const tier: Tier | undefined = group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined;\n return omitUndefined({ key: group.key, tier });\n}\n\nfunction fromWireCreditGrant(grant: WireCreditGrant): CreditGrant {\n return omitUndefined({\n meter: grant.meter,\n amount: grant.amount,\n renewal: grant.renewal,\n expiresAfterDays: grant.expires_after_days ?? undefined,\n });\n}\n\nfunction fromWireCheckout(checkout: WireCheckout): CheckoutSettings {\n return omitUndefined({\n layoutMode: checkout.layout_mode ?? undefined,\n paymentStyle: checkout.payment_style ?? undefined,\n providerMode: checkout.provider_mode ?? undefined,\n contactFields: checkout.contact_fields\n ? omitUndefined({ name: checkout.contact_fields.name ?? undefined, phone: checkout.contact_fields.phone ?? undefined })\n : undefined,\n });\n}\n\nfunction fromWireTheme(theme: NonNullable<WireProduct[\"theme\"]>): NonNullable<Product[\"theme\"]> {\n return omitUndefined({\n primaryColor: theme.primary_color ?? undefined,\n buttonRadius: theme.button_radius ?? undefined,\n accentMode: theme.accent_mode ?? undefined,\n logoStorageId: theme.logo_storage_id,\n logoUrl: theme.logo_url,\n });\n}\n\nfunction fromWireStripe(stripe: WireStripe): StripeSettings {\n return { priceId: stripe.price_id };\n}\n\n/** Strip server-only fields from a fetched product so it can be re-declared in a config file. */\nexport function productToInput(product: Product): ProductInput | null {\n if (!product.key) return null;\n return omitUndefined({\n key: product.key,\n name: product.name,\n description: product.description,\n price: product.price,\n billing: product.billing,\n group: product.group,\n credits: product.credits,\n // File delivery and logos are managed in the dashboard / via the API, never from config.\n delivery: product.delivery?.method === \"file\" ? undefined : product.delivery,\n theme: product.theme\n ? omitUndefined({ primaryColor: product.theme.primaryColor, buttonRadius: product.theme.buttonRadius, accentMode: product.theme.accentMode })\n : undefined,\n slug: product.slug ?? undefined,\n stripe: product.stripe,\n active: product.active,\n // The API always reports buyer_emails; only the opt-out is worth writing into a config.\n buyerEmails: product.buyerEmails === false ? false : undefined,\n offers: product.offers && Object.keys(product.offers).length > 0 ? product.offers : undefined,\n tabTitle: product.tabTitle || undefined,\n });\n}\n\nexport function fromWirePlanItem(item: WirePlanItem): PlanItem {\n let error: PlanItem[\"error\"];\n if (typeof item.error === \"string\") error = { code: item.error, message: item.error };\n else if (item.error && typeof item.error === \"object\") {\n error = { code: item.error.code ?? \"error\", message: item.error.message ?? item.error.code ?? \"Unknown error\" };\n }\n return omitUndefined({\n key: item.key,\n action: item.action,\n changes: (item.changes ?? []).map((change) =>\n omitUndefined({ path: change.path, from: change.from, to: change.to, note: change.note ?? undefined }),\n ),\n product: item.product ? fromWireProduct(item.product) : undefined,\n error,\n });\n}\n\nexport function fromWireConfigPushResult(wire: WireConfigPushResult): ConfigPushResult {\n return {\n applied: Boolean(wire.applied),\n summary: {\n create: wire.summary?.create ?? 0,\n update: wire.summary?.update ?? 0,\n unchanged: wire.summary?.unchanged ?? 0,\n archive: wire.summary?.archive ?? 0,\n conflict: wire.summary?.conflict ?? 0,\n error: wire.summary?.error ?? 0,\n },\n results: (wire.results ?? []).map(fromWirePlanItem),\n };\n}\n\nexport function fromWireConfigGetResult(wire: WireConfigGetResult): ConfigGetResult {\n return { products: (wire.products ?? []).map(fromWireProduct), unmanagedCount: wire.unmanaged_count ?? 0 };\n}\n\nexport function fromWireAccount(wire: WireAccount): Account {\n return {\n id: wire.id,\n email: wire.email,\n name: wire.name ?? null,\n stripe: { connected: Boolean(wire.stripe?.connected), chargesEnabled: Boolean(wire.stripe?.charges_enabled) },\n paypal: { connected: Boolean(wire.paypal?.connected) },\n key: { prefix: wire.key?.prefix ?? \"\", name: wire.key?.name ?? null, scopes: wire.key?.scopes ?? [] },\n };\n}\n\nexport function fromWirePage<W, T>(wire: WirePage<W>, map: (item: W) => T): Page<T> {\n return { data: (wire.data ?? []).map(map), nextCursor: wire.next_cursor ?? null };\n}\n\nfunction fromWireCustomerRef(ref: WireCustomerRef | null | undefined): CustomerRef {\n return { email: ref?.email ?? null, externalId: ref?.external_id ?? null };\n}\n\nexport function fromWireCreditBalances(wire: WireCreditBalancesResult): CreditBalancesResult {\n return {\n customer: fromWireCustomerRef(wire.customer),\n balances: (wire.balances ?? []).map((balance) => ({\n meter: balance.meter,\n balance: balance.balance,\n expiresAt: balance.expires_at ?? null,\n lifetimeGranted: balance.lifetime_granted ?? 0,\n lifetimeConsumed: balance.lifetime_consumed ?? 0,\n })),\n };\n}\n\nexport function fromWireCreditConsume(wire: WireCreditConsumeResult): CreditConsumeResult {\n return { meter: wire.meter, balance: wire.balance, consumed: wire.consumed, replayed: Boolean(wire.replayed) };\n}\n\nexport function fromWireCreditAdjust(wire: WireCreditAdjustResult): CreditAdjustResult {\n return { meter: wire.meter, balance: wire.balance };\n}\n\n/** camelCase → snake_case keys, deeply. Values are left untouched. */\nexport function snakeizeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(snakeizeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n out[key.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`)] = snakeizeKeys(entry);\n }\n return out;\n }\n return value;\n}\n\n/** snake_case → camelCase for a single key. */\nexport function camelCaseKey(key: string): string {\n return key.replace(/_([a-z0-9])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** Deeply convert object keys to camelCase. Values are left untouched. */\nexport function camelizeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(camelizeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) out[camelCaseKey(key)] = camelizeKeys(entry);\n return out;\n }\n return value;\n}\n\nexport function fromWireLedgerEntry(wire: WireLedgerEntry): LedgerEntry {\n const entry = camelizeKeys(wire) as Record<string, unknown>;\n return {\n ...entry,\n id: String(entry.id ?? \"\"),\n kind: entry.kind as LedgerEntry[\"kind\"],\n meter: String(entry.meter ?? \"\"),\n amount: Number(entry.amount ?? 0),\n balanceAfter: Number(entry.balanceAfter ?? 0),\n note: (entry.note as string | null | undefined) ?? null,\n createdAt: Number(entry.createdAt ?? 0),\n };\n}\n\nexport function fromWireEntitlement(wire: WireEntitlement): Entitlement {\n const { credits, ...rest } = wire;\n const base = camelizeKeys(rest) as Record<string, unknown>;\n const entitlement: Entitlement = {\n ...(base as Partial<Entitlement>),\n hasAccess: Boolean(base.hasAccess),\n status: String(base.status ?? \"none\"),\n };\n if (credits && typeof credits === \"object\") {\n // Meter names are user-defined keys; keep them verbatim and only camelize the values.\n entitlement.credits = Object.fromEntries(\n Object.entries(credits as Record<string, Record<string, unknown>>).map(([meter, value]) => [\n meter,\n { balance: Number(value?.balance ?? 0), expiresAt: (value?.expires_at as number | null | undefined) ?? null },\n ]),\n );\n }\n return entitlement;\n}\n","import type { Account } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { type WireAccount, camelizeKeys, fromWireAccount } from \"../wire\";\n\n/*\n * account.update, Stripe/PayPal status + connect, billing portal, keys list, support. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\n/** GET/PATCH /account body; superset of `Account` (which `client.account.get()` still returns). */\nexport interface AccountDetails extends Account {\n profile: { givenName: string | null; familyName: string | null };\n checkoutProviders: { stripe: boolean; paypal: boolean };\n plan: { status: \"none\" | \"active\" | \"trialing\" | \"past_due\" | \"canceled\"; active: boolean };\n sandbox: boolean;\n accountKind: \"standard\" | \"platform_merchant\" | \"sandbox\";\n createdAt: number;\n}\n\nexport interface AccountUpdateOptions {\n givenName?: string;\n familyName?: string;\n /** Both `false` is stored as `{ stripe: true, paypal: false }`. */\n checkoutProviders?: { stripe: boolean; paypal: boolean };\n}\n\nexport interface StripeAccount {\n connectionMode: \"connect\" | \"api_key\" | \"platform\";\n chargesEnabled: boolean;\n payoutsEnabled: boolean;\n detailsSubmitted: boolean;\n country: string | null;\n defaultCurrency: string | null;\n publishableKey: string | null;\n displayName: string | null;\n pendingReplacement: boolean;\n updatedAt: number;\n}\n\nexport interface StripeMigration {\n id: string;\n status: \"running\" | \"completed\" | \"failed\" | \"canceled\";\n phase: \"products\" | \"customers\" | \"done\";\n sourceConnectionMode: \"connect\" | \"api_key\" | \"platform\";\n includeCustomers: boolean;\n products: { scanned: number; cloned: number; skipped: number; failed: number };\n customers: { scanned: number; cloned: number; skipped: number; failed: number };\n lastError: string | null;\n startedAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nexport interface StripeStatus {\n state: \"not_connected\" | \"action_required\" | \"pending_verification\" | \"ready\";\n hasAccount: boolean;\n items: { code: string; label: string; severity: \"past_due\" | \"currently_due\" }[];\n errors: { code: string; reason: string; requirement: string; label: string }[];\n disabledReason: string | null;\n account: StripeAccount | null;\n migration: StripeMigration | null;\n}\n\nexport interface StripeRefresh {\n ready: boolean;\n transfersStatus: string;\n payoutsEnabled: boolean;\n disabledReason: string | null;\n}\n\nexport interface StripeOnboardingLinkOptions {\n /** ISO-3166 alpha-2; required when no Stripe account exists yet. */\n country?: string;\n /** Dashboard path starting with `/dashboard/`; anything else falls back to `/dashboard/onboarding`. */\n returnTo?: string;\n}\n\nexport interface StripeConnectApiKeyOptions {\n /** `sk_` or `rk_` key; never echoed back. */\n secretKey: string;\n /** `pk_` key. */\n publishableKey: string;\n migration?: { includeCustomers: boolean };\n}\n\nexport interface StripeBrandingOptions {\n /** Hex color, passed to Stripe as-is. */\n primaryColor?: string;\n /** Must start with `https://`. */\n logoUrl?: string;\n}\n\nexport interface PaypalAccount {\n clientId: string;\n environment: \"live\" | \"sandbox\" | null;\n email: string | null;\n displayName: string | null;\n enabled: boolean;\n connectedAt: number;\n updatedAt: number;\n}\n\nexport interface PaypalStatus {\n state: \"not_connected\" | \"ready\";\n hasAccount: boolean;\n account: PaypalAccount | null;\n}\n\nexport interface PaypalConnectOptions {\n clientId: string;\n /** Never echoed back. */\n secret: string;\n}\n\nexport interface SupportRequestOptions {\n /** ≤160 chars. */\n subject?: string;\n /** 10–5000 chars. */\n message: string;\n /** Replaying the same key and body returns the stored result. */\n idempotencyKey?: string;\n}\n\nexport interface SupportRequestCreated {\n id: string;\n createdAt: number;\n}\n\nexport type WireAccountDetails = Record<string, unknown>;\nexport type WireStripeStatus = Record<string, unknown>;\nexport type WirePaypalStatus = Record<string, unknown>;\n\n// fromWireAccount supplies the `null` defaults for the base fields; the rest is a straight camelize.\nexport const fromWireAccountDetails = (wire: WireAccountDetails) =>\n ({ ...(camelizeKeys(wire) as object), ...fromWireAccount(wire as unknown as WireAccount) }) as AccountDetails;\nconst fromWireStripeStatus = (wire: WireStripeStatus) => camelizeKeys(wire) as StripeStatus;\nconst fromWirePaypalStatus = (wire: WirePaypalStatus) => camelizeKeys(wire) as PaypalStatus;\n\nexport function accountApi(client: PurpleturretClient) {\n return {\n /** An empty patch is a no-op that returns the current account. */\n update: async (patch: AccountUpdateOptions): Promise<AccountDetails> =>\n fromWireAccountDetails(\n await client.request<WireAccountDetails>(\"PATCH\", \"/account\", {\n body: { given_name: patch.givenName, family_name: patch.familyName, checkout_providers: patch.checkoutProviders },\n }),\n ),\n stripeStatus: async (): Promise<StripeStatus> => fromWireStripeStatus(await client.request<WireStripeStatus>(\"GET\", \"/account/stripe\")),\n stripeOnboardingLink: async (options: StripeOnboardingLinkOptions = {}): Promise<{ url: string }> =>\n client.request(\"POST\", \"/account/stripe/onboarding-link\", { body: { country: options.country, return_to: options.returnTo } }),\n /** Re-reads capabilities from Stripe; 404 when no Stripe account. */\n stripeRefresh: async (): Promise<StripeRefresh> => camelizeKeys(await client.request(\"POST\", \"/account/stripe/refresh\")) as StripeRefresh,\n /** Sandbox accounts accept test-mode keys only. */\n stripeConnectApiKey: async (options: StripeConnectApiKeyOptions): Promise<StripeStatus> =>\n fromWireStripeStatus(\n await client.request<WireStripeStatus>(\"POST\", \"/account/stripe/connect-api-key\", {\n body: {\n secret_key: options.secretKey,\n publishable_key: options.publishableKey,\n migration: options.migration ? { include_customers: options.migration.includeCustomers } : undefined,\n },\n }),\n ),\n /** `applied: false` for api_key / platform accounts (branding lives in their own Stripe dashboard). */\n stripeBranding: async (options: StripeBrandingOptions = {}): Promise<{ applied: boolean }> =>\n client.request(\"PUT\", \"/account/stripe/branding\", { body: { primary_color: options.primaryColor, logo_url: options.logoUrl } }),\n paypalStatus: async (): Promise<PaypalStatus> => fromWirePaypalStatus(await client.request<WirePaypalStatus>(\"GET\", \"/account/paypal\")),\n paypalConnect: async (options: PaypalConnectOptions): Promise<PaypalStatus> =>\n fromWirePaypalStatus(\n await client.request<WirePaypalStatus>(\"POST\", \"/account/paypal/connect\", { body: { client_id: options.clientId, secret: options.secret } }),\n ),\n paypalDisconnect: async (): Promise<PaypalStatus> => fromWirePaypalStatus(await client.request<WirePaypalStatus>(\"DELETE\", \"/account/paypal\")),\n /** Purpleturret's own plan portal (not the seller's connected account); 422 before any plan purchase. */\n billingPortal: async (): Promise<{ url: string }> => client.request(\"POST\", \"/account/billing-portal\"),\n };\n}\n\nexport function supportApi(client: PurpleturretClient) {\n return {\n /** Filed under the account's email and name. */\n create: async (options: SupportRequestOptions): Promise<SupportRequestCreated> =>\n camelizeKeys(\n await client.request(\"POST\", \"/support\", {\n body: { subject: options.subject, message: options.message },\n idempotencyKey: options.idempotencyKey,\n }),\n ) as SupportRequestCreated,\n };\n}\n","import type { Page } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * orders, subscriptions, customers, leads. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport type OrderStatus = \"pending\" | \"paid\" | \"failed\" | \"refunded\" | \"partially_refunded\";\nexport type OrderKind = \"one_time\" | \"subscription_initial\" | \"subscription_renewal\";\nexport type PaymentProvider = \"stripe\" | \"paypal\";\nexport type RefundReason = \"requested_by_customer\" | \"duplicate\" | \"fraudulent\" | \"other\";\nexport type RefundScope = \"main\" | \"upsell\" | \"all\";\nexport type SubscriptionStatus = \"incomplete\" | \"incomplete_expired\" | \"trialing\" | \"active\" | \"past_due\" | \"canceled\" | \"unpaid\" | \"paused\";\n\nexport interface OrderCustomer {\n email: string | null;\n name: string | null;\n phone: string | null;\n externalId: string | null;\n}\n\nexport interface OrderLineItem {\n productId: string;\n role: \"main\" | \"bump\" | \"upsell\";\n amount: number;\n name: string | null;\n}\n\nexport interface OrderRefund {\n amount: number | null;\n refundedAt: number;\n reason: RefundReason | null;\n customReason: string | null;\n}\n\nexport interface Order {\n id: string;\n status: OrderStatus;\n provider: PaymentProvider;\n kind: OrderKind;\n productId: string;\n customer: OrderCustomer;\n /** Main charge total in minor units (bumps included, upsell excluded). */\n amount: number;\n currency: string;\n lineItems: OrderLineItem[];\n refund: OrderRefund | null;\n upsell: { decision: \"pending\" | \"accepted\" | \"declined\" | \"expired\"; decidedAt: number | null; refund: OrderRefund | null } | null;\n stripe: { paymentIntentId: string | null; invoiceId: string | null; subscriptionId: string | null } | null;\n paypal: { orderId: string | null; captureId: string | null; subscriptionId: string | null } | null;\n failureReason: string | null;\n createdAt: number;\n}\n\nexport interface OrderListOptions {\n /** Case-insensitive exact match. */\n email?: string;\n status?: OrderStatus;\n cursor?: string;\n limit?: number;\n}\n\nexport interface OrderRefundOptions {\n /** Default `all`. */\n scope?: RefundScope;\n reason: RefundReason;\n /** Stored only when `reason` is `other`; max 500 chars. */\n customReason?: string;\n /** Sent as `Idempotency-Key`; generated when absent. */\n idempotencyKey?: string;\n}\n\nexport interface OrderRefundResult {\n refundedMain: boolean;\n refundedUpsell: boolean;\n order: Order;\n}\n\nexport interface Subscription {\n id: string;\n status: SubscriptionStatus;\n provider: PaymentProvider;\n productId: string;\n customer: OrderCustomer & { email: string };\n amount: number;\n currency: string;\n interval: \"month\" | \"year\";\n cancelAtPeriodEnd: boolean;\n currentPeriodStart: number | null;\n currentPeriodEnd: number | null;\n stripeSubscriptionId: string | null;\n paypalSubscriptionId: string | null;\n createdAt: number;\n updatedAt: number;\n endedAt: number | null;\n}\n\nexport interface SubscriptionListOptions {\n email?: string;\n /** `canceled` is the churned view. */\n status?: SubscriptionStatus;\n /** Product id (not the config key). Ignored when `email` is given. */\n product?: string;\n cursor?: string;\n limit?: number;\n}\n\nexport interface PortalLink {\n url: string;\n /** Links are valid for 7 days. */\n expiresAt: number;\n}\n\nexport interface Customer {\n email: string;\n name: string | null;\n phone: string | null;\n externalId: string | null;\n stripeCustomerId: string;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface CustomerCredit {\n meter: string;\n balance: number;\n expiresAt: number | null;\n lifetimeGranted: number;\n lifetimeConsumed: number;\n}\n\nexport interface CustomerDetail extends Omit<Customer, \"stripeCustomerId\" | \"createdAt\" | \"updatedAt\"> {\n stripeCustomerId: string | null;\n createdAt: number | null;\n updatedAt: number | null;\n /** Newest 100. */\n orders: Order[];\n /** Newest 100. */\n subscriptions: Subscription[];\n credits: CustomerCredit[];\n /** One entry per currency over paid orders. */\n lifetimeSpend: { currency: string; amount: number }[];\n}\n\nexport interface CustomerListOptions {\n cursor?: string;\n limit?: number;\n}\n\nexport interface CheckoutLead {\n id: string;\n email: string | null;\n name: string | null;\n phone: string | null;\n externalId: string | null;\n productId: string;\n status: \"active\" | \"payment_started\" | \"completed\";\n amount: number;\n currency: string;\n createdAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nexport interface CheckoutLeadListOptions {\n /** Only leads not completed and untouched for 30+ minutes. */\n abandoned?: boolean;\n /** Window for `abandoned`, 1–180 (default 30). */\n lookbackDays?: number;\n}\n\nexport interface PageLead {\n id: string;\n email: string;\n name: string | null;\n /** `page:<slug>`. */\n source: string;\n firstPageId: string;\n lastPageId: string;\n submissionCount: number;\n createdAt: number;\n updatedAt: number;\n}\n\nexport type WireOrder = Record<string, unknown>;\nexport type WireSubscription = Record<string, unknown>;\nexport type WireCustomer = Record<string, unknown>;\nexport type WireLead = Record<string, unknown>;\n\nexport const fromWireOrder = (wire: WireOrder): Order => camelizeKeys(wire) as Order;\nexport const fromWireSubscription = (wire: WireSubscription): Subscription => camelizeKeys(wire) as Subscription;\n\nexport function ordersApi(client: PurpleturretClient) {\n const path = (id: string) => `/orders/${encodeURIComponent(id)}`;\n return {\n list: async (options: OrderListOptions = {}): Promise<Page<Order>> =>\n fromWirePage(\n await client.request<WirePage<WireOrder>>(\"GET\", \"/orders\", {\n query: { email: options.email, status: options.status, cursor: options.cursor, limit: options.limit },\n }),\n fromWireOrder,\n ),\n get: async (id: string): Promise<Order> => fromWireOrder(await client.request<WireOrder>(\"GET\", path(id))),\n /** Refunds the main and/or upsell charge through the payment provider; cannot be undone. */\n refund: async (id: string, options: OrderRefundOptions): Promise<OrderRefundResult> =>\n camelizeKeys(\n await client.request<Record<string, unknown>>(\"POST\", `${path(id)}/refund`, {\n body: { scope: options.scope, reason: options.reason, custom_reason: options.customReason },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ) as OrderRefundResult,\n };\n}\n\nexport function subscriptionsApi(client: PurpleturretClient) {\n const path = (id: string) => `/subscriptions/${encodeURIComponent(id)}`;\n return {\n list: async (options: SubscriptionListOptions = {}): Promise<Page<Subscription>> =>\n fromWirePage(\n await client.request<WirePage<WireSubscription>>(\"GET\", \"/subscriptions\", {\n query: { email: options.email, status: options.status, product: options.product, cursor: options.cursor, limit: options.limit },\n }),\n fromWireSubscription,\n ),\n get: async (id: string): Promise<Subscription> => fromWireSubscription(await client.request<WireSubscription>(\"GET\", path(id))),\n /** Creates a fresh 7-day billing portal link on every call. */\n portalLink: async (id: string): Promise<PortalLink> =>\n camelizeKeys(await client.request<Record<string, unknown>>(\"POST\", `${path(id)}/portal-link`)) as PortalLink,\n /** E-mails the buyer a fresh portal link. */\n portalEmail: async (id: string): Promise<{ sent: true }> => client.request<{ sent: true }>(\"POST\", `${path(id)}/portal-email`),\n };\n}\n\nexport function customersApi(client: PurpleturretClient) {\n return {\n /** Ordered by email ascending, one row per email. */\n list: async (options: CustomerListOptions = {}): Promise<Page<Customer>> =>\n fromWirePage(\n await client.request<WirePage<WireCustomer>>(\"GET\", \"/customers\", { query: { cursor: options.cursor, limit: options.limit } }),\n (wire) => camelizeKeys(wire) as Customer,\n ),\n /** `emailOrExternalId`: an e-mail address (contains `@`) or the seller's own external id. */\n get: async (emailOrExternalId: string): Promise<CustomerDetail> =>\n camelizeKeys(await client.request<WireCustomer>(\"GET\", `/customers/${encodeURIComponent(emailOrExternalId)}`)) as CustomerDetail,\n };\n}\n\nexport function leadsApi(client: PurpleturretClient) {\n return {\n /** Not paginated: newest first, at most 2000 rows (200 when `abandoned`). */\n checkout: async (options: CheckoutLeadListOptions = {}): Promise<Page<CheckoutLead>> =>\n fromWirePage(\n await client.request<WirePage<WireLead>>(\"GET\", \"/leads/checkout\", {\n query: { abandoned: options.abandoned ? \"true\" : undefined, lookback_days: options.lookbackDays },\n }),\n (wire) => camelizeKeys(wire) as CheckoutLead,\n ),\n /** Not paginated: newest first, at most 1000 rows. */\n pages: async (): Promise<Page<PageLead>> =>\n fromWirePage(await client.request<WirePage<WireLead>>(\"GET\", \"/leads/pages\"), (wire) => camelizeKeys(wire) as PageLead),\n };\n}\n","import type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\nimport type { Page } from \"../../types\";\n\n/*\n * pixels + analytics. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport interface PixelFunnelDef {\n key: string;\n label: string;\n /** An event name or a `/path` prefix. */\n steps: string[];\n}\n\nexport interface Pixel {\n id: string;\n /** Public snippet key `pt_px_…` (not a secret). */\n key: string;\n name: string;\n /** null = any origin. */\n allowedHosts: string[] | null;\n declaredEvents: string[] | null;\n funnels: PixelFunnelDef[] | null;\n /** Also runs on the seller's Purpleturret checkout pages. */\n checkout: boolean;\n archivedAt: number | null;\n createdAt: number;\n}\n\nexport interface PixelAttachment {\n pixelId: string | null;\n productId: string | null;\n pageId: string | null;\n}\n\nexport interface PixelKpis {\n visitors: number;\n sessions: number;\n pageviews: number;\n avgDurationMs: number;\n /** 0..1 share of sessions with at most one pageview. */\n bounceRate: number;\n}\n\nexport interface PixelSourceRow {\n source: string;\n medium: string;\n campaign: string;\n sessions: number;\n visitors: number;\n}\nexport interface PixelPathRow {\n path: string;\n sessions: number;\n visitors: number;\n}\n/** For regions and cities `name` is `\"<Region or City>|<ISO country>\"`. */\nexport interface PixelNamedRow {\n name: string;\n sessions: number;\n visitors: number;\n}\n\nexport interface PixelSessionRow {\n sid: string;\n visitorId: string;\n startedAt: number;\n lastAt: number;\n pageviews: number;\n entryPath: string;\n exitPath: string | null;\n source: { source: string; medium: string; campaign: string };\n externalId: string | null;\n email: string | null;\n name: string | null;\n phone: string | null;\n device: string | null;\n os: string | null;\n browser: string | null;\n screen: string | null;\n country: string | null;\n region: string | null;\n city: string | null;\n spent: number;\n currency: string | null;\n purchasedAt: number | null;\n}\n\nexport interface PixelOverview {\n start: number;\n end: number;\n truncated: boolean;\n kpis: PixelKpis;\n /** Only with `compare: true`. */\n prior: PixelKpis | null;\n /** Empty without `bucket`; oldest first, last bucket ends at `end`. */\n series: PixelKpis[];\n online: number;\n entryPages: PixelPathRow[];\n exitPages: PixelPathRow[];\n devices: PixelNamedRow[];\n os: PixelNamedRow[];\n browsers: PixelNamedRow[];\n countries: PixelNamedRow[];\n regions: PixelNamedRow[];\n cities: PixelNamedRow[];\n sessionSources: PixelSourceRow[];\n visitorSources: PixelSourceRow[];\n referrers: { host: string; sessions: number; visitors: number }[];\n recent: PixelSessionRow[];\n}\n\nexport interface PixelTopPages {\n start: number;\n end: number;\n truncated: boolean;\n pages: { path: string; views: number; visitors: number; avgDurationMs: number | null }[];\n}\n\nexport interface PixelFunnels {\n start: number;\n end: number;\n funnels: { key: string; label: string; steps: { match: string; sessions: number }[] }[];\n}\n\nexport interface PixelAdRow {\n source: string;\n medium: string;\n campaign: string;\n content: string;\n term: string;\n sessions: number;\n visitors: number;\n conversions: number;\n converters: number;\n revenue: number;\n}\n\nexport interface PixelAdPerformance {\n start: number;\n end: number;\n truncated: boolean;\n rows: PixelAdRow[];\n campaigns: (PixelAdRow & { spend: number })[];\n currency: string | null;\n conversions: number;\n other: { sessions: number; conversions: number; revenue: number };\n unattributed: number;\n candidates: string[];\n}\n\nexport interface PixelPerson {\n id: string;\n externalId: string | null;\n email: string | null;\n name: string | null;\n phone: string | null;\n visitors: number;\n firstSeen: number;\n lastSeen: number;\n sessions: number;\n pageviews: number;\n spent: number;\n currency: string | null;\n purchasedAt: number | null;\n durationMs: number;\n country: string | null;\n region: string | null;\n city: string | null;\n device: string | null;\n os: string | null;\n browser: string | null;\n screen: string | null;\n firstTouch: { source: string; medium: string; campaign: string };\n recent: PixelSessionRow[];\n}\n\nexport interface PixelPeople {\n start: number;\n end: number;\n truncated: boolean;\n /** Everyone in the range, across all pages. */\n total: number;\n /** How many of `total` have bought. */\n customers: number;\n people: PixelPerson[];\n}\n\nexport interface PixelTimelineEvent {\n /** `pageview` | `click` | `scroll` | `form` | a custom event. */\n name: string;\n ts: number;\n path: string;\n duration: number | null;\n /** Prop keys are kept verbatim (not camelized). */\n props: Record<string, string | number | boolean> | null;\n}\n\nexport interface PixelSessionTimeline {\n sid: string;\n events: PixelTimelineEvent[];\n}\n\nexport interface PixelPersonTimeline {\n sids: string[];\n events: (PixelTimelineEvent & { sid: string })[];\n}\n\nexport interface PixelAdSpend {\n source: string;\n campaign: string;\n start: number;\n end: number;\n spend: number;\n}\n\nexport interface PixelCreateInput {\n name: string;\n /** Registrable hosts allowed to send events; omit for any origin. */\n allowedHosts?: string[];\n /** Defaults to a random UUID. */\n idempotencyKey?: string;\n}\n\nexport interface PixelPatch {\n name?: string;\n allowedHosts?: string[];\n archived?: boolean;\n /** true makes this the seller's checkout pixel. */\n checkout?: boolean;\n}\n\nexport interface PixelTarget {\n productId?: string;\n pageId?: string;\n}\n\n/** `start`/`end` as epoch ms or ISO 8601; default last 7 days, max 90. */\nexport interface PixelRangeOptions {\n start?: number | string;\n end?: number | string;\n /** Adds a time series to the overview. */\n bucket?: \"hour\" | \"day\";\n /** Adds `prior` KPIs to the overview. */\n compare?: boolean;\n}\n\nexport interface PixelPeopleOptions extends PixelRangeOptions {\n /** People to skip, most recently seen first (default 0). */\n offset?: number;\n /** Page size, 1 to 100 (default 100). */\n limit?: number;\n}\n\nexport interface PixelAdPerformanceOptions extends PixelRangeOptions {\n /** A custom event name (e.g. `purchase`) or a `/path` prefix. */\n conversion: string;\n attribution?: \"first\" | \"last\";\n}\n\nexport interface PixelPersonOptions {\n /** Extra session ids to merge into the timeline (max 20 in total). */\n sids?: string[];\n}\n\nexport interface PixelAdSpendInput {\n source: string;\n campaign?: string;\n start: number | string;\n end: number | string;\n /** 0 clears the campaign's spend for the range. */\n spend: number;\n idempotencyKey?: string;\n}\n\n/*\n * Wire shapes.\n */\n\nexport interface WirePixel {\n id: string;\n key: string;\n name: string;\n allowed_hosts: string[] | null;\n declared_events: string[] | null;\n funnels: PixelFunnelDef[] | null;\n checkout: boolean;\n archived_at: number | null;\n created_at: number;\n}\n\nexport interface WirePixelAttachment {\n pixel_id: string | null;\n product_id: string | null;\n page_id: string | null;\n}\n\ntype WireTimeline = { events: Record<string, unknown>[]; [key: string]: unknown };\n\nexport const fromWirePixel = (wire: WirePixel): Pixel => camelizeKeys(wire) as Pixel;\n\n/** Event prop keys are seller-defined; keep them verbatim. */\nfunction fromWireTimeline<T>(wire: WireTimeline): T {\n const events = (wire.events ?? []).map((event) => ({ ...(camelizeKeys(event) as object), props: event.props ?? null }));\n return { ...(camelizeKeys({ ...wire, events: [] }) as object), events } as T;\n}\n\nconst rangeQuery = (range: PixelRangeOptions) => ({ start: range.start, end: range.end, bucket: range.bucket, compare: range.compare });\nconst targetBody = (target: PixelTarget) => ({ product_id: target.productId, page_id: target.pageId });\n\nexport function pixelsApi(client: PurpleturretClient) {\n const p = (id: string) => `/pixels/${encodeURIComponent(id)}`;\n return {\n list: async (options: { includeArchived?: boolean } = {}): Promise<Page<Pixel>> =>\n fromWirePage(\n await client.request<WirePage<WirePixel>>(\"GET\", \"/pixels\", { query: { include_archived: options.includeArchived } }),\n fromWirePixel,\n ),\n get: async (id: string): Promise<Pixel> => fromWirePixel(await client.request<WirePixel>(\"GET\", p(id))),\n create: async (input: PixelCreateInput): Promise<Pixel> =>\n fromWirePixel(\n await client.request<WirePixel>(\"POST\", \"/pixels\", {\n body: { name: input.name, allowed_hosts: input.allowedHosts },\n idempotencyKey: input.idempotencyKey ?? globalThis.crypto.randomUUID(),\n }),\n ),\n update: async (id: string, patch: PixelPatch): Promise<Pixel> =>\n fromWirePixel(\n await client.request<WirePixel>(\"PATCH\", p(id), {\n body: { name: patch.name, allowed_hosts: patch.allowedHosts, archived: patch.archived, checkout: patch.checkout },\n }),\n ),\n /** Archives the pixel (same as `update(id, { archived: true })`). */\n archive: async (id: string): Promise<Pixel> => fromWirePixel(await client.request<WirePixel>(\"PATCH\", p(id), { body: { archived: true } })),\n /** Exactly one of `productId` / `pageId`. */\n attach: async (id: string, target: PixelTarget): Promise<PixelAttachment> =>\n camelizeKeys(await client.request<WirePixelAttachment>(\"POST\", `${p(id)}/attach`, { body: targetBody(target) })) as PixelAttachment,\n /** Exactly one of `productId` / `pageId`. */\n detach: async (target: PixelTarget): Promise<PixelAttachment> =>\n camelizeKeys(await client.request<WirePixelAttachment>(\"DELETE\", \"/pixels/attachments\", { body: targetBody(target) })) as PixelAttachment,\n overview: async (id: string, range: PixelRangeOptions = {}): Promise<PixelOverview> =>\n camelizeKeys(await client.request(\"GET\", `${p(id)}/overview`, { query: rangeQuery(range) })) as PixelOverview,\n topPages: async (id: string, range: PixelRangeOptions = {}): Promise<PixelTopPages> =>\n camelizeKeys(await client.request(\"GET\", `${p(id)}/top-pages`, { query: rangeQuery(range) })) as PixelTopPages,\n funnels: async (id: string, range: PixelRangeOptions = {}): Promise<PixelFunnels> =>\n camelizeKeys(await client.request(\"GET\", `${p(id)}/funnels`, { query: rangeQuery(range) })) as PixelFunnels,\n adPerformance: async (id: string, options: PixelAdPerformanceOptions): Promise<PixelAdPerformance> =>\n camelizeKeys(\n await client.request(\"GET\", `${p(id)}/ad-performance`, {\n query: { ...rangeQuery(options), conversion: options.conversion, attribution: options.attribution },\n }),\n ) as PixelAdPerformance,\n people: async (id: string, options: PixelPeopleOptions = {}): Promise<PixelPeople> =>\n camelizeKeys(\n await client.request(\"GET\", `${p(id)}/people`, { query: { ...rangeQuery(options), offset: options.offset, limit: options.limit } }),\n ) as PixelPeople,\n session: async (id: string, sid: string): Promise<PixelSessionTimeline> =>\n fromWireTimeline(await client.request<WireTimeline>(\"GET\", `${p(id)}/sessions/${encodeURIComponent(sid)}`)),\n person: async (id: string, sid: string, options: PixelPersonOptions = {}): Promise<PixelPersonTimeline> =>\n fromWireTimeline(\n await client.request<WireTimeline>(\"GET\", `${p(id)}/people/${encodeURIComponent(sid)}`, { query: { sids: options.sids?.join(\",\") } }),\n ),\n setAdSpend: async (id: string, input: PixelAdSpendInput): Promise<PixelAdSpend> =>\n camelizeKeys(\n await client.request(\"PUT\", `${p(id)}/ad-spend`, {\n body: { source: input.source, campaign: input.campaign, start: input.start, end: input.end, spend: input.spend },\n idempotencyKey: input.idempotencyKey,\n }),\n ) as PixelAdSpend,\n };\n}\n","import type { Page } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * hosted pages. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport interface HostedPage {\n id: string;\n slug: string;\n url: string;\n title: string;\n published: boolean;\n disabled: boolean;\n disabledReason: string | null;\n fileCount: number;\n totalBytes: number;\n linkedProductIds: string[];\n pixelId: string | null;\n submissionCount: number;\n notifyOnSubmission: boolean;\n addToLeads: boolean;\n spaFallback: boolean;\n customDomain: { hostname: string; status: \"pending\" | \"active\" | \"error\" | null } | null;\n lastDeployedAt: number | null;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface PageFileInput {\n /** Site-relative path (`index.html`, `assets/app.js`). */\n path: string;\n /** Convex storage id returned by `client.uploads.put`. */\n storageId: string;\n size: number;\n}\n\nexport interface PageFile {\n path: string;\n size: number;\n contentType: string;\n}\n\nexport interface PageSlugAvailability {\n slug: string;\n available: boolean;\n reason: string | null;\n}\n\nexport interface PageCreateOptions {\n title: string;\n slug: string;\n files: PageFileInput[];\n pixelId?: string;\n /** Defaults to a random UUID. */\n idempotencyKey?: string;\n}\n\nexport interface PageUpdateOptions {\n title?: string;\n slug?: string;\n published?: boolean;\n /** Seller's own products; first 5 kept, `[]` clears. */\n linkedProductIds?: string[];\n notifyOnSubmission?: boolean;\n addToLeads?: boolean;\n}\n\nexport interface PageDeleteResult {\n /** `true` when the page had submissions and was archived instead of hard-deleted. */\n archived: boolean;\n page: HostedPage;\n}\n\nexport interface PageFormSubmission {\n id: string;\n pageId: string;\n fields: { name: string; value: string }[];\n submitterEmail: string | null;\n referrer: string | null;\n createdAt: number;\n}\n\nexport interface PageVisitSummary {\n start: number;\n end: number;\n visits: number;\n visitors: number;\n days: { day: string; visits: number; visitors: number }[];\n}\n\nexport interface PageClickSummary {\n start: number;\n end: number;\n clicks: number;\n visitors: number;\n days: { day: string; clicks: number }[];\n topTargets: { elementKey: string; label: string; pathname: string; clicks: number; visitors: number }[];\n}\n\nexport interface PageRangeOptions {\n /** Epoch ms or ISO 8601; default 7 days ago. */\n start?: string | number;\n /** Epoch ms or ISO 8601; default now. Range capped at 90 days. */\n end?: string | number;\n}\n\nexport type WireHostedPage = Record<string, unknown>;\nexport type WirePageFile = Record<string, unknown>;\nexport type WirePageFormSubmission = Record<string, unknown>;\n\nconst toWireFiles = (files: PageFileInput[]) => files.map((f) => ({ path: f.path, storage_id: f.storageId, size: f.size }));\nconst fromWireHostedPage = (wire: WireHostedPage) => camelizeKeys(wire) as HostedPage;\nconst fromWirePageFile = (wire: WirePageFile) => camelizeKeys(wire) as PageFile;\nconst fromWireSubmission = (wire: WirePageFormSubmission) => camelizeKeys(wire) as PageFormSubmission;\nconst CONTENT_TYPES: Record<string, string> = {\n html: \"text/html\",\n css: \"text/css\",\n js: \"text/javascript\",\n json: \"application/json\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n svg: \"image/svg+xml\",\n webp: \"image/webp\",\n ico: \"image/x-icon\",\n txt: \"text/plain\",\n woff2: \"font/woff2\",\n};\n\n/** Content type for a site file by extension; `application/octet-stream` when unknown. */\nexport const contentTypeFor = (path: string): string => CONTENT_TYPES[path.split(\".\").pop()?.toLowerCase() ?? \"\"] ?? \"application/octet-stream\";\nconst pagePath = (id: string, suffix = \"\") => `/pages/${encodeURIComponent(id)}${suffix}`;\n\nexport function pagesApi(client: PurpleturretClient) {\n return {\n /** Live, seller-managed pages, newest first (not paginated). */\n list: async (): Promise<Page<HostedPage>> => fromWirePage(await client.request<WirePage<WireHostedPage>>(\"GET\", \"/pages\"), fromWireHostedPage),\n get: async (id: string): Promise<HostedPage> => fromWireHostedPage(await client.request<WireHostedPage>(\"GET\", pagePath(id))),\n files: async (id: string): Promise<Page<PageFile>> =>\n fromWirePage(await client.request<WirePage<WirePageFile>>(\"GET\", pagePath(id, \"/files\")), fromWirePageFile),\n slugAvailable: async (slug: string, options: { exclude?: string } = {}): Promise<PageSlugAvailability> =>\n camelizeKeys(\n await client.request(\"GET\", \"/pages/slug-available\", { query: { slug, exclude_page_id: options.exclude } }),\n ) as PageSlugAvailability,\n /** Files must already be uploaded (`client.uploads.put`) and include a root `index.html`. */\n create: async (options: PageCreateOptions): Promise<HostedPage> =>\n fromWireHostedPage(\n await client.request<WireHostedPage>(\"POST\", \"/pages\", {\n body: { title: options.title, slug: options.slug, files: toWireFiles(options.files), pixel_id: options.pixelId },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ),\n /** Replaces the whole file set; old blobs are deleted. */\n replaceFiles: async (id: string, files: PageFileInput[]): Promise<HostedPage & { files: PageFile[] }> =>\n camelizeKeys(await client.request(\"PUT\", pagePath(id, \"/files\"), { body: { files: toWireFiles(files) } })) as HostedPage & {\n files: PageFile[];\n },\n update: async (id: string, patch: PageUpdateOptions): Promise<HostedPage> =>\n fromWireHostedPage(\n await client.request<WireHostedPage>(\"PATCH\", pagePath(id), {\n body: {\n title: patch.title,\n slug: patch.slug,\n published: patch.published,\n linked_product_ids: patch.linkedProductIds,\n notify_on_submission: patch.notifyOnSubmission,\n add_to_leads: patch.addToLeads,\n },\n }),\n ),\n /** Archives instead of deleting when the page has form submissions. */\n delete: async (id: string): Promise<PageDeleteResult> => {\n const wire = await client.request<{ archived: boolean; page: WireHostedPage }>(\"DELETE\", pagePath(id));\n return { archived: Boolean(wire.archived), page: fromWireHostedPage(wire.page) };\n },\n submissions: async (id: string, options: { cursor?: string; limit?: number } = {}): Promise<Page<PageFormSubmission>> =>\n fromWirePage(\n await client.request<WirePage<WirePageFormSubmission>>(\"GET\", pagePath(id, \"/submissions\"), {\n query: { cursor: options.cursor, limit: options.limit },\n }),\n fromWireSubmission,\n ),\n visits: async (id: string, options: PageRangeOptions = {}): Promise<PageVisitSummary> =>\n camelizeKeys(await client.request(\"GET\", pagePath(id, \"/visits\"), { query: { start: options.start, end: options.end } })) as PageVisitSummary,\n clicks: async (id: string, options: PageRangeOptions = {}): Promise<PageClickSummary> =>\n camelizeKeys(await client.request(\"GET\", pagePath(id, \"/clicks\"), { query: { start: options.start, end: options.end } })) as PageClickSummary,\n };\n}\n","import type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys } from \"../wire\";\n\n/*\n * Tracking: account-level Meta pixel / Conversions API + Google Analytics defaults, with per-product and per-page overrides.\n * The Conversions API token is write-only: send it in `conversionsApiToken`, read presence via `hasConversionsApiToken`.\n */\n\nexport type TrackingMode = \"inherit\" | \"custom\" | \"disabled\";\nexport type TrackingEventsMode = \"inherit\" | \"custom\";\n\nexport interface MetaEvents {\n viewContent: boolean;\n initiateCheckout: boolean;\n purchase: boolean;\n}\n\nexport interface GaEvents {\n viewItem: boolean;\n beginCheckout: boolean;\n purchase: boolean;\n}\n\nexport interface AccountTracking {\n meta: { enabled: boolean; pixelId: string | null; hasConversionsApiToken: boolean; events: MetaEvents };\n googleAnalytics: { enabled: boolean; measurementId: string | null; events: GaEvents };\n}\n\nexport interface AccountTrackingInput {\n /** Omit to leave Meta untouched; `enabled: false` deletes the account pixel and its token. */\n meta?: { enabled: boolean; pixelId?: string; conversionsApiToken?: string | null; events?: Partial<MetaEvents> };\n googleAnalytics?: { enabled: boolean; measurementId?: string; events?: Partial<GaEvents> };\n}\n\nexport interface ProductTracking {\n meta: {\n mode: TrackingMode;\n pixelId: string | null;\n hasConversionsApiToken: boolean;\n eventsMode: TrackingEventsMode;\n events: MetaEvents;\n inherited: { enabled: boolean; pixelId: string | null; hasConversionsApiToken: boolean; events: MetaEvents };\n };\n googleAnalytics: {\n mode: TrackingMode;\n measurementId: string | null;\n eventsMode: TrackingEventsMode;\n events: GaEvents;\n inherited: { enabled: boolean; measurementId: string | null; events: GaEvents };\n };\n}\n\nexport interface ProductTrackingInput {\n meta?: {\n mode: TrackingMode;\n pixelId?: string;\n /** Omit/null keeps the stored token, \"\" clears it; only stored when `mode` is \"custom\". */\n conversionsApiToken?: string | null;\n eventsMode?: TrackingEventsMode;\n events?: Partial<MetaEvents>;\n };\n googleAnalytics?: { mode: TrackingMode; measurementId?: string; eventsMode?: TrackingEventsMode; events?: Partial<GaEvents> };\n}\n\nexport interface PageTracking {\n meta: {\n mode: TrackingMode;\n pixelId: string | null;\n hasConversionsApiToken: boolean;\n events: { lead: boolean };\n /** A different pixel for URLs under a path prefix; the longest matching prefix wins. */\n paths: { path: string; pixelId: string; hasConversionsApiToken: boolean }[];\n inherited: { enabled: boolean; pixelId: string | null; hasConversionsApiToken: boolean };\n };\n googleAnalytics: {\n mode: TrackingMode;\n measurementId: string | null;\n events: { generateLead: boolean };\n inherited: { enabled: boolean; measurementId: string | null };\n };\n}\n\nexport interface PageTrackingInput {\n meta?: {\n mode: TrackingMode;\n pixelId?: string;\n conversionsApiToken?: string | null;\n events?: { lead?: boolean };\n /** Omit to keep the stored path overrides; `[]` clears them. An omitted token keeps the one stored for that path. */\n paths?: { path: string; pixelId: string; conversionsApiToken?: string }[];\n };\n googleAnalytics?: { mode: TrackingMode; measurementId?: string; events?: { generateLead?: boolean } };\n}\n\n/** camelCase → snake_case keys, deeply. Wire rejects unknown keys, so every input key must round-trip exactly. */\nfunction snakeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(snakeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n out[key.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`)] = snakeKeys(entry);\n }\n return out;\n }\n return value;\n}\n\nexport function trackingApi(client: PurpleturretClient) {\n return {\n get: async (): Promise<AccountTracking> => camelizeKeys(await client.request(\"GET\", \"/tracking\")) as AccountTracking,\n set: async (input: AccountTrackingInput): Promise<AccountTracking> =>\n camelizeKeys(await client.request(\"PUT\", \"/tracking\", { body: snakeKeys(input) })) as AccountTracking,\n getProduct: async (idOrKey: string): Promise<ProductTracking> =>\n camelizeKeys(await client.request(\"GET\", `/products/${encodeURIComponent(idOrKey)}/tracking`)) as ProductTracking,\n setProduct: async (idOrKey: string, input: ProductTrackingInput): Promise<ProductTracking> =>\n camelizeKeys(await client.request(\"PUT\", `/products/${encodeURIComponent(idOrKey)}/tracking`, { body: snakeKeys(input) })) as ProductTracking,\n getPage: async (id: string): Promise<PageTracking> =>\n camelizeKeys(await client.request(\"GET\", `/pages/${encodeURIComponent(id)}/tracking`)) as PageTracking,\n setPage: async (id: string, input: PageTrackingInput): Promise<PageTracking> =>\n camelizeKeys(await client.request(\"PUT\", `/pages/${encodeURIComponent(id)}/tracking`, { body: snakeKeys(input) })) as PageTracking,\n };\n}\n","import type { Page } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * custom domains. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport type DomainStatus = \"pending\" | \"active\" | \"error\";\nexport type DomainRoutingType = \"A\" | \"CNAME\";\n\nexport interface DnsRecord {\n purpose: \"routing\" | \"verification\";\n type: string;\n name: string;\n value: string;\n}\n\nexport interface Domain {\n id: string;\n hostname: string;\n apex: string | null;\n status: DomainStatus;\n routingType: DomainRoutingType | null;\n requestedRoutingType: DomainRoutingType | null;\n verified: boolean;\n dnsConfigured: boolean;\n dnsRecords: DnsRecord[];\n lastError: string | null;\n lastCheckedAt: number | null;\n activatedAt: number | null;\n pageId: string | null;\n productIds: string[];\n defaultProductId: string | null;\n createdAt: number;\n}\n\nexport interface DomainAddOptions {\n hostname: string;\n /** DNS record shape hint; omitted → provider picks (CNAME for subdomains, A for apex). */\n routingType?: DomainRoutingType;\n /** Sent as `Idempotency-Key`; generated when absent. */\n idempotencyKey?: string;\n}\n\nexport interface DomainUpdateOptions {\n /** Page served at `/`; `null` detaches. */\n pageId?: string | null;\n /** Replaces the checkout allowlist (max 50). */\n productIds?: string[];\n /** `/` redirect when no page is attached; `null` clears. */\n defaultProductId?: string | null;\n}\n\nexport type WireDomain = Record<string, unknown>;\n\nexport const fromWireDomain = (wire: WireDomain): Domain => camelizeKeys(wire) as Domain;\n\nexport function domainsApi(client: PurpleturretClient) {\n const path = (id: string) => `/domains/${encodeURIComponent(id)}`;\n return {\n list: async (): Promise<Page<Domain>> => fromWirePage(await client.request<WirePage<WireDomain>>(\"GET\", \"/domains\"), fromWireDomain),\n get: async (id: string): Promise<Domain> => fromWireDomain(await client.request<WireDomain>(\"GET\", path(id))),\n add: async (options: DomainAddOptions): Promise<Domain> =>\n fromWireDomain(\n await client.request<WireDomain>(\"POST\", \"/domains\", {\n body: { hostname: options.hostname, routing_type: options.routingType },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ),\n verify: async (id: string): Promise<Domain> => fromWireDomain(await client.request<WireDomain>(\"POST\", `${path(id)}/verify`)),\n update: async (id: string, options: DomainUpdateOptions): Promise<Domain> =>\n fromWireDomain(\n await client.request<WireDomain>(\"PATCH\", path(id), {\n body: { page_id: options.pageId, product_ids: options.productIds, default_product_id: options.defaultProductId },\n }),\n ),\n remove: async (id: string): Promise<Domain> => fromWireDomain(await client.request<WireDomain>(\"DELETE\", path(id))),\n };\n}\n","import type { PurpleturretClient } from \"../client\";\nimport type { Page } from \"../../types\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * webhook endpoints + integration groups + the read-only API key list. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport interface WebhookDelivery {\n status: \"pending\" | \"success\" | \"failed\";\n at: number;\n}\n\nexport interface WebhookEndpoint {\n id: string;\n groupKey: string;\n url: string;\n enabled: boolean;\n description: string | null;\n createdAt: number;\n updatedAt: number;\n lastDelivery: WebhookDelivery | null;\n}\n\n/** Only `webhooks.create` returns `secret`; store it on receipt, it is never returned again. */\nexport interface CreatedWebhookEndpoint extends WebhookEndpoint {\n secret: string;\n}\n\nexport interface WebhookCreateOptions {\n groupKey: string;\n /** HTTPS URL. */\n url: string;\n /** Up to 80 chars. */\n description?: string;\n /** Sent as `Idempotency-Key`; defaults to a random UUID. */\n idempotencyKey?: string;\n}\n\nexport interface WebhookUpdateOptions {\n url?: string;\n enabled?: boolean;\n /** `\"\"` clears it. */\n description?: string;\n}\n\nexport interface WebhookTestResult {\n queued: true;\n deliveryId: string;\n}\n\nexport interface IntegrationGroup {\n id: string;\n key: string;\n name: string;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface ApiKey {\n id: string;\n prefix: string;\n name: string | null;\n scopes: string[];\n createdAt: number;\n lastUsedAt: number | null;\n revokedAt: number | null;\n}\n\nexport type WireWebhookEndpoint = Record<string, unknown>;\nexport type WireIntegrationGroup = Record<string, unknown>;\nexport type WireApiKey = Record<string, unknown>;\n\nconst fromWireWebhook = (wire: WireWebhookEndpoint) => camelizeKeys(wire) as WebhookEndpoint;\nconst fromWireGroup = (wire: WireIntegrationGroup) => camelizeKeys(wire) as IntegrationGroup;\nconst fromWireApiKey = (wire: WireApiKey) => camelizeKeys(wire) as ApiKey;\n\nexport function webhooksApi(client: PurpleturretClient) {\n const path = (id: string) => `/webhooks/${encodeURIComponent(id)}`;\n return {\n list: async (): Promise<Page<WebhookEndpoint>> =>\n fromWirePage(await client.request<WirePage<WireWebhookEndpoint>>(\"GET\", \"/webhooks\"), fromWireWebhook),\n create: async (options: WebhookCreateOptions): Promise<CreatedWebhookEndpoint> =>\n camelizeKeys(\n await client.request<WireWebhookEndpoint>(\"POST\", \"/webhooks\", {\n body: { group_key: options.groupKey, url: options.url, description: options.description },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ) as CreatedWebhookEndpoint,\n update: async (id: string, patch: WebhookUpdateOptions): Promise<WebhookEndpoint> =>\n fromWireWebhook(await client.request<WireWebhookEndpoint>(\"PATCH\", path(id), { body: patch })),\n /** Also drops the endpoint's pending deliveries. Returns the deleted row. */\n delete: async (id: string): Promise<WebhookEndpoint> => fromWireWebhook(await client.request<WireWebhookEndpoint>(\"DELETE\", path(id))),\n /** Queues a `test.event` delivery to the endpoint's URL (even when disabled); the HTTP call happens asynchronously. */\n test: async (id: string): Promise<WebhookTestResult> =>\n camelizeKeys(await client.request<Record<string, unknown>>(\"POST\", `${path(id)}/test`)) as WebhookTestResult,\n };\n}\n\nexport function groupsApi(client: PurpleturretClient) {\n const path = (key: string) => `/groups/${encodeURIComponent(key)}`;\n return {\n list: async (): Promise<Page<IntegrationGroup>> =>\n fromWirePage(await client.request<WirePage<WireIntegrationGroup>>(\"GET\", \"/groups\"), fromWireGroup),\n create: async (options: { key: string; name: string }): Promise<IntegrationGroup> =>\n fromWireGroup(await client.request<WireIntegrationGroup>(\"POST\", \"/groups\", { body: options })),\n update: async (key: string, patch: { name: string }): Promise<IntegrationGroup> =>\n fromWireGroup(await client.request<WireIntegrationGroup>(\"PATCH\", path(key), { body: patch })),\n /** Cascades: deletes the group's webhooks, deliveries and events, and clears its products' group/tier. Returns the deleted row. */\n delete: async (key: string): Promise<IntegrationGroup> => fromWireGroup(await client.request<WireIntegrationGroup>(\"DELETE\", path(key))),\n };\n}\n\nexport function keysApi(client: PurpleturretClient) {\n return {\n /** Seller API keys on the account (never the secret hash; hosting keys are not listed). */\n list: async (options: { includeRevoked?: boolean } = {}): Promise<Page<ApiKey>> =>\n fromWirePage(\n await client.request<WirePage<WireApiKey>>(\"GET\", \"/account/keys\", { query: { include_revoked: options.includeRevoked } }),\n fromWireApiKey,\n ),\n };\n}\n","export interface PurpleturretApiErrorInit {\n status: number;\n code: string;\n message: string;\n requestId?: string | null;\n details?: unknown;\n retryAfter?: number | null;\n}\n\n/** A non-2xx response from the Purpleturret API. */\nexport class PurpleturretApiError extends Error {\n override readonly name = \"PurpleturretApiError\";\n readonly status: number;\n readonly code: string;\n readonly requestId: string | null;\n readonly details: unknown;\n /** Seconds to wait before retrying, from `Retry-After` (or `reset_at` on legacy envelopes). */\n readonly retryAfter: number | null;\n\n constructor(init: PurpleturretApiErrorInit) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId ?? null;\n this.details = init.details;\n this.retryAfter = init.retryAfter ?? null;\n }\n\n /**\n * Build an error from a response body. Accepts the structured envelope\n * `{ error: { code, message, request_id, details } }` as well as the legacy entitlements envelope\n * `{ error: \"code\", ...extra }`.\n */\n static fromResponse(status: number, body: unknown, retryAfterHeader?: string | null): PurpleturretApiError {\n const retryAfter = parseRetryAfter(retryAfterHeader);\n const record = body && typeof body === \"object\" && !Array.isArray(body) ? (body as Record<string, unknown>) : null;\n const envelope = record?.error;\n\n if (envelope && typeof envelope === \"object\") {\n const err = envelope as Record<string, unknown>;\n const code = typeof err.code === \"string\" && err.code ? err.code : `http_${status}`;\n const message = typeof err.message === \"string\" && err.message ? err.message : defaultMessage(status, code);\n const requestId = typeof err.request_id === \"string\" ? err.request_id : typeof err.requestId === \"string\" ? err.requestId : null;\n return new PurpleturretApiError({ status, code, message, requestId, details: err.details, retryAfter });\n }\n\n if (typeof envelope === \"string\" && record) {\n const { error: _code, message: rawMessage, request_id: requestId, ...rest } = record;\n const code = envelope || `http_${status}`;\n const message = typeof rawMessage === \"string\" && rawMessage ? rawMessage : defaultMessage(status, code);\n const resetAt = typeof rest.reset_at === \"number\" ? rest.reset_at : null;\n const legacyRetryAfter = retryAfter ?? (resetAt !== null ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)) : null);\n return new PurpleturretApiError({\n status,\n code,\n message,\n requestId: typeof requestId === \"string\" ? requestId : null,\n details: Object.keys(rest).length > 0 ? rest : undefined,\n retryAfter: legacyRetryAfter,\n });\n }\n\n const text = typeof body === \"string\" ? body.trim().slice(0, 300) : \"\";\n return new PurpleturretApiError({\n status,\n code: `http_${status}`,\n message: text || defaultMessage(status, `http_${status}`),\n details: record ?? undefined,\n retryAfter,\n });\n }\n}\n\n/** The request never produced an HTTP response (DNS, connection refused, timeout, aborted). */\nexport class PurpleturretNetworkError extends Error {\n override readonly name = \"PurpleturretNetworkError\";\n readonly url: string;\n readonly timedOut: boolean;\n override readonly cause: unknown;\n\n constructor(url: string, cause: unknown, timedOut: boolean) {\n super(timedOut ? `Request to ${url} timed out` : `Request to ${url} failed: ${describeCause(cause)}`);\n this.url = url;\n this.cause = cause;\n this.timedOut = timedOut;\n }\n}\n\nexport function isTimeoutError(cause: unknown): boolean {\n return Boolean(cause && typeof cause === \"object\" && \"name\" in cause && (cause as { name?: unknown }).name === \"TimeoutError\");\n}\n\nfunction describeCause(cause: unknown): string {\n if (cause && typeof cause === \"object\") {\n const inner = (cause as { cause?: unknown }).cause;\n if (inner && typeof inner === \"object\" && \"message\" in inner && typeof (inner as { message?: unknown }).message === \"string\") {\n const code = (inner as { code?: unknown }).code;\n return typeof code === \"string\" ? `${code} (${(inner as { message: string }).message})` : (inner as { message: string }).message;\n }\n if (\"message\" in cause && typeof (cause as { message?: unknown }).message === \"string\") return (cause as { message: string }).message;\n }\n return String(cause);\n}\n\nfunction defaultMessage(status: number, code: string): string {\n switch (status) {\n case 401:\n return \"The API key was rejected\";\n case 403:\n return \"The API key is not allowed to perform this operation\";\n case 404:\n return \"The requested resource was not found\";\n case 409:\n return \"The request conflicts with the current state\";\n case 422:\n return \"The request was rejected as invalid\";\n case 429:\n return \"Too many requests; slow down and retry\";\n default:\n return status >= 500 ? `The Purpleturret API returned ${status}` : `Request failed with ${code}`;\n }\n}\n\nexport function parseRetryAfter(header: string | null | undefined): number | null {\n if (!header) return null;\n const trimmed = header.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return null;\n return Math.max(0, Math.ceil((when - Date.now()) / 1000));\n}\n","import type { PurpleturretClient } from \"../client\";\nimport type { DeliveryFileRef } from \"../../types\";\nimport { PurpleturretApiError } from \"../errors\";\nimport { camelizeKeys } from \"../wire\";\n\n/*\n * Upload URLs (Convex storage for logos/page files, R2 for delivery files). `index.ts` re-exports the file.\n */\n\nexport interface UploadUrl {\n /** POST the raw bytes here with the file's Content-Type; the response is `{ storageId }`. */\n uploadUrl: string;\n /** Epoch ms; URLs last 1 hour. */\n expiresAt: number;\n}\n\nexport interface DeliveryFileUploadOptions {\n fileName: string;\n /** Defaults to application/octet-stream. */\n contentType?: string;\n fileSize: number;\n}\n\nexport interface DeliveryFileUpload {\n /** PUT the raw bytes here sending exactly `headers`. */\n uploadUrl: string;\n objectKey: string;\n headers: Record<string, string>;\n /** Seconds. */\n expiresIn: number;\n}\n\nexport type UploadData = Blob | Uint8Array | ArrayBuffer;\n\nconst byteLength = (data: UploadData) => (data instanceof Blob ? data.size : data.byteLength);\n\nexport function uploadsApi(client: PurpleturretClient) {\n const send = async (method: string, url: string, headers: Record<string, string>, data: UploadData) => {\n // `client.fetch` is read per call: this namespace is built before the constructor assigns it.\n const response = await client.fetch(url, { method, headers, body: data as RequestInit[\"body\"] });\n if (!response.ok) {\n throw PurpleturretApiError.fromResponse(response.status, await response.text().catch(() => \"\"), response.headers.get(\"retry-after\"));\n }\n return response;\n };\n const api = {\n /** Signed Convex upload URL for logos and page files. */\n create: async (): Promise<UploadUrl> => camelizeKeys(await client.request(\"POST\", \"/uploads\")) as UploadUrl,\n /** Signed R2 upload for a product delivery file. */\n deliveryFile: async (options: DeliveryFileUploadOptions): Promise<DeliveryFileUpload> =>\n camelizeKeys(\n await client.request(\"POST\", \"/uploads/delivery-file\", {\n body: { file_name: options.fileName, content_type: options.contentType, file_size: options.fileSize },\n }),\n ) as DeliveryFileUpload,\n /** Uploads bytes to Convex storage and returns the `storageId` (for `theme.logoStorageId` and page files). */\n put: async (data: UploadData, contentType: string): Promise<string> => {\n const { uploadUrl } = await api.create();\n const response = await send(\"POST\", uploadUrl, { \"content-type\": contentType }, data);\n return ((await response.json()) as { storageId: string }).storageId;\n },\n /** Uploads a delivery file to R2 and returns the descriptor for `products.setDelivery({ method: \"file\", ... })`. */\n putDeliveryFile: async (data: UploadData, options: { fileName: string; contentType?: string }): Promise<Required<DeliveryFileRef>> => {\n const fileSize = byteLength(data);\n const upload = await api.deliveryFile({ fileName: options.fileName, contentType: options.contentType, fileSize });\n await send(\"PUT\", upload.uploadUrl, upload.headers, data);\n const contentType = upload.headers[\"Content-Type\"] ?? options.contentType ?? \"application/octet-stream\";\n return { objectKey: upload.objectKey, fileName: options.fileName, contentType, fileSize };\n },\n };\n return api;\n}\n","import type {\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CustomerSelector,\n Entitlement,\n LedgerEntry,\n DeliveryInput,\n Page,\n Product,\n ProductCreateInput,\n ProductInput,\n ProductUpdateInput,\n VisitsSummary,\n} from \"../types\";\nimport { SDK_VERSION } from \"../version\";\nimport { type AccountDetails, accountApi, fromWireAccountDetails, supportApi, type WireAccountDetails } from \"./areas/account\";\nimport { customersApi, leadsApi, ordersApi, subscriptionsApi } from \"./areas/orders\";\nimport { pixelsApi } from \"./areas/pixels\";\nimport { pagesApi } from \"./areas/pages\";\nimport { trackingApi } from \"./areas/tracking\";\nimport { domainsApi } from \"./areas/domains\";\nimport { groupsApi, keysApi, webhooksApi } from \"./areas/webhooks\";\nimport { uploadsApi } from \"./areas/uploads\";\nimport { PurpleturretApiError, PurpleturretNetworkError, isTimeoutError } from \"./errors\";\nimport {\n fromWireConfigGetResult,\n fromWireConfigPushResult,\n fromWireCreditAdjust,\n fromWireCreditBalances,\n fromWireCreditConsume,\n fromWireEntitlement,\n fromWireLedgerEntry,\n fromWirePage,\n fromWireProduct,\n camelizeKeys,\n snakeizeKeys,\n toWireProduct,\n type WireConfigGetResult,\n type WireConfigPushResult,\n type WireCreditAdjustResult,\n type WireCreditBalancesResult,\n type WireCreditConsumeResult,\n type WireEntitlement,\n type WireLedgerEntry,\n type WirePage,\n type WireProduct,\n} from \"./wire\";\n\nexport const DEFAULT_BASE_URL = \"https://api.purpleturret.com\";\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\nexport interface PurpleturretClientOptions {\n /** Seller API key (`pt_sk_…`). */\n apiKey: string;\n /** API origin without `/v1`. Defaults to `https://api.purpleturret.com`; local dev uses `http://localhost:3001/api`. */\n baseUrl?: string;\n /** Custom fetch implementation (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout. Defaults to 30 s. */\n timeoutMs?: number;\n /** Extra `User-Agent` value; the SDK version is appended. */\n userAgent?: string;\n}\n\nexport interface ConfigPushOptions {\n products: ProductInput[];\n /** Archive keyed products that are missing from `products`. */\n prune?: boolean;\n /** Compute the plan without applying it. */\n dryRun?: boolean;\n /** Sent as `Idempotency-Key`; reuse it when retrying a failed apply. */\n idempotencyKey?: string;\n}\n\nexport interface ProductListOptions {\n cursor?: string;\n limit?: number;\n includeArchived?: boolean;\n}\n\nexport type CreditBalancesOptions = CustomerSelector & { meter?: string };\n\nexport type CreditConsumeOptions = CustomerSelector & {\n meter: string;\n amount: number;\n /** Required. Reusing a key replays the original result instead of consuming twice. */\n idempotencyKey: string;\n note?: string;\n};\n\nexport type CreditAdjustOptions = CustomerSelector & {\n meter: string;\n /** Signed amount: positive grants, negative removes. */\n amount: number;\n idempotencyKey?: string;\n note?: string;\n};\n\nexport type CreditLedgerOptions = CustomerSelector & { cursor?: string; limit?: number };\n\nexport type EntitlementOptions = CustomerSelector & { groupKey: string };\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n idempotencyKey?: string;\n /** Statuses (besides 2xx) whose bodies are returned instead of thrown. */\n acceptStatuses?: number[];\n}\n\nexport class PurpleturretClient {\n readonly baseUrl: string;\n readonly timeoutMs: number;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n private readonly userAgent: string;\n\n constructor(options: PurpleturretClientOptions) {\n if (!options || typeof options.apiKey !== \"string\" || !options.apiKey.trim()) {\n throw new TypeError(\"PurpleturretClient: apiKey is required\");\n }\n this.apiKey = options.apiKey.trim();\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).trim().replace(/\\/+$/, \"\");\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") throw new TypeError(\"PurpleturretClient: no fetch implementation available; pass options.fetch\");\n this.fetchImpl = fetchImpl;\n const sdkAgent = `purpleturret-sdk/${SDK_VERSION}`;\n this.userAgent = options.userAgent ? `${options.userAgent} ${sdkAgent}` : sdkAgent;\n }\n\n /** The fetch used for API calls (also for raw byte uploads to signed URLs). */\n get fetch(): typeof fetch {\n return this.fetchImpl;\n }\n\n /** Absolute URL for an API path such as `/config`. */\n url(path: string, query?: RequestOptions[\"query\"]): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n let url = `${this.baseUrl}/v1${normalizedPath}`;\n if (query) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n params.set(key, String(value));\n }\n const qs = params.toString();\n if (qs) url += `?${qs}`;\n }\n return url;\n }\n\n readonly account = {\n get: async (): Promise<AccountDetails> => fromWireAccountDetails(await this.request<WireAccountDetails>(\"GET\", \"/account\")),\n ...accountApi(this),\n keys: keysApi(this),\n };\n\n readonly config = {\n get: async (): Promise<ConfigGetResult> => fromWireConfigGetResult(await this.request<WireConfigGetResult>(\"GET\", \"/config\")),\n push: async (options: ConfigPushOptions): Promise<ConfigPushResult> => {\n const body: Record<string, unknown> = { products: options.products.map(toWireProduct) };\n if (options.prune !== undefined) body.prune = options.prune;\n if (options.dryRun !== undefined) body.dry_run = options.dryRun;\n const wire = await this.request<WireConfigPushResult>(\"PUT\", \"/config\", {\n body,\n idempotencyKey: options.idempotencyKey,\n // A conflict returns the full plan with a 409; surface it as a result so callers can render it.\n acceptStatuses: [409],\n });\n return fromWireConfigPushResult(wire);\n },\n };\n\n readonly products = {\n list: async (options: ProductListOptions = {}): Promise<Page<Product>> =>\n fromWirePage(\n await this.request<WirePage<WireProduct>>(\"GET\", \"/products\", {\n query: { cursor: options.cursor, limit: options.limit, include_archived: options.includeArchived },\n }),\n fromWireProduct,\n ),\n get: async (idOrKey: string): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"GET\", `/products/${encodeURIComponent(idOrKey)}`)),\n /** POST /products. Sends an `Idempotency-Key` (random unless given). */\n create: async (input: ProductCreateInput, options: { idempotencyKey?: string } = {}): Promise<Product> =>\n fromWireProduct(\n await this.request<WireProduct>(\"POST\", \"/products\", {\n body: snakeizeKeys(input),\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ),\n /** PATCH /products/{id|key}: only the given fields change. */\n update: async (idOrKey: string, patch: ProductUpdateInput): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"PATCH\", `/products/${encodeURIComponent(idOrKey)}`, { body: snakeizeKeys(patch) })),\n /** PUT /products/{key}: create or update one config-managed product (single-product `config.push`). */\n upsert: async (key: string, input: Omit<ProductInput, \"key\">, options: { idempotencyKey?: string } = {}): Promise<Product> =>\n fromWireProduct(\n await this.request<WireProduct>(\"PUT\", `/products/${encodeURIComponent(key)}`, {\n body: toWireProduct({ ...input, key }),\n idempotencyKey: options.idempotencyKey,\n }),\n ),\n /** File entries come from `uploads.putDeliveryFile`. */\n setDelivery: async (idOrKey: string, delivery: DeliveryInput): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"PUT\", `/products/${encodeURIComponent(idOrKey)}/delivery`, { body: snakeizeKeys(delivery) })),\n /** Copy checkout + theme settings from another product (`from` is an id or key). */\n copyStyles: async (idOrKey: string, options: { from: string }): Promise<Product> =>\n fromWireProduct(\n await this.request<WireProduct>(\"POST\", `/products/${encodeURIComponent(idOrKey)}/copy-styles`, { body: { from: options.from } }),\n ),\n visits: async (idOrKey: string): Promise<VisitsSummary> =>\n camelizeKeys(await this.request(\"GET\", `/products/${encodeURIComponent(idOrKey)}/visits`)) as VisitsSummary,\n /** Archives the product (never hard-deletes). */\n archive: async (idOrKey: string): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"DELETE\", `/products/${encodeURIComponent(idOrKey)}`)),\n };\n\n readonly credits = {\n balances: async (options: CreditBalancesOptions): Promise<CreditBalancesResult> =>\n fromWireCreditBalances(\n await this.request<WireCreditBalancesResult>(\"GET\", \"/credits/balances\", {\n query: { ...customerQuery(options), meter: options.meter },\n }),\n ),\n consume: async (options: CreditConsumeOptions): Promise<CreditConsumeResult> => {\n if (!options.idempotencyKey) throw new TypeError(\"credits.consume: idempotencyKey is required\");\n return fromWireCreditConsume(\n await this.request<WireCreditConsumeResult>(\"POST\", \"/credits/consume\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n );\n },\n adjust: async (options: CreditAdjustOptions): Promise<CreditAdjustResult> =>\n fromWireCreditAdjust(\n await this.request<WireCreditAdjustResult>(\"POST\", \"/credits/adjust\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n ),\n ledger: async (options: CreditLedgerOptions): Promise<Page<LedgerEntry>> =>\n fromWirePage(\n await this.request<WirePage<WireLedgerEntry>>(\"GET\", \"/credits/ledger\", {\n query: { ...customerQuery(options), cursor: options.cursor, limit: options.limit },\n }),\n fromWireLedgerEntry,\n ),\n };\n\n readonly orders = ordersApi(this);\n readonly subscriptions = subscriptionsApi(this);\n readonly customers = customersApi(this);\n readonly leads = leadsApi(this);\n readonly pixels = pixelsApi(this);\n readonly pages = pagesApi(this);\n readonly tracking = trackingApi(this);\n readonly domains = domainsApi(this);\n readonly webhooks = webhooksApi(this);\n readonly groups = groupsApi(this);\n readonly support = supportApi(this);\n readonly uploads = uploadsApi(this);\n\n readonly entitlements = {\n /** Resolves with `hasAccess: false` (rather than throwing) when the customer has no subscription. */\n get: async (options: EntitlementOptions): Promise<Entitlement> =>\n fromWireEntitlement(\n await this.request<WireEntitlement>(\"GET\", \"/entitlements\", {\n query: { group_key: options.groupKey, ...customerQuery(options) },\n acceptStatuses: [404],\n }),\n ),\n };\n\n /** Low-level request used by the per-area namespaces; prefer the typed namespaces. @internal */\n async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const url = this.url(path, options.query);\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.apiKey}`,\n accept: \"application/json\",\n \"user-agent\": this.userAgent,\n };\n const hasBody = options.body !== undefined;\n if (hasBody) headers[\"content-type\"] = \"application/json\";\n if (options.idempotencyKey) headers[\"idempotency-key\"] = options.idempotencyKey;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: hasBody ? JSON.stringify(stripUndefined(options.body)) : undefined,\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n } catch (cause) {\n throw new PurpleturretNetworkError(url, cause, isTimeoutError(cause));\n }\n\n const text = await response.text();\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n }\n\n const accepted = response.ok || (options.acceptStatuses?.includes(response.status) ?? false);\n if (!accepted) {\n throw PurpleturretApiError.fromResponse(response.status, parsed ?? text, response.headers.get(\"retry-after\"));\n }\n if (!response.ok && parsed && typeof parsed === \"object\" && \"error\" in (parsed as Record<string, unknown>)) {\n const record = parsed as Record<string, unknown>;\n // A 409 config conflict carries the full plan under error.details; hand it back unapplied.\n const details = (record.error as { details?: Record<string, unknown> } | undefined)?.details;\n if (details && \"results\" in details && \"summary\" in details) return { applied: false, ...details } as T;\n // A 404 entitlement lookup returns `{ has_access: false }` (no error); anything else with an\n // error envelope is still an error even if the status was in acceptStatuses.\n const looksLikePlan = \"results\" in record && \"summary\" in record;\n const looksLikeEntitlement = \"has_access\" in record;\n if (!looksLikePlan && !looksLikeEntitlement) {\n throw PurpleturretApiError.fromResponse(response.status, parsed, response.headers.get(\"retry-after\"));\n }\n }\n if (response.status === 204 || parsed === undefined) return undefined as T;\n return parsed as T;\n }\n}\n\nexport function customerQuery(selector: CustomerSelector): { external_id?: string; email?: string } {\n const out: { external_id?: string; email?: string } = {};\n if (selector.externalId) out.external_id = selector.externalId;\n if (selector.email) out.email = selector.email;\n if (!out.external_id && !out.email) throw new TypeError(\"Provide externalId or email to identify the customer\");\n return out;\n}\n\nfunction stripUndefined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stripUndefined);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = stripUndefined(entry);\n }\n return out;\n }\n return value;\n}\n","/** Keep in sync with package.json. */\nexport const CLI_VERSION = \"0.6.0\";\n","import { chmod, mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport interface Profile {\n apiKey: string;\n /** Only stored when the key was validated against a non-default API URL. */\n apiUrl?: string;\n email?: string;\n keyPrefix?: string;\n scopes?: string[];\n savedAt: string;\n}\n\nexport interface CredentialsFile {\n version: 1;\n profiles: Record<string, Profile>;\n}\n\nexport const DEFAULT_PROFILE = \"default\";\n\n/** `$XDG_CONFIG_HOME/purpleturret/credentials.json`, defaulting to `~/.config`. */\nexport function credentialsPath(env: NodeJS.ProcessEnv = process.env): string {\n const xdg = env.XDG_CONFIG_HOME?.trim();\n const home = env.HOME?.trim() || homedir();\n const configHome = xdg && xdg.length > 0 ? xdg : join(home, \".config\");\n return join(configHome, \"purpleturret\", \"credentials.json\");\n}\n\nexport class CredentialsStore {\n readonly path: string;\n\n constructor(path: string = credentialsPath()) {\n this.path = path;\n }\n\n async read(): Promise<CredentialsFile> {\n let text: string;\n try {\n text = await readFile(this.path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { version: 1, profiles: {} };\n throw error;\n }\n try {\n const parsed = JSON.parse(text) as Partial<CredentialsFile>;\n if (!parsed || typeof parsed !== \"object\" || typeof parsed.profiles !== \"object\" || parsed.profiles === null) {\n return { version: 1, profiles: {} };\n }\n return { version: 1, profiles: parsed.profiles as Record<string, Profile> };\n } catch {\n throw new Error(`Credentials file ${this.path} is not valid JSON. Fix or delete it and run \\`purpleturret login\\` again.`);\n }\n }\n\n async write(file: CredentialsFile): Promise<void> {\n await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });\n const tmp = `${this.path}.${process.pid}.tmp`;\n await writeFile(tmp, `${JSON.stringify(file, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await chmod(tmp, 0o600);\n await rename(tmp, this.path);\n }\n\n async getProfile(name: string = DEFAULT_PROFILE): Promise<Profile | null> {\n const file = await this.read();\n return file.profiles[name] ?? null;\n }\n\n async saveProfile(name: string, profile: Profile): Promise<void> {\n const file = await this.read();\n file.profiles[name] = profile;\n await this.write(file);\n }\n\n /** Returns true when a profile was removed. */\n async deleteProfile(name: string): Promise<boolean> {\n const file = await this.read();\n if (!(name in file.profiles)) return false;\n delete file.profiles[name];\n await this.write(file);\n return true;\n }\n}\n","import { ConfigValidationError, PurpleturretApiError, PurpleturretNetworkError } from \"@purpleturret/sdk\";\n\nexport const EXIT = {\n OK: 0,\n ERROR: 1,\n USAGE: 2,\n AUTH: 3,\n CONFLICT: 4,\n ABORTED: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\nexport const DASHBOARD_SETTINGS_URL = \"https://purpleturret.com/dashboard/settings\";\n\nexport class CliError extends Error {\n override readonly name = \"CliError\";\n readonly exitCode: ExitCode;\n readonly hint: string | undefined;\n readonly code: string | undefined;\n override readonly cause: unknown;\n\n constructor(message: string, exitCode: ExitCode = EXIT.ERROR, options: { hint?: string; code?: string; cause?: unknown } = {}) {\n super(message);\n this.exitCode = exitCode;\n this.hint = options.hint;\n this.code = options.code;\n this.cause = options.cause;\n }\n}\n\nexport interface ErrorContext {\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n credentialSource?: \"flag\" | \"env\" | \"profile\" | \"none\";\n}\n\n/** Map any thrown value to a `CliError` with the exit code and actionable message from the plan. */\nexport function toCliError(error: unknown, ctx: ErrorContext): CliError {\n if (error instanceof CliError) return error;\n\n if (error instanceof ConfigValidationError) {\n return new CliError(error.message, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n\n if (error instanceof PurpleturretNetworkError) {\n const where = ctx.apiUrlSource === \"default\" ? \"\" : ` (from ${describeUrlSource(ctx.apiUrlSource)})`;\n return new CliError(error.message, EXIT.ERROR, {\n code: error.timedOut ? \"timeout\" : \"network_error\",\n hint: `Check that the API URL ${ctx.apiUrl}${where} is reachable, or override it with --api-url / PURPLETURRET_API_URL.`,\n cause: error,\n });\n }\n\n if (error instanceof PurpleturretApiError) return fromApiError(error, ctx);\n\n if (error instanceof Error) return new CliError(error.message, EXIT.ERROR, { cause: error });\n return new CliError(String(error), EXIT.ERROR);\n}\n\nfunction fromApiError(error: PurpleturretApiError, ctx: ErrorContext): CliError {\n const requestId = error.requestId ? ` (request ${error.requestId})` : \"\";\n const detailText = formatDetails(error.details);\n\n if (error.code === \"stripe_not_connected\") {\n return new CliError(`${error.message}${requestId}`, EXIT.ERROR, {\n code: error.code,\n hint: `Connect Stripe first in Dashboard → Settings → Payments: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n\n switch (error.status) {\n case 401: {\n const source = ctx.credentialSource;\n const hint =\n source === \"flag\"\n ? \"The key passed with --api-key was rejected. Mint a new seller key in Dashboard → Settings → Developers.\"\n : source === \"env\"\n ? \"PURPLETURRET_API_KEY was rejected. Mint a new seller key in Dashboard → Settings → Developers and update your .env.local.\"\n : \"Run `purpleturret login` to store a valid seller key, or pass --api-key / set PURPLETURRET_API_KEY.\";\n return new CliError(`The API key was rejected (401 ${error.code})${requestId}.`, EXIT.AUTH, { code: error.code, hint, cause: error });\n }\n case 403: {\n if (error.code === \"forbidden_key_type\") {\n return new CliError(`This is a hosting key (pt_host_…), which cannot manage products or credits${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: `Use a seller key (pt_sk_…) minted in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n const required = pickString(error.details, \"required_scope\") ?? pickString(error.details, \"scope\");\n return new CliError(`${error.message} (403 ${error.code})${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: required\n ? `The key is missing the ${required} scope. Mint a key with that scope in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`\n : `Mint a seller key with the config:read, config:write, credits:read, credits:write and entitlements:read scopes in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n case 402:\n return new CliError(`${error.message} (402 ${error.code})${requestId}.${detailText}`, EXIT.ERROR, { code: error.code, cause: error });\n case 404:\n return new CliError(`${error.message} (404 ${error.code})${requestId}.`, EXIT.ERROR, { code: error.code, cause: error });\n case 409: {\n if (error.code === \"immutable_field_changed\") {\n return new CliError(`${error.message} (409 immutable_field_changed)${requestId}.${detailText}`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one (push --prune).\",\n cause: error,\n });\n }\n if (error.code === \"idempotency_conflict\") {\n return new CliError(`${error.message} (409 idempotency_conflict)${requestId}.`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"The Idempotency-Key was already used with a different request body. Run push again to generate a fresh key.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (409 ${error.code})${requestId}.${detailText}`, EXIT.CONFLICT, { code: error.code, cause: error });\n }\n case 422:\n return new CliError(`The API rejected the request (422 ${error.code})${requestId}: ${error.message}${detailText}`, EXIT.USAGE, {\n code: error.code,\n cause: error,\n });\n case 429:\n return new CliError(`Rate limited (429 ${error.code})${requestId}.`, EXIT.ERROR, {\n code: error.code,\n hint: error.retryAfter !== null ? `Retry after ${error.retryAfter}s.` : \"Slow down and retry shortly.\",\n cause: error,\n });\n default:\n if (error.status >= 500) {\n return new CliError(`The Purpleturret API returned ${error.status} ${error.code}${requestId}: ${error.message}`, EXIT.ERROR, {\n code: error.code,\n hint: \"This is a server-side failure. Retry in a moment; if it persists, contact support with the request id.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (${error.status} ${error.code})${requestId}.${detailText}`, EXIT.ERROR, {\n code: error.code,\n cause: error,\n });\n }\n}\n\nfunction describeUrlSource(source: ErrorContext[\"apiUrlSource\"]): string {\n switch (source) {\n case \"flag\":\n return \"--api-url\";\n case \"env\":\n return \"PURPLETURRET_API_URL\";\n case \"profile\":\n return \"the saved profile\";\n default:\n return \"the default\";\n }\n}\n\nfunction pickString(details: unknown, key: string): string | undefined {\n if (details && typeof details === \"object\" && key in details) {\n const value = (details as Record<string, unknown>)[key];\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function formatDetails(details: unknown): string {\n if (details === undefined || details === null) return \"\";\n if (typeof details === \"string\") return `\\n ${details}`;\n if (Array.isArray(details)) {\n if (details.length === 0) return \"\";\n return `\\n${details.map((entry) => ` - ${formatDetailEntry(entry)}`).join(\"\\n\")}`;\n }\n if (typeof details === \"object\") {\n const entries = Object.entries(details as Record<string, unknown>);\n if (entries.length === 0) return \"\";\n if (\"issues\" in (details as Record<string, unknown>) && Array.isArray((details as Record<string, unknown>).issues)) {\n return formatDetails((details as Record<string, unknown>).issues);\n }\n return `\\n${entries.map(([key, value]) => ` ${key}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`).join(\"\\n\")}`;\n }\n return `\\n ${String(details)}`;\n}\n\nfunction formatDetailEntry(entry: unknown): string {\n if (entry && typeof entry === \"object\") {\n const record = entry as Record<string, unknown>;\n const path = typeof record.path === \"string\" ? record.path : Array.isArray(record.path) ? record.path.join(\".\") : undefined;\n const message = typeof record.message === \"string\" ? record.message : JSON.stringify(record);\n return path ? `${path}: ${message}` : message;\n }\n return String(entry);\n}\n","import { createColors } from \"picocolors\";\n\nimport type { CliError } from \"./errors\";\n\nexport type Paint = (text: string | number) => string;\n\nexport interface Palette {\n enabled: boolean;\n green: Paint;\n yellow: Paint;\n red: Paint;\n cyan: Paint;\n magenta: Paint;\n dim: Paint;\n bold: Paint;\n}\n\nexport function createPalette(enabled: boolean): Palette {\n const colors = createColors(enabled);\n return {\n enabled,\n green: colors.green,\n yellow: colors.yellow,\n red: colors.red,\n cyan: colors.cyan,\n magenta: colors.magenta,\n dim: colors.dim,\n bold: colors.bold,\n };\n}\n\n/** Color is on only for a TTY, unless `--no-color` or `NO_COLOR` turns it off. */\nexport function shouldUseColor(options: { flag?: boolean; env?: NodeJS.ProcessEnv; stream?: { isTTY?: boolean } } = {}): boolean {\n const env = options.env ?? process.env;\n const stream = options.stream ?? process.stdout;\n if (options.flag === false) return false;\n if (env.NO_COLOR !== undefined && env.NO_COLOR !== \"\") return false;\n if (env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== \"\" && env.FORCE_COLOR !== \"0\") return true;\n return Boolean(stream.isTTY);\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\nexport interface OutputOptions {\n json: boolean;\n verbose: boolean;\n palette: Palette;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n}\n\n/** Human messages go to stderr; results (plans, tables, JSON) go to stdout. */\nexport class Output {\n readonly json: boolean;\n readonly verbose: boolean;\n readonly palette: Palette;\n private readonly stdout: NodeJS.WritableStream;\n private readonly stderr: NodeJS.WritableStream;\n\n constructor(options: OutputOptions) {\n this.json = options.json;\n this.verbose = options.verbose;\n this.palette = options.palette;\n this.stdout = options.stdout ?? process.stdout;\n this.stderr = options.stderr ?? process.stderr;\n }\n\n /** Write result lines to stdout (suppressed in --json mode unless `force`). */\n print(text: string, force = false): void {\n if (this.json && !force) return;\n this.stdout.write(`${text}\\n`);\n }\n\n /** Write a JSON document to stdout. */\n printJson(value: unknown): void {\n this.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n }\n\n info(text: string): void {\n if (this.json) return;\n this.stderr.write(`${text}\\n`);\n }\n\n success(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.green(\"✔\")} ${text}\\n`);\n }\n\n warn(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.yellow(\"!\")} ${text}\\n`);\n }\n\n debug(text: string): void {\n if (!this.verbose) return;\n this.stderr.write(`${this.palette.dim(`[debug] ${text}`)}\\n`);\n }\n\n /** Report a fatal error. In --json mode the error is emitted as JSON on stdout. */\n fail(error: CliError): void {\n if (this.json) {\n this.stdout.write(\n `${JSON.stringify({ error: { code: error.code ?? \"error\", message: error.message, hint: error.hint, exit_code: error.exitCode } })}\\n`,\n );\n return;\n }\n this.stderr.write(`${this.palette.red(\"error:\")} ${error.message}\\n`);\n if (error.hint) this.stderr.write(`${this.palette.dim(\"hint:\")} ${error.hint}\\n`);\n if (this.verbose && error.cause instanceof Error && error.cause.stack) {\n this.stderr.write(`${this.palette.dim(error.cause.stack)}\\n`);\n }\n }\n}\n","import { DEFAULT_BASE_URL } from \"@purpleturret/sdk\";\nimport { isCancel } from \"@clack/prompts\";\nimport type { ArgsDef, CommandContext } from \"citty\";\n\nimport { createContext, type CliContext, type GlobalFlags } from \"./context\";\nimport { CliError, EXIT, toCliError } from \"./errors\";\nimport { Output, createPalette, shouldUseColor } from \"./output\";\n\nexport type Handler<A extends ArgsDef> = (ctx: CliContext, args: CommandContext<A>[\"args\"]) => Promise<void>;\n\n/**\n * Wrap a command body: build the CLI context from the parsed flags, run, and translate any error into\n * a message plus exit code. Errors never escape to citty (which would print a stack and exit 1).\n */\nexport function defineRun<A extends ArgsDef>(handler: Handler<A>) {\n return async (command: CommandContext<A>): Promise<void> => {\n let ctx: CliContext | undefined;\n try {\n ctx = await createContext(command.args as GlobalFlags);\n await handler(ctx, command.args);\n } catch (error) {\n const cliError = toCliError(error, ctx ?? { apiUrl: DEFAULT_BASE_URL, apiUrlSource: \"default\" });\n const out =\n ctx?.out ??\n new Output({\n json: Boolean((command.args as GlobalFlags).json),\n verbose: Boolean((command.args as GlobalFlags).verbose),\n palette: createPalette(shouldUseColor({ flag: (command.args as GlobalFlags).color })),\n });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n };\n}\n\n/** Convert a cancelled @clack prompt into an exit-130 error. */\nexport function unwrapPrompt<T>(value: T | symbol): T {\n if (isCancel(value)) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n return value as T;\n}\n","/** Render a plain-text table with left-aligned, space-padded columns. */\nexport function renderTable(headers: string[], rows: string[][], dimHeader: (text: string) => string = (text) => text): string[] {\n const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? \"\").length)));\n const line = (cells: string[]) =>\n cells\n .map((cell, index) => cell.padEnd(widths[index] ?? 0))\n .join(\" \")\n .trimEnd();\n return [dimHeader(line(headers)), ...rows.map(line)];\n}\n","import { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst yesArg = { yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt (required in CI)\" } } as const;\n\n/** Ask before a destructive call unless `--yes`; refuses silently-destructive runs in non-interactive terminals. */\nexport async function confirmOrYes(yes: boolean, json: boolean, message: string): Promise<void> {\n if (yes) return;\n if (!isInteractive() || json) {\n throw new CliError(\"Refusing to delete without confirmation because this is not an interactive terminal.\", EXIT.USAGE, {\n code: \"confirmation_required\",\n hint: \"Re-run with --yes to confirm non-interactively.\",\n });\n }\n if (!unwrapPrompt(await confirm({ message, initialValue: false }))) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List webhook endpoints\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().webhooks.list();\n if (ctx.json) return ctx.out.printJson({ webhooks: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No webhook endpoints yet. Run `purpleturret webhooks add <group-key> <url>`.\"));\n const rows = data.map((w) => [\n w.id,\n w.groupKey,\n w.url,\n w.enabled ? \"enabled\" : palette.yellow(\"disabled\"),\n w.lastDelivery ? `${w.lastDelivery.status} ${new Date(w.lastDelivery.at).toISOString()}` : palette.dim(\"—\"),\n w.description ?? \"\",\n ]);\n for (const line of renderTable([\"ID\", \"GROUP\", \"URL\", \"STATUS\", \"LAST DELIVERY\", \"DESCRIPTION\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst add = defineCommand({\n meta: { name: \"add\", description: \"Create a webhook endpoint in an integration group\" },\n args: {\n ...globalArgs,\n group: { type: \"positional\", required: true, description: \"Integration group key\" },\n url: { type: \"positional\", required: true, description: \"HTTPS URL to deliver events to\" },\n description: { type: \"string\", description: \"Label (up to 80 chars)\" },\n },\n run: defineRun(async (ctx, args) => {\n const created = await ctx.client().webhooks.create({ groupKey: args.group, url: args.url, description: args.description });\n if (ctx.json) return ctx.out.printJson(created);\n ctx.out.print(`Created webhook ${created.id} for ${created.groupKey} → ${created.url}`);\n ctx.out.print(`Signing secret (shown once, store it now): ${created.secret}`);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Change a webhook endpoint's URL, enabled flag or description\" },\n args: {\n ...globalArgs,\n id: { type: \"positional\", required: true },\n url: { type: \"string\", description: \"New HTTPS URL\" },\n enabled: { type: \"boolean\", description: \"Enable (--enabled) or disable (--no-enabled) deliveries\" },\n description: { type: \"string\", description: 'New label; pass \"\" to clear' },\n },\n run: defineRun(async (ctx, args) => {\n const updated = await ctx.client().webhooks.update(args.id, { url: args.url, enabled: args.enabled, description: args.description });\n ctx.json\n ? ctx.out.printJson(updated)\n : ctx.out.print(`Updated webhook ${updated.id} (${updated.enabled ? \"enabled\" : \"disabled\"}) → ${updated.url}`);\n }),\n});\n\nconst del = defineCommand({\n meta: { name: \"delete\", description: \"Delete a webhook endpoint and its pending deliveries\" },\n args: { ...globalArgs, ...yesArg, id: { type: \"positional\", required: true } },\n run: defineRun(async (ctx, args) => {\n await confirmOrYes(Boolean(args.yes), ctx.json, `Delete webhook ${args.id}? Pending deliveries are dropped.`);\n const deleted = await ctx.client().webhooks.delete(args.id);\n ctx.json ? ctx.out.printJson(deleted) : ctx.out.print(`Deleted webhook ${deleted.id} (${deleted.url})`);\n }),\n});\n\nconst test = defineCommand({\n meta: { name: \"test\", description: \"Queue a test.event delivery to a webhook endpoint\" },\n args: { ...globalArgs, id: { type: \"positional\", required: true } },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().webhooks.test(args.id);\n ctx.json ? ctx.out.printJson(result) : ctx.out.print(`Queued test delivery ${result.deliveryId}; it is sent asynchronously.`);\n }),\n});\n\nexport const webhooks = defineCommand({\n meta: { name: \"webhooks\", description: \"Webhook endpoints\" },\n args: { ...globalArgs },\n subCommands: { list, add, update, delete: del, test },\n});\n","import { type Order } from \"@purpleturret/sdk\";\nimport { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { type: \"positional\", required: true, description: \"Order id\" } as const;\nconst REASONS = [\"requested_by_customer\", \"duplicate\", \"fraudulent\", \"other\"] as const;\nconst SCOPES = [\"main\", \"upsell\", \"all\"] as const;\n\nfunction printOrder(ctx: CliContext, order: Order): void {\n if (ctx.json) return ctx.out.printJson(order);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"ID\", order.id],\n [\"STATUS\", order.status],\n [\"KIND\", order.kind],\n [\"PROVIDER\", order.provider],\n [\"PRODUCT\", order.productId],\n [\"EMAIL\", order.customer.email ?? palette.dim(\"—\")],\n [\"NAME\", order.customer.name ?? palette.dim(\"—\")],\n [\"AMOUNT\", formatMoney(order)],\n [\"CREATED\", new Date(order.createdAt).toISOString()],\n ];\n if (order.refund) rows.push([\"REFUND\", `${order.refund.reason ?? \"\"} ${new Date(order.refund.refundedAt).toISOString()}`.trim()]);\n if (order.upsell) rows.push([\"UPSELL\", `${order.upsell.decision}${order.upsell.refund ? \" (refunded)\" : \"\"}`]);\n if (order.failureReason) rows.push([\"FAILURE\", palette.red(order.failureReason)]);\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n ctx.out.print(\"\");\n const items = order.lineItems.map((item) => [\n item.role,\n item.name ?? palette.dim(item.productId),\n formatMoney({ amount: item.amount, currency: order.currency }),\n ]);\n for (const line of renderTable([\"ROLE\", \"ITEM\", \"AMOUNT\"], items, palette.dim)) ctx.out.print(line);\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List orders, newest first\" },\n args: {\n ...globalArgs,\n email: { type: \"string\", description: \"Buyer email (exact, case-insensitive)\" },\n status: { type: \"string\", description: \"pending | paid | failed | refunded | partially_refunded\" },\n },\n run: defineRun(async (ctx, args) => {\n const page = await ctx.client().orders.list({ email: args.email, status: args.status as Order[\"status\"] | undefined, limit: 100 });\n if (ctx.json) return ctx.out.printJson(page);\n const { palette } = ctx.out;\n if (page.data.length === 0) return ctx.out.print(palette.dim(\"No orders.\"));\n const rows = page.data.map((o) => [\n o.id,\n o.status,\n o.customer.email ?? palette.dim(\"—\"),\n formatMoney(o),\n o.productId,\n new Date(o.createdAt).toISOString(),\n ]);\n for (const line of renderTable([\"ID\", \"STATUS\", \"EMAIL\", \"AMOUNT\", \"PRODUCT\", \"CREATED\"], rows, palette.dim)) ctx.out.print(line);\n if (page.nextCursor) ctx.out.print(palette.dim(\"More results available; use --json and the API cursor.\"));\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show an order\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printOrder(ctx, await ctx.client().orders.get(args.id))),\n});\n\nconst refund = defineCommand({\n meta: { name: \"refund\", description: \"Refund an order through the payment provider (cannot be undone)\" },\n args: {\n ...globalArgs,\n id,\n reason: { type: \"string\", required: true, description: REASONS.join(\" | \") },\n scope: { type: \"string\", description: \"main | upsell | all (default all)\" },\n \"custom-reason\": { type: \"string\", description: \"Free text, stored only with --reason other\" },\n yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" },\n },\n run: defineRun(async (ctx, args) => {\n const reason = args.reason as (typeof REASONS)[number];\n const scope = args.scope as (typeof SCOPES)[number] | undefined;\n if (!REASONS.includes(reason)) throw new Error(`--reason must be one of ${REASONS.join(\", \")}`);\n if (scope !== undefined && !SCOPES.includes(scope)) throw new Error(`--scope must be one of ${SCOPES.join(\", \")}`);\n if (!args.yes && !unwrapPrompt(await confirm({ message: `Refund ${scope ?? \"all\"} charges of order ${args.id}?`, initialValue: false }))) return;\n const result = await ctx.client().orders.refund(args.id, { reason, scope, customReason: args[\"custom-reason\"] });\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.print(`Refunded main: ${result.refundedMain}, upsell: ${result.refundedUpsell}`);\n printOrder(ctx, result.order);\n }),\n});\n\nexport const orders = defineCommand({\n meta: { name: \"orders\", description: \"Orders\" },\n args: { ...globalArgs },\n subCommands: { list, get, refund },\n});\n","import type { Billing, ConfigPushResult, Money, PlanAction, PlanItem, PlanSummary, Product } from \"@purpleturret/sdk\";\n\nimport type { Palette } from \"./output\";\n\nexport const PRICE_AMOUNT_NOTE = \"new Stripe price; existing subscriptions keep the old price\";\n\nconst ACTION_ORDER: PlanAction[] = [\"conflict\", \"error\", \"create\", \"update\", \"archive\", \"unchanged\"];\n\nconst ACTION_SYMBOL: Record<PlanAction, string> = {\n create: \"+\",\n update: \"~\",\n unchanged: \"=\",\n archive: \"-\",\n conflict: \"!\",\n error: \"x\",\n};\n\nexport function formatMoney(money: Money): string {\n const currency = money.currency.toUpperCase();\n const major = (money.amount / 100).toFixed(2);\n if (currency === \"USD\") return `$${major}`;\n return `${major} ${currency}`;\n}\n\nexport function describeBilling(billing: Billing): string {\n if (billing.type === \"recurring\") return billing.interval === \"year\" ? \"/year\" : \"/month\";\n return \" one-time\";\n}\n\nexport function describeProduct(product: Pick<Product, \"name\" | \"price\" | \"billing\">): string {\n return `${product.name} — ${formatMoney(product.price)}${describeBilling(product.billing)}`;\n}\n\nexport function formatValue(value: unknown): string {\n if (value === undefined || value === null) return \"(none)\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n\nfunction paintFor(action: PlanAction, palette: Palette) {\n switch (action) {\n case \"create\":\n return palette.green;\n case \"update\":\n return palette.yellow;\n case \"archive\":\n return palette.red;\n case \"conflict\":\n case \"error\":\n return (text: string | number) => palette.bold(palette.red(text));\n default:\n return palette.dim;\n }\n}\n\nexport interface RenderOptions {\n palette: Palette;\n /** `plan` renders a dry-run; `apply` renders the applied result. */\n mode: \"plan\" | \"apply\";\n}\n\n/** Render one plan item (header line plus nested change lines). */\nexport function renderPlanItem(item: PlanItem, options: RenderOptions & { keyWidth?: number }): string[] {\n const { palette } = options;\n const paint = paintFor(item.action, palette);\n const keyWidth = Math.max(options.keyWidth ?? 0, item.key.length);\n const symbol = ACTION_SYMBOL[item.action];\n const label = item.action.padEnd(9);\n const key = item.key.padEnd(keyWidth);\n\n let detail = \"\";\n if (item.action === \"create\" && item.product) detail = describeProduct(item.product);\n else if (item.action === \"unchanged\" && item.product) detail = palette.dim(describeProduct(item.product));\n else if (item.action === \"archive\" && item.product) detail = describeProduct(item.product);\n else if ((item.action === \"conflict\" || item.action === \"error\") && item.error) detail = `${item.error.code}: ${item.error.message}`;\n\n const lines = [`${paint(`${symbol} ${label}`)} ${paint(key)}${detail ? ` ${detail}` : \"\"}`.trimEnd()];\n\n if (item.changes.length === 0) return lines;\n const pathWidth = Math.max(...item.changes.map((change) => change.path.length));\n for (const change of item.changes) {\n const note = change.note ?? (change.path === \"price.amount\" && item.action !== \"create\" ? PRICE_AMOUNT_NOTE : undefined);\n const isNew = change.from === undefined || change.from === null;\n const transition =\n item.action === \"create\" || (isNew && item.action !== \"archive\")\n ? formatValue(change.to)\n : `${formatValue(change.from)} → ${formatValue(change.to)}`;\n const line = ` ${paint(symbol)} ${change.path.padEnd(pathWidth)} ${transition}${note ? ` ${palette.dim(`(${note})`)}` : \"\"}`;\n lines.push(line);\n }\n return lines;\n}\n\n/** Sort conflicts and errors first, then creates/updates/archives, unchanged last. */\nexport function sortPlanItems(items: PlanItem[]): PlanItem[] {\n return [...items].sort((a, b) => {\n const order = ACTION_ORDER.indexOf(a.action) - ACTION_ORDER.indexOf(b.action);\n return order !== 0 ? order : a.key.localeCompare(b.key);\n });\n}\n\nexport function hasChanges(summary: PlanSummary): boolean {\n return summary.create + summary.update + summary.archive + summary.conflict + summary.error > 0;\n}\n\nexport function renderSummary(summary: PlanSummary, options: RenderOptions): string {\n const { palette, mode } = options;\n const parts: string[] = [];\n if (mode === \"plan\") {\n if (summary.create) parts.push(palette.green(`${summary.create} to create`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} to update`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} to archive`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} error${summary.error === 1 ? \"\" : \"s\"}`)));\n if (!hasChanges(summary))\n return palette.dim(`No changes. ${summary.unchanged} product${summary.unchanged === 1 ? \"\" : \"s\"} already match the config.`);\n return `Plan: ${parts.join(\", \")}.`;\n }\n if (summary.create) parts.push(palette.green(`${summary.create} created`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} updated`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} archived`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} failed`)));\n const prefix = summary.error || summary.conflict ? \"Apply incomplete\" : \"Apply complete\";\n return `${prefix}: ${parts.length ? parts.join(\", \") : \"nothing to do\"}.`;\n}\n\n/** Full plan/apply rendering: one block per product followed by a summary line. */\nexport function renderPlan(result: ConfigPushResult, options: RenderOptions): string[] {\n const items = sortPlanItems(result.results);\n const keyWidth = items.reduce((width, item) => Math.max(width, item.key.length), 0);\n const lines: string[] = [];\n for (const item of items) {\n lines.push(...renderPlanItem(item, { ...options, keyWidth }));\n }\n if (lines.length) lines.push(\"\");\n lines.push(renderSummary(result.summary, options));\n return lines;\n}\n","import { type Subscription } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { type: \"positional\", required: true, description: \"Subscription id\" } as const;\nconst iso = (ms: number | null) => (ms === null ? \"—\" : new Date(ms).toISOString());\n\nfunction printSubscription(ctx: CliContext, sub: Subscription): void {\n if (ctx.json) return ctx.out.printJson(sub);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"ID\", sub.id],\n [\"STATUS\", sub.status + (sub.cancelAtPeriodEnd ? \" (cancels at period end)\" : \"\")],\n [\"PROVIDER\", sub.provider],\n [\"PRODUCT\", sub.productId],\n [\"EMAIL\", sub.customer.email],\n [\"NAME\", sub.customer.name ?? palette.dim(\"—\")],\n [\"PRICE\", `${formatMoney(sub)}/${sub.interval}`],\n [\"PERIOD\", `${iso(sub.currentPeriodStart)} → ${iso(sub.currentPeriodEnd)}`],\n [\"CREATED\", iso(sub.createdAt)],\n [\"ENDED\", iso(sub.endedAt)],\n ];\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List subscriptions, newest first\" },\n args: {\n ...globalArgs,\n email: { type: \"string\", description: \"Buyer email (wins over --product)\" },\n status: { type: \"string\", description: \"incomplete | incomplete_expired | trialing | active | past_due | canceled | unpaid | paused\" },\n product: { type: \"string\", description: \"Product id (not the config key)\" },\n },\n run: defineRun(async (ctx, args) => {\n const page = await ctx\n .client()\n .subscriptions.list({ email: args.email, status: args.status as Subscription[\"status\"] | undefined, product: args.product, limit: 100 });\n if (ctx.json) return ctx.out.printJson(page);\n const { palette } = ctx.out;\n if (page.data.length === 0) return ctx.out.print(palette.dim(\"No subscriptions.\"));\n const rows = page.data.map((s) => [s.id, s.status, s.customer.email, `${formatMoney(s)}/${s.interval}`, s.productId, iso(s.currentPeriodEnd)]);\n for (const line of renderTable([\"ID\", \"STATUS\", \"EMAIL\", \"PRICE\", \"PRODUCT\", \"PERIOD END\"], rows, palette.dim)) ctx.out.print(line);\n if (page.nextCursor) ctx.out.print(palette.dim(\"More results available; use --json and the API cursor.\"));\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show a subscription\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printSubscription(ctx, await ctx.client().subscriptions.get(args.id))),\n});\n\nconst portalLink = defineCommand({\n meta: { name: \"portal-link\", description: \"Create a billing-portal link for the buyer (valid 7 days)\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => {\n const link = await ctx.client().subscriptions.portalLink(args.id);\n if (ctx.json) return ctx.out.printJson(link);\n ctx.out.print(link.url);\n ctx.out.print(ctx.out.palette.dim(`Expires ${iso(link.expiresAt)}`));\n }),\n});\n\nconst portalEmail = defineCommand({\n meta: { name: \"portal-email\", description: \"E-mail the buyer a billing-portal link\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().subscriptions.portalEmail(args.id);\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.print(\"Portal e-mail sent.\");\n }),\n});\n\nexport const subscriptions = defineCommand({\n meta: { name: \"subscriptions\", description: \"Subscriptions\" },\n args: { ...globalArgs },\n subCommands: { list, get, \"portal-link\": portalLink, \"portal-email\": portalEmail },\n});\n","import { type Customer } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List customers (one row per email, ordered by email)\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const client = ctx.client();\n const customers: Customer[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.customers.list({ cursor, limit: 100 });\n customers.push(...page.data);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n if (ctx.json) return ctx.out.printJson({ customers });\n const { palette } = ctx.out;\n if (customers.length === 0) return ctx.out.print(palette.dim(\"No customers yet.\"));\n const rows = customers.map((c) => [c.email, c.name ?? palette.dim(\"—\"), c.externalId ?? palette.dim(\"—\"), new Date(c.createdAt).toISOString()]);\n for (const line of renderTable([\"EMAIL\", \"NAME\", \"EXTERNAL ID\", \"CREATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show a customer with orders, subscriptions, credits and lifetime spend\" },\n args: { ...globalArgs, id: { type: \"positional\", required: true, description: \"E-mail address or your external id\" } },\n run: defineRun(async (ctx, args) => {\n const customer = await ctx.client().customers.get(args.id);\n if (ctx.json) return ctx.out.printJson(customer);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"EMAIL\", customer.email],\n [\"NAME\", customer.name ?? palette.dim(\"—\")],\n [\"PHONE\", customer.phone ?? palette.dim(\"—\")],\n [\"EXTERNAL\", customer.externalId ?? palette.dim(\"—\")],\n [\"STRIPE\", customer.stripeCustomerId ?? palette.dim(\"—\")],\n [\"SPEND\", customer.lifetimeSpend.map(formatMoney).join(\", \") || palette.dim(\"—\")],\n [\"ORDERS\", String(customer.orders.length)],\n [\"SUBS\", customer.subscriptions.map((s) => `${s.id} (${s.status})`).join(\", \") || palette.dim(\"—\")],\n ];\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n if (customer.credits.length) {\n ctx.out.print(\"\");\n const credits = customer.credits.map((c) => [c.meter, String(c.balance), c.expiresAt ? new Date(c.expiresAt).toISOString() : \"—\"]);\n for (const line of renderTable([\"METER\", \"BALANCE\", \"EXPIRES\"], credits, palette.dim)) ctx.out.print(line);\n }\n }),\n});\n\nexport const customers = defineCommand({\n meta: { name: \"customers\", description: \"Customers\" },\n args: { ...globalArgs },\n subCommands: { list, get },\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst checkout = defineCommand({\n meta: { name: \"checkout\", description: \"List checkout leads (buyers who started a checkout), newest first\" },\n args: {\n ...globalArgs,\n abandoned: { type: \"boolean\", description: \"Only leads not completed and idle for 30+ minutes\" },\n \"lookback-days\": { type: \"string\", description: \"Window for --abandoned, 1-180 (default 30)\" },\n },\n run: defineRun(async (ctx, args) => {\n const lookbackDays = args[\"lookback-days\"] === undefined ? undefined : Number(args[\"lookback-days\"]);\n if (lookbackDays !== undefined && !Number.isFinite(lookbackDays)) throw new Error(\"--lookback-days must be a number\");\n const { data } = await ctx.client().leads.checkout({ abandoned: Boolean(args.abandoned), lookbackDays });\n if (ctx.json) return ctx.out.printJson({ leads: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No checkout leads.\"));\n const rows = data.map((l) => [l.email ?? palette.dim(\"—\"), l.status, formatMoney(l), l.productId, new Date(l.updatedAt).toISOString()]);\n for (const line of renderTable([\"EMAIL\", \"STATUS\", \"AMOUNT\", \"PRODUCT\", \"UPDATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst pages = defineCommand({\n meta: { name: \"pages\", description: \"List e-mail leads captured by page forms, newest first\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().leads.pages();\n if (ctx.json) return ctx.out.printJson({ leads: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No page leads.\"));\n const rows = data.map((l) => [l.email, l.name ?? palette.dim(\"—\"), l.source, String(l.submissionCount), new Date(l.updatedAt).toISOString()]);\n for (const line of renderTable([\"EMAIL\", \"NAME\", \"SOURCE\", \"SUBMISSIONS\", \"UPDATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const leads = defineCommand({\n meta: { name: \"leads\", description: \"Checkout and page leads\" },\n args: { ...globalArgs },\n subCommands: { checkout, pages },\n});\n","import { type Pixel, type PixelKpis, type PixelRangeOptions } from \"@purpleturret/sdk\";\nimport { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport type { CliContext } from \"../lib/context\";\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst idArg = { id: { type: \"positional\", required: true, description: \"Pixel id\" } } as const;\nconst rangeArgs = {\n start: { type: \"string\", description: \"Epoch ms or ISO 8601 (default: 7 days before end)\" },\n end: { type: \"string\", description: \"Epoch ms or ISO 8601 (default: now); max 90 days\" },\n} as const;\nconst targetArgs = {\n product: { type: \"string\", description: \"Product id (give this or --page)\" },\n page: { type: \"string\", description: \"Page id (give this or --product)\" },\n} as const;\n\nconst range = (args: { start?: string; end?: string }): PixelRangeOptions => ({ start: args.start, end: args.end });\nconst target = (args: { product?: string; page?: string }) => ({ productId: args.product, pageId: args.page });\nconst hosts = (value?: string) =>\n value === undefined\n ? undefined\n : value\n .split(\",\")\n .map((h) => h.trim())\n .filter(Boolean);\nconst when = (ts: number | null | undefined) => (ts ? new Date(ts).toISOString() : \"—\");\nconst pct = (n: number) => `${(n * 100).toFixed(1)}%`;\nconst secs = (ms: number | null) => (ms === null ? \"—\" : `${(ms / 1000).toFixed(1)}s`);\nconst n = (v: number | undefined) => String(v ?? 0);\n\nfunction printTable(ctx: CliContext, headers: string[], rows: string[][]): void {\n for (const line of renderTable(headers, rows, ctx.out.palette.dim)) ctx.out.print(line);\n}\nfunction printKv(ctx: CliContext, rows: [string, string][]): void {\n const width = Math.max(...rows.map(([k]) => k.length));\n for (const [k, v] of rows) ctx.out.print(`${ctx.out.palette.dim(k.padEnd(width))} ${v}`);\n}\nfunction printPixel(ctx: CliContext, pixel: Pixel): void {\n if (ctx.json) return ctx.out.printJson(pixel);\n printKv(ctx, [\n [\"id\", pixel.id],\n [\"key\", pixel.key],\n [\"name\", pixel.name],\n [\"hosts\", pixel.allowedHosts?.join(\", \") || \"any origin\"],\n [\"checkout\", String(pixel.checkout)],\n [\"events\", pixel.declaredEvents?.join(\", \") || \"—\"],\n [\"funnels\", pixel.funnels?.map((f) => `${f.label} (${f.steps.join(\" → \")})`).join(\"; \") || \"—\"],\n [\"archived\", when(pixel.archivedAt)],\n [\"created\", when(pixel.createdAt)],\n ]);\n}\nconst kpiRow = (k: PixelKpis) => [n(k.visitors), n(k.sessions), n(k.pageviews), pct(k.bounceRate ?? 0), secs(k.avgDurationMs ?? 0)];\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List pixels\" },\n args: { ...globalArgs, all: { type: \"boolean\", description: \"Include archived pixels\" } },\n run: defineRun(async (ctx, args) => {\n const { data } = await ctx.client().pixels.list({ includeArchived: Boolean(args.all) });\n if (ctx.json) return ctx.out.printJson({ pixels: data });\n if (data.length === 0) return ctx.out.print(ctx.out.palette.dim(\"No pixels yet. Run `purpleturret pixels create --name <name>`.\"));\n const rows = data.map((p) => [\n p.id,\n p.key,\n p.name,\n p.allowedHosts?.join(\",\") ?? \"*\",\n p.checkout ? \"yes\" : \"\",\n p.archivedAt ? ctx.out.palette.red(\"archived\") : \"active\",\n ]);\n printTable(ctx, [\"ID\", \"KEY\", \"NAME\", \"HOSTS\", \"CHECKOUT\", \"STATUS\"], rows);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show one pixel\" },\n args: { ...globalArgs, ...idArg },\n run: defineRun(async (ctx, args) => printPixel(ctx, await ctx.client().pixels.get(args.id))),\n});\n\nconst create = defineCommand({\n meta: { name: \"create\", description: \"Create a pixel\" },\n args: {\n ...globalArgs,\n name: { type: \"string\", required: true, description: \"Pixel name\" },\n hosts: { type: \"string\", description: \"Comma-separated hosts allowed to send events (default: any origin)\" },\n },\n run: defineRun(async (ctx, args) => {\n const pixel = await ctx.client().pixels.create({ name: args.name, allowedHosts: hosts(args.hosts) });\n ctx.out.success(`Created pixel ${pixel.key}`);\n printPixel(ctx, pixel);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Rename a pixel, change its hosts, or make it the checkout pixel\" },\n args: {\n ...globalArgs,\n ...idArg,\n name: { type: \"string\", description: \"New name\" },\n hosts: { type: \"string\", description: \"Comma-separated allowed hosts (empty string = any origin)\" },\n checkout: { type: \"boolean\", description: \"Make this the checkout pixel (--no-checkout to unset)\" },\n archived: { type: \"boolean\", description: \"Archive (--no-archived restores)\" },\n },\n run: defineRun(async (ctx, args) => {\n const pixel = await ctx.client().pixels.update(args.id, {\n name: args.name,\n allowedHosts: hosts(args.hosts),\n checkout: args.checkout as boolean | undefined,\n archived: args.archived as boolean | undefined,\n });\n ctx.out.success(`Updated pixel ${pixel.key}`);\n printPixel(ctx, pixel);\n }),\n});\n\nconst archive = defineCommand({\n meta: { name: \"archive\", description: \"Archive a pixel (it stops accepting events)\" },\n args: { ...globalArgs, ...idArg, yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes && !unwrapPrompt(await confirm({ message: `Archive pixel ${args.id}?`, initialValue: false }))) return;\n const pixel = await ctx.client().pixels.archive(args.id);\n ctx.out.success(`Archived pixel ${pixel.key}`);\n printPixel(ctx, pixel);\n }),\n});\n\nconst attach = defineCommand({\n meta: { name: \"attach\", description: \"Attach a pixel to a product or page\" },\n args: { ...globalArgs, ...idArg, ...targetArgs },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().pixels.attach(args.id, target(args));\n ctx.json ? ctx.out.printJson(result) : ctx.out.success(`Attached ${result.pixelId} to ${result.productId ?? result.pageId}`);\n }),\n});\n\nconst detach = defineCommand({\n meta: { name: \"detach\", description: \"Detach the pixel from a product or page\" },\n args: { ...globalArgs, ...targetArgs },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().pixels.detach(target(args));\n ctx.json ? ctx.out.printJson(result) : ctx.out.success(`Detached pixel from ${result.productId ?? result.pageId}`);\n }),\n});\n\nconst stats = defineCommand({\n meta: { name: \"stats\", description: \"Visitors, sessions, pageviews and sources for a range\" },\n args: {\n ...globalArgs,\n ...idArg,\n ...rangeArgs,\n bucket: { type: \"string\", description: \"hour | day: add a per-bucket table\" },\n compare: { type: \"boolean\", description: \"Also show the prior period\" },\n },\n run: defineRun(async (ctx, args) => {\n const o = await ctx\n .client()\n .pixels.overview(args.id, { ...range(args), bucket: args.bucket as PixelRangeOptions[\"bucket\"], compare: args.compare as boolean | undefined });\n if (ctx.json) return ctx.out.printJson(o);\n const prior = (pick: (k: PixelKpis) => string) => (o.prior ? ` (prior ${pick(o.prior)})` : \"\");\n printKv(ctx, [\n [\"range\", `${when(o.start)} → ${when(o.end)}${o.truncated ? \" (truncated)\" : \"\"}`],\n [\"visitors\", `${n(o.kpis.visitors)}${prior((k) => n(k.visitors))}`],\n [\"sessions\", `${n(o.kpis.sessions)}${prior((k) => n(k.sessions))}`],\n [\"pageviews\", `${n(o.kpis.pageviews)}${prior((k) => n(k.pageviews))}`],\n [\"bounce\", `${pct(o.kpis.bounceRate ?? 0)}${prior((k) => pct(k.bounceRate ?? 0))}`],\n [\"avg session\", `${secs(o.kpis.avgDurationMs ?? 0)}${prior((k) => secs(k.avgDurationMs ?? 0))}`],\n [\"online now\", n(o.online)],\n [\n \"top sources\",\n o.sessionSources\n .slice(0, 5)\n .map((s) => `${s.source || \"direct\"} ${s.sessions}`)\n .join(\", \") || \"—\",\n ],\n [\n \"top entry\",\n o.entryPages\n .slice(0, 5)\n .map((p) => `${p.path} ${p.sessions}`)\n .join(\", \") || \"—\",\n ],\n ]);\n if (o.series.length === 0) return;\n const bucketMs = (o.end - o.start) / o.series.length;\n ctx.out.print(\"\");\n printTable(\n ctx,\n [\"BUCKET\", \"VISITORS\", \"SESSIONS\", \"PAGEVIEWS\", \"BOUNCE\", \"AVG\"],\n o.series.map((k, i) => [when(o.end - bucketMs * (o.series.length - i)), ...kpiRow(k)]),\n );\n }),\n});\n\nconst pages = defineCommand({\n meta: { name: \"pages\", description: \"Top pages by views\" },\n args: { ...globalArgs, ...idArg, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.topPages(args.id, range(args));\n if (ctx.json) return ctx.out.printJson(r);\n printTable(\n ctx,\n [\"PATH\", \"VIEWS\", \"VISITORS\", \"AVG\"],\n r.pages.map((p) => [p.path, n(p.views), n(p.visitors), secs(p.avgDurationMs)]),\n );\n }),\n});\n\nconst funnels = defineCommand({\n meta: { name: \"funnels\", description: \"Session counts per declared funnel step\" },\n args: { ...globalArgs, ...idArg, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.funnels(args.id, range(args));\n if (ctx.json) return ctx.out.printJson(r);\n if (r.funnels.length === 0) return ctx.out.print(ctx.out.palette.dim(\"No funnels declared from code.\"));\n printTable(\n ctx,\n [\"FUNNEL\", \"STEP\", \"SESSIONS\"],\n r.funnels.flatMap((f) => f.steps.map((s, i) => [i === 0 ? f.label : \"\", s.match, n(s.sessions)])),\n );\n }),\n});\n\nconst ads = defineCommand({\n meta: { name: \"ads\", description: \"Paid-traffic attribution per campaign\" },\n args: {\n ...globalArgs,\n ...idArg,\n ...rangeArgs,\n conversion: { type: \"string\", required: true, description: \"Conversion event name (e.g. purchase) or /path prefix\" },\n attribution: { type: \"string\", description: \"first | last (default last)\" },\n },\n run: defineRun(async (ctx, args) => {\n const r = await ctx\n .client()\n .pixels.adPerformance(args.id, { ...range(args), conversion: args.conversion, attribution: args.attribution as \"first\" | \"last\" | undefined });\n if (ctx.json) return ctx.out.printJson(r);\n printKv(ctx, [\n [\n \"conversions\",\n `${n(r.conversions)} (${n(r.other.conversions)} organic, ${n(r.unattributed)} unattributed)${r.truncated ? \" (truncated)\" : \"\"}`,\n ],\n [\"currency\", r.currency ?? \"—\"],\n ]);\n ctx.out.print(\"\");\n printTable(\n ctx,\n [\"SOURCE\", \"CAMPAIGN\", \"SESSIONS\", \"CONVERSIONS\", \"REVENUE\", \"SPEND\"],\n r.campaigns.map((c) => [c.source, c.campaign, n(c.sessions), n(c.conversions), c.revenue.toFixed(2), c.spend.toFixed(2)]),\n );\n }),\n});\n\nconst people = defineCommand({\n meta: { name: \"people\", description: \"Identified visitors active in the range\" },\n args: {\n ...globalArgs,\n ...idArg,\n ...rangeArgs,\n offset: { type: \"string\", description: \"People to skip (default 0)\" },\n limit: { type: \"string\", description: \"Page size, up to 100 (default 100)\" },\n },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.people(args.id, {\n ...range(args),\n offset: args.offset ? Number(args.offset) : undefined,\n limit: args.limit ? Number(args.limit) : undefined,\n });\n if (ctx.json) return ctx.out.printJson(r);\n printTable(\n ctx,\n [\"PERSON\", \"SESSIONS\", \"PAGEVIEWS\", \"SPENT\", \"LAST SEEN\", \"LAST SID\"],\n r.people.map((p) => [p.id, n(p.sessions), n(p.pageviews), `${p.spent} ${p.currency ?? \"\"}`.trim(), when(p.lastSeen), p.recent[0]?.sid ?? \"—\"]),\n );\n }),\n});\n\nconst timelineArgs = { ...idArg, sid: { type: \"positional\", required: true, description: \"Session id\" } } as const;\nconst eventRows = (events: { ts: number; name: string; path: string; props: Record<string, unknown> | null; sid?: string }[]) =>\n events.map((e) => [when(e.ts), e.sid ?? \"\", e.name, e.path, e.props ? JSON.stringify(e.props) : \"\"]);\n\nconst session = defineCommand({\n meta: { name: \"session\", description: \"Event timeline of one session\" },\n args: { ...globalArgs, ...timelineArgs },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.session(args.id, args.sid);\n if (ctx.json) return ctx.out.printJson(r);\n printTable(ctx, [\"TIME\", \"\", \"EVENT\", \"PATH\", \"PROPS\"], eventRows(r.events));\n }),\n});\n\nconst person = defineCommand({\n meta: { name: \"person\", description: \"Merged event timeline across a person's sessions\" },\n args: { ...globalArgs, ...timelineArgs, sids: { type: \"string\", description: \"Comma-separated extra session ids (max 20 in total)\" } },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.person(args.id, args.sid, { sids: hosts(args.sids) });\n if (ctx.json) return ctx.out.printJson(r);\n printTable(ctx, [\"TIME\", \"SID\", \"EVENT\", \"PATH\", \"PROPS\"], eventRows(r.events));\n }),\n});\n\nconst spend = defineCommand({\n meta: { name: \"spend\", description: \"Record ad spend for a source/campaign over a date range\" },\n args: {\n ...globalArgs,\n ...idArg,\n source: { type: \"string\", required: true, description: \"Ad source (e.g. google)\" },\n campaign: { type: \"string\", description: \"Campaign name (default: none)\" },\n start: { type: \"string\", required: true, description: \"Epoch ms or ISO 8601\" },\n end: { type: \"string\", required: true, description: \"Epoch ms or ISO 8601 (max 90 days after start)\" },\n spend: { type: \"string\", required: true, description: \"Amount (0 clears the range)\" },\n },\n run: defineRun(async (ctx, args) => {\n const r = await ctx\n .client()\n .pixels.setAdSpend(args.id, { source: args.source, campaign: args.campaign, start: args.start, end: args.end, spend: Number(args.spend) });\n if (ctx.json) return ctx.out.printJson(r);\n ctx.out.success(`Recorded ${r.spend} for ${r.source}${r.campaign ? ` / ${r.campaign}` : \"\"} (${when(r.start)} → ${when(r.end)})`);\n }),\n});\n\nexport const pixels = defineCommand({\n meta: { name: \"pixels\", description: \"Pixels and analytics\" },\n args: { ...globalArgs },\n subCommands: { list, get, create, update, archive, attach, detach, stats, pages, funnels, ads, people, session, person, spend },\n});\n","import { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative, resolve, sep } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { contentTypeFor, type HostedPage, type PageFileInput, type PageUpdateOptions } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { id: { type: \"positional\", required: true, description: \"Page id\" } } as const;\n\nfunction printPage(ctx: CliContext, page: HostedPage): void {\n if (ctx.json) return ctx.out.printJson(page);\n const rows: [string, string][] = [\n [\"id\", page.id],\n [\"title\", page.title],\n [\"url\", page.url],\n [\"published\", String(page.published)],\n [\"files\", `${page.fileCount} (${page.totalBytes} bytes)`],\n [\"submissions\", String(page.submissionCount)],\n [\"pixel\", page.pixelId ?? \"—\"],\n [\"products\", page.linkedProductIds.join(\", \") || \"—\"],\n [\"custom domain\", page.customDomain ? `${page.customDomain.hostname} (${page.customDomain.status ?? \"unknown\"})` : \"—\"],\n [\"last deployed\", page.lastDeployedAt ? new Date(page.lastDeployedAt).toISOString() : \"never\"],\n ];\n if (page.disabled) rows.push([\"disabled\", page.disabledReason ?? \"yes\"]);\n for (const [key, value] of rows) ctx.out.print(`${ctx.out.palette.dim(key.padEnd(14))} ${value}`);\n}\n\n/** Site files under `dir`, skipping dotfiles and node_modules. */\nfunction walk(dir: string): string[] {\n return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") return [];\n const full = join(dir, entry.name);\n return entry.isDirectory() ? walk(full) : [full];\n });\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List hosted pages\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().pages.list();\n if (ctx.json) return ctx.out.printJson({ pages: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No pages yet. Run `purpleturret pages deploy <dir>` to create one.\"));\n const rows = data.map((p) => [\n p.id,\n p.title,\n p.disabled ? palette.red(\"disabled\") : p.published ? \"published\" : palette.yellow(\"draft\"),\n String(p.fileCount),\n p.url,\n ]);\n for (const line of renderTable([\"ID\", \"TITLE\", \"STATUS\", \"FILES\", \"URL\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show one hosted page\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => printPage(ctx, await ctx.client().pages.get(args.id))),\n});\n\nconst files = defineCommand({\n meta: { name: \"files\", description: \"List a page's files\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => {\n const { data } = await ctx.client().pages.files(args.id);\n if (ctx.json) return ctx.out.printJson({ files: data });\n for (const line of renderTable(\n [\"PATH\", \"SIZE\", \"TYPE\"],\n data.map((f) => [f.path, String(f.size), f.contentType]),\n ctx.out.palette.dim,\n ))\n ctx.out.print(line);\n }),\n});\n\nconst deploy = defineCommand({\n meta: { name: \"deploy\", description: \"Upload a directory as a hosted page (creates it, or replaces the files of the page with that slug)\" },\n args: {\n ...globalArgs,\n dir: { type: \"positional\", required: true, description: \"Directory containing index.html\" },\n id: { type: \"string\", description: \"Replace the files of this page instead of matching by slug\" },\n slug: { type: \"string\", description: \"Subdomain label (default: directory name)\" },\n title: { type: \"string\", description: \"Page title (default: slug)\" },\n pixel: { type: \"string\", description: \"Pixel id to attach when creating\" },\n },\n run: defineRun(async (ctx, args) => {\n const dir = resolve(ctx.cwd, args.dir);\n if (!statSync(dir, { throwIfNoEntry: false })?.isDirectory()) throw new CliError(`${args.dir} is not a directory`, EXIT.USAGE, { code: \"usage\" });\n const client = ctx.client();\n const slug = args.slug ?? basename(dir);\n const uploaded: PageFileInput[] = [];\n for (const file of walk(dir)) {\n const bytes = readFileSync(file);\n const path = relative(dir, file).split(sep).join(\"/\");\n ctx.out.debug(`upload ${path} (${bytes.byteLength} bytes)`);\n uploaded.push({ path, storageId: await client.uploads.put(bytes, contentTypeFor(path)), size: bytes.byteLength });\n }\n const existingId = args.id ?? (await client.pages.list()).data.find((p) => p.slug === slug)?.id;\n const page = existingId\n ? await client.pages.replaceFiles(existingId, uploaded)\n : await client.pages.create({ title: args.title ?? slug, slug, files: uploaded, pixelId: args.pixel });\n if (ctx.json) return ctx.out.printJson(page);\n ctx.out.success(`${existingId ? \"Updated\" : \"Created\"} ${page.title} (${uploaded.length} files)`);\n ctx.out.print(page.url);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Update a page's title, slug, linked products or submission settings\" },\n args: {\n ...globalArgs,\n ...id,\n title: { type: \"string\" },\n slug: { type: \"string\" },\n products: { type: \"string\", description: \"Comma-separated product ids to link (max 5; empty string clears)\" },\n notify: { type: \"boolean\", description: \"Email on each form submission (--no-notify to disable)\" },\n leads: { type: \"boolean\", description: \"Add submitters to leads (--no-leads to disable)\" },\n },\n run: defineRun(async (ctx, args) => {\n const patch: PageUpdateOptions = { title: args.title, slug: args.slug, notifyOnSubmission: args.notify, addToLeads: args.leads };\n if (args.products !== undefined)\n patch.linkedProductIds = args.products\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n printPage(ctx, await ctx.client().pages.update(args.id, patch));\n }),\n});\n\nconst setPublished = (published: boolean) =>\n defineCommand({\n meta: { name: published ? \"publish\" : \"unpublish\", description: published ? \"Publish a page\" : \"Unpublish a page (stops serving)\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => printPage(ctx, await ctx.client().pages.update(args.id, { published }))),\n });\n\nconst del = defineCommand({\n meta: { name: \"delete\", description: \"Delete a page and its files (archived instead when it has submissions)\" },\n args: { ...globalArgs, ...id, yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes) {\n if (!isInteractive() || ctx.json)\n throw new CliError(\"Refusing to delete without confirmation.\", EXIT.USAGE, { code: \"confirmation_required\", hint: \"Re-run with --yes.\" });\n if (!unwrapPrompt(await confirm({ message: `Delete page ${args.id}?`, initialValue: false })))\n throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n const result = await ctx.client().pages.delete(args.id);\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.success(result.archived ? `Archived ${result.page.title} (it had submissions)` : `Deleted ${result.page.title}`);\n }),\n});\n\nconst submissions = defineCommand({\n meta: { name: \"submissions\", description: \"List form submissions, newest first\" },\n args: { ...globalArgs, ...id, cursor: { type: \"string\" }, limit: { type: \"string\", description: \"Page size (default 25)\" } },\n run: defineRun(async (ctx, args) => {\n const page = await ctx.client().pages.submissions(args.id, { cursor: args.cursor, limit: args.limit ? Number(args.limit) : undefined });\n if (ctx.json) return ctx.out.printJson(page);\n const rows = page.data.map((s) => [\n new Date(s.createdAt).toISOString(),\n s.submitterEmail ?? \"—\",\n s.fields.map((f) => `${f.name}=${f.value}`).join(\" \"),\n ]);\n for (const line of renderTable([\"DATE\", \"EMAIL\", \"FIELDS\"], rows, ctx.out.palette.dim)) ctx.out.print(line);\n if (page.nextCursor) ctx.out.print(ctx.out.palette.dim(`More: --cursor ${page.nextCursor}`));\n }),\n});\n\nconst rangeArgs = {\n start: { type: \"string\", description: \"Epoch ms or ISO 8601 (default 7 days ago)\" },\n end: { type: \"string\", description: \"Epoch ms or ISO 8601 (default now)\" },\n} as const;\n\nconst visits = defineCommand({\n meta: { name: \"visits\", description: \"Visits and visitors by day\" },\n args: { ...globalArgs, ...id, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const summary = await ctx.client().pages.visits(args.id, { start: args.start, end: args.end });\n if (ctx.json) return ctx.out.printJson(summary);\n ctx.out.print(`${summary.visits} visits, ${summary.visitors} visitors`);\n for (const line of renderTable(\n [\"DAY\", \"VISITS\", \"VISITORS\"],\n summary.days.map((d) => [d.day, String(d.visits), String(d.visitors)]),\n ctx.out.palette.dim,\n ))\n ctx.out.print(line);\n }),\n});\n\nconst clicks = defineCommand({\n meta: { name: \"clicks\", description: \"Tracked clicks by day and top targets\" },\n args: { ...globalArgs, ...id, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const summary = await ctx.client().pages.clicks(args.id, { start: args.start, end: args.end });\n if (ctx.json) return ctx.out.printJson(summary);\n ctx.out.print(`${summary.clicks} clicks, ${summary.visitors} visitors`);\n const rows = summary.topTargets.map((t) => [t.pathname, t.elementKey, t.label, String(t.clicks), String(t.visitors)]);\n for (const line of renderTable([\"PATH\", \"ELEMENT\", \"LABEL\", \"CLICKS\", \"VISITORS\"], rows, ctx.out.palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const pages = defineCommand({\n meta: { name: \"pages\", description: \"Hosted pages\" },\n args: { ...globalArgs },\n subCommands: {\n list,\n get,\n files,\n deploy,\n update,\n publish: setPublished(true),\n unpublish: setPublished(false),\n delete: del,\n submissions,\n visits,\n clicks,\n },\n});\n","import type { PageTracking, PageTrackingInput, TrackingMode } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { type CliContext, globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\ntype Section = {\n enabled?: boolean;\n mode?: string;\n pixelId?: string | null;\n measurementId?: string | null;\n hasConversionsApiToken?: boolean;\n events?: object;\n paths?: { path: string; pixelId: string; hasConversionsApiToken: boolean }[];\n};\n\n/** Print Meta and GA as label/value rows; works for account, product and page shapes. */\nfunction printTracking(ctx: CliContext, tracking: { meta: Section; googleAnalytics: Section }): void {\n const { palette } = ctx.out;\n const describe = (section: Section, id: string | null | undefined) => {\n const state = section.mode ?? (section.enabled ? \"enabled\" : \"disabled\");\n const events = Object.entries(section.events ?? {})\n .filter(([, on]) => on)\n .map(([name]) => name)\n .join(\", \");\n return `${state}${id ? ` (${id})` : \"\"}${section.hasConversionsApiToken ? \", CAPI token set\" : \"\"}${events ? palette.dim(` events: ${events}`) : \"\"}`;\n };\n ctx.out.print(`${palette.dim(\"Meta\")} ${describe(tracking.meta, tracking.meta.pixelId)}`);\n for (const p of tracking.meta.paths ?? []) {\n ctx.out.print(`${palette.dim(\" \")}${p.path} → ${p.pixelId}${p.hasConversionsApiToken ? \", CAPI token set\" : \"\"}`);\n }\n ctx.out.print(`${palette.dim(\"GA \")} ${describe(tracking.googleAnalytics, tracking.googleAnalytics.measurementId)}`);\n}\n\nconst metaArgs = {\n \"meta-pixel-id\": { type: \"string\", description: \"Meta pixel id (10–20 digits)\" },\n \"meta-token\": { type: \"string\", description: 'Meta Conversions API token (write-only; \"\" clears, omit keeps)' },\n \"ga-measurement-id\": { type: \"string\", description: \"GA4 measurement id (G-XXXXXXX)\" },\n} as const;\n\n// shortcut: event toggles are not exposed as flags (a set resets them to the all-on default); add --meta-events/--ga-events when someone asks.\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show account tracking defaults\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().tracking.get();\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n});\n\nconst set = defineCommand({\n meta: { name: \"set\", description: \"Set account tracking defaults (only the sections you pass flags for are changed)\" },\n args: {\n ...globalArgs,\n ...metaArgs,\n \"meta-enabled\": { type: \"boolean\", description: \"Enable the account Meta pixel (--no-meta-enabled removes it and its token)\" },\n \"ga-enabled\": { type: \"boolean\", description: \"Enable account Google Analytics (--no-ga-enabled removes it)\" },\n },\n run: defineRun(async (ctx, args) => {\n const metaTouched = args[\"meta-enabled\"] !== undefined || args[\"meta-pixel-id\"] !== undefined || args[\"meta-token\"] !== undefined;\n const gaTouched = args[\"ga-enabled\"] !== undefined || args[\"ga-measurement-id\"] !== undefined;\n const result = await ctx.client().tracking.set({\n meta: metaTouched\n ? { enabled: args[\"meta-enabled\"] ?? true, pixelId: args[\"meta-pixel-id\"], conversionsApiToken: args[\"meta-token\"] }\n : undefined,\n googleAnalytics: gaTouched ? { enabled: args[\"ga-enabled\"] ?? true, measurementId: args[\"ga-measurement-id\"] } : undefined,\n });\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n});\n\nconst productId = { type: \"positional\", required: true, description: \"Product id or config key\" } as const;\nconst pageId = { type: \"positional\", required: true, description: \"Page id\" } as const;\n\nconst overrideArgs = {\n ...globalArgs,\n ...metaArgs,\n id: { type: \"positional\", required: true },\n \"meta-mode\": { type: \"string\", description: \"inherit | custom | disabled (defaults to custom when a pixel id or token is given)\" },\n \"ga-mode\": { type: \"string\", description: \"inherit | custom | disabled (defaults to custom when a measurement id is given)\" },\n} as const;\n\nconst pageOverrideArgs = {\n ...overrideArgs,\n \"meta-paths\": {\n type: \"string\",\n description: 'Pages only: per-path pixels as \"/path=PIXEL_ID[:CAPI_TOKEN],…\" (\"\" clears them; an omitted token keeps the stored one)',\n },\n} as const;\n\n/** \"/ad1=123:EAAB,/ad2=456\" → [{ path, pixelId, conversionsApiToken? }]. */\nexport function parseMetaPaths(raw: string): { path: string; pixelId: string; conversionsApiToken?: string }[] {\n return raw\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => {\n const eq = part.indexOf(\"=\");\n if (eq < 1) throw new Error(`--meta-paths entry \"${part}\" must look like /path=PIXEL_ID[:CAPI_TOKEN]`);\n const [pixelId = \"\", ...token] = part.slice(eq + 1).split(\":\");\n return { path: part.slice(0, eq), pixelId, conversionsApiToken: token.length > 0 ? token.join(\":\") : undefined };\n });\n}\n\n/** The page's stored meta settings as a set input; events included, since an omitted toggle resets to its default. */\nexport function currentMetaInput(current: PageTracking[\"meta\"]): NonNullable<PageTrackingInput[\"meta\"]> {\n return { mode: current.mode, pixelId: current.pixelId ?? undefined, events: current.events };\n}\n\nfunction overrideInput(args: { [K in keyof typeof overrideArgs]?: string | boolean }) {\n const metaMode = (args[\"meta-mode\"] ?? (args[\"meta-pixel-id\"] !== undefined || args[\"meta-token\"] !== undefined ? \"custom\" : undefined)) as\n | TrackingMode\n | undefined;\n const gaMode = (args[\"ga-mode\"] ?? (args[\"ga-measurement-id\"] !== undefined ? \"custom\" : undefined)) as TrackingMode | undefined;\n return {\n meta: metaMode\n ? { mode: metaMode, pixelId: args[\"meta-pixel-id\"] as string | undefined, conversionsApiToken: args[\"meta-token\"] as string | undefined }\n : undefined,\n googleAnalytics: gaMode ? { mode: gaMode, measurementId: args[\"ga-measurement-id\"] as string | undefined } : undefined,\n };\n}\n\nconst product = defineCommand({\n meta: { name: \"product\", description: \"Per-product tracking override\" },\n args: { ...globalArgs },\n subCommands: {\n get: defineCommand({\n meta: { name: \"get\", description: \"Show a product's tracking settings (by id or config key)\" },\n args: { ...globalArgs, id: productId },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().tracking.getProduct(args.id);\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n set: defineCommand({\n meta: { name: \"set\", description: \"Set a product's tracking override (by id or config key)\" },\n args: overrideArgs,\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().tracking.setProduct(args.id, overrideInput(args));\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n },\n});\n\nconst page = defineCommand({\n meta: { name: \"page\", description: \"Per-page tracking override\" },\n args: { ...globalArgs },\n subCommands: {\n get: defineCommand({\n meta: { name: \"get\", description: \"Show a hosted page's tracking settings\" },\n args: { ...globalArgs, id: pageId },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().tracking.getPage(args.id);\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n set: defineCommand({\n meta: { name: \"set\", description: \"Set a hosted page's tracking override\" },\n args: pageOverrideArgs,\n run: defineRun(async (ctx, args) => {\n const input = overrideInput(args);\n const paths = args[\"meta-paths\"] === undefined ? undefined : parseMetaPaths(args[\"meta-paths\"]);\n let meta: PageTrackingInput[\"meta\"] = input.meta;\n if (paths !== undefined) {\n // Path overrides ride on the meta section; with no other meta flags, re-send the page's current settings.\n meta = { ...(meta ?? currentMetaInput((await ctx.client().tracking.getPage(args.id)).meta)), paths };\n }\n const result = await ctx.client().tracking.setPage(args.id, { ...input, meta });\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n },\n});\n\nexport const tracking = defineCommand({\n meta: { name: \"tracking\", description: \"Tracking defaults (Meta pixel, Google Analytics)\" },\n args: { ...globalArgs },\n subCommands: { get, set, product, page },\n});\n","import { type Domain } from \"@purpleturret/sdk\";\nimport { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { type: \"positional\", required: true, description: \"Domain id\" } as const;\n\nfunction printDomain(ctx: CliContext, domain: Domain): void {\n if (ctx.json) return ctx.out.printJson(domain);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"ID\", domain.id],\n [\"HOSTNAME\", domain.hostname],\n [\"STATUS\", domain.status],\n [\"VERIFIED\", String(domain.verified)],\n [\"DNS\", domain.dnsConfigured ? \"configured\" : \"not configured\"],\n [\"PAGE\", domain.pageId ?? palette.dim(\"—\")],\n [\"PRODUCTS\", domain.productIds.join(\", \") || palette.dim(\"—\")],\n [\"DEFAULT\", domain.defaultProductId ?? palette.dim(\"—\")],\n ];\n if (domain.lastError) rows.push([\"ERROR\", palette.red(domain.lastError)]);\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n if (domain.dnsRecords.length) {\n ctx.out.print(\"\");\n for (const line of renderTable(\n [\"TYPE\", \"NAME\", \"VALUE\"],\n domain.dnsRecords.map((r) => [r.type, r.name, r.value]),\n palette.dim,\n ))\n ctx.out.print(line);\n }\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List custom domains\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().domains.list();\n if (ctx.json) return ctx.out.printJson({ domains: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No custom domains yet.\"));\n const rows = data.map((d) => [\n d.id,\n d.hostname,\n d.status === \"active\" ? \"active\" : d.status === \"error\" ? palette.red(\"error\") : palette.yellow(\"pending\"),\n d.pageId ?? palette.dim(\"—\"),\n ]);\n for (const line of renderTable([\"ID\", \"HOSTNAME\", \"STATUS\", \"PAGE\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show a custom domain and its DNS records\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printDomain(ctx, await ctx.client().domains.get(args.id))),\n});\n\nconst add = defineCommand({\n meta: { name: \"add\", description: \"Add a custom domain\" },\n args: {\n ...globalArgs,\n hostname: { type: \"positional\", required: true, description: \"Hostname, e.g. shop.example.com\" },\n \"routing-type\": { type: \"string\", description: \"DNS record hint: A or CNAME\" },\n },\n run: defineRun(async (ctx, args) => {\n const routingType = args[\"routing-type\"]?.toUpperCase();\n if (routingType !== undefined && routingType !== \"A\" && routingType !== \"CNAME\") throw new Error(\"--routing-type must be A or CNAME\");\n printDomain(ctx, await ctx.client().domains.add({ hostname: args.hostname, routingType }));\n }),\n});\n\nconst verify = defineCommand({\n meta: { name: \"verify\", description: \"Re-check DNS with the provider\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printDomain(ctx, await ctx.client().domains.verify(args.id))),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Attach a page, set the checkout allowlist, or set the default checkout link\" },\n args: {\n ...globalArgs,\n id,\n page: { type: \"string\", description: \"Page id to serve at /\" },\n \"no-page\": { type: \"boolean\", description: \"Detach the page\" },\n products: { type: \"string\", description: \"Comma-separated product ids (replaces the allowlist)\" },\n default: { type: \"string\", description: \"Default product id for /\" },\n \"no-default\": { type: \"boolean\", description: \"Clear the default product\" },\n },\n run: defineRun(async (ctx, args) => {\n const domain = await ctx.client().domains.update(args.id, {\n pageId: args[\"no-page\"] ? null : args.page,\n productIds:\n args.products === undefined\n ? undefined\n : args.products\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean),\n defaultProductId: args[\"no-default\"] ? null : args.default,\n });\n printDomain(ctx, domain);\n }),\n});\n\nconst remove = defineCommand({\n meta: { name: \"remove\", description: \"Remove a custom domain\" },\n args: { ...globalArgs, id, yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes && !unwrapPrompt(await confirm({ message: `Remove domain ${args.id}?`, initialValue: false }))) return;\n printDomain(ctx, await ctx.client().domains.remove(args.id));\n }),\n});\n\nexport const domains = defineCommand({\n meta: { name: \"domains\", description: \"Custom domains\" },\n args: { ...globalArgs },\n subCommands: { list, get, add, verify, update, remove },\n});\n","import { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\n\n/** Print a result as JSON or as dim-label key/value rows. */\nfunction printRows(ctx: CliContext, result: unknown, rows: [string, string][]) {\n if (ctx.json) return ctx.out.printJson(result);\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) ctx.out.print(`${ctx.out.palette.dim(label.padEnd(width))} ${value}`);\n}\n\n/** Flag value or env var; fails with a usage error when neither is set. */\nfunction secret(value: unknown, env: NodeJS.ProcessEnv, flag: string, envName: string): string {\n const resolved = typeof value === \"string\" && value ? value : env[envName];\n if (!resolved) throw new CliError(`Missing --${flag} (or ${envName}).`, EXIT.USAGE, { code: \"usage\" });\n return resolved;\n}\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show the account behind the current key\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const account = await ctx.client().account.get();\n printRows(ctx, account, [\n [\"Email\", account.email],\n [\"Name\", account.name ?? ctx.out.palette.dim(\"—\")],\n [\"Stripe\", account.stripe.connected ? (account.stripe.chargesEnabled ? \"connected\" : \"connected (charges not enabled)\") : \"not connected\"],\n [\"PayPal\", account.paypal.connected ? \"connected\" : \"not connected\"],\n [\"Scopes\", account.key.scopes.join(\", \")],\n ]);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Update profile name and enabled checkout providers\" },\n args: {\n ...globalArgs,\n \"given-name\": { type: \"string\", description: \"First name\" },\n \"family-name\": { type: \"string\", description: \"Last name\" },\n stripe: { type: \"boolean\", description: \"Enable/disable Stripe at checkout (pair with --paypal/--no-paypal)\" },\n paypal: { type: \"boolean\", description: \"Enable/disable PayPal at checkout (pair with --stripe/--no-stripe)\" },\n },\n run: defineRun(async (ctx, args) => {\n const providers = args.stripe !== undefined || args.paypal !== undefined;\n if (providers && (args.stripe === undefined || args.paypal === undefined)) {\n throw new CliError(\"Pass both --stripe/--no-stripe and --paypal/--no-paypal.\", EXIT.USAGE, { code: \"usage\" });\n }\n const account = await ctx.client().account.update({\n givenName: args[\"given-name\"],\n familyName: args[\"family-name\"],\n checkoutProviders: providers ? { stripe: Boolean(args.stripe), paypal: Boolean(args.paypal) } : undefined,\n });\n printRows(ctx, account, [\n [\"Name\", [account.profile.givenName, account.profile.familyName].filter(Boolean).join(\" \") || ctx.out.palette.dim(\"—\")],\n [\"Checkout\", `stripe=${account.checkoutProviders.stripe} paypal=${account.checkoutProviders.paypal}`],\n ]);\n }),\n});\n\nconst stripeStatus = defineCommand({\n meta: { name: \"status\", description: \"Stripe connection state and outstanding requirements\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const status = await ctx.client().account.stripeStatus();\n printRows(ctx, status, [\n [\"State\", status.state],\n [\"Mode\", status.account?.connectionMode ?? ctx.out.palette.dim(\"—\")],\n [\"Charges\", String(status.account?.chargesEnabled ?? false)],\n [\"Payouts\", String(status.account?.payoutsEnabled ?? false)],\n [\"Country\", status.account?.country ?? ctx.out.palette.dim(\"—\")],\n [\"Needs\", status.items.map((item) => `${item.label} (${item.severity})`).join(\", \") || ctx.out.palette.dim(\"nothing\")],\n [\"Disabled\", status.disabledReason ?? ctx.out.palette.dim(\"—\")],\n [\"Migration\", status.migration ? `${status.migration.status} (${status.migration.phase})` : ctx.out.palette.dim(\"none\")],\n ]);\n }),\n});\n\nconst stripeOnboard = defineCommand({\n meta: { name: \"onboard\", description: \"Create a Stripe Connect onboarding link\" },\n args: {\n ...globalArgs,\n country: { type: \"string\", description: \"ISO-3166 alpha-2; required when no Stripe account exists yet\" },\n \"return-to\": { type: \"string\", description: \"Dashboard path to return to (must start with /dashboard/)\" },\n },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().account.stripeOnboardingLink({ country: args.country, returnTo: args[\"return-to\"] });\n printRows(ctx, result, [[\"URL\", result.url]]);\n }),\n});\n\nconst stripeRefresh = defineCommand({\n meta: { name: \"refresh\", description: \"Re-read capabilities from Stripe\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().account.stripeRefresh();\n printRows(ctx, result, [\n [\"Ready\", String(result.ready)],\n [\"Transfers\", result.transfersStatus],\n [\"Payouts\", String(result.payoutsEnabled)],\n [\"Disabled\", result.disabledReason ?? ctx.out.palette.dim(\"—\")],\n ]);\n }),\n});\n\nconst stripeConnectKey = defineCommand({\n meta: { name: \"connect-key\", description: \"Connect Stripe with your own API keys instead of Connect\" },\n args: {\n ...globalArgs,\n \"secret-key\": { type: \"string\", description: \"sk_/rk_ key (default: STRIPE_SECRET_KEY)\" },\n \"publishable-key\": { type: \"string\", description: \"pk_ key (default: STRIPE_PUBLISHABLE_KEY)\" },\n \"migrate-customers\": { type: \"boolean\", description: \"Also copy customers when migrating from a Connect account\" },\n },\n run: defineRun(async (ctx, args) => {\n const status = await ctx.client().account.stripeConnectApiKey({\n secretKey: secret(args[\"secret-key\"], ctx.env, \"secret-key\", \"STRIPE_SECRET_KEY\"),\n publishableKey: secret(args[\"publishable-key\"], ctx.env, \"publishable-key\", \"STRIPE_PUBLISHABLE_KEY\"),\n migration: args[\"migrate-customers\"] !== undefined ? { includeCustomers: Boolean(args[\"migrate-customers\"]) } : undefined,\n });\n printRows(ctx, status, [\n [\"State\", status.state],\n [\"Mode\", status.account?.connectionMode ?? ctx.out.palette.dim(\"—\")],\n [\"Migration\", status.migration ? `${status.migration.status} (${status.migration.phase})` : ctx.out.palette.dim(\"none\")],\n ]);\n }),\n});\n\nconst stripeBranding = defineCommand({\n meta: { name: \"branding\", description: \"Set checkout branding on the connected Stripe account\" },\n args: {\n ...globalArgs,\n \"primary-color\": { type: \"string\", description: \"Hex color, e.g. #7c3aed\" },\n \"logo-url\": { type: \"string\", description: \"https:// logo URL\" },\n },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().account.stripeBranding({ primaryColor: args[\"primary-color\"], logoUrl: args[\"logo-url\"] });\n printRows(ctx, result, [[\"Applied\", String(result.applied)]]);\n }),\n});\n\nconst stripe = defineCommand({\n meta: { name: \"stripe\", description: \"Stripe connection\" },\n args: { ...globalArgs },\n subCommands: { status: stripeStatus, onboard: stripeOnboard, refresh: stripeRefresh, \"connect-key\": stripeConnectKey, branding: stripeBranding },\n});\n\nconst paypalRows = (ctx: CliContext, status: Awaited<ReturnType<ReturnType<CliContext[\"client\"]>[\"account\"][\"paypalStatus\"]>>) =>\n printRows(ctx, status, [\n [\"State\", status.state],\n [\"Client ID\", status.account?.clientId ?? ctx.out.palette.dim(\"—\")],\n [\"Environment\", status.account?.environment ?? ctx.out.palette.dim(\"default\")],\n [\"Email\", status.account?.email ?? ctx.out.palette.dim(\"—\")],\n ]);\n\nconst paypalStatus = defineCommand({\n meta: { name: \"status\", description: \"PayPal connection state\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => paypalRows(ctx, await ctx.client().account.paypalStatus())),\n});\n\nconst paypalConnect = defineCommand({\n meta: { name: \"connect\", description: \"Connect PayPal with REST API credentials\" },\n args: {\n ...globalArgs,\n \"client-id\": { type: \"string\", description: \"PayPal client id (default: PAYPAL_CLIENT_ID)\" },\n secret: { type: \"string\", description: \"PayPal secret (default: PAYPAL_SECRET)\" },\n },\n run: defineRun(async (ctx, args) =>\n paypalRows(\n ctx,\n await ctx.client().account.paypalConnect({\n clientId: secret(args[\"client-id\"], ctx.env, \"client-id\", \"PAYPAL_CLIENT_ID\"),\n secret: secret(args.secret, ctx.env, \"secret\", \"PAYPAL_SECRET\"),\n }),\n ),\n ),\n});\n\nconst paypalDisconnect = defineCommand({\n meta: { name: \"disconnect\", description: \"Disconnect PayPal\" },\n args: { ...globalArgs, yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes) {\n const approved = unwrapPrompt(await confirm({ message: \"Disconnect PayPal? Buyers will no longer see it at checkout.\", initialValue: false }));\n if (!approved) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n paypalRows(ctx, await ctx.client().account.paypalDisconnect());\n }),\n});\n\nconst paypal = defineCommand({\n meta: { name: \"paypal\", description: \"PayPal connection\" },\n args: { ...globalArgs },\n subCommands: { status: paypalStatus, connect: paypalConnect, disconnect: paypalDisconnect },\n});\n\nconst billingPortal = defineCommand({\n meta: { name: \"billing-portal\", description: \"Open a link to manage your Purpleturret plan\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().account.billingPortal();\n printRows(ctx, result, [[\"URL\", result.url]]);\n }),\n});\n\nconst keys = defineCommand({\n meta: { name: \"keys\", description: \"List API keys on the account\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().account.keys.list();\n ctx.out.printJson(result);\n }),\n});\n\nexport const account = defineCommand({\n meta: { name: \"account\", description: \"Account, Stripe and PayPal\" },\n args: { ...globalArgs },\n subCommands: { get, update, stripe, paypal, \"billing-portal\": billingPortal, keys },\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\nexport const support = defineCommand({\n meta: { name: \"support\", description: \"Message Purpleturret support\" },\n args: {\n ...globalArgs,\n message: { type: \"positional\", required: true, description: \"The message (10–5000 characters)\" },\n subject: { type: \"string\", description: \"Subject line (≤160 characters)\" },\n },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().support.create({ message: args.message, subject: args.subject });\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.success(`Sent. We'll reply to your account email. (ref ${result.id})`);\n }),\n});\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { renderConfigSource, renderStarterConfig, type ConfigFormat } from \"../lib/pull-writer\";\nimport { defineRun } from \"../lib/run\";\n\nexport const init = defineCommand({\n meta: { name: \"init\", description: \"Create a purpleturret.config.ts in the current directory\" },\n args: {\n ...globalArgs,\n \"from-remote\": { type: \"boolean\", description: \"Seed the file with the products already managed on your account\" },\n force: { type: \"boolean\", description: \"Overwrite an existing config file\" },\n format: { type: \"string\", description: \"File format: ts (default) or json\" },\n },\n run: defineRun(async (ctx, args) => {\n const formatArg = (args.format ?? \"ts\").toLowerCase();\n if (formatArg !== \"ts\" && formatArg !== \"json\") {\n throw new CliError(`Unknown --format \"${args.format}\"; expected ts or json.`, EXIT.USAGE, { code: \"usage\" });\n }\n const format: ConfigFormat = formatArg;\n const target = resolve(ctx.cwd, ctx.configPath ?? `purpleturret.config.${format}`);\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --config <path> to write elsewhere.\",\n });\n }\n\n let source: string;\n let count: number;\n if (args[\"from-remote\"]) {\n const { products } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n source = renderConfigSource(inputs, format);\n count = inputs.length;\n } else {\n source = renderStarterConfig(format);\n count = 1;\n }\n await writeFile(target, source, \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ written: target, products: count, from_remote: Boolean(args[\"from-remote\"]) });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Created ${relative(ctx.cwd, target) || target}${args[\"from-remote\"] ? ` with ${count} product${count === 1 ? \"\" : \"s\"} from your account` : \"\"}`,\n );\n ctx.out.info(\"\");\n ctx.out.info(\"Next steps:\");\n if (format === \"ts\") ctx.out.info(` ${palette.dim(\"1.\")} pnpm add -D @purpleturret/sdk ${palette.dim(\"(types + helpers used by the config)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"2.\" : \"1.\")} purpleturret login ${palette.dim(\"(or set PURPLETURRET_API_KEY)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"3.\" : \"2.\")} purpleturret push --dry-run`);\n }),\n});\n","import type { ProductInput, PurpleturretConfig } from \"@purpleturret/sdk\";\n\nexport type ConfigFormat = \"ts\" | \"json\";\n\nconst PRODUCT_KEY_ORDER: (keyof ProductInput)[] = [\n \"key\",\n \"name\",\n \"description\",\n \"price\",\n \"billing\",\n \"slug\",\n \"group\",\n \"credits\",\n \"delivery\",\n \"checkout\",\n \"theme\",\n \"stripe\",\n \"active\",\n \"buyerEmails\",\n \"offers\",\n \"tabTitle\",\n];\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** Serialize products into a `purpleturret.config.ts` (or `.json`) source string. */\nexport function renderConfigSource(products: ProductInput[], format: ConfigFormat = \"ts\"): string {\n if (format === \"json\") {\n const config: PurpleturretConfig = { products: products.map(orderProductKeys) };\n return `${JSON.stringify(config, null, 2)}\\n`;\n }\n\n const helpers = new Set<string>([\"defineConfig\", \"product\"]);\n const body = products.map((product) => renderProduct(product, helpers, 4)).join(\"\\n\");\n const imports = [\"defineConfig\", \"money\", \"product\", \"usd\"].filter((name) => helpers.has(name));\n const productsBlock = products.length ? `[\\n${body}\\n ]` : \"[]\";\n return [\n `import { ${imports.join(\", \")} } from \"@purpleturret/sdk\";`,\n \"\",\n \"export default defineConfig({\",\n ` products: ${productsBlock},`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Starter config written by `purpleturret init`. */\nexport function renderStarterConfig(format: ConfigFormat = \"ts\"): string {\n const example: ProductInput = {\n key: \"pro_monthly\",\n name: \"Pro\",\n description: \"Everything you need to get started.\",\n price: { amount: 2900, currency: \"usd\" },\n billing: { type: \"recurring\", interval: \"month\" },\n group: { key: \"my_app\", tier: { key: \"pro\", name: \"Pro\", rank: 1 } },\n delivery: { method: \"none\" },\n };\n if (format === \"json\") return renderConfigSource([example], \"json\");\n return [\n \"// Purpleturret product catalog. Push with `purpleturret push`; preview with `purpleturret push --dry-run`.\",\n \"// Docs: https://purpleturret.com/docs/cli\",\n renderConfigSource([example], \"ts\"),\n ].join(\"\\n\");\n}\n\nfunction orderProductKeys(product: ProductInput): ProductInput {\n const out: Record<string, unknown> = {};\n for (const key of PRODUCT_KEY_ORDER) {\n if (product[key] !== undefined) out[key] = product[key];\n }\n return out as unknown as ProductInput;\n}\n\nfunction renderProduct(product: ProductInput, helpers: Set<string>, indent: number): string {\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n const lines: string[] = [`${pad}product({`];\n for (const key of PRODUCT_KEY_ORDER) {\n const value = product[key];\n if (value === undefined) continue;\n let rendered: string;\n if (key === \"price\") {\n rendered = renderPrice(product.price, helpers);\n } else {\n rendered = renderValue(value, indent + 2);\n }\n lines.push(`${inner}${key}: ${rendered},`);\n }\n lines.push(`${pad}}),`);\n return lines.join(\"\\n\");\n}\n\nfunction renderPrice(price: ProductInput[\"price\"], helpers: Set<string>): string {\n if (price.currency === \"usd\") {\n helpers.add(\"usd\");\n return `usd(${formatDollars(price.amount)})`;\n }\n helpers.add(\"money\");\n return `money(${price.amount}, ${JSON.stringify(price.currency)})`;\n}\n\nfunction formatDollars(cents: number): string {\n if (cents % 100 === 0) return String(cents / 100);\n return (cents / 100).toFixed(2);\n}\n\nfunction renderKey(key: string): string {\n return IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n\nfunction isFlat(value: unknown): boolean {\n if (Array.isArray(value)) return value.every((entry) => entry === null || typeof entry !== \"object\");\n if (value && typeof value === \"object\")\n return Object.values(value as Record<string, unknown>).every((entry) => entry === null || typeof entry !== \"object\");\n return true;\n}\n\nexport function renderValue(value: unknown, indent: number): string {\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (typeof value === \"undefined\") return \"undefined\";\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n if (Array.isArray(value)) {\n if (value.length === 0) return \"[]\";\n if (isFlat(value)) {\n const inline = `[${value.map((entry) => renderValue(entry, indent + 2)).join(\", \")}]`;\n if (inline.length + indent <= 100) return inline;\n }\n return `[\\n${value.map((entry) => `${inner}${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}]`;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(([, entry]) => entry !== undefined);\n if (entries.length === 0) return \"{}\";\n if (isFlat(value)) {\n const inline = `{ ${entries.map(([key, entry]) => `${renderKey(key)}: ${renderValue(entry, indent + 2)}`).join(\", \")} }`;\n if (inline.length + indent <= 100) return inline;\n }\n return `{\\n${entries.map(([key, entry]) => `${inner}${renderKey(key)}: ${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}}`;\n }\n return JSON.stringify(value);\n}\n","import { password } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\n\nexport const login = defineCommand({\n meta: { name: \"login\", description: \"Validate a seller API key and save it to ~/.config/purpleturret/credentials.json\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n let apiKey = ctx.credentialSource === \"flag\" || ctx.credentialSource === \"env\" ? ctx.apiKey : null;\n if (!apiKey) {\n if (!isInteractive()) {\n throw new CliError(\"No API key provided and stdin is not a terminal.\", EXIT.USAGE, {\n code: \"missing_api_key\",\n hint: \"Pass --api-key <pt_sk_…> or set PURPLETURRET_API_KEY when logging in non-interactively.\",\n });\n }\n const entered = unwrapPrompt(\n await password({\n message: \"Paste your seller API key (pt_sk_…). Mint one in Dashboard → Settings → Developers.\",\n validate: (value) => (value && value.trim().length > 0 ? undefined : \"An API key is required\"),\n }),\n );\n apiKey = entered.trim();\n }\n if (apiKey.startsWith(\"pt_host_\")) {\n throw new CliError(\"That is a hosting key (pt_host_…). The CLI needs a seller key (pt_sk_…).\", EXIT.AUTH, { code: \"forbidden_key_type\" });\n }\n\n const client = ctx.clientFor(apiKey);\n const account = await client.account.get();\n const apiUrl = ctx.apiUrlSource === \"default\" ? undefined : ctx.apiUrl;\n await ctx.credentials.saveProfile(ctx.profileName, {\n apiKey,\n apiUrl,\n email: account.email,\n keyPrefix: account.key.prefix,\n scopes: account.key.scopes,\n savedAt: new Date().toISOString(),\n });\n\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, credentials_file: ctx.credentials.path, api_url: ctx.apiUrl, account });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Logged in as ${palette.bold(account.email)} with key ${account.key.prefix}… (scopes: ${account.key.scopes.join(\", \") || \"none\"})`,\n );\n ctx.out.info(palette.dim(`Saved profile \"${ctx.profileName}\" to ${ctx.credentials.path} (mode 0600)`));\n if (!account.stripe.connected) ctx.out.warn(\"Stripe is not connected on this account yet; `push` cannot create products until it is.\");\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\nexport const logout = defineCommand({\n meta: { name: \"logout\", description: \"Remove the saved credentials profile\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const removed = await ctx.credentials.deleteProfile(ctx.profileName);\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, removed });\n return;\n }\n if (removed) ctx.out.success(`Removed profile \"${ctx.profileName}\" from ${ctx.credentials.path}`);\n else ctx.out.warn(`No profile \"${ctx.profileName}\" in ${ctx.credentials.path}; nothing to do.`);\n }),\n});\n","import { serveStdio } from \"@modelcontextprotocol/server/stdio\";\nimport { createPurpleturretMcpServer } from \"@purpleturret/mcp\";\nimport { PurpleturretApiError } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { defineRun } from \"../lib/run\";\nimport { CLI_VERSION } from \"../version\";\n\nexport const mcp = defineCommand({\n meta: {\n name: \"mcp\",\n description: \"Run the Purpleturret MCP server over stdio for Claude Code, Cursor, Codex and other agents\",\n },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const client = ctx.client();\n // Fail fast on a rejected key; a key that merely lacks config:read still works for its own scopes.\n try {\n await client.account.get();\n } catch (error) {\n if (error instanceof PurpleturretApiError && error.status === 401) {\n throw new CliError(\"The API key was rejected.\", EXIT.AUTH, { code: \"invalid_api_key\", hint: \"Run `purpleturret login` with a valid key.\" });\n }\n if (!(error instanceof PurpleturretApiError && error.status === 403)) throw error;\n }\n ctx.out.debug(`MCP server ready (${ctx.apiUrl})`);\n const handle = serveStdio(() => createPurpleturretMcpServer(client, { version: CLI_VERSION }), {\n onerror: (error) => ctx.out.debug(`mcp: ${error.message}`),\n });\n await new Promise<void>((resolve) => {\n const stop = () => void handle.close().finally(resolve);\n process.stdin.once(\"end\", stop);\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n });\n }),\n});\n","import { McpServer, type CallToolResult, type ToolAnnotations, type ToolCallback } from \"@modelcontextprotocol/server\";\nimport { PurpleturretApiError, PurpleturretClient, SDK_VERSION } from \"@purpleturret/sdk\";\nimport type { z } from \"zod\";\n\nimport { registerCoreTools } from \"./tools/core\";\nimport { registerAccountTools } from \"./tools/account\";\nimport { registerProductsTools } from \"./tools/products\";\nimport { registerOrdersTools } from \"./tools/orders\";\nimport { registerPixelsTools } from \"./tools/pixels\";\nimport { registerPagesTools } from \"./tools/pages\";\nimport { registerTrackingTools } from \"./tools/tracking\";\nimport { registerDomainsTools } from \"./tools/domains\";\nimport { registerWebhooksTools } from \"./tools/webhooks\";\n\nexport { createMcpHandler } from \"@modelcontextprotocol/server\";\nexport { PurpleturretClient };\n\nexport interface PurpleturretMcpOptions {\n /** Reported as the MCP server version; defaults to the SDK's. */\n version?: string;\n}\n\nexport const READ: ToolAnnotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };\nexport const WRITE: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };\nexport const CREATE: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };\nexport const DESTRUCTIVE: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };\n\ntype ToolResult = CallToolResult;\n\nfunction text(value: unknown): ToolResult {\n return { content: [{ type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2) }] };\n}\n\nfunction errorText(error: unknown): ToolResult {\n const message =\n error instanceof PurpleturretApiError\n ? `${error.status} ${error.code}: ${error.message}${error.requestId ? ` (request ${error.requestId})` : \"\"}`\n : error instanceof Error\n ? error.message\n : String(error);\n return { content: [{ type: \"text\", text: message }], isError: true };\n}\n\n/** Registers one tool: the SDK call's result is JSON-stringified, API errors become `isError` results. */\nexport type ToolRegistrar = <S extends z.ZodObject>(\n name: string,\n description: string,\n schema: S,\n annotations: ToolAnnotations,\n run: (args: z.output<S>) => Promise<unknown>,\n) => void;\n\n/**\n * Builds the Purpleturret MCP server over an SDK client. Every tool proxies one seller REST API call,\n * so stdio (CLI) and the hosted endpoint behave identically.\n */\nexport function createPurpleturretMcpServer(client: PurpleturretClient, options: PurpleturretMcpOptions = {}): McpServer {\n const server = new McpServer({ name: \"purpleturret\", version: options.version ?? SDK_VERSION });\n\n const tool: ToolRegistrar = (name, description, schema, annotations, run) => {\n const cb = async (args: z.output<typeof schema>): Promise<ToolResult> => {\n try {\n return text(await run(args));\n } catch (error) {\n return errorText(error);\n }\n };\n // Generic zod objects do not unify with the SDK's StandardSchema inference; the runtime shape is identical.\n server.registerTool(name, { description, inputSchema: schema, annotations }, cb as unknown as ToolCallback<typeof schema>);\n };\n\n registerCoreTools(tool, client);\n registerAccountTools(tool, client);\n registerProductsTools(tool, client);\n registerOrdersTools(tool, client);\n registerPixelsTools(tool, client);\n registerPagesTools(tool, client);\n registerTrackingTools(tool, client);\n registerDomainsTools(tool, client);\n registerWebhooksTools(tool, client);\n\n server.registerResource(\n \"skill\",\n \"purpleturret://skill\",\n { title: \"Purpleturret agent skill\", description: \"SKILL.md: scopes, CLI, SDK, REST endpoints, MCP rules\", mimeType: \"text/markdown\" },\n async (uri) => ({\n contents: [{ uri: uri.href, mimeType: \"text/markdown\", text: await fetchText(\"https://purpleturret.com/skills/purpleturret/SKILL.md\") }],\n }),\n );\n server.registerResource(\n \"openapi\",\n \"purpleturret://openapi\",\n { title: \"Purpleturret OpenAPI\", description: \"OpenAPI 3.1 document for the seller REST API\", mimeType: \"application/json\" },\n async (uri) => ({\n contents: [{ uri: uri.href, mimeType: \"application/json\", text: await fetchText(`${client.baseUrl}/v1/openapi.json`) }],\n }),\n );\n\n return server;\n}\n\nasync function fetchText(url: string): Promise<string> {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`${url} returned ${response.status}`);\n return response.text();\n}\n","import { type CustomerSelector, type PurpleturretClient, productInputSchema } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst idOrKey = z.string().describe(\"Product id or config key\");\nconst shape = productInputSchema.shape;\nconst tier = z\n .object({ key: z.string(), name: z.string().max(80).optional(), rank: z.number().int().min(0).optional() })\n .nullable()\n .optional();\nconst bump = z.object({\n productId: z.string().describe(\"Product id or key\"),\n headline: z.string().max(80),\n description: z.string().max(240).optional(),\n});\nconst deliveryFile = z.object({\n objectKey: z.string(),\n fileName: z.string(),\n contentType: z.string().optional(),\n fileSize: z.number().int().positive(),\n});\n\nconst customer = {\n email: z.string().optional().describe(\"Buyer email; give this or externalId\"),\n externalId: z.string().optional().describe(\"Your own customer id, as passed at checkout\"),\n};\n// The SDK requires one of the two; it throws a TypeError (surfaced as isError) when both are missing.\nconst asCustomer = <T extends { email?: string; externalId?: string }>(a: T) => a as T & CustomerSelector;\n\n/** Config-as-code, credits and entitlements: the pre-parity surface. */\nexport function registerCoreTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\"get_account\", \"The seller account behind this API key: email, Stripe/PayPal status, key scopes.\", z.object({}), READ, () =>\n client.account.get(),\n );\n\n tool(\n \"list_products\",\n \"List checkout links (products). Returns a page with next_cursor.\",\n z.object({ cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional(), includeArchived: z.boolean().optional() }),\n READ,\n (a) => client.products.list(a),\n );\n tool(\"get_product\", \"Fetch one product by id or config key.\", z.object({ idOrKey }), READ, (a) => client.products.get(a.idOrKey));\n tool(\n \"create_product\",\n \"Create a checkout link (product). Needs a connected Stripe account and an active plan. Billing, currency and slug are immutable afterwards; file delivery is set with set_product_delivery.\",\n z.object({\n name: z.string().max(120),\n description: z.string().max(2000).nullable().optional(),\n price: shape.price,\n billing: shape.billing,\n slug: shape.slug.describe(\"Checkout slug (/c/<slug>); random when omitted\"),\n key: shape.key.optional().describe(\"Config key; omit for an unkeyed product\"),\n delivery: shape.delivery,\n checkout: shape.checkout,\n theme: shape.theme,\n pixelId: z.string().nullable().optional(),\n groupKey: z.string().nullable().optional().describe(\"Existing integration group key\"),\n tier,\n credits: shape.credits,\n active: z.boolean().optional(),\n buyerEmails: z.boolean().optional(),\n idempotencyKey: z.string().optional(),\n }),\n CREATE,\n ({ idempotencyKey, ...input }) => client.products.create(input, { idempotencyKey }),\n );\n tool(\n \"update_product\",\n \"Patch a product by id or key; omitted fields are untouched, null clears. `theme` and `checkout` replace their whole section. Bumps/upsells only on one-time products.\",\n z.object({\n idOrKey,\n name: z.string().max(120).optional(),\n description: z.string().max(2000).nullable().optional(),\n active: z.boolean().optional(),\n theme: shape.theme\n .unwrap()\n .extend({ logoStorageId: z.string().nullable().optional().describe(\"From an upload; null clears the logo\") })\n .optional(),\n checkout: shape.checkout,\n bumps: z.array(bump).max(3).optional().describe(\"Order bumps; [] clears\"),\n upsell: bump.nullable().optional(),\n pixelId: z.string().nullable().optional(),\n groupKey: z.string().nullable().optional().describe(\"null clears the group and tier\"),\n tier,\n credits: shape.credits.nullable(),\n buyerEmails: z.boolean().optional(),\n }),\n WRITE,\n ({ idOrKey: target, ...patch }) => client.products.update(target, patch),\n );\n tool(\n \"upsert_product\",\n \"Create or update one config-managed product by key (single-product push_config).\",\n z.object({ ...productInputSchema.shape, idempotencyKey: z.string().optional() }),\n WRITE,\n ({ key, idempotencyKey, ...input }) => client.products.upsert(key, input, { idempotencyKey }),\n );\n tool(\n \"set_product_delivery\",\n \"Set what buyers receive: none, a redirect URL, instructions text, or 1-10 files already uploaded via POST /uploads/delivery-file (give the returned objectKey/fileName/contentType/fileSize). Bytes cannot be uploaded through this tool.\",\n z.object({\n idOrKey,\n delivery: z.discriminatedUnion(\"method\", [\n ...shape.delivery.unwrap().options,\n z.object({ method: z.literal(\"file\"), files: z.array(deliveryFile).min(1).max(10) }),\n ]),\n }),\n WRITE,\n (a) => client.products.setDelivery(a.idOrKey, a.delivery),\n );\n tool(\n \"copy_product_styles\",\n \"Copy checkout layout and theme from another product (`from` is an id or key).\",\n z.object({ idOrKey, from: z.string() }),\n WRITE,\n (a) => client.products.copyStyles(a.idOrKey, { from: a.from }),\n );\n tool(\"get_product_visits\", \"Checkout page views and unique visitors for a product, total and by day.\", z.object({ idOrKey }), READ, (a) =>\n client.products.visits(a.idOrKey),\n );\n tool(\"archive_product\", \"Archive a product (never hard-deletes). Ask the user before calling.\", z.object({ idOrKey }), DESTRUCTIVE, (a) =>\n client.products.archive(a.idOrKey),\n );\n\n tool(\"get_config\", \"Read the managed product config (all keyed products) plus the count of unmanaged dashboard products.\", z.object({}), READ, () =>\n client.config.get(),\n );\n tool(\n \"push_config\",\n \"Apply a product config (upsert by key). Runs as a dry run unless confirm=true; show the plan to the user and only confirm after they approve.\",\n z.object({\n products: z.array(productInputSchema),\n prune: z.boolean().optional().describe(\"Archive keyed products missing from `products`\"),\n confirm: z.boolean().default(false),\n }),\n DESTRUCTIVE,\n (a) =>\n client.config.push({ products: a.products, prune: a.prune, dryRun: !a.confirm, idempotencyKey: a.confirm ? crypto.randomUUID() : undefined }),\n );\n\n tool(\n \"get_credit_balances\",\n \"Credit balances for a customer, optionally one meter.\",\n z.object({ ...customer, meter: z.string().optional() }),\n READ,\n (a) => client.credits.balances(asCustomer(a)),\n );\n tool(\n \"consume_credits\",\n \"Deduct credits from a customer. Fails with 402 insufficient_credits when the balance is short.\",\n z.object({ ...customer, meter: z.string(), amount: z.number().int().positive(), note: z.string().optional(), idempotencyKey: z.string() }),\n DESTRUCTIVE,\n (a) => client.credits.consume(asCustomer(a)),\n );\n tool(\n \"adjust_credits\",\n \"Grant (positive) or remove (negative) credits manually. Ask the user before removing.\",\n z.object({ ...customer, meter: z.string(), amount: z.number().int(), note: z.string().optional(), idempotencyKey: z.string().optional() }),\n DESTRUCTIVE,\n (a) => client.credits.adjust(asCustomer(a)),\n );\n tool(\n \"list_credit_ledger\",\n \"Credit ledger entries for a customer, newest first.\",\n z.object({ ...customer, cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() }),\n READ,\n (a) => client.credits.ledger(asCustomer(a)),\n );\n tool(\n \"get_entitlement\",\n \"Whether a customer has an active subscription in a product group; hasAccess=false when not.\",\n z.object({ ...customer, groupKey: z.string() }),\n READ,\n (a) => client.entitlements.get(asCustomer(a)),\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nexport function registerAccountTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\n \"update_account\",\n \"Update the seller's profile name and which checkout providers (Stripe/PayPal) buyers see; both false is stored as Stripe-only.\",\n z.object({\n givenName: z.string().max(100).optional(),\n familyName: z.string().max(100).optional(),\n checkoutProviders: z.object({ stripe: z.boolean(), paypal: z.boolean() }).optional(),\n }),\n WRITE,\n (a) => client.account.update(a),\n );\n\n tool(\n \"get_stripe_status\",\n \"Stripe connection state, outstanding requirements, account details and any running key migration.\",\n z.object({}),\n READ,\n () => client.account.stripeStatus(),\n );\n tool(\n \"create_stripe_onboarding_link\",\n \"Create a Stripe Connect onboarding URL for the seller to open in a browser. country is required when no Stripe account exists yet.\",\n z.object({\n country: z.string().length(2).optional().describe(\"ISO-3166 alpha-2\"),\n returnTo: z.string().optional().describe(\"Dashboard path starting with /dashboard/\"),\n }),\n CREATE,\n (a) => client.account.stripeOnboardingLink(a),\n );\n tool(\n \"refresh_stripe_status\",\n \"Re-read capabilities (charges, payouts, transfers) from Stripe. 404 when no Stripe account.\",\n z.object({}),\n WRITE,\n () => client.account.stripeRefresh(),\n );\n tool(\n \"connect_stripe_api_key\",\n \"Connect Stripe with the seller's own secret + publishable keys (replaces Stripe Connect). Ask the user to paste the keys; never guess them. Sandbox accounts take test-mode keys only.\",\n z.object({\n secretKey: z.string().describe(\"sk_ or rk_ key\"),\n publishableKey: z.string().describe(\"pk_ key\"),\n migration: z\n .object({ includeCustomers: z.boolean() })\n .optional()\n .describe(\"Copy the Connect catalog (and optionally customers) into the new account\"),\n }),\n WRITE,\n (a) => client.account.stripeConnectApiKey(a),\n );\n tool(\n \"set_stripe_branding\",\n \"Set checkout branding (primary color, https logo URL) on a Stripe Connect account; applied=false for API-key or platform accounts.\",\n z.object({\n primaryColor: z.string().optional().describe(\"Hex color\"),\n logoUrl: z.string().url().optional().describe(\"Must start with https://\"),\n }),\n WRITE,\n (a) => client.account.stripeBranding(a),\n );\n\n tool(\"get_paypal_status\", \"PayPal connection state and account details (never the secret).\", z.object({}), READ, () =>\n client.account.paypalStatus(),\n );\n tool(\n \"connect_paypal\",\n \"Connect PayPal with REST API client id + secret. Ask the user to paste the keys; never guess them.\",\n z.object({ clientId: z.string(), secret: z.string() }),\n WRITE,\n (a) => client.account.paypalConnect(a),\n );\n tool(\"disconnect_paypal\", \"Disconnect PayPal so buyers no longer see it at checkout. Ask the user before calling.\", z.object({}), DESTRUCTIVE, () =>\n client.account.paypalDisconnect(),\n );\n\n tool(\n \"create_billing_portal_link\",\n \"Create a Stripe billing-portal URL for the seller's own Purpleturret plan (not their connected account); fails before any plan purchase.\",\n z.object({}),\n CREATE,\n () => client.account.billingPortal(),\n );\n tool(\n \"create_support_request\",\n \"Send a message to Purpleturret support, filed under the account's email.\",\n z.object({ subject: z.string().max(160).optional(), message: z.string().min(10).max(5000), idempotencyKey: z.string().optional() }),\n CREATE,\n (a) => client.support.create(a),\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\n\nimport type { ToolRegistrar } from \"../index\";\n\nexport function registerProductsTools(_tool: ToolRegistrar, _client: PurpleturretClient): void {}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, type ToolRegistrar } from \"../index\";\n\nconst page = { cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() };\nconst orderStatus = z.enum([\"pending\", \"paid\", \"failed\", \"refunded\", \"partially_refunded\"]);\nconst subscriptionStatus = z.enum([\"incomplete\", \"incomplete_expired\", \"trialing\", \"active\", \"past_due\", \"canceled\", \"unpaid\", \"paused\"]);\n\nexport function registerOrdersTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n const orderId = z.string().describe(\"Order id\");\n const subscriptionId = z.string().describe(\"Subscription id\");\n\n tool(\n \"list_orders\",\n \"List orders newest first, optionally filtered by buyer email (exact, case-insensitive) and status. Returns a page with nextCursor.\",\n z.object({ email: z.string().optional(), status: orderStatus.optional(), ...page }),\n READ,\n (a) => client.orders.list(a),\n );\n tool(\"get_order\", \"Get one order with line items, refund and upsell state.\", z.object({ id: orderId }), READ, (a) => client.orders.get(a.id));\n tool(\n \"refund_order\",\n \"Refund an order's main charge, upsell charge, or both through Stripe/PayPal; cannot be undone. Ask the user before calling.\",\n z.object({\n id: orderId,\n reason: z.enum([\"requested_by_customer\", \"duplicate\", \"fraudulent\", \"other\"]),\n scope: z.enum([\"main\", \"upsell\", \"all\"]).optional().describe(\"Default all\"),\n customReason: z.string().max(500).optional().describe(\"Only stored when reason is other\"),\n }),\n DESTRUCTIVE,\n ({ id, ...options }) => client.orders.refund(id, options),\n );\n\n tool(\n \"list_subscriptions\",\n \"List subscriptions newest first; filter by email, status (canceled = churned) or product id (ignored when email is given).\",\n z.object({\n email: z.string().optional(),\n status: subscriptionStatus.optional(),\n product: z.string().optional().describe(\"Product id, not the config key\"),\n ...page,\n }),\n READ,\n (a) => client.subscriptions.list(a),\n );\n tool(\"get_subscription\", \"Get one subscription with its billing period and provider ids.\", z.object({ id: subscriptionId }), READ, (a) =>\n client.subscriptions.get(a.id),\n );\n tool(\n \"create_subscription_portal_link\",\n \"Create a billing-portal link (valid 7 days) the buyer can use to manage the subscription; a new link on every call.\",\n z.object({ id: subscriptionId }),\n CREATE,\n (a) => client.subscriptions.portalLink(a.id),\n );\n tool(\n \"send_subscription_portal_email\",\n \"E-mail the buyer a billing-portal link for the subscription. Ask the user before calling.\",\n z.object({ id: subscriptionId }),\n CREATE,\n (a) => client.subscriptions.portalEmail(a.id),\n );\n\n tool(\"list_customers\", \"List customers (one row per email, ordered by email). Returns a page with nextCursor.\", z.object(page), READ, (a) =>\n client.customers.list(a),\n );\n tool(\n \"get_customer\",\n \"Get a customer by email or your own external id, with their orders, subscriptions, credit balances and lifetime spend.\",\n z.object({ id: z.string().describe(\"E-mail address or external id\") }),\n READ,\n (a) => client.customers.get(a.id),\n );\n\n tool(\n \"list_checkout_leads\",\n \"List checkout leads (buyers who started a checkout), newest first. abandoned=true returns only leads not completed and idle for 30+ minutes within lookbackDays.\",\n z.object({\n abandoned: z.boolean().optional(),\n lookbackDays: z.number().int().min(1).max(180).optional().describe(\"Default 30; only used with abandoned\"),\n }),\n READ,\n (a) => client.leads.checkout(a),\n );\n tool(\"list_page_leads\", \"List e-mail leads captured by page forms, newest first.\", z.object({}), READ, () => client.leads.pages());\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst id = z.string().describe(\"Pixel id (not its pt_px_ key)\");\nconst range = {\n start: z.union([z.number(), z.string()]).optional().describe(\"Epoch ms or ISO 8601; default 7 days before end\"),\n end: z.union([z.number(), z.string()]).optional().describe(\"Epoch ms or ISO 8601; default now. Range is capped at 90 days\"),\n};\nconst target = {\n productId: z.string().optional().describe(\"Product id; give this or pageId\"),\n pageId: z.string().optional().describe(\"Page id; give this or productId\"),\n};\n\n/** Purpleturret Pixel: site analytics, funnels, ad attribution. */\nexport function registerPixelsTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\n \"list_pixels\",\n \"List the seller's pixels (newest first); archived ones only with includeArchived.\",\n z.object({ includeArchived: z.boolean().optional() }),\n READ,\n (a) => client.pixels.list(a),\n );\n tool(\"get_pixel\", \"Fetch one pixel: snippet key, allowed hosts, declared events and funnels.\", z.object({ id }), READ, (a) =>\n client.pixels.get(a.id),\n );\n tool(\n \"create_pixel\",\n \"Create a pixel. allowedHosts restricts which sites may send events (omit for any origin).\",\n z.object({ name: z.string(), allowedHosts: z.array(z.string()).optional() }),\n CREATE,\n (a) => client.pixels.create(a),\n );\n tool(\n \"update_pixel\",\n \"Update a pixel's name or allowed hosts, or make it the checkout pixel (checkout=true unsets the others).\",\n z.object({\n id,\n name: z.string().optional(),\n allowedHosts: z.array(z.string()).optional(),\n checkout: z.boolean().optional(),\n }),\n WRITE,\n ({ id, ...patch }) => client.pixels.update(id, patch),\n );\n tool(\"archive_pixel\", \"Archive a pixel; it stops accepting events. Ask the user before calling.\", z.object({ id }), DESTRUCTIVE, (a) =>\n client.pixels.archive(a.id),\n );\n tool(\n \"attach_pixel\",\n \"Attach a pixel to exactly one product or page so its checkout/page fires the pixel.\",\n z.object({ id, ...target }),\n WRITE,\n ({ id, ...t }) => client.pixels.attach(id, t),\n );\n tool(\"detach_pixel\", \"Detach the pixel from exactly one product or page. Ask the user before calling.\", z.object(target), DESTRUCTIVE, (a) =>\n client.pixels.detach(a),\n );\n\n tool(\n \"get_pixel_overview\",\n \"Site analytics for a range: KPIs (visitors, sessions, pageviews, bounce), optional time series (bucket) and prior-period comparison, top entry/exit pages, devices, countries, sources, referrers, recent sessions.\",\n z.object({\n id,\n ...range,\n bucket: z.enum([\"hour\", \"day\"]).optional().describe(\"Adds a time series; hour needs a range of 400 hours or fewer\"),\n compare: z.boolean().optional(),\n }),\n READ,\n ({ id, ...r }) => client.pixels.overview(id, r),\n );\n tool(\n \"get_pixel_top_pages\",\n \"Top pages by views for a range, with visitors and average time on page.\",\n z.object({ id, ...range }),\n READ,\n ({ id, ...r }) => client.pixels.topPages(id, r),\n );\n tool(\n \"get_pixel_funnels\",\n \"Step-by-step session counts for every funnel the site declared from code.\",\n z.object({ id, ...range }),\n READ,\n ({ id, ...r }) => client.pixels.funnels(id, r),\n );\n tool(\n \"get_pixel_ad_performance\",\n \"Paid-traffic attribution: sessions, conversions and revenue per utm combination and per campaign (with recorded spend). conversion is an event name such as purchase or a /path prefix; candidates lists the declared options.\",\n z.object({ id, ...range, conversion: z.string(), attribution: z.enum([\"first\", \"last\"]).optional() }),\n READ,\n ({ id, ...o }) => client.pixels.adPerformance(id, o),\n );\n tool(\n \"get_pixel_people\",\n \"Identified visitors (by external id, email or cookie) active in the range, with spend and recent sessions. Paged: total counts everyone, offset/limit pick the page.\",\n z.object({\n id,\n ...range,\n offset: z.number().int().min(0).optional().describe(\"People to skip, most recently seen first\"),\n limit: z.number().int().min(1).max(100).optional().describe(\"Page size; default 100\"),\n }),\n READ,\n ({ id, ...r }) => client.pixels.people(id, r),\n );\n tool(\n \"get_pixel_session\",\n \"The event timeline (pageviews, clicks, custom events) of one session id.\",\n z.object({ id, sid: z.string() }),\n READ,\n (a) => client.pixels.session(a.id, a.sid),\n );\n tool(\n \"get_pixel_person\",\n \"Merged event timeline across a person's sessions: the given sid plus any extra sids (max 20).\",\n z.object({ id, sid: z.string(), sids: z.array(z.string()).optional() }),\n READ,\n (a) => client.pixels.person(a.id, a.sid, { sids: a.sids }),\n );\n tool(\n \"set_pixel_ad_spend\",\n \"Record ad spend for a source/campaign over a date range (spread evenly per UTC day; spend 0 clears it) so ad performance can report ROI.\",\n z.object({\n id,\n source: z.string(),\n campaign: z.string().optional(),\n start: z.union([z.number(), z.string()]),\n end: z.union([z.number(), z.string()]),\n spend: z.number().min(0),\n }),\n WRITE,\n ({ id, ...input }) => client.pixels.setAdSpend(id, input),\n );\n}\n","import { contentTypeFor, type PageFileInput, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst fileInput = z.object({ path: z.string(), storageId: z.string(), size: z.number().int().min(0) });\nconst range = {\n start: z.union([z.string(), z.number()]).optional().describe(\"Epoch ms or ISO 8601; default 7 days ago\"),\n end: z.union([z.string(), z.number()]).optional(),\n};\nconst patch = {\n title: z.string().optional(),\n slug: z.string().optional(),\n published: z.boolean().optional(),\n linkedProductIds: z.array(z.string()).optional().describe(\"Seller's own product ids; first 5 kept, [] clears\"),\n notifyOnSubmission: z.boolean().optional(),\n addToLeads: z.boolean().optional(),\n};\n\nexport function registerPagesTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\"list_pages\", \"List hosted pages (static sites) on the account, newest first.\", z.object({}), READ, () => client.pages.list());\n tool(\"get_page\", \"Fetch one hosted page by id.\", z.object({ id: z.string() }), READ, (a) => client.pages.get(a.id));\n tool(\"list_page_files\", \"List the files of a hosted page (path, size, content type).\", z.object({ id: z.string() }), READ, (a) =>\n client.pages.files(a.id),\n );\n tool(\n \"check_page_slug\",\n \"Check whether a page slug (subdomain) is available; pass exclude to ignore a page's own slug when renaming.\",\n z.object({ slug: z.string(), exclude: z.string().optional().describe(\"Page id whose current slug to ignore\") }),\n READ,\n (a) => client.pages.slugAvailable(a.slug, { exclude: a.exclude }),\n );\n tool(\n \"create_page\",\n \"Create a hosted page from already-uploaded files (storage ids from create_upload/put); must include a root index.html. Prefer deploy_page when you have the file contents.\",\n z.object({\n title: z.string(),\n slug: z.string(),\n files: z.array(fileInput),\n pixelId: z.string().optional(),\n idempotencyKey: z.string().optional(),\n }),\n CREATE,\n (a) => client.pages.create(a),\n );\n tool(\n \"replace_page_files\",\n \"Replace all files of a hosted page with already-uploaded files; old files are deleted.\",\n z.object({ id: z.string(), files: z.array(fileInput) }),\n WRITE,\n (a) => client.pages.replaceFiles(a.id, a.files),\n );\n tool(\n \"update_page\",\n \"Update a hosted page: title, slug, published, linked products, submission settings.\",\n z.object({ id: z.string(), ...patch }),\n WRITE,\n ({ id, ...p }) => client.pages.update(id, p),\n );\n tool(\n \"delete_page\",\n \"Delete a hosted page and its files (archived instead when it has form submissions). Ask the user before calling.\",\n z.object({ id: z.string() }),\n DESTRUCTIVE,\n (a) => client.pages.delete(a.id),\n );\n tool(\n \"list_page_submissions\",\n \"List form submissions for a hosted page, newest first. Returns a page with nextCursor.\",\n z.object({ id: z.string(), cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() }),\n READ,\n (a) => client.pages.submissions(a.id, a),\n );\n tool(\n \"get_page_visits\",\n \"Visits and visitors for a hosted page by day (default last 7 days, max 90).\",\n z.object({ id: z.string(), ...range }),\n READ,\n (a) => client.pages.visits(a.id, a),\n );\n tool(\n \"get_page_clicks\",\n \"Tracked clicks for a hosted page by day plus top targets (default last 7 days, max 90).\",\n z.object({ id: z.string(), ...range }),\n READ,\n (a) => client.pages.clicks(a.id, a),\n );\n tool(\n \"deploy_page\",\n \"Upload file contents and create the hosted page, or replace the files of the existing page with that slug. Must include index.html. Use base64 encoding for binary files.\",\n z.object({\n title: z.string(),\n slug: z.string(),\n files: z.array(z.object({ path: z.string(), content: z.string(), encoding: z.enum([\"utf8\", \"base64\"]).default(\"utf8\") })),\n pixelId: z.string().optional(),\n }),\n CREATE,\n async (a) => {\n const files: PageFileInput[] = [];\n for (const file of a.files) {\n const bytes = Buffer.from(file.content, file.encoding);\n files.push({ path: file.path, storageId: await client.uploads.put(bytes, contentTypeFor(file.path)), size: bytes.byteLength });\n }\n const existing = (await client.pages.list()).data.find((p) => p.slug === a.slug);\n return existing\n ? client.pages.replaceFiles(existing.id, files)\n : client.pages.create({ title: a.title, slug: a.slug, files, pixelId: a.pixelId });\n },\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst TOKEN =\n 'The Meta Conversions API token is write-only (reads only report hasConversionsApiToken). Ask the user to paste the value; never guess it. Omit/null keeps the stored token, \"\" clears it.';\nconst SECTIONS =\n \"Each section (meta, googleAnalytics) is optional; a present section fully replaces that section and omitted event toggles default to true.\";\n\nconst mode = z.enum([\"inherit\", \"custom\", \"disabled\"]);\nconst eventsMode = z.enum([\"inherit\", \"custom\"]).optional();\nconst pixelId = z.string().optional().describe(\"Meta pixel id, 10–20 digits; required when enabled/custom\");\nconst token = z.string().nullable().optional().describe(\"Meta Conversions API token (write-only)\");\nconst measurementId = z.string().optional().describe(\"GA4 measurement id, G-XXXXXXX; required when enabled/custom\");\nconst metaEvents = z\n .object({ viewContent: z.boolean().optional(), initiateCheckout: z.boolean().optional(), purchase: z.boolean().optional() })\n .optional();\nconst gaEvents = z.object({ viewItem: z.boolean().optional(), beginCheckout: z.boolean().optional(), purchase: z.boolean().optional() }).optional();\n\nconst accountInput = z.object({\n meta: z\n .object({\n enabled: z.boolean().describe(\"false deletes the account pixel and its token\"),\n pixelId,\n conversionsApiToken: token,\n events: metaEvents,\n })\n .optional(),\n googleAnalytics: z.object({ enabled: z.boolean(), measurementId, events: gaEvents }).optional(),\n});\nconst productInput = z.object({\n meta: z.object({ mode, pixelId, conversionsApiToken: token, eventsMode, events: metaEvents }).optional(),\n googleAnalytics: z.object({ mode, measurementId, eventsMode, events: gaEvents }).optional(),\n});\nconst pageInput = z.object({\n meta: z\n .object({\n mode,\n pixelId,\n conversionsApiToken: token,\n events: z.object({ lead: z.boolean().optional() }).optional(),\n paths: z\n .array(z.object({ path: z.string(), pixelId: z.string(), conversionsApiToken: z.string().optional() }))\n .optional()\n .describe(\"A different Meta pixel + token for URLs under a path prefix (e.g. /ad1). Omit to keep stored overrides; [] clears them.\"),\n })\n .optional(),\n googleAnalytics: z.object({ mode, measurementId, events: z.object({ generateLead: z.boolean().optional() }).optional() }).optional(),\n});\n\nexport function registerTrackingTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\n \"get_tracking\",\n \"Account-level tracking defaults: Meta pixel / Conversions API and Google Analytics, with event toggles.\",\n z.object({}),\n READ,\n () => client.tracking.get(),\n );\n // meta.enabled=false deletes the account pixel and its CAPI token, so this asks like a destructive tool.\n tool(\"set_tracking\", `Set account-level tracking defaults. ${SECTIONS} ${TOKEN}`, accountInput, DESTRUCTIVE, (a) => client.tracking.set(a));\n\n tool(\n \"get_product_tracking\",\n \"A product's tracking settings (inherit/custom/disabled per Meta and GA) plus the inherited account values. Takes a product id or config key.\",\n z.object({ idOrKey: z.string() }),\n READ,\n (a) => client.tracking.getProduct(a.idOrKey),\n );\n tool(\n \"set_product_tracking\",\n `Set a product's tracking override by id or config key. ${SECTIONS} mode=inherit with eventsMode=inherit removes the override. ${TOKEN}`,\n productInput.extend({ idOrKey: z.string() }),\n WRITE,\n ({ idOrKey, ...input }) => client.tracking.setProduct(idOrKey, input),\n );\n\n tool(\n \"get_page_tracking\",\n \"A hosted page's tracking settings (inherit/custom/disabled per Meta and GA, lead event toggles) plus the inherited account values.\",\n z.object({ id: z.string() }),\n READ,\n (a) => client.tracking.getPage(a.id),\n );\n tool(\n \"set_page_tracking\",\n `Set a hosted page's tracking override. ${SECTIONS} mode=inherit with the lead toggle on removes the override. ${TOKEN}`,\n pageInput.extend({ id: z.string() }),\n WRITE,\n ({ id, ...input }) => client.tracking.setPage(id, input),\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst id = z.string().describe(\"Domain id\");\n\nexport function registerDomainsTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\"list_domains\", \"List the seller's custom domains with status and DNS records.\", z.object({}), READ, () => client.domains.list());\n tool(\"get_domain\", \"Get one custom domain, including the DNS records the seller must create.\", z.object({ id }), READ, (a) =>\n client.domains.get(a.id),\n );\n tool(\n \"add_domain\",\n \"Add a custom domain and register it with the provider; needs an active subscription and a live key. On provider failure the row stays in status error: list, then verify or remove it.\",\n z.object({\n hostname: z.string().describe(\"e.g. shop.example.com\"),\n routingType: z.enum([\"A\", \"CNAME\"]).optional().describe(\"DNS record hint; omit to let the provider pick\"),\n }),\n CREATE,\n (a) => client.domains.add(a),\n );\n tool(\"verify_domain\", \"Re-check a domain's DNS with the provider (re-registers domains in status error).\", z.object({ id }), WRITE, (a) =>\n client.domains.verify(a.id),\n );\n tool(\n \"update_domain\",\n \"Attach a page at / (pageId, null detaches), replace the checkout allowlist (productIds, max 50), or set the default checkout link for / (defaultProductId, null clears). Omitted fields are untouched.\",\n z.object({\n id,\n pageId: z.string().nullable().optional(),\n productIds: z.array(z.string()).max(50).optional(),\n defaultProductId: z.string().nullable().optional(),\n }),\n WRITE,\n ({ id, ...options }) => client.domains.update(id, options),\n );\n tool(\"remove_domain\", \"Remove a custom domain; it stops serving immediately. Ask the user before calling.\", z.object({ id }), DESTRUCTIVE, (a) =>\n client.domains.remove(a.id),\n );\n}\n","import { groupsApi, keysApi, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nexport function registerWebhooksTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n const groups = groupsApi(client);\n const keys = keysApi(client);\n const id = z.string().describe(\"Webhook endpoint id\");\n const key = z.string().describe(\"Integration group key\");\n\n tool(\"list_webhooks\", \"List the account's outgoing webhook endpoints with their last delivery status.\", z.object({}), READ, () =>\n client.webhooks.list(),\n );\n tool(\n \"create_webhook\",\n \"Create a webhook endpoint in an integration group. The response is the only time the signing secret is returned; relay it to the user verbatim.\",\n z.object({\n groupKey: key,\n url: z.string().describe(\"HTTPS URL that receives events\"),\n description: z.string().max(80).optional(),\n idempotencyKey: z.string().optional().describe(\"Reuse to retry safely; defaults to a random UUID\"),\n }),\n CREATE,\n (a) => client.webhooks.create(a),\n );\n tool(\n \"update_webhook\",\n \"Change a webhook endpoint's URL, enabled flag or description (empty description clears it).\",\n z.object({ id, url: z.string().optional(), enabled: z.boolean().optional(), description: z.string().max(80).optional() }),\n WRITE,\n ({ id, ...patch }) => client.webhooks.update(id, patch),\n );\n tool(\n \"delete_webhook\",\n \"Delete a webhook endpoint and drop its pending deliveries. Ask the user before calling.\",\n z.object({ id }),\n DESTRUCTIVE,\n (a) => client.webhooks.delete(a.id),\n );\n tool(\"test_webhook\", \"Queue a test.event delivery to a webhook endpoint (sent asynchronously, even if disabled).\", z.object({ id }), WRITE, (a) =>\n client.webhooks.test(a.id),\n );\n\n tool(\"list_groups\", \"List the account's integration groups.\", z.object({}), READ, () => groups.list());\n tool(\n \"create_group\",\n \"Create an integration group (key: 2-64 letters, numbers, dashes, underscores; name: 1-80 chars).\",\n z.object({ key, name: z.string().min(1).max(80) }),\n CREATE,\n (a) => groups.create(a),\n );\n tool(\"update_group\", \"Rename an integration group.\", z.object({ key, name: z.string().min(1).max(80) }), WRITE, (a) =>\n groups.update(a.key, { name: a.name }),\n );\n tool(\n \"delete_group\",\n \"Delete an integration group. Also deletes its webhook endpoints, deliveries and events, and clears the group/tier on its products (they keep selling). Ask the user before calling.\",\n z.object({ key }),\n DESTRUCTIVE,\n (a) => groups.delete(a.key),\n );\n\n tool(\n \"list_api_keys\",\n \"List the account's seller API keys (prefix, name, scopes, last use); never returns secrets.\",\n z.object({ includeRevoked: z.boolean().optional() }),\n READ,\n (a) => keys.list(a),\n );\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { money, type Product, type ProductUpdateInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { describeBilling, formatMoney } from \"../lib/render\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { id: { type: \"positional\", required: true, description: \"Product id or config key\" } } as const;\n\nfunction describeDelivery(delivery: Product[\"delivery\"]): string {\n if (!delivery || delivery.method === \"none\") return \"none\";\n if (delivery.method === \"redirect\") return `redirect → ${delivery.url}`;\n if (delivery.method === \"instructions\") return \"instructions\";\n return `${delivery.fileCount} file(s)${delivery.files ? `: ${delivery.files.map((f) => f.fileName).join(\", \")}` : \"\"}`;\n}\n\nfunction printProduct(ctx: CliContext, product: Product): void {\n if (ctx.json) return ctx.out.printJson(product);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"id\", product.id],\n [\"key\", product.key ?? palette.dim(\"(unmanaged)\")],\n [\"name\", product.name],\n [\"price\", `${formatMoney(product.price)}${describeBilling(product.billing)}`],\n [\"status\", product.archivedAt ? palette.red(\"archived\") : product.active ? \"active\" : palette.yellow(\"inactive\")],\n [\"url\", product.url ?? palette.dim(\"—\")],\n [\"delivery\", describeDelivery(product.delivery)],\n [\"pixel\", product.pixelId ?? palette.dim(\"—\")],\n ];\n for (const [label, value] of rows) ctx.out.print(`${palette.dim(label.padEnd(10))}${value}`);\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List products on the account (config-managed and dashboard-only)\" },\n args: {\n ...globalArgs,\n all: { type: \"boolean\", description: \"Include archived products\" },\n },\n run: defineRun(async (ctx, args) => {\n const client = ctx.client();\n const products: Product[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.products.list({ cursor, limit: 100, includeArchived: Boolean(args.all) });\n products.push(...page.data);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n\n if (ctx.json) {\n ctx.out.printJson({ products });\n return;\n }\n const { palette } = ctx.out;\n if (products.length === 0) {\n ctx.out.print(palette.dim(\"No products yet. Run `purpleturret init` and `purpleturret push` to create some.\"));\n return;\n }\n const rows = products.map((product) => [\n product.key ?? palette.dim(\"(unmanaged)\"),\n product.name,\n `${formatMoney(product.price)}${describeBilling(product.billing)}`,\n product.archivedAt ? palette.red(\"archived\") : product.active ? \"active\" : palette.yellow(\"inactive\"),\n product.url ?? palette.dim(\"—\"),\n ]);\n for (const line of renderTable([\"KEY\", \"NAME\", \"PRICE\", \"STATUS\", \"URL\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show one product\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => printProduct(ctx, await ctx.client().products.get(args.id))),\n});\n\nconst create = defineCommand({\n meta: { name: \"create\", description: \"Create a checkout link (needs a connected Stripe account)\" },\n args: {\n ...globalArgs,\n name: { type: \"string\", required: true, description: \"Product name\" },\n price: { type: \"string\", required: true, description: \"Price in major units, e.g. 19.99\" },\n currency: { type: \"string\", default: \"usd\", description: \"3-letter ISO currency\" },\n interval: { type: \"string\", description: \"Recurring billing: month or year (default: one-time)\" },\n slug: { type: \"string\", description: \"Checkout slug (/c/<slug>); random when omitted\" },\n description: { type: \"string\" },\n key: { type: \"string\", description: \"Config key (omit for an unkeyed product)\" },\n redirect: { type: \"string\", description: \"Deliver by redirecting to this https URL\" },\n instructions: { type: \"string\", description: \"Deliver by showing these instructions\" },\n },\n run: defineRun(async (ctx, args) => {\n const major = Number(args.price);\n if (!Number.isFinite(major) || major < 0) throw new CliError(`--price must be a number (got ${args.price})`, EXIT.USAGE, { code: \"usage\" });\n const interval = args.interval as \"month\" | \"year\" | undefined;\n if (interval && interval !== \"month\" && interval !== \"year\")\n throw new CliError(\"--interval must be month or year\", EXIT.USAGE, { code: \"usage\" });\n const product = await ctx.client().products.create({\n name: args.name,\n description: args.description,\n // shortcut: assumes a 2-decimal currency; add a zero-decimal table (jpy, krw, …) when a seller asks\n price: money(Math.round((major + Number.EPSILON) * 100), args.currency),\n billing: interval ? { type: \"recurring\", interval } : { type: \"one_time\" },\n slug: args.slug,\n key: args.key,\n delivery: args.redirect\n ? { method: \"redirect\", url: args.redirect }\n : args.instructions\n ? { method: \"instructions\", instructions: args.instructions }\n : undefined,\n });\n printProduct(ctx, product);\n ctx.out.success(`Created ${product.name}${product.url ? ` → ${product.url}` : \"\"}`);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Change a product's name, description, status, brand color or pixel\" },\n args: {\n ...globalArgs,\n ...id,\n name: { type: \"string\" },\n description: { type: \"string\", description: 'New description (\"\" clears)' },\n active: { type: \"string\", description: \"true or false\" },\n \"primary-color\": { type: \"string\", description: \"Brand color, e.g. #5F34CC\" },\n pixel: { type: \"string\", description: 'Pixel id to attach (\"\" detaches)' },\n },\n run: defineRun(async (ctx, args) => {\n const patch: ProductUpdateInput = { name: args.name };\n if (args.description !== undefined) patch.description = args.description || null;\n if (args.active !== undefined) patch.active = args.active === \"true\";\n if (args[\"primary-color\"] !== undefined) patch.theme = { primaryColor: args[\"primary-color\"] };\n if (args.pixel !== undefined) patch.pixelId = args.pixel || null;\n printProduct(ctx, await ctx.client().products.update(args.id, patch));\n }),\n});\n\nconst delivery = defineCommand({\n meta: { name: \"delivery\", description: \"Set what buyers get after paying\" },\n args: {\n ...globalArgs,\n ...id,\n redirect: { type: \"string\", description: \"https URL to send buyers to\" },\n instructions: { type: \"string\", description: \"Text shown after purchase\" },\n file: { type: \"string\", description: \"Path of a file to upload and deliver\" },\n \"content-type\": { type: \"string\", description: \"MIME type of --file (default: application/octet-stream)\" },\n },\n run: defineRun(async (ctx, args) => {\n const client = ctx.client();\n let product: Product;\n if (args.file) {\n const uploaded = await client.uploads.putDeliveryFile(await readFile(args.file), {\n fileName: basename(args.file),\n contentType: args[\"content-type\"],\n });\n product = await client.products.setDelivery(args.id, { method: \"file\", ...uploaded });\n } else if (args.redirect) product = await client.products.setDelivery(args.id, { method: \"redirect\", url: args.redirect });\n else if (args.instructions) product = await client.products.setDelivery(args.id, { method: \"instructions\", instructions: args.instructions });\n else throw new CliError(\"Pass one of --redirect, --instructions or --file\", EXIT.USAGE, { code: \"usage\" });\n printProduct(ctx, product);\n }),\n});\n\nconst copyStyles = defineCommand({\n meta: { name: \"copy-styles\", description: \"Copy checkout layout and theme from another product\" },\n args: { ...globalArgs, ...id, from: { type: \"string\", required: true, description: \"Source product id or key\" } },\n run: defineRun(async (ctx, args) => printProduct(ctx, await ctx.client().products.copyStyles(args.id, { from: args.from }))),\n});\n\nconst archive = defineCommand({\n meta: { name: \"archive\", description: \"Archive a product (closes its checkout; never hard-deletes)\" },\n args: { ...globalArgs, ...id, yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes) {\n if (!isInteractive() || ctx.json) {\n throw new CliError(\"Refusing to archive without confirmation.\", EXIT.USAGE, { code: \"confirmation_required\", hint: \"Re-run with --yes.\" });\n }\n if (!unwrapPrompt(await confirm({ message: `Archive product ${args.id}?`, initialValue: false }))) {\n throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n }\n printProduct(ctx, await ctx.client().products.archive(args.id));\n }),\n});\n\nconst visits = defineCommand({\n meta: { name: \"visits\", description: \"Checkout page views and unique visitors, by day\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => {\n const summary = await ctx.client().products.visits(args.id);\n if (ctx.json) return ctx.out.printJson(summary);\n ctx.out.print(`${summary.total} visits, ${summary.uniqueVisitors} unique visitors`);\n const rows = summary.byDay.map((day) => [day.date, String(day.visits), String(day.uniqueVisitors)]);\n for (const line of renderTable([\"DATE\", \"VISITS\", \"UNIQUE\"], rows, ctx.out.palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const products = defineCommand({\n meta: { name: \"products\", description: \"Inspect and manage products (checkout links)\" },\n args: { ...globalArgs },\n subCommands: { list, get, create, update, delivery, \"copy-styles\": copyStyles, archive, visits },\n});\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { renderConfigSource, type ConfigFormat } from \"../lib/pull-writer\";\nimport { defineRun } from \"../lib/run\";\n\nexport const pull = defineCommand({\n meta: { name: \"pull\", description: \"Write the account's config-managed products to a local config file\" },\n args: {\n ...globalArgs,\n out: { type: \"string\", description: \"Output file (default: purpleturret.config.ts; a .json extension writes JSON)\" },\n force: { type: \"boolean\", description: \"Overwrite an existing file\" },\n },\n run: defineRun(async (ctx, args) => {\n const { products, unmanagedCount } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n\n const out = args.out?.trim();\n if (ctx.json && !out) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: null });\n return;\n }\n\n const target = resolve(ctx.cwd, out || \"purpleturret.config.ts\");\n const format: ConfigFormat = target.endsWith(\".json\") ? \"json\" : \"ts\";\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --out <path> to write elsewhere.\",\n });\n }\n await writeFile(target, renderConfigSource(inputs, format), \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: target });\n return;\n }\n ctx.out.success(`Wrote ${inputs.length} product${inputs.length === 1 ? \"\" : \"s\"} to ${relative(ctx.cwd, target) || target}`);\n if (unmanagedCount > 0) {\n ctx.out.info(\n ctx.out.palette.dim(\n `${unmanagedCount} dashboard-only product${unmanagedCount === 1 ? \"\" : \"s\"} without a key were skipped (see \\`purpleturret products list\\`).`,\n ),\n );\n }\n }),\n});\n","import { randomUUID } from \"node:crypto\";\nimport { relative } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { PurpleturretNetworkError, type ConfigPushResult, type ProductInput, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader\";\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { hasChanges, renderPlan } from \"../lib/render\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\n\nexport const push = defineCommand({\n meta: { name: \"push\", description: \"Plan and apply the local config to your Purpleturret account\" },\n args: {\n ...globalArgs,\n prune: { type: \"boolean\", description: \"Archive config-managed products that are missing from the config\" },\n \"dry-run\": { type: \"boolean\", description: \"Show the plan without applying it\" },\n yes: { type: \"boolean\", alias: \"y\", description: \"Apply without asking for confirmation (required in CI)\" },\n },\n run: defineRun(async (ctx, args) => {\n const prune = Boolean(args.prune);\n const dryRun = Boolean(args[\"dry-run\"]);\n const yes = Boolean(args.yes);\n\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const products = loaded.config.products;\n const { palette } = ctx.out;\n ctx.out.info(\n palette.dim(`Config: ${relative(ctx.cwd, loaded.path) || loaded.path} (${products.length} product${products.length === 1 ? \"\" : \"s\"})`),\n );\n\n const client = ctx.client();\n const plan = await client.config.push({ products, prune, dryRun: true });\n for (const line of renderPlan(plan, { palette, mode: \"plan\" })) ctx.out.print(line);\n\n if (plan.summary.conflict > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"conflict\", message: `${plan.summary.conflict} conflict(s); nothing applied` } });\n process.exitCode = EXIT.CONFLICT;\n return;\n }\n throw new CliError(`${plan.summary.conflict} conflict${plan.summary.conflict === 1 ? \"\" : \"s\"}; nothing was applied.`, EXIT.CONFLICT, {\n code: \"conflict\",\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one with --prune.\",\n });\n }\n if (plan.summary.error > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"plan_error\", message: `${plan.summary.error} product(s) cannot be applied` } });\n process.exitCode = EXIT.ERROR;\n return;\n }\n throw new CliError(`${plan.summary.error} product${plan.summary.error === 1 ? \"\" : \"s\"} cannot be applied; see the errors above.`, EXIT.ERROR, {\n code: \"plan_error\",\n });\n }\n\n if (!hasChanges(plan.summary)) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n return;\n }\n if (dryRun) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n else ctx.out.info(palette.dim(\"Dry run; nothing was applied. Run `purpleturret push` to apply.\"));\n return;\n }\n\n if (!yes) {\n if (!isInteractive() || ctx.json) {\n throw new CliError(\"Refusing to apply without confirmation because this is not an interactive terminal.\", EXIT.USAGE, {\n code: \"confirmation_required\",\n hint: \"Re-run with --yes to apply non-interactively, or --dry-run to only preview.\",\n });\n }\n const approved = unwrapPrompt(await confirm({ message: \"Apply these changes?\", initialValue: false }));\n if (!approved) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n\n const idempotencyKey = `pt-push-${randomUUID()}`;\n ctx.out.debug(`Idempotency-Key ${idempotencyKey}`);\n const result = await applyWithRetry(ctx, client, { products, prune, idempotencyKey });\n\n ctx.out.print(\"\");\n for (const line of renderPlan(result, { palette, mode: \"apply\" })) ctx.out.print(line);\n if (ctx.json) ctx.out.printJson({ plan, result, applied: result.applied });\n\n if (result.summary.conflict > 0) {\n process.exitCode = EXIT.CONFLICT;\n if (!ctx.json)\n ctx.out.fail(new CliError(\"The apply hit a conflict; some products may have been applied.\", EXIT.CONFLICT, { code: \"conflict\" }));\n return;\n }\n if (result.summary.error > 0) {\n process.exitCode = EXIT.ERROR;\n if (!ctx.json) {\n ctx.out.fail(\n new CliError(\n `${result.summary.error} product${result.summary.error === 1 ? \"\" : \"s\"} failed to apply; the rest were applied.`,\n EXIT.ERROR,\n {\n code: \"apply_error\",\n hint: \"Fix the reported errors and run push again; completed steps are skipped.\",\n },\n ),\n );\n }\n return;\n }\n const urls = result.results.filter((item) => item.action === \"create\" && item.product?.url).map((item) => ` ${item.key} ${item.product?.url}`);\n if (urls.length) {\n ctx.out.info(\"\");\n ctx.out.info(palette.dim(\"Checkout links:\"));\n for (const line of urls) ctx.out.info(line);\n }\n }),\n});\n\nasync function applyWithRetry(\n ctx: CliContext,\n client: PurpleturretClient,\n options: { products: ProductInput[]; prune: boolean; idempotencyKey: string },\n): Promise<ConfigPushResult> {\n try {\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n } catch (error) {\n if (!(error instanceof PurpleturretNetworkError)) throw error;\n ctx.out.warn(`Network error while applying (${error.message}); retrying once with the same Idempotency-Key…`);\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n }\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, extname, isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { validateConfig, type PurpleturretConfig } from \"@purpleturret/sdk\";\nimport { createJiti } from \"jiti\";\n\nimport { CliError, EXIT } from \"./errors\";\n\nexport const CONFIG_FILENAMES = [\n \"purpleturret.config.ts\",\n \"purpleturret.config.mts\",\n \"purpleturret.config.js\",\n \"purpleturret.config.mjs\",\n \"purpleturret.config.json\",\n] as const;\n\nexport interface LoadedConfig {\n path: string;\n config: PurpleturretConfig;\n}\n\n/**\n * Locate the config file. An explicit path is resolved against `cwd` and must exist. Otherwise the\n * standard names are searched in `cwd` and each parent, stopping at the git root (the first\n * directory containing `.git`) or the filesystem root.\n */\nexport function findConfigFile(cwd: string, explicit?: string): string {\n if (explicit) {\n const path = isAbsolute(explicit) ? explicit : resolve(cwd, explicit);\n if (!existsSync(path) || !statSync(path).isFile()) {\n throw new CliError(`Config file not found: ${path}`, EXIT.USAGE, { code: \"config_not_found\" });\n }\n return path;\n }\n\n let dir = resolve(cwd);\n const searched: string[] = [];\n for (;;) {\n searched.push(dir);\n for (const name of CONFIG_FILENAMES) {\n const candidate = join(dir, name);\n if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;\n }\n const isGitRoot = existsSync(join(dir, \".git\"));\n const parent = dirname(dir);\n if (isGitRoot || parent === dir) break;\n dir = parent;\n }\n throw new CliError(`No purpleturret.config.{ts,mts,js,mjs,json} found in ${searched[0]} or its parents up to the git root.`, EXIT.USAGE, {\n code: \"config_not_found\",\n hint: \"Run `purpleturret init` to create one, or pass --config <path>.\",\n });\n}\n\n/** Load and validate a config file. TypeScript/ESM files are transpiled on the fly with jiti. */\nexport async function loadConfigFile(path: string): Promise<LoadedConfig> {\n const raw = await importConfigModule(path);\n const candidate = pickConfigExport(raw, path);\n const config = validateConfig(candidate);\n return { path, config };\n}\n\nexport async function loadConfig(cwd: string, explicit?: string): Promise<LoadedConfig> {\n return loadConfigFile(findConfigFile(cwd, explicit));\n}\n\nasync function importConfigModule(path: string): Promise<unknown> {\n const ext = extname(path).toLowerCase();\n if (ext === \".json\") {\n const text = await readFile(path, \"utf8\");\n try {\n return JSON.parse(text);\n } catch (error) {\n throw new CliError(`${path} is not valid JSON: ${(error as Error).message}`, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n }\n if (![\".ts\", \".mts\", \".js\", \".mjs\", \".cts\", \".cjs\"].includes(ext)) {\n throw new CliError(`Unsupported config file extension \"${ext}\" (${path}). Use .ts, .mts, .js, .mjs or .json.`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n }\n const jiti = createJiti(import.meta.url, { interopDefault: false, moduleCache: false, fsCache: false });\n try {\n return await jiti.import(pathToFileURL(path).href);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Failed to load ${path}: ${message}`, EXIT.USAGE, { code: \"config_load_failed\", cause: error });\n }\n}\n\nfunction pickConfigExport(raw: unknown, path: string): unknown {\n if (raw && typeof raw === \"object\") {\n const record = raw as Record<string, unknown>;\n if (\"default\" in record && record.default !== undefined) {\n const def = record.default;\n // `export default { default: ... }` interop layering\n if (def && typeof def === \"object\" && !(\"products\" in (def as object)) && \"default\" in (def as Record<string, unknown>)) {\n return (def as Record<string, unknown>).default;\n }\n return def;\n }\n if (\"config\" in record && record.config !== undefined) return record.config;\n if (\"products\" in record) return raw;\n }\n throw new CliError(`${path} must export a config as its default export or a named \\`config\\` export (see \\`purpleturret init\\`).`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n}\n","import { relative } from \"node:path\";\n\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader\";\nimport { describeSource, globalArgs } from \"../lib/context\";\nimport { renderSummary, sortPlanItems } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\n\nexport const status = defineCommand({\n meta: { name: \"status\", description: \"Compare the local config with the account (dry run) and print a summary\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const plan = await ctx.client().config.push({ products: loaded.config.products, dryRun: true });\n if (ctx.json) {\n ctx.out.printJson({ config: loaded.path, api_url: ctx.apiUrl, summary: plan.summary, results: plan.results });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.print(`${palette.dim(\"Config\")} ${relative(ctx.cwd, loaded.path) || loaded.path} (${loaded.config.products.length} products)`);\n ctx.out.print(`${palette.dim(\"API URL\")} ${ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)}`);\n ctx.out.print(\n `${palette.dim(\"Credentials\")} ${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`,\n );\n ctx.out.print(\"\");\n for (const item of sortPlanItems(plan.results)) {\n if (item.action === \"unchanged\") continue;\n const detail = item.error ? ` ${item.error.code}: ${item.error.message}` : \"\";\n ctx.out.print(` ${item.action.padEnd(9)} ${item.key}${detail}`);\n }\n ctx.out.print(renderSummary(plan.summary, { palette, mode: \"plan\" }));\n if (plan.summary.create + plan.summary.update + plan.summary.archive > 0) ctx.out.info(palette.dim(\"Run `purpleturret push` to apply.\"));\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { describeSource, globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\nexport const whoami = defineCommand({\n meta: { name: \"whoami\", description: \"Show the account and key behind the current credentials\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const account = await ctx.client().account.get();\n if (ctx.json) {\n ctx.out.printJson({ account, api_url: ctx.apiUrl, credential_source: ctx.credentialSource, profile: ctx.profileName });\n return;\n }\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"Account\", `${account.email}${account.name ? ` (${account.name})` : \"\"}`],\n [\"Key\", `${account.key.prefix}…${account.key.name ? ` \"${account.key.name}\"` : \"\"}`],\n [\"Scopes\", account.key.scopes.join(\", \") || palette.dim(\"none\")],\n [\n \"Stripe\",\n account.stripe.connected\n ? account.stripe.chargesEnabled\n ? \"connected\"\n : \"connected (charges not enabled)\"\n : palette.yellow(\"not connected\"),\n ],\n [\"PayPal\", account.paypal.connected ? \"connected\" : palette.dim(\"not connected\")],\n [\"API URL\", ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)],\n [\"Credentials\", `${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`],\n ];\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) ctx.out.print(`${palette.dim(label.padEnd(width))} ${value}`);\n }),\n});\n","import { runCli } from \"./main\";\n\nawait runCli();\n"],"mappings":";AAAA,SAAS,iBAAAA,iBAAe,YAAY,iBAAkC;;;ACAtE,SAAS,iBAAAC,sBAAqB;;;ACA9B,SAAS,kBAAkB;AAC3B,SAAS,QAAAC,aAAY;;;ACAd,IAAM,cAAc;;;ACD3B,SAAS,SAAS;AAKX,IAAM,cAAc;AAEpB,IAAM,eAAe;AAC5B,IAAM,oBAAoB;AAE1B,IAAM,cAAc;AAEb,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAC3D,IAAM,cAAc,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAE7D,IAAM,cAAc,EAAE,aAAa;AAAA,EACxC,QAAQ,EACL,OAAO,sEAAsE,EAC7E,IAAI,sEAAsE,EAC1E,IAAI,IAAI,+DAA+D;AAAA,EAC1E,UAAU,EACP,OAAO,EACP,KAAK,EACL,YAAY,EACZ,MAAM,cAAc,sCAAsC;AAC/D,CAAC;AAEM,IAAM,gBAAgB,EAAE,mBAAmB,QAAQ;AAAA,EACxD,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAAA,EAC9C,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,WAAW,GAAG,UAAU,EAAE,KAAK,CAAC,SAAS,MAAM,CAAC,EAAE,CAAC;AACtF,CAAC;AAEM,IAAM,aAAa,EAAE,aAAa;AAAA,EACvC,KAAK;AAAA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","id","patch","files","id","patch","idOrKey","id","id","fromWireGroup","id","patch","init","status","text","when","idOrKey","patch","delivery","text","text","text","join","init","text","list","defineCommand","update","del","confirm","defineCommand","money","product","text","mode","list","defineCommand","page","confirm","defineCommand","id","list","defineCommand","page","get","defineCommand","list","defineCommand","customers","page","get","customer","defineCommand","defineCommand","confirm","defineCommand","n","list","defineCommand","get","create","update","confirm","pages","join","confirm","defineCommand","id","page","join","list","defineCommand","get","update","patch","del","confirm","rangeArgs","pages","defineCommand","tracking","id","get","defineCommand","pixelId","token","product","confirm","defineCommand","id","list","defineCommand","get","add","update","confirm","confirm","defineCommand","get","defineCommand","account","update","status","confirm","defineCommand","defineCommand","existsSync","writeFile","relative","resolve","defineCommand","products","product","defineCommand","target","resolve","existsSync","relative","products","writeFile","defineCommand","defineCommand","account","defineCommand","defineCommand","z","z","target","patch","z","z","z","page","z","id","z","id","z","range","target","patch","z","z","range","id","files","z","z","idOrKey","id","z","id","z","z","groups","keys","id","z","patch","defineCommand","defineCommand","resolve","readFile","basename","confirm","defineCommand","id","delivery","product","list","defineCommand","products","page","get","create","update","patch","readFile","basename","archive","confirm","visits","existsSync","writeFile","relative","resolve","defineCommand","defineCommand","products","target","resolve","existsSync","relative","writeFile","relative","confirm","defineCommand","existsSync","statSync","readFile","dirname","join","resolve","resolve","existsSync","statSync","join","dirname","text","readFile","defineCommand","products","relative","confirm","relative","defineCommand","defineCommand","relative","defineCommand","defineCommand","account","defineCommand","pages","token"]}
|
|
1
|
+
{"version":3,"sources":["../src/main.ts","../src/commands/groups.ts","../src/lib/context.ts","../../sdk/src/version.ts","../../sdk/src/config/schema.ts","../../sdk/src/config/define.ts","../../sdk/src/client/wire.ts","../../sdk/src/client/areas/account.ts","../../sdk/src/client/areas/orders.ts","../../sdk/src/client/areas/pixels.ts","../../sdk/src/client/areas/pages.ts","../../sdk/src/client/areas/tracking.ts","../../sdk/src/client/areas/domains.ts","../../sdk/src/client/areas/webhooks.ts","../../sdk/src/client/errors.ts","../../sdk/src/client/areas/uploads.ts","../../sdk/src/client/client.ts","../src/version.ts","../src/lib/credentials.ts","../src/lib/errors.ts","../src/lib/output.ts","../src/lib/run.ts","../src/lib/table.ts","../src/commands/webhooks.ts","../src/commands/orders.ts","../src/lib/render.ts","../src/commands/subscriptions.ts","../src/commands/customers.ts","../src/commands/leads.ts","../src/commands/pixels.ts","../src/commands/pages.ts","../src/commands/tracking.ts","../src/commands/domains.ts","../src/commands/account.ts","../src/commands/support.ts","../src/commands/init.ts","../src/lib/pull-writer.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/mcp.ts","../../mcp/src/index.ts","../../mcp/src/tools/core.ts","../../mcp/src/tools/account.ts","../../mcp/src/tools/products.ts","../../mcp/src/tools/orders.ts","../../mcp/src/tools/pixels.ts","../../mcp/src/tools/pages.ts","../../mcp/src/tools/tracking.ts","../../mcp/src/tools/domains.ts","../../mcp/src/tools/webhooks.ts","../src/commands/products.ts","../src/commands/pull.ts","../src/commands/push.ts","../src/lib/config-loader.ts","../src/commands/status.ts","../src/commands/whoami.ts","../src/cli.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage, type CommandDef } from \"citty\";\n\nimport { groups } from \"./commands/groups\";\nimport { orders } from \"./commands/orders\";\nimport { subscriptions } from \"./commands/subscriptions\";\nimport { customers } from \"./commands/customers\";\nimport { leads } from \"./commands/leads\";\nimport { pixels } from \"./commands/pixels\";\nimport { pages } from \"./commands/pages\";\nimport { tracking } from \"./commands/tracking\";\nimport { domains } from \"./commands/domains\";\nimport { webhooks } from \"./commands/webhooks\";\nimport { account } from \"./commands/account\";\nimport { support } from \"./commands/support\";\nimport { init } from \"./commands/init\";\nimport { login } from \"./commands/login\";\nimport { logout } from \"./commands/logout\";\nimport { mcp } from \"./commands/mcp\";\nimport { products } from \"./commands/products\";\nimport { pull } from \"./commands/pull\";\nimport { push } from \"./commands/push\";\nimport { status } from \"./commands/status\";\nimport { whoami } from \"./commands/whoami\";\nimport { globalArgs, stashGlobalFlags, type GlobalFlags } from \"./lib/context\";\nimport { CliError, EXIT } from \"./lib/errors\";\nimport { Output, createPalette, shouldUseColor } from \"./lib/output\";\nimport { CLI_VERSION } from \"./version\";\n\nexport const main = defineCommand({\n meta: {\n name: \"purpleturret\",\n version: CLI_VERSION,\n description: \"Sync purpleturret.config.ts with your Purpleturret account. Also available as `pt`.\",\n },\n args: { ...globalArgs },\n setup({ args }) {\n stashGlobalFlags(args as GlobalFlags);\n },\n subCommands: {\n init,\n login,\n logout,\n whoami,\n status,\n push,\n pull,\n mcp,\n products,\n groups,\n orders,\n subscriptions,\n customers,\n leads,\n pixels,\n pages,\n tracking,\n domains,\n webhooks,\n account,\n support,\n },\n});\n\ntype AnyCommand = CommandDef<Record<string, never>>;\n\nasync function resolveSubCommand(cmd: AnyCommand, rawArgs: string[]): Promise<[AnyCommand, AnyCommand | undefined]> {\n let current: AnyCommand = cmd;\n let parent: AnyCommand | undefined;\n let args = rawArgs;\n for (;;) {\n const subCommands = (await current.subCommands) as Record<string, AnyCommand> | undefined;\n if (!subCommands) return [current, parent];\n const index = args.findIndex((arg) => !arg.startsWith(\"-\"));\n const name = index >= 0 ? args[index] : undefined;\n const next = name ? subCommands[name] : undefined;\n if (!next) return [current, parent];\n parent = current;\n current = next;\n args = args.slice(index + 1);\n }\n}\n\nfunction isCittyError(error: unknown): error is Error & { code?: string } {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\nconst GLOBAL_STRING_FLAGS = new Set([\"--config\", \"--api-url\", \"--api-key\", \"--profile\"]);\n\n/**\n * citty picks the first token that does not start with \"-\" as the subcommand, so `pt --api-key x push`\n * would treat `x` as the command. Move flags that precede the subcommand behind it instead.\n */\nexport function hoistLeadingFlags(rawArgs: string[]): string[] {\n const leading: string[] = [];\n let index = 0;\n while (index < rawArgs.length) {\n const token = rawArgs[index]!;\n if (!token.startsWith(\"-\")) break;\n leading.push(token);\n index += 1;\n const next = rawArgs[index];\n if (GLOBAL_STRING_FLAGS.has(token) && next !== undefined && !next.startsWith(\"-\")) {\n leading.push(next);\n index += 1;\n }\n }\n if (index === 0 || index >= rawArgs.length) return rawArgs;\n return [...rawArgs.slice(index), ...leading];\n}\n\n/** Entry point shared by the bin shim and tests. Sets `process.exitCode`; never calls `process.exit`. */\nexport async function runCli(argv: string[] = process.argv.slice(2)): Promise<void> {\n const root = main as unknown as AnyCommand;\n const rawArgs = hoistLeadingFlags(argv);\n try {\n if (rawArgs.includes(\"--help\") || rawArgs.includes(\"-h\")) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n return;\n }\n if (rawArgs.length === 1 && rawArgs[0] === \"--version\") {\n process.stdout.write(`${CLI_VERSION}\\n`);\n return;\n }\n if (rawArgs.length === 0) {\n await showUsage(root);\n return;\n }\n await runCommand(root, { rawArgs });\n } catch (error) {\n const flags = parseLooseGlobals(rawArgs);\n const out = new Output({ json: flags.json, verbose: flags.verbose, palette: createPalette(shouldUseColor({ flag: flags.color })) });\n if (isCittyError(error)) {\n out.fail(new CliError(error.message, EXIT.USAGE, { code: \"usage\" }));\n if (!flags.json) {\n const [cmd, parent] = await resolveSubCommand(root, rawArgs);\n await showUsage(cmd, parent);\n }\n process.exitCode = EXIT.USAGE;\n return;\n }\n const cliError =\n error instanceof CliError ? error : new CliError(error instanceof Error ? error.message : String(error), EXIT.ERROR, { cause: error });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n}\n\nfunction parseLooseGlobals(rawArgs: string[]): { json: boolean; verbose: boolean; color: boolean | undefined } {\n return {\n json: rawArgs.includes(\"--json\"),\n verbose: rawArgs.includes(\"--verbose\"),\n color: rawArgs.includes(\"--no-color\") ? false : undefined,\n };\n}\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\nimport { confirmOrYes } from \"./webhooks\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List integration groups\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().groups.list();\n if (ctx.json) return ctx.out.printJson({ groups: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No integration groups yet. Run `purpleturret groups create <key> <name>`.\"));\n const rows = data.map((g) => [g.key, g.name, new Date(g.createdAt).toISOString()]);\n for (const line of renderTable([\"KEY\", \"NAME\", \"CREATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst create = defineCommand({\n meta: { name: \"create\", description: \"Create an integration group\" },\n args: {\n ...globalArgs,\n key: { type: \"positional\", required: true, description: \"Group key (2-64 letters, numbers, dashes, underscores)\" },\n name: { type: \"positional\", required: true, description: \"Display name (1-80 chars)\" },\n },\n run: defineRun(async (ctx, args) => {\n const group = await ctx.client().groups.create({ key: args.key, name: args.name });\n ctx.json ? ctx.out.printJson(group) : ctx.out.print(`Created group ${group.key} (${group.name})`);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Rename an integration group\" },\n args: { ...globalArgs, key: { type: \"positional\", required: true }, name: { type: \"string\", required: true, description: \"New display name\" } },\n run: defineRun(async (ctx, args) => {\n const group = await ctx.client().groups.update(args.key, { name: args.name });\n ctx.json ? ctx.out.printJson(group) : ctx.out.print(`Renamed group ${group.key} to ${group.name}`);\n }),\n});\n\nconst del = defineCommand({\n meta: { name: \"delete\", description: \"Delete an integration group (cascades to its webhooks; products keep selling without a tier)\" },\n args: {\n ...globalArgs,\n key: { type: \"positional\", required: true },\n yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt (required in CI)\" },\n },\n run: defineRun(async (ctx, args) => {\n await confirmOrYes(\n Boolean(args.yes),\n ctx.json,\n `Delete group ${args.key}? This also deletes its webhook endpoints, deliveries and events, and clears the group and tier on its products.`,\n );\n const group = await ctx.client().groups.delete(args.key);\n ctx.json ? ctx.out.printJson(group) : ctx.out.print(`Deleted group ${group.key}`);\n }),\n});\n\nexport const groups = defineCommand({\n meta: { name: \"groups\", description: \"Integration groups\" },\n args: { ...globalArgs },\n subCommands: { list, create, update, delete: del },\n});\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { DEFAULT_BASE_URL, PurpleturretClient } from \"@purpleturret/sdk\";\nimport dotenv from \"dotenv\";\n\nimport { CLI_VERSION } from \"../version\";\nimport { CredentialsStore, DEFAULT_PROFILE, credentialsPath, type Profile } from \"./credentials\";\nimport { CliError, EXIT, type ErrorContext } from \"./errors\";\nimport { Output, createPalette, shouldUseColor } from \"./output\";\n\n/** Flags accepted by every command. */\nexport interface GlobalFlags {\n config?: string;\n \"api-url\"?: string;\n apiUrl?: string;\n \"api-key\"?: string;\n apiKey?: string;\n profile?: string;\n json?: boolean;\n color?: boolean;\n verbose?: boolean;\n}\n\nexport const globalArgs = {\n config: { type: \"string\", description: \"Path to purpleturret.config.{ts,mts,js,mjs,json} (default: search up to the git root)\" },\n \"api-url\": { type: \"string\", description: \"API origin (default: PURPLETURRET_API_URL, saved profile, or https://api.purpleturret.com)\" },\n \"api-key\": { type: \"string\", description: \"Seller API key (default: PURPLETURRET_API_KEY, .env.local/.env, or saved profile)\" },\n profile: { type: \"string\", description: 'Credentials profile name (default: \"default\")' },\n json: { type: \"boolean\", description: \"Print machine-readable JSON on stdout\" },\n color: { type: \"boolean\", description: \"Colorize output (disable with --no-color or NO_COLOR)\" },\n verbose: { type: \"boolean\", description: \"Log requests and stack traces to stderr\" },\n} as const;\n\nlet stashedGlobals: GlobalFlags = {};\n\n/** Remember flags parsed on the root command so `pt --json push` works as well as `pt push --json`. */\nexport function stashGlobalFlags(flags: GlobalFlags): void {\n stashedGlobals = { ...flags };\n}\n\nexport function mergeGlobalFlags(flags: GlobalFlags): GlobalFlags {\n const merged: GlobalFlags = { ...stashedGlobals };\n for (const [key, value] of Object.entries(flags)) {\n if (value !== undefined) (merged as Record<string, unknown>)[key] = value;\n }\n return merged;\n}\n\nexport type Source = \"flag\" | \"env\" | \"profile\" | \"default\" | \"none\";\n\nexport interface CliContext extends ErrorContext {\n cwd: string;\n env: NodeJS.ProcessEnv;\n flags: GlobalFlags;\n json: boolean;\n verbose: boolean;\n out: Output;\n profileName: string;\n profile: Profile | null;\n credentials: CredentialsStore;\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n apiKey: string | null;\n credentialSource: \"flag\" | \"env\" | \"profile\" | \"none\";\n configPath: string | undefined;\n /** Build an authenticated client, or fail with exit 3 when no key is available. */\n client(): PurpleturretClient;\n /** Build a client for an explicit key (used by `login`). */\n clientFor(apiKey: string): PurpleturretClient;\n}\n\nexport interface CreateContextOptions {\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n credentialsFile?: string;\n}\n\nexport function loadDotenv(cwd: string, env: NodeJS.ProcessEnv): string[] {\n const loaded: string[] = [];\n for (const name of [\".env.local\", \".env\"]) {\n const path = join(cwd, name);\n if (!existsSync(path)) continue;\n dotenv.config({ path, override: false, quiet: true, processEnv: env as Record<string, string> });\n loaded.push(path);\n }\n return loaded;\n}\n\nexport async function createContext(rawFlags: GlobalFlags, options: CreateContextOptions = {}): Promise<CliContext> {\n const cwd = options.cwd ?? process.cwd();\n const env = options.env ?? process.env;\n const flags = mergeGlobalFlags(rawFlags);\n const json = Boolean(flags.json);\n const verbose = Boolean(flags.verbose);\n const palette = createPalette(\n shouldUseColor({ flag: flags.color, env, stream: (options.stderr as { isTTY?: boolean } | undefined) ?? process.stderr }),\n );\n const out = new Output({ json, verbose, palette, stdout: options.stdout, stderr: options.stderr });\n\n const loadedEnvFiles = loadDotenv(cwd, env);\n if (loadedEnvFiles.length) out.debug(`loaded ${loadedEnvFiles.join(\", \")}`);\n\n const profileName = flags.profile?.trim() || DEFAULT_PROFILE;\n const credentials = new CredentialsStore(options.credentialsFile ?? credentialsPath(env));\n const profile = await credentials.getProfile(profileName);\n\n const flagKey = (flags[\"api-key\"] ?? flags.apiKey)?.trim();\n const envKey = env.PURPLETURRET_API_KEY?.trim();\n let apiKey: string | null = null;\n let credentialSource: CliContext[\"credentialSource\"] = \"none\";\n if (flagKey) [apiKey, credentialSource] = [flagKey, \"flag\"];\n else if (envKey) [apiKey, credentialSource] = [envKey, \"env\"];\n else if (profile?.apiKey) [apiKey, credentialSource] = [profile.apiKey, \"profile\"];\n\n const flagUrl = (flags[\"api-url\"] ?? flags.apiUrl)?.trim();\n const envUrl = env.PURPLETURRET_API_URL?.trim();\n let apiUrl = DEFAULT_BASE_URL;\n let apiUrlSource: CliContext[\"apiUrlSource\"] = \"default\";\n if (flagUrl) [apiUrl, apiUrlSource] = [flagUrl, \"flag\"];\n else if (envUrl) [apiUrl, apiUrlSource] = [envUrl, \"env\"];\n else if (profile?.apiUrl) [apiUrl, apiUrlSource] = [profile.apiUrl, \"profile\"];\n apiUrl = apiUrl.replace(/\\/+$/, \"\");\n if (!/^https?:\\/\\//.test(apiUrl)) {\n throw new CliError(`Invalid API URL \"${apiUrl}\"; it must start with http:// or https://`, EXIT.USAGE, { code: \"invalid_api_url\" });\n }\n\n let announcedUrl = false;\n const announceUrl = () => {\n if (announcedUrl || apiUrlSource === \"default\") return;\n announcedUrl = true;\n out.info(palette.yellow(`Using API ${apiUrl} (from ${describeSource(apiUrlSource)})`));\n };\n\n const fetchImpl: typeof fetch = async (input, init) => {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n out.debug(`${init?.method ?? \"GET\"} ${url}`);\n const started = Date.now();\n const response = await fetch(input, init);\n out.debug(`→ ${response.status} ${response.headers.get(\"x-request-id\") ?? \"\"} (${Date.now() - started}ms)`.trimEnd());\n return response;\n };\n\n const clientFor = (key: string) => {\n announceUrl();\n return new PurpleturretClient({ apiKey: key, baseUrl: apiUrl, fetch: fetchImpl, userAgent: `purpleturret-cli/${CLI_VERSION}` });\n };\n\n const context: CliContext = {\n cwd,\n env,\n flags,\n json,\n verbose,\n out,\n profileName,\n profile,\n credentials,\n apiUrl,\n apiUrlSource,\n apiKey,\n credentialSource,\n configPath: flags.config,\n clientFor,\n client() {\n if (!apiKey) {\n throw new CliError(`No API key found for profile \"${profileName}\".`, EXIT.AUTH, {\n code: \"no_credentials\",\n hint: \"Run `purpleturret login`, pass --api-key, or set PURPLETURRET_API_KEY (also read from .env.local / .env in the current directory).\",\n });\n }\n return clientFor(apiKey);\n },\n };\n return context;\n}\n\nexport function describeSource(source: Source): string {\n switch (source) {\n case \"flag\":\n return \"command-line flag\";\n case \"env\":\n return \"environment\";\n case \"profile\":\n return \"saved profile\";\n case \"default\":\n return \"default\";\n default:\n return \"none\";\n }\n}\n","/** Keep in sync with package.json. */\nexport const SDK_VERSION = \"0.7.0\";\n","import { z } from \"zod\";\n\nimport type { ProductInput, PurpleturretConfig } from \"../types\";\n\n/** Product keys and credit meters: 1-64 chars, lowercase letters, digits, `_` or `-`, starting with a letter or digit. */\nexport const KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n/** Public checkout slugs: 3-64 chars, lowercase letters, digits, or `-`. */\nexport const SLUG_PATTERN = /^[a-z0-9-]{3,64}$/;\nconst HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\nconst KEY_MESSAGE = \"must be 1-64 characters of lowercase letters, digits, '_' or '-', starting with a letter or digit\";\n\nexport const keySchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\nexport const meterSchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);\n\nexport const moneySchema = z.strictObject({\n amount: z\n .number(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .int(\"must be an integer amount in the smallest currency unit (e.g. cents)\")\n .min(50, \"must be at least 50 (e.g. $0.50); use usd(dollars) to convert\"),\n currency: z\n .string()\n .trim()\n .toLowerCase()\n .regex(/^[a-z]{3}$/, \"must be a 3-letter ISO currency code\"),\n});\n\nexport const billingSchema = z.discriminatedUnion(\"type\", [\n z.strictObject({ type: z.literal(\"one_time\") }),\n z.strictObject({ type: z.literal(\"recurring\"), interval: z.enum([\"month\", \"year\"]) }),\n]);\n\nexport const tierSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(80),\n rank: z.number().int(\"must be an integer\").min(0),\n});\n\nexport const groupSchema = z.strictObject({\n key: keySchema,\n tier: tierSchema.optional(),\n});\n\nexport const creditGrantSchema = z.strictObject({\n meter: meterSchema,\n amount: z.number().int(\"must be an integer\").positive(\"must be a positive integer\"),\n renewal: z.enum([\"reset\", \"accumulate\"]),\n expiresAfterDays: z.number().int(\"must be an integer\").positive(\"must be a positive integer\").optional(),\n});\n\nexport const deliverySchema = z.discriminatedUnion(\"method\", [\n z.strictObject({ method: z.literal(\"none\") }),\n z.strictObject({\n method: z.literal(\"redirect\"),\n url: z\n .string()\n .url(\"must be an absolute URL\")\n .refine((value) => value.startsWith(\"https://\"), \"must be an https:// URL\"),\n }),\n z.strictObject({ method: z.literal(\"instructions\"), instructions: z.string().trim().min(1, \"must not be empty\").max(10_000) }),\n]);\n\nexport const checkoutSchema = z.strictObject({\n layoutMode: z.enum([\"two_step\", \"one_step\"]).optional(),\n paymentStyle: z.enum([\"classic\", \"express\"]).optional(),\n providerMode: z.enum([\"inherit\", \"stripe\", \"paypal\", \"both\"]).optional(),\n contactFields: z.strictObject({ name: z.boolean().optional(), phone: z.boolean().optional() }).optional(),\n});\n\nexport const themeSchema = z.strictObject({\n primaryColor: z.string().regex(HEX_COLOR_PATTERN, \"must be a hex color such as #5F34CC\").optional(),\n buttonRadius: z.enum([\"sm\", \"md\", \"lg\"]).optional(),\n accentMode: z.enum([\"light\", \"dark\", \"system\"]).optional(),\n});\n\nexport const stripeSchema = z.strictObject({\n priceId: z.string().trim().min(1, \"must be a Stripe price id (price_…)\"),\n});\n\nexport const productInputSchema = z.strictObject({\n key: keySchema,\n name: z.string().trim().min(1, \"must not be empty\").max(120),\n description: z.string().max(5_000).optional(),\n price: moneySchema,\n billing: billingSchema,\n group: groupSchema.optional(),\n credits: z.array(creditGrantSchema).optional(),\n delivery: deliverySchema.optional(),\n checkout: checkoutSchema.optional(),\n theme: themeSchema.optional(),\n slug: z.string().regex(SLUG_PATTERN, \"must be 3-64 characters of lowercase letters, digits, or '-'\").optional(),\n stripe: stripeSchema.optional(),\n active: z.boolean().optional(),\n buyerEmails: z.boolean().optional(),\n offers: z\n .record(\n z.string().regex(/^[a-z0-9-]{1,32}$/, \"must be 1-32 characters of lowercase letters, digits, or '-'\"),\n z.strictObject({ title: z.string().trim().min(1, \"must not be empty\").max(120), subtitle: z.string().trim().max(120).optional() }),\n )\n .refine((offers) => Object.keys(offers).length <= 10, \"must have 10 entries or fewer\")\n .optional(),\n tabTitle: z.string().trim().max(80).optional(),\n trustBadge: z\n .strictObject({\n title: z.string().trim().max(80).optional(),\n caption: z.string().trim().max(80).optional(),\n logos: z\n .array(\n z.strictObject({\n imageUrl: z\n .string()\n .trim()\n .max(500)\n .regex(/^https:\\/\\/\\S+$/, \"must be an https URL\"),\n alt: z.string().trim().min(1).max(80),\n }),\n )\n .min(1)\n .max(12),\n })\n .nullable()\n .optional(),\n});\n\nexport const configSchema = z\n .strictObject({\n products: z.array(productInputSchema),\n })\n .superRefine((config, ctx) => {\n const seenKeys = new Map<string, number>();\n config.products.forEach((product, index) => {\n const firstIndex = seenKeys.get(product.key);\n if (firstIndex !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"key\"],\n message: `duplicate product key \"${product.key}\" (also used by products[${firstIndex}])`,\n });\n } else {\n seenKeys.set(product.key, index);\n }\n const seenMeters = new Map<string, number>();\n product.credits?.forEach((grant, grantIndex) => {\n const firstMeter = seenMeters.get(grant.meter);\n if (firstMeter !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"products\", index, \"credits\", grantIndex, \"meter\"],\n message: `duplicate credit meter \"${grant.meter}\" (also used by credits[${firstMeter}])`,\n });\n } else {\n seenMeters.set(grant.meter, grantIndex);\n }\n });\n });\n });\n\nexport interface ConfigIssue {\n /** Dotted path such as `products[0].price.amount`. */\n path: string;\n message: string;\n}\n\nexport class ConfigValidationError extends Error {\n override readonly name = \"ConfigValidationError\";\n readonly issues: ConfigIssue[];\n\n constructor(issues: ConfigIssue[]) {\n super(formatIssues(issues));\n this.issues = issues;\n }\n}\n\nexport function formatIssuePath(path: ReadonlyArray<PropertyKey>): string {\n let out = \"\";\n for (const segment of path) {\n if (typeof segment === \"number\") out += `[${segment}]`;\n else out += out ? `.${String(segment)}` : String(segment);\n }\n return out || \"(root)\";\n}\n\nfunction formatIssues(issues: ConfigIssue[]): string {\n const lines = issues.map((issue) => ` - ${issue.path}: ${issue.message}`);\n return `Invalid Purpleturret config (${issues.length} issue${issues.length === 1 ? \"\" : \"s\"}):\\n${lines.join(\"\\n\")}`;\n}\n\n/**\n * Validate an arbitrary value as a Purpleturret config. Returns the normalized config (currencies\n * lowercased, strings trimmed) or throws `ConfigValidationError` listing every problem found.\n */\nexport function validateConfig(input: unknown): PurpleturretConfig {\n const result = configSchema.safeParse(input);\n if (result.success) return result.data as PurpleturretConfig;\n const issues: ConfigIssue[] = result.error.issues.map((issue) => ({\n path: formatIssuePath(issue.path),\n message: issue.message,\n }));\n throw new ConfigValidationError(issues);\n}\n\n/** Validate a single product declaration. */\nexport function validateProduct(input: unknown): ProductInput {\n const result = productInputSchema.safeParse(input);\n if (result.success) return result.data as ProductInput;\n throw new ConfigValidationError(result.error.issues.map((issue) => ({ path: formatIssuePath(issue.path), message: issue.message })));\n}\n","import type { Money, ProductInput, PurpleturretConfig } from \"../types\";\n\n/** Identity helper that gives `purpleturret.config.ts` type checking and editor completion. */\nexport function defineConfig(config: PurpleturretConfig): PurpleturretConfig {\n return config;\n}\n\n/** Identity helper for a single product declaration. */\nexport function product(input: ProductInput): ProductInput {\n return input;\n}\n\n/** Build a price from an integer amount in the smallest currency unit and a 3-letter currency code. */\nexport function money(amount: number, currency: string): Money {\n if (!Number.isInteger(amount)) {\n throw new TypeError(`money(): amount must be an integer in the smallest currency unit (got ${amount}); use usd(dollars) for dollars`);\n }\n return { amount, currency: currency.trim().toLowerCase() };\n}\n\n/** Build a USD price from a dollar amount (`usd(29)` → 2900 cents, `usd(19.99)` → 1999). */\nexport function usd(dollars: number): Money {\n if (!Number.isFinite(dollars)) throw new TypeError(`usd(): expected a finite number of dollars (got ${dollars})`);\n return { amount: Math.round((dollars + Number.EPSILON) * 100), currency: \"usd\" };\n}\n","import type {\n Account,\n Billing,\n CheckoutSettings,\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CreditGrant,\n CustomerRef,\n Delivery,\n Entitlement,\n LedgerEntry,\n Page,\n PlanAction,\n PlanItem,\n Product,\n ProductBump,\n ProductDelivery,\n ProductOffer,\n ProductGroup,\n ProductInput,\n ProductTheme,\n StripeSettings,\n Tier,\n} from \"../types\";\n\n/*\n * Wire (snake_case) shapes as sent and received by the REST API.\n */\n\nexport interface WireMoney {\n amount: number;\n currency: string;\n}\n\nexport type WireBilling = { type: \"one_time\" } | { type: \"recurring\"; interval: \"month\" | \"year\" };\n\nexport interface WireTier {\n key: string;\n name: string;\n rank: number;\n}\n\nexport interface WireGroup {\n key: string;\n tier?: WireTier | null;\n}\n\nexport interface WireCreditGrant {\n meter: string;\n amount: number;\n renewal: \"reset\" | \"accumulate\";\n expires_after_days?: number | null;\n}\n\nexport type WireDelivery = { method: \"none\" } | { method: \"redirect\"; url: string } | { method: \"instructions\"; instructions: string };\n\nexport interface WireCheckout {\n layout_mode?: \"two_step\" | \"one_step\" | null;\n payment_style?: \"classic\" | \"express\" | null;\n provider_mode?: \"inherit\" | \"stripe\" | \"paypal\" | \"both\" | null;\n contact_fields?: { name?: boolean | null; phone?: boolean | null } | null;\n}\n\nexport interface WireTheme {\n primary_color?: string | null;\n button_radius?: \"sm\" | \"md\" | \"lg\" | null;\n accent_mode?: \"light\" | \"dark\" | \"system\" | null;\n}\n\nexport interface WireStripe {\n price_id: string;\n}\n\nexport interface WireProductInput {\n key: string;\n name: string;\n description?: string | null;\n price: WireMoney;\n billing: WireBilling;\n group?: WireGroup | null;\n credits?: WireCreditGrant[] | null;\n delivery?: WireDelivery | null;\n checkout?: WireCheckout | null;\n theme?: WireTheme | null;\n slug?: string | null;\n stripe?: WireStripe | null;\n active?: boolean;\n buyer_emails?: boolean;\n offers?: Record<string, ProductOffer>;\n tab_title?: string | null;\n trust_badge?: { title?: string | null; caption?: string | null; logos: { image_url: string; alt: string }[] } | null;\n}\n\nexport type WireProductDelivery =\n | WireDelivery\n | { method: \"file\"; file_count: number; files?: { file_name: string; content_type: string; file_size: number }[] };\n\nexport interface WireBump {\n product_id: string;\n headline: string;\n description: string;\n}\n\nexport interface WireProduct extends Omit<WireProductInput, \"key\" | \"slug\" | \"active\" | \"delivery\" | \"theme\"> {\n key: string | null;\n id: string;\n slug: string | null;\n url: string | null;\n active: boolean;\n delivery?: WireProductDelivery | null;\n theme?: (WireTheme & { logo_storage_id?: string | null; logo_url?: string | null }) | null;\n bumps?: WireBump[] | null;\n upsell?: WireBump | null;\n pixel_id?: string | null;\n archived_at: number | null;\n created_at: number;\n updated_at: number;\n}\n\nexport interface WirePlanChange {\n path: string;\n from: unknown;\n to: unknown;\n note?: string | null;\n}\n\nexport interface WirePlanItem {\n key: string;\n action: PlanAction;\n changes?: WirePlanChange[] | null;\n product?: WireProduct | null;\n error?: { code?: string; message?: string } | string | null;\n}\n\nexport interface WireConfigPushResult {\n applied: boolean;\n summary: { create: number; update: number; unchanged: number; archive: number; conflict: number; error: number };\n results: WirePlanItem[];\n}\n\nexport interface WireConfigGetResult {\n products: WireProduct[];\n unmanaged_count: number;\n}\n\nexport interface WireAccount {\n id: string;\n email: string;\n name?: string | null;\n stripe: { connected: boolean; charges_enabled: boolean };\n paypal: { connected: boolean };\n key: { prefix: string; name?: string | null; scopes: string[] };\n}\n\nexport interface WirePage<T> {\n data: T[];\n next_cursor?: string | null;\n}\n\nexport interface WireCustomerRef {\n email?: string | null;\n external_id?: string | null;\n}\n\nexport interface WireCreditBalance {\n meter: string;\n balance: number;\n expires_at?: number | null;\n lifetime_granted: number;\n lifetime_consumed: number;\n}\n\nexport interface WireCreditBalancesResult {\n customer: WireCustomerRef;\n balances: WireCreditBalance[];\n}\n\nexport interface WireCreditConsumeResult {\n meter: string;\n balance: number;\n consumed: number;\n replayed: boolean;\n}\n\nexport interface WireCreditAdjustResult {\n meter: string;\n balance: number;\n}\n\nexport type WireLedgerEntry = Record<string, unknown>;\n\nexport type WireEntitlement = Record<string, unknown>;\n\n/*\n * Mappers.\n */\n\nfunction omitUndefined<T extends object>(value: T): T {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = entry;\n }\n return out as T;\n}\n\nexport function toWireProduct(input: ProductInput): WireProductInput {\n const wire: WireProductInput = {\n key: input.key,\n name: input.name,\n description: input.description,\n price: { amount: input.price.amount, currency: input.price.currency },\n billing: input.billing.type === \"recurring\" ? { type: \"recurring\", interval: input.billing.interval } : { type: \"one_time\" },\n group: input.group ? toWireGroup(input.group) : undefined,\n credits: input.credits?.map(toWireCreditGrant),\n delivery: input.delivery ? toWireDelivery(input.delivery) : undefined,\n checkout: input.checkout ? toWireCheckout(input.checkout) : undefined,\n theme: input.theme ? toWireTheme(input.theme) : undefined,\n slug: input.slug,\n stripe: input.stripe ? { price_id: input.stripe.priceId } : undefined,\n active: input.active,\n buyer_emails: input.buyerEmails,\n offers: input.offers,\n tab_title: input.tabTitle,\n trust_badge: input.trustBadge && {\n title: input.trustBadge.title,\n caption: input.trustBadge.caption,\n logos: input.trustBadge.logos.map((logo) => ({ image_url: logo.imageUrl, alt: logo.alt })),\n },\n };\n return omitUndefined(wire);\n}\n\nfunction toWireGroup(group: ProductGroup): WireGroup {\n return omitUndefined({ key: group.key, tier: group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined });\n}\n\nfunction toWireCreditGrant(grant: CreditGrant): WireCreditGrant {\n return omitUndefined({ meter: grant.meter, amount: grant.amount, renewal: grant.renewal, expires_after_days: grant.expiresAfterDays });\n}\n\nfunction toWireDelivery(delivery: Delivery): WireDelivery {\n switch (delivery.method) {\n case \"none\":\n return { method: \"none\" };\n case \"redirect\":\n return { method: \"redirect\", url: delivery.url };\n case \"instructions\":\n return { method: \"instructions\", instructions: delivery.instructions };\n }\n}\n\nfunction toWireCheckout(checkout: CheckoutSettings): WireCheckout {\n return omitUndefined({\n layout_mode: checkout.layoutMode,\n payment_style: checkout.paymentStyle,\n provider_mode: checkout.providerMode,\n contact_fields: checkout.contactFields ? omitUndefined({ name: checkout.contactFields.name, phone: checkout.contactFields.phone }) : undefined,\n });\n}\n\nfunction toWireTheme(theme: ProductTheme): WireTheme {\n return omitUndefined({ primary_color: theme.primaryColor, button_radius: theme.buttonRadius, accent_mode: theme.accentMode });\n}\n\nexport function fromWireProduct(wire: WireProduct): Product {\n const product: Product = {\n key: wire.key ?? null,\n id: wire.id,\n slug: wire.slug ?? null,\n url: wire.url ?? null,\n name: wire.name,\n description: wire.description ?? undefined,\n price: { amount: wire.price.amount, currency: wire.price.currency },\n billing: fromWireBilling(wire.billing),\n group: wire.group ? fromWireGroup(wire.group) : undefined,\n credits: wire.credits ? wire.credits.map(fromWireCreditGrant) : undefined,\n delivery: wire.delivery ? (camelizeKeys(wire.delivery) as ProductDelivery) : undefined,\n checkout: wire.checkout ? fromWireCheckout(wire.checkout) : undefined,\n theme: wire.theme ? fromWireTheme(wire.theme) : undefined,\n stripe: wire.stripe ? fromWireStripe(wire.stripe) : undefined,\n active: wire.active,\n buyerEmails: wire.buyer_emails ?? undefined,\n offers: wire.offers,\n tabTitle: wire.tab_title ?? undefined,\n trustBadge: wire.trust_badge\n ? omitUndefined({\n title: wire.trust_badge.title ?? undefined,\n caption: wire.trust_badge.caption ?? undefined,\n logos: wire.trust_badge.logos.map((logo) => ({ imageUrl: logo.image_url, alt: logo.alt })),\n })\n : undefined,\n bumps: wire.bumps ? (camelizeKeys(wire.bumps) as ProductBump[]) : undefined,\n upsell: wire.upsell === undefined ? undefined : wire.upsell && (camelizeKeys(wire.upsell) as ProductBump),\n pixelId: wire.pixel_id,\n archivedAt: wire.archived_at ?? null,\n createdAt: wire.created_at,\n updatedAt: wire.updated_at,\n };\n return omitUndefined(product);\n}\n\nfunction fromWireBilling(billing: WireBilling): Billing {\n return billing.type === \"recurring\" ? { type: \"recurring\", interval: billing.interval } : { type: \"one_time\" };\n}\n\nfunction fromWireGroup(group: WireGroup): ProductGroup {\n const tier: Tier | undefined = group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : undefined;\n return omitUndefined({ key: group.key, tier });\n}\n\nfunction fromWireCreditGrant(grant: WireCreditGrant): CreditGrant {\n return omitUndefined({\n meter: grant.meter,\n amount: grant.amount,\n renewal: grant.renewal,\n expiresAfterDays: grant.expires_after_days ?? undefined,\n });\n}\n\nfunction fromWireCheckout(checkout: WireCheckout): CheckoutSettings {\n return omitUndefined({\n layoutMode: checkout.layout_mode ?? undefined,\n paymentStyle: checkout.payment_style ?? undefined,\n providerMode: checkout.provider_mode ?? undefined,\n contactFields: checkout.contact_fields\n ? omitUndefined({ name: checkout.contact_fields.name ?? undefined, phone: checkout.contact_fields.phone ?? undefined })\n : undefined,\n });\n}\n\nfunction fromWireTheme(theme: NonNullable<WireProduct[\"theme\"]>): NonNullable<Product[\"theme\"]> {\n return omitUndefined({\n primaryColor: theme.primary_color ?? undefined,\n buttonRadius: theme.button_radius ?? undefined,\n accentMode: theme.accent_mode ?? undefined,\n logoStorageId: theme.logo_storage_id,\n logoUrl: theme.logo_url,\n });\n}\n\nfunction fromWireStripe(stripe: WireStripe): StripeSettings {\n return { priceId: stripe.price_id };\n}\n\n/** Strip server-only fields from a fetched product so it can be re-declared in a config file. */\nexport function productToInput(product: Product): ProductInput | null {\n if (!product.key) return null;\n return omitUndefined({\n key: product.key,\n name: product.name,\n description: product.description,\n price: product.price,\n billing: product.billing,\n group: product.group,\n credits: product.credits,\n // File delivery and logos are managed in the dashboard / via the API, never from config.\n delivery: product.delivery?.method === \"file\" ? undefined : product.delivery,\n theme: product.theme\n ? omitUndefined({ primaryColor: product.theme.primaryColor, buttonRadius: product.theme.buttonRadius, accentMode: product.theme.accentMode })\n : undefined,\n slug: product.slug ?? undefined,\n stripe: product.stripe,\n active: product.active,\n // The API always reports buyer_emails; only the opt-out is worth writing into a config.\n buyerEmails: product.buyerEmails === false ? false : undefined,\n offers: product.offers && Object.keys(product.offers).length > 0 ? product.offers : undefined,\n tabTitle: product.tabTitle || undefined,\n trustBadge: product.trustBadge || undefined,\n });\n}\n\nexport function fromWirePlanItem(item: WirePlanItem): PlanItem {\n let error: PlanItem[\"error\"];\n if (typeof item.error === \"string\") error = { code: item.error, message: item.error };\n else if (item.error && typeof item.error === \"object\") {\n error = { code: item.error.code ?? \"error\", message: item.error.message ?? item.error.code ?? \"Unknown error\" };\n }\n return omitUndefined({\n key: item.key,\n action: item.action,\n changes: (item.changes ?? []).map((change) =>\n omitUndefined({ path: change.path, from: change.from, to: change.to, note: change.note ?? undefined }),\n ),\n product: item.product ? fromWireProduct(item.product) : undefined,\n error,\n });\n}\n\nexport function fromWireConfigPushResult(wire: WireConfigPushResult): ConfigPushResult {\n return {\n applied: Boolean(wire.applied),\n summary: {\n create: wire.summary?.create ?? 0,\n update: wire.summary?.update ?? 0,\n unchanged: wire.summary?.unchanged ?? 0,\n archive: wire.summary?.archive ?? 0,\n conflict: wire.summary?.conflict ?? 0,\n error: wire.summary?.error ?? 0,\n },\n results: (wire.results ?? []).map(fromWirePlanItem),\n };\n}\n\nexport function fromWireConfigGetResult(wire: WireConfigGetResult): ConfigGetResult {\n return { products: (wire.products ?? []).map(fromWireProduct), unmanagedCount: wire.unmanaged_count ?? 0 };\n}\n\nexport function fromWireAccount(wire: WireAccount): Account {\n return {\n id: wire.id,\n email: wire.email,\n name: wire.name ?? null,\n stripe: { connected: Boolean(wire.stripe?.connected), chargesEnabled: Boolean(wire.stripe?.charges_enabled) },\n paypal: { connected: Boolean(wire.paypal?.connected) },\n key: { prefix: wire.key?.prefix ?? \"\", name: wire.key?.name ?? null, scopes: wire.key?.scopes ?? [] },\n };\n}\n\nexport function fromWirePage<W, T>(wire: WirePage<W>, map: (item: W) => T): Page<T> {\n return { data: (wire.data ?? []).map(map), nextCursor: wire.next_cursor ?? null };\n}\n\nfunction fromWireCustomerRef(ref: WireCustomerRef | null | undefined): CustomerRef {\n return { email: ref?.email ?? null, externalId: ref?.external_id ?? null };\n}\n\nexport function fromWireCreditBalances(wire: WireCreditBalancesResult): CreditBalancesResult {\n return {\n customer: fromWireCustomerRef(wire.customer),\n balances: (wire.balances ?? []).map((balance) => ({\n meter: balance.meter,\n balance: balance.balance,\n expiresAt: balance.expires_at ?? null,\n lifetimeGranted: balance.lifetime_granted ?? 0,\n lifetimeConsumed: balance.lifetime_consumed ?? 0,\n })),\n };\n}\n\nexport function fromWireCreditConsume(wire: WireCreditConsumeResult): CreditConsumeResult {\n return { meter: wire.meter, balance: wire.balance, consumed: wire.consumed, replayed: Boolean(wire.replayed) };\n}\n\nexport function fromWireCreditAdjust(wire: WireCreditAdjustResult): CreditAdjustResult {\n return { meter: wire.meter, balance: wire.balance };\n}\n\n/** camelCase → snake_case keys, deeply. Values are left untouched. */\nexport function snakeizeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(snakeizeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n out[key.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`)] = snakeizeKeys(entry);\n }\n return out;\n }\n return value;\n}\n\n/** snake_case → camelCase for a single key. */\nexport function camelCaseKey(key: string): string {\n return key.replace(/_([a-z0-9])/g, (_, char: string) => char.toUpperCase());\n}\n\n/** Deeply convert object keys to camelCase. Values are left untouched. */\nexport function camelizeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(camelizeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) out[camelCaseKey(key)] = camelizeKeys(entry);\n return out;\n }\n return value;\n}\n\nexport function fromWireLedgerEntry(wire: WireLedgerEntry): LedgerEntry {\n const entry = camelizeKeys(wire) as Record<string, unknown>;\n return {\n ...entry,\n id: String(entry.id ?? \"\"),\n kind: entry.kind as LedgerEntry[\"kind\"],\n meter: String(entry.meter ?? \"\"),\n amount: Number(entry.amount ?? 0),\n balanceAfter: Number(entry.balanceAfter ?? 0),\n note: (entry.note as string | null | undefined) ?? null,\n createdAt: Number(entry.createdAt ?? 0),\n };\n}\n\nexport function fromWireEntitlement(wire: WireEntitlement): Entitlement {\n const { credits, ...rest } = wire;\n const base = camelizeKeys(rest) as Record<string, unknown>;\n const entitlement: Entitlement = {\n ...(base as Partial<Entitlement>),\n hasAccess: Boolean(base.hasAccess),\n status: String(base.status ?? \"none\"),\n };\n if (credits && typeof credits === \"object\") {\n // Meter names are user-defined keys; keep them verbatim and only camelize the values.\n entitlement.credits = Object.fromEntries(\n Object.entries(credits as Record<string, Record<string, unknown>>).map(([meter, value]) => [\n meter,\n { balance: Number(value?.balance ?? 0), expiresAt: (value?.expires_at as number | null | undefined) ?? null },\n ]),\n );\n }\n return entitlement;\n}\n","import type { Account } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { type WireAccount, camelizeKeys, fromWireAccount } from \"../wire\";\n\n/*\n * account.update, Stripe/PayPal status + connect, billing portal, keys list, support. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\n/** GET/PATCH /account body; superset of `Account` (which `client.account.get()` still returns). */\nexport interface AccountDetails extends Account {\n profile: { givenName: string | null; familyName: string | null };\n checkoutProviders: { stripe: boolean; paypal: boolean };\n plan: { status: \"none\" | \"active\" | \"trialing\" | \"past_due\" | \"canceled\"; active: boolean };\n sandbox: boolean;\n accountKind: \"standard\" | \"platform_merchant\" | \"sandbox\";\n createdAt: number;\n}\n\nexport interface AccountUpdateOptions {\n givenName?: string;\n familyName?: string;\n /** Both `false` is stored as `{ stripe: true, paypal: false }`. */\n checkoutProviders?: { stripe: boolean; paypal: boolean };\n}\n\nexport interface StripeAccount {\n connectionMode: \"connect\" | \"api_key\" | \"platform\";\n chargesEnabled: boolean;\n payoutsEnabled: boolean;\n detailsSubmitted: boolean;\n country: string | null;\n defaultCurrency: string | null;\n publishableKey: string | null;\n displayName: string | null;\n pendingReplacement: boolean;\n updatedAt: number;\n}\n\nexport interface StripeMigration {\n id: string;\n status: \"running\" | \"completed\" | \"failed\" | \"canceled\";\n phase: \"products\" | \"customers\" | \"done\";\n sourceConnectionMode: \"connect\" | \"api_key\" | \"platform\";\n includeCustomers: boolean;\n products: { scanned: number; cloned: number; skipped: number; failed: number };\n customers: { scanned: number; cloned: number; skipped: number; failed: number };\n lastError: string | null;\n startedAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nexport interface StripeStatus {\n state: \"not_connected\" | \"action_required\" | \"pending_verification\" | \"ready\";\n hasAccount: boolean;\n items: { code: string; label: string; severity: \"past_due\" | \"currently_due\" }[];\n errors: { code: string; reason: string; requirement: string; label: string }[];\n disabledReason: string | null;\n account: StripeAccount | null;\n migration: StripeMigration | null;\n}\n\nexport interface StripeRefresh {\n ready: boolean;\n transfersStatus: string;\n payoutsEnabled: boolean;\n disabledReason: string | null;\n}\n\nexport interface StripeOnboardingLinkOptions {\n /** ISO-3166 alpha-2; required when no Stripe account exists yet. */\n country?: string;\n /** Dashboard path starting with `/dashboard/`; anything else falls back to `/dashboard/onboarding`. */\n returnTo?: string;\n}\n\nexport interface StripeConnectApiKeyOptions {\n /** `sk_` or `rk_` key; never echoed back. */\n secretKey: string;\n /** `pk_` key. */\n publishableKey: string;\n migration?: { includeCustomers: boolean };\n}\n\nexport interface StripeBrandingOptions {\n /** Hex color, passed to Stripe as-is. */\n primaryColor?: string;\n /** Must start with `https://`. */\n logoUrl?: string;\n}\n\nexport interface PaypalAccount {\n clientId: string;\n environment: \"live\" | \"sandbox\" | null;\n email: string | null;\n displayName: string | null;\n enabled: boolean;\n connectedAt: number;\n updatedAt: number;\n}\n\nexport interface PaypalStatus {\n state: \"not_connected\" | \"ready\";\n hasAccount: boolean;\n account: PaypalAccount | null;\n}\n\nexport interface PaypalConnectOptions {\n clientId: string;\n /** Never echoed back. */\n secret: string;\n}\n\nexport interface SupportRequestOptions {\n /** ≤160 chars. */\n subject?: string;\n /** 10–5000 chars. */\n message: string;\n /** Replaying the same key and body returns the stored result. */\n idempotencyKey?: string;\n}\n\nexport interface SupportRequestCreated {\n id: string;\n createdAt: number;\n}\n\nexport type WireAccountDetails = Record<string, unknown>;\nexport type WireStripeStatus = Record<string, unknown>;\nexport type WirePaypalStatus = Record<string, unknown>;\n\n// fromWireAccount supplies the `null` defaults for the base fields; the rest is a straight camelize.\nexport const fromWireAccountDetails = (wire: WireAccountDetails) =>\n ({ ...(camelizeKeys(wire) as object), ...fromWireAccount(wire as unknown as WireAccount) }) as AccountDetails;\nconst fromWireStripeStatus = (wire: WireStripeStatus) => camelizeKeys(wire) as StripeStatus;\nconst fromWirePaypalStatus = (wire: WirePaypalStatus) => camelizeKeys(wire) as PaypalStatus;\n\nexport function accountApi(client: PurpleturretClient) {\n return {\n /** An empty patch is a no-op that returns the current account. */\n update: async (patch: AccountUpdateOptions): Promise<AccountDetails> =>\n fromWireAccountDetails(\n await client.request<WireAccountDetails>(\"PATCH\", \"/account\", {\n body: { given_name: patch.givenName, family_name: patch.familyName, checkout_providers: patch.checkoutProviders },\n }),\n ),\n stripeStatus: async (): Promise<StripeStatus> => fromWireStripeStatus(await client.request<WireStripeStatus>(\"GET\", \"/account/stripe\")),\n stripeOnboardingLink: async (options: StripeOnboardingLinkOptions = {}): Promise<{ url: string }> =>\n client.request(\"POST\", \"/account/stripe/onboarding-link\", { body: { country: options.country, return_to: options.returnTo } }),\n /** Re-reads capabilities from Stripe; 404 when no Stripe account. */\n stripeRefresh: async (): Promise<StripeRefresh> => camelizeKeys(await client.request(\"POST\", \"/account/stripe/refresh\")) as StripeRefresh,\n /** Sandbox accounts accept test-mode keys only. */\n stripeConnectApiKey: async (options: StripeConnectApiKeyOptions): Promise<StripeStatus> =>\n fromWireStripeStatus(\n await client.request<WireStripeStatus>(\"POST\", \"/account/stripe/connect-api-key\", {\n body: {\n secret_key: options.secretKey,\n publishable_key: options.publishableKey,\n migration: options.migration ? { include_customers: options.migration.includeCustomers } : undefined,\n },\n }),\n ),\n /** `applied: false` for api_key / platform accounts (branding lives in their own Stripe dashboard). */\n stripeBranding: async (options: StripeBrandingOptions = {}): Promise<{ applied: boolean }> =>\n client.request(\"PUT\", \"/account/stripe/branding\", { body: { primary_color: options.primaryColor, logo_url: options.logoUrl } }),\n paypalStatus: async (): Promise<PaypalStatus> => fromWirePaypalStatus(await client.request<WirePaypalStatus>(\"GET\", \"/account/paypal\")),\n paypalConnect: async (options: PaypalConnectOptions): Promise<PaypalStatus> =>\n fromWirePaypalStatus(\n await client.request<WirePaypalStatus>(\"POST\", \"/account/paypal/connect\", { body: { client_id: options.clientId, secret: options.secret } }),\n ),\n paypalDisconnect: async (): Promise<PaypalStatus> => fromWirePaypalStatus(await client.request<WirePaypalStatus>(\"DELETE\", \"/account/paypal\")),\n /** Purpleturret's own plan portal (not the seller's connected account); 422 before any plan purchase. */\n billingPortal: async (): Promise<{ url: string }> => client.request(\"POST\", \"/account/billing-portal\"),\n };\n}\n\nexport function supportApi(client: PurpleturretClient) {\n return {\n /** Filed under the account's email and name. */\n create: async (options: SupportRequestOptions): Promise<SupportRequestCreated> =>\n camelizeKeys(\n await client.request(\"POST\", \"/support\", {\n body: { subject: options.subject, message: options.message },\n idempotencyKey: options.idempotencyKey,\n }),\n ) as SupportRequestCreated,\n };\n}\n","import type { Page } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * orders, subscriptions, customers, leads. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport type OrderStatus = \"pending\" | \"paid\" | \"failed\" | \"refunded\" | \"partially_refunded\";\nexport type OrderKind = \"one_time\" | \"subscription_initial\" | \"subscription_renewal\";\nexport type PaymentProvider = \"stripe\" | \"paypal\";\nexport type RefundReason = \"requested_by_customer\" | \"duplicate\" | \"fraudulent\" | \"other\";\nexport type RefundScope = \"main\" | \"upsell\" | \"all\";\nexport type SubscriptionStatus = \"incomplete\" | \"incomplete_expired\" | \"trialing\" | \"active\" | \"past_due\" | \"canceled\" | \"unpaid\" | \"paused\";\n\nexport interface OrderCustomer {\n email: string | null;\n name: string | null;\n phone: string | null;\n externalId: string | null;\n}\n\nexport interface OrderLineItem {\n productId: string;\n role: \"main\" | \"bump\" | \"upsell\";\n amount: number;\n name: string | null;\n}\n\nexport interface OrderRefund {\n amount: number | null;\n refundedAt: number;\n reason: RefundReason | null;\n customReason: string | null;\n}\n\nexport interface Order {\n id: string;\n status: OrderStatus;\n provider: PaymentProvider;\n kind: OrderKind;\n productId: string;\n customer: OrderCustomer;\n /** Main charge total in minor units (bumps included, upsell excluded). */\n amount: number;\n currency: string;\n lineItems: OrderLineItem[];\n refund: OrderRefund | null;\n upsell: { decision: \"pending\" | \"accepted\" | \"declined\" | \"expired\"; decidedAt: number | null; refund: OrderRefund | null } | null;\n stripe: { paymentIntentId: string | null; invoiceId: string | null; subscriptionId: string | null } | null;\n paypal: { orderId: string | null; captureId: string | null; subscriptionId: string | null } | null;\n failureReason: string | null;\n createdAt: number;\n}\n\nexport interface OrderListOptions {\n /** Case-insensitive exact match. */\n email?: string;\n status?: OrderStatus;\n cursor?: string;\n limit?: number;\n}\n\nexport interface OrderRefundOptions {\n /** Default `all`. */\n scope?: RefundScope;\n reason: RefundReason;\n /** Stored only when `reason` is `other`; max 500 chars. */\n customReason?: string;\n /** Sent as `Idempotency-Key`; generated when absent. */\n idempotencyKey?: string;\n}\n\nexport interface OrderRefundResult {\n refundedMain: boolean;\n refundedUpsell: boolean;\n order: Order;\n}\n\nexport interface Subscription {\n id: string;\n status: SubscriptionStatus;\n provider: PaymentProvider;\n productId: string;\n customer: OrderCustomer & { email: string };\n amount: number;\n currency: string;\n interval: \"month\" | \"year\";\n cancelAtPeriodEnd: boolean;\n currentPeriodStart: number | null;\n currentPeriodEnd: number | null;\n stripeSubscriptionId: string | null;\n paypalSubscriptionId: string | null;\n createdAt: number;\n updatedAt: number;\n endedAt: number | null;\n}\n\nexport interface SubscriptionListOptions {\n email?: string;\n /** `canceled` is the churned view. */\n status?: SubscriptionStatus;\n /** Product id (not the config key). Ignored when `email` is given. */\n product?: string;\n cursor?: string;\n limit?: number;\n}\n\nexport interface PortalLink {\n url: string;\n /** Links are valid for 7 days. */\n expiresAt: number;\n}\n\nexport interface Customer {\n email: string;\n name: string | null;\n phone: string | null;\n externalId: string | null;\n stripeCustomerId: string;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface CustomerCredit {\n meter: string;\n balance: number;\n expiresAt: number | null;\n lifetimeGranted: number;\n lifetimeConsumed: number;\n}\n\nexport interface CustomerDetail extends Omit<Customer, \"stripeCustomerId\" | \"createdAt\" | \"updatedAt\"> {\n stripeCustomerId: string | null;\n createdAt: number | null;\n updatedAt: number | null;\n /** Newest 100. */\n orders: Order[];\n /** Newest 100. */\n subscriptions: Subscription[];\n credits: CustomerCredit[];\n /** One entry per currency over paid orders. */\n lifetimeSpend: { currency: string; amount: number }[];\n}\n\nexport interface CustomerListOptions {\n cursor?: string;\n limit?: number;\n}\n\nexport interface CheckoutLead {\n id: string;\n email: string | null;\n name: string | null;\n phone: string | null;\n externalId: string | null;\n productId: string;\n status: \"active\" | \"payment_started\" | \"completed\";\n amount: number;\n currency: string;\n createdAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nexport interface CheckoutLeadListOptions {\n /** Only leads not completed and untouched for 30+ minutes. */\n abandoned?: boolean;\n /** Window for `abandoned`, 1–180 (default 30). */\n lookbackDays?: number;\n}\n\nexport interface PageLead {\n id: string;\n email: string;\n name: string | null;\n /** `page:<slug>`. */\n source: string;\n firstPageId: string;\n lastPageId: string;\n submissionCount: number;\n createdAt: number;\n updatedAt: number;\n}\n\nexport type WireOrder = Record<string, unknown>;\nexport type WireSubscription = Record<string, unknown>;\nexport type WireCustomer = Record<string, unknown>;\nexport type WireLead = Record<string, unknown>;\n\nexport const fromWireOrder = (wire: WireOrder): Order => camelizeKeys(wire) as Order;\nexport const fromWireSubscription = (wire: WireSubscription): Subscription => camelizeKeys(wire) as Subscription;\n\nexport function ordersApi(client: PurpleturretClient) {\n const path = (id: string) => `/orders/${encodeURIComponent(id)}`;\n return {\n list: async (options: OrderListOptions = {}): Promise<Page<Order>> =>\n fromWirePage(\n await client.request<WirePage<WireOrder>>(\"GET\", \"/orders\", {\n query: { email: options.email, status: options.status, cursor: options.cursor, limit: options.limit },\n }),\n fromWireOrder,\n ),\n get: async (id: string): Promise<Order> => fromWireOrder(await client.request<WireOrder>(\"GET\", path(id))),\n /** Refunds the main and/or upsell charge through the payment provider; cannot be undone. */\n refund: async (id: string, options: OrderRefundOptions): Promise<OrderRefundResult> =>\n camelizeKeys(\n await client.request<Record<string, unknown>>(\"POST\", `${path(id)}/refund`, {\n body: { scope: options.scope, reason: options.reason, custom_reason: options.customReason },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ) as OrderRefundResult,\n };\n}\n\nexport function subscriptionsApi(client: PurpleturretClient) {\n const path = (id: string) => `/subscriptions/${encodeURIComponent(id)}`;\n return {\n list: async (options: SubscriptionListOptions = {}): Promise<Page<Subscription>> =>\n fromWirePage(\n await client.request<WirePage<WireSubscription>>(\"GET\", \"/subscriptions\", {\n query: { email: options.email, status: options.status, product: options.product, cursor: options.cursor, limit: options.limit },\n }),\n fromWireSubscription,\n ),\n get: async (id: string): Promise<Subscription> => fromWireSubscription(await client.request<WireSubscription>(\"GET\", path(id))),\n /** Creates a fresh 7-day billing portal link on every call. */\n portalLink: async (id: string): Promise<PortalLink> =>\n camelizeKeys(await client.request<Record<string, unknown>>(\"POST\", `${path(id)}/portal-link`)) as PortalLink,\n /** E-mails the buyer a fresh portal link. */\n portalEmail: async (id: string): Promise<{ sent: true }> => client.request<{ sent: true }>(\"POST\", `${path(id)}/portal-email`),\n };\n}\n\nexport function customersApi(client: PurpleturretClient) {\n return {\n /** Ordered by email ascending, one row per email. */\n list: async (options: CustomerListOptions = {}): Promise<Page<Customer>> =>\n fromWirePage(\n await client.request<WirePage<WireCustomer>>(\"GET\", \"/customers\", { query: { cursor: options.cursor, limit: options.limit } }),\n (wire) => camelizeKeys(wire) as Customer,\n ),\n /** `emailOrExternalId`: an e-mail address (contains `@`) or the seller's own external id. */\n get: async (emailOrExternalId: string): Promise<CustomerDetail> =>\n camelizeKeys(await client.request<WireCustomer>(\"GET\", `/customers/${encodeURIComponent(emailOrExternalId)}`)) as CustomerDetail,\n };\n}\n\nexport function leadsApi(client: PurpleturretClient) {\n return {\n /** Not paginated: newest first, at most 2000 rows (200 when `abandoned`). */\n checkout: async (options: CheckoutLeadListOptions = {}): Promise<Page<CheckoutLead>> =>\n fromWirePage(\n await client.request<WirePage<WireLead>>(\"GET\", \"/leads/checkout\", {\n query: { abandoned: options.abandoned ? \"true\" : undefined, lookback_days: options.lookbackDays },\n }),\n (wire) => camelizeKeys(wire) as CheckoutLead,\n ),\n /** Not paginated: newest first, at most 1000 rows. */\n pages: async (): Promise<Page<PageLead>> =>\n fromWirePage(await client.request<WirePage<WireLead>>(\"GET\", \"/leads/pages\"), (wire) => camelizeKeys(wire) as PageLead),\n };\n}\n","import type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\nimport type { Page } from \"../../types\";\n\n/*\n * pixels + analytics. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport interface PixelFunnelDef {\n key: string;\n label: string;\n /** An event name or a `/path` prefix. */\n steps: string[];\n}\n\nexport interface Pixel {\n id: string;\n /** Public snippet key `pt_px_…` (not a secret). */\n key: string;\n name: string;\n /** null = any origin. */\n allowedHosts: string[] | null;\n declaredEvents: string[] | null;\n funnels: PixelFunnelDef[] | null;\n /** Also runs on the seller's Purpleturret checkout pages. */\n checkout: boolean;\n archivedAt: number | null;\n createdAt: number;\n}\n\nexport interface PixelAttachment {\n pixelId: string | null;\n productId: string | null;\n pageId: string | null;\n}\n\nexport interface PixelKpis {\n visitors: number;\n sessions: number;\n pageviews: number;\n avgDurationMs: number;\n /** 0..1 share of sessions with at most one pageview. */\n bounceRate: number;\n}\n\nexport interface PixelSourceRow {\n source: string;\n medium: string;\n campaign: string;\n sessions: number;\n visitors: number;\n}\nexport interface PixelPathRow {\n path: string;\n sessions: number;\n visitors: number;\n}\n/** For regions and cities `name` is `\"<Region or City>|<ISO country>\"`. */\nexport interface PixelNamedRow {\n name: string;\n sessions: number;\n visitors: number;\n}\n\nexport interface PixelSessionRow {\n sid: string;\n visitorId: string;\n startedAt: number;\n lastAt: number;\n pageviews: number;\n entryPath: string;\n exitPath: string | null;\n source: { source: string; medium: string; campaign: string };\n externalId: string | null;\n email: string | null;\n name: string | null;\n phone: string | null;\n device: string | null;\n os: string | null;\n browser: string | null;\n screen: string | null;\n country: string | null;\n region: string | null;\n city: string | null;\n spent: number;\n currency: string | null;\n purchasedAt: number | null;\n}\n\nexport interface PixelOverview {\n start: number;\n end: number;\n truncated: boolean;\n kpis: PixelKpis;\n /** Only with `compare: true`. */\n prior: PixelKpis | null;\n /** Empty without `bucket`; oldest first, last bucket ends at `end`. */\n series: PixelKpis[];\n online: number;\n entryPages: PixelPathRow[];\n exitPages: PixelPathRow[];\n devices: PixelNamedRow[];\n os: PixelNamedRow[];\n browsers: PixelNamedRow[];\n countries: PixelNamedRow[];\n regions: PixelNamedRow[];\n cities: PixelNamedRow[];\n sessionSources: PixelSourceRow[];\n visitorSources: PixelSourceRow[];\n referrers: { host: string; sessions: number; visitors: number }[];\n recent: PixelSessionRow[];\n}\n\nexport interface PixelTopPages {\n start: number;\n end: number;\n truncated: boolean;\n pages: { path: string; views: number; visitors: number; avgDurationMs: number | null }[];\n}\n\nexport interface PixelFunnels {\n start: number;\n end: number;\n funnels: { key: string; label: string; steps: { match: string; sessions: number }[] }[];\n}\n\nexport interface PixelAdRow {\n source: string;\n medium: string;\n campaign: string;\n content: string;\n term: string;\n sessions: number;\n visitors: number;\n conversions: number;\n converters: number;\n revenue: number;\n}\n\nexport interface PixelAdPerformance {\n start: number;\n end: number;\n truncated: boolean;\n rows: PixelAdRow[];\n campaigns: (PixelAdRow & { spend: number })[];\n currency: string | null;\n conversions: number;\n other: { sessions: number; conversions: number; revenue: number };\n unattributed: number;\n candidates: string[];\n}\n\nexport interface PixelPerson {\n id: string;\n externalId: string | null;\n email: string | null;\n name: string | null;\n phone: string | null;\n visitors: number;\n firstSeen: number;\n lastSeen: number;\n sessions: number;\n pageviews: number;\n spent: number;\n currency: string | null;\n purchasedAt: number | null;\n durationMs: number;\n country: string | null;\n region: string | null;\n city: string | null;\n device: string | null;\n os: string | null;\n browser: string | null;\n screen: string | null;\n firstTouch: { source: string; medium: string; campaign: string };\n recent: PixelSessionRow[];\n}\n\nexport interface PixelPeople {\n start: number;\n end: number;\n truncated: boolean;\n /** Everyone in the range, across all pages. */\n total: number;\n /** How many of `total` have bought. */\n customers: number;\n people: PixelPerson[];\n}\n\nexport interface PixelTimelineEvent {\n /** `pageview` | `click` | `scroll` | `form` | a custom event. */\n name: string;\n ts: number;\n path: string;\n duration: number | null;\n /** Prop keys are kept verbatim (not camelized). */\n props: Record<string, string | number | boolean> | null;\n}\n\nexport interface PixelSessionTimeline {\n sid: string;\n events: PixelTimelineEvent[];\n}\n\nexport interface PixelPersonTimeline {\n sids: string[];\n events: (PixelTimelineEvent & { sid: string })[];\n}\n\nexport interface PixelAdSpend {\n source: string;\n campaign: string;\n start: number;\n end: number;\n spend: number;\n}\n\nexport interface PixelCreateInput {\n name: string;\n /** Registrable hosts allowed to send events; omit for any origin. */\n allowedHosts?: string[];\n /** Defaults to a random UUID. */\n idempotencyKey?: string;\n}\n\nexport interface PixelPatch {\n name?: string;\n allowedHosts?: string[];\n archived?: boolean;\n /** true makes this the seller's checkout pixel. */\n checkout?: boolean;\n}\n\nexport interface PixelTarget {\n productId?: string;\n pageId?: string;\n}\n\n/** `start`/`end` as epoch ms or ISO 8601; default last 7 days, max 90. */\nexport interface PixelRangeOptions {\n start?: number | string;\n end?: number | string;\n /** Adds a time series to the overview. */\n bucket?: \"hour\" | \"day\";\n /** Adds `prior` KPIs to the overview. */\n compare?: boolean;\n}\n\nexport interface PixelPeopleOptions extends PixelRangeOptions {\n /** People to skip, most recently seen first (default 0). */\n offset?: number;\n /** Page size, 1 to 100 (default 100). */\n limit?: number;\n}\n\nexport interface PixelAdPerformanceOptions extends PixelRangeOptions {\n /** A custom event name (e.g. `purchase`) or a `/path` prefix. */\n conversion: string;\n attribution?: \"first\" | \"last\";\n}\n\nexport interface PixelPersonOptions {\n /** Extra session ids to merge into the timeline (max 20 in total). */\n sids?: string[];\n}\n\nexport interface PixelAdSpendInput {\n source: string;\n campaign?: string;\n start: number | string;\n end: number | string;\n /** 0 clears the campaign's spend for the range. */\n spend: number;\n idempotencyKey?: string;\n}\n\n/*\n * Wire shapes.\n */\n\nexport interface WirePixel {\n id: string;\n key: string;\n name: string;\n allowed_hosts: string[] | null;\n declared_events: string[] | null;\n funnels: PixelFunnelDef[] | null;\n checkout: boolean;\n archived_at: number | null;\n created_at: number;\n}\n\nexport interface WirePixelAttachment {\n pixel_id: string | null;\n product_id: string | null;\n page_id: string | null;\n}\n\ntype WireTimeline = { events: Record<string, unknown>[]; [key: string]: unknown };\n\nexport const fromWirePixel = (wire: WirePixel): Pixel => camelizeKeys(wire) as Pixel;\n\n/** Event prop keys are seller-defined; keep them verbatim. */\nfunction fromWireTimeline<T>(wire: WireTimeline): T {\n const events = (wire.events ?? []).map((event) => ({ ...(camelizeKeys(event) as object), props: event.props ?? null }));\n return { ...(camelizeKeys({ ...wire, events: [] }) as object), events } as T;\n}\n\nconst rangeQuery = (range: PixelRangeOptions) => ({ start: range.start, end: range.end, bucket: range.bucket, compare: range.compare });\nconst targetBody = (target: PixelTarget) => ({ product_id: target.productId, page_id: target.pageId });\n\nexport function pixelsApi(client: PurpleturretClient) {\n const p = (id: string) => `/pixels/${encodeURIComponent(id)}`;\n return {\n list: async (options: { includeArchived?: boolean } = {}): Promise<Page<Pixel>> =>\n fromWirePage(\n await client.request<WirePage<WirePixel>>(\"GET\", \"/pixels\", { query: { include_archived: options.includeArchived } }),\n fromWirePixel,\n ),\n get: async (id: string): Promise<Pixel> => fromWirePixel(await client.request<WirePixel>(\"GET\", p(id))),\n create: async (input: PixelCreateInput): Promise<Pixel> =>\n fromWirePixel(\n await client.request<WirePixel>(\"POST\", \"/pixels\", {\n body: { name: input.name, allowed_hosts: input.allowedHosts },\n idempotencyKey: input.idempotencyKey ?? globalThis.crypto.randomUUID(),\n }),\n ),\n update: async (id: string, patch: PixelPatch): Promise<Pixel> =>\n fromWirePixel(\n await client.request<WirePixel>(\"PATCH\", p(id), {\n body: { name: patch.name, allowed_hosts: patch.allowedHosts, archived: patch.archived, checkout: patch.checkout },\n }),\n ),\n /** Archives the pixel (same as `update(id, { archived: true })`). */\n archive: async (id: string): Promise<Pixel> => fromWirePixel(await client.request<WirePixel>(\"PATCH\", p(id), { body: { archived: true } })),\n /** Exactly one of `productId` / `pageId`. */\n attach: async (id: string, target: PixelTarget): Promise<PixelAttachment> =>\n camelizeKeys(await client.request<WirePixelAttachment>(\"POST\", `${p(id)}/attach`, { body: targetBody(target) })) as PixelAttachment,\n /** Exactly one of `productId` / `pageId`. */\n detach: async (target: PixelTarget): Promise<PixelAttachment> =>\n camelizeKeys(await client.request<WirePixelAttachment>(\"DELETE\", \"/pixels/attachments\", { body: targetBody(target) })) as PixelAttachment,\n overview: async (id: string, range: PixelRangeOptions = {}): Promise<PixelOverview> =>\n camelizeKeys(await client.request(\"GET\", `${p(id)}/overview`, { query: rangeQuery(range) })) as PixelOverview,\n topPages: async (id: string, range: PixelRangeOptions = {}): Promise<PixelTopPages> =>\n camelizeKeys(await client.request(\"GET\", `${p(id)}/top-pages`, { query: rangeQuery(range) })) as PixelTopPages,\n funnels: async (id: string, range: PixelRangeOptions = {}): Promise<PixelFunnels> =>\n camelizeKeys(await client.request(\"GET\", `${p(id)}/funnels`, { query: rangeQuery(range) })) as PixelFunnels,\n adPerformance: async (id: string, options: PixelAdPerformanceOptions): Promise<PixelAdPerformance> =>\n camelizeKeys(\n await client.request(\"GET\", `${p(id)}/ad-performance`, {\n query: { ...rangeQuery(options), conversion: options.conversion, attribution: options.attribution },\n }),\n ) as PixelAdPerformance,\n people: async (id: string, options: PixelPeopleOptions = {}): Promise<PixelPeople> =>\n camelizeKeys(\n await client.request(\"GET\", `${p(id)}/people`, { query: { ...rangeQuery(options), offset: options.offset, limit: options.limit } }),\n ) as PixelPeople,\n session: async (id: string, sid: string): Promise<PixelSessionTimeline> =>\n fromWireTimeline(await client.request<WireTimeline>(\"GET\", `${p(id)}/sessions/${encodeURIComponent(sid)}`)),\n person: async (id: string, sid: string, options: PixelPersonOptions = {}): Promise<PixelPersonTimeline> =>\n fromWireTimeline(\n await client.request<WireTimeline>(\"GET\", `${p(id)}/people/${encodeURIComponent(sid)}`, { query: { sids: options.sids?.join(\",\") } }),\n ),\n setAdSpend: async (id: string, input: PixelAdSpendInput): Promise<PixelAdSpend> =>\n camelizeKeys(\n await client.request(\"PUT\", `${p(id)}/ad-spend`, {\n body: { source: input.source, campaign: input.campaign, start: input.start, end: input.end, spend: input.spend },\n idempotencyKey: input.idempotencyKey,\n }),\n ) as PixelAdSpend,\n };\n}\n","import type { Page } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * hosted pages. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport interface HostedPage {\n id: string;\n slug: string;\n url: string;\n title: string;\n published: boolean;\n disabled: boolean;\n disabledReason: string | null;\n fileCount: number;\n totalBytes: number;\n linkedProductIds: string[];\n pixelId: string | null;\n submissionCount: number;\n notifyOnSubmission: boolean;\n addToLeads: boolean;\n spaFallback: boolean;\n customDomain: { hostname: string; status: \"pending\" | \"active\" | \"error\" | null } | null;\n lastDeployedAt: number | null;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface PageFileInput {\n /** Site-relative path (`index.html`, `assets/app.js`). */\n path: string;\n /** Convex storage id returned by `client.uploads.put`. */\n storageId: string;\n size: number;\n}\n\nexport interface PageFile {\n path: string;\n size: number;\n contentType: string;\n}\n\nexport interface PageSlugAvailability {\n slug: string;\n available: boolean;\n reason: string | null;\n}\n\nexport interface PageCreateOptions {\n title: string;\n slug: string;\n files: PageFileInput[];\n pixelId?: string;\n /** Defaults to a random UUID. */\n idempotencyKey?: string;\n}\n\nexport interface PageUpdateOptions {\n title?: string;\n slug?: string;\n published?: boolean;\n /** Seller's own products; first 5 kept, `[]` clears. */\n linkedProductIds?: string[];\n notifyOnSubmission?: boolean;\n addToLeads?: boolean;\n}\n\nexport interface PageDeleteResult {\n /** `true` when the page had submissions and was archived instead of hard-deleted. */\n archived: boolean;\n page: HostedPage;\n}\n\nexport interface PageFormSubmission {\n id: string;\n pageId: string;\n fields: { name: string; value: string }[];\n submitterEmail: string | null;\n referrer: string | null;\n createdAt: number;\n}\n\nexport interface PageVisitSummary {\n start: number;\n end: number;\n visits: number;\n visitors: number;\n days: { day: string; visits: number; visitors: number }[];\n}\n\nexport interface PageClickSummary {\n start: number;\n end: number;\n clicks: number;\n visitors: number;\n days: { day: string; clicks: number }[];\n topTargets: { elementKey: string; label: string; pathname: string; clicks: number; visitors: number }[];\n}\n\nexport interface PageRangeOptions {\n /** Epoch ms or ISO 8601; default 7 days ago. */\n start?: string | number;\n /** Epoch ms or ISO 8601; default now. Range capped at 90 days. */\n end?: string | number;\n}\n\nexport type WireHostedPage = Record<string, unknown>;\nexport type WirePageFile = Record<string, unknown>;\nexport type WirePageFormSubmission = Record<string, unknown>;\n\nconst toWireFiles = (files: PageFileInput[]) => files.map((f) => ({ path: f.path, storage_id: f.storageId, size: f.size }));\nconst fromWireHostedPage = (wire: WireHostedPage) => camelizeKeys(wire) as HostedPage;\nconst fromWirePageFile = (wire: WirePageFile) => camelizeKeys(wire) as PageFile;\nconst fromWireSubmission = (wire: WirePageFormSubmission) => camelizeKeys(wire) as PageFormSubmission;\nconst CONTENT_TYPES: Record<string, string> = {\n html: \"text/html\",\n css: \"text/css\",\n js: \"text/javascript\",\n json: \"application/json\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n svg: \"image/svg+xml\",\n webp: \"image/webp\",\n ico: \"image/x-icon\",\n txt: \"text/plain\",\n woff2: \"font/woff2\",\n};\n\n/** Content type for a site file by extension; `application/octet-stream` when unknown. */\nexport const contentTypeFor = (path: string): string => CONTENT_TYPES[path.split(\".\").pop()?.toLowerCase() ?? \"\"] ?? \"application/octet-stream\";\nconst pagePath = (id: string, suffix = \"\") => `/pages/${encodeURIComponent(id)}${suffix}`;\n\nexport function pagesApi(client: PurpleturretClient) {\n return {\n /** Live, seller-managed pages, newest first (not paginated). */\n list: async (): Promise<Page<HostedPage>> => fromWirePage(await client.request<WirePage<WireHostedPage>>(\"GET\", \"/pages\"), fromWireHostedPage),\n get: async (id: string): Promise<HostedPage> => fromWireHostedPage(await client.request<WireHostedPage>(\"GET\", pagePath(id))),\n files: async (id: string): Promise<Page<PageFile>> =>\n fromWirePage(await client.request<WirePage<WirePageFile>>(\"GET\", pagePath(id, \"/files\")), fromWirePageFile),\n slugAvailable: async (slug: string, options: { exclude?: string } = {}): Promise<PageSlugAvailability> =>\n camelizeKeys(\n await client.request(\"GET\", \"/pages/slug-available\", { query: { slug, exclude_page_id: options.exclude } }),\n ) as PageSlugAvailability,\n /** Files must already be uploaded (`client.uploads.put`) and include a root `index.html`. */\n create: async (options: PageCreateOptions): Promise<HostedPage> =>\n fromWireHostedPage(\n await client.request<WireHostedPage>(\"POST\", \"/pages\", {\n body: { title: options.title, slug: options.slug, files: toWireFiles(options.files), pixel_id: options.pixelId },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ),\n /** Replaces the whole file set; old blobs are deleted. */\n replaceFiles: async (id: string, files: PageFileInput[]): Promise<HostedPage & { files: PageFile[] }> =>\n camelizeKeys(await client.request(\"PUT\", pagePath(id, \"/files\"), { body: { files: toWireFiles(files) } })) as HostedPage & {\n files: PageFile[];\n },\n update: async (id: string, patch: PageUpdateOptions): Promise<HostedPage> =>\n fromWireHostedPage(\n await client.request<WireHostedPage>(\"PATCH\", pagePath(id), {\n body: {\n title: patch.title,\n slug: patch.slug,\n published: patch.published,\n linked_product_ids: patch.linkedProductIds,\n notify_on_submission: patch.notifyOnSubmission,\n add_to_leads: patch.addToLeads,\n },\n }),\n ),\n /** Archives instead of deleting when the page has form submissions. */\n delete: async (id: string): Promise<PageDeleteResult> => {\n const wire = await client.request<{ archived: boolean; page: WireHostedPage }>(\"DELETE\", pagePath(id));\n return { archived: Boolean(wire.archived), page: fromWireHostedPage(wire.page) };\n },\n submissions: async (id: string, options: { cursor?: string; limit?: number } = {}): Promise<Page<PageFormSubmission>> =>\n fromWirePage(\n await client.request<WirePage<WirePageFormSubmission>>(\"GET\", pagePath(id, \"/submissions\"), {\n query: { cursor: options.cursor, limit: options.limit },\n }),\n fromWireSubmission,\n ),\n visits: async (id: string, options: PageRangeOptions = {}): Promise<PageVisitSummary> =>\n camelizeKeys(await client.request(\"GET\", pagePath(id, \"/visits\"), { query: { start: options.start, end: options.end } })) as PageVisitSummary,\n clicks: async (id: string, options: PageRangeOptions = {}): Promise<PageClickSummary> =>\n camelizeKeys(await client.request(\"GET\", pagePath(id, \"/clicks\"), { query: { start: options.start, end: options.end } })) as PageClickSummary,\n };\n}\n","import type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys } from \"../wire\";\n\n/*\n * Tracking: account-level Meta pixel / Conversions API + Google Analytics defaults, with per-product and per-page overrides.\n * The Conversions API token is write-only: send it in `conversionsApiToken`, read presence via `hasConversionsApiToken`.\n */\n\nexport type TrackingMode = \"inherit\" | \"custom\" | \"disabled\";\nexport type TrackingEventsMode = \"inherit\" | \"custom\";\n\nexport interface MetaEvents {\n viewContent: boolean;\n initiateCheckout: boolean;\n purchase: boolean;\n}\n\nexport interface GaEvents {\n viewItem: boolean;\n beginCheckout: boolean;\n purchase: boolean;\n}\n\nexport interface AccountTracking {\n meta: { enabled: boolean; pixelId: string | null; hasConversionsApiToken: boolean; events: MetaEvents };\n googleAnalytics: { enabled: boolean; measurementId: string | null; events: GaEvents };\n}\n\nexport interface AccountTrackingInput {\n /** Omit to leave Meta untouched; `enabled: false` deletes the account pixel and its token. */\n meta?: { enabled: boolean; pixelId?: string; conversionsApiToken?: string | null; events?: Partial<MetaEvents> };\n googleAnalytics?: { enabled: boolean; measurementId?: string; events?: Partial<GaEvents> };\n}\n\nexport interface ProductTracking {\n meta: {\n mode: TrackingMode;\n pixelId: string | null;\n hasConversionsApiToken: boolean;\n eventsMode: TrackingEventsMode;\n events: MetaEvents;\n inherited: { enabled: boolean; pixelId: string | null; hasConversionsApiToken: boolean; events: MetaEvents };\n };\n googleAnalytics: {\n mode: TrackingMode;\n measurementId: string | null;\n eventsMode: TrackingEventsMode;\n events: GaEvents;\n inherited: { enabled: boolean; measurementId: string | null; events: GaEvents };\n };\n}\n\nexport interface ProductTrackingInput {\n meta?: {\n mode: TrackingMode;\n pixelId?: string;\n /** Omit/null keeps the stored token, \"\" clears it; only stored when `mode` is \"custom\". */\n conversionsApiToken?: string | null;\n eventsMode?: TrackingEventsMode;\n events?: Partial<MetaEvents>;\n };\n googleAnalytics?: { mode: TrackingMode; measurementId?: string; eventsMode?: TrackingEventsMode; events?: Partial<GaEvents> };\n}\n\nexport interface PageTracking {\n meta: {\n mode: TrackingMode;\n pixelId: string | null;\n hasConversionsApiToken: boolean;\n events: { lead: boolean };\n /** A different pixel for URLs under a path prefix; the longest matching prefix wins. */\n paths: { path: string; pixelId: string; hasConversionsApiToken: boolean }[];\n inherited: { enabled: boolean; pixelId: string | null; hasConversionsApiToken: boolean };\n };\n googleAnalytics: {\n mode: TrackingMode;\n measurementId: string | null;\n events: { generateLead: boolean };\n inherited: { enabled: boolean; measurementId: string | null };\n };\n}\n\nexport interface PageTrackingInput {\n meta?: {\n mode: TrackingMode;\n pixelId?: string;\n conversionsApiToken?: string | null;\n events?: { lead?: boolean };\n /** Omit to keep the stored path overrides; `[]` clears them. An omitted token keeps the one stored for that path. */\n paths?: { path: string; pixelId: string; conversionsApiToken?: string }[];\n };\n googleAnalytics?: { mode: TrackingMode; measurementId?: string; events?: { generateLead?: boolean } };\n}\n\n/** camelCase → snake_case keys, deeply. Wire rejects unknown keys, so every input key must round-trip exactly. */\nfunction snakeKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(snakeKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n out[key.replace(/[A-Z]/g, (char) => `_${char.toLowerCase()}`)] = snakeKeys(entry);\n }\n return out;\n }\n return value;\n}\n\nexport function trackingApi(client: PurpleturretClient) {\n return {\n get: async (): Promise<AccountTracking> => camelizeKeys(await client.request(\"GET\", \"/tracking\")) as AccountTracking,\n set: async (input: AccountTrackingInput): Promise<AccountTracking> =>\n camelizeKeys(await client.request(\"PUT\", \"/tracking\", { body: snakeKeys(input) })) as AccountTracking,\n getProduct: async (idOrKey: string): Promise<ProductTracking> =>\n camelizeKeys(await client.request(\"GET\", `/products/${encodeURIComponent(idOrKey)}/tracking`)) as ProductTracking,\n setProduct: async (idOrKey: string, input: ProductTrackingInput): Promise<ProductTracking> =>\n camelizeKeys(await client.request(\"PUT\", `/products/${encodeURIComponent(idOrKey)}/tracking`, { body: snakeKeys(input) })) as ProductTracking,\n getPage: async (id: string): Promise<PageTracking> =>\n camelizeKeys(await client.request(\"GET\", `/pages/${encodeURIComponent(id)}/tracking`)) as PageTracking,\n setPage: async (id: string, input: PageTrackingInput): Promise<PageTracking> =>\n camelizeKeys(await client.request(\"PUT\", `/pages/${encodeURIComponent(id)}/tracking`, { body: snakeKeys(input) })) as PageTracking,\n };\n}\n","import type { Page } from \"../../types\";\nimport type { PurpleturretClient } from \"../client\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * custom domains. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport type DomainStatus = \"pending\" | \"active\" | \"error\";\nexport type DomainRoutingType = \"A\" | \"CNAME\";\n\nexport interface DnsRecord {\n purpose: \"routing\" | \"verification\";\n type: string;\n name: string;\n value: string;\n}\n\nexport interface Domain {\n id: string;\n hostname: string;\n apex: string | null;\n status: DomainStatus;\n routingType: DomainRoutingType | null;\n requestedRoutingType: DomainRoutingType | null;\n verified: boolean;\n dnsConfigured: boolean;\n dnsRecords: DnsRecord[];\n lastError: string | null;\n lastCheckedAt: number | null;\n activatedAt: number | null;\n pageId: string | null;\n productIds: string[];\n defaultProductId: string | null;\n createdAt: number;\n}\n\nexport interface DomainAddOptions {\n hostname: string;\n /** DNS record shape hint; omitted → provider picks (CNAME for subdomains, A for apex). */\n routingType?: DomainRoutingType;\n /** Sent as `Idempotency-Key`; generated when absent. */\n idempotencyKey?: string;\n}\n\nexport interface DomainUpdateOptions {\n /** Page served at `/`; `null` detaches. */\n pageId?: string | null;\n /** Replaces the checkout allowlist (max 50). */\n productIds?: string[];\n /** `/` redirect when no page is attached; `null` clears. */\n defaultProductId?: string | null;\n}\n\nexport type WireDomain = Record<string, unknown>;\n\nexport const fromWireDomain = (wire: WireDomain): Domain => camelizeKeys(wire) as Domain;\n\nexport function domainsApi(client: PurpleturretClient) {\n const path = (id: string) => `/domains/${encodeURIComponent(id)}`;\n return {\n list: async (): Promise<Page<Domain>> => fromWirePage(await client.request<WirePage<WireDomain>>(\"GET\", \"/domains\"), fromWireDomain),\n get: async (id: string): Promise<Domain> => fromWireDomain(await client.request<WireDomain>(\"GET\", path(id))),\n add: async (options: DomainAddOptions): Promise<Domain> =>\n fromWireDomain(\n await client.request<WireDomain>(\"POST\", \"/domains\", {\n body: { hostname: options.hostname, routing_type: options.routingType },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ),\n verify: async (id: string): Promise<Domain> => fromWireDomain(await client.request<WireDomain>(\"POST\", `${path(id)}/verify`)),\n update: async (id: string, options: DomainUpdateOptions): Promise<Domain> =>\n fromWireDomain(\n await client.request<WireDomain>(\"PATCH\", path(id), {\n body: { page_id: options.pageId, product_ids: options.productIds, default_product_id: options.defaultProductId },\n }),\n ),\n remove: async (id: string): Promise<Domain> => fromWireDomain(await client.request<WireDomain>(\"DELETE\", path(id))),\n };\n}\n","import type { PurpleturretClient } from \"../client\";\nimport type { Page } from \"../../types\";\nimport { camelizeKeys, fromWirePage, type WirePage } from \"../wire\";\n\n/*\n * webhook endpoints + integration groups + the read-only API key list. Types, wire shapes and mappers for this area live here; `index.ts` re-exports the file.\n */\n\nexport interface WebhookDelivery {\n status: \"pending\" | \"success\" | \"failed\";\n at: number;\n}\n\nexport interface WebhookEndpoint {\n id: string;\n groupKey: string;\n url: string;\n enabled: boolean;\n description: string | null;\n createdAt: number;\n updatedAt: number;\n lastDelivery: WebhookDelivery | null;\n}\n\n/** Only `webhooks.create` returns `secret`; store it on receipt, it is never returned again. */\nexport interface CreatedWebhookEndpoint extends WebhookEndpoint {\n secret: string;\n}\n\nexport interface WebhookCreateOptions {\n groupKey: string;\n /** HTTPS URL. */\n url: string;\n /** Up to 80 chars. */\n description?: string;\n /** Sent as `Idempotency-Key`; defaults to a random UUID. */\n idempotencyKey?: string;\n}\n\nexport interface WebhookUpdateOptions {\n url?: string;\n enabled?: boolean;\n /** `\"\"` clears it. */\n description?: string;\n}\n\nexport interface WebhookTestResult {\n queued: true;\n deliveryId: string;\n}\n\nexport interface IntegrationGroup {\n id: string;\n key: string;\n name: string;\n createdAt: number;\n updatedAt: number;\n}\n\nexport interface ApiKey {\n id: string;\n prefix: string;\n name: string | null;\n scopes: string[];\n createdAt: number;\n lastUsedAt: number | null;\n revokedAt: number | null;\n}\n\nexport type WireWebhookEndpoint = Record<string, unknown>;\nexport type WireIntegrationGroup = Record<string, unknown>;\nexport type WireApiKey = Record<string, unknown>;\n\nconst fromWireWebhook = (wire: WireWebhookEndpoint) => camelizeKeys(wire) as WebhookEndpoint;\nconst fromWireGroup = (wire: WireIntegrationGroup) => camelizeKeys(wire) as IntegrationGroup;\nconst fromWireApiKey = (wire: WireApiKey) => camelizeKeys(wire) as ApiKey;\n\nexport function webhooksApi(client: PurpleturretClient) {\n const path = (id: string) => `/webhooks/${encodeURIComponent(id)}`;\n return {\n list: async (): Promise<Page<WebhookEndpoint>> =>\n fromWirePage(await client.request<WirePage<WireWebhookEndpoint>>(\"GET\", \"/webhooks\"), fromWireWebhook),\n create: async (options: WebhookCreateOptions): Promise<CreatedWebhookEndpoint> =>\n camelizeKeys(\n await client.request<WireWebhookEndpoint>(\"POST\", \"/webhooks\", {\n body: { group_key: options.groupKey, url: options.url, description: options.description },\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ) as CreatedWebhookEndpoint,\n update: async (id: string, patch: WebhookUpdateOptions): Promise<WebhookEndpoint> =>\n fromWireWebhook(await client.request<WireWebhookEndpoint>(\"PATCH\", path(id), { body: patch })),\n /** Also drops the endpoint's pending deliveries. Returns the deleted row. */\n delete: async (id: string): Promise<WebhookEndpoint> => fromWireWebhook(await client.request<WireWebhookEndpoint>(\"DELETE\", path(id))),\n /** Queues a `test.event` delivery to the endpoint's URL (even when disabled); the HTTP call happens asynchronously. */\n test: async (id: string): Promise<WebhookTestResult> =>\n camelizeKeys(await client.request<Record<string, unknown>>(\"POST\", `${path(id)}/test`)) as WebhookTestResult,\n };\n}\n\nexport function groupsApi(client: PurpleturretClient) {\n const path = (key: string) => `/groups/${encodeURIComponent(key)}`;\n return {\n list: async (): Promise<Page<IntegrationGroup>> =>\n fromWirePage(await client.request<WirePage<WireIntegrationGroup>>(\"GET\", \"/groups\"), fromWireGroup),\n create: async (options: { key: string; name: string }): Promise<IntegrationGroup> =>\n fromWireGroup(await client.request<WireIntegrationGroup>(\"POST\", \"/groups\", { body: options })),\n update: async (key: string, patch: { name: string }): Promise<IntegrationGroup> =>\n fromWireGroup(await client.request<WireIntegrationGroup>(\"PATCH\", path(key), { body: patch })),\n /** Cascades: deletes the group's webhooks, deliveries and events, and clears its products' group/tier. Returns the deleted row. */\n delete: async (key: string): Promise<IntegrationGroup> => fromWireGroup(await client.request<WireIntegrationGroup>(\"DELETE\", path(key))),\n };\n}\n\nexport function keysApi(client: PurpleturretClient) {\n return {\n /** Seller API keys on the account (never the secret hash; hosting keys are not listed). */\n list: async (options: { includeRevoked?: boolean } = {}): Promise<Page<ApiKey>> =>\n fromWirePage(\n await client.request<WirePage<WireApiKey>>(\"GET\", \"/account/keys\", { query: { include_revoked: options.includeRevoked } }),\n fromWireApiKey,\n ),\n };\n}\n","export interface PurpleturretApiErrorInit {\n status: number;\n code: string;\n message: string;\n requestId?: string | null;\n details?: unknown;\n retryAfter?: number | null;\n}\n\n/** A non-2xx response from the Purpleturret API. */\nexport class PurpleturretApiError extends Error {\n override readonly name = \"PurpleturretApiError\";\n readonly status: number;\n readonly code: string;\n readonly requestId: string | null;\n readonly details: unknown;\n /** Seconds to wait before retrying, from `Retry-After` (or `reset_at` on legacy envelopes). */\n readonly retryAfter: number | null;\n\n constructor(init: PurpleturretApiErrorInit) {\n super(init.message);\n this.status = init.status;\n this.code = init.code;\n this.requestId = init.requestId ?? null;\n this.details = init.details;\n this.retryAfter = init.retryAfter ?? null;\n }\n\n /**\n * Build an error from a response body. Accepts the structured envelope\n * `{ error: { code, message, request_id, details } }` as well as the legacy entitlements envelope\n * `{ error: \"code\", ...extra }`.\n */\n static fromResponse(status: number, body: unknown, retryAfterHeader?: string | null): PurpleturretApiError {\n const retryAfter = parseRetryAfter(retryAfterHeader);\n const record = body && typeof body === \"object\" && !Array.isArray(body) ? (body as Record<string, unknown>) : null;\n const envelope = record?.error;\n\n if (envelope && typeof envelope === \"object\") {\n const err = envelope as Record<string, unknown>;\n const code = typeof err.code === \"string\" && err.code ? err.code : `http_${status}`;\n const message = typeof err.message === \"string\" && err.message ? err.message : defaultMessage(status, code);\n const requestId = typeof err.request_id === \"string\" ? err.request_id : typeof err.requestId === \"string\" ? err.requestId : null;\n return new PurpleturretApiError({ status, code, message, requestId, details: err.details, retryAfter });\n }\n\n if (typeof envelope === \"string\" && record) {\n const { error: _code, message: rawMessage, request_id: requestId, ...rest } = record;\n const code = envelope || `http_${status}`;\n const message = typeof rawMessage === \"string\" && rawMessage ? rawMessage : defaultMessage(status, code);\n const resetAt = typeof rest.reset_at === \"number\" ? rest.reset_at : null;\n const legacyRetryAfter = retryAfter ?? (resetAt !== null ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1000)) : null);\n return new PurpleturretApiError({\n status,\n code,\n message,\n requestId: typeof requestId === \"string\" ? requestId : null,\n details: Object.keys(rest).length > 0 ? rest : undefined,\n retryAfter: legacyRetryAfter,\n });\n }\n\n const text = typeof body === \"string\" ? body.trim().slice(0, 300) : \"\";\n return new PurpleturretApiError({\n status,\n code: `http_${status}`,\n message: text || defaultMessage(status, `http_${status}`),\n details: record ?? undefined,\n retryAfter,\n });\n }\n}\n\n/** The request never produced an HTTP response (DNS, connection refused, timeout, aborted). */\nexport class PurpleturretNetworkError extends Error {\n override readonly name = \"PurpleturretNetworkError\";\n readonly url: string;\n readonly timedOut: boolean;\n override readonly cause: unknown;\n\n constructor(url: string, cause: unknown, timedOut: boolean) {\n super(timedOut ? `Request to ${url} timed out` : `Request to ${url} failed: ${describeCause(cause)}`);\n this.url = url;\n this.cause = cause;\n this.timedOut = timedOut;\n }\n}\n\nexport function isTimeoutError(cause: unknown): boolean {\n return Boolean(cause && typeof cause === \"object\" && \"name\" in cause && (cause as { name?: unknown }).name === \"TimeoutError\");\n}\n\nfunction describeCause(cause: unknown): string {\n if (cause && typeof cause === \"object\") {\n const inner = (cause as { cause?: unknown }).cause;\n if (inner && typeof inner === \"object\" && \"message\" in inner && typeof (inner as { message?: unknown }).message === \"string\") {\n const code = (inner as { code?: unknown }).code;\n return typeof code === \"string\" ? `${code} (${(inner as { message: string }).message})` : (inner as { message: string }).message;\n }\n if (\"message\" in cause && typeof (cause as { message?: unknown }).message === \"string\") return (cause as { message: string }).message;\n }\n return String(cause);\n}\n\nfunction defaultMessage(status: number, code: string): string {\n switch (status) {\n case 401:\n return \"The API key was rejected\";\n case 403:\n return \"The API key is not allowed to perform this operation\";\n case 404:\n return \"The requested resource was not found\";\n case 409:\n return \"The request conflicts with the current state\";\n case 422:\n return \"The request was rejected as invalid\";\n case 429:\n return \"Too many requests; slow down and retry\";\n default:\n return status >= 500 ? `The Purpleturret API returned ${status}` : `Request failed with ${code}`;\n }\n}\n\nexport function parseRetryAfter(header: string | null | undefined): number | null {\n if (!header) return null;\n const trimmed = header.trim();\n if (/^\\d+$/.test(trimmed)) return Number(trimmed);\n const when = Date.parse(trimmed);\n if (Number.isNaN(when)) return null;\n return Math.max(0, Math.ceil((when - Date.now()) / 1000));\n}\n","import type { PurpleturretClient } from \"../client\";\nimport type { DeliveryFileRef } from \"../../types\";\nimport { PurpleturretApiError } from \"../errors\";\nimport { camelizeKeys } from \"../wire\";\n\n/*\n * Upload URLs (Convex storage for logos/page files, R2 for delivery files). `index.ts` re-exports the file.\n */\n\nexport interface UploadUrl {\n /** POST the raw bytes here with the file's Content-Type; the response is `{ storageId }`. */\n uploadUrl: string;\n /** Epoch ms; URLs last 1 hour. */\n expiresAt: number;\n}\n\nexport interface DeliveryFileUploadOptions {\n fileName: string;\n /** Defaults to application/octet-stream. */\n contentType?: string;\n fileSize: number;\n}\n\nexport interface DeliveryFileUpload {\n /** PUT the raw bytes here sending exactly `headers`. */\n uploadUrl: string;\n objectKey: string;\n headers: Record<string, string>;\n /** Seconds. */\n expiresIn: number;\n}\n\nexport type UploadData = Blob | Uint8Array | ArrayBuffer;\n\nconst byteLength = (data: UploadData) => (data instanceof Blob ? data.size : data.byteLength);\n\nexport function uploadsApi(client: PurpleturretClient) {\n const send = async (method: string, url: string, headers: Record<string, string>, data: UploadData) => {\n // `client.fetch` is read per call: this namespace is built before the constructor assigns it.\n const response = await client.fetch(url, { method, headers, body: data as RequestInit[\"body\"] });\n if (!response.ok) {\n throw PurpleturretApiError.fromResponse(response.status, await response.text().catch(() => \"\"), response.headers.get(\"retry-after\"));\n }\n return response;\n };\n const api = {\n /** Signed Convex upload URL for logos and page files. */\n create: async (): Promise<UploadUrl> => camelizeKeys(await client.request(\"POST\", \"/uploads\")) as UploadUrl,\n /** Signed R2 upload for a product delivery file. */\n deliveryFile: async (options: DeliveryFileUploadOptions): Promise<DeliveryFileUpload> =>\n camelizeKeys(\n await client.request(\"POST\", \"/uploads/delivery-file\", {\n body: { file_name: options.fileName, content_type: options.contentType, file_size: options.fileSize },\n }),\n ) as DeliveryFileUpload,\n /** Uploads bytes to Convex storage and returns the `storageId` (for `theme.logoStorageId` and page files). */\n put: async (data: UploadData, contentType: string): Promise<string> => {\n const { uploadUrl } = await api.create();\n const response = await send(\"POST\", uploadUrl, { \"content-type\": contentType }, data);\n return ((await response.json()) as { storageId: string }).storageId;\n },\n /** Uploads a delivery file to R2 and returns the descriptor for `products.setDelivery({ method: \"file\", ... })`. */\n putDeliveryFile: async (data: UploadData, options: { fileName: string; contentType?: string }): Promise<Required<DeliveryFileRef>> => {\n const fileSize = byteLength(data);\n const upload = await api.deliveryFile({ fileName: options.fileName, contentType: options.contentType, fileSize });\n await send(\"PUT\", upload.uploadUrl, upload.headers, data);\n const contentType = upload.headers[\"Content-Type\"] ?? options.contentType ?? \"application/octet-stream\";\n return { objectKey: upload.objectKey, fileName: options.fileName, contentType, fileSize };\n },\n };\n return api;\n}\n","import type {\n ConfigGetResult,\n ConfigPushResult,\n CreditAdjustResult,\n CreditBalancesResult,\n CreditConsumeResult,\n CustomerSelector,\n Entitlement,\n LedgerEntry,\n DeliveryInput,\n Page,\n Product,\n ProductCreateInput,\n ProductInput,\n ProductUpdateInput,\n VisitsSummary,\n} from \"../types\";\nimport { SDK_VERSION } from \"../version\";\nimport { type AccountDetails, accountApi, fromWireAccountDetails, supportApi, type WireAccountDetails } from \"./areas/account\";\nimport { customersApi, leadsApi, ordersApi, subscriptionsApi } from \"./areas/orders\";\nimport { pixelsApi } from \"./areas/pixels\";\nimport { pagesApi } from \"./areas/pages\";\nimport { trackingApi } from \"./areas/tracking\";\nimport { domainsApi } from \"./areas/domains\";\nimport { groupsApi, keysApi, webhooksApi } from \"./areas/webhooks\";\nimport { uploadsApi } from \"./areas/uploads\";\nimport { PurpleturretApiError, PurpleturretNetworkError, isTimeoutError } from \"./errors\";\nimport {\n fromWireConfigGetResult,\n fromWireConfigPushResult,\n fromWireCreditAdjust,\n fromWireCreditBalances,\n fromWireCreditConsume,\n fromWireEntitlement,\n fromWireLedgerEntry,\n fromWirePage,\n fromWireProduct,\n camelizeKeys,\n snakeizeKeys,\n toWireProduct,\n type WireConfigGetResult,\n type WireConfigPushResult,\n type WireCreditAdjustResult,\n type WireCreditBalancesResult,\n type WireCreditConsumeResult,\n type WireEntitlement,\n type WireLedgerEntry,\n type WirePage,\n type WireProduct,\n} from \"./wire\";\n\nexport const DEFAULT_BASE_URL = \"https://api.purpleturret.com\";\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\nexport interface PurpleturretClientOptions {\n /** Seller API key (`pt_sk_…`). */\n apiKey: string;\n /** API origin without `/v1`. Defaults to `https://api.purpleturret.com`; local dev uses `http://localhost:3001/api`. */\n baseUrl?: string;\n /** Custom fetch implementation (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Per-request timeout. Defaults to 30 s. */\n timeoutMs?: number;\n /** Extra `User-Agent` value; the SDK version is appended. */\n userAgent?: string;\n}\n\nexport interface ConfigPushOptions {\n products: ProductInput[];\n /** Archive keyed products that are missing from `products`. */\n prune?: boolean;\n /** Compute the plan without applying it. */\n dryRun?: boolean;\n /** Sent as `Idempotency-Key`; reuse it when retrying a failed apply. */\n idempotencyKey?: string;\n}\n\nexport interface ProductListOptions {\n cursor?: string;\n limit?: number;\n includeArchived?: boolean;\n}\n\nexport type CreditBalancesOptions = CustomerSelector & { meter?: string };\n\nexport type CreditConsumeOptions = CustomerSelector & {\n meter: string;\n amount: number;\n /** Required. Reusing a key replays the original result instead of consuming twice. */\n idempotencyKey: string;\n note?: string;\n};\n\nexport type CreditAdjustOptions = CustomerSelector & {\n meter: string;\n /** Signed amount: positive grants, negative removes. */\n amount: number;\n idempotencyKey?: string;\n note?: string;\n};\n\nexport type CreditLedgerOptions = CustomerSelector & { cursor?: string; limit?: number };\n\nexport type EntitlementOptions = CustomerSelector & { groupKey: string };\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n idempotencyKey?: string;\n /** Statuses (besides 2xx) whose bodies are returned instead of thrown. */\n acceptStatuses?: number[];\n}\n\nexport class PurpleturretClient {\n readonly baseUrl: string;\n readonly timeoutMs: number;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n private readonly userAgent: string;\n\n constructor(options: PurpleturretClientOptions) {\n if (!options || typeof options.apiKey !== \"string\" || !options.apiKey.trim()) {\n throw new TypeError(\"PurpleturretClient: apiKey is required\");\n }\n this.apiKey = options.apiKey.trim();\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).trim().replace(/\\/+$/, \"\");\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") throw new TypeError(\"PurpleturretClient: no fetch implementation available; pass options.fetch\");\n this.fetchImpl = fetchImpl;\n const sdkAgent = `purpleturret-sdk/${SDK_VERSION}`;\n this.userAgent = options.userAgent ? `${options.userAgent} ${sdkAgent}` : sdkAgent;\n }\n\n /** The fetch used for API calls (also for raw byte uploads to signed URLs). */\n get fetch(): typeof fetch {\n return this.fetchImpl;\n }\n\n /** Absolute URL for an API path such as `/config`. */\n url(path: string, query?: RequestOptions[\"query\"]): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n let url = `${this.baseUrl}/v1${normalizedPath}`;\n if (query) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n params.set(key, String(value));\n }\n const qs = params.toString();\n if (qs) url += `?${qs}`;\n }\n return url;\n }\n\n readonly account = {\n get: async (): Promise<AccountDetails> => fromWireAccountDetails(await this.request<WireAccountDetails>(\"GET\", \"/account\")),\n ...accountApi(this),\n keys: keysApi(this),\n };\n\n readonly config = {\n get: async (): Promise<ConfigGetResult> => fromWireConfigGetResult(await this.request<WireConfigGetResult>(\"GET\", \"/config\")),\n push: async (options: ConfigPushOptions): Promise<ConfigPushResult> => {\n const body: Record<string, unknown> = { products: options.products.map(toWireProduct) };\n if (options.prune !== undefined) body.prune = options.prune;\n if (options.dryRun !== undefined) body.dry_run = options.dryRun;\n const wire = await this.request<WireConfigPushResult>(\"PUT\", \"/config\", {\n body,\n idempotencyKey: options.idempotencyKey,\n // A conflict returns the full plan with a 409; surface it as a result so callers can render it.\n acceptStatuses: [409],\n });\n return fromWireConfigPushResult(wire);\n },\n };\n\n readonly products = {\n list: async (options: ProductListOptions = {}): Promise<Page<Product>> =>\n fromWirePage(\n await this.request<WirePage<WireProduct>>(\"GET\", \"/products\", {\n query: { cursor: options.cursor, limit: options.limit, include_archived: options.includeArchived },\n }),\n fromWireProduct,\n ),\n get: async (idOrKey: string): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"GET\", `/products/${encodeURIComponent(idOrKey)}`)),\n /** POST /products. Sends an `Idempotency-Key` (random unless given). */\n create: async (input: ProductCreateInput, options: { idempotencyKey?: string } = {}): Promise<Product> =>\n fromWireProduct(\n await this.request<WireProduct>(\"POST\", \"/products\", {\n body: snakeizeKeys(input),\n idempotencyKey: options.idempotencyKey ?? crypto.randomUUID(),\n }),\n ),\n /** PATCH /products/{id|key}: only the given fields change. */\n update: async (idOrKey: string, patch: ProductUpdateInput): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"PATCH\", `/products/${encodeURIComponent(idOrKey)}`, { body: snakeizeKeys(patch) })),\n /** PUT /products/{key}: create or update one config-managed product (single-product `config.push`). */\n upsert: async (key: string, input: Omit<ProductInput, \"key\">, options: { idempotencyKey?: string } = {}): Promise<Product> =>\n fromWireProduct(\n await this.request<WireProduct>(\"PUT\", `/products/${encodeURIComponent(key)}`, {\n body: toWireProduct({ ...input, key }),\n idempotencyKey: options.idempotencyKey,\n }),\n ),\n /** File entries come from `uploads.putDeliveryFile`. */\n setDelivery: async (idOrKey: string, delivery: DeliveryInput): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"PUT\", `/products/${encodeURIComponent(idOrKey)}/delivery`, { body: snakeizeKeys(delivery) })),\n /** Copy checkout + theme settings from another product (`from` is an id or key). */\n copyStyles: async (idOrKey: string, options: { from: string }): Promise<Product> =>\n fromWireProduct(\n await this.request<WireProduct>(\"POST\", `/products/${encodeURIComponent(idOrKey)}/copy-styles`, { body: { from: options.from } }),\n ),\n visits: async (idOrKey: string): Promise<VisitsSummary> =>\n camelizeKeys(await this.request(\"GET\", `/products/${encodeURIComponent(idOrKey)}/visits`)) as VisitsSummary,\n /** Archives the product (never hard-deletes). */\n archive: async (idOrKey: string): Promise<Product> =>\n fromWireProduct(await this.request<WireProduct>(\"DELETE\", `/products/${encodeURIComponent(idOrKey)}`)),\n };\n\n readonly credits = {\n balances: async (options: CreditBalancesOptions): Promise<CreditBalancesResult> =>\n fromWireCreditBalances(\n await this.request<WireCreditBalancesResult>(\"GET\", \"/credits/balances\", {\n query: { ...customerQuery(options), meter: options.meter },\n }),\n ),\n consume: async (options: CreditConsumeOptions): Promise<CreditConsumeResult> => {\n if (!options.idempotencyKey) throw new TypeError(\"credits.consume: idempotencyKey is required\");\n return fromWireCreditConsume(\n await this.request<WireCreditConsumeResult>(\"POST\", \"/credits/consume\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n );\n },\n adjust: async (options: CreditAdjustOptions): Promise<CreditAdjustResult> =>\n fromWireCreditAdjust(\n await this.request<WireCreditAdjustResult>(\"POST\", \"/credits/adjust\", {\n body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },\n idempotencyKey: options.idempotencyKey,\n }),\n ),\n ledger: async (options: CreditLedgerOptions): Promise<Page<LedgerEntry>> =>\n fromWirePage(\n await this.request<WirePage<WireLedgerEntry>>(\"GET\", \"/credits/ledger\", {\n query: { ...customerQuery(options), cursor: options.cursor, limit: options.limit },\n }),\n fromWireLedgerEntry,\n ),\n };\n\n readonly orders = ordersApi(this);\n readonly subscriptions = subscriptionsApi(this);\n readonly customers = customersApi(this);\n readonly leads = leadsApi(this);\n readonly pixels = pixelsApi(this);\n readonly pages = pagesApi(this);\n readonly tracking = trackingApi(this);\n readonly domains = domainsApi(this);\n readonly webhooks = webhooksApi(this);\n readonly groups = groupsApi(this);\n readonly support = supportApi(this);\n readonly uploads = uploadsApi(this);\n\n readonly entitlements = {\n /** Resolves with `hasAccess: false` (rather than throwing) when the customer has no subscription. */\n get: async (options: EntitlementOptions): Promise<Entitlement> =>\n fromWireEntitlement(\n await this.request<WireEntitlement>(\"GET\", \"/entitlements\", {\n query: { group_key: options.groupKey, ...customerQuery(options) },\n acceptStatuses: [404],\n }),\n ),\n };\n\n /** Low-level request used by the per-area namespaces; prefer the typed namespaces. @internal */\n async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n const url = this.url(path, options.query);\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.apiKey}`,\n accept: \"application/json\",\n \"user-agent\": this.userAgent,\n };\n const hasBody = options.body !== undefined;\n if (hasBody) headers[\"content-type\"] = \"application/json\";\n if (options.idempotencyKey) headers[\"idempotency-key\"] = options.idempotencyKey;\n\n let response: Response;\n try {\n response = await this.fetchImpl(url, {\n method,\n headers,\n body: hasBody ? JSON.stringify(stripUndefined(options.body)) : undefined,\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n } catch (cause) {\n throw new PurpleturretNetworkError(url, cause, isTimeoutError(cause));\n }\n\n const text = await response.text();\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = undefined;\n }\n }\n\n const accepted = response.ok || (options.acceptStatuses?.includes(response.status) ?? false);\n if (!accepted) {\n throw PurpleturretApiError.fromResponse(response.status, parsed ?? text, response.headers.get(\"retry-after\"));\n }\n if (!response.ok && parsed && typeof parsed === \"object\" && \"error\" in (parsed as Record<string, unknown>)) {\n const record = parsed as Record<string, unknown>;\n // A 409 config conflict carries the full plan under error.details; hand it back unapplied.\n const details = (record.error as { details?: Record<string, unknown> } | undefined)?.details;\n if (details && \"results\" in details && \"summary\" in details) return { applied: false, ...details } as T;\n // A 404 entitlement lookup returns `{ has_access: false }` (no error); anything else with an\n // error envelope is still an error even if the status was in acceptStatuses.\n const looksLikePlan = \"results\" in record && \"summary\" in record;\n const looksLikeEntitlement = \"has_access\" in record;\n if (!looksLikePlan && !looksLikeEntitlement) {\n throw PurpleturretApiError.fromResponse(response.status, parsed, response.headers.get(\"retry-after\"));\n }\n }\n if (response.status === 204 || parsed === undefined) return undefined as T;\n return parsed as T;\n }\n}\n\nexport function customerQuery(selector: CustomerSelector): { external_id?: string; email?: string } {\n const out: { external_id?: string; email?: string } = {};\n if (selector.externalId) out.external_id = selector.externalId;\n if (selector.email) out.email = selector.email;\n if (!out.external_id && !out.email) throw new TypeError(\"Provide externalId or email to identify the customer\");\n return out;\n}\n\nfunction stripUndefined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(stripUndefined);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (entry !== undefined) out[key] = stripUndefined(entry);\n }\n return out;\n }\n return value;\n}\n","/** Keep in sync with package.json. */\nexport const CLI_VERSION = \"0.7.0\";\n","import { chmod, mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nexport interface Profile {\n apiKey: string;\n /** Only stored when the key was validated against a non-default API URL. */\n apiUrl?: string;\n email?: string;\n keyPrefix?: string;\n scopes?: string[];\n savedAt: string;\n}\n\nexport interface CredentialsFile {\n version: 1;\n profiles: Record<string, Profile>;\n}\n\nexport const DEFAULT_PROFILE = \"default\";\n\n/** `$XDG_CONFIG_HOME/purpleturret/credentials.json`, defaulting to `~/.config`. */\nexport function credentialsPath(env: NodeJS.ProcessEnv = process.env): string {\n const xdg = env.XDG_CONFIG_HOME?.trim();\n const home = env.HOME?.trim() || homedir();\n const configHome = xdg && xdg.length > 0 ? xdg : join(home, \".config\");\n return join(configHome, \"purpleturret\", \"credentials.json\");\n}\n\nexport class CredentialsStore {\n readonly path: string;\n\n constructor(path: string = credentialsPath()) {\n this.path = path;\n }\n\n async read(): Promise<CredentialsFile> {\n let text: string;\n try {\n text = await readFile(this.path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { version: 1, profiles: {} };\n throw error;\n }\n try {\n const parsed = JSON.parse(text) as Partial<CredentialsFile>;\n if (!parsed || typeof parsed !== \"object\" || typeof parsed.profiles !== \"object\" || parsed.profiles === null) {\n return { version: 1, profiles: {} };\n }\n return { version: 1, profiles: parsed.profiles as Record<string, Profile> };\n } catch {\n throw new Error(`Credentials file ${this.path} is not valid JSON. Fix or delete it and run \\`purpleturret login\\` again.`);\n }\n }\n\n async write(file: CredentialsFile): Promise<void> {\n await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });\n const tmp = `${this.path}.${process.pid}.tmp`;\n await writeFile(tmp, `${JSON.stringify(file, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await chmod(tmp, 0o600);\n await rename(tmp, this.path);\n }\n\n async getProfile(name: string = DEFAULT_PROFILE): Promise<Profile | null> {\n const file = await this.read();\n return file.profiles[name] ?? null;\n }\n\n async saveProfile(name: string, profile: Profile): Promise<void> {\n const file = await this.read();\n file.profiles[name] = profile;\n await this.write(file);\n }\n\n /** Returns true when a profile was removed. */\n async deleteProfile(name: string): Promise<boolean> {\n const file = await this.read();\n if (!(name in file.profiles)) return false;\n delete file.profiles[name];\n await this.write(file);\n return true;\n }\n}\n","import { ConfigValidationError, PurpleturretApiError, PurpleturretNetworkError } from \"@purpleturret/sdk\";\n\nexport const EXIT = {\n OK: 0,\n ERROR: 1,\n USAGE: 2,\n AUTH: 3,\n CONFLICT: 4,\n ABORTED: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\nexport const DASHBOARD_SETTINGS_URL = \"https://purpleturret.com/dashboard/settings\";\n\nexport class CliError extends Error {\n override readonly name = \"CliError\";\n readonly exitCode: ExitCode;\n readonly hint: string | undefined;\n readonly code: string | undefined;\n override readonly cause: unknown;\n\n constructor(message: string, exitCode: ExitCode = EXIT.ERROR, options: { hint?: string; code?: string; cause?: unknown } = {}) {\n super(message);\n this.exitCode = exitCode;\n this.hint = options.hint;\n this.code = options.code;\n this.cause = options.cause;\n }\n}\n\nexport interface ErrorContext {\n apiUrl: string;\n apiUrlSource: \"flag\" | \"env\" | \"profile\" | \"default\";\n credentialSource?: \"flag\" | \"env\" | \"profile\" | \"none\";\n}\n\n/** Map any thrown value to a `CliError` with the exit code and actionable message from the plan. */\nexport function toCliError(error: unknown, ctx: ErrorContext): CliError {\n if (error instanceof CliError) return error;\n\n if (error instanceof ConfigValidationError) {\n return new CliError(error.message, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n\n if (error instanceof PurpleturretNetworkError) {\n const where = ctx.apiUrlSource === \"default\" ? \"\" : ` (from ${describeUrlSource(ctx.apiUrlSource)})`;\n return new CliError(error.message, EXIT.ERROR, {\n code: error.timedOut ? \"timeout\" : \"network_error\",\n hint: `Check that the API URL ${ctx.apiUrl}${where} is reachable, or override it with --api-url / PURPLETURRET_API_URL.`,\n cause: error,\n });\n }\n\n if (error instanceof PurpleturretApiError) return fromApiError(error, ctx);\n\n if (error instanceof Error) return new CliError(error.message, EXIT.ERROR, { cause: error });\n return new CliError(String(error), EXIT.ERROR);\n}\n\nfunction fromApiError(error: PurpleturretApiError, ctx: ErrorContext): CliError {\n const requestId = error.requestId ? ` (request ${error.requestId})` : \"\";\n const detailText = formatDetails(error.details);\n\n if (error.code === \"stripe_not_connected\") {\n return new CliError(`${error.message}${requestId}`, EXIT.ERROR, {\n code: error.code,\n hint: `Connect Stripe first in Dashboard → Settings → Payments: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n\n switch (error.status) {\n case 401: {\n const source = ctx.credentialSource;\n const hint =\n source === \"flag\"\n ? \"The key passed with --api-key was rejected. Mint a new seller key in Dashboard → Settings → Developers.\"\n : source === \"env\"\n ? \"PURPLETURRET_API_KEY was rejected. Mint a new seller key in Dashboard → Settings → Developers and update your .env.local.\"\n : \"Run `purpleturret login` to store a valid seller key, or pass --api-key / set PURPLETURRET_API_KEY.\";\n return new CliError(`The API key was rejected (401 ${error.code})${requestId}.`, EXIT.AUTH, { code: error.code, hint, cause: error });\n }\n case 403: {\n if (error.code === \"forbidden_key_type\") {\n return new CliError(`This is a hosting key (pt_host_…), which cannot manage products or credits${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: `Use a seller key (pt_sk_…) minted in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n const required = pickString(error.details, \"required_scope\") ?? pickString(error.details, \"scope\");\n return new CliError(`${error.message} (403 ${error.code})${requestId}.`, EXIT.AUTH, {\n code: error.code,\n hint: required\n ? `The key is missing the ${required} scope. Mint a key with that scope in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`\n : `Mint a seller key with the config:read, config:write, credits:read, credits:write and entitlements:read scopes in Dashboard → Settings → Developers: ${DASHBOARD_SETTINGS_URL}`,\n cause: error,\n });\n }\n case 402:\n return new CliError(`${error.message} (402 ${error.code})${requestId}.${detailText}`, EXIT.ERROR, { code: error.code, cause: error });\n case 404:\n return new CliError(`${error.message} (404 ${error.code})${requestId}.`, EXIT.ERROR, { code: error.code, cause: error });\n case 409: {\n if (error.code === \"immutable_field_changed\") {\n return new CliError(`${error.message} (409 immutable_field_changed)${requestId}.${detailText}`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one (push --prune).\",\n cause: error,\n });\n }\n if (error.code === \"idempotency_conflict\") {\n return new CliError(`${error.message} (409 idempotency_conflict)${requestId}.`, EXIT.CONFLICT, {\n code: error.code,\n hint: \"The Idempotency-Key was already used with a different request body. Run push again to generate a fresh key.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (409 ${error.code})${requestId}.${detailText}`, EXIT.CONFLICT, { code: error.code, cause: error });\n }\n case 422:\n return new CliError(`The API rejected the request (422 ${error.code})${requestId}: ${error.message}${detailText}`, EXIT.USAGE, {\n code: error.code,\n cause: error,\n });\n case 429:\n return new CliError(`Rate limited (429 ${error.code})${requestId}.`, EXIT.ERROR, {\n code: error.code,\n hint: error.retryAfter !== null ? `Retry after ${error.retryAfter}s.` : \"Slow down and retry shortly.\",\n cause: error,\n });\n default:\n if (error.status >= 500) {\n return new CliError(`The Purpleturret API returned ${error.status} ${error.code}${requestId}: ${error.message}`, EXIT.ERROR, {\n code: error.code,\n hint: \"This is a server-side failure. Retry in a moment; if it persists, contact support with the request id.\",\n cause: error,\n });\n }\n return new CliError(`${error.message} (${error.status} ${error.code})${requestId}.${detailText}`, EXIT.ERROR, {\n code: error.code,\n cause: error,\n });\n }\n}\n\nfunction describeUrlSource(source: ErrorContext[\"apiUrlSource\"]): string {\n switch (source) {\n case \"flag\":\n return \"--api-url\";\n case \"env\":\n return \"PURPLETURRET_API_URL\";\n case \"profile\":\n return \"the saved profile\";\n default:\n return \"the default\";\n }\n}\n\nfunction pickString(details: unknown, key: string): string | undefined {\n if (details && typeof details === \"object\" && key in details) {\n const value = (details as Record<string, unknown>)[key];\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function formatDetails(details: unknown): string {\n if (details === undefined || details === null) return \"\";\n if (typeof details === \"string\") return `\\n ${details}`;\n if (Array.isArray(details)) {\n if (details.length === 0) return \"\";\n return `\\n${details.map((entry) => ` - ${formatDetailEntry(entry)}`).join(\"\\n\")}`;\n }\n if (typeof details === \"object\") {\n const entries = Object.entries(details as Record<string, unknown>);\n if (entries.length === 0) return \"\";\n if (\"issues\" in (details as Record<string, unknown>) && Array.isArray((details as Record<string, unknown>).issues)) {\n return formatDetails((details as Record<string, unknown>).issues);\n }\n return `\\n${entries.map(([key, value]) => ` ${key}: ${typeof value === \"string\" ? value : JSON.stringify(value)}`).join(\"\\n\")}`;\n }\n return `\\n ${String(details)}`;\n}\n\nfunction formatDetailEntry(entry: unknown): string {\n if (entry && typeof entry === \"object\") {\n const record = entry as Record<string, unknown>;\n const path = typeof record.path === \"string\" ? record.path : Array.isArray(record.path) ? record.path.join(\".\") : undefined;\n const message = typeof record.message === \"string\" ? record.message : JSON.stringify(record);\n return path ? `${path}: ${message}` : message;\n }\n return String(entry);\n}\n","import { createColors } from \"picocolors\";\n\nimport type { CliError } from \"./errors\";\n\nexport type Paint = (text: string | number) => string;\n\nexport interface Palette {\n enabled: boolean;\n green: Paint;\n yellow: Paint;\n red: Paint;\n cyan: Paint;\n magenta: Paint;\n dim: Paint;\n bold: Paint;\n}\n\nexport function createPalette(enabled: boolean): Palette {\n const colors = createColors(enabled);\n return {\n enabled,\n green: colors.green,\n yellow: colors.yellow,\n red: colors.red,\n cyan: colors.cyan,\n magenta: colors.magenta,\n dim: colors.dim,\n bold: colors.bold,\n };\n}\n\n/** Color is on only for a TTY, unless `--no-color` or `NO_COLOR` turns it off. */\nexport function shouldUseColor(options: { flag?: boolean; env?: NodeJS.ProcessEnv; stream?: { isTTY?: boolean } } = {}): boolean {\n const env = options.env ?? process.env;\n const stream = options.stream ?? process.stdout;\n if (options.flag === false) return false;\n if (env.NO_COLOR !== undefined && env.NO_COLOR !== \"\") return false;\n if (env.FORCE_COLOR !== undefined && env.FORCE_COLOR !== \"\" && env.FORCE_COLOR !== \"0\") return true;\n return Boolean(stream.isTTY);\n}\n\nexport function isInteractive(): boolean {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY);\n}\n\nexport interface OutputOptions {\n json: boolean;\n verbose: boolean;\n palette: Palette;\n stdout?: NodeJS.WritableStream;\n stderr?: NodeJS.WritableStream;\n}\n\n/** Human messages go to stderr; results (plans, tables, JSON) go to stdout. */\nexport class Output {\n readonly json: boolean;\n readonly verbose: boolean;\n readonly palette: Palette;\n private readonly stdout: NodeJS.WritableStream;\n private readonly stderr: NodeJS.WritableStream;\n\n constructor(options: OutputOptions) {\n this.json = options.json;\n this.verbose = options.verbose;\n this.palette = options.palette;\n this.stdout = options.stdout ?? process.stdout;\n this.stderr = options.stderr ?? process.stderr;\n }\n\n /** Write result lines to stdout (suppressed in --json mode unless `force`). */\n print(text: string, force = false): void {\n if (this.json && !force) return;\n this.stdout.write(`${text}\\n`);\n }\n\n /** Write a JSON document to stdout. */\n printJson(value: unknown): void {\n this.stdout.write(`${JSON.stringify(value, null, 2)}\\n`);\n }\n\n info(text: string): void {\n if (this.json) return;\n this.stderr.write(`${text}\\n`);\n }\n\n success(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.green(\"✔\")} ${text}\\n`);\n }\n\n warn(text: string): void {\n if (this.json) return;\n this.stderr.write(`${this.palette.yellow(\"!\")} ${text}\\n`);\n }\n\n debug(text: string): void {\n if (!this.verbose) return;\n this.stderr.write(`${this.palette.dim(`[debug] ${text}`)}\\n`);\n }\n\n /** Report a fatal error. In --json mode the error is emitted as JSON on stdout. */\n fail(error: CliError): void {\n if (this.json) {\n this.stdout.write(\n `${JSON.stringify({ error: { code: error.code ?? \"error\", message: error.message, hint: error.hint, exit_code: error.exitCode } })}\\n`,\n );\n return;\n }\n this.stderr.write(`${this.palette.red(\"error:\")} ${error.message}\\n`);\n if (error.hint) this.stderr.write(`${this.palette.dim(\"hint:\")} ${error.hint}\\n`);\n if (this.verbose && error.cause instanceof Error && error.cause.stack) {\n this.stderr.write(`${this.palette.dim(error.cause.stack)}\\n`);\n }\n }\n}\n","import { DEFAULT_BASE_URL } from \"@purpleturret/sdk\";\nimport { isCancel } from \"@clack/prompts\";\nimport type { ArgsDef, CommandContext } from \"citty\";\n\nimport { createContext, type CliContext, type GlobalFlags } from \"./context\";\nimport { CliError, EXIT, toCliError } from \"./errors\";\nimport { Output, createPalette, shouldUseColor } from \"./output\";\n\nexport type Handler<A extends ArgsDef> = (ctx: CliContext, args: CommandContext<A>[\"args\"]) => Promise<void>;\n\n/**\n * Wrap a command body: build the CLI context from the parsed flags, run, and translate any error into\n * a message plus exit code. Errors never escape to citty (which would print a stack and exit 1).\n */\nexport function defineRun<A extends ArgsDef>(handler: Handler<A>) {\n return async (command: CommandContext<A>): Promise<void> => {\n let ctx: CliContext | undefined;\n try {\n ctx = await createContext(command.args as GlobalFlags);\n await handler(ctx, command.args);\n } catch (error) {\n const cliError = toCliError(error, ctx ?? { apiUrl: DEFAULT_BASE_URL, apiUrlSource: \"default\" });\n const out =\n ctx?.out ??\n new Output({\n json: Boolean((command.args as GlobalFlags).json),\n verbose: Boolean((command.args as GlobalFlags).verbose),\n palette: createPalette(shouldUseColor({ flag: (command.args as GlobalFlags).color })),\n });\n out.fail(cliError);\n process.exitCode = cliError.exitCode;\n }\n };\n}\n\n/** Convert a cancelled @clack prompt into an exit-130 error. */\nexport function unwrapPrompt<T>(value: T | symbol): T {\n if (isCancel(value)) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n return value as T;\n}\n","/** Render a plain-text table with left-aligned, space-padded columns. */\nexport function renderTable(headers: string[], rows: string[][], dimHeader: (text: string) => string = (text) => text): string[] {\n const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? \"\").length)));\n const line = (cells: string[]) =>\n cells\n .map((cell, index) => cell.padEnd(widths[index] ?? 0))\n .join(\" \")\n .trimEnd();\n return [dimHeader(line(headers)), ...rows.map(line)];\n}\n","import { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst yesArg = { yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt (required in CI)\" } } as const;\n\n/** Ask before a destructive call unless `--yes`; refuses silently-destructive runs in non-interactive terminals. */\nexport async function confirmOrYes(yes: boolean, json: boolean, message: string): Promise<void> {\n if (yes) return;\n if (!isInteractive() || json) {\n throw new CliError(\"Refusing to delete without confirmation because this is not an interactive terminal.\", EXIT.USAGE, {\n code: \"confirmation_required\",\n hint: \"Re-run with --yes to confirm non-interactively.\",\n });\n }\n if (!unwrapPrompt(await confirm({ message, initialValue: false }))) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List webhook endpoints\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().webhooks.list();\n if (ctx.json) return ctx.out.printJson({ webhooks: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No webhook endpoints yet. Run `purpleturret webhooks add <group-key> <url>`.\"));\n const rows = data.map((w) => [\n w.id,\n w.groupKey,\n w.url,\n w.enabled ? \"enabled\" : palette.yellow(\"disabled\"),\n w.lastDelivery ? `${w.lastDelivery.status} ${new Date(w.lastDelivery.at).toISOString()}` : palette.dim(\"—\"),\n w.description ?? \"\",\n ]);\n for (const line of renderTable([\"ID\", \"GROUP\", \"URL\", \"STATUS\", \"LAST DELIVERY\", \"DESCRIPTION\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst add = defineCommand({\n meta: { name: \"add\", description: \"Create a webhook endpoint in an integration group\" },\n args: {\n ...globalArgs,\n group: { type: \"positional\", required: true, description: \"Integration group key\" },\n url: { type: \"positional\", required: true, description: \"HTTPS URL to deliver events to\" },\n description: { type: \"string\", description: \"Label (up to 80 chars)\" },\n },\n run: defineRun(async (ctx, args) => {\n const created = await ctx.client().webhooks.create({ groupKey: args.group, url: args.url, description: args.description });\n if (ctx.json) return ctx.out.printJson(created);\n ctx.out.print(`Created webhook ${created.id} for ${created.groupKey} → ${created.url}`);\n ctx.out.print(`Signing secret (shown once, store it now): ${created.secret}`);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Change a webhook endpoint's URL, enabled flag or description\" },\n args: {\n ...globalArgs,\n id: { type: \"positional\", required: true },\n url: { type: \"string\", description: \"New HTTPS URL\" },\n enabled: { type: \"boolean\", description: \"Enable (--enabled) or disable (--no-enabled) deliveries\" },\n description: { type: \"string\", description: 'New label; pass \"\" to clear' },\n },\n run: defineRun(async (ctx, args) => {\n const updated = await ctx.client().webhooks.update(args.id, { url: args.url, enabled: args.enabled, description: args.description });\n ctx.json\n ? ctx.out.printJson(updated)\n : ctx.out.print(`Updated webhook ${updated.id} (${updated.enabled ? \"enabled\" : \"disabled\"}) → ${updated.url}`);\n }),\n});\n\nconst del = defineCommand({\n meta: { name: \"delete\", description: \"Delete a webhook endpoint and its pending deliveries\" },\n args: { ...globalArgs, ...yesArg, id: { type: \"positional\", required: true } },\n run: defineRun(async (ctx, args) => {\n await confirmOrYes(Boolean(args.yes), ctx.json, `Delete webhook ${args.id}? Pending deliveries are dropped.`);\n const deleted = await ctx.client().webhooks.delete(args.id);\n ctx.json ? ctx.out.printJson(deleted) : ctx.out.print(`Deleted webhook ${deleted.id} (${deleted.url})`);\n }),\n});\n\nconst test = defineCommand({\n meta: { name: \"test\", description: \"Queue a test.event delivery to a webhook endpoint\" },\n args: { ...globalArgs, id: { type: \"positional\", required: true } },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().webhooks.test(args.id);\n ctx.json ? ctx.out.printJson(result) : ctx.out.print(`Queued test delivery ${result.deliveryId}; it is sent asynchronously.`);\n }),\n});\n\nexport const webhooks = defineCommand({\n meta: { name: \"webhooks\", description: \"Webhook endpoints\" },\n args: { ...globalArgs },\n subCommands: { list, add, update, delete: del, test },\n});\n","import { type Order } from \"@purpleturret/sdk\";\nimport { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { type: \"positional\", required: true, description: \"Order id\" } as const;\nconst REASONS = [\"requested_by_customer\", \"duplicate\", \"fraudulent\", \"other\"] as const;\nconst SCOPES = [\"main\", \"upsell\", \"all\"] as const;\n\nfunction printOrder(ctx: CliContext, order: Order): void {\n if (ctx.json) return ctx.out.printJson(order);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"ID\", order.id],\n [\"STATUS\", order.status],\n [\"KIND\", order.kind],\n [\"PROVIDER\", order.provider],\n [\"PRODUCT\", order.productId],\n [\"EMAIL\", order.customer.email ?? palette.dim(\"—\")],\n [\"NAME\", order.customer.name ?? palette.dim(\"—\")],\n [\"AMOUNT\", formatMoney(order)],\n [\"CREATED\", new Date(order.createdAt).toISOString()],\n ];\n if (order.refund) rows.push([\"REFUND\", `${order.refund.reason ?? \"\"} ${new Date(order.refund.refundedAt).toISOString()}`.trim()]);\n if (order.upsell) rows.push([\"UPSELL\", `${order.upsell.decision}${order.upsell.refund ? \" (refunded)\" : \"\"}`]);\n if (order.failureReason) rows.push([\"FAILURE\", palette.red(order.failureReason)]);\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n ctx.out.print(\"\");\n const items = order.lineItems.map((item) => [\n item.role,\n item.name ?? palette.dim(item.productId),\n formatMoney({ amount: item.amount, currency: order.currency }),\n ]);\n for (const line of renderTable([\"ROLE\", \"ITEM\", \"AMOUNT\"], items, palette.dim)) ctx.out.print(line);\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List orders, newest first\" },\n args: {\n ...globalArgs,\n email: { type: \"string\", description: \"Buyer email (exact, case-insensitive)\" },\n status: { type: \"string\", description: \"pending | paid | failed | refunded | partially_refunded\" },\n },\n run: defineRun(async (ctx, args) => {\n const page = await ctx.client().orders.list({ email: args.email, status: args.status as Order[\"status\"] | undefined, limit: 100 });\n if (ctx.json) return ctx.out.printJson(page);\n const { palette } = ctx.out;\n if (page.data.length === 0) return ctx.out.print(palette.dim(\"No orders.\"));\n const rows = page.data.map((o) => [\n o.id,\n o.status,\n o.customer.email ?? palette.dim(\"—\"),\n formatMoney(o),\n o.productId,\n new Date(o.createdAt).toISOString(),\n ]);\n for (const line of renderTable([\"ID\", \"STATUS\", \"EMAIL\", \"AMOUNT\", \"PRODUCT\", \"CREATED\"], rows, palette.dim)) ctx.out.print(line);\n if (page.nextCursor) ctx.out.print(palette.dim(\"More results available; use --json and the API cursor.\"));\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show an order\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printOrder(ctx, await ctx.client().orders.get(args.id))),\n});\n\nconst refund = defineCommand({\n meta: { name: \"refund\", description: \"Refund an order through the payment provider (cannot be undone)\" },\n args: {\n ...globalArgs,\n id,\n reason: { type: \"string\", required: true, description: REASONS.join(\" | \") },\n scope: { type: \"string\", description: \"main | upsell | all (default all)\" },\n \"custom-reason\": { type: \"string\", description: \"Free text, stored only with --reason other\" },\n yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" },\n },\n run: defineRun(async (ctx, args) => {\n const reason = args.reason as (typeof REASONS)[number];\n const scope = args.scope as (typeof SCOPES)[number] | undefined;\n if (!REASONS.includes(reason)) throw new Error(`--reason must be one of ${REASONS.join(\", \")}`);\n if (scope !== undefined && !SCOPES.includes(scope)) throw new Error(`--scope must be one of ${SCOPES.join(\", \")}`);\n if (!args.yes && !unwrapPrompt(await confirm({ message: `Refund ${scope ?? \"all\"} charges of order ${args.id}?`, initialValue: false }))) return;\n const result = await ctx.client().orders.refund(args.id, { reason, scope, customReason: args[\"custom-reason\"] });\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.print(`Refunded main: ${result.refundedMain}, upsell: ${result.refundedUpsell}`);\n printOrder(ctx, result.order);\n }),\n});\n\nexport const orders = defineCommand({\n meta: { name: \"orders\", description: \"Orders\" },\n args: { ...globalArgs },\n subCommands: { list, get, refund },\n});\n","import type { Billing, ConfigPushResult, Money, PlanAction, PlanItem, PlanSummary, Product } from \"@purpleturret/sdk\";\n\nimport type { Palette } from \"./output\";\n\nexport const PRICE_AMOUNT_NOTE = \"new Stripe price; existing subscriptions keep the old price\";\n\nconst ACTION_ORDER: PlanAction[] = [\"conflict\", \"error\", \"create\", \"update\", \"archive\", \"unchanged\"];\n\nconst ACTION_SYMBOL: Record<PlanAction, string> = {\n create: \"+\",\n update: \"~\",\n unchanged: \"=\",\n archive: \"-\",\n conflict: \"!\",\n error: \"x\",\n};\n\nexport function formatMoney(money: Money): string {\n const currency = money.currency.toUpperCase();\n const major = (money.amount / 100).toFixed(2);\n if (currency === \"USD\") return `$${major}`;\n return `${major} ${currency}`;\n}\n\nexport function describeBilling(billing: Billing): string {\n if (billing.type === \"recurring\") return billing.interval === \"year\" ? \"/year\" : \"/month\";\n return \" one-time\";\n}\n\nexport function describeProduct(product: Pick<Product, \"name\" | \"price\" | \"billing\">): string {\n return `${product.name} — ${formatMoney(product.price)}${describeBilling(product.billing)}`;\n}\n\nexport function formatValue(value: unknown): string {\n if (value === undefined || value === null) return \"(none)\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return JSON.stringify(value);\n}\n\nfunction paintFor(action: PlanAction, palette: Palette) {\n switch (action) {\n case \"create\":\n return palette.green;\n case \"update\":\n return palette.yellow;\n case \"archive\":\n return palette.red;\n case \"conflict\":\n case \"error\":\n return (text: string | number) => palette.bold(palette.red(text));\n default:\n return palette.dim;\n }\n}\n\nexport interface RenderOptions {\n palette: Palette;\n /** `plan` renders a dry-run; `apply` renders the applied result. */\n mode: \"plan\" | \"apply\";\n}\n\n/** Render one plan item (header line plus nested change lines). */\nexport function renderPlanItem(item: PlanItem, options: RenderOptions & { keyWidth?: number }): string[] {\n const { palette } = options;\n const paint = paintFor(item.action, palette);\n const keyWidth = Math.max(options.keyWidth ?? 0, item.key.length);\n const symbol = ACTION_SYMBOL[item.action];\n const label = item.action.padEnd(9);\n const key = item.key.padEnd(keyWidth);\n\n let detail = \"\";\n if (item.action === \"create\" && item.product) detail = describeProduct(item.product);\n else if (item.action === \"unchanged\" && item.product) detail = palette.dim(describeProduct(item.product));\n else if (item.action === \"archive\" && item.product) detail = describeProduct(item.product);\n else if ((item.action === \"conflict\" || item.action === \"error\") && item.error) detail = `${item.error.code}: ${item.error.message}`;\n\n const lines = [`${paint(`${symbol} ${label}`)} ${paint(key)}${detail ? ` ${detail}` : \"\"}`.trimEnd()];\n\n if (item.changes.length === 0) return lines;\n const pathWidth = Math.max(...item.changes.map((change) => change.path.length));\n for (const change of item.changes) {\n const note = change.note ?? (change.path === \"price.amount\" && item.action !== \"create\" ? PRICE_AMOUNT_NOTE : undefined);\n const isNew = change.from === undefined || change.from === null;\n const transition =\n item.action === \"create\" || (isNew && item.action !== \"archive\")\n ? formatValue(change.to)\n : `${formatValue(change.from)} → ${formatValue(change.to)}`;\n const line = ` ${paint(symbol)} ${change.path.padEnd(pathWidth)} ${transition}${note ? ` ${palette.dim(`(${note})`)}` : \"\"}`;\n lines.push(line);\n }\n return lines;\n}\n\n/** Sort conflicts and errors first, then creates/updates/archives, unchanged last. */\nexport function sortPlanItems(items: PlanItem[]): PlanItem[] {\n return [...items].sort((a, b) => {\n const order = ACTION_ORDER.indexOf(a.action) - ACTION_ORDER.indexOf(b.action);\n return order !== 0 ? order : a.key.localeCompare(b.key);\n });\n}\n\nexport function hasChanges(summary: PlanSummary): boolean {\n return summary.create + summary.update + summary.archive + summary.conflict + summary.error > 0;\n}\n\nexport function renderSummary(summary: PlanSummary, options: RenderOptions): string {\n const { palette, mode } = options;\n const parts: string[] = [];\n if (mode === \"plan\") {\n if (summary.create) parts.push(palette.green(`${summary.create} to create`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} to update`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} to archive`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} error${summary.error === 1 ? \"\" : \"s\"}`)));\n if (!hasChanges(summary))\n return palette.dim(`No changes. ${summary.unchanged} product${summary.unchanged === 1 ? \"\" : \"s\"} already match the config.`);\n return `Plan: ${parts.join(\", \")}.`;\n }\n if (summary.create) parts.push(palette.green(`${summary.create} created`));\n if (summary.update) parts.push(palette.yellow(`${summary.update} updated`));\n if (summary.archive) parts.push(palette.red(`${summary.archive} archived`));\n if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));\n if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? \"\" : \"s\"}`)));\n if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} failed`)));\n const prefix = summary.error || summary.conflict ? \"Apply incomplete\" : \"Apply complete\";\n return `${prefix}: ${parts.length ? parts.join(\", \") : \"nothing to do\"}.`;\n}\n\n/** Full plan/apply rendering: one block per product followed by a summary line. */\nexport function renderPlan(result: ConfigPushResult, options: RenderOptions): string[] {\n const items = sortPlanItems(result.results);\n const keyWidth = items.reduce((width, item) => Math.max(width, item.key.length), 0);\n const lines: string[] = [];\n for (const item of items) {\n lines.push(...renderPlanItem(item, { ...options, keyWidth }));\n }\n if (lines.length) lines.push(\"\");\n lines.push(renderSummary(result.summary, options));\n return lines;\n}\n","import { type Subscription } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { type: \"positional\", required: true, description: \"Subscription id\" } as const;\nconst iso = (ms: number | null) => (ms === null ? \"—\" : new Date(ms).toISOString());\n\nfunction printSubscription(ctx: CliContext, sub: Subscription): void {\n if (ctx.json) return ctx.out.printJson(sub);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"ID\", sub.id],\n [\"STATUS\", sub.status + (sub.cancelAtPeriodEnd ? \" (cancels at period end)\" : \"\")],\n [\"PROVIDER\", sub.provider],\n [\"PRODUCT\", sub.productId],\n [\"EMAIL\", sub.customer.email],\n [\"NAME\", sub.customer.name ?? palette.dim(\"—\")],\n [\"PRICE\", `${formatMoney(sub)}/${sub.interval}`],\n [\"PERIOD\", `${iso(sub.currentPeriodStart)} → ${iso(sub.currentPeriodEnd)}`],\n [\"CREATED\", iso(sub.createdAt)],\n [\"ENDED\", iso(sub.endedAt)],\n ];\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List subscriptions, newest first\" },\n args: {\n ...globalArgs,\n email: { type: \"string\", description: \"Buyer email (wins over --product)\" },\n status: { type: \"string\", description: \"incomplete | incomplete_expired | trialing | active | past_due | canceled | unpaid | paused\" },\n product: { type: \"string\", description: \"Product id (not the config key)\" },\n },\n run: defineRun(async (ctx, args) => {\n const page = await ctx\n .client()\n .subscriptions.list({ email: args.email, status: args.status as Subscription[\"status\"] | undefined, product: args.product, limit: 100 });\n if (ctx.json) return ctx.out.printJson(page);\n const { palette } = ctx.out;\n if (page.data.length === 0) return ctx.out.print(palette.dim(\"No subscriptions.\"));\n const rows = page.data.map((s) => [s.id, s.status, s.customer.email, `${formatMoney(s)}/${s.interval}`, s.productId, iso(s.currentPeriodEnd)]);\n for (const line of renderTable([\"ID\", \"STATUS\", \"EMAIL\", \"PRICE\", \"PRODUCT\", \"PERIOD END\"], rows, palette.dim)) ctx.out.print(line);\n if (page.nextCursor) ctx.out.print(palette.dim(\"More results available; use --json and the API cursor.\"));\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show a subscription\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printSubscription(ctx, await ctx.client().subscriptions.get(args.id))),\n});\n\nconst portalLink = defineCommand({\n meta: { name: \"portal-link\", description: \"Create a billing-portal link for the buyer (valid 7 days)\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => {\n const link = await ctx.client().subscriptions.portalLink(args.id);\n if (ctx.json) return ctx.out.printJson(link);\n ctx.out.print(link.url);\n ctx.out.print(ctx.out.palette.dim(`Expires ${iso(link.expiresAt)}`));\n }),\n});\n\nconst portalEmail = defineCommand({\n meta: { name: \"portal-email\", description: \"E-mail the buyer a billing-portal link\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().subscriptions.portalEmail(args.id);\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.print(\"Portal e-mail sent.\");\n }),\n});\n\nexport const subscriptions = defineCommand({\n meta: { name: \"subscriptions\", description: \"Subscriptions\" },\n args: { ...globalArgs },\n subCommands: { list, get, \"portal-link\": portalLink, \"portal-email\": portalEmail },\n});\n","import { type Customer } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List customers (one row per email, ordered by email)\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const client = ctx.client();\n const customers: Customer[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.customers.list({ cursor, limit: 100 });\n customers.push(...page.data);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n if (ctx.json) return ctx.out.printJson({ customers });\n const { palette } = ctx.out;\n if (customers.length === 0) return ctx.out.print(palette.dim(\"No customers yet.\"));\n const rows = customers.map((c) => [c.email, c.name ?? palette.dim(\"—\"), c.externalId ?? palette.dim(\"—\"), new Date(c.createdAt).toISOString()]);\n for (const line of renderTable([\"EMAIL\", \"NAME\", \"EXTERNAL ID\", \"CREATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show a customer with orders, subscriptions, credits and lifetime spend\" },\n args: { ...globalArgs, id: { type: \"positional\", required: true, description: \"E-mail address or your external id\" } },\n run: defineRun(async (ctx, args) => {\n const customer = await ctx.client().customers.get(args.id);\n if (ctx.json) return ctx.out.printJson(customer);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"EMAIL\", customer.email],\n [\"NAME\", customer.name ?? palette.dim(\"—\")],\n [\"PHONE\", customer.phone ?? palette.dim(\"—\")],\n [\"EXTERNAL\", customer.externalId ?? palette.dim(\"—\")],\n [\"STRIPE\", customer.stripeCustomerId ?? palette.dim(\"—\")],\n [\"SPEND\", customer.lifetimeSpend.map(formatMoney).join(\", \") || palette.dim(\"—\")],\n [\"ORDERS\", String(customer.orders.length)],\n [\"SUBS\", customer.subscriptions.map((s) => `${s.id} (${s.status})`).join(\", \") || palette.dim(\"—\")],\n ];\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n if (customer.credits.length) {\n ctx.out.print(\"\");\n const credits = customer.credits.map((c) => [c.meter, String(c.balance), c.expiresAt ? new Date(c.expiresAt).toISOString() : \"—\"]);\n for (const line of renderTable([\"METER\", \"BALANCE\", \"EXPIRES\"], credits, palette.dim)) ctx.out.print(line);\n }\n }),\n});\n\nexport const customers = defineCommand({\n meta: { name: \"customers\", description: \"Customers\" },\n args: { ...globalArgs },\n subCommands: { list, get },\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { formatMoney } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst checkout = defineCommand({\n meta: { name: \"checkout\", description: \"List checkout leads (buyers who started a checkout), newest first\" },\n args: {\n ...globalArgs,\n abandoned: { type: \"boolean\", description: \"Only leads not completed and idle for 30+ minutes\" },\n \"lookback-days\": { type: \"string\", description: \"Window for --abandoned, 1-180 (default 30)\" },\n },\n run: defineRun(async (ctx, args) => {\n const lookbackDays = args[\"lookback-days\"] === undefined ? undefined : Number(args[\"lookback-days\"]);\n if (lookbackDays !== undefined && !Number.isFinite(lookbackDays)) throw new Error(\"--lookback-days must be a number\");\n const { data } = await ctx.client().leads.checkout({ abandoned: Boolean(args.abandoned), lookbackDays });\n if (ctx.json) return ctx.out.printJson({ leads: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No checkout leads.\"));\n const rows = data.map((l) => [l.email ?? palette.dim(\"—\"), l.status, formatMoney(l), l.productId, new Date(l.updatedAt).toISOString()]);\n for (const line of renderTable([\"EMAIL\", \"STATUS\", \"AMOUNT\", \"PRODUCT\", \"UPDATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst pages = defineCommand({\n meta: { name: \"pages\", description: \"List e-mail leads captured by page forms, newest first\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().leads.pages();\n if (ctx.json) return ctx.out.printJson({ leads: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No page leads.\"));\n const rows = data.map((l) => [l.email, l.name ?? palette.dim(\"—\"), l.source, String(l.submissionCount), new Date(l.updatedAt).toISOString()]);\n for (const line of renderTable([\"EMAIL\", \"NAME\", \"SOURCE\", \"SUBMISSIONS\", \"UPDATED\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const leads = defineCommand({\n meta: { name: \"leads\", description: \"Checkout and page leads\" },\n args: { ...globalArgs },\n subCommands: { checkout, pages },\n});\n","import { type Pixel, type PixelKpis, type PixelRangeOptions } from \"@purpleturret/sdk\";\nimport { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport type { CliContext } from \"../lib/context\";\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst idArg = { id: { type: \"positional\", required: true, description: \"Pixel id\" } } as const;\nconst rangeArgs = {\n start: { type: \"string\", description: \"Epoch ms or ISO 8601 (default: 7 days before end)\" },\n end: { type: \"string\", description: \"Epoch ms or ISO 8601 (default: now); max 90 days\" },\n} as const;\nconst targetArgs = {\n product: { type: \"string\", description: \"Product id (give this or --page)\" },\n page: { type: \"string\", description: \"Page id (give this or --product)\" },\n} as const;\n\nconst range = (args: { start?: string; end?: string }): PixelRangeOptions => ({ start: args.start, end: args.end });\nconst target = (args: { product?: string; page?: string }) => ({ productId: args.product, pageId: args.page });\nconst hosts = (value?: string) =>\n value === undefined\n ? undefined\n : value\n .split(\",\")\n .map((h) => h.trim())\n .filter(Boolean);\nconst when = (ts: number | null | undefined) => (ts ? new Date(ts).toISOString() : \"—\");\nconst pct = (n: number) => `${(n * 100).toFixed(1)}%`;\nconst secs = (ms: number | null) => (ms === null ? \"—\" : `${(ms / 1000).toFixed(1)}s`);\nconst n = (v: number | undefined) => String(v ?? 0);\n\nfunction printTable(ctx: CliContext, headers: string[], rows: string[][]): void {\n for (const line of renderTable(headers, rows, ctx.out.palette.dim)) ctx.out.print(line);\n}\nfunction printKv(ctx: CliContext, rows: [string, string][]): void {\n const width = Math.max(...rows.map(([k]) => k.length));\n for (const [k, v] of rows) ctx.out.print(`${ctx.out.palette.dim(k.padEnd(width))} ${v}`);\n}\nfunction printPixel(ctx: CliContext, pixel: Pixel): void {\n if (ctx.json) return ctx.out.printJson(pixel);\n printKv(ctx, [\n [\"id\", pixel.id],\n [\"key\", pixel.key],\n [\"name\", pixel.name],\n [\"hosts\", pixel.allowedHosts?.join(\", \") || \"any origin\"],\n [\"checkout\", String(pixel.checkout)],\n [\"events\", pixel.declaredEvents?.join(\", \") || \"—\"],\n [\"funnels\", pixel.funnels?.map((f) => `${f.label} (${f.steps.join(\" → \")})`).join(\"; \") || \"—\"],\n [\"archived\", when(pixel.archivedAt)],\n [\"created\", when(pixel.createdAt)],\n ]);\n}\nconst kpiRow = (k: PixelKpis) => [n(k.visitors), n(k.sessions), n(k.pageviews), pct(k.bounceRate ?? 0), secs(k.avgDurationMs ?? 0)];\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List pixels\" },\n args: { ...globalArgs, all: { type: \"boolean\", description: \"Include archived pixels\" } },\n run: defineRun(async (ctx, args) => {\n const { data } = await ctx.client().pixels.list({ includeArchived: Boolean(args.all) });\n if (ctx.json) return ctx.out.printJson({ pixels: data });\n if (data.length === 0) return ctx.out.print(ctx.out.palette.dim(\"No pixels yet. Run `purpleturret pixels create --name <name>`.\"));\n const rows = data.map((p) => [\n p.id,\n p.key,\n p.name,\n p.allowedHosts?.join(\",\") ?? \"*\",\n p.checkout ? \"yes\" : \"\",\n p.archivedAt ? ctx.out.palette.red(\"archived\") : \"active\",\n ]);\n printTable(ctx, [\"ID\", \"KEY\", \"NAME\", \"HOSTS\", \"CHECKOUT\", \"STATUS\"], rows);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show one pixel\" },\n args: { ...globalArgs, ...idArg },\n run: defineRun(async (ctx, args) => printPixel(ctx, await ctx.client().pixels.get(args.id))),\n});\n\nconst create = defineCommand({\n meta: { name: \"create\", description: \"Create a pixel\" },\n args: {\n ...globalArgs,\n name: { type: \"string\", required: true, description: \"Pixel name\" },\n hosts: { type: \"string\", description: \"Comma-separated hosts allowed to send events (default: any origin)\" },\n },\n run: defineRun(async (ctx, args) => {\n const pixel = await ctx.client().pixels.create({ name: args.name, allowedHosts: hosts(args.hosts) });\n ctx.out.success(`Created pixel ${pixel.key}`);\n printPixel(ctx, pixel);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Rename a pixel, change its hosts, or make it the checkout pixel\" },\n args: {\n ...globalArgs,\n ...idArg,\n name: { type: \"string\", description: \"New name\" },\n hosts: { type: \"string\", description: \"Comma-separated allowed hosts (empty string = any origin)\" },\n checkout: { type: \"boolean\", description: \"Make this the checkout pixel (--no-checkout to unset)\" },\n archived: { type: \"boolean\", description: \"Archive (--no-archived restores)\" },\n },\n run: defineRun(async (ctx, args) => {\n const pixel = await ctx.client().pixels.update(args.id, {\n name: args.name,\n allowedHosts: hosts(args.hosts),\n checkout: args.checkout as boolean | undefined,\n archived: args.archived as boolean | undefined,\n });\n ctx.out.success(`Updated pixel ${pixel.key}`);\n printPixel(ctx, pixel);\n }),\n});\n\nconst archive = defineCommand({\n meta: { name: \"archive\", description: \"Archive a pixel (it stops accepting events)\" },\n args: { ...globalArgs, ...idArg, yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes && !unwrapPrompt(await confirm({ message: `Archive pixel ${args.id}?`, initialValue: false }))) return;\n const pixel = await ctx.client().pixels.archive(args.id);\n ctx.out.success(`Archived pixel ${pixel.key}`);\n printPixel(ctx, pixel);\n }),\n});\n\nconst attach = defineCommand({\n meta: { name: \"attach\", description: \"Attach a pixel to a product or page\" },\n args: { ...globalArgs, ...idArg, ...targetArgs },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().pixels.attach(args.id, target(args));\n ctx.json ? ctx.out.printJson(result) : ctx.out.success(`Attached ${result.pixelId} to ${result.productId ?? result.pageId}`);\n }),\n});\n\nconst detach = defineCommand({\n meta: { name: \"detach\", description: \"Detach the pixel from a product or page\" },\n args: { ...globalArgs, ...targetArgs },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().pixels.detach(target(args));\n ctx.json ? ctx.out.printJson(result) : ctx.out.success(`Detached pixel from ${result.productId ?? result.pageId}`);\n }),\n});\n\nconst stats = defineCommand({\n meta: { name: \"stats\", description: \"Visitors, sessions, pageviews and sources for a range\" },\n args: {\n ...globalArgs,\n ...idArg,\n ...rangeArgs,\n bucket: { type: \"string\", description: \"hour | day: add a per-bucket table\" },\n compare: { type: \"boolean\", description: \"Also show the prior period\" },\n },\n run: defineRun(async (ctx, args) => {\n const o = await ctx\n .client()\n .pixels.overview(args.id, { ...range(args), bucket: args.bucket as PixelRangeOptions[\"bucket\"], compare: args.compare as boolean | undefined });\n if (ctx.json) return ctx.out.printJson(o);\n const prior = (pick: (k: PixelKpis) => string) => (o.prior ? ` (prior ${pick(o.prior)})` : \"\");\n printKv(ctx, [\n [\"range\", `${when(o.start)} → ${when(o.end)}${o.truncated ? \" (truncated)\" : \"\"}`],\n [\"visitors\", `${n(o.kpis.visitors)}${prior((k) => n(k.visitors))}`],\n [\"sessions\", `${n(o.kpis.sessions)}${prior((k) => n(k.sessions))}`],\n [\"pageviews\", `${n(o.kpis.pageviews)}${prior((k) => n(k.pageviews))}`],\n [\"bounce\", `${pct(o.kpis.bounceRate ?? 0)}${prior((k) => pct(k.bounceRate ?? 0))}`],\n [\"avg session\", `${secs(o.kpis.avgDurationMs ?? 0)}${prior((k) => secs(k.avgDurationMs ?? 0))}`],\n [\"online now\", n(o.online)],\n [\n \"top sources\",\n o.sessionSources\n .slice(0, 5)\n .map((s) => `${s.source || \"direct\"} ${s.sessions}`)\n .join(\", \") || \"—\",\n ],\n [\n \"top entry\",\n o.entryPages\n .slice(0, 5)\n .map((p) => `${p.path} ${p.sessions}`)\n .join(\", \") || \"—\",\n ],\n ]);\n if (o.series.length === 0) return;\n const bucketMs = (o.end - o.start) / o.series.length;\n ctx.out.print(\"\");\n printTable(\n ctx,\n [\"BUCKET\", \"VISITORS\", \"SESSIONS\", \"PAGEVIEWS\", \"BOUNCE\", \"AVG\"],\n o.series.map((k, i) => [when(o.end - bucketMs * (o.series.length - i)), ...kpiRow(k)]),\n );\n }),\n});\n\nconst pages = defineCommand({\n meta: { name: \"pages\", description: \"Top pages by views\" },\n args: { ...globalArgs, ...idArg, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.topPages(args.id, range(args));\n if (ctx.json) return ctx.out.printJson(r);\n printTable(\n ctx,\n [\"PATH\", \"VIEWS\", \"VISITORS\", \"AVG\"],\n r.pages.map((p) => [p.path, n(p.views), n(p.visitors), secs(p.avgDurationMs)]),\n );\n }),\n});\n\nconst funnels = defineCommand({\n meta: { name: \"funnels\", description: \"Session counts per declared funnel step\" },\n args: { ...globalArgs, ...idArg, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.funnels(args.id, range(args));\n if (ctx.json) return ctx.out.printJson(r);\n if (r.funnels.length === 0) return ctx.out.print(ctx.out.palette.dim(\"No funnels declared from code.\"));\n printTable(\n ctx,\n [\"FUNNEL\", \"STEP\", \"SESSIONS\"],\n r.funnels.flatMap((f) => f.steps.map((s, i) => [i === 0 ? f.label : \"\", s.match, n(s.sessions)])),\n );\n }),\n});\n\nconst ads = defineCommand({\n meta: { name: \"ads\", description: \"Paid-traffic attribution per campaign\" },\n args: {\n ...globalArgs,\n ...idArg,\n ...rangeArgs,\n conversion: { type: \"string\", required: true, description: \"Conversion event name (e.g. purchase) or /path prefix\" },\n attribution: { type: \"string\", description: \"first | last (default last)\" },\n },\n run: defineRun(async (ctx, args) => {\n const r = await ctx\n .client()\n .pixels.adPerformance(args.id, { ...range(args), conversion: args.conversion, attribution: args.attribution as \"first\" | \"last\" | undefined });\n if (ctx.json) return ctx.out.printJson(r);\n printKv(ctx, [\n [\n \"conversions\",\n `${n(r.conversions)} (${n(r.other.conversions)} organic, ${n(r.unattributed)} unattributed)${r.truncated ? \" (truncated)\" : \"\"}`,\n ],\n [\"currency\", r.currency ?? \"—\"],\n ]);\n ctx.out.print(\"\");\n printTable(\n ctx,\n [\"SOURCE\", \"CAMPAIGN\", \"SESSIONS\", \"CONVERSIONS\", \"REVENUE\", \"SPEND\"],\n r.campaigns.map((c) => [c.source, c.campaign, n(c.sessions), n(c.conversions), c.revenue.toFixed(2), c.spend.toFixed(2)]),\n );\n }),\n});\n\nconst people = defineCommand({\n meta: { name: \"people\", description: \"Identified visitors active in the range\" },\n args: {\n ...globalArgs,\n ...idArg,\n ...rangeArgs,\n offset: { type: \"string\", description: \"People to skip (default 0)\" },\n limit: { type: \"string\", description: \"Page size, up to 100 (default 100)\" },\n },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.people(args.id, {\n ...range(args),\n offset: args.offset ? Number(args.offset) : undefined,\n limit: args.limit ? Number(args.limit) : undefined,\n });\n if (ctx.json) return ctx.out.printJson(r);\n printTable(\n ctx,\n [\"PERSON\", \"SESSIONS\", \"PAGEVIEWS\", \"SPENT\", \"LAST SEEN\", \"LAST SID\"],\n r.people.map((p) => [p.id, n(p.sessions), n(p.pageviews), `${p.spent} ${p.currency ?? \"\"}`.trim(), when(p.lastSeen), p.recent[0]?.sid ?? \"—\"]),\n );\n }),\n});\n\nconst timelineArgs = { ...idArg, sid: { type: \"positional\", required: true, description: \"Session id\" } } as const;\nconst eventRows = (events: { ts: number; name: string; path: string; props: Record<string, unknown> | null; sid?: string }[]) =>\n events.map((e) => [when(e.ts), e.sid ?? \"\", e.name, e.path, e.props ? JSON.stringify(e.props) : \"\"]);\n\nconst session = defineCommand({\n meta: { name: \"session\", description: \"Event timeline of one session\" },\n args: { ...globalArgs, ...timelineArgs },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.session(args.id, args.sid);\n if (ctx.json) return ctx.out.printJson(r);\n printTable(ctx, [\"TIME\", \"\", \"EVENT\", \"PATH\", \"PROPS\"], eventRows(r.events));\n }),\n});\n\nconst person = defineCommand({\n meta: { name: \"person\", description: \"Merged event timeline across a person's sessions\" },\n args: { ...globalArgs, ...timelineArgs, sids: { type: \"string\", description: \"Comma-separated extra session ids (max 20 in total)\" } },\n run: defineRun(async (ctx, args) => {\n const r = await ctx.client().pixels.person(args.id, args.sid, { sids: hosts(args.sids) });\n if (ctx.json) return ctx.out.printJson(r);\n printTable(ctx, [\"TIME\", \"SID\", \"EVENT\", \"PATH\", \"PROPS\"], eventRows(r.events));\n }),\n});\n\nconst spend = defineCommand({\n meta: { name: \"spend\", description: \"Record ad spend for a source/campaign over a date range\" },\n args: {\n ...globalArgs,\n ...idArg,\n source: { type: \"string\", required: true, description: \"Ad source (e.g. google)\" },\n campaign: { type: \"string\", description: \"Campaign name (default: none)\" },\n start: { type: \"string\", required: true, description: \"Epoch ms or ISO 8601\" },\n end: { type: \"string\", required: true, description: \"Epoch ms or ISO 8601 (max 90 days after start)\" },\n spend: { type: \"string\", required: true, description: \"Amount (0 clears the range)\" },\n },\n run: defineRun(async (ctx, args) => {\n const r = await ctx\n .client()\n .pixels.setAdSpend(args.id, { source: args.source, campaign: args.campaign, start: args.start, end: args.end, spend: Number(args.spend) });\n if (ctx.json) return ctx.out.printJson(r);\n ctx.out.success(`Recorded ${r.spend} for ${r.source}${r.campaign ? ` / ${r.campaign}` : \"\"} (${when(r.start)} → ${when(r.end)})`);\n }),\n});\n\nexport const pixels = defineCommand({\n meta: { name: \"pixels\", description: \"Pixels and analytics\" },\n args: { ...globalArgs },\n subCommands: { list, get, create, update, archive, attach, detach, stats, pages, funnels, ads, people, session, person, spend },\n});\n","import { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative, resolve, sep } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { contentTypeFor, type HostedPage, type PageFileInput, type PageUpdateOptions } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { id: { type: \"positional\", required: true, description: \"Page id\" } } as const;\n\nfunction printPage(ctx: CliContext, page: HostedPage): void {\n if (ctx.json) return ctx.out.printJson(page);\n const rows: [string, string][] = [\n [\"id\", page.id],\n [\"title\", page.title],\n [\"url\", page.url],\n [\"published\", String(page.published)],\n [\"files\", `${page.fileCount} (${page.totalBytes} bytes)`],\n [\"submissions\", String(page.submissionCount)],\n [\"pixel\", page.pixelId ?? \"—\"],\n [\"products\", page.linkedProductIds.join(\", \") || \"—\"],\n [\"custom domain\", page.customDomain ? `${page.customDomain.hostname} (${page.customDomain.status ?? \"unknown\"})` : \"—\"],\n [\"last deployed\", page.lastDeployedAt ? new Date(page.lastDeployedAt).toISOString() : \"never\"],\n ];\n if (page.disabled) rows.push([\"disabled\", page.disabledReason ?? \"yes\"]);\n for (const [key, value] of rows) ctx.out.print(`${ctx.out.palette.dim(key.padEnd(14))} ${value}`);\n}\n\n/** Site files under `dir`, skipping dotfiles and node_modules. */\nfunction walk(dir: string): string[] {\n return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") return [];\n const full = join(dir, entry.name);\n return entry.isDirectory() ? walk(full) : [full];\n });\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List hosted pages\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().pages.list();\n if (ctx.json) return ctx.out.printJson({ pages: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No pages yet. Run `purpleturret pages deploy <dir>` to create one.\"));\n const rows = data.map((p) => [\n p.id,\n p.title,\n p.disabled ? palette.red(\"disabled\") : p.published ? \"published\" : palette.yellow(\"draft\"),\n String(p.fileCount),\n p.url,\n ]);\n for (const line of renderTable([\"ID\", \"TITLE\", \"STATUS\", \"FILES\", \"URL\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show one hosted page\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => printPage(ctx, await ctx.client().pages.get(args.id))),\n});\n\nconst files = defineCommand({\n meta: { name: \"files\", description: \"List a page's files\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => {\n const { data } = await ctx.client().pages.files(args.id);\n if (ctx.json) return ctx.out.printJson({ files: data });\n for (const line of renderTable(\n [\"PATH\", \"SIZE\", \"TYPE\"],\n data.map((f) => [f.path, String(f.size), f.contentType]),\n ctx.out.palette.dim,\n ))\n ctx.out.print(line);\n }),\n});\n\nconst deploy = defineCommand({\n meta: { name: \"deploy\", description: \"Upload a directory as a hosted page (creates it, or replaces the files of the page with that slug)\" },\n args: {\n ...globalArgs,\n dir: { type: \"positional\", required: true, description: \"Directory containing index.html\" },\n id: { type: \"string\", description: \"Replace the files of this page instead of matching by slug\" },\n slug: { type: \"string\", description: \"Subdomain label (default: directory name)\" },\n title: { type: \"string\", description: \"Page title (default: slug)\" },\n pixel: { type: \"string\", description: \"Pixel id to attach when creating\" },\n },\n run: defineRun(async (ctx, args) => {\n const dir = resolve(ctx.cwd, args.dir);\n if (!statSync(dir, { throwIfNoEntry: false })?.isDirectory()) throw new CliError(`${args.dir} is not a directory`, EXIT.USAGE, { code: \"usage\" });\n const client = ctx.client();\n const slug = args.slug ?? basename(dir);\n const uploaded: PageFileInput[] = [];\n for (const file of walk(dir)) {\n const bytes = readFileSync(file);\n const path = relative(dir, file).split(sep).join(\"/\");\n ctx.out.debug(`upload ${path} (${bytes.byteLength} bytes)`);\n uploaded.push({ path, storageId: await client.uploads.put(bytes, contentTypeFor(path)), size: bytes.byteLength });\n }\n const existingId = args.id ?? (await client.pages.list()).data.find((p) => p.slug === slug)?.id;\n const page = existingId\n ? await client.pages.replaceFiles(existingId, uploaded)\n : await client.pages.create({ title: args.title ?? slug, slug, files: uploaded, pixelId: args.pixel });\n if (ctx.json) return ctx.out.printJson(page);\n ctx.out.success(`${existingId ? \"Updated\" : \"Created\"} ${page.title} (${uploaded.length} files)`);\n ctx.out.print(page.url);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Update a page's title, slug, linked products or submission settings\" },\n args: {\n ...globalArgs,\n ...id,\n title: { type: \"string\" },\n slug: { type: \"string\" },\n products: { type: \"string\", description: \"Comma-separated product ids to link (max 5; empty string clears)\" },\n notify: { type: \"boolean\", description: \"Email on each form submission (--no-notify to disable)\" },\n leads: { type: \"boolean\", description: \"Add submitters to leads (--no-leads to disable)\" },\n },\n run: defineRun(async (ctx, args) => {\n const patch: PageUpdateOptions = { title: args.title, slug: args.slug, notifyOnSubmission: args.notify, addToLeads: args.leads };\n if (args.products !== undefined)\n patch.linkedProductIds = args.products\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n printPage(ctx, await ctx.client().pages.update(args.id, patch));\n }),\n});\n\nconst setPublished = (published: boolean) =>\n defineCommand({\n meta: { name: published ? \"publish\" : \"unpublish\", description: published ? \"Publish a page\" : \"Unpublish a page (stops serving)\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => printPage(ctx, await ctx.client().pages.update(args.id, { published }))),\n });\n\nconst del = defineCommand({\n meta: { name: \"delete\", description: \"Delete a page and its files (archived instead when it has submissions)\" },\n args: { ...globalArgs, ...id, yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes) {\n if (!isInteractive() || ctx.json)\n throw new CliError(\"Refusing to delete without confirmation.\", EXIT.USAGE, { code: \"confirmation_required\", hint: \"Re-run with --yes.\" });\n if (!unwrapPrompt(await confirm({ message: `Delete page ${args.id}?`, initialValue: false })))\n throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n const result = await ctx.client().pages.delete(args.id);\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.success(result.archived ? `Archived ${result.page.title} (it had submissions)` : `Deleted ${result.page.title}`);\n }),\n});\n\nconst submissions = defineCommand({\n meta: { name: \"submissions\", description: \"List form submissions, newest first\" },\n args: { ...globalArgs, ...id, cursor: { type: \"string\" }, limit: { type: \"string\", description: \"Page size (default 25)\" } },\n run: defineRun(async (ctx, args) => {\n const page = await ctx.client().pages.submissions(args.id, { cursor: args.cursor, limit: args.limit ? Number(args.limit) : undefined });\n if (ctx.json) return ctx.out.printJson(page);\n const rows = page.data.map((s) => [\n new Date(s.createdAt).toISOString(),\n s.submitterEmail ?? \"—\",\n s.fields.map((f) => `${f.name}=${f.value}`).join(\" \"),\n ]);\n for (const line of renderTable([\"DATE\", \"EMAIL\", \"FIELDS\"], rows, ctx.out.palette.dim)) ctx.out.print(line);\n if (page.nextCursor) ctx.out.print(ctx.out.palette.dim(`More: --cursor ${page.nextCursor}`));\n }),\n});\n\nconst rangeArgs = {\n start: { type: \"string\", description: \"Epoch ms or ISO 8601 (default 7 days ago)\" },\n end: { type: \"string\", description: \"Epoch ms or ISO 8601 (default now)\" },\n} as const;\n\nconst visits = defineCommand({\n meta: { name: \"visits\", description: \"Visits and visitors by day\" },\n args: { ...globalArgs, ...id, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const summary = await ctx.client().pages.visits(args.id, { start: args.start, end: args.end });\n if (ctx.json) return ctx.out.printJson(summary);\n ctx.out.print(`${summary.visits} visits, ${summary.visitors} visitors`);\n for (const line of renderTable(\n [\"DAY\", \"VISITS\", \"VISITORS\"],\n summary.days.map((d) => [d.day, String(d.visits), String(d.visitors)]),\n ctx.out.palette.dim,\n ))\n ctx.out.print(line);\n }),\n});\n\nconst clicks = defineCommand({\n meta: { name: \"clicks\", description: \"Tracked clicks by day and top targets\" },\n args: { ...globalArgs, ...id, ...rangeArgs },\n run: defineRun(async (ctx, args) => {\n const summary = await ctx.client().pages.clicks(args.id, { start: args.start, end: args.end });\n if (ctx.json) return ctx.out.printJson(summary);\n ctx.out.print(`${summary.clicks} clicks, ${summary.visitors} visitors`);\n const rows = summary.topTargets.map((t) => [t.pathname, t.elementKey, t.label, String(t.clicks), String(t.visitors)]);\n for (const line of renderTable([\"PATH\", \"ELEMENT\", \"LABEL\", \"CLICKS\", \"VISITORS\"], rows, ctx.out.palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const pages = defineCommand({\n meta: { name: \"pages\", description: \"Hosted pages\" },\n args: { ...globalArgs },\n subCommands: {\n list,\n get,\n files,\n deploy,\n update,\n publish: setPublished(true),\n unpublish: setPublished(false),\n delete: del,\n submissions,\n visits,\n clicks,\n },\n});\n","import type { PageTracking, PageTrackingInput, TrackingMode } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { type CliContext, globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\ntype Section = {\n enabled?: boolean;\n mode?: string;\n pixelId?: string | null;\n measurementId?: string | null;\n hasConversionsApiToken?: boolean;\n events?: object;\n paths?: { path: string; pixelId: string; hasConversionsApiToken: boolean }[];\n};\n\n/** Print Meta and GA as label/value rows; works for account, product and page shapes. */\nfunction printTracking(ctx: CliContext, tracking: { meta: Section; googleAnalytics: Section }): void {\n const { palette } = ctx.out;\n const describe = (section: Section, id: string | null | undefined) => {\n const state = section.mode ?? (section.enabled ? \"enabled\" : \"disabled\");\n const events = Object.entries(section.events ?? {})\n .filter(([, on]) => on)\n .map(([name]) => name)\n .join(\", \");\n return `${state}${id ? ` (${id})` : \"\"}${section.hasConversionsApiToken ? \", CAPI token set\" : \"\"}${events ? palette.dim(` events: ${events}`) : \"\"}`;\n };\n ctx.out.print(`${palette.dim(\"Meta\")} ${describe(tracking.meta, tracking.meta.pixelId)}`);\n for (const p of tracking.meta.paths ?? []) {\n ctx.out.print(`${palette.dim(\" \")}${p.path} → ${p.pixelId}${p.hasConversionsApiToken ? \", CAPI token set\" : \"\"}`);\n }\n ctx.out.print(`${palette.dim(\"GA \")} ${describe(tracking.googleAnalytics, tracking.googleAnalytics.measurementId)}`);\n}\n\nconst metaArgs = {\n \"meta-pixel-id\": { type: \"string\", description: \"Meta pixel id (10–20 digits)\" },\n \"meta-token\": { type: \"string\", description: 'Meta Conversions API token (write-only; \"\" clears, omit keeps)' },\n \"ga-measurement-id\": { type: \"string\", description: \"GA4 measurement id (G-XXXXXXX)\" },\n} as const;\n\n// shortcut: event toggles are not exposed as flags (a set resets them to the all-on default); add --meta-events/--ga-events when someone asks.\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show account tracking defaults\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().tracking.get();\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n});\n\nconst set = defineCommand({\n meta: { name: \"set\", description: \"Set account tracking defaults (only the sections you pass flags for are changed)\" },\n args: {\n ...globalArgs,\n ...metaArgs,\n \"meta-enabled\": { type: \"boolean\", description: \"Enable the account Meta pixel (--no-meta-enabled removes it and its token)\" },\n \"ga-enabled\": { type: \"boolean\", description: \"Enable account Google Analytics (--no-ga-enabled removes it)\" },\n },\n run: defineRun(async (ctx, args) => {\n const metaTouched = args[\"meta-enabled\"] !== undefined || args[\"meta-pixel-id\"] !== undefined || args[\"meta-token\"] !== undefined;\n const gaTouched = args[\"ga-enabled\"] !== undefined || args[\"ga-measurement-id\"] !== undefined;\n const result = await ctx.client().tracking.set({\n meta: metaTouched\n ? { enabled: args[\"meta-enabled\"] ?? true, pixelId: args[\"meta-pixel-id\"], conversionsApiToken: args[\"meta-token\"] }\n : undefined,\n googleAnalytics: gaTouched ? { enabled: args[\"ga-enabled\"] ?? true, measurementId: args[\"ga-measurement-id\"] } : undefined,\n });\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n});\n\nconst productId = { type: \"positional\", required: true, description: \"Product id or config key\" } as const;\nconst pageId = { type: \"positional\", required: true, description: \"Page id\" } as const;\n\nconst overrideArgs = {\n ...globalArgs,\n ...metaArgs,\n id: { type: \"positional\", required: true },\n \"meta-mode\": { type: \"string\", description: \"inherit | custom | disabled (defaults to custom when a pixel id or token is given)\" },\n \"ga-mode\": { type: \"string\", description: \"inherit | custom | disabled (defaults to custom when a measurement id is given)\" },\n} as const;\n\nconst pageOverrideArgs = {\n ...overrideArgs,\n \"meta-paths\": {\n type: \"string\",\n description: 'Pages only: per-path pixels as \"/path=PIXEL_ID[:CAPI_TOKEN],…\" (\"\" clears them; an omitted token keeps the stored one)',\n },\n} as const;\n\n/** \"/ad1=123:EAAB,/ad2=456\" → [{ path, pixelId, conversionsApiToken? }]. */\nexport function parseMetaPaths(raw: string): { path: string; pixelId: string; conversionsApiToken?: string }[] {\n return raw\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map((part) => {\n const eq = part.indexOf(\"=\");\n if (eq < 1) throw new Error(`--meta-paths entry \"${part}\" must look like /path=PIXEL_ID[:CAPI_TOKEN]`);\n const [pixelId = \"\", ...token] = part.slice(eq + 1).split(\":\");\n return { path: part.slice(0, eq), pixelId, conversionsApiToken: token.length > 0 ? token.join(\":\") : undefined };\n });\n}\n\n/** The page's stored meta settings as a set input; events included, since an omitted toggle resets to its default. */\nexport function currentMetaInput(current: PageTracking[\"meta\"]): NonNullable<PageTrackingInput[\"meta\"]> {\n return { mode: current.mode, pixelId: current.pixelId ?? undefined, events: current.events };\n}\n\nfunction overrideInput(args: { [K in keyof typeof overrideArgs]?: string | boolean }) {\n const metaMode = (args[\"meta-mode\"] ?? (args[\"meta-pixel-id\"] !== undefined || args[\"meta-token\"] !== undefined ? \"custom\" : undefined)) as\n | TrackingMode\n | undefined;\n const gaMode = (args[\"ga-mode\"] ?? (args[\"ga-measurement-id\"] !== undefined ? \"custom\" : undefined)) as TrackingMode | undefined;\n return {\n meta: metaMode\n ? { mode: metaMode, pixelId: args[\"meta-pixel-id\"] as string | undefined, conversionsApiToken: args[\"meta-token\"] as string | undefined }\n : undefined,\n googleAnalytics: gaMode ? { mode: gaMode, measurementId: args[\"ga-measurement-id\"] as string | undefined } : undefined,\n };\n}\n\nconst product = defineCommand({\n meta: { name: \"product\", description: \"Per-product tracking override\" },\n args: { ...globalArgs },\n subCommands: {\n get: defineCommand({\n meta: { name: \"get\", description: \"Show a product's tracking settings (by id or config key)\" },\n args: { ...globalArgs, id: productId },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().tracking.getProduct(args.id);\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n set: defineCommand({\n meta: { name: \"set\", description: \"Set a product's tracking override (by id or config key)\" },\n args: overrideArgs,\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().tracking.setProduct(args.id, overrideInput(args));\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n },\n});\n\nconst page = defineCommand({\n meta: { name: \"page\", description: \"Per-page tracking override\" },\n args: { ...globalArgs },\n subCommands: {\n get: defineCommand({\n meta: { name: \"get\", description: \"Show a hosted page's tracking settings\" },\n args: { ...globalArgs, id: pageId },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().tracking.getPage(args.id);\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n set: defineCommand({\n meta: { name: \"set\", description: \"Set a hosted page's tracking override\" },\n args: pageOverrideArgs,\n run: defineRun(async (ctx, args) => {\n const input = overrideInput(args);\n const paths = args[\"meta-paths\"] === undefined ? undefined : parseMetaPaths(args[\"meta-paths\"]);\n let meta: PageTrackingInput[\"meta\"] = input.meta;\n if (paths !== undefined) {\n // Path overrides ride on the meta section; with no other meta flags, re-send the page's current settings.\n meta = { ...(meta ?? currentMetaInput((await ctx.client().tracking.getPage(args.id)).meta)), paths };\n }\n const result = await ctx.client().tracking.setPage(args.id, { ...input, meta });\n ctx.json ? ctx.out.printJson(result) : printTracking(ctx, result);\n }),\n }),\n },\n});\n\nexport const tracking = defineCommand({\n meta: { name: \"tracking\", description: \"Tracking defaults (Meta pixel, Google Analytics)\" },\n args: { ...globalArgs },\n subCommands: { get, set, product, page },\n});\n","import { type Domain } from \"@purpleturret/sdk\";\nimport { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { type: \"positional\", required: true, description: \"Domain id\" } as const;\n\nfunction printDomain(ctx: CliContext, domain: Domain): void {\n if (ctx.json) return ctx.out.printJson(domain);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"ID\", domain.id],\n [\"HOSTNAME\", domain.hostname],\n [\"STATUS\", domain.status],\n [\"VERIFIED\", String(domain.verified)],\n [\"DNS\", domain.dnsConfigured ? \"configured\" : \"not configured\"],\n [\"PAGE\", domain.pageId ?? palette.dim(\"—\")],\n [\"PRODUCTS\", domain.productIds.join(\", \") || palette.dim(\"—\")],\n [\"DEFAULT\", domain.defaultProductId ?? palette.dim(\"—\")],\n ];\n if (domain.lastError) rows.push([\"ERROR\", palette.red(domain.lastError)]);\n for (const [key, value] of rows) ctx.out.print(`${palette.dim(key.padEnd(9))} ${value}`);\n if (domain.dnsRecords.length) {\n ctx.out.print(\"\");\n for (const line of renderTable(\n [\"TYPE\", \"NAME\", \"VALUE\"],\n domain.dnsRecords.map((r) => [r.type, r.name, r.value]),\n palette.dim,\n ))\n ctx.out.print(line);\n }\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List custom domains\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const { data } = await ctx.client().domains.list();\n if (ctx.json) return ctx.out.printJson({ domains: data });\n const { palette } = ctx.out;\n if (data.length === 0) return ctx.out.print(palette.dim(\"No custom domains yet.\"));\n const rows = data.map((d) => [\n d.id,\n d.hostname,\n d.status === \"active\" ? \"active\" : d.status === \"error\" ? palette.red(\"error\") : palette.yellow(\"pending\"),\n d.pageId ?? palette.dim(\"—\"),\n ]);\n for (const line of renderTable([\"ID\", \"HOSTNAME\", \"STATUS\", \"PAGE\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show a custom domain and its DNS records\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printDomain(ctx, await ctx.client().domains.get(args.id))),\n});\n\nconst add = defineCommand({\n meta: { name: \"add\", description: \"Add a custom domain\" },\n args: {\n ...globalArgs,\n hostname: { type: \"positional\", required: true, description: \"Hostname, e.g. shop.example.com\" },\n \"routing-type\": { type: \"string\", description: \"DNS record hint: A or CNAME\" },\n },\n run: defineRun(async (ctx, args) => {\n const routingType = args[\"routing-type\"]?.toUpperCase();\n if (routingType !== undefined && routingType !== \"A\" && routingType !== \"CNAME\") throw new Error(\"--routing-type must be A or CNAME\");\n printDomain(ctx, await ctx.client().domains.add({ hostname: args.hostname, routingType }));\n }),\n});\n\nconst verify = defineCommand({\n meta: { name: \"verify\", description: \"Re-check DNS with the provider\" },\n args: { ...globalArgs, id },\n run: defineRun(async (ctx, args) => printDomain(ctx, await ctx.client().domains.verify(args.id))),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Attach a page, set the checkout allowlist, or set the default checkout link\" },\n args: {\n ...globalArgs,\n id,\n page: { type: \"string\", description: \"Page id to serve at /\" },\n \"no-page\": { type: \"boolean\", description: \"Detach the page\" },\n products: { type: \"string\", description: \"Comma-separated product ids (replaces the allowlist)\" },\n default: { type: \"string\", description: \"Default product id for /\" },\n \"no-default\": { type: \"boolean\", description: \"Clear the default product\" },\n },\n run: defineRun(async (ctx, args) => {\n const domain = await ctx.client().domains.update(args.id, {\n pageId: args[\"no-page\"] ? null : args.page,\n productIds:\n args.products === undefined\n ? undefined\n : args.products\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean),\n defaultProductId: args[\"no-default\"] ? null : args.default,\n });\n printDomain(ctx, domain);\n }),\n});\n\nconst remove = defineCommand({\n meta: { name: \"remove\", description: \"Remove a custom domain\" },\n args: { ...globalArgs, id, yes: { type: \"boolean\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes && !unwrapPrompt(await confirm({ message: `Remove domain ${args.id}?`, initialValue: false }))) return;\n printDomain(ctx, await ctx.client().domains.remove(args.id));\n }),\n});\n\nexport const domains = defineCommand({\n meta: { name: \"domains\", description: \"Custom domains\" },\n args: { ...globalArgs },\n subCommands: { list, get, add, verify, update, remove },\n});\n","import { confirm } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\n\n/** Print a result as JSON or as dim-label key/value rows. */\nfunction printRows(ctx: CliContext, result: unknown, rows: [string, string][]) {\n if (ctx.json) return ctx.out.printJson(result);\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) ctx.out.print(`${ctx.out.palette.dim(label.padEnd(width))} ${value}`);\n}\n\n/** Flag value or env var; fails with a usage error when neither is set. */\nfunction secret(value: unknown, env: NodeJS.ProcessEnv, flag: string, envName: string): string {\n const resolved = typeof value === \"string\" && value ? value : env[envName];\n if (!resolved) throw new CliError(`Missing --${flag} (or ${envName}).`, EXIT.USAGE, { code: \"usage\" });\n return resolved;\n}\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show the account behind the current key\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const account = await ctx.client().account.get();\n printRows(ctx, account, [\n [\"Email\", account.email],\n [\"Name\", account.name ?? ctx.out.palette.dim(\"—\")],\n [\"Stripe\", account.stripe.connected ? (account.stripe.chargesEnabled ? \"connected\" : \"connected (charges not enabled)\") : \"not connected\"],\n [\"PayPal\", account.paypal.connected ? \"connected\" : \"not connected\"],\n [\"Scopes\", account.key.scopes.join(\", \")],\n ]);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Update profile name and enabled checkout providers\" },\n args: {\n ...globalArgs,\n \"given-name\": { type: \"string\", description: \"First name\" },\n \"family-name\": { type: \"string\", description: \"Last name\" },\n stripe: { type: \"boolean\", description: \"Enable/disable Stripe at checkout (pair with --paypal/--no-paypal)\" },\n paypal: { type: \"boolean\", description: \"Enable/disable PayPal at checkout (pair with --stripe/--no-stripe)\" },\n },\n run: defineRun(async (ctx, args) => {\n const providers = args.stripe !== undefined || args.paypal !== undefined;\n if (providers && (args.stripe === undefined || args.paypal === undefined)) {\n throw new CliError(\"Pass both --stripe/--no-stripe and --paypal/--no-paypal.\", EXIT.USAGE, { code: \"usage\" });\n }\n const account = await ctx.client().account.update({\n givenName: args[\"given-name\"],\n familyName: args[\"family-name\"],\n checkoutProviders: providers ? { stripe: Boolean(args.stripe), paypal: Boolean(args.paypal) } : undefined,\n });\n printRows(ctx, account, [\n [\"Name\", [account.profile.givenName, account.profile.familyName].filter(Boolean).join(\" \") || ctx.out.palette.dim(\"—\")],\n [\"Checkout\", `stripe=${account.checkoutProviders.stripe} paypal=${account.checkoutProviders.paypal}`],\n ]);\n }),\n});\n\nconst stripeStatus = defineCommand({\n meta: { name: \"status\", description: \"Stripe connection state and outstanding requirements\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const status = await ctx.client().account.stripeStatus();\n printRows(ctx, status, [\n [\"State\", status.state],\n [\"Mode\", status.account?.connectionMode ?? ctx.out.palette.dim(\"—\")],\n [\"Charges\", String(status.account?.chargesEnabled ?? false)],\n [\"Payouts\", String(status.account?.payoutsEnabled ?? false)],\n [\"Country\", status.account?.country ?? ctx.out.palette.dim(\"—\")],\n [\"Needs\", status.items.map((item) => `${item.label} (${item.severity})`).join(\", \") || ctx.out.palette.dim(\"nothing\")],\n [\"Disabled\", status.disabledReason ?? ctx.out.palette.dim(\"—\")],\n [\"Migration\", status.migration ? `${status.migration.status} (${status.migration.phase})` : ctx.out.palette.dim(\"none\")],\n ]);\n }),\n});\n\nconst stripeOnboard = defineCommand({\n meta: { name: \"onboard\", description: \"Create a Stripe Connect onboarding link\" },\n args: {\n ...globalArgs,\n country: { type: \"string\", description: \"ISO-3166 alpha-2; required when no Stripe account exists yet\" },\n \"return-to\": { type: \"string\", description: \"Dashboard path to return to (must start with /dashboard/)\" },\n },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().account.stripeOnboardingLink({ country: args.country, returnTo: args[\"return-to\"] });\n printRows(ctx, result, [[\"URL\", result.url]]);\n }),\n});\n\nconst stripeRefresh = defineCommand({\n meta: { name: \"refresh\", description: \"Re-read capabilities from Stripe\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().account.stripeRefresh();\n printRows(ctx, result, [\n [\"Ready\", String(result.ready)],\n [\"Transfers\", result.transfersStatus],\n [\"Payouts\", String(result.payoutsEnabled)],\n [\"Disabled\", result.disabledReason ?? ctx.out.palette.dim(\"—\")],\n ]);\n }),\n});\n\nconst stripeConnectKey = defineCommand({\n meta: { name: \"connect-key\", description: \"Connect Stripe with your own API keys instead of Connect\" },\n args: {\n ...globalArgs,\n \"secret-key\": { type: \"string\", description: \"sk_/rk_ key (default: STRIPE_SECRET_KEY)\" },\n \"publishable-key\": { type: \"string\", description: \"pk_ key (default: STRIPE_PUBLISHABLE_KEY)\" },\n \"migrate-customers\": { type: \"boolean\", description: \"Also copy customers when migrating from a Connect account\" },\n },\n run: defineRun(async (ctx, args) => {\n const status = await ctx.client().account.stripeConnectApiKey({\n secretKey: secret(args[\"secret-key\"], ctx.env, \"secret-key\", \"STRIPE_SECRET_KEY\"),\n publishableKey: secret(args[\"publishable-key\"], ctx.env, \"publishable-key\", \"STRIPE_PUBLISHABLE_KEY\"),\n migration: args[\"migrate-customers\"] !== undefined ? { includeCustomers: Boolean(args[\"migrate-customers\"]) } : undefined,\n });\n printRows(ctx, status, [\n [\"State\", status.state],\n [\"Mode\", status.account?.connectionMode ?? ctx.out.palette.dim(\"—\")],\n [\"Migration\", status.migration ? `${status.migration.status} (${status.migration.phase})` : ctx.out.palette.dim(\"none\")],\n ]);\n }),\n});\n\nconst stripeBranding = defineCommand({\n meta: { name: \"branding\", description: \"Set checkout branding on the connected Stripe account\" },\n args: {\n ...globalArgs,\n \"primary-color\": { type: \"string\", description: \"Hex color, e.g. #7c3aed\" },\n \"logo-url\": { type: \"string\", description: \"https:// logo URL\" },\n },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().account.stripeBranding({ primaryColor: args[\"primary-color\"], logoUrl: args[\"logo-url\"] });\n printRows(ctx, result, [[\"Applied\", String(result.applied)]]);\n }),\n});\n\nconst stripe = defineCommand({\n meta: { name: \"stripe\", description: \"Stripe connection\" },\n args: { ...globalArgs },\n subCommands: { status: stripeStatus, onboard: stripeOnboard, refresh: stripeRefresh, \"connect-key\": stripeConnectKey, branding: stripeBranding },\n});\n\nconst paypalRows = (ctx: CliContext, status: Awaited<ReturnType<ReturnType<CliContext[\"client\"]>[\"account\"][\"paypalStatus\"]>>) =>\n printRows(ctx, status, [\n [\"State\", status.state],\n [\"Client ID\", status.account?.clientId ?? ctx.out.palette.dim(\"—\")],\n [\"Environment\", status.account?.environment ?? ctx.out.palette.dim(\"default\")],\n [\"Email\", status.account?.email ?? ctx.out.palette.dim(\"—\")],\n ]);\n\nconst paypalStatus = defineCommand({\n meta: { name: \"status\", description: \"PayPal connection state\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => paypalRows(ctx, await ctx.client().account.paypalStatus())),\n});\n\nconst paypalConnect = defineCommand({\n meta: { name: \"connect\", description: \"Connect PayPal with REST API credentials\" },\n args: {\n ...globalArgs,\n \"client-id\": { type: \"string\", description: \"PayPal client id (default: PAYPAL_CLIENT_ID)\" },\n secret: { type: \"string\", description: \"PayPal secret (default: PAYPAL_SECRET)\" },\n },\n run: defineRun(async (ctx, args) =>\n paypalRows(\n ctx,\n await ctx.client().account.paypalConnect({\n clientId: secret(args[\"client-id\"], ctx.env, \"client-id\", \"PAYPAL_CLIENT_ID\"),\n secret: secret(args.secret, ctx.env, \"secret\", \"PAYPAL_SECRET\"),\n }),\n ),\n ),\n});\n\nconst paypalDisconnect = defineCommand({\n meta: { name: \"disconnect\", description: \"Disconnect PayPal\" },\n args: { ...globalArgs, yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes) {\n const approved = unwrapPrompt(await confirm({ message: \"Disconnect PayPal? Buyers will no longer see it at checkout.\", initialValue: false }));\n if (!approved) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n paypalRows(ctx, await ctx.client().account.paypalDisconnect());\n }),\n});\n\nconst paypal = defineCommand({\n meta: { name: \"paypal\", description: \"PayPal connection\" },\n args: { ...globalArgs },\n subCommands: { status: paypalStatus, connect: paypalConnect, disconnect: paypalDisconnect },\n});\n\nconst billingPortal = defineCommand({\n meta: { name: \"billing-portal\", description: \"Open a link to manage your Purpleturret plan\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().account.billingPortal();\n printRows(ctx, result, [[\"URL\", result.url]]);\n }),\n});\n\nconst keys = defineCommand({\n meta: { name: \"keys\", description: \"List API keys on the account\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const result = await ctx.client().account.keys.list();\n ctx.out.printJson(result);\n }),\n});\n\nexport const account = defineCommand({\n meta: { name: \"account\", description: \"Account, Stripe and PayPal\" },\n args: { ...globalArgs },\n subCommands: { get, update, stripe, paypal, \"billing-portal\": billingPortal, keys },\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\nexport const support = defineCommand({\n meta: { name: \"support\", description: \"Message Purpleturret support\" },\n args: {\n ...globalArgs,\n message: { type: \"positional\", required: true, description: \"The message (10–5000 characters)\" },\n subject: { type: \"string\", description: \"Subject line (≤160 characters)\" },\n },\n run: defineRun(async (ctx, args) => {\n const result = await ctx.client().support.create({ message: args.message, subject: args.subject });\n if (ctx.json) return ctx.out.printJson(result);\n ctx.out.success(`Sent. We'll reply to your account email. (ref ${result.id})`);\n }),\n});\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { renderConfigSource, renderStarterConfig, type ConfigFormat } from \"../lib/pull-writer\";\nimport { defineRun } from \"../lib/run\";\n\nexport const init = defineCommand({\n meta: { name: \"init\", description: \"Create a purpleturret.config.ts in the current directory\" },\n args: {\n ...globalArgs,\n \"from-remote\": { type: \"boolean\", description: \"Seed the file with the products already managed on your account\" },\n force: { type: \"boolean\", description: \"Overwrite an existing config file\" },\n format: { type: \"string\", description: \"File format: ts (default) or json\" },\n },\n run: defineRun(async (ctx, args) => {\n const formatArg = (args.format ?? \"ts\").toLowerCase();\n if (formatArg !== \"ts\" && formatArg !== \"json\") {\n throw new CliError(`Unknown --format \"${args.format}\"; expected ts or json.`, EXIT.USAGE, { code: \"usage\" });\n }\n const format: ConfigFormat = formatArg;\n const target = resolve(ctx.cwd, ctx.configPath ?? `purpleturret.config.${format}`);\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --config <path> to write elsewhere.\",\n });\n }\n\n let source: string;\n let count: number;\n if (args[\"from-remote\"]) {\n const { products } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n source = renderConfigSource(inputs, format);\n count = inputs.length;\n } else {\n source = renderStarterConfig(format);\n count = 1;\n }\n await writeFile(target, source, \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ written: target, products: count, from_remote: Boolean(args[\"from-remote\"]) });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Created ${relative(ctx.cwd, target) || target}${args[\"from-remote\"] ? ` with ${count} product${count === 1 ? \"\" : \"s\"} from your account` : \"\"}`,\n );\n ctx.out.info(\"\");\n ctx.out.info(\"Next steps:\");\n if (format === \"ts\") ctx.out.info(` ${palette.dim(\"1.\")} pnpm add -D @purpleturret/sdk ${palette.dim(\"(types + helpers used by the config)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"2.\" : \"1.\")} purpleturret login ${palette.dim(\"(or set PURPLETURRET_API_KEY)\")}`);\n ctx.out.info(` ${palette.dim(format === \"ts\" ? \"3.\" : \"2.\")} purpleturret push --dry-run`);\n }),\n});\n","import type { ProductInput, PurpleturretConfig } from \"@purpleturret/sdk\";\n\nexport type ConfigFormat = \"ts\" | \"json\";\n\nconst PRODUCT_KEY_ORDER: (keyof ProductInput)[] = [\n \"key\",\n \"name\",\n \"description\",\n \"price\",\n \"billing\",\n \"slug\",\n \"group\",\n \"credits\",\n \"delivery\",\n \"checkout\",\n \"theme\",\n \"stripe\",\n \"active\",\n \"buyerEmails\",\n \"offers\",\n \"tabTitle\",\n \"trustBadge\",\n];\n\nconst IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** Serialize products into a `purpleturret.config.ts` (or `.json`) source string. */\nexport function renderConfigSource(products: ProductInput[], format: ConfigFormat = \"ts\"): string {\n if (format === \"json\") {\n const config: PurpleturretConfig = { products: products.map(orderProductKeys) };\n return `${JSON.stringify(config, null, 2)}\\n`;\n }\n\n const helpers = new Set<string>([\"defineConfig\", \"product\"]);\n const body = products.map((product) => renderProduct(product, helpers, 4)).join(\"\\n\");\n const imports = [\"defineConfig\", \"money\", \"product\", \"usd\"].filter((name) => helpers.has(name));\n const productsBlock = products.length ? `[\\n${body}\\n ]` : \"[]\";\n return [\n `import { ${imports.join(\", \")} } from \"@purpleturret/sdk\";`,\n \"\",\n \"export default defineConfig({\",\n ` products: ${productsBlock},`,\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Starter config written by `purpleturret init`. */\nexport function renderStarterConfig(format: ConfigFormat = \"ts\"): string {\n const example: ProductInput = {\n key: \"pro_monthly\",\n name: \"Pro\",\n description: \"Everything you need to get started.\",\n price: { amount: 2900, currency: \"usd\" },\n billing: { type: \"recurring\", interval: \"month\" },\n group: { key: \"my_app\", tier: { key: \"pro\", name: \"Pro\", rank: 1 } },\n delivery: { method: \"none\" },\n };\n if (format === \"json\") return renderConfigSource([example], \"json\");\n return [\n \"// Purpleturret product catalog. Push with `purpleturret push`; preview with `purpleturret push --dry-run`.\",\n \"// Docs: https://purpleturret.com/docs/cli\",\n renderConfigSource([example], \"ts\"),\n ].join(\"\\n\");\n}\n\nfunction orderProductKeys(product: ProductInput): ProductInput {\n const out: Record<string, unknown> = {};\n for (const key of PRODUCT_KEY_ORDER) {\n if (product[key] !== undefined) out[key] = product[key];\n }\n return out as unknown as ProductInput;\n}\n\nfunction renderProduct(product: ProductInput, helpers: Set<string>, indent: number): string {\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n const lines: string[] = [`${pad}product({`];\n for (const key of PRODUCT_KEY_ORDER) {\n const value = product[key];\n if (value === undefined) continue;\n let rendered: string;\n if (key === \"price\") {\n rendered = renderPrice(product.price, helpers);\n } else {\n rendered = renderValue(value, indent + 2);\n }\n lines.push(`${inner}${key}: ${rendered},`);\n }\n lines.push(`${pad}}),`);\n return lines.join(\"\\n\");\n}\n\nfunction renderPrice(price: ProductInput[\"price\"], helpers: Set<string>): string {\n if (price.currency === \"usd\") {\n helpers.add(\"usd\");\n return `usd(${formatDollars(price.amount)})`;\n }\n helpers.add(\"money\");\n return `money(${price.amount}, ${JSON.stringify(price.currency)})`;\n}\n\nfunction formatDollars(cents: number): string {\n if (cents % 100 === 0) return String(cents / 100);\n return (cents / 100).toFixed(2);\n}\n\nfunction renderKey(key: string): string {\n return IDENTIFIER.test(key) ? key : JSON.stringify(key);\n}\n\nfunction isFlat(value: unknown): boolean {\n if (Array.isArray(value)) return value.every((entry) => entry === null || typeof entry !== \"object\");\n if (value && typeof value === \"object\")\n return Object.values(value as Record<string, unknown>).every((entry) => entry === null || typeof entry !== \"object\");\n return true;\n}\n\nexport function renderValue(value: unknown, indent: number): string {\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (typeof value === \"undefined\") return \"undefined\";\n const pad = \" \".repeat(indent);\n const inner = \" \".repeat(indent + 2);\n if (Array.isArray(value)) {\n if (value.length === 0) return \"[]\";\n if (isFlat(value)) {\n const inline = `[${value.map((entry) => renderValue(entry, indent + 2)).join(\", \")}]`;\n if (inline.length + indent <= 100) return inline;\n }\n return `[\\n${value.map((entry) => `${inner}${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}]`;\n }\n if (typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(([, entry]) => entry !== undefined);\n if (entries.length === 0) return \"{}\";\n if (isFlat(value)) {\n const inline = `{ ${entries.map(([key, entry]) => `${renderKey(key)}: ${renderValue(entry, indent + 2)}`).join(\", \")} }`;\n if (inline.length + indent <= 100) return inline;\n }\n return `{\\n${entries.map(([key, entry]) => `${inner}${renderKey(key)}: ${renderValue(entry, indent + 2)},`).join(\"\\n\")}\\n${pad}}`;\n }\n return JSON.stringify(value);\n}\n","import { password } from \"@clack/prompts\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\n\nexport const login = defineCommand({\n meta: { name: \"login\", description: \"Validate a seller API key and save it to ~/.config/purpleturret/credentials.json\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n let apiKey = ctx.credentialSource === \"flag\" || ctx.credentialSource === \"env\" ? ctx.apiKey : null;\n if (!apiKey) {\n if (!isInteractive()) {\n throw new CliError(\"No API key provided and stdin is not a terminal.\", EXIT.USAGE, {\n code: \"missing_api_key\",\n hint: \"Pass --api-key <pt_sk_…> or set PURPLETURRET_API_KEY when logging in non-interactively.\",\n });\n }\n const entered = unwrapPrompt(\n await password({\n message: \"Paste your seller API key (pt_sk_…). Mint one in Dashboard → Settings → Developers.\",\n validate: (value) => (value && value.trim().length > 0 ? undefined : \"An API key is required\"),\n }),\n );\n apiKey = entered.trim();\n }\n if (apiKey.startsWith(\"pt_host_\")) {\n throw new CliError(\"That is a hosting key (pt_host_…). The CLI needs a seller key (pt_sk_…).\", EXIT.AUTH, { code: \"forbidden_key_type\" });\n }\n\n const client = ctx.clientFor(apiKey);\n const account = await client.account.get();\n const apiUrl = ctx.apiUrlSource === \"default\" ? undefined : ctx.apiUrl;\n await ctx.credentials.saveProfile(ctx.profileName, {\n apiKey,\n apiUrl,\n email: account.email,\n keyPrefix: account.key.prefix,\n scopes: account.key.scopes,\n savedAt: new Date().toISOString(),\n });\n\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, credentials_file: ctx.credentials.path, api_url: ctx.apiUrl, account });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.success(\n `Logged in as ${palette.bold(account.email)} with key ${account.key.prefix}… (scopes: ${account.key.scopes.join(\", \") || \"none\"})`,\n );\n ctx.out.info(palette.dim(`Saved profile \"${ctx.profileName}\" to ${ctx.credentials.path} (mode 0600)`));\n if (!account.stripe.connected) ctx.out.warn(\"Stripe is not connected on this account yet; `push` cannot create products until it is.\");\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\nexport const logout = defineCommand({\n meta: { name: \"logout\", description: \"Remove the saved credentials profile\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const removed = await ctx.credentials.deleteProfile(ctx.profileName);\n if (ctx.json) {\n ctx.out.printJson({ profile: ctx.profileName, removed });\n return;\n }\n if (removed) ctx.out.success(`Removed profile \"${ctx.profileName}\" from ${ctx.credentials.path}`);\n else ctx.out.warn(`No profile \"${ctx.profileName}\" in ${ctx.credentials.path}; nothing to do.`);\n }),\n});\n","import { serveStdio } from \"@modelcontextprotocol/server/stdio\";\nimport { createPurpleturretMcpServer } from \"@purpleturret/mcp\";\nimport { PurpleturretApiError } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { defineRun } from \"../lib/run\";\nimport { CLI_VERSION } from \"../version\";\n\nexport const mcp = defineCommand({\n meta: {\n name: \"mcp\",\n description: \"Run the Purpleturret MCP server over stdio for Claude Code, Cursor, Codex and other agents\",\n },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const client = ctx.client();\n // Fail fast on a rejected key; a key that merely lacks config:read still works for its own scopes.\n try {\n await client.account.get();\n } catch (error) {\n if (error instanceof PurpleturretApiError && error.status === 401) {\n throw new CliError(\"The API key was rejected.\", EXIT.AUTH, { code: \"invalid_api_key\", hint: \"Run `purpleturret login` with a valid key.\" });\n }\n if (!(error instanceof PurpleturretApiError && error.status === 403)) throw error;\n }\n ctx.out.debug(`MCP server ready (${ctx.apiUrl})`);\n const handle = serveStdio(() => createPurpleturretMcpServer(client, { version: CLI_VERSION }), {\n onerror: (error) => ctx.out.debug(`mcp: ${error.message}`),\n });\n await new Promise<void>((resolve) => {\n const stop = () => void handle.close().finally(resolve);\n process.stdin.once(\"end\", stop);\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n });\n }),\n});\n","import { McpServer, type CallToolResult, type ToolAnnotations, type ToolCallback } from \"@modelcontextprotocol/server\";\nimport { PurpleturretApiError, PurpleturretClient, SDK_VERSION } from \"@purpleturret/sdk\";\nimport type { z } from \"zod\";\n\nimport { registerCoreTools } from \"./tools/core\";\nimport { registerAccountTools } from \"./tools/account\";\nimport { registerProductsTools } from \"./tools/products\";\nimport { registerOrdersTools } from \"./tools/orders\";\nimport { registerPixelsTools } from \"./tools/pixels\";\nimport { registerPagesTools } from \"./tools/pages\";\nimport { registerTrackingTools } from \"./tools/tracking\";\nimport { registerDomainsTools } from \"./tools/domains\";\nimport { registerWebhooksTools } from \"./tools/webhooks\";\n\nexport { createMcpHandler } from \"@modelcontextprotocol/server\";\nexport { PurpleturretClient };\n\nexport interface PurpleturretMcpOptions {\n /** Reported as the MCP server version; defaults to the SDK's. */\n version?: string;\n}\n\nexport const READ: ToolAnnotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };\nexport const WRITE: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };\nexport const CREATE: ToolAnnotations = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };\nexport const DESTRUCTIVE: ToolAnnotations = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };\n\ntype ToolResult = CallToolResult;\n\nfunction text(value: unknown): ToolResult {\n return { content: [{ type: \"text\", text: typeof value === \"string\" ? value : JSON.stringify(value, null, 2) }] };\n}\n\nfunction errorText(error: unknown): ToolResult {\n const message =\n error instanceof PurpleturretApiError\n ? `${error.status} ${error.code}: ${error.message}${error.requestId ? ` (request ${error.requestId})` : \"\"}`\n : error instanceof Error\n ? error.message\n : String(error);\n return { content: [{ type: \"text\", text: message }], isError: true };\n}\n\n/** Registers one tool: the SDK call's result is JSON-stringified, API errors become `isError` results. */\nexport type ToolRegistrar = <S extends z.ZodObject>(\n name: string,\n description: string,\n schema: S,\n annotations: ToolAnnotations,\n run: (args: z.output<S>) => Promise<unknown>,\n) => void;\n\n/**\n * Builds the Purpleturret MCP server over an SDK client. Every tool proxies one seller REST API call,\n * so stdio (CLI) and the hosted endpoint behave identically.\n */\nexport function createPurpleturretMcpServer(client: PurpleturretClient, options: PurpleturretMcpOptions = {}): McpServer {\n const server = new McpServer({ name: \"purpleturret\", version: options.version ?? SDK_VERSION });\n\n const tool: ToolRegistrar = (name, description, schema, annotations, run) => {\n const cb = async (args: z.output<typeof schema>): Promise<ToolResult> => {\n try {\n return text(await run(args));\n } catch (error) {\n return errorText(error);\n }\n };\n // Generic zod objects do not unify with the SDK's StandardSchema inference; the runtime shape is identical.\n server.registerTool(name, { description, inputSchema: schema, annotations }, cb as unknown as ToolCallback<typeof schema>);\n };\n\n registerCoreTools(tool, client);\n registerAccountTools(tool, client);\n registerProductsTools(tool, client);\n registerOrdersTools(tool, client);\n registerPixelsTools(tool, client);\n registerPagesTools(tool, client);\n registerTrackingTools(tool, client);\n registerDomainsTools(tool, client);\n registerWebhooksTools(tool, client);\n\n server.registerResource(\n \"skill\",\n \"purpleturret://skill\",\n { title: \"Purpleturret agent skill\", description: \"SKILL.md: scopes, CLI, SDK, REST endpoints, MCP rules\", mimeType: \"text/markdown\" },\n async (uri) => ({\n contents: [{ uri: uri.href, mimeType: \"text/markdown\", text: await fetchText(\"https://purpleturret.com/skills/purpleturret/SKILL.md\") }],\n }),\n );\n server.registerResource(\n \"openapi\",\n \"purpleturret://openapi\",\n { title: \"Purpleturret OpenAPI\", description: \"OpenAPI 3.1 document for the seller REST API\", mimeType: \"application/json\" },\n async (uri) => ({\n contents: [{ uri: uri.href, mimeType: \"application/json\", text: await fetchText(`${client.baseUrl}/v1/openapi.json`) }],\n }),\n );\n\n return server;\n}\n\nasync function fetchText(url: string): Promise<string> {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`${url} returned ${response.status}`);\n return response.text();\n}\n","import { type CustomerSelector, type PurpleturretClient, productInputSchema } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst idOrKey = z.string().describe(\"Product id or config key\");\nconst shape = productInputSchema.shape;\nconst tier = z\n .object({ key: z.string(), name: z.string().max(80).optional(), rank: z.number().int().min(0).optional() })\n .nullable()\n .optional();\nconst bump = z.object({\n productId: z.string().describe(\"Product id or key\"),\n headline: z.string().max(80),\n description: z.string().max(240).optional(),\n});\nconst deliveryFile = z.object({\n objectKey: z.string(),\n fileName: z.string(),\n contentType: z.string().optional(),\n fileSize: z.number().int().positive(),\n});\n\nconst customer = {\n email: z.string().optional().describe(\"Buyer email; give this or externalId\"),\n externalId: z.string().optional().describe(\"Your own customer id, as passed at checkout\"),\n};\n// The SDK requires one of the two; it throws a TypeError (surfaced as isError) when both are missing.\nconst asCustomer = <T extends { email?: string; externalId?: string }>(a: T) => a as T & CustomerSelector;\n\n/** Config-as-code, credits and entitlements: the pre-parity surface. */\nexport function registerCoreTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\"get_account\", \"The seller account behind this API key: email, Stripe/PayPal status, key scopes.\", z.object({}), READ, () =>\n client.account.get(),\n );\n\n tool(\n \"list_products\",\n \"List checkout links (products). Returns a page with next_cursor.\",\n z.object({ cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional(), includeArchived: z.boolean().optional() }),\n READ,\n (a) => client.products.list(a),\n );\n tool(\"get_product\", \"Fetch one product by id or config key.\", z.object({ idOrKey }), READ, (a) => client.products.get(a.idOrKey));\n tool(\n \"create_product\",\n \"Create a checkout link (product). Needs a connected Stripe account and an active plan. Billing, currency and slug are immutable afterwards; file delivery is set with set_product_delivery.\",\n z.object({\n name: z.string().max(120),\n description: z.string().max(2000).nullable().optional(),\n price: shape.price,\n billing: shape.billing,\n slug: shape.slug.describe(\"Checkout slug (/c/<slug>); random when omitted\"),\n key: shape.key.optional().describe(\"Config key; omit for an unkeyed product\"),\n delivery: shape.delivery,\n checkout: shape.checkout,\n theme: shape.theme,\n pixelId: z.string().nullable().optional(),\n groupKey: z.string().nullable().optional().describe(\"Existing integration group key\"),\n tier,\n credits: shape.credits,\n active: z.boolean().optional(),\n buyerEmails: z.boolean().optional(),\n idempotencyKey: z.string().optional(),\n }),\n CREATE,\n ({ idempotencyKey, ...input }) => client.products.create(input, { idempotencyKey }),\n );\n tool(\n \"update_product\",\n \"Patch a product by id or key; omitted fields are untouched, null clears. `theme` and `checkout` replace their whole section. Bumps/upsells only on one-time products.\",\n z.object({\n idOrKey,\n name: z.string().max(120).optional(),\n description: z.string().max(2000).nullable().optional(),\n active: z.boolean().optional(),\n theme: shape.theme\n .unwrap()\n .extend({ logoStorageId: z.string().nullable().optional().describe(\"From an upload; null clears the logo\") })\n .optional(),\n checkout: shape.checkout,\n bumps: z.array(bump).max(3).optional().describe(\"Order bumps; [] clears\"),\n upsell: bump.nullable().optional(),\n pixelId: z.string().nullable().optional(),\n groupKey: z.string().nullable().optional().describe(\"null clears the group and tier\"),\n tier,\n credits: shape.credits.nullable(),\n buyerEmails: z.boolean().optional(),\n }),\n WRITE,\n ({ idOrKey: target, ...patch }) => client.products.update(target, patch),\n );\n tool(\n \"upsert_product\",\n \"Create or update one config-managed product by key (single-product push_config).\",\n z.object({ ...productInputSchema.shape, idempotencyKey: z.string().optional() }),\n WRITE,\n ({ key, idempotencyKey, ...input }) => client.products.upsert(key, input, { idempotencyKey }),\n );\n tool(\n \"set_product_delivery\",\n \"Set what buyers receive: none, a redirect URL, instructions text, or 1-10 files already uploaded via POST /uploads/delivery-file (give the returned objectKey/fileName/contentType/fileSize). Bytes cannot be uploaded through this tool.\",\n z.object({\n idOrKey,\n delivery: z.discriminatedUnion(\"method\", [\n ...shape.delivery.unwrap().options,\n z.object({ method: z.literal(\"file\"), files: z.array(deliveryFile).min(1).max(10) }),\n ]),\n }),\n WRITE,\n (a) => client.products.setDelivery(a.idOrKey, a.delivery),\n );\n tool(\n \"copy_product_styles\",\n \"Copy checkout layout and theme from another product (`from` is an id or key).\",\n z.object({ idOrKey, from: z.string() }),\n WRITE,\n (a) => client.products.copyStyles(a.idOrKey, { from: a.from }),\n );\n tool(\"get_product_visits\", \"Checkout page views and unique visitors for a product, total and by day.\", z.object({ idOrKey }), READ, (a) =>\n client.products.visits(a.idOrKey),\n );\n tool(\"archive_product\", \"Archive a product (never hard-deletes). Ask the user before calling.\", z.object({ idOrKey }), DESTRUCTIVE, (a) =>\n client.products.archive(a.idOrKey),\n );\n\n tool(\"get_config\", \"Read the managed product config (all keyed products) plus the count of unmanaged dashboard products.\", z.object({}), READ, () =>\n client.config.get(),\n );\n tool(\n \"push_config\",\n \"Apply a product config (upsert by key). Runs as a dry run unless confirm=true; show the plan to the user and only confirm after they approve.\",\n z.object({\n products: z.array(productInputSchema),\n prune: z.boolean().optional().describe(\"Archive keyed products missing from `products`\"),\n confirm: z.boolean().default(false),\n }),\n DESTRUCTIVE,\n (a) =>\n client.config.push({ products: a.products, prune: a.prune, dryRun: !a.confirm, idempotencyKey: a.confirm ? crypto.randomUUID() : undefined }),\n );\n\n tool(\n \"get_credit_balances\",\n \"Credit balances for a customer, optionally one meter.\",\n z.object({ ...customer, meter: z.string().optional() }),\n READ,\n (a) => client.credits.balances(asCustomer(a)),\n );\n tool(\n \"consume_credits\",\n \"Deduct credits from a customer. Fails with 402 insufficient_credits when the balance is short.\",\n z.object({ ...customer, meter: z.string(), amount: z.number().int().positive(), note: z.string().optional(), idempotencyKey: z.string() }),\n DESTRUCTIVE,\n (a) => client.credits.consume(asCustomer(a)),\n );\n tool(\n \"adjust_credits\",\n \"Grant (positive) or remove (negative) credits manually. Ask the user before removing.\",\n z.object({ ...customer, meter: z.string(), amount: z.number().int(), note: z.string().optional(), idempotencyKey: z.string().optional() }),\n DESTRUCTIVE,\n (a) => client.credits.adjust(asCustomer(a)),\n );\n tool(\n \"list_credit_ledger\",\n \"Credit ledger entries for a customer, newest first.\",\n z.object({ ...customer, cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() }),\n READ,\n (a) => client.credits.ledger(asCustomer(a)),\n );\n tool(\n \"get_entitlement\",\n \"Whether a customer has an active subscription in a product group; hasAccess=false when not.\",\n z.object({ ...customer, groupKey: z.string() }),\n READ,\n (a) => client.entitlements.get(asCustomer(a)),\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nexport function registerAccountTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\n \"update_account\",\n \"Update the seller's profile name and which checkout providers (Stripe/PayPal) buyers see; both false is stored as Stripe-only.\",\n z.object({\n givenName: z.string().max(100).optional(),\n familyName: z.string().max(100).optional(),\n checkoutProviders: z.object({ stripe: z.boolean(), paypal: z.boolean() }).optional(),\n }),\n WRITE,\n (a) => client.account.update(a),\n );\n\n tool(\n \"get_stripe_status\",\n \"Stripe connection state, outstanding requirements, account details and any running key migration.\",\n z.object({}),\n READ,\n () => client.account.stripeStatus(),\n );\n tool(\n \"create_stripe_onboarding_link\",\n \"Create a Stripe Connect onboarding URL for the seller to open in a browser. country is required when no Stripe account exists yet.\",\n z.object({\n country: z.string().length(2).optional().describe(\"ISO-3166 alpha-2\"),\n returnTo: z.string().optional().describe(\"Dashboard path starting with /dashboard/\"),\n }),\n CREATE,\n (a) => client.account.stripeOnboardingLink(a),\n );\n tool(\n \"refresh_stripe_status\",\n \"Re-read capabilities (charges, payouts, transfers) from Stripe. 404 when no Stripe account.\",\n z.object({}),\n WRITE,\n () => client.account.stripeRefresh(),\n );\n tool(\n \"connect_stripe_api_key\",\n \"Connect Stripe with the seller's own secret + publishable keys (replaces Stripe Connect). Ask the user to paste the keys; never guess them. Sandbox accounts take test-mode keys only.\",\n z.object({\n secretKey: z.string().describe(\"sk_ or rk_ key\"),\n publishableKey: z.string().describe(\"pk_ key\"),\n migration: z\n .object({ includeCustomers: z.boolean() })\n .optional()\n .describe(\"Copy the Connect catalog (and optionally customers) into the new account\"),\n }),\n WRITE,\n (a) => client.account.stripeConnectApiKey(a),\n );\n tool(\n \"set_stripe_branding\",\n \"Set checkout branding (primary color, https logo URL) on a Stripe Connect account; applied=false for API-key or platform accounts.\",\n z.object({\n primaryColor: z.string().optional().describe(\"Hex color\"),\n logoUrl: z.string().url().optional().describe(\"Must start with https://\"),\n }),\n WRITE,\n (a) => client.account.stripeBranding(a),\n );\n\n tool(\"get_paypal_status\", \"PayPal connection state and account details (never the secret).\", z.object({}), READ, () =>\n client.account.paypalStatus(),\n );\n tool(\n \"connect_paypal\",\n \"Connect PayPal with REST API client id + secret. Ask the user to paste the keys; never guess them.\",\n z.object({ clientId: z.string(), secret: z.string() }),\n WRITE,\n (a) => client.account.paypalConnect(a),\n );\n tool(\"disconnect_paypal\", \"Disconnect PayPal so buyers no longer see it at checkout. Ask the user before calling.\", z.object({}), DESTRUCTIVE, () =>\n client.account.paypalDisconnect(),\n );\n\n tool(\n \"create_billing_portal_link\",\n \"Create a Stripe billing-portal URL for the seller's own Purpleturret plan (not their connected account); fails before any plan purchase.\",\n z.object({}),\n CREATE,\n () => client.account.billingPortal(),\n );\n tool(\n \"create_support_request\",\n \"Send a message to Purpleturret support, filed under the account's email.\",\n z.object({ subject: z.string().max(160).optional(), message: z.string().min(10).max(5000), idempotencyKey: z.string().optional() }),\n CREATE,\n (a) => client.support.create(a),\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\n\nimport type { ToolRegistrar } from \"../index\";\n\nexport function registerProductsTools(_tool: ToolRegistrar, _client: PurpleturretClient): void {}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, type ToolRegistrar } from \"../index\";\n\nconst page = { cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() };\nconst orderStatus = z.enum([\"pending\", \"paid\", \"failed\", \"refunded\", \"partially_refunded\"]);\nconst subscriptionStatus = z.enum([\"incomplete\", \"incomplete_expired\", \"trialing\", \"active\", \"past_due\", \"canceled\", \"unpaid\", \"paused\"]);\n\nexport function registerOrdersTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n const orderId = z.string().describe(\"Order id\");\n const subscriptionId = z.string().describe(\"Subscription id\");\n\n tool(\n \"list_orders\",\n \"List orders newest first, optionally filtered by buyer email (exact, case-insensitive) and status. Returns a page with nextCursor.\",\n z.object({ email: z.string().optional(), status: orderStatus.optional(), ...page }),\n READ,\n (a) => client.orders.list(a),\n );\n tool(\"get_order\", \"Get one order with line items, refund and upsell state.\", z.object({ id: orderId }), READ, (a) => client.orders.get(a.id));\n tool(\n \"refund_order\",\n \"Refund an order's main charge, upsell charge, or both through Stripe/PayPal; cannot be undone. Ask the user before calling.\",\n z.object({\n id: orderId,\n reason: z.enum([\"requested_by_customer\", \"duplicate\", \"fraudulent\", \"other\"]),\n scope: z.enum([\"main\", \"upsell\", \"all\"]).optional().describe(\"Default all\"),\n customReason: z.string().max(500).optional().describe(\"Only stored when reason is other\"),\n }),\n DESTRUCTIVE,\n ({ id, ...options }) => client.orders.refund(id, options),\n );\n\n tool(\n \"list_subscriptions\",\n \"List subscriptions newest first; filter by email, status (canceled = churned) or product id (ignored when email is given).\",\n z.object({\n email: z.string().optional(),\n status: subscriptionStatus.optional(),\n product: z.string().optional().describe(\"Product id, not the config key\"),\n ...page,\n }),\n READ,\n (a) => client.subscriptions.list(a),\n );\n tool(\"get_subscription\", \"Get one subscription with its billing period and provider ids.\", z.object({ id: subscriptionId }), READ, (a) =>\n client.subscriptions.get(a.id),\n );\n tool(\n \"create_subscription_portal_link\",\n \"Create a billing-portal link (valid 7 days) the buyer can use to manage the subscription; a new link on every call.\",\n z.object({ id: subscriptionId }),\n CREATE,\n (a) => client.subscriptions.portalLink(a.id),\n );\n tool(\n \"send_subscription_portal_email\",\n \"E-mail the buyer a billing-portal link for the subscription. Ask the user before calling.\",\n z.object({ id: subscriptionId }),\n CREATE,\n (a) => client.subscriptions.portalEmail(a.id),\n );\n\n tool(\"list_customers\", \"List customers (one row per email, ordered by email). Returns a page with nextCursor.\", z.object(page), READ, (a) =>\n client.customers.list(a),\n );\n tool(\n \"get_customer\",\n \"Get a customer by email or your own external id, with their orders, subscriptions, credit balances and lifetime spend.\",\n z.object({ id: z.string().describe(\"E-mail address or external id\") }),\n READ,\n (a) => client.customers.get(a.id),\n );\n\n tool(\n \"list_checkout_leads\",\n \"List checkout leads (buyers who started a checkout), newest first. abandoned=true returns only leads not completed and idle for 30+ minutes within lookbackDays.\",\n z.object({\n abandoned: z.boolean().optional(),\n lookbackDays: z.number().int().min(1).max(180).optional().describe(\"Default 30; only used with abandoned\"),\n }),\n READ,\n (a) => client.leads.checkout(a),\n );\n tool(\"list_page_leads\", \"List e-mail leads captured by page forms, newest first.\", z.object({}), READ, () => client.leads.pages());\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst id = z.string().describe(\"Pixel id (not its pt_px_ key)\");\nconst range = {\n start: z.union([z.number(), z.string()]).optional().describe(\"Epoch ms or ISO 8601; default 7 days before end\"),\n end: z.union([z.number(), z.string()]).optional().describe(\"Epoch ms or ISO 8601; default now. Range is capped at 90 days\"),\n};\nconst target = {\n productId: z.string().optional().describe(\"Product id; give this or pageId\"),\n pageId: z.string().optional().describe(\"Page id; give this or productId\"),\n};\n\n/** Purpleturret Pixel: site analytics, funnels, ad attribution. */\nexport function registerPixelsTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\n \"list_pixels\",\n \"List the seller's pixels (newest first); archived ones only with includeArchived.\",\n z.object({ includeArchived: z.boolean().optional() }),\n READ,\n (a) => client.pixels.list(a),\n );\n tool(\"get_pixel\", \"Fetch one pixel: snippet key, allowed hosts, declared events and funnels.\", z.object({ id }), READ, (a) =>\n client.pixels.get(a.id),\n );\n tool(\n \"create_pixel\",\n \"Create a pixel. allowedHosts restricts which sites may send events (omit for any origin).\",\n z.object({ name: z.string(), allowedHosts: z.array(z.string()).optional() }),\n CREATE,\n (a) => client.pixels.create(a),\n );\n tool(\n \"update_pixel\",\n \"Update a pixel's name or allowed hosts, or make it the checkout pixel (checkout=true unsets the others).\",\n z.object({\n id,\n name: z.string().optional(),\n allowedHosts: z.array(z.string()).optional(),\n checkout: z.boolean().optional(),\n }),\n WRITE,\n ({ id, ...patch }) => client.pixels.update(id, patch),\n );\n tool(\"archive_pixel\", \"Archive a pixel; it stops accepting events. Ask the user before calling.\", z.object({ id }), DESTRUCTIVE, (a) =>\n client.pixels.archive(a.id),\n );\n tool(\n \"attach_pixel\",\n \"Attach a pixel to exactly one product or page so its checkout/page fires the pixel.\",\n z.object({ id, ...target }),\n WRITE,\n ({ id, ...t }) => client.pixels.attach(id, t),\n );\n tool(\"detach_pixel\", \"Detach the pixel from exactly one product or page. Ask the user before calling.\", z.object(target), DESTRUCTIVE, (a) =>\n client.pixels.detach(a),\n );\n\n tool(\n \"get_pixel_overview\",\n \"Site analytics for a range: KPIs (visitors, sessions, pageviews, bounce), optional time series (bucket) and prior-period comparison, top entry/exit pages, devices, countries, sources, referrers, recent sessions.\",\n z.object({\n id,\n ...range,\n bucket: z.enum([\"hour\", \"day\"]).optional().describe(\"Adds a time series; hour needs a range of 400 hours or fewer\"),\n compare: z.boolean().optional(),\n }),\n READ,\n ({ id, ...r }) => client.pixels.overview(id, r),\n );\n tool(\n \"get_pixel_top_pages\",\n \"Top pages by views for a range, with visitors and average time on page.\",\n z.object({ id, ...range }),\n READ,\n ({ id, ...r }) => client.pixels.topPages(id, r),\n );\n tool(\n \"get_pixel_funnels\",\n \"Step-by-step session counts for every funnel the site declared from code.\",\n z.object({ id, ...range }),\n READ,\n ({ id, ...r }) => client.pixels.funnels(id, r),\n );\n tool(\n \"get_pixel_ad_performance\",\n \"Paid-traffic attribution: sessions, conversions and revenue per utm combination and per campaign (with recorded spend). conversion is an event name such as purchase or a /path prefix; candidates lists the declared options.\",\n z.object({ id, ...range, conversion: z.string(), attribution: z.enum([\"first\", \"last\"]).optional() }),\n READ,\n ({ id, ...o }) => client.pixels.adPerformance(id, o),\n );\n tool(\n \"get_pixel_people\",\n \"Identified visitors (by external id, email or cookie) active in the range, with spend and recent sessions. Paged: total counts everyone, offset/limit pick the page.\",\n z.object({\n id,\n ...range,\n offset: z.number().int().min(0).optional().describe(\"People to skip, most recently seen first\"),\n limit: z.number().int().min(1).max(100).optional().describe(\"Page size; default 100\"),\n }),\n READ,\n ({ id, ...r }) => client.pixels.people(id, r),\n );\n tool(\n \"get_pixel_session\",\n \"The event timeline (pageviews, clicks, custom events) of one session id.\",\n z.object({ id, sid: z.string() }),\n READ,\n (a) => client.pixels.session(a.id, a.sid),\n );\n tool(\n \"get_pixel_person\",\n \"Merged event timeline across a person's sessions: the given sid plus any extra sids (max 20).\",\n z.object({ id, sid: z.string(), sids: z.array(z.string()).optional() }),\n READ,\n (a) => client.pixels.person(a.id, a.sid, { sids: a.sids }),\n );\n tool(\n \"set_pixel_ad_spend\",\n \"Record ad spend for a source/campaign over a date range (spread evenly per UTC day; spend 0 clears it) so ad performance can report ROI.\",\n z.object({\n id,\n source: z.string(),\n campaign: z.string().optional(),\n start: z.union([z.number(), z.string()]),\n end: z.union([z.number(), z.string()]),\n spend: z.number().min(0),\n }),\n WRITE,\n ({ id, ...input }) => client.pixels.setAdSpend(id, input),\n );\n}\n","import { contentTypeFor, type PageFileInput, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst fileInput = z.object({ path: z.string(), storageId: z.string(), size: z.number().int().min(0) });\nconst range = {\n start: z.union([z.string(), z.number()]).optional().describe(\"Epoch ms or ISO 8601; default 7 days ago\"),\n end: z.union([z.string(), z.number()]).optional(),\n};\nconst patch = {\n title: z.string().optional(),\n slug: z.string().optional(),\n published: z.boolean().optional(),\n linkedProductIds: z.array(z.string()).optional().describe(\"Seller's own product ids; first 5 kept, [] clears\"),\n notifyOnSubmission: z.boolean().optional(),\n addToLeads: z.boolean().optional(),\n};\n\nexport function registerPagesTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\"list_pages\", \"List hosted pages (static sites) on the account, newest first.\", z.object({}), READ, () => client.pages.list());\n tool(\"get_page\", \"Fetch one hosted page by id.\", z.object({ id: z.string() }), READ, (a) => client.pages.get(a.id));\n tool(\"list_page_files\", \"List the files of a hosted page (path, size, content type).\", z.object({ id: z.string() }), READ, (a) =>\n client.pages.files(a.id),\n );\n tool(\n \"check_page_slug\",\n \"Check whether a page slug (subdomain) is available; pass exclude to ignore a page's own slug when renaming.\",\n z.object({ slug: z.string(), exclude: z.string().optional().describe(\"Page id whose current slug to ignore\") }),\n READ,\n (a) => client.pages.slugAvailable(a.slug, { exclude: a.exclude }),\n );\n tool(\n \"create_page\",\n \"Create a hosted page from already-uploaded files (storage ids from create_upload/put); must include a root index.html. Prefer deploy_page when you have the file contents.\",\n z.object({\n title: z.string(),\n slug: z.string(),\n files: z.array(fileInput),\n pixelId: z.string().optional(),\n idempotencyKey: z.string().optional(),\n }),\n CREATE,\n (a) => client.pages.create(a),\n );\n tool(\n \"replace_page_files\",\n \"Replace all files of a hosted page with already-uploaded files; old files are deleted.\",\n z.object({ id: z.string(), files: z.array(fileInput) }),\n WRITE,\n (a) => client.pages.replaceFiles(a.id, a.files),\n );\n tool(\n \"update_page\",\n \"Update a hosted page: title, slug, published, linked products, submission settings.\",\n z.object({ id: z.string(), ...patch }),\n WRITE,\n ({ id, ...p }) => client.pages.update(id, p),\n );\n tool(\n \"delete_page\",\n \"Delete a hosted page and its files (archived instead when it has form submissions). Ask the user before calling.\",\n z.object({ id: z.string() }),\n DESTRUCTIVE,\n (a) => client.pages.delete(a.id),\n );\n tool(\n \"list_page_submissions\",\n \"List form submissions for a hosted page, newest first. Returns a page with nextCursor.\",\n z.object({ id: z.string(), cursor: z.string().optional(), limit: z.number().int().min(1).max(100).optional() }),\n READ,\n (a) => client.pages.submissions(a.id, a),\n );\n tool(\n \"get_page_visits\",\n \"Visits and visitors for a hosted page by day (default last 7 days, max 90).\",\n z.object({ id: z.string(), ...range }),\n READ,\n (a) => client.pages.visits(a.id, a),\n );\n tool(\n \"get_page_clicks\",\n \"Tracked clicks for a hosted page by day plus top targets (default last 7 days, max 90).\",\n z.object({ id: z.string(), ...range }),\n READ,\n (a) => client.pages.clicks(a.id, a),\n );\n tool(\n \"deploy_page\",\n \"Upload file contents and create the hosted page, or replace the files of the existing page with that slug. Must include index.html. Use base64 encoding for binary files.\",\n z.object({\n title: z.string(),\n slug: z.string(),\n files: z.array(z.object({ path: z.string(), content: z.string(), encoding: z.enum([\"utf8\", \"base64\"]).default(\"utf8\") })),\n pixelId: z.string().optional(),\n }),\n CREATE,\n async (a) => {\n const files: PageFileInput[] = [];\n for (const file of a.files) {\n const bytes = Buffer.from(file.content, file.encoding);\n files.push({ path: file.path, storageId: await client.uploads.put(bytes, contentTypeFor(file.path)), size: bytes.byteLength });\n }\n const existing = (await client.pages.list()).data.find((p) => p.slug === a.slug);\n return existing\n ? client.pages.replaceFiles(existing.id, files)\n : client.pages.create({ title: a.title, slug: a.slug, files, pixelId: a.pixelId });\n },\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst TOKEN =\n 'The Meta Conversions API token is write-only (reads only report hasConversionsApiToken). Ask the user to paste the value; never guess it. Omit/null keeps the stored token, \"\" clears it.';\nconst SECTIONS =\n \"Each section (meta, googleAnalytics) is optional; a present section fully replaces that section and omitted event toggles default to true.\";\n\nconst mode = z.enum([\"inherit\", \"custom\", \"disabled\"]);\nconst eventsMode = z.enum([\"inherit\", \"custom\"]).optional();\nconst pixelId = z.string().optional().describe(\"Meta pixel id, 10–20 digits; required when enabled/custom\");\nconst token = z.string().nullable().optional().describe(\"Meta Conversions API token (write-only)\");\nconst measurementId = z.string().optional().describe(\"GA4 measurement id, G-XXXXXXX; required when enabled/custom\");\nconst metaEvents = z\n .object({ viewContent: z.boolean().optional(), initiateCheckout: z.boolean().optional(), purchase: z.boolean().optional() })\n .optional();\nconst gaEvents = z.object({ viewItem: z.boolean().optional(), beginCheckout: z.boolean().optional(), purchase: z.boolean().optional() }).optional();\n\nconst accountInput = z.object({\n meta: z\n .object({\n enabled: z.boolean().describe(\"false deletes the account pixel and its token\"),\n pixelId,\n conversionsApiToken: token,\n events: metaEvents,\n })\n .optional(),\n googleAnalytics: z.object({ enabled: z.boolean(), measurementId, events: gaEvents }).optional(),\n});\nconst productInput = z.object({\n meta: z.object({ mode, pixelId, conversionsApiToken: token, eventsMode, events: metaEvents }).optional(),\n googleAnalytics: z.object({ mode, measurementId, eventsMode, events: gaEvents }).optional(),\n});\nconst pageInput = z.object({\n meta: z\n .object({\n mode,\n pixelId,\n conversionsApiToken: token,\n events: z.object({ lead: z.boolean().optional() }).optional(),\n paths: z\n .array(z.object({ path: z.string(), pixelId: z.string(), conversionsApiToken: z.string().optional() }))\n .optional()\n .describe(\"A different Meta pixel + token for URLs under a path prefix (e.g. /ad1). Omit to keep stored overrides; [] clears them.\"),\n })\n .optional(),\n googleAnalytics: z.object({ mode, measurementId, events: z.object({ generateLead: z.boolean().optional() }).optional() }).optional(),\n});\n\nexport function registerTrackingTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\n \"get_tracking\",\n \"Account-level tracking defaults: Meta pixel / Conversions API and Google Analytics, with event toggles.\",\n z.object({}),\n READ,\n () => client.tracking.get(),\n );\n // meta.enabled=false deletes the account pixel and its CAPI token, so this asks like a destructive tool.\n tool(\"set_tracking\", `Set account-level tracking defaults. ${SECTIONS} ${TOKEN}`, accountInput, DESTRUCTIVE, (a) => client.tracking.set(a));\n\n tool(\n \"get_product_tracking\",\n \"A product's tracking settings (inherit/custom/disabled per Meta and GA) plus the inherited account values. Takes a product id or config key.\",\n z.object({ idOrKey: z.string() }),\n READ,\n (a) => client.tracking.getProduct(a.idOrKey),\n );\n tool(\n \"set_product_tracking\",\n `Set a product's tracking override by id or config key. ${SECTIONS} mode=inherit with eventsMode=inherit removes the override. ${TOKEN}`,\n productInput.extend({ idOrKey: z.string() }),\n WRITE,\n ({ idOrKey, ...input }) => client.tracking.setProduct(idOrKey, input),\n );\n\n tool(\n \"get_page_tracking\",\n \"A hosted page's tracking settings (inherit/custom/disabled per Meta and GA, lead event toggles) plus the inherited account values.\",\n z.object({ id: z.string() }),\n READ,\n (a) => client.tracking.getPage(a.id),\n );\n tool(\n \"set_page_tracking\",\n `Set a hosted page's tracking override. ${SECTIONS} mode=inherit with the lead toggle on removes the override. ${TOKEN}`,\n pageInput.extend({ id: z.string() }),\n WRITE,\n ({ id, ...input }) => client.tracking.setPage(id, input),\n );\n}\n","import type { PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nconst id = z.string().describe(\"Domain id\");\n\nexport function registerDomainsTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n tool(\"list_domains\", \"List the seller's custom domains with status and DNS records.\", z.object({}), READ, () => client.domains.list());\n tool(\"get_domain\", \"Get one custom domain, including the DNS records the seller must create.\", z.object({ id }), READ, (a) =>\n client.domains.get(a.id),\n );\n tool(\n \"add_domain\",\n \"Add a custom domain and register it with the provider; needs an active subscription and a live key. On provider failure the row stays in status error: list, then verify or remove it.\",\n z.object({\n hostname: z.string().describe(\"e.g. shop.example.com\"),\n routingType: z.enum([\"A\", \"CNAME\"]).optional().describe(\"DNS record hint; omit to let the provider pick\"),\n }),\n CREATE,\n (a) => client.domains.add(a),\n );\n tool(\"verify_domain\", \"Re-check a domain's DNS with the provider (re-registers domains in status error).\", z.object({ id }), WRITE, (a) =>\n client.domains.verify(a.id),\n );\n tool(\n \"update_domain\",\n \"Attach a page at / (pageId, null detaches), replace the checkout allowlist (productIds, max 50), or set the default checkout link for / (defaultProductId, null clears). Omitted fields are untouched.\",\n z.object({\n id,\n pageId: z.string().nullable().optional(),\n productIds: z.array(z.string()).max(50).optional(),\n defaultProductId: z.string().nullable().optional(),\n }),\n WRITE,\n ({ id, ...options }) => client.domains.update(id, options),\n );\n tool(\"remove_domain\", \"Remove a custom domain; it stops serving immediately. Ask the user before calling.\", z.object({ id }), DESTRUCTIVE, (a) =>\n client.domains.remove(a.id),\n );\n}\n","import { groupsApi, keysApi, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { z } from \"zod\";\n\nimport { CREATE, DESTRUCTIVE, READ, WRITE, type ToolRegistrar } from \"../index\";\n\nexport function registerWebhooksTools(tool: ToolRegistrar, client: PurpleturretClient): void {\n const groups = groupsApi(client);\n const keys = keysApi(client);\n const id = z.string().describe(\"Webhook endpoint id\");\n const key = z.string().describe(\"Integration group key\");\n\n tool(\"list_webhooks\", \"List the account's outgoing webhook endpoints with their last delivery status.\", z.object({}), READ, () =>\n client.webhooks.list(),\n );\n tool(\n \"create_webhook\",\n \"Create a webhook endpoint in an integration group. The response is the only time the signing secret is returned; relay it to the user verbatim.\",\n z.object({\n groupKey: key,\n url: z.string().describe(\"HTTPS URL that receives events\"),\n description: z.string().max(80).optional(),\n idempotencyKey: z.string().optional().describe(\"Reuse to retry safely; defaults to a random UUID\"),\n }),\n CREATE,\n (a) => client.webhooks.create(a),\n );\n tool(\n \"update_webhook\",\n \"Change a webhook endpoint's URL, enabled flag or description (empty description clears it).\",\n z.object({ id, url: z.string().optional(), enabled: z.boolean().optional(), description: z.string().max(80).optional() }),\n WRITE,\n ({ id, ...patch }) => client.webhooks.update(id, patch),\n );\n tool(\n \"delete_webhook\",\n \"Delete a webhook endpoint and drop its pending deliveries. Ask the user before calling.\",\n z.object({ id }),\n DESTRUCTIVE,\n (a) => client.webhooks.delete(a.id),\n );\n tool(\"test_webhook\", \"Queue a test.event delivery to a webhook endpoint (sent asynchronously, even if disabled).\", z.object({ id }), WRITE, (a) =>\n client.webhooks.test(a.id),\n );\n\n tool(\"list_groups\", \"List the account's integration groups.\", z.object({}), READ, () => groups.list());\n tool(\n \"create_group\",\n \"Create an integration group (key: 2-64 letters, numbers, dashes, underscores; name: 1-80 chars).\",\n z.object({ key, name: z.string().min(1).max(80) }),\n CREATE,\n (a) => groups.create(a),\n );\n tool(\"update_group\", \"Rename an integration group.\", z.object({ key, name: z.string().min(1).max(80) }), WRITE, (a) =>\n groups.update(a.key, { name: a.name }),\n );\n tool(\n \"delete_group\",\n \"Delete an integration group. Also deletes its webhook endpoints, deliveries and events, and clears the group/tier on its products (they keep selling). Ask the user before calling.\",\n z.object({ key }),\n DESTRUCTIVE,\n (a) => groups.delete(a.key),\n );\n\n tool(\n \"list_api_keys\",\n \"List the account's seller API keys (prefix, name, scopes, last use); never returns secrets.\",\n z.object({ includeRevoked: z.boolean().optional() }),\n READ,\n (a) => keys.list(a),\n );\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { money, type Product, type ProductUpdateInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { describeBilling, formatMoney } from \"../lib/render\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\nimport { renderTable } from \"../lib/table\";\n\nconst id = { id: { type: \"positional\", required: true, description: \"Product id or config key\" } } as const;\n\nfunction describeDelivery(delivery: Product[\"delivery\"]): string {\n if (!delivery || delivery.method === \"none\") return \"none\";\n if (delivery.method === \"redirect\") return `redirect → ${delivery.url}`;\n if (delivery.method === \"instructions\") return \"instructions\";\n return `${delivery.fileCount} file(s)${delivery.files ? `: ${delivery.files.map((f) => f.fileName).join(\", \")}` : \"\"}`;\n}\n\nfunction printProduct(ctx: CliContext, product: Product): void {\n if (ctx.json) return ctx.out.printJson(product);\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"id\", product.id],\n [\"key\", product.key ?? palette.dim(\"(unmanaged)\")],\n [\"name\", product.name],\n [\"price\", `${formatMoney(product.price)}${describeBilling(product.billing)}`],\n [\"status\", product.archivedAt ? palette.red(\"archived\") : product.active ? \"active\" : palette.yellow(\"inactive\")],\n [\"url\", product.url ?? palette.dim(\"—\")],\n [\"delivery\", describeDelivery(product.delivery)],\n [\"pixel\", product.pixelId ?? palette.dim(\"—\")],\n ];\n for (const [label, value] of rows) ctx.out.print(`${palette.dim(label.padEnd(10))}${value}`);\n}\n\nconst list = defineCommand({\n meta: { name: \"list\", description: \"List products on the account (config-managed and dashboard-only)\" },\n args: {\n ...globalArgs,\n all: { type: \"boolean\", description: \"Include archived products\" },\n },\n run: defineRun(async (ctx, args) => {\n const client = ctx.client();\n const products: Product[] = [];\n let cursor: string | undefined;\n do {\n const page = await client.products.list({ cursor, limit: 100, includeArchived: Boolean(args.all) });\n products.push(...page.data);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n\n if (ctx.json) {\n ctx.out.printJson({ products });\n return;\n }\n const { palette } = ctx.out;\n if (products.length === 0) {\n ctx.out.print(palette.dim(\"No products yet. Run `purpleturret init` and `purpleturret push` to create some.\"));\n return;\n }\n const rows = products.map((product) => [\n product.key ?? palette.dim(\"(unmanaged)\"),\n product.name,\n `${formatMoney(product.price)}${describeBilling(product.billing)}`,\n product.archivedAt ? palette.red(\"archived\") : product.active ? \"active\" : palette.yellow(\"inactive\"),\n product.url ?? palette.dim(\"—\"),\n ]);\n for (const line of renderTable([\"KEY\", \"NAME\", \"PRICE\", \"STATUS\", \"URL\"], rows, palette.dim)) ctx.out.print(line);\n }),\n});\n\nconst get = defineCommand({\n meta: { name: \"get\", description: \"Show one product\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => printProduct(ctx, await ctx.client().products.get(args.id))),\n});\n\nconst create = defineCommand({\n meta: { name: \"create\", description: \"Create a checkout link (needs a connected Stripe account)\" },\n args: {\n ...globalArgs,\n name: { type: \"string\", required: true, description: \"Product name\" },\n price: { type: \"string\", required: true, description: \"Price in major units, e.g. 19.99\" },\n currency: { type: \"string\", default: \"usd\", description: \"3-letter ISO currency\" },\n interval: { type: \"string\", description: \"Recurring billing: month or year (default: one-time)\" },\n slug: { type: \"string\", description: \"Checkout slug (/c/<slug>); random when omitted\" },\n description: { type: \"string\" },\n key: { type: \"string\", description: \"Config key (omit for an unkeyed product)\" },\n redirect: { type: \"string\", description: \"Deliver by redirecting to this https URL\" },\n instructions: { type: \"string\", description: \"Deliver by showing these instructions\" },\n },\n run: defineRun(async (ctx, args) => {\n const major = Number(args.price);\n if (!Number.isFinite(major) || major < 0) throw new CliError(`--price must be a number (got ${args.price})`, EXIT.USAGE, { code: \"usage\" });\n const interval = args.interval as \"month\" | \"year\" | undefined;\n if (interval && interval !== \"month\" && interval !== \"year\")\n throw new CliError(\"--interval must be month or year\", EXIT.USAGE, { code: \"usage\" });\n const product = await ctx.client().products.create({\n name: args.name,\n description: args.description,\n // shortcut: assumes a 2-decimal currency; add a zero-decimal table (jpy, krw, …) when a seller asks\n price: money(Math.round((major + Number.EPSILON) * 100), args.currency),\n billing: interval ? { type: \"recurring\", interval } : { type: \"one_time\" },\n slug: args.slug,\n key: args.key,\n delivery: args.redirect\n ? { method: \"redirect\", url: args.redirect }\n : args.instructions\n ? { method: \"instructions\", instructions: args.instructions }\n : undefined,\n });\n printProduct(ctx, product);\n ctx.out.success(`Created ${product.name}${product.url ? ` → ${product.url}` : \"\"}`);\n }),\n});\n\nconst update = defineCommand({\n meta: { name: \"update\", description: \"Change a product's name, description, status, brand color or pixel\" },\n args: {\n ...globalArgs,\n ...id,\n name: { type: \"string\" },\n description: { type: \"string\", description: 'New description (\"\" clears)' },\n active: { type: \"string\", description: \"true or false\" },\n \"primary-color\": { type: \"string\", description: \"Brand color, e.g. #5F34CC\" },\n pixel: { type: \"string\", description: 'Pixel id to attach (\"\" detaches)' },\n },\n run: defineRun(async (ctx, args) => {\n const patch: ProductUpdateInput = { name: args.name };\n if (args.description !== undefined) patch.description = args.description || null;\n if (args.active !== undefined) patch.active = args.active === \"true\";\n if (args[\"primary-color\"] !== undefined) patch.theme = { primaryColor: args[\"primary-color\"] };\n if (args.pixel !== undefined) patch.pixelId = args.pixel || null;\n printProduct(ctx, await ctx.client().products.update(args.id, patch));\n }),\n});\n\nconst delivery = defineCommand({\n meta: { name: \"delivery\", description: \"Set what buyers get after paying\" },\n args: {\n ...globalArgs,\n ...id,\n redirect: { type: \"string\", description: \"https URL to send buyers to\" },\n instructions: { type: \"string\", description: \"Text shown after purchase\" },\n file: { type: \"string\", description: \"Path of a file to upload and deliver\" },\n \"content-type\": { type: \"string\", description: \"MIME type of --file (default: application/octet-stream)\" },\n },\n run: defineRun(async (ctx, args) => {\n const client = ctx.client();\n let product: Product;\n if (args.file) {\n const uploaded = await client.uploads.putDeliveryFile(await readFile(args.file), {\n fileName: basename(args.file),\n contentType: args[\"content-type\"],\n });\n product = await client.products.setDelivery(args.id, { method: \"file\", ...uploaded });\n } else if (args.redirect) product = await client.products.setDelivery(args.id, { method: \"redirect\", url: args.redirect });\n else if (args.instructions) product = await client.products.setDelivery(args.id, { method: \"instructions\", instructions: args.instructions });\n else throw new CliError(\"Pass one of --redirect, --instructions or --file\", EXIT.USAGE, { code: \"usage\" });\n printProduct(ctx, product);\n }),\n});\n\nconst copyStyles = defineCommand({\n meta: { name: \"copy-styles\", description: \"Copy checkout layout and theme from another product\" },\n args: { ...globalArgs, ...id, from: { type: \"string\", required: true, description: \"Source product id or key\" } },\n run: defineRun(async (ctx, args) => printProduct(ctx, await ctx.client().products.copyStyles(args.id, { from: args.from }))),\n});\n\nconst archive = defineCommand({\n meta: { name: \"archive\", description: \"Archive a product (closes its checkout; never hard-deletes)\" },\n args: { ...globalArgs, ...id, yes: { type: \"boolean\", alias: \"y\", description: \"Skip the confirmation prompt\" } },\n run: defineRun(async (ctx, args) => {\n if (!args.yes) {\n if (!isInteractive() || ctx.json) {\n throw new CliError(\"Refusing to archive without confirmation.\", EXIT.USAGE, { code: \"confirmation_required\", hint: \"Re-run with --yes.\" });\n }\n if (!unwrapPrompt(await confirm({ message: `Archive product ${args.id}?`, initialValue: false }))) {\n throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n }\n printProduct(ctx, await ctx.client().products.archive(args.id));\n }),\n});\n\nconst visits = defineCommand({\n meta: { name: \"visits\", description: \"Checkout page views and unique visitors, by day\" },\n args: { ...globalArgs, ...id },\n run: defineRun(async (ctx, args) => {\n const summary = await ctx.client().products.visits(args.id);\n if (ctx.json) return ctx.out.printJson(summary);\n ctx.out.print(`${summary.total} visits, ${summary.uniqueVisitors} unique visitors`);\n const rows = summary.byDay.map((day) => [day.date, String(day.visits), String(day.uniqueVisitors)]);\n for (const line of renderTable([\"DATE\", \"VISITS\", \"UNIQUE\"], rows, ctx.out.palette.dim)) ctx.out.print(line);\n }),\n});\n\nexport const products = defineCommand({\n meta: { name: \"products\", description: \"Inspect and manage products (checkout links)\" },\n args: { ...globalArgs },\n subCommands: { list, get, create, update, delivery, \"copy-styles\": copyStyles, archive, visits },\n});\n","import { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\n\nimport { productToInput, type ProductInput } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { globalArgs } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { renderConfigSource, type ConfigFormat } from \"../lib/pull-writer\";\nimport { defineRun } from \"../lib/run\";\n\nexport const pull = defineCommand({\n meta: { name: \"pull\", description: \"Write the account's config-managed products to a local config file\" },\n args: {\n ...globalArgs,\n out: { type: \"string\", description: \"Output file (default: purpleturret.config.ts; a .json extension writes JSON)\" },\n force: { type: \"boolean\", description: \"Overwrite an existing file\" },\n },\n run: defineRun(async (ctx, args) => {\n const { products, unmanagedCount } = await ctx.client().config.get();\n const inputs = products.map(productToInput).filter((input): input is ProductInput => input !== null);\n\n const out = args.out?.trim();\n if (ctx.json && !out) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: null });\n return;\n }\n\n const target = resolve(ctx.cwd, out || \"purpleturret.config.ts\");\n const format: ConfigFormat = target.endsWith(\".json\") ? \"json\" : \"ts\";\n if (existsSync(target) && !args.force) {\n throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {\n code: \"file_exists\",\n hint: \"Pass --force to overwrite it, or --out <path> to write elsewhere.\",\n });\n }\n await writeFile(target, renderConfigSource(inputs, format), \"utf8\");\n\n if (ctx.json) {\n ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: target });\n return;\n }\n ctx.out.success(`Wrote ${inputs.length} product${inputs.length === 1 ? \"\" : \"s\"} to ${relative(ctx.cwd, target) || target}`);\n if (unmanagedCount > 0) {\n ctx.out.info(\n ctx.out.palette.dim(\n `${unmanagedCount} dashboard-only product${unmanagedCount === 1 ? \"\" : \"s\"} without a key were skipped (see \\`purpleturret products list\\`).`,\n ),\n );\n }\n }),\n});\n","import { randomUUID } from \"node:crypto\";\nimport { relative } from \"node:path\";\n\nimport { confirm } from \"@clack/prompts\";\nimport { PurpleturretNetworkError, type ConfigPushResult, type ProductInput, type PurpleturretClient } from \"@purpleturret/sdk\";\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader\";\nimport { globalArgs, type CliContext } from \"../lib/context\";\nimport { CliError, EXIT } from \"../lib/errors\";\nimport { isInteractive } from \"../lib/output\";\nimport { hasChanges, renderPlan } from \"../lib/render\";\nimport { defineRun, unwrapPrompt } from \"../lib/run\";\n\nexport const push = defineCommand({\n meta: { name: \"push\", description: \"Plan and apply the local config to your Purpleturret account\" },\n args: {\n ...globalArgs,\n prune: { type: \"boolean\", description: \"Archive config-managed products that are missing from the config\" },\n \"dry-run\": { type: \"boolean\", description: \"Show the plan without applying it\" },\n yes: { type: \"boolean\", alias: \"y\", description: \"Apply without asking for confirmation (required in CI)\" },\n },\n run: defineRun(async (ctx, args) => {\n const prune = Boolean(args.prune);\n const dryRun = Boolean(args[\"dry-run\"]);\n const yes = Boolean(args.yes);\n\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const products = loaded.config.products;\n const { palette } = ctx.out;\n ctx.out.info(\n palette.dim(`Config: ${relative(ctx.cwd, loaded.path) || loaded.path} (${products.length} product${products.length === 1 ? \"\" : \"s\"})`),\n );\n\n const client = ctx.client();\n const plan = await client.config.push({ products, prune, dryRun: true });\n for (const line of renderPlan(plan, { palette, mode: \"plan\" })) ctx.out.print(line);\n\n if (plan.summary.conflict > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"conflict\", message: `${plan.summary.conflict} conflict(s); nothing applied` } });\n process.exitCode = EXIT.CONFLICT;\n return;\n }\n throw new CliError(`${plan.summary.conflict} conflict${plan.summary.conflict === 1 ? \"\" : \"s\"}; nothing was applied.`, EXIT.CONFLICT, {\n code: \"conflict\",\n hint: \"price.currency, billing, slug and stripe.priceId are immutable after create. Declare the change under a new product key and archive the old one with --prune.\",\n });\n }\n if (plan.summary.error > 0) {\n if (ctx.json) {\n ctx.out.printJson({ plan, applied: false, error: { code: \"plan_error\", message: `${plan.summary.error} product(s) cannot be applied` } });\n process.exitCode = EXIT.ERROR;\n return;\n }\n throw new CliError(`${plan.summary.error} product${plan.summary.error === 1 ? \"\" : \"s\"} cannot be applied; see the errors above.`, EXIT.ERROR, {\n code: \"plan_error\",\n });\n }\n\n if (!hasChanges(plan.summary)) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n return;\n }\n if (dryRun) {\n if (ctx.json) ctx.out.printJson({ plan, applied: false });\n else ctx.out.info(palette.dim(\"Dry run; nothing was applied. Run `purpleturret push` to apply.\"));\n return;\n }\n\n if (!yes) {\n if (!isInteractive() || ctx.json) {\n throw new CliError(\"Refusing to apply without confirmation because this is not an interactive terminal.\", EXIT.USAGE, {\n code: \"confirmation_required\",\n hint: \"Re-run with --yes to apply non-interactively, or --dry-run to only preview.\",\n });\n }\n const approved = unwrapPrompt(await confirm({ message: \"Apply these changes?\", initialValue: false }));\n if (!approved) throw new CliError(\"Aborted.\", EXIT.ABORTED, { code: \"aborted\" });\n }\n\n const idempotencyKey = `pt-push-${randomUUID()}`;\n ctx.out.debug(`Idempotency-Key ${idempotencyKey}`);\n const result = await applyWithRetry(ctx, client, { products, prune, idempotencyKey });\n\n ctx.out.print(\"\");\n for (const line of renderPlan(result, { palette, mode: \"apply\" })) ctx.out.print(line);\n if (ctx.json) ctx.out.printJson({ plan, result, applied: result.applied });\n\n if (result.summary.conflict > 0) {\n process.exitCode = EXIT.CONFLICT;\n if (!ctx.json)\n ctx.out.fail(new CliError(\"The apply hit a conflict; some products may have been applied.\", EXIT.CONFLICT, { code: \"conflict\" }));\n return;\n }\n if (result.summary.error > 0) {\n process.exitCode = EXIT.ERROR;\n if (!ctx.json) {\n ctx.out.fail(\n new CliError(\n `${result.summary.error} product${result.summary.error === 1 ? \"\" : \"s\"} failed to apply; the rest were applied.`,\n EXIT.ERROR,\n {\n code: \"apply_error\",\n hint: \"Fix the reported errors and run push again; completed steps are skipped.\",\n },\n ),\n );\n }\n return;\n }\n const urls = result.results.filter((item) => item.action === \"create\" && item.product?.url).map((item) => ` ${item.key} ${item.product?.url}`);\n if (urls.length) {\n ctx.out.info(\"\");\n ctx.out.info(palette.dim(\"Checkout links:\"));\n for (const line of urls) ctx.out.info(line);\n }\n }),\n});\n\nasync function applyWithRetry(\n ctx: CliContext,\n client: PurpleturretClient,\n options: { products: ProductInput[]; prune: boolean; idempotencyKey: string },\n): Promise<ConfigPushResult> {\n try {\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n } catch (error) {\n if (!(error instanceof PurpleturretNetworkError)) throw error;\n ctx.out.warn(`Network error while applying (${error.message}); retrying once with the same Idempotency-Key…`);\n return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });\n }\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, extname, isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { validateConfig, type PurpleturretConfig } from \"@purpleturret/sdk\";\nimport { createJiti } from \"jiti\";\n\nimport { CliError, EXIT } from \"./errors\";\n\nexport const CONFIG_FILENAMES = [\n \"purpleturret.config.ts\",\n \"purpleturret.config.mts\",\n \"purpleturret.config.js\",\n \"purpleturret.config.mjs\",\n \"purpleturret.config.json\",\n] as const;\n\nexport interface LoadedConfig {\n path: string;\n config: PurpleturretConfig;\n}\n\n/**\n * Locate the config file. An explicit path is resolved against `cwd` and must exist. Otherwise the\n * standard names are searched in `cwd` and each parent, stopping at the git root (the first\n * directory containing `.git`) or the filesystem root.\n */\nexport function findConfigFile(cwd: string, explicit?: string): string {\n if (explicit) {\n const path = isAbsolute(explicit) ? explicit : resolve(cwd, explicit);\n if (!existsSync(path) || !statSync(path).isFile()) {\n throw new CliError(`Config file not found: ${path}`, EXIT.USAGE, { code: \"config_not_found\" });\n }\n return path;\n }\n\n let dir = resolve(cwd);\n const searched: string[] = [];\n for (;;) {\n searched.push(dir);\n for (const name of CONFIG_FILENAMES) {\n const candidate = join(dir, name);\n if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;\n }\n const isGitRoot = existsSync(join(dir, \".git\"));\n const parent = dirname(dir);\n if (isGitRoot || parent === dir) break;\n dir = parent;\n }\n throw new CliError(`No purpleturret.config.{ts,mts,js,mjs,json} found in ${searched[0]} or its parents up to the git root.`, EXIT.USAGE, {\n code: \"config_not_found\",\n hint: \"Run `purpleturret init` to create one, or pass --config <path>.\",\n });\n}\n\n/** Load and validate a config file. TypeScript/ESM files are transpiled on the fly with jiti. */\nexport async function loadConfigFile(path: string): Promise<LoadedConfig> {\n const raw = await importConfigModule(path);\n const candidate = pickConfigExport(raw, path);\n const config = validateConfig(candidate);\n return { path, config };\n}\n\nexport async function loadConfig(cwd: string, explicit?: string): Promise<LoadedConfig> {\n return loadConfigFile(findConfigFile(cwd, explicit));\n}\n\nasync function importConfigModule(path: string): Promise<unknown> {\n const ext = extname(path).toLowerCase();\n if (ext === \".json\") {\n const text = await readFile(path, \"utf8\");\n try {\n return JSON.parse(text);\n } catch (error) {\n throw new CliError(`${path} is not valid JSON: ${(error as Error).message}`, EXIT.USAGE, { code: \"config_invalid\", cause: error });\n }\n }\n if (![\".ts\", \".mts\", \".js\", \".mjs\", \".cts\", \".cjs\"].includes(ext)) {\n throw new CliError(`Unsupported config file extension \"${ext}\" (${path}). Use .ts, .mts, .js, .mjs or .json.`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n }\n const jiti = createJiti(import.meta.url, { interopDefault: false, moduleCache: false, fsCache: false });\n try {\n return await jiti.import(pathToFileURL(path).href);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CliError(`Failed to load ${path}: ${message}`, EXIT.USAGE, { code: \"config_load_failed\", cause: error });\n }\n}\n\nfunction pickConfigExport(raw: unknown, path: string): unknown {\n if (raw && typeof raw === \"object\") {\n const record = raw as Record<string, unknown>;\n if (\"default\" in record && record.default !== undefined) {\n const def = record.default;\n // `export default { default: ... }` interop layering\n if (def && typeof def === \"object\" && !(\"products\" in (def as object)) && \"default\" in (def as Record<string, unknown>)) {\n return (def as Record<string, unknown>).default;\n }\n return def;\n }\n if (\"config\" in record && record.config !== undefined) return record.config;\n if (\"products\" in record) return raw;\n }\n throw new CliError(`${path} must export a config as its default export or a named \\`config\\` export (see \\`purpleturret init\\`).`, EXIT.USAGE, {\n code: \"config_invalid\",\n });\n}\n","import { relative } from \"node:path\";\n\nimport { defineCommand } from \"citty\";\n\nimport { loadConfig } from \"../lib/config-loader\";\nimport { describeSource, globalArgs } from \"../lib/context\";\nimport { renderSummary, sortPlanItems } from \"../lib/render\";\nimport { defineRun } from \"../lib/run\";\n\nexport const status = defineCommand({\n meta: { name: \"status\", description: \"Compare the local config with the account (dry run) and print a summary\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const loaded = await loadConfig(ctx.cwd, ctx.configPath);\n const plan = await ctx.client().config.push({ products: loaded.config.products, dryRun: true });\n if (ctx.json) {\n ctx.out.printJson({ config: loaded.path, api_url: ctx.apiUrl, summary: plan.summary, results: plan.results });\n return;\n }\n const { palette } = ctx.out;\n ctx.out.print(`${palette.dim(\"Config\")} ${relative(ctx.cwd, loaded.path) || loaded.path} (${loaded.config.products.length} products)`);\n ctx.out.print(`${palette.dim(\"API URL\")} ${ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)}`);\n ctx.out.print(\n `${palette.dim(\"Credentials\")} ${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`,\n );\n ctx.out.print(\"\");\n for (const item of sortPlanItems(plan.results)) {\n if (item.action === \"unchanged\") continue;\n const detail = item.error ? ` ${item.error.code}: ${item.error.message}` : \"\";\n ctx.out.print(` ${item.action.padEnd(9)} ${item.key}${detail}`);\n }\n ctx.out.print(renderSummary(plan.summary, { palette, mode: \"plan\" }));\n if (plan.summary.create + plan.summary.update + plan.summary.archive > 0) ctx.out.info(palette.dim(\"Run `purpleturret push` to apply.\"));\n }),\n});\n","import { defineCommand } from \"citty\";\n\nimport { describeSource, globalArgs } from \"../lib/context\";\nimport { defineRun } from \"../lib/run\";\n\nexport const whoami = defineCommand({\n meta: { name: \"whoami\", description: \"Show the account and key behind the current credentials\" },\n args: { ...globalArgs },\n run: defineRun(async (ctx) => {\n const account = await ctx.client().account.get();\n if (ctx.json) {\n ctx.out.printJson({ account, api_url: ctx.apiUrl, credential_source: ctx.credentialSource, profile: ctx.profileName });\n return;\n }\n const { palette } = ctx.out;\n const rows: [string, string][] = [\n [\"Account\", `${account.email}${account.name ? ` (${account.name})` : \"\"}`],\n [\"Key\", `${account.key.prefix}…${account.key.name ? ` \"${account.key.name}\"` : \"\"}`],\n [\"Scopes\", account.key.scopes.join(\", \") || palette.dim(\"none\")],\n [\n \"Stripe\",\n account.stripe.connected\n ? account.stripe.chargesEnabled\n ? \"connected\"\n : \"connected (charges not enabled)\"\n : palette.yellow(\"not connected\"),\n ],\n [\"PayPal\", account.paypal.connected ? \"connected\" : palette.dim(\"not connected\")],\n [\"API URL\", ctx.apiUrlSource === \"default\" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)],\n [\"Credentials\", `${describeSource(ctx.credentialSource)}${ctx.credentialSource === \"profile\" ? ` \"${ctx.profileName}\"` : \"\"}`],\n ];\n const width = Math.max(...rows.map(([label]) => label.length));\n for (const [label, value] of rows) ctx.out.print(`${palette.dim(label.padEnd(width))} ${value}`);\n }),\n});\n","import { runCli } from \"./main\";\n\nawait runCli();\n"],"mappings":";AAAA,SAAS,iBAAAA,iBAAe,YAAY,iBAAkC;;;ACAtE,SAAS,iBAAAC,sBAAqB;;;ACA9B,SAAS,kBAAkB;AAC3B,SAAS,QAAAC,aAAY;;;ACAd,IAAM,cAAc;;;ACD3B,SAAS,SAAS;AAKX,IAAM,cAAc;AAEpB,IAAM,eAAe;AAC5B,IAAM,oBAAoB;AAE1B,IAAM,cAAc;AAEb,IAAM,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAC3D,IAAM,cAAc,EAAE,OAAO,EAAE,MAAM,aAAa,WAAW;AAE7D,IAAM,cAAc,EAAE,aAAa;AAAA,EACxC,QAAQ,EACL,OAAO,sEAAsE,EAC7E,IAAI,sEAAsE,EAC1E,IAAI,IAAI,+DAA+D;AAAA,EAC1E,UAAU,EACP,OAAO,EACP,KAAK,EACL,YAAY,EACZ,MAAM,cAAc,sCAAsC;AAC/D,CAAC;AAEM,IAAM,gBAAgB,EAAE,mBAAmB,QAAQ;AAAA,EACxD,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAAA,EAC9C,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,WAAW,GAAG,UAAU,EAAE,KAAK,CAAC,SAAS,MAAM,CAAC,EAAE,CAAC;AACtF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B,YAAM,UAAU,IAAI;AACpB;AAAA,IACF;AACA,UAAM,WAAW,MAAM,EAAE,QAAQ,CAAC;AAAA,EACpC,SAAS,OAAO;AACd,UAAM,QAAQ,kBAAkB,OAAO;AACvC,UAAM,MAAM,IAAI,OAAO,EAAE,MAAM,MAAM,MAAM,SAAS,MAAM,SAAS,SAAS,cAAc,eAAe,EAAE,MAAM,MAAM,MAAM,CAAC,CAAC,EAAE,CAAC;AAClI,QAAI,aAAa,KAAK,GAAG;AACvB,UAAI,KAAK,IAAI,SAAS,MAAM,SAAS,KAAK,OAAO,EAAE,MAAM,QAAQ,CAAC,CAAC;AACnE,UAAI,CAAC,MAAM,MAAM;AACf,cAAM,CAAC,KAAK,MAAM,IAAI,MAAM,kBAAkB,MAAM,OAAO;AAC3D,cAAM,UAAU,KAAK,MAAM;AAAA,MAC7B;AACA,cAAQ,WAAW,KAAK;AACxB;AAAA,IACF;AACA,UAAM,WACJ,iBAAiB,WAAW,QAAQ,IAAI,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,KAAK,OAAO,EAAE,OAAO,MAAM,CAAC;AACvI,QAAI,KAAK,QAAQ;AACjB,YAAQ,WAAW,SAAS;AAAA,EAC9B;AACF;AAEA,SAAS,kBAAkB,SAAoF;AAC7G,SAAO;AAAA,IACL,MAAM,QAAQ,SAAS,QAAQ;AAAA,IAC/B,SAAS,QAAQ,SAAS,WAAW;AAAA,IACrC,OAAO,QAAQ,SAAS,YAAY,IAAI,QAAQ;AAAA,EAClD;AACF;;;AwDxJA,MAAM,OAAO;","names":["defineCommand","defineCommand","join","product","delivery","checkout","product","tier","stripe","patch","id","range","target","id","patch","files","id","patch","idOrKey","id","id","fromWireGroup","id","patch","init","status","text","when","idOrKey","patch","delivery","text","text","text","join","init","text","list","defineCommand","update","del","confirm","defineCommand","money","product","text","mode","list","defineCommand","page","confirm","defineCommand","id","list","defineCommand","page","get","defineCommand","list","defineCommand","customers","page","get","customer","defineCommand","defineCommand","confirm","defineCommand","n","list","defineCommand","get","create","update","confirm","pages","join","confirm","defineCommand","id","page","join","list","defineCommand","get","update","patch","del","confirm","rangeArgs","pages","defineCommand","tracking","id","get","defineCommand","pixelId","token","product","confirm","defineCommand","id","list","defineCommand","get","add","update","confirm","confirm","defineCommand","get","defineCommand","account","update","status","confirm","defineCommand","defineCommand","existsSync","writeFile","relative","resolve","defineCommand","products","product","defineCommand","target","resolve","existsSync","relative","products","writeFile","defineCommand","defineCommand","account","defineCommand","defineCommand","z","z","target","patch","z","z","z","page","z","id","z","id","z","range","target","patch","z","z","range","id","files","z","z","idOrKey","id","z","id","z","z","groups","keys","id","z","patch","defineCommand","defineCommand","resolve","readFile","basename","confirm","defineCommand","id","delivery","product","list","defineCommand","products","page","get","create","update","patch","readFile","basename","archive","confirm","visits","existsSync","writeFile","relative","resolve","defineCommand","defineCommand","products","target","resolve","existsSync","relative","writeFile","relative","confirm","defineCommand","existsSync","statSync","readFile","dirname","join","resolve","resolve","existsSync","statSync","join","dirname","text","readFile","defineCommand","products","relative","confirm","relative","defineCommand","defineCommand","relative","defineCommand","defineCommand","account","defineCommand","pages","token"]}
|