@bangerpage/cli 0.1.0 → 0.1.2

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
  }
@@ -460,7 +735,13 @@ var USAGE = "usage: banger check [file] [--json]";
460
735
  async function checkDeck(file) {
461
736
  const warnings = [];
462
737
  const failed = /* @__PURE__ */ new Set();
463
- const stops = await withCapture(file, { onWarning: (message) => warnings.push(message) }, async (session) => {
738
+ const pinned = runtimeVersionWarning(readInput(file), CORE_PACKAGE, coreVersion())?.message;
739
+ const onWarning = (message) => {
740
+ if (message === pinned) process.stderr.write(`note: ${message}
741
+ `);
742
+ else warnings.push(message);
743
+ };
744
+ const stops = await withCapture(file, { onWarning }, async (session) => {
464
745
  for (const ref of expandStates(session.path, "last")) {
465
746
  const report = await session.goto(ref);
466
747
  for (const failure of report.failed) failed.add(formatReadyFailure(failure));
@@ -497,10 +778,10 @@ async function runCheck(argv) {
497
778
 
498
779
  // src/export/pdf.ts
499
780
  import { mkdir, writeFile } from "node:fs/promises";
500
- import { basename as basename2, dirname as dirname3, extname as extname2, resolve as resolve2 } from "node:path";
781
+ import { basename as basename2, dirname as dirname4, extname as extname2, resolve as resolve2 } from "node:path";
501
782
  import { PDFDocument } from "@cantoo/pdf-lib";
502
783
  async function exportPdf(file, opts = {}) {
503
- const out = resolve2(opts.out ?? resolve2(dirname3(file), `${basename2(file, extname2(file))}.pdf`));
784
+ const out = resolve2(opts.out ?? resolve2(dirname4(file), `${basename2(file, extname2(file))}.pdf`));
504
785
  const failures = /* @__PURE__ */ new Map();
505
786
  const pages = [];
506
787
  const title = await withCapture(
@@ -527,7 +808,7 @@ ${[...failures.keys()].join("\n")}`);
527
808
  for (const copied of await merged.copyPages(doc, doc.getPageIndices())) merged.addPage(copied);
528
809
  }
529
810
  merged.setTitle(title);
530
- await mkdir(dirname3(out), { recursive: true });
811
+ await mkdir(dirname4(out), { recursive: true });
531
812
  await writeFile(out, await merged.save());
532
813
  return out;
533
814
  }
@@ -558,15 +839,15 @@ ${USAGE2}`);
558
839
  }
559
840
 
560
841
  // 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";
842
+ import { copyFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2 } from "node:fs";
843
+ import { join as join5, resolve as resolve3 } from "node:path";
563
844
  import { fileURLToPath as fileURLToPath2 } from "node:url";
564
845
  var USAGE3 = "usage: banger init [dir] [--force]";
565
846
  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 });
847
+ const target = join5(opts.dir, "index.html");
848
+ if (existsSync4(target) && !opts.force) throw new CliError(2, `${target} already exists; pass --force to overwrite`);
849
+ if (!existsSync4(opts.starter)) throw new CliError(2, `the bundled starter is missing: ${opts.starter}`);
850
+ mkdirSync2(opts.dir, { recursive: true });
570
851
  copyFileSync(opts.starter, target);
571
852
  return target;
572
853
  }
@@ -604,25 +885,209 @@ async function runPreview(argv) {
604
885
  return 0;
605
886
  }
606
887
 
888
+ // src/commands/publish.ts
889
+ import { createHash as createHash2, randomUUID } from "node:crypto";
890
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, readdirSync, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
891
+ import { basename as basename3, extname as extname3, join as join6, relative, resolve as resolve4, sep as sep2 } from "node:path";
892
+ var USAGE5 = "usage: banger publish [dir] [--slug <slug>] [--title <title>] [--visibility public|unlisted] [--strict] [--skip-check] [--dry-run]";
893
+ var ACCEPTED = Object.fromEntries(
894
+ [".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".woff2", ".mp4", ".webm", ".json", ".css", ".js", ".pdf"].map((e) => [e, true])
895
+ );
896
+ var LIMITS = { html: 2 * 1024 * 1024, file: 10 * 1024 * 1024, total: 50 * 1024 * 1024, files: 200 };
897
+ function isAccepted(path) {
898
+ return path === "index.html" || extname3(path).toLowerCase() in ACCEPTED;
899
+ }
900
+ function collectDeck(dir) {
901
+ const root = resolve4(dir);
902
+ if (!existsSync5(join6(root, "index.html"))) throw new CliError(2, `no index.html in ${root}`);
903
+ const files = [];
904
+ const skipped = [];
905
+ const walk = (current) => {
906
+ for (const entry2 of readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
907
+ if (entry2.name.startsWith(".") || entry2.name === "node_modules") continue;
908
+ const abs = join6(current, entry2.name);
909
+ const path = relative(root, abs).split(sep2).join("/");
910
+ if (entry2.isDirectory()) {
911
+ walk(abs);
912
+ continue;
913
+ }
914
+ if (!entry2.isFile()) continue;
915
+ if (!isAccepted(path)) {
916
+ skipped.push(path);
917
+ continue;
918
+ }
919
+ const body = readFileSync5(abs);
920
+ files.push({ abs, path, size: body.length, sha256: createHash2("sha256").update(body).digest("hex") });
921
+ }
922
+ };
923
+ walk(root);
924
+ return { files, skipped };
925
+ }
926
+ function limitProblems(files) {
927
+ const problems = [];
928
+ if (files.length > LIMITS.files) problems.push(`${files.length} files; at most ${LIMITS.files} can be published`);
929
+ for (const f of files) {
930
+ const limit = f.path === "index.html" ? LIMITS.html : LIMITS.file;
931
+ if (f.size > limit) problems.push(`${f.path} is ${formatSize(f.size)}; the limit is ${formatSize(limit)}`);
932
+ }
933
+ const total = files.reduce((sum, f) => sum + f.size, 0);
934
+ if (total > LIMITS.total) problems.push(`the files add up to ${formatSize(total)}; the limit is ${formatSize(LIMITS.total)}`);
935
+ return problems;
936
+ }
937
+ function formatSize(bytes) {
938
+ if (bytes < 1024) return `${bytes} B`;
939
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
940
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
941
+ }
942
+ function slugFrom(name) {
943
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
944
+ }
945
+ function statePath(dir) {
946
+ return join6(resolve4(dir), ".banger", "deck.json");
947
+ }
948
+ function readState(dir) {
949
+ const file = statePath(dir);
950
+ if (!existsSync5(file)) return { decks: {} };
951
+ try {
952
+ const data = JSON.parse(readFileSync5(file, "utf8"));
953
+ return { decks: data.decks && typeof data.decks === "object" ? data.decks : {} };
954
+ } catch {
955
+ throw new CliError(2, `${file} could not be read; fix or delete it`);
956
+ }
957
+ }
958
+ function writeState(dir, state) {
959
+ const file = statePath(dir);
960
+ mkdirSync3(join6(resolve4(dir), ".banger"), { recursive: true });
961
+ writeFileSync2(file, `${JSON.stringify(state, null, 2)}
962
+ `);
963
+ }
964
+ async function runPublish(argv, fetchImpl = fetch) {
965
+ if (argv.includes("--help")) {
966
+ process.stdout.write(`${USAGE5}
967
+ `);
968
+ return 0;
969
+ }
970
+ const { values, positionals } = parseArgsStrict(argv, {
971
+ slug: { type: "string" },
972
+ title: { type: "string" },
973
+ visibility: { type: "string" },
974
+ strict: { type: "boolean" },
975
+ "skip-check": { type: "boolean" },
976
+ "dry-run": { type: "boolean" }
977
+ });
978
+ if (positionals.length > 1) throw new CliError(2, USAGE5);
979
+ const dir = positionals[0] ?? ".";
980
+ if (values.visibility !== void 0 && values.visibility !== "public" && values.visibility !== "unlisted") {
981
+ throw new CliError(2, `--visibility must be public or unlisted
982
+ ${USAGE5}`);
983
+ }
984
+ if (values.slug !== void 0 && slugFrom(values.slug) !== values.slug) {
985
+ throw new CliError(2, `--slug may use lower case letters, digits and single hyphens: ${values.slug}`);
986
+ }
987
+ const { files, skipped } = collectDeck(dir);
988
+ const total = files.reduce((sum, f) => sum + f.size, 0);
989
+ for (const f of files) process.stdout.write(` ${f.path} ${formatSize(f.size)}
990
+ `);
991
+ process.stdout.write(`${files.length} files, ${formatSize(total)}
992
+ `);
993
+ if (skipped.length > 0) process.stderr.write(`not sent (banger.page does not take these): ${skipped.join(", ")}
994
+ `);
995
+ const problems = limitProblems(files);
996
+ if (problems.length > 0) throw new CliError(1, problems.join("\n"));
997
+ if (!values["skip-check"]) {
998
+ const result2 = await checkDeck(join6(resolve4(dir), "index.html"));
999
+ for (const warning of result2.warnings) process.stderr.write(`warning: ${warning}
1000
+ `);
1001
+ for (const failure of result2.failed) process.stderr.write(`failed: ${failure}
1002
+ `);
1003
+ if (result2.failed.length > 0 || values.strict && result2.warnings.length > 0) {
1004
+ throw new CliError(1, "banger check found problems; fix them, or pass --skip-check to publish anyway");
1005
+ }
1006
+ }
1007
+ if (values["dry-run"]) return 0;
1008
+ const host = platformHost();
1009
+ const token = tokenFor(host);
1010
+ if (!token) throw new CliError(2, `not logged in to ${host}; run banger login --token <token>`);
1011
+ const client = new PlatformClient(host, token, fetchImpl);
1012
+ const state = readState(dir);
1013
+ const known = state.decks[host];
1014
+ const updating = known !== void 0 && (values.slug === void 0 || values.slug === known.slug);
1015
+ let result;
1016
+ try {
1017
+ const plan = await client.beginUpload(files.map(({ path, sha256, size }) => ({ path, sha256, size })));
1018
+ const bySha = new Map(files.map((f) => [f.sha256, f]));
1019
+ for (const blob of plan.uploads) {
1020
+ const file = bySha.get(blob.sha256);
1021
+ if (!file) throw new CliError(1, `${host} asked for a file that was not offered (${blob.path})`);
1022
+ await client.putBlob(blob.url, readFileSync5(file.abs), blob.method);
1023
+ }
1024
+ const kept = files.length - plan.uploads.length;
1025
+ process.stdout.write(
1026
+ kept === 0 ? `sent ${files.length} files
1027
+ ` : `sent ${plan.uploads.length} of ${files.length} files (${kept} already on ${host})
1028
+ `
1029
+ );
1030
+ const idempotency_key = randomUUID();
1031
+ const strict = values.strict === true;
1032
+ if (updating) {
1033
+ result = await client.update(known.slug, {
1034
+ upload_id: plan.upload_id,
1035
+ strict,
1036
+ idempotency_key,
1037
+ ...values.title ? { title: values.title } : {},
1038
+ ...values.visibility ? { visibility: values.visibility } : {}
1039
+ });
1040
+ } else {
1041
+ const slug = values.slug ?? (slugFrom(basename3(resolve4(dir))) || void 0);
1042
+ result = await client.publish({
1043
+ upload_id: plan.upload_id,
1044
+ idempotency_key,
1045
+ strict,
1046
+ ...slug ? { slug } : {},
1047
+ ...values.title ? { title: values.title } : {},
1048
+ ...values.visibility ? { visibility: values.visibility } : {}
1049
+ });
1050
+ }
1051
+ } catch (error) {
1052
+ if (!(error instanceof ApiError)) throw error;
1053
+ if (error.status === 401) throw new CliError(2, `${host} did not accept the token; run banger login --token <token> again`);
1054
+ if (error.code === "slug_taken") throw new CliError(1, `${error.message}
1055
+ pick another slug with --slug`);
1056
+ if (error.code === "pro_required") throw new CliError(1, `${error.message}
1057
+ (--visibility unlisted needs a paid plan)`);
1058
+ if (error.code === "not_found" && updating) {
1059
+ throw new CliError(1, `${error.message}
1060
+ the deck ${known.slug} is gone; delete ${statePath(dir)} to publish it as a new deck`);
1061
+ }
1062
+ throw new CliError(1, `${host}: ${error.message}`);
1063
+ }
1064
+ state.decks[host] = { slug: result.slug, url: result.url };
1065
+ writeState(dir, state);
1066
+ const version2 = result.version === void 0 ? "" : ` (version ${result.version})`;
1067
+ process.stdout.write(`${updating ? "updated" : "published"}${version2}: ${result.url}
1068
+ `);
1069
+ return 0;
1070
+ }
1071
+
607
1072
  // 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";
1073
+ import { cpSync, existsSync as existsSync6, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1074
+ import { homedir as homedir2 } from "node:os";
1075
+ import { join as join7, resolve as resolve5 } from "node:path";
611
1076
  import { fileURLToPath as fileURLToPath3 } from "node:url";
612
- var USAGE5 = "usage: banger skill install [--project | --dir <path>] [--force]";
1077
+ var USAGE6 = "usage: banger skill install [--project | --dir <path>] [--force]";
613
1078
  var MARKER = ".banger-skill";
614
1079
  function installSkill(opts) {
615
- if (!existsSync4(join5(opts.source, "SKILL.md"))) throw new CliError(2, `the bundled skill is missing: ${opts.source}`);
1080
+ if (!existsSync6(join7(opts.source, "SKILL.md"))) throw new CliError(2, `the bundled skill is missing: ${opts.source}`);
616
1081
  let outcome = "installed";
617
- if (existsSync4(opts.dest)) {
618
- if (!existsSync4(join5(opts.dest, MARKER)) && !opts.force) {
1082
+ if (existsSync6(opts.dest)) {
1083
+ if (!existsSync6(join7(opts.dest, MARKER)) && !opts.force) {
619
1084
  throw new CliError(2, `${opts.dest} already exists and was not written by banger; pass --force to replace it`);
620
1085
  }
621
- rmSync(opts.dest, { recursive: true, force: true });
1086
+ rmSync2(opts.dest, { recursive: true, force: true });
622
1087
  outcome = "updated";
623
1088
  }
624
1089
  cpSync(opts.source, opts.dest, { recursive: true });
625
- writeFileSync(join5(opts.dest, MARKER), `${opts.version}
1090
+ writeFileSync3(join7(opts.dest, MARKER), `${opts.version}
626
1091
  `);
627
1092
  return outcome;
628
1093
  }
@@ -631,18 +1096,18 @@ function bundledSkill() {
631
1096
  }
632
1097
  function cliVersion() {
633
1098
  const manifest = fileURLToPath3(new URL("../package.json", import.meta.url));
634
- return JSON.parse(readFileSync4(manifest, "utf8")).version;
1099
+ return JSON.parse(readFileSync6(manifest, "utf8")).version;
635
1100
  }
636
1101
  function runSkill(argv) {
637
1102
  const [sub, ...rest] = argv;
638
- if (sub !== "install") throw new CliError(2, USAGE5);
1103
+ if (sub !== "install") throw new CliError(2, USAGE6);
639
1104
  const { values, positionals } = parseArgsStrict(rest, {
640
1105
  project: { type: "boolean" },
641
1106
  dir: { type: "string" },
642
1107
  force: { type: "boolean" }
643
1108
  });
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");
1109
+ if (positionals.length > 0 || values.project && values.dir !== void 0) throw new CliError(2, USAGE6);
1110
+ const dest = values.dir !== void 0 ? resolve5(values.dir) : values.project ? resolve5(".claude", "skills", "banger") : join7(homedir2(), ".claude", "skills", "banger");
646
1111
  const outcome = installSkill({ source: bundledSkill(), dest, version: cliVersion(), force: values.force });
647
1112
  process.stdout.write(`${outcome}: ${dest}
648
1113
  `);
@@ -651,15 +1116,15 @@ function runSkill(argv) {
651
1116
 
652
1117
  // src/commands/snap.ts
653
1118
  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]";
1119
+ import { dirname as dirname5, join as join8 } from "node:path";
1120
+ var USAGE7 = "usage: banger snap [file] [--stop N] [--step M|last] [--steps last|all] [--out path] [--out-dir dir] [--scale 1|2]";
656
1121
  function parseCount(name, value) {
657
1122
  if (!/^\d+$/.test(value)) throw new CliError(2, `invalid --${name}: ${value}`);
658
1123
  return Number(value);
659
1124
  }
660
1125
  async function runSnap(argv) {
661
1126
  if (argv.includes("--help")) {
662
- process.stdout.write(`${USAGE6}
1127
+ process.stdout.write(`${USAGE7}
663
1128
  `);
664
1129
  return 0;
665
1130
  }
@@ -671,7 +1136,7 @@ async function runSnap(argv) {
671
1136
  "out-dir": { type: "string" },
672
1137
  scale: { type: "string" }
673
1138
  });
674
- const file = deckFile(positionals, USAGE6);
1139
+ const file = deckFile(positionals, USAGE7);
675
1140
  if (values.scale !== void 0 && values.scale !== "1" && values.scale !== "2") {
676
1141
  throw new CliError(2, `invalid --scale: ${values.scale} (expected 1 or 2)`);
677
1142
  }
@@ -703,8 +1168,8 @@ async function runSnap(argv) {
703
1168
  const report = await session.goto(ref);
704
1169
  for (const failure of report.failed) failures.add(formatReadyFailure(failure));
705
1170
  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 });
1171
+ const target = single && values.out || join8(outDir, stopFileName(ref.stop, ref.step));
1172
+ await mkdir2(dirname5(target), { recursive: true });
708
1173
  await writeFile2(target, png);
709
1174
  }
710
1175
  return void 0;
@@ -715,18 +1180,18 @@ async function runSnap(argv) {
715
1180
  }
716
1181
 
717
1182
  // 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]
1183
+ import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "node:fs";
1184
+ var USAGE8 = `usage: banger theme init [file] [--from <preset>] [--force]
720
1185
  banger theme apply <theme.json> <deck.html>`;
721
1186
  function runThemeInit(argv) {
722
1187
  const { values, positionals } = parseArgsStrict(argv, { from: { type: "string" }, force: { type: "boolean" } });
723
- if (positionals.length > 1) throw new CliError(2, USAGE7);
1188
+ if (positionals.length > 1) throw new CliError(2, USAGE8);
724
1189
  const file = positionals[0] ?? "theme.json";
725
1190
  const name = values.from ?? "signal";
726
1191
  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`);
1192
+ if (existsSync7(file) && !values.force) throw new CliError(2, `${file} already exists; pass --force to overwrite`);
728
1193
  try {
729
- writeFileSync2(file, `${serializeTheme(presetTheme(name))}
1194
+ writeFileSync4(file, `${serializeTheme(presetTheme(name))}
730
1195
  `);
731
1196
  } catch (error) {
732
1197
  throw new CliError(2, `cannot write ${file}: ${error.code ?? "error"}`);
@@ -737,7 +1202,7 @@ function runThemeInit(argv) {
737
1202
  }
738
1203
  function runThemeApply(argv) {
739
1204
  const { positionals } = parseArgsStrict(argv, {});
740
- if (positionals.length !== 2) throw new CliError(2, USAGE7);
1205
+ if (positionals.length !== 2) throw new CliError(2, USAGE8);
741
1206
  const [themeFile, deckFile2] = positionals;
742
1207
  const parsed = parseThemeJson(readInput(themeFile));
743
1208
  if (!parsed.definition) {
@@ -763,7 +1228,7 @@ function runThemeApply(argv) {
763
1228
  );
764
1229
  }
765
1230
  if (result.html !== html) {
766
- writeFileSync2(deckFile2, result.html);
1231
+ writeFileSync4(deckFile2, result.html);
767
1232
  process.stdout.write(`applied: ${deckFile2}
768
1233
  `);
769
1234
  } else {
@@ -774,28 +1239,28 @@ function runThemeApply(argv) {
774
1239
  }
775
1240
  async function runTheme(argv) {
776
1241
  const [sub, ...rest] = argv;
777
- if (sub === void 0) throw new CliError(2, USAGE7);
1242
+ if (sub === void 0) throw new CliError(2, USAGE8);
778
1243
  if (sub === "--help" || sub === "-h" || rest.includes("--help")) {
779
- process.stdout.write(`${USAGE7}
1244
+ process.stdout.write(`${USAGE8}
780
1245
  `);
781
1246
  return 0;
782
1247
  }
783
1248
  if (sub === "init") return runThemeInit(rest);
784
1249
  if (sub === "apply") return runThemeApply(rest);
785
1250
  throw new CliError(2, `unknown theme subcommand: ${sub}
786
- ${USAGE7}`);
1251
+ ${USAGE8}`);
787
1252
  }
788
1253
 
789
1254
  // 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";
1255
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "node:fs";
1256
+ import { homedir as homedir3 } from "node:os";
1257
+ import { dirname as dirname6, join as join9 } from "node:path";
793
1258
  var PACKAGE = "@bangerpage/cli";
794
1259
  var LATEST_URL = "https://registry.npmjs.org/@bangerpage%2fcli/latest";
795
1260
  var INTERVAL_MS = 24 * 60 * 60 * 1e3;
796
1261
  var TIMEOUT_MS = 2e3;
797
1262
  function updateCacheFile(env = process.env) {
798
- return join7(env.XDG_CACHE_HOME || join7(homedir2(), ".cache"), "banger", "update-check.json");
1263
+ return join9(env.XDG_CACHE_HOME || join9(homedir3(), ".cache"), "banger", "update-check.json");
799
1264
  }
800
1265
  function enabled(env, isTTY) {
801
1266
  return isTTY && !env.CI && !env.BANGER_NO_UPDATE_CHECK && !env.NO_UPDATE_NOTIFIER;
@@ -813,7 +1278,7 @@ function isNewer(latest, current) {
813
1278
  }
814
1279
  function readCache(file) {
815
1280
  try {
816
- const data = JSON.parse(readFileSync5(file, "utf8"));
1281
+ const data = JSON.parse(readFileSync7(file, "utf8"));
817
1282
  return typeof data.checkedAt === "number" && typeof data.latest === "string" ? { checkedAt: data.checkedAt, latest: data.latest } : void 0;
818
1283
  } catch {
819
1284
  return void 0;
@@ -839,14 +1304,14 @@ function checkForUpdate(opts) {
839
1304
  if (cache && now - cache.checkedAt < INTERVAL_MS) return Promise.resolve();
840
1305
  return (opts.fetchLatest ?? fetchFromRegistry)().then((latest) => {
841
1306
  if (!latest) return;
842
- mkdirSync2(dirname5(file), { recursive: true });
843
- writeFileSync3(file, `${JSON.stringify({ checkedAt: now, latest })}
1307
+ mkdirSync4(dirname6(file), { recursive: true });
1308
+ writeFileSync5(file, `${JSON.stringify({ checkedAt: now, latest })}
844
1309
  `);
845
1310
  }).catch(() => void 0);
846
1311
  }
847
1312
 
848
1313
  // src/bin.ts
849
- var USAGE8 = `usage: banger <command> [options]
1314
+ var USAGE9 = `usage: banger <command> [options]
850
1315
 
851
1316
  commands:
852
1317
  init [dir] [--force] start a deck: write index.html from the starter
@@ -864,27 +1329,35 @@ commands:
864
1329
  skill install [--project | --dir <path>] [--force]
865
1330
  copy the agent skill to ~/.claude/skills/banger
866
1331
  (--project: ./.claude/skills/banger)
1332
+ login [--token <token>] log in to banger.page in the browser (or store a token made
1333
+ on the site's settings page)
1334
+ logout forget the stored token
1335
+ publish [dir] [--slug <slug>] [--title <title>] [--visibility public|unlisted] [--strict]
1336
+ [--skip-check] [--dry-run]
1337
+ check the deck in dir (default: here) and publish it to banger.page;
1338
+ later runs update the same deck
867
1339
 
868
1340
  [file] defaults to index.html in the working directory.
869
1341
 
870
1342
  In a terminal, banger checks npm for a newer release once a day and prints a notice.
871
1343
  Set BANGER_NO_UPDATE_CHECK=1 to turn it off; it is also off when CI is set.
1344
+ BANGER_TOKEN gives publish a token without logging in (for CI); BANGER_HOST changes the site.
872
1345
 
873
1346
  options:
874
1347
  --help show this help
875
1348
  --version show the version
876
1349
  `;
877
- var COMMANDS = /* @__PURE__ */ new Set(["init", "preview", "snap", "check", "export", "theme", "skill"]);
1350
+ var COMMANDS = /* @__PURE__ */ new Set(["init", "preview", "snap", "check", "export", "theme", "skill", "login", "logout", "publish"]);
878
1351
  function version() {
879
1352
  const manifest = fileURLToPath4(new URL("../package.json", import.meta.url));
880
- return JSON.parse(readFileSync6(manifest, "utf8")).version;
1353
+ return JSON.parse(readFileSync8(manifest, "utf8")).version;
881
1354
  }
882
1355
  async function dispatch(argv) {
883
1356
  const [command, ...rest] = argv;
884
1357
  if (command === void 0) throw new CliError(2, `missing command
885
- ${USAGE8}`);
1358
+ ${USAGE9}`);
886
1359
  if (command === "--help" || command === "-h" || command === "help") {
887
- process.stdout.write(USAGE8);
1360
+ process.stdout.write(USAGE9);
888
1361
  return 0;
889
1362
  }
890
1363
  if (command === "--version" || command === "-v") {
@@ -908,9 +1381,15 @@ ${USAGE8}`);
908
1381
  return runTheme(rest);
909
1382
  case "skill":
910
1383
  return runSkill(rest);
1384
+ case "login":
1385
+ return runLogin(rest);
1386
+ case "logout":
1387
+ return runLogout(rest);
1388
+ case "publish":
1389
+ return runPublish(rest);
911
1390
  default:
912
1391
  throw new CliError(2, `unknown command: ${command}
913
- ${USAGE8}`);
1392
+ ${USAGE9}`);
914
1393
  }
915
1394
  }
916
1395
  async function main(argv) {
@@ -937,7 +1416,7 @@ if (entry && import.meta.url === pathToFileURL(realpathSync(entry)).href) {
937
1416
  process.exitCode = await main(process.argv.slice(2));
938
1417
  }
939
1418
  export {
940
- USAGE8 as USAGE,
1419
+ USAGE9 as USAGE,
941
1420
  main
942
1421
  };
943
1422
  //# sourceMappingURL=bin.js.map