create-disposabl-app 0.15.0 → 0.17.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 (101) hide show
  1. package/README.md +26 -9
  2. package/dist/disposabl.js +357 -50
  3. package/dist/index.js +9026 -160
  4. package/dist/templates/default/.github/scripts/mobile.sh +3 -2
  5. package/dist/templates/default/.github/scripts/release.sh +1 -0
  6. package/dist/templates/default/.github/scripts/verify-android-abis.mjs +22 -0
  7. package/dist/templates/default/apps/desktop/forge.config.mts +2 -1
  8. package/dist/templates/default/apps/docs/content/getting-started.mdx +1 -1
  9. package/dist/templates/default/apps/mobile/app.config.js +18 -9
  10. package/dist/templates/default/apps/mobile/package.json +1 -0
  11. package/dist/templates/default/apps/mobile/plugins/with-e2e-network.js +41 -0
  12. package/dist/templates/default/apps/web/eslint.config.ts +5 -1
  13. package/dist/templates/default/apps/web/public/disposabl-logo-light.svg +8 -0
  14. package/dist/templates/default/apps/web/public/landing/coast.jpg +0 -0
  15. package/dist/templates/default/apps/web/public/landing/community.jpg +0 -0
  16. package/dist/templates/default/apps/web/public/landing/stores/app-store.svg +46 -0
  17. package/dist/templates/default/apps/web/public/landing/stores/google-play.png +0 -0
  18. package/dist/templates/default/apps/web/public/landing/taste/LICENSE +21 -0
  19. package/dist/templates/default/apps/web/public/landing/taste/init.js +3 -0
  20. package/dist/templates/default/apps/web/public/landing/taste/moments/lib.js +189 -0
  21. package/dist/templates/default/apps/web/public/landing/taste/moments/moments.js +109 -0
  22. package/dist/templates/default/apps/web/public/landing/taste/moments/word-highlight/moment.css +8 -0
  23. package/dist/templates/default/apps/web/public/landing/taste/moments/word-highlight/moment.js +35 -0
  24. package/dist/templates/default/apps/web/public/landing/taste/motion/motion.css +321 -0
  25. package/dist/templates/default/apps/web/public/landing/taste/motion/motion.js +406 -0
  26. package/dist/templates/default/apps/web/routes.config.ts +14 -0
  27. package/dist/templates/default/apps/web/src/router/__root.tsx +8 -2
  28. package/dist/templates/default/apps/web/tsr.config.json +1 -1
  29. package/dist/templates/default/apps/web/vite.config.ts +10 -2
  30. package/dist/templates/default/bun.lock +6 -0
  31. package/dist/templates/default/bunfig.toml +1 -0
  32. package/dist/templates/default/disposabl.json +2 -1
  33. package/dist/templates/default/packages/backend/convex/authSetup.ts +2 -5
  34. package/dist/templates/default/packages/backend/convex/billing.ts +5 -0
  35. package/dist/templates/default/packages/backend/convex/billingHandoff.ts +6 -0
  36. package/dist/templates/default/packages/backend/convex/convex.config.ts +8 -0
  37. package/dist/templates/default/packages/backend/convex/http.ts +6 -0
  38. package/dist/templates/default/packages/backend/convex/revenuecat.ts +13 -0
  39. package/dist/templates/default/packages/backend/convex/schema.ts +44 -0
  40. package/dist/templates/default/packages/backend/convex/telemetry.ts +41 -5
  41. package/dist/templates/default/packages/backend/generate.ts +6 -0
  42. package/dist/templates/default/packages/cli/auth.ts +36 -3
  43. package/dist/templates/default/packages/cli/build.ts +6 -0
  44. package/dist/templates/default/packages/cli/client.ts +189 -19
  45. package/dist/templates/default/packages/cli/errors.ts +18 -0
  46. package/dist/templates/default/packages/cli/telemetry-build.ts +27 -0
  47. package/dist/templates/default/packages/cli/telemetry.ts +266 -0
  48. package/dist/templates/default/packages/disposabl-kit/PAYMENTS.md +23 -5
  49. package/dist/templates/default/packages/disposabl-kit/android-architectures.ts +35 -0
  50. package/dist/templates/default/packages/disposabl-kit/client/lib/telemetry.ts +24 -2
  51. package/dist/templates/default/packages/disposabl-kit/client/lib/theme.ts +1 -0
  52. package/dist/templates/default/packages/disposabl-kit/client/routes/billing-login.tsx +92 -0
  53. package/dist/templates/default/packages/disposabl-kit/client/routes/pricing.tsx +113 -43
  54. package/dist/templates/default/packages/disposabl-kit/client/routes/route.tsx +13 -5
  55. package/dist/templates/default/packages/disposabl-kit/client/vite.config.ts +3 -2
  56. package/dist/templates/default/packages/disposabl-kit/lib/telemetry.ts +148 -12
  57. package/dist/templates/default/packages/disposabl-kit/mobile/billing/account-billing.tsx +143 -40
  58. package/dist/templates/default/packages/disposabl-kit/mobile/billing/paywall.ts +83 -0
  59. package/dist/templates/default/packages/disposabl-kit/mobile/billing/policy.ts +125 -0
  60. package/dist/templates/default/packages/disposabl-kit/mobile/billing/session.ts +31 -3
  61. package/dist/templates/default/packages/disposabl-kit/mobile/billing/topup.ts +99 -0
  62. package/dist/templates/default/packages/disposabl-kit/mobile/billing/use-topup.ts +116 -0
  63. package/dist/templates/default/packages/disposabl-kit/mobile/billing/web-checkout.ts +190 -0
  64. package/dist/templates/default/packages/disposabl-kit/mobile/expo-plugin.cjs +23 -1
  65. package/dist/templates/default/packages/disposabl-kit/mobile/layout.tsx +9 -2
  66. package/dist/templates/default/packages/disposabl-kit/package.json +10 -1
  67. package/dist/templates/default/packages/disposabl-kit/payments/checkout-attempt.ts +64 -0
  68. package/dist/templates/default/packages/disposabl-kit/payments/config.ts +16 -3
  69. package/dist/templates/default/packages/disposabl-kit/server/billing-functions.ts +218 -9
  70. package/dist/templates/default/packages/disposabl-kit/server/billing-handoff.ts +126 -0
  71. package/dist/templates/default/packages/disposabl-kit/server/billing-native-capability.ts +12 -0
  72. package/dist/templates/default/packages/disposabl-kit/server/billing-setup.ts +2 -0
  73. package/dist/templates/default/packages/disposabl-kit/server/billing.ts +31 -0
  74. package/dist/templates/default/packages/disposabl-kit/server/browser-session.ts +27 -0
  75. package/dist/templates/default/packages/disposabl-kit/server/lib/telemetry.ts +173 -59
  76. package/dist/templates/default/packages/disposabl-kit/server/revenuecat-contract.ts +233 -0
  77. package/dist/templates/default/packages/disposabl-kit/server/revenuecat-functions.ts +554 -0
  78. package/dist/templates/default/packages/disposabl-kit/server/revenuecat-validator.ts +76 -0
  79. package/dist/templates/default/packages/reconfigure-skill/SKILL.md +38 -0
  80. package/dist/templates/default/packages/sdk/README.md +21 -0
  81. package/dist/templates/default/packages/sdk/src/analytics.ts +102 -0
  82. package/dist/templates/default/packages/sdk/src/index.ts +2 -0
  83. package/dist/templates/default/packages/skill/SKILL.md +2 -0
  84. package/dist/templates/default/packages/skill/references/agent.md +2 -0
  85. package/dist/templates/default/packages/tests/android-architectures.test.ts +43 -0
  86. package/dist/templates/default/packages/tests/android-ota-artifacts.test.ts +5 -1
  87. package/dist/templates/default/packages/tests/android-ota-selection.test.ts +7 -2
  88. package/dist/templates/default/packages/tests/billing-attempts.test.ts +156 -0
  89. package/dist/templates/default/packages/tests/billing-handoff.test.ts +116 -0
  90. package/dist/templates/default/packages/tests/billing-setup.test.ts +4 -3
  91. package/dist/templates/default/packages/tests/billing.test.ts +48 -4
  92. package/dist/templates/default/packages/tests/desktop-packaging.test.ts +12 -0
  93. package/dist/templates/default/packages/tests/flows/seo.e2e.ts +3 -1
  94. package/dist/templates/default/packages/tests/mobile-android-e2e-network.test.ts +112 -0
  95. package/dist/templates/default/packages/tests/native-billing.test.ts +417 -0
  96. package/dist/templates/default/packages/tests/page-telemetry.test.ts +218 -0
  97. package/dist/templates/default/packages/tests/revenuecat-inbox.test.ts +476 -0
  98. package/dist/templates/default/packages/tests/sdk-analytics.test.ts +158 -0
  99. package/dist/templates/default/packages/tests/telemetry.test.ts +272 -55
  100. package/package.json +1 -1
  101. package/dist/templates/default/apps/web/src/routeTree.gen.ts +0 -578
