@superwall/cli 1.6.2 → 2.0.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 (162) hide show
  1. package/README.md +281 -34
  2. package/dist/apple-CkKlHBZ9.js +195 -0
  3. package/dist/auth.d.ts +4 -19
  4. package/dist/auth.js +4 -2
  5. package/dist/{actions-H7f6knyY.js → billing-XCZU_T46.js} +98 -28
  6. package/dist/{bind-BIzaGq8K.js → bind-drne__Ys.js} +38 -33
  7. package/dist/{build-B7BS1rF2.js → build-Gpdq5QXP.js} +20 -26
  8. package/dist/client-BZ1UbpXz.js +66 -0
  9. package/dist/client-DP6Rc0t_.js +176 -0
  10. package/dist/config-BO1Y87kV.js +105 -0
  11. package/dist/create-BBrtgUgS.js +969 -0
  12. package/dist/{create-CwnnNqv4.js → create-Cwc3SRWJ.js} +194 -168
  13. package/dist/create-Yvf2gStM.js +19 -0
  14. package/dist/doctor-C9ldpPFC.js +83 -0
  15. package/dist/{drivers-6RMOPIdn.js → drivers-DNrx4LWA.js} +185 -172
  16. package/dist/entry.d.ts +0 -5
  17. package/dist/entry.js +28083 -801
  18. package/dist/environment-DF1qKlny.js +58 -0
  19. package/dist/{existing-DHpPn1y6.js → existing-78LWSsqS.js} +12 -6
  20. package/dist/held-Cy8Wl4D1.js +1112 -0
  21. package/dist/held-Ddw1XSsr.js +16 -0
  22. package/dist/input-vi0bou04.js +42 -0
  23. package/dist/{integrate-BR2LR-EK.js → integrate-DcJhpXy8.js} +277 -253
  24. package/dist/kinds-GFXB3sYu.js +11 -0
  25. package/dist/log-NVhVe_oe.js +62 -0
  26. package/dist/login-B2TsCE2H.js +53 -0
  27. package/dist/login-BoBe8Psl.js +16 -0
  28. package/dist/{login-Bhxgqwtm.js → login-D0lh3_JI.js} +144 -66
  29. package/dist/lookup-D-nmmAbw.js +71 -0
  30. package/dist/migrate-Cfec564E.js +274 -0
  31. package/dist/notification-url-YDbq6FMA.js +100 -0
  32. package/dist/{open-studio-BnVD6tJ9.js → open-Ba2vBl1_.js} +34 -43
  33. package/dist/org-D0g_q3mv.js +35 -0
  34. package/dist/output-Ggzq5_-t.js +122 -0
  35. package/dist/paths-DxSLdpOI.js +29 -0
  36. package/dist/playbook-DIeb7hne.js +53 -0
  37. package/dist/{asc-products-Dvcyef3_.js → products-DH_fK9tY.js} +6 -39
  38. package/dist/promote-COD4fYdz.js +91 -0
  39. package/dist/push-CncywhkQ.js +482 -0
  40. package/dist/push-CtD4FZQV.js +22 -0
  41. package/dist/registry-DSrosOYs.js +10228 -0
  42. package/dist/{reports-DqMs9xNR.js → reports-DdPq4blM.js} +7 -6
  43. package/dist/{resources-Bf9O1JNM.js → resources-Dqr01Dep.js} +150 -55
  44. package/dist/{run-D-NbZLpj.js → run-C9qg_QlC.js} +16 -22
  45. package/dist/scan-Cv5uOwVY.js +4 -0
  46. package/dist/{scan-BmAW413l.js → scan-DLrsrFS9.js} +48 -37
  47. package/dist/scope-V336uz8j.js +198 -0
  48. package/dist/screenshot-file-0UETadF8.js +16 -0
  49. package/dist/{selection-BGi6GyxC.js → selection-Rdw-ZUoG.js} +94 -51
  50. package/dist/send-BxD9yf6F.js +150 -0
  51. package/dist/{dev-CgGAb5Al.js → server-D0tGG8C4.js} +82 -87
  52. package/dist/server-z1LH94R_.js +22 -0
  53. package/dist/session-1AV_Bs_d.js +6 -0
  54. package/dist/session-CFAmMhem.js +40 -0
  55. package/dist/session-D_nEWKXT.js +768 -0
  56. package/dist/skills/animate-onboarding/SKILL.md +467 -0
  57. package/dist/skills/animate-onboarding/references/engine.md +494 -0
  58. package/dist/skills/animate-onboarding/references/framework/Question.tsx +71 -0
  59. package/dist/skills/animate-onboarding/references/framework/README.md +40 -0
  60. package/dist/skills/animate-onboarding/references/framework/answers.ts +19 -0
  61. package/dist/skills/animate-onboarding/references/framework/flow.ts +80 -0
  62. package/dist/skills/animate-onboarding/references/framework/handoffs.ts +869 -0
  63. package/dist/skills/animate-onboarding/references/framework/layout.tsx +113 -0
  64. package/dist/skills/animate-onboarding/references/framework/motion.css +559 -0
  65. package/dist/skills/animate-onboarding/references/framework/useStoryRouter.ts +48 -0
  66. package/dist/skills/animate-onboarding/references/handoffs.md +375 -0
  67. package/dist/skills/animate-onboarding/references/imageReady.ts +92 -0
  68. package/dist/skills/animate-onboarding/references/morphFrame.ts +356 -0
  69. package/dist/skills/animate-onboarding/references/performance.md +41 -0
  70. package/dist/skills/animate-onboarding/references/web-runtime/README.md +17 -0
  71. package/dist/skills/animate-onboarding/references/web-runtime/handoffs.ts +858 -0
  72. package/dist/skills/animate-onboarding/references/web-runtime/story-motion.css +301 -0
  73. package/dist/skills/index.json +37 -0
  74. package/dist/skills/mobile-design/SKILL.md +447 -0
  75. package/dist/skills/mobile-design/references/responsive.md +162 -0
  76. package/dist/skills/onboarding-questions/SKILL.md +231 -0
  77. package/dist/skills/onboarding-questions/references/arpu-questions.md +139 -0
  78. package/dist/skills/onboarding-questions/references/craft.md +142 -0
  79. package/dist/skills/onboarding-questions/references/example-reflective.md +117 -0
  80. package/dist/skills/superwall/SKILL.md +82 -9
  81. package/dist/skills/superwall/references/api.md +153 -37
  82. package/dist/skills/superwall/references/apple-setup.md +316 -0
  83. package/dist/skills/superwall/references/asc.md +74 -38
  84. package/dist/skills/superwall/references/data-analytics.md +55 -21
  85. package/dist/skills/superwall/workflows/dashboard/playbook.md +3 -3
  86. package/dist/skills/superwall/workflows/dashboard/setup.md +8 -8
  87. package/dist/skills/superwall/workflows/migrate/adapty.md +6 -6
  88. package/dist/skills/superwall/workflows/migrate/playbook.md +4 -4
  89. package/dist/skills/superwall/workflows/migrate/qonversion.md +5 -5
  90. package/dist/skills/superwall/workflows/migrate/revenuecat.md +6 -6
  91. package/dist/skills/superwall/workflows/placements/android.md +2 -2
  92. package/dist/skills/superwall/workflows/placements/expo.md +2 -2
  93. package/dist/skills/superwall/workflows/placements/flutter.md +2 -2
  94. package/dist/skills/superwall/workflows/placements/ios.md +2 -2
  95. package/dist/skills/superwall/workflows/placements/playbook.md +2 -2
  96. package/dist/skills/superwall/workflows/placements/react-native.md +2 -2
  97. package/dist/skills/superwall/workflows/placements/strategy.md +2 -2
  98. package/dist/skills/superwall/workflows/review/playbook.md +1 -1
  99. package/dist/skills/superwall-editor/SKILL.md +61 -0
  100. package/dist/skills/superwall-editor/references/cli.md +135 -0
  101. package/dist/skills/superwall-editor/references/design.md +51 -0
  102. package/dist/skills/superwall-editor/references/native-elements.md +171 -0
  103. package/dist/skills/superwall-editor/references/workflow.md +65 -0
  104. package/dist/skills/superwall-editor/scripts/sw-editor.sh +662 -0
  105. package/dist/skills/superwall-framework/SKILL.md +78 -28
  106. package/dist/skills/superwall-framework/references/cli.md +58 -28
  107. package/dist/skills/superwall-framework/references/examples.md +4 -3
  108. package/dist/skills/superwall-framework/references/layout.md +30 -8
  109. package/dist/skills/superwall-framework/references/migrate-from-editor.md +1 -1
  110. package/dist/skills/superwall-framework/references/onboarding-state.md +245 -0
  111. package/dist/skills/wwdc/SKILL.md +22 -0
  112. package/dist/skills/wwdc/references/docs.md +52 -0
  113. package/dist/skills/wwdc/scripts/wwdc.sh +266 -0
  114. package/dist/{skills-AxAf7bDB.js → skills-BvFOa4y6.js} +99 -122
  115. package/dist/skills-DMG4bpKk.js +14 -0
  116. package/dist/{spawn-DSoTXy_j.js → spawn-DmmmHIP-.js} +14 -12
  117. package/dist/spinner-CneRK5rk.js +294 -0
  118. package/dist/storage-DYvmIOHa.d.ts +16 -0
  119. package/dist/storage-s2Dnz-yl.js +31 -0
  120. package/dist/storekit-DafAnGkM.js +16 -0
  121. package/dist/storekit-yY_kS2iR.js +47 -0
  122. package/dist/telemetry-DtG92m5O.js +56 -0
  123. package/dist/theme-DUsCh-Vd.js +25 -0
  124. package/dist/timing-BVxPrYq3.js +5 -0
  125. package/dist/{token-BGAVPSQc.js → token-DzRh7dI1.js} +6 -38
  126. package/dist/tools.d.ts +96 -0
  127. package/dist/tools.js +11178 -0
  128. package/dist/ui-D_qf3Gvw.js +53 -0
  129. package/dist/upgrade-Bt4Ouw1y.js +117 -0
  130. package/dist/upgrade-Cqy5orjb.js +7 -0
  131. package/package.json +10 -5
  132. package/dist/api-Dv3LyZ5m.js +0 -151
  133. package/dist/api-output-aJNw7Syy.js +0 -20
  134. package/dist/app-mJC5NDtW.js +0 -189
  135. package/dist/asa-D6H7Pjae.js +0 -1194
  136. package/dist/asc-xCin0akG.js +0 -539
  137. package/dist/auth-ZlLL-Gko.js +0 -139
  138. package/dist/billing-C8kBge_S.js +0 -80
  139. package/dist/command-3fGYyC8r.js +0 -301
  140. package/dist/dev-Dx99K183.js +0 -22
  141. package/dist/doctor-CyUvut31.js +0 -88
  142. package/dist/feedback-RKyGuQ8_.js +0 -152
  143. package/dist/hosted-BeGVAntr.js +0 -32
  144. package/dist/migrate-C-4ISELN.js +0 -284
  145. package/dist/org-CQduIOic.js +0 -40
  146. package/dist/output-C-4UKMot.js +0 -136
  147. package/dist/params-l3CrvRtR.js +0 -51
  148. package/dist/pipeline-CHX0Syre.js +0 -977
  149. package/dist/print-skill-BiZLdCKv.js +0 -74
  150. package/dist/promote-Pgpz-3xl.js +0 -88
  151. package/dist/publish-BPeuc3lq.js +0 -35
  152. package/dist/push-DcSQ4odB.js +0 -35
  153. package/dist/query-CWLaZkdm.js +0 -53
  154. package/dist/resource-jwASPCrw.js +0 -483
  155. package/dist/skills-FK5aDuNV.js +0 -64
  156. package/dist/spinner-DFctF_Jw.js +0 -18
  157. package/dist/storekit-CC4gnTI6.js +0 -29
  158. package/dist/telemetry-Ch9cCTI-.js +0 -169
  159. package/dist/ui-4gLyfrgl.js +0 -27737
  160. package/dist/update-DIXbL-H9.js +0 -59
  161. package/dist/upgrade-De7JMI1g.js +0 -72
  162. /package/dist/{devtools-8EgLo86w.js → devtools-ByZ6XYnn.js} +0 -0
