@disposabl/cli 0.0.0-stage → 1.0.1

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 (3) hide show
  1. package/README.md +41 -2
  2. package/dist/index.js +1035 -0
  3. package/package.json +42 -4
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # Disposabl CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The CLI connects to `https://www.disposabl.dev`.
4
+
5
+ Install it with `bun add --dev @disposabl/cli@latest`, or run `bunx @disposabl/cli@latest`. New generated apps include `@disposabl/cli: "latest"` in root devDependencies. A lockfile keeps the installed version stable; use `bun update @disposabl/cli --latest` to refresh it.
6
+
7
+ ```sh
8
+ disposabl login status
9
+ disposabl login
10
+ disposabl apps create --name my-app --platforms '["web","android","api","mcp","cli","typescript-sdk"]'
11
+ disposabl apps list --paginationOpts '{"numItems":20,"cursor":null}'
12
+ disposabl apps get --appId <uuid>
13
+ disposabl previews token create --configure .
14
+ disposabl previews get
15
+ disposabl agent getMessages
16
+ disposabl agent sendMessage --prompt "Build a meal planner remotely"
17
+ disposabl agent sendMessage --appId <uuid> --prompt "Try two preview variants"
18
+ disposabl agent getMessages --appId <uuid>
19
+ disposabl agent abortMessage --appId <uuid>
20
+ disposabl apps delete --appId <uuid> --dangerously-delete-app
21
+ disposabl logout
22
+ ```
23
+
24
+ Save the returned app UUID as `appId` in `disposabl.json`. Preview commands read it automatically. Both preview commands detect the current Git branch, or the worktree name when detached. Use `--reference` only to select a different preview. Token creation reuses that preview and issues a fresh development key. `--configure .` writes ignored local environment files without printing the key.
25
+
26
+ `login status` returns `currentUser`. `login --no-browser` prints the OAuth URL. The CLI owns PKCE, the loopback callback, refresh, and logout. The generator only invokes these commands.
27
+
28
+ Credentials live under `~/.config/disposabl` with restricted file permissions. `DISPOSABL_CONFIG_DIR` changes the local credential directory. `DISPOSABL_API_KEY` provides an automation credential. The service origin has no public override.
29
+
30
+ Use `--json` for machine-readable preview output. Other commands return JSON; `--help` lists their arguments.
31
+
32
+ App deletion runs in the Convex action using connected provider credentials. Apps with production releases cannot be deleted. The CLI never launches EAS or asks for an Expo password.
33
+
34
+ When Expo rejects token-based deletion, the action records that Expo cleanup is pending and continues deleting GitHub and Convex. Once both are removed, it returns `expo_manual_delete_required` with the app ID, Expo project ID, and exact `projectUrl` ending in `/settings/advanced`. The CLI opens that URL in the browser and prints it. Sign in directly to Expo if needed, then use Delete project. Pass `--no-browser` to print the link without opening it.
35
+
36
+ The command exits unsuccessfully while manual cleanup is pending. Rerun the same Disposabl deletion command after deleting the Expo project. The action verifies the connected Expo account and project removal, then deletes previews and the app record. Interrupted provider cleanup remains resumable. Keep the owning accounts connected until deletion finishes; Disposabl does not accept Expo passwords or session cookies.
37
+
38
+ ## Usage analytics
39
+
40
+ When configured for a published release, Disposabl collects the command category, outcome, package version, operating system and package-manager category. A random ID stored in `~/.config/disposabl/telemetry.json` connects anonymous usage to the Disposabl user ID after login. Logout and account changes reset that ID. Prompts, arguments, paths, error messages, credentials and email addresses are not collected. 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 a generated app's analytics.
41
+
42
+ Release builds must supply the central public PostHog project token in `DISPOSABL_CLI_POSTHOG_PROJECT_TOKEN` and its ingestion host in `DISPOSABL_CLI_POSTHOG_HOST` (US or EU PostHog ingestion origin) at build time. The build embeds these public values and rejects a release without them. Set `DISPOSABL_CLI_TELEMETRY_REQUIRED=1` to enforce the same check on a development-version qualification build. Development builds without this configuration remain inert. Do not use a personal API key or an app owner's project token. Configure the central PostHog project to disable IP data capture.
package/dist/index.js ADDED
@@ -0,0 +1,1035 @@
1
+ #!/usr/bin/env node
2
+
3
+ // auth.ts
4
+ import { lock } from "proper-lockfile";
5
+ // package.json
6
+ var version = "1.0.1";
7
+ var package_default = {
8
+ name: "@disposabl/cli",
9
+ version,
10
+ type: "module",
11
+ description: "Command-line access to your Disposabl app",
12
+ license: "MIT",
13
+ bin: {
14
+ disposabl: "dist/index.js"
15
+ },
16
+ files: [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ engines: {
21
+ node: ">=22.12.0"
22
+ },
23
+ publishConfig: {
24
+ access: "public"
25
+ },
26
+ scripts: {
27
+ build: "bun build.ts",
28
+ typecheck: "bun check",
29
+ lint: "bun check",
30
+ release: "semantic-release"
31
+ },
32
+ dependencies: {
33
+ "@modelcontextprotocol/sdk": "1.32.2",
34
+ commander: "15.0.0",
35
+ "proper-lockfile": "4.1.2"
36
+ },
37
+ devDependencies: {
38
+ "@types/bun": "1.4.4",
39
+ typescript: "~6.0.3",
40
+ "@types/proper-lockfile": "4.1.4",
41
+ "semantic-release": "25.0.9",
42
+ "@semantic-release/exec": "7.1.0",
43
+ "conventional-changelog-conventionalcommits": "9.3.1"
44
+ },
45
+ repository: {
46
+ type: "git",
47
+ url: "git+https://github.com/disposabl-dev/create-disposabl-app.git",
48
+ directory: "packages/cli"
49
+ }
50
+ };
51
+
52
+ // auth.ts
53
+ import {
54
+ auth
55
+ } from "@modelcontextprotocol/sdk/client/auth.js";
56
+ import { createServer } from "node:http";
57
+ import { randomBytes, createHash } from "node:crypto";
58
+ import {
59
+ mkdir,
60
+ readFile,
61
+ writeFile,
62
+ rename,
63
+ rm,
64
+ chmod
65
+ } from "node:fs/promises";
66
+ import { homedir } from "node:os";
67
+ import { join } from "node:path";
68
+ import { spawn } from "node:child_process";
69
+
70
+ // origin.ts
71
+ var SERVICE_ORIGIN = "https://www.disposabl.dev";
72
+ function apiUrl(value) {
73
+ const url = new URL(value);
74
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)))
75
+ throw new Error("Use HTTPS, or HTTP on loopback for local development.");
76
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/")
77
+ throw new Error("Use the API origin without a path or credentials.");
78
+ return url.origin;
79
+ }
80
+
81
+ // auth.ts
82
+ function openUrl(url) {
83
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
84
+ const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
85
+ const child = spawn(command, args, { stdio: "ignore" });
86
+ child.on("error", () => console.error("Open the URL manually."));
87
+ child.unref();
88
+ }
89
+
90
+ class NotAuthenticated extends Error {
91
+ }
92
+ var directory = () => process.env.DISPOSABL_CONFIG_DIR || join(homedir(), ".config", "disposabl");
93
+ var sessionPath = (url) => join(directory(), `${createHash("sha256").update(url).digest("hex")}.json`);
94
+ var fetchFor = (origin) => Object.assign(async (input, init) => {
95
+ const url = new URL(input instanceof Request ? input.url : input);
96
+ if (url.origin !== origin)
97
+ throw new Error("OAuth endpoint must belong to the configured API origin.");
98
+ return fetch(input, {
99
+ ...init,
100
+ redirect: "error",
101
+ signal: init?.signal ?? AbortSignal.timeout(30000)
102
+ });
103
+ }, {
104
+ preconnect: fetch.preconnect
105
+ });
106
+ async function load(url) {
107
+ try {
108
+ return JSON.parse(await readFile(sessionPath(url), "utf8"));
109
+ } catch (error) {
110
+ if (error.code === "ENOENT")
111
+ return {};
112
+ throw error;
113
+ }
114
+ }
115
+ async function credentialRevision() {
116
+ const session = await load("https://www.disposabl.dev");
117
+ return createHash("sha256").update(session.tokens?.access_token ?? "anonymous").digest("hex");
118
+ }
119
+ async function save(url, session) {
120
+ await mkdir(directory(), { recursive: true, mode: 448 });
121
+ await chmod(directory(), 448);
122
+ const temporary = `${sessionPath(url)}.${randomBytes(8).toString("hex")}`;
123
+ try {
124
+ await writeFile(temporary, JSON.stringify(session), {
125
+ mode: 384,
126
+ flag: "wx"
127
+ });
128
+ await rename(temporary, sessionPath(url));
129
+ } finally {
130
+ await rm(temporary, { force: true });
131
+ }
132
+ }
133
+ function provider(url, session, redirect, state) {
134
+ let verifier = "";
135
+ return {
136
+ redirectUrl: session.redirectUrl,
137
+ clientMetadata: {
138
+ client_name: `${Object.keys(package_default.bin)[0]} CLI`,
139
+ redirect_uris: session.redirectUrl ? [session.redirectUrl] : [],
140
+ grant_types: ["authorization_code", "refresh_token"],
141
+ response_types: ["code"],
142
+ token_endpoint_auth_method: "none"
143
+ },
144
+ state: () => state ?? "",
145
+ clientInformation: () => session.client,
146
+ saveClientInformation: (client) => {
147
+ session.client = client;
148
+ },
149
+ tokens: () => session.tokens,
150
+ saveTokens: async (tokens) => {
151
+ session.tokens = tokens;
152
+ session.expiresAt = tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : 0;
153
+ await save(url, session);
154
+ },
155
+ saveCodeVerifier: (value) => {
156
+ verifier = value;
157
+ },
158
+ codeVerifier: () => verifier,
159
+ redirectToAuthorization: redirect,
160
+ invalidateCredentials: async (scope) => {
161
+ if (scope === "all" || scope === "tokens") {
162
+ delete session.tokens;
163
+ delete session.expiresAt;
164
+ }
165
+ if (scope === "all" || scope === "client")
166
+ delete session.client;
167
+ if (scope === "all" || scope === "verifier")
168
+ verifier = "";
169
+ await save(url, session);
170
+ }
171
+ };
172
+ }
173
+ async function unlockedLogin(url, openBrowser = true) {
174
+ const state = randomBytes(32).toString("base64url");
175
+ const server = createServer();
176
+ await new Promise((resolve, reject) => {
177
+ server.once("error", reject);
178
+ server.listen(0, "127.0.0.1", resolve);
179
+ });
180
+ const address = server.address();
181
+ if (!address || typeof address === "string")
182
+ throw new Error("Could not bind the login callback.");
183
+ const session = {
184
+ redirectUrl: `http://127.0.0.1:${address.port}/callback`
185
+ };
186
+ const oauth = provider(url, session, (authorizationUrl) => {
187
+ if (authorizationUrl.origin !== url)
188
+ throw new Error("Unexpected authorization server.");
189
+ console.error(`Open this URL to sign in:
190
+ ${authorizationUrl.href}`);
191
+ if (openBrowser)
192
+ openUrl(authorizationUrl.href);
193
+ }, state);
194
+ let timer;
195
+ try {
196
+ const callback = new Promise((resolve, reject) => {
197
+ timer = setTimeout(() => reject(new Error("Login timed out. Start login again.")), 300000);
198
+ server.on("request", async (request, response) => {
199
+ const callbackUrl = new URL(request.url ?? "/", session.redirectUrl);
200
+ const invalid = request.method !== "GET" || request.headers.host !== `127.0.0.1:${address.port}` || callbackUrl.pathname !== "/callback" || callbackUrl.searchParams.getAll("state").length !== 1 || callbackUrl.searchParams.get("state") !== state;
201
+ if (invalid) {
202
+ response.writeHead(400).end("Invalid login callback.");
203
+ return;
204
+ }
205
+ try {
206
+ if (callbackUrl.searchParams.get("iss")?.replace(/\/$/, "") !== url)
207
+ throw new Error("Unexpected OAuth issuer.");
208
+ const code = callbackUrl.searchParams.get("code");
209
+ if (!code || callbackUrl.searchParams.getAll("code").length !== 1 || callbackUrl.searchParams.has("error"))
210
+ throw new Error("Login was not approved.");
211
+ const result = await auth(oauth, {
212
+ serverUrl: `${url}/mcp`,
213
+ authorizationCode: code,
214
+ fetchFn: fetchFor(url)
215
+ });
216
+ if (result !== "AUTHORIZED")
217
+ throw new Error("Login did not complete.");
218
+ response.writeHead(200, {
219
+ "Content-Type": "text/plain",
220
+ "Cache-Control": "no-store"
221
+ }).end("Signed in. You can close this tab.");
222
+ resolve();
223
+ } catch (error) {
224
+ response.writeHead(400).end("Login failed. Return to your terminal.");
225
+ reject(error);
226
+ }
227
+ });
228
+ });
229
+ callback.catch(() => {});
230
+ await auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
231
+ await callback;
232
+ } finally {
233
+ clearTimeout(timer);
234
+ server.closeAllConnections();
235
+ server.close();
236
+ }
237
+ }
238
+ async function unlockedAccessToken(url, forceRefresh = false) {
239
+ if (process.env.DISPOSABL_API_KEY)
240
+ return process.env.DISPOSABL_API_KEY;
241
+ const session = await load(url);
242
+ if (!session.tokens)
243
+ throw new NotAuthenticated("Run login first, or set DISPOSABL_API_KEY.");
244
+ if (forceRefresh || !session.expiresAt || Date.now() >= session.expiresAt - 30000) {
245
+ if (!session.client || !session.tokens.refresh_token)
246
+ throw new NotAuthenticated("Session cannot be renewed. Sign in again or start a newly authorized agent run.");
247
+ const oauth = provider(url, session, () => {
248
+ throw new NotAuthenticated("Session expired. Run login again.");
249
+ });
250
+ await auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
251
+ }
252
+ if (!session.tokens)
253
+ throw new NotAuthenticated("Session expired. Run login again.");
254
+ return session.tokens.access_token;
255
+ }
256
+ async function unlockedLogout(url) {
257
+ const session = await load(url);
258
+ if (session.tokens) {
259
+ for (const token of [
260
+ session.tokens.refresh_token,
261
+ session.tokens.access_token
262
+ ].filter(Boolean)) {
263
+ const response = await fetchFor(url)(`${url}/mcp/oauth/revoke`, {
264
+ method: "POST",
265
+ body: new URLSearchParams({
266
+ token,
267
+ client_id: session.client?.client_id ?? ""
268
+ })
269
+ });
270
+ if (!response.ok)
271
+ throw new Error("Revocation failed; credentials retained so logout can be retried.");
272
+ }
273
+ }
274
+ await rm(sessionPath(url), { force: true });
275
+ }
276
+ async function withCredentials(url, operation) {
277
+ await mkdir(directory(), { recursive: true, mode: 448 });
278
+ const release = await lock(sessionPath(url), {
279
+ realpath: false,
280
+ stale: 1e4,
281
+ retries: { retries: 8, minTimeout: 100, maxTimeout: 1000 }
282
+ });
283
+ try {
284
+ return await operation();
285
+ } finally {
286
+ await release();
287
+ }
288
+ }
289
+ function withCredentialSession(url, operation) {
290
+ return withCredentials(url, () => operation({
291
+ login: (browser) => unlockedLogin(url, browser),
292
+ logout: () => unlockedLogout(url),
293
+ hasCredentials: () => hasCredentials(url),
294
+ accessToken: (refresh) => unlockedAccessToken(url, refresh),
295
+ loginAccessToken: () => loginAccessToken(url)
296
+ }));
297
+ }
298
+ var login = (url, browser = true) => withCredentials(url, () => unlockedLogin(url, browser));
299
+ var accessToken = (url, refresh = false) => withCredentials(url, () => unlockedAccessToken(url, refresh));
300
+ var logout = (url) => withCredentials(url, () => unlockedLogout(url));
301
+ var hasCredentials = async (url) => Boolean(process.env.DISPOSABL_API_KEY || (await load(url)).tokens?.access_token);
302
+ var loginAccessToken = async (url) => (await load(url)).tokens?.access_token;
303
+
304
+ // delete.ts
305
+ function openExpoDeletion(body, appId, browser) {
306
+ if (!body || typeof body !== "object" || !("error" in body))
307
+ return;
308
+ const error = body.error;
309
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "expo_manual_delete_required")
310
+ return;
311
+ if (!("appId" in error) || error.appId !== appId || !("projectUrl" in error) || typeof error.projectUrl !== "string")
312
+ throw new Error("Invalid Expo deletion response. The app record has been kept.");
313
+ const url = new URL(error.projectUrl);
314
+ const parts = url.pathname.split("/");
315
+ if (url.origin !== "https://expo.dev" || url.username || url.password || url.search || url.hash || parts.length !== 7 || parts[1] !== "accounts" || !parts[2] || parts[3] !== "projects" || parts[4] !== `app-${appId}` || parts[5] !== "settings" || parts[6] !== "advanced")
316
+ throw new Error("Invalid Expo project URL. The app record has been kept.");
317
+ console.error(`GitHub and Convex cleanup is complete. Finish deleting the Expo project here:
318
+ ${url.href}
319
+ Sign in to Expo if needed and choose Delete project. Then rerun this command to verify cleanup. The Disposabl app record is still pending deletion.`);
320
+ if (browser)
321
+ openUrl(url.href);
322
+ }
323
+
324
+ // telemetry.ts
325
+ import { createHash as createHash2, randomUUID } from "node:crypto";
326
+ import { realpathSync } from "node:fs";
327
+ import { mkdir as mkdir2, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
328
+ import { homedir as homedir2 } from "node:os";
329
+ import { dirname, join as join2 } from "node:path";
330
+ import { lock as lock2 } from "proper-lockfile";
331
+ function installedRelease(version, entry = process.argv[1] ?? "") {
332
+ try {
333
+ entry = realpathSync(entry);
334
+ } catch {}
335
+ return /(?:^|[\\/])node_modules[\\/]/.test(entry) && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) && !version.includes("development");
336
+ }
337
+ function telemetryConfig(version, entry = process.argv[1] ?? "") {
338
+ const env = process.env;
339
+ const host = "https://us.i.posthog.com";
340
+ const token = "phc_AkMtHdssxpHojfRGD985EUbxkX2GuMSxKiULHaTT9TgM";
341
+ 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 ?? ""))
342
+ return null;
343
+ return { token, host };
344
+ }
345
+ var directory2 = () => join2(homedir2(), ".config", "disposabl");
346
+ var telemetryStatePath = () => join2(directory2(), "telemetry.json");
347
+ async function state(path) {
348
+ const revision = await credentialRevision();
349
+ try {
350
+ const value = JSON.parse(await readFile2(path, "utf8"));
351
+ if (/^[0-9a-f-]{36}$/.test(value.anonymousId) && (!value.userId || /^[a-zA-Z0-9_-]{1,128}$/.test(value.userId)) && value.credentialRevision === revision)
352
+ return value;
353
+ } catch (error) {
354
+ if (!(error instanceof SyntaxError) && error.code !== "ENOENT")
355
+ throw error;
356
+ }
357
+ await mkdir2(join2(path, ".."), { recursive: true, mode: 448 });
358
+ const fresh = {
359
+ anonymousId: randomUUID(),
360
+ credentialRevision: revision
361
+ };
362
+ await writeFile2(path, JSON.stringify(fresh), { mode: 384 });
363
+ return fresh;
364
+ }
365
+ async function synchronized(path, run) {
366
+ await mkdir2(dirname(path), { recursive: true, mode: 448 });
367
+ const release = await lock2(path, {
368
+ realpath: false,
369
+ stale: 5000,
370
+ retries: { retries: 20, minTimeout: 50, maxTimeout: 50 }
371
+ });
372
+ try {
373
+ return await run();
374
+ } finally {
375
+ await release();
376
+ }
377
+ }
378
+ async function send(config, event, distinctId, properties) {
379
+ const response = await fetch(`${config.host}/i/v0/e/`, {
380
+ method: "POST",
381
+ redirect: "error",
382
+ signal: AbortSignal.timeout(500),
383
+ headers: { "Content-Type": "application/json" },
384
+ body: JSON.stringify({
385
+ api_key: config.token,
386
+ event,
387
+ distinct_id: distinctId,
388
+ properties: { ...properties, $geoip_disable: true, $ip: "0.0.0.0" }
389
+ })
390
+ });
391
+ return response.ok;
392
+ }
393
+ async function capture(version, product, command, outcome, path) {
394
+ const config = telemetryConfig(version);
395
+ if (!config)
396
+ return;
397
+ try {
398
+ const current = await synchronized(path, () => state(path));
399
+ if (current.credentialRevision !== await credentialRevision())
400
+ return;
401
+ const allowed = [
402
+ "agent",
403
+ "login",
404
+ "logout",
405
+ "apps",
406
+ "previews",
407
+ "connections",
408
+ "users",
409
+ "help",
410
+ "version",
411
+ "other",
412
+ "create"
413
+ ];
414
+ await send(config, "cli_command", current.userId ?? current.anonymousId, {
415
+ product,
416
+ command: allowed.includes(command) ? command : "other",
417
+ outcome,
418
+ version,
419
+ invocation: process.env.npm_command === "exec" ? "npx" : /^(npm|pnpm|yarn|bun)\//.exec(process.env.npm_config_user_agent ?? "")?.[1] ?? "direct",
420
+ platform: ["darwin", "linux", "win32"].includes(process.platform) ? process.platform : "other",
421
+ ...!current.userId ? { $process_person_profile: false } : {}
422
+ });
423
+ } catch {}
424
+ }
425
+ async function prepareLogin(path) {
426
+ try {
427
+ return await synchronized(path, async () => {
428
+ const current = await state(path);
429
+ const loginAttempt = randomUUID();
430
+ const next = {
431
+ anonymousId: current.userId || current.loginAttempt || current.credentialRevision !== createHash2("sha256").update("anonymous").digest("hex") ? randomUUID() : current.anonymousId,
432
+ loginAttempt,
433
+ credentialRevision: await credentialRevision()
434
+ };
435
+ await writeFile2(path, JSON.stringify(next), { mode: 384 });
436
+ return loginAttempt;
437
+ });
438
+ } catch {
439
+ return;
440
+ }
441
+ }
442
+ async function identify(version, userId, path, attempt, revision = undefined) {
443
+ const config = telemetryConfig(version);
444
+ if (!config || !attempt || typeof userId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(userId))
445
+ return;
446
+ try {
447
+ const expectedRevision = revision ?? await credentialRevision();
448
+ await synchronized(path, async () => {
449
+ const current = JSON.parse(await readFile2(path, "utf8"));
450
+ if (current.loginAttempt !== attempt || expectedRevision !== await credentialRevision() || current.userId || !/^[0-9a-f-]{36}$/.test(current.anonymousId))
451
+ return;
452
+ const opaqueId = createHash2("sha256").update(`disposabl:${config.token}:${userId}`).digest("hex");
453
+ if (await send(config, "$identify", opaqueId, {
454
+ $anon_distinct_id: current.anonymousId
455
+ })) {
456
+ await writeFile2(path, JSON.stringify({
457
+ anonymousId: current.anonymousId,
458
+ userId: opaqueId,
459
+ credentialRevision: expectedRevision
460
+ }), { mode: 384 });
461
+ }
462
+ });
463
+ } catch {}
464
+ }
465
+ async function resetIdentity(path, attempt) {
466
+ try {
467
+ await synchronized(path, async () => {
468
+ if (attempt) {
469
+ const current = JSON.parse(await readFile2(path, "utf8"));
470
+ if (current.loginAttempt !== attempt)
471
+ return;
472
+ }
473
+ await rm2(path, { force: true });
474
+ });
475
+ } catch {}
476
+ }
477
+
478
+ // errors.ts
479
+ function apiError(status, body) {
480
+ try {
481
+ const data = JSON.parse(body)?.error;
482
+ if (data?.code === "credits_required") {
483
+ const paymentUrl = data.paymentUrl === "https://www.disposabl.dev/pricing" ? `
484
+ Add credits: ${data.paymentUrl}` : "";
485
+ 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}`;
486
+ }
487
+ if (data?.code === "credits_unavailable")
488
+ return "Credits are temporarily unavailable. Please retry.";
489
+ } catch {}
490
+ return `API request failed (${status}): ${body}`;
491
+ }
492
+
493
+ // client.ts
494
+ import { Command } from "commander";
495
+ function createProgram(serviceOrigin, centralAnalytics = false, dependencies = {}) {
496
+ const version = dependencies.version ?? package_default.version;
497
+ const path = () => dependencies.telemetryPath ?? telemetryStatePath();
498
+ const sessionLogin = dependencies.login ?? login;
499
+ const sessionLogout = dependencies.logout ?? logout;
500
+ const sessionHasCredentials = dependencies.hasCredentials ?? hasCredentials;
501
+ const sessionAccessToken = dependencies.accessToken ?? accessToken;
502
+ const sessionLoginAccessToken = dependencies.loginAccessToken ?? loginAccessToken;
503
+ const credentialSession = (url, operation) => {
504
+ if (dependencies.credentialSession)
505
+ return dependencies.credentialSession(url, operation);
506
+ if (!(dependencies.login || dependencies.logout || dependencies.hasCredentials || dependencies.accessToken || dependencies.loginAccessToken))
507
+ return withCredentialSession(url, operation);
508
+ return operation({
509
+ login: (browser) => sessionLogin(url, browser),
510
+ logout: () => sessionLogout(url),
511
+ hasCredentials: () => sessionHasCredentials(url),
512
+ accessToken: (refresh) => sessionAccessToken(url, refresh),
513
+ loginAccessToken: () => sessionLoginAccessToken(url)
514
+ });
515
+ };
516
+ const program = new Command().name(Object.keys(package_default.bin)[0]).version(package_default.version);
517
+ if (centralAnalytics)
518
+ program.addHelpText("after", `
519
+ Disposabl collects limited CLI usage when configured. Set DO_NOT_TRACK=1 to opt out.
520
+ `);
521
+ const origin = () => apiUrl(serviceOrigin);
522
+ const loginCommand = program.command("login").option("--no-browser", "Print the login URL without opening a browser").action(async (options) => {
523
+ const base = origin();
524
+ const central = centralAnalytics && base === "https://www.disposabl.dev" && installedRelease(version);
525
+ const enabled = central && telemetryConfig(version);
526
+ const { attempt, token, revision } = await credentialSession(base, async (session) => {
527
+ let attempt;
528
+ if (central) {
529
+ if (enabled)
530
+ attempt = await prepareLogin(path());
531
+ else
532
+ await resetIdentity(path());
533
+ }
534
+ await session.login(options.browser);
535
+ return {
536
+ attempt,
537
+ revision: enabled ? await credentialRevision().catch(() => {
538
+ return;
539
+ }) : undefined,
540
+ token: enabled ? await session.loginAccessToken().catch(() => {
541
+ return;
542
+ }) : undefined
543
+ };
544
+ });
545
+ if (enabled && token && revision) {
546
+ try {
547
+ const response = await fetch(`${base}/api/users/current`, {
548
+ headers: { Authorization: `Bearer ${token}` },
549
+ redirect: "error",
550
+ signal: AbortSignal.timeout(500)
551
+ });
552
+ if (response.ok)
553
+ await identify(version, (await response.json())?.id, path(), attempt, revision);
554
+ } catch {}
555
+ }
556
+ console.error("Signed in.");
557
+ });
558
+ loginCommand.command("status").description("Return the server-verified current user").action(async () => {
559
+ const base = origin();
560
+ const enabled = centralAnalytics && base === "https://www.disposabl.dev" && telemetryConfig(version);
561
+ let snapshot;
562
+ try {
563
+ snapshot = await credentialSession(base, async (session) => {
564
+ if (!await session.hasCredentials()) {
565
+ if (enabled)
566
+ await resetIdentity(path());
567
+ return;
568
+ }
569
+ const attempt = enabled ? await prepareLogin(path()) : undefined;
570
+ try {
571
+ const token = await session.accessToken();
572
+ return {
573
+ token,
574
+ attempt,
575
+ revision: enabled ? await credentialRevision().catch(() => {
576
+ return;
577
+ }) : undefined
578
+ };
579
+ } catch (error) {
580
+ if (enabled && attempt)
581
+ await resetIdentity(path(), attempt);
582
+ throw error;
583
+ }
584
+ });
585
+ } catch (error) {
586
+ if (!(error instanceof NotAuthenticated))
587
+ throw error;
588
+ console.log(JSON.stringify({ currentUser: null }));
589
+ return;
590
+ }
591
+ if (!snapshot) {
592
+ console.log(JSON.stringify({ currentUser: null }));
593
+ return;
594
+ }
595
+ const send = (token) => fetch(`${base}/api/users/current`, {
596
+ headers: {
597
+ Authorization: `Bearer ${token}`,
598
+ "X-Disposabl-Source": "cli"
599
+ },
600
+ redirect: "error",
601
+ signal: AbortSignal.timeout(30000)
602
+ });
603
+ let response = await send(snapshot.token);
604
+ if (response.status === 401 && !process.env.DISPOSABL_API_KEY) {
605
+ try {
606
+ const refreshed = await credentialSession(base, async (session) => {
607
+ if (await session.loginAccessToken() !== snapshot.token)
608
+ return;
609
+ const token = await session.accessToken(true);
610
+ return {
611
+ token,
612
+ revision: enabled ? await credentialRevision().catch(() => {
613
+ return;
614
+ }) : undefined
615
+ };
616
+ });
617
+ if (refreshed) {
618
+ snapshot.revision = refreshed.revision;
619
+ response = await send(refreshed.token);
620
+ }
621
+ } catch (error) {
622
+ if (!(error instanceof NotAuthenticated))
623
+ throw error;
624
+ }
625
+ }
626
+ if (response.status === 401) {
627
+ if (enabled && snapshot.attempt)
628
+ await resetIdentity(path(), snapshot.attempt);
629
+ console.log(JSON.stringify({ currentUser: null }));
630
+ return;
631
+ }
632
+ if (!response.ok)
633
+ throw new Error(`Login status failed (${response.status}).`);
634
+ const currentUser = await response.json();
635
+ if (enabled && snapshot.revision)
636
+ await identify(version, currentUser?.id, path(), snapshot.attempt, snapshot.revision);
637
+ console.log(JSON.stringify({ currentUser }));
638
+ });
639
+ program.command("logout").action(async () => {
640
+ const base = origin();
641
+ await credentialSession(base, async (session) => {
642
+ await session.logout();
643
+ if (centralAnalytics && base === "https://www.disposabl.dev" && installedRelease(version))
644
+ await resetIdentity(path());
645
+ });
646
+ console.error("Signed out.");
647
+ });
648
+ return program;
649
+ }
650
+ async function loadContract(base) {
651
+ const response = await fetch(`${base}/openapi.json`, {
652
+ redirect: "error",
653
+ signal: AbortSignal.timeout(30000)
654
+ });
655
+ if (!response.ok)
656
+ throw new Error(`Could not load OpenAPI (${response.status}).`);
657
+ return await response.json();
658
+ }
659
+ function operationFields(method, operation) {
660
+ const schema = operation.requestBody?.content["application/json"].schema;
661
+ return method === "get" ? (operation.parameters ?? []).map((p) => ({
662
+ name: p.name,
663
+ required: p.required,
664
+ schema: p.content["application/json"].schema
665
+ })) : Object.entries(schema?.properties ?? {}).map(([name, value]) => ({
666
+ name,
667
+ required: schema?.required?.includes(name),
668
+ schema: value
669
+ }));
670
+ }
671
+ function addOperation(program, path) {
672
+ if (!path.startsWith("/api/") || path.includes("?") || path.includes("#"))
673
+ throw new Error("Invalid API path in contract.");
674
+ const parts = path.slice(5).split("/");
675
+ let parent = program;
676
+ for (const part of parts.slice(0, -1))
677
+ parent = parent.commands.find((command) => command.name() === part) ?? parent.command(part);
678
+ return parent.command(parts.at(-1));
679
+ }
680
+ function requestOperation(base, path, method, input, timeout = 30000) {
681
+ const target = new URL(path, base);
682
+ if (target.origin !== base || !target.pathname.startsWith("/api/"))
683
+ throw new Error("Invalid operation URL.");
684
+ if (method === "get")
685
+ for (const [name, value] of Object.entries(input))
686
+ target.searchParams.set(name, JSON.stringify(value));
687
+ const send = async (refresh = false) => fetch(target, {
688
+ method: method.toUpperCase(),
689
+ redirect: "error",
690
+ signal: AbortSignal.timeout(timeout),
691
+ headers: {
692
+ Authorization: `Bearer ${await accessToken(base, refresh)}`,
693
+ "Content-Type": "application/json",
694
+ "X-Disposabl-Source": "cli"
695
+ },
696
+ body: method === "post" ? JSON.stringify(input) : undefined
697
+ });
698
+ return async () => {
699
+ const response = await send();
700
+ return response.status === 401 && !process.env.DISPOSABL_API_KEY ? send(true) : response;
701
+ };
702
+ }
703
+ function needsContract(program, argv, origin) {
704
+ const args = argv.slice(2);
705
+ const { operands } = program.parseOptions(args);
706
+ const command = operands[0] === "help" ? operands[1] : operands[0];
707
+ return Boolean(origin) && !args.some((arg) => arg === "--version" || arg === "-V") && command !== "login" && command !== "logout";
708
+ }
709
+
710
+ // commands.ts
711
+ import { readFile as readFile4 } from "node:fs/promises";
712
+ import { join as join5 } from "node:path";
713
+
714
+ // repository.ts
715
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
716
+ import { mkdir as mkdir3, chmod as chmod2, writeFile as writeFile3, rename as rename2, rm as rm3 } from "node:fs/promises";
717
+ import { homedir as homedir3 } from "node:os";
718
+ import { join as join3 } from "node:path";
719
+ async function configureRepository(origin, appId, value) {
720
+ if (!value.token || !/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(value.repository))
721
+ throw new Error("Invalid repository credential response.");
722
+ const directory = process.env.DISPOSABL_CONFIG_DIR || join3(homedir3(), ".config", "disposabl");
723
+ const key = createHash3("sha256").update(JSON.stringify([origin, appId])).digest("hex");
724
+ const credentialFile = join3(directory, `repository-${key}.json`);
725
+ const temporary = `${credentialFile}.${randomUUID2()}`;
726
+ await mkdir3(directory, { recursive: true, mode: 448 });
727
+ await chmod2(directory, 448);
728
+ try {
729
+ await writeFile3(temporary, JSON.stringify(value), {
730
+ mode: 384,
731
+ flag: "wx"
732
+ });
733
+ await rename2(temporary, credentialFile);
734
+ } finally {
735
+ await rm3(temporary, { force: true });
736
+ }
737
+ return { repository: value.repository, credentialFile };
738
+ }
739
+
740
+ // preview.ts
741
+ import {
742
+ chmod as chmod3,
743
+ lstat,
744
+ readFile as readFile3,
745
+ rename as rename3,
746
+ writeFile as writeFile4,
747
+ rm as rm4
748
+ } from "node:fs/promises";
749
+ import { basename, join as join4, resolve } from "node:path";
750
+ import { randomUUID as randomUUID3 } from "node:crypto";
751
+ import { spawnSync } from "node:child_process";
752
+ function detectReference(directory = process.cwd()) {
753
+ const git = (...args) => spawnSync("git", args, { cwd: directory, encoding: "utf8" }).stdout?.trim();
754
+ const branch = git("symbolic-ref", "--quiet", "--short", "HEAD");
755
+ if (branch)
756
+ return branch;
757
+ const root = git("rev-parse", "--show-toplevel");
758
+ const common = git("rev-parse", "--path-format=absolute", "--git-common-dir");
759
+ const local = git("rev-parse", "--absolute-git-dir");
760
+ if (root && common && local && common !== local)
761
+ return basename(root);
762
+ throw new Error("Cannot detect a branch or worktree. Run inside the app's Git checkout or supply --reference.");
763
+ }
764
+ async function updateEnv(file, values, remove = []) {
765
+ const stat = await lstat(file).catch((error) => {
766
+ if (error.code !== "ENOENT")
767
+ throw error;
768
+ return;
769
+ });
770
+ if (stat && (!stat.isFile() || stat.isSymbolicLink()))
771
+ throw new Error(`Refusing to replace non-regular file ${file}.`);
772
+ const text = stat ? await readFile3(file, "utf8") : "";
773
+ const keys = new Set([...Object.keys(values), ...remove]);
774
+ const lines = text.split(`
775
+ `).filter((line) => !keys.has(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=/.exec(line)?.[1] ?? ""));
776
+ const next = lines.join(`
777
+ `).trimEnd() + `
778
+ ` + Object.entries(values).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(`
779
+ `) + `
780
+ `;
781
+ const temporary = `${file}.${randomUUID3()}.tmp`;
782
+ try {
783
+ await writeFile4(temporary, next, { flag: "wx", mode: 384 });
784
+ await rename3(temporary, file);
785
+ await chmod3(file, 384);
786
+ } finally {
787
+ await rm4(temporary, { force: true });
788
+ }
789
+ }
790
+ async function configureDevelopment(directory, value) {
791
+ const root = resolve(directory);
792
+ const config = JSON.parse(await readFile3(join4(root, "disposabl.json"), "utf8"));
793
+ if (config.appId !== value.appId || !value.deployKey.startsWith(`dev:${value.name}|`))
794
+ throw new Error("Development credentials do not match this app.");
795
+ if (!/^[a-z0-9-]+$/.test(value.name) || value.convexUrl !== `https://${value.name}.convex.cloud` || value.convexSiteUrl !== `https://${value.name}.convex.site`)
796
+ throw new Error("Development URLs do not match the deployment.");
797
+ if (value.productionConvexSiteUrl && !/^https:\/\/[a-z0-9-]+\.convex\.site$/.test(value.productionConvexSiteUrl))
798
+ throw new Error("Unexpected production Convex site URL.");
799
+ if (config.features?.includes("analytics") && !value.analytics)
800
+ throw new Error("Analytics setup is incomplete. Connect PostHog and retry app setup.");
801
+ if (value.analytics && (!Number.isSafeInteger(value.analytics.projectId) || !value.analytics.projectToken.startsWith("phc_") || !["https://us.i.posthog.com", "https://eu.i.posthog.com"].includes(value.analytics.host)))
802
+ throw new Error("Unexpected PostHog project configuration.");
803
+ if (value.repositoryUrl) {
804
+ const repository = /^https:\/\/github\.com\/([a-zA-Z0-9-]+)\/([a-zA-Z0-9_.-]+)\.git$/.exec(value.repositoryUrl);
805
+ if (!repository)
806
+ throw new Error("Unexpected GitHub repository URL.");
807
+ const remote = spawnSync("git", ["remote", "get-url", "origin"], {
808
+ cwd: root,
809
+ encoding: "utf8"
810
+ });
811
+ if (remote.status === 0) {
812
+ const current = remote.stdout.trim();
813
+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(current);
814
+ if (!match || `${match[1]}/${match[2]}`.toLowerCase() !== `${repository[1]}/${repository[2]}`.toLowerCase())
815
+ throw new Error("Existing origin points to a different repository; it was not changed.");
816
+ } else {
817
+ const added = spawnSync("git", ["remote", "add", "origin", value.repositoryUrl], { cwd: root, encoding: "utf8" });
818
+ if (added.status !== 0)
819
+ throw new Error(`Could not add origin: ${added.stderr.trim()}`);
820
+ }
821
+ }
822
+ const files = ["packages/backend/.env.local", "apps/web/.env.local"];
823
+ if (config.platforms.some((p) => p === "android" || p === "ios"))
824
+ files.push("apps/mobile/.env.local");
825
+ for (const file of files) {
826
+ const ignored = spawnSync("git", ["check-ignore", "--quiet", file], {
827
+ cwd: root,
828
+ stdio: "ignore"
829
+ });
830
+ const tracked = spawnSync("git", ["ls-files", "--error-unmatch", file], {
831
+ cwd: root,
832
+ stdio: "ignore"
833
+ });
834
+ if (ignored.status !== 0 || tracked.status !== 1)
835
+ throw new Error(`${file} must be untracked and ignored by Git.`);
836
+ }
837
+ if (value.productionConvexSiteUrl || value.analytics || config.analytics) {
838
+ if (value.productionConvexSiteUrl)
839
+ config.productionConvexSiteUrl = value.productionConvexSiteUrl;
840
+ if (config.features?.includes("analytics"))
841
+ config.analytics = value.analytics;
842
+ else
843
+ delete config.analytics;
844
+ await writeFile4(join4(root, "disposabl.json"), JSON.stringify(config, null, 2) + `
845
+ `);
846
+ const formatted = spawnSync("bun", ["fmt", "disposabl.json"], {
847
+ cwd: root,
848
+ stdio: "pipe"
849
+ });
850
+ if (formatted.status !== 0)
851
+ throw new Error("Could not format disposabl.json after configuring development.");
852
+ }
853
+ await updateEnv(join4(root, files[0]), {
854
+ CONVEX_DEPLOY_KEY: value.deployKey,
855
+ CONVEX_URL: value.convexUrl,
856
+ CONVEX_SITE_URL: value.convexSiteUrl
857
+ }, ["CONVEX_DEPLOYMENT"]);
858
+ await updateEnv(join4(root, files[1]), {
859
+ VITE_CONVEX_URL: value.convexUrl,
860
+ VITE_CONVEX_SITE_URL: value.convexSiteUrl
861
+ });
862
+ if (files[2])
863
+ await updateEnv(join4(root, files[2]), {
864
+ EXPO_PUBLIC_CONVEX_URL: value.convexUrl,
865
+ EXPO_PUBLIC_CONVEX_SITE_URL: value.convexSiteUrl
866
+ });
867
+ }
868
+ function formatPreview(preview) {
869
+ if (!preview)
870
+ return "Preview not found. Create it with disposabl previews token create --configure .";
871
+ const lines = [
872
+ `Preview: ${preview.reference}`,
873
+ `App: ${preview.appId}`,
874
+ `Stage: ${preview.stage ?? "building"}`
875
+ ];
876
+ for (const [name, state] of Object.entries(preview.platforms)) {
877
+ if (!state.enabled) {
878
+ lines.push(`${name}: disabled`);
879
+ continue;
880
+ }
881
+ const latest = state.latest;
882
+ lines.push(`${name}: ${latest?.status ?? "not built"}${latest?.version ? ` (${latest.version})` : ["cli", "sdk"].includes(name) ? " (not published)" : ""}`);
883
+ for (const [label, url] of Object.entries({
884
+ URL: state.url,
885
+ Preview: latest?.url,
886
+ Release: latest?.githubReleaseUrl,
887
+ Download: latest?.artifactUrl,
888
+ Update: latest?.updateUrl,
889
+ "Workflow run": latest?.run?.url,
890
+ Reason: latest?.reason
891
+ }))
892
+ if (url)
893
+ lines.push(` ${label}: ${url}`);
894
+ }
895
+ return lines.join(`
896
+ `);
897
+ }
898
+
899
+ // commands.ts
900
+ async function runCli(argv = process.argv, serviceOrigin = process.env.DISPOSABL_API_ORIGIN || SERVICE_ORIGIN) {
901
+ const program = createProgram(serviceOrigin, true);
902
+ const origin = () => apiUrl(serviceOrigin);
903
+ async function main() {
904
+ if (needsContract(program, argv, serviceOrigin)) {
905
+ const base = origin();
906
+ const spec = await loadContract(base);
907
+ for (const [path, methods] of Object.entries(spec.paths)) {
908
+ for (const [method, operation] of Object.entries(methods)) {
909
+ if (!["get", "post"].includes(method))
910
+ continue;
911
+ const command = addOperation(program, path);
912
+ const connectionStatus = path === "/api/connections/status";
913
+ if (connectionStatus)
914
+ command.option("--wait", "Open setup and continue when GitHub and Convex are ready");
915
+ if (connectionStatus)
916
+ command.option("--setup-origin", "Show the terminal setup completion screen");
917
+ if (connectionStatus)
918
+ command.option("--mobile", "Also wait for Expo when creating a mobile app");
919
+ const deleteApp = path === "/api/apps/delete";
920
+ if (deleteApp)
921
+ command.option("--no-browser", "Print the Expo cleanup URL without opening a browser");
922
+ const previewGet = path === "/api/previews/get";
923
+ const tokenCreate = path === "/api/previews/token/create";
924
+ const repositoryToken = path === "/api/apps/repositoryToken";
925
+ if (repositoryToken)
926
+ command.option("--configure", "Save repository credentials privately outside the project");
927
+ if (previewGet)
928
+ command.option("--json", "Print the full preview as JSON");
929
+ if (tokenCreate)
930
+ command.option("--configure <directory>", "Write local development environment files");
931
+ const fields = operationFields(method, operation);
932
+ for (const field of fields) {
933
+ if (deleteApp && field.name === "dangerouslyDeleteApp") {
934
+ command.option("--dangerously-delete-app", "Permanently delete this preview app and its GitHub, Convex and Expo projects");
935
+ continue;
936
+ }
937
+ const flag = `--${field.name} <value>`;
938
+ if (field.required && !(field.name === "appId" && (previewGet || tokenCreate)) && !(field.name === "reference" && (previewGet || tokenCreate)))
939
+ command.requiredOption(flag, field.schema.type === "string" ? field.name : `${field.name} as JSON`);
940
+ else
941
+ command.option(flag, field.name);
942
+ }
943
+ command.action(async (options) => {
944
+ if (deleteApp && options.dangerouslyDeleteApp !== true)
945
+ throw new Error("Permanent deletion requires --dangerously-delete-app. Apps with production releases cannot be deleted.");
946
+ if ((previewGet || tokenCreate) && !options.appId) {
947
+ const config = JSON.parse(await readFile4(join5(options.configure ?? process.cwd(), "disposabl.json"), "utf8"));
948
+ if (!config.appId)
949
+ throw new Error("No appId in disposabl.json. Run setup or pass --appId.");
950
+ options.appId = config.appId;
951
+ }
952
+ if ((previewGet || tokenCreate) && !options.reference)
953
+ options.reference = detectReference(options.configure);
954
+ const input = Object.fromEntries(fields.filter((field) => options[field.name] !== undefined).map((field) => [
955
+ field.name,
956
+ field.schema.type === "string" || typeof options[field.name] === "boolean" ? options[field.name] : JSON.parse(options[field.name])
957
+ ]));
958
+ const send = requestOperation(base, path, method, input, deleteApp ? 300000 : 30000);
959
+ let result = await send();
960
+ if (deleteApp && !result.ok)
961
+ openExpoDeletion(await result.clone().json().catch(() => null), options.appId, options.browser !== false);
962
+ if (!result.ok)
963
+ throw new Error(apiError(result.status, await result.text()));
964
+ let value = await result.json();
965
+ const ready = () => value.ready && (!options.mobile || Boolean(value.expo));
966
+ if (connectionStatus && options.wait && !ready()) {
967
+ const requested = Array.isArray(input.features) ? input.features : [];
968
+ const connections = new URL("/dashboard/connections", base);
969
+ if (options.setupOrigin)
970
+ connections.searchParams.set("origin", "cli");
971
+ const requiredFeatures = requested.filter((f) => f === "analytics" || f === "payments");
972
+ if (requiredFeatures.length)
973
+ connections.searchParams.set("features", requiredFeatures.join(","));
974
+ if (options.mobile)
975
+ connections.searchParams.set("mobile", "1");
976
+ const url = connections.href;
977
+ const names = {
978
+ github: "GitHub",
979
+ convex: "Convex",
980
+ posthog: "PostHog",
981
+ expo: "Expo",
982
+ autumn: "Autumn"
983
+ };
984
+ const missing = Array.isArray(value.missing) ? value.missing.map((id) => names[id] ?? id).join(" and ") : "GitHub and Convex";
985
+ console.error(`Connect ${missing} for this app:
986
+ ${url}
987
+ Waiting for connections. Press Ctrl+C to keep your files and finish later.`);
988
+ openUrl(url);
989
+ const deadline = Date.now() + 15 * 60000;
990
+ while (!ready() && Date.now() < deadline) {
991
+ await new Promise((resolve) => setTimeout(resolve, 3000));
992
+ result = await send();
993
+ if (!result.ok)
994
+ throw new Error(`Connection status failed (${result.status}). Your login and app files are saved.`);
995
+ value = await result.json();
996
+ }
997
+ if (!ready())
998
+ throw new Error(`Connections are still incomplete. Finish at ${url}, then retry setup.`);
999
+ }
1000
+ if (repositoryToken && options.configure) {
1001
+ console.log(JSON.stringify(await configureRepository(base, options.appId, value), null, 2));
1002
+ } else if (tokenCreate && options.configure) {
1003
+ await configureDevelopment(options.configure, value);
1004
+ const { deployKey: _secret, ...details } = value;
1005
+ console.log(JSON.stringify({ ...details, configured: true }, null, 2));
1006
+ } else if (previewGet && !options.json)
1007
+ console.log(formatPreview(value));
1008
+ else
1009
+ console.log(JSON.stringify(value, null, 2));
1010
+ });
1011
+ }
1012
+ }
1013
+ }
1014
+ await program.parseAsync(argv);
1015
+ }
1016
+ const command = argv[2] ?? "help";
1017
+ const central = serviceOrigin === SERVICE_ORIGIN;
1018
+ if (central)
1019
+ await capture(version, "cli", command, "started", telemetryStatePath());
1020
+ try {
1021
+ await main();
1022
+ if (central)
1023
+ await capture(version, "cli", command, "success", telemetryStatePath());
1024
+ } catch (error) {
1025
+ if (central)
1026
+ await capture(version, "cli", command, "failure", telemetryStatePath());
1027
+ throw error;
1028
+ }
1029
+ }
1030
+
1031
+ // index.ts
1032
+ runCli().catch((error) => {
1033
+ console.error(error instanceof Error ? error.message : "Command failed.");
1034
+ process.exitCode = 1;
1035
+ });
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@disposabl/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "type": "module",
5
+ "description": "Command-line access to your Disposabl app",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "disposabl": "dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=22.12.0"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "scripts": {
21
+ "build": "bun build.ts",
22
+ "typecheck": "bun check",
23
+ "lint": "bun check",
24
+ "release": "semantic-release"
25
+ },
26
+ "dependencies": {
27
+ "@modelcontextprotocol/sdk": "1.32.2",
28
+ "commander": "15.0.0",
29
+ "proper-lockfile": "4.1.2"
30
+ },
31
+ "devDependencies": {
32
+ "@types/bun": "1.4.4",
33
+ "typescript": "~6.0.3",
34
+ "@types/proper-lockfile": "4.1.4",
35
+ "semantic-release": "25.0.9",
36
+ "@semantic-release/exec": "7.1.0",
37
+ "conventional-changelog-conventionalcommits": "9.3.1"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/disposabl-dev/create-disposabl-app.git",
42
+ "directory": "packages/cli"
43
+ }
44
+ }