@bangerpage/cli 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/bin.ts
4
- import { readFileSync as readFileSync6, realpathSync } from "node:fs";
4
+ import { readFileSync as readFileSync8, realpathSync } from "node:fs";
5
5
  import { fileURLToPath as fileURLToPath4, pathToFileURL } from "node:url";
6
6
 
7
7
  // src/browser.ts
@@ -62,25 +62,300 @@ function deckFile(positionals, usage) {
62
62
  return positionals[0] ?? "index.html";
63
63
  }
64
64
 
65
+ // src/platform/browser-login.ts
66
+ import { spawn } from "node:child_process";
67
+ import { createHash, randomBytes } from "node:crypto";
68
+ import { createServer } from "node:http";
69
+
70
+ // src/platform/client.ts
71
+ import { chmodSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
72
+ import { homedir } from "node:os";
73
+ import { dirname, join } from "node:path";
74
+ var DEFAULT_HOST = "https://banger.page";
75
+ function platformHost(env = process.env) {
76
+ return (env.BANGER_HOST?.trim() || DEFAULT_HOST).replace(/\/+$/, "");
77
+ }
78
+ function credentialsPath(env = process.env) {
79
+ const base = env.XDG_CONFIG_HOME?.trim() || join(homedir(), ".config");
80
+ return join(base, "banger", "credentials.json");
81
+ }
82
+ function readCredentials(env) {
83
+ const file = credentialsPath(env);
84
+ if (!existsSync2(file)) return { hosts: {} };
85
+ try {
86
+ const data = JSON.parse(readFileSync2(file, "utf8"));
87
+ return { hosts: data.hosts && typeof data.hosts === "object" ? data.hosts : {} };
88
+ } catch {
89
+ throw new CliError(2, `${file} could not be read; run banger logout and log in again`);
90
+ }
91
+ }
92
+ function writeCredentials(credentials, env) {
93
+ const file = credentialsPath(env);
94
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
95
+ writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
96
+ `, { mode: 384 });
97
+ chmodSync(file, 384);
98
+ }
99
+ function saveToken(host, token, username, env = process.env) {
100
+ const credentials = readCredentials(env);
101
+ credentials.hosts[host] = { token, ...username ? { username } : {} };
102
+ writeCredentials(credentials, env);
103
+ }
104
+ function forgetToken(host, env = process.env) {
105
+ const credentials = readCredentials(env);
106
+ if (!credentials.hosts[host]) return false;
107
+ delete credentials.hosts[host];
108
+ if (Object.keys(credentials.hosts).length === 0) rmSync(credentialsPath(env), { force: true });
109
+ else writeCredentials(credentials, env);
110
+ return true;
111
+ }
112
+ function tokenFor(host, env = process.env) {
113
+ const fromEnv = env.BANGER_TOKEN?.trim();
114
+ if (fromEnv) return fromEnv;
115
+ return readCredentials(env).hosts[host]?.token ?? null;
116
+ }
117
+ var CLIENT_ID = "banger-cli";
118
+ async function exchangeCode(host, params, fetchImpl = fetch) {
119
+ const body = new URLSearchParams({
120
+ grant_type: "authorization_code",
121
+ code: params.code,
122
+ code_verifier: params.verifier,
123
+ redirect_uri: params.redirectUri,
124
+ client_id: CLIENT_ID
125
+ });
126
+ const response = await fetchImpl(`${host}/oauth/token`, { method: "POST", body });
127
+ const data = await response.json().catch(() => ({}));
128
+ if (!response.ok || !data.access_token) {
129
+ throw new ApiError(response.status, data.error ?? `http_${response.status}`, data.error_description ?? data.error ?? "the token request failed");
130
+ }
131
+ return data.access_token;
132
+ }
133
+ async function revokeToken(host, token, fetchImpl = fetch) {
134
+ const response = await fetchImpl(`${host}/oauth/revoke`, { method: "POST", body: new URLSearchParams({ token, client_id: CLIENT_ID }) });
135
+ if (!response.ok) throw new ApiError(response.status, `http_${response.status}`, `${response.status} ${response.statusText}`.trim());
136
+ }
137
+ function storedToken(host, env = process.env) {
138
+ return readCredentials(env).hosts[host]?.token ?? null;
139
+ }
140
+ var ApiError = class extends Error {
141
+ constructor(status, code, message) {
142
+ super(message);
143
+ this.status = status;
144
+ this.code = code;
145
+ this.name = "ApiError";
146
+ }
147
+ };
148
+ var PlatformClient = class {
149
+ constructor(host, token, fetchImpl = fetch) {
150
+ this.host = host;
151
+ this.token = token;
152
+ this.fetchImpl = fetchImpl;
153
+ }
154
+ me() {
155
+ return this.call("GET", "/api/v1/me");
156
+ }
157
+ beginUpload(files) {
158
+ return this.call("POST", "/api/v1/uploads", { files });
159
+ }
160
+ async putBlob(url, body, method = "PUT") {
161
+ const response = await this.fetchImpl(url, { method, body });
162
+ if (!response.ok) throw await apiError(response);
163
+ }
164
+ publish(body) {
165
+ return this.call("POST", "/api/v1/decks", body);
166
+ }
167
+ update(slug, body) {
168
+ return this.call("PUT", `/api/v1/decks/${encodeURIComponent(slug)}`, body);
169
+ }
170
+ async call(method, path, body) {
171
+ let response;
172
+ try {
173
+ response = await this.fetchImpl(`${this.host}${path}`, {
174
+ method,
175
+ headers: {
176
+ authorization: `Bearer ${this.token}`,
177
+ accept: "application/json",
178
+ ...body === void 0 ? {} : { "content-type": "application/json" }
179
+ },
180
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
181
+ });
182
+ } catch (error) {
183
+ throw new ApiError(0, "network", `could not reach ${this.host}: ${error.message}`);
184
+ }
185
+ if (!response.ok) throw await apiError(response);
186
+ return await response.json();
187
+ }
188
+ };
189
+ async function apiError(response) {
190
+ let code = `http_${response.status}`;
191
+ let message = `${response.status} ${response.statusText}`.trim();
192
+ try {
193
+ const data = await response.json();
194
+ if (data.error?.code) code = data.error.code;
195
+ if (data.error?.message) message = data.error.message;
196
+ } catch {
197
+ }
198
+ return new ApiError(response.status, code, message);
199
+ }
200
+
201
+ // src/platform/browser-login.ts
202
+ var LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
203
+ var base64url = (bytes) => bytes.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
204
+ function pkcePair() {
205
+ const verifier = base64url(randomBytes(32));
206
+ return { verifier, challenge: base64url(createHash("sha256").update(verifier).digest()) };
207
+ }
208
+ function openInBrowser(url) {
209
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
210
+ try {
211
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
212
+ child.on("error", () => void 0);
213
+ child.unref();
214
+ } catch {
215
+ }
216
+ }
217
+ var PAGE = (message) => `<!doctype html><meta charset="utf-8"><title>Banger</title><body style="font:20px system-ui;margin:64px">${message}</body>`;
218
+ async function authorizeInBrowser(host, opts = {}) {
219
+ const { verifier, challenge } = pkcePair();
220
+ const state = base64url(randomBytes(16));
221
+ let settle;
222
+ const result = new Promise((resolve6, reject) => settle = { resolve: resolve6, reject });
223
+ const server = createServer((req, res) => {
224
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
225
+ if (url.pathname !== "/callback") {
226
+ res.writeHead(404).end();
227
+ return;
228
+ }
229
+ const error = url.searchParams.get("error");
230
+ const code = url.searchParams.get("code");
231
+ if (url.searchParams.get("state") !== state) {
232
+ res.writeHead(400, { "content-type": "text/html; charset=utf-8" }).end(PAGE("This login link does not match the one the CLI started. Run banger login again."));
233
+ return;
234
+ }
235
+ if (error || !code) {
236
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(PAGE("The login was not allowed. You can close this tab."));
237
+ settle?.reject(new CliError(2, error === "access_denied" ? "the login was not allowed in the browser" : `the login failed: ${error ?? "no code"}`));
238
+ return;
239
+ }
240
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(PAGE("Logged in to Banger. You can close this tab and go back to the terminal."));
241
+ settle?.resolve(code);
242
+ });
243
+ await new Promise((resolve6, reject) => {
244
+ server.once("error", reject);
245
+ server.listen(0, "127.0.0.1", () => resolve6());
246
+ });
247
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
248
+ const authorize = new URL(`${host}/authorize`);
249
+ authorize.search = new URLSearchParams({
250
+ response_type: "code",
251
+ client_id: CLIENT_ID,
252
+ redirect_uri: redirectUri,
253
+ code_challenge: challenge,
254
+ code_challenge_method: "S256",
255
+ state,
256
+ scope: "publish read"
257
+ }).toString();
258
+ process.stdout.write(`opening ${authorize.href}
259
+ if the browser does not open, open that URL yourself
260
+ `);
261
+ (opts.open ?? openInBrowser)(authorize.href);
262
+ const timer = setTimeout(
263
+ () => settle?.reject(new CliError(2, "no answer from the browser within 5 minutes; run banger login again")),
264
+ opts.timeoutMs ?? LOGIN_TIMEOUT_MS
265
+ );
266
+ try {
267
+ const code = await result;
268
+ return { code, verifier, redirectUri };
269
+ } finally {
270
+ clearTimeout(timer);
271
+ server.closeAllConnections();
272
+ server.close();
273
+ }
274
+ }
275
+
276
+ // src/commands/account.ts
277
+ var LOGIN_USAGE = "usage: banger login [--token <token>]";
278
+ var LOGOUT_USAGE = "usage: banger logout";
279
+ async function runLogin(argv, deps = {}) {
280
+ if (argv.includes("--help")) {
281
+ process.stdout.write(`${LOGIN_USAGE}
282
+ `);
283
+ return 0;
284
+ }
285
+ const { values, positionals } = parseArgsStrict(argv, { token: { type: "string" } });
286
+ if (positionals.length > 0) throw new CliError(2, LOGIN_USAGE);
287
+ const fetchImpl = deps.fetchImpl ?? fetch;
288
+ const host = platformHost();
289
+ let token = values.token?.trim();
290
+ if (values.token !== void 0 && !token) throw new CliError(2, LOGIN_USAGE);
291
+ if (!token) {
292
+ const grant = await authorizeInBrowser(host, { open: deps.open });
293
+ try {
294
+ token = await exchangeCode(host, grant, fetchImpl);
295
+ } catch (error) {
296
+ if (error instanceof ApiError) throw new CliError(2, `could not log in to ${host}: ${error.message}`);
297
+ throw error;
298
+ }
299
+ }
300
+ let username;
301
+ try {
302
+ username = (await new PlatformClient(host, token, fetchImpl).me()).username;
303
+ } catch (error) {
304
+ if (error instanceof ApiError && error.status === 401) throw new CliError(2, `${host} did not accept the token`);
305
+ if (error instanceof ApiError) throw new CliError(2, `could not log in to ${host}: ${error.message}`);
306
+ throw error;
307
+ }
308
+ saveToken(host, token, username);
309
+ process.stdout.write(`logged in to ${host} as ${username}
310
+ `);
311
+ return 0;
312
+ }
313
+ async function runLogout(argv, deps = {}) {
314
+ if (argv.includes("--help")) {
315
+ process.stdout.write(`${LOGOUT_USAGE}
316
+ `);
317
+ return 0;
318
+ }
319
+ const { positionals } = parseArgsStrict(argv, {});
320
+ if (positionals.length > 0) throw new CliError(2, LOGOUT_USAGE);
321
+ const host = platformHost();
322
+ const token = storedToken(host);
323
+ if (!token) {
324
+ process.stdout.write(`not logged in to ${host}
325
+ `);
326
+ return 0;
327
+ }
328
+ try {
329
+ await revokeToken(host, token, deps.fetchImpl ?? fetch);
330
+ } catch (error) {
331
+ process.stderr.write(`warning: could not revoke the token on ${host} (${error.message}); remove it on the settings page
332
+ `);
333
+ }
334
+ forgetToken(host);
335
+ process.stdout.write(`logged out of ${host}
336
+ `);
337
+ return 0;
338
+ }
339
+
65
340
  // src/capture.ts
66
341
  import { readdir, rm } from "node:fs/promises";
67
- import { join as join3 } from "node:path";
342
+ import { join as join4 } from "node:path";
68
343
 
69
344
  // src/core-package.ts
70
- import { readFileSync as readFileSync2 } from "node:fs";
71
- import { dirname, join } from "node:path";
345
+ import { readFileSync as readFileSync3 } from "node:fs";
346
+ import { dirname as dirname2, join as join2 } from "node:path";
72
347
  import { fileURLToPath } from "node:url";
73
348
  import { PRESET_NAMES, isPresetName, parseThemeJson, presetTheme, resolveTheme, serializeTheme } from "@bangerpage/core/theme";
74
349
  var CORE_PACKAGE = "@bangerpage/core";
75
350
  var CDN_HOSTS = ["cdn.jsdelivr.net/npm", "unpkg.com"];
76
351
  function corePackageDir() {
77
- return dirname(fileURLToPath(import.meta.resolve(`${CORE_PACKAGE}/package.json`)));
352
+ return dirname2(fileURLToPath(import.meta.resolve(`${CORE_PACKAGE}/package.json`)));
78
353
  }
79
354
  function coreDistDir() {
80
- return join(corePackageDir(), "dist");
355
+ return join2(corePackageDir(), "dist");
81
356
  }
82
357
  function coreVersion() {
83
- return JSON.parse(readFileSync2(join(corePackageDir(), "package.json"), "utf8")).version;
358
+ return JSON.parse(readFileSync3(join2(corePackageDir(), "package.json"), "utf8")).version;
84
359
  }
85
360
 
86
361
  // src/html-transform.ts
@@ -232,9 +507,9 @@ function applyThemeBlock(html, json) {
232
507
  }
233
508
 
234
509
  // src/server.ts
235
- import { createReadStream, existsSync as existsSync2, readFileSync as readFileSync3, statSync as statSync2, watch } from "node:fs";
236
- import { createServer } from "node:http";
237
- import { basename, dirname as dirname2, extname, join as join2, normalize, resolve, sep } from "node:path";
510
+ import { createReadStream, existsSync as existsSync3, readFileSync as readFileSync4, statSync as statSync2, watch } from "node:fs";
511
+ import { createServer as createServer2 } from "node:http";
512
+ import { basename, dirname as dirname3, extname, join as join3, normalize, resolve, sep } from "node:path";
238
513
  var CONTENT_TYPES = {
239
514
  ".html": "text/html; charset=utf-8",
240
515
  ".js": "text/javascript; charset=utf-8",
@@ -264,7 +539,7 @@ function resolveWithin(root, urlPath) {
264
539
  }
265
540
  if (decoded.includes("\0")) return null;
266
541
  const base = resolve(root);
267
- const full = normalize(join2(base, decoded));
542
+ const full = normalize(join3(base, decoded));
268
543
  return full === base || full.startsWith(base + sep) ? full : null;
269
544
  }
270
545
  var RELOAD_SNIPPET = `<script>new EventSource("/__banger/events").addEventListener("reload",()=>location.reload())</script>`;
@@ -273,14 +548,14 @@ var CORE_PREFIX = "/__banger/core/";
273
548
  async function startServer(opts) {
274
549
  readInput(opts.file);
275
550
  const file = resolve(opts.file);
276
- const root = dirname2(file);
551
+ const root = dirname3(file);
277
552
  const served = /* @__PURE__ */ new Set();
278
553
  const clients = /* @__PURE__ */ new Set();
279
554
  const send = (res, status, body, type = "text/plain; charset=utf-8") => {
280
555
  res.writeHead(status, { "content-type": type, "cache-control": "no-store" });
281
556
  res.end(body);
282
557
  };
283
- const server = createServer((req, res) => {
558
+ const server = createServer2((req, res) => {
284
559
  if (req.method !== "GET" && req.method !== "HEAD") return send(res, 405, "method not allowed");
285
560
  const urlPath = (req.url ?? "/").split("?")[0] ?? "/";
286
561
  if (urlPath === EVENTS_PATH && opts.watch) {
@@ -292,11 +567,11 @@ async function startServer(opts) {
292
567
  }
293
568
  const isCore = urlPath.startsWith(CORE_PREFIX);
294
569
  const target = isCore ? resolveWithin(coreDistDir(), urlPath.slice(CORE_PREFIX.length)) : resolveWithin(root, urlPath === "/" ? basename(file) : urlPath);
295
- if (!target || !existsSync2(target) || !statSync2(target).isFile()) return send(res, 404, "not found");
570
+ if (!target || !existsSync3(target) || !statSync2(target).isFile()) return send(res, 404, "not found");
296
571
  if (!isCore) served.add(target);
297
572
  const type = contentType(target);
298
573
  if (!isCore && extname(target).toLowerCase() === ".html") {
299
- let html = rewriteRuntimeScript(readFileSync3(target, "utf8"), CORE_PACKAGE, `${CORE_PREFIX}index.js`);
574
+ let html = rewriteRuntimeScript(readFileSync4(target, "utf8"), CORE_PACKAGE, `${CORE_PREFIX}index.js`);
300
575
  if (opts.watch) html = injectBeforeBodyEnd(html, RELOAD_SNIPPET);
301
576
  return send(res, 200, req.method === "HEAD" ? "" : html, type);
302
577
  }
@@ -316,7 +591,7 @@ async function startServer(opts) {
316
591
  let timer;
317
592
  if (opts.watch) {
318
593
  watcher = watch(root, { recursive: true }, (_event, name) => {
319
- if (!name || !served.has(join2(root, name.toString()))) return;
594
+ if (!name || !served.has(join3(root, name.toString()))) return;
320
595
  clearTimeout(timer);
321
596
  timer = setTimeout(() => {
322
597
  for (const client of clients) client.write("event: reload\ndata: {}\n\n");
@@ -362,7 +637,7 @@ async function clearStopFiles(dir) {
362
637
  const removed = [];
363
638
  for (const entry2 of entries) {
364
639
  if (entry2.isFile() && STOP_FILE_PATTERN.test(entry2.name)) {
365
- await rm(join3(dir, entry2.name));
640
+ await rm(join4(dir, entry2.name));
366
641
  removed.push(entry2.name);
367
642
  }
368
643
  }
@@ -497,10 +772,10 @@ async function runCheck(argv) {
497
772
 
498
773
  // src/export/pdf.ts
499
774
  import { mkdir, writeFile } from "node:fs/promises";
500
- import { basename as basename2, dirname as dirname3, extname as extname2, resolve as resolve2 } from "node:path";
775
+ import { basename as basename2, dirname as dirname4, extname as extname2, resolve as resolve2 } from "node:path";
501
776
  import { PDFDocument } from "@cantoo/pdf-lib";
502
777
  async function exportPdf(file, opts = {}) {
503
- const out = resolve2(opts.out ?? resolve2(dirname3(file), `${basename2(file, extname2(file))}.pdf`));
778
+ const out = resolve2(opts.out ?? resolve2(dirname4(file), `${basename2(file, extname2(file))}.pdf`));
504
779
  const failures = /* @__PURE__ */ new Map();
505
780
  const pages = [];
506
781
  const title = await withCapture(
@@ -527,7 +802,7 @@ ${[...failures.keys()].join("\n")}`);
527
802
  for (const copied of await merged.copyPages(doc, doc.getPageIndices())) merged.addPage(copied);
528
803
  }
