@superwall/cli 1.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.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +201 -0
  3. package/dist/actions-MB-eBY64.js +140 -0
  4. package/dist/api-BF7-toqM.js +151 -0
  5. package/dist/api-output-B5hh0q4V.js +20 -0
  6. package/dist/app-K6j9Es7h.js +189 -0
  7. package/dist/asc-CArSwo5D.js +539 -0
  8. package/dist/asc-products-YQ6Oc6YO.js +93 -0
  9. package/dist/auth-CY2cO_NF.js +139 -0
  10. package/dist/auth.d.ts +30 -0
  11. package/dist/auth.js +4 -0
  12. package/dist/billing-DWyfEQ6l.js +80 -0
  13. package/dist/bind-hslFhcTR.js +213 -0
  14. package/dist/chunk-DQxbwPpZ.js +30 -0
  15. package/dist/command-Kwx4ekbo.js +283 -0
  16. package/dist/create-Bbi8BOO1.js +410 -0
  17. package/dist/dev-D0lQDCQI.js +397 -0
  18. package/dist/devtools-8EgLo86w.js +3638 -0
  19. package/dist/doctor-ByeRdMcl.js +88 -0
  20. package/dist/drivers-DVAZgone.js +413 -0
  21. package/dist/entry.d.ts +9 -0
  22. package/dist/entry.js +495 -0
  23. package/dist/existing-CcJrIIAU.js +88 -0
  24. package/dist/feedback-Z0Wk7VC5.js +73 -0
  25. package/dist/git-3OX9u3xE.js +433 -0
  26. package/dist/hosted-CHwaUqLd.js +32 -0
  27. package/dist/integrate-DqOAqK7J.js +863 -0
  28. package/dist/json-C3hPIMkI.js +7 -0
  29. package/dist/login-Dr8UN_Gx.js +290 -0
  30. package/dist/migrate-D92bJTg6.js +114 -0
  31. package/dist/org-B2gy9Pmu.js +40 -0
  32. package/dist/params-Bvq0iqQK.js +52 -0
  33. package/dist/pipeline-CHHIg6BU.js +1056 -0
  34. package/dist/print-skill-BnZAk7dV.js +74 -0
  35. package/dist/promote-CRe9170G.js +88 -0
  36. package/dist/publish-DsODvrOD.js +35 -0
  37. package/dist/push-BDkZUC0v.js +35 -0
  38. package/dist/query-DIllrSnk.js +53 -0
  39. package/dist/resource-CdP1MDla.js +483 -0
  40. package/dist/resources-CVrWwA1K.js +233 -0
  41. package/dist/run-cGGBUMs5.js +89 -0
  42. package/dist/scan-BQexuUPO.js +236 -0
  43. package/dist/skills-DhuUs28u.js +64 -0
  44. package/dist/skills-xrfXt9u0.js +205 -0
  45. package/dist/spawn-DSoTXy_j.js +69 -0
  46. package/dist/spinner-gOxIMz-V.js +18 -0
  47. package/dist/storekit-Ddvs4Ynw.js +29 -0
  48. package/dist/telemetry-CcfrtXdf.js +204 -0
  49. package/dist/token-DHRH8cxi.js +102 -0
  50. package/dist/ui-C4ncRJqd.js +27703 -0
  51. package/dist/update-BiVeR024.js +137 -0
  52. package/dist/upgrade-DYWspApv.js +72 -0
  53. package/package.json +87 -0
  54. package/prompts/actions/dashboard-setup.xml +10 -0
  55. package/prompts/actions/integrate.xml +5 -0
  56. package/prompts/actions/migrate.xml +11 -0
  57. package/prompts/actions/placements-implement.xml +20 -0
  58. package/prompts/actions/placements-review.xml +18 -0
  59. package/prompts/actions/review-fix.xml +18 -0
  60. package/prompts/actions/review.xml +18 -0
  61. package/prompts/commandments.xml +17 -0
  62. package/prompts/context.xml +9 -0
  63. package/skills/README.md +118 -0
  64. package/skills/superwall-dashboard/SKILL.md +81 -0
  65. package/skills/superwall-dashboard/references/setup.md +101 -0
  66. package/skills/superwall-integrate/SKILL.md +76 -0
  67. package/skills/superwall-integrate/references/expo.md +269 -0
  68. package/skills/superwall-integrate/references/flutter.md +285 -0
  69. package/skills/superwall-integrate/references/ios.md +314 -0
  70. package/skills/superwall-integrate/references/react-native.md +245 -0
  71. package/skills/superwall-migrate/SKILL.md +83 -0
  72. package/skills/superwall-migrate/references/adapty.md +229 -0
  73. package/skills/superwall-migrate/references/qonversion.md +227 -0
  74. package/skills/superwall-migrate/references/revenuecat.md +414 -0
  75. package/skills/superwall-placements/SKILL.md +73 -0
  76. package/skills/superwall-placements/references/expo.md +161 -0
  77. package/skills/superwall-placements/references/flutter.md +139 -0
  78. package/skills/superwall-placements/references/ios.md +165 -0
  79. package/skills/superwall-placements/references/react-native.md +145 -0
  80. package/skills/superwall-placements/references/strategy.md +221 -0
  81. package/skills/superwall-review/SKILL.md +75 -0
  82. package/skills/superwall-review/references/expo.md +100 -0
  83. package/skills/superwall-review/references/flutter.md +99 -0
  84. package/skills/superwall-review/references/ios.md +108 -0
  85. package/skills/superwall-review/references/react-native.md +100 -0
