@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/README.md CHANGED
@@ -1,44 +1,15 @@
1
1
  # Disposabl CLI
2
2
 
3
- The CLI connects to `https://www.disposabl.dev`.
3
+ Run `bunx disposabl` from a generated app. The CLI uses its local Convex HTTP origin when configured and its hosted API otherwise. Use `--origin <url>` or `DISPOSABL_API_ORIGIN` to choose a target.
4
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.
5
+ | Command | What it does |
6
+ | --- | --- |
7
+ | `disposabl status` | Reports the current user and whether the app uses authentication. |
8
+ | `disposabl login` and `disposabl logout` | Manage the session for an app with authentication enabled. |
9
+ | `disposabl list` | Lists the app’s enabled commands and their operation IDs. |
10
+ | `disposabl call <operationId> '<json>'` | Invokes an operation with a JSON object. |
11
+ | `disposabl billing status` | Reads plan and credits when payments are enabled and an Autumn key is configured. |
6
12
 
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
- ```
13
+ Use `disposabl <command> --help` to see the arguments for a function command. Run `disposabl login --no-browser` to print the approval link. For automation, set `DISPOSABL_API_KEY` to a scoped key issued for the target app.
23
14
 
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
- Published Disposabl releases collect command category, outcome, package version, operating system and package-manager category. Requests to the Disposabl API also send operation timings and a trace ID to link CLI requests with backend timing and failure logs. A random ID stored in `~/.config/disposabl/telemetry.json` connects anonymous usage to a pseudonymous ID after login. Logout and account changes reset that ID. Prompts, arguments, paths, error messages, credentials and email addresses are excluded. Set `DO_NOT_TRACK=1` or `DISPOSABL_TELEMETRY_DISABLED=1` to opt out. Local source, development, CI and E2E runs do not send CLI telemetry. Generated apps use their own analytics configuration.
41
-
42
- Failed commands also send a fixed, coarse error-tracking event with no exception message or stack trace.
43
-
44
- 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.
15
+ On the Disposabl service, run `disposabl connections status` to check both providers. Run `disposabl connections github` or `disposabl connections convex` followed by `status`, `connect`, or `disconnect`. The `connect` command opens the authorization link. Use `--no-browser` to print it instead.
package/auth.mjs ADDED
@@ -0,0 +1,221 @@
1
+ import { lock } from "proper-lockfile";
2
+ import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
3
+ import { createServer } from "node:http";
4
+ import { randomBytes, createHash } from "node:crypto";
5
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { spawn } from "node:child_process";
9
+ export function openUrl(url) {
10
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
11
+ const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
12
+ const child = spawn(command, args, { stdio: "ignore" });
13
+ child.on("error", () => console.error("Open the URL manually."));
14
+ child.unref();
15
+ }
16
+
17
+ export class NotAuthenticated extends Error {
18
+ }
19
+ const directory = () => process.env.DISPOSABL_CONFIG_DIR || join(homedir(), ".config", "disposabl");
20
+ const sessionPath = (url) => join(directory(), `${createHash("sha256").update(url).digest("hex")}.json`);
21
+ const fetchFor = (origin) => Object.assign(async (input, init) => {
22
+ const url = new URL(input instanceof Request ? input.url : input);
23
+ if (url.origin !== origin)
24
+ throw new Error("OAuth endpoint must belong to the configured API origin.");
25
+ return fetch(input, {
26
+ ...init,
27
+ redirect: "error",
28
+ signal: init?.signal ?? AbortSignal.timeout(30000)
29
+ });
30
+ }, {
31
+ preconnect: fetch.preconnect
32
+ });
33
+ async function load(url) {
34
+ try {
35
+ return JSON.parse(await readFile(sessionPath(url), "utf8"));
36
+ } catch (error) {
37
+ if (error.code === "ENOENT")
38
+ return {};
39
+ throw error;
40
+ }
41
+ }
42
+ async function save(url, session) {
43
+ await mkdir(directory(), { recursive: true, mode: 0o700 });
44
+ await chmod(directory(), 0o700);
45
+ const temporary = `${sessionPath(url)}.${randomBytes(8).toString("hex")}`;
46
+ try {
47
+ await writeFile(temporary, JSON.stringify(session), {
48
+ mode: 0o600,
49
+ flag: "wx"
50
+ });
51
+ await rename(temporary, sessionPath(url));
52
+ } finally {
53
+ await rm(temporary, { force: true });
54
+ }
55
+ }
56
+ function provider(url, session, redirect, state) {
57
+ let verifier = "";
58
+ return {
59
+ redirectUrl: session.redirectUrl,
60
+ clientMetadata: {
61
+ client_name: "Disposabl CLI",
62
+ redirect_uris: session.redirectUrl ? [session.redirectUrl] : [],
63
+ grant_types: ["authorization_code", "refresh_token"],
64
+ response_types: ["code"],
65
+ token_endpoint_auth_method: "none"
66
+ },
67
+ state: () => state ?? "",
68
+ clientInformation: () => session.client,
69
+ saveClientInformation: (client) => {
70
+ session.client = client;
71
+ },
72
+ tokens: () => session.tokens,
73
+ saveTokens: async (tokens) => {
74
+ session.tokens = tokens;
75
+ session.expiresAt = tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : 0;
76
+ await save(url, session);
77
+ },
78
+ saveCodeVerifier: (value) => {
79
+ verifier = value;
80
+ },
81
+ codeVerifier: () => verifier,
82
+ redirectToAuthorization: redirect,
83
+ invalidateCredentials: async (scope) => {
84
+ if (scope === "all" || scope === "tokens") {
85
+ delete session.tokens;
86
+ delete session.expiresAt;
87
+ }
88
+ if (scope === "all" || scope === "client")
89
+ delete session.client;
90
+ if (scope === "all" || scope === "verifier")
91
+ verifier = "";
92
+ await save(url, session);
93
+ }
94
+ };
95
+ }
96
+ async function unlockedLogin(url, openBrowser = true) {
97
+ const state = randomBytes(32).toString("base64url");
98
+ const server = createServer();
99
+ await new Promise((resolve, reject) => {
100
+ server.once("error", reject);
101
+ server.listen(0, "127.0.0.1", resolve);
102
+ });
103
+ const address = server.address();
104
+ if (!address || typeof address === "string")
105
+ throw new Error("Could not bind the login callback.");
106
+ const session = {
107
+ redirectUrl: `http://127.0.0.1:${address.port}/callback`
108
+ };
109
+ const oauth = provider(url, session, (authorizationUrl) => {
110
+ if (authorizationUrl.origin !== url)
111
+ throw new Error("Unexpected authorization server.");
112
+ console.error(`Open this URL to sign in:
113
+ ${authorizationUrl.href}`);
114
+ if (openBrowser)
115
+ openUrl(authorizationUrl.href);
116
+ }, state);
117
+ let timer;
118
+ let rejectCallback;
119
+ const interrupt = () => rejectCallback(new Error("Sign-in paused."));
120
+ try {
121
+ const callback = new Promise((resolve, reject) => {
122
+ rejectCallback = reject;
123
+ timer = setTimeout(() => reject(new Error("Login timed out. Start login again.")), 300000);
124
+ server.on("request", async (request, response) => {
125
+ const callbackUrl = new URL(request.url ?? "/", session.redirectUrl);
126
+ 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;
127
+ if (invalid) {
128
+ response.writeHead(400).end("Invalid login callback.");
129
+ return;
130
+ }
131
+ try {
132
+ if (callbackUrl.searchParams.get("iss")?.replace(/\/$/, "") !== url)
133
+ throw new Error("Unexpected OAuth issuer.");
134
+ const code = callbackUrl.searchParams.get("code");
135
+ if (!code || callbackUrl.searchParams.getAll("code").length !== 1 || callbackUrl.searchParams.has("error"))
136
+ throw new Error("Login was not approved.");
137
+ const result = await auth(oauth, {
138
+ serverUrl: `${url}/mcp`,
139
+ authorizationCode: code,
140
+ fetchFn: fetchFor(url)
141
+ });
142
+ if (result !== "AUTHORIZED")
143
+ throw new Error("Login did not complete.");
144
+ response.writeHead(200, {
145
+ "Content-Type": "text/plain",
146
+ "Cache-Control": "no-store"
147
+ }).end("Signed in. You can close this tab.");
148
+ resolve();
149
+ } catch (error) {
150
+ response.writeHead(400).end("Login failed. Return to your terminal.");
151
+ reject(error);
152
+ }
153
+ });
154
+ });
155
+ process.once("SIGINT", interrupt);
156
+ process.once("SIGTERM", interrupt);
157
+ const authorize = auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
158
+ await Promise.race([authorize.then(() => callback), callback]);
159
+ } finally {
160
+ process.removeListener("SIGINT", interrupt);
161
+ process.removeListener("SIGTERM", interrupt);
162
+ clearTimeout(timer);
163
+ server.closeAllConnections();
164
+ server.close();
165
+ }
166
+ }
167
+ async function unlockedAccessToken(url, forceRefresh = false) {
168
+ if (process.env.DISPOSABL_API_KEY)
169
+ return process.env.DISPOSABL_API_KEY;
170
+ const session = await load(url);
171
+ if (!session.tokens)
172
+ throw new NotAuthenticated("Run disposabl login or set DISPOSABL_API_KEY.");
173
+ if (forceRefresh || !session.expiresAt || Date.now() >= session.expiresAt - 30000) {
174
+ if (!session.client || !session.tokens.refresh_token)
175
+ throw new NotAuthenticated("Session cannot be renewed. Sign in again or start a newly authorized agent run.");
176
+ const oauth = provider(url, session, () => {
177
+ throw new NotAuthenticated("Session expired. Run disposabl login again.");
178
+ });
179
+ await auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
180
+ }
181
+ if (!session.tokens)
182
+ throw new NotAuthenticated("Session expired. Run disposabl login again.");
183
+ return session.tokens.access_token;
184
+ }
185
+ async function unlockedLogout(url) {
186
+ const session = await load(url);
187
+ if (session.tokens) {
188
+ for (const token of [
189
+ session.tokens.refresh_token,
190
+ session.tokens.access_token
191
+ ].filter(Boolean)) {
192
+ const response = await fetchFor(url)(`${url}/mcp/oauth/revoke`, {
193
+ method: "POST",
194
+ body: new URLSearchParams({
195
+ token,
196
+ client_id: session.client?.client_id ?? ""
197
+ })
198
+ });
199
+ if (!response.ok)
200
+ throw new Error("Revocation failed; credentials retained so logout can be retried.");
201
+ }
202
+ }
203
+ await rm(sessionPath(url), { force: true });
204
+ }
205
+ async function withCredentials(url, operation) {
206
+ await mkdir(directory(), { recursive: true, mode: 0o700 });
207
+ const release = await lock(sessionPath(url), {
208
+ realpath: false,
209
+ stale: 1e4,
210
+ retries: { retries: 8, minTimeout: 100, maxTimeout: 1000 }
211
+ });
212
+ try {
213
+ return await operation();
214
+ } finally {
215
+ await release();
216
+ }
217
+ }
218
+ export const login = (url, browser = true) => withCredentials(url, () => unlockedLogin(url, browser));
219
+ export const accessToken = (url, refresh = false) => withCredentials(url, () => unlockedAccessToken(url, refresh));
220
+ export const logout = (url) => withCredentials(url, () => unlockedLogout(url));
221
+ export const hasCredentials = async (url) => Boolean(process.env.DISPOSABL_API_KEY || (await load(url)).tokens?.access_token);
package/client.mjs ADDED
@@ -0,0 +1,65 @@
1
+ import { accessToken, hasCredentials, login, NotAuthenticated } from "./auth.mjs";
2
+ import { sandboxSession } from "./sandbox.mjs";
3
+
4
+ export function apiOrigin(value) {
5
+ const url = URL.parse(value);
6
+ const localhost = url?.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
7
+ if (!url || (url.protocol !== "https:" && !localhost) || url.href !== url.origin + "/") {
8
+ throw new Error("Use an HTTPS API origin, or an HTTP loopback origin for local development.");
9
+ }
10
+ return url.origin;
11
+ }
12
+
13
+ export function providerLink(provider, value) {
14
+ const url = URL.parse(value);
15
+ const expected = provider === "github" ? "https://github.com" : "https://dashboard.convex.dev";
16
+ if (!url || url.origin !== expected || url.username || url.password) throw new Error("Invalid provider authorization link.");
17
+ return url.href;
18
+ }
19
+
20
+ export function createClient(value) {
21
+ const origin = apiOrigin(value);
22
+ const session = sandboxSession();
23
+ const sandbox = !process.env.DISPOSABL_API_KEY && session?.origin === origin;
24
+ async function send(path, options = {}, authenticated) {
25
+ const url = new URL(path, origin);
26
+ if (url.origin !== origin) throw new Error("The request must target the configured API origin.");
27
+ const { timeout = 30_000, signal, ...init } = options;
28
+ const timeoutSignal = AbortSignal.timeout(timeout);
29
+ const fetchSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
30
+ const request = async (refresh = false) => {
31
+ const headers = new Headers(init.headers);
32
+ if (authenticated) {
33
+ const token = sandbox ? session.token : await accessToken(origin, refresh);
34
+ headers.set("Authorization", "Bearer " + token);
35
+ }
36
+ return fetch(url, { ...init, headers, redirect: "error", signal: fetchSignal });
37
+ };
38
+ const response = await request();
39
+ return response.status === 401 && authenticated && !sandbox && !process.env.DISPOSABL_API_KEY
40
+ ? request(true) : response;
41
+ }
42
+
43
+ return {
44
+ origin, sandbox,
45
+ signIn: browser => login(origin, browser),
46
+ async currentUser(options) {
47
+ if (!sandbox && !await hasCredentials(origin)) return null;
48
+ try {
49
+ const response = await send("/api/users/current", options, true);
50
+ if (response.status === 401) return null;
51
+ if (!response.ok) throw new Error("Sign-in status is unavailable (HTTP " + response.status + ").");
52
+ return response.json();
53
+ } catch (error) {
54
+ if (error instanceof NotAuthenticated) return null;
55
+ throw error;
56
+ }
57
+ },
58
+ async request(path, options, authenticated = false) {
59
+ const response = await send(path, options, authenticated);
60
+ const body = await response.json().catch(() => null);
61
+ if (!response.ok) throw new Error(body?.error ?? ("HTTP " + response.status));
62
+ return body;
63
+ },
64
+ };
65
+ }
package/index.mjs ADDED
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { parseEnv } from "node:util";
5
+ import { Command } from "commander";
6
+ import { logout, openUrl } from "./auth.mjs";
7
+ import { apiOrigin, createClient, providerLink } from "./client.mjs";
8
+ import { sandboxSession } from "./sandbox.mjs";
9
+
10
+ const { version } = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
11
+ const program = new Command().name("disposabl").version(version)
12
+ .description("Control a Disposabl app from the command line")
13
+ .option("--origin <url>", "App API origin");
14
+
15
+ function readOptional(file) {
16
+ try {
17
+ return readFileSync(file, "utf8");
18
+ } catch (error) {
19
+ if (error.code === "ENOENT") return null;
20
+ throw error;
21
+ }
22
+ }
23
+
24
+ function targetOrigin() {
25
+ const explicit = program.opts().origin ?? process.env.DISPOSABL_API_ORIGIN;
26
+ if (explicit) return apiOrigin(explicit);
27
+ for (let directory = process.cwd(); ; directory = dirname(directory)) {
28
+ const config = readOptional(join(directory, "disposabl.json"));
29
+ if (config) {
30
+ const local = readOptional(join(directory, "packages/backend/.env.local"));
31
+ const origin = (local && parseEnv(local).CONVEX_SITE_URL) || JSON.parse(config).apiOrigin;
32
+ if (origin) return apiOrigin(origin);
33
+ throw new Error("Start this app with bun run dev or set DISPOSABL_API_ORIGIN.");
34
+ }
35
+ if (directory === dirname(directory)) return apiOrigin(sandboxSession()?.origin ?? "https://www.disposabl.dev");
36
+ }
37
+ }
38
+
39
+ let contractPromise;
40
+ function contract(timeout) {
41
+ return contractPromise ??= (async () => {
42
+ const client = createClient(targetOrigin());
43
+ const spec = await client.request("/openapi.json", { timeout });
44
+ const operations = Object.entries(spec.paths).flatMap(([path, methods]) =>
45
+ ["get", "post"].filter(method => methods[method]).map(method => ({ path, method, ...methods[method] })),
46
+ );
47
+ return { client, authentication: spec["x-disposabl"]?.authentication ?? true, operations };
48
+ })();
49
+ }
50
+
51
+ async function loginStatus() {
52
+ const { client, authentication } = await contract();
53
+ return { authentication, currentUser: authentication ? await client.currentUser() : null };
54
+ }
55
+
56
+ const output = value => console.log(JSON.stringify(value, null, 2));
57
+ const loginCommand = program.command("login").description("Sign in to the target app")
58
+ .option("--no-browser", "Print the sign-in link")
59
+ .action(async ({ browser }) => {
60
+ const { client, authentication } = await contract();
61
+ if (!authentication) return output({ authentication });
62
+ if (client.sandbox) return output(await loginStatus());
63
+ await client.signIn(browser);
64
+ console.error("Signed in.");
65
+ });
66
+ loginCommand.command("status").description("Check the current session")
67
+ .action(async () => output(await loginStatus()));
68
+ program.command("status").description("Check whether the app requires login and report the current user")
69
+ .action(async () => output(await loginStatus()));
70
+ program.command("logout").description("Sign out of the target app").action(async () => {
71
+ const { client, authentication } = await contract();
72
+ if (authentication) await logout(client.origin);
73
+ output({ authentication, currentUser: null });
74
+ });
75
+
76
+ function commandParts(path) {
77
+ if (!/^\/api\/[a-zA-Z0-9_/-]+$/.test(path)) throw new Error("Invalid operation path in OpenAPI.");
78
+ const parts = path.slice(5).split("/");
79
+ if (parts.at(-2) === "index" || parts.at(-2) === "internal") parts.splice(-2, 1);
80
+ return parts;
81
+ }
82
+
83
+ function fields(operation) {
84
+ if (operation.method === "get") {
85
+ return (operation.parameters ?? []).filter(field => field.in === "query").map(field => ({
86
+ name: field.name, required: field.required, jsonEncoded: Boolean(field.content),
87
+ schema: field.schema ?? field.content?.["application/json"]?.schema,
88
+ }));
89
+ }
90
+ const schema = operation.requestBody?.content?.["application/json"]?.schema;
91
+ return Object.entries(schema?.properties ?? {}).map(([name, field]) => ({
92
+ name, schema: field, required: schema.required?.includes(name),
93
+ }));
94
+ }
95
+
96
+ async function call(operation, args) {
97
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
98
+ throw new Error("Operation arguments must be a JSON object.");
99
+ }
100
+ const { client, authentication } = await contract();
101
+ const url = new URL(operation.path, client.origin);
102
+ commandParts(operation.path);
103
+ const parameters = fields(operation);
104
+ for (const name of Object.keys(args)) {
105
+ if (!parameters.some(field => field.name === name)) throw new Error("Unknown argument " + name + ".");
106
+ }
107
+ const options = { method: operation.method.toUpperCase() };
108
+ if (operation.method === "get") {
109
+ for (const field of parameters) {
110
+ if (!(field.name in args)) continue;
111
+ const value = args[field.name];
112
+ url.searchParams.set(field.name, field.jsonEncoded ? JSON.stringify(value) : String(value));
113
+ }
114
+ } else {
115
+ options.headers = { "Content-Type": "application/json" };
116
+ options.body = JSON.stringify(args);
117
+ if (operation.path === "/api/apps/create") options.timeout = 120_000;
118
+ }
119
+
120
+ if (operation.security?.length === 0) return client.request(url, options);
121
+ if (!authentication && !process.env.DISPOSABL_API_KEY) {
122
+ throw new Error("Set DISPOSABL_API_KEY for this user-scoped operation.");
123
+ }
124
+ return client.request(url, options, true);
125
+ }
126
+
127
+ program.command("list").description("List the operations enabled for this app").action(async () => {
128
+ const { operations } = await contract();
129
+ output(operations.map(({ operationId, path, description }) =>
130
+ ({ operationId, command: "disposabl " + commandParts(path).join(" "), description })));
131
+ });
132
+ program.command("call <operationId> [jsonArgs]").description("Call an operation with a JSON object")
133
+ .action(async (id, jsonArgs = "{}") => {
134
+ const operation = (await contract()).operations.find(entry => entry.operationId === id);
135
+ if (!operation) throw new Error("Unknown operation " + id + ". Run disposabl list.");
136
+ output(await call(operation, JSON.parse(jsonArgs)));
137
+ });
138
+
139
+ function addOperation(operation) {
140
+ const parts = commandParts(operation.path);
141
+ const [first] = parts;
142
+ if (["login", "status", "logout", "list", "call", "help"].includes(first)) return;
143
+ let parent = program;
144
+ for (const part of parts.slice(0, -1)) {
145
+ parent = parent.commands.find(command => command.name() === part) ?? parent.command(part);
146
+ }
147
+ const command = parent.command(parts.at(-1)).description(operation.description ?? "");
148
+ const parameters = fields(operation);
149
+ for (const field of parameters) {
150
+ const flag = "--" + field.name + " <value>";
151
+ const description = field.schema?.type === "string" ? field.name : field.name + " as JSON";
152
+ if (field.required) command.requiredOption(flag, description);
153
+ else command.option(flag, description);
154
+ }
155
+ const provider = parts[0] === "connections" && parts[2] === "connect" ? parts[1] : null;
156
+ if (provider) command.option("--no-browser", "Print the provider link");
157
+ command.action(async options => {
158
+ const args = Object.fromEntries(parameters.filter(field => options[field.name] !== undefined)
159
+ .map(field => [field.name, field.schema?.type === "string" ? options[field.name] : JSON.parse(options[field.name])]));
160
+ const response = await call(operation, args);
161
+ if (provider && options.browser) openUrl(providerLink(provider, response?.url));
162
+ output(response);
163
+ });
164
+ }
165
+
166
+ try {
167
+ program.exitOverride();
168
+ const args = process.argv.slice(2);
169
+ const operands = program.parseOptions(args).operands;
170
+ const first = operands[0];
171
+ const help = args.includes("--help") || args.includes("-h") || first === "help";
172
+ const dynamic = first && !["login", "status", "logout", "list", "call", "help"].includes(first);
173
+ if (dynamic || (help && first !== "login") || !args.length) {
174
+ try {
175
+ for (const operation of (await contract(dynamic ? undefined : 2_000)).operations) addOperation(operation);
176
+ } catch (error) {
177
+ if (dynamic) throw error;
178
+ }
179
+ }
180
+ if (!args.length) program.outputHelp();
181
+ else await program.parseAsync(args, { from: "user" });
182
+ } catch (error) {
183
+ if (error.code !== "commander.helpDisplayed" && error.code !== "commander.version") {
184
+ if (!error.code?.startsWith("commander.")) console.error(error.message);
185
+ process.exitCode = error.exitCode ?? 1;
186
+ }
187
+ }
package/package.json CHANGED
@@ -1,45 +1,29 @@
1
1
  {
2
2
  "name": "@disposabl/cli",
3
- "version": "4.0.0",
3
+ "version": "5.0.0",
4
+ "description": "Command-line client for an Exact app's API",
4
5
  "type": "module",
5
- "description": "Command-line access to your Disposabl app",
6
- "license": "MIT",
6
+ "engines": {
7
+ "node": ">=22.12.0"
8
+ },
7
9
  "bin": {
8
- "disposabl": "dist/index.js"
10
+ "disposabl": "./index.mjs"
9
11
  },
10
12
  "files": [
11
- "dist",
13
+ "*.mjs",
12
14
  "README.md"
13
15
  ],
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
- "prepack": "node dist/verify-metadata.mjs"
26
- },
27
16
  "dependencies": {
28
17
  "@modelcontextprotocol/sdk": "1.32.2",
29
18
  "commander": "15.0.0",
30
19
  "proper-lockfile": "4.1.2"
31
20
  },
