@purpleturret/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,1952 @@
1
+ // src/main.ts
2
+ import { defineCommand as defineCommand9, runCommand, showUsage } from "citty";
3
+
4
+ // src/commands/init.ts
5
+ import { existsSync as existsSync2 } from "fs";
6
+ import { writeFile as writeFile2 } from "fs/promises";
7
+ import { relative, resolve } from "path";
8
+
9
+ // ../sdk/src/version.ts
10
+ var SDK_VERSION = "0.1.0";
11
+
12
+ // ../sdk/src/config/schema.ts
13
+ import { z } from "zod";
14
+ var KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
15
+ var SLUG_PATTERN = /^[a-z0-9-]{3,64}$/;
16
+ var HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
17
+ var KEY_MESSAGE = "must be 1-64 characters of lowercase letters, digits, '_' or '-', starting with a letter or digit";
18
+ var keySchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);
19
+ var meterSchema = z.string().regex(KEY_PATTERN, KEY_MESSAGE);
20
+ var moneySchema = z.strictObject({
21
+ amount: z.number("must be an integer amount in the smallest currency unit (e.g. cents)").int("must be an integer amount in the smallest currency unit (e.g. cents)").min(50, "must be at least 50 (e.g. $0.50); use usd(dollars) to convert"),
22
+ currency: z.string().trim().toLowerCase().regex(/^[a-z]{3}$/, "must be a 3-letter ISO currency code")
23
+ });
24
+ var billingSchema = z.discriminatedUnion("type", [
25
+ z.strictObject({ type: z.literal("one_time") }),
26
+ z.strictObject({ type: z.literal("recurring"), interval: z.enum(["month", "year"]) })
27
+ ]);
28
+ var tierSchema = z.strictObject({
29
+ key: keySchema,
30
+ name: z.string().trim().min(1, "must not be empty").max(80),
31
+ rank: z.number().int("must be an integer").min(0)
32
+ });
33
+ var groupSchema = z.strictObject({
34
+ key: keySchema,
35
+ tier: tierSchema.optional()
36
+ });
37
+ var creditGrantSchema = z.strictObject({
38
+ meter: meterSchema,
39
+ amount: z.number().int("must be an integer").positive("must be a positive integer"),
40
+ renewal: z.enum(["reset", "accumulate"]),
41
+ expiresAfterDays: z.number().int("must be an integer").positive("must be a positive integer").optional()
42
+ });
43
+ var deliverySchema = z.discriminatedUnion("method", [
44
+ z.strictObject({ method: z.literal("none") }),
45
+ z.strictObject({
46
+ method: z.literal("redirect"),
47
+ url: z.string().url("must be an absolute URL").refine((value) => value.startsWith("https://"), "must be an https:// URL")
48
+ }),
49
+ z.strictObject({ method: z.literal("instructions"), instructions: z.string().trim().min(1, "must not be empty").max(1e4) })
50
+ ]);
51
+ var checkoutSchema = z.strictObject({
52
+ layoutMode: z.enum(["two_step", "one_step"]).optional(),
53
+ paymentStyle: z.enum(["classic", "express"]).optional(),
54
+ providerMode: z.enum(["inherit", "stripe", "paypal", "both"]).optional(),
55
+ contactFields: z.strictObject({ name: z.boolean().optional(), phone: z.boolean().optional() }).optional()
56
+ });
57
+ var themeSchema = z.strictObject({
58
+ primaryColor: z.string().regex(HEX_COLOR_PATTERN, "must be a hex color such as #5F34CC").optional(),
59
+ buttonRadius: z.enum(["sm", "md", "lg"]).optional(),
60
+ accentMode: z.enum(["light", "dark", "system"]).optional()
61
+ });
62
+ var stripeSchema = z.strictObject({
63
+ priceId: z.string().trim().min(1, "must be a Stripe price id (price_\u2026)")
64
+ });
65
+ var productInputSchema = z.strictObject({
66
+ key: keySchema,
67
+ name: z.string().trim().min(1, "must not be empty").max(120),
68
+ description: z.string().max(5e3).optional(),
69
+ price: moneySchema,
70
+ billing: billingSchema,
71
+ group: groupSchema.optional(),
72
+ credits: z.array(creditGrantSchema).optional(),
73
+ delivery: deliverySchema.optional(),
74
+ checkout: checkoutSchema.optional(),
75
+ theme: themeSchema.optional(),
76
+ slug: z.string().regex(SLUG_PATTERN, "must be 3-64 characters of lowercase letters, digits, or '-'").optional(),
77
+ stripe: stripeSchema.optional(),
78
+ active: z.boolean().optional()
79
+ });
80
+ var configSchema = z.strictObject({
81
+ products: z.array(productInputSchema)
82
+ }).superRefine((config, ctx) => {
83
+ const seenKeys = /* @__PURE__ */ new Map();
84
+ config.products.forEach((product, index) => {
85
+ const firstIndex = seenKeys.get(product.key);
86
+ if (firstIndex !== void 0) {
87
+ ctx.addIssue({
88
+ code: "custom",
89
+ path: ["products", index, "key"],
90
+ message: `duplicate product key "${product.key}" (also used by products[${firstIndex}])`
91
+ });
92
+ } else {
93
+ seenKeys.set(product.key, index);
94
+ }
95
+ const seenMeters = /* @__PURE__ */ new Map();
96
+ product.credits?.forEach((grant, grantIndex) => {
97
+ const firstMeter = seenMeters.get(grant.meter);
98
+ if (firstMeter !== void 0) {
99
+ ctx.addIssue({
100
+ code: "custom",
101
+ path: ["products", index, "credits", grantIndex, "meter"],
102
+ message: `duplicate credit meter "${grant.meter}" (also used by credits[${firstMeter}])`
103
+ });
104
+ } else {
105
+ seenMeters.set(grant.meter, grantIndex);
106
+ }
107
+ });
108
+ });
109
+ });
110
+ var ConfigValidationError = class extends Error {
111
+ name = "ConfigValidationError";
112
+ issues;
113
+ constructor(issues) {
114
+ super(formatIssues(issues));
115
+ this.issues = issues;
116
+ }
117
+ };
118
+ function formatIssuePath(path) {
119
+ let out = "";
120
+ for (const segment of path) {
121
+ if (typeof segment === "number") out += `[${segment}]`;
122
+ else out += out ? `.${String(segment)}` : String(segment);
123
+ }
124
+ return out || "(root)";
125
+ }
126
+ function formatIssues(issues) {
127
+ const lines = issues.map((issue) => ` - ${issue.path}: ${issue.message}`);
128
+ return `Invalid Purpleturret config (${issues.length} issue${issues.length === 1 ? "" : "s"}):
129
+ ${lines.join("\n")}`;
130
+ }
131
+ function validateConfig(input) {
132
+ const result = configSchema.safeParse(input);
133
+ if (result.success) return result.data;
134
+ const issues = result.error.issues.map((issue) => ({
135
+ path: formatIssuePath(issue.path),
136
+ message: issue.message
137
+ }));
138
+ throw new ConfigValidationError(issues);
139
+ }
140
+
141
+ // ../sdk/src/client/errors.ts
142
+ var PurpleturretApiError = class _PurpleturretApiError extends Error {
143
+ name = "PurpleturretApiError";
144
+ status;
145
+ code;
146
+ requestId;
147
+ details;
148
+ /** Seconds to wait before retrying, from `Retry-After` (or `reset_at` on legacy envelopes). */
149
+ retryAfter;
150
+ constructor(init2) {
151
+ super(init2.message);
152
+ this.status = init2.status;
153
+ this.code = init2.code;
154
+ this.requestId = init2.requestId ?? null;
155
+ this.details = init2.details;
156
+ this.retryAfter = init2.retryAfter ?? null;
157
+ }
158
+ /**
159
+ * Build an error from a response body. Accepts the structured envelope
160
+ * `{ error: { code, message, request_id, details } }` as well as the legacy entitlements envelope
161
+ * `{ error: "code", ...extra }`.
162
+ */
163
+ static fromResponse(status2, body, retryAfterHeader) {
164
+ const retryAfter = parseRetryAfter(retryAfterHeader);
165
+ const record = body && typeof body === "object" && !Array.isArray(body) ? body : null;
166
+ const envelope = record?.error;
167
+ if (envelope && typeof envelope === "object") {
168
+ const err = envelope;
169
+ const code = typeof err.code === "string" && err.code ? err.code : `http_${status2}`;
170
+ const message = typeof err.message === "string" && err.message ? err.message : defaultMessage(status2, code);
171
+ const requestId = typeof err.request_id === "string" ? err.request_id : typeof err.requestId === "string" ? err.requestId : null;
172
+ return new _PurpleturretApiError({ status: status2, code, message, requestId, details: err.details, retryAfter });
173
+ }
174
+ if (typeof envelope === "string" && record) {
175
+ const { error: _code, message: rawMessage, request_id: requestId, ...rest } = record;
176
+ const code = envelope || `http_${status2}`;
177
+ const message = typeof rawMessage === "string" && rawMessage ? rawMessage : defaultMessage(status2, code);
178
+ const resetAt = typeof rest.reset_at === "number" ? rest.reset_at : null;
179
+ const legacyRetryAfter = retryAfter ?? (resetAt !== null ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1e3)) : null);
180
+ return new _PurpleturretApiError({
181
+ status: status2,
182
+ code,
183
+ message,
184
+ requestId: typeof requestId === "string" ? requestId : null,
185
+ details: Object.keys(rest).length > 0 ? rest : void 0,
186
+ retryAfter: legacyRetryAfter
187
+ });
188
+ }
189
+ const text = typeof body === "string" ? body.trim().slice(0, 300) : "";
190
+ return new _PurpleturretApiError({
191
+ status: status2,
192
+ code: `http_${status2}`,
193
+ message: text || defaultMessage(status2, `http_${status2}`),
194
+ details: record ?? void 0,
195
+ retryAfter
196
+ });
197
+ }
198
+ };
199
+ var PurpleturretNetworkError = class extends Error {
200
+ name = "PurpleturretNetworkError";
201
+ url;
202
+ timedOut;
203
+ cause;
204
+ constructor(url, cause, timedOut) {
205
+ super(timedOut ? `Request to ${url} timed out` : `Request to ${url} failed: ${describeCause(cause)}`);
206
+ this.url = url;
207
+ this.cause = cause;
208
+ this.timedOut = timedOut;
209
+ }
210
+ };
211
+ function isTimeoutError(cause) {
212
+ return Boolean(cause && typeof cause === "object" && "name" in cause && cause.name === "TimeoutError");
213
+ }
214
+ function describeCause(cause) {
215
+ if (cause && typeof cause === "object") {
216
+ const inner = cause.cause;
217
+ if (inner && typeof inner === "object" && "message" in inner && typeof inner.message === "string") {
218
+ const code = inner.code;
219
+ return typeof code === "string" ? `${code} (${inner.message})` : inner.message;
220
+ }
221
+ if ("message" in cause && typeof cause.message === "string") return cause.message;
222
+ }
223
+ return String(cause);
224
+ }
225
+ function defaultMessage(status2, code) {
226
+ switch (status2) {
227
+ case 401:
228
+ return "The API key was rejected";
229
+ case 403:
230
+ return "The API key is not allowed to perform this operation";
231
+ case 404:
232
+ return "The requested resource was not found";
233
+ case 409:
234
+ return "The request conflicts with the current state";
235
+ case 422:
236
+ return "The request was rejected as invalid";
237
+ case 429:
238
+ return "Too many requests; slow down and retry";
239
+ default:
240
+ return status2 >= 500 ? `The Purpleturret API returned ${status2}` : `Request failed with ${code}`;
241
+ }
242
+ }
243
+ function parseRetryAfter(header) {
244
+ if (!header) return null;
245
+ const trimmed = header.trim();
246
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
247
+ const when = Date.parse(trimmed);
248
+ if (Number.isNaN(when)) return null;
249
+ return Math.max(0, Math.ceil((when - Date.now()) / 1e3));
250
+ }
251
+
252
+ // ../sdk/src/client/wire.ts
253
+ function omitUndefined(value) {
254
+ const out = {};
255
+ for (const [key, entry] of Object.entries(value)) {
256
+ if (entry !== void 0) out[key] = entry;
257
+ }
258
+ return out;
259
+ }
260
+ function toWireProduct(input) {
261
+ const wire = {
262
+ key: input.key,
263
+ name: input.name,
264
+ description: input.description,
265
+ price: { amount: input.price.amount, currency: input.price.currency },
266
+ billing: input.billing.type === "recurring" ? { type: "recurring", interval: input.billing.interval } : { type: "one_time" },
267
+ group: input.group ? toWireGroup(input.group) : void 0,
268
+ credits: input.credits?.map(toWireCreditGrant),
269
+ delivery: input.delivery ? toWireDelivery(input.delivery) : void 0,
270
+ checkout: input.checkout ? toWireCheckout(input.checkout) : void 0,
271
+ theme: input.theme ? toWireTheme(input.theme) : void 0,
272
+ slug: input.slug,
273
+ stripe: input.stripe ? { price_id: input.stripe.priceId } : void 0,
274
+ active: input.active
275
+ };
276
+ return omitUndefined(wire);
277
+ }
278
+ function toWireGroup(group) {
279
+ return omitUndefined({ key: group.key, tier: group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : void 0 });
280
+ }
281
+ function toWireCreditGrant(grant) {
282
+ return omitUndefined({ meter: grant.meter, amount: grant.amount, renewal: grant.renewal, expires_after_days: grant.expiresAfterDays });
283
+ }
284
+ function toWireDelivery(delivery) {
285
+ switch (delivery.method) {
286
+ case "none":
287
+ return { method: "none" };
288
+ case "redirect":
289
+ return { method: "redirect", url: delivery.url };
290
+ case "instructions":
291
+ return { method: "instructions", instructions: delivery.instructions };
292
+ }
293
+ }
294
+ function toWireCheckout(checkout) {
295
+ return omitUndefined({
296
+ layout_mode: checkout.layoutMode,
297
+ payment_style: checkout.paymentStyle,
298
+ provider_mode: checkout.providerMode,
299
+ contact_fields: checkout.contactFields ? omitUndefined({ name: checkout.contactFields.name, phone: checkout.contactFields.phone }) : void 0
300
+ });
301
+ }
302
+ function toWireTheme(theme) {
303
+ return omitUndefined({ primary_color: theme.primaryColor, button_radius: theme.buttonRadius, accent_mode: theme.accentMode });
304
+ }
305
+ function fromWireProduct(wire) {
306
+ const product = {
307
+ key: wire.key ?? null,
308
+ id: wire.id,
309
+ slug: wire.slug ?? null,
310
+ url: wire.url ?? null,
311
+ name: wire.name,
312
+ description: wire.description ?? void 0,
313
+ price: { amount: wire.price.amount, currency: wire.price.currency },
314
+ billing: fromWireBilling(wire.billing),
315
+ group: wire.group ? fromWireGroup(wire.group) : void 0,
316
+ credits: wire.credits ? wire.credits.map(fromWireCreditGrant) : void 0,
317
+ delivery: wire.delivery ?? void 0,
318
+ checkout: wire.checkout ? fromWireCheckout(wire.checkout) : void 0,
319
+ theme: wire.theme ? fromWireTheme(wire.theme) : void 0,
320
+ stripe: wire.stripe ? fromWireStripe(wire.stripe) : void 0,
321
+ active: wire.active,
322
+ archivedAt: wire.archived_at ?? null,
323
+ createdAt: wire.created_at,
324
+ updatedAt: wire.updated_at
325
+ };
326
+ return omitUndefined(product);
327
+ }
328
+ function fromWireBilling(billing) {
329
+ return billing.type === "recurring" ? { type: "recurring", interval: billing.interval } : { type: "one_time" };
330
+ }
331
+ function fromWireGroup(group) {
332
+ const tier = group.tier ? { key: group.tier.key, name: group.tier.name, rank: group.tier.rank } : void 0;
333
+ return omitUndefined({ key: group.key, tier });
334
+ }
335
+ function fromWireCreditGrant(grant) {
336
+ return omitUndefined({
337
+ meter: grant.meter,
338
+ amount: grant.amount,
339
+ renewal: grant.renewal,
340
+ expiresAfterDays: grant.expires_after_days ?? void 0
341
+ });
342
+ }
343
+ function fromWireCheckout(checkout) {
344
+ return omitUndefined({
345
+ layoutMode: checkout.layout_mode ?? void 0,
346
+ paymentStyle: checkout.payment_style ?? void 0,
347
+ providerMode: checkout.provider_mode ?? void 0,
348
+ contactFields: checkout.contact_fields ? omitUndefined({ name: checkout.contact_fields.name ?? void 0, phone: checkout.contact_fields.phone ?? void 0 }) : void 0
349
+ });
350
+ }
351
+ function fromWireTheme(theme) {
352
+ return omitUndefined({
353
+ primaryColor: theme.primary_color ?? void 0,
354
+ buttonRadius: theme.button_radius ?? void 0,
355
+ accentMode: theme.accent_mode ?? void 0
356
+ });
357
+ }
358
+ function fromWireStripe(stripe) {
359
+ return { priceId: stripe.price_id };
360
+ }
361
+ function productToInput(product) {
362
+ if (!product.key) return null;
363
+ return omitUndefined({
364
+ key: product.key,
365
+ name: product.name,
366
+ description: product.description,
367
+ price: product.price,
368
+ billing: product.billing,
369
+ group: product.group,
370
+ credits: product.credits,
371
+ delivery: product.delivery,
372
+ checkout: product.checkout,
373
+ theme: product.theme,
374
+ slug: product.slug ?? void 0,
375
+ stripe: product.stripe,
376
+ active: product.active
377
+ });
378
+ }
379
+ function fromWirePlanItem(item) {
380
+ let error;
381
+ if (typeof item.error === "string") error = { code: item.error, message: item.error };
382
+ else if (item.error && typeof item.error === "object") {
383
+ error = { code: item.error.code ?? "error", message: item.error.message ?? item.error.code ?? "Unknown error" };
384
+ }
385
+ return omitUndefined({
386
+ key: item.key,
387
+ action: item.action,
388
+ changes: (item.changes ?? []).map(
389
+ (change) => omitUndefined({ path: change.path, from: change.from, to: change.to, note: change.note ?? void 0 })
390
+ ),
391
+ product: item.product ? fromWireProduct(item.product) : void 0,
392
+ error
393
+ });
394
+ }
395
+ function fromWireConfigPushResult(wire) {
396
+ return {
397
+ applied: Boolean(wire.applied),
398
+ summary: {
399
+ create: wire.summary?.create ?? 0,
400
+ update: wire.summary?.update ?? 0,
401
+ unchanged: wire.summary?.unchanged ?? 0,
402
+ archive: wire.summary?.archive ?? 0,
403
+ conflict: wire.summary?.conflict ?? 0,
404
+ error: wire.summary?.error ?? 0
405
+ },
406
+ results: (wire.results ?? []).map(fromWirePlanItem)
407
+ };
408
+ }
409
+ function fromWireConfigGetResult(wire) {
410
+ return { products: (wire.products ?? []).map(fromWireProduct), unmanagedCount: wire.unmanaged_count ?? 0 };
411
+ }
412
+ function fromWireAccount(wire) {
413
+ return {
414
+ id: wire.id,
415
+ email: wire.email,
416
+ name: wire.name ?? null,
417
+ stripe: { connected: Boolean(wire.stripe?.connected), chargesEnabled: Boolean(wire.stripe?.charges_enabled) },
418
+ paypal: { connected: Boolean(wire.paypal?.connected) },
419
+ key: { prefix: wire.key?.prefix ?? "", name: wire.key?.name ?? null, scopes: wire.key?.scopes ?? [] }
420
+ };
421
+ }
422
+ function fromWirePage(wire, map) {
423
+ return { data: (wire.data ?? []).map(map), nextCursor: wire.next_cursor ?? null };
424
+ }
425
+ function fromWireCustomerRef(ref) {
426
+ return { email: ref?.email ?? null, externalId: ref?.external_id ?? null };
427
+ }
428
+ function fromWireCreditBalances(wire) {
429
+ return {
430
+ customer: fromWireCustomerRef(wire.customer),
431
+ balances: (wire.balances ?? []).map((balance) => ({
432
+ meter: balance.meter,
433
+ balance: balance.balance,
434
+ expiresAt: balance.expires_at ?? null,
435
+ lifetimeGranted: balance.lifetime_granted ?? 0,
436
+ lifetimeConsumed: balance.lifetime_consumed ?? 0
437
+ }))
438
+ };
439
+ }
440
+ function fromWireCreditConsume(wire) {
441
+ return { meter: wire.meter, balance: wire.balance, consumed: wire.consumed, replayed: Boolean(wire.replayed) };
442
+ }
443
+ function fromWireCreditAdjust(wire) {
444
+ return { meter: wire.meter, balance: wire.balance };
445
+ }
446
+ function camelCaseKey(key) {
447
+ return key.replace(/_([a-z0-9])/g, (_, char) => char.toUpperCase());
448
+ }
449
+ function camelizeKeys(value) {
450
+ if (Array.isArray(value)) return value.map(camelizeKeys);
451
+ if (value && typeof value === "object") {
452
+ const out = {};
453
+ for (const [key, entry] of Object.entries(value)) out[camelCaseKey(key)] = camelizeKeys(entry);
454
+ return out;
455
+ }
456
+ return value;
457
+ }
458
+ function fromWireLedgerEntry(wire) {
459
+ const entry = camelizeKeys(wire);
460
+ return {
461
+ ...entry,
462
+ id: String(entry.id ?? ""),
463
+ kind: entry.kind,
464
+ meter: String(entry.meter ?? ""),
465
+ amount: Number(entry.amount ?? 0),
466
+ balanceAfter: Number(entry.balanceAfter ?? 0),
467
+ note: entry.note ?? null,
468
+ createdAt: Number(entry.createdAt ?? 0)
469
+ };
470
+ }
471
+ function fromWireEntitlement(wire) {
472
+ const { credits, ...rest } = wire;
473
+ const base = camelizeKeys(rest);
474
+ const entitlement = {
475
+ ...base,
476
+ hasAccess: Boolean(base.hasAccess),
477
+ status: String(base.status ?? "none")
478
+ };
479
+ if (credits && typeof credits === "object") {
480
+ entitlement.credits = Object.fromEntries(
481
+ Object.entries(credits).map(([meter, value]) => [
482
+ meter,
483
+ { balance: Number(value?.balance ?? 0), expiresAt: value?.expires_at ?? null }
484
+ ])
485
+ );
486
+ }
487
+ return entitlement;
488
+ }
489
+
490
+ // ../sdk/src/client/client.ts
491
+ var DEFAULT_BASE_URL = "https://api.purpleturret.com";
492
+ var DEFAULT_TIMEOUT_MS = 3e4;
493
+ var PurpleturretClient = class {
494
+ baseUrl;
495
+ timeoutMs;
496
+ apiKey;
497
+ fetchImpl;
498
+ userAgent;
499
+ constructor(options) {
500
+ if (!options || typeof options.apiKey !== "string" || !options.apiKey.trim()) {
501
+ throw new TypeError("PurpleturretClient: apiKey is required");
502
+ }
503
+ this.apiKey = options.apiKey.trim();
504
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).trim().replace(/\/+$/, "");
505
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
506
+ const fetchImpl = options.fetch ?? globalThis.fetch;
507
+ if (typeof fetchImpl !== "function") throw new TypeError("PurpleturretClient: no fetch implementation available; pass options.fetch");
508
+ this.fetchImpl = fetchImpl;
509
+ const sdkAgent = `purpleturret-sdk/${SDK_VERSION}`;
510
+ this.userAgent = options.userAgent ? `${options.userAgent} ${sdkAgent}` : sdkAgent;
511
+ }
512
+ /** Absolute URL for an API path such as `/config`. */
513
+ url(path, query) {
514
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
515
+ let url = `${this.baseUrl}/v1${normalizedPath}`;
516
+ if (query) {
517
+ const params = new URLSearchParams();
518
+ for (const [key, value] of Object.entries(query)) {
519
+ if (value === void 0) continue;
520
+ params.set(key, String(value));
521
+ }
522
+ const qs = params.toString();
523
+ if (qs) url += `?${qs}`;
524
+ }
525
+ return url;
526
+ }
527
+ account = {
528
+ get: async () => fromWireAccount(await this.request("GET", "/account"))
529
+ };
530
+ config = {
531
+ get: async () => fromWireConfigGetResult(await this.request("GET", "/config")),
532
+ push: async (options) => {
533
+ const body = { products: options.products.map(toWireProduct) };
534
+ if (options.prune !== void 0) body.prune = options.prune;
535
+ if (options.dryRun !== void 0) body.dry_run = options.dryRun;
536
+ const wire = await this.request("PUT", "/config", {
537
+ body,
538
+ idempotencyKey: options.idempotencyKey,
539
+ // A conflict returns the full plan with a 409; surface it as a result so callers can render it.
540
+ acceptStatuses: [409]
541
+ });
542
+ return fromWireConfigPushResult(wire);
543
+ }
544
+ };
545
+ products = {
546
+ list: async (options = {}) => fromWirePage(
547
+ await this.request("GET", "/products", {
548
+ query: { cursor: options.cursor, limit: options.limit, include_archived: options.includeArchived }
549
+ }),
550
+ fromWireProduct
551
+ ),
552
+ get: async (key) => fromWireProduct(await this.request("GET", `/products/${encodeURIComponent(key)}`)),
553
+ /** Archives the product (never hard-deletes). */
554
+ archive: async (key) => fromWireProduct(await this.request("DELETE", `/products/${encodeURIComponent(key)}`))
555
+ };
556
+ credits = {
557
+ balances: async (options) => fromWireCreditBalances(
558
+ await this.request("GET", "/credits/balances", {
559
+ query: { ...customerQuery(options), meter: options.meter }
560
+ })
561
+ ),
562
+ consume: async (options) => {
563
+ if (!options.idempotencyKey) throw new TypeError("credits.consume: idempotencyKey is required");
564
+ return fromWireCreditConsume(
565
+ await this.request("POST", "/credits/consume", {
566
+ body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },
567
+ idempotencyKey: options.idempotencyKey
568
+ })
569
+ );
570
+ },
571
+ adjust: async (options) => fromWireCreditAdjust(
572
+ await this.request("POST", "/credits/adjust", {
573
+ body: { meter: options.meter, amount: options.amount, ...customerQuery(options), note: options.note },
574
+ idempotencyKey: options.idempotencyKey
575
+ })
576
+ ),
577
+ ledger: async (options) => fromWirePage(
578
+ await this.request("GET", "/credits/ledger", {
579
+ query: { ...customerQuery(options), cursor: options.cursor, limit: options.limit }
580
+ }),
581
+ fromWireLedgerEntry
582
+ )
583
+ };
584
+ entitlements = {
585
+ /** Resolves with `hasAccess: false` (rather than throwing) when the customer has no subscription. */
586
+ get: async (options) => fromWireEntitlement(
587
+ await this.request("GET", "/entitlements", {
588
+ query: { group_key: options.groupKey, ...customerQuery(options) },
589
+ acceptStatuses: [404]
590
+ })
591
+ )
592
+ };
593
+ async request(method, path, options = {}) {
594
+ const url = this.url(path, options.query);
595
+ const headers = {
596
+ authorization: `Bearer ${this.apiKey}`,
597
+ accept: "application/json",
598
+ "user-agent": this.userAgent
599
+ };
600
+ const hasBody = options.body !== void 0;
601
+ if (hasBody) headers["content-type"] = "application/json";
602
+ if (options.idempotencyKey) headers["idempotency-key"] = options.idempotencyKey;
603
+ let response;
604
+ try {
605
+ response = await this.fetchImpl(url, {
606
+ method,
607
+ headers,
608
+ body: hasBody ? JSON.stringify(stripUndefined(options.body)) : void 0,
609
+ signal: AbortSignal.timeout(this.timeoutMs)
610
+ });
611
+ } catch (cause) {
612
+ throw new PurpleturretNetworkError(url, cause, isTimeoutError(cause));
613
+ }
614
+ const text = await response.text();
615
+ let parsed = void 0;
616
+ if (text) {
617
+ try {
618
+ parsed = JSON.parse(text);
619
+ } catch {
620
+ parsed = void 0;
621
+ }
622
+ }
623
+ const accepted = response.ok || (options.acceptStatuses?.includes(response.status) ?? false);
624
+ if (!accepted) {
625
+ throw PurpleturretApiError.fromResponse(response.status, parsed ?? text, response.headers.get("retry-after"));
626
+ }
627
+ if (!response.ok && parsed && typeof parsed === "object" && "error" in parsed) {
628
+ const record = parsed;
629
+ const looksLikePlan = "results" in record && "summary" in record;
630
+ const looksLikeEntitlement = "has_access" in record;
631
+ if (!looksLikePlan && !looksLikeEntitlement) {
632
+ throw PurpleturretApiError.fromResponse(response.status, parsed, response.headers.get("retry-after"));
633
+ }
634
+ }
635
+ if (response.status === 204 || parsed === void 0) return void 0;
636
+ return parsed;
637
+ }
638
+ };
639
+ function customerQuery(selector) {
640
+ const out = {};
641
+ if (selector.externalId) out.external_id = selector.externalId;
642
+ if (selector.email) out.email = selector.email;
643
+ if (!out.external_id && !out.email) throw new TypeError("Provide externalId or email to identify the customer");
644
+ return out;
645
+ }
646
+ function stripUndefined(value) {
647
+ if (Array.isArray(value)) return value.map(stripUndefined);
648
+ if (value && typeof value === "object") {
649
+ const out = {};
650
+ for (const [key, entry] of Object.entries(value)) {
651
+ if (entry !== void 0) out[key] = stripUndefined(entry);
652
+ }
653
+ return out;
654
+ }
655
+ return value;
656
+ }
657
+
658
+ // src/commands/init.ts
659
+ import { defineCommand } from "citty";
660
+
661
+ // src/lib/context.ts
662
+ import { existsSync } from "fs";
663
+ import { join as join2 } from "path";
664
+ import dotenv from "dotenv";
665
+
666
+ // src/version.ts
667
+ var CLI_VERSION = "0.1.0";
668
+
669
+ // src/lib/credentials.ts
670
+ import { chmod, mkdir, readFile, rename, writeFile } from "fs/promises";
671
+ import { homedir } from "os";
672
+ import { dirname, join } from "path";
673
+ var DEFAULT_PROFILE = "default";
674
+ function credentialsPath(env = process.env) {
675
+ const xdg = env.XDG_CONFIG_HOME?.trim();
676
+ const home = env.HOME?.trim() || homedir();
677
+ const configHome = xdg && xdg.length > 0 ? xdg : join(home, ".config");
678
+ return join(configHome, "purpleturret", "credentials.json");
679
+ }
680
+ var CredentialsStore = class {
681
+ path;
682
+ constructor(path = credentialsPath()) {
683
+ this.path = path;
684
+ }
685
+ async read() {
686
+ let text;
687
+ try {
688
+ text = await readFile(this.path, "utf8");
689
+ } catch (error) {
690
+ if (error.code === "ENOENT") return { version: 1, profiles: {} };
691
+ throw error;
692
+ }
693
+ try {
694
+ const parsed = JSON.parse(text);
695
+ if (!parsed || typeof parsed !== "object" || typeof parsed.profiles !== "object" || parsed.profiles === null) {
696
+ return { version: 1, profiles: {} };
697
+ }
698
+ return { version: 1, profiles: parsed.profiles };
699
+ } catch {
700
+ throw new Error(`Credentials file ${this.path} is not valid JSON. Fix or delete it and run \`purpleturret login\` again.`);
701
+ }
702
+ }
703
+ async write(file) {
704
+ await mkdir(dirname(this.path), { recursive: true, mode: 448 });
705
+ const tmp = `${this.path}.${process.pid}.tmp`;
706
+ await writeFile(tmp, `${JSON.stringify(file, null, 2)}
707
+ `, { encoding: "utf8", mode: 384 });
708
+ await chmod(tmp, 384);
709
+ await rename(tmp, this.path);
710
+ }
711
+ async getProfile(name = DEFAULT_PROFILE) {
712
+ const file = await this.read();
713
+ return file.profiles[name] ?? null;
714
+ }
715
+ async saveProfile(name, profile) {
716
+ const file = await this.read();
717
+ file.profiles[name] = profile;
718
+ await this.write(file);
719
+ }
720
+ /** Returns true when a profile was removed. */
721
+ async deleteProfile(name) {
722
+ const file = await this.read();
723
+ if (!(name in file.profiles)) return false;
724
+ delete file.profiles[name];
725
+ await this.write(file);
726
+ return true;
727
+ }
728
+ };
729
+
730
+ // src/lib/errors.ts
731
+ var EXIT = {
732
+ OK: 0,
733
+ ERROR: 1,
734
+ USAGE: 2,
735
+ AUTH: 3,
736
+ CONFLICT: 4,
737
+ ABORTED: 130
738
+ };
739
+ var DASHBOARD_SETTINGS_URL = "https://purpleturret.com/dashboard/settings";
740
+ var CliError = class extends Error {
741
+ name = "CliError";
742
+ exitCode;
743
+ hint;
744
+ code;
745
+ cause;
746
+ constructor(message, exitCode = EXIT.ERROR, options = {}) {
747
+ super(message);
748
+ this.exitCode = exitCode;
749
+ this.hint = options.hint;
750
+ this.code = options.code;
751
+ this.cause = options.cause;
752
+ }
753
+ };
754
+ function toCliError(error, ctx) {
755
+ if (error instanceof CliError) return error;
756
+ if (error instanceof ConfigValidationError) {
757
+ return new CliError(error.message, EXIT.USAGE, { code: "config_invalid", cause: error });
758
+ }
759
+ if (error instanceof PurpleturretNetworkError) {
760
+ const where = ctx.apiUrlSource === "default" ? "" : ` (from ${describeUrlSource(ctx.apiUrlSource)})`;
761
+ return new CliError(error.message, EXIT.ERROR, {
762
+ code: error.timedOut ? "timeout" : "network_error",
763
+ hint: `Check that the API URL ${ctx.apiUrl}${where} is reachable, or override it with --api-url / PURPLETURRET_API_URL.`,
764
+ cause: error
765
+ });
766
+ }
767
+ if (error instanceof PurpleturretApiError) return fromApiError(error, ctx);
768
+ if (error instanceof Error) return new CliError(error.message, EXIT.ERROR, { cause: error });
769
+ return new CliError(String(error), EXIT.ERROR);
770
+ }
771
+ function fromApiError(error, ctx) {
772
+ const requestId = error.requestId ? ` (request ${error.requestId})` : "";
773
+ const detailText = formatDetails(error.details);
774
+ if (error.code === "stripe_not_connected") {
775
+ return new CliError(`${error.message}${requestId}`, EXIT.ERROR, {
776
+ code: error.code,
777
+ hint: `Connect Stripe first in Dashboard \u2192 Settings \u2192 Payments: ${DASHBOARD_SETTINGS_URL}`,
778
+ cause: error
779
+ });
780
+ }
781
+ switch (error.status) {
782
+ case 401: {
783
+ const source = ctx.credentialSource;
784
+ const hint = source === "flag" ? "The key passed with --api-key was rejected. Mint a new seller key in Dashboard \u2192 Settings \u2192 Developers." : source === "env" ? "PURPLETURRET_API_KEY was rejected. Mint a new seller key in Dashboard \u2192 Settings \u2192 Developers and update your .env.local." : "Run `purpleturret login` to store a valid seller key, or pass --api-key / set PURPLETURRET_API_KEY.";
785
+ return new CliError(`The API key was rejected (401 ${error.code})${requestId}.`, EXIT.AUTH, { code: error.code, hint, cause: error });
786
+ }
787
+ case 403: {
788
+ if (error.code === "forbidden_key_type") {
789
+ return new CliError(`This is a hosting key (pt_host_\u2026), which cannot manage products or credits${requestId}.`, EXIT.AUTH, {
790
+ code: error.code,
791
+ hint: `Use a seller key (pt_sk_\u2026) minted in Dashboard \u2192 Settings \u2192 Developers: ${DASHBOARD_SETTINGS_URL}`,
792
+ cause: error
793
+ });
794
+ }
795
+ const required = pickString(error.details, "required_scope") ?? pickString(error.details, "scope");
796
+ return new CliError(`${error.message} (403 ${error.code})${requestId}.`, EXIT.AUTH, {
797
+ code: error.code,
798
+ hint: required ? `The key is missing the ${required} scope. Mint a key with that scope in Dashboard \u2192 Settings \u2192 Developers: ${DASHBOARD_SETTINGS_URL}` : `Mint a seller key with the config:read, config:write, credits:read, credits:write and entitlements:read scopes in Dashboard \u2192 Settings \u2192 Developers: ${DASHBOARD_SETTINGS_URL}`,
799
+ cause: error
800
+ });
801
+ }
802
+ case 402:
803
+ return new CliError(`${error.message} (402 ${error.code})${requestId}.${detailText}`, EXIT.ERROR, { code: error.code, cause: error });
804
+ case 404:
805
+ return new CliError(`${error.message} (404 ${error.code})${requestId}.`, EXIT.ERROR, { code: error.code, cause: error });
806
+ case 409: {
807
+ if (error.code === "immutable_field_changed") {
808
+ return new CliError(`${error.message} (409 immutable_field_changed)${requestId}.${detailText}`, EXIT.CONFLICT, {
809
+ code: error.code,
810
+ 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).",
811
+ cause: error
812
+ });
813
+ }
814
+ if (error.code === "idempotency_conflict") {
815
+ return new CliError(`${error.message} (409 idempotency_conflict)${requestId}.`, EXIT.CONFLICT, {
816
+ code: error.code,
817
+ hint: "The Idempotency-Key was already used with a different request body. Run push again to generate a fresh key.",
818
+ cause: error
819
+ });
820
+ }
821
+ return new CliError(`${error.message} (409 ${error.code})${requestId}.${detailText}`, EXIT.CONFLICT, { code: error.code, cause: error });
822
+ }
823
+ case 422:
824
+ return new CliError(`The API rejected the request (422 ${error.code})${requestId}: ${error.message}${detailText}`, EXIT.USAGE, {
825
+ code: error.code,
826
+ cause: error
827
+ });
828
+ case 429:
829
+ return new CliError(`Rate limited (429 ${error.code})${requestId}.`, EXIT.ERROR, {
830
+ code: error.code,
831
+ hint: error.retryAfter !== null ? `Retry after ${error.retryAfter}s.` : "Slow down and retry shortly.",
832
+ cause: error
833
+ });
834
+ default:
835
+ if (error.status >= 500) {
836
+ return new CliError(`The Purpleturret API returned ${error.status} ${error.code}${requestId}: ${error.message}`, EXIT.ERROR, {
837
+ code: error.code,
838
+ hint: "This is a server-side failure. Retry in a moment; if it persists, contact support with the request id.",
839
+ cause: error
840
+ });
841
+ }
842
+ return new CliError(`${error.message} (${error.status} ${error.code})${requestId}.${detailText}`, EXIT.ERROR, {
843
+ code: error.code,
844
+ cause: error
845
+ });
846
+ }
847
+ }
848
+ function describeUrlSource(source) {
849
+ switch (source) {
850
+ case "flag":
851
+ return "--api-url";
852
+ case "env":
853
+ return "PURPLETURRET_API_URL";
854
+ case "profile":
855
+ return "the saved profile";
856
+ default:
857
+ return "the default";
858
+ }
859
+ }
860
+ function pickString(details, key) {
861
+ if (details && typeof details === "object" && key in details) {
862
+ const value = details[key];
863
+ return typeof value === "string" ? value : void 0;
864
+ }
865
+ return void 0;
866
+ }
867
+ function formatDetails(details) {
868
+ if (details === void 0 || details === null) return "";
869
+ if (typeof details === "string") return `
870
+ ${details}`;
871
+ if (Array.isArray(details)) {
872
+ if (details.length === 0) return "";
873
+ return `
874
+ ${details.map((entry) => ` - ${formatDetailEntry(entry)}`).join("\n")}`;
875
+ }
876
+ if (typeof details === "object") {
877
+ const entries = Object.entries(details);
878
+ if (entries.length === 0) return "";
879
+ if ("issues" in details && Array.isArray(details.issues)) {
880
+ return formatDetails(details.issues);
881
+ }
882
+ return `
883
+ ${entries.map(([key, value]) => ` ${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`).join("\n")}`;
884
+ }
885
+ return `
886
+ ${String(details)}`;
887
+ }
888
+ function formatDetailEntry(entry) {
889
+ if (entry && typeof entry === "object") {
890
+ const record = entry;
891
+ const path = typeof record.path === "string" ? record.path : Array.isArray(record.path) ? record.path.join(".") : void 0;
892
+ const message = typeof record.message === "string" ? record.message : JSON.stringify(record);
893
+ return path ? `${path}: ${message}` : message;
894
+ }
895
+ return String(entry);
896
+ }
897
+
898
+ // src/lib/output.ts
899
+ import { createColors } from "picocolors";
900
+ function createPalette(enabled) {
901
+ const colors = createColors(enabled);
902
+ return {
903
+ enabled,
904
+ green: colors.green,
905
+ yellow: colors.yellow,
906
+ red: colors.red,
907
+ cyan: colors.cyan,
908
+ magenta: colors.magenta,
909
+ dim: colors.dim,
910
+ bold: colors.bold
911
+ };
912
+ }
913
+ function shouldUseColor(options = {}) {
914
+ const env = options.env ?? process.env;
915
+ const stream = options.stream ?? process.stdout;
916
+ if (options.flag === false) return false;
917
+ if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return false;
918
+ if (env.FORCE_COLOR !== void 0 && env.FORCE_COLOR !== "" && env.FORCE_COLOR !== "0") return true;
919
+ return Boolean(stream.isTTY);
920
+ }
921
+ function isInteractive() {
922
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
923
+ }
924
+ var Output = class {
925
+ json;
926
+ verbose;
927
+ palette;
928
+ stdout;
929
+ stderr;
930
+ constructor(options) {
931
+ this.json = options.json;
932
+ this.verbose = options.verbose;
933
+ this.palette = options.palette;
934
+ this.stdout = options.stdout ?? process.stdout;
935
+ this.stderr = options.stderr ?? process.stderr;
936
+ }
937
+ /** Write result lines to stdout (suppressed in --json mode unless `force`). */
938
+ print(text, force = false) {
939
+ if (this.json && !force) return;
940
+ this.stdout.write(`${text}
941
+ `);
942
+ }
943
+ /** Write a JSON document to stdout. */
944
+ printJson(value) {
945
+ this.stdout.write(`${JSON.stringify(value, null, 2)}
946
+ `);
947
+ }
948
+ info(text) {
949
+ if (this.json) return;
950
+ this.stderr.write(`${text}
951
+ `);
952
+ }
953
+ success(text) {
954
+ if (this.json) return;
955
+ this.stderr.write(`${this.palette.green("\u2714")} ${text}
956
+ `);
957
+ }
958
+ warn(text) {
959
+ if (this.json) return;
960
+ this.stderr.write(`${this.palette.yellow("!")} ${text}
961
+ `);
962
+ }
963
+ debug(text) {
964
+ if (!this.verbose) return;
965
+ this.stderr.write(`${this.palette.dim(`[debug] ${text}`)}
966
+ `);
967
+ }
968
+ /** Report a fatal error. In --json mode the error is emitted as JSON on stdout. */
969
+ fail(error) {
970
+ if (this.json) {
971
+ this.stdout.write(
972
+ `${JSON.stringify({ error: { code: error.code ?? "error", message: error.message, hint: error.hint, exit_code: error.exitCode } })}
973
+ `
974
+ );
975
+ return;
976
+ }
977
+ this.stderr.write(`${this.palette.red("error:")} ${error.message}
978
+ `);
979
+ if (error.hint) this.stderr.write(`${this.palette.dim("hint:")} ${error.hint}
980
+ `);
981
+ if (this.verbose && error.cause instanceof Error && error.cause.stack) {
982
+ this.stderr.write(`${this.palette.dim(error.cause.stack)}
983
+ `);
984
+ }
985
+ }
986
+ };
987
+
988
+ // src/lib/context.ts
989
+ var globalArgs = {
990
+ config: { type: "string", description: "Path to purpleturret.config.{ts,mts,js,mjs,json} (default: search up to the git root)" },
991
+ "api-url": { type: "string", description: "API origin (default: PURPLETURRET_API_URL, saved profile, or https://api.purpleturret.com)" },
992
+ "api-key": { type: "string", description: "Seller API key (default: PURPLETURRET_API_KEY, .env.local/.env, or saved profile)" },
993
+ profile: { type: "string", description: 'Credentials profile name (default: "default")' },
994
+ json: { type: "boolean", description: "Print machine-readable JSON on stdout" },
995
+ color: { type: "boolean", description: "Colorize output (disable with --no-color or NO_COLOR)" },
996
+ verbose: { type: "boolean", description: "Log requests and stack traces to stderr" }
997
+ };
998
+ var stashedGlobals = {};
999
+ function stashGlobalFlags(flags) {
1000
+ stashedGlobals = { ...flags };
1001
+ }
1002
+ function mergeGlobalFlags(flags) {
1003
+ const merged = { ...stashedGlobals };
1004
+ for (const [key, value] of Object.entries(flags)) {
1005
+ if (value !== void 0) merged[key] = value;
1006
+ }
1007
+ return merged;
1008
+ }
1009
+ function loadDotenv(cwd, env) {
1010
+ const loaded = [];
1011
+ for (const name of [".env.local", ".env"]) {
1012
+ const path = join2(cwd, name);
1013
+ if (!existsSync(path)) continue;
1014
+ dotenv.config({ path, override: false, quiet: true, processEnv: env });
1015
+ loaded.push(path);
1016
+ }
1017
+ return loaded;
1018
+ }
1019
+ async function createContext(rawFlags, options = {}) {
1020
+ const cwd = options.cwd ?? process.cwd();
1021
+ const env = options.env ?? process.env;
1022
+ const flags = mergeGlobalFlags(rawFlags);
1023
+ const json = Boolean(flags.json);
1024
+ const verbose = Boolean(flags.verbose);
1025
+ const palette = createPalette(
1026
+ shouldUseColor({ flag: flags.color, env, stream: options.stderr ?? process.stderr })
1027
+ );
1028
+ const out = new Output({ json, verbose, palette, stdout: options.stdout, stderr: options.stderr });
1029
+ const loadedEnvFiles = loadDotenv(cwd, env);
1030
+ if (loadedEnvFiles.length) out.debug(`loaded ${loadedEnvFiles.join(", ")}`);
1031
+ const profileName = flags.profile?.trim() || DEFAULT_PROFILE;
1032
+ const credentials = new CredentialsStore(options.credentialsFile ?? credentialsPath(env));
1033
+ const profile = await credentials.getProfile(profileName);
1034
+ const flagKey = (flags["api-key"] ?? flags.apiKey)?.trim();
1035
+ const envKey = env.PURPLETURRET_API_KEY?.trim();
1036
+ let apiKey = null;
1037
+ let credentialSource = "none";
1038
+ if (flagKey) [apiKey, credentialSource] = [flagKey, "flag"];
1039
+ else if (envKey) [apiKey, credentialSource] = [envKey, "env"];
1040
+ else if (profile?.apiKey) [apiKey, credentialSource] = [profile.apiKey, "profile"];
1041
+ const flagUrl = (flags["api-url"] ?? flags.apiUrl)?.trim();
1042
+ const envUrl = env.PURPLETURRET_API_URL?.trim();
1043
+ let apiUrl = DEFAULT_BASE_URL;
1044
+ let apiUrlSource = "default";
1045
+ if (flagUrl) [apiUrl, apiUrlSource] = [flagUrl, "flag"];
1046
+ else if (envUrl) [apiUrl, apiUrlSource] = [envUrl, "env"];
1047
+ else if (profile?.apiUrl) [apiUrl, apiUrlSource] = [profile.apiUrl, "profile"];
1048
+ apiUrl = apiUrl.replace(/\/+$/, "");
1049
+ if (!/^https?:\/\//.test(apiUrl)) {
1050
+ throw new CliError(`Invalid API URL "${apiUrl}"; it must start with http:// or https://`, EXIT.USAGE, { code: "invalid_api_url" });
1051
+ }
1052
+ let announcedUrl = false;
1053
+ const announceUrl = () => {
1054
+ if (announcedUrl || apiUrlSource === "default") return;
1055
+ announcedUrl = true;
1056
+ out.info(palette.yellow(`Using API ${apiUrl} (from ${describeSource(apiUrlSource)})`));
1057
+ };
1058
+ const fetchImpl = async (input, init2) => {
1059
+ const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
1060
+ out.debug(`${init2?.method ?? "GET"} ${url}`);
1061
+ const started = Date.now();
1062
+ const response = await fetch(input, init2);
1063
+ out.debug(`\u2192 ${response.status} ${response.headers.get("x-request-id") ?? ""} (${Date.now() - started}ms)`.trimEnd());
1064
+ return response;
1065
+ };
1066
+ const clientFor = (key) => {
1067
+ announceUrl();
1068
+ return new PurpleturretClient({ apiKey: key, baseUrl: apiUrl, fetch: fetchImpl, userAgent: `purpleturret-cli/${CLI_VERSION}` });
1069
+ };
1070
+ const context = {
1071
+ cwd,
1072
+ env,
1073
+ flags,
1074
+ json,
1075
+ verbose,
1076
+ out,
1077
+ profileName,
1078
+ profile,
1079
+ credentials,
1080
+ apiUrl,
1081
+ apiUrlSource,
1082
+ apiKey,
1083
+ credentialSource,
1084
+ configPath: flags.config,
1085
+ clientFor,
1086
+ client() {
1087
+ if (!apiKey) {
1088
+ throw new CliError(`No API key found for profile "${profileName}".`, EXIT.AUTH, {
1089
+ code: "no_credentials",
1090
+ hint: "Run `purpleturret login`, pass --api-key, or set PURPLETURRET_API_KEY (also read from .env.local / .env in the current directory)."
1091
+ });
1092
+ }
1093
+ return clientFor(apiKey);
1094
+ }
1095
+ };
1096
+ return context;
1097
+ }
1098
+ function describeSource(source) {
1099
+ switch (source) {
1100
+ case "flag":
1101
+ return "command-line flag";
1102
+ case "env":
1103
+ return "environment";
1104
+ case "profile":
1105
+ return "saved profile";
1106
+ case "default":
1107
+ return "default";
1108
+ default:
1109
+ return "none";
1110
+ }
1111
+ }
1112
+
1113
+ // src/lib/pull-writer.ts
1114
+ var PRODUCT_KEY_ORDER = [
1115
+ "key",
1116
+ "name",
1117
+ "description",
1118
+ "price",
1119
+ "billing",
1120
+ "slug",
1121
+ "group",
1122
+ "credits",
1123
+ "delivery",
1124
+ "checkout",
1125
+ "theme",
1126
+ "stripe",
1127
+ "active"
1128
+ ];
1129
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
1130
+ function renderConfigSource(products2, format = "ts") {
1131
+ if (format === "json") {
1132
+ const config = { products: products2.map(orderProductKeys) };
1133
+ return `${JSON.stringify(config, null, 2)}
1134
+ `;
1135
+ }
1136
+ const helpers = /* @__PURE__ */ new Set(["defineConfig", "product"]);
1137
+ const body = products2.map((product) => renderProduct(product, helpers, 4)).join("\n");
1138
+ const imports = ["defineConfig", "money", "product", "usd"].filter((name) => helpers.has(name));
1139
+ const productsBlock = products2.length ? `[
1140
+ ${body}
1141
+ ]` : "[]";
1142
+ return [
1143
+ `import { ${imports.join(", ")} } from "@purpleturret/sdk";`,
1144
+ "",
1145
+ "export default defineConfig({",
1146
+ ` products: ${productsBlock},`,
1147
+ "});",
1148
+ ""
1149
+ ].join("\n");
1150
+ }
1151
+ function renderStarterConfig(format = "ts") {
1152
+ const example = {
1153
+ key: "pro_monthly",
1154
+ name: "Pro",
1155
+ description: "Everything you need to get started.",
1156
+ price: { amount: 2900, currency: "usd" },
1157
+ billing: { type: "recurring", interval: "month" },
1158
+ group: { key: "my_app", tier: { key: "pro", name: "Pro", rank: 1 } },
1159
+ delivery: { method: "none" }
1160
+ };
1161
+ if (format === "json") return renderConfigSource([example], "json");
1162
+ return [
1163
+ "// Purpleturret product catalog. Push with `purpleturret push`; preview with `purpleturret push --dry-run`.",
1164
+ "// Docs: https://purpleturret.com/docs/cli",
1165
+ renderConfigSource([example], "ts")
1166
+ ].join("\n");
1167
+ }
1168
+ function orderProductKeys(product) {
1169
+ const out = {};
1170
+ for (const key of PRODUCT_KEY_ORDER) {
1171
+ if (product[key] !== void 0) out[key] = product[key];
1172
+ }
1173
+ return out;
1174
+ }
1175
+ function renderProduct(product, helpers, indent) {
1176
+ const pad = " ".repeat(indent);
1177
+ const inner = " ".repeat(indent + 2);
1178
+ const lines = [`${pad}product({`];
1179
+ for (const key of PRODUCT_KEY_ORDER) {
1180
+ const value = product[key];
1181
+ if (value === void 0) continue;
1182
+ let rendered;
1183
+ if (key === "price") {
1184
+ rendered = renderPrice(product.price, helpers);
1185
+ } else {
1186
+ rendered = renderValue(value, indent + 2);
1187
+ }
1188
+ lines.push(`${inner}${key}: ${rendered},`);
1189
+ }
1190
+ lines.push(`${pad}}),`);
1191
+ return lines.join("\n");
1192
+ }
1193
+ function renderPrice(price, helpers) {
1194
+ if (price.currency === "usd") {
1195
+ helpers.add("usd");
1196
+ return `usd(${formatDollars(price.amount)})`;
1197
+ }
1198
+ helpers.add("money");
1199
+ return `money(${price.amount}, ${JSON.stringify(price.currency)})`;
1200
+ }
1201
+ function formatDollars(cents) {
1202
+ if (cents % 100 === 0) return String(cents / 100);
1203
+ return (cents / 100).toFixed(2);
1204
+ }
1205
+ function renderKey(key) {
1206
+ return IDENTIFIER.test(key) ? key : JSON.stringify(key);
1207
+ }
1208
+ function isFlat(value) {
1209
+ if (Array.isArray(value)) return value.every((entry) => entry === null || typeof entry !== "object");
1210
+ if (value && typeof value === "object")
1211
+ return Object.values(value).every((entry) => entry === null || typeof entry !== "object");
1212
+ return true;
1213
+ }
1214
+ function renderValue(value, indent) {
1215
+ if (value === null) return "null";
1216
+ if (typeof value === "string") return JSON.stringify(value);
1217
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1218
+ if (typeof value === "undefined") return "undefined";
1219
+ const pad = " ".repeat(indent);
1220
+ const inner = " ".repeat(indent + 2);
1221
+ if (Array.isArray(value)) {
1222
+ if (value.length === 0) return "[]";
1223
+ if (isFlat(value)) {
1224
+ const inline = `[${value.map((entry) => renderValue(entry, indent + 2)).join(", ")}]`;
1225
+ if (inline.length + indent <= 100) return inline;
1226
+ }
1227
+ return `[
1228
+ ${value.map((entry) => `${inner}${renderValue(entry, indent + 2)},`).join("\n")}
1229
+ ${pad}]`;
1230
+ }
1231
+ if (typeof value === "object") {
1232
+ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0);
1233
+ if (entries.length === 0) return "{}";
1234
+ if (isFlat(value)) {
1235
+ const inline = `{ ${entries.map(([key, entry]) => `${renderKey(key)}: ${renderValue(entry, indent + 2)}`).join(", ")} }`;
1236
+ if (inline.length + indent <= 100) return inline;
1237
+ }
1238
+ return `{
1239
+ ${entries.map(([key, entry]) => `${inner}${renderKey(key)}: ${renderValue(entry, indent + 2)},`).join("\n")}
1240
+ ${pad}}`;
1241
+ }
1242
+ return JSON.stringify(value);
1243
+ }
1244
+
1245
+ // src/lib/run.ts
1246
+ import { isCancel } from "@clack/prompts";
1247
+ function defineRun(handler) {
1248
+ return async (command) => {
1249
+ let ctx;
1250
+ try {
1251
+ ctx = await createContext(command.args);
1252
+ await handler(ctx, command.args);
1253
+ } catch (error) {
1254
+ const cliError = toCliError(error, ctx ?? { apiUrl: DEFAULT_BASE_URL, apiUrlSource: "default" });
1255
+ const out = ctx?.out ?? new Output({
1256
+ json: Boolean(command.args.json),
1257
+ verbose: Boolean(command.args.verbose),
1258
+ palette: createPalette(shouldUseColor({ flag: command.args.color }))
1259
+ });
1260
+ out.fail(cliError);
1261
+ process.exitCode = cliError.exitCode;
1262
+ }
1263
+ };
1264
+ }
1265
+ function unwrapPrompt(value) {
1266
+ if (isCancel(value)) throw new CliError("Aborted.", EXIT.ABORTED, { code: "aborted" });
1267
+ return value;
1268
+ }
1269
+
1270
+ // src/commands/init.ts
1271
+ var init = defineCommand({
1272
+ meta: { name: "init", description: "Create a purpleturret.config.ts in the current directory" },
1273
+ args: {
1274
+ ...globalArgs,
1275
+ "from-remote": { type: "boolean", description: "Seed the file with the products already managed on your account" },
1276
+ force: { type: "boolean", description: "Overwrite an existing config file" },
1277
+ format: { type: "string", description: "File format: ts (default) or json" }
1278
+ },
1279
+ run: defineRun(async (ctx, args) => {
1280
+ const formatArg = (args.format ?? "ts").toLowerCase();
1281
+ if (formatArg !== "ts" && formatArg !== "json") {
1282
+ throw new CliError(`Unknown --format "${args.format}"; expected ts or json.`, EXIT.USAGE, { code: "usage" });
1283
+ }
1284
+ const format = formatArg;
1285
+ const target = resolve(ctx.cwd, ctx.configPath ?? `purpleturret.config.${format}`);
1286
+ if (existsSync2(target) && !args.force) {
1287
+ throw new CliError(`${relative(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {
1288
+ code: "file_exists",
1289
+ hint: "Pass --force to overwrite it, or --config <path> to write elsewhere."
1290
+ });
1291
+ }
1292
+ let source;
1293
+ let count;
1294
+ if (args["from-remote"]) {
1295
+ const { products: products2 } = await ctx.client().config.get();
1296
+ const inputs = products2.map(productToInput).filter((input) => input !== null);
1297
+ source = renderConfigSource(inputs, format);
1298
+ count = inputs.length;
1299
+ } else {
1300
+ source = renderStarterConfig(format);
1301
+ count = 1;
1302
+ }
1303
+ await writeFile2(target, source, "utf8");
1304
+ if (ctx.json) {
1305
+ ctx.out.printJson({ written: target, products: count, from_remote: Boolean(args["from-remote"]) });
1306
+ return;
1307
+ }
1308
+ const { palette } = ctx.out;
1309
+ ctx.out.success(
1310
+ `Created ${relative(ctx.cwd, target) || target}${args["from-remote"] ? ` with ${count} product${count === 1 ? "" : "s"} from your account` : ""}`
1311
+ );
1312
+ ctx.out.info("");
1313
+ ctx.out.info("Next steps:");
1314
+ if (format === "ts") ctx.out.info(` ${palette.dim("1.")} pnpm add -D @purpleturret/sdk ${palette.dim("(types + helpers used by the config)")}`);
1315
+ ctx.out.info(` ${palette.dim(format === "ts" ? "2." : "1.")} purpleturret login ${palette.dim("(or set PURPLETURRET_API_KEY)")}`);
1316
+ ctx.out.info(` ${palette.dim(format === "ts" ? "3." : "2.")} purpleturret push --dry-run`);
1317
+ })
1318
+ });
1319
+
1320
+ // src/commands/login.ts
1321
+ import { password } from "@clack/prompts";
1322
+ import { defineCommand as defineCommand2 } from "citty";
1323
+ var login = defineCommand2({
1324
+ meta: { name: "login", description: "Validate a seller API key and save it to ~/.config/purpleturret/credentials.json" },
1325
+ args: { ...globalArgs },
1326
+ run: defineRun(async (ctx) => {
1327
+ let apiKey = ctx.credentialSource === "flag" || ctx.credentialSource === "env" ? ctx.apiKey : null;
1328
+ if (!apiKey) {
1329
+ if (!isInteractive()) {
1330
+ throw new CliError("No API key provided and stdin is not a terminal.", EXIT.USAGE, {
1331
+ code: "missing_api_key",
1332
+ hint: "Pass --api-key <pt_sk_\u2026> or set PURPLETURRET_API_KEY when logging in non-interactively."
1333
+ });
1334
+ }
1335
+ const entered = unwrapPrompt(
1336
+ await password({
1337
+ message: "Paste your seller API key (pt_sk_\u2026). Mint one in Dashboard \u2192 Settings \u2192 Developers.",
1338
+ validate: (value) => value && value.trim().length > 0 ? void 0 : "An API key is required"
1339
+ })
1340
+ );
1341
+ apiKey = entered.trim();
1342
+ }
1343
+ if (apiKey.startsWith("pt_host_")) {
1344
+ throw new CliError("That is a hosting key (pt_host_\u2026). The CLI needs a seller key (pt_sk_\u2026).", EXIT.AUTH, { code: "forbidden_key_type" });
1345
+ }
1346
+ const client = ctx.clientFor(apiKey);
1347
+ const account = await client.account.get();
1348
+ const apiUrl = ctx.apiUrlSource === "default" ? void 0 : ctx.apiUrl;
1349
+ await ctx.credentials.saveProfile(ctx.profileName, {
1350
+ apiKey,
1351
+ apiUrl,
1352
+ email: account.email,
1353
+ keyPrefix: account.key.prefix,
1354
+ scopes: account.key.scopes,
1355
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
1356
+ });
1357
+ if (ctx.json) {
1358
+ ctx.out.printJson({ profile: ctx.profileName, credentials_file: ctx.credentials.path, api_url: ctx.apiUrl, account });
1359
+ return;
1360
+ }
1361
+ const { palette } = ctx.out;
1362
+ ctx.out.success(
1363
+ `Logged in as ${palette.bold(account.email)} with key ${account.key.prefix}\u2026 (scopes: ${account.key.scopes.join(", ") || "none"})`
1364
+ );
1365
+ ctx.out.info(palette.dim(`Saved profile "${ctx.profileName}" to ${ctx.credentials.path} (mode 0600)`));
1366
+ if (!account.stripe.connected) ctx.out.warn("Stripe is not connected on this account yet; `push` cannot create products until it is.");
1367
+ })
1368
+ });
1369
+
1370
+ // src/commands/logout.ts
1371
+ import { defineCommand as defineCommand3 } from "citty";
1372
+ var logout = defineCommand3({
1373
+ meta: { name: "logout", description: "Remove the saved credentials profile" },
1374
+ args: { ...globalArgs },
1375
+ run: defineRun(async (ctx) => {
1376
+ const removed = await ctx.credentials.deleteProfile(ctx.profileName);
1377
+ if (ctx.json) {
1378
+ ctx.out.printJson({ profile: ctx.profileName, removed });
1379
+ return;
1380
+ }
1381
+ if (removed) ctx.out.success(`Removed profile "${ctx.profileName}" from ${ctx.credentials.path}`);
1382
+ else ctx.out.warn(`No profile "${ctx.profileName}" in ${ctx.credentials.path}; nothing to do.`);
1383
+ })
1384
+ });
1385
+
1386
+ // src/commands/products.ts
1387
+ import { defineCommand as defineCommand4 } from "citty";
1388
+
1389
+ // src/lib/render.ts
1390
+ var PRICE_AMOUNT_NOTE = "new Stripe price; existing subscriptions keep the old price";
1391
+ var ACTION_ORDER = ["conflict", "error", "create", "update", "archive", "unchanged"];
1392
+ var ACTION_SYMBOL = {
1393
+ create: "+",
1394
+ update: "~",
1395
+ unchanged: "=",
1396
+ archive: "-",
1397
+ conflict: "!",
1398
+ error: "x"
1399
+ };
1400
+ function formatMoney(money) {
1401
+ const currency = money.currency.toUpperCase();
1402
+ const major = (money.amount / 100).toFixed(2);
1403
+ if (currency === "USD") return `$${major}`;
1404
+ return `${major} ${currency}`;
1405
+ }
1406
+ function describeBilling(billing) {
1407
+ if (billing.type === "recurring") return billing.interval === "year" ? "/year" : "/month";
1408
+ return " one-time";
1409
+ }
1410
+ function describeProduct(product) {
1411
+ return `${product.name} \u2014 ${formatMoney(product.price)}${describeBilling(product.billing)}`;
1412
+ }
1413
+ function formatValue(value) {
1414
+ if (value === void 0 || value === null) return "(none)";
1415
+ if (typeof value === "string") return JSON.stringify(value);
1416
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
1417
+ return JSON.stringify(value);
1418
+ }
1419
+ function paintFor(action, palette) {
1420
+ switch (action) {
1421
+ case "create":
1422
+ return palette.green;
1423
+ case "update":
1424
+ return palette.yellow;
1425
+ case "archive":
1426
+ return palette.red;
1427
+ case "conflict":
1428
+ case "error":
1429
+ return (text) => palette.bold(palette.red(text));
1430
+ default:
1431
+ return palette.dim;
1432
+ }
1433
+ }
1434
+ function renderPlanItem(item, options) {
1435
+ const { palette } = options;
1436
+ const paint = paintFor(item.action, palette);
1437
+ const keyWidth = Math.max(options.keyWidth ?? 0, item.key.length);
1438
+ const symbol = ACTION_SYMBOL[item.action];
1439
+ const label = item.action.padEnd(9);
1440
+ const key = item.key.padEnd(keyWidth);
1441
+ let detail = "";
1442
+ if (item.action === "create" && item.product) detail = describeProduct(item.product);
1443
+ else if (item.action === "unchanged" && item.product) detail = palette.dim(describeProduct(item.product));
1444
+ else if (item.action === "archive" && item.product) detail = describeProduct(item.product);
1445
+ else if ((item.action === "conflict" || item.action === "error") && item.error) detail = `${item.error.code}: ${item.error.message}`;
1446
+ const lines = [`${paint(`${symbol} ${label}`)} ${paint(key)}${detail ? ` ${detail}` : ""}`.trimEnd()];
1447
+ if (item.changes.length === 0) return lines;
1448
+ const pathWidth = Math.max(...item.changes.map((change) => change.path.length));
1449
+ for (const change of item.changes) {
1450
+ const note = change.note ?? (change.path === "price.amount" && item.action !== "create" ? PRICE_AMOUNT_NOTE : void 0);
1451
+ const isNew = change.from === void 0 || change.from === null;
1452
+ const transition = item.action === "create" || isNew && item.action !== "archive" ? formatValue(change.to) : `${formatValue(change.from)} \u2192 ${formatValue(change.to)}`;
1453
+ const line = ` ${paint(symbol)} ${change.path.padEnd(pathWidth)} ${transition}${note ? ` ${palette.dim(`(${note})`)}` : ""}`;
1454
+ lines.push(line);
1455
+ }
1456
+ return lines;
1457
+ }
1458
+ function sortPlanItems(items) {
1459
+ return [...items].sort((a, b) => {
1460
+ const order = ACTION_ORDER.indexOf(a.action) - ACTION_ORDER.indexOf(b.action);
1461
+ return order !== 0 ? order : a.key.localeCompare(b.key);
1462
+ });
1463
+ }
1464
+ function hasChanges(summary) {
1465
+ return summary.create + summary.update + summary.archive + summary.conflict + summary.error > 0;
1466
+ }
1467
+ function renderSummary(summary, options) {
1468
+ const { palette, mode } = options;
1469
+ const parts = [];
1470
+ if (mode === "plan") {
1471
+ if (summary.create) parts.push(palette.green(`${summary.create} to create`));
1472
+ if (summary.update) parts.push(palette.yellow(`${summary.update} to update`));
1473
+ if (summary.archive) parts.push(palette.red(`${summary.archive} to archive`));
1474
+ if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));
1475
+ if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? "" : "s"}`)));
1476
+ if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} error${summary.error === 1 ? "" : "s"}`)));
1477
+ if (!hasChanges(summary))
1478
+ return palette.dim(`No changes. ${summary.unchanged} product${summary.unchanged === 1 ? "" : "s"} already match the config.`);
1479
+ return `Plan: ${parts.join(", ")}.`;
1480
+ }
1481
+ if (summary.create) parts.push(palette.green(`${summary.create} created`));
1482
+ if (summary.update) parts.push(palette.yellow(`${summary.update} updated`));
1483
+ if (summary.archive) parts.push(palette.red(`${summary.archive} archived`));
1484
+ if (summary.unchanged) parts.push(palette.dim(`${summary.unchanged} unchanged`));
1485
+ if (summary.conflict) parts.push(palette.bold(palette.red(`${summary.conflict} conflict${summary.conflict === 1 ? "" : "s"}`)));
1486
+ if (summary.error) parts.push(palette.bold(palette.red(`${summary.error} failed`)));
1487
+ const prefix = summary.error || summary.conflict ? "Apply incomplete" : "Apply complete";
1488
+ return `${prefix}: ${parts.length ? parts.join(", ") : "nothing to do"}.`;
1489
+ }
1490
+ function renderPlan(result, options) {
1491
+ const items = sortPlanItems(result.results);
1492
+ const keyWidth = items.reduce((width, item) => Math.max(width, item.key.length), 0);
1493
+ const lines = [];
1494
+ for (const item of items) {
1495
+ lines.push(...renderPlanItem(item, { ...options, keyWidth }));
1496
+ }
1497
+ if (lines.length) lines.push("");
1498
+ lines.push(renderSummary(result.summary, options));
1499
+ return lines;
1500
+ }
1501
+
1502
+ // src/lib/table.ts
1503
+ function renderTable(headers, rows, dimHeader = (text) => text) {
1504
+ const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length)));
1505
+ const line = (cells) => cells.map((cell, index) => cell.padEnd(widths[index] ?? 0)).join(" ").trimEnd();
1506
+ return [dimHeader(line(headers)), ...rows.map(line)];
1507
+ }
1508
+
1509
+ // src/commands/products.ts
1510
+ var list = defineCommand4({
1511
+ meta: { name: "list", description: "List products on the account (config-managed and dashboard-only)" },
1512
+ args: {
1513
+ ...globalArgs,
1514
+ all: { type: "boolean", description: "Include archived products" }
1515
+ },
1516
+ run: defineRun(async (ctx, args) => {
1517
+ const client = ctx.client();
1518
+ const products2 = [];
1519
+ let cursor;
1520
+ do {
1521
+ const page = await client.products.list({ cursor, limit: 100, includeArchived: Boolean(args.all) });
1522
+ products2.push(...page.data);
1523
+ cursor = page.nextCursor ?? void 0;
1524
+ } while (cursor);
1525
+ if (ctx.json) {
1526
+ ctx.out.printJson({ products: products2 });
1527
+ return;
1528
+ }
1529
+ const { palette } = ctx.out;
1530
+ if (products2.length === 0) {
1531
+ ctx.out.print(palette.dim("No products yet. Run `purpleturret init` and `purpleturret push` to create some."));
1532
+ return;
1533
+ }
1534
+ const rows = products2.map((product) => [
1535
+ product.key ?? palette.dim("(unmanaged)"),
1536
+ product.name,
1537
+ `${formatMoney(product.price)}${describeBilling(product.billing)}`,
1538
+ product.archivedAt ? palette.red("archived") : product.active ? "active" : palette.yellow("inactive"),
1539
+ product.url ?? palette.dim("\u2014")
1540
+ ]);
1541
+ for (const line of renderTable(["KEY", "NAME", "PRICE", "STATUS", "URL"], rows, palette.dim)) ctx.out.print(line);
1542
+ })
1543
+ });
1544
+ var products = defineCommand4({
1545
+ meta: { name: "products", description: "Inspect products on the account" },
1546
+ args: { ...globalArgs },
1547
+ subCommands: { list }
1548
+ });
1549
+
1550
+ // src/commands/pull.ts
1551
+ import { existsSync as existsSync3 } from "fs";
1552
+ import { writeFile as writeFile3 } from "fs/promises";
1553
+ import { relative as relative2, resolve as resolve2 } from "path";
1554
+ import { defineCommand as defineCommand5 } from "citty";
1555
+ var pull = defineCommand5({
1556
+ meta: { name: "pull", description: "Write the account's config-managed products to a local config file" },
1557
+ args: {
1558
+ ...globalArgs,
1559
+ out: { type: "string", description: "Output file (default: purpleturret.config.ts; a .json extension writes JSON)" },
1560
+ force: { type: "boolean", description: "Overwrite an existing file" }
1561
+ },
1562
+ run: defineRun(async (ctx, args) => {
1563
+ const { products: products2, unmanagedCount } = await ctx.client().config.get();
1564
+ const inputs = products2.map(productToInput).filter((input) => input !== null);
1565
+ const out = args.out?.trim();
1566
+ if (ctx.json && !out) {
1567
+ ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: null });
1568
+ return;
1569
+ }
1570
+ const target = resolve2(ctx.cwd, out || "purpleturret.config.ts");
1571
+ const format = target.endsWith(".json") ? "json" : "ts";
1572
+ if (existsSync3(target) && !args.force) {
1573
+ throw new CliError(`${relative2(ctx.cwd, target) || target} already exists.`, EXIT.USAGE, {
1574
+ code: "file_exists",
1575
+ hint: "Pass --force to overwrite it, or --out <path> to write elsewhere."
1576
+ });
1577
+ }
1578
+ await writeFile3(target, renderConfigSource(inputs, format), "utf8");
1579
+ if (ctx.json) {
1580
+ ctx.out.printJson({ products: inputs, unmanaged_count: unmanagedCount, written: target });
1581
+ return;
1582
+ }
1583
+ ctx.out.success(`Wrote ${inputs.length} product${inputs.length === 1 ? "" : "s"} to ${relative2(ctx.cwd, target) || target}`);
1584
+ if (unmanagedCount > 0) {
1585
+ ctx.out.info(
1586
+ ctx.out.palette.dim(
1587
+ `${unmanagedCount} dashboard-only product${unmanagedCount === 1 ? "" : "s"} without a key were skipped (see \`purpleturret products list\`).`
1588
+ )
1589
+ );
1590
+ }
1591
+ })
1592
+ });
1593
+
1594
+ // src/commands/push.ts
1595
+ import { randomUUID } from "crypto";
1596
+ import { relative as relative3 } from "path";
1597
+ import { confirm } from "@clack/prompts";
1598
+ import { defineCommand as defineCommand6 } from "citty";
1599
+
1600
+ // src/lib/config-loader.ts
1601
+ import { existsSync as existsSync4, statSync } from "fs";
1602
+ import { readFile as readFile2 } from "fs/promises";
1603
+ import { dirname as dirname2, extname, isAbsolute, join as join3, resolve as resolve3 } from "path";
1604
+ import { pathToFileURL } from "url";
1605
+ import { createJiti } from "jiti";
1606
+ var CONFIG_FILENAMES = [
1607
+ "purpleturret.config.ts",
1608
+ "purpleturret.config.mts",
1609
+ "purpleturret.config.js",
1610
+ "purpleturret.config.mjs",
1611
+ "purpleturret.config.json"
1612
+ ];
1613
+ function findConfigFile(cwd, explicit) {
1614
+ if (explicit) {
1615
+ const path = isAbsolute(explicit) ? explicit : resolve3(cwd, explicit);
1616
+ if (!existsSync4(path) || !statSync(path).isFile()) {
1617
+ throw new CliError(`Config file not found: ${path}`, EXIT.USAGE, { code: "config_not_found" });
1618
+ }
1619
+ return path;
1620
+ }
1621
+ let dir = resolve3(cwd);
1622
+ const searched = [];
1623
+ for (; ; ) {
1624
+ searched.push(dir);
1625
+ for (const name of CONFIG_FILENAMES) {
1626
+ const candidate = join3(dir, name);
1627
+ if (existsSync4(candidate) && statSync(candidate).isFile()) return candidate;
1628
+ }
1629
+ const isGitRoot = existsSync4(join3(dir, ".git"));
1630
+ const parent = dirname2(dir);
1631
+ if (isGitRoot || parent === dir) break;
1632
+ dir = parent;
1633
+ }
1634
+ 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, {
1635
+ code: "config_not_found",
1636
+ hint: "Run `purpleturret init` to create one, or pass --config <path>."
1637
+ });
1638
+ }
1639
+ async function loadConfigFile(path) {
1640
+ const raw = await importConfigModule(path);
1641
+ const candidate = pickConfigExport(raw, path);
1642
+ const config = validateConfig(candidate);
1643
+ return { path, config };
1644
+ }
1645
+ async function loadConfig(cwd, explicit) {
1646
+ return loadConfigFile(findConfigFile(cwd, explicit));
1647
+ }
1648
+ async function importConfigModule(path) {
1649
+ const ext = extname(path).toLowerCase();
1650
+ if (ext === ".json") {
1651
+ const text = await readFile2(path, "utf8");
1652
+ try {
1653
+ return JSON.parse(text);
1654
+ } catch (error) {
1655
+ throw new CliError(`${path} is not valid JSON: ${error.message}`, EXIT.USAGE, { code: "config_invalid", cause: error });
1656
+ }
1657
+ }
1658
+ if (![".ts", ".mts", ".js", ".mjs", ".cts", ".cjs"].includes(ext)) {
1659
+ throw new CliError(`Unsupported config file extension "${ext}" (${path}). Use .ts, .mts, .js, .mjs or .json.`, EXIT.USAGE, {
1660
+ code: "config_invalid"
1661
+ });
1662
+ }
1663
+ const jiti = createJiti(import.meta.url, { interopDefault: false, moduleCache: false, fsCache: false });
1664
+ try {
1665
+ return await jiti.import(pathToFileURL(path).href);
1666
+ } catch (error) {
1667
+ const message = error instanceof Error ? error.message : String(error);
1668
+ throw new CliError(`Failed to load ${path}: ${message}`, EXIT.USAGE, { code: "config_load_failed", cause: error });
1669
+ }
1670
+ }
1671
+ function pickConfigExport(raw, path) {
1672
+ if (raw && typeof raw === "object") {
1673
+ const record = raw;
1674
+ if ("default" in record && record.default !== void 0) {
1675
+ const def = record.default;
1676
+ if (def && typeof def === "object" && !("products" in def) && "default" in def) {
1677
+ return def.default;
1678
+ }
1679
+ return def;
1680
+ }
1681
+ if ("config" in record && record.config !== void 0) return record.config;
1682
+ if ("products" in record) return raw;
1683
+ }
1684
+ throw new CliError(`${path} must export a config as its default export or a named \`config\` export (see \`purpleturret init\`).`, EXIT.USAGE, {
1685
+ code: "config_invalid"
1686
+ });
1687
+ }
1688
+
1689
+ // src/commands/push.ts
1690
+ var push = defineCommand6({
1691
+ meta: { name: "push", description: "Plan and apply the local config to your Purpleturret account" },
1692
+ args: {
1693
+ ...globalArgs,
1694
+ prune: { type: "boolean", description: "Archive config-managed products that are missing from the config" },
1695
+ "dry-run": { type: "boolean", description: "Show the plan without applying it" },
1696
+ yes: { type: "boolean", alias: "y", description: "Apply without asking for confirmation (required in CI)" }
1697
+ },
1698
+ run: defineRun(async (ctx, args) => {
1699
+ const prune = Boolean(args.prune);
1700
+ const dryRun = Boolean(args["dry-run"]);
1701
+ const yes = Boolean(args.yes);
1702
+ const loaded = await loadConfig(ctx.cwd, ctx.configPath);
1703
+ const products2 = loaded.config.products;
1704
+ const { palette } = ctx.out;
1705
+ ctx.out.info(
1706
+ palette.dim(`Config: ${relative3(ctx.cwd, loaded.path) || loaded.path} (${products2.length} product${products2.length === 1 ? "" : "s"})`)
1707
+ );
1708
+ const client = ctx.client();
1709
+ const plan = await client.config.push({ products: products2, prune, dryRun: true });
1710
+ for (const line of renderPlan(plan, { palette, mode: "plan" })) ctx.out.print(line);
1711
+ if (plan.summary.conflict > 0) {
1712
+ if (ctx.json) {
1713
+ ctx.out.printJson({ plan, applied: false, error: { code: "conflict", message: `${plan.summary.conflict} conflict(s); nothing applied` } });
1714
+ process.exitCode = EXIT.CONFLICT;
1715
+ return;
1716
+ }
1717
+ throw new CliError(`${plan.summary.conflict} conflict${plan.summary.conflict === 1 ? "" : "s"}; nothing was applied.`, EXIT.CONFLICT, {
1718
+ code: "conflict",
1719
+ 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."
1720
+ });
1721
+ }
1722
+ if (plan.summary.error > 0) {
1723
+ if (ctx.json) {
1724
+ ctx.out.printJson({ plan, applied: false, error: { code: "plan_error", message: `${plan.summary.error} product(s) cannot be applied` } });
1725
+ process.exitCode = EXIT.ERROR;
1726
+ return;
1727
+ }
1728
+ throw new CliError(`${plan.summary.error} product${plan.summary.error === 1 ? "" : "s"} cannot be applied; see the errors above.`, EXIT.ERROR, {
1729
+ code: "plan_error"
1730
+ });
1731
+ }
1732
+ if (!hasChanges(plan.summary)) {
1733
+ if (ctx.json) ctx.out.printJson({ plan, applied: false });
1734
+ return;
1735
+ }
1736
+ if (dryRun) {
1737
+ if (ctx.json) ctx.out.printJson({ plan, applied: false });
1738
+ else ctx.out.info(palette.dim("Dry run; nothing was applied. Run `purpleturret push` to apply."));
1739
+ return;
1740
+ }
1741
+ if (!yes) {
1742
+ if (!isInteractive() || ctx.json) {
1743
+ throw new CliError("Refusing to apply without confirmation because this is not an interactive terminal.", EXIT.USAGE, {
1744
+ code: "confirmation_required",
1745
+ hint: "Re-run with --yes to apply non-interactively, or --dry-run to only preview."
1746
+ });
1747
+ }
1748
+ const approved = unwrapPrompt(await confirm({ message: "Apply these changes?", initialValue: false }));
1749
+ if (!approved) throw new CliError("Aborted.", EXIT.ABORTED, { code: "aborted" });
1750
+ }
1751
+ const idempotencyKey = `pt-push-${randomUUID()}`;
1752
+ ctx.out.debug(`Idempotency-Key ${idempotencyKey}`);
1753
+ const result = await applyWithRetry(ctx, client, { products: products2, prune, idempotencyKey });
1754
+ ctx.out.print("");
1755
+ for (const line of renderPlan(result, { palette, mode: "apply" })) ctx.out.print(line);
1756
+ if (ctx.json) ctx.out.printJson({ plan, result, applied: result.applied });
1757
+ if (result.summary.conflict > 0) {
1758
+ process.exitCode = EXIT.CONFLICT;
1759
+ if (!ctx.json)
1760
+ ctx.out.fail(new CliError("The apply hit a conflict; some products may have been applied.", EXIT.CONFLICT, { code: "conflict" }));
1761
+ return;
1762
+ }
1763
+ if (result.summary.error > 0) {
1764
+ process.exitCode = EXIT.ERROR;
1765
+ if (!ctx.json) {
1766
+ ctx.out.fail(
1767
+ new CliError(
1768
+ `${result.summary.error} product${result.summary.error === 1 ? "" : "s"} failed to apply; the rest were applied.`,
1769
+ EXIT.ERROR,
1770
+ {
1771
+ code: "apply_error",
1772
+ hint: "Fix the reported errors and run push again; completed steps are skipped."
1773
+ }
1774
+ )
1775
+ );
1776
+ }
1777
+ return;
1778
+ }
1779
+ const urls = result.results.filter((item) => item.action === "create" && item.product?.url).map((item) => ` ${item.key} ${item.product?.url}`);
1780
+ if (urls.length) {
1781
+ ctx.out.info("");
1782
+ ctx.out.info(palette.dim("Checkout links:"));
1783
+ for (const line of urls) ctx.out.info(line);
1784
+ }
1785
+ })
1786
+ });
1787
+ async function applyWithRetry(ctx, client, options) {
1788
+ try {
1789
+ return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });
1790
+ } catch (error) {
1791
+ if (!(error instanceof PurpleturretNetworkError)) throw error;
1792
+ ctx.out.warn(`Network error while applying (${error.message}); retrying once with the same Idempotency-Key\u2026`);
1793
+ return await client.config.push({ products: options.products, prune: options.prune, dryRun: false, idempotencyKey: options.idempotencyKey });
1794
+ }
1795
+ }
1796
+
1797
+ // src/commands/status.ts
1798
+ import { relative as relative4 } from "path";
1799
+ import { defineCommand as defineCommand7 } from "citty";
1800
+ var status = defineCommand7({
1801
+ meta: { name: "status", description: "Compare the local config with the account (dry run) and print a summary" },
1802
+ args: { ...globalArgs },
1803
+ run: defineRun(async (ctx) => {
1804
+ const loaded = await loadConfig(ctx.cwd, ctx.configPath);
1805
+ const plan = await ctx.client().config.push({ products: loaded.config.products, dryRun: true });
1806
+ if (ctx.json) {
1807
+ ctx.out.printJson({ config: loaded.path, api_url: ctx.apiUrl, summary: plan.summary, results: plan.results });
1808
+ return;
1809
+ }
1810
+ const { palette } = ctx.out;
1811
+ ctx.out.print(`${palette.dim("Config")} ${relative4(ctx.cwd, loaded.path) || loaded.path} (${loaded.config.products.length} products)`);
1812
+ ctx.out.print(`${palette.dim("API URL")} ${ctx.apiUrlSource === "default" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)}`);
1813
+ ctx.out.print(
1814
+ `${palette.dim("Credentials")} ${describeSource(ctx.credentialSource)}${ctx.credentialSource === "profile" ? ` "${ctx.profileName}"` : ""}`
1815
+ );
1816
+ ctx.out.print("");
1817
+ for (const item of sortPlanItems(plan.results)) {
1818
+ if (item.action === "unchanged") continue;
1819
+ const detail = item.error ? ` ${item.error.code}: ${item.error.message}` : "";
1820
+ ctx.out.print(` ${item.action.padEnd(9)} ${item.key}${detail}`);
1821
+ }
1822
+ ctx.out.print(renderSummary(plan.summary, { palette, mode: "plan" }));
1823
+ if (plan.summary.create + plan.summary.update + plan.summary.archive > 0) ctx.out.info(palette.dim("Run `purpleturret push` to apply."));
1824
+ })
1825
+ });
1826
+
1827
+ // src/commands/whoami.ts
1828
+ import { defineCommand as defineCommand8 } from "citty";
1829
+ var whoami = defineCommand8({
1830
+ meta: { name: "whoami", description: "Show the account and key behind the current credentials" },
1831
+ args: { ...globalArgs },
1832
+ run: defineRun(async (ctx) => {
1833
+ const account = await ctx.client().account.get();
1834
+ if (ctx.json) {
1835
+ ctx.out.printJson({ account, api_url: ctx.apiUrl, credential_source: ctx.credentialSource, profile: ctx.profileName });
1836
+ return;
1837
+ }
1838
+ const { palette } = ctx.out;
1839
+ const rows = [
1840
+ ["Account", `${account.email}${account.name ? ` (${account.name})` : ""}`],
1841
+ ["Key", `${account.key.prefix}\u2026${account.key.name ? ` "${account.key.name}"` : ""}`],
1842
+ ["Scopes", account.key.scopes.join(", ") || palette.dim("none")],
1843
+ [
1844
+ "Stripe",
1845
+ account.stripe.connected ? account.stripe.chargesEnabled ? "connected" : "connected (charges not enabled)" : palette.yellow("not connected")
1846
+ ],
1847
+ ["PayPal", account.paypal.connected ? "connected" : palette.dim("not connected")],
1848
+ ["API URL", ctx.apiUrlSource === "default" ? ctx.apiUrl : palette.yellow(ctx.apiUrl)],
1849
+ ["Credentials", `${describeSource(ctx.credentialSource)}${ctx.credentialSource === "profile" ? ` "${ctx.profileName}"` : ""}`]
1850
+ ];
1851
+ const width = Math.max(...rows.map(([label]) => label.length));
1852
+ for (const [label, value] of rows) ctx.out.print(`${palette.dim(label.padEnd(width))} ${value}`);
1853
+ })
1854
+ });
1855
+
1856
+ // src/main.ts
1857
+ var main = defineCommand9({
1858
+ meta: {
1859
+ name: "purpleturret",
1860
+ version: CLI_VERSION,
1861
+ description: "Sync purpleturret.config.ts with your Purpleturret account. Also available as `pt`."
1862
+ },
1863
+ args: { ...globalArgs },
1864
+ setup({ args }) {
1865
+ stashGlobalFlags(args);
1866
+ },
1867
+ subCommands: { init, login, logout, whoami, status, push, pull, products }
1868
+ });
1869
+ async function resolveSubCommand(cmd, rawArgs) {
1870
+ let current = cmd;
1871
+ let parent;
1872
+ let args = rawArgs;
1873
+ for (; ; ) {
1874
+ const subCommands = await current.subCommands;
1875
+ if (!subCommands) return [current, parent];
1876
+ const index = args.findIndex((arg) => !arg.startsWith("-"));
1877
+ const name = index >= 0 ? args[index] : void 0;
1878
+ const next = name ? subCommands[name] : void 0;
1879
+ if (!next) return [current, parent];
1880
+ parent = current;
1881
+ current = next;
1882
+ args = args.slice(index + 1);
1883
+ }
1884
+ }
1885
+ function isCittyError(error) {
1886
+ return error instanceof Error && error.name === "CLIError";
1887
+ }
1888
+ var GLOBAL_STRING_FLAGS = /* @__PURE__ */ new Set(["--config", "--api-url", "--api-key", "--profile"]);
1889
+ function hoistLeadingFlags(rawArgs) {
1890
+ const leading = [];
1891
+ let index = 0;
1892
+ while (index < rawArgs.length) {
1893
+ const token = rawArgs[index];
1894
+ if (!token.startsWith("-")) break;
1895
+ leading.push(token);
1896
+ index += 1;
1897
+ const next = rawArgs[index];
1898
+ if (GLOBAL_STRING_FLAGS.has(token) && next !== void 0 && !next.startsWith("-")) {
1899
+ leading.push(next);
1900
+ index += 1;
1901
+ }
1902
+ }
1903
+ if (index === 0 || index >= rawArgs.length) return rawArgs;
1904
+ return [...rawArgs.slice(index), ...leading];
1905
+ }
1906
+ async function runCli(argv = process.argv.slice(2)) {
1907
+ const root = main;
1908
+ const rawArgs = hoistLeadingFlags(argv);
1909
+ try {
1910
+ if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
1911
+ const [cmd, parent] = await resolveSubCommand(root, rawArgs);
1912
+ await showUsage(cmd, parent);
1913
+ return;
1914
+ }
1915
+ if (rawArgs.length === 1 && rawArgs[0] === "--version") {
1916
+ process.stdout.write(`${CLI_VERSION}
1917
+ `);
1918
+ return;
1919
+ }
1920
+ if (rawArgs.length === 0) {
1921
+ await showUsage(root);
1922
+ return;
1923
+ }
1924
+ await runCommand(root, { rawArgs });
1925
+ } catch (error) {
1926
+ const flags = parseLooseGlobals(rawArgs);
1927
+ const out = new Output({ json: flags.json, verbose: flags.verbose, palette: createPalette(shouldUseColor({ flag: flags.color })) });
1928
+ if (isCittyError(error)) {
1929
+ out.fail(new CliError(error.message, EXIT.USAGE, { code: "usage" }));
1930
+ if (!flags.json) {
1931
+ const [cmd, parent] = await resolveSubCommand(root, rawArgs);
1932
+ await showUsage(cmd, parent);
1933
+ }
1934
+ process.exitCode = EXIT.USAGE;
1935
+ return;
1936
+ }
1937
+ const cliError = error instanceof CliError ? error : new CliError(error instanceof Error ? error.message : String(error), EXIT.ERROR, { cause: error });
1938
+ out.fail(cliError);
1939
+ process.exitCode = cliError.exitCode;
1940
+ }
1941
+ }
1942
+ function parseLooseGlobals(rawArgs) {
1943
+ return {
1944
+ json: rawArgs.includes("--json"),
1945
+ verbose: rawArgs.includes("--verbose"),
1946
+ color: rawArgs.includes("--no-color") ? false : void 0
1947
+ };
1948
+ }
1949
+
1950
+ // src/cli.ts
1951
+ await runCli();
1952
+ //# sourceMappingURL=cli.js.map