@@ -0,0 +1,539 @@
1
+ import "./telemetry-CcfrtXdf.js";
2
+ import "./json-C3hPIMkI.js";
3
+ import "./update-BiVeR024.js";
4
+ import "./token-DHRH8cxi.js";
5
+ import { t as defineCommand } from "./command-Kwx4ekbo.js";
6
+ import "./ui-C4ncRJqd.js";
7
+ import "./spinner-gOxIMz-V.js";
8
+ import { C as rowName } from "./resources-CVrWwA1K.js";
9
+ import { t as requireOrg } from "./org-B2gy9Pmu.js";
10
+ import { t as parseParams } from "./params-Bvq0iqQK.js";
11
+ import { n as emitJson, t as apiCall } from "./api-output-B5hh0q4V.js";
12
+ import { a as ascProxy, c as listAscConfigs, i as listAscApps, n as fetchUnimportedAscProducts, o as createAscConfig, r as findAscAppId, s as deleteAscConfig, t as ascTypeDisplay } from "./asc-products-YQ6Oc6YO.js";
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { dirname, join } from "node:path";
16
+ import { spawn } from "node:child_process";
17
+ import { inflateRawSync } from "node:zlib";
18
+
19
+ //#region src/core/api/asc-index.ts
20
+ const SPEC_URL = "https://developer.apple.com/sample-code/app-store-connect/app-store-connect-openapi-specification.zip";
21
+ const REFRESH_TTL_MS = 10080 * 60 * 1e3;
22
+ function cachePath() {
23
+ return process.env.SUPERWALL_ASC_INDEX_PATH ?? join(homedir(), ".superwall", "asc-index.json");
24
+ }
25
+ let mem;
26
+ function readCachedIndex() {
27
+ if (mem) return mem;
28
+ return mem = JSON.parse(readFileSync(cachePath(), "utf8"));
29
+ }
30
+ function indexIsStale(index$1) {
31
+ return !index$1.fetchedAt || Date.now() - index$1.fetchedAt > REFRESH_TTL_MS;
32
+ }
33
+ function writeCachedIndex(index$1) {
34
+ const path = cachePath();
35
+ mkdirSync(dirname(path), { recursive: true });
36
+ const tmp = `${path}.${process.pid}.tmp`;
37
+ writeFileSync(tmp, JSON.stringify(index$1));
38
+ renameSync(tmp, path);
39
+ mem = index$1;
40
+ }
41
+ function unzipSingleJson(zip) {
42
+ let eocd = zip.length - 22;
43
+ while (eocd >= 0 && zip.readUInt32LE(eocd) !== 101010256) eocd--;
44
+ if (eocd < 0) throw new Error("App Store Connect spec: no zip directory found.");
45
+ let entry = zip.readUInt32LE(eocd + 16);
46
+ const count = zip.readUInt16LE(eocd + 10);
47
+ for (let i = 0; i < count; i++) {
48
+ if (zip.readUInt32LE(entry) !== 33639248) throw new Error("App Store Connect spec: malformed zip directory.");
49
+ const method = zip.readUInt16LE(entry + 10);
50
+ const compSize = zip.readUInt32LE(entry + 20);
51
+ const nameLen = zip.readUInt16LE(entry + 28);
52
+ const extraLen = zip.readUInt16LE(entry + 30);
53
+ const commentLen = zip.readUInt16LE(entry + 32);
54
+ const localOff = zip.readUInt32LE(entry + 42);
55
+ if (zip.toString("utf8", entry + 46, entry + 46 + nameLen).endsWith(".json")) {
56
+ const lNameLen = zip.readUInt16LE(localOff + 26);
57
+ const lExtraLen = zip.readUInt16LE(localOff + 28);
58
+ const start = localOff + 30 + lNameLen + lExtraLen;
59
+ const data = zip.subarray(start, start + compSize);
60
+ return method === 0 ? data : inflateRawSync(data);
61
+ }
62
+ entry += 46 + nameLen + extraLen + commentLen;
63
+ }
64
+ throw new Error("App Store Connect spec: no JSON entry in archive.");
65
+ }
66
+ const METHODS = [
67
+ "get",
68
+ "post",
69
+ "patch",
70
+ "delete",
71
+ "put"
72
+ ];
73
+ function deriveIndex(spec) {
74
+ const schemas = spec.components?.schemas ?? {};
75
+ const deref = (node) => node && node.$ref ? schemas[node.$ref.split("/").pop()] : node;
76
+ const fields = (schema) => {
77
+ const out = {};
78
+ if (!schema) return out;
79
+ const required = new Set(schema.required ?? []);
80
+ for (const [name, raw] of Object.entries(schema.properties ?? {})) {
81
+ const p = deref(raw);
82
+ const f = { required: required.has(name) };
83
+ if (Array.isArray(p.enum)) f.enum = p.enum;
84
+ else if (p.type) f.type = p.type;
85
+ out[name] = f;
86
+ }
87
+ return out;
88
+ };
89
+ const relationships = (schema) => {
90
+ const out = {};
91
+ if (!schema) return out;
92
+ const required = new Set(schema.required ?? []);
93
+ for (const [name, raw] of Object.entries(schema.properties ?? {})) {
94
+ const data = deref(deref(raw)?.properties?.data);
95
+ const rel = { required: required.has(name) };
96
+ const ident = data?.type === "array" ? deref(data.items) : data;
97
+ rel.many = data?.type === "array";
98
+ const t = deref(ident?.properties?.type);
99
+ if (Array.isArray(t?.enum)) rel.target = t.enum[0];
100
+ out[name] = rel;
101
+ }
102
+ return out;
103
+ };
104
+ const paths = {};
105
+ for (const [path, ops] of Object.entries(spec.paths ?? {})) for (const method of METHODS) {
106
+ const op = ops[method];
107
+ if (!op) continue;
108
+ const entry = {
109
+ opId: op.operationId,
110
+ summary: op.summary,
111
+ ...op.deprecated ? { deprecated: true } : {}
112
+ };
113
+ const bodySchema = deref(deref(op.requestBody)?.content?.["application/json"]?.schema);
114
+ if (bodySchema) {
115
+ const data = deref(bodySchema.properties?.data);
116
+ const type = deref(data?.properties?.type);
117
+ if (Array.isArray(type?.enum)) entry.dataType = type.enum[0];
118
+ const attrs = fields(deref(data?.properties?.attributes));
119
+ const rels = relationships(deref(data?.properties?.relationships));
120
+ if (Object.keys(attrs).length) entry.attributes = attrs;
121
+ if (Object.keys(rels).length) entry.relationships = rels;
122
+ }
123
+ const query = (op.parameters ?? []).map(deref).filter((p) => p?.in === "query").map((p) => p.name);
124
+ if (query.length) entry.query = query;
125
+ (paths[path] ??= {})[method] = entry;
126
+ }
127
+ return {
128
+ specVersion: String(spec.info?.version ?? "unknown"),
129
+ openapi: String(spec.openapi ?? "unknown"),
130
+ paths
131
+ };
132
+ }
133
+ async function fetchAscIndex() {
134
+ const res = await fetch(SPEC_URL);
135
+ if (!res.ok) throw new Error(`Couldn't fetch the App Store Connect schema (HTTP ${res.status}). Check your connection and retry.`);
136
+ const zip = Buffer.from(await res.arrayBuffer());
137
+ const index$1 = deriveIndex(JSON.parse(unzipSingleJson(zip).toString("utf8")));
138
+ index$1.fetchedAt = Date.now();
139
+ return index$1;
140
+ }
141
+ function triggerBackgroundRefresh() {
142
+ if (process.env.SW_ASC_REFRESH === "1") return;
143
+ const entry = process.argv[1];
144
+ if (!entry) return;
145
+ try {
146
+ spawn(process.execPath, [
147
+ entry,
148
+ "asc",
149
+ "docs",
150
+ "refresh",
151
+ "--quiet"
152
+ ], {
153
+ detached: true,
154
+ stdio: "ignore",
155
+ env: {
156
+ ...process.env,
157
+ SW_ASC_REFRESH: "1"
158
+ }
159
+ }).unref();
160
+ } catch {
161
+ return;
162
+ }
163
+ }
164
+
165
+ //#endregion
166
+ //#region src/core/api/asc-schema.ts
167
+ function index() {
168
+ return readCachedIndex();
169
+ }
170
+ function segments(path) {
171
+ return path.split("?")[0].split("/").filter(Boolean);
172
+ }
173
+ function matches(tmpl, concrete) {
174
+ if (tmpl.length !== concrete.length) return false;
175
+ return tmpl.every((s, i) => s.startsWith("{") || concrete[i].startsWith("{") || s === concrete[i]);
176
+ }
177
+ function lookupAscOp(method, rawPath) {
178
+ const m = method.toLowerCase();
179
+ const concrete = segments(rawPath);
180
+ for (const [tmpl, ops] of Object.entries(index().paths)) if (ops[m] && matches(segments(tmpl), concrete)) return {
181
+ path: tmpl,
182
+ op: ops[m]
183
+ };
184
+ }
185
+ function castAttr(field, v) {
186
+ if (typeof v !== "string" || !field) return v;
187
+ if (field.type === "boolean") {
188
+ if (v === "true") return true;
189
+ if (v === "false") return false;
190
+ }
191
+ if ((field.type === "integer" || field.type === "number") && v.trim() !== "") {
192
+ const n = Number(v);
193
+ if (!Number.isNaN(n)) return n;
194
+ }
195
+ return v;
196
+ }
197
+ function lastId(rawPath) {
198
+ const segs = segments(rawPath);
199
+ const last = segs[segs.length - 1];
200
+ return last && !last.startsWith("{") ? last : void 0;
201
+ }
202
+ function buildAscBody(op, method, rawPath, flat) {
203
+ if (!op.dataType) return flat;
204
+ if (flat.data && typeof flat.data === "object") return flat;
205
+ const attributes = {};
206
+ const relationships = {};
207
+ for (const [k, v] of Object.entries(flat)) {
208
+ const rel = op.relationships?.[k];
209
+ if (rel) {
210
+ const ids = rel.many ? Array.isArray(v) ? v : [v] : v;
211
+ relationships[k] = { data: rel.many ? ids.map((id) => ({
212
+ type: rel.target,
213
+ id: String(id)
214
+ })) : {
215
+ type: rel.target,
216
+ id: String(ids)
217
+ } };
218
+ } else attributes[k] = castAttr(op.attributes?.[k], v);
219
+ }
220
+ const data = { type: op.dataType };
221
+ if (method.toLowerCase() === "patch") {
222
+ const id = lastId(rawPath);
223
+ if (id) data.id = id;
224
+ }
225
+ if (Object.keys(attributes).length) data.attributes = attributes;
226
+ if (Object.keys(relationships).length) data.relationships = relationships;
227
+ return { data };
228
+ }
229
+ function validateAscBody(op, method, body) {
230
+ const problems = [];
231
+ const data = body.data ?? {};
232
+ const attrs = data.attributes ?? {};
233
+ const rels = data.relationships ?? {};
234
+ const isPatch = method.toLowerCase() === "patch";
235
+ for (const [name, f] of Object.entries(op.attributes ?? {})) {
236
+ if (f.required && !isPatch && !(name in attrs)) problems.push(`missing required attribute: ${name}`);
237
+ const val = attrs[name];
238
+ if (f.enum && typeof val === "string" && !f.enum.includes(val)) problems.push(`${name} "${val}" not allowed — use ${f.enum.join("|")}`);
239
+ }
240
+ for (const [name, r] of Object.entries(op.relationships ?? {})) if (r.required && !isPatch && !(name in rels)) problems.push(`missing required relationship: ${name}${r.target ? ` → ${r.target}` : ""}`);
241
+ return problems;
242
+ }
243
+ function exampleInvocation(method, path, op) {
244
+ const parts = [`superwall asc ${method.toLowerCase()} ${path}`];
245
+ for (const [name, f] of Object.entries(op.attributes ?? {})) {
246
+ if (!f.required) continue;
247
+ parts.push(`-d ${name}=${f.enum ? f.enum[0] : `<${f.type ?? "value"}>`}`);
248
+ }
249
+ for (const [name, r] of Object.entries(op.relationships ?? {})) if (r.required) parts.push(`-d ${name}=<${r.target ?? "id"} id>`);
250
+ return parts.join(" ");
251
+ }
252
+ function renderOp(method, path, op) {
253
+ const lines = [];
254
+ lines.push(`### ${method.toUpperCase()} ${path}`);
255
+ if (op.summary) lines.push(op.summary);
256
+ if (op.deprecated) lines.push("> ⚠ Deprecated in the App Store Connect API.");
257
+ const attrs = Object.entries(op.attributes ?? {});
258
+ const rels = Object.entries(op.relationships ?? {});
259
+ if (op.dataType) lines.push("", `Body → \`data.type: ${op.dataType}\``);
260
+ if (attrs.length) {
261
+ lines.push("", "Attributes:");
262
+ for (const [name, f] of attrs) {
263
+ const kind = f.enum ? f.enum.join("|") : f.type ?? "";
264
+ lines.push(` - ${name} ${kind}${f.required ? " (required)" : ""}`);
265
+ }
266
+ }
267
+ if (rels.length) {
268
+ lines.push("", "Relationships:");
269
+ for (const [name, r] of rels) lines.push(` - ${name} → ${r.target ?? "?"}${r.many ? "[]" : ""}${r.required ? " (required)" : ""}`);
270
+ }
271
+ if (op.query?.length) lines.push("", `Query: ${op.query.map((q) => `\`${q}\``).join(", ")}`);
272
+ lines.push("", "Example:", ` ${exampleInvocation(method, path, op)}`);
273
+ return lines.join("\n");
274
+ }
275
+ function renderAscDocs(query, verb) {
276
+ const idx = index();
277
+ const header = `App Store Connect API — spec ${idx.specVersion}\n`;
278
+ if (!query.trim()) {
279
+ const roots = /* @__PURE__ */ new Set();
280
+ for (const tmpl of Object.keys(idx.paths)) if (segments(tmpl).length === 2) roots.add(tmpl);
281
+ const list = [...roots].sort();
282
+ return `${header}\n${list.length} top-level resources. Run \`asc docs <path> [verb]\` for a schema, or \`asc docs <search term>\` to filter.
283
+
284
+ ` + list.join("\n");
285
+ }
286
+ if (query.startsWith("/")) {
287
+ const concrete = segments(query);
288
+ const out = [];
289
+ for (const [tmpl, ops] of Object.entries(idx.paths)) {
290
+ if (!matches(segments(tmpl), concrete)) continue;
291
+ for (const [method, op] of Object.entries(ops)) {
292
+ if (verb && method !== verb.toLowerCase()) continue;
293
+ out.push(renderOp(method, tmpl, op));
294
+ }
295
+ }
296
+ if (!out.length) return `${header}\nNo operation matches ${query}. Try \`asc docs <search term>\`.`;
297
+ return `${header}\n${out.join("\n\n")}`;
298
+ }
299
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
300
+ const hits = [];
301
+ for (const [tmpl, ops] of Object.entries(idx.paths)) for (const [method, op] of Object.entries(ops)) {
302
+ const hay = `${tmpl} ${op.summary ?? ""} ${op.opId ?? ""}`.toLowerCase();
303
+ if (terms.every((t) => hay.includes(t))) hits.push(`${method.toUpperCase().padEnd(6)} ${tmpl}${op.summary ? ` — ${op.summary}` : ""}`);
304
+ }
305
+ if (!hits.length) return `${header}\nNothing matches "${query}".`;
306
+ return `${header}\n${hits.slice(0, 60).join("\n")}${hits.length > 60 ? `\n… ${hits.length - 60} more` : ""}\n\nRun \`asc docs <path> [verb]\` for a full schema.`;
307
+ }
308
+
309
+ //#endregion
310
+ //#region src/commands/platform/keys.ts
311
+ async function runAscKeys(ctx, api) {
312
+ const action = ctx.argv.value ?? "list";
313
+ if (action === "list") return listKeys(ctx, api);
314
+ if (action === "set") return setKey(ctx, api);
315
+ if (action === "rm") return removeKey(ctx, api);
316
+ throw new Error(`Unknown "asc keys ${action}". Use list | set | rm.`);
317
+ }
318
+ async function listKeys(ctx, api) {
319
+ const configs = await apiCall(ctx, "Loading credentials", () => listAscConfigs(api));
320
+ if (ctx.json) return emitJson(ctx, configs);
321
+ if (configs.length === 0) {
322
+ ctx.ui.step("No App Store Connect credentials yet");
323
+ if (ctx.interactive) {
324
+ if (await ctx.ui.confirm({ message: "Connect an App Store Connect key now?" })) return setKey(ctx, api);
325
+ return;
326
+ }
327
+ ctx.ui.info("Add one: superwall asc keys set --key-id <id> --issuer <id> --key-file <path.p8>");
328
+ return;
329
+ }
330
+ ctx.ui.step(`${configs.length} App Store Connect credential${configs.length === 1 ? "" : "s"}`);
331
+ for (const c of configs) ctx.ui.info(`\`${rowName(c)}\` ${c.team_id ?? c.id ?? ""}`);
332
+ }
333
+ async function setKey(ctx, api) {
334
+ const input = await resolveKeyInput(ctx);
335
+ if (!input) return void ctx.ui.warn("Cancelled.");
336
+ const { keyId, issuerId, keyFile, accountName } = input;
337
+ if (ctx.dryRun) {
338
+ const plan = {
339
+ dryRun: true,
340
+ action: "set",
341
+ keyId,
342
+ issuerId,
343
+ keyFile
344
+ };
345
+ ctx.json ? emitJson(ctx, plan) : ctx.ui.info(`[dry-run] would upload ASC key ${keyId} (issuer ${issuerId}) from ${keyFile}`);
346
+ return;
347
+ }
348
+ const privateKey = readFileSync(keyFile, "utf8");
349
+ const created = await apiCall(ctx, "Connecting App Store Connect", () => createAscConfig(api, {
350
+ keyId,
351
+ issuerId,
352
+ privateKey,
353
+ accountName
354
+ }));
355
+ if (ctx.json) return emitJson(ctx, created);
356
+ ctx.ui.success(`App Store Connect connected ${created.team_id ?? created.id ?? ""}`);
357
+ }
358
+ async function removeKey(ctx, api) {
359
+ const teamId = ctx.argv.value2;
360
+ if (!teamId) throw new Error("Usage: superwall asc keys rm <team_id>");
361
+ if (ctx.dryRun) {
362
+ const plan = {
363
+ dryRun: true,
364
+ action: "rm",
365
+ teamId
366
+ };
367
+ ctx.json ? emitJson(ctx, plan) : ctx.ui.info(`[dry-run] would delete ASC credential ${teamId}`);
368
+ return;
369
+ }
370
+ await apiCall(ctx, "Removing credential", () => deleteAscConfig(api, teamId));
371
+ if (ctx.json) return emitJson(ctx, {
372
+ deleted: true,
373
+ teamId
374
+ });
375
+ ctx.ui.success(`Removed App Store Connect credential ${teamId}`);
376
+ }
377
+ async function resolveKeyInput(ctx) {
378
+ const { argv, ui, interactive } = ctx;
379
+ let keyId = argv["key-id"]?.trim();
380
+ let issuerId = argv.issuer?.trim();
381
+ let keyFile = argv["key-file"]?.trim();
382
+ let name = argv.name?.trim();
383
+ if (interactive && (!keyId || !issuerId || !keyFile)) {
384
+ ui.note("Create a key in App Store Connect → Users and Access → Integrations →\nApp Store Connect API. You'll need its Key ID, the Issuer ID, and the\ndownloaded .p8 file. This is stored org-wide for the signed proxy.", "Connect App Store Connect");
385
+ if (!keyId) {
386
+ const v = await ui.text({
387
+ message: "Key ID",
388
+ placeholder: "2X9R4HXF34",
389
+ validate: (s) => s?.trim() ? void 0 : "Required"
390
+ });
391
+ if (v === null) return null;
392
+ keyId = v.trim();
393
+ }
394
+ if (!issuerId) {
395
+ const v = await ui.text({
396
+ message: "Issuer ID",
397
+ placeholder: "57246542-96fe-1a63-e053-0824d011072a",
398
+ validate: (s) => s?.trim() ? void 0 : "Required"
399
+ });
400
+ if (v === null) return null;
401
+ issuerId = v.trim();
402
+ }
403
+ if (!keyFile) {
404
+ const v = await ui.text({
405
+ message: "Path to the .p8 key file",
406
+ placeholder: "~/Downloads/AuthKey_2X9R4HXF34.p8",
407
+ validate: (s) => {
408
+ const path$1 = expandHome(s?.trim() ?? "");
409
+ if (!path$1) return "Required";
410
+ if (!existsSync(path$1)) return "No file at that path";
411
+ }
412
+ });
413
+ if (v === null) return null;
414
+ keyFile = v.trim();
415
+ }
416
+ if (!name) {
417
+ const v = await ui.text({
418
+ message: "Name (optional)",
419
+ placeholder: "App Store Connect"
420
+ });
421
+ if (v === null) return null;
422
+ name = v.trim();
423
+ }
424
+ }
425
+ if (!keyId || !issuerId || !keyFile) throw new Error("Usage: superwall asc keys set --key-id <id> --issuer <id> --key-file <path.p8> [--name <name>]");
426
+ const path = expandHome(keyFile);
427
+ if (!existsSync(path)) throw new Error(`Couldn't find the .p8 key file at ${keyFile}`);
428
+ return {
429
+ keyId,
430
+ issuerId,
431
+ keyFile: path,
432
+ accountName: name || "App Store Connect"
433
+ };
434
+ }
435
+ function expandHome(path) {
436
+ return path.startsWith("~/") ? `${homedir()}/${path.slice(2)}` : path;
437
+ }
438
+
439
+ //#endregion
440
+ //#region src/commands/platform/asc.ts
441
+ const VERBS = new Set([
442
+ "get",
443
+ "post",
444
+ "patch",
445
+ "delete"
446
+ ]);
447
+ async function ensureAscIndex(ctx) {
448
+ let cached;
449
+ try {
450
+ cached = readCachedIndex();
451
+ } catch {
452
+ cached = void 0;
453
+ }
454
+ if (!cached) {
455
+ writeCachedIndex(await apiCall(ctx, "Fetching App Store Connect schema", () => fetchAscIndex()));
456
+ return;
457
+ }
458
+ if (indexIsStale(cached)) triggerBackgroundRefresh();
459
+ }
460
+ const runAsc = defineCommand({
461
+ name: "asc",
462
+ auth: "required",
463
+ output: "both",
464
+ async run(ctx) {
465
+ const target = String(ctx.argv.target ?? "");
466
+ if (target === "docs") {
467
+ const query = String(ctx.argv.value ?? "");
468
+ if (query === "refresh") {
469
+ const quiet = Boolean(ctx.argv.quiet);
470
+ const index$1 = quiet ? await fetchAscIndex() : await apiCall(ctx, "Updating App Store Connect schema", () => fetchAscIndex());
471
+ writeCachedIndex(index$1);
472
+ if (quiet) return;
473
+ if (ctx.json) return emitJson(ctx, { specVersion: index$1.specVersion });
474
+ process.stdout.write(`App Store Connect schema updated — spec ${index$1.specVersion}\n`);
475
+ return;
476
+ }
477
+ await ensureAscIndex(ctx);
478
+ const md = renderAscDocs(query, ctx.argv.value2);
479
+ if (ctx.json) return emitJson(ctx, { markdown: md });
480
+ process.stdout.write(`${md}\n`);
481
+ return;
482
+ }
483
+ await requireOrg(ctx.api, ctx.interactive);
484
+ if (target === "keys") return runAscKeys(ctx, ctx.api);
485
+ if (VERBS.has(target)) {
486
+ const path = String(ctx.argv.value ?? "");
487
+ if (!path.startsWith("/")) throw new Error(`Path must start with "/", e.g. /v1/apps`);
488
+ let body = parseParams(ctx.argv.d);
489
+ if (target === "post" || target === "patch") {
490
+ await ensureAscIndex(ctx);
491
+ const found = lookupAscOp(target, path);
492
+ if (found) {
493
+ body = buildAscBody(found.op, target, path, body);
494
+ const problems = validateAscBody(found.op, target, body);
495
+ if (problems.length && !ctx.argv.force) throw new Error(`Invalid ${target.toUpperCase()} ${path} body:\n` + problems.map((p) => ` • ${p}`).join("\n") + `\nFix and retry, run \`superwall asc docs ${path} ${target}\`, or pass --force to send as-is.`);
496
+ }
497
+ }
498
+ const teamId$1 = await resolveTeam(ctx, ctx.api);
499
+ return emitJson(ctx, await apiCall(ctx, `${target.toUpperCase()} ${path}`, () => ascProxy(ctx.api, teamId$1, target, path, body)));
500
+ }
501
+ const teamId = await resolveTeam(ctx, ctx.api);
502
+ if (target.startsWith("/")) return emitJson(ctx, await apiCall(ctx, `GET ${target}`, () => ascProxy(ctx.api, teamId, "GET", target)));
503
+ if (target === "apps") {
504
+ const apps = await apiCall(ctx, "Loading apps", () => listAscApps(ctx.api, teamId));
505
+ if (ctx.json) return emitJson(ctx, apps);
506
+ ctx.ui.step(`${apps.length} app${apps.length === 1 ? "" : "s"}`);
507
+ for (const a of apps) ctx.ui.info(`\`${a.name ?? a.id}\` ${a.bundleId ?? ""} ${a.id}`);
508
+ return;
509
+ }
510
+ if (target === "products" || target === "subscriptions" || target === "iaps") {
511
+ const appArg = ctx.argv.value;
512
+ if (!appArg) throw new Error(`Usage: superwall asc ${target} <bundle-id | asc-app-id>`);
513
+ const ascAppId = /^\d+$/.test(appArg) ? appArg : await apiCall(ctx, "Finding app", () => findAscAppId(ctx.api, teamId, appArg));
514
+ if (!ascAppId) throw new Error(`No App Store Connect app found for "${appArg}".`);
515
+ const all = await apiCall(ctx, "Loading products", () => fetchUnimportedAscProducts(ctx.api, teamId, ascAppId, /* @__PURE__ */ new Set()));
516
+ const isSub = (t) => t.includes("SUBSCRIPTION") && t !== "NON_RENEWING_SUBSCRIPTION";
517
+ const rows = target === "subscriptions" ? all.filter((p) => isSub(p.type)) : target === "iaps" ? all.filter((p) => !isSub(p.type)) : all;
518
+ if (ctx.json) return emitJson(ctx, rows);
519
+ ctx.ui.step(`${rows.length} product${rows.length === 1 ? "" : "s"}`);
520
+ for (const p of rows) ctx.ui.info(`\`${p.productId}\` ${ascTypeDisplay(p.type)}${p.subscriptionPeriod ? ` ${p.subscriptionPeriod}` : ""}`);
521
+ return;
522
+ }
523
+ throw new Error(`Unknown "${target}". Use get|post|patch|delete <path>, a raw path, or: apps | products | subscriptions | iaps | docs | keys`);
524
+ }
525
+ });
526
+ async function resolveTeam(ctx, api) {
527
+ const flag = ctx.argv.team;
528
+ if (flag) return flag;
529
+ const configs = await apiCall(ctx, "Finding App Store Connect", () => listAscConfigs(api));
530
+ if (configs.length === 0) throw new Error("App Store Connect isn't connected. Run `superwall asc keys set --help`.");
531
+ if (configs.length > 1) {
532
+ const teams = configs.map((c) => String(c.team_id ?? c.id ?? "")).join(", ");
533
+ throw new Error(`Multiple App Store Connect teams (${teams}). Pass --team <id>.`);
534
+ }
535
+ return String(configs[0].team_id ?? configs[0].id ?? "");
536
+ }
537
+
538
+ //#endregion
539
+ export { runAsc };
@@ -0,0 +1,93 @@
1
+ //#region src/core/api/asc.ts
2
+ function ascBase(api) {
3
+ const orgId = api.org.id;
4
+ if (!orgId) throw new Error("No organization selected - run `superwall orgs use <id|name>` first.");
5
+ return `/v2/organizations/${orgId}/app-store-connect`;
6
+ }
7
+ async function listAscConfigs(api) {
8
+ return (await api.get(ascBase(api))).data ?? [];
9
+ }
10
+ function createAscConfig(api, c) {
11
+ return api.post(ascBase(api), {
12
+ key_id: c.keyId,
13
+ issuer_id: c.issuerId,
14
+ private_key: c.privateKey,
15
+ ...c.accountName ? { account_name: c.accountName } : {}
16
+ });
17
+ }
18
+ function deleteAscConfig(api, teamId) {
19
+ return api.del(`${ascBase(api)}/${teamId}`);
20
+ }
21
+ function ascProxy(api, teamId, method, ascPath, body) {
22
+ const path = `${ascBase(api)}/proxy/${teamId}${ascPath}`;
23
+ switch (method.toUpperCase()) {
24
+ case "GET": return api.get(path);
25
+ case "POST": return api.post(path, body ?? {});
26
+ case "PATCH": return api.patch(path, body ?? {});
27
+ case "DELETE": return api.del(path);
28
+ default: throw new Error(`Unsupported method: ${method}`);
29
+ }
30
+ }
31
+ function ascProxyGet(api, teamId, ascPath) {
32
+ return ascProxy(api, teamId, "GET", ascPath);
33
+ }
34
+
35
+ //#endregion
36
+ //#region src/core/api/asc-products.ts
37
+ function attr(r, key) {
38
+ const v = r.attributes?.[key];
39
+ return typeof v === "string" ? v : void 0;
40
+ }
41
+ async function findAscAppId(api, teamId, bundleId) {
42
+ return (await ascProxyGet(api, teamId, `/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}&fields[apps]=bundleId&limit=10`)).data?.[0]?.id;
43
+ }
44
+ async function listAscApps(api, teamId) {
45
+ return ((await ascProxyGet(api, teamId, "/v1/apps?limit=200&fields[apps]=bundleId,name")).data ?? []).map((a) => ({
46
+ id: a.id,
47
+ name: attr(a, "name"),
48
+ bundleId: attr(a, "bundleId")
49
+ }));
50
+ }
51
+ async function fetchUnimportedAscProducts(api, teamId, ascAppId, existingIds) {
52
+ const byId = /* @__PURE__ */ new Map();
53
+ const groups = await ascProxyGet(api, teamId, `/v1/apps/${ascAppId}/subscriptionGroups?limit=200`);
54
+ for (const group of groups.data ?? []) {
55
+ const groupName = attr(group, "referenceName") ?? "";
56
+ const subs = await ascProxyGet(api, teamId, `/v1/subscriptionGroups/${group.id}/subscriptions?limit=200`);
57
+ for (const sub of subs.data ?? []) {
58
+ const productId = attr(sub, "productId");
59
+ if (productId && !byId.has(productId)) byId.set(productId, {
60
+ productId,
61
+ referenceName: attr(sub, "name") ?? groupName,
62
+ type: "AUTO_RENEWABLE_SUBSCRIPTION",
63
+ state: attr(sub, "state") ?? "UNKNOWN",
64
+ subscriptionPeriod: attr(sub, "subscriptionPeriod"),
65
+ subscriptionGroupName: groupName
66
+ });
67
+ }
68
+ }
69
+ const iaps = await ascProxyGet(api, teamId, `/v1/apps/${ascAppId}/inAppPurchases?limit=200`);
70
+ for (const iap of iaps.data ?? []) {
71
+ const productId = attr(iap, "productId");
72
+ if (productId && !byId.has(productId)) byId.set(productId, {
73
+ productId,
74
+ referenceName: attr(iap, "referenceName") ?? "",
75
+ type: attr(iap, "inAppPurchaseType") ?? "UNKNOWN",
76
+ state: attr(iap, "state") ?? "UNKNOWN"
77
+ });
78
+ }
79
+ return [...byId.values()].filter((p) => !existingIds.has(p.productId));
80
+ }
81
+ function ascTypeDisplay(type) {
82
+ switch (type) {
83
+ case "AUTO_RENEWABLE_SUBSCRIPTION":
84
+ case "AUTOMATICALLY_RENEWABLE_SUBSCRIPTION": return "Subscription";
85
+ case "NON_CONSUMABLE": return "Non-Consumable";
86
+ case "CONSUMABLE": return "Consumable";
87
+ case "NON_RENEWING_SUBSCRIPTION": return "Non-Renewing";
88
+ default: return type;
89
+ }
90
+ }
91
+
92
+ //#endregion
93
+ export { ascProxy as a, listAscConfigs as c, listAscApps as i, fetchUnimportedAscProducts as n, createAscConfig as o, findAscAppId as r, deleteAscConfig as s, ascTypeDisplay as t };