32
- "devDependencies": {
33
- "@types/bun": "1.4.4",
34
- "typescript": "~6.0.3",
35
- "@types/proper-lockfile": "4.1.4",
36
- "semantic-release": "25.0.9",
37
- "@semantic-release/exec": "7.1.0",
38
- "conventional-changelog-conventionalcommits": "9.3.1"
21
+ "publishConfig": {
22
+ "access": "public"
39
23
  },
40
24
  "repository": {
41
25
  "type": "git",
42
- "url": "git+https://github.com/disposabl-dev/create-disposabl-app.git",
26
+ "url": "git+https://github.com/disposabl-dev/disposabl-exact.git",
43
27
  "directory": "packages/cli"
44
28
  }
45
29
  }
package/sandbox.mjs ADDED
@@ -0,0 +1,13 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export function sandboxSession() {
4
+ if (process.platform !== "linux") return null;
5
+ try {
6
+ const { origin, token, expiresAt } = JSON.parse(readFileSync("/dev/shm/disposabl/session.json", "utf8"));
7
+ if (typeof origin !== "string" || !Number.isFinite(expiresAt) || Date.now() >= expiresAt || !/^dsp_sandbox_[a-f0-9]{64}$/.test(token)) return null;
8
+ return { origin, token };
9
+ } catch (error) {
10
+ if (error.code === "ENOENT") return null;
11
+ throw error;
12
+ }
13
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Disposabl
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.