@@ -0,0 +1,969 @@
1
+ import { r as formatJson, t as blocks } from "./output-Ggzq5_-t.js";
2
+ import { _ as VERSION, d as ENV_APPLE_PASSWORD, u as ENV_APPLE_ID, y as appleCredentialsFromEnv } from "./environment-DF1qKlny.js";
3
+ import { t as ApiError } from "./client-DP6Rc0t_.js";
4
+ import { i as savedKey, m as KEY_LABEL, n as testModeWarning, o as chooseIosApp, s as resolveApp, t as upsertHeldKey, x as keyKind, y as findIntegrations } from "./held-Cy8Wl4D1.js";
5
+ import { t as apiCall } from "./spinner-CneRK5rk.js";
6
+ import { n as SUPERWALL_HOME } from "./paths-DxSLdpOI.js";
7
+ import { D as listField, O as parseJson, T as field, k as textField } from "./resources-Dqr01Dep.js";
8
+ import { c as replaceAppPurchaseKey, s as replaceAppAscKey } from "./client-BZ1UbpXz.js";
9
+ import { t as timing } from "./timing-BVxPrYq3.js";
10
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { createHash, pbkdf2Sync, randomBytes } from "node:crypto";
13
+
14
+ //#region src/core/app-store-connect/apple-web/pending.ts
15
+ const LIFETIME_MS = 600 * 1e3;
16
+ function dir() {
17
+ return SUPERWALL_HOME();
18
+ }
19
+ function file() {
20
+ return join(dir(), "apple-sign-in.json");
21
+ }
22
+ function writePending(pending, now = Date.now()) {
23
+ mkdirSync(dir(), {
24
+ recursive: true,
25
+ mode: 448
26
+ });
27
+ const stored = {
28
+ savedAt: now,
29
+ pending
30
+ };
31
+ writeFileSync(file(), `${formatJson(stored)}\n`, { mode: 384 });
32
+ }
33
+ function readPending(now = Date.now()) {
34
+ try {
35
+ if (!existsSync(file())) return void 0;
36
+ const stored = JSON.parse(readFileSync(file(), "utf8"));
37
+ if (now - stored.savedAt > LIFETIME_MS) {
38
+ removePending();
39
+ return;
40
+ }
41
+ return stored.pending;
42
+ } catch {
43
+ return;
44
+ }
45
+ }
46
+ function removePending() {
47
+ rmSync(file(), { force: true });
48
+ }
49
+
50
+ //#endregion
51
+ //#region src/core/app-store-connect/apple-web/cookies.ts
52
+ function parse(url, line) {
53
+ const [pair = "", ...attributes] = line.split(";");
54
+ const separator = pair.indexOf("=");
55
+ if (separator <= 0) return void 0;
56
+ const cookie = {
57
+ name: pair.slice(0, separator).trim(),
58
+ value: pair.slice(separator + 1).trim(),
59
+ domain: url.hostname.toLowerCase(),
60
+ hostOnly: true,
61
+ path: "/"
62
+ };
63
+ let expired = false;
64
+ for (const attribute of attributes) {
65
+ const split = attribute.indexOf("=");
66
+ const key = (split === -1 ? attribute : attribute.slice(0, split)).trim().toLowerCase();
67
+ const value = split === -1 ? "" : attribute.slice(split + 1).trim();
68
+ if (key === "domain" && value) {
69
+ cookie.domain = value.replace(/^\./, "").toLowerCase();
70
+ cookie.hostOnly = false;
71
+ } else if (key === "path" && value.startsWith("/")) cookie.path = value;
72
+ else if (key === "max-age" && Number(value) <= 0) expired = true;
73
+ else if (key === "expires") {
74
+ const at = Date.parse(value);
75
+ if (!Number.isNaN(at) && at <= Date.now()) expired = true;
76
+ }
77
+ }
78
+ return {
79
+ cookie,
80
+ expired
81
+ };
82
+ }
83
+ function matches(cookie, url) {
84
+ const host = url.hostname.toLowerCase();
85
+ if (!(cookie.hostOnly ? host === cookie.domain : host === cookie.domain || host.endsWith(`.${cookie.domain}`))) return false;
86
+ if (cookie.path === "/") return true;
87
+ return url.pathname === cookie.path || url.pathname.startsWith(`${cookie.path.replace(/\/$/, "")}/`);
88
+ }
89
+ function createCookieJar(initial = []) {
90
+ let cookies = [...initial];
91
+ const same = (a, b) => {
92
+ return a.name === b.name && a.domain === b.domain && a.path === b.path;
93
+ };
94
+ return {
95
+ store(url, setCookie) {
96
+ for (const line of setCookie) {
97
+ const parsed = parse(url, line);
98
+ if (!parsed) continue;
99
+ cookies = cookies.filter((existing) => !same(existing, parsed.cookie));
100
+ if (!parsed.expired) cookies.push(parsed.cookie);
101
+ }
102
+ },
103
+ header(url) {
104
+ const sent = cookies.filter((cookie) => matches(cookie, url));
105
+ if (sent.length === 0) return void 0;
106
+ return sent.map((cookie) => `${cookie.name}=${cookie.value}`).join("; ");
107
+ },
108
+ snapshot: () => cookies.map((cookie) => ({ ...cookie }))
109
+ };
110
+ }
111
+
112
+ //#endregion
113
+ //#region src/core/app-store-connect/apple-web/hashcash.ts
114
+ function leadingZeroBits(sum, bits) {
115
+ const whole = Math.floor(bits / 8);
116
+ for (let index = 0; index < whole; index++) if (sum[index] !== 0) return false;
117
+ const remaining = bits % 8;
118
+ return remaining === 0 || (sum.readUInt8(whole) & 255 << 8 - remaining) === 0;
119
+ }
120
+ const two = (value) => String(value).padStart(2, "0");
121
+ function mintHashcash(bits, challenge, now) {
122
+ const date = String(now.getUTCFullYear()) + two(now.getUTCMonth() + 1) + two(now.getUTCDate()) + two(now.getUTCHours()) + two(now.getUTCMinutes()) + two(now.getUTCSeconds());
123
+ for (let counter = 0;; counter++) {
124
+ const candidate = `1:${bits}:${date}:${challenge}::${counter}`;
125
+ if (leadingZeroBits(createHash("sha1").update(candidate).digest(), bits)) return candidate;
126
+ }
127
+ }
128
+
129
+ //#endregion
130
+ //#region src/core/app-store-connect/apple-web/srp.ts
131
+ const MODULUS_HEX = "ac6bdb41324a9a9bf166de5e1389582faf72b6651987ee07fc3192943db56050a37329cbb4a099ed8193e0757767a13dd52312ab4b03310dcd7f48a9da04fd50e8083969edb767b0cf6095179a163ab3661a05fbd5faaae82918a9962f0b93b855f97993ec975eeaa80d740adbf4ff747359d041d5c33ea71d281e446b14773bca97b43a23fb801676bd207a436c6481f1d2b9078717461a5b9d32e688f87748544523b524b0d57d5ea77a2775d2ecfa032cfbdbf52fb3786160279004e57ae6af874e7303ce53299ccc041c7bc308d82a5698f3a8d0c38271ae35f8e9dbfbb694b5c803d89f7ae435de236d525f54759b65e372fcd68ef20fa7111f9e4aff73";
132
+ const MODULUS = BigInt(`0x${MODULUS_HEX}`);
133
+ const GENERATOR = 2n;
134
+ const WIDTH = 512;
135
+ const SECRET_BYTES = 256;
136
+ const DERIVED_BYTES = 32;
137
+ const digest = (bytes) => createHash("sha256").update(bytes).digest();
138
+ const hashHex = (hex) => digest(Buffer.from(hex, "hex")).toString("hex");
139
+ const evenHex = (value) => {
140
+ const hex = value.toString(16);
141
+ return hex.length % 2 === 1 ? `0${hex}` : hex;
142
+ };
143
+ const paddedHash = (...values) => {
144
+ return BigInt(`0x${hashHex(values.map((value) => value.padStart(WIDTH, "0")).join(""))}`);
145
+ };
146
+ function modPow(base, exponent, modulus) {
147
+ let result = 1n;
148
+ let factor = base % modulus;
149
+ let remaining = exponent;
150
+ while (remaining > 0n) {
151
+ if (remaining & 1n) result = result * factor % modulus;
152
+ factor = factor * factor % modulus;
153
+ remaining >>= 1n;
154
+ }
155
+ return result;
156
+ }
157
+ function createEphemeral(random = randomBytes) {
158
+ const secret = BigInt(`0x${random(SECRET_BYTES).toString("hex")}`);
159
+ return {
160
+ secret,
161
+ publicKey: Buffer.from(evenHex(modPow(GENERATOR, secret, MODULUS)), "hex").toString("base64")
162
+ };
163
+ }
164
+ function derivePassword(input, salt) {
165
+ const hashed = digest(Buffer.from(input.password, "utf8"));
166
+ return pbkdf2Sync(input.protocol === "s2k_fo" ? Buffer.from(hashed.toString("hex"), "utf8") : hashed, salt, input.iterations, DERIVED_BYTES, "sha256");
167
+ }
168
+ function createProof(input) {
169
+ const salt = Buffer.from(input.salt, "base64");
170
+ const serverHex = Buffer.from(input.serverPublicKey, "base64").toString("hex");
171
+ if (serverHex.length > WIDTH) throw new Error("Apple sent an invalid sign-in challenge.");
172
+ const serverPublic = BigInt(`0x${serverHex || "0"}`);
173
+ if (serverPublic % MODULUS === 0n) throw new Error("Apple sent an invalid sign-in challenge.");
174
+ const clientHex = evenHex(modPow(GENERATOR, input.secret, MODULUS));
175
+ const saltHex = salt.toString("hex");
176
+ const derivedHex = derivePassword(input, salt).toString("hex");
177
+ const x = BigInt(`0x${hashHex(saltHex + hashHex(`3a${derivedHex}`))}`);
178
+ const k = paddedHash(MODULUS_HEX, evenHex(GENERATOR));
179
+ const u = paddedHash(clientHex, serverHex);
180
+ if (u === 0n) throw new Error("Apple sent an invalid sign-in challenge.");
181
+ const sessionKey = hashHex(evenHex(modPow(((serverPublic - k * modPow(GENERATOR, x, MODULUS) % MODULUS) % MODULUS + MODULUS) % MODULUS, input.secret + u * x, MODULUS)));
182
+ const modulusHash = digest(Buffer.from(MODULUS_HEX, "hex"));
183
+ const generatorHash = digest(Buffer.from(evenHex(GENERATOR).padStart(WIDTH, "0"), "hex"));
184
+ const mixed = Buffer.from(modulusHash.map((byte, index) => byte ^ generatorHash.readUInt8(index)));
185
+ const accountHash = digest(Buffer.from(input.accountName, "utf8")).toString("hex");
186
+ const m1 = hashHex(mixed.toString("hex") + accountHash + saltHex + clientHex + serverHex + sessionKey);
187
+ const m2 = hashHex(clientHex + m1 + sessionKey);
188
+ return {
189
+ m1: Buffer.from(m1, "hex").toString("base64"),
190
+ m2: Buffer.from(m2, "hex").toString("base64")
191
+ };
192
+ }
193
+
194
+ //#endregion
195
+ //#region src/core/app-store-connect/apple-web/transport.ts
196
+ const MAX_REDIRECTS = 5;
197
+ var AppleUnreachableError = class extends Error {
198
+ constructor(cause) {
199
+ super("Couldn't reach Apple. Check your network or proxy, then try again.");
200
+ this.name = "AppleUnreachableError";
201
+ this.cause = cause;
202
+ }
203
+ };
204
+ function createTransport(jar, doFetch = fetch) {
205
+ return { async send(method, url, request = {}) {
206
+ let target = new URL(url);
207
+ let verb = method;
208
+ let body = request.body === void 0 ? void 0 : JSON.stringify(request.body);
209
+ for (let hop = 0;; hop++) {
210
+ const cookie = jar.header(target);
211
+ let response;
212
+ try {
213
+ response = await doFetch(target, {
214
+ method: verb,
215
+ redirect: "manual",
216
+ headers: {
217
+ accept: "application/json",
218
+ "user-agent": `superwall-cli/${VERSION}`,
219
+ ...body === void 0 ? {} : { "content-type": "application/json" },
220
+ ...request.headers,
221
+ ...cookie ? { cookie } : {}
222
+ },
223
+ ...body === void 0 ? {} : { body }
224
+ });
225
+ } catch (error) {
226
+ throw new AppleUnreachableError(error);
227
+ }
228
+ jar.store(target, response.headers.getSetCookie());
229
+ const location = response.headers.get("location");
230
+ if (!(response.status >= 300 && response.status < 400 && location) || hop >= MAX_REDIRECTS) return {
231
+ status: response.status,
232
+ headers: response.headers,
233
+ body: await response.text()
234
+ };
235
+ target = new URL(location, target);
236
+ if (response.status !== 307 && response.status !== 308) {
237
+ verb = "GET";
238
+ body = void 0;
239
+ }
240
+ }
241
+ } };
242
+ }
243
+
244
+ //#endregion
245
+ //#region src/core/app-store-connect/apple-web/session.ts
246
+ const AUTH_URL = "https://idmsa.apple.com/appleauth/auth";
247
+ const ASC_URL = "https://appstoreconnect.apple.com";
248
+ var AppleError = class extends Error {
249
+ constructor(kind, message, status) {
250
+ super(message);
251
+ this.kind = kind;
252
+ this.status = status;
253
+ this.name = "AppleError";
254
+ }
255
+ };
256
+ function serviceMessages(body) {
257
+ return [
258
+ ...listField(body, "serviceErrors"),
259
+ ...listField(body, "service_errors"),
260
+ ...listField(body, "validationErrors")
261
+ ].map((error) => {
262
+ const message = textField(error, "message") ?? textField(error, "title") ?? "request rejected";
263
+ const code = field(error, "code");
264
+ return typeof code === "string" || typeof code === "number" ? `${message} (${code})` : message;
265
+ });
266
+ }
267
+ function failureMessage(response) {
268
+ const body = parseJson(response.body);
269
+ const service = serviceMessages(body);
270
+ if (service.length > 0) return service.join("; ");
271
+ const first = listField(body, "errors")[0];
272
+ return textField(first, "detail") ?? textField(first, "title") ?? `HTTP ${response.status}`;
273
+ }
274
+ function phoneMatches(requested, masked) {
275
+ const clean = (value) => value.replace(/[\s \-()"]/g, "");
276
+ const number = clean(requested);
277
+ const label = clean(masked);
278
+ const bullets = [...label].filter((character) => character === "•").length;
279
+ if (bullets === 0) return number === label;
280
+ const prefix = label.slice(0, label.indexOf("•"));
281
+ const suffix = label.slice(label.lastIndexOf("•") + 1);
282
+ const hidden = number.slice(prefix.length, number.length - suffix.length);
283
+ return number.startsWith(prefix) && number.endsWith(suffix) && /^\d+$/.test(hidden) && hidden.length >= Math.max(1, bullets - 2) && hidden.length <= bullets;
284
+ }
285
+ function readTeam(value) {
286
+ const id = field(value, "providerId");
287
+ if (typeof id !== "number") return void 0;
288
+ return {
289
+ id,
290
+ issuerId: textField(value, "publicProviderId"),
291
+ name: textField(value, "name") ?? String(id)
292
+ };
293
+ }
294
+ function createAppleSession(options = {}) {
295
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
296
+ const doFetch = options.fetch ?? fetch;
297
+ const jar = createCookieJar(options.pending?.cookies);
298
+ const transport = createTransport(jar, doFetch);
299
+ let appleId = options.pending?.appleId ?? "";
300
+ let serviceKey = options.pending?.serviceKey ?? "";
301
+ let sessionId = options.pending?.sessionId ?? "";
302
+ let scnt = options.pending?.scnt ?? "";
303
+ let factor = options.pending?.factor;
304
+ let current;
305
+ let available = [];
306
+ const authHeaders = () => ({
307
+ accept: "application/json, text/javascript",
308
+ "x-requested-with": "XMLHttpRequest",
309
+ "x-apple-widget-key": serviceKey,
310
+ ...sessionId ? { "x-apple-id-session-id": sessionId } : {},
311
+ ...scnt ? { scnt } : {}
312
+ });
313
+ const auth = async (method, path, body) => {
314
+ const response = await transport.send(method, `${AUTH_URL}${path}`, {
315
+ headers: authHeaders(),
316
+ body
317
+ });
318
+ const parsed = parseJson(response.body);
319
+ if (response.status < 200 || response.status >= 300 || serviceMessages(parsed).length > 0) throw new AppleError("verification", failureMessage(response), response.status);
320
+ return parsed;
321
+ };
322
+ const resolveServiceKey = async () => {
323
+ let location;
324
+ try {
325
+ location = (await doFetch(`${ASC_URL}/logout`, {
326
+ method: "HEAD",
327
+ redirect: "manual"
328
+ })).headers.get("location");
329
+ } catch (error) {
330
+ throw new AppleUnreachableError(error);
331
+ }
332
+ if (!location) throw new AppleError("request", "Apple didn't return its sign-in configuration.");
333
+ const key = new URL(location, ASC_URL).searchParams.get("widgetKey")?.trim();
334
+ if (!key) throw new AppleError("request", "Apple didn't return its sign-in configuration.");
335
+ return key;
336
+ };
337
+ const createHashcash = async () => {
338
+ const response = await transport.send("GET", `${AUTH_URL}/signin?widgetKey=${encodeURIComponent(serviceKey)}`);
339
+ const bits = Number(response.headers.get("x-apple-hc-bits"));
340
+ const challenge = response.headers.get("x-apple-hc-challenge");
341
+ if (!challenge || !Number.isInteger(bits) || bits <= 0) return void 0;
342
+ return mintHashcash(bits, challenge, now());
343
+ };
344
+ const resolveTeams = async () => {
345
+ const response = await transport.send("GET", `${ASC_URL}/olympus/v1/session`);
346
+ if (response.status < 200 || response.status >= 300) throw new AppleError(response.status === 401 || response.status === 403 ? "forbidden" : "request", `App Store Connect didn't accept the sign-in: ${failureMessage(response)}`, response.status);
347
+ const body = parseJson(response.body);
348
+ current = readTeam(field(body, "provider"));
349
+ const listed = listField(body, "availableProviders").map(readTeam).filter((team) => team !== void 0);
350
+ available = current && !listed.some((team) => team.id === current?.id) ? [current, ...listed] : listed;
351
+ appleId = textField(field(body, "user"), "emailAddress") ?? appleId;
352
+ if (!current) throw new AppleError("forbidden", "This Apple Account has no App Store Connect team. Join the Apple Developer Program or accept your team invite, then try again.");
353
+ };
354
+ const listTrustedPhones = (optionsBody) => {
355
+ return listField(optionsBody, "trustedPhoneNumbers").flatMap((phone) => {
356
+ const id = field(phone, "id");
357
+ if (typeof id !== "number") return [];
358
+ return [{
359
+ id,
360
+ mode: textField(phone, "pushMode") ?? "sms",
361
+ label: textField(phone, "numberWithDialCode") ?? ""
362
+ }];
363
+ });
364
+ };
365
+ const requireContinuation = () => {
366
+ if (!serviceKey || !sessionId || !scnt) throw new AppleError("verification", "The Apple sign-in expired. Start again.");
367
+ };
368
+ return {
369
+ async signIn(email, password) {
370
+ appleId = email.trim();
371
+ sessionId = "";
372
+ scnt = "";
373
+ factor = void 0;
374
+ serviceKey = await resolveServiceKey();
375
+ const ephemeral = createEphemeral(options.random);
376
+ const init = await transport.send("POST", `${AUTH_URL}/signin/init`, {
377
+ headers: authHeaders(),
378
+ body: {
379
+ a: ephemeral.publicKey,
380
+ accountName: appleId,
381
+ protocols: ["s2k", "s2k_fo"]
382
+ }
383
+ });
384
+ if (init.status === 401 || init.status === 403) throw new AppleError("credentials", "Incorrect Apple Account email or password.", init.status);
385
+ const challenge = parseJson(init.body);
386
+ const salt = textField(challenge, "salt");
387
+ const serverPublicKey = textField(challenge, "b");
388
+ const iterations = field(challenge, "iteration");
389
+ const protocol = textField(challenge, "protocol");
390
+ if (init.status !== 200 || !salt || !serverPublicKey || typeof iterations !== "number" || protocol !== "s2k" && protocol !== "s2k_fo") throw new AppleError("request", `Apple sign-in failed: ${failureMessage(init)}`, init.status);
391
+ const proof = createProof({
392
+ accountName: appleId,
393
+ password,
394
+ protocol,
395
+ salt,
396
+ iterations,
397
+ serverPublicKey,
398
+ secret: ephemeral.secret
399
+ });
400
+ const hashcash = await createHashcash();
401
+ const complete = await transport.send("POST", `${AUTH_URL}/signin/complete?isRememberMeEnabled=false`, {
402
+ headers: {
403
+ ...authHeaders(),
404
+ ...hashcash ? { "x-apple-hc": hashcash } : {}
405
+ },
406
+ body: {
407
+ accountName: appleId,
408
+ c: field(challenge, "c"),
409
+ m1: proof.m1,
410
+ m2: proof.m2,
411
+ rememberMe: false
412
+ }
413
+ });
414
+ if (complete.status === 409) {
415
+ sessionId = complete.headers.get("x-apple-id-session-id") ?? "";
416
+ scnt = complete.headers.get("scnt") ?? "";
417
+ requireContinuation();
418
+ return "verification-required";
419
+ }
420
+ if (complete.status === 401 || complete.status === 403) throw new AppleError("credentials", "Incorrect Apple Account email or password.", complete.status);
421
+ if (complete.status === 412) throw new AppleError("account-action", "Apple needs you to review something on this account first. Sign in at https://account.apple.com, finish the prompt, then try again.", complete.status);
422
+ if (complete.status !== 200 || serviceMessages(parseJson(complete.body)).length > 0) throw new AppleError("request", `Apple sign-in failed: ${failureMessage(complete)}`, complete.status);
423
+ await resolveTeams();
424
+ return "signed-in";
425
+ },
426
+ async requestCode(request = {}) {
427
+ requireContinuation();
428
+ const body = await auth("GET", "");
429
+ const length = field(field(body, "securityCode"), "length");
430
+ const codeLength = typeof length === "number" && length > 0 ? length : 6;
431
+ const noTrustedDevices = field(body, "noTrustedDevices") === true;
432
+ const phones = listTrustedPhones(body);
433
+ if (!request.sms && !request.phone && !noTrustedDevices) {
434
+ factor = {
435
+ method: "device",
436
+ codeLength
437
+ };
438
+ return {
439
+ method: "device",
440
+ codeLength
441
+ };
442
+ }
443
+ if (phones.length === 0) throw new AppleError("verification", "This Apple Account has no trusted phone number.");
444
+ const wanted = request.phone;
445
+ const phone = wanted ? phones.find((candidate) => phoneMatches(wanted, candidate.label)) : phones[0];
446
+ if (!phone) throw new AppleError("verification", `No trusted phone number matches ${wanted}. Apple lists: ${phones.map((candidate) => candidate.label).join(", ")}.`);
447
+ if (!(noTrustedDevices && phones.length === 1)) await auth("PUT", "/verify/phone", {
448
+ phoneNumber: { id: phone.id },
449
+ mode: phone.mode
450
+ });
451
+ factor = {
452
+ method: "phone",
453
+ phoneId: phone.id,
454
+ phoneMode: phone.mode,
455
+ destination: phone.label,
456
+ codeLength
457
+ };
458
+ return {
459
+ method: phone.mode === "voice" ? "voice" : "sms",
460
+ destination: phone.label || void 0,
461
+ codeLength
462
+ };
463
+ },
464
+ async submitCode(code) {
465
+ requireContinuation();
466
+ const securityCode = { code: code.trim() };
467
+ if (factor?.method === "phone") await auth("POST", "/verify/phone/securitycode", {
468
+ securityCode,
469
+ phoneNumber: { id: factor.phoneId },
470
+ mode: factor.phoneMode
471
+ });
472
+ else await auth("POST", "/verify/trusteddevice/securitycode", { securityCode });
473
+ await auth("GET", "/2sv/trust");
474
+ await resolveTeams();
475
+ },
476
+ pending() {
477
+ requireContinuation();
478
+ return {
479
+ appleId,
480
+ serviceKey,
481
+ sessionId,
482
+ scnt,
483
+ cookies: jar.snapshot(),
484
+ factor
485
+ };
486
+ },
487
+ team() {
488
+ if (!current) throw new AppleError("request", "Sign in to Apple first.");
489
+ return current;
490
+ },
491
+ teams: () => available,
492
+ async selectTeam(id) {
493
+ if (current?.id === id) return;
494
+ if (!available.some((team) => team.id === id)) throw new AppleError("request", `This Apple Account isn't on team ${id}. Its teams: ${available.map((team) => `${team.id} (${team.name})`).join(", ")}.`);
495
+ const response = await transport.send("POST", `${ASC_URL}/olympus/v1/session`, {
496
+ headers: { "x-requested-with": "olympus-ui" },
497
+ body: { provider: { providerId: id } }
498
+ });
499
+ if (response.status < 200 || response.status >= 300) throw new AppleError("request", `Couldn't switch Apple team: ${failureMessage(response)}`, response.status);
500
+ await resolveTeams();
501
+ if (current?.id !== id) throw new AppleError("request", `Apple didn't switch to team ${id}.`);
502
+ },
503
+ async iris(method, path, request = {}) {
504
+ const query = new URLSearchParams(request.query).toString();
505
+ const response = await transport.send(method, `${ASC_URL}/iris/v1${path}${query ? `?${query}` : ""}`, {
506
+ headers: {
507
+ accept: "application/vnd.api+json, application/json",
508
+ origin: ASC_URL,
509
+ referer: `${ASC_URL}/access/integrations/api`,
510
+ "x-csrf-itc": "[asc-ui]"
511
+ },
512
+ body: request.body
513
+ });
514
+ if (response.status < 200 || response.status >= 300) throw new AppleError(response.status === 401 || response.status === 403 ? "forbidden" : "request", failureMessage(response), response.status);
515
+ return parseJson(response.body);
516
+ }
517
+ };
518
+ }
519
+
520
+ //#endregion
521
+ //#region src/core/app-store-connect/setup/deps.ts
522
+ const appleDeps = {
523
+ session: createAppleSession,
524
+ credentials: appleCredentialsFromEnv,
525
+ pending: {
526
+ load: () => readPending(),
527
+ save: (pending) => writePending(pending),
528
+ clear: removePending
529
+ },
530
+ sleep: (ms) => timing.sleep(ms),
531
+ writeKeyFile: (name, privateKey) => {
532
+ const path = join(process.cwd(), name);
533
+ writeFileSync(path, privateKey, { mode: 384 });
534
+ return path;
535
+ }
536
+ };
537
+
538
+ //#endregion
539
+ //#region src/core/app-store-connect/setup/sign-in.ts
540
+ const MAX_CODE_ATTEMPTS = 3;
541
+ function describeChallenge(challenge) {
542
+ if (challenge.method === "device") return "Apple sent a code to your trusted devices.";
543
+ return `Apple ${challenge.method === "voice" ? "is calling" : "texted a code to"} ${challenge.destination ?? "your trusted phone number"}.`;
544
+ }
545
+ async function startSession(ctx, deps, flags) {
546
+ const stored = deps.pending.load();
547
+ if (stored !== void 0 && (flags.code !== void 0 || flags.sms || flags.phone !== void 0) && (!flags.appleId || flags.appleId.toLowerCase() === stored.appleId.toLowerCase())) return {
548
+ session: deps.session({ pending: stored }),
549
+ needsCode: true,
550
+ continued: true
551
+ };
552
+ deps.pending.clear();
553
+ const env = deps.credentials();
554
+ let appleId = flags.appleId ?? env.appleId;
555
+ let password = flags.password ?? env.password;
556
+ if (ctx.interactive && (!appleId || !password)) {
557
+ ctx.ui.note("Your Apple password goes from this computer straight to Apple.\nSuperwall never receives it and it is not saved.", "Sign in to Apple");
558
+ if (!appleId) {
559
+ const typed = await ctx.ui.text({
560
+ message: "Apple Account email",
561
+ placeholder: "you@example.com",
562
+ validate: (value) => value.trim() ? void 0 : "Required"
563
+ });
564
+ if (typed === null) throw new Error("Cancelled.");
565
+ appleId = typed.trim();
566
+ }
567
+ if (!password) {
568
+ const typed = await ctx.ui.text({
569
+ message: "Apple Account password",
570
+ secret: true,
571
+ validate: (value) => value ? void 0 : "Required"
572
+ });
573
+ if (typed === null) throw new Error("Cancelled.");
574
+ password = typed;
575
+ }
576
+ }
577
+ if (!appleId || !password) throw new Error([
578
+ `Can't prompt for Apple sign-in here. Run this in a terminal, or supply the email and password with --apple-id/--apple-password (or ${ENV_APPLE_ID}/${ENV_APPLE_PASSWORD}).`,
579
+ "If you are an agent, never ask for the password in chat. Instead:",
580
+ ` 1. Create a private file (chmod 600) holding two lines: \`${ENV_APPLE_ID}=\` and \`${ENV_APPLE_PASSWORD}=\`.`,
581
+ " 2. Open it in the user's text editor and ask them to fill in both values and save.",
582
+ " 3. Read each value into that environment variable without printing it, then run this again.",
583
+ " 4. Delete the file when you are done."
584
+ ].join("\n"));
585
+ const email = appleId;
586
+ const secret = password;
587
+ const session = deps.session();
588
+ return {
589
+ session,
590
+ needsCode: await apiCall(ctx, "Signing in to Apple", () => session.signIn(email, secret)) === "verification-required",
591
+ continued: false
592
+ };
593
+ }
594
+ async function signInToApple(ctx, deps, flags) {
595
+ const { session, needsCode, continued } = await startSession(ctx, deps, flags);
596
+ if (!needsCode) return {
597
+ status: "signed-in",
598
+ session
599
+ };
600
+ let code = flags.code;
601
+ let challenge = {
602
+ method: "device",
603
+ codeLength: 6
604
+ };
605
+ if (!continued || !code) challenge = await apiCall(ctx, "Requesting a verification code", () => {
606
+ return session.requestCode({
607
+ sms: flags.sms,
608
+ phone: flags.phone
609
+ });
610
+ });
611
+ for (let attempt = 1;; attempt++) {
612
+ if (!code) {
613
+ if (!ctx.interactive) {
614
+ deps.pending.save(session.pending());
615
+ return {
616
+ status: "verification-required",
617
+ challenge
618
+ };
619
+ }
620
+ ctx.ui.info(describeChallenge(challenge));
621
+ const typed = await ctx.ui.text({
622
+ message: "Verification code",
623
+ placeholder: "0".repeat(challenge.codeLength),
624
+ footer: challenge.method === "device" ? "No code? Type sms to get a text message instead." : void 0,
625
+ validate: (value) => value.trim() ? void 0 : "Required"
626
+ });
627
+ if (typed === null) throw new Error("Cancelled.");
628
+ if (typed.trim().toLowerCase() === "sms") {
629
+ challenge = await apiCall(ctx, "Requesting a text message", () => {
630
+ return session.requestCode({
631
+ sms: true,
632
+ phone: flags.phone
633
+ });
634
+ });
635
+ continue;
636
+ }
637
+ code = typed.trim();
638
+ }
639
+ const submitted = code;
640
+ try {
641
+ await apiCall(ctx, "Verifying", () => session.submitCode(submitted));
642
+ break;
643
+ } catch (error) {
644
+ if (!(error instanceof AppleError) || error.kind !== "verification") throw error;
645
+ const message = `Apple didn't accept that code: ${error.message}`;
646
+ if (!ctx.interactive) {
647
+ deps.pending.save(session.pending());
648
+ throw new Error(`${message}\nRun it again with --code <code>, or --sms to get a text.`);
649
+ }
650
+ if (attempt >= MAX_CODE_ATTEMPTS) throw new Error(message);
651
+ ctx.ui.warn(message);
652
+ code = void 0;
653
+ }
654
+ }
655
+ deps.pending.clear();
656
+ return {
657
+ status: "signed-in",
658
+ session
659
+ };
660
+ }
661
+ async function chooseTeam(ctx, session, requested) {
662
+ const teams = session.teams();
663
+ if (requested) {
664
+ const found = teams.find((team) => String(team.id) === requested || team.name.toLowerCase() === requested.toLowerCase());
665
+ if (!found) throw new Error(`This Apple Account isn't on team ${requested}. Its teams: ${teams.map((team) => `${team.id} (${team.name})`).join(", ")}.`);
666
+ await session.selectTeam(found.id);
667
+ return session.team();
668
+ }
669
+ if (teams.length <= 1) return session.team();
670
+ if (!ctx.interactive) throw new Error(`This Apple Account is on several teams: ${teams.map((team) => `${team.id} (${team.name})`).join(", ")}. Pass --team <id>.`);
671
+ const picked = await ctx.ui.select({
672
+ message: "Which Apple team?",
673
+ options: teams.map((team) => ({
674
+ value: String(team.id),
675
+ label: team.name
676
+ })),
677
+ initialValue: String(session.team().id)
678
+ });
679
+ if (picked === null) throw new Error("Cancelled.");
680
+ await session.selectTeam(Number(picked));
681
+ return session.team();
682
+ }
683
+ async function signIn(ctx, deps, command, flags) {
684
+ const signedIn = await signInToApple(ctx, deps, flags);
685
+ if (signedIn.status === "signed-in") return signedIn.session;
686
+ const next = `superwall ${command} --code <code>`;
687
+ if (ctx.json) ctx.output.data({
688
+ status: "verification_required",
689
+ method: signedIn.challenge.method,
690
+ destination: signedIn.challenge.destination ?? null,
691
+ next
692
+ });
693
+ else ctx.ui.warn(`${describeChallenge(signedIn.challenge)}\nRun \`${next}\` with the same flags within 10 minutes to continue, or add --sms to get a text instead.`);
694
+ ctx.fail();
695
+ }
696
+
697
+ //#endregion
698
+ //#region src/core/app-store-connect/apple-web/keys.ts
699
+ const RESOURCE = {
700
+ team: "apiKeys",
701
+ purchase: "subscriptionKeys"
702
+ };
703
+ function decodePrivateKey(value) {
704
+ const trimmed = value.trim();
705
+ if (trimmed.includes("PRIVATE KEY")) return `${trimmed}\n`;
706
+ const decoded = Buffer.from(trimmed, "base64").toString("utf8").trim();
707
+ const unquoted = parseJson(decoded);
708
+ const pem = typeof unquoted === "string" ? unquoted.trim() : decoded;
709
+ if (!pem.includes("PRIVATE KEY")) throw new AppleError("request", "Apple returned something that isn't a private key.");
710
+ return `${pem}\n`;
711
+ }
712
+ async function createKey(session, kind, attributes) {
713
+ const resource = RESOURCE[kind];
714
+ const issuerId = session.team().issuerId;
715
+ if (!issuerId) throw new AppleError("request", "App Store Connect didn't say which issuer this team uses.");
716
+ const id = textField(field(await session.iris("POST", `/${resource}`, { body: { data: {
717
+ type: resource,
718
+ attributes
719
+ } } }), "data"), "id");
720
+ if (!id) throw new AppleError("request", "Apple created a key but didn't return its ID.");
721
+ const privateKey = textField(field(field(await session.iris("GET", `/${resource}/${encodeURIComponent(id)}`, { query: { [`fields[${resource}]`]: "privateKey" } }), "data"), "attributes"), "privateKey");
722
+ if (!privateKey) throw new AppleError("request", `Apple created key ${id} but didn't release its private key. Revoke it in App Store Connect → Users and Access → Integrations, then try again.`);
723
+ return {
724
+ id,
725
+ issuerId,
726
+ privateKey: decodePrivateKey(privateKey)
727
+ };
728
+ }
729
+ function createTeamKey(session, options) {
730
+ return createKey(session, "team", {
731
+ nickname: options.name,
732
+ roles: [options.role],
733
+ allAppsVisible: true,
734
+ keyType: "PUBLIC_API"
735
+ });
736
+ }
737
+ function createPurchaseKey(session, options) {
738
+ return createKey(session, "purchase", { nickname: options.name });
739
+ }
740
+ async function checkKeyAccess(session, kind) {
741
+ await session.iris("GET", `/${RESOURCE[kind]}`, { query: { limit: "1" } });
742
+ }
743
+
744
+ //#endregion
745
+ //#region src/core/app-store-connect/keys/create.ts
746
+ const KEY_NAME = "Superwall";
747
+ const KEY_FILE = {
748
+ api_key: "AuthKey",
749
+ purchase_key: "SubscriptionKey"
750
+ };
751
+ const APPLE_KIND = {
752
+ api_key: "team",
753
+ purchase_key: "purchase"
754
+ };
755
+ const ACTIVATION_DELAYS = [
756
+ 1e3,
757
+ 2e3,
758
+ 3e3
759
+ ];
760
+ const ACTIVATION_STATUSES = new Set([
761
+ 400,
762
+ 401,
763
+ 403,
764
+ 422,
765
+ 502
766
+ ]);
767
+ function keyRole(requested) {
768
+ const value = (requested ?? "app_manager").toUpperCase().replace(/-/g, "_");
769
+ if (value === "APP_MANAGER" || value === "ADMIN") return value;
770
+ throw new Error("--key-role must be app_manager or admin.");
771
+ }
772
+ function keyRefusal(error, kind) {
773
+ const message = error.message.toLowerCase();
774
+ if (message.includes("maximum") || message.includes("revoke")) return "This team is at Apple's limit of active keys. Revoke an unused one in App Store Connect → Users and Access → Integrations, then run this again.";
775
+ if (error.kind === "forbidden" || message.includes("does not allow")) return kind === "purchase_key" ? "Apple refused. Either this Apple Account isn't an Admin or the Account Holder, or the team has an agreement waiting to be signed at https://appstoreconnect.apple.com/agreements." : "Apple refused. Only an Admin or the Account Holder can create team keys, and the team's agreements must be signed at https://appstoreconnect.apple.com/agreements.";
776
+ return `Apple refused: ${error.message}`;
777
+ }
778
+ async function untilActive(ctx, deps, label, work, rejected) {
779
+ return apiCall(ctx, label, async () => {
780
+ for (let attempt = 0;; attempt++) {
781
+ const delay = ACTIVATION_DELAYS[attempt];
782
+ try {
783
+ const result = await work();
784
+ if (!rejected(result) || delay === void 0) return result;
785
+ } catch (error) {
786
+ if (!(error instanceof ApiError && ACTIVATION_STATUSES.has(error.status)) || delay === void 0) throw error;
787
+ }
788
+ await deps.sleep(delay);
789
+ }
790
+ });
791
+ }
792
+ async function keyAccess(ctx, session, kind) {
793
+ try {
794
+ await apiCall(ctx, `Checking ${KEY_LABEL[kind]} access`, () => {
795
+ return checkKeyAccess(session, APPLE_KIND[kind]);
796
+ });
797
+ return "ok";
798
+ } catch (error) {
799
+ if (!(error instanceof AppleError)) throw error;
800
+ return keyRefusal(error, kind);
801
+ }
802
+ }
803
+ function keepKey(ctx, deps, kind, key, reason) {
804
+ const detail = `${reason} Apple only releases a key once, so it was saved to ${deps.writeKeyFile(`${KEY_FILE[kind]}_${key.id}.p8`, key.privateKey)} (issuer ${key.issuerId}).`;
805
+ ctx.output.render(blocks.warning(detail));
806
+ return detail;
807
+ }
808
+ async function createAndSaveKey(ctx, deps, api, session, app, kind, role) {
809
+ let key;
810
+ try {
811
+ key = await apiCall(ctx, `Creating the ${KEY_LABEL[kind]}`, () => {
812
+ if (kind === "api_key") return createTeamKey(session, {
813
+ name: KEY_NAME,
814
+ role
815
+ });
816
+ return createPurchaseKey(session, { name: KEY_NAME });
817
+ });
818
+ } catch (error) {
819
+ if (!(error instanceof AppleError)) throw error;
820
+ const detail = keyRefusal(error, kind);
821
+ ctx.output.render(blocks.warning(`${KEY_LABEL[kind]}: ${detail}`));
822
+ return {
823
+ status: "failed",
824
+ detail
825
+ };
826
+ }
827
+ const appRef = {
828
+ projectId: app.projectId,
829
+ applicationId: app.applicationId
830
+ };
831
+ const credentials = {
832
+ keyId: key.id,
833
+ issuerId: key.issuerId,
834
+ privateKey: key.privateKey
835
+ };
836
+ const setApplicationBundleId = kind === "purchase_key" && app.savedBundleId === null;
837
+ const save = () => {
838
+ if (kind === "api_key") return replaceAppAscKey(api, appRef, credentials);
839
+ return replaceAppPurchaseKey(api, appRef, {
840
+ ...credentials,
841
+ bundleId: app.bundleId,
842
+ setApplicationBundleId
843
+ });
844
+ };
845
+ let reason;
846
+ try {
847
+ const verdict = await untilActive(ctx, deps, `Saving the ${KEY_LABEL[kind]} on ${app.name}`, save, (result) => !result.valid);
848
+ if (verdict.valid) {
849
+ if (setApplicationBundleId) ctx.output.render(blocks.info(`Saved the bundle ID ${app.bundleId} on \`${app.name}\` with the key`));
850
+ return {
851
+ status: "done",
852
+ detail: key.id
853
+ };
854
+ }
855
+ reason = `Apple hasn't accepted the new key yet${verdict.error ? ` (${verdict.error})` : ""}.`;
856
+ } catch (error) {
857
+ reason = `Superwall couldn't save the key: ${error instanceof Error ? error.message : String(error)}.`;
858
+ }
859
+ return {
860
+ status: "failed",
861
+ detail: keepKey(ctx, deps, kind, key, reason)
862
+ };
863
+ }
864
+ async function createAtApple(ctx, request) {
865
+ const { api } = ctx;
866
+ const deps = appleDeps;
867
+ const { kind } = request;
868
+ const role = keyRole(request.role);
869
+ ctx.output.render(blocks.intro(`Create an ${KEY_LABEL[kind]}`));
870
+ const chosen = await chooseIosApp(ctx, api, request.app);
871
+ const applicationId = String(chosen.app.id);
872
+ const appName = chosen.app.name ?? applicationId;
873
+ const existing = savedKey(await apiCall(ctx, "Checking what is saved", () => findIntegrations(api, applicationId)), kind);
874
+ if (existing && !request.replace) {
875
+ if (ctx.json) return ctx.output.data({
876
+ status: "already_saved",
877
+ kind,
878
+ key_id: existing.key_id,
879
+ app: {
880
+ id: applicationId,
881
+ project_id: String(chosen.project.id),
882
+ name: appName
883
+ }
884
+ });
885
+ ctx.ui.success(`\`${appName}\` already has an ${KEY_LABEL[kind]} (${existing.key_id}). Nothing was created. Pass --replace to create another and save it instead.`);
886
+ return;
887
+ }
888
+ const session = await signIn(ctx, deps, `asc keys create ${kind}`, request.signIn);
889
+ if (!session) return;
890
+ const appleTeam = await chooseTeam(ctx, session, request.team);
891
+ ctx.output.render(blocks.info(`Apple team \`${appleTeam.name}\``));
892
+ if (ctx.dryRun) {
893
+ const access = await keyAccess(ctx, session, kind);
894
+ if (ctx.json) return ctx.output.data({
895
+ dryRun: true,
896
+ kind,
897
+ team: appleTeam,
898
+ access
899
+ });
900
+ ctx.ui.report(`${access === "ok" ? "✓" : "✗"} ${KEY_LABEL[kind]} ${access}`);
901
+ ctx.ui.info("[dry-run] nothing was created or changed.");
902
+ return;
903
+ }
904
+ const resolved = await resolveApp(ctx, api, session, {
905
+ kind: "existing",
906
+ ...chosen
907
+ }, request.app);
908
+ if (kind === "purchase_key" && resolved.savedBundleId === null) {
909
+ const warning = await testModeWarning(ctx, api, resolved.applicationId, resolved.bundleId);
910
+ if (warning) ctx.output.render(blocks.warning(warning));
911
+ }
912
+ const result = await createAndSaveKey(ctx, deps, api, session, resolved, kind, role);
913
+ const created = result.status === "done";
914
+ if (ctx.json) ctx.output.data({
915
+ status: created ? "created" : "failed",
916
+ kind,
917
+ key_id: created ? result.detail : null,
918
+ detail: created ? null : result.detail,
919
+ replaced: created && existing ? existing.key_id : null,
920
+ team: appleTeam,
921
+ app: {
922
+ id: resolved.applicationId,
923
+ project_id: resolved.projectId,
924
+ name: resolved.name,
925
+ bundle_id: resolved.bundleId
926
+ },
927
+ ...kind === "purchase_key" ? { bundle_id_saved: created && resolved.savedBundleId === null } : {}
928
+ });
929
+ else if (created) ctx.ui.success(`${KEY_LABEL[kind]} ${result.detail} created and saved on \`${resolved.name}\`.`);
930
+ if (!created) ctx.fail();
931
+ }
932
+ async function runAscKeysCreate(ctx, { args, flags }) {
933
+ const kind = keyKind(args.kind);
934
+ const app = {
935
+ app: flags.app,
936
+ project: flags.project,
937
+ bundleId: flags.bundleId
938
+ };
939
+ if (flags.keyFile !== void 0) return upsertHeldKey(ctx, {
940
+ action: "create",
941
+ key: {
942
+ keyId: flags.keyId,
943
+ issuer: flags.issuer,
944
+ keyFile: flags.keyFile,
945
+ name: flags.name
946
+ },
947
+ ...flags.app === void 0 ? {} : { app },
948
+ kind,
949
+ team: flags.team
950
+ });
951
+ if (!kind) throw new Error("Usage: superwall asc keys create <api_key | purchase_key> --app <id>");
952
+ return createAtApple(ctx, {
953
+ kind,
954
+ role: flags.keyRole,
955
+ replace: flags.replace,
956
+ team: flags.team,
957
+ app,
958
+ signIn: {
959
+ appleId: flags.appleId,
960
+ password: flags.applePassword,
961
+ code: flags.code,
962
+ sms: flags.sms,
963
+ phone: flags.phone
964
+ }
965
+ });
966
+ }
967
+
968
+ //#endregion
969
+ export { chooseTeam as a, runAscKeysCreate as i, keyAccess as n, signIn as o, keyRole as r, appleDeps as s, createAndSaveKey as t };