@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,7 @@
1
+ //#region src/util/json.ts
2
+ function formatJson(value) {
3
+ return JSON.stringify(value, null, 2);
4
+ }
5
+
6
+ //#endregion
7
+ export { formatJson as t };
@@ -0,0 +1,290 @@
1
+ import { E as OAUTH_SCOPE, S as CLI_CLIENT_ID, T as Integration, d as getOnboardingIdempotencyKey, g as setOnboardedOrg, h as setOnboardedApp, u as getOnboardedOrg, x as AUTH_HOST, y as API_HOST } from "./telemetry-CcfrtXdf.js";
2
+ import { a as saveSession } from "./token-DHRH8cxi.js";
3
+ import { n as ui } from "./ui-C4ncRJqd.js";
4
+ import { spawn } from "node:child_process";
5
+
6
+ //#region src/core/account/onboarding.ts
7
+ function onboardingHooks(app) {
8
+ const ref = { current: null };
9
+ const platform = app?.integration === Integration.swift ? "ios" : app?.integration === Integration.web ? "web" : void 0;
10
+ return {
11
+ onOnboard: async () => {
12
+ let onboardApp;
13
+ if (app && platform) {
14
+ ui.info(`Welcome to Superwall! Let's get \`${app.name}\` set up.`);
15
+ const create = await ui.confirm({ message: `Create \`${app.name}\` as your first app?` });
16
+ if (create === null) return null;
17
+ if (create) onboardApp = {
18
+ name: app.name,
19
+ platform
20
+ };
21
+ } else ui.info("Welcome to Superwall! Let's set up your account.");
22
+ const orgName = await ui.text({
23
+ message: "What's your organization called?",
24
+ placeholder: "Acme Inc",
25
+ initialValue: app?.name,
26
+ validate: (v) => v?.trim() ? void 0 : "Required"
27
+ });
28
+ if (orgName === null) return null;
29
+ return {
30
+ orgName: orgName.trim(),
31
+ app: onboardApp
32
+ };
33
+ },
34
+ onProvisioned: (result) => {
35
+ ref.current = result;
36
+ if (app && result.publicApiKey) setOnboardedApp(app.path, {
37
+ publicApiKey: result.publicApiKey,
38
+ projectId: result.projectId,
39
+ applicationId: result.applicationId
40
+ });
41
+ },
42
+ provisioned: () => ref.current
43
+ };
44
+ }
45
+
46
+ //#endregion
47
+ //#region src/core/auth/browser.ts
48
+ function openBrowser(url) {
49
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
50
+ const args = process.platform === "win32" ? [
51
+ "/c",
52
+ "start",
53
+ "",
54
+ url
55
+ ] : [url];
56
+ try {
57
+ spawn(cmd, args, {
58
+ stdio: "ignore",
59
+ detached: true
60
+ }).unref();
61
+ } catch {}
62
+ }
63
+
64
+ //#endregion
65
+ //#region src/core/auth/login.ts
66
+ const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
67
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
68
+ async function performLogin(opts = {}) {
69
+ const issuer = opts.issuer ?? AUTH_HOST;
70
+ const apiHost = opts.apiHost ?? API_HOST;
71
+ const clientId = opts.clientId ?? CLI_CLIENT_ID;
72
+ const disc = await discover(issuer);
73
+ if (!disc.device_authorization_endpoint) throw new Error("auth.superwall.com does not advertise a device-authorization endpoint.");
74
+ const dev = await startDeviceAuth(disc.device_authorization_endpoint, clientId);
75
+ const url = dev.verification_uri_complete ?? dev.verification_uri;
76
+ opts.onVerify?.({
77
+ url,
78
+ userCode: dev.user_code
79
+ });
80
+ openBrowser(url);
81
+ const { accessToken, refreshToken, expiresIn, idToken } = await pollForToken(disc.token_endpoint, clientId, dev, opts.onStatus);
82
+ let apiToken = accessToken;
83
+ if (idToken) await getJson(`${apiHost}/v2/me`, idToken).catch(() => null);
84
+ const me = await getJson(`${apiHost}/v2/me`, apiToken).catch(() => null);
85
+ let orgList = [];
86
+ try {
87
+ orgList = (await getJson(`${apiHost}/v2/me/organizations`, apiToken)).data ?? [];
88
+ } catch {
89
+ orgList = [];
90
+ }
91
+ const uniqueOrgs = [...new Map(orgList.map((o) => [String(o.id), o])).values()];
92
+ let org;
93
+ let createdNewOrg = false;
94
+ if (uniqueOrgs.length === 0) {
95
+ const remembered = getOnboardedOrg();
96
+ if (remembered) org = {
97
+ id: remembered.id,
98
+ name: remembered.name
99
+ };
100
+ else if (opts.onOnboard) {
101
+ const setup = await opts.onOnboard();
102
+ if (!setup) throw new Error("Cancelled.");
103
+ opts.onStatus?.("Creating your account…");
104
+ if (setup.app) {
105
+ const provisioned = await provisionAccount(apiHost, apiToken, setup);
106
+ if (provisioned.orgId) org = {
107
+ id: provisioned.orgId,
108
+ name: setup.orgName
109
+ };
110
+ opts.onProvisioned?.(provisioned);
111
+ } else org = await createOrganization(apiHost, apiToken, setup.orgName);
112
+ if (org) setOnboardedOrg({
113
+ id: String(org.id),
114
+ name: org.name
115
+ });
116
+ createdNewOrg = true;
117
+ } else throw new Error("Your account has no organization yet - run `superwall login` interactively to create one.");
118
+ } else if (uniqueOrgs.length === 1) org = uniqueOrgs[0];
119
+ if (createdNewOrg && refreshToken) {
120
+ opts.onStatus?.("Activating your organization…");
121
+ const fresh = await refreshAccessToken(disc.token_endpoint, clientId, refreshToken);
122
+ if (fresh) apiToken = fresh;
123
+ }
124
+ const session = {
125
+ authMethod: "oauth",
126
+ orgId: org ? String(org.id) : void 0,
127
+ orgName: org?.name,
128
+ orgCount: createdNewOrg ? 1 : uniqueOrgs.length,
129
+ userEmail: me?.email,
130
+ host: apiHost,
131
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
132
+ accessToken: apiToken,
133
+ refreshToken,
134
+ accessTokenExpiresAt: expiresIn ? Date.now() + expiresIn * 1e3 : void 0,
135
+ tokenEndpoint: disc.token_endpoint,
136
+ oauthClientId: clientId
137
+ };
138
+ saveSession(session);
139
+ return session;
140
+ }
141
+ async function loginWithApiKey(apiKey, apiHost = API_HOST) {
142
+ const key = apiKey.trim();
143
+ if (!key) throw new Error("An API key is required.");
144
+ let org = {};
145
+ try {
146
+ const first = (await getJson(`${apiHost}/v2/me/organizations`, key)).data?.[0];
147
+ if (first) org = {
148
+ id: String(first.id),
149
+ name: first.name
150
+ };
151
+ } catch {
152
+ throw new Error("That API key was rejected. Check it and try again.");
153
+ }
154
+ const session = {
155
+ authMethod: "api_key",
156
+ apiKey: key,
157
+ orgId: org.id,
158
+ orgName: org.name,
159
+ host: apiHost,
160
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
161
+ };
162
+ saveSession(session);
163
+ return session;
164
+ }
165
+ async function discover(issuer) {
166
+ const r = await fetch(`${issuer}/.well-known/openid-configuration`, { headers: { accept: "application/json" } });
167
+ if (!r.ok) throw new Error(`OIDC discovery failed (HTTP ${r.status}).`);
168
+ return await r.json();
169
+ }
170
+ async function startDeviceAuth(endpoint, clientId) {
171
+ const r = await fetch(endpoint, {
172
+ method: "POST",
173
+ headers: { "content-type": "application/x-www-form-urlencoded" },
174
+ body: new URLSearchParams({
175
+ client_id: clientId,
176
+ scope: OAUTH_SCOPE
177
+ })
178
+ });
179
+ if (!r.ok) {
180
+ const detail = await r.text().catch(() => "");
181
+ throw new Error(`Device authorization failed (HTTP ${r.status}). Register a CLI OAuth client with the device grant. ${detail}`.trim());
182
+ }
183
+ return await r.json();
184
+ }
185
+ async function pollForToken(tokenEndpoint, clientId, dev, onStatus) {
186
+ const deadline = Date.now() + (dev.expires_in ?? 600) * 1e3;
187
+ let interval = dev.interval ?? 5;
188
+ while (Date.now() < deadline) {
189
+ await sleep(interval * 1e3);
190
+ const r = await fetch(tokenEndpoint, {
191
+ method: "POST",
192
+ headers: { "content-type": "application/x-www-form-urlencoded" },
193
+ body: new URLSearchParams({
194
+ grant_type: DEVICE_GRANT,
195
+ device_code: dev.device_code,
196
+ client_id: clientId
197
+ })
198
+ });
199
+ const d = await r.json().catch(() => ({}));
200
+ if (r.ok && d.access_token) return {
201
+ accessToken: d.access_token,
202
+ refreshToken: d.refresh_token,
203
+ expiresIn: d.expires_in,
204
+ idToken: d.id_token
205
+ };
206
+ switch (d.error) {
207
+ case "authorization_pending":
208
+ onStatus?.("Waiting for you to approve in the browser…");
209
+ continue;
210
+ case "slow_down":
211
+ interval += 5;
212
+ continue;
213
+ case "expired_token": throw new Error("The login request expired - run `superwall login` again.");
214
+ case "access_denied": throw new Error("Login was denied.");
215
+ default: throw new Error(d.error_description || d.error || "Token polling failed.");
216
+ }
217
+ }
218
+ throw new Error("Login timed out.");
219
+ }
220
+ async function createOrganization(apiHost, token, name) {
221
+ const created = await postJson(`${apiHost}/v2/me/organizations`, token, { name });
222
+ return {
223
+ id: created.id,
224
+ name: created.name
225
+ };
226
+ }
227
+ async function provisionAccount(apiHost, token, setup) {
228
+ const app = setup.app;
229
+ const res = await postJson(`${apiHost}/internal/v2/onboarding/provision`, token, {
230
+ idempotency_key: getOnboardingIdempotencyKey(),
231
+ organization: { name: setup.orgName },
232
+ applications: [{
233
+ name: app.name,
234
+ platform: app.platform,
235
+ ...app.bundleId ? { bundle_id: app.bundleId } : {}
236
+ }],
237
+ marketing_metadata: { source: "cli" }
238
+ });
239
+ const created = res.project?.applications?.[0];
240
+ return {
241
+ publicApiKey: created?.public_api_key,
242
+ projectId: res.project?.id !== void 0 ? String(res.project.id) : void 0,
243
+ applicationId: created?.id !== void 0 ? String(created.id) : void 0,
244
+ orgId: res.project?.organization_id !== void 0 ? String(res.project.organization_id) : void 0
245
+ };
246
+ }
247
+ async function refreshAccessToken(tokenEndpoint, clientId, refreshToken) {
248
+ try {
249
+ const r = await fetch(tokenEndpoint, {
250
+ method: "POST",
251
+ headers: { "content-type": "application/x-www-form-urlencoded" },
252
+ body: new URLSearchParams({
253
+ grant_type: "refresh_token",
254
+ refresh_token: refreshToken,
255
+ client_id: clientId
256
+ })
257
+ });
258
+ if (!r.ok) return null;
259
+ return (await r.json()).access_token ?? null;
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+ async function getJson(url, accessToken) {
265
+ const r = await fetch(url, { headers: {
266
+ authorization: `Bearer ${accessToken}`,
267
+ accept: "application/json"
268
+ } });
269
+ if (!r.ok) throw new Error(`GET ${url} failed (HTTP ${r.status}).`);
270
+ return r.json();
271
+ }
272
+ async function postJson(url, accessToken, body) {
273
+ const r = await fetch(url, {
274
+ method: "POST",
275
+ headers: {
276
+ authorization: `Bearer ${accessToken}`,
277
+ "content-type": "application/json",
278
+ accept: "application/json"
279
+ },
280
+ body: JSON.stringify(body)
281
+ });
282
+ if (!r.ok) {
283
+ const detail = await r.text().catch(() => "");
284
+ throw new Error(`POST ${url} failed (HTTP ${r.status}). ${detail}`.trim());
285
+ }
286
+ return r.json();
287
+ }
288
+
289
+ //#endregion
290
+ export { performLogin as n, onboardingHooks as r, loginWithApiKey as t };
@@ -0,0 +1,114 @@
1
+ import { C as DASHBOARD_URL, k as VERSION } from "./telemetry-CcfrtXdf.js";
2
+ import "./json-C3hPIMkI.js";
3
+ import { o as blocks } from "./update-BiVeR024.js";
4
+ import { i as loadSession } from "./token-DHRH8cxi.js";
5
+ import { t as defineCommand } from "./command-Kwx4ekbo.js";
6
+ import { n as ui, r as stripReport } from "./ui-C4ncRJqd.js";
7
+ import "./skills-xrfXt9u0.js";
8
+ import "./spawn-DSoTXy_j.js";
9
+ import "./login-Dr8UN_Gx.js";
10
+ import { t as scanProject } from "./scan-BQexuUPO.js";
11
+ import { t as detectDrivers } from "./drivers-DVAZgone.js";
12
+ import "./hosted-CHwaUqLd.js";
13
+ import { t as detectExisting } from "./existing-CcJrIIAU.js";
14
+ import "./spinner-gOxIMz-V.js";
15
+ import "./resources-CVrWwA1K.js";
16
+ import "./org-B2gy9Pmu.js";
17
+ import "./bind-hslFhcTR.js";
18
+ import { r as actionById } from "./actions-MB-eBY64.js";
19
+ import { r as performLoginWithUi } from "./app-K6j9Es7h.js";
20
+ import { i as saveReport, t as runAction } from "./run-cGGBUMs5.js";
21
+ import { t as detectBilling } from "./billing-DWyfEQ6l.js";
22
+
23
+ //#region src/commands/workflow/migrate.ts
24
+ const runMigrate = defineCommand({
25
+ name: "migrate",
26
+ auth: "optional",
27
+ async run(ctx) {
28
+ const { installDir, dryRun } = ctx;
29
+ ui.intro(`Superwall migrate v${VERSION}`);
30
+ const drivers = await detectDrivers();
31
+ if (drivers.length === 0) throw new Error("No coding agent found (Claude Code or Codex).");
32
+ const driver = drivers[0].driver;
33
+ const fallbackDrivers = drivers.slice(1).map((candidate) => candidate.driver);
34
+ const app = (await scanProject(installDir)).apps[0];
35
+ if (!app) throw new Error("No iOS / Expo / React Native / Flutter app found here.");
36
+ ui.info(`Detected \`${app.framework.name}\`${app.details ? ` · \`${app.details}\`` : ""}`);
37
+ const billing = detectBilling(app);
38
+ const provider = billing.revenueCat ? "RevenueCat" : billing.adapty ? "Adapty" : billing.qonversion ? "Qonversion" : null;
39
+ if (!provider) {
40
+ ui.warn("No RevenueCat / Adapty / Qonversion detected - nothing to migrate.");
41
+ ui.info("Starting fresh? Run `superwall integrate` to set up directly.");
42
+ ui.outro("");
43
+ return;
44
+ }
45
+ ui.info(`Found \`${provider}\``);
46
+ let intent = "full";
47
+ if (ctx.interactive && !dryRun) {
48
+ const sel = await ui.select({
49
+ message: `Migrate from ${provider} - how far?`,
50
+ options: [{
51
+ value: "full",
52
+ label: "Full migration",
53
+ hint: `replace ${provider} with Superwall`
54
+ }, {
55
+ value: "paywalls",
56
+ label: "Paywalls only",
57
+ hint: `keep ${provider} for billing`
58
+ }],
59
+ initialValue: "full"
60
+ });
61
+ if (sel === null) return void ui.warn("Cancelled.");
62
+ intent = sel;
63
+ }
64
+ let session = loadSession();
65
+ if (session) ui.success(`Logged in as \`${session.userEmail ?? "you"}\`${session.orgName ? ` · \`${session.orgName}\`` : ""}`);
66
+ else if (ctx.interactive && !dryRun) session = await performLoginWithUi();
67
+ if (session?.apiKey) process.env.SUPERWALL_API_KEY = session.apiKey;
68
+ const existing = detectExisting(app);
69
+ const actionCtx = {
70
+ app,
71
+ apiKey: existing.apiKey ?? "",
72
+ existing,
73
+ billingProvider: provider,
74
+ migrateIntent: intent
75
+ };
76
+ if (dryRun) {
77
+ ui.note([
78
+ `Provider: ${provider}`,
79
+ `Mode: ${intent}`,
80
+ `App: ${app.name} (${app.framework.name})`,
81
+ `Path: ${app.path}`
82
+ ].join("\n"), "Migration plan");
83
+ ui.outro("Dry run - no changes made.");
84
+ return;
85
+ }
86
+ const spin = ui.spinner();
87
+ spin.start(`Migrating from ${provider}`);
88
+ const result = await runAction({
89
+ driver,
90
+ fallbackDrivers,
91
+ action: actionById["migrate"],
92
+ ctx: actionCtx,
93
+ onEvent: (e) => {
94
+ if (e.type === "status") spin.message(e.text);
95
+ }
96
+ });
97
+ if (result.ok) {
98
+ spin.stop("Migration complete");
99
+ if (result.finalText) {
100
+ const plain = stripReport(result.finalText);
101
+ saveReport(app.path, "migrate", plain);
102
+ ui.report(plain);
103
+ }
104
+ } else {
105
+ spin.stop("Migration stopped early");
106
+ if (result.finalText) ui.report(stripReport(result.finalText).slice(0, 1500));
107
+ throw new Error("Migration did not complete.");
108
+ }
109
+ ctx.output.render(blocks.nextSteps(["Rebuild your paywalls - as code (`superwall create`) or in the dashboard editor - and attach products.", "Verify a purchase on device."]), blocks.outro(`Done. ${DASHBOARD_URL}`));
110
+ }
111
+ });
112
+
113
+ //#endregion
114
+ export { runMigrate };
@@ -0,0 +1,40 @@
1
+ import { n as ui } from "./ui-C4ncRJqd.js";
2
+ import { t as withSpinner } from "./spinner-gOxIMz-V.js";
3
+ import { C as rowName, p as listOrganizations, w as titleCase } from "./resources-CVrWwA1K.js";
4
+
5
+ //#region src/core/account/org.ts
6
+ /**
7
+ * Login is user-scoped and doesn't pick an org; org-scoped endpoints resolve
8
+ * one here on first use and persist it to the session.
9
+ */
10
+ async function requireOrg(api, interactive) {
11
+ if (api.org.id) return {
12
+ id: api.org.id,
13
+ name: api.org.name
14
+ };
15
+ const orgs = await withSpinner("Finding your organization", () => listOrganizations(api));
16
+ if (orgs.length === 0) throw new Error("Your account has no organization yet - run `superwall login` to create one.");
17
+ let picked = orgs.length === 1 ? orgs[0] : void 0;
18
+ if (!picked) {
19
+ if (!interactive) throw new Error("Your account has multiple organizations - run `superwall orgs use <id|name>` to pick one.");
20
+ const sel = await ui.select({
21
+ message: "Which organization?",
22
+ options: orgs.map((o) => ({
23
+ value: String(o.id),
24
+ label: rowName(o),
25
+ hint: titleCase(String(o.role ?? ""))
26
+ }))
27
+ });
28
+ if (sel === null) throw new Error("An organization is required.");
29
+ picked = orgs.find((o) => String(o.id) === sel);
30
+ }
31
+ const org = {
32
+ id: String(picked.id),
33
+ name: rowName(picked)
34
+ };
35
+ api.setOrg(org);
36
+ return org;
37
+ }
38
+
39
+ //#endregion
40
+ export { requireOrg as t };
@@ -0,0 +1,52 @@
1
+ //#region src/util/params.ts
2
+ function parseParams(pairs) {
3
+ const root = {};
4
+ for (const pair of pairs ?? []) {
5
+ const eq = pair.indexOf("=");
6
+ if (eq < 0) throw new Error(`Invalid -d "${pair}" - expected key=value (or key:=jsonValue).`);
7
+ const typed = pair[eq - 1] === ":";
8
+ const key = pair.slice(0, typed ? eq - 1 : eq);
9
+ const raw = pair.slice(eq + 1);
10
+ const value = typed ? parseTyped(raw, pair) : raw;
11
+ setPath(root, splitKey(key), value);
12
+ }
13
+ return root;
14
+ }
15
+ function parseTyped(raw, pair) {
16
+ try {
17
+ return JSON.parse(raw);
18
+ } catch {
19
+ throw new Error(`Invalid -d "${pair}" - value after := must be JSON (number, true/false, null, "quoted", [...], {...}).`);
20
+ }
21
+ }
22
+ /** `items[0][price]` → ["items", "0", "price"]. */
23
+ function splitKey(key) {
24
+ return key.replace(/\]/g, "").split("[").filter((p) => p !== "");
25
+ }
26
+ function setPath(root, parts, value) {
27
+ let cur = root;
28
+ for (let i = 0; i < parts.length; i++) {
29
+ const key = parts[i];
30
+ if (i === parts.length - 1) {
31
+ assign(cur, key, value);
32
+ return;
33
+ }
34
+ const nextIsIndex = /^\d+$/.test(parts[i + 1]);
35
+ let next = get(cur, key);
36
+ if (next === void 0) {
37
+ next = nextIsIndex ? [] : {};
38
+ assign(cur, key, next);
39
+ }
40
+ cur = next;
41
+ }
42
+ }
43
+ function get(container, key) {
44
+ return Array.isArray(container) ? container[Number(key)] : container[key];
45
+ }
46
+ function assign(container, key, value) {
47
+ if (Array.isArray(container)) container[Number(key)] = value;
48
+ else container[key] = value;
49
+ }
50
+
51
+ //#endregion
52
+ export { parseParams as t };