@disposabl/cli 4.0.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,1234 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // auth.ts
4
- import { lock } from "proper-lockfile";
5
- // package.json
6
- var version = "4.0.0";
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
- prepack: "node dist/verify-metadata.mjs"
32
- },
33
- dependencies: {
34
- "@modelcontextprotocol/sdk": "1.32.2",
35
- commander: "15.0.0",
36
- "proper-lockfile": "4.1.2"
37
- },
38
- devDependencies: {
39
- "@types/bun": "1.4.4",
40
- typescript: "~6.0.3",
41
- "@types/proper-lockfile": "4.1.4",
42
- "semantic-release": "25.0.9",
43
- "@semantic-release/exec": "7.1.0",
44
- "conventional-changelog-conventionalcommits": "9.3.1"
45
- },
46
- repository: {
47
- type: "git",
48
- url: "git+https://github.com/disposabl-dev/create-disposabl-app.git",
49
- directory: "packages/cli"
50
- }
51
- };
52
-
53
- // auth.ts
54
- import {
55
- auth
56
- } from "@modelcontextprotocol/sdk/client/auth.js";
57
- import { createServer } from "node:http";
58
- import { randomBytes, createHash } from "node:crypto";
59
- import {
60
- mkdir,
61
- readFile,
62
- writeFile,
63
- rename,
64
- rm,
65
- chmod
66
- } from "node:fs/promises";
67
- import { homedir } from "node:os";
68
- import { join } from "node:path";
69
- import { spawn } from "node:child_process";
70
-
71
- // origin.ts
72
- var SERVICE_ORIGIN = "https://www.disposabl.dev";
73
- function apiUrl(value) {
74
- const url = new URL(value);
75
- if (url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)))
76
- throw new Error("Use HTTPS, or HTTP on loopback for local development.");
77
- if (url.username || url.password || url.search || url.hash || url.pathname !== "/")
78
- throw new Error("Use the API origin without a path or credentials.");
79
- return url.origin;
80
- }
81
-
82
- // auth.ts
83
- function openUrl(url) {
84
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
85
- const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
86
- const child = spawn(command, args, { stdio: "ignore" });
87
- child.on("error", () => console.error("Open the URL manually."));
88
- child.unref();
89
- }
90
-
91
- class NotAuthenticated extends Error {
92
- }
93
- var directory = () => process.env.DISPOSABL_CONFIG_DIR || join(homedir(), ".config", "disposabl");
94
- var sessionPath = (url) => join(directory(), `${createHash("sha256").update(url).digest("hex")}.json`);
95
- var fetchFor = (origin) => Object.assign(async (input, init) => {
96
- const url = new URL(input instanceof Request ? input.url : input);
97
- if (url.origin !== origin)
98
- throw new Error("OAuth endpoint must belong to the configured API origin.");
99
- return fetch(input, {
100
- ...init,
101
- redirect: "error",
102
- signal: init?.signal ?? AbortSignal.timeout(30000)
103
- });
104
- }, {
105
- preconnect: fetch.preconnect
106
- });
107
- async function load(url) {
108
- try {
109
- return JSON.parse(await readFile(sessionPath(url), "utf8"));
110
- } catch (error) {
111
- if (error.code === "ENOENT")
112
- return {};
113
- throw error;
114
- }
115
- }
116
- async function credentialRevision() {
117
- const session = await load("https://www.disposabl.dev");
118
- return createHash("sha256").update(session.tokens?.access_token ?? "anonymous").digest("hex");
119
- }
120
- async function save(url, session) {
121
- await mkdir(directory(), { recursive: true, mode: 448 });
122
- await chmod(directory(), 448);
123
- const temporary = `${sessionPath(url)}.${randomBytes(8).toString("hex")}`;
124
- try {
125
- await writeFile(temporary, JSON.stringify(session), {
126
- mode: 384,
127
- flag: "wx"
128
- });
129
- await rename(temporary, sessionPath(url));
130
- } finally {
131
- await rm(temporary, { force: true });
132
- }
133
- }
134
- function provider(url, session, redirect, state) {
135
- let verifier = "";
136
- return {
137
- redirectUrl: session.redirectUrl,
138
- clientMetadata: {
139
- client_name: `${Object.keys(package_default.bin)[0]} CLI`,
140
- redirect_uris: session.redirectUrl ? [session.redirectUrl] : [],
141
- grant_types: ["authorization_code", "refresh_token"],
142
- response_types: ["code"],
143
- token_endpoint_auth_method: "none"
144
- },
145
- state: () => state ?? "",
146
- clientInformation: () => session.client,
147
- saveClientInformation: (client) => {
148
- session.client = client;
149
- },
150
- tokens: () => session.tokens,
151
- saveTokens: async (tokens) => {
152
- session.tokens = tokens;
153
- session.expiresAt = tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : 0;
154
- await save(url, session);
155
- },
156
- saveCodeVerifier: (value) => {
157
- verifier = value;
158
- },
159
- codeVerifier: () => verifier,
160
- redirectToAuthorization: redirect,
161
- invalidateCredentials: async (scope) => {
162
- if (scope === "all" || scope === "tokens") {
163
- delete session.tokens;
164
- delete session.expiresAt;
165
- }
166
- if (scope === "all" || scope === "client")
167
- delete session.client;
168
- if (scope === "all" || scope === "verifier")
169
- verifier = "";
170
- await save(url, session);
171
- }
172
- };
173
- }
174
- async function unlockedLogin(url, openBrowser = true) {
175
- const state = randomBytes(32).toString("base64url");
176
- const server = createServer();
177
- await new Promise((resolve, reject) => {
178
- server.once("error", reject);
179
- server.listen(0, "127.0.0.1", resolve);
180
- });
181
- const address = server.address();
182
- if (!address || typeof address === "string")
183
- throw new Error("Could not bind the login callback.");
184
- const session = {
185
- redirectUrl: `http://127.0.0.1:${address.port}/callback`
186
- };
187
- const oauth = provider(url, session, (authorizationUrl) => {
188
- if (authorizationUrl.origin !== url)
189
- throw new Error("Unexpected authorization server.");
190
- console.error(`Open this URL to sign in:
191
- ${authorizationUrl.href}`);
192
- if (openBrowser)
193
- openUrl(authorizationUrl.href);
194
- }, state);
195
- let timer;
196
- try {
197
- const callback = new Promise((resolve, reject) => {
198
- timer = setTimeout(() => reject(new Error("Login timed out. Start login again.")), 300000);
199
- server.on("request", async (request, response) => {
200
- const callbackUrl = new URL(request.url ?? "/", session.redirectUrl);
201
- 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;
202
- if (invalid) {
203
- response.writeHead(400).end("Invalid login callback.");
204
- return;
205
- }
206
- try {
207
- if (callbackUrl.searchParams.get("iss")?.replace(/\/$/, "") !== url)
208
- throw new Error("Unexpected OAuth issuer.");
209
- const code = callbackUrl.searchParams.get("code");
210
- if (!code || callbackUrl.searchParams.getAll("code").length !== 1 || callbackUrl.searchParams.has("error"))
211
- throw new Error("Login was not approved.");
212
- const result = await auth(oauth, {
213
- serverUrl: `${url}/mcp`,
214
- authorizationCode: code,
215
- fetchFn: fetchFor(url)
216
- });
217
- if (result !== "AUTHORIZED")
218
- throw new Error("Login did not complete.");
219
- response.writeHead(200, {
220
- "Content-Type": "text/plain",
221
- "Cache-Control": "no-store"
222
- }).end("Signed in. You can close this tab.");
223
- resolve();
224
- } catch (error) {
225
- response.writeHead(400).end("Login failed. Return to your terminal.");
226
- reject(error);
227
- }
228
- });
229
- });
230
- callback.catch(() => {});
231
- await auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
232
- await callback;
233
- } finally {
234
- clearTimeout(timer);
235
- server.closeAllConnections();
236
- server.close();
237
- }
238
- }
239
- async function unlockedAccessToken(url, forceRefresh = false) {
240
- if (process.env.DISPOSABL_API_KEY)
241
- return process.env.DISPOSABL_API_KEY;
242
- const session = await load(url);
243
- if (!session.tokens)
244
- throw new NotAuthenticated("Run login first, or set DISPOSABL_API_KEY.");
245
- if (forceRefresh || !session.expiresAt || Date.now() >= session.expiresAt - 30000) {
246
- if (!session.client || !session.tokens.refresh_token)
247
- throw new NotAuthenticated("Session cannot be renewed. Sign in again or start a newly authorized agent run.");
248
- const oauth = provider(url, session, () => {
249
- throw new NotAuthenticated("Session expired. Run login again.");
250
- });
251
- await auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
252
- }
253
- if (!session.tokens)
254
- throw new NotAuthenticated("Session expired. Run login again.");
255
- return session.tokens.access_token;
256
- }
257
- async function unlockedLogout(url) {
258
- const session = await load(url);
259
- if (session.tokens) {
260
- for (const token of [
261
- session.tokens.refresh_token,
262
- session.tokens.access_token
263
- ].filter(Boolean)) {
264
- const response = await fetchFor(url)(`${url}/mcp/oauth/revoke`, {
265
- method: "POST",
266
- body: new URLSearchParams({
267
- token,
268
- client_id: session.client?.client_id ?? ""
269
- })
270
- });
271
- if (!response.ok)
272
- throw new Error("Revocation failed; credentials retained so logout can be retried.");
273
- }
274
- }
275
- await rm(sessionPath(url), { force: true });
276
- }
277
- async function withCredentials(url, operation) {
278
- await mkdir(directory(), { recursive: true, mode: 448 });
279
- const release = await lock(sessionPath(url), {
280
- realpath: false,
281
- stale: 1e4,
282
- retries: { retries: 8, minTimeout: 100, maxTimeout: 1000 }
283
- });
284
- try {
285
- return await operation();
286
- } finally {
287
- await release();
288
- }
289
- }
290
- function withCredentialSession(url, operation) {
291
- return withCredentials(url, () => operation({
292
- login: (browser) => unlockedLogin(url, browser),
293
- logout: () => unlockedLogout(url),
294
- hasCredentials: () => hasCredentials(url),
295
- accessToken: (refresh) => unlockedAccessToken(url, refresh),
296
- loginAccessToken: () => loginAccessToken(url)
297
- }));
298
- }
299
- var login = (url, browser = true) => withCredentials(url, () => unlockedLogin(url, browser));
300
- var accessToken = (url, refresh = false) => withCredentials(url, () => unlockedAccessToken(url, refresh));
301
- var logout = (url) => withCredentials(url, () => unlockedLogout(url));
302
- var hasCredentials = async (url) => Boolean(process.env.DISPOSABL_API_KEY || (await load(url)).tokens?.access_token);
303
- var loginAccessToken = async (url) => (await load(url)).tokens?.access_token;
304
-
305
- // delete.ts
306
- function openExpoDeletion(body, appId, browser) {
307
- if (!body || typeof body !== "object" || !("error" in body))
308
- return;
309
- const error = body.error;
310
- if (!error || typeof error !== "object" || !("code" in error) || error.code !== "expo_manual_delete_required")
311
- return;
312
- if (!("appId" in error) || error.appId !== appId || !("projectUrl" in error) || typeof error.projectUrl !== "string")
313
- throw new Error("Invalid Expo deletion response. The app record has been kept.");
314
- const url = new URL(error.projectUrl);
315
- const parts = url.pathname.split("/");
316
- 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")
317
- throw new Error("Invalid Expo project URL. The app record has been kept.");
318
- console.error(`GitHub and Convex cleanup is complete. Finish deleting the Expo project here:
319
- ${url.href}
320
- 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.`);
321
- if (browser)
322
- openUrl(url.href);
323
- }
324
-
325
- // commands.ts
326
- import { CommanderError } from "commander";
327
-
328
- // telemetry.ts
329
- import { createHash as createHash2, randomUUID } from "node:crypto";
330
- import { realpathSync } from "node:fs";
331
- import { mkdir as mkdir2, open, readFile as readFile2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
332
- import { homedir as homedir2 } from "node:os";
333
- import { dirname, join as join2 } from "node:path";
334
- import { lock as lock2 } from "proper-lockfile";
335
- function installedRelease(version, entry = process.argv[1] ?? "") {
336
- try {
337
- entry = realpathSync(entry);
338
- } catch {}
339
- return /(?:^|[\\/])node_modules[\\/]/.test(entry) && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) && !version.includes("development");
340
- }
341
- function telemetryConfig(version, entry = process.argv[1] ?? "") {
342
- const env = process.env;
343
- const host = "https://us.i.posthog.com";
344
- const token = "phc_AkMtHdssxpHojfRGD985EUbxkX2GuMSxKiULHaTT9TgM";
345
- if (!installedRelease(version, entry) || env.NODE_ENV === "test" || env.NODE_ENV === "development" || env.BUN_ENV === "test" || env.CI || env.E2E_TELEMETRY_DISABLED || telemetryOptedOut() || 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 ?? ""))
346
- return null;
347
- return { token, host };
348
- }
349
- function telemetryOptedOut() {
350
- return ["1", "true"].includes(process.env.DO_NOT_TRACK?.toLowerCase() ?? "") || process.env.DISPOSABL_TELEMETRY_DISABLED === "1";
351
- }
352
- var directory2 = () => join2(homedir2(), ".config", "disposabl");
353
- var telemetryStatePath = () => join2(directory2(), "telemetry.json");
354
- async function state(path) {
355
- const revision = await credentialRevision();
356
- try {
357
- const value = JSON.parse(await readFile2(path, "utf8"));
358
- if (/^[0-9a-f-]{36}$/.test(value.anonymousId) && (!value.userId || /^[a-zA-Z0-9_-]{1,128}$/.test(value.userId)) && value.credentialRevision === revision)
359
- return value;
360
- } catch (error) {
361
- if (!(error instanceof SyntaxError) && error.code !== "ENOENT")
362
- throw error;
363
- }
364
- await mkdir2(join2(path, ".."), { recursive: true, mode: 448 });
365
- const fresh = {
366
- anonymousId: randomUUID(),
367
- credentialRevision: revision
368
- };
369
- await writeFile2(path, JSON.stringify(fresh), { mode: 384 });
370
- return fresh;
371
- }
372
- async function synchronized(path, run) {
373
- await mkdir2(dirname(path), { recursive: true, mode: 448 });
374
- const release = await lock2(path, {
375
- realpath: false,
376
- stale: 5000,
377
- retries: { retries: 20, minTimeout: 50, maxTimeout: 50 }
378
- });
379
- try {
380
- return await run();
381
- } finally {
382
- await release();
383
- }
384
- }
385
- async function send(config, event, distinctId, properties) {
386
- const response = await fetch(`${config.host}/i/v0/e/`, {
387
- method: "POST",
388
- redirect: "error",
389
- signal: AbortSignal.timeout(2000),
390
- headers: { "Content-Type": "application/json" },
391
- body: JSON.stringify({
392
- api_key: config.token,
393
- event,
394
- distinct_id: distinctId,
395
- properties: {
396
- ...properties,
397
- environment: "production",
398
- $geoip_disable: true,
399
- $ip: "0.0.0.0"
400
- }
401
- })
402
- });
403
- return response.ok;
404
- }
405
- async function firstExecution(path, product, version) {
406
- try {
407
- const directory = join2(dirname(path), "activations");
408
- await mkdir2(directory, { recursive: true, mode: 448 });
409
- const name = createHash2("sha256").update(`${product}:${version}`).digest("hex");
410
- const file = await open(join2(directory, name), "wx", 384);
411
- await file.close();
412
- return true;
413
- } catch {
414
- return false;
415
- }
416
- }
417
- async function capture(version, product, command, outcome, path) {
418
- const config = telemetryConfig(version);
419
- if (!config)
420
- return;
421
- try {
422
- const current = await synchronized(path, () => state(path));
423
- if (current.credentialRevision !== await credentialRevision())
424
- return;
425
- const allowed = [
426
- "agent",
427
- "login",
428
- "logout",
429
- "apps",
430
- "previews",
431
- "connections",
432
- "users",
433
- "help",
434
- "version",
435
- "other",
436
- "create"
437
- ];
438
- const distinctId = current.userId ?? current.anonymousId;
439
- const activation = outcome === "started" && await firstExecution(path, product, version);
440
- const properties = {
441
- product,
442
- source: product,
443
- command: allowed.includes(command) ? command : "other",
444
- outcome,
445
- version,
446
- ...activation ? { first_execution: true } : {},
447
- invocation: process.env.npm_command === "exec" ? "npx" : /^(npm|pnpm|yarn|bun)\//.exec(process.env.npm_config_user_agent ?? "")?.[1] ?? "direct",
448
- platform: ["darwin", "linux", "win32"].includes(process.platform) ? process.platform : "other",
449
- ...!current.userId ? { $process_person_profile: false } : {}
450
- };
451
- const pending = [send(config, "cli_command", distinctId, properties)];
452
- if (outcome === "failure") {
453
- pending.push(send(config, "$exception", distinctId, {
454
- ...properties,
455
- $exception_list: [
456
- { type: "CommandFailure", value: "Command failed" }
457
- ],
458
- $exception_fingerprint: `disposabl-${product}-${properties.command}`
459
- }));
460
- }
461
- await Promise.allSettled(pending);
462
- } catch {}
463
- }
464
- async function prepareLogin(path) {
465
- try {
466
- return await synchronized(path, async () => {
467
- const current = await state(path);
468
- const loginAttempt = randomUUID();
469
- const next = {
470
- anonymousId: current.userId || current.loginAttempt || current.credentialRevision !== createHash2("sha256").update("anonymous").digest("hex") ? randomUUID() : current.anonymousId,
471
- loginAttempt,
472
- credentialRevision: await credentialRevision()
473
- };
474
- await writeFile2(path, JSON.stringify(next), { mode: 384 });
475
- return loginAttempt;
476
- });
477
- } catch {
478
- return;
479
- }
480
- }
481
- async function identify(version, userId, path, attempt, revision = undefined) {
482
- const config = telemetryConfig(version);
483
- if (!config || !attempt || typeof userId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(userId))
484
- return;
485
- try {
486
- const expectedRevision = revision ?? await credentialRevision();
487
- await synchronized(path, async () => {
488
- const current = JSON.parse(await readFile2(path, "utf8"));
489
- if (current.loginAttempt !== attempt || expectedRevision !== await credentialRevision() || current.userId || !/^[0-9a-f-]{36}$/.test(current.anonymousId))
490
- return;
491
- const opaqueId = createHash2("sha256").update(`disposabl:${config.token}:${userId}`).digest("hex");
492
- if (await send(config, "$identify", opaqueId, {
493
- $anon_distinct_id: current.anonymousId
494
- })) {
495
- await writeFile2(path, JSON.stringify({
496
- anonymousId: current.anonymousId,
497
- userId: opaqueId,
498
- credentialRevision: expectedRevision
499
- }), { mode: 384 });
500
- }
501
- });
502
- } catch {}
503
- }
504
- async function resetIdentity(path, attempt) {
505
- try {
506
- await synchronized(path, async () => {
507
- if (attempt) {
508
- const current = JSON.parse(await readFile2(path, "utf8"));
509
- if (current.loginAttempt !== attempt)
510
- return;
511
- }
512
- await rm2(path, { force: true });
513
- });
514
- } catch {}
515
- }
516
-
517
- // errors.ts
518
- function apiError(status, body) {
519
- try {
520
- const data = JSON.parse(body)?.error;
521
- if (data?.code === "credits_required") {
522
- const paymentUrl = data.paymentUrl === "https://www.disposabl.dev/pricing" ? `
523
- Add credits: ${data.paymentUrl}` : "";
524
- 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}`;
525
- }
526
- if (data?.code === "credits_unavailable")
527
- return "Credits are temporarily unavailable. Please retry.";
528
- } catch {}
529
- return `API request failed (${status}): ${body}`;
530
- }
531
-
532
- // client.ts
533
- import { Command } from "commander";
534
-
535
- // ../disposabl-kit/lib/observability.ts
536
- var traceparentPattern = /^00-([0-9a-f]{32})-([0-9a-f]{16})-01$/;
537
- function parseTraceparent(value) {
538
- const match = traceparentPattern.exec(value ?? "");
539
- if (!match || /^0+$/.test(match[1]) || /^0+$/.test(match[2]))
540
- return null;
541
- return { traceId: match[1], parentSpanId: match[2] };
542
- }
543
- function startSpan(parent) {
544
- const context = parseTraceparent(parent);
545
- const traceId = context?.traceId ?? crypto.randomUUID().replaceAll("-", "");
546
- const spanId = Array.from(crypto.getRandomValues(new Uint8Array(8)), (byte) => byte.toString(16).padStart(2, "0")).join("");
547
- return {
548
- traceId,
549
- spanId,
550
- parentSpanId: context?.parentSpanId,
551
- traceparent: `00-${traceId}-${spanId}-01`
552
- };
553
- }
554
- var attribute = (key, stringValue) => ({
555
- key,
556
- value: { stringValue }
557
- });
558
- var nanoseconds = (ms) => String(BigInt(Math.round(ms)) * 1000000n);
559
- async function exportOperation(config, operation, timeout) {
560
- const {
561
- service,
562
- name,
563
- source,
564
- startedAt,
565
- endedAt,
566
- failed,
567
- distinctId,
568
- span
569
- } = operation;
570
- const resource = {
571
- attributes: [
572
- attribute("service.name", service),
573
- attribute("deployment.environment.name", "production")
574
- ]
575
- };
576
- const attributes = [
577
- attribute("disposabl.source", source),
578
- attribute("disposabl.operation", name)
579
- ];
580
- const context = { traceId: span.traceId, spanId: span.spanId, attributes };
581
- const send = (signal, data) => fetch(`${config.host}/i/v1/${signal}`, {
582
- method: "POST",
583
- redirect: "error",
584
- signal: AbortSignal.timeout(timeout),
585
- headers: {
586
- Authorization: `Bearer ${config.token}`,
587
- "Content-Type": "application/json"
588
- },
589
- body: JSON.stringify(data)
590
- });
591
- const endTime = nanoseconds(Math.max(startedAt, endedAt));
592
- const pending = [
593
- send("traces", {
594
- resourceSpans: [
595
- {
596
- resource,
597
- scopeSpans: [
598
- {
599
- spans: [
600
- {
601
- ...context,
602
- attributes: distinctId ? [
603
- ...attributes,
604
- attribute("posthog.distinct_id", distinctId)
605
- ] : attributes,
606
- ...span.parentSpanId ? { parentSpanId: span.parentSpanId } : {},
607
- name,
608
- kind: service === "disposabl-cli" ? 3 : 2,
609
- startTimeUnixNano: nanoseconds(startedAt),
610
- endTimeUnixNano: endTime,
611
- status: { code: failed ? 2 : 1 }
612
- }
613
- ]
614
- }
615
- ]
616
- }
617
- ]
618
- })
619
- ];
620
- if (failed)
621
- pending.push(send("logs", {
622
- resourceLogs: [
623
- {
624
- resource,
625
- scopeLogs: [
626
- {
627
- logRecords: [
628
- {
629
- ...context,
630
- attributes: distinctId ? [
631
- ...attributes,
632
- attribute("posthogDistinctId", distinctId)
633
- ] : attributes,
634
- timeUnixNano: endTime,
635
- severityNumber: 17,
636
- severityText: "ERROR",
637
- body: { stringValue: "Disposabl operation failed" }
638
- }
639
- ]
640
- }
641
- ]
642
- }
643
- ]
644
- }));
645
- await Promise.allSettled(pending);
646
- }
647
-
648
- // client.ts
649
- function createProgram(serviceOrigin, centralAnalytics = false, dependencies = {}) {
650
- const version = dependencies.version ?? package_default.version;
651
- const path = () => dependencies.telemetryPath ?? telemetryStatePath();
652
- const sessionLogin = dependencies.login ?? login;
653
- const sessionLogout = dependencies.logout ?? logout;
654
- const sessionHasCredentials = dependencies.hasCredentials ?? hasCredentials;
655
- const sessionAccessToken = dependencies.accessToken ?? accessToken;
656
- const sessionLoginAccessToken = dependencies.loginAccessToken ?? loginAccessToken;
657
- const credentialSession = (url, operation) => {
658
- if (dependencies.credentialSession)
659
- return dependencies.credentialSession(url, operation);
660
- if (!(dependencies.login || dependencies.logout || dependencies.hasCredentials || dependencies.accessToken || dependencies.loginAccessToken))
661
- return withCredentialSession(url, operation);
662
- return operation({
663
- login: (browser) => sessionLogin(url, browser),
664
- logout: () => sessionLogout(url),
665
- hasCredentials: () => sessionHasCredentials(url),
666
- accessToken: (refresh) => sessionAccessToken(url, refresh),
667
- loginAccessToken: () => sessionLoginAccessToken(url)
668
- });
669
- };
670
- const program = new Command().name(Object.keys(package_default.bin)[0]).version(package_default.version);
671
- program.addHelpText("after", `
672
- API commands are loaded from the configured service. Use <command> --help for their options.
673
- `);
674
- if (centralAnalytics)
675
- program.addHelpText("after", `
676
- Disposabl collects limited CLI usage when configured. Set DO_NOT_TRACK=1 to opt out.
677
- `);
678
- const origin = () => apiUrl(serviceOrigin);
679
- const loginCommand = program.command("login").option("--no-browser", "Print the login URL without opening a browser").action(async (options) => {
680
- const base = origin();
681
- const central = centralAnalytics && base === "https://www.disposabl.dev" && installedRelease(version);
682
- const enabled = central && telemetryConfig(version);
683
- const { attempt, token, revision } = await credentialSession(base, async (session) => {
684
- let attempt;
685
- if (central) {
686
- if (enabled)
687
- attempt = await prepareLogin(path());
688
- else
689
- await resetIdentity(path());
690
- }
691
- await session.login(options.browser);
692
- return {
693
- attempt,
694
- revision: enabled ? await credentialRevision().catch(() => {
695
- return;
696
- }) : undefined,
697
- token: enabled ? await session.loginAccessToken().catch(() => {
698
- return;
699
- }) : undefined
700
- };
701
- });
702
- if (enabled && token && revision) {
703
- try {
704
- const response = await fetch(`${base}/api/users/current`, {
705
- headers: { Authorization: `Bearer ${token}` },
706
- redirect: "error",
707
- signal: AbortSignal.timeout(500)
708
- });
709
- if (response.ok)
710
- await identify(version, (await response.json())?.id, path(), attempt, revision);
711
- } catch {}
712
- }
713
- console.error("Signed in.");
714
- });
715
- loginCommand.command("status").description("Return the server-verified current user").action(async () => {
716
- const base = origin();
717
- const enabled = centralAnalytics && base === "https://www.disposabl.dev" && telemetryConfig(version);
718
- let snapshot;
719
- try {
720
- snapshot = await credentialSession(base, async (session) => {
721
- if (!await session.hasCredentials()) {
722
- if (enabled)
723
- await resetIdentity(path());
724
- return;
725
- }
726
- const attempt = enabled ? await prepareLogin(path()) : undefined;
727
- try {
728
- const token = await session.accessToken();
729
- return {
730
- token,
731
- attempt,
732
- revision: enabled ? await credentialRevision().catch(() => {
733
- return;
734
- }) : undefined
735
- };
736
- } catch (error) {
737
- if (enabled && attempt)
738
- await resetIdentity(path(), attempt);
739
- throw error;
740
- }
741
- });
742
- } catch (error) {
743
- if (!(error instanceof NotAuthenticated))
744
- throw error;
745
- console.log(JSON.stringify({ currentUser: null }));
746
- return;
747
- }
748
- if (!snapshot) {
749
- console.log(JSON.stringify({ currentUser: null }));
750
- return;
751
- }
752
- const send = (token) => fetch(`${base}/api/users/current`, {
753
- headers: {
754
- Authorization: `Bearer ${token}`,
755
- "X-Disposabl-Source": "cli",
756
- ...telemetryOptedOut() && { DNT: "1" }
757
- },
758
- redirect: "error",
759
- signal: AbortSignal.timeout(30000)
760
- });
761
- let response = await send(snapshot.token);
762
- if (response.status === 401 && !process.env.DISPOSABL_API_KEY) {
763
- try {
764
- const refreshed = await credentialSession(base, async (session) => {
765
- if (await session.loginAccessToken() !== snapshot.token)
766
- return;
767
- const token = await session.accessToken(true);
768
- return {
769
- token,
770
- revision: enabled ? await credentialRevision().catch(() => {
771
- return;
772
- }) : undefined
773
- };
774
- });
775
- if (refreshed) {
776
- snapshot.revision = refreshed.revision;
777
- response = await send(refreshed.token);
778
- }
779
- } catch (error) {
780
- if (!(error instanceof NotAuthenticated))
781
- throw error;
782
- }
783
- }
784
- if (response.status === 401) {
785
- if (enabled && snapshot.attempt)
786
- await resetIdentity(path(), snapshot.attempt);
787
- console.log(JSON.stringify({ currentUser: null }));
788
- return;
789
- }
790
- if (!response.ok)
791
- throw new Error(`Login status failed (${response.status}).`);
792
- const currentUser = await response.json();
793
- if (enabled && snapshot.revision)
794
- await identify(version, currentUser?.id, path(), snapshot.attempt, snapshot.revision);
795
- console.log(JSON.stringify({ currentUser }));
796
- });
797
- program.command("logout").action(async () => {
798
- const base = origin();
799
- await credentialSession(base, async (session) => {
800
- await session.logout();
801
- if (centralAnalytics && base === "https://www.disposabl.dev" && installedRelease(version))
802
- await resetIdentity(path());
803
- });
804
- console.error("Signed out.");
805
- });
806
- return program;
807
- }
808
- async function loadContract(base) {
809
- const response = await fetch(`${base}/openapi.json`, {
810
- redirect: "error",
811
- signal: AbortSignal.timeout(30000)
812
- });
813
- if (!response.ok)
814
- throw new Error(`Could not load OpenAPI (${response.status}).`);
815
- return await response.json();
816
- }
817
- function operationFields(method, operation) {
818
- const schema = operation.requestBody?.content["application/json"].schema;
819
- return method === "get" ? (operation.parameters ?? []).map((p) => ({
820
- name: p.name,
821
- required: p.required,
822
- schema: p.content["application/json"].schema
823
- })) : Object.entries(schema?.properties ?? {}).map(([name, value]) => ({
824
- name,
825
- required: schema?.required?.includes(name),
826
- schema: value
827
- }));
828
- }
829
- function addOperation(program, path) {
830
- if (!path.startsWith("/api/") || path.includes("?") || path.includes("#"))
831
- throw new Error("Invalid API path in contract.");
832
- const parts = path.slice(5).split("/");
833
- let parent = program;
834
- for (const part of parts.slice(0, -1))
835
- parent = parent.commands.find((command) => command.name() === part) ?? parent.command(part);
836
- return parent.command(parts.at(-1));
837
- }
838
- function requestOperation(base, path, method, input, timeout = 30000) {
839
- const target = new URL(path, base);
840
- if (target.origin !== base || !target.pathname.startsWith("/api/"))
841
- throw new Error("Invalid operation URL.");
842
- if (method === "get")
843
- for (const [name, value] of Object.entries(input))
844
- target.searchParams.set(name, JSON.stringify(value));
845
- const send = async (traceparent, refresh = false) => fetch(target, {
846
- method: method.toUpperCase(),
847
- redirect: "error",
848
- signal: AbortSignal.timeout(timeout),
849
- headers: {
850
- Authorization: `Bearer ${await accessToken(base, refresh)}`,
851
- "Content-Type": "application/json",
852
- "X-Disposabl-Source": "cli",
853
- ...telemetryOptedOut() && { DNT: "1" },
854
- ...traceparent && { traceparent }
855
- },
856
- body: method === "post" ? JSON.stringify(input) : undefined
857
- });
858
- return async () => {
859
- const config = base === "https://www.disposabl.dev" && telemetryConfig(package_default.version);
860
- const span = config && startSpan();
861
- const startedAt = Date.now();
862
- let failed = true;
863
- try {
864
- let response = await send(span ? span.traceparent : undefined);
865
- if (response.status === 401 && !process.env.DISPOSABL_API_KEY)
866
- response = await send(span ? span.traceparent : undefined, true);
867
- failed = !response.ok;
868
- return response;
869
- } finally {
870
- if (config && span)
871
- await exportOperation(config, {
872
- service: "disposabl-cli",
873
- name: "cli_api_request",
874
- source: "cli",
875
- startedAt,
876
- endedAt: Date.now(),
877
- failed,
878
- span
879
- }, 500).catch(() => {});
880
- }
881
- };
882
- }
883
- function needsContract(program, argv, origin) {
884
- const args = argv.slice(2);
885
- const { operands } = program.parseOptions(args);
886
- const command = operands[0] === "help" ? operands[1] : operands[0];
887
- return Boolean(origin) && command !== undefined && !args.some((arg) => arg === "--version" || arg === "-V") && command !== "login" && command !== "logout";
888
- }
889
-
890
- // commands.ts
891
- import { readFile as readFile4 } from "node:fs/promises";
892
- import { join as join5 } from "node:path";
893
-
894
- // repository.ts
895
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
896
- import { mkdir as mkdir3, chmod as chmod2, writeFile as writeFile3, rename as rename2, rm as rm3 } from "node:fs/promises";
897
- import { homedir as homedir3 } from "node:os";
898
- import { join as join3 } from "node:path";
899
- async function configureRepository(origin, appId, value) {
900
- if (!value.token || !/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(value.repository))
901
- throw new Error("Invalid repository credential response.");
902
- const directory = process.env.DISPOSABL_CONFIG_DIR || join3(homedir3(), ".config", "disposabl");
903
- const key = createHash3("sha256").update(JSON.stringify([origin, appId])).digest("hex");
904
- const credentialFile = join3(directory, `repository-${key}.json`);
905
- const temporary = `${credentialFile}.${randomUUID2()}`;
906
- await mkdir3(directory, { recursive: true, mode: 448 });
907
- await chmod2(directory, 448);
908
- try {
909
- await writeFile3(temporary, JSON.stringify(value), {
910
- mode: 384,
911
- flag: "wx"
912
- });
913
- await rename2(temporary, credentialFile);
914
- } finally {
915
- await rm3(temporary, { force: true });
916
- }
917
- return { repository: value.repository, credentialFile };
918
- }
919
-
920
- // preview.ts
921
- import {
922
- chmod as chmod3,
923
- lstat,
924
- readFile as readFile3,
925
- rename as rename3,
926
- writeFile as writeFile4,
927
- rm as rm4
928
- } from "node:fs/promises";
929
- import { basename, join as join4, resolve } from "node:path";
930
- import { randomUUID as randomUUID3 } from "node:crypto";
931
- import { spawnSync } from "node:child_process";
932
- function detectReference(directory = process.cwd()) {
933
- const git = (...args) => spawnSync("git", args, { cwd: directory, encoding: "utf8" }).stdout?.trim();
934
- const branch = git("symbolic-ref", "--quiet", "--short", "HEAD");
935
- if (branch)
936
- return branch;
937
- const root = git("rev-parse", "--show-toplevel");
938
- const common = git("rev-parse", "--path-format=absolute", "--git-common-dir");
939
- const local = git("rev-parse", "--absolute-git-dir");
940
- if (root && common && local && common !== local)
941
- return basename(root);
942
- throw new Error("Cannot detect a branch or worktree. Run inside the app's Git checkout or supply --reference.");
943
- }
944
- async function updateEnv(file, values, remove = []) {
945
- const stat = await lstat(file).catch((error) => {
946
- if (error.code !== "ENOENT")
947
- throw error;
948
- return;
949
- });
950
- if (stat && (!stat.isFile() || stat.isSymbolicLink()))
951
- throw new Error(`Refusing to replace non-regular file ${file}.`);
952
- const text = stat ? await readFile3(file, "utf8") : "";
953
- const keys = new Set([...Object.keys(values), ...remove]);
954
- const lines = text.split(`
955
- `).filter((line) => !keys.has(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=/.exec(line)?.[1] ?? ""));
956
- const next = lines.join(`
957
- `).trimEnd() + `
958
- ` + Object.entries(values).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(`
959
- `) + `
960
- `;
961
- const temporary = `${file}.${randomUUID3()}.tmp`;
962
- try {
963
- await writeFile4(temporary, next, { flag: "wx", mode: 384 });
964
- await rename3(temporary, file);
965
- await chmod3(file, 384);
966
- } finally {
967
- await rm4(temporary, { force: true });
968
- }
969
- }
970
- async function configureDevelopment(directory, value) {
971
- const root = resolve(directory);
972
- const config = JSON.parse(await readFile3(join4(root, "disposabl.json"), "utf8"));
973
- if (config.appId !== value.appId || !value.deployKey.startsWith(`dev:${value.name}|`))
974
- throw new Error("Development credentials do not match this app.");
975
- if (!/^[a-z0-9-]+$/.test(value.name) || value.convexUrl !== `https://${value.name}.convex.cloud` || value.convexSiteUrl !== `https://${value.name}.convex.site`)
976
- throw new Error("Development URLs do not match the deployment.");
977
- if (value.productionConvexSiteUrl && !/^https:\/\/[a-z0-9-]+\.convex\.site$/.test(value.productionConvexSiteUrl))
978
- throw new Error("Unexpected production Convex site URL.");
979
- for (const url of [value.publicSiteUrl, value.productionSiteUrl]) {
980
- if (url !== undefined && !/^https:\/\/[a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?\.disposabl\.xyz$/.test(url))
981
- throw new Error("Unexpected public site URL.");
982
- }
983
- if (config.features?.includes("analytics") && !value.analytics)
984
- throw new Error("Analytics setup is incomplete. Connect PostHog and retry app setup.");
985
- 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)))
986
- throw new Error("Unexpected PostHog project configuration.");
987
- if (value.repositoryUrl) {
988
- const repository = /^https:\/\/github\.com\/([a-zA-Z0-9-]+)\/([a-zA-Z0-9_.-]+)\.git$/.exec(value.repositoryUrl);
989
- if (!repository)
990
- throw new Error("Unexpected GitHub repository URL.");
991
- const remote = spawnSync("git", ["remote", "get-url", "origin"], {
992
- cwd: root,
993
- encoding: "utf8"
994
- });
995
- if (remote.status === 0) {
996
- const current = remote.stdout.trim();
997
- const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(current);
998
- if (!match || `${match[1]}/${match[2]}`.toLowerCase() !== `${repository[1]}/${repository[2]}`.toLowerCase())
999
- throw new Error("Existing origin points to a different repository; it was not changed.");
1000
- } else {
1001
- const added = spawnSync("git", ["remote", "add", "origin", value.repositoryUrl], { cwd: root, encoding: "utf8" });
1002
- if (added.status !== 0)
1003
- throw new Error(`Could not add origin: ${added.stderr.trim()}`);
1004
- }
1005
- }
1006
- const files = ["packages/backend/.env.local", "apps/web/.env.local"];
1007
- if (config.platforms.some((p) => p === "android" || p === "ios"))
1008
- files.push("apps/mobile/.env.local");
1009
- for (const file of files) {
1010
- const ignored = spawnSync("git", ["check-ignore", "--quiet", file], {
1011
- cwd: root,
1012
- stdio: "ignore"
1013
- });
1014
- const tracked = spawnSync("git", ["ls-files", "--error-unmatch", file], {
1015
- cwd: root,
1016
- stdio: "ignore"
1017
- });
1018
- if (ignored.status !== 0 || tracked.status !== 1)
1019
- throw new Error(`${file} must be untracked and ignored by Git.`);
1020
- }
1021
- if (value.productionConvexSiteUrl || value.productionSiteUrl || value.analytics || config.analytics) {
1022
- if (value.productionSiteUrl)
1023
- config.productionSiteUrl = value.productionSiteUrl;
1024
- if (value.productionConvexSiteUrl)
1025
- config.productionConvexSiteUrl = value.productionConvexSiteUrl;
1026
- if (config.features?.includes("analytics"))
1027
- config.analytics = value.analytics;
1028
- else
1029
- delete config.analytics;
1030
- await writeFile4(join4(root, "disposabl.json"), JSON.stringify(config, null, 2) + `
1031
- `);
1032
- const formatted = spawnSync("bun", ["fmt", "disposabl.json"], {
1033
- cwd: root,
1034
- stdio: "pipe"
1035
- });
1036
- if (formatted.status !== 0)
1037
- throw new Error("Could not format disposabl.json after configuring development.");
1038
- }
1039
- await updateEnv(join4(root, files[0]), {
1040
- CONVEX_DEPLOY_KEY: value.deployKey,
1041
- CONVEX_URL: value.convexUrl,
1042
- CONVEX_SITE_URL: value.convexSiteUrl,
1043
- ...value.publicSiteUrl ? { PUBLIC_SITE_URL: value.publicSiteUrl } : {}
1044
- }, ["CONVEX_DEPLOYMENT", "PUBLIC_SITE_URL"]);
1045
- await updateEnv(join4(root, files[1]), {
1046
- VITE_CONVEX_URL: value.convexUrl,
1047
- VITE_CONVEX_SITE_URL: value.publicSiteUrl ?? value.convexSiteUrl
1048
- });
1049
- if (files[2])
1050
- await updateEnv(join4(root, files[2]), {
1051
- EXPO_PUBLIC_CONVEX_URL: value.convexUrl,
1052
- EXPO_PUBLIC_CONVEX_SITE_URL: value.publicSiteUrl ?? value.convexSiteUrl
1053
- });
1054
- }
1055
- function formatPreview(preview) {
1056
- if (!preview)
1057
- return "Preview not found. Create it with disposabl previews token create --configure .";
1058
- const lines = [
1059
- `Preview: ${preview.reference}`,
1060
- `App: ${preview.appId}`,
1061
- `Stage: ${preview.stage ?? "building"}`
1062
- ];
1063
- for (const [name, state] of Object.entries(preview.platforms)) {
1064
- if (!state.enabled) {
1065
- lines.push(`${name}: disabled`);
1066
- continue;
1067
- }
1068
- const latest = state.latest;
1069
- lines.push(`${name}: ${latest?.status ?? "not built"}${latest?.version ? ` (${latest.version})` : ["cli", "sdk"].includes(name) ? " (not published)" : ""}`);
1070
- for (const [label, url] of Object.entries({
1071
- URL: state.url,
1072
- Preview: latest?.url,
1073
- Release: latest?.githubReleaseUrl,
1074
- Download: latest?.artifactUrl,
1075
- Update: latest?.updateUrl,
1076
- "Workflow run": latest?.run?.url,
1077
- Reason: latest?.reason
1078
- }))
1079
- if (url)
1080
- lines.push(` ${label}: ${url}`);
1081
- }
1082
- return lines.join(`
1083
- `);
1084
- }
1085
-
1086
- // commands.ts
1087
- async function runCli(argv = process.argv, serviceOrigin = process.env.DISPOSABL_API_ORIGIN || SERVICE_ORIGIN) {
1088
- const program = createProgram(serviceOrigin, true);
1089
- program.exitOverride();
1090
- const origin = () => apiUrl(serviceOrigin);
1091
- async function main() {
1092
- if (needsContract(program, argv, serviceOrigin)) {
1093
- const base = origin();
1094
- const spec = await loadContract(base);
1095
- for (const [path, methods] of Object.entries(spec.paths)) {
1096
- for (const [method, operation] of Object.entries(methods)) {
1097
- if (!["get", "post"].includes(method))
1098
- continue;
1099
- const command = addOperation(program, path);
1100
- const connectionStatus = path === "/api/connections/status";
1101
- if (connectionStatus)
1102
- command.option("--wait", "Open setup and continue when GitHub and Convex are ready");
1103
- if (connectionStatus)
1104
- command.option("--setup-origin", "Show the terminal setup completion screen");
1105
- if (connectionStatus)
1106
- command.option("--mobile", "Also wait for Expo when creating a mobile app");
1107
- const deleteApp = path === "/api/apps/delete";
1108
- if (deleteApp)
1109
- command.option("--no-browser", "Print the Expo cleanup URL without opening a browser");
1110
- const previewGet = path === "/api/previews/get";
1111
- const tokenCreate = path === "/api/previews/token/create";
1112
- const repositoryToken = path === "/api/apps/repositoryToken";
1113
- if (repositoryToken)
1114
- command.option("--configure", "Save repository credentials privately outside the project");
1115
- if (previewGet)
1116
- command.option("--json", "Print the full preview as JSON");
1117
- if (tokenCreate)
1118
- command.option("--configure <directory>", "Write local development environment files");
1119
- const fields = operationFields(method, operation);
1120
- for (const field of fields) {
1121
- if (deleteApp && field.name === "dangerouslyDeleteApp") {
1122
- command.option("--dangerously-delete-app", "Permanently delete this preview app and its GitHub, Convex and Expo projects");
1123
- continue;
1124
- }
1125
- const flag = `--${field.name} <value>`;
1126
- if (field.required && !(field.name === "appId" && (previewGet || tokenCreate)) && !(field.name === "reference" && (previewGet || tokenCreate)))
1127
- command.requiredOption(flag, field.schema.type === "string" ? field.name : `${field.name} as JSON`);
1128
- else
1129
- command.option(flag, field.name);
1130
- }
1131
- command.action(async (options) => {
1132
- if (deleteApp && options.dangerouslyDeleteApp !== true)
1133
- throw new Error("Permanent deletion requires --dangerously-delete-app. Apps with production releases cannot be deleted.");
1134
- if ((previewGet || tokenCreate) && !options.appId) {
1135
- const config = JSON.parse(await readFile4(join5(options.configure ?? process.cwd(), "disposabl.json"), "utf8"));
1136
- if (!config.appId)
1137
- throw new Error("No appId in disposabl.json. Run setup or pass --appId.");
1138
- options.appId = config.appId;
1139
- }
1140
- if ((previewGet || tokenCreate) && !options.reference)
1141
- options.reference = detectReference(options.configure);
1142
- const input = Object.fromEntries(fields.filter((field) => options[field.name] !== undefined).map((field) => [
1143
- field.name,
1144
- field.schema.type === "string" || typeof options[field.name] === "boolean" ? options[field.name] : JSON.parse(options[field.name])
1145
- ]));
1146
- const send = requestOperation(base, path, method, input, deleteApp ? 300000 : 30000);
1147
- let result = await send();
1148
- if (deleteApp && !result.ok)
1149
- openExpoDeletion(await result.clone().json().catch(() => null), options.appId, options.browser !== false);
1150
- if (!result.ok)
1151
- throw new Error(apiError(result.status, await result.text()));
1152
- let value = await result.json();
1153
- const ready = () => value.ready && (!options.mobile || Boolean(value.expo));
1154
- if (connectionStatus && options.wait && !ready()) {
1155
- const requested = Array.isArray(input.features) ? input.features : [];
1156
- const connections = new URL("/dashboard/connections", base);
1157
- if (options.setupOrigin)
1158
- connections.searchParams.set("origin", "cli");
1159
- const requiredFeatures = requested.filter((f) => f === "analytics" || f === "payments");
1160
- if (requiredFeatures.length)
1161
- connections.searchParams.set("features", requiredFeatures.join(","));
1162
- if (options.mobile)
1163
- connections.searchParams.set("mobile", "1");
1164
- const url = connections.href;
1165
- const names = {
1166
- github: "GitHub",
1167
- convex: "Convex",
1168
- posthog: "PostHog",
1169
- expo: "Expo",
1170
- autumn: "Autumn"
1171
- };
1172
- const missing = Array.isArray(value.missing) ? value.missing.map((id) => names[id] ?? id).join(" and ") : "GitHub and Convex";
1173
- console.error(`Connect ${missing} for this app:
1174
- ${url}
1175
- Waiting for connections. Press Ctrl+C to keep your files and finish later.`);
1176
- openUrl(url);
1177
- const deadline = Date.now() + 15 * 60000;
1178
- while (!ready() && Date.now() < deadline) {
1179
- await new Promise((resolve) => setTimeout(resolve, 3000));
1180
- result = await send();
1181
- if (!result.ok)
1182
- throw new Error(`Connection status failed (${result.status}). Your login and app files are saved.`);
1183
- value = await result.json();
1184
- }
1185
- if (!ready())
1186
- throw new Error(`Connections are still incomplete. Finish at ${url}, then retry setup.`);
1187
- }
1188
- if (repositoryToken && options.configure) {
1189
- console.log(JSON.stringify(await configureRepository(base, options.appId, value), null, 2));
1190
- } else if (tokenCreate && options.configure) {
1191
- await configureDevelopment(options.configure, value);
1192
- const {
1193
- deployKey: _secret,
1194
- convexSiteUrl: _provider,
1195
- productionConvexSiteUrl: _productionProvider,
1196
- ...details
1197
- } = value;
1198
- console.log(JSON.stringify({ ...details, configured: true }, null, 2));
1199
- } else if (previewGet && !options.json)
1200
- console.log(formatPreview(value));
1201
- else
1202
- console.log(JSON.stringify(value, null, 2));
1203
- });
1204
- }
1205
- }
1206
- }
1207
- if (argv.length <= 2)
1208
- program.outputHelp();
1209
- else
1210
- await program.parseAsync(argv);
1211
- }
1212
- const command = ["--version", "-V"].includes(argv[2] ?? "") ? "version" : ["--help", "-h"].includes(argv[2] ?? "") ? "help" : argv[2] ?? "help";
1213
- const central = serviceOrigin === SERVICE_ORIGIN;
1214
- const started = central ? capture(version, "cli", command, "started", telemetryStatePath()) : undefined;
1215
- try {
1216
- await main();
1217
- await started;
1218
- if (central)
1219
- await capture(version, "cli", command, "success", telemetryStatePath());
1220
- } catch (error) {
1221
- await started;
1222
- const success = error instanceof CommanderError && error.exitCode === 0;
1223
- if (central)
1224
- await capture(version, "cli", command, success ? "success" : "failure", telemetryStatePath());
1225
- if (!success)
1226
- throw error;
1227
- }
1228
- }
1229
-
1230
- // index.ts
1231
- runCli().catch((error) => {
1232
- console.error(error instanceof Error ? error.message : "Command failed.");
1233
- process.exitCode = 1;
1234
- });