529
804
  merged.setTitle(title);
530
- await mkdir(dirname3(out), { recursive: true });
805
+ await mkdir(dirname4(out), { recursive: true });
531
806
  await writeFile(out, await merged.save());
532
807
  return out;
533
808
  }
@@ -558,15 +833,15 @@ ${USAGE2}`);
558
833
  }
559
834
 
560
835
  // src/commands/init.ts
561
- import { copyFileSync, existsSync as existsSync3, mkdirSync } from "node:fs";
562
- import { join as join4, resolve as resolve3 } from "node:path";
836
+ import { copyFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "node:fs";
837
+ import { join as join5, resolve as resolve3 } from "node:path";
563
838
  import { fileURLToPath as fileURLToPath2 } from "node:url";
564
839
  var USAGE3 = "usage: banger init [dir] [--force]";
565
840
  function initDeck(opts) {
566
- const target = join4(opts.dir, "index.html");
567
- if (existsSync3(target) && !opts.force) throw new CliError(2, `${target} already exists; pass --force to overwrite`);
568
- if (!existsSync3(opts.starter)) throw new CliError(2, `the bundled starter is missing: ${opts.starter}`);
569
- mkdirSync(opts.dir, { recursive: true });
841
+ const target = join5(opts.dir, "index.html");
842
+ if (existsSync4(target) && !opts.force) throw new CliError(2, `${target} already exists; pass --force to overwrite`);
843
+ if (!existsSync4(opts.starter)) throw new CliError(2, `the bundled starter is missing: ${opts.starter}`);
844
+ mkdirSync2(opts.dir, { recursive: true });
570
845
  copyFileSync(opts.starter, target);
571
846
  return target;
572
847
  }
@@ -604,25 +879,209 @@ async function runPreview(argv) {
604
879
  return 0;
605
880
  }
606
881
 
882
+ // src/commands/publish.ts
883
+ import { createHash as createHash2, randomUUID } from "node:crypto";
884
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, readdirSync, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
885
+ import { basename as basename3, extname as extname3, join as join6, relative, resolve as resolve4, sep as sep2 } from "node:path";
886
+ var USAGE5 = "usage: banger publish [dir] [--slug <slug>] [--title <title>] [--visibility public|unlisted] [--strict] [--skip-check] [--dry-run]";
887
+ var ACCEPTED = Object.fromEntries(
888
+ [".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".woff2", ".mp4", ".webm", ".json", ".css", ".js", ".pdf"].map((e) => [e, true])
889
+ );
890
+ var LIMITS = { html: 2 * 1024 * 1024, file: 10 * 1024 * 1024, total: 50 * 1024 * 1024, files: 200 };
891
+ function isAccepted(path) {
892
+ return path === "index.html" || extname3(path).toLowerCase() in ACCEPTED;
893
+ }
894
+ function collectDeck(dir) {
895
+ const root = resolve4(dir);
896
+ if (!existsSync5(join6(root, "index.html"))) throw new CliError(2, `no index.html in ${root}`);
897
+ const files = [];
898
+ const skipped = [];
899
+ const walk = (current) => {
900
+ for (const entry2 of readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
901
+ if (entry2.name.startsWith(".") || entry2.name === "node_modules") continue;
902
+ const abs = join6(current, entry2.name);
903
+ const path = relative(root, abs).split(sep2).join("/");
904
+ if (entry2.isDirectory()) {
905
+ walk(abs);
906
+ continue;
907
+ }
908
+ if (!entry2.isFile()) continue;
909
+ if (!isAccepted(path)) {
910
+ skipped.push(path);
911
+ continue;
912
+ }
913
+ const body = readFileSync5(abs);
914
+ files.push({ abs, path, size: body.length, sha256: createHash2("sha256").update(body).digest("hex") });
915
+ }
916
+ };
917
+ walk(root);
918
+ return { files, skipped };
919
+ }
920
+ function limitProblems(files) {
921
+ const problems = [];
922
+ if (files.length > LIMITS.files) problems.push(`${files.length} files; at most ${LIMITS.files} can be published`);
923
+ for (const f of files) {
924
+ const limit = f.path === "index.html" ? LIMITS.html : LIMITS.file;
925
+ if (f.size > limit) problems.push(`${f.path} is ${formatSize(f.size)}; the limit is ${formatSize(limit)}`);
926
+ }
927
+ const total = files.reduce((sum, f) => sum + f.size, 0);
928
+ if (total > LIMITS.total) problems.push(`the files add up to ${formatSize(total)}; the limit is ${formatSize(LIMITS.total)}`);
929
+ return problems;
930
+ }
931
+ function formatSize(bytes) {
932
+ if (bytes < 1024) return `${bytes} B`;
933
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
934
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
935
+ }
936
+ function slugFrom(name) {
937
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
938
+ }
939
+ function statePath(dir) {
940
+ return join6(resolve4(dir), ".banger", "deck.json");
941
+ }
942
+ function readState(dir) {
943
+ const file = statePath(dir);
944
+ if (!existsSync5(file)) return { decks: {} };
945
+ try {
946
+ const data = JSON.parse(readFileSync5(file, "utf8"));
947
+ return { decks: data.decks && typeof data.decks === "object" ? data.decks : {} };
948
+ } catch {
949
+ throw new CliError(2, `${file} could not be read; fix or delete it`);
950
+ }
951
+ }
952
+ function writeState(dir, state) {
953
+ const file = statePath(dir);
954
+ mkdirSync3(join6(resolve4(dir), ".banger"), { recursive: true });
955
+ writeFileSync2(file, `${JSON.stringify(state, null, 2)}
956
+ `);
957
+ }
958
+ async function runPublish(argv, fetchImpl = fetch) {
959
+ if (argv.includes("--help")) {
960
+ process.stdout.write(`${USAGE5}
961
+ `);
962
+ return 0;
963
+ }
964
+ const { values, positionals } = parseArgsStrict(argv, {
965
+ slug: { type: "string" },
966
+ title: { type: "string" },
967
+ visibility: { type: "string" },
968
+ strict: { type: "boolean" },
969
+ "skip-check": { type: "boolean" },
970
+ "dry-run": { type: "boolean" }
971
+ });
972
+ if (positionals.length > 1) throw new CliError(2, USAGE5);
973
+ const dir = positionals[0] ?? ".";
974
+ if (values.visibility !== void 0 && values.visibility !== "public" && values.visibility !== "unlisted") {
975
+ throw new CliError(2, `--visibility must be public or unlisted
976
+ ${USAGE5}`);
977
+ }
978
+ if (values.slug !== void 0 && slugFrom(values.slug) !== values.slug) {
979
+ throw new CliError(2, `--slug may use lower case letters, digits and single hyphens: ${values.slug}`);
980
+ }
981
+ const { files, skipped } = collectDeck(dir);
982
+ const total = files.reduce((sum, f) => sum + f.size, 0);
983
+ for (const f of files) process.stdout.write(` ${f.path} ${formatSize(f.size)}
984
+ `);
985
+ process.stdout.write(`${files.length} files, ${formatSize(total)}
986
+ `);
987
+ if (skipped.length > 0) process.stderr.write(`not sent (banger.page does not take these): ${skipped.join(", ")}
988
+ `);
989
+ const problems = limitProblems(files);
990
+ if (problems.length > 0) throw new CliError(1, problems.join("\n"));
991
+ if (!values["skip-check"]) {
992
+ const result2 = await checkDeck(join6(resolve4(dir), "index.html"));
993
+ for (const warning of result2.warnings) process.stderr.write(`warning: ${warning}
994
+ `);
995
+ for (const failure of result2.failed) process.stderr.write(`failed: ${failure}
996
+ `);
997
+ if (result2.failed.length > 0 || values.strict && result2.warnings.length > 0) {
998
+ throw new CliError(1, "banger check found problems; fix them, or pass --skip-check to publish anyway");
999
+ }
1000
+ }
1001
+ if (values["dry-run"]) return 0;
1002
+ const host = platformHost();
1003
+ const token = tokenFor(host);
1004
+ if (!token) throw new CliError(2, `not logged in to ${host}; run banger login --token <token>`);
1005
+ const client = new PlatformClient(host, token, fetchImpl);
1006
+ const state = readState(dir);
1007
+ const known = state.decks[host];
1008
+ const updating = known !== void 0 && (values.slug === void 0 || values.slug === known.slug);
1009
+ let result;
1010
+ try {
1011
+ const plan = await client.beginUpload(files.map(({ path, sha256, size }) => ({ path, sha256, size })));
1012
+ const bySha = new Map(files.map((f) => [f.sha256, f]));
1013
+ for (const blob of plan.uploads) {
1014
+ const file = bySha.get(blob.sha256);
1015
+ if (!file) throw new CliError(1, `${host} asked for a file that was not offered (${blob.path})`);
1016
+ await client.putBlob(blob.url, readFileSync5(file.abs), blob.method);
1017
+ }
1018
+ const kept = files.length - plan.uploads.length;
1019
+ process.stdout.write(
1020
+ kept === 0 ? `sent ${files.length} files
1021
+ ` : `sent ${plan.uploads.length} of ${files.length} files (${kept} already on ${host})
1022
+ `
1023
+ );
1024
+ const idempotency_key = randomUUID();
1025
+ const strict = values.strict === true;
1026
+ if (updating) {
1027
+ result = await client.update(known.slug, {
1028
+ upload_id: plan.upload_id,
1029
+ strict,
1030
+ idempotency_key,
1031
+ ...values.title ? { title: values.title } : {},
1032
+ ...values.visibility ? { visibility: values.visibility } : {}
1033
+ });
1034
+ } else {
1035
+ const slug = values.slug ?? (slugFrom(basename3(resolve4(dir))) || void 0);
1036
+ result = await client.publish({
1037
+ upload_id: plan.upload_id,
1038
+ idempotency_key,
1039
+ strict,
1040
+ ...slug ? { slug } : {},
1041
+ ...values.title ? { title: values.title } : {},
1042
+ ...values.visibility ? { visibility: values.visibility } : {}
1043
+ });
1044
+ }
1045
+ } catch (error) {
1046
+ if (!(error instanceof ApiError)) throw error;
1047
+ if (error.status === 401) throw new CliError(2, `${host} did not accept the token; run banger login --token <token> again`);
1048
+ if (error.code === "slug_taken") throw new CliError(1, `${error.message}
1049
+ pick another slug with --slug`);
1050
+ if (error.code === "pro_required") throw new CliError(1, `${error.message}
1051
+ (--visibility unlisted needs a paid plan)`);
1052
+ if (error.code === "not_found" && updating) {
1053
+ throw new CliError(1, `${error.message}
1054
+ the deck ${known.slug} is gone; delete ${statePath(dir)} to publish it as a new deck`);
1055
+ }
1056
+ throw new CliError(1, `${host}: ${error.message}`);
1057
+ }
1058
+ state.decks[host] = { slug: result.slug, url: result.url };
1059
+ writeState(dir, state);
1060
+ const version2 = result.version === void 0 ? "" : ` (version ${result.version})`;
1061
+ process.stdout.write(`${updating ? "updated" : "published"}${version2}: ${result.url}
1062
+ `);
1063
+ return 0;
1064
+ }
1065
+
607
1066
  // src/commands/skill.ts
608
- import { cpSync, existsSync as existsSync4, readFileSync as readFileSync4, rmSync, writeFileSync } from "node:fs";
609
- import { homedir } from "node:os";
610
- import { join as join5, resolve as resolve4 } from "node:path";
1067
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1068
+ import { homedir as homedir2 } from "node:os";
1069
+ import { join as join7, resolve as resolve5 } from "node:path";
611
1070
  import { fileURLToPath as fileURLToPath3 } from "node:url";
612
- var USAGE5 = "usage: banger skill install [--project | --dir <path>] [--force]";
1071
+ var USAGE6 = "usage: banger skill install [--project | --dir <path>] [--force]";
613
1072
  var MARKER = ".banger-skill";
614
1073
  function installSkill(opts) {
615
- if (!existsSync4(join5(opts.source, "SKILL.md"))) throw new CliError(2, `the bundled skill is missing: ${opts.source}`);
1074
+ if (!existsSync6(join7(opts.source, "SKILL.md"))) throw new CliError(2, `the bundled skill is missing: ${opts.source}`);
616
1075
  let outcome = "installed";
617
- if (existsSync4(opts.dest)) {
618
- if (!existsSync4(join5(opts.dest, MARKER)) && !opts.force) {
1076
+ if (existsSync6(opts.dest)) {
1077
+ if (!existsSync6(join7(opts.dest, MARKER)) && !opts.force) {
619
1078
  throw new CliError(2, `${opts.dest} already exists and was not written by banger; pass --force to replace it`);
620
1079
  }
621
- rmSync(opts.dest, { recursive: true, force: true });
1080
+ rmSync2(opts.dest, { recursive: true, force: true });
622
1081
  outcome = "updated";
623
1082
  }
624
1083
  cpSync(opts.source, opts.dest, { recursive: true });
625
- writeFileSync(join5(opts.dest, MARKER), `${opts.version}
1084
+ writeFileSync3(join7(opts.dest, MARKER), `${opts.version}
626
1085
  `);