package/README.md CHANGED
@@ -47,18 +47,31 @@ For example, create a web and mobile app with sign-in:
47
47
  bunx create-disposabl-app@latest my-app --platforms web,ios,android --yes
48
48
  ```
49
49
 
50
- | Option | What it does |
51
- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
52
- | `--platforms <ids>` | Choose `web`, `ios`, `android`, `macos`, `windows`, `linux`, `mcp`, `api`, `cli`, or `typescript-sdk`. Separate multiple choices with commas. Web is always included. |
53
- | `--features <ids>` | Choose features from `--list-options`, such as `authentication` and `docs`. The default is `authentication`. Use `--features none` to omit optional features. |
54
- | `--yes` | Skip the name, platform, and feature questions. Supply an app name in the command. |
55
- | `--list-options` | Show available platforms and features without creating an app. |
56
- | `--skip-install` | Create files without installing dependencies. Account setup still runs. |
57
- | `--json` | Return a result coding agents can read. Supply an app name. Account setup still runs. |
50
+ | Option | What it does |
51
+ | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
52
+ | `--platforms <ids>` | Choose `web`, `ios`, `android`, `macos`, `windows`, `linux`, `mcp`, `api`, `cli`, or `typescript-sdk`. Separate multiple choices with commas. Web is always included. |
53
+ | `--android-architectures <ids>` | Choose Android ABIs for one APK. Defaults to `arm64-v8a,x86_64`; `armeabi-v7a` and `x86` are also supported. |
54
+ | `--features <ids>` | Choose features from `--list-options`, such as `authentication` and `docs`. The default is `authentication`. Use `--features none` to omit optional features. |
55
+ | `--yes` | Skip the name, platform, and feature questions. Supply an app name in the command. |
56
+ | `--list-options` | Show available platforms and features without creating an app. |
57
+ | `--skip-install` | Create files without installing dependencies. Account setup still runs. |
58
+ | `--json` | Return a result coding agents can read. Supply an app name. Account setup still runs. |
58
59
 
59
60
  CLI and TypeScript SDK include API support automatically. Backend authentication and access checks remain installed even with `--features none`.
60
61
 
61
- ## If setup stops
62
+ ## Change an existing app's features
63
+
64
+ The generated `disposabl-reconfigure` skill handles code changes separately from account setup. From the app's parent directory, use the version in its `disposabl.json`:
65
+
66
+ ```sh
67
+ npx create-disposabl-app@<version> my-app --reconfigure-only --features authentication,payments --skip-install --json
68
+ ```
69
+
70
+ Supply the complete desired feature list. Add `--platforms` with a complete list to change platforms too. Omitted lists stay unchanged. Run `bun install` in the app afterward, review the diff, and test affected platforms. The code-only command does not log in, provision providers, commit, or deploy. Store and payment-provider configuration is a separate step.
71
+
72
+ Use `--android-architectures arm64-v8a,x86_64` to change the Android ABI selection. This replaces the list and requires a compatible new native build; it does not create separate APKs.
73
+
74
+ ## Resume setup
62
75
 
63
76
  Your files are saved. Follow the error's instructions, then run the same command from the parent folder:
64
77
 
@@ -95,3 +108,7 @@ Faster CI selects an eight-vCPU Linux runner for universal Android builds and a
95
108
  ## Generator release checks
96
109
 
97
110
  Before publishing the generator, `bun run --cwd packages/create-disposabl-app build && bun run --cwd packages/create-disposabl-app verify:starter` creates fresh minimal-web, Web + Android, mobile-without-authentication, and all-platform projects. Each follows the CLI's formatting and installation steps, then runs the first CI frozen install, `bun run check`, its retained unit tests, and web and selected CLI/SDK builds. Pass `web-minimal`, `web-android`, `mobile-minimal`, or `all-platforms` after `verify:starter` to check one selection. These checks use no provider credentials and do not provision or deploy resources. Native builds and installed-app behavior still need the platform checks below.
111
+
112
+ Published generator releases can collect limited Disposabl usage analytics when centrally configured. They record the generator version, operating system, package-manager category and outcome, using a random ID that can be linked to your Disposabl user ID after login. They do not collect prompts, arguments, paths, error messages, credentials or email. Set `DO_NOT_TRACK=1` or `DISPOSABL_TELEMETRY_DISABLED=1` to opt out. Local source, development, CI and E2E runs do not send events. This is separate from analytics you configure for your own app.
113
+
114
+ Release builds must receive the central public PostHog project token in `DISPOSABL_CLI_POSTHOG_PROJECT_TOKEN` and its approved ingestion origin in `DISPOSABL_CLI_POSTHOG_HOST`. Both values are embedded at build time; a release build fails if they are missing. `DISPOSABL_CLI_TELEMETRY_REQUIRED=1` enforces this check for development-version qualification builds. Use the central public project token, never a personal API key or a generated app owner’s project token.
package/dist/disposabl.js CHANGED
@@ -3,9 +3,10 @@
3
3
  // ../cli/auth.ts
4
4
  import { lock } from "proper-lockfile";
5
5
  // ../cli/package.json
6
+ var version = "0.17.0";
6
7
  var package_default = {
7
8
  name: "@disposabl/cli",
8
- version: "0.15.0",
9
+ version,
9
10
  type: "module",
10
11
  description: "Command-line access to your Disposabl app",
11
12
  license: "MIT",
@@ -70,7 +71,9 @@ var fetchFor = (origin) => Object.assign(async (input, init) => {
70
71
  redirect: "error",
71
72
  signal: init?.signal ?? AbortSignal.timeout(30000)
72
73
  });
73
- }, { preconnect: fetch.preconnect });
74
+ }, {
75
+ preconnect: fetch.preconnect
76
+ });
74
77
  async function load(url) {
75
78
  try {
76
79
  return JSON.parse(await readFile(sessionPath(url), "utf8"));
@@ -80,6 +83,10 @@ async function load(url) {
80
83
  throw error;
81
84
  }
82
85
  }
86
+ async function credentialRevision() {
87
+ const session = await load("https://www.disposabl.dev");
88
+ return createHash("sha256").update(session.tokens?.access_token ?? "anonymous").digest("hex");
89
+ }
83
90
  async function save(url, session) {
84
91
  await mkdir(directory(), { recursive: true, mode: 448 });
85
92
  await chmod(directory(), 448);
@@ -250,10 +257,20 @@ async function withCredentials(url, operation) {
250
257
  await release();
251
258
  }
252
259
  }
260
+ function withCredentialSession(url, operation) {
261
+ return withCredentials(url, () => operation({
262
+ login: (browser) => unlockedLogin(url, browser),
263
+ logout: () => unlockedLogout(url),
264
+ hasCredentials: () => hasCredentials(url),
265
+ accessToken: (refresh) => unlockedAccessToken(url, refresh),
266
+ loginAccessToken: () => loginAccessToken(url)
267
+ }));
268
+ }
253
269
  var login = (url, browser = true) => withCredentials(url, () => unlockedLogin(url, browser));
254
270
  var accessToken = (url, refresh = false) => withCredentials(url, () => unlockedAccessToken(url, refresh));
255
271
  var logout = (url) => withCredentials(url, () => unlockedLogout(url));
256
272
  var hasCredentials = async (url) => Boolean(process.env.DISPOSABL_API_KEY || (await load(url)).tokens?.access_token);
273
+ var loginAccessToken = async (url) => (await load(url)).tokens?.access_token;
257
274
 
258
275
  // ../cli/delete.ts
259
276
  function openExpoDeletion(body, appId, browser) {
@@ -275,50 +292,328 @@ Sign in to Expo if needed and choose Delete project. Then rerun this command to
275
292
  openUrl(url.href);
276
293
  }
277
294
 
295
+ // ../cli/telemetry.ts
296
+ import { createHash as createHash2, randomUUID } from "node:crypto";
297
+ import { realpathSync } from "node:fs";
298
+ import { mkdir as mkdir2, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
299
+ import { homedir as homedir2 } from "node:os";
300
+ import { dirname, join as join2 } from "node:path";
301
+ import { lock as lock2 } from "proper-lockfile";
302
+ function installedRelease(version, entry = process.argv[1] ?? "") {
303
+ try {
304
+ entry = realpathSync(entry);
305
+ } catch {}
306
+ return /(?:^|[\\/])node_modules[\\/]/.test(entry) && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) && !version.includes("development");
307
+ }
308
+ function telemetryConfig(version, entry = process.argv[1] ?? "") {
309
+ const env = process.env;
310
+ const host = "https://us.i.posthog.com";
311
+ const token = "phc_AkMtHdssxpHojfRGD985EUbxkX2GuMSxKiULHaTT9TgM";
312
+ if (!installedRelease(version, entry) || env.NODE_ENV === "test" || env.NODE_ENV === "development" || env.BUN_ENV === "test" || env.CI || env.E2E_TELEMETRY_DISABLED || ["1", "true"].includes(env.DO_NOT_TRACK?.toLowerCase() ?? "") || env.DISPOSABL_TELEMETRY_DISABLED === "1" || env.DISPOSABL_API_KEY || env.DISPOSABL_API_ORIGIN && env.DISPOSABL_API_ORIGIN !== "https://www.disposabl.dev" || !token?.startsWith("phc_") || !["https://us.i.posthog.com", "https://eu.i.posthog.com"].includes(host ?? ""))
313
+ return null;
314
+ return { token, host };
315
+ }
316
+ var directory2 = () => join2(homedir2(), ".config", "disposabl");
317
+ var telemetryStatePath = () => join2(directory2(), "telemetry.json");
318
+ async function state(path) {
319
+ const revision = await credentialRevision();
320
+ try {
321
+ const value = JSON.parse(await readFile2(path, "utf8"));
322
+ if (/^[0-9a-f-]{36}$/.test(value.anonymousId) && (!value.userId || /^[a-zA-Z0-9_-]{1,128}$/.test(value.userId)) && value.credentialRevision === revision)
323
+ return value;
324
+ } catch (error) {
325
+ if (!(error instanceof SyntaxError) && error.code !== "ENOENT")
326
+ throw error;
327
+ }
328
+ await mkdir2(join2(path, ".."), { recursive: true, mode: 448 });
329
+ const fresh = {
330
+ anonymousId: randomUUID(),
331
+ credentialRevision: revision
332
+ };
333
+ await writeFile2(path, JSON.stringify(fresh), { mode: 384 });
334
+ return fresh;
335
+ }
336
+ async function synchronized(path, run) {
337
+ await mkdir2(dirname(path), { recursive: true, mode: 448 });
338
+ const release = await lock2(path, {
339
+ realpath: false,
340
+ stale: 5000,
341
+ retries: { retries: 20, minTimeout: 50, maxTimeout: 50 }
342
+ });
343
+ try {
344
+ return await run();
345
+ } finally {
346
+ await release();
347
+ }
348
+ }
349
+ async function send(config, event, distinctId, properties) {
350
+ const response = await fetch(`${config.host}/i/v0/e/`, {
351
+ method: "POST",
352
+ redirect: "error",
353
+ signal: AbortSignal.timeout(500),
354
+ headers: { "Content-Type": "application/json" },
355
+ body: JSON.stringify({
356
+ api_key: config.token,
357
+ event,
358
+ distinct_id: distinctId,
359
+ properties: { ...properties, $geoip_disable: true, $ip: "0.0.0.0" }
360
+ })
361
+ });
362
+ return response.ok;
363
+ }
364
+ async function capture(version, product, command, outcome, path) {
365
+ const config = telemetryConfig(version);
366
+ if (!config)
367
+ return;
368
+ try {
369
+ const current = await synchronized(path, () => state(path));
370
+ if (current.credentialRevision !== await credentialRevision())
371
+ return;
372
+ const allowed = [
373
+ "agent",
374
+ "login",
375
+ "logout",
376
+ "apps",
377
+ "previews",
378
+ "connections",
379
+ "users",
380
+ "help",
381
+ "version",
382
+ "other",
383
+ "create"
384
+ ];
385
+ await send(config, "cli_command", current.userId ?? current.anonymousId, {
386
+ product,
387
+ command: allowed.includes(command) ? command : "other",
388
+ outcome,
389
+ version,
390
+ invocation: process.env.npm_command === "exec" ? "npx" : /^(npm|pnpm|yarn|bun)\//.exec(process.env.npm_config_user_agent ?? "")?.[1] ?? "direct",
391
+ platform: ["darwin", "linux", "win32"].includes(process.platform) ? process.platform : "other",
392
+ ...!current.userId ? { $process_person_profile: false } : {}
393
+ });
394
+ } catch {}
395
+ }
396
+ async function prepareLogin(path) {
397
+ try {
398
+ return await synchronized(path, async () => {
399
+ const current = await state(path);
400
+ const loginAttempt = randomUUID();
401
+ const next = {
402
+ anonymousId: current.userId || current.loginAttempt || current.credentialRevision !== createHash2("sha256").update("anonymous").digest("hex") ? randomUUID() : current.anonymousId,
403
+ loginAttempt,
404
+ credentialRevision: await credentialRevision()
405
+ };
406
+ await writeFile2(path, JSON.stringify(next), { mode: 384 });
407
+ return loginAttempt;
408
+ });
409
+ } catch {
410
+ return;
411
+ }
412
+ }
413
+ async function identify(version, userId, path, attempt, revision = undefined) {
414
+ const config = telemetryConfig(version);
415
+ if (!config || !attempt || typeof userId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(userId))
416
+ return;
417
+ try {
418
+ const expectedRevision = revision ?? await credentialRevision();
419
+ await synchronized(path, async () => {
420
+ const current = JSON.parse(await readFile2(path, "utf8"));
421
+ if (current.loginAttempt !== attempt || expectedRevision !== await credentialRevision() || current.userId || !/^[0-9a-f-]{36}$/.test(current.anonymousId))
422
+ return;
423
+ const opaqueId = createHash2("sha256").update(`disposabl:${config.token}:${userId}`).digest("hex");
424
+ if (await send(config, "$identify", opaqueId, {
425
+ $anon_distinct_id: current.anonymousId
426
+ })) {
427
+ await writeFile2(path, JSON.stringify({
428
+ anonymousId: current.anonymousId,
429
+ userId: opaqueId,
430
+ credentialRevision: expectedRevision
431
+ }), { mode: 384 });
432
+ }
433
+ });
434
+ } catch {}
435
+ }
436
+ async function resetIdentity(path, attempt) {
437
+ try {
438
+ await synchronized(path, async () => {
439
+ if (attempt) {
440
+ const current = JSON.parse(await readFile2(path, "utf8"));
441
+ if (current.loginAttempt !== attempt)
442
+ return;
443
+ }
444
+ await rm2(path, { force: true });
445
+ });
446
+ } catch {}
447
+ }
448
+
449
+ // ../cli/errors.ts
450
+ function apiError(status, body) {
451
+ try {
452
+ const data = JSON.parse(body)?.error;
453
+ if (data?.code === "credits_required") {
454
+ const paymentUrl = data.paymentUrl === "https://www.disposabl.dev/pricing" ? `
455
+ Add credits: ${data.paymentUrl}` : "";
456
+ return `At least 10 credits are required for each agent request. Agent compute costs 10 credits per 10-minute window; AI is currently included.${paymentUrl}`;
457
+ }
458
+ if (data?.code === "credits_unavailable")
459
+ return "Credits are temporarily unavailable. Please retry.";
460
+ } catch {}
461
+ return `API request failed (${status}): ${body}`;
462
+ }
463
+
278
464
  // ../cli/client.ts
279
465
  import { Command } from "commander";
280
- function createProgram(serviceOrigin) {
466
+ function createProgram(serviceOrigin, centralAnalytics = false, dependencies = {}) {
467
+ const version = dependencies.version ?? package_default.version;
468
+ const path = () => dependencies.telemetryPath ?? telemetryStatePath();
469
+ const sessionLogin = dependencies.login ?? login;
470
+ const sessionLogout = dependencies.logout ?? logout;
471
+ const sessionHasCredentials = dependencies.hasCredentials ?? hasCredentials;
472
+ const sessionAccessToken = dependencies.accessToken ?? accessToken;
473
+ const sessionLoginAccessToken = dependencies.loginAccessToken ?? loginAccessToken;
474
+ const credentialSession = (url, operation) => {
475
+ if (dependencies.credentialSession)
476
+ return dependencies.credentialSession(url, operation);
477
+ if (!(dependencies.login || dependencies.logout || dependencies.hasCredentials || dependencies.accessToken || dependencies.loginAccessToken))
478
+ return withCredentialSession(url, operation);
479
+ return operation({
480
+ login: (browser) => sessionLogin(url, browser),
481
+ logout: () => sessionLogout(url),
482
+ hasCredentials: () => sessionHasCredentials(url),
483
+ accessToken: (refresh) => sessionAccessToken(url, refresh),
484
+ loginAccessToken: () => sessionLoginAccessToken(url)
485
+ });
486
+ };
281
487
  const program = new Command().name(Object.keys(package_default.bin)[0]).version(package_default.version);
488
+ if (centralAnalytics)
489
+ program.addHelpText("after", `
490
+ Disposabl collects limited CLI usage when configured. Set DO_NOT_TRACK=1 to opt out.
491
+ `);
282
492
  const origin = () => apiUrl(serviceOrigin);
283
493
  const loginCommand = program.command("login").option("--no-browser", "Print the login URL without opening a browser").action(async (options) => {
284
- await login(origin(), options.browser);
494
+ const base = origin();
495
+ const central = centralAnalytics && base === "https://www.disposabl.dev" && installedRelease(version);
496
+ const enabled = central && telemetryConfig(version);
497
+ const { attempt, token, revision } = await credentialSession(base, async (session) => {
498
+ let attempt;
499
+ if (central) {
500
+ if (enabled)
501
+ attempt = await prepareLogin(path());
502
+ else
503
+ await resetIdentity(path());
504
+ }
505
+ await session.login(options.browser);
506
+ return {
507
+ attempt,
508
+ revision: enabled ? await credentialRevision().catch(() => {
509
+ return;
510
+ }) : undefined,
511
+ token: enabled ? await session.loginAccessToken().catch(() => {
512
+ return;
513
+ }) : undefined
514
+ };
515
+ });
516
+ if (enabled && token && revision) {
517
+ try {
518
+ const response = await fetch(`${base}/api/users/current`, {
519
+ headers: { Authorization: `Bearer ${token}` },
520
+ redirect: "error",
521
+ signal: AbortSignal.timeout(500)
522
+ });
523
+ if (response.ok)
524
+ await identify(version, (await response.json())?.id, path(), attempt, revision);
525
+ } catch {}
526
+ }
285
527
  console.error("Signed in.");
286
528
  });
287
529
  loginCommand.command("status").description("Return the server-verified current user").action(async () => {
288
530
  const base = origin();
289
- if (!await hasCredentials(base)) {
531
+ const enabled = centralAnalytics && base === "https://www.disposabl.dev" && telemetryConfig(version);
532
+ let snapshot;
533
+ try {
534
+ snapshot = await credentialSession(base, async (session) => {
535
+ if (!await session.hasCredentials()) {
536
+ if (enabled)
537
+ await resetIdentity(path());
538
+ return;
539
+ }
540
+ const attempt = enabled ? await prepareLogin(path()) : undefined;
541
+ try {
542
+ const token = await session.accessToken();
543
+ return {
544
+ token,
545
+ attempt,
546
+ revision: enabled ? await credentialRevision().catch(() => {
547
+ return;
548
+ }) : undefined
549
+ };
550
+ } catch (error) {
551
+ if (enabled && attempt)
552
+ await resetIdentity(path(), attempt);
553
+ throw error;
554
+ }
555
+ });
556
+ } catch (error) {
557
+ if (!(error instanceof NotAuthenticated))
558
+ throw error;
559
+ console.log(JSON.stringify({ currentUser: null }));
560
+ return;
561
+ }
562
+ if (!snapshot) {
290
563
  console.log(JSON.stringify({ currentUser: null }));
291
564
  return;
292
565
  }
293
- const send = async (refresh = false) => fetch(`${base}/api/users/current`, {
566
+ const send = (token) => fetch(`${base}/api/users/current`, {
294
567
  headers: {
295
- Authorization: `Bearer ${await accessToken(base, refresh)}`,
568
+ Authorization: `Bearer ${token}`,
296
569
  "X-Disposabl-Source": "cli"
297
570
  },
298
571
  redirect: "error",
299
572
  signal: AbortSignal.timeout(30000)
300
573
  });
301
- let response;
302
- try {
303
- response = await send();
304
- if (response.status === 401 && !process.env.DISPOSABL_API_KEY)
305
- response = await send(true);
306
- } catch (error) {
307
- if (!(error instanceof NotAuthenticated))
308
- throw error;
309
- console.log(JSON.stringify({ currentUser: null }));
310
- return;
574
+ let response = await send(snapshot.token);
575
+ if (response.status === 401 && !process.env.DISPOSABL_API_KEY) {
576
+ try {
577
+ const refreshed = await credentialSession(base, async (session) => {
578
+ if (await session.loginAccessToken() !== snapshot.token)
579
+ return;
580
+ const token = await session.accessToken(true);
581
+ return {
582
+ token,
583
+ revision: enabled ? await credentialRevision().catch(() => {
584
+ return;
585
+ }) : undefined
586
+ };
587
+ });
588
+ if (refreshed) {
589
+ snapshot.revision = refreshed.revision;
590
+ response = await send(refreshed.token);
591
+ }
592
+ } catch (error) {
593
+ if (!(error instanceof NotAuthenticated))
594
+ throw error;
595
+ }
311
596
  }
312
597
  if (response.status === 401) {
598
+ if (enabled && snapshot.attempt)
599
+ await resetIdentity(path(), snapshot.attempt);
313
600
  console.log(JSON.stringify({ currentUser: null }));
314
601
  return;
315
602
  }
316
603
  if (!response.ok)
317
604
  throw new Error(`Login status failed (${response.status}).`);
318
- console.log(JSON.stringify({ currentUser: await response.json() }));
605
+ const currentUser = await response.json();
606
+ if (enabled && snapshot.revision)
607
+ await identify(version, currentUser?.id, path(), snapshot.attempt, snapshot.revision);
608
+ console.log(JSON.stringify({ currentUser }));
319
609
  });
320
610
  program.command("logout").action(async () => {
321
- await logout(origin());
611
+ const base = origin();
612
+ await credentialSession(base, async (session) => {
613
+ await session.logout();
614
+ if (centralAnalytics && base === "https://www.disposabl.dev" && installedRelease(version))
615
+ await resetIdentity(path());
616
+ });
322
617
  console.error("Signed out.");
323
618
  });
324
619
  return program;
@@ -384,31 +679,31 @@ function needsContract(program, argv, origin) {
384
679
  }
385
680
 
386
681
  // ../cli/commands.ts
387
- import { readFile as readFile3 } from "node:fs/promises";
388
- import { join as join4 } from "node:path";
682
+ import { readFile as readFile4 } from "node:fs/promises";
683
+ import { join as join5 } from "node:path";
389
684
 
390
685
  // ../cli/repository.ts
391
- import { createHash as createHash2, randomUUID } from "node:crypto";
392
- import { mkdir as mkdir2, chmod as chmod2, writeFile as writeFile2, rename as rename2, rm as rm2 } from "node:fs/promises";
393
- import { homedir as homedir2 } from "node:os";
394
- import { join as join2 } from "node:path";
686
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
687
+ import { mkdir as mkdir3, chmod as chmod2, writeFile as writeFile3, rename as rename2, rm as rm3 } from "node:fs/promises";
688
+ import { homedir as homedir3 } from "node:os";
689
+ import { join as join3 } from "node:path";
395
690
  async function configureRepository(origin, appId, value) {
396
691
  if (!value.token || !/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(value.repository))
397
692
  throw new Error("Invalid repository credential response.");
398
- const directory = process.env.DISPOSABL_CONFIG_DIR || join2(homedir2(), ".config", "disposabl");
399
- const key = createHash2("sha256").update(JSON.stringify([origin, appId])).digest("hex");
400
- const credentialFile = join2(directory, `repository-${key}.json`);
401
- const temporary = `${credentialFile}.${randomUUID()}`;
402
- await mkdir2(directory, { recursive: true, mode: 448 });
693
+ const directory = process.env.DISPOSABL_CONFIG_DIR || join3(homedir3(), ".config", "disposabl");
694
+ const key = createHash3("sha256").update(JSON.stringify([origin, appId])).digest("hex");
695
+ const credentialFile = join3(directory, `repository-${key}.json`);
696
+ const temporary = `${credentialFile}.${randomUUID2()}`;
697
+ await mkdir3(directory, { recursive: true, mode: 448 });
403
698
  await chmod2(directory, 448);
404
699
  try {
405
- await writeFile2(temporary, JSON.stringify(value), {
700
+ await writeFile3(temporary, JSON.stringify(value), {
406
701
  mode: 384,
407
702
  flag: "wx"
408
703
  });
409
704
  await rename2(temporary, credentialFile);
410
705
  } finally {
411
- await rm2(temporary, { force: true });
706
+ await rm3(temporary, { force: true });
412
707
  }
413
708
  return { repository: value.repository, credentialFile };
414
709
  }
@@ -417,13 +712,13 @@ async function configureRepository(origin, appId, value) {
417
712
  import {
418
713
  chmod as chmod3,
419
714
  lstat,
420
- readFile as readFile2,
715
+ readFile as readFile3,
421
716
  rename as rename3,
422
- writeFile as writeFile3,
423
- rm as rm3
717
+ writeFile as writeFile4,
718
+ rm as rm4
424
719
  } from "node:fs/promises";
425
- import { basename, join as join3, resolve } from "node:path";
426
- import { randomUUID as randomUUID2 } from "node:crypto";
720
+ import { basename, join as join4, resolve } from "node:path";
721
+ import { randomUUID as randomUUID3 } from "node:crypto";
427
722
  import { spawnSync } from "node:child_process";
428
723
  function detectReference(directory = process.cwd()) {
429
724
  const git = (...args) => spawnSync("git", args, { cwd: directory, encoding: "utf8" }).stdout?.trim();
@@ -445,7 +740,7 @@ async function updateEnv(file, values, remove = []) {
445
740
  });
446
741
  if (stat && (!stat.isFile() || stat.isSymbolicLink()))
447
742
  throw new Error(`Refusing to replace non-regular file ${file}.`);
448
- const text = stat ? await readFile2(file, "utf8") : "";
743
+ const text = stat ? await readFile3(file, "utf8") : "";
449
744
  const keys = new Set([...Object.keys(values), ...remove]);
450
745
  const lines = text.split(`
