create-disposabl-app 0.7.1 → 0.8.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 (31) hide show
  1. package/dist/disposabl.js +35 -4
  2. package/dist/index.js +1 -1
  3. package/dist/templates/default/.github/workflows/pipeline.yml +4 -4
  4. package/dist/templates/default/packages/backend/AGENTS.md +2 -0
  5. package/dist/templates/default/packages/backend/README.md +2 -2
  6. package/dist/templates/default/packages/backend/convex/_generated/api.d.ts +10 -0
  7. package/dist/templates/default/packages/backend/convex/apps/actions/cleanup.ts +295 -0
  8. package/dist/templates/default/packages/backend/convex/apps/actions/delete.ts +15 -0
  9. package/dist/templates/default/packages/backend/convex/apps/actions/expo.ts +174 -0
  10. package/dist/templates/default/packages/backend/convex/apps/internal.ts +4 -21
  11. package/dist/templates/default/packages/backend/convex/apps/operations/internal.ts +213 -0
  12. package/dist/templates/default/packages/backend/convex/apps/validator.ts +23 -0
  13. package/dist/templates/default/packages/backend/convex/connections/actions/github.ts +1 -3
  14. package/dist/templates/default/packages/backend/convex/connections/index.ts +8 -8
  15. package/dist/templates/default/packages/backend/convex/connections/internal.ts +1 -2
  16. package/dist/templates/default/packages/backend/convex/github/actions/internal.ts +6 -0
  17. package/dist/templates/default/packages/backend/convex/github/actions/secrets.ts +35 -2
  18. package/dist/templates/default/packages/backend/convex/github/actions/tokens.ts +6 -2
  19. package/dist/templates/default/packages/backend/convex/github/internal.ts +5 -4
  20. package/dist/templates/default/packages/backend/convex/previews/internal.ts +5 -5
  21. package/dist/templates/default/packages/backend/convex/previews/token/actions/create.ts +30 -19
  22. package/dist/templates/default/packages/backend/convex/previews/token/actions/management.ts +2 -1
  23. package/dist/templates/default/packages/backend/convex/schema.ts +10 -0
  24. package/dist/templates/default/packages/backend/generated/openapi.json +5 -2
  25. package/dist/templates/default/packages/backend/generated/platforms.ts +14 -12
  26. package/dist/templates/default/packages/cli/README.md +3 -1
  27. package/dist/templates/default/packages/cli/commands.ts +23 -2
  28. package/dist/templates/default/packages/cli/delete.ts +39 -0
  29. package/dist/templates/default/packages/disposabl-kit/server/lib/platform-spec.ts +10 -2
  30. package/dist/templates/default/packages/sdk/src/generated/types.gen.ts +1 -0
  31. package/package.json +1 -1
package/dist/disposabl.js CHANGED
@@ -1,5 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // ../cli/delete.ts
4
+ import { spawn } from "node:child_process";
5
+ async function completeExpoDeletion(projectId) {
6
+ if (typeof projectId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(projectId))
7
+ throw new Error("The service returned an invalid Expo project ID.");
8
+ const command = `bunx eas-cli@27.2.0 project:delete ${projectId}`;
9
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
10
+ throw new Error(`Expo needs an interactive login and password confirmation. Run ${command}, then retry apps delete. Your app and remaining resources are retained.`);
11
+ console.error("Expo requires you to confirm deletion in your Expo account. Complete the following EAS prompts to continue.");
12
+ const { EXPO_TOKEN: _token, ...env } = process.env;
13
+ await new Promise((resolve, reject) => {
14
+ const child = spawn("bunx", ["eas-cli@27.2.0", "project:delete", projectId], { stdio: "inherit", env });
15
+ child.on("error", reject);
16
+ child.on("exit", (code) => code === 0 ? resolve() : reject(new Error("Expo deletion was not completed. Retry apps delete when ready.")));
17
+ });
18
+ }
19
+
3
20
  // ../cli/commands.ts
4
21
  import { Command } from "commander";
5
22
  // ../cli/package.json
@@ -65,11 +82,11 @@ import {
65
82
  } from "node:fs/promises";
66
83
  import { homedir } from "node:os";
67
84
  import { join } from "node:path";