627
1086
  return outcome;
628
1087
  }
@@ -631,18 +1090,18 @@ function bundledSkill() {
631
1090
  }
632
1091
  function cliVersion() {
633
1092
  const manifest = fileURLToPath3(new URL("../package.json", import.meta.url));
634
- return JSON.parse(readFileSync4(manifest, "utf8")).version;
1093
+ return JSON.parse(readFileSync6(manifest, "utf8")).version;
635
1094
  }
636
1095
  function runSkill(argv) {
637
1096
  const [sub, ...rest] = argv;
638
- if (sub !== "install") throw new CliError(2, USAGE5);
1097
+ if (sub !== "install") throw new CliError(2, USAGE6);
639
1098
  const { values, positionals } = parseArgsStrict(rest, {
640
1099
  project: { type: "boolean" },
641
1100
  dir: { type: "string" },
642
1101
  force: { type: "boolean" }
643
1102
  });
644
- if (positionals.length > 0 || values.project && values.dir !== void 0) throw new CliError(2, USAGE5);
645
- const dest = values.dir !== void 0 ? resolve4(values.dir) : values.project ? resolve4(".claude", "skills", "banger") : join5(homedir(), ".claude", "skills", "banger");
1103
+ if (positionals.length > 0 || values.project && values.dir !== void 0) throw new CliError(2, USAGE6);
1104
+ const dest = values.dir !== void 0 ? resolve5(values.dir) : values.project ? resolve5(".claude", "skills", "banger") : join7(homedir2(), ".claude", "skills", "banger");
646
1105
  const outcome = installSkill({ source: bundledSkill(), dest, version: cliVersion(), force: values.force });
647
1106
  process.stdout.write(`${outcome}: ${dest}
648
1107
  `);
@@ -651,15 +1110,15 @@ function runSkill(argv) {
651
1110
 
652
1111
  // src/commands/snap.ts
653
1112
  import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
654
- import { dirname as dirname4, join as join6 } from "node:path";
655
- var USAGE6 = "usage: banger snap [file] [--stop N] [--step M|last] [--steps last|all] [--out path] [--out-dir dir] [--scale 1|2]";
1113
+ import { dirname as dirname5, join as join8 } from "node:path";
1114
+ var USAGE7 = "usage: banger snap [file] [--stop N] [--step M|last] [--steps last|all] [--out path] [--out-dir dir] [--scale 1|2]";
656
1115
  function parseCount(name, value) {
657
1116
  if (!/^\d+$/.test(value)) throw new CliError(2, `invalid --${name}: ${value}`);
658
1117
  return Number(value);
659
1118
  }
660
1119
  async function runSnap(argv) {
661
1120
  if (argv.includes("--help")) {
662
- process.stdout.write(`${USAGE6}
1121
+ process.stdout.write(`${USAGE7}
663
1122
  `);
664
1123
  return 0;
665
1124
  }
@@ -671,7 +1130,7 @@ async function runSnap(argv) {
671
1130
  "out-dir": { type: "string" },
672
1131
  scale: { type: "string" }
673
1132
  });
674
- const file = deckFile(positionals, USAGE6);
1133
+ const file = deckFile(positionals, USAGE7);
675
1134
  if (values.scale !== void 0 && values.scale !== "1" && values.scale !== "2") {
676
1135
  throw new CliError(2, `invalid --scale: ${values.scale} (expected 1 or 2)`);
677
1136
  }
@@ -703,8 +1162,8 @@ async function runSnap(argv) {
703
1162
  const report = await session.goto(ref);
704
1163
  for (const failure of report.failed) failures.add(formatReadyFailure(failure));
705
1164
  const png = await captureState(session, ref);
706
- const target = single && values.out || join6(outDir, stopFileName(ref.stop, ref.step));
707
- await mkdir2(dirname4(target), { recursive: true });
1165
+ const target = single && values.out || join8(outDir, stopFileName(ref.stop, ref.step));
1166
+ await mkdir2(dirname5(target), { recursive: true });
708
1167
  await writeFile2(target, png);
709
1168
  }
710
1169
  return void 0;
@@ -715,18 +1174,18 @@ async function runSnap(argv) {
715
1174
  }
716
1175
 
717
1176
  // src/commands/theme.ts
718
- import { existsSync as existsSync5, writeFileSync as writeFileSync2 } from "node:fs";
719
- var USAGE7 = `usage: banger theme init [file] [--from <preset>] [--force]
1177
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "node:fs";
1178
+ var USAGE8 = `usage: banger theme init [file] [--from <preset>] [--force]
720
1179
  banger theme apply <theme.json> <deck.html>`;
721
1180
  function runThemeInit(argv) {
722
1181
  const { values, positionals } = parseArgsStrict(argv, { from: { type: "string" }, force: { type: "boolean" } });
723
- if (positionals.length > 1) throw new CliError(2, USAGE7);
1182
+ if (positionals.length > 1) throw new CliError(2, USAGE8);
724
1183
  const file = positionals[0] ?? "theme.json";
725
1184
  const name = values.from ?? "signal";
726
1185
  if (!isPresetName(name)) throw new CliError(2, `unknown preset: ${name} (choose one of: ${PRESET_NAMES.join(", ")})`);
727
- if (existsSync5(file) && !values.force) throw new CliError(2, `${file} already exists; pass --force to overwrite`);
1186
+ if (existsSync7(file) && !values.force) throw new CliError(2, `${file} already exists; pass --force to overwrite`);
728
1187
  try {
729
- writeFileSync2(file, `${serializeTheme(presetTheme(name))}
1188
+ writeFileSync4(file, `${serializeTheme(presetTheme(name))}
730
1189
  `);
731
1190
  } catch (error) {
732
1191
  throw new CliError(2, `cannot write ${file}: ${error.code ?? "error"}`);
@@ -737,7 +1196,7 @@ function runThemeInit(argv) {
737
1196
  }
738
1197
  function runThemeApply(argv) {
739
1198
  const { positionals } = parseArgsStrict(argv, {});
740
- if (positionals.length !== 2) throw new CliError(2, USAGE7);
1199
+ if (positionals.length !== 2) throw new CliError(2, USAGE8);
741
1200
  const [themeFile, deckFile2] = positionals;
742
1201
  const parsed = parseThemeJson(readInput(themeFile));
743
1202
  if (!parsed.definition) {
@@ -763,7 +1222,7 @@ function runThemeApply(argv) {
763
1222
  );
764
1223
  }
765
1224
  if (result.html !== html) {
766
- writeFileSync2(deckFile2, result.html);
1225
+ writeFileSync4(deckFile2, result.html);
767
1226
  process.stdout.write(`applied: ${deckFile2}
768
1227
  `);
769
1228
  } else {
@@ -774,28 +1233,28 @@ function runThemeApply(argv) {
774
1233
  }
775
1234
  async function runTheme(argv) {
776
1235
  const [sub, ...rest] = argv;
777
- if (sub === void 0) throw new CliError(2, USAGE7);
1236
+ if (sub === void 0) throw new CliError(2, USAGE8);
778
1237
  if (sub === "--help" || sub === "-h" || rest.includes("--help")) {
779
- process.stdout.write(`${USAGE7}
1238
+ process.stdout.write(`${USAGE8}
780
1239
  `);
781
1240
  return 0;
782
1241
  }
783
1242
  if (sub === "init") return runThemeInit(rest);
784
1243
  if (sub === "apply") return runThemeApply(rest);
785
1244
  throw new CliError(2, `unknown theme subcommand: ${sub}
786
- ${USAGE7}`);
1245
+ ${USAGE8}`);
787
1246
  }
788
1247
 
789
1248
  // src/update-check.ts
790
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "node:fs";
791
- import { homedir as homedir2 } from "node:os";
792
- import { dirname as dirname5, join as join7 } from "node:path";
1249
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "node:fs";
1250
+ import { homedir as homedir3 } from "node:os";
1251
+ import { dirname as dirname6, join as join9 } from "node:path";
793
1252
  var PACKAGE = "@bangerpage/cli";
794
1253
  var LATEST_URL = "https://registry.npmjs.org/@bangerpage%2fcli/latest";
795
1254
  var INTERVAL_MS = 24 * 60 * 60 * 1e3;
796
1255
  var TIMEOUT_MS = 2e3;
797
1256
  function updateCacheFile(env = process.env) {
798
- return join7(env.XDG_CACHE_HOME || join7(homedir2(), ".cache"), "banger", "update-check.json");
1257
+ return join9(env.XDG_CACHE_HOME || join9(homedir3(), ".cache"), "banger", "update-check.json");
799
1258
  }
800
1259
  function enabled(env, isTTY) {
801
1260
  return isTTY && !env.CI && !env.BANGER_NO_UPDATE_CHECK && !env.NO_UPDATE_NOTIFIER;
@@ -813,7 +1272,7 @@ function isNewer(latest, current) {
813
1272
  }
814
1273
  function readCache(file) {
815
1274
  try {
816
- const data = JSON.parse(readFileSync5(file, "utf8"));
1275
+ const data = JSON.parse(readFileSync7(file, "utf8"));
817
1276
  return typeof data.checkedAt === "number" && typeof data.latest === "string" ? { checkedAt: data.checkedAt, latest: data.latest } : void 0;
818
1277
  } catch {
819
1278
  return void 0;
@@ -839,14 +1298,14 @@ function checkForUpdate(opts) {
839
1298
  if (cache && now - cache.checkedAt < INTERVAL_MS) return Promise.resolve();
840
1299
  return (opts.fetchLatest ?? fetchFromRegistry)().then((latest) => {
841
1300
  if (!latest) return;
842
- mkdirSync2(dirname5(file), { recursive: true });
843
- writeFileSync3(file, `${JSON.stringify({ checkedAt: now, latest })}
1301
+ mkdirSync4(dirname6(file), { recursive: true });
1302
+ writeFileSync5(file, `${JSON.stringify({ checkedAt: now, latest })}
844
1303
  `);
845
1304
  }).catch(() => void 0);
846
1305
  }
847
1306
 
848
1307
  // src/bin.ts
849
- var USAGE8 = `usage: banger <command> [options]
1308
+ var USAGE9 = `usage: banger <command> [options]
850
1309
 
851
1310
  commands:
852
1311
  init [dir] [--force] start a deck: write index.html from the starter
@@ -864,27 +1323,35 @@ commands:
864
1323
  skill install [--project | --dir <path>] [--force]
865
1324
  copy the agent skill to ~/.claude/skills/banger
866
1325
  (--project: ./.claude/skills/banger)
1326
+ login [--token <token>] log in to banger.page in the browser (or store a token made
1327
+ on the site's settings page)
1328
+ logout forget the stored token
1329
+ publish [dir] [--slug <slug>] [--title <title>] [--visibility public|unlisted] [--strict]
1330
+ [--skip-check] [--dry-run]
1331
+ check the deck in dir (default: here) and publish it to banger.page;
1332
+ later runs update the same deck
867
1333
 
868
1334
  [file] defaults to index.html in the working directory.
869
1335
 
870
1336
  In a terminal, banger checks npm for a newer release once a day and prints a notice.
871
1337
  Set BANGER_NO_UPDATE_CHECK=1 to turn it off; it is also off when CI is set.
1338
+ BANGER_TOKEN gives publish a token without logging in (for CI); BANGER_HOST changes the site.
872
1339
 
873
1340
  options:
874
1341
  --help show this help
875
1342
  --version show the version
876
1343
  `;
877
- var COMMANDS = /* @__PURE__ */ new Set(["init", "preview", "snap", "check", "export", "theme", "skill"]);
1344
+ var COMMANDS = /* @__PURE__ */ new Set(["init", "preview", "snap", "check", "export", "theme", "skill", "login", "logout", "publish"]);
878
1345
  function version() {
879
1346
  const manifest = fileURLToPath4(new URL("../package.json", import.meta.url));
880
- return JSON.parse(readFileSync6(manifest, "utf8")).version;
1347
+ return JSON.parse(readFileSync8(manifest, "utf8")).version;
881
1348
  }
882
1349
  async function dispatch(argv) {
883
1350
  const [command, ...rest] = argv;
884
1351
  if (command === void 0) throw new CliError(2, `missing command
885
- ${USAGE8}`);
1352
+ ${USAGE9}`);
886
1353
  if (command === "--help" || command === "-h" || command === "help") {
887
- process.stdout.write(USAGE8);
1354
+ process.stdout.write(USAGE9);
888
1355
  return 0;
889
1356
  }
890
1357
  if (command === "--version" || command === "-v") {
@@ -908,9 +1375,15 @@ ${USAGE8}`);
908
1375
  return runTheme(rest);
909
1376
  case "skill":
910
1377
  return runSkill(rest);
1378
+ case "login":
1379
+ return runLogin(rest);
1380
+ case "logout":
1381
+ return runLogout(rest);
1382
+ case "publish":
1383
+ return runPublish(rest);
911
1384
  default:
912
1385
  throw new CliError(2, `unknown command: ${command}
913
- ${USAGE8}`);
1386
+ ${USAGE9}`);
914
1387
  }
915
1388
  }
916
1389
  async function main(argv) {
@@ -937,7 +1410,7 @@ if (entry && import.meta.url === pathToFileURL(realpathSync(entry)).href) {
937
1410
  process.exitCode = await main(process.argv.slice(2));
938
1411
  }
939
1412
  export {
940
- USAGE8 as USAGE,
1413
+ USAGE9 as USAGE,
941
1414
  main
942
1415
  };
943
1416
  //# sourceMappingURL=bin.js.map