451
746
  `).filter((line) => !keys.has(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=/.exec(line)?.[1] ?? ""));
@@ -454,18 +749,18 @@ async function updateEnv(file, values, remove = []) {
454
749
  ` + Object.entries(values).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(`
455
750
  `) + `
456
751
  `;
457
- const temporary = `${file}.${randomUUID2()}.tmp`;
752
+ const temporary = `${file}.${randomUUID3()}.tmp`;
458
753
  try {
459
- await writeFile3(temporary, next, { flag: "wx", mode: 384 });
754
+ await writeFile4(temporary, next, { flag: "wx", mode: 384 });
460
755
  await rename3(temporary, file);
461
756
  await chmod3(file, 384);
462
757
  } finally {
463
- await rm3(temporary, { force: true });
758
+ await rm4(temporary, { force: true });
464
759
  }
465
760
  }
466
761
  async function configureDevelopment(directory, value) {
467
762
  const root = resolve(directory);
468
- const config = JSON.parse(await readFile2(join3(root, "disposabl.json"), "utf8"));
763
+ const config = JSON.parse(await readFile3(join4(root, "disposabl.json"), "utf8"));
469
764
  if (config.appId !== value.appId || !value.deployKey.startsWith(`dev:${value.name}|`))
470
765
  throw new Error("Development credentials do not match this app.");
471
766
  if (!/^[a-z0-9-]+$/.test(value.name) || value.convexUrl !== `https://${value.name}.convex.cloud` || value.convexSiteUrl !== `https://${value.name}.convex.site`)
@@ -517,7 +812,7 @@ async function configureDevelopment(directory, value) {
517
812
  config.analytics = value.analytics;
518
813
  else
519
814
  delete config.analytics;
520
- await writeFile3(join3(root, "disposabl.json"), JSON.stringify(config, null, 2) + `
815
+ await writeFile4(join4(root, "disposabl.json"), JSON.stringify(config, null, 2) + `
521
816
  `);
522
817
  const formatted = spawnSync("bun", ["fmt", "disposabl.json"], {
523
818
  cwd: root,
@@ -526,17 +821,17 @@ async function configureDevelopment(directory, value) {
526
821
  if (formatted.status !== 0)
527
822
  throw new Error("Could not format disposabl.json after configuring development.");
528
823
  }
529
- await updateEnv(join3(root, files[0]), {
824
+ await updateEnv(join4(root, files[0]), {
530
825
  CONVEX_DEPLOY_KEY: value.deployKey,
531
826
  CONVEX_URL: value.convexUrl,
532
827
  CONVEX_SITE_URL: value.convexSiteUrl
533
828
  }, ["CONVEX_DEPLOYMENT"]);
534
- await updateEnv(join3(root, files[1]), {
829
+ await updateEnv(join4(root, files[1]), {
535
830
  VITE_CONVEX_URL: value.convexUrl,
536
831
  VITE_CONVEX_SITE_URL: value.convexSiteUrl
537
832
  });
538
833
  if (files[2])
539
- await updateEnv(join3(root, files[2]), {
834
+ await updateEnv(join4(root, files[2]), {
540
835
  EXPO_PUBLIC_CONVEX_URL: value.convexUrl,
541
836
  EXPO_PUBLIC_CONVEX_SITE_URL: value.convexSiteUrl
542
837
  });
@@ -574,7 +869,7 @@ function formatPreview(preview) {
574
869
 
575
870
  // ../cli/commands.ts
576
871
  async function runCli(argv = process.argv, serviceOrigin = process.env.DISPOSABL_API_ORIGIN || SERVICE_ORIGIN) {
577
- const program = createProgram(serviceOrigin);
872
+ const program = createProgram(serviceOrigin, true);
578
873
  const origin = () => apiUrl(serviceOrigin);
579
874
  async function main() {
580
875
  if (needsContract(program, argv, serviceOrigin)) {
@@ -620,7 +915,7 @@ async function runCli(argv = process.argv, serviceOrigin = process.env.DISPOSABL
620
915
  if (deleteApp && options.dangerouslyDeleteApp !== true)
621
916
  throw new Error("Permanent deletion requires --dangerously-delete-app. Apps with production releases cannot be deleted.");
622
917
  if ((previewGet || tokenCreate) && !options.appId) {
623
- const config = JSON.parse(await readFile3(join4(options.configure ?? process.cwd(), "disposabl.json"), "utf8"));
918
+ const config = JSON.parse(await readFile4(join5(options.configure ?? process.cwd(), "disposabl.json"), "utf8"));
624
919
  if (!config.appId)
625
920
  throw new Error("No appId in disposabl.json. Run setup or pass --appId.");
626
921
  options.appId = config.appId;
@@ -636,7 +931,7 @@ async function runCli(argv = process.argv, serviceOrigin = process.env.DISPOSABL
636
931
  if (deleteApp && !result.ok)
637
932
  openExpoDeletion(await result.clone().json().catch(() => null), options.appId, options.browser !== false);
638
933
  if (!result.ok)
639
- throw new Error(`API request failed (${result.status}): ${await result.text()}`);
934
+ throw new Error(apiError(result.status, await result.text()));
640
935
  let value = await result.json();
641
936
  const ready = () => value.ready && (!options.mobile || Boolean(value.expo));
642
937
  if (connectionStatus && options.wait && !ready()) {
@@ -689,7 +984,19 @@ Waiting for connections. Press Ctrl+C to keep your files and finish later.`);
689
984
  }
690
985
  await program.parseAsync(argv);
691
986
  }
692
- await main();
987
+ const command = argv[2] ?? "help";
988
+ const central = serviceOrigin === SERVICE_ORIGIN;
989
+ if (central)
990
+ await capture(version, "cli", command, "started", telemetryStatePath());
991
+ try {
992
+ await main();
993
+ if (central)
994
+ await capture(version, "cli", command, "success", telemetryStatePath());
995
+ } catch (error) {
996
+ if (central)
997
+ await capture(version, "cli", command, "failure", telemetryStatePath());
998
+ throw error;
999
+ }
693
1000
  }
694
1001
 
695
1002
  // ../cli/index.ts