filecafe 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +128 -2
  2. package/dist/cli.js +1043 -0
  3. package/package.json +36 -4
package/README.md CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # filecafe
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
+ Upload files to [file.cafe](https://file.cafe) from the command line and get share links back.
4
+
5
+ Built for AI coding agents (Claude Code, Codex, Cursor), humans, and CI: share URLs go to stdout, progress and errors go to stderr, `--json` gives machine-readable results, and nothing ever prompts (except the one-time browser login).
6
+
7
+ ## Install
8
+
9
+ Run it without installing:
10
+
11
+ ```sh
12
+ npx filecafe upload report.pdf
13
+ ```
14
+
15
+ Or install it globally:
16
+
17
+ ```sh
18
+ npm i -g filecafe
19
+ filecafe --help
20
+ ```
21
+
22
+ Requires Node.js 20 or newer.
23
+
24
+ ## Log in
25
+
26
+ ```sh
27
+ filecafe login
28
+ ```
29
+
30
+ This opens your browser so you can approve the CLI on file.cafe. The token is saved to `~/.config/filecafe/config.json` (or `$XDG_CONFIG_HOME/filecafe/config.json`; `%APPDATA%\filecafe\config.json` on Windows) with owner-only permissions.
31
+
32
+ Headless machines and CI can use an existing token instead:
33
+
34
+ ```sh
35
+ echo "$FILECAFE_TOKEN" | filecafe login --with-token # validate and save
36
+ # ...or skip saving entirely and just set FILECAFE_TOKEN for each run
37
+ ```
38
+
39
+ Other account commands:
40
+
41
+ ```sh
42
+ filecafe whoami # Logged in to https://file.cafe as Ada (ada@example.com)
43
+ filecafe whoami --json # {"name":"Ada","email":"ada@example.com","url":"https://file.cafe","token_source":"config"}
44
+ filecafe logout # revoke the saved token on file.cafe and delete it locally
45
+ ```
46
+
47
+ Saved logins never expire. They last until you run `filecafe logout` or revoke the token in
48
+ Settings → API tokens on file.cafe. `logout` revokes the token even if you saved it with
49
+ `filecafe login --token`, so don't log out with a token that CI or another machine still uses.
50
+
51
+ ## Upload
52
+
53
+ ```sh
54
+ filecafe upload screenshot.png # prints the share URL
55
+ filecafe upload a.png b.mp4 notes.txt # one URL per line, in order
56
+ filecafe upload build.zip | pbcopy # copy the link to the clipboard
57
+ filecafe upload video.mp4 --collection <uuid> # add to a collection
58
+ filecafe upload report.pdf --json # machine-readable output
59
+ filecafe upload big.mov --quiet # no progress output
60
+ ```
61
+
62
+ Files are uploaded one after another; large files (over 64 MiB) are split into parts that upload in parallel. Every input is checked before anything is uploaded: if any path is missing or is not a regular file, nothing is uploaded.
63
+
64
+ ### `--json` output
65
+
66
+ A single JSON array on stdout with one object per input file, in the order given:
67
+
68
+ ```json
69
+ [
70
+ {
71
+ "file": "report.pdf",
72
+ "ok": true,
73
+ "id": "9d3c3f8e-5a8b-4c1e-9f0a-2b7d6e4c1a90",
74
+ "filename": "report.pdf",
75
+ "size": 482113,
76
+ "url": "https://file.cafe/...",
77
+ "password_protected": false
78
+ },
79
+ {
80
+ "file": "missing.png",
81
+ "ok": false,
82
+ "error": "No such file."
83
+ }
84
+ ]
85
+ ```
86
+
87
+ The exit code is `0` if every file uploaded and `1` if any failed.
88
+
89
+ ## Configuration
90
+
91
+ | Setting | How to set | Default |
92
+ | --- | --- | --- |
93
+ | Site URL | `--url <url>`, then `FILECAFE_URL`, then the URL you logged in to | `https://file.cafe` |
94
+ | API token | `FILECAFE_TOKEN`, then the token saved by `filecafe login` | none |
95
+
96
+ A saved token is only ever sent to the site it was issued for. To work against another server (for example a local development site), log in to it explicitly: `filecafe login --url http://file-cafe.test`.
97
+
98
+ Set `FILECAFE_DEBUG=1` to print stack traces for unexpected errors.
99
+
100
+ ## Using file.cafe with AI agents
101
+
102
+ Paste this into your project's `CLAUDE.md`, `AGENTS.md`, or Cursor rules:
103
+
104
+ ```markdown
105
+ ## Sharing files
106
+
107
+ To share a file with the user (screenshots, build artifacts, logs, exports), run:
108
+
109
+ npx -y filecafe upload <path> --json
110
+
111
+ and give the user the `url` from the JSON output. Upload several files at once by passing
112
+ multiple paths. If the command fails with "Not logged in", ask the user to run
113
+ `npx filecafe login` (or set `FILECAFE_TOKEN`) and then try again.
114
+ ```
115
+
116
+ Agents can run `filecafe --help` and `filecafe upload --help` to see every option with examples.
117
+
118
+ ## Development
119
+
120
+ ```sh
121
+ npm install
122
+ npm run typecheck
123
+ npm test # node:test, runs the TypeScript sources directly (Node 24)
124
+ npm run build # bundles to dist/cli.js with tsdown
125
+ node dist/cli.js --help
126
+ npm run dev -- --url http://file-cafe.test whoami # run from source
127
+ ```
128
+
129
+ Releases are published to npm from GitHub Actions when a `v*` tag is pushed (npm trusted publishing with provenance). Bump `version` in `package.json` to match the tag first.
package/dist/cli.js ADDED
@@ -0,0 +1,1043 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { homedir, hostname } from "node:os";
4
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, extname, join } from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
8
+ import { randomBytes, timingSafeEqual } from "node:crypto";
9
+ import { createServer } from "node:http";
10
+ import { openAsBlob } from "node:fs";
11
+ // src/api.ts
12
+ const LOGIN_HINT = "Run \"filecafe login\" or set FILECAFE_TOKEN.";
13
+ var ApiError = class extends Error {
14
+ /** HTTP status, or null for network-level failures. */
15
+ status;
16
+ constructor(message, status) {
17
+ super(message);
18
+ this.name = "ApiError";
19
+ this.status = status;
20
+ }
21
+ /** Errors that will fail every subsequent request too (bad token, unverified account). */
22
+ get isFatal() {
23
+ return this.status === 401 || this.status === 403;
24
+ }
25
+ };
26
+ const MAX_RETRY_AFTER_SECONDS = 120;
27
+ /** Parse a Retry-After header (delta-seconds or HTTP date) into milliseconds. */
28
+ function parseRetryAfter(value, now = Date.now()) {
29
+ if (!value) return null;
30
+ const trimmed = value.trim();
31
+ if (/^\d+$/.test(trimmed)) return Math.min(Number(trimmed), MAX_RETRY_AFTER_SECONDS) * 1e3;
32
+ const date = Date.parse(trimmed);
33
+ if (Number.isNaN(date)) return null;
34
+ return Math.min(Math.max(date - now, 0), MAX_RETRY_AFTER_SECONDS * 1e3);
35
+ }
36
+ function messageFrom(body) {
37
+ if (body && typeof body === "object" && "message" in body && typeof body.message === "string" && body.message) return body.message;
38
+ return null;
39
+ }
40
+ /** Build the user-facing message for a failed API response. */
41
+ function apiErrorMessage(status, body) {
42
+ const message = messageFrom(body);
43
+ switch (status) {
44
+ case 401: return `Authentication failed: your token is missing, invalid, or revoked. ${LOGIN_HINT}`;
45
+ case 403: return message ?? "This action is not allowed for your account.";
46
+ case 404: return message && message !== "Not Found." ? message : "Not found. Check the --url option and the IDs you passed.";
47
+ case 422: {
48
+ const errors = body && typeof body === "object" && "errors" in body && body.errors && typeof body.errors === "object" ? body.errors : {};
49
+ const firstMessages = Object.values(errors).map((value) => Array.isArray(value) ? value[0] : value).filter((value) => typeof value === "string" && value.length > 0);
50
+ if (firstMessages.length > 0) return firstMessages.join(" ");
51
+ return message ?? "The request was invalid.";
52
+ }
53
+ case 429: return message ?? "Too many requests. Please wait a minute and try again.";
54
+ case 503: return message ?? "file.cafe is temporarily unavailable. Please try again later.";
55
+ default: return message ? `${message} (HTTP ${status})` : `Request failed with HTTP ${status}.`;
56
+ }
57
+ }
58
+ function describeNetworkError(error) {
59
+ if (error instanceof Error) {
60
+ if (error.name === "TimeoutError" || error.name === "AbortError") return "the request timed out";
61
+ const cause = error.cause;
62
+ if (cause && typeof cause === "object") {
63
+ const code = "code" in cause && typeof cause.code === "string" ? cause.code : null;
64
+ const causeMessage = "message" in cause && typeof cause.message === "string" ? cause.message : null;
65
+ return code ?? causeMessage ?? error.message;
66
+ }
67
+ return error.message;
68
+ }
69
+ return String(error);
70
+ }
71
+ function createApiClient(options) {
72
+ const { baseUrl, token, fetch, sleep, userAgent, onNotice, maxRateLimitRetries = 3, maxNetworkRetries = 3, timeoutMs = 6e4 } = options;
73
+ async function request(method, path, body, requestOptions = {}) {
74
+ const url = `${baseUrl}${path}`;
75
+ let rateLimitRetries = 0;
76
+ let networkRetries = 0;
77
+ for (;;) {
78
+ const headers = {
79
+ Accept: "application/json",
80
+ Authorization: `Bearer ${token}`,
81
+ "User-Agent": userAgent
82
+ };
83
+ if (body !== void 0) headers["Content-Type"] = "application/json";
84
+ let response;
85
+ try {
86
+ response = await fetch(url, {
87
+ method,
88
+ headers,
89
+ body: body === void 0 ? void 0 : JSON.stringify(body),
90
+ redirect: "manual",
91
+ signal: AbortSignal.timeout(timeoutMs)
92
+ });
93
+ } catch (error) {
94
+ if (requestOptions.idempotent && networkRetries < maxNetworkRetries) {
95
+ networkRetries++;
96
+ await sleep(1e3 * 2 ** (networkRetries - 1));
97
+ continue;
98
+ }
99
+ throw new ApiError(`Could not reach ${baseUrl} (${describeNetworkError(error)}).`, null);
100
+ }
101
+ if (response.status >= 300 && response.status < 400) {
102
+ const location = response.headers.get("Location");
103
+ await response.body?.cancel();
104
+ throw new ApiError(`${url} redirected to ${location ?? "another location"}. Check the --url option / FILECAFE_URL (e.g. use https:// instead of http://).`, response.status);
105
+ }
106
+ const text = await response.text();
107
+ let json = null;
108
+ if (text) try {
109
+ json = JSON.parse(text);
110
+ } catch {
111
+ json = null;
112
+ }
113
+ if (response.status === 429 && rateLimitRetries < maxRateLimitRetries) {
114
+ rateLimitRetries++;
115
+ const waitMs = parseRetryAfter(response.headers.get("Retry-After")) ?? 5e3 * rateLimitRetries;
116
+ onNotice?.(`Rate limited by ${baseUrl}; retrying in ${Math.ceil(waitMs / 1e3)}s...`);
117
+ await sleep(waitMs);
118
+ continue;
119
+ }
120
+ if (requestOptions.idempotent && (response.status === 502 || response.status === 504) && networkRetries < maxNetworkRetries) {
121
+ networkRetries++;
122
+ await sleep(1e3 * 2 ** (networkRetries - 1));
123
+ continue;
124
+ }
125
+ if (!response.ok) throw new ApiError(apiErrorMessage(response.status, json), response.status);
126
+ if (response.status === 204) return;
127
+ if (json && typeof json === "object" && "data" in json) return json.data;
128
+ throw new ApiError(`Unexpected response from ${url} (HTTP ${response.status}, not file.cafe API JSON). Check the --url option / FILECAFE_URL.`, response.status);
129
+ }
130
+ }
131
+ return {
132
+ baseUrl,
133
+ request
134
+ };
135
+ }
136
+ async function fetchMe(client) {
137
+ const me = await client.request("GET", "/api/v1/me", void 0, { idempotent: true });
138
+ if (!me || typeof me.email !== "string") throw new ApiError("Unexpected response from /api/v1/me.", null);
139
+ return {
140
+ name: typeof me.name === "string" ? me.name : "",
141
+ email: me.email
142
+ };
143
+ }
144
+ /**
145
+ * Location of the config file:
146
+ * - Windows: %APPDATA%\filecafe\config.json
147
+ * - Elsewhere: $XDG_CONFIG_HOME/filecafe/config.json, falling back to ~/.config/filecafe/config.json
148
+ */
149
+ function configPath({ env, platform, homedir }) {
150
+ if (platform === "win32") {
151
+ const appData = env.APPDATA || join(homedir, "AppData", "Roaming");
152
+ return join(appData, "filecafe", "config.json");
153
+ }
154
+ const xdg = env.XDG_CONFIG_HOME;
155
+ const base = xdg && xdg.startsWith("/") ? xdg : join(homedir, ".config");
156
+ return join(base, "filecafe", "config.json");
157
+ }
158
+ /** Validate and normalize a base URL (http/https only, no trailing slash). */
159
+ function normalizeBaseUrl(value) {
160
+ let url;
161
+ try {
162
+ url = new URL(value.trim());
163
+ } catch {
164
+ throw new Error(`Invalid URL "${value}". Expected something like https://file.cafe`);
165
+ }
166
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`Invalid URL "${value}". Only http:// and https:// URLs are supported.`);
167
+ if (url.username || url.password || url.search || url.hash) throw new Error(`Invalid URL "${value}". Pass only the site address, e.g. https://file.cafe`);
168
+ return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
169
+ }
170
+ async function readConfig(environment) {
171
+ let raw;
172
+ try {
173
+ raw = await readFile(configPath(environment), "utf8");
174
+ } catch (error) {
175
+ if (error.code === "ENOENT") return null;
176
+ throw error;
177
+ }
178
+ try {
179
+ const parsed = JSON.parse(raw);
180
+ if (typeof parsed.url === "string" && typeof parsed.token === "string" && parsed.token) return {
181
+ url: normalizeBaseUrl(parsed.url),
182
+ token: parsed.token
183
+ };
184
+ } catch {}
185
+ return null;
186
+ }
187
+ /** Write the config file atomically with owner-only permissions (dir 0700, file 0600). */
188
+ async function writeConfig(environment, config) {
189
+ const path = configPath(environment);
190
+ const directory = dirname(path);
191
+ await mkdir(directory, {
192
+ recursive: true,
193
+ mode: 448
194
+ });
195
+ if (environment.platform !== "win32") await chmod(directory, 448);
196
+ const temporary = `${path}.${process.pid}.tmp`;
197
+ const contents = `${JSON.stringify({
198
+ url: config.url,
199
+ token: config.token
200
+ }, null, 2)}\n`;
201
+ await writeFile(temporary, contents, { mode: 384 });
202
+ await rename(temporary, path);
203
+ if (environment.platform !== "win32") await chmod(path, 384);
204
+ return path;
205
+ }
206
+ /** Delete the saved config. Returns true if a file was removed. */
207
+ async function deleteConfig(environment) {
208
+ const path = configPath(environment);
209
+ try {
210
+ await rm(path);
211
+ return true;
212
+ } catch (error) {
213
+ if (error.code === "ENOENT") return false;
214
+ throw error;
215
+ }
216
+ }
217
+ /**
218
+ * Resolve the base URL and token.
219
+ *
220
+ * Base URL: --url, then FILECAFE_URL, then the URL saved by `filecafe login`, then https://file.cafe.
221
+ * Token: FILECAFE_TOKEN, then the saved token — but the saved token is only used when it was
222
+ * issued for the resolved base URL, so a token is never sent to a different site.
223
+ */
224
+ async function resolveSettings(environment, urlOption) {
225
+ const saved = await readConfig(environment);
226
+ const baseUrl = normalizeBaseUrl(urlOption || environment.env.FILECAFE_URL || saved?.url || "https://file.cafe");
227
+ const envToken = environment.env.FILECAFE_TOKEN?.trim();
228
+ if (envToken) return {
229
+ baseUrl,
230
+ token: envToken,
231
+ tokenSource: "env",
232
+ saved
233
+ };
234
+ if (saved && saved.url === baseUrl) return {
235
+ baseUrl,
236
+ token: saved.token,
237
+ tokenSource: "config",
238
+ saved
239
+ };
240
+ return {
241
+ baseUrl,
242
+ token: null,
243
+ tokenSource: null,
244
+ saved
245
+ };
246
+ }
247
+ // src/version.ts
248
+ const VERSION = "0.1.0";
249
+ // src/context.ts
250
+ /** Open a URL in the default browser without ever throwing. */
251
+ function openBrowser(url, platform = process.platform) {
252
+ try {
253
+ const [command, args, extra] = platform === "darwin" ? [
254
+ "open",
255
+ [url],
256
+ {}
257
+ ] : platform === "win32" ? [
258
+ "cmd",
259
+ [
260
+ "/c",
261
+ "start",
262
+ "\"\"",
263
+ url.replace(/&/g, "^&")
264
+ ],
265
+ { windowsVerbatimArguments: true }
266
+ ] : [
267
+ "xdg-open",
268
+ [url],
269
+ {}
270
+ ];
271
+ const child = spawn(command, args, {
272
+ stdio: "ignore",
273
+ detached: true,
274
+ ...extra
275
+ });
276
+ child.on("error", () => {});
277
+ child.unref();
278
+ } catch {}
279
+ }
280
+ function createDefaultContext() {
281
+ return {
282
+ env: process.env,
283
+ platform: process.platform,
284
+ homedir: homedir(),
285
+ fetch: (input, init) => fetch(input, init),
286
+ sleep: (ms) => setTimeout$1(ms),
287
+ stdout: process.stdout,
288
+ stderr: process.stderr,
289
+ stdin: process.stdin,
290
+ openBrowser: (url) => openBrowser(url),
291
+ userAgent: `filecafe-cli/${VERSION} node/${process.versions.node} (${process.platform})`
292
+ };
293
+ }
294
+ /** Thrown for expected failures; the message is printed as-is and the process exits with code 1. */
295
+ var CliError = class extends Error {
296
+ constructor(message) {
297
+ super(message);
298
+ this.name = "CliError";
299
+ }
300
+ };
301
+ // src/login-server.ts
302
+ const LOGIN_TIMEOUT_MS = 3e5;
303
+ function generateState() {
304
+ return randomBytes(16).toString("hex");
305
+ }
306
+ function statesMatch(received, expected) {
307
+ if (received === null) return false;
308
+ const a = Buffer.from(received, "utf8");
309
+ const b = Buffer.from(expected, "utf8");
310
+ return a.length === b.length && timingSafeEqual(a, b);
311
+ }
312
+ function page(title, message) {
313
+ return `<!doctype html>
314
+ <html lang="en">
315
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${title}</title>
316
+ <style>body{font-family:system-ui,-apple-system,sans-serif;display:flex;min-height:100vh;margin:0;align-items:center;justify-content:center;background:#faf9f7;color:#1c1917}main{max-width:28rem;padding:2rem;text-align:center}h1{font-size:1.25rem}p{color:#57534e}</style>
317
+ </head>
318
+ <body><main><h1>${title}</h1><p>${message}</p></main></body>
319
+ </html>
320
+ `;
321
+ }
322
+ const SUCCESS_PAGE = page("You're logged in to file.cafe.", "You can close this tab and return to your terminal.");
323
+ const DENIED_PAGE = page("Login cancelled.", "The file.cafe CLI was not authorized. You can close this tab.");
324
+ const FAILED_PAGE = page("Login failed.", "Something went wrong. Return to your terminal and run \"filecafe login\" again.");
325
+ const INVALID_PAGE = page("Invalid login request.", "This link does not match the login started in your terminal. Run \"filecafe login\" again.");
326
+ /**
327
+ * Decide how to answer a request to the local callback server. Only
328
+ * `GET /callback` with the expected `state` concludes the login; anything
329
+ * else is rejected and the server keeps waiting.
330
+ */
331
+ function handleCallbackRequest(method, rawUrl, expectedState) {
332
+ const url = new URL(rawUrl ?? "/", "http://127.0.0.1");
333
+ if (method !== "GET" || url.pathname !== "/callback") return {
334
+ status: 404,
335
+ body: page("Not found.", "Nothing to see here.")
336
+ };
337
+ if (!statesMatch(url.searchParams.get("state"), expectedState)) return {
338
+ status: 400,
339
+ body: INVALID_PAGE
340
+ };
341
+ const error = url.searchParams.get("error");
342
+ if (error) return {
343
+ status: 200,
344
+ body: error === "access_denied" ? DENIED_PAGE : FAILED_PAGE,
345
+ result: { error }
346
+ };
347
+ const token = url.searchParams.get("token");
348
+ if (!token) return {
349
+ status: 400,
350
+ body: FAILED_PAGE
351
+ };
352
+ return {
353
+ status: 200,
354
+ body: SUCCESS_PAGE,
355
+ result: { token }
356
+ };
357
+ }
358
+ /** Listen on a random loopback port for the browser redirect. */
359
+ function startCallbackServer(state, timeoutMs = LOGIN_TIMEOUT_MS) {
360
+ let settle = () => {};
361
+ let fail = () => {};
362
+ let settled = false;
363
+ const result = new Promise((resolve, reject) => {
364
+ settle = resolve;
365
+ fail = reject;
366
+ });
367
+ const server = createServer((request, response) => {
368
+ const outcome = handleCallbackRequest(request.method, request.url, state);
369
+ response.writeHead(outcome.status, {
370
+ "Content-Type": "text/html; charset=utf-8",
371
+ "Cache-Control": "no-store",
372
+ "Referrer-Policy": "no-referrer",
373
+ Connection: "close"
374
+ });
375
+ response.end(outcome.body);
376
+ if (outcome.result && !settled) {
377
+ const loginResult = outcome.result;
378
+ response.on("finish", () => finish(() => settle(loginResult)));
379
+ }
380
+ });
381
+ let timer;
382
+ const close = () => {
383
+ clearTimeout(timer);
384
+ server.close();
385
+ server.closeAllConnections();
386
+ };
387
+ const finish = (callback) => {
388
+ if (settled) return;
389
+ settled = true;
390
+ close();
391
+ callback();
392
+ };
393
+ return new Promise((resolve, reject) => {
394
+ server.once("error", reject);
395
+ server.listen(0, "127.0.0.1", () => {
396
+ const address = server.address();
397
+ if (!address || typeof address === "string") {
398
+ close();
399
+ reject(/* @__PURE__ */ new Error("Could not start the local login server."));
400
+ return;
401
+ }
402
+ timer = setTimeout(() => finish(() => fail(/* @__PURE__ */ new Error("Timed out waiting for the browser login (5 minutes). Run \"filecafe login\" again, or use \"filecafe login --token <token>\"."))), timeoutMs);
403
+ resolve({
404
+ port: address.port,
405
+ result,
406
+ close: () => finish(() => fail(/* @__PURE__ */ new Error("Login cancelled.")))
407
+ });
408
+ });
409
+ });
410
+ }
411
+ // src/session.ts
412
+ const NOT_LOGGED_IN = "Not logged in. Run \"filecafe login\" or set FILECAFE_TOKEN.";
413
+ function clientFor(context, baseUrl, token, onNotice) {
414
+ return createApiClient({
415
+ baseUrl,
416
+ token,
417
+ fetch: context.fetch,
418
+ sleep: context.sleep,
419
+ userAgent: context.userAgent,
420
+ onNotice
421
+ });
422
+ }
423
+ /** Resolve the base URL and token, failing with a helpful message when not logged in. */
424
+ async function requireSession(context, globals, onNotice) {
425
+ let settings;
426
+ try {
427
+ settings = await resolveSettings(context, globals.url);
428
+ } catch (error) {
429
+ throw new CliError(error.message);
430
+ }
431
+ const { token } = settings;
432
+ if (!token) {
433
+ if (settings.saved && settings.saved.url !== settings.baseUrl) throw new CliError(`Not logged in to ${settings.baseUrl} (the saved login is for ${settings.saved.url}). Run "filecafe login --url ${settings.baseUrl}" or set FILECAFE_TOKEN.`);
434
+ throw new CliError(NOT_LOGGED_IN);
435
+ }
436
+ return {
437
+ client: clientFor(context, settings.baseUrl, token, onNotice),
438
+ settings: {
439
+ ...settings,
440
+ token
441
+ }
442
+ };
443
+ }
444
+ // src/commands/login.ts
445
+ async function readAll(input) {
446
+ let text = "";
447
+ for await (const chunk of input) text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
448
+ return text;
449
+ }
450
+ function authorizeUrl(baseUrl, port, state, name) {
451
+ return `${baseUrl}/cli/authorize?port=${port}&state=${state}&name=${encodeURIComponent(name)}`;
452
+ }
453
+ async function tokenFromBrowser(context, baseUrl, timeoutMs) {
454
+ const state = generateState();
455
+ const server = await startCallbackServer(state, timeoutMs);
456
+ const url = authorizeUrl(baseUrl, server.port, state, hostname());
457
+ context.stderr.write(`Opening your browser to log in to ${baseUrl}.\n`);
458
+ context.stderr.write(`If it does not open, visit this URL on this machine:\n\n ${url}\n\nWaiting for approval...\n`);
459
+ context.openBrowser(url);
460
+ const result = await server.result;
461
+ if ("error" in result) throw new CliError(result.error === "access_denied" ? "Login was cancelled in the browser." : `Login failed in the browser (${result.error}).`);
462
+ return result.token;
463
+ }
464
+ async function loginCommand(options, globals, context) {
465
+ if (options.token !== void 0 && options.withToken) throw new CliError("Use either --token <token> or --with-token, not both.");
466
+ let baseUrl;
467
+ try {
468
+ baseUrl = normalizeBaseUrl(globals.url || context.env.FILECAFE_URL || "https://file.cafe");
469
+ } catch (error) {
470
+ throw new CliError(error.message);
471
+ }
472
+ let token;
473
+ if (options.token !== void 0) token = options.token.trim();
474
+ else if (options.withToken) {
475
+ if (context.stdin.isTTY) throw new CliError("--with-token reads the token from standard input, e.g.: echo \"$TOKEN\" | filecafe login --with-token");
476
+ token = (await readAll(context.stdin)).trim();
477
+ } else token = await tokenFromBrowser(context, baseUrl, options.timeoutMs ?? 3e5);
478
+ if (!token || /\s/.test(token)) throw new CliError("The token is empty or malformed.");
479
+ let me;
480
+ try {
481
+ me = await fetchMe(clientFor(context, baseUrl, token));
482
+ } catch (error) {
483
+ if (error.status === 401) throw new CliError(`That token was rejected by ${baseUrl}. Check that it is correct and has not been revoked.`);
484
+ throw new CliError(error.message);
485
+ }
486
+ await writeConfig(context, {
487
+ url: baseUrl,
488
+ token
489
+ });
490
+ context.stdout.write(`Logged in as ${me.name} (${me.email})\n`);
491
+ context.stderr.write(`Saved credentials for ${baseUrl} to ${configPath(context)}\n`);
492
+ if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write("Note: FILECAFE_TOKEN is set in your environment and takes precedence over the saved login.\n");
493
+ return 0;
494
+ }
495
+ // src/commands/logout.ts
496
+ async function logoutCommand(context) {
497
+ const saved = await readConfig(context).catch(() => null);
498
+ if (saved) try {
499
+ await clientFor(context, saved.url, saved.token).request("DELETE", "/api/v1/token", void 0, { idempotent: true });
500
+ } catch (error) {
501
+ if (!(error instanceof ApiError && error.status === 401)) context.stderr.write(`Could not revoke the token on ${saved.url}: ${error.message}\nIt may still be active; revoke it in Settings → API tokens.\n`);
502
+ }
503
+ if (await deleteConfig(context)) {
504
+ context.stdout.write(saved ? `Logged out of ${saved.url}.\n` : "Logged out.\n");
505
+ context.stderr.write(`Removed ${configPath(context)}\n`);
506
+ } else context.stdout.write("Not logged in; nothing to do.\n");
507
+ if (context.env.FILECAFE_TOKEN?.trim()) context.stderr.write("Note: FILECAFE_TOKEN is still set in your environment; unset it to stop using that token.\n");
508
+ return 0;
509
+ }
510
+ // src/mime.ts
511
+ /**
512
+ * A deliberately small extension → MIME type map. The server re-detects the
513
+ * real type from the uploaded bytes, so this only needs to be plausible.
514
+ */
515
+ const MIME_TYPES = {
516
+ png: "image/png",
517
+ jpg: "image/jpeg",
518
+ jpeg: "image/jpeg",
519
+ gif: "image/gif",
520
+ webp: "image/webp",
521
+ avif: "image/avif",
522
+ heic: "image/heic",
523
+ heif: "image/heif",
524
+ bmp: "image/bmp",
525
+ tif: "image/tiff",
526
+ tiff: "image/tiff",
527
+ ico: "image/vnd.microsoft.icon",
528
+ svg: "image/svg+xml",
529
+ psd: "image/vnd.adobe.photoshop",
530
+ mp4: "video/mp4",
531
+ m4v: "video/x-m4v",
532
+ mov: "video/quicktime",
533
+ webm: "video/webm",
534
+ mkv: "video/x-matroska",
535
+ avi: "video/x-msvideo",
536
+ wmv: "video/x-ms-wmv",
537
+ mpeg: "video/mpeg",
538
+ mpg: "video/mpeg",
539
+ "3gp": "video/3gpp",
540
+ mp3: "audio/mpeg",
541
+ wav: "audio/wav",
542
+ ogg: "audio/ogg",
543
+ oga: "audio/ogg",
544
+ opus: "audio/opus",
545
+ flac: "audio/flac",
546
+ aac: "audio/aac",
547
+ m4a: "audio/mp4",
548
+ weba: "audio/webm",
549
+ aiff: "audio/aiff",
550
+ mid: "audio/midi",
551
+ midi: "audio/midi",
552
+ pdf: "application/pdf",
553
+ doc: "application/msword",
554
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
555
+ xls: "application/vnd.ms-excel",
556
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
557
+ ppt: "application/vnd.ms-powerpoint",
558
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
559
+ odt: "application/vnd.oasis.opendocument.text",
560
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
561
+ odp: "application/vnd.oasis.opendocument.presentation",
562
+ rtf: "application/rtf",
563
+ epub: "application/epub+zip",
564
+ key: "application/vnd.apple.keynote",
565
+ pages: "application/vnd.apple.pages",
566
+ numbers: "application/vnd.apple.numbers",
567
+ zip: "application/zip",
568
+ gz: "application/gzip",
569
+ tgz: "application/gzip",
570
+ tar: "application/x-tar",
571
+ bz2: "application/x-bzip2",
572
+ xz: "application/x-xz",
573
+ "7z": "application/x-7z-compressed",
574
+ rar: "application/vnd.rar",
575
+ zst: "application/zstd",
576
+ dmg: "application/x-apple-diskimage",
577
+ iso: "application/x-iso9660-image",
578
+ apk: "application/vnd.android.package-archive",
579
+ wasm: "application/wasm",
580
+ woff: "font/woff",
581
+ woff2: "font/woff2",
582
+ ttf: "font/ttf",
583
+ otf: "font/otf",
584
+ txt: "text/plain",
585
+ log: "text/plain",
586
+ md: "text/markdown",
587
+ markdown: "text/markdown",
588
+ csv: "text/csv",
589
+ tsv: "text/tab-separated-values",
590
+ html: "text/html",
591
+ htm: "text/html",
592
+ css: "text/css",
593
+ xml: "application/xml",
594
+ json: "application/json",
595
+ jsonl: "application/jsonl",
596
+ ndjson: "application/x-ndjson",
597
+ yaml: "application/yaml",
598
+ yml: "application/yaml",
599
+ toml: "application/toml",
600
+ ini: "text/plain",
601
+ js: "text/javascript",
602
+ mjs: "text/javascript",
603
+ cjs: "text/javascript",
604
+ jsx: "text/javascript",
605
+ ts: "text/x-typescript",
606
+ tsx: "text/x-typescript",
607
+ py: "text/x-python",
608
+ rb: "text/x-ruby",
609
+ php: "text/x-php",
610
+ go: "text/x-go",
611
+ rs: "text/x-rust",
612
+ java: "text/x-java",
613
+ kt: "text/x-kotlin",
614
+ swift: "text/x-swift",
615
+ c: "text/x-c",
616
+ h: "text/x-c",
617
+ cc: "text/x-c++",
618
+ cpp: "text/x-c++",
619
+ hpp: "text/x-c++",
620
+ cs: "text/x-csharp",
621
+ sh: "application/x-sh",
622
+ bash: "application/x-sh",
623
+ zsh: "application/x-sh",
624
+ sql: "application/sql",
625
+ diff: "text/x-diff",
626
+ patch: "text/x-diff",
627
+ vtt: "text/vtt",
628
+ srt: "application/x-subrip",
629
+ ics: "text/calendar"
630
+ };
631
+ /** Guess a MIME type from a file name's extension. */
632
+ function guessMimeType(filename) {
633
+ const extension = extname(filename).slice(1).toLowerCase();
634
+ return extension && MIME_TYPES[extension] || "application/octet-stream";
635
+ }
636
+ // src/upload.ts
637
+ /** An error while transferring bytes to the upload server. */
638
+ var TransferError = class extends Error {
639
+ status;
640
+ /** The upload must be started again from scratch (e.g. the receipt for a written object was lost). */
641
+ restartUpload;
642
+ constructor(message, status, restartUpload = false) {
643
+ super(message);
644
+ this.name = "TransferError";
645
+ this.status = status;
646
+ this.restartUpload = restartUpload;
647
+ }
648
+ };
649
+ const DEFAULT_CONCURRENCY = 4;
650
+ const DEFAULT_PART_RETRIES = 3;
651
+ const DEFAULT_PART_TIMEOUT_MS = 9e5;
652
+ function isRecord(value) {
653
+ return typeof value === "object" && value !== null && !Array.isArray(value);
654
+ }
655
+ function isSignedTarget(value) {
656
+ return isRecord(value) && typeof value.url === "string" && isRecord(value.headers) && Object.values(value.headers).every((header) => typeof header === "string");
657
+ }
658
+ /** Validate the start response and turn it into a list of byte ranges to PUT. */
659
+ function planTransfer(upload, size) {
660
+ const unexpected = (detail) => new ApiError(`Unexpected response when starting the upload: ${detail}.`, null);
661
+ const data = upload;
662
+ if (!isRecord(data) || typeof data.id !== "string" || typeof data.token !== "string") throw unexpected("missing id or token");
663
+ if ("parts" in data) {
664
+ const { parts, part_size: partSize } = data;
665
+ if (typeof partSize !== "number" || !Number.isSafeInteger(partSize) || partSize <= 0) throw unexpected("invalid part_size");
666
+ if (!Array.isArray(parts) || !parts.every(isSignedTarget)) throw unexpected("invalid parts");
667
+ const expectedParts = Math.max(1, Math.ceil(size / partSize));
668
+ if (parts.length !== expectedParts) throw unexpected(`expected ${expectedParts} parts but got ${parts.length}`);
669
+ return {
670
+ targets: parts,
671
+ partSize
672
+ };
673
+ }
674
+ if (!isSignedTarget(data)) throw unexpected("missing upload url");
675
+ return {
676
+ targets: [{
677
+ url: data.url,
678
+ headers: data.headers
679
+ }],
680
+ partSize: Math.max(size, 1)
681
+ };
682
+ }
683
+ function describeFetchError(error) {
684
+ if (error instanceof Error) {
685
+ if (error.name === "TimeoutError") return "timed out";
686
+ const cause = error.cause;
687
+ if (cause && typeof cause.code === "string") return cause.code;
688
+ if (cause && typeof cause.message === "string") return cause.message;
689
+ return error.message;
690
+ }
691
+ return String(error);
692
+ }
693
+ /** PUT one byte range, retrying network errors and 5xx responses. Returns the upload receipt. */
694
+ async function putPart(target, body, options) {
695
+ for (let attempt = 0;; attempt++) {
696
+ options.signal.throwIfAborted();
697
+ let response;
698
+ try {
699
+ response = await options.fetch(target.url, {
700
+ method: "PUT",
701
+ headers: target.headers,
702
+ body,
703
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
704
+ });
705
+ } catch (error) {
706
+ if (options.signal.aborted) throw options.signal.reason;
707
+ if (attempt < options.maxRetries) {
708
+ await options.sleep(1e3 * 2 ** attempt);
709
+ continue;
710
+ }
711
+ throw new TransferError(`Upload of ${options.label} failed: network error (${describeFetchError(error)}).`, null);
712
+ }
713
+ if (response.ok) {
714
+ await response.body?.cancel();
715
+ const receipt = response.headers.get("X-Upload-Receipt");
716
+ if (!receipt && options.requireReceipt) throw new TransferError(`Upload of ${options.label} succeeded but the server did not return an upload receipt.`, response.status);
717
+ return receipt;
718
+ }
719
+ const detail = (await response.text().catch(() => "")).trim().slice(0, 500);
720
+ if (response.status === 412) throw new TransferError(`Upload of ${options.label} failed: the file already exists and its receipt was lost.`, 412, true);
721
+ if (response.status >= 500 && attempt < options.maxRetries) {
722
+ await options.sleep(1e3 * 2 ** attempt);
723
+ continue;
724
+ }
725
+ throw new TransferError(`Upload of ${options.label} failed (HTTP ${response.status})${detail ? `: ${detail}` : "."}`, response.status);
726
+ }
727
+ }
728
+ /** Run `worker` for indexes 0..count-1 with bounded concurrency, stopping on the first error. */
729
+ async function runPool(count, concurrency, controller, worker) {
730
+ let next = 0;
731
+ let firstError = null;
732
+ const runner = async () => {
733
+ while (next < count && !controller.signal.aborted) {
734
+ const index = next++;
735
+ try {
736
+ await worker(index);
737
+ } catch (error) {
738
+ if (firstError === null) {
739
+ firstError = error;
740
+ controller.abort(error);
741
+ }
742
+ return;
743
+ }
744
+ }
745
+ };
746
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(concurrency, count)) }, runner));
747
+ if (firstError !== null) throw firstError;
748
+ }
749
+ async function transferOnce(options, blob) {
750
+ const { client, size } = options;
751
+ const started = await client.request("POST", "/api/v1/uploads", {
752
+ filename: options.filename,
753
+ size,
754
+ mime_type: options.mimeType,
755
+ ...options.collectionId ? { collection_id: options.collectionId } : {}
756
+ });
757
+ const { targets, partSize } = planTransfer(started, size);
758
+ const requireReceipt = started.requires_receipts !== false;
759
+ const receipts = new Array(targets.length).fill(null);
760
+ const controller = new AbortController();
761
+ let uploadedBytes = 0;
762
+ options.onProgress?.(0, size);
763
+ await runPool(targets.length, options.concurrency ?? DEFAULT_CONCURRENCY, controller, async (index) => {
764
+ const start = index * partSize;
765
+ const end = Math.min(start + partSize, size);
766
+ const target = targets[index];
767
+ receipts[index] = await putPart(target, blob.slice(start, end), {
768
+ fetch: options.fetch,
769
+ sleep: options.sleep,
770
+ maxRetries: options.maxPartRetries ?? DEFAULT_PART_RETRIES,
771
+ timeoutMs: options.partTimeoutMs ?? DEFAULT_PART_TIMEOUT_MS,
772
+ signal: controller.signal,
773
+ requireReceipt,
774
+ label: targets.length > 1 ? `part ${index + 1}/${targets.length}` : options.filename
775
+ });
776
+ uploadedBytes += end - start;
777
+ options.onProgress?.(uploadedBytes, size);
778
+ });
779
+ return client.request("PUT", `/api/v1/uploads/${encodeURIComponent(started.id)}`, {
780
+ token: started.token,
781
+ receipts: receipts.filter((receipt) => receipt !== null)
782
+ }, { idempotent: true });
783
+ }
784
+ /**
785
+ * Upload one file: start the upload, PUT each part (in parallel for multipart),
786
+ * then complete it with the receipts in part order.
787
+ */
788
+ async function uploadFile(options) {
789
+ const blob = await openAsBlob(options.path);
790
+ if (blob.size !== options.size) throw new Error(`${options.path} changed size while uploading. Please retry.`);
791
+ try {
792
+ return await transferOnce(options, blob);
793
+ } catch (error) {
794
+ if (error instanceof TransferError && error.restartUpload) {
795
+ options.onNotice?.(`Restarting the upload of ${options.filename}...`);
796
+ return transferOnce(options, blob);
797
+ }
798
+ throw error;
799
+ }
800
+ }
801
+ // src/commands/upload.ts
802
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
803
+ const MAX_FILENAME_LENGTH = 255;
804
+ /** The name sent to the server: a basename without slashes or control characters, at most 255 characters. */
805
+ function uploadFilename(path) {
806
+ let name = basename(path).replace(/[\u0000-\u001f\u007f\\/]/g, "_").trim();
807
+ if (!name || name === "." || name === "..") name = "file";
808
+ const characters = Array.from(name);
809
+ if (characters.length <= MAX_FILENAME_LENGTH) return name;
810
+ const extension = Array.from(extname(name));
811
+ const keep = extension.length > 0 && extension.length <= 16 ? extension : [];
812
+ return characters.slice(0, MAX_FILENAME_LENGTH - keep.length).join("") + keep.join("");
813
+ }
814
+ function formatBytes(bytes) {
815
+ const units = [
816
+ "B",
817
+ "KB",
818
+ "MB",
819
+ "GB",
820
+ "TB"
821
+ ];
822
+ let value = bytes;
823
+ let unit = 0;
824
+ while (value >= 1024 && unit < units.length - 1) {
825
+ value /= 1024;
826
+ unit++;
827
+ }
828
+ return unit === 0 ? `${value} ${units[unit]}` : `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit]}`;
829
+ }
830
+ async function validateFile(file) {
831
+ try {
832
+ const stats = await stat(file);
833
+ if (stats.isDirectory()) return {
834
+ file,
835
+ error: "Is a directory. Only regular files can be uploaded."
836
+ };
837
+ if (!stats.isFile()) return {
838
+ file,
839
+ error: "Not a regular file."
840
+ };
841
+ return {
842
+ file,
843
+ size: stats.size
844
+ };
845
+ } catch (error) {
846
+ const code = error.code;
847
+ if (code === "ENOENT") return {
848
+ file,
849
+ error: "No such file."
850
+ };
851
+ if (code === "EACCES" || code === "EPERM") return {
852
+ file,
853
+ error: "Permission denied."
854
+ };
855
+ return {
856
+ file,
857
+ error: error.message
858
+ };
859
+ }
860
+ }
861
+ function createProgress(context, enabled) {
862
+ let active = false;
863
+ return {
864
+ update(line) {
865
+ if (!enabled) return;
866
+ active = true;
867
+ context.stderr.write(`\r\u001b[2K${line}`);
868
+ },
869
+ clear() {
870
+ if (enabled && active) {
871
+ context.stderr.write("\r\x1B[2K");
872
+ active = false;
873
+ }
874
+ }
875
+ };
876
+ }
877
+ async function uploadCommand(files, options, globals, context) {
878
+ if (options.collection !== void 0 && !UUID_PATTERN.test(options.collection)) throw new CliError(`Invalid --collection "${options.collection}". Expected a collection UUID.`);
879
+ if (files.length === 0) throw new CliError("No files given. Usage: filecafe upload <files...>");
880
+ const progress = createProgress(context, Boolean(context.stderr.isTTY) && !options.json && !options.quiet);
881
+ const notice = (message) => {
882
+ if (!options.quiet) {
883
+ progress.clear();
884
+ context.stderr.write(`${message}\n`);
885
+ }
886
+ };
887
+ const { client } = await requireSession(context, globals, notice);
888
+ const checked = await Promise.all(files.map(validateFile));
889
+ const invalid = checked.filter((entry) => "error" in entry);
890
+ const results = [];
891
+ if (invalid.length > 0) for (const entry of checked) results.push({
892
+ file: entry.file,
893
+ ok: false,
894
+ error: "error" in entry ? entry.error : "Skipped because another input file is invalid; nothing was uploaded."
895
+ });
896
+ else {
897
+ let fatal = null;
898
+ for (const { file, size } of checked) {
899
+ let result;
900
+ if (fatal !== null) result = {
901
+ file,
902
+ ok: false,
903
+ error: fatal
904
+ };
905
+ else {
906
+ const filename = uploadFilename(file);
907
+ progress.update(`Uploading ${filename} (${formatBytes(size)})...`);
908
+ try {
909
+ const completed = await uploadFile({
910
+ client,
911
+ fetch: context.fetch,
912
+ sleep: context.sleep,
913
+ path: file,
914
+ filename,
915
+ size,
916
+ mimeType: guessMimeType(filename),
917
+ collectionId: options.collection,
918
+ concurrency: options.concurrency,
919
+ onNotice: notice,
920
+ onProgress: (uploaded, total) => {
921
+ if (uploaded > 0 && total > 0) {
922
+ const percent = Math.floor(uploaded / total * 100);
923
+ progress.update(`Uploading ${filename} ${percent}% (${formatBytes(uploaded)} / ${formatBytes(total)})`);
924
+ }
925
+ }
926
+ });
927
+ result = {
928
+ file,
929
+ ok: true,
930
+ id: completed.id,
931
+ filename: completed.filename,
932
+ size: completed.size,
933
+ url: completed.url ?? null,
934
+ password_protected: Boolean(completed.password_protected)
935
+ };
936
+ } catch (error) {
937
+ result = {
938
+ file,
939
+ ok: false,
940
+ error: error instanceof Error ? error.message : String(error)
941
+ };
942
+ if (error instanceof ApiError && error.isFatal) fatal = result.error;
943
+ } finally {
944
+ progress.clear();
945
+ }
946
+ }
947
+ results.push(result);
948
+ if (!options.json) {
949
+ if (result.ok && result.url) context.stdout.write(`${result.url}\n`);
950
+ else if (result.ok) context.stderr.write(`${file}: uploaded (id ${result.id}), but the server returned no share link.\n`);
951
+ else context.stderr.write(`${file}: ${result.error}\n`);
952
+ }
953
+ }
954
+ }
955
+ if (options.json) context.stdout.write(`${JSON.stringify(results, null, 2)}\n`);
956
+ else if (invalid.length > 0) {
957
+ for (const entry of invalid) context.stderr.write(`${entry.file}: ${entry.error}\n`);
958
+ context.stderr.write("Nothing was uploaded.\n");
959
+ }
960
+ return results.every((result) => result.ok) ? 0 : 1;
961
+ }
962
+ // src/commands/whoami.ts
963
+ async function whoamiCommand(options, globals, context) {
964
+ const { client, settings } = await requireSession(context, globals);
965
+ let me;
966
+ try {
967
+ me = await fetchMe(client);
968
+ } catch (error) {
969
+ throw new CliError(error.message);
970
+ }
971
+ if (options.json) context.stdout.write(`${JSON.stringify({
972
+ name: me.name,
973
+ email: me.email,
974
+ url: settings.baseUrl,
975
+ token_source: settings.tokenSource
976
+ })}\n`);
977
+ else {
978
+ context.stdout.write(`Logged in to ${settings.baseUrl} as ${me.name} (${me.email})\n`);
979
+ if (settings.tokenSource === "env") context.stderr.write("(using FILECAFE_TOKEN)\n");
980
+ }
981
+ return 0;
982
+ }
983
+ // src/cli.ts
984
+ const MAIN_EXAMPLES = `
985
+ Examples:
986
+ $ filecafe login # log in via your browser (one time)
987
+ $ filecafe upload report.pdf # prints the share URL on stdout
988
+ $ filecafe upload a.png b.mp4 --json # machine-readable results (for scripts and AI agents)
989
+ $ filecafe upload ./build.zip | pbcopy # copy the share URL to the clipboard
990
+ $ FILECAFE_TOKEN=... npx filecafe upload notes.txt --json # CI / headless
991
+
992
+ Environment:
993
+ FILECAFE_TOKEN API token; takes precedence over the saved login
994
+ FILECAFE_URL Site URL (default: https://file.cafe)
995
+
996
+ Exit codes: 0 on success, 1 on any failure. Errors and progress go to stderr.
997
+ `;
998
+ const UPLOAD_EXAMPLES = `
999
+ Output:
1000
+ Default: one share URL per line on stdout, in the order the files were given.
1001
+ --json: a JSON array on stdout with one object per input file:
1002
+ {"file": "a.png", "ok": true, "id": "...", "filename": "a.png",
1003
+ "size": 1234, "url": "https://file.cafe/...", "password_protected": false}
1004
+ {"file": "b.png", "ok": false, "error": "No such file."}
1005
+ Exit code is 0 if every file uploaded, 1 if any failed.
1006
+
1007
+ Examples:
1008
+ $ filecafe upload screenshot.png
1009
+ $ filecafe upload report.pdf data.csv --json
1010
+ $ filecafe upload video.mp4 --collection 0b6f9a2e-3c1d-4f7a-9e5b-2d8c4a1f6e3b
1011
+ $ filecafe upload build.zip --quiet | pbcopy
1012
+ $ FILECAFE_TOKEN=... filecafe upload logs.txt --json # no saved login needed
1013
+ `;
1014
+ const LOGIN_EXAMPLES = `
1015
+ Examples:
1016
+ $ filecafe login # opens your browser to approve this device
1017
+ $ echo "$FILECAFE_TOKEN" | filecafe login --with-token
1018
+ $ filecafe login --url http://file-cafe.test # log in to another file.cafe server
1019
+
1020
+ In CI you can skip login entirely and set FILECAFE_TOKEN instead.
1021
+ `;
1022
+ async function execute(context, action) {
1023
+ try {
1024
+ process.exitCode = await action();
1025
+ } catch (error) {
1026
+ const message = error instanceof CliError || error instanceof ApiError ? error.message : `Unexpected error: ${error instanceof Error ? error.message : String(error)}`;
1027
+ context.stderr.write(`${message}\n`);
1028
+ if (context.env.FILECAFE_DEBUG && error instanceof Error && error.stack) context.stderr.write(`${error.stack}\n`);
1029
+ process.exitCode = 1;
1030
+ }
1031
+ }
1032
+ function createProgram(context) {
1033
+ const program = new Command();
1034
+ program.name("filecafe").description("Upload files to file.cafe and get share links. Designed for AI coding agents, humans, and CI.").version(VERSION, "-v, --version", "print the version").option("--url <url>", "file.cafe site URL (env: FILECAFE_URL, default: https://file.cafe)").helpOption("-h, --help", "show help").showHelpAfterError("(run \"filecafe --help\" for usage and examples)").addHelpText("after", MAIN_EXAMPLES);
1035
+ const globals = (command) => command.optsWithGlobals();
1036
+ program.command("login").description("Log in via your browser, or save an existing API token").option("--token <token>", "save this API token instead of opening a browser (visible in shell history; prefer --with-token)").option("--with-token", "read the API token from standard input").addHelpText("after", LOGIN_EXAMPLES).action((options, command) => execute(context, () => loginCommand(options, globals(command), context)));
1037
+ program.command("logout").description("Revoke the saved login token on file.cafe and delete it from this machine (does not affect FILECAFE_TOKEN)").addHelpText("after", "\nThe token is revoked even if it was saved with \"filecafe login --token\", so don't log out\nwith a token that CI or another machine still uses.\n").action(() => execute(context, () => logoutCommand(context)));
1038
+ program.command("whoami").description("Show the account you are logged in as").option("--json", "print {\"name\",\"email\",\"url\",\"token_source\"} as JSON").addHelpText("after", "\nExamples:\n $ filecafe whoami\n $ filecafe whoami --json\n").action((options, command) => execute(context, () => whoamiCommand(options, globals(command), context)));
1039
+ program.command("upload").description("Upload one or more files and print their share URLs").argument("<files...>", "files to upload (uploaded one after another)").option("--collection <uuid>", "add the files to this collection").option("--json", "print a JSON array of per-file results on stdout").option("-q, --quiet", "no progress or notices on stderr (errors are still printed)").addHelpText("after", UPLOAD_EXAMPLES).action((files, options, command) => execute(context, () => uploadCommand(files, options, globals(command), context)));
1040
+ return program;
1041
+ }
1042
+ await createProgram(createDefaultContext()).parseAsync(process.argv);
1043
+ export { createProgram };
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "filecafe",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Upload files to file.cafe from the command line. Built for AI coding agents, humans, and CI.",
5
+ "keywords": [
6
+ "file.cafe",
7
+ "file-sharing",
8
+ "upload",
9
+ "cli",
10
+ "ai-agents"
11
+ ],
12
+ "homepage": "https://file.cafe",
13
+ "type": "module",
14
+ "bin": {
15
+ "filecafe": "dist/cli.js"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "scripts": {
24
+ "build": "tsdown",
25
+ "dev": "node src/cli.ts",
26
+ "test": "node --test \"test/**/*.test.ts\"",
27
+ "typecheck": "tsc --noEmit",
28
+ "prepublishOnly": "npm run build && npm test"
29
+ },
30
+ "dependencies": {
31
+ "commander": "^14.0.3"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^24.19.2",
35
+ "tsdown": "^0.23.1",
36
+ "typescript": "^7.0.2"
37
+ }
38
+ }