68
- import { spawn } from "node:child_process";
85
+ import { spawn as spawn2 } from "node:child_process";
69
86
  function openUrl(url) {
70
87
  const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
71
88
  const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
72
- const child = spawn(command, args, { stdio: "ignore" });
89
+ const child = spawn2(command, args, { stdio: "ignore" });
73
90
  child.on("error", () => console.error("Open the URL manually."));
74
91
  child.unref();
75
92
  }
@@ -470,6 +487,7 @@ async function runCli(argv = process.argv, serviceOrigin = SERVICE_ORIGIN) {
470
487
  const connectionStatus = path === "/api/connections/status";
471
488
  if (connectionStatus)
472
489
  command.option("--wait", "Open Connections and continue when GitHub and Convex are connected");
490
+ const deleteApp = path === "/api/apps/delete";
473
491
  const previewGet = path === "/api/previews/get";
474
492
  const tokenCreate = path === "/api/previews/token/create";
475
493
  if (previewGet)
@@ -487,6 +505,10 @@ async function runCli(argv = process.argv, serviceOrigin = SERVICE_ORIGIN) {
487
505
  schema: value
488
506
  }));
489
507
  for (const field of fields) {
508
+ if (deleteApp && field.name === "dangerouslyDeleteApp") {
509
+ command.option("--dangerously-delete-app", "Permanently delete this preview app and its GitHub, Convex and Expo projects");
510
+ continue;
511
+ }
490
512
  const flag = `--${field.name} <value>`;
491
513
  if (field.required && !(field.name === "appId" && (previewGet || tokenCreate)) && !(field.name === "reference" && (previewGet || tokenCreate)))
492
514
  command.requiredOption(flag, field.schema.type === "string" ? field.name : `${field.name} as JSON`);
@@ -494,6 +516,8 @@ async function runCli(argv = process.argv, serviceOrigin = SERVICE_ORIGIN) {
494
516
  command.option(flag, field.name);
495
517
  }
496
518
  command.action(async (options) => {
519
+ if (deleteApp && options.dangerouslyDeleteApp !== true)
520
+ throw new Error("Permanent deletion requires --dangerously-delete-app. Apps with production releases cannot be deleted.");
497
521
  if ((previewGet || tokenCreate) && !options.appId) {
498
522
  const config = JSON.parse(await readFile3(join3(options.configure ?? process.cwd(), "disposabl.json"), "utf8"));
499
523
  if (!config.appId)
@@ -504,7 +528,7 @@ async function runCli(argv = process.argv, serviceOrigin = SERVICE_ORIGIN) {
504
528
  options.reference = detectReference(options.configure);
505
529
  const input = Object.fromEntries(fields.filter((field) => options[field.name] !== undefined).map((field) => [
506
530
  field.name,
507
- field.schema.type === "string" ? options[field.name] : JSON.parse(options[field.name])
531
+ field.schema.type === "string" || typeof options[field.name] === "boolean" ? options[field.name] : JSON.parse(options[field.name])
508
532
  ]));
509
533
  const target = new URL(path, base);
510
534
  if (target.origin !== base || !target.pathname.startsWith("/api/"))
@@ -515,7 +539,7 @@ async function runCli(argv = process.argv, serviceOrigin = SERVICE_ORIGIN) {
515
539
  const send = async (refresh = false) => fetch(target, {
516
540
  method: method.toUpperCase(),
517
541
  redirect: "error",
518
- signal: AbortSignal.timeout(30000),
542
+ signal: AbortSignal.timeout(deleteApp ? 300000 : 30000),
519
543
  headers: {
520
544
  Authorization: `Bearer ${await accessToken(base, refresh)}`,
521
545
  "Content-Type": "application/json"
@@ -525,6 +549,13 @@ async function runCli(argv = process.argv, serviceOrigin = SERVICE_ORIGIN) {
525
549
  let result = await send();
526
550
  if (result.status === 401 && !process.env.DISPOSABL_API_KEY)
527
551
  result = await send(true);
552
+ if (deleteApp && result.status === 400) {
553
+ const body = await result.clone().json();
554
+ if (body.error?.code === "expo_delete_requires_login") {
555
+ await completeExpoDeletion(body.error.projectId);
556
+ result = await send();
557
+ }
558
+ }
528
559
  if (!result.ok)
529
560
  throw new Error(`API request failed (${result.status}): ${await result.text()}`);
530
561
  let value = await result.json();
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
8
8
  import { Command, CommanderError } from "commander";
9
9
  import * as p2 from "@clack/prompts";
10
10
  // package.json
11
- var version = "0.7.1";
11
+ var version = "0.8.0";
12
12
 
13
13
  // ../disposabl-kit/platforms.ts
14
14
  var platforms = [
@@ -49,9 +49,9 @@ jobs:
49
49
  PLATFORM: android
50
50
  ANDROID_SIGNING_READY: ${{ secrets.ANDROID_KEYSTORE_BASE64 != '' && secrets.ANDROID_KEYSTORE_PASSWORD != '' && secrets.ANDROID_KEY_ALIAS != '' && secrets.ANDROID_KEY_PASSWORD != '' }}
51
51
  EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
52
- EXPO_PROJECT_ID: ${{ vars.EXPO_PROJECT_ID }}
52
+ EXPO_PROJECT_ID: ${{ secrets.EXPO_PROJECT_ID || vars.EXPO_PROJECT_ID }}
53
53
  EXPO_OWNER: ${{ secrets.EXPO_OWNER || vars.EXPO_OWNER }}
54
- EXPO_SLUG: ${{ vars.EXPO_SLUG }}
54
+ EXPO_SLUG: ${{ secrets.EXPO_SLUG || vars.EXPO_SLUG }}
55
55
  EXPO_NO_DOTENV: "1"
56
56
  steps:
57
57
  - &checkout
@@ -159,9 +159,9 @@ jobs:
159
159
  env:
160
160
  PLATFORM: android
161
161
  EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
162
- EXPO_PROJECT_ID: ${{ vars.EXPO_PROJECT_ID }}
162
+ EXPO_PROJECT_ID: ${{ secrets.EXPO_PROJECT_ID || vars.EXPO_PROJECT_ID }}
163
163
  EXPO_OWNER: ${{ secrets.EXPO_OWNER || vars.EXPO_OWNER }}
164
- EXPO_SLUG: ${{ vars.EXPO_SLUG }}
164
+ EXPO_SLUG: ${{ secrets.EXPO_SLUG || vars.EXPO_SLUG }}
165
165
  EXPO_NO_DOTENV: "1"
166
166
  CONVEX_URL: ${{ needs.web.outputs.convex_url }}
167
167
  CONVEX_SITE_URL: ${{ needs.web.outputs.convex_site_url }}
@@ -7,6 +7,8 @@
7
7
  ## Modules
8
8
 
9
9
  - `index.ts`: web/mobile functions. Resolve `userId`, then call the internal function with the same name.
10
+ - Authenticate only at entry points: web/mobile `index.ts` uses `getAuthUserId` (or a `requireUser` helper); API/MCP verifies the caller before dispatch. Never accept a client-supplied `userId`.
11
+ - Internal functions validate their `userId` argument and trust the authenticated caller. Keep resource ownership and business rules there; do not repeat session/auth checks.
10
12
  - `internal.ts`: shared queries and mutations. Use `platforms: true` to expose functions to enabled platforms in `disposabl.json`.
11
13
  - `actions/`: all actions, including ordinary and `"use node"` actions. Never put queries or mutations in a Node action file.
12
14
  - Re-export ordinary platform actions from `internal.ts`. Call Node actions through `ctx.runAction`; never import a Node file into the default runtime.
@@ -2,9 +2,9 @@
2
2
 
3
3
  Run `bun run dev` at the workspace root, or `bun run dev` here for Convex alone.
4
4
 
5
- `apps`, `previews`, and `appReleases` hold application data. `githubConnections` stores installation bindings; `connections` stores encrypted Convex and Expo credentials. `users` provides authentication identities. App IDs are UUID v4 values; preview references are branch/worktree names, including `main`. Deletion permanently removes app, preview, and release records.
5
+ `apps`, `previews`, and `appReleases` hold application data. `githubConnections` stores installation bindings; `connections` stores encrypted Convex and Expo credentials. `users` provides authentication identities. App IDs are UUID v4 values; preview references are branch/worktree names, including `main`. Deletion requires explicit confirmation, removes linked cloud resources and previews, and permanently removes the app. A production release prevents deletion.
6
6
 
7
- `index.ts` resolves the authenticated user for web/mobile. `internal.ts` implements operations; `platforms: true` exposes them through enabled API, MCP, SDK, and CLI platforms. Actions live under `actions/`. Put argument/return validators in `validator.ts`, and table definitions in `schema.ts`.
7
+ `index.ts` resolves the authenticated user for web/mobile. `internal.ts` implements operations; `platforms: true` exposes them through enabled API, MCP, SDK, and CLI platforms. Internal functions validate the supplied `userId`; entry points authenticate it. Internal code checks resource ownership without repeating session checks. Actions live under `actions/`. Put argument/return validators in `validator.ts`, and table definitions in `schema.ts`.
8
8
 
9
9
  Managed setup uses the user's GitHub and Convex connections; Expo is optional. Connect accounts at `/dashboard/connections`. Login works independently. The CLI saves the app UUID before creating cloud resources so setup can resume after a failure.
10
10
 
@@ -8,9 +8,14 @@
8
8
  * @module
9
9
  */
10
10
 
11
+ import type * as apps_actions_cleanup from "../apps/actions/cleanup.js";
11
12
  import type * as apps_actions_create from "../apps/actions/create.js";
13
+ import type * as apps_actions_delete from "../apps/actions/delete.js";
14
+ import type * as apps_actions_expo from "../apps/actions/expo.js";
12
15
  import type * as apps_actions_setup from "../apps/actions/setup.js";
13
16
  import type * as apps_internal from "../apps/internal.js";
17
+ import type * as apps_operations_internal from "../apps/operations/internal.js";
18
+ import type * as apps_validator from "../apps/validator.js";
14
19
  import type * as auth from "../auth.js";
15
20
  import type * as connections_actions_credentials from "../connections/actions/credentials.js";
16
21
  import type * as connections_actions_expo from "../connections/actions/expo.js";
@@ -44,9 +49,14 @@ import type {
44
49
  } from "convex/server";
45
50
 
46
51
  declare const fullApi: ApiFromModules<{
52
+ "apps/actions/cleanup": typeof apps_actions_cleanup;
47
53
  "apps/actions/create": typeof apps_actions_create;
54
+ "apps/actions/delete": typeof apps_actions_delete;
55
+ "apps/actions/expo": typeof apps_actions_expo;
48
56
  "apps/actions/setup": typeof apps_actions_setup;
49
57
  "apps/internal": typeof apps_internal;
58
+ "apps/operations/internal": typeof apps_operations_internal;
59
+ "apps/validator": typeof apps_validator;
50
60
  auth: typeof auth;
51
61
  "connections/actions/credentials": typeof connections_actions_credentials;
52
62
  "connections/actions/expo": typeof connections_actions_expo;
@@ -0,0 +1,295 @@
1
+ "use node";
2
+
3
+ import {
4
+ identityFields,
5
+ internalAction,
6
+ } from "@disposabl/disposabl-kit/server/lib/functions";
7
+ import { ConvexError, v } from "convex/values";
8
+ import { internal } from "../../_generated/api";
9
+ import { credential } from "../../connections/actions/credentials";
10
+ import { validateExpo } from "../../connections/actions/expo";
11
+ import {
12
+ GitHubError,
13
+ githubRequest,
14
+ githubToken,
15
+ } from "../../github/actions/tokens";
16
+ import {
17
+ ManagementError,
18
+ management,
19
+ } from "../../previews/token/actions/management";
20
+ import { deleteArgs } from "../validator";
21
+ import { ExpoLoginRequired, deleteExpo, findExpo, verifyExpo } from "./expo";
22
+
23
+ export const remove = internalAction({
24
+ args: { ...identityFields, ...deleteArgs },
25
+ returns: v.null(),
26
+ handler: async (ctx, { userId, appId }): Promise<null> => {
27
+ const identity = { userId, appId };
28
+ const { until, resuming, pending } = await ctx.runMutation(
29
+ internal.apps.operations.internal.begin,
30
+ { ...identity, kind: "delete" },
31
+ );
32
+ let started = false;
33
+ const resume = (
34
+ provider: "github" | "convex" | "expo",
35
+ accountId: string,
36
+ ) => {
37
+ if (pending?.provider !== provider) return undefined;
38
+ if (pending.accountId !== accountId)
39
+ throw new ConvexError(
40
+ `Reconnect the original ${provider} account to finish deleting this app.`,
41
+ );
42
+ return pending;
43
+ };
44
+ const deleting = (
45
+ provider: "github" | "convex" | "expo",
46
+ accountId: string,
47
+ receipt?: string,
48
+ ) =>
49
+ ctx.runMutation(internal.apps.operations.internal.deletingResource, {
50
+ ...identity,
51
+ until,
52
+ pending: { provider, accountId, ...(receipt ? { receipt } : {}) },
53
+ });
54
+ const forget = (provider: "github" | "convex" | "expo") =>
55
+ ctx.runMutation(internal.apps.operations.internal.forget, {
56
+ ...identity,
57
+ until,
58
+ provider,
59
+ });
60
+ try {
61
+ const linked = await ctx.runQuery(
62
+ internal.apps.operations.internal.linked,
63
+ identity,
64
+ );
65
+ // Preflight every provider before deleting anything. Missing access is never success.
66
+ let github:
67
+ | { token: string; path: string; accountId: string; absent: boolean }
68
+ | undefined;
69
+ if (linked.githubRepo) {
70
+ const app = await ctx.runQuery(internal.apps.internal.githubApp, {
71
+ appId,
72
+ });
73
+ if (!app)
74
+ throw new ConvexError(
75
+ "Reconnect the GitHub account that owns this app before deleting it.",
76
+ );
77
+ const repository = `${app.githubOwner}/${app.githubRepo}`;
78
+ const retry = resume("github", app.githubOwner);
79
+ // An installation-wide token remains usable after this repository is deleted.
80
+ const token = await githubToken(
81
+ app.installationId,
82
+ ["administration:write", "contents:read", "actions:read"],
83
+ retry ? undefined : repository,
84
+ );
85
+ const path = `/repos/${repository}`;
86
+ let absent = false;
87
+ try {
88
+ const repo = await githubRequest<{
89
+ full_name: string;
90
+ description: string;
91
+ }>(token, path);
92
+ if (
93
+ repo.full_name.toLowerCase() !== repository.toLowerCase() ||
94
+ repo.description !== `Disposabl app ${appId}`
95
+ )
96
+ throw new ConvexError(
97
+ "The GitHub repository does not match this app. No resources were deleted.",
98
+ );
99
+ } catch (error) {
100
+ if (!retry || !(error instanceof GitHubError) || error.status !== 404)
101
+ throw error;
102
+ await githubRequest(token, "/installation/repositories?per_page=1");
103
+ absent = true;
104
+ }
105
+ if (!absent) {
106
+ for (let page = 1; ; page++) {
107
+ const releases = await githubRequest<
108
+ { draft: boolean; prerelease: boolean }[]
109
+ >(token, `${path}/releases?per_page=100&page=${page}`);
110
+ if (
111
+ releases.some((release) => !release.draft && !release.prerelease)
112
+ )
113
+ throw new ConvexError(
114
+ "Apps with production releases cannot be deleted.",
115
+ );
116
+ if (releases.length < 100) break;
117
+ }
118
+ for (const status of [
119
+ "queued",
120
+ "in_progress",
121
+ "waiting",
122
+ "pending",
123
+ "requested",
124
+ ]) {
125
+ const runs = await githubRequest<{ total_count: number }>(
126
+ token,
127
+ `${path}/actions/runs?status=${status}&per_page=1`,
128
+ );
129
+ if (runs.total_count)
130
+ throw new ConvexError(
131
+ "Wait for this app's GitHub Actions to finish before deleting it.",
132
+ );
133
+ }
134
+ }
135
+ github = { token, path, accountId: app.githubOwner, absent };
136
+ }
137
+ let convex:
138
+ | {
139
+ token: string;
140
+ projectId: number;
141
+ accountId: string;
142
+ absent: boolean;
143
+ }
144
+ | undefined;
145
+ if (linked.convexProjectId !== undefined) {
146
+ const connection = await credential(ctx, userId, "convex");
147
+ const retry = resume("convex", connection.accountId);
148
+ let absent = false;
149
+ try {
150
+ const project = await management<{
151
+ id: number;
152
+ name: string;
153
+ teamId: number;
154
+ }>(connection.token, `/projects/${linked.convexProjectId}`);
155
+ if (
156
+ project.id !== linked.convexProjectId ||
157
+ String(project.teamId) !== connection.accountId ||
158
+ project.name !== `disposabl-${appId}`
159
+ )
160
+ throw new ConvexError(
161
+ "The Convex project does not match this app and connected team.",
162
+ );
163
+ } catch (error) {
164
+ if (
165
+ !retry ||
166
+ !(error instanceof ManagementError) ||
167
+ error.status !== 404
168
+ )
169
+ throw error;
170
+ await management(
171
+ connection.token,
172
+ `/teams/${connection.accountId}/projects?limit=1`,
173
+ );
174
+ absent = true;
175
+ }
176
+ convex = {
177
+ token: connection.token,
178
+ projectId: linked.convexProjectId,
179
+ accountId: connection.accountId,
180
+ absent,
181
+ };
182
+ }
183
+ if (linked.expoAccountId === undefined && linked.githubRepo) {
184
+ const app = await ctx.runQuery(internal.apps.internal.get, identity);
185
+ if (
186
+ app.platforms.some(
187
+ (platform) => platform === "android" || platform === "ios",
188
+ )
189
+ )
190
+ throw new ConvexError(
191
+ "This older app has no recorded Expo ownership. Link its original Expo project before deleting it.",
192
+ );
193
+ }
194
+ let expo:
195
+ | {
196
+ token: string;
197
+ projectId?: string;
198
+ accountId: string;
199
+ receipt?: string;
200
+ }
201
+ | undefined;
202
+ if (linked.expoAccountId || linked.expoProjectId) {
203
+ const connection = await credential(ctx, userId, "expo");
204
+ const retry = resume("expo", connection.accountId);
205
+ if (
206
+ linked.expoAccountId !== connection.accountId ||
207
+ !(await validateExpo(connection.token)).some(
208
+ (account) => account.id === connection.accountId,
209
+ )
210
+ )
211
+ throw new ConvexError(
212
+ "Reconnect the Expo account that owns this app.",
213
+ );
214
+ const project = await findExpo(
215
+ connection.token,
216
+ `@${connection.name}/app-${appId}`,
217
+ linked.expoProjectId,
218
+ );
219
+ if (project) verifyExpo(project, connection.accountId, appId);
220
+ if (!project && linked.expoProjectId && !retry)
221
+ throw new ConvexError(
222
+ "The linked Expo project is unavailable. Reconnect its owner before deleting this app.",
223
+ );
224
+ expo = {
225
+ token: connection.token,
226
+ projectId: project?.id,
227
+ accountId: connection.accountId,
228
+ receipt: retry?.receipt,
229
+ };
230
+ }
231
+ started = true;
232
+ if (expo) {
233
+ // Resume the receipt even if Expo has already removed the project from lookup.
234
+ if (expo.projectId || expo.receipt) {
235
+ await deleting("expo", expo.accountId, expo.receipt);
236
+ try {
237
+ await deleteExpo(
238
+ expo.token,
239
+ expo.projectId ?? linked.expoProjectId!,
240
+ expo.receipt,
241
+ async (receipt) => {
242
+ await deleting("expo", expo.accountId, receipt);
243
+ },
244
+ );
245
+ } catch (error) {
246
+ if (error instanceof ExpoLoginRequired)
247
+ throw new ConvexError({
248
+ code: "expo_delete_requires_login",
249
+ projectId: expo.projectId ?? linked.expoProjectId!,
250
+ message:
251
+ "Expo requires a signed-in user and password confirmation to delete projects. Complete Expo deletion, then retry this command.",
252
+ });
253
+ throw error;
254
+ }
255
+ }
256
+ await forget("expo");
257
+ }
258
+ if (github) {
259
+ await deleting("github", github.accountId);
260
+ if (!github.absent)
261
+ await githubRequest(github.token, github.path, undefined, "DELETE");
262
+ await forget("github");
263
+ }
264
+ if (convex) {
265
+ await deleting("convex", convex.accountId);
266
+ if (!convex.absent)
267
+ await management(
268
+ convex.token,
269
+ `/projects/${convex.projectId}/delete`,
270
+ {},
271
+ );
272
+ await forget("convex");
273
+ }
274
+ while (
275
+ !(await ctx.runMutation(internal.apps.operations.internal.erase, {
276
+ ...identity,
277
+ until,
278
+ }))
279
+ ) {
280
+ /* Delete previews in bounded batches. */
281
+ }
282
+ return null;
283
+ } catch (error) {
284
+ await ctx.runMutation(internal.apps.operations.internal.finish, {
285
+ ...identity,
286
+ until,
287
+ retryDelete: started || resuming,
288
+ });
289
+ if (error instanceof ConvexError) throw error;
290
+ throw new ConvexError(
291
+ "App deletion could not finish. Check your connected accounts, then retry apps delete with --dangerously-delete-app. The app record has been kept.",
292
+ );
293
+ }
294
+ },
295
+ });
@@ -0,0 +1,15 @@
1
+ import {
2
+ identityFields,
3
+ internalAction,
4
+ } from "@disposabl/disposabl-kit/server/lib/functions";
5
+ import { v } from "convex/values";
6
+ import { internal } from "../../_generated/api";
7
+ import { deleteArgs } from "../validator";
8
+
9
+ export const remove = internalAction({
10
+ platforms: true,
11
+ args: { ...identityFields, ...deleteArgs },
12
+ returns: v.null(),
13
+ handler: async (ctx, args): Promise<null> =>
14
+ ctx.runAction(internal.apps.actions.cleanup.remove, args),
15
+ });
@@ -0,0 +1,174 @@
1
+ "use node";
2
+
3
+ import { ConvexError } from "convex/values";
4
+
5
+ type Project = {
6
+ id: string;
7
+ slug: string;
8
+ ownerAccount: { id: string; name: string };
9
+ };
10
+ type Receipt = { id: string; state: string; willRetry: boolean };
11
+ const fields = "id slug ownerAccount { id name }";
12
+ export async function expoRequest<T>(
13
+ token: string,
14
+ query: string,
15
+ variables: Record<string, unknown>,
16
+ ): Promise<T> {
17
+ const response = await fetch("https://api.expo.dev/graphql", {
18
+ method: "POST",
19
+ redirect: "error",
20
+ signal: AbortSignal.timeout(30_000),
21
+ headers: {
22
+ Authorization: `Bearer ${token}`,
23
+ "Content-Type": "application/json",
24
+ },
25
+ body: JSON.stringify({ query, variables }),
26
+ });
27
+ if (!response.ok)
28
+ throw new ConvexError(`Expo request failed (${response.status}).`);
29
+ const result = (await response.json()) as {
30
+ data?: T;
31
+ errors?: { message?: string; extensions?: { errorCode?: string } }[];
32
+ };
33
+ if (
34
+ result.errors?.some(
35
+ (error) =>
36
+ error.extensions?.errorCode === "SUDO_MODE_REQUIRED" ||
37
+ error.message ===
38
+ "Only regular user and SSO user access to this API is supported",
39
+ )
40
+ )
41
+ throw new ExpoLoginRequired();
42
+ if (result.errors?.length) {
43
+ if (
44
+ result.errors.every(
45
+ (error) => error.extensions?.errorCode === "EXPERIENCE_NOT_FOUND",
46
+ )
47
+ )
48
+ throw new ExpoNotFound();
49
+ throw new ConvexError(
50
+ "Expo could not complete this request. Check your token and project permissions.",
51
+ );
52
+ }
53
+ if (!result.data) throw new ConvexError("Expo returned no project details.");
54
+ return result.data;
55
+ }
56
+ export class ExpoLoginRequired extends Error {}
57
+ class ExpoNotFound extends Error {}
58
+ export async function findExpo(
59
+ token: string,
60
+ fullName: string,
61
+ projectId?: string,
62
+ ) {
63
+ try {
64
+ const data = projectId
65
+ ? await expoRequest<{ app: { project: Project } }>(
66
+ token,
67
+ `query($id: String!) { app { project: byId(appId: $id) { ${fields} } } }`,
68
+ { id: projectId },
69
+ )
70
+ : await expoRequest<{ app: { project: Project } }>(
71
+ token,
72
+ `query($name: String!) { app { project: byFullName(fullName: $name) { ${fields} } } }`,
73
+ { name: fullName },
74
+ );
75
+ if (!data.app.project)
76
+ throw new ConvexError("Expo returned no project details.");
77
+ return data.app.project;
78
+ } catch (error) {
79
+ if (error instanceof ExpoNotFound) return null;
80
+ throw error;
81
+ }
82
+ }
83
+ export function verifyExpo(project: Project, accountId: string, appId: string) {
84
+ if (project.ownerAccount.id !== accountId || project.slug !== `app-${appId}`)
85
+ throw new ConvexError(
86
+ "Reconnect the Expo account that owns this app. The linked project must match this app's UUID.",
87
+ );
88
+ }
89
+ export async function ensureExpo(
90
+ token: string,
91
+ accountId: string,
92
+ owner: string,
93
+ appId: string,
94
+ saved?: string,
95
+ ) {
96
+ const fullName = `@${owner}/app-${appId}`;
97
+ let project = await findExpo(token, fullName, saved);
98
+ if (!project) {
99
+ if (saved)
100
+ throw new ConvexError(
101
+ "The linked Expo project is unavailable. Reconnect its owner before continuing.",
102
+ );
103
+ try {
104
+ const created = await expoRequest<{ app: { createApp: { id: string } } }>(
105
+ token,
106
+ "mutation($input: AppInput!) { app { createApp(appInput: $input) { id } } }",
107
+ { input: { accountId, projectName: `app-${appId}` } },
108
+ );
109
+ project = await findExpo(token, fullName, created.app.createApp.id);
110
+ } catch (error) {
111
+ project = await findExpo(token, fullName);
112
+ if (!project) throw error;
113
+ }
114
+ }
115
+ if (!project)
116
+ throw new ConvexError("Expo project creation is incomplete. Retry setup.");
117
+ verifyExpo(project, accountId, appId);
118
+ return project;
119
+ }
120
+ export async function deleteExpo(
121
+ token: string,
122
+ projectId: string,
123
+ savedReceipt: string | undefined,
124
+ saveReceipt: (id: string) => Promise<void>,
125
+ ) {
126
+ let receipt: Receipt;
127
+ if (savedReceipt) {
128
+ const data = await expoRequest<{
129
+ backgroundJobReceipt: { byId: Receipt | null };
130
+ }>(
131
+ token,
132
+ "query($id: ID!) { backgroundJobReceipt { byId(id: $id) { id state willRetry } } }",
133
+ { id: savedReceipt },
134
+ );
135
+ if (!data.backgroundJobReceipt.byId)
136
+ throw new ConvexError(
137
+ "Expo deletion receipt is unavailable. Reconnect the owning account.",
138
+ );
139
+ receipt = data.backgroundJobReceipt.byId;
140
+ } else {
141
+ receipt = (
142
+ await expoRequest<{ app: { scheduleAppDeletion: Receipt } }>(
143
+ token,
144
+ "mutation($id: ID!) { app { scheduleAppDeletion(appId: $id) { id state willRetry } } }",
145
+ { id: projectId },
146
+ )
147
+ ).app.scheduleAppDeletion;
148
+ await saveReceipt(receipt.id);
149
+ }
150
+ const deadline = Date.now() + 90_000;
151
+ while (receipt.state !== "SUCCESS") {
152
+ if (receipt.state === "FAILURE" && !receipt.willRetry)
153
+ throw new ConvexError(
154
+ "Expo project deletion failed. Check your Expo account and retry apps delete.",
155
+ );
156
+ if (Date.now() >= deadline)
157
+ throw new ConvexError(
158
+ "Expo is still deleting the project. Retry apps delete to finish cleanup.",
159
+ );
160
+ await new Promise((resolve) => setTimeout(resolve, 1500));
161
+ const data = await expoRequest<{
162
+ backgroundJobReceipt: { byId: Receipt | null };
163
+ }>(
164
+ token,
165
+ "query($id: ID!) { backgroundJobReceipt { byId(id: $id) { id state willRetry } } }",
166
+ { id: receipt.id },
167
+ );
168
+ if (!data.backgroundJobReceipt.byId)
169
+ throw new ConvexError(
170
+ "Expo deletion could not be confirmed. Retry apps delete.",
171
+ );
172
+ receipt = data.backgroundJobReceipt.byId;
173
+ }
174
+ }